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: follow-up phase fix, multi-action, locale-aware messages

Louis Railledb3451ce4d61
diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swift
index 4bfe1bbe..e347b0b5 100644
--- a/NotchBuddy/Sources/App/IslandWindowController.swift
+++ b/NotchBuddy/Sources/App/IslandWindowController.swift
@@ -1310,17 +1310,45 @@ extension IslandWindowController {
@MainActor
func handleVoiceCommand(_ transcript: String) async {
let pills = PillCatalog.available
+ let runner = VoiceActionRunner.shared
+
+ // Propagate recognition locale so responses are in the spoken language.
+ runner.commandLocale = VoiceEngine.shared.speechLocale
// ── Follow-up answer to a pending question ────────────────────────────────
- if VoiceActionRunner.shared.pendingQuestion != nil {
- let result = await VoiceActionRunner.shared.handleAnswer(transcript, availablePills: pills)
+ if runner.pendingQuestion != nil {
+ let result = await runner.handleAnswer(transcript, availablePills: pills)
showVoiceResult(result, emote: result.outcome == .success ? BotEmote.happy : nil)
return
}
- // ── Normal command ────────────────────────────────────────────────────────
+ // ── Multi-action: "mets Gemini et enlève GitHub" ──────────────────────────
+ if let intents = IntentParser.parseMultiAction(transcript, pills: pills), intents.count >= 2 {
+ var parts: [String] = []
+ var anyFailure = false
+ for intent in intents {
+ let r = await runner.run(intent, availablePills: pills, rawTranscript: transcript)
+ parts.append(r.message)
+ if case .failure = r.outcome { anyFailure = true }
+ // .question in multi-action: treat as failure (no re-listen in combined flow).
+ if case .question = r.outcome { anyFailure = true }
+ }
+ let combined = VoiceActionResult(
+ outcome: anyFailure ? .failure : .success,
+ message: parts.joined(separator: " · ")
+ )
+ if anyFailure {
+ NotificationCenter.default.post(name: .botDizzy, object: nil)
+ } else {
+ NotificationCenter.default.post(name: .triggerEmote, object: BotEmote.happy)
+ }
+ showVoiceResult(combined)
+ return
+ }
+
+ // ── Single command ────────────────────────────────────────────────────────
let intent = IntentParser.parse(transcript, pills: pills)
- let result = await VoiceActionRunner.shared.run(intent, availablePills: pills, rawTranscript: transcript)
+ let result = await runner.run(intent, availablePills: pills, rawTranscript: transcript)
// Mochi reaction
switch result.outcome {
@@ -1337,15 +1365,16 @@ extension IslandWindowController {
expand(to: .voiceResult)
if case .question = result.outcome {
- // Re-open listening immediately (without wake phrase) so Mochi listens for the answer
+ // Re-open listening in command phase (skip wake gate) so the answer goes straight
+ // to the command pipeline. Give 5 s initial silence — user needs to read the question.
voiceResultWork?.cancel()
voiceResultWork = nil
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) { [weak self] in
guard self != nil else { return }
- VoiceEngine.shared.startListeningDirectly()
+ VoiceEngine.shared.startListeningDirectly(firstWordTimeout: 5.0)
}
} else {
- scheduleVoiceDismiss(delay: result.outcome == .success ? 2.0 : 2.0)
+ scheduleVoiceDismiss(delay: 2.0)
}
}
diff --git a/NotchBuddy/Sources/App/Voice/IntentParser.swift b/NotchBuddy/Sources/App/Voice/IntentParser.swift
index 6445f962..d25a6105 100644
--- a/NotchBuddy/Sources/App/Voice/IntentParser.swift
+++ b/NotchBuddy/Sources/App/Voice/IntentParser.swift
@@ -225,6 +225,37 @@ enum IntentParser {
return .unknown
}
+ // MARK: - Multi-action splitting
+
+ /// Try to parse `raw` as two or more sequential intents separated by "et/puis/ensuite/and/then".
+ /// Returns nil if fewer than 2 valid (non-.unknown) intents can be extracted — the caller
+ /// should fall back to single-intent `parse()` in that case.
+ ///
+ /// Safe against single-intent uses of conjunctions: if any part produces `.unknown`,
+ /// the whole call returns nil (e.g. "mets Gemini et Cursor" splits to ["mets Gemini", "Cursor"];
+ /// "Cursor" alone is unknown → falls back to the single-intent parser which returns
+ /// `.pillAddMultiple`).
+ static func parseMultiAction(_ raw: String, pills: [PillDefinition] = []) -> [VoiceIntent]? {
+ let conjunctions: Set<String> = ["et", "puis", "ensuite", "and", "then"]
+ let normWords = normalise(raw).split(separator: " ").map(String.init)
+
+ // Split normalised word array on conjunctions.
+ var normParts: [[String]] = []
+ var cur: [String] = []
+ for w in normWords {
+ if conjunctions.contains(w) {
+ if !cur.isEmpty { normParts.append(cur); cur = [] }
+ } else { cur.append(w) }
+ }
+ if !cur.isEmpty { normParts.append(cur) }
+ guard normParts.count >= 2 else { return nil }
+
+ // Each part must produce a non-.unknown intent.
+ let intents = normParts.map { parse($0.joined(separator: " "), pills: pills) }
+ let allValid = intents.allSatisfy { if case .unknown = $0 { return false }; return true }
+ return allValid ? intents : nil
+ }
+
// MARK: - Normalisation
static func normalise(_ s: String) -> String {
@@ -255,7 +286,10 @@ enum IntentParser {
private static func defilter(
_ words: [String], rawWords: [String]
) -> ([String], [String]) {
- let fillers: Set<String> = ["un", "peu", "s", "il", "te", "plait", "moi"]
+ // "truc", "chose", "machin", "bidule" = placeholder words used before an entity name
+ // e.g. "mets le truc Gemini" → "mets Gemini"
+ let fillers: Set<String> = ["un", "peu", "s", "il", "te", "plait", "moi",
+ "truc", "chose", "machin", "bidule"]
let synonyms: [String: String] = ["ma": "la", "mon": "le", "mes": "les"]
var fw: [String] = []
var fr: [String] = []
diff --git a/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift b/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift
index 174bc27d..606ffa9d 100644
--- a/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift
+++ b/NotchBuddy/Sources/App/Voice/VoiceActionRunner.swift
@@ -73,6 +73,10 @@ final class VoiceActionRunner {
/// VoiceEngine reads this flag in endCommand to skip music volume restoration.
var volumeCommandExecuted = false
+ /// Locale of the current recognition session — set by IslandWindowController before calling
+ /// run() or handleAnswer(). Used to produce responses in the spoken language rather than the UI language.
+ var commandLocale: Locale? = nil
+
init() {}
func run(_ intent: VoiceIntent,
@@ -144,7 +148,7 @@ final class VoiceActionRunner {
}
volumeCommandExecuted = true
music.setVolume(pct)
- let fmt = NSLocalizedString("voice.music-vol-set", comment: "")
+ let fmt = Self.localizedString("voice.music-vol-set", locale: commandLocale)
return .init(outcome: .success, message: fmt.contains("%") ? String(format: fmt, pct) : "\(pct)%")
case .musicPlaySearch(let name):
@@ -153,7 +157,7 @@ final class VoiceActionRunner {
}
let found = await music.playSearch(name)
if found { return ok("voice.music-playing") }
- let fmt = NSLocalizedString("voice.music-artist-err", comment: "")
+ let fmt = Self.localizedString("voice.music-artist-err", locale: commandLocale)
return .init(outcome: .failure,
message: fmt.contains("%@") ? String(format: fmt, name) : name)
@@ -163,7 +167,7 @@ final class VoiceActionRunner {
}
let found = await music.playPlaylist(name)
if found { return ok("voice.music-playing") }
- let fmt = NSLocalizedString("voice.music-artist-err", comment: "")
+ let fmt = Self.localizedString("voice.music-artist-err", locale: commandLocale)
return .init(outcome: .failure,
message: fmt.contains("%@") ? String(format: fmt, name) : name)
@@ -174,13 +178,13 @@ final class VoiceActionRunner {
return ok("voice.pill-already-active")
}
guard pills.activeCount() < 4 else {
- let qFmt = NSLocalizedString("voice.ask-which-remove", comment: "")
+ let qFmt = Self.localizedString("voice.ask-which-remove", locale: commandLocale)
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 fmt = Self.localizedString("voice.pill-added", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, name) : name
return .init(outcome: .success, message: msg)
@@ -192,10 +196,10 @@ final class VoiceActionRunner {
added.append(pillName(id, from: availablePills))
}
let names = added.joined(separator: ", ")
- let fmt = NSLocalizedString("voice.pill-added", comment: "")
+ let fmt = Self.localizedString("voice.pill-added", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, names) : names
return .init(outcome: added.isEmpty ? .failure : .success,
- message: added.isEmpty ? NSLocalizedString("voice.unknown", comment: "") : msg)
+ message: added.isEmpty ? Self.localizedString("voice.unknown", locale: commandLocale) : msg)
case .pillRemove(let id):
guard pills.activeIds().contains(id) else {
@@ -203,7 +207,7 @@ final class VoiceActionRunner {
}
pills.toggleIntegration(id)
let name = pillName(id, from: availablePills)
- let fmt = NSLocalizedString("voice.pill-removed", comment: "")
+ let fmt = Self.localizedString("voice.pill-removed", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, name) : name
return .init(outcome: .success, message: msg)
@@ -215,15 +219,15 @@ final class VoiceActionRunner {
removed.append(pillName(id, from: availablePills))
}
let names = removed.joined(separator: ", ")
- let fmt = NSLocalizedString("voice.pill-removed", comment: "")
+ let fmt = Self.localizedString("voice.pill-removed", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, names) : names
return .init(outcome: removed.isEmpty ? .failure : .success,
- message: removed.isEmpty ? NSLocalizedString("voice.unknown", comment: "") : msg)
+ message: removed.isEmpty ? Self.localizedString("voice.unknown", locale: commandLocale) : msg)
case .pillSetMain(let id):
pills.setMainPill(id)
let name = pillName(id, from: availablePills)
- let fmt = NSLocalizedString("voice.pill-main", comment: "")
+ let fmt = Self.localizedString("voice.pill-main", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, name) : name
return .init(outcome: .success, message: msg)
@@ -232,7 +236,7 @@ final class VoiceActionRunner {
if !pills.activeIds().contains(newId) { pills.toggleIntegration(newId) }
let n1 = pillName(oldId, from: availablePills)
let n2 = pillName(newId, from: availablePills)
- let fmt = NSLocalizedString("voice.pill-replaced", comment: "")
+ let fmt = Self.localizedString("voice.pill-replaced", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, n1, n2) : "\(n1) → \(n2)"
return .init(outcome: .success, message: msg)
@@ -241,13 +245,13 @@ final class VoiceActionRunner {
for id in current { if !ids.contains(id) { pills.toggleIntegration(id) } }
for id in ids { if !pills.activeIds().contains(id) { pills.toggleIntegration(id) } }
let names = ids.map { pillName($0, from: availablePills) }.joined(separator: ", ")
- let fmt = NSLocalizedString("voice.pill-only", comment: "")
+ let fmt = Self.localizedString("voice.pill-only", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, names) : names
return .init(outcome: .success, message: msg)
case .unknown:
if rawTranscript.isEmpty { return fail("voice.unknown") }
- let fmt = NSLocalizedString("voice.unknown-transcript", comment: "")
+ let fmt = Self.localizedString("voice.unknown-transcript", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, rawTranscript) : rawTranscript
return .init(outcome: .failure, message: msg)
}
@@ -279,7 +283,7 @@ final class VoiceActionRunner {
}
let removedName = pillName(entity, from: availablePills)
let addedName = pillName(toAdd, from: availablePills)
- let fmt = NSLocalizedString("voice.pill-replaced", comment: "")
+ let fmt = Self.localizedString("voice.pill-replaced", locale: commandLocale)
let msg = fmt.contains("%@") ? String(format: fmt, removedName, addedName)
: "\(removedName) → \(addedName)"
return .init(outcome: .success, message: msg)
@@ -289,15 +293,33 @@ final class VoiceActionRunner {
// MARK: - Helpers
private func ok(_ key: String) -> VoiceActionResult {
- .init(outcome: .success, message: NSLocalizedString(key, comment: ""))
+ .init(outcome: .success, message: Self.localizedString(key, locale: commandLocale))
}
private func fail(_ key: String) -> VoiceActionResult {
- .init(outcome: .failure, message: NSLocalizedString(key, comment: ""))
+ .init(outcome: .failure, message: Self.localizedString(key, locale: commandLocale))
}
private func pillName(_ id: String, from available: [PillDefinition]) -> String {
available.first(where: { $0.id == id })?.name ?? id
}
+
+ /// Look up `key` in the lproj bundle matching `locale`, falling back to NSLocalizedString.
+ static func localizedString(_ key: String, locale: Locale?) -> String {
+ guard let locale else { return NSLocalizedString(key, comment: "") }
+ // Try locale.identifier ("fr-FR" → "fr_FR"), hyphenated form, then base language code.
+ let langCode = locale.language.languageCode?.identifier ?? ""
+ let candidates = [locale.identifier,
+ locale.identifier.replacingOccurrences(of: "_", with: "-"),
+ langCode].filter { !$0.isEmpty }
+ for code in candidates {
+ if let path = Bundle.main.path(forResource: code, ofType: "lproj"),
+ let bundle = Bundle(path: path) {
+ let s = bundle.localizedString(forKey: key, value: nil, table: "Localizable")
+ if s != key { return s }
+ }
+ }
+ return NSLocalizedString(key, comment: "")
+ }
}
#endif
diff --git a/NotchBuddy/Sources/App/Voice/VoiceEngine.swift b/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
index 1f59d122..8a4fca78 100644
--- a/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
+++ b/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
@@ -82,6 +82,11 @@ final class VoiceEngine: ObservableObject {
private var minuteWindowStart: Date = .distantPast
private static let initialTimeout: TimeInterval = 3.0
+ private static let directListenInitialTimeout: TimeInterval = 5.0 // follow-up: user reads question first
+ private static let directListenMaxTime: TimeInterval = 20.0
+
+ /// Initial silence timeout for the current direct-listen session.
+ private var directInitialTimeout: TimeInterval = 3.0
private static let silenceTimeout: TimeInterval = 1.2
private static let commandMaxTime: TimeInterval = 10.0
private static let wakeWindowMax: TimeInterval = 20.0
@@ -115,27 +120,35 @@ final class VoiceEngine: ObservableObject {
func cancelListening() { endCommand(postFinished: false) }
- func startListeningDirectly() {
+ /// `firstWordTimeout`: seconds of silence allowed before the first word (default 3 s;
+ /// pass `Self.directListenInitialTimeout` = 5 s for follow-up questions so the user
+ /// has time to read the question before speaking).
+ func startListeningDirectly(firstWordTimeout: TimeInterval = 3.0) {
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
+ directInitialTimeout = firstWordTimeout
audio.bypassVAD = true
duckMusic()
- appendAppLog("nb.log", "[Voice] direct listen start")
+ appendAppLog("nb.log", "[Voice] direct listen start (firstWordTimeout: \(firstWordTimeout)s)")
NotificationCenter.default.post(name: .voiceWoke, object: "direct" as NSString)
let preroll = audio.drainPreroll()
- spotter.beginWindow(locale: loc, preroll: preroll)
+ // startInCommandPhase: skip wake-phrase gate, deliver speech directly as command.
+ spotter.beginWindow(locale: loc, preroll: preroll, startInCommandPhase: true)
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)
+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.directListenMaxTime, execute: maxItem)
}
+ /// Locale used for the current recognition session — nil if pipeline is not running.
+ var speechLocale: Locale? { locale }
+
// MARK: - Pipeline lifecycle
private func startAudioPipeline() {
@@ -487,7 +500,7 @@ final class VoiceEngine: ObservableObject {
private func resetSilenceTimer() {
silenceWork?.cancel()
- let timeout = lastWordCount > 0 ? Self.silenceTimeout : Self.initialTimeout
+ let timeout = lastWordCount > 0 ? Self.silenceTimeout : directInitialTimeout
let item = DispatchWorkItem { [weak self] in
Task { @MainActor in self?.endCommand(postFinished: true) }
}
diff --git a/NotchBuddy/Sources/App/Voice/WakeSpotter.swift b/NotchBuddy/Sources/App/Voice/WakeSpotter.swift
index e0251c3f..28acb0a9 100644
--- a/NotchBuddy/Sources/App/Voice/WakeSpotter.swift
+++ b/NotchBuddy/Sources/App/Voice/WakeSpotter.swift
@@ -53,10 +53,15 @@ final class WakeSpotter: @unchecked Sendable {
var isInCommandPhase: Bool { lock.withLock { phase == .command } }
- /// Open a wake+command recognition window.
+ /// Open a recognition window.
+ /// - `startInCommandPhase`: when `true`, skip the wake-phrase gate and start
+ /// delivering transcripts directly as command updates (used for follow-up
+ /// answers and the ⌃⌥V direct-listen shortcut).
/// Returns `true` if the underlying recognition task was successfully started.
@discardableResult
- func beginWindow(locale: Locale, preroll: [AVAudioPCMBuffer] = []) -> Bool {
+ func beginWindow(locale: Locale,
+ preroll: [AVAudioPCMBuffer] = [],
+ startInCommandPhase: Bool = false) -> Bool {
enum Refusal { case alreadyActive, unavailable }
var refusal: Refusal? = nil
var rSnap: SFSpeechRecognizer?
@@ -78,7 +83,7 @@ final class WakeSpotter: @unchecked Sendable {
recognizer = r
request = req
active = true
- phase = .wake
+ phase = startInCommandPhase ? .command : .wake
partialCount = 0
taskGen = gen.bump() // new generation for this task
rSnap = r
diff --git a/tests/IntentParserTests.swift b/tests/IntentParserTests.swift
index 7f21df17..596de50b 100644
--- a/tests/IntentParserTests.swift
+++ b/tests/IntentParserTests.swift
@@ -188,6 +188,37 @@ enum IntentParserTests {
parse("tu pourrais baisser le son"),
.musicVolumeDown)
+ // ── Filler words: "truc", "chose", "machin" ──────────────────────────
+ check("mets le truc Gemini",
+ parse("mets le truc Gemini", pills: pills),
+ .pillAdd(id: "agent_gemini"))
+ check("ajoute la chose GitHub",
+ parse("ajoute la chose GitHub", pills: pills),
+ .pillAdd(id: "integration_github"))
+ check("enlève le machin Vercel",
+ parse("enlève le machin Vercel", pills: pills),
+ .pillRemove(id: "integration_vercel"))
+ check("mets le bidule Stripe",
+ parse("mets le bidule Stripe", pills: pills),
+ .pillAdd(id: "integration_stripe"))
+
+ // ── parseMultiAction ─────────────────────────────────────────────────
+ checkMultiAction("mets le truc Gemini et enlève GitHub",
+ parseMulti("mets le truc Gemini et enlève GitHub"),
+ [.pillAdd(id: "agent_gemini"), .pillRemove(id: "integration_github")])
+ checkMultiAction("ajoute Stripe puis enlève Vercel",
+ parseMulti("ajoute Stripe puis enlève Vercel"),
+ [.pillAdd(id: "integration_stripe"), .pillRemove(id: "integration_vercel")])
+ checkMultiAction("add GitHub then remove Vercel",
+ parseMulti("add GitHub then remove Vercel"),
+ [.pillAdd(id: "integration_github"), .pillRemove(id: "integration_vercel")])
+ // Single pill with conjunction → NOT multi-action (fallback to single-intent)
+ checkNilMultiAction("mets Gemini et Cursor",
+ parseMulti("mets Gemini et Cursor"))
+ // Unknown part → not multi-action
+ checkNilMultiAction("mets Gemini et blahblah",
+ parseMulti("mets Gemini et blahblah"))
+
// Summary
let total = pass + fail
if fail == 0 { print("\n\(total)/\(total) passed.") }
@@ -198,6 +229,29 @@ enum IntentParserTests {
IntentParser.parse(s, pills: pills)
}
+ static func parseMulti(_ s: String) -> [VoiceIntent]? {
+ IntentParser.parseMultiAction(s, pills: pills)
+ }
+
+ static func checkMultiAction(_ label: String, _ got: [VoiceIntent]?, _ want: [VoiceIntent]) {
+ guard let got else {
+ print("✗ \(label) — got nil, want \(want)"); fail += 1; return
+ }
+ if got == want {
+ print("✓ \(label)"); pass += 1
+ } else {
+ print("✗ \(label) — got \(got), want \(want)"); fail += 1
+ }
+ }
+
+ static func checkNilMultiAction(_ label: String, _ got: [VoiceIntent]?) {
+ if got == nil {
+ print("✓ \(label) → nil (expected)"); pass += 1
+ } else {
+ print("✗ \(label) — expected nil, got \(got!)"); fail += 1
+ }
+ }
+
static func check(_ label: String, _ got: VoiceIntent, _ want: VoiceIntent) {
if got == want {
print("✓ \(label)"); pass += 1