Skip to content

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

Mac: chat on your own subscription for Claude, Gemini, ChatGPT, Cursor and Copilot

Claudec0be2a48e6bb
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index b1d95ebb..49060ea1 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -45,6 +45,9 @@ jobs:
- name: Test session titles in the relay
run: python3 scripts/test-session-title.py
+ - name: Test the chat on your subscription (Claude Code, Antigravity, Gemini, Codex, Cursor, Copilot)
+ run: bash scripts/test-cli-relay.sh
+
- name: Test Flow dictation keys
run: bash scripts/test-flow-keys.sh
diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstrings
index e0ffb572..49ee689d 100644
--- a/NotchBuddy/Resources/Localizable.xcstrings
+++ b/NotchBuddy/Resources/Localizable.xcstrings
@@ -75183,6 +75183,985 @@
}
}
}
+ },
+ "chat.subscriptions.title" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "اشتراكاتك في الذكاء الاصطناعي"
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "আপনার AI সাবস্ক্রিপশন"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Deine KI-Abos"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Your AI subscriptions"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tus suscripciones de IA"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tes abonnements IA"
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "आपकी AI सदस्यताएँ"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Langganan AI-mu"
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Suas assinaturas de IA"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ваши подписки на ИИ"
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "การสมัครใช้ AI ของคุณ"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Yapay zekâ abonelikleriniz"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的 AI 订阅"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的 AI 訂閱"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.description" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "تحدّث باستخدام الخطة التي تدفع ثمنها بالفعل. يستعين Coucou بأداة الطرفية الرسمية للذكاء الاصطناعي الخاص بك، المسجّلة بحسابك أنت: لا يرى أبدًا كلمة مرورك أو مفتاحك."
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "যে প্ল্যানের জন্য আপনি আগেই টাকা দেন, সেটি দিয়েই চ্যাট করুন। Coucou আপনার AI-এর অফিশিয়াল টার্মিনাল টুলকে জিজ্ঞেস করে, যা আপনার নিজের অ্যাকাউন্টে সাইন ইন করা: এটি কখনো আপনার পাসওয়ার্ড বা কী দেখে না।"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Chatte mit dem Abo, das du schon bezahlst. Coucou fragt das offizielle Terminal-Tool deiner KI, angemeldet mit deinem eigenen Konto: Es sieht nie dein Passwort oder deinen Schlüssel."
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Chat on the plan you already pay for. Coucou asks your AI's official terminal tool, signed in with your own account: it never sees your password or your key."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Chatea con el plan que ya pagas. Coucou usa la herramienta oficial de terminal de tu IA, con tu propia cuenta: nunca ve tu contraseña ni tu clave."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Discute avec l'abonnement que tu paies déjà. Coucou passe par l'outil terminal officiel de ton IA, connecté à ton propre compte : il ne voit jamais ton mot de passe ni ta clé."
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "उस प्लान से चैट करें जिसका आप पहले से भुगतान करते हैं। Coucou आपकी AI के आधिकारिक टर्मिनल टूल से पूछता है, जो आपके अपने खाते से साइन इन है: वह आपका पासवर्ड या कुंजी कभी नहीं देखता।"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Chat dengan paket yang sudah kamu bayar. Coucou memakai alat terminal resmi AI-mu, masuk dengan akunmu sendiri: Coucou tidak pernah melihat kata sandi atau kuncimu."
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Converse usando o plano que você já paga. O Coucou usa a ferramenta oficial de terminal da sua IA, conectada à sua própria conta: ele nunca vê sua senha nem sua chave."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Общайтесь в рамках подписки, за которую вы уже платите. Coucou обращается к официальному терминальному инструменту вашего ИИ, вошедшему в вашу учётную запись: он никогда не видит ваш пароль или ключ."
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "แชตด้วยแพ็กเกจที่คุณจ่ายอยู่แล้ว Coucou จะถามเครื่องมือเทอร์มินัลทางการของ AI ของคุณ ซึ่งลงชื่อเข้าใช้ด้วยบัญชีของคุณเอง: Coucou ไม่เคยเห็นรหัสผ่านหรือคีย์ของคุณ"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Zaten ödediğiniz planla sohbet edin. Coucou, yapay zekânızın kendi hesabınızla oturum açmış resmi terminal aracına sorar: şifrenizi veya anahtarınızı asla görmez."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "用你已经付费的套餐聊天。Coucou 会调用你的 AI 的官方终端工具,并使用你自己的账户登录:它永远看不到你的密码或密钥。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "用你已經付費的方案聊天。Coucou 會呼叫你的 AI 的官方終端工具,並使用你自己的帳號登入:它永遠看不到你的密碼或金鑰。"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.use" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "استخدام اشتراكي"
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "আমার সাবস্ক্রিপশন ব্যবহার করুন"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mein Abo verwenden"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Use my subscription"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Usar mi suscripción"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Utiliser mon abonnement"
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "मेरी सदस्यता इस्तेमाल करें"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Pakai langgananku"
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Usar minha assinatura"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Использовать мою подписку"
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ใช้การสมัครใช้ของฉัน"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aboneliğimi kullan"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "使用我的订阅"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "使用我的訂閱"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.found" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "تم العثور على %@ ✓"
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ পাওয়া গেছে ✓"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ gefunden ✓"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ found ✓"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ encontrado ✓"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ trouvé ✓"
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ मिला ✓"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ ditemukan ✓"
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ encontrado ✓"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ найден ✓"
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "พบ %@ ✓"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ bulundu ✓"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已找到 %@ ✓"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已找到 %@ ✓"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.missing" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "لم يتم العثور على %@."
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ পাওয়া যায়নি।"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ nicht gefunden."
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ not found."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "No se encontró %@."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ introuvable."
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ नहीं मिला।"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ tidak ditemukan."
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ não encontrado."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ не найден."
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ไม่พบ %@"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ bulunamadı."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "未找到 %@。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "找不到 %@。"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.install" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "تثبيته"
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ইনস্টল করুন"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Installieren"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Install it"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Instalarlo"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "L'installer"
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "इंस्टॉल करें"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Pasang"
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Instalar"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Установить"
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ติดตั้ง"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Yükle"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "去安装"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "前往安裝"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.sign-in" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "لم تسجّل الدخول بعد؟ شغّل مرة واحدة في Terminal: %@"
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "এখনও সাইন ইন করেননি? টার্মিনালে একবার চালান: %@"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Noch nicht angemeldet? Einmal im Terminal ausführen: %@"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Not signed in yet? Run this once in Terminal: %@"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "¿Aún no has iniciado sesión? Ejecuta una vez en la Terminal: %@"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Pas encore connecté ? Lance une fois dans le Terminal : %@"
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "अभी तक साइन इन नहीं किया? टर्मिनल में एक बार चलाएँ: %@"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Belum masuk? Jalankan sekali di Terminal: %@"
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ainda não entrou? Rode uma vez no Terminal: %@"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ещё не вошли? Выполните один раз в Терминале: %@"
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ยังไม่ได้ลงชื่อเข้าใช้? รันหนึ่งครั้งใน Terminal: %@"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Henüz oturum açmadınız mı? Terminal'de bir kez çalıştırın: %@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "还没登录?在终端里运行一次:%@"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "還沒登入?在終端機執行一次:%@"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.off" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "متوقف: تستخدم الدردشة مفتاح API أدناه."
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "বন্ধ: চ্যাট নিচের আপনার API কী ব্যবহার করে।"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Aus: Der Chat nutzt deinen API-Schlüssel unten."
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Off: the chat uses your API key below."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Desactivado: el chat usa tu clave API de abajo."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Désactivé : le chat utilise ta clé API ci-dessous."
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "बंद: चैट नीचे दी गई आपकी API कुंजी का इस्तेमाल करती है।"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mati: chat memakai kunci API-mu di bawah."
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Desligado: o chat usa sua chave de API abaixo."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Выключено: чат использует ваш API-ключ ниже."
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ปิดอยู่: แชตใช้คีย์ API ของคุณด้านล่าง"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Kapalı: sohbet aşağıdaki API anahtarınızı kullanır."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已关闭:聊天使用下方的 API 密钥。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已關閉:聊天使用下方的 API 金鑰。"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.default-model" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "النموذج المختار في %@"
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@-এ বেছে নেওয়া মডেল"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Das in %@ gewählte Modell"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "The model chosen in %@"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "El modelo elegido en %@"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Le modèle choisi dans %@"
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ में चुना गया मॉडल"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Model yang dipilih di %@"
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O modelo escolhido no %@"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Модель, выбранная в %@"
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "โมเดลที่เลือกไว้ใน %@"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ içinde seçilen model"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "在 %@ 中选择的模型"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "在 %@ 中選擇的模型"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.pill" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "خطتك · %@"
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "আপনার প্ল্যান · %@"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dein Abo · %@"
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Your plan · %@"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Tu plan · %@"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ton abonnement · %@"
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "आपका प्लान · %@"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Paketmu · %@"
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Seu plano · %@"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ваша подписка · %@"
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "แพ็กเกจของคุณ · %@"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Planınız · %@"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的套餐 · %@"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "你的方案 · %@"
+ }
+ }
+ }
+ },
+ "chat.subscriptions.error.missing" : {
+ "extractionState" : "manual",
+ "localizations" : {
+ "ar" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ غير مثبّت. ثبّته من الإعدادات ← الدردشة، وسجّل الدخول مرة واحدة في Terminal، ثم اسأل مجددًا."
+ }
+ },
+ "bn" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ ইনস্টল করা নেই। সেটিংস → চ্যাট থেকে এটি ইনস্টল করুন, টার্মিনালে একবার সাইন ইন করুন, তারপর আবার জিজ্ঞেস করুন।"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ ist nicht installiert. Installiere es über Einstellungen → Chat, melde dich einmal im Terminal an und frag dann erneut."
+ }
+ },
+ "en" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ is not installed. Install it from Settings → Chat, sign in once in Terminal, then ask again."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ no está instalado. Instálalo desde Ajustes → Chat, inicia sesión una vez en la Terminal y vuelve a preguntar."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ n'est pas installé. Installe-le depuis Réglages → Chat, connecte-toi une fois dans le Terminal, puis redemande."
+ }
+ },
+ "hi" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ इंस्टॉल नहीं है। सेटिंग्स → चैट से इसे इंस्टॉल करें, टर्मिनल में एक बार साइन इन करें, फिर दोबारा पूछें।"
+ }
+ },
+ "id" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ belum terpasang. Pasang dari Pengaturan → Chat, masuk sekali di Terminal, lalu tanya lagi."
+ }
+ },
+ "pt-BR" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O %@ não está instalado. Instale em Ajustes → Chat, entre uma vez no Terminal e pergunte de novo."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ не установлен. Установите его в Настройки → Чат, один раз войдите в Терминале и спросите снова."
+ }
+ },
+ "th" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "ยังไม่ได้ติดตั้ง %@ ติดตั้งได้จาก การตั้งค่า → แชต ลงชื่อเข้าใช้หนึ่งครั้งใน Terminal แล้วถามอีกครั้ง"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ yüklü değil. Ayarlar → Sohbet'ten yükleyin, Terminal'de bir kez oturum açın, sonra tekrar sorun."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 未安装。请在 设置 → 聊天 中安装,在终端登录一次,然后再问一次。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%@ 尚未安裝。請在 設定 → 聊天 中安裝,在終端機登入一次,然後再問一次。"
+ }
+ }
+ }
}
},
"version" : "1.0"
diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift
index 8e9ceeed..3e09de05 100644
--- a/NotchBuddy/Sources/App/AppState.swift
+++ b/NotchBuddy/Sources/App/AppState.swift
@@ -167,6 +167,22 @@ final class AppState: ObservableObject {
func fetchModelsIfNeeded(for provider: ChatProvider) {
guard !loadingProviderModels.contains(provider),
fetchedProviderModels[provider] == nil else { return }
+ #if !APPSTORE
+ // Through the subscription: Claude Code takes the model aliases; the other tools
+ // use the model chosen in them.
+ if usesSubscription(provider) {
+ providerModelFetchError.removeValue(forKey: provider)
+ if provider == .anthropic {
+ var models = Self.claudeCodeModels
+ if !models.contains(where: { $0.id == claudeModel }) { models.insert((claudeModel, claudeModel), at: 0) }
+ fetchedProviderModels[provider] = models
+ } else {
+ let tool = (provider.installedCLI ?? provider.subscriptionCLIs.first)?.displayName ?? provider.displayName
+ fetchedProviderModels[provider] = [("", String(format: String(localized: "chat.subscriptions.default-model"), tool))]
+ }
+ return
+ }
+ #endif
// Local providers: fetch from server URL (no API key needed)
if provider.isLocal {
let baseURL = provider == .ollama ? ollamaServerURL : lmstudioServerURL
@@ -218,6 +234,7 @@ final class AppState: ObservableObject {
case .qwen: models = await ClaudeService.fetchOpenAICompatibleModels(baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1", apiKey: apiKey)
case .moonshot: models = await ClaudeService.fetchOpenAICompatibleModels(baseURL: "https://api.moonshot.cn/v1", apiKey: apiKey)
case .ollama, .lmstudio: models = [] // handled above
+ case .cursor, .copilot: models = [] // subscription only, handled above
}
loadingProviderModels.remove(provider)
if models.isEmpty {
@@ -249,12 +266,17 @@ final class AppState: ObservableObject {
if !models.contains(where: { $0.id == moonshotChatModel }) {
moonshotChatModel = models.first!.id
}
- case .ollama, .lmstudio: break
+ case .ollama, .lmstudio, .cursor, .copilot: break
}
}
}
}
+ /// The models offered when Claude Code answers: its aliases always point at the latest.
+ static let claudeCodeModels: [(id: String, label: String)] = [
+ ("sonnet", "Claude Sonnet"), ("opus", "Claude Opus"), ("haiku", "Claude Haiku"),
+ ]
+
/// The model currently active for chat (provider-aware).
var activeChatModel: String {
switch chatProvider {
@@ -266,6 +288,7 @@ final class AppState: ObservableObject {
case .deepseek: return deepseekChatModel
case .qwen: return qwenChatModel
case .moonshot: return moonshotChatModel
+ case .cursor, .copilot: return ""
}
}
diff --git a/NotchBuddy/Sources/App/CLIRelay.swift b/NotchBuddy/Sources/App/CLIRelay.swift
new file mode 100644
index 00000000..2187ee73
--- /dev/null
+++ b/NotchBuddy/Sources/App/CLIRelay.swift
@@ -0,0 +1,297 @@
+import Foundation
+
+// MARK: - The chat on your own subscription (GitHub build)
+//
+// With "Use my subscription" on in Settings → Chat, the chat is answered by the
+// official terminal tool of the user's AI, signed in with their own account: Claude
+// Code (Claude plan), Antigravity CLI or Gemini CLI (Google AI plan), Codex CLI
+// (ChatGPT plan), Cursor CLI and GitHub Copilot CLI. Coucou reads no credential and
+// makes no network call of its own: the tool answers exactly as it does in a terminal.
+//
+// Each run is kept apart from the user's own sessions: nothing saved to resume, no
+// user hooks, MCP servers, extensions or plugins where the tool lets us turn them off,
+// and it runs in an empty folder of Coucou's, so no project instructions are picked up.
+// It may search the web for the chat and nothing else: no shell, no edits. A dropped
+// file is read with no web at all (a file written to steer the model could otherwise
+// send what it reads to a website): Claude Code reads a copy of that one file, the
+// other tools get its text in the prompt.
+//
+// This file is pure (Foundation only) so scripts/test-cli-relay.sh can test it;
+// CLIRelayRun.swift starts the processes. The App Store build is sandboxed and can't
+// start them: there the chat still needs a key.
+
+enum SubscriptionCLI: String, CaseIterable, Sendable {
+ case claude, antigravity, gemini, codex, cursor, copilot
+
+ var displayName: String {
+ switch self {
+ case .claude: "Claude Code"
+ case .antigravity: "Antigravity CLI"
+ case .gemini: "Gemini CLI"
+ case .codex: "Codex CLI"
+ case .cursor: "Cursor CLI"
+ case .copilot: "Copilot CLI"
+ }
+ }
+
+ /// Its executable names, the official one first.
+ var binaries: [String] {
+ switch self {
+ case .claude: ["claude"]
+ case .antigravity: ["agy"]
+ case .gemini: ["gemini"]
+ case .codex: ["codex"]
+ case .cursor: ["cursor-agent", "agent"]
+ case .copilot: ["copilot"]
+ }
+ }
+
+ /// What to type once in a terminal to sign in.
+ var signIn: String {
+ switch self {
+ case .claude: "claude"
+ case .antigravity: "agy"
+ case .gemini: "gemini"
+ case .codex: "codex login"
+ case .cursor: "cursor-agent login"
+ case .copilot: "copilot"
+ }
+ }
+
+ /// Where it is installed from (opened in the browser from Settings).
+ var installURL: String {
+ switch self {
+ case .claude: "https://code.claude.com/docs/en/setup"
+ case .antigravity: "https://antigravity.google/docs/cli"
+ case .gemini: "https://geminicli.com"
+ case .codex: "https://developers.openai.com/codex/cli"
+ case .cursor: "https://cursor.com/cli"
+ case .copilot: "https://docs.github.com/copilot/how-tos/copilot-cli"
+ }
+ }
+
+ /// The prompt goes in on stdin; the others take it as an argument.
+ var promptOnStdin: Bool { self == .claude || self == .codex }
+}
+
+struct CLIRequest: Sendable {
+ /// nil: the tool's own default model.
+ var model: String?
+ var system: String
+ var prompt: String
+ /// Web search for the chat; off while a dropped file is read.
+ var web: Bool
+ /// Claude Code only: the folder holding the copy of the dropped file it may read.
+ var readDir: URL?
+ /// Gemini CLI only: a policy file that denies its web tools (written by the runner).
+ var noWebPolicy: URL?
+ var timeout: TimeInterval
+}
+
+enum CLIFailure: LocalizedError, Equatable {
+ case notInstalled(String)
+ case timedOut(String)
+ case noAnswer(String)
+ case failed(String)
+
+ var errorDescription: String? {
+ switch self {
+ case .notInstalled(let name): return "\(name) is not installed."
+ case .timedOut(let name): return "\(name) took too long to answer."
+ case .noAnswer(let name): return "\(name) gave no answer."
+ case .failed(let why): return why
+ }
+ }
+}
+
+enum CLIRelay {
+
+ /// The Gemini CLI policy that keeps a run off the web (see `CLIRequest.noWebPolicy`).
+ static let noWebPolicyTOML = """
+ [[rule]]
+ toolName = ["google_web_search", "web_fetch"]
+ decision = "deny"
+ priority = 900
+ denyMessage = "No web while Coucou reads a file."
+
+ """
+
+ /// The prompt as the tool receives it: Claude Code takes the system prompt apart,
+ /// the others get it on top.
+ static func fullPrompt(_ cli: SubscriptionCLI, _ r: CLIRequest) -> String {
+ if cli == .claude { return r.prompt }
+ return "<instructions>\n\(r.system)\n</instructions>\n\n\(r.prompt)"
+ }
+
+ /// The command line of one run. Pure, so it can be tested.
+ static func arguments(_ cli: SubscriptionCLI, _ r: CLIRequest) -> [String] {
+ let model = r.model.flatMap { $0.isEmpty ? nil : $0 }
+ switch cli {
+ case .claude:
+ let tools = r.readDir != nil ? ["Read"] : (r.web ? ["WebSearch", "WebFetch"] : [])
+ var out = ["-p", "--output-format", "json"]
+ if let model { out += ["--model", model] }
+ out += ["--system-prompt", r.system, "--tools", tools.joined(separator: ",")]
+ if !tools.isEmpty { out += ["--allowedTools", tools.joined(separator: ",")] }
+ if let dir = r.readDir { out += ["--add-dir", dir.path] }
+ return out + ["--setting-sources", "", "--strict-mcp-config", "--no-session-persistence", "--disable-slash-commands"]
+
+ case .gemini:
+ // Plan mode: read-only tools and Google search, nothing that writes or runs.
+ var out = ["-p", fullPrompt(cli, r), "--output-format", "json", "--approval-mode", "plan",
+ "--skip-trust", "--extensions", "none", "--allowed-mcp-server-names", "coucou-none"]
+ if let model { out += ["--model", model] }
+ if !r.web, let policy = r.noWebPolicy { out += ["--policy", policy.path] }
+ return out
+
+ case .antigravity:
+ var out = ["-p", fullPrompt(cli, r), "--output-format", "json", "--mode", "plan", "--disable-slash-commands"]
+ if let model { out += ["--model", model] }
+ return out
+
+ case .codex:
+ // Read-only sandbox and no shell at all: it can only answer (and search, for the chat).
+ var out = r.web ? ["--search"] : []
+ out += ["exec", "--json", "--skip-git-repo-check", "--ephemeral", "--ignore-user-config", "--ignore-rules",
+ "--sandbox", "read-only", "--color", "never"]
+ for feature in ["shell_tool", "unified_exec", "apps", "plugins", "hooks"] { out += ["--disable", feature] }
+ if let model { out += ["--model", model] }
+ return out + ["-"]
+
+ case .cursor:
+ // Ask mode: answers and reads, never edits or runs (no --force).
+ var out = ["-p", fullPrompt(cli, r), "--output-format", "json", "--mode", "ask", "--trust"]
+ if let model { out += ["--model", model] }
+ return out
+
+ case .copilot:
+ var out = ["-p", fullPrompt(cli, r), "--silent", "--no-custom-instructions", "--disable-builtin-mcps",
+ "--no-ask-user", "--no-auto-update", "--no-color"]
+ out += r.web ? ["--available-tools", "web_fetch", "--allow-all-urls"] : ["--available-tools", "view"]
+ if let model { out += ["--model", model] }
+ return out
+ }
+ }
+
+ /// The answer's text, or why there is none.
+ static func parse(_ cli: SubscriptionCLI, stdout: Data, stderr: Data, exitCode: Int32) -> Result<String, CLIFailure> {
+ let detail = lastLine(stderr)
+ let result: Result<String, CLIFailure>
+ switch cli {
+ case .claude, .cursor:
+ result = parseResultObject(cli, stdout)
+ case .gemini, .antigravity:
+ result = parseResponseObject(cli, stdout, stderr)
+ case .codex:
+ result = parseCodexEvents(cli, stdout)
+ case .copilot:
+ let text = String(decoding: stdout, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines)
+ result = exitCode == 0 && !text.isEmpty ? .success(text) : .failure(.noAnswer(cli.displayName))
+ }
+ guard case .failure(let failure) = result else { return result }
+ // Not signed in: say how to sign in rather than the tool's own wording only.
+ let said: String = {
+ if case .failed(let why) = failure { return why }
+ return detail
+ }()
+ if needsSignIn(said) {
+ return .failure(.failed("\(cli.displayName) is not signed in. Sign in once in Terminal: \(cli.signIn)"))
+ }
+ if case .failed = failure { return .failure(failure) }
+ return detail.isEmpty ? .failure(failure) : .failure(.failed("\(failure.localizedDescription) (\(detail))"))
+ }
+
+ /// One chat turn as a single prompt: the earlier turns, the context the first
+ /// question carries, then the question.
+ static func chatPrompt(history: [(user: String, assistant: String)], context: String?, query: String) -> String {
+ var out = ""
+ if !history.isEmpty {
+ out += "The conversation so far:\n<conversation>\n"
+ for turn in history {
+ out += "<user>\n\(turn.user)\n</user>\n<assistant>\n\(turn.assistant)\n</assistant>\n"
+ }
+ out += "</conversation>\n\nThe user's new message:\n"
+ }
+ if let context { out += context + "\n\n" }
+ return out + query
+ }
+
+ // MARK: - Output formats
+
+ /// `claude -p` and Cursor's `--output-format json`: `{"result": …, "is_error": …}`.
+ private static func parseResultObject(_ cli: SubscriptionCLI, _ stdout: Data) -> Result<String, CLIFailure> {
+ guard let json = lastJSONObject(stdout) else { return .failure(.noAnswer(cli.displayName)) }
+ let text = (json["result"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ if json["is_error"] as? Bool == true {
+ return .failure(.failed(text.isEmpty ? "\(cli.displayName) could not answer." : text))
+ }
+ return text.isEmpty ? .failure(.noAnswer(cli.displayName)) : .success(text)
+ }
+
+ /// Gemini CLI and Antigravity CLI: `{"response": …, "error": {…}}`, the error on stderr too.
+ private static func parseResponseObject(_ cli: SubscriptionCLI, _ stdout: Data, _ stderr: Data) -> Result<String, CLIFailure> {
+ let out = lastJSONObject(stdout)
+ let text = (out?["response"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ if !text.isEmpty { return .success(text) }
+ for json in [out, lastJSONObject(stderr)] {
+ guard let json else { continue }
+ if let error = json["error"] as? [String: Any], let message = error["message"] as? String, !message.isEmpty {
+ return .failure(.failed(message))
+ }
+ if let message = json["error"] as? String, !message.isEmpty { return .failure(.failed(message)) }
+ }
+ return .failure(.noAnswer(cli.displayName))
+ }
+
+ /// `codex exec --json`: one event per line; the answer is the last finished agent message.
+ private static func parseCodexEvents(_ cli: SubscriptionCLI, _ stdout: Data) -> Result<String, CLIFailure> {
+ var answer: String?
+ var failure: String?
+ for line in String(decoding: stdout, as: UTF8.self).split(whereSeparator: \.isNewline) {
+ guard let data = line.data(using: .utf8),
+ let event = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else { continue }
+ switch event["type"] as? String {
+ case "item.completed":
+ if let item = event["item"] as? [String: Any], item["type"] as? String == "agent_message",
+ let text = item["text"] as? String, !text.isEmpty {
+ answer = text
+ }
+ case "turn.failed":
+ if let error = event["error"] as? [String: Any], let message = error["message"] as? String {
+ failure = message
+ }
+ case "error":
+ if let message = event["message"] as? String { failure = message }
+ default:
+ break
+ }
+ }
+ if let answer { return .success(answer.trimmingCharacters(in: .whitespacesAndNewlines)) }
+ if let failure { return .failure(.failed(failure)) }
+ return .failure(.noAnswer(cli.displayName))
+ }
+
+ /// The last JSON object in a tool's output (some print a line or two before it).
+ static func lastJSONObject(_ data: Data) -> [String: Any]? {
+ if let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] { return json }
+ let text = String(decoding: data, as: UTF8.self)
+ guard let start = text.range(of: "\n{", options: .backwards)?.lowerBound else { return nil }
+ let tail = text[text.index(after: start)...]
+ return (try? JSONSerialization.jsonObject(with: Data(tail.utf8))) as? [String: Any]
+ }
+
+ /// The last line a tool wrote on stderr, without terminal colours.
+ static func lastLine(_ data: Data) -> String {
+ let text = String(decoding: data, as: UTF8.self)
+ .replacingOccurrences(of: "\u{1B}\\[[0-9;]*[A-Za-z]", with: "", options: .regularExpression)
+ return text.split(whereSeparator: \.isNewline)
+ .map { $0.trimmingCharacters(in: .whitespaces) }
+ .last(where: { !$0.isEmpty }) ?? ""
+ }
+
+ static func needsSignIn(_ text: String) -> Bool {
+ let t = text.lowercased()
+ return ["log in", "login", "logged in", "authenticat", "unauthorized", "401", "sign in", "signed in",
+ "auth method", "invalid api key"].contains { t.contains($0) }
+ }
+}
diff --git a/NotchBuddy/Sources/App/CLIRelayRun.swift b/NotchBuddy/Sources/App/CLIRelayRun.swift
new file mode 100644
index 00000000..0cb96d9f
--- /dev/null
+++ b/NotchBuddy/Sources/App/CLIRelayRun.swift
@@ -0,0 +1,213 @@
+import Foundation
+
+#if !APPSTORE
+// MARK: - Finding and running the subscription tools (see CLIRelay.swift)
+
+/// Where each tool is installed. The app doesn't get the shell's PATH, so the usual
+/// install folders are looked at first (npm, nvm, fnm, Volta, Bun, pnpm, Homebrew, the
+/// tools' own installers); for anything else the user's login shell is asked once, in
+/// the background, and the views are told when it answers.
+final class CLILocator: @unchecked Sendable {
+ static let shared = CLILocator()
+ static let changed = Notification.Name("notchBuddy.cliLocatorChanged")
+
+ private let lock = NSLock()
+ private var found: [SubscriptionCLI: String] = [:]
+ private var looked = false
+ private var askedShell = false
+
+ /// The tool's executable, or nil when it isn't installed.
+ func path(_ cli: SubscriptionCLI) -> String? {
+ lock.lock()
+ if !looked {
+ looked = true
+ found = Self.scanFolders()
+ }
+ let path = found[cli]
+ let askShell = path == nil && !askedShell
+ if askShell { askedShell = true }
+ lock.unlock()
+ if askShell { askLoginShell() }
+ return path
+ }
+
+ func isInstalled(_ cli: SubscriptionCLI) -> Bool { path(cli) != nil }
+
+ /// Looks again (Settings opens, or the user just installed a tool).
+ func refresh() {
+ lock.lock()
+ looked = false
+ askedShell = false
+ lock.unlock()
+ NotificationCenter.default.post(name: Self.changed, object: nil)
+ }
+
+ // MARK: Folders
+
+ private static func scanFolders() -> [SubscriptionCLI: String] {
+ let fm = FileManager.default
+ let home = fm.homeDirectoryForCurrentUser.path
+ var dirs = [
+ "\(home)/.local/bin", "\(home)/.claude/local", "/opt/homebrew/bin", "/usr/local/bin",
+ "\(home)/.npm-global/bin", "\(home)/.npm/bin", "\(home)/.volta/bin", "\(home)/.bun/bin",
+ "\(home)/Library/pnpm", "\(home)/.local/share/pnpm", "\(home)/.yarn/bin",
+ "\(home)/.asdf/shims", "\(home)/.local/share/mise/shims", "\(home)/.cursor/bin",
+ ]
+ // nvm and fnm keep one folder per Node version: newest first.
+ dirs += versionDirs("\(home)/.nvm/versions/node") { "\($0)/bin" }
+ dirs += versionDirs("\(home)/Library/Application Support/fnm/node-versions") { "\($0)/installation/bin" }
+ dirs += versionDirs("\(home)/.local/share/fnm/node-versions") { "\($0)/installation/bin" }
+ var out: [SubscriptionCLI: String] = [:]
+ for cli in SubscriptionCLI.allCases {
+ search: for name in cli.binaries {
+ for dir in dirs where fm.isExecutableFile(atPath: "\(dir)/\(name)") {
+ out[cli] = "\(dir)/\(name)"
+ break search
+ }
+ }
+ }
+ return out
+ }
+
+ private static func versionDirs(_ root: String, _ bin: (String) -> String) -> [String] {
+ let names = (try? FileManager.default.contentsOfDirectory(atPath: root)) ?? []
+ return names.sorted { $0.compare($1, options: .numeric) == .orderedDescending }
+ .map { bin("\(root)/\($0)") }
+ }
+
+ // MARK: Login shell
+
+ /// `command -v` for every tool in one interactive login shell (that is where nvm and
+ /// friends set PATH up), with no input and a short timeout.
+ private func askLoginShell() {
+ DispatchQueue.global(qos: .utility).async { [self] in
+ let names = SubscriptionCLI.allCases.flatMap(\.binaries)
+ let script = names.map { "command -v \($0)" }.joined(separator: "; ")
+ let shell = ProcessInfo.processInfo.environment["SHELL"].flatMap { $0.isEmpty ? nil : $0 } ?? "/bin/zsh"
+ let p = Process()
+ p.executableURL = URL(fileURLWithPath: shell)
+ p.arguments = ["-ilc", script]
+ p.standardInput = FileHandle.nullDevice
+ let out = Pipe()
+ p.standardOutput = out
+ p.standardError = FileHandle.nullDevice
+ do { try p.run() } catch { return }
+ let killer = DispatchWorkItem { if p.isRunning { p.terminate() } }
+ DispatchQueue.global().asyncAfter(deadline: .now() + 4, execute: killer)
+ let data = out.fileHandleForReading.readDataToEndOfFile()
+ p.waitUntilExit()
+ killer.cancel()
+ var more: [SubscriptionCLI: String] = [:]
+ for line in String(decoding: data, as: UTF8.self).split(whereSeparator: \.isNewline) {
+ let path = line.trimmingCharacters(in: .whitespaces)
+ guard path.hasPrefix("/"), FileManager.default.isExecutableFile(atPath: path) else { continue }
+ let name = (path as NSString).lastPathComponent
+ for cli in SubscriptionCLI.allCases where more[cli] == nil && cli.binaries.contains(name) {
+ more[cli] = path
+ }
+ }
+ lock.lock()
+ var added = false
+ for (cli, path) in more where found[cli] == nil {
+ found[cli] = path
+ added = true
+ }
+ lock.unlock()
+ if added {
+ DispatchQueue.main.async { NotificationCenter.default.post(name: Self.changed, object: nil) }
+ }
+ }
+ }
+}
+
+extension CLIRelay {
+
+ /// Runs the tool once and returns the text of its answer.
+ static func ask(_ cli: SubscriptionCLI, _ request: CLIRequest) async throws -> String {
+ guard let exe = CLILocator.shared.path(cli) else { throw CLIFailure.notInstalled(cli.displayName) }
+ let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
+ let workdir = support.appendingPathComponent("NotchBuddy/relay", isDirectory: true)
+ try FileManager.default.createDirectory(at: workdir, withIntermediateDirectories: true)
+ var request = request
+ if cli == .gemini && !request.web {
+ let policy = workdir.appendingPathComponent("gemini-no-web.toml")
+ try? noWebPolicyTOML.write(to: policy, atomically: true, encoding: .utf8)
+ request.noWebPolicy = policy
+ }
+
+ let run = Run()
+ run.process.executableURL = URL(fileURLWithPath: exe)
+ run.process.arguments = arguments(cli, request)
+ run.process.currentDirectoryURL = workdir
+ var env = ProcessInfo.processInfo.environment
+ env.removeValue(forKey: "CLAUDECODE")
+ // An npm install is a `#!/usr/bin/env node` script: its own folder (nvm keeps Node
+ // there) and the usual ones first on PATH so it finds its Node.
+ let dir = (exe as NSString).deletingLastPathComponent
+ env["PATH"] = ([dir, "/opt/homebrew/bin", "/usr/local/bin"] + [env["PATH"] ?? "/usr/bin:/bin"])
+ .joined(separator: ":")
+ env["NO_COLOR"] = "1"
+ run.process.environment = env
+ run.process.standardInput = run.input
+ run.process.standardOutput = run.output
+ run.process.standardError = run.errors
+ let stdin = cli.promptOnStdin ? Data(fullPrompt(cli, request).utf8) : Data()
+ let timeout = request.timeout
+
+ return try await withCheckedThrowingContinuation { continuation in
+ DispatchQueue.global(qos: .userInitiated).async {
+ do { try run.process.run() } catch {
+ continuation.resume(throwing: CLIFailure.failed("Could not start \(cli.displayName): \(error.localizedDescription)"))
+ return
+ }
+ let timer = DispatchWorkItem { if run.process.isRunning { run.process.terminate() } }
+ DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: timer)
+ if !stdin.isEmpty { run.input.fileHandleForWriting.write(stdin) }
+ try? run.input.fileHandleForWriting.close()
+ // Read both pipes to the end before waiting, so a long answer can't fill one and stall.
+ let group = DispatchGroup()
+ group.enter()
+ DispatchQueue.global().async { run.stderrData = run.errors.fileHandleForReading.readDataToEndOfFile(); group.leave() }
+ let stdoutData = run.output.fileHandleForReading.readDataToEndOfFile()
+ group.wait()
+ run.process.waitUntilExit()
+ timer.cancel()
+ if run.process.terminationReason == .uncaughtSignal {
+ continuation.resume(throwing: CLIFailure.timedOut(cli.displayName))
+ return
+ }
+ switch parse(cli, stdout: stdoutData, stderr: run.stderrData, exitCode: run.process.terminationStatus) {
+ case .success(let text): continuation.resume(returning: text)
+ case .failure(let failure): continuation.resume(throwing: failure)
+ }
+ }
+ }
+ }
+
+ /// One run's process and pipes, handed between the queues that drive it.
+ private final class Run: @unchecked Sendable {
+ let process = Process()
+ let input = Pipe(), output = Pipe(), errors = Pipe()
+ var stderrData = Data()
+ }
+
+ /// A dropped file copied alone into a fresh folder, so Claude Code can read that file
+ /// and nothing else that was ever dropped. Removed by the caller once the run is over.
+ static func isolate(_ file: URL) throws -> URL {
+ let dir = FileManager.default.temporaryDirectory
+ .appendingPathComponent("coucou-relay-\(UUID().uuidString)", isDirectory: true)
+ try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
+ try FileManager.default.copyItem(at: file, to: dir.appendingPathComponent(file.lastPathComponent))
+ return dir
+ }
+
+ /// A dropped text file's contents for the tools that can't read files here (up to
+ /// 200 KB), or nil for anything else.
+ static func inlineText(_ file: URL) -> String? {
+ guard let size = (try? file.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, size <= 200_000,
+ let data = try? Data(contentsOf: file),
+ let text = String(data: data, encoding: .utf8), !text.contains("\u{0}") else { return nil }
+ return text
+ }
+}
+#endif
diff --git a/NotchBuddy/Sources/App/ChatSubscription.swift b/NotchBuddy/Sources/App/ChatSubscription.swift
new file mode 100644
index 00000000..599ebf27
--- /dev/null
+++ b/NotchBuddy/Sources/App/ChatSubscription.swift
@@ -0,0 +1,105 @@
+import Foundation
+
+// MARK: - Which chat providers can answer through the user's subscription
+//
+// Settings → Chat → Your AI subscriptions: one switch per provider. On, the chat goes
+// through the provider's own terminal tool (CLIRelay.swift); off, through its API key.
+// Cursor and GitHub Copilot have no API here: the switch shows or hides them in the chat.
+
+extension ChatProvider {
+ /// The tools that answer for this provider, the preferred one first. Empty: API only.
+ var subscriptionCLIs: [SubscriptionCLI] {
+ switch self {
+ case .anthropic: [.claude]
+ case .google: [.antigravity, .gemini]
+ case .openai: [.codex]
+ case .cursor: [.cursor]
+ case .copilot: [.copilot]
+ case .ollama, .lmstudio, .deepseek, .qwen, .moonshot: []
+ }
+ }
+
+ /// Answered only through a subscription (no key to fall back on).
+ var subscriptionOnly: Bool { self == .cursor || self == .copilot }
+
+ /// The providers listed under "Your AI subscriptions", in order.
+ static let subscriptionProviders: [ChatProvider] = [.anthropic, .google, .openai, .cursor, .copilot]
+
+ /// The name under "Your AI subscriptions": the plan people know.
+ var subscriptionName: String {
+ switch self {
+ case .anthropic: "Claude"
+ case .google: "Google Gemini"
+ case .openai: "ChatGPT"
+ case .cursor: "Cursor"
+ case .copilot: "GitHub Copilot"
+ default: displayName
+ }
+ }
+
+ #if !APPSTORE
+ /// The installed tool that answers for this provider, if any.
+ var installedCLI: SubscriptionCLI? {
+ subscriptionCLIs.first { CLILocator.shared.isInstalled($0) }
+ }
+ #endif
+}
+
+extension AppState {
+ private static func subscriptionKey(_ p: ChatProvider) -> String { "chat.useSubscription.\(p.rawValue)" }
+
+ /// Whether the chat with `p` goes through the user's subscription.
+ func usesSubscription(_ p: ChatProvider) -> Bool {
+ #if APPSTORE
+ return false
+ #else
+ guard !p.subscriptionCLIs.isEmpty else { return false }
+ if let chosen = UserDefaults.standard.object(forKey: Self.subscriptionKey(p)) as? Bool { return chosen }
+ // Never chosen: on when there is no key to use instead (what 0.5.5 did for Claude),
+ // and for Cursor and Copilot once their tool is installed.
+ if p.subscriptionOnly { return p.installedCLI != nil }
+ return (KeychainStore.shared.get(p.keychainKey) ?? "").isEmpty
+ #endif
+ }
+
+ func setUsesSubscription(_ on: Bool, for p: ChatProvider) {
+ UserDefaults.standard.set(on, forKey: Self.subscriptionKey(p))
+ objectWillChange.send()
+ // The chat can't stay on a provider that no longer answers.
+ if !on && p.subscriptionOnly && chatProvider == p { chatProvider = .anthropic }
+ fetchedProviderModels[p] = nil
+ providerModelFetchError[p] = nil
+ }
+
+ /// Shown on the chat's model chip.
+ var chatChipLabel: String {
+ #if !APPSTORE
+ if usesSubscription(chatProvider) {
+ let tool = (chatProvider.installedCLI ?? chatProvider.subscriptionCLIs.first)?.displayName ?? ""
+ return chatProvider == .anthropic ? "\(claudeModel) · \(tool)" : tool
+ }
+ #endif
+ return activeChatModel
+ }
+}
+
+extension AppState {
+ /// The subscription answers for `p` right now: switched on and its tool installed.
+ func subscriptionReady(_ p: ChatProvider) -> Bool { subscriptionTool(p) != nil }
+
+ /// The tool answering for `p` through the subscription, if it does.
+ func subscriptionTool(_ p: ChatProvider) -> String? {
+ #if APPSTORE
+ return nil
+ #else
+ guard usesSubscription(p) else { return nil }
+ return p.installedCLI?.displayName
+ #endif
+ }
+
+ /// The model the chat's picker shows as chosen: the tool's own default ("") when a
+ /// tool other than Claude Code answers.
+ var pickerModel: String {
+ usesSubscription(chatProvider) && chatProvider != .anthropic ? "" : activeChatModel
+ }
+}
diff --git a/NotchBuddy/Sources/App/ClaudeCodeRelay.swift b/NotchBuddy/Sources/App/ClaudeCodeRelay.swift
deleted file mode 100644
index 68aa6948..00000000
--- a/NotchBuddy/Sources/App/ClaudeCodeRelay.swift
+++ /dev/null
@@ -1,181 +0,0 @@
-import Foundation
-
-// MARK: - The Claude Code relay (GitHub build)
-//
-// With no Anthropic API key saved, the chat is answered by the user's own Claude
-// Code (`claude -p`), signed in with their own account: their Claude plan, no key.
-// Coucou reads no credential and makes no network call of its own; Claude Code
-// answers exactly as it does in a terminal. Same design as the Windows and Linux
-// relay (windows/src-tauri/src/claude_code.rs, #903).
-//
-// Each run is kept apart from the user's sessions: no settings file is loaded (so
-// no hooks: Coucou's own would show the relay's runs as sessions), no MCP server,
-// no skill or slash command, nothing saved to resume, and it runs in an empty
-// folder of Coucou's, so no CLAUDE.md is picked up. It may only use the tools it
-// is given: web search for the chat or, with no web at all, reading the one
-// dropped file, copied alone into a folder of its own.
-//
-// The App Store build is sandboxed and can't start `claude`: there the chat still
-// needs a key.
-
-enum ClaudeCodeRelay {
-
- #if APPSTORE
- static var isAvailable: Bool { false }
- #else
- static var isAvailable: Bool { executable() != nil }
- #endif
-
- /// Where `claude` usually lives; the app doesn't get the shell's PATH.
- static func executable() -> String? {
- let home = FileManager.default.homeDirectoryForCurrentUser.path
- let candidates = [
- "\(home)/.local/bin/claude",
- "\(home)/.claude/local/claude",
- "/opt/homebrew/bin/claude",
- "/usr/local/bin/claude",
- "\(home)/.npm-global/bin/claude",
- "\(home)/.volta/bin/claude",
- "\(home)/.bun/bin/claude",
- ]
- return candidates.first { FileManager.default.isExecutableFile(atPath: $0) }
- }
-
- struct Request: Sendable {
- var model: String
- var system: String
- var prompt: String
- /// Built-in tools the run may use; none at all when empty.
- var tools: [String]
- /// A folder the run may read from, besides its own.
- var readDir: URL?
- var timeout: TimeInterval
- }
-
- enum Failure: LocalizedError {
- case notInstalled, timedOut, noAnswer, failed(String)
- var errorDescription: String? {
- switch self {
- case .notInstalled: return "Claude Code is not installed."
- case .timedOut: return "Claude Code took too long to answer."
- case .noAnswer: return "Claude Code gave no answer."
- case .failed(let why): return why
- }
- }
- }
-
- /// The command line of one run. Pure, so it can be tested.
- static func arguments(_ r: Request) -> [String] {
- var out = ["-p", "--output-format", "json", "--model", r.model, "--system-prompt", r.system,
- "--tools", r.tools.joined(separator: ",")]
- if !r.tools.isEmpty { out += ["--allowedTools", r.tools.joined(separator: ",")] }
- if let dir = r.readDir { out += ["--add-dir", dir.path] }
- out += ["--setting-sources", "", "--strict-mcp-config", "--no-session-persistence", "--disable-slash-commands"]
- return out
- }
-
- /// The answer's text from `claude -p --output-format json`, or why there is none.
- static func parse(_ stdout: Data) -> Result<String, Failure> {
- guard let json = (try? JSONSerialization.jsonObject(with: stdout)) as? [String: Any] else {
- return .failure(.noAnswer)
- }
- let result = (json["result"] as? String ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
- if json["is_error"] as? Bool == true {
- return .failure(.failed(result.isEmpty ? "Claude Code could not answer." : result))
- }
- return result.isEmpty ? .failure(.noAnswer) : .success(result)
- }
-
- /// One chat turn as a single prompt: the earlier turns, the context the first
- /// question carries, then the question.
- static func chatPrompt(history: [(user: String, assistant: String)], context: String?, query: String) -> String {
- var out = ""
- if !history.isEmpty {
- out += "The conversation so far:\n<conversation>\n"
- for turn in history {
- out += "<user>\n\(turn.user)\n</user>\n<assistant>\n\(turn.assistant)\n</assistant>\n"
- }
- out += "</conversation>\n\nThe user's new message:\n"
- }
- if let context { out += context + "\n\n" }
- return out + query
- }
-
- #if !APPSTORE
- /// Runs `claude -p` once and returns the text of its answer.
- static func ask(_ request: Request) async throws -> String {
- guard let exe = executable() else { throw Failure.notInstalled }
- let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
- let workdir = support.appendingPathComponent("NotchBuddy/relay", isDirectory: true)
- try FileManager.default.createDirectory(at: workdir, withIntermediateDirectories: true)
-
- let run = Run()
- run.process.executableURL = URL(fileURLWithPath: exe)
- run.process.arguments = arguments(request)
- run.process.currentDirectoryURL = workdir
- var env = ProcessInfo.processInfo.environment
- env.removeValue(forKey: "CLAUDECODE")
- // An npm install is a `#!/usr/bin/env node` script: its own folder and the
- // usual ones first on PATH so it finds its Node.
- let dir = (exe as NSString).deletingLastPathComponent
- env["PATH"] = ([dir, "/opt/homebrew/bin", "/usr/local/bin"] + [env["PATH"] ?? "/usr/bin:/bin"])
- .joined(separator: ":")
- run.process.environment = env
- run.process.standardInput = run.input
- run.process.standardOutput = run.output
- run.process.standardError = run.errors
- let prompt = Data(request.prompt.utf8)
- let timeout = request.timeout
-
- return try await withCheckedThrowingContinuation { continuation in
- DispatchQueue.global(qos: .userInitiated).async {
- do { try run.process.run() } catch {
- continuation.resume(throwing: Failure.failed("Could not start Claude Code: \(error.localizedDescription)"))
- return
- }
- let timer = DispatchWorkItem { if run.process.isRunning { run.process.terminate() } }
- DispatchQueue.global().asyncAfter(deadline: .now() + timeout, execute: timer)
- run.input.fileHandleForWriting.write(prompt)
- try? run.input.fileHandleForWriting.close()
- // Read both pipes to the end before waiting, so a long answer can't fill one and stall.
- let group = DispatchGroup()
- group.enter()
- DispatchQueue.global().async { run.stderrData = run.errors.fileHandleForReading.readDataToEndOfFile(); group.leave() }
- let stdoutData = run.output.fileHandleForReading.readDataToEndOfFile()
- group.wait()
- run.process.waitUntilExit()
- timer.cancel()
- if run.process.terminationReason == .uncaughtSignal {
- continuation.resume(throwing: Failure.timedOut)
- return
- }
- switch parse(stdoutData) {
- case .success(let text): continuation.resume(returning: text)
- case .failure(let failure):
- let detail = String(decoding: run.stderrData, as: UTF8.self)
- .split(separator: "\n").last.map(String.init)?.trimmingCharacters(in: .whitespaces) ?? ""
- if detail.isEmpty { continuation.resume(throwing: failure) }
- else { continuation.resume(throwing: Failure.failed("\(failure.localizedDescription) (\(detail))")) }
- }
- }
- }
- }
-
- /// One run's process and pipes, handed between the queues that drive it.
- private final class Run: @unchecked Sendable {
- let process = Process()
- let input = Pipe(), output = Pipe(), errors = Pipe()
- var stderrData = Data()
- }
-
- /// A dropped file copied alone into a fresh folder, so the run can read that file and
- /// nothing else that was ever dropped. Removed by the caller once the run is over.
- static func isolate(_ file: URL) throws -> URL {
- let dir = FileManager.default.temporaryDirectory
- .appendingPathComponent("coucou-relay-\(UUID().uuidString)", isDirectory: true)
- try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
- try FileManager.default.copyItem(at: file, to: dir.appendingPathComponent(file.lastPathComponent))
- return dir
- }
- #endif
-}
diff --git a/NotchBuddy/Sources/App/ClaudeService.swift b/NotchBuddy/Sources/App/ClaudeService.swift
index b95ec5d9..3c5d14e2 100644
--- a/NotchBuddy/Sources/App/ClaudeService.swift
+++ b/NotchBuddy/Sources/App/ClaudeService.swift
@@ -222,17 +222,29 @@ final class ClaudeService {
/// Whether the chat can answer with Claude: an API key, or else Claude Code (GitHub build).
var canAnswer: Bool {
- !(apiKey ?? "").isEmpty || ClaudeCodeRelay.isAvailable
+ #if APPSTORE
+ return !(apiKey ?? "").isEmpty
+ #else
+ return !(apiKey ?? "").isEmpty || CLILocator.shared.isInstalled(.claude)
+ #endif
}
#if !APPSTORE
- // MARK: - Chat through Claude Code (no API key)
+ // MARK: - Chat through the user's subscription (CLIRelay.swift)
/// The relay's turns, as plain text: they never mix with the API's content blocks.
private var relayHistory: [(user: String, assistant: String)] = []
- private func chatThroughClaudeCode(query: String, context: PromptContext?, state: AppState) async {
+ private func chatThroughSubscription(_ provider: ChatProvider, query: String, context: PromptContext?, state: AppState) async {
+ guard let cli = provider.installedCLI else {
+ let tool = provider.subscriptionCLIs.first?.displayName ?? provider.displayName
+ await showError(String(format: String(localized: "chat.subscriptions.error.missing"), tool), state: state)
+ return
+ }
var contextLine: String?
+ // What later turns see of this one: never a file's contents, which go out with
+ // the web search of the turns after it otherwise.
+ var historyContext: String?
var readDir: URL?
if relayHistory.isEmpty, let context {
switch context {
@@ -240,29 +252,38 @@ final class ClaudeService {
var text = "Context — App: \(app), Window: \(title)"
if let url { text += ", URL: \(url)" }
contextLine = text
+ historyContext = text
case .file(let name, let fileURL):
- if let fileURL, let dir = try? ClaudeCodeRelay.isolate(fileURL) {
+ historyContext = "File: \(name)"
+ if cli == .claude, let fileURL, let dir = try? CLIRelay.isolate(fileURL) {
readDir = dir
contextLine = "File: \(name) (read it at \(dir.appendingPathComponent(fileURL.lastPathComponent).path))"
+ } else if let fileURL, let text = CLIRelay.inlineText(fileURL) {
+ contextLine = "File: \(name)\nFile contents:\n\(text)"
} else {
- contextLine = "File: \(name)"
+ contextLine = "File: \(name) (its contents can't be read here)"
}
}
}
defer { if let readDir { try? FileManager.default.removeItem(at: readDir) } }
- let request = ClaudeCodeRelay.Request(
- model: model,
+ // A dropped file is read with no web at all: a file written to steer the model
+ // could otherwise send what it reads to a website.
+ let readsFile: Bool = {
+ if case .file = context, relayHistory.isEmpty { return true }
+ return false
+ }()
+ let request = CLIRequest(
+ model: provider == .anthropic ? model : nil,
system: systemPrompt,
- prompt: ClaudeCodeRelay.chatPrompt(history: relayHistory, context: contextLine, query: query),
- // Reading a dropped file, no web at all: a file written to steer the model
- // could otherwise send what it reads to a website.
- tools: readDir == nil ? ["WebSearch", "WebFetch"] : ["Read"],
+ prompt: CLIRelay.chatPrompt(history: relayHistory, context: contextLine, query: query),
+ web: !readsFile,
readDir: readDir,
+ noWebPolicy: nil,
timeout: 180
)
do {
- let text = try await ClaudeCodeRelay.ask(request)
- relayHistory.append((user: contextLine.map { "\($0)\n\n\(query)" } ?? query, assistant: text))
+ let text = try await CLIRelay.ask(cli, request)
+ relayHistory.append((user: historyContext.map { "\($0)\n\n\(query)" } ?? query, assistant: text))
state.chatHistory.append(ChatMessage(role: .assistant, content: text))
state.stateOverride = nil
state.view = .prompt
@@ -306,18 +327,19 @@ final class ClaudeService {
state.stateOverride = nil
return
}
+ #if !APPSTORE
+ // "Use my subscription": the provider's own terminal tool answers, signed in with
+ // the user's account.
+ if state.usesSubscription(state.chatProvider) {
+ await chatThroughSubscription(state.chatProvider, query: query, context: context, state: state)
+ return
+ }
+ #endif
guard state.chatProvider == .anthropic else {
await chatOpenAICompatible(query: query, context: context, state: state)
return
}
guard let key = apiKey, !key.isEmpty else {
- #if !APPSTORE
- // No key: the user's own Claude Code answers, on their Claude plan.
- if ClaudeCodeRelay.isAvailable {
- await chatThroughClaudeCode(query: query, context: context, state: state)
- return
- }
- #endif
await showError("API key missing. Open settings.", state: state)
return
}
@@ -378,7 +400,7 @@ final class ClaudeService {
case .deepseek: baseURL = "https://api.deepseek.com/v1"
case .qwen: baseURL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
case .moonshot: baseURL = "https://api.moonshot.cn/v1"
- case .anthropic, .ollama, .lmstudio: baseURL = ""
+ case .anthropic, .ollama, .lmstudio, .cursor, .copilot: baseURL = ""
}
}
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
index e6f63b1a..f88489c8 100644
--- a/NotchBuddy/Sources/App/IslandViewContent.swift
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -1475,7 +1475,7 @@ struct PromptView: View {
Circle()
.fill(Color(hex: state.chatProvider.accentHex))
.frame(width: 6, height: 6)
- Text(state.activeChatModel)
+ Text(state.chatChipLabel)
.font(.system(size: 10.5, weight: .medium))
.foregroundColor(Color(hex: "#7B8089"))
Image(systemName: "chevron.up.chevron.down")
@@ -1632,6 +1632,8 @@ struct ModelPickerView: View {
let visibleProviders = ChatProvider.allCases.filter { p in
if p == .ollama { return !AppState.shared.ollamaServerURL.isEmpty || state.chatProvider == .ollama }
if p == .lmstudio { return !AppState.shared.lmstudioServerURL.isEmpty || state.chatProvider == .lmstudio }
+ // Cursor and Copilot answer only through the subscription switched on in Settings.
+ if p.subscriptionOnly { return state.usesSubscription(p) || state.chatProvider == p }
return true
}
ChipFlowLayout(spacing: 6) {
@@ -1713,6 +1715,8 @@ struct ModelPickerView: View {
VStack(alignment: .leading, spacing: 2) {
ForEach(models, id: \.id) { model in
Button {
+ // The tool's own default model: nothing to pick.
+ guard !model.id.isEmpty else { isPresented = false; return }
switch state.chatProvider {
case .anthropic: state.claudeModel = model.id
case .google: state.googleChatModel = model.id
@@ -1722,6 +1726,7 @@ struct ModelPickerView: View {
case .deepseek: state.deepseekChatModel = model.id
case .qwen: state.qwenChatModel = model.id
case .moonshot: state.moonshotChatModel = model.id
+ case .cursor, .copilot: break
}
isPresented = false
SoundEngine.shared.play("blip")
@@ -1729,11 +1734,11 @@ struct ModelPickerView: View {
HStack {
Text(model.label)
.font(.system(size: 12))
- .foregroundColor(state.activeChatModel == model.id
+ .foregroundColor(state.pickerModel == model.id
? Color(hex: state.chatProvider.accentHex)
: Color(hex: "#C8CDD4"))
Spacer()
- if state.activeChatModel == model.id {
+ if state.pickerModel == model.id {
Image(systemName: "checkmark")
.font(.system(size: 10, weight: .semibold))
.foregroundColor(Color(hex: state.chatProvider.accentHex))
@@ -1741,7 +1746,7 @@ struct ModelPickerView: View {
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
- .background(state.activeChatModel == model.id
+ .background(state.pickerModel == model.id
? Color(hex: state.chatProvider.accentHex).opacity(0.1)
: Color.clear)
.clipShape(RoundedRectangle(cornerRadius: 6))
@@ -2008,9 +2013,9 @@ struct IntegrationCardView: View {
return true // public market data: no key, nothing to set up
case "integration_portfolio":
return PortfolioSettings.hasAnyAccount
- case "ai_anthropic": return KeychainStore.shared.get("anthropic-api-key") != nil || ClaudeCodeRelay.isAvailable
- case "ai_google": return KeychainStore.shared.get("google-api-key") != nil
- case "ai_openai": return KeychainStore.shared.get("openai-api-key") != nil
+ case "ai_anthropic": return KeychainStore.shared.get("anthropic-api-key") != nil || AppState.shared.subscriptionReady(.anthropic)
+ case "ai_google": return KeychainStore.shared.get("google-api-key") != nil || AppState.shared.subscriptionReady(.google)
+ case "ai_openai": return KeychainStore.shared.get("openai-api-key") != nil || AppState.shared.subscriptionReady(.openai)
case "ai_ollama": return !AppState.shared.ollamaServerURL.isEmpty
case "ai_lmstudio": return !AppState.shared.lmstudioServerURL.isEmpty
case "integration_resend": return KeychainStore.shared.get("resend-api-key") != nil
@@ -2178,6 +2183,9 @@ struct IntegrationCardView: View {
let model = provider == .ollama ? appState.ollamaChatModel : appState.lmstudioChatModel
return String(localized: "Connected · \(model)")
}
+ if let tool = appState.subscriptionTool(provider) {
+ return String(format: String(localized: "chat.subscriptions.pill"), tool)
+ }
let model: String
switch task.id {
case "ai_anthropic": model = appState.claudeModel
diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift
index 3fb81f78..b56c6f19 100644
--- a/NotchBuddy/Sources/App/SettingsView.swift
+++ b/NotchBuddy/Sources/App/SettingsView.swift
@@ -34,6 +34,8 @@ struct SettingsView: View {
@State private var hookNeedsUpdate: Bool = HookServer.hooksNeedUpdate()
#if !APPSTORE
+ /// Bumped when a subscription tool is found or a switch moves: redraws Settings → Chat.
+ @State private var cliScan = 0
@State private var showStatusLineDiff: Bool = false
@State private var pendingStatusLineJSON: String = ""
@State private var statusLinePendingInstall: Bool = true
@@ -1039,7 +1041,74 @@ struct SettingsView: View {
// MARK: - Chat section
+ #if !APPSTORE
+ /// One provider under "Your AI subscriptions": its switch, and whether its tool is there.
+ @ViewBuilder private func subscriptionRow(_ provider: ChatProvider) -> some View {
+ let installed = provider.installedCLI
+ let tool = installed ?? provider.subscriptionCLIs[0]
+ VStack(alignment: .leading, spacing: 4) {
+ HStack(spacing: 8) {
+ Circle().fill(Color(hex: provider.accentHex)).frame(width: 8, height: 8)
+ Text(provider.subscriptionName).font(.system(size: 12, weight: .semibold))
+ Spacer()
+ Toggle(String(localized: "chat.subscriptions.use"), isOn: Binding(
+ get: { state.usesSubscription(provider) },
+ set: { on in
+ state.setUsesSubscription(on, for: provider)
+ cliScan += 1
+ }))
+ .toggleStyle(.switch)
+ .controlSize(.small)
+ }
+ if let installed {
+ Text(String(format: String(localized: "chat.subscriptions.found"), installed.displayName))
+ .font(.system(size: 11))
+ .foregroundColor(Color(hex: "#22C55E"))
+ Text(String(format: String(localized: "chat.subscriptions.sign-in"), installed.signIn))
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ .textSelection(.enabled)
+ } else {
+ HStack(spacing: 6) {
+ Text(String(format: String(localized: "chat.subscriptions.missing"), tool.displayName))
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ Button(String(localized: "chat.subscriptions.install")) {
+ if let url = URL(string: tool.installURL) { NSWorkspace.shared.open(url) }
+ }
+ .buttonStyle(.link)
+ .font(.system(size: 11))
+ }
+ }
+ if !provider.subscriptionOnly && !state.usesSubscription(provider) {
+ Text(String(localized: "chat.subscriptions.off"))
+ .font(.system(size: 11))
+ .foregroundColor(.secondary)
+ }
+ }
+ }
+ #endif
+
@ViewBuilder private var chatSection: some View {
+ #if !APPSTORE
+ GroupBox(String(localized: "chat.subscriptions.title")) {
+ VStack(alignment: .leading, spacing: 10) {
+ Text(String(localized: "chat.subscriptions.description"))
+ .font(.system(size: 12))
+ .foregroundColor(.secondary)
+ .fixedSize(horizontal: false, vertical: true)
+ ForEach(ChatProvider.subscriptionProviders, id: \.self) { provider in
+ subscriptionRow(provider)
+ if provider != ChatProvider.subscriptionProviders.last { Divider() }
+ }
+ }
+ .padding(6)
+ .id(cliScan)
+ }
+ .onAppear { CLILocator.shared.refresh() }
+ .onReceive(NotificationCenter.default.publisher(for: CLILocator.changed)) { _ in cliScan += 1 }
+ #endif
+
GroupBox(String(localized: "chat.anthropic-api.title")) {
VStack(alignment: .leading, spacing: 8) {
SecureField(String(localized: "chat.api-key.claude"), text: $apiKey)
@@ -1050,12 +1119,6 @@ struct SettingsView: View {
}
.buttonStyle(.borderedProminent)
- if apiKey.isEmpty && ClaudeCodeRelay.isAvailable {
- Text(String(localized: "chat.relay.no-key"))
- .font(.system(size: 11))
- .foregroundColor(.secondary)
- .fixedSize(horizontal: false, vertical: true)
- }
Divider().padding(.vertical, 2)
diff --git a/NotchBuddy/Sources/CoucouKit/IslandTypes.swift b/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
index 6707ed9b..7dc25bd8 100644
--- a/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
+++ b/NotchBuddy/Sources/CoucouKit/IslandTypes.swift
@@ -120,6 +120,9 @@ enum ChatProvider: String, CaseIterable, Codable {
case deepseek = "deepseek"
case qwen = "qwen"
case moonshot = "moonshot"
+ // Answered only through the user's own subscription (CLIRelay.swift, GitHub build)
+ case cursor = "cursor"
+ case copilot = "copilot"
var displayName: String {
switch self {
@@ -131,6 +134,8 @@ enum ChatProvider: String, CaseIterable, Codable {
case .deepseek: "DeepSeek"
case .qwen: "Qwen"
case .moonshot: "Moonshot"
+ case .cursor: "Cursor"
+ case .copilot: "GitHub Copilot"
}
}
@@ -144,6 +149,8 @@ enum ChatProvider: String, CaseIterable, Codable {
case .deepseek: "#5B8FF9"
case .qwen: "#FF6A00"
case .moonshot: "#7C5CFC"
+ case .cursor: "#A1A1AA"
+ case .copilot: "#8B5CF6"
}
}
@@ -157,6 +164,8 @@ enum ChatProvider: String, CaseIterable, Codable {
case .deepseek: "deepseek-chat"
case .qwen: "qwen-max"
case .moonshot: "moonshot-v1-32k"
+ case .cursor: ""
+ case .copilot: ""
}
}
@@ -170,6 +179,8 @@ enum ChatProvider: String, CaseIterable, Codable {
case .deepseek: "deepseek-api-key"
case .qwen: "qwen-api-key"
case .moonshot: "moonshot-api-key"
+ case .cursor: ""
+ case .copilot: ""
}
}
@@ -187,6 +198,8 @@ enum ChatProvider: String, CaseIterable, Codable {
case .deepseek: "ai_deepseek"
case .qwen: "ai_qwen"
case .moonshot: "ai_moonshot"
+ case .cursor: "ai_cursor"
+ case .copilot: "ai_copilot"
}
}
@@ -200,6 +213,8 @@ enum ChatProvider: String, CaseIterable, Codable {
case "ai_deepseek": self = .deepseek
case "ai_qwen": self = .qwen
case "ai_moonshot": self = .moonshot
+ case "ai_cursor": self = .cursor
+ case "ai_copilot": self = .copilot
default: return nil
}
}
diff --git a/scripts/test-cli-relay.sh b/scripts/test-cli-relay.sh
new file mode 100755
index 00000000..862e9fed
--- /dev/null
+++ b/scripts/test-cli-relay.sh
@@ -0,0 +1,8 @@
+#!/usr/bin/env bash
+set -euo pipefail
+cd "$(dirname "$0")/.."
+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-cli-relay.XXXXXX")"
+trap 'rm -rf "$TEST_DIR"' EXIT
+swiftc -swift-version 6 -strict-concurrency=complete \
+ NotchBuddy/Sources/App/CLIRelay.swift tests/CLIRelayTests.swift -o "$TEST_DIR/cli-relay-tests"
+"$TEST_DIR/cli-relay-tests"
diff --git a/tests/CLIRelayTests.swift b/tests/CLIRelayTests.swift
new file mode 100644
index 00000000..5a6f3e62
--- /dev/null
+++ b/tests/CLIRelayTests.swift
@@ -0,0 +1,121 @@
+import Foundation
+
+@main
+enum CLIRelayTests {
+ static func request(web: Bool = true, readDir: URL? = nil, policy: URL? = nil, model: String? = nil) -> CLIRequest {
+ CLIRequest(model: model, system: "SYS", prompt: "Hello?", web: web, readDir: readDir,
+ noWebPolicy: policy, timeout: 60)
+ }
+
+ static func main() {
+ commandLines()
+ answers()
+ failures()
+ prompt()
+ print("CLIRelay tests: all passed")
+ }
+
+ static func value(after flag: String, in args: [String]) -> String? {
+ guard let i = args.firstIndex(of: flag), i + 1 < args.count else { return nil }
+ return args[i + 1]
+ }
+
+ static func commandLines() {
+ // Claude Code: no settings, no MCP, nothing saved; web for the chat, Read for a file.
+ let chat = CLIRelay.arguments(.claude, request(model: "claude-sonnet-5"))
+ precondition(value(after: "--tools", in: chat) == "WebSearch,WebFetch")
+ precondition(value(after: "--setting-sources", in: chat) == "")
+ precondition(chat.contains("--strict-mcp-config") && chat.contains("--no-session-persistence"))
+ precondition(value(after: "--model", in: chat) == "claude-sonnet-5")
+ precondition(value(after: "--system-prompt", in: chat) == "SYS")
+ let dir = URL(fileURLWithPath: "/tmp/coucou-relay-x")
+ let file = CLIRelay.arguments(.claude, request(web: false, readDir: dir))
+ precondition(value(after: "--tools", in: file) == "Read" && value(after: "--add-dir", in: file) == dir.path)
+ precondition(!file.contains("--model"), "no model: Claude Code's own default")
+ // The others get the system prompt inside the prompt.
+ let gemini = CLIRelay.arguments(.gemini, request())
+ precondition(value(after: "-p", in: gemini)!.hasPrefix("<instructions>\nSYS\n</instructions>"))
+ precondition(value(after: "--approval-mode", in: gemini) == "plan" && value(after: "--extensions", in: gemini) == "none")
+ precondition(!gemini.contains("--policy"))
+ let policy = URL(fileURLWithPath: "/tmp/no-web.toml")
+ let geminiFile = CLIRelay.arguments(.gemini, request(web: false, policy: policy))
+ precondition(value(after: "--policy", in: geminiFile) == policy.path, "no web while a file is read")
+ let agy = CLIRelay.arguments(.antigravity, request())
+ precondition(value(after: "--mode", in: agy) == "plan" && value(after: "--output-format", in: agy) == "json")
+ // Codex: read-only, no shell, search only for the chat, prompt on stdin.
+ let codex = CLIRelay.arguments(.codex, request())
+ precondition(codex.first == "--search" && codex[1] == "exec" && codex.last == "-")
+ precondition(value(after: "--sandbox", in: codex) == "read-only" && codex.contains("--ephemeral"))
+ precondition(codex.contains("shell_tool") && codex.contains("unified_exec"))
+ precondition(!CLIRelay.arguments(.codex, request(web: false)).contains("--search"))
+ // Cursor: ask mode, never --force.
+ let cursor = CLIRelay.arguments(.cursor, request())
+ precondition(value(after: "--mode", in: cursor) == "ask" && !cursor.contains("--force") && !cursor.contains("--yolo"))
+ // Copilot: only the web fetch for the chat, nothing that writes or runs.
+ let copilot = CLIRelay.arguments(.copilot, request())
+ precondition(value(after: "--available-tools", in: copilot) == "web_fetch" && copilot.contains("--silent"))
+ precondition(!copilot.contains("--allow-all-tools") && !copilot.contains("--yolo"))
+ precondition(value(after: "--available-tools", in: CLIRelay.arguments(.copilot, request(web: false))) == "view")
+ precondition(!CLIRelay.arguments(.copilot, request(web: false)).contains("--allow-all-urls"))
+ // An empty model is the tool's default too.
+ precondition(!CLIRelay.arguments(.cursor, request(model: "")).contains("--model"))
+ precondition(SubscriptionCLI.claude.promptOnStdin && SubscriptionCLI.codex.promptOnStdin && !SubscriptionCLI.gemini.promptOnStdin)
+ }
+
+ static func ok(_ r: Result<String, CLIFailure>) -> String? {
+ if case .success(let s) = r { return s }
+ return nil
+ }
+
+ static func err(_ r: Result<String, CLIFailure>) -> String? {
+ if case .failure(let f) = r { return f.localizedDescription }
+ return nil
+ }
+
+ static func answers() {
+ let none = Data()
+ precondition(ok(CLIRelay.parse(.claude, stdout: Data(#"{"result":" Hi ","is_error":false}"#.utf8), stderr: none, exitCode: 0)) == "Hi")
+ precondition(ok(CLIRelay.parse(.cursor, stdout: Data("warming up\n{\"type\":\"result\",\"result\":\"Yo\",\"is_error\":false}".utf8), stderr: none, exitCode: 0)) == "Yo")
+ precondition(ok(CLIRelay.parse(.gemini, stdout: Data(#"{"response":"Bonjour","stats":{}}"#.utf8), stderr: none, exitCode: 0)) == "Bonjour")
+ precondition(ok(CLIRelay.parse(.antigravity, stdout: Data(#"{"status":"SUCCESS","response":"Hey"}"#.utf8), stderr: none, exitCode: 0)) == "Hey")
+ let events = """
+ {"type":"thread.started","thread_id":"t"}
+ {"type":"item.completed","item":{"id":"1","type":"reasoning","text":"thinking"}}
+ {"type":"item.completed","item":{"id":"2","type":"agent_message","text":"First"}}
+ {"type":"item.completed","item":{"id":"3","type":"agent_message","text":"Final answer"}}
+ {"type":"turn.completed","usage":{}}
+ """
+ precondition(ok(CLIRelay.parse(.codex, stdout: Data(events.utf8), stderr: none, exitCode: 0)) == "Final answer")
+ precondition(ok(CLIRelay.parse(.copilot, stdout: Data(" The answer\n".utf8), stderr: none, exitCode: 0)) == "The answer")
+ }
+
+ static func failures() {
+ let none = Data()
+ precondition(err(CLIRelay.parse(.claude, stdout: Data(#"{"result":"Credit balance is too low","is_error":true}"#.utf8), stderr: none, exitCode: 1)) == "Credit balance is too low")
+ // Gemini puts its error object on stderr.
+ let gErr = Data(#"{"session_id":"x","error":{"type":"Error","message":"Quota exceeded","code":1}}"#.utf8)
+ precondition(err(CLIRelay.parse(.gemini, stdout: none, stderr: gErr, exitCode: 1)) == "Quota exceeded")
+ // Not signed in: how to sign in.
+ let auth = Data(#"{"error":{"message":"Please set an Auth method in your settings.json"}}"#.utf8)
+ precondition(err(CLIRelay.parse(.gemini, stdout: none, stderr: auth, exitCode: 41))!.contains("Sign in once in Terminal: gemini"))
+ let codexAuth = Data(#"{"type":"error","message":"unexpected status 401 Unauthorized"}"#.utf8)
+ precondition(err(CLIRelay.parse(.codex, stdout: codexAuth, stderr: none, exitCode: 1))!.hasSuffix("codex login"))
+ let copilotAuth = Data("Error: Authentication token found but could not be validated.\nRun /login\n".utf8)
+ precondition(err(CLIRelay.parse(.copilot, stdout: none, stderr: copilotAuth, exitCode: 1))!.contains("not signed in"))
+ // Anything else: the tool's last words, without colours.
+ let crash = Data("\u{1B}[31mboom: model not found\u{1B}[0m\n".utf8)
+ precondition(err(CLIRelay.parse(.copilot, stdout: none, stderr: crash, exitCode: 1)) == "Copilot CLI gave no answer. (boom: model not found)")
+ precondition(err(CLIRelay.parse(.claude, stdout: Data("not json".utf8), stderr: none, exitCode: 1)) == "Claude Code gave no answer.")
+ let failedTurn = Data(#"{"type":"turn.failed","error":{"message":"Model overloaded"}}"#.utf8)
+ precondition(err(CLIRelay.parse(.codex, stdout: failedTurn, stderr: none, exitCode: 1)) == "Model overloaded")
+ }
+
+ static func prompt() {
+ let first = CLIRelay.chatPrompt(history: [], context: "File: a.txt", query: "What is it?")
+ precondition(first == "File: a.txt\n\nWhat is it?")
+ let later = CLIRelay.chatPrompt(history: [(user: "Hi", assistant: "Hello")], context: nil, query: "And?")
+ precondition(later.contains("<user>\nHi\n</user>\n<assistant>\nHello\n</assistant>") && later.hasSuffix("The user's new message:\nAnd?"))
+ precondition(CLIRelay.fullPrompt(.claude, request()) == "Hello?")
+ precondition(CLIRelay.noWebPolicyTOML.contains("google_web_search") && CLIRelay.noWebPolicyTOML.contains("\"deny\""))
+ }
+}