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
voice: ask Coucou about everything — services, weather, mail, apps
Claude5eacaa1175d3
diff --git a/.github/workflows/build.yml b/.github/workflows/build.ymlindex ef47d5ce..96addfb1 100644--- a/.github/workflows/build.yml+++ b/.github/workflows/build.yml@@ -54,6 +54,11 @@ jobs:- name: Voice ActionRunner testsrun: bash scripts/test-voice-runner.sh++ - name: Voice query tests++ run: bash scripts/test-voice-query.sh+- name: Voice conversation end-phrase testsrun: bash scripts/test-voice-conversation.shdiff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxprojindex 9b4fbe3a..c92e9e6e 100644--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj@@ -71,6 +71,10 @@326971DDA23F331116E5A628 /* VoiceBrain.swift in Sources */ = {isa = PBXBuildFile; fileRef = C563E55884A7750B40EC9A01 /* VoiceBrain.swift */; };3451DB0668FAEEF09503D808 /* WakePhrase.swift in Sources */ = {isa = PBXBuildFile; fileRef = A12EC8F605BBC37F8223D7AA /* WakePhrase.swift */; };36EBFB9A047DEBAC43E5D0CC /* VoiceCaptionManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A8FB03801C49690C3789EFD /* VoiceCaptionManager.swift */; };+ D08B378612B4CB0C8811925B /* VoiceDataSources.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2C300BDBDD5FB8403291892 /* VoiceDataSources.swift */; };+ A51E53A7BF9F23535F3A8B15 /* VoiceDataSources.swift in Sources */ = {isa = PBXBuildFile; fileRef = F2C300BDBDD5FB8403291892 /* VoiceDataSources.swift */; };+ 968932802E8017E2C23FF473 /* VoiceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62762B5BCD2B2209EAF89A7A /* VoiceQuery.swift */; };+ EEDE0A39D216069D77F097C8 /* VoiceQuery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 62762B5BCD2B2209EAF89A7A /* VoiceQuery.swift */; };3756B7E1A55D9CEC8C4D34A4 /* IslandStateMachine.swift in Sources */ = {isa = PBXBuildFile; fileRef = D8212018F09EA1E96FBD63CD /* IslandStateMachine.swift */; };38EEB2D3A6EC538958D92575 /* GitHubPulse.swift in Sources */ = {isa = PBXBuildFile; fileRef = F8D3AD61802A32C4833F3EDA /* GitHubPulse.swift */; };390486F7CDC01C1BCDBB27F9 /* VoiceActionRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2737EC4885ADB8FDDA1C610 /* VoiceActionRunner.swift */; };@@ -383,6 +387,8 @@38BEAB5F20A13E5806A42EC9 /* ApprovalCard.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApprovalCard.swift; sourceTree = "<group>"; };3A27178AA6007F7B56901750 /* SessionDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SessionDetailView.swift; sourceTree = "<group>"; };3A8FB03801C49690C3789EFD /* VoiceCaptionManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceCaptionManager.swift; sourceTree = "<group>"; };+ F2C300BDBDD5FB8403291892 /* VoiceDataSources.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceDataSources.swift; sourceTree = "<group>"; };+ 62762B5BCD2B2209EAF89A7A /* VoiceQuery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VoiceQuery.swift; sourceTree = "<group>"; };3B238F6E7B20EFDED5CD3E8E /* ClaudeSettingsFile.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeSettingsFile.swift; sourceTree = "<group>"; };444604C7E2C530B664849EF9 /* ClaudeResponseText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ClaudeResponseText.swift; sourceTree = "<group>"; };49E39852175E81C9632A59C9 /* KitPreviewView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KitPreviewView.swift; sourceTree = "<group>"; };@@ -731,6 +737,8 @@A87F39805C78722F614295B4 /* VoiceAudio.swift */,C563E55884A7750B40EC9A01 /* VoiceBrain.swift */,3A8FB03801C49690C3789EFD /* VoiceCaptionManager.swift */,+ F2C300BDBDD5FB8403291892 /* VoiceDataSources.swift */,+ 62762B5BCD2B2209EAF89A7A /* VoiceQuery.swift */,B328028D18F590D6680B8A2B /* VoiceEngine.swift */,D1A7C62058BB0C9D0DF58DCB /* VoiceIntent.swift */,22E03C8E267399FA25C75877 /* VoiceIslandView.swift */,@@ -1042,6 +1050,8 @@88A8F2E4E754FAFABF6B1960 /* VoiceAudio.swift in Sources */,326971DDA23F331116E5A628 /* VoiceBrain.swift in Sources */,525FB188F09F68D26A9D587D /* VoiceCaptionManager.swift in Sources */,+ D08B378612B4CB0C8811925B /* VoiceDataSources.swift in Sources */,+ 968932802E8017E2C23FF473 /* VoiceQuery.swift in Sources */,BDEFF4223DA949E2B8AB85A7 /* VoiceEngine.swift in Sources */,9C11C226915DBC97B5CD7953 /* VoiceIntent.swift in Sources */,9088C7BADF166685E471D248 /* VoiceIslandView.swift in Sources */,@@ -1229,6 +1239,8 @@64FE8055CCAD30B44FE398E7 /* VoiceAudio.swift in Sources */,273B404F55739D661D9489D8 /* VoiceBrain.swift in Sources */,36EBFB9A047DEBAC43E5D0CC /* VoiceCaptionManager.swift in Sources */,+ A51E53A7BF9F23535F3A8B15 /* VoiceDataSources.swift in Sources */,+ EEDE0A39D216069D77F097C8 /* VoiceQuery.swift in Sources */,80B0B3C777A9DC8C82952FD2 /* VoiceEngine.swift in Sources */,15D69752806E1D1D589B20A7 /* VoiceIntent.swift in Sources */,C3BA3FA2A4025194FC088C5A /* VoiceIslandView.swift in Sources */,diff --git a/NotchBuddy/Resources/Coucou.entitlements b/NotchBuddy/Resources/Coucou.entitlementsindex 432a719c..66776d6a 100644--- a/NotchBuddy/Resources/Coucou.entitlements+++ b/NotchBuddy/Resources/Coucou.entitlements@@ -4,6 +4,8 @@<dict><key>com.apple.security.device.audio-input</key><true/>+ <key>com.apple.security.personal-information.addressbook</key>+ <true/><key>com.apple.security.automation.apple-events</key><true/></dict>diff --git a/NotchBuddy/Resources/CoucouCloud.entitlements b/NotchBuddy/Resources/CoucouCloud.entitlementsindex 6a9fba60..e9bf8de6 100644--- a/NotchBuddy/Resources/CoucouCloud.entitlements+++ b/NotchBuddy/Resources/CoucouCloud.entitlements@@ -4,6 +4,8 @@<dict><key>com.apple.security.device.audio-input</key><true/>+ <key>com.apple.security.personal-information.addressbook</key>+ <true/><key>com.apple.security.automation.apple-events</key><true/><key>com.apple.developer.icloud-container-identifiers</key>diff --git a/NotchBuddy/Resources/CoucouReleaseCloud.entitlements b/NotchBuddy/Resources/CoucouReleaseCloud.entitlementsindex 04486d66..abed9fa2 100644--- a/NotchBuddy/Resources/CoucouReleaseCloud.entitlements+++ b/NotchBuddy/Resources/CoucouReleaseCloud.entitlements@@ -4,6 +4,8 @@<dict><key>com.apple.security.device.audio-input</key><true/>+ <key>com.apple.security.personal-information.addressbook</key>+ <true/><key>com.apple.security.automation.apple-events</key><true/><key>com.apple.application-identifier</key>diff --git a/NotchBuddy/Resources/Info.plist b/NotchBuddy/Resources/Info.plistindex 3c945b07..78742941 100644--- a/NotchBuddy/Resources/Info.plist+++ b/NotchBuddy/Resources/Info.plist@@ -44,6 +44,8 @@</dict><key>NSAppleEventsUsageDescription</key><string>Pour sauter au terminal, envoyer des mails et piloter Musique et Spotify.</string>+ <key>NSContactsUsageDescription</key>+ <string>Coucou looks up an email address when you ask it, by voice, to prepare an email.</string><key>NSHighResolutionCapable</key><true/><key>NSMicrophoneUsageDescription</key>diff --git a/NotchBuddy/Resources/Localizable.xcstrings b/NotchBuddy/Resources/Localizable.xcstringsindex e9915152..57b3b551 100644--- a/NotchBuddy/Resources/Localizable.xcstrings+++ b/NotchBuddy/Resources/Localizable.xcstrings@@ -24776,6 +24776,201 @@}}}+ },+ "voice.setting-weather": {+ "extractionState": "manual",+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "الطقس بالصوت"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "কণ্ঠে আবহাওয়া"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Weather by voice"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "El tiempo por voz"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Météo à la voix"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "आवाज़ से मौसम"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Cuaca lewat suara"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Clima por voz"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Погода голосом"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "语音天气"+ }+ }+ }+ },+ "voice.setting-weather-city": {+ "extractionState": "manual",+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "المدينة"+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "শহর"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "City"+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "Ciudad"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Ville"+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "शहर"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Kota"+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Cidade"+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Город"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "城市"+ }+ }+ }+ },+ "voice.setting-weather-desc": {+ "extractionState": "manual",+ "localizations": {+ "ar": {+ "stringUnit": {+ "state": "translated",+ "value": "من Open-Meteo لهذه المدينة، فقط عندما تسأل."+ }+ },+ "bn": {+ "stringUnit": {+ "state": "translated",+ "value": "এই শহরের জন্য Open-Meteo থেকে, শুধু জিজ্ঞেস করলে।"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "From Open-Meteo for this city, only when you ask."+ }+ },+ "es": {+ "stringUnit": {+ "state": "translated",+ "value": "De Open-Meteo para esta ciudad, solo cuando preguntas."+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Open-Meteo pour cette ville, seulement quand tu demandes."+ }+ },+ "hi": {+ "stringUnit": {+ "state": "translated",+ "value": "इस शहर के लिए Open-Meteo से, सिर्फ़ पूछने पर।"+ }+ },+ "id": {+ "stringUnit": {+ "state": "translated",+ "value": "Dari Open-Meteo untuk kota ini, hanya saat kamu bertanya."+ }+ },+ "pt-BR": {+ "stringUnit": {+ "state": "translated",+ "value": "Do Open-Meteo para esta cidade, só quando você pergunta."+ }+ },+ "ru": {+ "stringUnit": {+ "state": "translated",+ "value": "Из Open-Meteo для этого города, только когда спрашиваешь."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "仅在你询问时,从 Open-Meteo 获取该城市的天气。"+ }+ }+ }}},"version": "1.0"diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swiftindex fa9c794a..f24f5829 100644--- a/NotchBuddy/Sources/App/SettingsView.swift+++ b/NotchBuddy/Sources/App/SettingsView.swift@@ -1260,6 +1260,8 @@ struct SettingsView: View {@ObservedObject private var voiceEngine = VoiceEngine.shared@AppStorage("voiceSpeakEnabled") private var speakEnabled: Bool = true@AppStorage("voiceCaptionEnabled") private var captionEnabled: Bool = true+ @AppStorage("voiceWeatherEnabled") private var weatherEnabled: Bool = false+ @AppStorage("voiceWeatherCity") private var weatherCity: String = ""@ViewBuilder private var voiceSection: some View {GroupBox(String(localized: "«\u{202F}OK Coucou\u{202F}» — voice wake word")) {@@ -1271,6 +1273,17 @@ struct SettingsView: View {Toggle(String(localized: "voice.setting-captions"), isOn: $captionEnabled)+ Toggle(String(localized: "voice.setting-weather"), isOn: $weatherEnabled)+ if weatherEnabled {+ TextField(String(localized: "voice.setting-weather-city"), text: $weatherCity)+ .textFieldStyle(.roundedBorder)+ .frame(maxWidth: 220)+ Text(String(localized: "voice.setting-weather-desc"))+ .font(.system(size: 11))+ .foregroundColor(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+Text("When enabled, Coucou listens for the wake word «\u{202F}OK Coucou\u{202F}». Speech recognition runs entirely on-device — no audio or transcript leaves your Mac.").font(.system(size: 11)).foregroundColor(.secondary)diff --git a/NotchBuddy/Sources/App/Voice/IntentParser.swift b/NotchBuddy/Sources/App/Voice/IntentParser.swiftindex 0ff29341..cd34f44b 100644--- a/NotchBuddy/Sources/App/Voice/IntentParser.swift+++ b/NotchBuddy/Sources/App/Voice/IntentParser.swift@@ -15,6 +15,11 @@ enum IntentParser {let words = norm.split(separator: " ").map(String.init)guard !words.isEmpty else { return .unknown }+ // Email, questions about the services, opening an app (VoiceQuery).+ if let m = VoiceQuery.mail(of: raw) { return .mail(m) }+ if let t = VoiceQuery.topic(of: raw) { return .query(t) }+ if let app = VoiceQuery.appToOpen(raw) { return .openApp(name: app) }+// rawWords: same splits as normalise but no diacritics strip, no letter filter, original caselet rawWords0 = buildRawWords(raw)// defilter both arrays in parallel: ma→la, mon→le, strip filler wordsdiff --git a/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swift b/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swiftindex 7aa53609..c9d44656 100644--- a/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swift+++ b/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swift@@ -91,6 +91,7 @@ extension VoiceActionRunner {func configureLive() {music = LiveMusicControl()pills = LivePillControl()+ info = LiveVoiceInfo.shared}}#endifdiff --git a/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift b/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swiftindex 0139d4f1..f703d41f 100644--- a/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift+++ b/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift@@ -31,6 +31,24 @@ protocol PillControlling {func setMainPill(_ id: String)}+/// Answers questions and prepares mail / opens apps (Mac side: VoiceDataSources.swift).+@MainActor+protocol VoiceInfoProviding {+ func answer(_ topic: VoiceTopic, locale: Locale?) async -> String+ /// Opens a compose window (Mail) — never sends: I click Send myself.+ func composeMail(_ request: VoiceQuery.MailRequest, locale: Locale?) async -> VoiceActionResult+ func openApp(_ name: String, locale: Locale?) -> VoiceActionResult+}++@MainActor+private final class NullInfo: VoiceInfoProviding {+ func answer(_ topic: VoiceTopic, locale: Locale?) async -> String { "" }+ func composeMail(_ request: VoiceQuery.MailRequest, locale: Locale?) async -> VoiceActionResult {+ .init(outcome: .failure, message: "")+ }+ func openApp(_ name: String, locale: Locale?) -> VoiceActionResult { .init(outcome: .failure, message: "") }+}+// MARK: - Null implementations (test-safe, no AppKit)private final class NullMusic: MusicControlling, @unchecked Sendable {@@ -67,6 +85,7 @@ final class VoiceActionRunner {var music: MusicControlling = NullMusic()var pills: PillControlling = NullPills()+ var info: VoiceInfoProviding = NullInfo()/// Pending follow-up question (4-pill limit, ambiguity). Set when outcome is .question.var pendingQuestion: PendingVoiceQuestion? = nil@@ -256,6 +275,18 @@ final class VoiceActionRunner {let msg = fmt.contains("%@") ? String(format: fmt, names) : namesreturn .init(outcome: .success, message: msg)+ // ── Questions, mail, apps ─────────────────────────────────────────────++ case .query(let topic):+ let text = await info.answer(topic, locale: commandLocale)+ return text.isEmpty ? fail("voice.unknown") : .init(outcome: .success, message: text)++ case .mail(let request):+ return await info.composeMail(request, locale: commandLocale)++ case .openApp(let name):+ return info.openApp(name, locale: commandLocale)+case .unknown:if rawTranscript.isEmpty { return fail("voice.unknown") }let fmt = Self.localizedString("voice.unknown-transcript", locale: commandLocale)diff --git a/NotchBuddy/Sources/App/Voice/VoiceBrain.swift b/NotchBuddy/Sources/App/Voice/VoiceBrain.swiftindex 6cbfe4dc..1b10f0d1 100644--- a/NotchBuddy/Sources/App/Voice/VoiceBrain.swift+++ b/NotchBuddy/Sources/App/Voice/VoiceBrain.swift@@ -116,13 +116,15 @@ final class VoiceBrain {let session = LanguageModelSession(tools: [PillTool(collector: collector),MusicTool(collector: collector),- StatusTool(collector: collector)],+ StatusTool(collector: collector),+ ServiceTool()],instructions: """Tu es Coucou, un assistant dans le notch du MacBook.Réponds toujours dans la langue de l'utilisateur.Réponds avec 1 à 2 phrases maximum. Sois direct et concis.Ne pose une question que si tu as vraiment besoin d'une précision pour agir : une seule, courte, qui finit par « ? ». Sinon, ne finis jamais par une question.Utilise les outils disponibles pour exécuter des commandes sur les pills et la musique.+ Pour toute question sur Stripe, GitHub, Vercel, Resend, n8n, Notion, Cal.com, les agents (Claude Code, Codex…), le plan Claude ou Codex, la musique ou la météo, appelle d'abord l'outil service et réponds avec ses données, sans rien inventer.Pour les noms de pilules, utilise le nom exact fourni par l'utilisateur.""")@@ -364,6 +366,25 @@ struct MusicTool: Tool, @unchecked Sendable {// MARK: StatusTool+@available(macOS 26, *)+struct ServiceTool: Tool, @unchecked Sendable {+ let name = "service"+ let description = "Real data from Coucou: Stripe sales and balance, GitHub stars/PRs/CI, Vercel deployments, Resend emails, n8n runs, Notion pages, Cal.com bookings, agent sessions (Claude Code…), Claude/Codex plan usage, music now playing, active pills, weather today or tomorrow."++ @Generable+ struct Arguments {+ @Guide(description: "One of: stripe, github, vercel, resend, n8n, notion, calcom, agents, claudePlan, codexPlan, music, pills, weatherToday, weatherTomorrow")+ var topic: String+ }++ func call(arguments: Arguments) async throws -> String {+ guard let topic = VoiceTopic(rawValue: arguments.topic) else {+ return "unknown topic: \(arguments.topic)"+ }+ return await LiveVoiceInfo.shared.answer(topic, locale: nil)+ }+}+@available(macOS 26, *)struct StatusTool: Tool, @unchecked Sendable {let name = "status"diff --git a/NotchBuddy/Sources/App/Voice/VoiceDataSources.swift b/NotchBuddy/Sources/App/Voice/VoiceDataSources.swiftnew file mode 100644index 00000000..e65e9f7e--- /dev/null+++ b/NotchBuddy/Sources/App/Voice/VoiceDataSources.swift@@ -0,0 +1,389 @@+#if !APPSTORE+import AppKit+import Contacts++// MARK: - LiveVoiceInfo+//+// Mac side of VoiceQuery: reads what the pollers already keep in AppState and turns it+// into a VoiceSnapshot for VoiceAnswer. Network only to services the user configured:+// • Stripe (their key) for today's total, only when asked;+// • Open-Meteo for the weather, only when the user turned it on and set a city.+// Mail: opens a compose window (mailto: or Mail's share sheet). It never sends — the+// user clicks Send (CLAUDE.md).++@MainActor+final class LiveVoiceInfo: VoiceInfoProviding {+ static let shared = LiveVoiceInfo()++ // MARK: Questions++ func answer(_ topic: VoiceTopic, locale: Locale?) async -> String {+ let fr = Self.isFrench(locale)+ let snap = await snapshot(for: topic, french: fr)+ return VoiceAnswer.text(topic, snap, french: fr)+ }++ static func isFrench(_ locale: Locale?) -> Bool {+ (locale ?? Locale.current).language.languageCode?.identifier == "fr"+ }++ private func snapshot(for topic: VoiceTopic, french fr: Bool) async -> VoiceSnapshot {+ let app = AppState.shared+ var s = VoiceSnapshot()+ func key(_ k: String) -> Bool { KeychainStore.shared.get(k) != nil }++ switch topic {+ case .stripe:+ guard key("stripe-api-key") else { s.configured = false; break }+ let cur = app.stripeCurrency+ var st = VoiceSnapshot.Stripe(balance: Self.money(app.stripeBalance, cur, fr: fr))+ st.last = app.stripePayments.prefix(3).map {+ .init(amount: Self.money($0.amount, $0.currency, fr: fr), description: $0.description,+ ago: Self.ago($0.createdAt, fr: fr), succeeded: $0.isSuccess)+ }+ if let today = await StripeToday.fetch() {+ st.today = Self.money(today.cents, today.currency ?? cur, fr: fr)+ st.todayCount = today.count+ }+ s.stripe = st++ case .github:+ guard key("github-token") else { s.configured = false; break }+ var g = VoiceSnapshot.GitHub(stars: app.githubStats?.totalStars, repos: app.githubStats?.totalRepos)+ if let p = app.githubPulse {+ g.myPRs = p.myPRs.map { .init(title: $0.title, repo: $0.repo,+ ci: String(describing: $0.ci), review: String(describing: $0.review)) }+ g.toReview = p.toReview.count+ g.failingRepos = p.mainCI.filter { $0.ci == .failure }.map(\.repo)+ }+ s.github = g++ case .vercel:+ guard key("vercel-token") else { s.configured = false; break }+ s.deploys = app.vercelDeployments.map {+ .init(project: $0.projectName, state: $0.state, ago: Self.ago($0.createdAt, fr: fr), commit: $0.commitMessage)+ }++ case .resend:+ guard key("resend-api-key") else { s.configured = false; break }+ s.emailsTotal = app.resendTotal+ s.emails = app.resendEmails.map { (to: $0.recipientShort, subject: $0.subject, state: $0.lastEvent) }++ case .n8n:+ guard key("n8n-api-key") else { s.configured = false; break }+ s.runs = app.n8nRuns.map { (workflow: $0.workflow, ok: $0.success, ago: Self.ago($0.date, fr: fr)) }++ case .notion:+ guard key("notion-api-key") else { s.configured = false; break }+ s.pages = app.notionPages.map { (title: $0.title, ago: Self.ago($0.lastEditedAt, fr: fr)) }++ case .calcom:+ guard key("calcom-api-key") else { s.configured = false; break }+ let now = Date()+ s.bookings = app.calcomBookings+ .filter { $0.isActive && $0.endTime > now }+ .sorted { $0.startTime < $1.startTime }+ .map { .init(title: $0.title, when: Self.when($0.startTime, fr: fr), with: $0.attendeeName) }++ case .agents:+ s.approvalPending = app.pendingApproval?.tool+ s.sessions = app.tasks+ .filter { $0.source == .claudeCode || $0.source == .agent }+ .map { t in+ var detail: String? = t.steps.indices.contains(t.stepIndex) ? t.steps[t.stepIndex] : t.finalLine+ if let d = detail, d.count > 90 { detail = String(d.prefix(90)) + "…" }+ return .init(name: t.name, state: t.state.rawValue, detail: detail)+ }++ case .claudePlan:+ s.plan = Self.plan(app.claudePlanUsage, fr: fr)++ case .codexPlan:+ s.plan = Self.plan(app.codexPlanUsage?.planUsage, fr: fr)++ case .music:+ if app.musicPlaying, let title = MusicController.shared.trackTitle {+ s.nowPlaying = (title: title, artist: MusicController.shared.artist)+ } else if SpotifyController.shared.isPlaying, let t = SpotifyController.shared.track {+ s.nowPlaying = (title: t.title, artist: Optional(t.artist))+ }++ case .pills:+ s.mainPill = PillCatalog.definition(for: app.mainPillId)?.name+ s.activePills = app.activeIntegrations.compactMap { PillCatalog.definition(for: $0)?.name }.sorted()++ case .weatherToday, .weatherTomorrow:+ guard VoiceSettings.weatherEnabled else { s.weatherOff = true; break }+ let city = VoiceSettings.weatherCity.trimmingCharacters(in: .whitespaces)+ guard !city.isEmpty else { s.weatherNoCity = true; break }+ s.weather = await WeatherSource.shared.forecast(city: city, tomorrow: topic == .weatherTomorrow, french: fr)+ }+ return s+ }++ // MARK: Formatting++ static func money(_ cents: Int, _ currency: String, fr: Bool) -> String {+ let f = NumberFormatter()+ f.numberStyle = .currency+ f.currencyCode = currency.uppercased()+ f.locale = Locale(identifier: fr ? "fr_FR" : "en_US")+ return f.string(from: NSNumber(value: Double(cents) / 100)) ?? "\(cents / 100) \(currency.uppercased())"+ }++ static func ago(_ date: Date, fr: Bool) -> String {+ let secs = max(60, Date().timeIntervalSince(date))+ return duration(secs, fr: fr, units: 1)+ }++ static func duration(_ secs: TimeInterval, fr: Bool, units: Int) -> String {+ let f = DateComponentsFormatter()+ f.unitsStyle = .full+ f.maximumUnitCount = units+ f.allowedUnits = [.day, .hour, .minute]+ var cal = Calendar.current+ cal.locale = Locale(identifier: fr ? "fr_FR" : "en_US")+ f.calendar = cal+ return f.string(from: secs) ?? ""+ }++ static func when(_ date: Date, fr: Bool) -> String {+ let f = DateFormatter()+ f.locale = Locale(identifier: fr ? "fr_FR" : "en_US")+ f.doesRelativeDateFormatting = true+ f.dateStyle = .medium+ f.timeStyle = .short+ return f.string(from: date)+ }++ static func plan(_ u: PlanUsage?, fr: Bool) -> VoiceSnapshot.Plan? {+ guard let u else { return nil }+ let reset = [u.fiveHour?.resetsAt, u.sevenDay?.resetsAt].compactMap { $0 }.filter { $0 > Date() }.min()+ return .init(fiveHourPct: u.fiveHour.map { Int($0.usedPct.rounded()) },+ sevenDayPct: u.sevenDay.map { Int($0.usedPct.rounded()) },+ resetsIn: reset.map { duration($0.timeIntervalSinceNow, fr: fr, units: 2) })+ }++ // MARK: Mail — prepare only, the user clicks Send++ func composeMail(_ request: VoiceQuery.MailRequest, locale: Locale?) async -> VoiceActionResult {+ let fr = Self.isFrench(locale)+ func t(_ f: String, _ e: String) -> String { fr ? f : e }++ guard let address = await ContactLookup.email(for: request.recipient) else {+ return .init(outcome: .failure,+ message: t("Je ne trouve pas l'adresse de \(request.recipient) dans tes contacts.",+ "I can't find \(request.recipient)'s address in your contacts."))+ }+ var fileURL: URL? = nil+ if let name = request.file {+ fileURL = FileLookup.find(name, in: request.folder)+ if fileURL == nil {+ return .init(outcome: .failure,+ message: t("Je ne trouve pas le fichier « \(name) ».", "I can't find the file “\(name)”."))+ }+ }++ if let fileURL, let service = NSSharingService(named: .composeEmail) {+ service.recipients = [address]+ service.subject = fileURL.deletingPathExtension().lastPathComponent+ service.perform(withItems: [fileURL])+ return .init(outcome: .success,+ message: t("Mail prêt pour \(request.recipient) avec \(fileURL.lastPathComponent). Tu n'as plus qu'à cliquer sur Envoyer.",+ "Email to \(request.recipient) with \(fileURL.lastPathComponent) is ready. Just click Send."))+ }+ guard let url = URL(string: "mailto:\(address)") else {+ return .init(outcome: .failure, message: t("Je n'arrive pas à ouvrir Mail.", "I can't open Mail."))+ }+ NSWorkspace.shared.open(url)+ return .init(outcome: .success,+ message: t("Mail prêt pour \(request.recipient). Écris ton message et clique sur Envoyer.",+ "Email to \(request.recipient) is ready. Write it and click Send."))+ }++ // MARK: Apps++ func openApp(_ name: String, locale: Locale?) -> VoiceActionResult {+ let fr = Self.isFrench(locale)+ guard let url = AppLookup.find(name) else {+ return .init(outcome: .failure,+ message: fr ? "Je ne trouve pas l'app \(name)." : "I can't find the app \(name).")+ }+ NSWorkspace.shared.openApplication(at: url, configuration: NSWorkspace.OpenConfiguration())+ let shown = url.deletingPathExtension().lastPathComponent+ return .init(outcome: .success, message: fr ? "J'ouvre \(shown)." : "Opening \(shown).")+ }+}++// MARK: - Stripe: today's total (asked on demand, same key as StripePoller)++enum StripeToday {+ struct Total { var cents: Int; var count: Int; var currency: String? }++ static func fetch() async -> Total? {+ guard let key = KeychainStore.shared.get("stripe-api-key") else { return nil }+ let midnight = Calendar.current.startOfDay(for: Date())+ var comps = URLComponents(string: "https://api.stripe.com/v1/charges")!+ comps.queryItems = [URLQueryItem(name: "created[gte]", value: String(Int(midnight.timeIntervalSince1970))),+ URLQueryItem(name: "limit", value: "100")]+ guard let url = comps.url else { return nil }+ var req = URLRequest(url: url, timeoutInterval: 6)+ req.setValue("Basic \(Data("\(key):".utf8).base64EncodedString())", forHTTPHeaderField: "Authorization")+ guard let (data, resp) = try? await URLSession.shared.data(for: req),+ (resp as? HTTPURLResponse)?.statusCode == 200,+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let items = json["data"] as? [[String: Any]] else { return nil }+ var total = Total(cents: 0, count: 0, currency: nil)+ for c in items where (c["status"] as? String) == "succeeded" && (c["paid"] as? Bool ?? true) {+ let amount = c["amount"] as? Int ?? 0+ let refunded = c["amount_refunded"] as? Int ?? 0+ total.cents += amount - refunded+ total.count += 1+ if total.currency == nil { total.currency = c["currency"] as? String }+ }+ return total+ }+}++// MARK: - Weather (Open-Meteo, opt-in, 15 min cache)++@MainActor+final class WeatherSource {+ static let shared = WeatherSource()+ private var place: (query: String, name: String, lat: Double, lon: Double)?+ private var cache: (key: String, at: Date, json: [String: Any])?++ func forecast(city: String, tomorrow: Bool, french fr: Bool) async -> VoiceSnapshot.Weather? {+ guard let p = await geocode(city, fr: fr) else { return nil }+ let key = "\(p.lat),\(p.lon)"+ var json: [String: Any]+ if let c = cache, c.key == key, Date().timeIntervalSince(c.at) < 900 {+ json = c.json+ } else {+ var comps = URLComponents(string: "https://api.open-meteo.com/v1/forecast")!+ comps.queryItems = [+ .init(name: "latitude", value: String(p.lat)), .init(name: "longitude", value: String(p.lon)),+ .init(name: "current", value: "temperature_2m,weather_code,wind_speed_10m"),+ .init(name: "daily", value: "weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"),+ .init(name: "timezone", value: "auto"), .init(name: "forecast_days", value: "2"),+ ]+ guard let url = comps.url,+ let (data, _) = try? await URLSession.shared.data(for: URLRequest(url: url, timeoutInterval: 6)),+ let j = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil }+ json = j+ cache = (key, Date(), j)+ }+ guard let daily = json["daily"] as? [String: Any] else { return nil }+ let i = tomorrow ? 1 : 0+ func num(_ k: String) -> Double? {+ guard let arr = daily[k] as? [Any], arr.indices.contains(i) else { return nil }+ if let d = arr[i] as? Double { return d }+ if let n = arr[i] as? Int { return Double(n) }+ return nil+ }+ func int(_ k: String) -> Int? { num(k).map { Int($0.rounded()) } }+ let current = json["current"] as? [String: Any]+ let currentCode: Int? = (current?["weather_code"] as? Int) ?? (current?["weather_code"] as? Double).map { Int($0) }+ let code = tomorrow ? (int("weather_code") ?? 0) : (currentCode ?? int("weather_code") ?? 0)+ return .init(city: p.name,+ nowTemp: tomorrow ? nil : (current?["temperature_2m"] as? Double).map { Int($0.rounded()) },+ code: code,+ min: Int((num("temperature_2m_min") ?? 0).rounded()),+ max: Int((num("temperature_2m_max") ?? 0).rounded()),+ rainChance: int("precipitation_probability_max"),+ wind: (current?["wind_speed_10m"] as? Double).map { Int($0.rounded()) })+ }++ private func geocode(_ city: String, fr: Bool) async -> (name: String, lat: Double, lon: Double)? {+ if let p = place, p.query == city { return (p.name, p.lat, p.lon) }+ var comps = URLComponents(string: "https://geocoding-api.open-meteo.com/v1/search")!+ comps.queryItems = [.init(name: "name", value: city), .init(name: "count", value: "1"),+ .init(name: "language", value: fr ? "fr" : "en")]+ guard let url = comps.url,+ let (data, _) = try? await URLSession.shared.data(for: URLRequest(url: url, timeoutInterval: 6)),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let first = (json["results"] as? [[String: Any]])?.first,+ let lat = first["latitude"] as? Double, let lon = first["longitude"] as? Double else { return nil }+ let name = first["name"] as? String ?? city+ place = (city, name, lat, lon)+ return (name, lat, lon)+ }+}++// MARK: - Contacts (asked the first time a mail is prepared)++enum ContactLookup {+ static func email(for name: String) async -> String? {+ let trimmed = name.trimmingCharacters(in: .whitespaces)+ if trimmed.contains("@") { return trimmed.replacingOccurrences(of: " ", with: "") }+ let store = CNContactStore()+ if CNContactStore.authorizationStatus(for: .contacts) == .notDetermined {+ _ = try? await store.requestAccess(for: .contacts)+ }+ guard CNContactStore.authorizationStatus(for: .contacts) == .authorized else { return nil }+ return await Task.detached(priority: .userInitiated) { () -> String? in+ let keys = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactNicknameKey,+ CNContactEmailAddressesKey] as [CNKeyDescriptor]+ let pred = CNContact.predicateForContacts(matchingName: trimmed)+ let found = (try? CNContactStore().unifiedContacts(matching: pred, keysToFetch: keys)) ?? []+ return found.lazy.compactMap { $0.emailAddresses.first?.value as String? }.first+ }.value+ }+}++// MARK: - Files: Downloads / Desktop / Documents only++enum FileLookup {+ static func find(_ query: String, in folder: VoiceQuery.MailRequest.Folder?) -> URL? {+ let fm = FileManager.default+ let dirs: [FileManager.SearchPathDirectory]+ switch folder {+ case .downloads: dirs = [.downloadsDirectory]+ case .desktop: dirs = [.desktopDirectory]+ case .documents: dirs = [.documentDirectory]+ case nil: dirs = [.downloadsDirectory, .desktopDirectory, .documentDirectory]+ }+ let wanted = IntentParser.normalise(query).split(separator: " ").map(String.init)+ guard !wanted.isEmpty else { return nil }+ var best: (url: URL, date: Date)?+ for d in dirs {+ guard let root = fm.urls(for: d, in: .userDomainMask).first,+ let e = fm.enumerator(at: root, includingPropertiesForKeys: [.contentModificationDateKey, .isRegularFileKey],+ options: [.skipsHiddenFiles, .skipsPackageDescendants]) else { continue }+ for case let url as URL in e {+ if e.level > 2 { e.skipDescendants(); continue }+ guard (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true else { continue }+ let name = IntentParser.normalise(url.deletingPathExtension().lastPathComponent)+ let ext = url.pathExtension.lowercased()+ let ok = wanted.allSatisfy { w in name.contains(w) || ext == w }+ guard ok else { continue }+ let date = (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast+ if best == nil || date > best!.date { best = (url, date) }+ }+ }+ return best?.url+ }+}++// MARK: - Apps++enum AppLookup {+ static func find(_ name: String) -> URL? {+ let wanted = IntentParser.normalise(name)+ guard !wanted.isEmpty else { return nil }+ let fm = FileManager.default+ let roots = ["/Applications", "/System/Applications", "/System/Applications/Utilities",+ fm.homeDirectoryForCurrentUser.appendingPathComponent("Applications").path]+ var apps: [(norm: String, url: URL)] = []+ for r in roots {+ for item in (try? fm.contentsOfDirectory(atPath: r)) ?? [] where item.hasSuffix(".app") {+ let url = URL(fileURLWithPath: r).appendingPathComponent(item)+ apps.append((IntentParser.normalise(String(item.dropLast(4))), url))+ }+ }+ return apps.first(where: { $0.norm == wanted })?.url+ ?? apps.first(where: { $0.norm.hasPrefix(wanted) })?.url+ ?? apps.first(where: { $0.norm.contains(wanted) })?.url+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/Voice/VoiceIntent.swift b/NotchBuddy/Sources/App/Voice/VoiceIntent.swiftindex 4a0150ae..c3ad11fe 100644--- a/NotchBuddy/Sources/App/Voice/VoiceIntent.swift+++ b/NotchBuddy/Sources/App/Voice/VoiceIntent.swift@@ -37,6 +37,12 @@ enum VoiceIntent: Equatable {case pillReplace(old: String, new: String) // "remplace n8n par github"case pillOnly([String]) // "garde seulement GitHub et Vercel"+ // ── Questions, mail, apps ─────────────────────────────────────────────────++ case query(VoiceTopic) // "combien d'étoiles sur GitHub ?"+ case mail(VoiceQuery.MailRequest) // "envoie le fichier X à Tana" (Mail opens, I click Send)+ case openApp(name: String) // "ouvre Figma"+// ── Unknown ───────────────────────────────────────────────────────────────case unknowndiff --git a/NotchBuddy/Sources/App/Voice/VoiceQuery.swift b/NotchBuddy/Sources/App/Voice/VoiceQuery.swiftnew file mode 100644index 00000000..3cf3b4a3--- /dev/null+++ b/NotchBuddy/Sources/App/Voice/VoiceQuery.swift@@ -0,0 +1,390 @@+#if !APPSTORE+import Foundation++// MARK: - VoiceQuery+//+// Questions about what Coucou already knows ("combien d'étoiles sur GitHub ?",+// "mon déploiement Vercel est passé ?", "quel temps il fait ?") and the two+// requests that are not pill or music commands (prepare an email, open an app).+//+// Pure: no AppKit, no AppState, no network. The Mac side fills a VoiceSnapshot+// (VoiceDataSources.swift) and VoiceAnswer turns it into one or two spoken sentences.+// Answers are French or English (the spoken language); other languages get English.++enum VoiceTopic: String, Equatable, CaseIterable {+ case stripe, github, vercel, resend, n8n, notion, calcom+ case agents // Claude Code and the other agent sessions+ case claudePlan, codexPlan+ case music, pills+ case weatherToday, weatherTomorrow+}++enum VoiceQuery {++ // MARK: Detection++ /// The topic of a question, or nil when the phrase is a command or not a question.+ /// A phrase with an action verb ("est-ce que tu peux ajouter GitHub") stays a command.+ static func topic(of raw: String) -> VoiceTopic? {+ let norm = IntentParser.normalise(raw)+ let words = norm.split(separator: " ").map(String.init)+ guard !words.isEmpty else { return nil }+ let text = " " + norm + " "+ func has(_ s: String) -> Bool { text.contains(" " + s + " ") }+ func hasAny(_ list: [String]) -> Bool { list.contains(where: has) }++ if !Set(words).isDisjoint(with: actionVerbs) { return nil }++ let asks = raw.trimmingCharacters(in: .whitespaces).hasSuffix("?")+ || hasAny(questionMarkers)++ // Weather words are clear enough on their own ("météo", "il pleut ?").+ if hasAny(["meteo", "weather", "quel temps", "il pleut", "va pleuvoir", "pleuvoir",+ "temperature", "il fait chaud", "il fait froid", "fait il beau", "il fait beau",+ "forecast", "rain", "parapluie", "umbrella"]) {+ return hasAny(["demain", "tomorrow"]) ? .weatherTomorrow : .weatherToday+ }+ guard asks else { return nil }++ // Named services first.+ if has("stripe") { return .stripe }+ if hasAny(["github", "git hub", "gt"]) { return .github }+ if has("vercel") { return .vercel }+ if has("resend") { return .resend }+ if hasAny(["n8n", "n 8 n", "workflow", "workflows", "automatisation", "automatisations"]) { return .n8n }+ if has("notion") { return .notion }+ if hasAny(["cal com", "calcom", "rendez vous", "rdv", "agenda", "reunion", "reunions",+ "meeting", "meetings", "booking", "bookings", "reservation", "reservations"]) { return .calcom }+ if hasAny(["quota", "limite", "limites", "forfait", "usage", "plan"]) {+ return has("codex") ? .codexPlan : .claudePlan+ }+ if hasAny(["claude", "codex", "cursor", "gemini", "copilot", "agent", "agents",+ "session", "sessions", "qu est ce qui se passe", "ou en est", "il fait quoi",+ "what s happening", "whats happening"]) { return .agents }+ // Generic words.+ if hasAny(["argent", "vendu", "vente", "ventes", "chiffre", "revenu", "revenus", "gagne",+ "encaisse", "paiement", "paiements", "solde", "money", "sales", "revenue",+ "earned", "payments", "balance"]) { return .stripe }+ if hasAny(["etoile", "etoiles", "star", "stars", "pull request", "pull requests", "pr", "prs",+ "repo", "repos", "ci"]) { return .github }+ if hasAny(["deploiement", "deploiements", "deploy", "deploye", "deployment", "push", "pousse"]) { return .vercel }+ if hasAny(["mail", "mails", "email", "emails"]) { return .resend }+ if hasAny(["chanson", "musique", "titre", "morceau", "song", "track", "playing", "ecoute"]) { return .music }+ if hasAny(["pilule", "pilules", "pill", "pills"]) { return .pills }+ return nil+ }++ private static let questionMarkers = [+ "combien", "quel", "quelle", "quels", "quelles", "est ce", "c est quoi", "qu est ce",+ "ou en", "comment", "dis moi", "donne moi", "montre moi", "y a t il", "il y a",+ "how", "what", "whats", "did", "is", "are", "any", "tell me", "show me", "statut", "status",+ "etat", "est il", "est elle", "a t il", "a t elle",+ ]++ private static let actionVerbs: Set<String> = [+ "ajoute", "ajouter", "ajoutes", "rajoute", "enleve", "enlever", "enleves", "retire", "retirer",+ "supprime", "supprimer", "mets", "mettre", "met", "lance", "lancer", "joue", "jouer",+ "remplace", "remplacer", "active", "activer", "desactive", "vire", "virer",+ "envoie", "envoyer", "ouvre", "ouvrir", "add", "remove", "play", "open", "send",+ ]++ // MARK: Email: "envoie un mail à Tana", "envoie le fichier facture des téléchargements à Tana"++ struct MailRequest: Equatable {+ var recipient: String+ var file: String?+ var folder: Folder?+ enum Folder: String, Equatable { case downloads, desktop, documents }+ }++ static func mail(of raw: String) -> MailRequest? {+ let norm = IntentParser.normalise(raw)+ let n = norm.split(separator: " ").map(String.init)+ let r = rawWords(raw)+ guard n.count == r.count, !n.isEmpty else { return nil }+ let sendVerbs: Set<String> = ["envoie", "envoyer", "envoies", "ecris", "ecrire", "send", "email", "mail"]+ guard let v = n.firstIndex(where: { sendVerbs.contains($0) }) else { return nil }+ let rest = Array(n[(v + 1)...])+ let isMail = rest.contains(where: { ["mail", "email", "mel", "courriel", "fichier", "file", "document", "pdf"].contains($0) })+ || ["email", "mail"].contains(n[v])+ guard isMail else { return nil }+ // Recipient: after the last "à" / "to".+ guard let to = n.lastIndex(where: { $0 == "a" || $0 == "to" }), to > v, to + 1 < n.count else { return nil }+ let recipient = r[(to + 1)...].joined(separator: " ")+ .trimmingCharacters(in: .punctuationCharacters.union(.whitespaces))+ guard !recipient.isEmpty else { return nil }++ // Optional file: after "fichier"/"file"/"document", up to the folder words or "à".+ var file: String? = nil+ var folder: MailRequest.Folder? = nil+ let middle = Array(n[(v + 1)..<to])+ if middle.contains(where: { ["telechargements", "telechargement", "downloads"].contains($0) }) { folder = .downloads }+ else if middle.contains(where: { ["bureau", "desktop"].contains($0) }) { folder = .desktop }+ else if middle.contains(where: { ["documents"].contains($0) }) { folder = .documents }+ if let f = n[(v + 1)..<to].firstIndex(where: { ["fichier", "file", "document", "pdf"].contains($0) }) {+ let stop: Set<String> = ["des", "du", "de", "dans", "from", "in", "telechargements", "telechargement",+ "downloads", "bureau", "desktop", "documents", "mes", "my", "par", "en"]+ var end = f + 1+ while end < to && !(stop.contains(n[end]) && end > f + 1) { end += 1 }+ let name = r[(f + 1)..<end].joined(separator: " ")+ if !name.isEmpty { file = name }+ if n[f] == "pdf", file == nil { file = "pdf" }+ }+ return MailRequest(recipient: recipient, file: file, folder: folder)+ }++ // MARK: Open an app: "ouvre Figma", "open Safari"++ static func appToOpen(_ raw: String) -> String? {+ let n = IntentParser.normalise(raw).split(separator: " ").map(String.init)+ let r = rawWords(raw)+ guard n.count == r.count,+ let i = n.firstIndex(where: { ["ouvre", "ouvrir", "open"].contains($0) }),+ i + 1 < n.count else { return nil }+ var start = i + 1+ while start < n.count, ["moi", "l", "la", "le", "app", "application", "the", "appli"].contains(n[start]) { start += 1 }+ guard start < n.count else { return nil }+ let name = r[start...].joined(separator: " ").trimmingCharacters(in: .punctuationCharacters)+ return name.isEmpty ? nil : name+ }++ /// Same splits as IntentParser.normalise, original casing kept, one entry per word.+ static func rawWords(_ raw: String) -> [String] {+ var s = raw+ for c in ["'", "\u{2019}", "-"] { s = s.replacingOccurrences(of: c, with: " ") }+ return s.split(separator: " ").map(String.init).filter { w in+ !IntentParser.normalise(w).isEmpty+ }+ }+}++// MARK: - Snapshot (filled on the Mac side)++struct VoiceSnapshot {+ struct Payment { var amount: String; var description: String?; var ago: String; var succeeded: Bool }+ struct Stripe {+ var balance: String // "1 240,00 €"+ var today: String? // nil when the day total could not be fetched+ var todayCount: Int = 0+ var last: [Payment] = []+ }+ struct PR { var title: String; var repo: String; var ci: String; var review: String }+ struct GitHub {+ var stars: Int?; var repos: Int?+ var myPRs: [PR] = []; var toReview: Int = 0; var failingRepos: [String] = []+ }+ struct Deploy { var project: String; var state: String; var ago: String; var commit: String? }+ struct Session { var name: String; var state: String; var detail: String? }+ struct Plan { var fiveHourPct: Int?; var sevenDayPct: Int?; var resetsIn: String? }+ struct Booking { var title: String; var when: String; var with: String? }+ struct Weather {+ var city: String+ var nowTemp: Int?; var code: Int+ var min: Int; var max: Int; var rainChance: Int?; var wind: Int?+ }++ var configured: Bool = true // false → "<service> n'est pas connecté"+ var stripe: Stripe?+ var github: GitHub?+ var deploys: [Deploy] = []+ var emailsTotal: Int?; var emails: [(to: String, subject: String, state: String)] = []+ var runs: [(workflow: String, ok: Bool, ago: String)] = []+ var pages: [(title: String, ago: String)] = []+ var bookings: [Booking] = []+ var sessions: [Session] = []+ var approvalPending: String? // tool waiting for approval+ var plan: Plan?+ var nowPlaying: (title: String, artist: String?)?+ var mainPill: String?; var activePills: [String] = []+ var weather: Weather?+ var weatherOff = false // feature disabled in Settings+ var weatherNoCity = false+}++// MARK: - Answers++enum VoiceAnswer {++ static func text(_ topic: VoiceTopic, _ s: VoiceSnapshot, french fr: Bool) -> String {+ func t(_ f: String, _ e: String) -> String { fr ? f : e }+ if !s.configured {+ return t("\(serviceName(topic)) n'est pas connecté dans les réglages de Coucou.",+ "\(serviceName(topic)) isn't connected in Coucou's settings.")+ }+ switch topic {+ case .stripe:+ guard let st = s.stripe else { return t("Je n'ai pas encore les données Stripe.", "I don't have Stripe data yet.") }+ var out: String+ if let today = st.today {+ out = st.todayCount == 0+ ? t("Aucune vente aujourd'hui pour l'instant.", "No sales yet today.")+ : t("Aujourd'hui : \(today), \(st.todayCount) paiement\(st.todayCount > 1 ? "s" : "").",+ "Today: \(today) from \(st.todayCount) payment\(st.todayCount > 1 ? "s" : "").")+ out += t(" Solde : \(st.balance).", " Balance: \(st.balance).")+ } else {+ out = t("Ton solde Stripe est de \(st.balance).", "Your Stripe balance is \(st.balance).")+ if let p = st.last.first {+ out += t(" Dernier paiement : \(p.amount), il y a \(p.ago).", " Last payment: \(p.amount), \(p.ago) ago.")+ }+ }+ return out++ case .github:+ guard let g = s.github else { return t("Je n'ai pas encore les données GitHub.", "I don't have GitHub data yet.") }+ var parts: [String] = []+ if let stars = g.stars {+ let repos = g.repos.map { t(" sur \($0) repos", " across \($0) repos") } ?? ""+ parts.append(t("Tu as \(stars) étoile\(stars > 1 ? "s" : "")\(repos).", "You have \(stars) star\(stars == 1 ? "" : "s")\(repos)."))+ }+ if !g.myPRs.isEmpty {+ let red = g.myPRs.filter { $0.ci == "failure" }.count+ var p = t("\(g.myPRs.count) PR ouverte\(g.myPRs.count > 1 ? "s" : "")", "\(g.myPRs.count) open PR\(g.myPRs.count > 1 ? "s" : "")")+ if red > 0 { p += t(", dont \(red) avec la CI en échec", ", \(red) with failing CI") }+ parts.append(p + ".")+ }+ if g.toReview > 0 { parts.append(t("\(g.toReview) à relire.", "\(g.toReview) waiting for your review.")) }+ if let repo = g.failingRepos.first { parts.append(t("La CI de \(repo) est rouge.", "CI is red on \(repo).")) }+ return parts.isEmpty ? t("Rien de spécial sur GitHub.", "Nothing new on GitHub.") : parts.joined(separator: " ")++ case .vercel:+ guard let d = s.deploys.first else { return t("Aucun déploiement Vercel récent.", "No recent Vercel deployment.") }+ let ok = d.state == "READY"+ let state = ok ? t("est en ligne", "is live") : (d.state == "ERROR" ? t("a échoué", "failed")+ : d.state == "CANCELED" ? t("a été annulé", "was canceled") : t("est en cours", "is in progress"))+ var out = t("Le dernier déploiement de \(d.project) \(state), il y a \(d.ago).",+ "The last \(d.project) deployment \(state), \(d.ago) ago.")+ if !ok, let ready = s.deploys.dropFirst().first(where: { $0.state == "READY" }) {+ out += t(" Le précédent en ligne date de \(ready.ago).", " The previous live one is from \(ready.ago) ago.")+ }+ return out++ case .resend:+ if s.emails.isEmpty { return t("Aucun mail envoyé récemment avec Resend.", "No recent email sent with Resend.") }+ let e = s.emails[0]+ var out = s.emailsTotal.map { t("\($0) mails envoyés au total.", "\($0) emails sent in total.") } ?? ""+ out += t(" Le dernier, « \(e.subject) » à \(e.to) : \(e.state).", " Last one, “\(e.subject)” to \(e.to): \(e.state).")+ return out.trimmingCharacters(in: .whitespaces)++ case .n8n:+ guard let r = s.runs.first else { return t("Aucune exécution n8n récente.", "No recent n8n run.") }+ let failed = s.runs.filter { !$0.ok }.count+ var out = t("Dernier workflow : \(r.workflow), \(r.ok ? "réussi" : "en échec"), il y a \(r.ago).",+ "Last workflow: \(r.workflow), \(r.ok ? "succeeded" : "failed"), \(r.ago) ago.")+ if failed > 0 && r.ok { out += t(" \(failed) échec\(failed > 1 ? "s" : "") récent\(failed > 1 ? "s" : "").", " \(failed) recent failure\(failed > 1 ? "s" : "").") }+ return out++ case .notion:+ guard let p = s.pages.first else { return t("Aucune page Notion récente.", "No recent Notion page.") }+ return t("Dernière page modifiée : \(p.title), il y a \(p.ago).", "Last edited page: \(p.title), \(p.ago) ago.")++ case .calcom:+ guard let b = s.bookings.first else { return t("Aucun rendez-vous à venir.", "No upcoming booking.") }+ let who = b.with.map { t(" avec \($0)", " with \($0)") } ?? ""+ var out = t("Prochain rendez-vous : \(b.title)\(who), \(b.when).", "Next booking: \(b.title)\(who), \(b.when).")+ if s.bookings.count > 1 { out += t(" \(s.bookings.count) au total.", " \(s.bookings.count) in total.") }+ return out++ case .agents:+ if let tool = s.approvalPending {+ return t("Une demande d'autorisation attend ton clic : \(tool).", "A permission request is waiting for your click: \(tool).")+ }+ let busy = s.sessions.filter { $0.state != "idle" && $0.state != "sleeping" }+ guard !busy.isEmpty else { return t("Aucun agent ne travaille en ce moment.", "No agent is working right now.") }+ return busy.prefix(3).map { a in+ let st = stateText(a.state, fr: fr)+ return a.detail.map { "\(a.name) \(st) : \($0)." } ?? "\(a.name) \(st)."+ }.joined(separator: " ")++ case .claudePlan, .codexPlan:+ let name = topic == .claudePlan ? "Claude" : "Codex"+ guard let p = s.plan, p.fiveHourPct != nil || p.sevenDayPct != nil else {+ return t("Je n'ai pas encore l'usage de ton plan \(name).", "I don't have your \(name) plan usage yet.")+ }+ var parts: [String] = []+ if let h = p.fiveHourPct { parts.append(t("\(h) % sur 5 heures", "\(h)% of the 5-hour window")) }+ if let w = p.sevenDayPct { parts.append(t("\(w) % sur la semaine", "\(w)% of the week")) }+ var out = t("Plan \(name) : ", "\(name) plan: ") + parts.joined(separator: t(" et ", " and ")) + "."+ if let r = p.resetsIn { out += t(" Remise à zéro dans \(r).", " Resets in \(r).") }+ return out++ case .music:+ guard let n = s.nowPlaying else { return t("Rien ne joue en ce moment.", "Nothing is playing right now.") }+ return n.artist.map { t("C'est \(n.title), de \($0).", "It's \(n.title) by \($0).") } ?? n.title++ case .pills:+ let main = s.mainPill.map { t("Pilule principale : \($0).", "Main pill: \($0).") } ?? ""+ let others = s.activePills.isEmpty ? t(" Aucune autre pilule.", " No other pill.")+ : t(" Actives : \(s.activePills.joined(separator: ", ")).", " Active: \(s.activePills.joined(separator: ", ")).")+ return (main + others).trimmingCharacters(in: .whitespaces)++ case .weatherToday, .weatherTomorrow:+ if s.weatherOff { return t("Active la météo dans les réglages de Coucou, section Voix.", "Turn on weather in Coucou's settings, Voice section.") }+ if s.weatherNoCity { return t("Indique ta ville dans les réglages de Coucou, section Voix.", "Set your city in Coucou's settings, Voice section.") }+ guard let w = s.weather else { return t("Je n'arrive pas à avoir la météo pour l'instant.", "I can't get the weather right now.") }+ let sky = weatherText(w.code, fr: fr)+ var out: String+ if topic == .weatherTomorrow {+ out = t("Demain à \(w.city) : \(sky), de \(w.min) à \(w.max) degrés.", "Tomorrow in \(w.city): \(sky), \(w.min) to \(w.max) degrees.")+ } else if let now = w.nowTemp {+ out = t("À \(w.city), \(now) degrés, \(sky). Entre \(w.min) et \(w.max) aujourd'hui.",+ "In \(w.city), \(now) degrees, \(sky). Between \(w.min) and \(w.max) today.")+ } else {+ out = t("Aujourd'hui à \(w.city) : \(sky), de \(w.min) à \(w.max) degrés.", "Today in \(w.city): \(sky), \(w.min) to \(w.max) degrees.")+ }+ if let rain = w.rainChance, rain >= 30 { out += t(" \(rain) % de risque de pluie.", " \(rain)% chance of rain.") }+ return out+ }+ }++ static func serviceName(_ topic: VoiceTopic) -> String {+ switch topic {+ case .stripe: return "Stripe"+ case .github: return "GitHub"+ case .vercel: return "Vercel"+ case .resend: return "Resend"+ case .n8n: return "n8n"+ case .notion: return "Notion"+ case .calcom: return "Cal.com"+ case .claudePlan: return "Claude"+ case .codexPlan: return "Codex"+ case .agents: return "Claude Code"+ case .music: return "Music"+ case .pills: return "Coucou"+ case .weatherToday, .weatherTomorrow: return "Météo"+ }+ }++ static func stateText(_ state: String, fr: Bool) -> String {+ switch state {+ case "working": return fr ? "travaille" : "is working"+ case "thinking": return fr ? "réfléchit" : "is thinking"+ case "searching": return fr ? "cherche" : "is searching"+ case "approval": return fr ? "attend ton autorisation" : "is waiting for your approval"+ case "question": return fr ? "te pose une question" : "has a question for you"+ case "error": return fr ? "est en erreur" : "hit an error"+ case "finished": return fr ? "a terminé" : "is done"+ case "ratelimit": return fr ? "a atteint sa limite" : "hit its rate limit"+ default: return fr ? "est actif" : "is active"+ }+ }++ /// WMO weather codes (Open-Meteo).+ static func weatherText(_ code: Int, fr: Bool) -> String {+ switch code {+ case 0: return fr ? "ciel dégagé" : "clear sky"+ case 1, 2: return fr ? "quelques nuages" : "partly cloudy"+ case 3: return fr ? "couvert" : "overcast"+ case 45, 48: return fr ? "brouillard" : "fog"+ case 51, 53, 55, 56, 57: return fr ? "bruine" : "drizzle"+ case 61, 63, 66: return fr ? "pluie" : "rain"+ case 65, 67: return fr ? "forte pluie" : "heavy rain"+ case 71, 73, 75, 77: return fr ? "neige" : "snow"+ case 80, 81: return fr ? "averses" : "showers"+ case 82: return fr ? "fortes averses" : "heavy showers"+ case 85, 86: return fr ? "averses de neige" : "snow showers"+ case 95, 96, 99: return fr ? "orages" : "thunderstorms"+ default: return fr ? "temps variable" : "mixed weather"+ }+ }+}+#endifdiff --git a/NotchBuddy/Sources/App/Voice/VoiceSettings.swift b/NotchBuddy/Sources/App/Voice/VoiceSettings.swiftindex 8eaa9beb..60fe0748 100644--- a/NotchBuddy/Sources/App/Voice/VoiceSettings.swift+++ b/NotchBuddy/Sources/App/Voice/VoiceSettings.swift@@ -35,6 +35,17 @@ enum VoiceSettings {set { UserDefaults.standard.set(newValue, forKey: captionEnabledKey) }}+ /// Weather by voice (Open-Meteo, no key). Off by default: network only when the user+ /// turned it on and set a city.+ static var weatherEnabled: Bool {+ get { UserDefaults.standard.bool(forKey: "voiceWeatherEnabled") }+ set { UserDefaults.standard.set(newValue, forKey: "voiceWeatherEnabled") }+ }+ static var weatherCity: String {+ get { UserDefaults.standard.string(forKey: "voiceWeatherCity") ?? "" }+ set { UserDefaults.standard.set(newValue, forKey: "voiceWeatherCity") }+ }+// MARK: - Permissionsenum PermissionStatus { case granted, denied, undetermined }diff --git a/NotchBuddy/project.yml b/NotchBuddy/project.ymlindex 73dbd85c..3cdd969e 100644--- a/NotchBuddy/project.yml+++ b/NotchBuddy/project.yml@@ -139,6 +139,7 @@ targets:NSMicrophoneUsageDescription: "Coucou uses the microphone when you dictate a message in the chat."NSSpeechRecognitionUsageDescription: "Coucou turns your voice into the text of a chat message."NSAccessibilityUsageDescription: "Pour lire le titre de la fenêtre active et l'attacher comme contexte."+ NSContactsUsageDescription: "Coucou looks up an email address when you ask it, by voice, to prepare an email."NSAppTransportSecurity:NSAllowsLocalNetworking: trueCFBundleLocalizations:diff --git a/scripts/test-conversation-context.sh b/scripts/test-conversation-context.shindex 851b41e6..629076a1 100755--- a/scripts/test-conversation-context.sh+++ b/scripts/test-conversation-context.sh@@ -8,6 +8,7 @@ swiftc -swift-version 6 -strict-concurrency=complete \"$ROOT/tests/PillFixture.swift" \"$ROOT/NotchBuddy/Sources/App/Voice/VoiceIntent.swift" \"$ROOT/NotchBuddy/Sources/App/Voice/IntentParser.swift" \+ "$ROOT/NotchBuddy/Sources/App/Voice/VoiceQuery.swift" \"$ROOT/NotchBuddy/Sources/App/Voice/EntityResolver.swift" \"$ROOT/NotchBuddy/Sources/App/Voice/ConversationContext.swift" \"$ROOT/tests/ConversationContextTests.swift" \diff --git a/scripts/test-voice-entity.sh b/scripts/test-voice-entity.shindex 450b0098..453307ac 100755--- a/scripts/test-voice-entity.sh+++ b/scripts/test-voice-entity.sh@@ -6,6 +6,7 @@ swiftc -o /tmp/voice-entity-tests \tests/PillFixture.swift \NotchBuddy/Sources/App/Voice/VoiceIntent.swift \NotchBuddy/Sources/App/Voice/IntentParser.swift \+ NotchBuddy/Sources/App/Voice/VoiceQuery.swift \NotchBuddy/Sources/App/Voice/EntityResolver.swift \tests/EntityResolverTests.swift/tmp/voice-entity-testsdiff --git a/scripts/test-voice-intent.sh b/scripts/test-voice-intent.shindex a90bac5b..050e29b7 100755--- a/scripts/test-voice-intent.sh+++ b/scripts/test-voice-intent.sh@@ -7,5 +7,6 @@ swiftc -o /tmp/voice-intent-tests \NotchBuddy/Sources/App/Voice/VoiceIntent.swift \NotchBuddy/Sources/App/Voice/EntityResolver.swift \NotchBuddy/Sources/App/Voice/IntentParser.swift \+ NotchBuddy/Sources/App/Voice/VoiceQuery.swift \tests/IntentParserTests.swift/tmp/voice-intent-testsdiff --git a/scripts/test-voice-query.sh b/scripts/test-voice-query.shnew file mode 100755index 00000000..b045051f--- /dev/null+++ b/scripts/test-voice-query.sh@@ -0,0 +1,12 @@+#!/usr/bin/env bash+set -e+echo "Running VoiceQuery tests…"+swiftc -o /tmp/voice-query-tests \+ tests/VoiceTestStubs.swift \+ tests/PillFixture.swift \+ NotchBuddy/Sources/App/Voice/VoiceIntent.swift \+ NotchBuddy/Sources/App/Voice/EntityResolver.swift \+ NotchBuddy/Sources/App/Voice/IntentParser.swift \+ NotchBuddy/Sources/App/Voice/VoiceQuery.swift \+ tests/VoiceQueryTests.swift+/tmp/voice-query-testsdiff --git a/scripts/test-voice-runner.sh b/scripts/test-voice-runner.shindex ed03025b..a46c9a6a 100755--- a/scripts/test-voice-runner.sh+++ b/scripts/test-voice-runner.sh@@ -6,6 +6,7 @@ swiftc -o /tmp/voice-runner-tests \tests/PillFixture.swift \NotchBuddy/Sources/App/Voice/VoiceIntent.swift \NotchBuddy/Sources/App/Voice/IntentParser.swift \+ NotchBuddy/Sources/App/Voice/VoiceQuery.swift \NotchBuddy/Sources/App/Voice/EntityResolver.swift \NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift \tests/VoiceActionRunnerTests.swiftdiff --git a/tests/VoiceQueryTests.swift b/tests/VoiceQueryTests.swiftnew file mode 100644index 00000000..8eb15a77--- /dev/null+++ b/tests/VoiceQueryTests.swift@@ -0,0 +1,109 @@+// tests/VoiceQueryTests.swift — questions, mail and app requests, spoken answers.+import Foundation++@main+struct VoiceQueryTests {+ nonisolated(unsafe) static var pass = 0+ nonisolated(unsafe) static var fail = 0++ static func check<T: Equatable>(_ label: String, _ got: T, _ want: T) {+ if got == want { print("✓ \(label)"); pass += 1 }+ else { print("✗ \(label) — got \(got), want \(want)"); fail += 1 }+ }+ static func contains(_ label: String, _ text: String, _ part: String) {+ if text.contains(part) { print("✓ \(label)"); pass += 1 }+ else { print("✗ \(label) — \"\(text)\" has no \"\(part)\""); fail += 1 }+ }++ static func main() {+ let pills = PillFixture.available+ // ── Topics: Louis's own questions ─────────────────────────────────────+ let topics: [(String, VoiceTopic?)] = [+ ("Quel temps il fait aujourd'hui ?", .weatherToday),+ ("il va pleuvoir demain ?", .weatherTomorrow),+ ("météo", .weatherToday),+ ("Combien d'argent j'ai fait aujourd'hui sur Stripe ?", .stripe),+ ("combien j'ai vendu aujourd'hui", .stripe),+ ("Mon push Vercel, est-ce qu'il a été push ?", .vercel),+ ("est-ce que mon déploiement est passé", .vercel),+ ("Combien d'étoiles j'ai sur GitHub ?", .github),+ ("combien d'étoiles j'ai", .github),+ ("Qu'est-ce qui se passe sur mon Claude Code ?", .agents),+ ("il en est où Codex ?", .agents),+ ("il me reste combien sur mon plan Claude ?", .claudePlan),+ ("c'est quoi mon usage Codex", .codexPlan),+ ("j'ai des rendez-vous aujourd'hui ?", .calcom),+ ("c'est quoi cette chanson", .music),+ ("quelles pilules sont actives", .pills),+ ("how many stars do I have on GitHub?", .github),+ ("what's the weather like?", .weatherToday),+ // Commands stay commands+ ("est-ce que tu peux ajouter GitHub", nil),+ ("ajoute Stripe", nil),+ ("mets du Drake", nil),+ ("On s'en fout c'est", nil),+ ]+ for (phrase, want) in topics { check("topic «\(phrase)»", VoiceQuery.topic(of: phrase), want) }++ // ── Through the parser ────────────────────────────────────────────────+ check("parse stripe question", IntentParser.parse("Combien d'argent j'ai fait aujourd'hui sur Stripe ?", pills: pills), .query(.stripe))+ check("parse add stays add", IntentParser.parse("ajoute la pilule Stripe", pills: pills), .pillAdd(id: "integration_stripe"))++ // ── Mail ──────────────────────────────────────────────────────────────+ check("mail to Tana", VoiceQuery.mail(of: "Envoie un mail à Tana"),+ VoiceQuery.MailRequest(recipient: "Tana", file: nil, folder: nil))+ check("mail file from downloads", VoiceQuery.mail(of: "envoie le fichier facture octobre des téléchargements à Tana"),+ VoiceQuery.MailRequest(recipient: "Tana", file: "facture octobre", folder: .downloads))+ check("mail file from desktop", VoiceQuery.mail(of: "envoie le fichier devis du bureau à Paul Martin"),+ VoiceQuery.MailRequest(recipient: "Paul Martin", file: "devis", folder: .desktop))+ check("send an email to", VoiceQuery.mail(of: "send an email to Tana"),+ VoiceQuery.MailRequest(recipient: "Tana", file: nil, folder: nil))+ check("not a mail", VoiceQuery.mail(of: "envoie la musique"), nil)+ check("parse mail", IntentParser.parse("Envoie un mail à Intel", pills: pills),+ .mail(VoiceQuery.MailRequest(recipient: "Intel", file: nil, folder: nil)))++ // ── Apps ──────────────────────────────────────────────────────────────+ check("ouvre Figma", VoiceQuery.appToOpen("ouvre Figma"), "Figma")+ check("ouvre l'app Notes", VoiceQuery.appToOpen("ouvre l'app Notes"), "Notes")+ check("open Safari", VoiceQuery.appToOpen("open Safari"), "Safari")+ check("parse open app", IntentParser.parse("ouvre Figma", pills: pills), .openApp(name: "Figma"))++ // ── Answers ───────────────────────────────────────────────────────────+ var s = VoiceSnapshot()+ s.stripe = .init(balance: "1 240,00 €", today: "85,00 €", todayCount: 2, last: [])+ contains("stripe today fr", VoiceAnswer.text(.stripe, s, french: true), "Aujourd'hui : 85,00 €, 2 paiements")+ s.stripe = .init(balance: "1 240,00 €", today: "0,00 €", todayCount: 0, last: [])+ contains("stripe no sale", VoiceAnswer.text(.stripe, s, french: true), "Aucune vente aujourd'hui")+ s.github = .init(stars: 128, repos: 12,+ myPRs: [.init(title: "a", repo: "r", ci: "failure", review: "pending"),+ .init(title: "b", repo: "r", ci: "success", review: "approved")],+ toReview: 1, failingRepos: [])+ let gh = VoiceAnswer.text(.github, s, french: true)+ contains("github stars", gh, "128 étoiles sur 12 repos")+ contains("github red CI", gh, "dont 1 avec la CI en échec")+ s.deploys = [.init(project: "korus", state: "ERROR", ago: "5 minutes", commit: nil),+ .init(project: "korus", state: "READY", ago: "2 heures", commit: nil)]+ contains("vercel failed", VoiceAnswer.text(.vercel, s, french: true), "korus a échoué, il y a 5 minutes")+ s.sessions = [.init(name: "Claude Code", state: "working", detail: "Edit IntentParser.swift")]+ contains("agents", VoiceAnswer.text(.agents, s, french: true), "Claude Code travaille : Edit IntentParser.swift")+ s.approvalPending = "Bash"+ contains("approval first", VoiceAnswer.text(.agents, s, french: true), "autorisation attend ton clic : Bash")+ var off = VoiceSnapshot(); off.configured = false+ contains("not configured", VoiceAnswer.text(.stripe, off, french: true), "Stripe n'est pas connecté")+ var w = VoiceSnapshot()+ w.weatherOff = true+ contains("weather off", VoiceAnswer.text(.weatherToday, w, french: true), "Active la météo")+ w.weatherOff = false+ w.weather = .init(city: "Bordeaux", nowTemp: 17, code: 61, min: 12, max: 19, rainChance: 70, wind: 20)+ let wt = VoiceAnswer.text(.weatherToday, w, french: true)+ contains("weather now", wt, "À Bordeaux, 17 degrés, pluie")+ contains("weather rain", wt, "70 % de risque de pluie")+ contains("weather en", VoiceAnswer.text(.weatherTomorrow, w, french: false), "Tomorrow in Bordeaux: rain, 12 to 19 degrees")+ check("wmo 0", VoiceAnswer.weatherText(0, fr: true), "ciel dégagé")+ check("wmo 95", VoiceAnswer.weatherText(95, fr: false), "thunderstorms")++ let total = pass + fail+ if fail == 0 { print("\n\(total)/\(total) passed.") }+ else { print("\n\(fail) FAILED / \(total) total"); exit(1) }+ }+}