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
Flow dictation: hold a key, speak, the words are pasted where you type
Claudebab65ffe4ccc
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex d52b04ff..4dd68a00 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -33,6 +33,9 @@ jobs:- name: Test approval queuerun: bash scripts/test-approval-queue.sh+ - name: Test Flow dictation keys+ run: bash scripts/test-flow-keys.sh+- name: Desktop Mochi and gaze testsrun: bash scripts/test-desktop-mochi.shdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex a960b16a..771f6a63 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,5 +1,9 @@# Changelog+## Unreleased++- **Flow dictation** *(macOS, GitHub build)* — hold a key anywhere on the Mac (right ⌥ by default, or right ⌘, right ⌃ or fn), speak, let go: your words are pasted where you type, like Wispr Flow. A small pill at the bottom of the screen shows Mochi listening, its nine dots rising and falling with the graves and the aigus of your voice. Two quick taps keep it listening hands-free until the next tap; Esc cancels. Speech is recognised by the Mac (on-device when it can), and the clipboard gets back what it held after the paste. Off by default — Settings → Voice; it needs the Accessibility permission to see the key and paste+## Android 0.2.0 — October 13, 2026- **Home-screen widgets** — nine to pick from, each with a real preview in the widget picker: Mochi at a glance, Mochi's mood, Approvals waiting, Finished today, Plan usage, a one-line status with four buttons, all your agents, Mochi big (Mochi, plan usage and six buttons), and the agents summary, now on the same card. The colour follows your most urgent agent: orange when something waits for you, blue while it works, green when it's done, grey when the computer isn't there. Plan usage has its own colours (teal, yellow from 75 %, red from 90 %, with the time it resets). Read-only: the buttons only open a screen of the app, and a request is always decided in the app, behind your fingerprint. No background refresh: they redraw when something changes, plus once at midnight so Finished today starts again at zero, and that count stays on the phone (#620 by @Rhytam23)diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex ff726b2c..171a3401 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -47,6 +47,11 @@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 */; };+ 0AF77F5721986BE11151CE87 /* FlowSettingsBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0565D4D4D369E3ADD9CEF697 /* FlowSettingsBox.swift */; };+ 614F9783757FE777EF4CABB5 /* FlowPill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79D06C32348E26EAA1087BFC /* FlowPill.swift */; };+ F05CD98E6BF8679F12880345 /* FlowDictation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17870B121906BE24A935C407 /* FlowDictation.swift */; };+ 8B6743B43F9BB104B7C47981 /* FlowAudioBands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F2878AB6B6D0ED6F04F1583 /* FlowAudioBands.swift */; };+ EA0082A25D2A06EE27CA34DF /* FlowKeyLogic.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA7D186A42376F4F1277FED3 /* FlowKeyLogic.swift */; };1DAB0704A136FF8E6FB34191 /* ClaudeResponseText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 444604C7E2C530B664849EF9 /* ClaudeResponseText.swift */; };1DCF28998358810CDBC93F91 /* ClaudeHookDetection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1EA7D927F6BB2667D37AA963 /* ClaudeHookDetection.swift */; };1E55440B97C640993E93D04D /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = B32FB972D02162720E566674 /* DiffEngine.swift */; };@@ -127,6 +132,11 @@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 */; };+ 98863553DD449BD791A1E00C /* FlowSettingsBox.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0565D4D4D369E3ADD9CEF697 /* FlowSettingsBox.swift */; };+ 15C9E266B443EFE70908510B /* FlowPill.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79D06C32348E26EAA1087BFC /* FlowPill.swift */; };+ 8BF7CB586067C38AB5C4738C /* FlowDictation.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17870B121906BE24A935C407 /* FlowDictation.swift */; };+ B9DE5D941F640D9C701D0437 /* FlowAudioBands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F2878AB6B6D0ED6F04F1583 /* FlowAudioBands.swift */; };+ A093B567173936F128B68053 /* FlowKeyLogic.swift in Sources */ = {isa = PBXBuildFile; fileRef = CA7D186A42376F4F1277FED3 /* FlowKeyLogic.swift */; };68A950E3C23FD612639D9776 /* IslandViewContent.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA02B08886939FF6FE0475DD /* IslandViewContent.swift */; };68C3ACC708B69035FD0CB8C4 /* TurnSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1C4152EBDBD7C24CABFFD7 /* TurnSnapshot.swift */; };694AB4504CD65662E1681E5C /* ServicePublisher.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6F0C229BD085D76EB3DD94DF /* ServicePublisher.swift */; };@@ -460,6 +470,11 @@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>"; };+ 0565D4D4D369E3ADD9CEF697 /* FlowSettingsBox.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlowSettingsBox.swift; sourceTree = "<group>"; };+ 79D06C32348E26EAA1087BFC /* FlowPill.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlowPill.swift; sourceTree = "<group>"; };+ 17870B121906BE24A935C407 /* FlowDictation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlowDictation.swift; sourceTree = "<group>"; };+ 6F2878AB6B6D0ED6F04F1583 /* FlowAudioBands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlowAudioBands.swift; sourceTree = "<group>"; };+ CA7D186A42376F4F1277FED3 /* FlowKeyLogic.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = FlowKeyLogic.swift; sourceTree = "<group>"; };888B3E1420BCB6292BDC8117 /* WeeklyRecapView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeeklyRecapView.swift; sourceTree = "<group>"; };8ACB4350729C6513824D1ADF /* ColorHex.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ColorHex.swift; sourceTree = "<group>"; };8BF22817EC70748F2D1FB2E7 /* ClaudePlanGauge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudePlanGauge.swift; sourceTree = "<group>"; };@@ -615,6 +630,11 @@914A792788D403F836BEB570 /* SpotifyViews.swift */,2EF78999D68D56ADE4CEFBE2 /* StripePoller.swift */,87AF6F7A027AB1D46309DD49 /* TerminalTarget.swift */,+ 0565D4D4D369E3ADD9CEF697 /* FlowSettingsBox.swift */,+ 79D06C32348E26EAA1087BFC /* FlowPill.swift */,+ 17870B121906BE24A935C407 /* FlowDictation.swift */,+ 6F2878AB6B6D0ED6F04F1583 /* FlowAudioBands.swift */,+ CA7D186A42376F4F1277FED3 /* FlowKeyLogic.swift */,244A7909EEDA4BFF4C2EA9B5 /* TerminalTarget+AppKit.swift */,B241B043223AFBBFB7418A5E /* UploadCanvasView.swift */,6FD65943C32E150F1CD65C31 /* UploadSequenceEngine.swift */,@@ -1098,6 +1118,11 @@1558BB00C530B721172F6E65 /* StripePoller.swift in Sources */,9EA178EA395B116336C1FA10 /* TerminalTarget+AppKit.swift in Sources */,1D4CE0CCD2B5A0FFE50C7F06 /* TerminalTarget.swift in Sources */,+ 0AF77F5721986BE11151CE87 /* FlowSettingsBox.swift in Sources */,+ 614F9783757FE777EF4CABB5 /* FlowPill.swift in Sources */,+ F05CD98E6BF8679F12880345 /* FlowDictation.swift in Sources */,+ 8B6743B43F9BB104B7C47981 /* FlowAudioBands.swift in Sources */,+ EA0082A25D2A06EE27CA34DF /* FlowKeyLogic.swift in Sources */,8551E592C5FFC6A0A7458A26 /* TurnEndPolicy.swift in Sources */,0408FE7F86EBEE61CAED32DA /* TurnRecorder.swift in Sources */,68C3ACC708B69035FD0CB8C4 /* TurnSnapshot.swift in Sources */,@@ -1299,6 +1324,11 @@E4B9986674F4D425826F15A8 /* StripePoller.swift in Sources */,11F14DB97C93CF84DF9D5C43 /* TerminalTarget+AppKit.swift in Sources */,6726F74966EDE7F82BFE89B2 /* TerminalTarget.swift in Sources */,+ 98863553DD449BD791A1E00C /* FlowSettingsBox.swift in Sources */,+ 15C9E266B443EFE70908510B /* FlowPill.swift in Sources */,+ 8BF7CB586067C38AB5C4738C /* FlowDictation.swift in Sources */,+ B9DE5D941F640D9C701D0437 /* FlowAudioBands.swift in Sources */,+ A093B567173936F128B68053 /* FlowKeyLogic.swift in Sources */,ABE0CEF17018F1BAD8F7DBFA /* TurnEndPolicy.swift in Sources */,CE0A1BD64DF3E08D200691A6 /* TurnRecorder.swift in Sources */,4D34FF10654B19B69FE1964C /* TurnSnapshot.swift in Sources */,diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstringsindex 1367716a..c835d3bb 100644--- a/NotchBuddy/Resources/Localizable.xcstrings+++ b/NotchBuddy/Resources/Localizable.xcstrings@@ -75,6 +75,786 @@}}},+ "flow.accessibility" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "يحتاج Coucou إلى إذن تسهيلات الاستخدام لرؤية المفتاح ولصق كلماتك: فعّل Coucou في إعدادات النظام ← الخصوصية والأمن ← تسهيلات الاستخدام."+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "কী দেখতে আর আপনার কথা পেস্ট করতে Coucou-এর অ্যাক্সেসিবিলিটি অনুমতি দরকার: সিস্টেম সেটিংস → গোপনীয়তা ও নিরাপত্তা → অ্যাক্সেসিবিলিটিতে Coucou চালু করুন।"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Coucou needs the Accessibility permission to see the key and paste your words: turn on Coucou in System Settings → Privacy & Security → Accessibility."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Coucou necesita el permiso de Accesibilidad para ver la tecla y pegar tus palabras: activa Coucou en Ajustes del Sistema → Privacidad y seguridad → Accesibilidad."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Coucou a besoin de l'autorisation Accessibilité pour voir la touche et coller tes mots : active Coucou dans Réglages Système → Confidentialité et sécurité → Accessibilité."+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "कुंजी देखने और आपके शब्द चिपकाने के लिए Coucou को एक्सेसिबिलिटी अनुमति चाहिए: सिस्टम सेटिंग्स → गोपनीयता और सुरक्षा → एक्सेसिबिलिटी में Coucou चालू करें।"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Coucou butuh izin Aksesibilitas untuk melihat tombol dan menempel kata-katamu: aktifkan Coucou di Pengaturan Sistem → Privasi & Keamanan → Aksesibilitas."+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "O Coucou precisa da permissão de Acessibilidade para ver a tecla e colar suas palavras: ative o Coucou em Ajustes do Sistema → Privacidade e Segurança → Acessibilidade."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Coucou нужен доступ к Универсальному доступу, чтобы видеть клавишу и вставлять слова: включите Coucou в Системных настройках → Конфиденциальность и безопасность → Универсальный доступ."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Coucou 需要“辅助功能”权限才能识别按键并粘贴你的话:请在“系统设置”→“隐私与安全性”→“辅助功能”中打开 Coucou。"+ }+ }+ }+ },+ "flow.accessibility-open" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "فتح إعدادات تسهيلات الاستخدام"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "অ্যাক্সেসিবিলিটি সেটিংস খুলুন"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Open Accessibility settings"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Abrir ajustes de Accesibilidad"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ouvrir les réglages Accessibilité"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "एक्सेसिबिलिटी सेटिंग्स खोलें"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Buka pengaturan Aksesibilitas"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Abrir ajustes de Acessibilidade"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Открыть настройки Универсального доступа"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开辅助功能设置"+ }+ }+ }+ },+ "flow.copied" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "تم النسخ · اضغط ⌘V"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "কপি হয়েছে · ⌘V চাপুন"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Copied · press ⌘V"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Copiado · pulsa ⌘V"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Copié · fais ⌘V"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "कॉपी हुआ · ⌘V दबाएँ"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Disalin · tekan ⌘V"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Copiado · pressione ⌘V"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Скопировано · нажмите ⌘V"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已复制 · 按 ⌘V"+ }+ }+ }+ },+ "flow.enable" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "اضغط مطولًا على مفتاح للإملاء في أي مكان"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "যেকোনো জায়গায় ডিক্টেট করতে একটি কী চেপে ধরুন"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Hold a key to dictate anywhere"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mantén una tecla para dictar en cualquier lugar"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Maintenir une touche pour dicter partout"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "कहीं भी बोलकर लिखने के लिए एक कुंजी दबाए रखें"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tahan satu tombol untuk mendikte di mana saja"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Segure uma tecla para ditar em qualquer lugar"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Удерживайте клавишу, чтобы диктовать где угодно"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "按住一个键,在任何地方听写"+ }+ }+ }+ },+ "flow.failed" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "الميكروفون غير متاح"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "মাইক্রোফোন পাওয়া যাচ্ছে না"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Microphone unavailable"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Micrófono no disponible"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Micro indisponible"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "माइक्रोफ़ोन उपलब्ध नहीं"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mikrofon tidak tersedia"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Microfone indisponível"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Микрофон недоступен"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "麦克风不可用"+ }+ }+ }+ },+ "flow.fn-help" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "لاستخدام fn، اضبط إعدادات النظام ← لوحة المفاتيح ← «اضغط على مفتاح 🌐 لـ» على «عدم القيام بأي شيء»."+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn ব্যবহার করতে, সিস্টেম সেটিংস → কিবোর্ডে “🌐 কী চাপলে” “কিছুই করবেন না” সেট করুন।"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "To use fn, set System Settings → Keyboard → “Press 🌐 key to” to “Do Nothing”."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Para usar fn, en Ajustes del Sistema → Teclado, pon «Pulsar la tecla 🌐 para» en «No hacer nada»."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Pour utiliser fn, règle Réglages Système → Clavier → « Appuyer sur la touche 🌐 pour » sur « Ne rien faire »."+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn इस्तेमाल करने के लिए, सिस्टम सेटिंग्स → कीबोर्ड में “🌐 कुंजी दबाने पर” को “कुछ न करें” पर सेट करें।"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Untuk memakai fn, atur Pengaturan Sistem → Papan Ketik → “Tekan tombol 🌐 untuk” ke “Jangan Lakukan Apa-apa”."+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Para usar fn, em Ajustes do Sistema → Teclado, defina “Pressionar a tecla 🌐 para” como “Não fazer nada”."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Чтобы использовать fn, в Системных настройках → Клавиатура выберите для «Нажатие клавиши 🌐» вариант «Ничего не делать»."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要使用 fn,请在“系统设置”→“键盘”中将“按下 🌐 键时”设为“不执行任何操作”。"+ }+ }+ }+ },+ "flow.how %@" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "اضغط مطولًا على %@ وتحدث ثم اترك: تُلصق كلماتك حيث تكتب. اضغط مرتين للإملاء دون استخدام اليدين، ثم مرة أخرى للصق. Esc يلغي."+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ চেপে ধরুন, বলুন, ছেড়ে দিন: আপনি যেখানে লেখেন সেখানে আপনার কথা পেস্ট হয়। হাত ছাড়া ডিক্টেট করতে দুবার ট্যাপ করুন, পেস্ট করতে আরেকবার। Esc বাতিল করে।"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Hold %@, speak, let go: your words are pasted where you type. Tap it twice to keep listening hands-free, and once more to paste. Esc cancels."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Mantén %@, habla y suelta: tus palabras se pegan donde escribes. Púlsala dos veces para dictar sin manos y otra vez para pegar. Esc cancela."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Maintiens %@, parle, relâche : tes mots sont collés là où tu écris. Tape deux fois pour dicter sans les mains, puis une fois pour coller. Échap annule."+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ दबाए रखें, बोलें, छोड़ दें: आपके शब्द वहीं चिपक जाते हैं जहाँ आप टाइप करते हैं। बिना हाथ लगाए बोलने के लिए दो बार टैप करें, और चिपकाने के लिए एक बार फिर। Esc रद्द करता है।"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tahan %@, bicara, lalu lepas: kata-katamu ditempel di tempat kamu mengetik. Ketuk dua kali untuk mendikte tanpa tangan, lalu sekali lagi untuk menempel. Esc membatalkan."+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Segure %@, fale e solte: suas palavras são coladas onde você digita. Toque duas vezes para ditar sem as mãos e mais uma vez para colar. Esc cancela."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Удерживайте %@, говорите, отпустите — слова вставятся туда, где вы печатаете. Нажмите дважды, чтобы диктовать без рук, и ещё раз, чтобы вставить. Esc отменяет."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "按住 %@,说话,松开:你的话会粘贴到你正在输入的位置。连按两次可免手持听写,再按一次即粘贴。按 Esc 取消。"+ }+ }+ }+ },+ "flow.key" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "المفتاح"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "কী"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Key"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tecla"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Touche"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "कुंजी"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tombol"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tecla"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Клавиша"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "按键"+ }+ }+ }+ },+ "flow.key-fn" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "fn (🌐)"+ }+ }+ }+ },+ "flow.key-right %@" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ الأيمن"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ডান %@"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Right %@"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ derecha"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ de droite"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "दायाँ %@"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ kanan"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%@ da direita"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Правая %@"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "右侧 %@"+ }+ }+ }+ },+ "flow.privacy" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "يحوّل التعرّف على الكلام في جهاز Mac صوتك إلى نص، على الجهاز نفسه عندما يدعم جهازك ذلك؛ ولا يرسله Coucou إلى أي مكان. بعد اللصق تعود الحافظة إلى ما كانت تحتويه."+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "আপনার Mac-এর স্পিচ রিকগনিশন আপনার কণ্ঠকে টেক্সটে রূপান্তর করে, Mac সমর্থন করলে ডিভাইসেই; Coucou এটি কোথাও পাঠায় না। পেস্ট করার পর ক্লিপবোর্ডে আগের জিনিস ফিরে আসে।"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Your voice is turned into text by your Mac's speech recognition, on-device when your Mac supports it; Coucou sends it nowhere. After pasting, the clipboard gets back what it held."+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Tu voz se convierte en texto con el reconocimiento de voz de tu Mac, en el propio equipo cuando tu Mac lo admite; Coucou no la envía a ningún sitio. Tras pegar, el portapapeles recupera lo que tenía."+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ta voix est transformée en texte par la reconnaissance vocale de ton Mac, sur l'appareil quand ton Mac le permet ; Coucou ne l'envoie nulle part. Après le collage, le presse-papiers retrouve ce qu'il contenait."+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "आपकी आवाज़ को आपके Mac की वाक् पहचान टेक्स्ट में बदलती है, जब आपका Mac समर्थन करे तो डिवाइस पर ही; Coucou इसे कहीं नहीं भेजता। चिपकाने के बाद क्लिपबोर्ड में पहले वाली चीज़ वापस आ जाती है।"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Suaramu diubah menjadi teks oleh pengenalan suara Mac, langsung di perangkat bila Mac mendukungnya; Coucou tidak mengirimnya ke mana pun. Setelah menempel, papan klip kembali berisi apa yang ada sebelumnya."+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Sua voz vira texto pelo reconhecimento de fala do seu Mac, no próprio aparelho quando o Mac permite; o Coucou não a envia para lugar nenhum. Depois de colar, a área de transferência recupera o que tinha."+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ваш голос превращает в текст распознавание речи Mac — прямо на устройстве, если Mac это поддерживает; Coucou никуда его не отправляет. После вставки буфер обмена возвращает прежнее содержимое."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你的声音由 Mac 的语音识别转成文字,Mac 支持时在设备上完成;Coucou 不会把它发送到任何地方。粘贴之后,剪贴板会恢复原来的内容。"+ }+ }+ }+ },+ "flow.title" : {+ "extractionState" : "manual",+ "localizations" : {+ "ar" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "إملاء Flow"+ }+ },+ "bn" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Flow ডিক্টেশন"+ }+ },+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Flow dictation"+ }+ },+ "es" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dictado Flow"+ }+ },+ "fr" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dictée Flow"+ }+ },+ "hi" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Flow डिक्टेशन"+ }+ },+ "id" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Dikte Flow"+ }+ },+ "pt-BR" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Ditado Flow"+ }+ },+ "ru" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Диктовка Flow"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Flow 听写"+ }+ }+ }+ },"—" : {},diff --git a/NotchBuddy/Sources/App/AppDelegate.swift b/NotchBuddy/Sources/App/AppDelegate.swiftindex 912fc093..204f83bd 100644--- a/NotchBuddy/Sources/App/AppDelegate.swift+++ b/NotchBuddy/Sources/App/AppDelegate.swift@@ -191,6 +191,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {HookServer.shared.start()#if !APPSTORE_ = VoiceEngine.shared // registers system observers; starts mic only if the user enabled voice+ FlowDictation.shared.start() // watches the dictation key only if Flow dictation is on#endifN8nPoller.shared.start()VercelPoller.shared.start()diff --git a/NotchBuddy/Sources/App/FlowAudioBands.swift b/NotchBuddy/Sources/App/FlowAudioBands.swiftnew file mode 100644index 00000000..49d9edf7--- /dev/null+++ b/NotchBuddy/Sources/App/FlowAudioBands.swift@@ -0,0 +1,74 @@+#if !APPSTORE+import Accelerate+import AVFoundation+import os++/// Turns the microphone's buffers into nine levels (0…1) for the pill's dots, from the graves on+/// the left to the aigus on the right. Fed from the audio tap's thread, read by the pill at 60 fps;+/// the levels sit behind a lock. Nothing is kept: only the latest nine numbers.+final class FlowAudioBands: @unchecked Sendable {+ static let fftSize = 1024+ private let log2n = vDSP_Length(10)+ private let fft: vDSP.FFT<DSPSplitComplex>?+ private let window: [Float]+ private let lock = OSAllocatedUnfairLock(initialState: [Float](repeating: 0, count: FlowBands.count))+ private var ranges: [Range<Int>] = []+ private var rate: Double = 0+ // Scratch, used only on the tap's thread.+ private var frame = [Float](repeating: 0, count: FlowAudioBands.fftSize)+ private var real = [Float](repeating: 0, count: FlowAudioBands.fftSize / 2)+ private var imag = [Float](repeating: 0, count: FlowAudioBands.fftSize / 2)+ private var power = [Float](repeating: 0, count: FlowAudioBands.fftSize / 2)++ init() {+ fft = vDSP.FFT(log2n: log2n, radix: .radix2, ofType: DSPSplitComplex.self)+ window = vDSP.window(ofType: Float.self, usingSequence: .hanningDenormalized, count: Self.fftSize, isHalfWindow: false)+ }++ /// The latest levels, graves first.+ var levels: [Float] { lock.withLock { $0 } }++ func reset() { lock.withLock { $0 = [Float](repeating: 0, count: FlowBands.count) } }++ /// Called on the audio tap's thread for every buffer.+ func consume(_ buffer: AVAudioPCMBuffer) {+ guard let fft, let data = buffer.floatChannelData?[0] else { return }+ let n = Int(buffer.frameLength)+ guard n >= Self.fftSize else { return }+ let sampleRate = buffer.format.sampleRate+ if sampleRate != rate {+ rate = sampleRate+ ranges = FlowBands.binRanges(fftSize: Self.fftSize, sampleRate: sampleRate)+ }+ // The last 1024 samples of the buffer: the freshest sound.+ let start = n - Self.fftSize+ for i in 0..<Self.fftSize { frame[i] = data[start + i] * window[i] }++ real.withUnsafeMutableBufferPointer { rp in+ imag.withUnsafeMutableBufferPointer { ip in+ var split = DSPSplitComplex(realp: rp.baseAddress!, imagp: ip.baseAddress!)+ frame.withUnsafeBufferPointer { fp in+ fp.baseAddress!.withMemoryRebound(to: DSPComplex.self, capacity: Self.fftSize / 2) {+ vDSP_ctoz($0, 2, &split, 1, vDSP_Length(Self.fftSize / 2))+ }+ }+ var spectrum = split // the same buffers: vDSP transforms in place+ fft.forward(input: split, output: &spectrum)+ vDSP.squareMagnitudes(spectrum, result: &power)+ }+ }+ // vDSP's real FFT is scaled by 2; with the Hann window, a full-scale sine comes out near 0 dB.+ let scale = Float(1.0 / Double(Self.fftSize * Self.fftSize))+ var out = [Float](repeating: 0, count: FlowBands.count)+ for (i, range) in ranges.enumerated() {+ var sum: Float = 0+ for b in range where b < power.count { sum += power[b] }+ let db = 10 * log10(Double(max(sum * scale, 1e-12)))+ // Speech is weaker in the aigus: a little tilt so the right-hand dots move too.+ out[i] = Float(FlowBands.level(db: db + Double(i) * 2.2))+ }+ let latest = out+ lock.withLock { $0 = latest }+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/FlowDictation.swift b/NotchBuddy/Sources/App/FlowDictation.swiftnew file mode 100644index 00000000..451221ef--- /dev/null+++ b/NotchBuddy/Sources/App/FlowDictation.swift@@ -0,0 +1,302 @@+#if !APPSTORE+import AppKit+import ApplicationServices+import Carbon.HIToolbox++/// The key that you hold to dictate.+enum FlowKey: String, CaseIterable, Identifiable {+ case rightOption, rightCommand, rightControl, fn++ var id: String { rawValue }++ var keyCode: UInt16 {+ switch self {+ case .rightOption: return UInt16(kVK_RightOption)+ case .rightCommand: return UInt16(kVK_RightCommand)+ case .rightControl: return UInt16(kVK_RightControl)+ case .fn: return UInt16(kVK_Function)+ }+ }++ /// Whether this very key is down, from a flagsChanged event's flags. The device-dependent bits+ /// tell the right key from the left one, so holding the left ⌥ never keeps the right one "down".+ func isDown(_ flags: NSEvent.ModifierFlags) -> Bool {+ let raw = flags.rawValue+ switch self {+ case .rightOption: return raw & 0x0000_0040 != 0 // NX_DEVICERALTKEYMASK+ case .rightCommand: return raw & 0x0000_0010 != 0 // NX_DEVICERCMDKEYMASK+ case .rightControl: return raw & 0x0000_2000 != 0 // NX_DEVICERCTLKEYMASK+ case .fn: return flags.contains(.function)+ }+ }++ var symbol: String {+ switch self {+ case .rightOption: return "⌥"+ case .rightCommand: return "⌘"+ case .rightControl: return "⌃"+ case .fn: return "fn"+ }+ }++ var label: String {+ switch self {+ case .fn: return String(localized: "flow.key-fn")+ default: return String(format: String(localized: "flow.key-right %@"), symbol)+ }+ }+}++/// Flow dictation, like Wispr Flow (GitHub build): hold a key anywhere on the Mac, speak, let go,+/// and the words are pasted where you type. A small pill at the bottom of the screen shows that+/// Coucou listens, its dots moving with the graves and the aigus of your voice.+///+/// Speech is recognised by the Mac (on-device when it can, see MacDictation); pasting goes+/// through the clipboard and ⌘V, then the clipboard gets back what it held. Watching the key and+/// pasting both need the Accessibility permission. Off by default; nothing listens until you hold the key.+@MainActor+final class FlowDictation: ObservableObject {+ static let shared = FlowDictation()++ static let enabledKey = "flowDictationEnabled"+ static let keyKey = "flowDictationKey"++ @Published var isEnabled: Bool = UserDefaults.standard.bool(forKey: FlowDictation.enabledKey) {+ didSet {+ UserDefaults.standard.set(isEnabled, forKey: Self.enabledKey)+ if isEnabled && !AXIsProcessTrusted() { askForAccessibility() }+ refresh()+ }+ }+ @Published var key: FlowKey = FlowKey(rawValue: UserDefaults.standard.string(forKey: FlowDictation.keyKey) ?? "") ?? .rightOption {+ didSet {+ UserDefaults.standard.set(key.rawValue, forKey: Self.keyKey)+ cancelAll()+ }+ }+ /// Whether macOS lets Coucou watch the key and paste (System Settings → Privacy & Security → Accessibility).+ @Published private(set) var trusted: Bool = AXIsProcessTrusted()++ private var logic = FlowKeyLogic()+ private var monitors: [Any] = []+ private var current: Listen?+ private var startTask: Task<Void, Never>?+ private var tickTask: Task<Void, Never>?+ private var trustTask: Task<Void, Never>?+ private let bands = FlowAudioBands()+ let pill = FlowPillController()++ private init() {}++ /// At launch: listens for the key if Flow dictation is on.+ func start() { refresh() }++ func refresh() {+ removeMonitors()+ trusted = AXIsProcessTrusted()+ guard isEnabled else {+ cancelAll()+ trustTask?.cancel(); trustTask = nil+ return+ }+ installMonitors()+ if !trusted { waitForTrust() }+ }++ func askForAccessibility() {+ let options = ["AXTrustedCheckOptionPrompt": true] as CFDictionary+ trusted = AXIsProcessTrustedWithOptions(options)+ }++ func openAccessibilitySettings() {+ if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") {+ NSWorkspace.shared.open(url)+ }+ }++ // MARK: - The key++ private func installMonitors() {+ // A global monitor sees the key in other apps, a local one while Coucou itself is in front.+ if let global = NSEvent.addGlobalMonitorForEvents(matching: [.flagsChanged, .keyDown], handler: { [weak self] event in+ let info = (event.type, event.keyCode, event.modifierFlags)+ MainActor.assumeIsolated { self?.handle(type: info.0, keyCode: info.1, flags: info.2) }+ }) { monitors.append(global) }+ if let local = NSEvent.addLocalMonitorForEvents(matching: [.flagsChanged, .keyDown], handler: { [weak self] event in+ let info = (event.type, event.keyCode, event.modifierFlags)+ MainActor.assumeIsolated { self?.handle(type: info.0, keyCode: info.1, flags: info.2) }+ return event+ }) { monitors.append(local) }+ }++ private func removeMonitors() {+ monitors.forEach { NSEvent.removeMonitor($0) }+ monitors.removeAll()+ }++ /// Until macOS trusts Coucou, the global monitor gets nothing: check again every 2 s and+ /// reinstall the monitors once it does.+ private func waitForTrust() {+ trustTask?.cancel()+ trustTask = Task { @MainActor [weak self] in+ while !Task.isCancelled {+ try? await Task.sleep(for: .seconds(2))+ guard let self, self.isEnabled else { return }+ if AXIsProcessTrusted() {+ self.trusted = true+ self.removeMonitors()+ self.installMonitors()+ return+ }+ }+ }+ }++ private func handle(type: NSEvent.EventType, keyCode: UInt16, flags: NSEvent.ModifierFlags) {+ let now = ProcessInfo.processInfo.systemUptime+ switch type {+ case .keyDown:+ if keyCode == UInt16(kVK_Escape) { apply(logic.escape()) }+ else { apply(logic.otherKey()) }+ case .flagsChanged where keyCode == key.keyCode:+ apply(key.isDown(flags) ? logic.keyDown(at: now) : logic.keyUp(at: now))+ default:+ break+ }+ }++ private func apply(_ action: FlowKeyLogic.Action) {+ switch action {+ case .none: break+ case .start: begin()+ case .restart: abort(); begin()+ case .lock: pill.model.phase = .locked+ case .finish: finish()+ case .cancel: abort()+ }+ if case .tapWait(let until) = logic.phase { scheduleTick(at: until) }+ }++ private func scheduleTick(at until: Double) {+ tickTask?.cancel()+ let wait = max(0, until - ProcessInfo.processInfo.systemUptime) + 0.02+ tickTask = Task { @MainActor [weak self] in+ try? await Task.sleep(for: .seconds(wait))+ guard !Task.isCancelled, let self else { return }+ self.apply(self.logic.tick(at: ProcessInfo.processInfo.systemUptime))+ }+ }++ // MARK: - Listening++ /// One listen, from the key press to the paste. Cancelling it drops its words.+ private final class Listen {+ let dictation = MacDictation()+ var cancelled = false+ }++ private func begin() {+ let listen = Listen()+ current = listen+ bands.reset()+ listen.dictation.bands = bands+ pill.show(bands: bands)+ SoundEngine.shared.play("blip")+ startTask = Task { @MainActor [weak self] in+ await listen.dictation.start(from: "")+ guard let self else { return }+ if listen.cancelled { listen.dictation.stop(); return } // cancelled while the mic opened+ if !listen.dictation.isRecording, self.current === listen {+ // No permission, no recognizer for these languages, or no microphone.+ self.logic.reset()+ self.current = nil+ self.pill.flash(.failed)+ }+ }+ }++ private func finish() {+ guard let listen = current else { pill.hide(); return }+ pill.model.phase = .thinking+ let opening = startTask+ Task { @MainActor [weak self] in+ await opening?.value+ let text = await listen.dictation.finish().trimmingCharacters(in: .whitespacesAndNewlines)+ guard let self, !listen.cancelled else { return }+ // A new listen may have begun meanwhile: its pill is left alone, but these words still go in.+ let latest = self.current === listen+ if latest { self.current = nil }+ guard !text.isEmpty else { if latest { self.pill.hide() }; return }+ let pasted = FlowPaste.insert(text)+ guard latest else { return }+ if pasted { self.pill.hide() } else { self.pill.flash(.copied) } // no Accessibility: on the clipboard+ }+ }++ private func abort() {+ tickTask?.cancel()+ if let listen = current {+ listen.cancelled = true+ listen.dictation.stop()+ }+ current = nil+ pill.hide()+ }++ private func cancelAll() {+ logic.reset()+ abort()+ }+}++// MARK: - Paste++/// Puts the words where the cursor is: on the clipboard, then ⌘V, then the clipboard gets back what it held.+enum FlowPaste {+ @MainActor static func insert(_ text: String) -> Bool {+ let board = NSPasteboard.general+ let saved = snapshot(board)+ board.clearContents()+ board.setString(text, forType: .string)+ guard AXIsProcessTrusted() else { return false }++ let source = CGEventSource(stateID: .combinedSessionState)+ let v = CGKeyCode(kVK_ANSI_V)+ let down = CGEvent(keyboardEventSource: source, virtualKey: v, keyDown: true)+ let up = CGEvent(keyboardEventSource: source, virtualKey: v, keyDown: false)+ down?.flags = .maskCommand+ up?.flags = .maskCommand+ down?.post(tap: .cghidEventTap)+ up?.post(tap: .cghidEventTap)++ // Give the app time to read the clipboard, then put back what was there, unless something+ // else was copied meanwhile.+ let count = board.changeCount+ Task { @MainActor in+ try? await Task.sleep(for: .milliseconds(700))+ guard board.changeCount == count else { return }+ restore(saved, to: board)+ }+ return true+ }++ private static func snapshot(_ board: NSPasteboard) -> [[NSPasteboard.PasteboardType: Data]] {+ (board.pasteboardItems ?? []).map { item in+ var out: [NSPasteboard.PasteboardType: Data] = [:]+ for type in item.types { if let data = item.data(forType: type) { out[type] = data } }+ return out+ }+ }++ private static func restore(_ items: [[NSPasteboard.PasteboardType: Data]], to board: NSPasteboard) {+ board.clearContents()+ guard !items.isEmpty else { return }+ let objects: [NSPasteboardItem] = items.map { entry in+ let item = NSPasteboardItem()+ for (type, data) in entry { item.setData(data, forType: type) }+ return item+ }+ board.writeObjects(objects)+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/FlowKeyLogic.swift b/NotchBuddy/Sources/App/FlowKeyLogic.swiftnew file mode 100644index 00000000..76fccb1a--- /dev/null+++ b/NotchBuddy/Sources/App/FlowKeyLogic.swift@@ -0,0 +1,128 @@+import Foundation++/// The key logic of Flow dictation, with nothing from AppKit in it (tests/FlowKeyLogicTests.swift).+///+/// - Hold the key: Coucou listens. Release it: the words are pasted where you type.+/// - Two quick taps: hands-free, until the next tap.+/// - Esc, or another key pressed while the key is held (a shortcut such as ⌥E), cancels.+///+/// Listening starts on the first press, so a word said right away is not lost; a press too short+/// to be a hold waits a moment for the second tap, and is dropped if none comes.+struct FlowKeyLogic: Equatable {+ enum Phase: Equatable {+ case idle+ case holding(since: Double)+ case tapWait(until: Double)+ case locked+ }++ enum Action: Equatable {+ case none+ /// Open the microphone and show the pill.+ case start+ /// Hands-free: keep listening after the key is released.+ case lock+ /// Stop listening and paste what was said.+ case finish+ /// Stop listening and paste nothing.+ case cancel+ /// The last listen was dropped (too short) and a new one begins.+ case restart+ }++ /// A press shorter than this is a tap.+ static let holdThreshold = 0.30+ /// The second tap of a double tap comes within this.+ static let doubleTapWindow = 0.40++ private(set) var phase: Phase = .idle++ var isActive: Bool { phase != .idle }++ mutating func keyDown(at t: Double) -> Action {+ switch phase {+ case .idle:+ phase = .holding(since: t)+ return .start+ case .holding:+ return .none // key repeat+ case .tapWait(let until):+ if t <= until { phase = .locked; return .lock }+ phase = .holding(since: t) // the wait ran out unnoticed: start afresh+ return .restart+ case .locked:+ phase = .idle+ return .finish+ }+ }++ mutating func keyUp(at t: Double) -> Action {+ guard case .holding(let since) = phase else { return .none }+ if t - since >= Self.holdThreshold {+ phase = .idle+ return .finish+ }+ phase = .tapWait(until: t + Self.doubleTapWindow)+ return .none+ }++ /// Another key while the key is held, or between the two taps: it was a shortcut, not dictation.+ mutating func otherKey() -> Action {+ switch phase {+ case .holding, .tapWait:+ phase = .idle+ return .cancel+ case .idle, .locked:+ return .none+ }+ }++ mutating func escape() -> Action {+ guard phase != .idle else { return .none }+ phase = .idle+ return .cancel+ }++ /// Called when the double-tap window may have run out.+ mutating func tick(at t: Double) -> Action {+ guard case .tapWait(let until) = phase, t > until else { return .none }+ phase = .idle+ return .cancel+ }++ /// The listen ended on its own (no microphone, nothing heard…).+ mutating func reset() { phase = .idle }+}++/// Frequency bands for the pill's dots: graves on the left, aigus on the right.+enum FlowBands {+ static let count = 9+ static let lowHz: Double = 90+ static let highHz: Double = 7000++ /// The `count + 1` band edges in Hz, spaced evenly on a log scale.+ static func edges(count: Int = count, low: Double = lowHz, high: Double = highHz) -> [Double] {+ (0...count).map { low * pow(high / low, Double($0) / Double(count)) }+ }++ /// The FFT bins [from, to) of each band, for `fftSize` samples at `sampleRate`. Each band has at least one bin.+ static func binRanges(fftSize: Int, sampleRate: Double, count: Int = count) -> [Range<Int>] {+ let binHz = sampleRate / Double(fftSize)+ let maxBin = fftSize / 2+ let e = edges(count: count)+ var out: [Range<Int>] = []+ var last = 1+ for i in 0..<count {+ let from = max(last, Int((e[i] / binHz).rounded(.down)))+ let to = min(maxBin, max(from + 1, Int((e[i + 1] / binHz).rounded(.up))))+ out.append(from..<to)+ last = to+ }+ return out+ }++ /// A band's power in dB → 0…1 for the dot's height: silence stays low, a normal voice fills it.+ static func level(db: Double, floor: Double = -78, ceiling: Double = -30) -> Double {+ min(1, max(0, (db - floor) / (ceiling - floor)))+ }+}diff --git a/NotchBuddy/Sources/App/FlowPill.swift b/NotchBuddy/Sources/App/FlowPill.swiftnew file mode 100644index 00000000..bfbce111--- /dev/null+++ b/NotchBuddy/Sources/App/FlowPill.swift@@ -0,0 +1,217 @@+#if !APPSTORE+import AppKit+import SwiftUI++/// What the pill shows.+@MainActor+final class FlowPillModel: ObservableObject {+ enum Phase: Equatable {+ case hidden+ /// The key is held: the dots follow the voice.+ case listening+ /// Hands-free (double tap): same, with an orange ring.+ case locked+ /// Released: the Mac turns the voice into words.+ case thinking+ /// No Accessibility permission: the words are on the clipboard.+ case copied+ /// The microphone or speech recognition could not start.+ case failed+ }+ @Published var phase: Phase = .hidden+}++/// Eases the dots toward the microphone's levels, frame by frame (fast up, slower down), and+/// makes them ripple while the Mac turns the voice into words.+final class FlowLevelSmoother {+ private var values = [Double](repeating: 0, count: FlowBands.count)+ private var last: Date?++ func frame(at date: Date, target: [Float]?, thinking: Bool) -> [Double] {+ let dt = min(0.1, last.map { date.timeIntervalSince($0) } ?? 1.0 / 60)+ last = date+ let t = date.timeIntervalSinceReferenceDate+ for i in values.indices {+ var goal: Double+ if thinking {+ // A small wave running through the dots.+ goal = 0.10 + 0.22 * max(0, sin(t * 7.5 - Double(i) * 0.75))+ } else {+ let level = Double(target?[safe: i] ?? 0)+ // A touch of life so a steady sound does not freeze the dots.+ goal = level * (0.86 + 0.14 * sin(t * 11 + Double(i) * 1.7))+ }+ let rate = goal > values[i] ? 28.0 : 10.0+ values[i] += (goal - values[i]) * min(1, rate * dt)+ }+ return values+ }++ func reset() {+ values = [Double](repeating: 0, count: FlowBands.count)+ last = nil+ }+}++private extension Array {+ subscript(safe i: Int) -> Element? { indices.contains(i) ? self[i] : nil }+}++/// The pill at the bottom of the screen, like Wispr Flow's bar: a black capsule, a small Mochi,+/// and nine dots that rise and fall with the graves (left) and the aigus (right) of the voice.+struct FlowPillView: View {+ @ObservedObject var model: FlowPillModel+ let bands: FlowAudioBands+ let smoother: FlowLevelSmoother++ private var visible: Bool { model.phase != .hidden }++ var body: some View {+ VStack {+ Spacer(minLength: 0)+ capsule+ .scaleEffect(visible ? 1 : 0.55, anchor: .bottom)+ .opacity(visible ? 1 : 0)+ .offset(y: visible ? 0 : 6)+ .animation(.spring(response: 0.32, dampingFraction: 0.72), value: model.phase)+ }+ .frame(width: FlowPillController.size.width, height: FlowPillController.size.height)+ }++ private var capsule: some View {+ HStack(spacing: 9) {+ mochi+ switch model.phase {+ case .copied:+ Text("flow.copied")+ .font(.system(size: 12, weight: .medium))+ .foregroundColor(Color(hex: "#E8E9EC"))+ .fixedSize()+ case .failed:+ Text("flow.failed")+ .font(.system(size: 12, weight: .medium))+ .foregroundColor(Color(hex: "#E8E9EC"))+ .fixedSize()+ default:+ dots+ }+ }+ .padding(.horizontal, 13)+ .frame(height: 34)+ .background(+ Capsule()+ .fill(Color.black.opacity(0.94))+ .overlay(Capsule().strokeBorder(Color.white.opacity(0.16), lineWidth: 1))+ .overlay(Capsule().strokeBorder(Color(hex: "#F97316").opacity(model.phase == .locked ? 0.85 : 0), lineWidth: 1.5))+ )+ .shadow(color: .black.opacity(0.35), radius: 10, y: 4)+ }++ /// Mochi's face, tiny: two eyes that squint while he works out the words.+ private var mochi: some View {+ let thinking = model.phase == .thinking+ return RoundedRectangle(cornerRadius: 6.5, style: .continuous)+ .fill(LinearGradient(colors: [Color(hex: "#F5F6F8"), Color(hex: "#C9CBD1")], startPoint: .top, endPoint: .bottom))+ .frame(width: 19, height: 15)+ .overlay(+ HStack(spacing: 4.5) {+ ForEach(0..<2, id: \.self) { _ in+ Capsule()+ .fill(Color(hex: "#1A1412"))+ .frame(width: 2.6, height: thinking ? 1.4 : 4.2)+ }+ }+ .offset(y: 0.5)+ .animation(.easeOut(duration: 0.15), value: thinking)+ )+ }++ private var dots: some View {+ let active = model.phase == .listening || model.phase == .locked || model.phase == .thinking+ return TimelineView(.animation(minimumInterval: 1.0 / 60, paused: !active)) { context in+ let levels = smoother.frame(at: context.date,+ target: model.phase == .thinking ? nil : bands.levels,+ thinking: model.phase == .thinking)+ HStack(alignment: .center, spacing: 3.2) {+ ForEach(0..<FlowBands.count, id: \.self) { i in+ Capsule()+ .fill(Color.white.opacity(0.94))+ .frame(width: 3.4, height: 3.4 + 16 * CGFloat(levels[i]))+ }+ }+ .frame(height: 22)+ }+ }+}++/// The pill's window: borderless, never takes the focus (the words go to the app you type in),+/// lets clicks through, on every Space and over full-screen apps, at the bottom centre of the+/// screen the mouse is on.+@MainActor+final class FlowPillController {+ static let size = NSSize(width: 280, height: 80)++ let model = FlowPillModel()+ private let smoother = FlowLevelSmoother()+ private var panel: NSPanel?+ private var hideTask: Task<Void, Never>?+ private var bands: FlowAudioBands?++ func show(bands: FlowAudioBands) {+ hideTask?.cancel()+ if panel == nil || self.bands !== bands { build(bands) }+ guard let panel else { return }+ place(panel)+ smoother.reset()+ panel.orderFrontRegardless()+ model.phase = .listening+ }++ /// A short message, then the pill goes away.+ func flash(_ phase: FlowPillModel.Phase) {+ guard let panel else { return }+ hideTask?.cancel()+ if !panel.isVisible { place(panel); panel.orderFrontRegardless() }+ model.phase = phase+ hide(after: 1.8)+ }++ func hide(after delay: TimeInterval = 0) {+ hideTask?.cancel()+ hideTask = Task { @MainActor [weak self] in+ if delay > 0 { try? await Task.sleep(for: .seconds(delay)) }+ guard !Task.isCancelled, let self else { return }+ self.model.phase = .hidden+ try? await Task.sleep(for: .milliseconds(350))+ guard !Task.isCancelled, self.model.phase == .hidden else { return }+ self.panel?.orderOut(nil)+ }+ }++ private func build(_ bands: FlowAudioBands) {+ self.bands = bands+ let view = NSHostingView(rootView: FlowPillView(model: model, bands: bands, smoother: smoother))+ view.frame = NSRect(origin: .zero, size: Self.size)+ let p = NSPanel(contentRect: NSRect(origin: .zero, size: Self.size),+ styleMask: [.borderless, .nonactivatingPanel],+ backing: .buffered, defer: false)+ p.isOpaque = false+ p.backgroundColor = .clear+ p.hasShadow = false+ p.level = .statusBar+ p.ignoresMouseEvents = true+ p.hidesOnDeactivate = false+ p.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary, .stationary, .ignoresCycle]+ p.contentView = view+ panel = p+ }++ private func place(_ panel: NSPanel) {+ let mouse = NSEvent.mouseLocation+ let screen = NSScreen.screens.first { NSMouseInRect(mouse, $0.frame, false) } ?? NSScreen.main+ guard let area = screen?.visibleFrame else { return }+ // Just above the Dock (or the bottom edge when the Dock hides).+ panel.setFrameOrigin(NSPoint(x: area.midX - Self.size.width / 2, y: area.minY + 6))+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/FlowSettingsBox.swift b/NotchBuddy/Sources/App/FlowSettingsBox.swiftnew file mode 100644index 00000000..ae99f97f--- /dev/null+++ b/NotchBuddy/Sources/App/FlowSettingsBox.swift@@ -0,0 +1,61 @@+#if !APPSTORE+import SwiftUI++/// Settings → Voice: Flow dictation (hold a key, speak, the words are pasted where you type).+struct FlowSettingsBox: View {+ @ObservedObject private var flow = FlowDictation.shared++ var body: some View {+ GroupBox(String(localized: "flow.title")) {+ VStack(alignment: .leading, spacing: 10) {+ Toggle(String(localized: "flow.enable"), isOn: $flow.isEnabled)++ Text(String(format: String(localized: "flow.how %@"), flow.key.label))+ .font(.system(size: 11))+ .foregroundColor(.secondary)+ .fixedSize(horizontal: false, vertical: true)++ HStack(spacing: 8) {+ Text(String(localized: "flow.key"))+ Picker(String(localized: "flow.key"), selection: $flow.key) {+ ForEach(FlowKey.allCases) { key in+ Text(verbatim: key.label).tag(key)+ }+ }+ .labelsHidden()+ .frame(maxWidth: 200)+ }+ .disabled(!flow.isEnabled)++ if flow.key == .fn {+ Text(String(localized: "flow.fn-help"))+ .font(.system(size: 11))+ .foregroundColor(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }++ if flow.isEnabled && !flow.trusted {+ HStack(alignment: .top, spacing: 6) {+ Image(systemName: "exclamationmark.circle")+ .foregroundColor(.orange)+ VStack(alignment: .leading, spacing: 6) {+ Text(String(localized: "flow.accessibility"))+ .font(.system(size: 11))+ .fixedSize(horizontal: false, vertical: true)+ Button(String(localized: "flow.accessibility-open")) {+ flow.openAccessibilitySettings()+ }+ }+ }+ }++ Text(String(localized: "flow.privacy"))+ .font(.system(size: 11))+ .foregroundColor(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ .padding(6)+ }+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/MacDictation.swift b/NotchBuddy/Sources/App/MacDictation.swiftindex b80d1ecc..f9bc29b8 100644--- a/NotchBuddy/Sources/App/MacDictation.swift+++ b/NotchBuddy/Sources/App/MacDictation.swift@@ -37,6 +37,8 @@ final class MacDictation: @unchecked Sendable {@ObservationIgnored private var finishing: CheckedContinuation<Void, Never>?@ObservationIgnored private var isFinishing = false@ObservationIgnored private var tapInstalled = false+ /// Flow dictation's pill: the microphone's levels by frequency, fed from the same tap.+ @ObservationIgnored var bands: FlowAudioBands?/// The text field's content: what was typed, then the words heard so far.var text: String { prefix + transcript }@@ -65,7 +67,7 @@ final class MacDictation: @unchecked Sendable {@MainActor func start(from text: String) async {guard !isRecording, await Self.authorized() else { return }let built = Self.makeCandidates(language == Self.automatic ? Self.automaticLocales() : [Locale(identifier: language)])- guard !built.isEmpty, Self.startEngine(engine, feeding: built.map(\.request)) else { return }+ guard !built.isEmpty, Self.startEngine(engine, feeding: built.map(\.request), bands: bands) else { return }tapInstalled = trueprefix = text.isEmpty || text.hasSuffix(" ") ? text : text + " "transcript = ""@@ -178,10 +180,12 @@ final class MacDictation: @unchecked Sendable {// MARK: Audio and recognizers (off the main actor: they call back on their own threads)- nonisolated private static func startEngine(_ engine: AVAudioEngine, feeding requests: [SFSpeechAudioBufferRecognitionRequest]) -> Bool {+ nonisolated private static func startEngine(_ engine: AVAudioEngine, feeding requests: [SFSpeechAudioBufferRecognitionRequest],+ bands: FlowAudioBands? = nil) -> Bool {let input = engine.inputNodeinput.installTap(onBus: 0, bufferSize: 1024, format: input.outputFormat(forBus: 0)) { buffer, _ infor request in requests { request.append(buffer) }+ bands?.consume(buffer)}engine.prepare()do { try engine.start() } catch {diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex 0c70b6d3..a15d67df 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -1368,6 +1368,9 @@ struct SettingsView: View {}@ViewBuilder private var voiceSection: some View {+ // Flow dictation: hold a key anywhere, speak, the words are pasted where you type.+ FlowSettingsBox()+// Claude is Coucou's brain: no model, language or feature switches any more,// only the wake word, the Anthropic key it needs, and Coucou's voice.GroupBox(String(localized: "«\u{202F}OK Coucou\u{202F}» — voice wake word")) {diff --git a/scripts/test-flow-keys.sh b/scripts/test-flow-keys.shnew file mode 100755index 00000000..91b09ca5--- /dev/null+++ b/scripts/test-flow-keys.sh@@ -0,0 +1,8 @@+#!/usr/bin/env bash+set -euo pipefail+cd "$(dirname "$0")/.."+TEST_DIR="$(mktemp -d "${TMPDIR:-/tmp}/coucou-flow-keys.XXXXXX")"+trap 'rm -rf "$TEST_DIR"' EXIT+swiftc NotchBuddy/Sources/App/FlowKeyLogic.swift \+ tests/FlowKeyLogicTests.swift -o "$TEST_DIR/flow-keys-tests"+"$TEST_DIR/flow-keys-tests"diff --git a/tests/FlowKeyLogicTests.swift b/tests/FlowKeyLogicTests.swiftnew file mode 100644index 00000000..6328bc94--- /dev/null+++ b/tests/FlowKeyLogicTests.swift@@ -0,0 +1,100 @@+import Foundation++@main+enum FlowKeyLogicTests {++ static var failures = 0++ static func check(_ label: String, _ got: Bool) {+ if got { print(" ✓ \(label)") }+ else { print(" ✗ \(label)"); failures += 1 }+ }++ static func main() {++ print("\nHold to talk")+ do {+ var k = FlowKeyLogic()+ check("press starts listening at once", k.keyDown(at: 10) == .start)+ check("key repeat does nothing", k.keyDown(at: 10.1) == .none)+ check("release after a hold pastes", k.keyUp(at: 11.2) == .finish)+ check("back to idle", k.phase == .idle)+ }++ print("\nA short tap waits for a second one")+ do {+ var k = FlowKeyLogic()+ _ = k.keyDown(at: 10)+ check("short release does not paste yet", k.keyUp(at: 10.1) == .none)+ check("waiting for the second tap", k.phase == .tapWait(until: 10.1 + FlowKeyLogic.doubleTapWindow))+ check("no tick before the window ends", k.tick(at: 10.3) == .none)+ check("the window ends: dropped", k.tick(at: 10.6) == .cancel)+ check("idle after the drop", k.phase == .idle)+ }++ print("\nDouble tap: hands-free")+ do {+ var k = FlowKeyLogic()+ _ = k.keyDown(at: 10)+ _ = k.keyUp(at: 10.1)+ check("second tap locks", k.keyDown(at: 10.3) == .lock)+ check("release while locked does nothing", k.keyUp(at: 10.4) == .none)+ check("another key while locked does nothing", k.otherKey() == .none)+ check("next tap pastes", k.keyDown(at: 15) == .finish)+ check("idle after", k.phase == .idle)+ check("its release does nothing", k.keyUp(at: 15.1) == .none)+ }++ print("\nA second press after the window, before the tick")+ do {+ var k = FlowKeyLogic()+ _ = k.keyDown(at: 10)+ _ = k.keyUp(at: 10.1)+ check("starts afresh", k.keyDown(at: 11) == .restart)+ check("holding again", k.phase == .holding(since: 11))+ }++ print("\nShortcuts and Esc cancel")+ do {+ var k = FlowKeyLogic()+ _ = k.keyDown(at: 10)+ check("another key while held cancels (a shortcut such as ⌥E)", k.otherKey() == .cancel)+ check("idle", k.phase == .idle)+ check("Esc when idle does nothing", k.escape() == .none)+ _ = k.keyDown(at: 20)+ check("Esc while held cancels", k.escape() == .cancel)+ _ = k.keyDown(at: 30); _ = k.keyUp(at: 30.1); _ = k.keyDown(at: 30.2)+ check("Esc while hands-free cancels", k.escape() == .cancel)+ _ = k.keyDown(at: 40); _ = k.keyUp(at: 40.1)+ check("another key between the two taps cancels", k.otherKey() == .cancel)+ check("release when idle does nothing", k.keyUp(at: 41) == .none)+ }++ print("\nFrequency bands")+ do {+ let e = FlowBands.edges()+ check("ten edges for nine bands", e.count == FlowBands.count + 1)+ check("from the graves", abs(e.first! - FlowBands.lowHz) < 0.001)+ check("to the aigus", abs(e.last! - FlowBands.highHz) < 0.001)+ check("rising", zip(e, e.dropFirst()).allSatisfy { $0 < $1 })+ for rate in [44_100.0, 48_000.0, 16_000.0] {+ let r = FlowBands.binRanges(fftSize: 1024, sampleRate: rate)+ check("nine bands at \(Int(rate)) Hz", r.count == FlowBands.count)+ check("each band has a bin at \(Int(rate)) Hz", r.allSatisfy { !$0.isEmpty })+ check("bands do not overlap at \(Int(rate)) Hz", zip(r, r.dropFirst()).allSatisfy { $0.upperBound <= $1.lowerBound })+ check("bands stay under Nyquist at \(Int(rate)) Hz", r.allSatisfy { $0.upperBound <= 512 })+ }+ check("silence is low", FlowBands.level(db: -90) == 0)+ check("a loud voice is full", FlowBands.level(db: -20) == 1)+ check("in between", FlowBands.level(db: -54) > 0.3 && FlowBands.level(db: -54) < 0.7)+ }++ if failures == 0 {+ print("\nAll tests passed.")+ exit(0)+ } else {+ print("\n\(failures) test(s) failed.")+ exit(1)+ }+ }+}