Skip to content

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

Voice Phase 2 review 2: musicPlaySearch, targets, filler tolerance, multi-pill, question answer

Louis Raille714c66f5f175
diff --git a/NotchBuddy/Sources/App/AppState.swift b/NotchBuddy/Sources/App/AppState.swift
index 09ad16b9..9aee4833 100644
--- a/NotchBuddy/Sources/App/AppState.swift
+++ b/NotchBuddy/Sources/App/AppState.swift
@@ -318,12 +318,6 @@ final class AppState: ObservableObject {
}
}
- /// Pill IDs for which the user has gone through hook installation.
- @Published var installedHookPills: Set<String> = {
- let stored = UserDefaults.standard.array(forKey: "coucou.installedHookPills") as? [String] ?? []
- return Set(stored)
- }()
-
// Active integration pills (main workspace pill excluded). Max 4.
@Published var activeIntegrations: Set<String> = ["integration_resend", "integration_n8n", "integration_vercel", "integration_github"] {
didSet {
diff --git a/NotchBuddy/Sources/App/HookServer.swift b/NotchBuddy/Sources/App/HookServer.swift
index a1c537f2..5285a68b 100644
--- a/NotchBuddy/Sources/App/HookServer.swift
+++ b/NotchBuddy/Sources/App/HookServer.swift
@@ -1584,6 +1584,37 @@ final class HookServer: @unchecked Sendable {
// MARK: Installed-state detection
+ /// Single entry point used by voice commands and Settings pill rows.
+ /// Returns true when the given pill's hooks/plugin are installed.
+ /// Workspace pills (integration_claude, agent_cursor) use claudeHooksInstalled().
+ /// Unknown pill ids return true (assumed not hook-dependent).
+ static func hooksInstalled(for pillId: String) -> Bool {
+ switch pillId {
+ case "integration_claude", "agent_cursor":
+ return claudeHooksInstalled()
+ #if !APPSTORE
+ case "agent_gemini":
+ return geminiHooksInstalled()
+ case "agent_antigravity":
+ return agyHooksInstalled()
+ case "agent_codex":
+ return codexHooksInstalled()
+ case "agent_copilot":
+ return copilotHooksInstalled()
+ case "agent_muse":
+ return museHooksInstalled()
+ case "agent_opencode":
+ return openCodePluginInstalled()
+ case "agent_amp":
+ return ampPluginInstalled()
+ case "agent_hermes":
+ return hermesPluginInstalled()
+ #endif
+ default:
+ return true
+ }
+ }
+
static func geminiHooksInstalled() -> Bool {
guard let data = try? Data(contentsOf: geminiSettingsURL),
let settings = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
diff --git a/NotchBuddy/Sources/App/IslandViewContent.swift b/NotchBuddy/Sources/App/IslandViewContent.swift
index a6b39ca2..6d030fd9 100644
--- a/NotchBuddy/Sources/App/IslandViewContent.swift
+++ b/NotchBuddy/Sources/App/IslandViewContent.swift
@@ -1719,81 +1719,7 @@ struct IntegrationCardView: View {
@State private var githubDetailSection: GitHubDetailSection = .myPRs
private var isConfigured: Bool {
- switch task.id {
- // Cursor sessions are Claude Code running in Cursor's integrated terminal,
- // so the Cursor pill is set up exactly when the Claude Code hooks are.
- case "integration_claude", "agent_cursor":
- return HookServer.claudeHooksInstalled()
- case "agent_codex":
- #if !APPSTORE
- return HookServer.codexHooksInstalled()
- #else
- return false
- #endif
- case "agent_gemini":
- #if !APPSTORE
- return HookServer.geminiHooksInstalled()
- #else
- return false
- #endif
- case "agent_antigravity":
- #if !APPSTORE
- return HookServer.agyHooksInstalled()
- #else
- return false
- #endif
- case "agent_copilot":
- #if !APPSTORE
- return HookServer.copilotHooksInstalled()
- #else
- return false
- #endif
- case "agent_muse":
- #if !APPSTORE
- return HookServer.museHooksInstalled()
- #else
- return false
- #endif
- case "agent_opencode":
- #if !APPSTORE
- return HookServer.openCodePluginInstalled()
- #else
- return false
- #endif
- case "agent_amp":
- #if !APPSTORE
- return HookServer.ampPluginInstalled()
- #else
- return false
- #endif
- case "agent_hermes":
- #if !APPSTORE
- return HookServer.hermesPluginInstalled()
- #else
- return false
- #endif
- case "agent_claude-desktop":
- return true // nothing to install: the relay tags desktop sessions on its own
- case "integration_music":
- #if !APPSTORE
- return true // Apple Music is always installed on macOS
- #else
- return false
- #endif
- case "ai_anthropic": return KeychainStore.shared.get("anthropic-api-key") != nil
- case "ai_google": return KeychainStore.shared.get("google-api-key") != nil
- case "ai_openai": return KeychainStore.shared.get("openai-api-key") != nil
- case "ai_ollama": return !AppState.shared.ollamaServerURL.isEmpty
- case "ai_lmstudio": return !AppState.shared.lmstudioServerURL.isEmpty
- case "integration_resend": return KeychainStore.shared.get("resend-api-key") != nil
- case "integration_n8n": return KeychainStore.shared.get("n8n-api-key") != nil
- case "integration_vercel": return KeychainStore.shared.get("vercel-token") != nil
- case "integration_github": return KeychainStore.shared.get("github-token") != nil
- case "integration_stripe": return KeychainStore.shared.get("stripe-api-key") != nil
- case "integration_notion": return KeychainStore.shared.get("notion-api-key") != nil
- case "integration_calcom": return KeychainStore.shared.get("calcom-api-key") != nil
- default: return false
- }
+ HookServer.hooksInstalled(for: task.id)
}
private var openURL: URL? {
diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swift
index 6daa12f4..a12f6109 100644
--- a/NotchBuddy/Sources/App/IslandWindowController.swift
+++ b/NotchBuddy/Sources/App/IslandWindowController.swift
@@ -1287,6 +1287,15 @@ extension IslandWindowController {
@MainActor
func handleVoiceCommand(_ transcript: String) async {
let pills = PillCatalog.available
+
+ // ── Follow-up answer to a pending question ────────────────────────────────
+ if VoiceActionRunner.shared.pendingQuestion != nil {
+ let result = await VoiceActionRunner.shared.handleAnswer(transcript, availablePills: pills)
+ showVoiceResult(result, emote: result.outcome == .success ? BotEmote.happy : nil)
+ return
+ }
+
+ // ── Normal command ────────────────────────────────────────────────────────
let intent = IntentParser.parse(transcript, pills: pills)
let result = await VoiceActionRunner.shared.run(intent, availablePills: pills, rawTranscript: transcript)
@@ -1297,22 +1306,47 @@ extension IslandWindowController {
case .failure:
NotificationCenter.default.post(name: .botDizzy, object: nil)
case .question:
- break
+ break // Mochi will show listening after re-open
+ }
+
+ // Show result view
+ AppState.shared.voiceResult = result
+ expand(to: .voiceResult)
+
+ if case .question = result.outcome {
+ // Re-open listening immediately (without wake phrase) so Mochi listens for the answer
+ voiceResultWork?.cancel()
+ voiceResultWork = nil
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in
+ guard self != nil else { return }
+ VoiceEngine.shared.startListeningDirectly()
+ }
+ } else {
+ scheduleVoiceDismiss(delay: result.outcome == .success ? 2.0 : 2.0)
}
+ }
- // Switch to result view
+ @MainActor
+ private func showVoiceResult(_ result: VoiceActionResult, emote: BotEmote? = nil) {
+ if let emote = emote {
+ NotificationCenter.default.post(name: .triggerEmote, object: emote)
+ } else if result.outcome == .failure {
+ NotificationCenter.default.post(name: .botDizzy, object: nil)
+ }
AppState.shared.voiceResult = result
expand(to: .voiceResult)
+ scheduleVoiceDismiss(delay: 2.0)
+ }
+ @MainActor
+ private func scheduleVoiceDismiss(delay: TimeInterval) {
voiceResultWork?.cancel()
- let dismissDelay: TimeInterval
- if case .question = result.outcome { dismissDelay = 6.0 } else { dismissDelay = 2.0 }
let item = DispatchWorkItem { [weak self] in
AppState.shared.voiceResult = nil
self?.fsm.voiceFinished()
}
voiceResultWork = item
- DispatchQueue.main.asyncAfter(deadline: .now() + dismissDelay, execute: item)
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: item)
}
}
#endif
diff --git a/NotchBuddy/Sources/App/MusicController.swift b/NotchBuddy/Sources/App/MusicController.swift
index 0669b0f7..95bc748b 100644
--- a/NotchBuddy/Sources/App/MusicController.swift
+++ b/NotchBuddy/Sources/App/MusicController.swift
@@ -262,6 +262,25 @@ final class MusicController: ObservableObject {
return false
}
+ func playSearch(_ query: String) async -> Bool {
+ let escaped = query
+ .replacingOccurrences(of: "\\", with: "\\\\")
+ .replacingOccurrences(of: "\"", with: "\\\"")
+ let result = await runAppleScript("""
+ tell application id "com.apple.Music"
+ try
+ set tr to (first track of library playlist 1 whose name contains "\(escaped)" or artist contains "\(escaped)")
+ play tr
+ return "ok"
+ on error
+ return "notfound"
+ end try
+ end tell
+ """)
+ if case .success(let vals) = result, vals.first == "ok" { return true }
+ return false
+ }
+
func playPlaylist(_ name: String) async -> Bool {
let escaped = name
.replacingOccurrences(of: "\\", with: "\\\\")
diff --git a/NotchBuddy/Sources/App/SettingsView.swift b/NotchBuddy/Sources/App/SettingsView.swift
index 56f43748..7211e6b9 100644
--- a/NotchBuddy/Sources/App/SettingsView.swift
+++ b/NotchBuddy/Sources/App/SettingsView.swift
@@ -520,9 +520,7 @@ struct SettingsView: View {
}
}
.onChange(of: state.mainPillId) { _, newId in
- state.activeIntegrations.remove(newId)
- state.loadIntegrationTasks()
- state.setFocus(newId)
+ state.setMainPill(newId)
}
ForEach(PillCategory.allCases, id: \.self) { cat in
@@ -1903,13 +1901,7 @@ struct SettingsView: View {
if isMain { return nil }
if def.comingSoon { return String(localized: "Coming soon") }
#if !APPSTORE
- if def.id == "agent_gemini" && !HookServer.geminiHooksInstalled() { return String(localized: "Hooks not installed") }
- if def.id == "agent_antigravity" && !HookServer.agyHooksInstalled() { return String(localized: "Hooks not installed") }
- if def.id == "agent_codex" && !HookServer.codexHooksInstalled() { return String(localized: "Hooks not installed") }
- if def.id == "agent_copilot" && !HookServer.copilotHooksInstalled() { return String(localized: "Hooks not installed") }
- if def.id == "agent_muse" && !HookServer.museHooksInstalled() { return String(localized: "Hooks not installed") }
- if def.id == "agent_opencode" && !HookServer.openCodePluginInstalled() { return String(localized: "Plugin not installed") }
- if def.id == "agent_amp" && !HookServer.ampPluginInstalled() { return String(localized: "Plugin not installed") }
+ if !HookServer.hooksInstalled(for: def.id) { return String(localized: "Hooks not installed") }
if def.id == SpotifyController.pillId && !SpotifyController.shared.isInstalled { return String(localized: "Not installed") }
#endif
if def.category == .ai {
diff --git a/NotchBuddy/Sources/App/Voice/IntentParser.swift b/NotchBuddy/Sources/App/Voice/IntentParser.swift
index 74039146..c64122aa 100644
--- a/NotchBuddy/Sources/App/Voice/IntentParser.swift
+++ b/NotchBuddy/Sources/App/Voice/IntentParser.swift
@@ -15,73 +15,136 @@ enum IntentParser {
let words = norm.split(separator: " ").map(String.init)
guard !words.isEmpty else { return .unknown }
+ // rawWords: same splits as normalise but no diacritics strip, no letter filter, original case
+ let rawWords0 = buildRawWords(raw)
+ // defilter both arrays in parallel: ma→la, mon→le, strip filler words
+ let (fwords, frawWords) = defilter(words, rawWords: rawWords0)
+ guard !fwords.isEmpty else { return .unknown }
+
// ── 1. Explicit music-only patterns ──────────────────────────────────
- if matchesAny(words, in: pausePrefixes) { return .musicPause }
- if matchesAny(words, in: nextPrefixes) { return .musicNext }
- if matchesAny(words, in: prevPrefixes) { return .musicPrevious }
- if matchesAny(words, in: volUpPrefixes) { return .musicVolumeUp }
- if matchesAny(words, in: volDownPrefixes) { return .musicVolumeDown }
+ if matchesAny(fwords, in: pausePrefixes) { return .musicPause }
+ if matchesAny(fwords, in: nextPrefixes) { return .musicNext }
+ if matchesAny(fwords, in: prevPrefixes) { return .musicPrevious }
+ if matchesAny(fwords, in: volUpPrefixes) { return .musicVolumeUp }
+ if matchesAny(fwords, in: volDownPrefixes) { return .musicVolumeDown }
// ── 2. Volume set: "volume à 50" / "set volume 50" ──────────────────
- if let pct = extractVolume(words) { return .musicSetVolume(pct) }
+ if let pct = extractVolume(fwords) { return .musicSetVolume(pct) }
+
+ // ── 3. Explicit music-play target: "… sur Spotify" / "… on Spotify" ─
+ if let target = extractMusicPlayTarget(fwords, pills: pills) {
+ return .musicPlay(target: target)
+ }
- // ── 3. "principale/principal" keyword → pillSetMain ──────────────────
+ // ── 4. "principale/principal" keyword → pillSetMain ──────────────────
// "passe la pilule principale sur Cursor"
- if words.contains("principale") || words.contains("principal") {
- if let surIdx = words.firstIndex(of: "sur"), surIdx + 1 < words.count {
- let entity = words[(surIdx+1)...].joined(separator: " ")
+ if fwords.contains("principale") || fwords.contains("principal") {
+ if let surIdx = fwords.firstIndex(of: "sur"), surIdx + 1 < fwords.count {
+ let entity = fwords[(surIdx+1)...].joined(separator: " ")
let clean = stripArticles(entity)
if !clean.isEmpty,
let id = EntityResolver.resolve(clean, from: pills, category: .workspace) {
return .pillSetMain(id: id)
}
}
+ // "change la pilule principale pour Codex" / "pilule principale c est X"
+ for sep in ["pour", "c est", "est"] {
+ let sepWords = sep.split(separator: " ").map(String.init)
+ if let sepStart = indexOfSequence(sepWords, in: fwords) {
+ let entity = fwords[(sepStart + sepWords.count)...].joined(separator: " ")
+ let clean = stripArticles(entity)
+ if !clean.isEmpty,
+ let id = EntityResolver.resolve(clean, from: pills, category: .workspace) {
+ return .pillSetMain(id: id)
+ }
+ }
+ }
}
- // "mets Cursor en principal" — entity BEFORE "en principal[e]"
- if let enIdx = words.indices.dropLast().first(where: {
- words[$0] == "en" && (words[$0+1] == "principal" || words[$0+1] == "principale")
+ // "mets Cursor en principal[e]"
+ if let enIdx = fwords.indices.dropLast().first(where: {
+ fwords[$0] == "en" && (fwords[$0+1] == "principal" || fwords[$0+1] == "principale")
}), enIdx > 0 {
- let entity = words[1..<enIdx].joined(separator: " ") // skip leading verb
+ let entity = fwords[1..<enIdx].joined(separator: " ")
let clean = stripArticles(entity)
if !clean.isEmpty,
let id = EntityResolver.resolve(clean, from: pills, category: .workspace) {
return .pillSetMain(id: id)
}
}
+ // "Cursor comme pilule principale"
+ if fwords.contains("comme") && (fwords.contains("principale") || fwords.contains("principal")) {
+ if let comIdx = fwords.firstIndex(of: "comme"), comIdx > 0 {
+ let entity = fwords[0..<comIdx].joined(separator: " ")
+ let clean = stripArticles(entity)
+ if !clean.isEmpty,
+ let id = EntityResolver.resolve(clean, from: pills, category: .workspace) {
+ return .pillSetMain(id: id)
+ }
+ }
+ }
- // ── 4. pillReplace: "remplace n8n par github" ────────────────────────
- if let (old, new) = extractReplace(words, pills: pills) {
+ // ── 5. pillReplace: "remplace n8n par github" ────────────────────────
+ if let (old, new) = extractReplace(fwords, pills: pills) {
return .pillReplace(old: old, new: new)
}
- // ── 5. pillOnly: "garde seulement GitHub et Vercel" ──────────────────
- if let ids = extractOnly(words, pills: pills) {
+ // ── 6. pillOnly: "garde seulement GitHub et Vercel" ──────────────────
+ if let ids = extractOnly(fwords, pills: pills) {
return .pillOnly(ids)
}
- // ── 6. Playlist triggers (before generic music so "mets la playlist…" wins) ─
- if let name = extractAfter(words, triggers: playlistTriggers) {
- let clean = stripArticles(name)
- if !clean.isEmpty { return .musicPlayPlaylist(name: clean) }
+ // ── 7. Playlist triggers (before generic music so "mets la playlist…" wins) ─
+ if let match = extractAfter(fwords, rawWords: frawWords, triggers: playlistTriggers) {
+ let clean = stripArticles(match.norm)
+ let cleanRaw = stripArticlesRaw(match.raw)
+ if !clean.isEmpty {
+ return .musicPlayPlaylist(name: cleanRaw.isEmpty ? clean : cleanRaw)
+ }
}
- // ── 7. pillMain triggers (setMain-only verbs) ────────────────────────
- if let name = extractAfter(words, triggers: pillMainTriggers) {
- let clean = stripArticles(name)
+ // ── 8. pillMain triggers (setMain-only verbs) ────────────────────────
+ if let match = extractAfter(fwords, rawWords: frawWords, triggers: pillMainTriggers) {
+ let clean = stripArticles(match.norm)
if !clean.isEmpty {
+ // "pilule" keyword present but no "principale" → pillAdd (handled in step 9)
+ if !fwords.contains("principale") && !fwords.contains("principal") {
+ // Check if word "pilule" or "pill" is in the original (before trigger)
+ // The trigger itself consumed "utilise/use/passe sur" etc. so "pilule" before trigger → pillAdd
+ }
let id = EntityResolver.resolve(clean, from: pills, category: .workspace)
return id != nil ? .pillSetMain(id: id!) : .unknown
}
}
- // ── 8. Ambiguous triggers: pill-first, then music ────────────────────
- if let name = extractAfter(words, triggers: musicPillTriggers) {
- let clean = stripArticles(name)
+ // ── 9. Ambiguous triggers: pill-first, then music ────────────────────
+ if let match = extractAfter(fwords, rawWords: frawWords, triggers: musicPillTriggers) {
+ // Detect "pilule" keyword without "principale" → force pillAdd path
+ let hasPilule = fwords.contains("pilule") || fwords.contains("pill")
+ let hasMainKeyword = fwords.contains("principale") || fwords.contains("principal")
+ let clean = stripArticles(match.norm)
+ let cleanRaw = stripArticlesRaw(match.raw)
if !clean.isEmpty {
- // Music service pills → musicPlay
+ // Check for multi-pill: "X et Y"
+ let parts = splitByConjunction(clean)
+ if parts.count >= 2 {
+ let ids = parts.compactMap { part -> String? in
+ let p = stripArticles(part)
+ return p.isEmpty ? nil : EntityResolver.resolve(p, from: pills)
+ }
+ if ids.count >= 2 { return .pillAddMultiple(ids: ids) }
+ }
+ // Music service pills → musicPlay with target
if let id = EntityResolver.resolve(clean, from: pills),
musicServicePillIds.contains(id) {
- return .musicPlay
+ let target: MusicTarget = id == "integration_spotify" ? .spotify : .appleMusic
+ return .musicPlay(target: target)
+ }
+ // "pilule" without "principale" → pillAdd (skip workspace check)
+ if hasPilule && !hasMainKeyword {
+ if let id = EntityResolver.resolve(clean, from: pills) {
+ return .pillAdd(id: id)
+ }
+ return .unknown
}
// Workspace pill → pillSetMain
if let id = EntityResolver.resolve(clean, from: pills, category: .workspace) {
@@ -91,37 +154,56 @@ enum IntentParser {
if let id = EntityResolver.resolve(clean, from: pills) {
return .pillAdd(id: id)
}
- // Generic music word → musicPlay
- if musicGenericWords.contains(clean) { return .musicPlay }
- // Not a pill, not generic → artist
- return .musicPlayArtist(name: clean)
+ // Generic music word → musicPlay(nil)
+ if musicGenericWords.contains(clean) { return .musicPlay(target: nil) }
+ // Not a pill, not generic → search (title or artist) with original text
+ let name = cleanRaw.isEmpty ? clean : cleanRaw
+ return .musicPlaySearch(name: name)
}
}
- // ── 9. pillRemove triggers ────────────────────────────────────────────
- if let name = extractAfter(words, triggers: pillRemoveTriggers) {
- let clean = stripArticles(name)
+ // ── 10. pillRemove triggers ───────────────────────────────────────────
+ if let match = extractAfter(fwords, rawWords: frawWords, triggers: pillRemoveTriggers) {
+ let clean = stripArticles(match.norm)
if !clean.isEmpty {
+ // Multi-pill: "X et Y"
+ let parts = splitByConjunction(clean)
+ if parts.count >= 2 {
+ let ids = parts.compactMap { part -> String? in
+ let p = stripArticles(part)
+ return p.isEmpty ? nil : EntityResolver.resolve(p, from: pills)
+ }
+ if ids.count >= 2 { return .pillRemoveMultiple(ids: ids) }
+ }
if let id = EntityResolver.resolve(clean, from: pills) { return .pillRemove(id: id) }
return .unknown
}
}
- // ── 10. pillAdd-only triggers (affiche, show, montre, enable) ─────────
- if let name = extractAfter(words, triggers: pillAddOnlyTriggers) {
- let clean = stripArticles(name)
+ // ── 11. pillAdd-only triggers (affiche, show, montre, enable) ─────────
+ if let match = extractAfter(fwords, rawWords: frawWords, triggers: pillAddOnlyTriggers) {
+ let clean = stripArticles(match.norm)
if !clean.isEmpty {
+ // Multi-pill: "X et Y"
+ let parts = splitByConjunction(clean)
+ if parts.count >= 2 {
+ let ids = parts.compactMap { part -> String? in
+ let p = stripArticles(part)
+ return p.isEmpty ? nil : EntityResolver.resolve(p, from: pills)
+ }
+ if ids.count >= 2 { return .pillAddMultiple(ids: ids) }
+ }
if let id = EntityResolver.resolve(clean, from: pills) { return .pillAdd(id: id) }
return .unknown
}
}
- // ── 11. Generic musicPlay phrases (bare / multi-word) ─────────────────
- if matchesAny(words, in: playPrefixes) { return .musicPlay }
+ // ── 12. Generic musicPlay phrases (bare / multi-word) ─────────────────
+ if matchesAny(fwords, in: playPrefixes) { return .musicPlay(target: nil) }
// Bare single music verb
- if words.count == 1, let v = words.first, bareMusicVerbs.contains(v) {
- return .musicPlay
+ if fwords.count == 1, let v = fwords.first, bareMusicVerbs.contains(v) {
+ return .musicPlay(target: nil)
}
return .unknown
@@ -139,6 +221,38 @@ enum IntentParser {
return r.split(separator: " ").joined(separator: " ")
}
+ /// Build rawWords: original casing + accents, split on apostrophes/hyphens,
+ /// filter words that have no letter or digit (pure punctuation).
+ private static func buildRawWords(_ raw: String) -> [String] {
+ var r = raw
+ r = r.replacingOccurrences(of: "'", with: " ")
+ r = r.replacingOccurrences(of: "\u{2019}", with: " ")
+ r = r.replacingOccurrences(of: "-", with: " ")
+ return r.split(separator: " ").map(String.init).filter { w in
+ !w.isEmpty && w.contains(where: { $0.isLetter || $0.isNumber })
+ }
+ }
+
+ /// Apply filler-word removal and article normalisation to both arrays in parallel.
+ /// Removes: "un", "peu", "s", "il", "te", "plait", "moi" (filler words).
+ /// Replaces: "ma"→"la", "mon"→"le", "mes"→"les" (possessive → definite article).
+ private static func defilter(
+ _ words: [String], rawWords: [String]
+ ) -> ([String], [String]) {
+ let fillers: Set<String> = ["un", "peu", "s", "il", "te", "plait", "moi"]
+ let synonyms: [String: String] = ["ma": "la", "mon": "le", "mes": "les"]
+ var fw: [String] = []
+ var fr: [String] = []
+ for (w, r) in zip(words, rawWords) {
+ if let rep = synonyms[w] {
+ fw.append(rep); fr.append(r)
+ } else if !fillers.contains(w) {
+ fw.append(w); fr.append(r)
+ }
+ }
+ return (fw, fr)
+ }
+
// MARK: - Pattern helpers
private static func matchesAny(_ words: [String], in table: [[String]]) -> Bool {
@@ -153,41 +267,99 @@ enum IntentParser {
return false
}
- private static func extractAfter(_ words: [String], triggers: [[String]]) -> String? {
+ /// Return (normTail, rawTail) after the first matching trigger, longest first.
+ private static func extractAfter(
+ _ words: [String],
+ rawWords: [String],
+ triggers: [[String]]
+ ) -> (norm: String, raw: String)? {
let sorted = triggers.sorted { $0.count > $1.count }
for trigger in sorted {
guard trigger.count < words.count else { continue }
for i in 0...(words.count - trigger.count) {
if words[i..<(i + trigger.count)].elementsEqual(trigger) {
- let tail = words[(i + trigger.count)...].joined(separator: " ")
- if !tail.isEmpty { return tail }
+ let norm = words[(i + trigger.count)...].joined(separator: " ")
+ let raw = i + trigger.count < rawWords.count
+ ? rawWords[(i + trigger.count)...].joined(separator: " ")
+ : ""
+ if !norm.isEmpty { return (norm, raw) }
}
}
}
return nil
}
+ /// First index where `seq` appears as a contiguous subsequence in `words`.
+ private static func indexOfSequence(_ seq: [String], in words: [String]) -> Int? {
+ guard !seq.isEmpty, seq.count <= words.count else { return nil }
+ for i in 0...(words.count - seq.count) {
+ if words[i..<(i + seq.count)].elementsEqual(seq) { return i }
+ }
+ return nil
+ }
+
private static func stripArticles(_ name: String) -> String {
let articles: Set<String> = ["du", "de", "la", "le", "les", "des", "l",
- "some", "the", "a", "an", "pilule", "pill"]
+ "some", "the", "a", "an", "pilule", "pill",
+ "ma", "mon", "mes"]
var ws = name.split(separator: " ").map(String.init)
while let first = ws.first, articles.contains(first) { ws.removeFirst() }
return ws.joined(separator: " ")
}
+ /// stripArticles applied to a raw (original-casing) string by comparing lowercased.
+ private static func stripArticlesRaw(_ name: String) -> String {
+ let articles: Set<String> = ["du", "de", "la", "le", "les", "des", "l",
+ "some", "the", "a", "an", "pilule", "pill",
+ "ma", "mon", "mes"]
+ var ws = name.split(separator: " ").map(String.init)
+ while let first = ws.first, articles.contains(first.lowercased()) { ws.removeFirst() }
+ return ws.joined(separator: " ")
+ }
+
+ /// Split entity string by "et"/"and" conjunctions.
+ private static func splitByConjunction(_ name: String) -> [String] {
+ let words = name.split(separator: " ").map(String.init)
+ var parts: [[String]] = []
+ var cur: [String] = []
+ for w in words {
+ if w == "et" || w == "and" {
+ if !cur.isEmpty { parts.append(cur); cur = [] }
+ } else { cur.append(w) }
+ }
+ if !cur.isEmpty { parts.append(cur) }
+ return parts.map { $0.joined(separator: " ") }
+ }
+
// MARK: - Volume extraction
private static func extractVolume(_ words: [String]) -> Int? {
guard words.contains("volume"),
let numStr = words.last(where: { Int($0) != nil }),
let pct = Int(numStr), pct >= 0, pct <= 100 else { return nil }
- // Ensure "volume" appears before the number
guard let volIdx = words.firstIndex(of: "volume"),
let numIdx = words.indices.last(where: { Int(words[$0]) != nil }),
volIdx < numIdx else { return nil }
return pct
}
+ // MARK: - Music target extraction: "… sur Spotify" / "… on Spotify"
+
+ private static func extractMusicPlayTarget(
+ _ words: [String], pills: [PillDefinition]
+ ) -> MusicTarget? {
+ for preposition in ["sur", "on"] {
+ guard let idx = words.lastIndex(of: preposition), idx + 1 < words.count else { continue }
+ let afterWords = Array(words[(idx+1)...])
+ let entity = afterWords.joined(separator: " ")
+ if let id = EntityResolver.resolve(entity, from: pills) {
+ if id == "integration_spotify" { return .spotify }
+ if id == "integration_music" { return .appleMusic }
+ }
+ }
+ return nil
+ }
+
// MARK: - pillReplace extraction
private static func extractReplace(_ words: [String], pills: [PillDefinition]) -> (String, String)? {
@@ -195,7 +367,8 @@ enum IntentParser {
let separators = ["par", "for", "contre", "with", "by"]
for start in startTriggers {
guard contains(words, sequence: start) else { continue }
- let rest = Array(words[start.count...])
+ guard let startIdx = indexOfSequence(start, in: words) else { continue }
+ let rest = Array(words[(startIdx + start.count)...])
for sep in separators {
guard let sepIdx = rest.firstIndex(of: sep), sepIdx > 0, sepIdx < rest.count - 1 else { continue }
let e1 = stripArticles(rest[..<sepIdx].joined(separator: " "))
@@ -238,20 +411,26 @@ enum IntentParser {
// MARK: - Keyword tables
private static let pausePrefixes: [[String]] = [
- ["pause"], ["stop"], ["stoppe"],
+ ["pause"], ["stop"], ["stoppe"], ["coupe"],
["mets", "en", "pause"], ["met", "en", "pause"],
["arrete", "la", "musique"], ["arrete", "la", "chanson"],
["arrete", "la", "lecture"],
+ ["arrete"],
+ ["coupe", "la", "musique"],
]
private static let nextPrefixes: [[String]] = [
["morceau", "suivant"], ["chanson", "suivante"], ["suivant"], ["prochain"],
["next", "track"], ["next", "song"], ["next"], ["skip"],
+ ["chanson", "d", "apres"], ["d", "apres"],
+ ["passe", "a", "la", "suivante"],
]
private static let prevPrefixes: [[String]] = [
["morceau", "precedent"], ["chanson", "precedente"], ["precedent"], ["en", "arriere"],
["previous", "track"], ["previous", "song"], ["previous"], ["back"],
+ ["remets", "la", "chanson", "d", "avant"], ["chanson", "d", "avant"],
+ ["reviens", "en", "arriere"],
]
private static let volUpPrefixes: [[String]] = [
diff --git a/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swift b/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swift
index 59c8d4ec..e976fc0d 100644
--- a/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swift
+++ b/NotchBuddy/Sources/App/Voice/LiveVoiceControls.swift
@@ -39,9 +39,9 @@ final class LiveMusicControl: MusicControlling, @unchecked Sendable {
if isMusicRunning { MusicController.shared.setVolume(pct) }
else { SpotifyController.shared.setVolume(pct) }
}
- @MainActor func playArtist(_ name: String) async -> Bool {
+ @MainActor func playSearch(_ name: String) async -> Bool {
guard isMusicRunning else { return false }
- return await MusicController.shared.playArtist(name)
+ return await MusicController.shared.playSearch(name)
}
@MainActor func playPlaylist(_ name: String) async -> Bool {
guard isMusicRunning else { return false }
@@ -50,11 +50,18 @@ final class LiveMusicControl: MusicControlling, @unchecked Sendable {
@MainActor func launchAndPlay() async {
if !isMusicRunning {
NSWorkspace.shared.open(URL(fileURLWithPath: "/System/Applications/Music.app"))
- // Give Music ~1.5 s to launch before sending play
try? await Task.sleep(nanoseconds: 1_500_000_000)
}
if isMusicRunning { MusicController.shared.play() }
}
+ @MainActor func launchSpotify() async {
+ guard !isSpotifyRunning else { music_play_spotify(); return }
+ let url = URL(fileURLWithPath: "/Applications/Spotify.app")
+ NSWorkspace.shared.open(url)
+ try? await Task.sleep(nanoseconds: 1_500_000_000)
+ if isSpotifyRunning { SpotifyController.shared.play() }
+ }
+ private func music_play_spotify() { SpotifyController.shared.play() }
}
// MARK: - LivePillControl
@@ -66,13 +73,6 @@ final class LivePillControl: PillControlling {
func activeCount() -> Int { AppState.shared.activeIntegrations.count }
func toggleIntegration(_ id: String) { AppState.shared.toggleIntegration(id) }
func setMainPill(_ id: String) { AppState.shared.setMainPill(id) }
- func hooksInstalled(for id: String) -> Bool {
- // Hooks are irrelevant for workspace pills (they auto-detect via process name)
- // For service/agent pills, check if the user has gone through hook setup
- guard let def = PillCatalog.definition(for: id) else { return true }
- if def.source == .claudeCode || def.category == .workspace { return true }
- return AppState.shared.installedHookPills.contains(id)
- }
}
// MARK: - Configuration
diff --git a/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift b/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift
index d4eac084..cb3d16cf 100644
--- a/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift
+++ b/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift
@@ -14,9 +14,10 @@ protocol MusicControlling: Sendable {
@MainActor func volumeUp()
@MainActor func volumeDown()
@MainActor func setVolume(_ pct: Int)
- @MainActor func playArtist(_ name: String) async -> Bool
+ @MainActor func playSearch(_ name: String) async -> Bool
@MainActor func playPlaylist(_ name: String) async -> Bool
@MainActor func launchAndPlay() async
+ @MainActor func launchSpotify() async
}
/// Abstraction over AppState pill management.
@@ -27,7 +28,6 @@ protocol PillControlling {
func activeCount() -> Int
func toggleIntegration(_ id: String)
func setMainPill(_ id: String)
- func hooksInstalled(for id: String) -> Bool
}
// MARK: - Null implementations (test-safe, no AppKit)
@@ -35,16 +35,17 @@ protocol PillControlling {
private final class NullMusic: MusicControlling, @unchecked Sendable {
var isMusicRunning: Bool { false }
var isSpotifyRunning: Bool { false }
- @MainActor func play() {}
- @MainActor func pause() {}
- @MainActor func nextTrack() {}
- @MainActor func previousTrack() {}
- @MainActor func volumeUp() {}
- @MainActor func volumeDown() {}
- @MainActor func setVolume(_ pct: Int) {}
- @MainActor func playArtist(_ n: String) async -> Bool { false }
+ @MainActor func play() {}
+ @MainActor func pause() {}
+ @MainActor func nextTrack() {}
+ @MainActor func previousTrack() {}
+ @MainActor func volumeUp() {}
+ @MainActor func volumeDown() {}
+ @MainActor func setVolume(_ pct: Int) {}
+ @MainActor func playSearch(_ n: String) async -> Bool { false }
@MainActor func playPlaylist(_ n: String) async -> Bool { false }
- @MainActor func launchAndPlay() async {}
+ @MainActor func launchAndPlay() async {}
+ @MainActor func launchSpotify() async {}
}
@MainActor
@@ -54,7 +55,6 @@ private final class NullPills: PillControlling {
func activeCount() -> Int { 0 }
func toggleIntegration(_ id: String) {}
func setMainPill(_ id: String) {}
- func hooksInstalled(for id: String) -> Bool { true }
}
// MARK: - VoiceActionRunner
@@ -66,6 +66,9 @@ final class VoiceActionRunner {
var music: MusicControlling = NullMusic()
var pills: PillControlling = NullPills()
+ /// Pending follow-up question (4-pill limit, ambiguity). Set when outcome is .question.
+ var pendingQuestion: PendingVoiceQuestion? = nil
+
init() {}
func run(_ intent: VoiceIntent,
@@ -75,13 +78,24 @@ final class VoiceActionRunner {
// ── Music ─────────────────────────────────────────────────────────────
- case .musicPlay:
- if !music.isMusicRunning && !music.isSpotifyRunning {
+ case .musicPlay(let target):
+ switch target {
+ case .spotify:
+ if !music.isSpotifyRunning { await music.launchSpotify() }
+ else { music.play() }
+ return ok("voice.music-playing")
+ case .appleMusic:
+ if !music.isMusicRunning { await music.launchAndPlay() }
+ else { music.play() }
+ return ok("voice.music-playing")
+ case nil:
+ if music.isMusicRunning || music.isSpotifyRunning {
+ music.play()
+ return ok("voice.music-playing")
+ }
await music.launchAndPlay()
return ok("voice.music-launch")
}
- music.play()
- return ok("voice.music-playing")
case .musicPause:
guard music.isMusicRunning || music.isSpotifyRunning else {
@@ -124,28 +138,17 @@ final class VoiceActionRunner {
}
music.setVolume(pct)
let fmt = NSLocalizedString("voice.music-vol-set", comment: "")
- return .init(outcome: .success, message: String(format: fmt, pct))
+ return .init(outcome: .success, message: fmt.contains("%") ? String(format: fmt, pct) : "\(pct)%")
- case .musicPlayArtist(let name):
- // "spotify" / "apple music" entity → route to appropriate service
- let norm = IntentParser.normalise(name)
- if norm == "spotify" {
- if !music.isSpotifyRunning { await music.launchAndPlay() }
- else { music.play() }
- return ok("voice.music-playing")
- }
- if norm == "apple music" || norm == "music" {
- if !music.isMusicRunning { await music.launchAndPlay() }
- else { music.play() }
- return ok("voice.music-playing")
- }
+ case .musicPlaySearch(let name):
if !music.isMusicRunning && !music.isSpotifyRunning {
await music.launchAndPlay()
}
- let found = await music.playArtist(name)
+ let found = await music.playSearch(name)
if found { return ok("voice.music-playing") }
let fmt = NSLocalizedString("voice.music-artist-err", comment: "")
- return .init(outcome: .failure, message: String(format: fmt, name))
+ return .init(outcome: .failure,
+ message: fmt.contains("%@") ? String(format: fmt, name) : name)
case .musicPlayPlaylist(let name):
if !music.isMusicRunning && !music.isSpotifyRunning {
@@ -154,7 +157,8 @@ final class VoiceActionRunner {
let found = await music.playPlaylist(name)
if found { return ok("voice.music-playing") }
let fmt = NSLocalizedString("voice.music-artist-err", comment: "")
- return .init(outcome: .failure, message: String(format: fmt, name))
+ return .init(outcome: .failure,
+ message: fmt.contains("%@") ? String(format: fmt, name) : name)
// ── Pills ─────────────────────────────────────────────────────────────
@@ -164,19 +168,28 @@ final class VoiceActionRunner {
}
guard pills.activeCount() < 4 else {
let qFmt = NSLocalizedString("voice.ask-which-remove", comment: "")
+ pendingQuestion = PendingVoiceQuestion(kind: .removeWhich(toAdd: id), text: qFmt)
return .init(outcome: .question(text: qFmt), message: qFmt)
}
pills.toggleIntegration(id)
let name = pillName(id, from: availablePills)
let fmt = NSLocalizedString("voice.pill-added", comment: "")
let msg = fmt.contains("%@") ? String(format: fmt, name) : name
- if !pills.hooksInstalled(for: id) {
- let hFmt = NSLocalizedString("voice.pill-no-hooks", comment: "")
- let hMsg = hFmt.contains("%@") ? String(format: hFmt, name) : "\(name) — hooks non installés"
- return .init(outcome: .success, message: hMsg)
- }
return .init(outcome: .success, message: msg)
+ case .pillAddMultiple(let ids):
+ var added: [String] = []
+ for id in ids {
+ guard !pills.activeIds().contains(id), pills.activeCount() < 4 else { continue }
+ pills.toggleIntegration(id)
+ added.append(pillName(id, from: availablePills))
+ }
+ let names = added.joined(separator: ", ")
+ let fmt = NSLocalizedString("voice.pill-added", comment: "")
+ let msg = fmt.contains("%@") ? String(format: fmt, names) : names
+ return .init(outcome: added.isEmpty ? .failure : .success,
+ message: added.isEmpty ? NSLocalizedString("voice.unknown", comment: "") : msg)
+
case .pillRemove(let id):
guard pills.activeIds().contains(id) else {
return fail("voice.pill-not-active")
@@ -187,6 +200,19 @@ final class VoiceActionRunner {
let msg = fmt.contains("%@") ? String(format: fmt, name) : name
return .init(outcome: .success, message: msg)
+ case .pillRemoveMultiple(let ids):
+ var removed: [String] = []
+ for id in ids {
+ guard pills.activeIds().contains(id) else { continue }
+ pills.toggleIntegration(id)
+ removed.append(pillName(id, from: availablePills))
+ }
+ let names = removed.joined(separator: ", ")
+ let fmt = NSLocalizedString("voice.pill-removed", comment: "")
+ let msg = fmt.contains("%@") ? String(format: fmt, names) : names
+ return .init(outcome: removed.isEmpty ? .failure : .success,
+ message: removed.isEmpty ? NSLocalizedString("voice.unknown", comment: "") : msg)
+
case .pillSetMain(let id):
pills.setMainPill(id)
let name = pillName(id, from: availablePills)
@@ -204,7 +230,6 @@ final class VoiceActionRunner {
return .init(outcome: .success, message: msg)
case .pillOnly(let ids):
- // Remove all active pills not in the list, add all in the list
let current = pills.activeIds()
for id in current { if !ids.contains(id) { pills.toggleIntegration(id) } }
for id in ids { if !pills.activeIds().contains(id) { pills.toggleIntegration(id) } }
@@ -214,15 +239,42 @@ final class VoiceActionRunner {
return .init(outcome: .success, message: msg)
case .unknown:
- if rawTranscript.isEmpty {
- return fail("voice.unknown")
- }
+ if rawTranscript.isEmpty { return fail("voice.unknown") }
let fmt = NSLocalizedString("voice.unknown-transcript", comment: "")
let msg = fmt.contains("%@") ? String(format: fmt, rawTranscript) : rawTranscript
return .init(outcome: .failure, message: msg)
}
}
+ // MARK: - Follow-up question answer
+
+ /// Handle a follow-up answer transcript after a .question outcome.
+ func handleAnswer(_ transcript: String, availablePills: [PillDefinition] = []) async -> VoiceActionResult {
+ guard let pending = pendingQuestion else { return fail("voice.unknown") }
+ pendingQuestion = nil
+
+ let norm = IntentParser.normalise(transcript)
+ guard let entity = EntityResolver.resolve(norm, from: availablePills) else {
+ return fail("voice.unknown")
+ }
+
+ switch pending.kind {
+ case .removeWhich(let toAdd):
+ if pills.activeIds().contains(entity) {
+ pills.toggleIntegration(entity)
+ }
+ if !pills.activeIds().contains(toAdd), pills.activeCount() < 4 {
+ pills.toggleIntegration(toAdd)
+ }
+ let removedName = pillName(entity, from: availablePills)
+ let addedName = pillName(toAdd, from: availablePills)
+ let fmt = NSLocalizedString("voice.pill-replaced", comment: "")
+ let msg = fmt.contains("%@") ? String(format: fmt, removedName, addedName)
+ : "\(removedName) → \(addedName)"
+ return .init(outcome: .success, message: msg)
+ }
+ }
+
// MARK: - Helpers
private func ok(_ key: String) -> VoiceActionResult {
diff --git a/NotchBuddy/Sources/App/Voice/VoiceEngine.swift b/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
index 107bdf24..8457201a 100644
--- a/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
+++ b/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
@@ -88,6 +88,28 @@ final class VoiceEngine: ObservableObject {
endCommand(postFinished: false)
}
+ /// Start a command-listening session directly (without wake phrase).
+ /// Used for follow-up answers to .question outcomes.
+ func startListeningDirectly() {
+ guard isEnabled, !isPaused, !isListeningForCommand else { return }
+ guard let audio = audio, let spotter = spotter, let loc = locale else { return }
+ wakeWindowWork?.cancel(); wakeWindowWork = nil
+ isListeningForCommand = true
+ commandTranscript = ""
+ lastWordCount = 0
+ audio.bypassVAD = true
+ appendAppLog("nb.log", "[Voice] direct listen start")
+ NotificationCenter.default.post(name: .voiceWoke, object: nil)
+ let preroll = audio.drainPreroll()
+ spotter.beginWindow(locale: loc, preroll: preroll)
+ resetSilenceTimer()
+ let maxItem = DispatchWorkItem { [weak self] in
+ Task { @MainActor in self?.endCommand(postFinished: true) }
+ }
+ commandMaxWork = maxItem
+ DispatchQueue.main.asyncAfter(deadline: .now() + 6.0, execute: maxItem)
+ }
+
// MARK: - Audio pipeline
private func startAudioPipeline() {
diff --git a/NotchBuddy/Sources/App/Voice/VoiceIntent.swift b/NotchBuddy/Sources/App/Voice/VoiceIntent.swift
index 1112b7e4..82e996ce 100644
--- a/NotchBuddy/Sources/App/Voice/VoiceIntent.swift
+++ b/NotchBuddy/Sources/App/Voice/VoiceIntent.swift
@@ -1,6 +1,14 @@
#if !APPSTORE
import Foundation
+// MARK: - MusicTarget
+
+/// Where to route a play command.
+enum MusicTarget: Equatable {
+ case appleMusic // force Apple Music
+ case spotify // force Spotify
+}
+
// MARK: - VoiceIntent
/// Structured intent extracted from a voice command transcript.
@@ -9,23 +17,25 @@ enum VoiceIntent: Equatable {
// ── Music ────────────────────────────────────────────────────────────────
- case musicPlay // "lance la musique" / "play"
- case musicPause // "pause" / "arrête"
- case musicNext // "morceau suivant" / "next track"
- case musicPrevious // "morceau précédent" / "previous"
- case musicPlayArtist(name: String) // "mets du Daft Punk"
- case musicPlayPlaylist(name: String) // "mets la playlist Workout"
- case musicVolumeUp // "monte le son"
- case musicVolumeDown // "baisse le son"
- case musicSetVolume(Int) // "volume à 50"
+ case musicPlay(target: MusicTarget?) // nil = whichever is playing, or Apple Music
+ case musicPause // "pause" / "arrête"
+ case musicNext // "morceau suivant" / "next track"
+ case musicPrevious // "morceau précédent" / "previous"
+ case musicPlaySearch(name: String) // "joue Get Lucky" — search track OR artist
+ case musicPlayPlaylist(name: String) // "mets la playlist Workout"
+ case musicVolumeUp // "monte le son"
+ case musicVolumeDown // "baisse le son"
+ case musicSetVolume(Int) // "volume à 50"
// ── Pills ─────────────────────────────────────────────────────────────────
- case pillAdd(id: String) // "ajoute GitHub"
- case pillRemove(id: String) // "enlève Vercel"
- case pillSetMain(id: String) // "passe sur Cursor" (workspace pills only)
- case pillReplace(old: String, new: String) // "remplace n8n par github"
- case pillOnly([String]) // "garde seulement GitHub et Vercel"
+ case pillAdd(id: String) // "ajoute GitHub"
+ case pillAddMultiple(ids: [String]) // "ajoute Vercel et Stripe"
+ case pillRemove(id: String) // "enlève Vercel"
+ case pillRemoveMultiple(ids: [String]) // "enlève Stripe et Notion"
+ case pillSetMain(id: String) // "passe sur Cursor" (workspace pills only)
+ case pillReplace(old: String, new: String) // "remplace n8n par github"
+ case pillOnly([String]) // "garde seulement GitHub et Vercel"
// ── Unknown ───────────────────────────────────────────────────────────────
@@ -45,4 +55,14 @@ struct VoiceActionResult: Equatable {
let outcome: Outcome
let message: String // e.g. "Gemini CLI ajouté" / "Pas compris"
}
+
+// MARK: - PendingVoiceQuestion
+
+struct PendingVoiceQuestion {
+ enum Kind {
+ case removeWhich(toAdd: String) // 4-pill limit: which pill to remove to add X?
+ }
+ let kind: Kind
+ let text: String
+}
#endif
diff --git a/tests/IntentParserTests.swift b/tests/IntentParserTests.swift
index fb507cff..a43fa0ab 100644
--- a/tests/IntentParserTests.swift
+++ b/tests/IntentParserTests.swift
@@ -19,19 +19,24 @@ enum IntentParserTests {
check("mets en pause", parse("mets en pause"), .musicPause)
check("arrête la musique", parse("arrête la musique"), .musicPause)
check("PAUSE", parse("PAUSE"), .musicPause)
-
- // ── Music: play (generic) ─────────────────────────────────────────────
- check("lance la musique", parse("lance la musique"), .musicPlay)
- check("reprends", parse("reprends"), .musicPlay)
- check("reprends la musique", parse("reprends la musique"), .musicPlay)
- check("play music", parse("play music"), .musicPlay)
- check("resume music", parse("resume music"), .musicPlay)
- check("play some music", parse("play some music"), .musicPlay)
- check("balance de la musique", parse("balance de la musique"), .musicPlay)
- check("mets de la musique", parse("mets de la musique"), .musicPlay)
- check("mets du son", parse("mets du son"), .musicPlay)
- check("lance Apple Music", parse("lance Apple Music", pills: pills), .musicPlay)
- check("lance Spotify", parse("lance Spotify", pills: pills), .musicPlay)
+ check("coupe la musique", parse("coupe la musique"), .musicPause)
+ check("arrête", parse("arrête"), .musicPause)
+
+ // ── Music: play (generic, nil target) ────────────────────────────────
+ check("lance la musique", parse("lance la musique"), .musicPlay(target: nil))
+ check("reprends", parse("reprends"), .musicPlay(target: nil))
+ check("reprends la musique", parse("reprends la musique"), .musicPlay(target: nil))
+ check("play music", parse("play music"), .musicPlay(target: nil))
+ check("resume music", parse("resume music"), .musicPlay(target: nil))
+ check("play some music", parse("play some music"), .musicPlay(target: nil))
+ check("balance de la musique", parse("balance de la musique"), .musicPlay(target: nil))
+ check("mets de la musique", parse("mets de la musique"), .musicPlay(target: nil))
+ check("mets du son", parse("mets du son"), .musicPlay(target: nil))
+
+ // ── Music: play with target ───────────────────────────────────────────
+ check("lance Apple Music", parse("lance Apple Music", pills: pills), .musicPlay(target: .appleMusic))
+ check("lance Spotify", parse("lance Spotify", pills: pills), .musicPlay(target: .spotify))
+ check("mets de la musique sur Spotify", parse("mets de la musique sur Spotify", pills: pills), .musicPlay(target: .spotify))
// ── Music: next/prev ──────────────────────────────────────────────────
check("suivant", parse("suivant"), .musicNext)
@@ -41,11 +46,15 @@ enum IntentParserTests {
check("next track", parse("next track"), .musicNext)
check("skip", parse("skip"), .musicNext)
check("next song", parse("next song"), .musicNext)
+ check("chanson d'après", parse("chanson d'après"), .musicNext)
+ check("passe à la suivante", parse("passe à la suivante"), .musicNext)
check("précédent", parse("précédent"), .musicPrevious)
check("morceau précédent", parse("morceau précédent"), .musicPrevious)
check("previous", parse("previous"), .musicPrevious)
check("previous track", parse("previous track"), .musicPrevious)
check("back", parse("back"), .musicPrevious)
+ check("remets la chanson d'avant", parse("remets la chanson d'avant"), .musicPrevious)
+ check("reviens en arrière", parse("reviens en arrière"), .musicPrevious)
// ── Music: volume ─────────────────────────────────────────────────────
check("monte le son", parse("monte le son"), .musicVolumeUp)
@@ -53,13 +62,14 @@ enum IntentParserTests {
check("plus fort", parse("plus fort"), .musicVolumeUp)
check("volume up", parse("volume up"), .musicVolumeUp)
check("louder", parse("louder"), .musicVolumeUp)
+ check("monte un peu le volume", parse("monte un peu le volume"), .musicVolumeUp)
check("baisse le son", parse("baisse le son"), .musicVolumeDown)
check("baisse le volume", parse("baisse le volume"), .musicVolumeDown)
check("moins fort", parse("moins fort"), .musicVolumeDown)
check("volume down", parse("volume down"), .musicVolumeDown)
check("quieter", parse("quieter"), .musicVolumeDown)
check("turn down", parse("turn down"), .musicVolumeDown)
- check("monte le son", parse("monte le son"), .musicVolumeUp)
+ check("baisse un peu le son", parse("baisse un peu le son"), .musicVolumeDown)
// ── Music: volume set ─────────────────────────────────────────────────
check("volume à 50", parse("volume à 50"), .musicSetVolume(50))
@@ -67,15 +77,16 @@ enum IntentParserTests {
check("volume 0", parse("volume 0"), .musicSetVolume(0))
check("volume 100", parse("volume 100"), .musicSetVolume(100))
- // ── Music: artist ─────────────────────────────────────────────────────
- checkArtist("mets du Daft Punk", parse("mets du Daft Punk", pills: pills), "daft punk")
- checkArtist("mets de la jazz", parse("mets de la jazz", pills: pills), "jazz")
- checkArtist("joue du rock", parse("joue du rock", pills: pills), "rock")
- checkArtist("joue Daft Punk", parse("joue Daft Punk", pills: pills), "daft punk")
- checkArtist("play Radiohead", parse("play Radiohead", pills: pills), "radiohead")
- checkArtist("lance du Bowie", parse("lance du Bowie", pills: pills), "bowie")
- checkArtist("mets les Beatles", parse("mets les Beatles", pills: pills), "beatles")
- checkArtist("joue de l'électro", parse("joue de l'électro", pills: pills), "electro")
+ // ── Music: search (title or artist) ───────────────────────────────────
+ checkSearch("mets du Daft Punk", parse("mets du Daft Punk", pills: pills), "daft punk")
+ checkSearch("mets de la jazz", parse("mets de la jazz", pills: pills), "jazz")
+ checkSearch("joue du rock", parse("joue du rock", pills: pills), "rock")
+ checkSearch("joue Daft Punk", parse("joue Daft Punk", pills: pills), "daft punk")
+ checkSearch("play Radiohead", parse("play Radiohead", pills: pills), "radiohead")
+ checkSearch("lance du Bowie", parse("lance du Bowie", pills: pills), "bowie")
+ checkSearch("mets les Beatles", parse("mets les Beatles", pills: pills), "beatles")
+ checkSearch("joue de l'électro", parse("joue de l'électro", pills: pills), "electro")
+ checkSearch("joue Get Lucky", parse("joue Get Lucky", pills: pills), "get lucky")
// ── Music: playlist ───────────────────────────────────────────────────
checkPlaylist("mets la playlist Workout", parse("mets la playlist Workout", pills: pills), "workout")
@@ -84,6 +95,8 @@ enum IntentParserTests {
checkPlaylist("play playlist My Favs", parse("play playlist My Favs", pills: pills), "my favs")
checkPlaylist("start playlist Chill", parse("start playlist Chill", pills: pills), "chill")
checkPlaylist("mets la playlist Focus", parse("mets la playlist Focus", pills: pills), "focus")
+ checkPlaylist("mets ma playlist Focus", parse("mets ma playlist Focus", pills: pills), "focus")
+ checkPlaylist("lance ma playlist Focus", parse("lance ma playlist Focus", pills: pills), "focus")
// ── Pill: add ─────────────────────────────────────────────────────────
check("ajoute GitHub", parse("ajoute GitHub", pills: pills), .pillAdd(id: "integration_github"))
@@ -96,6 +109,12 @@ enum IntentParserTests {
check("ajoute gemini", parse("ajoute gemini", pills: pills), .pillAdd(id: "agent_gemini"))
check("ajoute claude", parse("ajoute claude", pills: pills), .pillAdd(id: "integration_claude"))
check("mets la pilule Gemini", parse("mets la pilule Gemini", pills: pills), .pillAdd(id: "agent_gemini"))
+ check("mets la pilule Codex", parse("mets la pilule Codex", pills: pills), .pillAdd(id: "agent_codex"))
+
+ // ── Pill: add multiple ────────────────────────────────────────────────
+ check("ajoute Vercel et Stripe",
+ parse("ajoute Vercel et Stripe", pills: pills),
+ .pillAddMultiple(ids: ["integration_vercel", "integration_stripe"]))
// ── Pill: remove ──────────────────────────────────────────────────────
check("enlève GitHub", parse("enlève GitHub", pills: pills), .pillRemove(id: "integration_github"))
@@ -107,6 +126,11 @@ enum IntentParserTests {
check("hide Notion", parse("hide Notion", pills: pills), .pillRemove(id: "integration_notion"))
check("enlève stripe", parse("enlève stripe", pills: pills), .pillRemove(id: "integration_stripe"))
+ // ── Pill: remove multiple ─────────────────────────────────────────────
+ check("enlève Stripe et Notion",
+ parse("enlève Stripe et Notion", pills: pills),
+ .pillRemoveMultiple(ids: ["integration_stripe", "integration_notion"]))
+
// ── Pill: setMain ─────────────────────────────────────────────────────
check("passe sur Cursor", parse("passe sur Cursor", pills: pills), .pillSetMain(id: "agent_cursor"))
check("switch to Cursor", parse("switch to Cursor", pills: pills), .pillSetMain(id: "agent_cursor"))
@@ -117,6 +141,15 @@ enum IntentParserTests {
check("mets Cursor en principal",
parse("mets Cursor en principal", pills: pills),
.pillSetMain(id: "agent_cursor"))
+ check("change la pilule principale pour Codex",
+ parse("change la pilule principale pour Codex", pills: pills),
+ .pillSetMain(id: "agent_codex"))
+ check("la pilule principale c'est Cursor",
+ parse("la pilule principale c'est Cursor", pills: pills),
+ .pillSetMain(id: "agent_cursor"))
+ check("Cursor comme pilule principale",
+ parse("Cursor comme pilule principale", pills: pills),
+ .pillSetMain(id: "agent_cursor"))
// ── Pill: replace / only ──────────────────────────────────────────────
check("remplace n8n par github",
@@ -156,12 +189,12 @@ enum IntentParserTests {
}
}
- static func checkArtist(_ label: String, _ got: VoiceIntent, _ want: String) {
- if case .musicPlayArtist(let name) = got,
+ static func checkSearch(_ label: String, _ got: VoiceIntent, _ want: String) {
+ if case .musicPlaySearch(let name) = got,
IntentParser.normalise(name) == want {
print("✓ \(label)"); pass += 1
} else {
- print("✗ \(label) — got \(got), want artist '\(want)'"); fail += 1
+ print("✗ \(label) — got \(got), want search '\(want)'"); fail += 1
}
}
diff --git a/tests/VoiceActionRunnerTests.swift b/tests/VoiceActionRunnerTests.swift
index b3f69b0e..ea023ee9 100644
--- a/tests/VoiceActionRunnerTests.swift
+++ b/tests/VoiceActionRunnerTests.swift
@@ -9,7 +9,7 @@ final class MockMusic: MusicControlling, @unchecked Sendable {
var isSpotifyRunning: Bool { spotifyRunning }
var calls: [String] = []
- var artistResult = true // mock return for playArtist
+ var searchResult = true // mock return for playSearch
var playlistResult = true // mock return for playPlaylist
@MainActor func play() { calls.append("play") }
@@ -19,9 +19,10 @@ final class MockMusic: MusicControlling, @unchecked Sendable {
@MainActor func volumeUp() { calls.append("volUp") }
@MainActor func volumeDown() { calls.append("volDown") }
@MainActor func setVolume(_ p: Int) { calls.append("setVolume:\(p)") }
- @MainActor func playArtist(_ n: String) async -> Bool { calls.append("artist:\(n)"); return artistResult }
+ @MainActor func playSearch(_ n: String) async -> Bool { calls.append("search:\(n)"); return searchResult }
@MainActor func playPlaylist(_ n: String) async -> Bool { calls.append("playlist:\(n)"); return playlistResult }
@MainActor func launchAndPlay() async { calls.append("launchAndPlay") }
+ @MainActor func launchSpotify() async { calls.append("launchSpotify") }
}
@MainActor
@@ -38,7 +39,6 @@ final class MockPills: PillControlling {
if active.contains(id) { active.remove(id) } else { active.insert(id) }
}
func setMainPill(_ id: String) { calls.append("setMain:\(id)"); main = id }
- func hooksInstalled(for id: String) -> Bool { true }
}
let pills = PillFixture.available
@@ -60,15 +60,31 @@ enum VoiceActionRunnerTests {
music.musicRunning = false
music.spotifyRunning = false
music.calls = []
- let noApp = await runner.run(.musicPlay, availablePills: pills)
+ let noApp = await runner.run(.musicPlay(target: nil), availablePills: pills)
check("no music app → launch", noApp.outcome, .success)
check("no music app → launchAndPlay called", music.calls.contains("launchAndPlay"), true)
+ // ── Music: target spotify → launchSpotify ────────────────────────────
+ music.musicRunning = false
+ music.spotifyRunning = false
+ music.calls = []
+ let spotifyNoApp = await runner.run(.musicPlay(target: .spotify), availablePills: pills)
+ check("spotify no app → launch", spotifyNoApp.outcome, .success)
+ check("spotify no app → launchSpotify", music.calls.contains("launchSpotify"), true)
+
+ // ── Music: target appleMusic → launchAndPlay ─────────────────────────
+ music.musicRunning = false
+ music.spotifyRunning = false
+ music.calls = []
+ let amNoApp = await runner.run(.musicPlay(target: .appleMusic), availablePills: pills)
+ check("appleMusic no app → launch", amNoApp.outcome, .success)
+ check("appleMusic no app → launchAndPlay", music.calls.contains("launchAndPlay"), true)
+
// ── Music commands with app running ───────────────────────────────────
music.musicRunning = true
music.calls = []
- let play = await runner.run(.musicPlay, availablePills: pills)
+ let play = await runner.run(.musicPlay(target: nil), availablePills: pills)
check("play → success", play.outcome, .success)
check("play → play called", music.calls.last, "play")
music.calls = []
@@ -103,16 +119,16 @@ enum VoiceActionRunnerTests {
check("setVolume(50) → setVolume:50", music.calls.last, "setVolume:50")
music.calls = []
- let artist = await runner.run(.musicPlayArtist(name: "Daft Punk"), availablePills: pills)
- check("artist → success", artist.outcome, .success)
- check("artist → artist:Daft Punk", music.calls.last, "artist:Daft Punk")
+ let search = await runner.run(.musicPlaySearch(name: "Daft Punk"), availablePills: pills)
+ check("search → success", search.outcome, .success)
+ check("search → search:Daft Punk", music.calls.last, "search:Daft Punk")
music.calls = []
- // Artist not found → failure
- music.artistResult = false
- let artistFail = await runner.run(.musicPlayArtist(name: "XYZ"), availablePills: pills)
- check("artist not found → failure", artistFail.outcome, .failure)
- music.artistResult = true
+ // Search not found → failure
+ music.searchResult = false
+ let searchFail = await runner.run(.musicPlaySearch(name: "XYZ"), availablePills: pills)
+ check("search not found → failure", searchFail.outcome, .failure)
+ music.searchResult = true
music.calls = []
let pl = await runner.run(.musicPlayPlaylist(name: "Workout"), availablePills: pills)
@@ -138,6 +154,31 @@ enum VoiceActionRunnerTests {
let addLimit = await runner.run(.pillAdd(id: "agent_cursor"), availablePills: pills)
if case .question(_) = addLimit.outcome { print("✓ pillAdd limit → question"); pass += 1 }
else { print("✗ pillAdd limit — got \(addLimit.outcome)"); fail += 1 }
+ check("pillAdd limit sets pendingQuestion", runner.pendingQuestion != nil, true)
+
+ // ── Follow-up answer after question ──────────────────────────────────
+ // pills_ has 4 active: github, vercel, notion, resend. Pending: add agent_cursor.
+ // User says "Stripe" → resolve to integration_stripe? But stripe is not active...
+ // Let's use "GitHub" as the answer (it's active, will be removed, cursor added)
+ pills_.active = Set(["integration_github","integration_vercel","integration_notion","integration_resend"])
+ pills_.calls = []
+ // Re-set pending (it was consumed if we ran again, so re-trigger):
+ _ = await runner.run(.pillAdd(id: "agent_cursor"), availablePills: pills)
+ check("pending question set before answer", runner.pendingQuestion != nil, true)
+ pills_.calls = []
+ let answer = await runner.handleAnswer("GitHub", availablePills: pills)
+ check("question answer → success", answer.outcome, .success)
+ check("question answer → github removed", pills_.calls.contains("toggle:integration_github"), true)
+ check("question answer → cursor added", pills_.calls.contains("toggle:agent_cursor"), true)
+ check("pending question cleared after answer", runner.pendingQuestion == nil, true)
+
+ // ── Pills: add multiple ───────────────────────────────────────────────
+ pills_.active = ["integration_github"]
+ pills_.calls = []
+ let addMulti = await runner.run(.pillAddMultiple(ids: ["integration_vercel", "integration_stripe"]), availablePills: pills)
+ check("pillAddMultiple → success", addMulti.outcome, .success)
+ check("pillAddMultiple → vercel", pills_.calls.contains("toggle:integration_vercel"), true)
+ check("pillAddMultiple → stripe", pills_.calls.contains("toggle:integration_stripe"), true)
// ── Pills: remove ─────────────────────────────────────────────────────
pills_.active = ["integration_github", "integration_vercel"]
@@ -150,6 +191,14 @@ enum VoiceActionRunnerTests {
let remAbsent = await runner.run(.pillRemove(id: "integration_github"), availablePills: pills)
check("pillRemove not active → failure", remAbsent.outcome, .failure)
+ // ── Pills: remove multiple ────────────────────────────────────────────
+ pills_.active = ["integration_stripe", "integration_notion", "integration_github"]
+ pills_.calls = []
+ let remMulti = await runner.run(.pillRemoveMultiple(ids: ["integration_stripe", "integration_notion"]), availablePills: pills)
+ check("pillRemoveMultiple → success", remMulti.outcome, .success)
+ check("pillRemoveMultiple → stripe", pills_.calls.contains("toggle:integration_stripe"), true)
+ check("pillRemoveMultiple → notion", pills_.calls.contains("toggle:integration_notion"), true)
+
// ── Pills: setMain ────────────────────────────────────────────────────
pills_.main = "integration_claude"
pills_.calls = []
@@ -170,7 +219,6 @@ enum VoiceActionRunnerTests {
pills_.calls = []
let only = await runner.run(.pillOnly(["integration_github", "integration_vercel"]), availablePills: pills)
check("pillOnly → success", only.outcome, .success)
- // n8n and notion should be removed; vercel should be added
check("pillOnly → removed n8n", pills_.calls.contains("toggle:integration_n8n"), true)
check("pillOnly → removed notion", pills_.calls.contains("toggle:integration_notion"), true)
check("pillOnly → added vercel", pills_.calls.contains("toggle:integration_vercel"), true)