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: reliability — backoff, auto-repair, idempotent endCommand, AEC

Louis Raillea1709acf77ba
diff --git a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
index dfcfbeac..c9b5452d 100644
--- a/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
+++ b/NotchBuddy/NotchBuddy.xcodeproj/project.pbxproj
@@ -85,6 +85,7 @@
4B6AC00F22EC75E90E0157D5 /* AppLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9F6D7015D6A77AA59323C0E7 /* AppLog.swift */; };
4B83070258D5AAAC8FCEB15F /* MochiOutfitDrawing.swift in Sources */ = {isa = PBXBuildFile; fileRef = E84E5D91129352E8A1D32AA4 /* MochiOutfitDrawing.swift */; };
4B99E2AD54926078AB087B43 /* SpotifyViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 914A792788D403F836BEB570 /* SpotifyViews.swift */; };
+ 4CA7948E8518229C04C6BE5A /* WakeWindowBackoff.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68C3405BCC9BF5F378094BFB /* WakeWindowBackoff.swift */; };
4D34FF10654B19B69FE1964C /* TurnSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2A1C4152EBDBD7C24CABFFD7 /* TurnSnapshot.swift */; };
4D958F2DDCE9504490FDA357 /* DiffEngine.swift in Sources */ = {isa = PBXBuildFile; fileRef = B32FB972D02162720E566674 /* DiffEngine.swift */; };
4F1E0B3C838DA3CD6F864BC0 /* CalcomPoller.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3104222B3F17BA5E8DEA5277 /* CalcomPoller.swift */; };
@@ -190,6 +191,7 @@
9EA178EA395B116336C1FA10 /* TerminalTarget+AppKit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 244A7909EEDA4BFF4C2EA9B5 /* TerminalTarget+AppKit.swift */; };
9ECEE890D4486B6E83BD5B7F /* ColorHex.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8ACB4350729C6513824D1ADF /* ColorHex.swift */; };
9F43BE6E77E371FCEB7FE8BA /* ServiceDetailRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = E6AAC67875F84A862BC2A9AF /* ServiceDetailRunner.swift */; };
+ A0ED41FB1AC8845BE1E30A66 /* WakeWindowBackoff.swift in Sources */ = {isa = PBXBuildFile; fileRef = 68C3405BCC9BF5F378094BFB /* WakeWindowBackoff.swift */; };
A7733EE60694EA3E2A86C37A /* IslandTypes.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0365DDE3C554F5E8570055F4 /* IslandTypes.swift */; };
A7EEF05A08F6B95370712089 /* error.wav in Resources */ = {isa = PBXBuildFile; fileRef = 871CA2BADC67D97C97C7009D /* error.wav */; };
A885B7E6DC43231BECE36E3D /* MochiWardrobe.swift in Sources */ = {isa = PBXBuildFile; fileRef = 79A7807ADD0963FF260D1FAD /* MochiWardrobe.swift */; };
@@ -382,6 +384,7 @@
66E6F5FC81429871B6F766A8 /* BotEngine.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BotEngine.swift; sourceTree = "<group>"; };
6762C38A8952A90F394EDFE4 /* LinkTestView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LinkTestView.swift; sourceTree = "<group>"; };
681E15F99FCF1E60C2553004 /* AppleStyle.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppleStyle.swift; sourceTree = "<group>"; };
+ 68C3405BCC9BF5F378094BFB /* WakeWindowBackoff.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WakeWindowBackoff.swift; sourceTree = "<group>"; };
6A9E6EB7C8468A8339CF6A5C /* SpotifyController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SpotifyController.swift; sourceTree = "<group>"; };
6C6993B34A0FFF8E3D454ADC /* QuestionPayload.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = QuestionPayload.swift; sourceTree = "<group>"; };
6E5F9E4BB282FDE68D65FE6B /* TurnArchive.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TurnArchive.swift; sourceTree = "<group>"; };
@@ -706,6 +709,7 @@
D4543CB771E0B723783F529E /* VoiceSettings.swift */,
A12EC8F605BBC37F8223D7AA /* WakePhrase.swift */,
BC1DE3225F5239394398E6B6 /* WakeSpotter.swift */,
+ 68C3405BCC9BF5F378094BFB /* WakeWindowBackoff.swift */,
);
path = Voice;
sourceTree = "<group>";
@@ -985,6 +989,7 @@
502F2B0D607C511DD3B836B3 /* VoiceSettings.swift in Sources */,
C2212AA8BF5834B62308235B /* WakePhrase.swift in Sources */,
63B87D9E49F228ADCEC4C293 /* WakeSpotter.swift in Sources */,
+ 4CA7948E8518229C04C6BE5A /* WakeWindowBackoff.swift in Sources */,
01B96F947DF2BDC352E8526D /* WeeklyRecapView.swift in Sources */,
2875610F701376BD65573386 /* WindowContextCapture.swift in Sources */,
);
@@ -1163,6 +1168,7 @@
035F9A85BF71B21F9AA5E004 /* VoiceSettings.swift in Sources */,
3451DB0668FAEEF09503D808 /* WakePhrase.swift in Sources */,
B5206E9D10AD77C0C24463AB /* WakeSpotter.swift in Sources */,
+ A0ED41FB1AC8845BE1E30A66 /* WakeWindowBackoff.swift in Sources */,
FB58020A389126865363C342 /* WeeklyRecapView.swift in Sources */,
2CC2E3B688B15BBEB3AE3BCE /* WindowContextCapture.swift in Sources */,
);
diff --git a/NotchBuddy/Sources/App/IslandWindowController.swift b/NotchBuddy/Sources/App/IslandWindowController.swift
index 5cc25158..8d8b83f2 100644
--- a/NotchBuddy/Sources/App/IslandWindowController.swift
+++ b/NotchBuddy/Sources/App/IslandWindowController.swift
@@ -298,32 +298,34 @@ final class IslandWindowController: NSWindowController {
NotificationCenter.default.addObserver(
forName: .voiceWoke, object: nil, queue: .main
) { [weak self] note in
- // Genuine wake phrase (not programmatic re-listen) → clear any pending question
let isDirect = (note.object as? String) == "direct"
- if !isDirect { VoiceActionRunner.shared.pendingQuestion = nil }
- self?.fsm.voiceWoke()
+ Task { @MainActor [weak self] in
+ // Genuine wake phrase (not programmatic re-listen) → clear any pending question
+ if !isDirect { VoiceActionRunner.shared.pendingQuestion = nil }
+ self?.fsm.voiceWoke()
+ }
}
// Voice: command session ended — run intent, show result for 2 s, then collapse.
NotificationCenter.default.addObserver(
forName: .voiceFinished, object: nil, queue: .main
) { [weak self] note in
- guard let self else { return }
let transcript = note.object as? String ?? ""
- if transcript.isEmpty {
- if VoiceActionRunner.shared.pendingQuestion != nil {
- // Re-listen timed out with no answer → show cancellation message
- Task { @MainActor in
+ Task { @MainActor [weak self] in
+ guard let self else { return }
+ if transcript.isEmpty {
+ if VoiceActionRunner.shared.pendingQuestion != nil {
+ // Re-listen timed out with no answer → show cancellation message
let result = await VoiceActionRunner.shared.handleAnswer(
"", availablePills: PillCatalog.available)
AppState.shared.voiceResult = result
self.expand(to: .voiceResult)
self.scheduleVoiceDismiss(delay: 1.5)
+ } else {
+ self.fsm.voiceFinished()
}
} else {
- self.fsm.voiceFinished()
+ await self.handleVoiceCommand(transcript)
}
- } else {
- Task { @MainActor in await self.handleVoiceCommand(transcript) }
}
}
#endif
diff --git a/NotchBuddy/Sources/App/Voice/VoiceAudio.swift b/NotchBuddy/Sources/App/Voice/VoiceAudio.swift
index 850a637b..d00d5dce 100644
--- a/NotchBuddy/Sources/App/Voice/VoiceAudio.swift
+++ b/NotchBuddy/Sources/App/Voice/VoiceAudio.swift
@@ -2,73 +2,102 @@
import AVFoundation
// MARK: - VoiceAudio
-
-/// Wraps AVAudioEngine to deliver a low-level audio tap for voice detection.
-///
-/// Thread model:
-/// - `start()` / `stop()` / `resetVAD()` called on the main thread.
-/// - `onVoiceStart`, `onVoiceEnd`, `onMicLevel` dispatched to the main thread.
-/// - `onBuffer` called **on the audio tap thread** — its closure must be thread-safe.
-///
-/// VAD modes:
-/// - Normal (wake): EnergyVAD drives `onVoiceStart`/`onVoiceEnd`.
-/// - Bypass (`bypassVAD = true`): every buffer is delivered via `onBuffer` regardless of
-/// silence; `onMicLevel` fires at ~20 Hz with a smoothed level.
+//
+// Wraps AVAudioEngine to deliver a low-level audio tap for voice detection.
+//
+// Thread model:
+// - `start()` / `stop()` / `resetVAD()` called on the main thread.
+// - `onVoiceStart`, `onVoiceEnd`, `onMicLevel`, `onConfigChange` dispatched to the main thread.
+// - `onBuffer` called on the audio tap thread — its closure must be thread-safe.
+//
+// VAD modes:
+// - Normal (wake): EnergyVAD drives `onVoiceStart`/`onVoiceEnd`.
+// - Bypass (`bypassVAD = true`): every buffer is delivered via `onBuffer` regardless of
+// silence; `onMicLevel` fires at ~20 Hz with a smoothed level.
+//
+// AEC: `setVoiceProcessingEnabled(true)` is applied on macOS 14+ to remove
+// acoustic echo (Mac speakers → mic feedback). Does NOT duck other apps' audio.
final class VoiceAudio: @unchecked Sendable {
- private let engine = AVAudioEngine()
- private var tapInstalled = false
+ private let engine = AVAudioEngine()
+ private var tapInstalled = false
+ private var configObserver: NSObjectProtocol? = nil
// VAD — read/written only on the audio tap thread.
private var vad = EnergyVAD()
// Smoothed mic level during bypass mode — audio tap thread.
- private var smoothedLevel: Double = 0
+ private var smoothedLevel: Double = 0
private var levelFrameCount = 0
// Pre-roll circular buffer (~500 ms).
// Read on main (via `drainPreroll()`), written on audio tap thread.
- private let prerollLock = NSLock()
+ private let prerollLock = NSLock()
private var prerollBuffers: [AVAudioPCMBuffer] = []
private static let prerollCapacity = 22 // ~500 ms at 43 Hz
+ /// Last time a buffer was processed in the tap (audio tap thread).
+ /// Read on main for stall detection — nonisolated for cross-thread access.
+ nonisolated(unsafe) private(set) var lastBufferTime: Date = .distantPast
+
/// When true, every audio buffer is delivered via `onBuffer` regardless of VAD.
- /// Written on the main thread; read on the audio tap thread.
nonisolated(unsafe) var bypassVAD: Bool = false
- /// Set on the main thread after a command ends; consumed (and acted on) by the audio
- /// tap thread on its next buffer — avoids a data race on the `vad` struct.
+ /// Set on the main thread after a command ends; consumed by the audio tap thread.
nonisolated(unsafe) private var pendingVADReset: Bool = false
// MARK: Callbacks
- /// Fired on the main thread when voice activity starts (VAD rise).
- var onVoiceStart: (() -> Void)?
- /// Fired on the main thread when voice activity ends (VAD fall, only when bypassVAD is false).
- var onVoiceEnd: (() -> Void)?
- /// Fired on the **audio tap thread** with each PCM buffer.
- /// Normal mode: only during voice activity. Bypass mode: every buffer.
- var onBuffer: ((AVAudioPCMBuffer, AVAudioTime) -> Void)?
- /// Fired on the main thread at ~20 Hz during bypass mode with smoothed mic level (0…1 approx).
- /// Nil or 0 when not in bypass mode.
- var onMicLevel: ((Double) -> Void)?
+ var onVoiceStart: (() -> Void)?
+ var onVoiceEnd: (() -> Void)?
+ /// Called on the audio tap thread.
+ var onBuffer: ((AVAudioPCMBuffer, AVAudioTime) -> Void)?
+ var onMicLevel: ((Double) -> Void)?
+ /// Fired on the main thread when AVAudioEngine reports a configuration change
+ /// (headphone connect/disconnect, sample-rate change, etc.).
+ var onConfigChange: (() -> Void)?
// MARK: - Control
func start() throws {
guard !tapInstalled else { return }
let input = engine.inputNode
- let fmt = input.outputFormat(forBus: 0)
+
+ // AEC: remove echo of Mac speakers from the mic signal (macOS 14+).
+ // Does NOT duck other apps' audio — music stays at full volume.
+ if #available(macOS 14, *) {
+ do {
+ try input.setVoiceProcessingEnabled(true)
+ appendAppLog("nb.log", "[VoiceAudio] AEC enabled")
+ } catch {
+ appendAppLog("nb.log", "[VoiceAudio] AEC unavailable: \(error.localizedDescription)")
+ }
+ }
+
+ let fmt = input.outputFormat(forBus: 0)
input.installTap(onBus: 0, bufferSize: 1024, format: fmt) { [weak self] buf, time in
self?.processTap(buf, time: time)
}
tapInstalled = true
+
+ // Rebuild on device change (headphones, sample-rate switch…).
+ configObserver = NotificationCenter.default.addObserver(
+ forName: .AVAudioEngineConfigurationChange,
+ object: engine, queue: .main
+ ) { [weak self] _ in
+ self?.onConfigChange?()
+ }
+
engine.prepare()
try engine.start()
}
func stop() {
guard tapInstalled else { return }
+ if let obs = configObserver {
+ NotificationCenter.default.removeObserver(obs)
+ configObserver = nil
+ }
engine.stop()
engine.inputNode.removeTap(onBus: 0)
tapInstalled = false
@@ -79,15 +108,8 @@ final class VoiceAudio: @unchecked Sendable {
}
}
- /// Hard-reset the VAD to inactive state; preserves the learned noise floor.
- /// Call from the main thread after a command ends so the next speech restarts cleanly.
- /// Uses a flag consumed by the audio tap thread to avoid a data race on `vad`.
- func resetVAD() {
- pendingVADReset = true
- }
+ func resetVAD() { pendingVADReset = true }
- /// Return a snapshot of the pre-roll ring buffer and clear it.
- /// Called on the main thread just before `WakeSpotter.beginWindow`.
func drainPreroll() -> [AVAudioPCMBuffer] {
prerollLock.withLock {
let snap = prerollBuffers
@@ -99,7 +121,8 @@ final class VoiceAudio: @unchecked Sendable {
// MARK: - Tap processing (audio thread)
private func processTap(_ buf: AVAudioPCMBuffer, time: AVAudioTime) {
- // Consume a pending VAD reset requested by the main thread.
+ lastBufferTime = Date()
+
if pendingVADReset {
pendingVADReset = false
vad.reset()
@@ -107,7 +130,6 @@ final class VoiceAudio: @unchecked Sendable {
levelFrameCount = 0
}
- // Always maintain the pre-roll ring buffer.
prerollLock.withLock {
if prerollBuffers.count >= Self.prerollCapacity { prerollBuffers.removeFirst() }
prerollBuffers.append(buf)
@@ -115,12 +137,11 @@ final class VoiceAudio: @unchecked Sendable {
if bypassVAD {
onBuffer?(buf, time)
- // Smoothed mic level for Mochi animation (~20 Hz).
let power = buf.meanSquarePower
smoothedLevel = smoothedLevel * 0.6 + power * 0.4
levelFrameCount += 1
if levelFrameCount % 2 == 0 {
- let level = min(1.0, smoothedLevel * 2000) // rough normalisation to 0…1
+ let level = min(1.0, smoothedLevel * 2000)
DispatchQueue.main.async { [weak self] in self?.onMicLevel?(level) }
}
return
@@ -138,9 +159,7 @@ final class VoiceAudio: @unchecked Sendable {
break
}
- if vad.isActive {
- onBuffer?(buf, time)
- }
+ if vad.isActive { onBuffer?(buf, time) }
}
}
diff --git a/NotchBuddy/Sources/App/Voice/VoiceEngine.swift b/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
index a44e3473..6c157698 100644
--- a/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
+++ b/NotchBuddy/Sources/App/Voice/VoiceEngine.swift
@@ -4,16 +4,20 @@ import AVFoundation
import Speech
// MARK: - VoiceEngine
-
-/// Coordinator for the «OK Coucou» voice feature.
-///
-/// - Uses VoiceAudio (energy VAD) and WakeSpotter (on-device recognition).
-/// - WakeSpotter handles both wake detection and command transcription in one session.
-/// - After wake: VoiceAudio.bypassVAD = true so the command receives continuous audio.
-/// - Fires island notifications (.voiceWoke / .voiceFinished) on the main thread.
-/// - Auto-pauses on: screen lock, screen sleep, system sleep, Low Power Mode,
-/// MacDictation active.
-/// - Wake window restarts every 20 s of continuous speech to bound recognition cost.
+//
+// Coordinator for the «OK Coucou» voice feature.
+//
+// - Uses VoiceAudio (energy VAD) and WakeSpotter (on-device recognition).
+// - WakeSpotter handles both wake detection and command transcription in one session.
+// - After wake: VoiceAudio.bypassVAD = true so the command receives continuous audio.
+// - Fires island notifications (.voiceWoke / .voiceFinished) on the main thread.
+// - Auto-pauses on: screen lock, screen sleep, system sleep, Low Power Mode,
+// MacDictation active.
+// - Wake window restarts every 20 s of continuous speech to bound recognition cost.
+// - Backoff: onWakeWindowEnded reopens with exponential delay (0.5 s → 5 s);
+// after maxFastFails consecutive fast-fails, waits for the next VAD segment.
+// - Auto-repair: consecutive window errors, audio stall, or device config change
+// trigger a full pipeline teardown + rebuild.
@MainActor
final class VoiceEngine: ObservableObject {
static let shared = VoiceEngine()
@@ -34,7 +38,7 @@ final class VoiceEngine: ObservableObject {
private var screenLocked = false
private var screenSleeping = false
private var lowPowerMode = false
- private var dictationActive = 0 // reference count: MacDictation instances currently recording
+ private var dictationActive = 0
var isPaused: Bool { screenLocked || screenSleeping || lowPowerMode || dictationActive > 0 }
@@ -44,21 +48,30 @@ final class VoiceEngine: ObservableObject {
private var spotter: WakeSpotter?
private var locale: Locale?
- /// True while the VAD has detected voice activity (VAD rose, hasn't fallen yet).
private var voiceSegmentActive = false
- // Command session timers and state
- private var silenceWork: DispatchWorkItem?
- private var commandMaxWork: DispatchWorkItem?
- private var wakeWindowWork: DispatchWorkItem? // 20 s window-restart timer
- private var lastWordCount = 0
+ // Command session timers
+ private var silenceWork: DispatchWorkItem?
+ private var commandMaxWork: DispatchWorkItem?
+ private var wakeWindowWork: DispatchWorkItem? // 20 s periodic restart
+ private var lastWordCount = 0
+
+ // Backoff / loop prevention
+ private var backoff = WakeWindowBackoff()
+ private var windowOpenedAt: Date = .distantPast
+ private var consecErrorStreak = 0
+ private static let maxConsecErrors = 3
+
+ // Stall watchdog + unavailability retry
+ private var stallWork: DispatchWorkItem?
+ private var unavailableWork: DispatchWorkItem?
+ private var firstUnavailableAt: Date? = nil
+ private static let stallTimeout: TimeInterval = 2.0
+ private static let unavailableRebuildDelay: TimeInterval = 10.0
- /// Time to start speaking after the wake phrase before the session times out.
private static let initialTimeout: TimeInterval = 3.0
- /// Silence duration that ends a command once speaking has started.
private static let silenceTimeout: TimeInterval = 1.2
private static let commandMaxTime: TimeInterval = 10.0
- /// Restart the wake recognition window every N seconds of continuous speech.
private static let wakeWindowMax: TimeInterval = 20.0
private static let cancelPhrases = ["annule", "annuler", "cancel", "laisse tomber", "never mind"]
@@ -83,17 +96,13 @@ final class VoiceEngine: ObservableObject {
else if isEnabled { startAudioPipeline() }
}
- /// Called by IslandWindowController when listening is dismissed externally.
- func cancelListening() {
- endCommand(postFinished: false)
- }
+ func cancelListening() { 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
+ stallWork?.cancel(); stallWork = nil
isListeningForCommand = true
commandTranscript = ""
lastWordCount = 0
@@ -110,7 +119,7 @@ final class VoiceEngine: ObservableObject {
DispatchQueue.main.asyncAfter(deadline: .now() + 6.0, execute: maxItem)
}
- // MARK: - Audio pipeline
+ // MARK: - Pipeline lifecycle
private func startAudioPipeline() {
guard audio == nil else { return }
@@ -125,6 +134,8 @@ final class VoiceEngine: ObservableObject {
let a = VoiceAudio()
let s = WakeSpotter()
+ // ── Spotter callbacks ─────────────────────────────────────────────────
+
s.onWake = { [weak self] transcript in
self?.wakeDetected(transcript: transcript)
}
@@ -137,46 +148,74 @@ final class VoiceEngine: ObservableObject {
self?.endCommand(postFinished: true)
}
- a.onMicLevel = { [weak self] level in
- self?.micLevel = level
+ s.onWakeWindowEnded = { [weak self] wasError in
+ guard let self, !isListeningForCommand, voiceSegmentActive else { return }
+
+ // Track consecutive error-ended windows (not clean final results).
+ if wasError {
+ consecErrorStreak += 1
+ if consecErrorStreak >= Self.maxConsecErrors {
+ appendAppLog("nb.log",
+ "[Voice] window error streak \(consecErrorStreak), rebuilding pipeline")
+ self.triggerPipelineRebuild(reason: "window error streak \(consecErrorStreak)")
+ return
+ }
+ } else {
+ consecErrorStreak = 0
+ }
+
+ // Backoff: fast-fail windows reopen with exponential delay.
+ let elapsed = Date().timeIntervalSince(windowOpenedAt)
+ switch backoff.windowEnded(elapsed: elapsed, wasError: wasError) {
+ case .open:
+ self.openWakeWindow(audio: a, spotter: s, locale: loc)
+ case .delay(let d):
+ appendAppLog("nb.log",
+ "[Voice] window backoff \(String(format: "%.2f", d))s (streak \(backoff.streak))")
+ DispatchQueue.main.asyncAfter(deadline: .now() + d) { [weak self] in
+ guard let self, !isListeningForCommand, voiceSegmentActive else { return }
+ self.openWakeWindow(audio: a, spotter: s, locale: loc)
+ }
+ case .stop:
+ appendAppLog("nb.log",
+ "[Voice] window fast-fail limit (\(backoff.maxFastFails)), waiting for next VAD")
+ }
}
- // Wake window ended naturally (final result in wake phase) — reopen if voice is still active.
- s.onWakeWindowEnded = { [weak self] in
- guard let self, !isListeningForCommand, voiceSegmentActive else { return }
- let preroll = a.drainPreroll()
- s.beginWindow(locale: loc, preroll: preroll)
- appendAppLog("nb.log", "[Voice] window open")
- scheduleWakeWindowRestart(audio: a, spotter: s, locale: loc)
+ // ── Audio callbacks ───────────────────────────────────────────────────
+
+ a.onMicLevel = { [weak self] level in self?.micLevel = level }
+
+ a.onConfigChange = { [weak self] in
+ guard let self else { return }
+ self.triggerPipelineRebuild(reason: "AVAudioEngine config change")
}
a.onVoiceStart = { [weak self] in
guard let self else { return }
appendAppLog("nb.log", "[Voice] vad start")
voiceSegmentActive = true
- let preroll = a.drainPreroll()
- s.beginWindow(locale: loc, preroll: preroll)
- appendAppLog("nb.log", "[Voice] window open")
- scheduleWakeWindowRestart(audio: a, spotter: s, locale: loc)
+ backoff.reset()
+ consecErrorStreak = 0
+ self.openWakeWindow(audio: a, spotter: s, locale: loc)
+ self.startStallWatchdog(audio: a)
}
a.onVoiceEnd = { [weak self] in
guard let self else { return }
appendAppLog("nb.log", "[Voice] vad end")
- voiceSegmentActive = false
+ voiceSegmentActive = false
+ stallWork?.cancel(); stallWork = nil
+ unavailableWork?.cancel(); unavailableWork = nil
+ firstUnavailableAt = nil
wakeWindowWork?.cancel(); wakeWindowWork = nil
- // Only close the wake window if we're not already in command mode.
- // isInCommandPhase is lock-protected and safe to check on main before
- // isListeningForCommand is set (race with onWake dispatch).
if !isListeningForCommand && !s.isInCommandPhase {
s.endWindow()
appendAppLog("nb.log", "[Voice] window close")
}
}
- a.onBuffer = { buf, _ in
- s.feed(buf)
- }
+ a.onBuffer = { buf, _ in s.feed(buf) }
do {
try a.start()
@@ -189,56 +228,120 @@ final class VoiceEngine: ObservableObject {
private func stopAudioPipeline() {
endCommand(postFinished: false)
- wakeWindowWork?.cancel(); wakeWindowWork = nil
+ wakeWindowWork?.cancel(); wakeWindowWork = nil
+ stallWork?.cancel(); stallWork = nil
+ unavailableWork?.cancel(); unavailableWork = nil
+ firstUnavailableAt = nil
+ // Null callbacks before stop() so any queued main-thread dispatches become no-ops.
+ audio?.onVoiceStart = nil
+ audio?.onVoiceEnd = nil
+ audio?.onBuffer = nil
+ audio?.onMicLevel = nil
+ audio?.onConfigChange = nil
+ spotter?.onWake = nil
+ spotter?.onCommandUpdate = nil
+ spotter?.onCommandEnd = nil
+ spotter?.onWakeWindowEnded = nil
audio?.stop()
- audio = nil
- spotter = nil
- locale = nil
+ audio = nil
+ spotter = nil
+ locale = nil
voiceSegmentActive = false
+ backoff.reset()
+ consecErrorStreak = 0
}
- // MARK: - 20-second wake-window restart
+ // MARK: - Wake window helpers
+
+ /// Open one wake+command recognition window.
+ /// Logs "[Voice] window open" only if the underlying task started.
+ /// Handles recognizer-unavailable retries and pipeline rebuild after 10 s.
+ @discardableResult
+ private func openWakeWindow(audio: VoiceAudio, spotter: WakeSpotter, locale: Locale) -> Bool {
+ let preroll = audio.drainPreroll()
+ let started = spotter.beginWindow(locale: locale, preroll: preroll)
+ if started {
+ windowOpenedAt = Date()
+ firstUnavailableAt = nil
+ unavailableWork?.cancel(); unavailableWork = nil
+ appendAppLog("nb.log", "[Voice] window open")
+ scheduleWakeWindowRestart(audio: audio, spotter: spotter, locale: locale)
+ } else {
+ // Recognizer unavailable or already active. Retry until rebuild threshold.
+ if firstUnavailableAt == nil { firstUnavailableAt = Date() }
+ let age = Date().timeIntervalSince(firstUnavailableAt!)
+ if age >= Self.unavailableRebuildDelay {
+ appendAppLog("nb.log", "[Voice] recognizer unavailable \(Int(age))s, rebuilding")
+ triggerPipelineRebuild(reason: "recognizer unavailable \(Int(age))s")
+ } else {
+ unavailableWork?.cancel()
+ let item = DispatchWorkItem { [weak self] in
+ guard let self, voiceSegmentActive, !isListeningForCommand else { return }
+ self.openWakeWindow(audio: audio, spotter: spotter, locale: locale)
+ }
+ unavailableWork = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: item)
+ }
+ }
+ return started
+ }
+ /// 20-second periodic wake-window restart to bound recognition cost.
private func scheduleWakeWindowRestart(audio: VoiceAudio, spotter: WakeSpotter, locale: Locale) {
wakeWindowWork?.cancel()
let item = DispatchWorkItem { [weak self] in
guard let self, !isListeningForCommand else { return }
- let preroll = audio.drainPreroll()
spotter.endWindow()
- appendAppLog("nb.log", "[Voice] window close")
- spotter.beginWindow(locale: locale, preroll: preroll)
- appendAppLog("nb.log", "[Voice] window open")
- scheduleWakeWindowRestart(audio: audio, spotter: spotter, locale: locale)
+ appendAppLog("nb.log", "[Voice] window close (20s)")
+ self.openWakeWindow(audio: audio, spotter: spotter, locale: locale)
}
wakeWindowWork = item
DispatchQueue.main.asyncAfter(deadline: .now() + Self.wakeWindowMax, execute: item)
}
+ /// 2-second audio stall watchdog: fires if no buffers arrive while VAD is active.
+ private func startStallWatchdog(audio: VoiceAudio) {
+ stallWork?.cancel()
+ let item = DispatchWorkItem { [weak self] in
+ guard let self, voiceSegmentActive, !isListeningForCommand else { return }
+ let age = Date().timeIntervalSince(audio.lastBufferTime)
+ guard age > Self.stallTimeout else { return }
+ appendAppLog("nb.log", "[Voice] audio stall \(String(format: "%.1f", age))s, rebuilding")
+ self.triggerPipelineRebuild(reason: "audio stall \(String(format: "%.1f", age))s")
+ }
+ stallWork = item
+ DispatchQueue.main.asyncAfter(deadline: .now() + Self.stallTimeout, execute: item)
+ }
+
+ /// Tear down and rebuild the full audio pipeline.
+ private func triggerPipelineRebuild(reason: String) {
+ appendAppLog("nb.log", "[Voice] pipeline rebuild (\(reason))")
+ stopAudioPipeline()
+ guard isEnabled, !isPaused else { return }
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { [weak self] in
+ guard let self, isEnabled, !isPaused else { return }
+ self.startAudioPipeline()
+ }
+ }
+
// MARK: - Wake detection
private func wakeDetected(transcript: String) {
- // FIX: reset spotter if we're going to ignore this wake, so the window doesn't
- // stay permanently in command phase and block future wake detections.
- guard isEnabled, !isPaused else {
- spotter?.endWindow()
- return
- }
- guard !isListeningForCommand else {
- spotter?.endWindow()
- return
- }
- guard !shouldIgnoreWake() else {
- spotter?.endWindow()
- return
- }
+ guard isEnabled, !isPaused else { spotter?.endWindow(); return }
+ guard !isListeningForCommand else { spotter?.endWindow(); return }
+ guard !shouldIgnoreWake() else { spotter?.endWindow(); return }
wakeWindowWork?.cancel(); wakeWindowWork = nil
+ stallWork?.cancel(); stallWork = nil
+ unavailableWork?.cancel(); unavailableWork = nil
+ firstUnavailableAt = nil
+ backoff.reset()
+ consecErrorStreak = 0
isListeningForCommand = true
commandTranscript = ""
lastWordCount = 0
audio?.bypassVAD = true
appendAppLog("nb.log", "[Voice] wake")
NotificationCenter.default.post(name: .voiceWoke, object: nil)
- // Initial timeout: 3 s to start speaking, then 1.2 s silence to finish.
resetSilenceTimer()
let maxItem = DispatchWorkItem { [weak self] in
Task { @MainActor in self?.endCommand(postFinished: true) }
@@ -253,7 +356,6 @@ final class VoiceEngine: ObservableObject {
if wc > lastWordCount {
lastWordCount = wc
resetSilenceTimer()
- // Cancel only when the ENTIRE command is a cancel phrase (not a substring).
let trimmed = command.trimmingCharacters(in: .whitespaces)
if Self.cancelPhrases.contains(WakePhrase.normalise(trimmed)) {
endCommand(postFinished: true)
@@ -265,8 +367,6 @@ final class VoiceEngine: ObservableObject {
private func resetSilenceTimer() {
silenceWork?.cancel()
- // Use the longer initial timeout before any words are spoken;
- // switch to the shorter silence timeout once speaking has begun.
let timeout = lastWordCount > 0 ? Self.silenceTimeout : Self.initialTimeout
let item = DispatchWorkItem { [weak self] in
Task { @MainActor in self?.endCommand(postFinished: true) }
@@ -275,12 +375,15 @@ final class VoiceEngine: ObservableObject {
DispatchQueue.main.asyncAfter(deadline: .now() + timeout, execute: item)
}
+ /// Idempotent: if not in command mode, only cancels timers (no endWindow, no resetVAD).
+ /// This prevents closing a freshly opened wake window when the result view is dismissed.
private func endCommand(postFinished: Bool) {
silenceWork?.cancel(); silenceWork = nil
commandMaxWork?.cancel(); commandMaxWork = nil
+ guard isListeningForCommand else { return }
audio?.bypassVAD = false
- audio?.resetVAD() // reset VAD so next speech triggers a fresh start
- voiceSegmentActive = false // treat the voice segment as ended after command
+ audio?.resetVAD()
+ voiceSegmentActive = false
micLevel = 0
spotter?.endWindow()
appendAppLog("nb.log", "[Voice] command end (had transcript: \(!commandTranscript.isEmpty))")
@@ -295,8 +398,6 @@ final class VoiceEngine: ObservableObject {
// MARK: - Helpers
- /// Returns true when the island is showing an approval, question, or chat prompt —
- /// wake detection is suppressed in those states to avoid interrupting the user.
private func shouldIgnoreWake() -> Bool {
let v = AppState.shared.view
return v == .approval || v == .question || v == .prompt || v == .voiceResult
@@ -380,6 +481,5 @@ final class VoiceEngine: ObservableObject {
extension Notification.Name {
static let voiceWoke = Notification.Name("notchBuddy.voiceWoke")
static let voiceFinished = Notification.Name("notchBuddy.voiceFinished")
- // dictationDidStart / dictationDidEnd are defined in MacDictation.swift
}
#endif
diff --git a/NotchBuddy/Sources/App/Voice/WakeSpotter.swift b/NotchBuddy/Sources/App/Voice/WakeSpotter.swift
index 591ed37f..2b13bacc 100644
--- a/NotchBuddy/Sources/App/Voice/WakeSpotter.swift
+++ b/NotchBuddy/Sources/App/Voice/WakeSpotter.swift
@@ -3,118 +3,133 @@ import AVFoundation
import Speech
// MARK: - WakeSpotter
-
-/// Runs a single SFSpeechRecognizer window to detect the "OK Coucou" wake phrase,
-/// then switches to command mode in the same recognition session so words spoken
-/// immediately after the wake phrase are not lost.
-///
-/// Wake detection uses `WakePhrase.split` which searches anywhere in the transcript
-/// at a word boundary, not just the start ("euh ok coucou…" matches).
-///
-/// Thread model: `beginWindow`, `endWindow` are called on the main actor.
-/// `feed(_:)` may be called from any thread (the audio tap thread).
-/// Recognition callbacks arrive on an internal Apple thread.
-/// All shared state is protected by a single `NSLock`.
+//
+// Runs a single SFSpeechRecognizer window to detect the "OK Coucou" wake phrase,
+// then switches to command mode in the same recognition session so words spoken
+// immediately after the wake phrase are not lost.
+//
+// Thread model: `beginWindow`, `endWindow` called on the main actor.
+// `feed(_:)` may be called from any thread (audio tap thread).
+// Recognition callbacks arrive on an internal Apple thread.
+// All shared state is protected by a single NSLock.
+//
+// Logging (to nb.log):
+// [WakeSpotter] task start
+// [WakeSpotter] task refused (already active)
+// [WakeSpotter] task refused (unavailable)
+// [WakeSpotter] task end: final, partials N
+// [WakeSpotter] task end: error <domain>/<code>, partials N
final class WakeSpotter: @unchecked Sendable {
// MARK: - Callbacks (all delivered on the main thread)
- /// Called once when the wake phrase is detected. Receives the raw partial transcript.
- var onWake: ((String) -> Void)?
- /// Called during the command phase with the command portion of the transcript (normalised).
- var onCommandUpdate: ((String) -> Void)?
- /// Called when the recognition session ends naturally (final result or error)
- /// while in command phase.
- var onCommandEnd: (() -> Void)?
- /// Called when the recognition session ends in wake phase (no command captured).
- /// VoiceEngine uses this to reopen the window immediately if the VAD is still active.
- var onWakeWindowEnded: (() -> Void)?
+ var onWake: ((String) -> Void)?
+ var onCommandUpdate: ((String) -> Void)?
+ var onCommandEnd: (() -> Void)?
+ /// Fired when the session ends in wake phase (no command captured).
+ /// `wasError` is true when the session ended with an error (not a clean final result).
+ var onWakeWindowEnded: ((Bool) -> Void)?
// MARK: - State (all guarded by `lock`)
private let lock = NSLock()
- private var recognizer: SFSpeechRecognizer?
- private var request: SFSpeechAudioBufferRecognitionRequest?
- private var task: SFSpeechRecognitionTask?
- private var active = false
- private var phase: Phase = .wake
+ private var recognizer: SFSpeechRecognizer?
+ private var request: SFSpeechAudioBufferRecognitionRequest?
+ private var task: SFSpeechRecognitionTask?
+ private var active = false
+ private var phase: Phase = .wake
+ private var partialCount = 0
private enum Phase { case wake, command }
// MARK: - Public API
- /// True when the session has advanced to command phase (thread-safe).
var isInCommandPhase: Bool { lock.withLock { phase == .command } }
- /// Begin a recognition window for the given locale.
- /// Pre-roll buffers (audio captured before VAD fired) are injected first.
- func beginWindow(locale: Locale, preroll: [AVAudioPCMBuffer] = []) {
- var recognizerSnap: SFSpeechRecognizer?
- var requestSnap: SFSpeechAudioBufferRecognitionRequest?
+ /// Open a wake+command recognition window.
+ /// Returns `true` if the underlying recognition task was successfully started.
+ @discardableResult
+ func beginWindow(locale: Locale, preroll: [AVAudioPCMBuffer] = []) -> Bool {
+ enum Refusal { case alreadyActive, unavailable }
+ var refusal: Refusal? = nil
+ var rSnap: SFSpeechRecognizer?
+ var reqSnap: SFSpeechAudioBufferRecognitionRequest?
lock.withLock {
- guard !active else { return }
+ guard !active else { refusal = .alreadyActive; return }
guard let r = SFSpeechRecognizer(locale: locale),
r.supportsOnDeviceRecognition,
- r.isAvailable else { return }
+ r.isAvailable else { refusal = .unavailable; return }
let req = SFSpeechAudioBufferRecognitionRequest()
req.shouldReportPartialResults = true
req.requiresOnDeviceRecognition = true
- req.contextualStrings = ["Coucou", "OK Coucou", "okay Coucou",
- "hey Coucou"]
+ req.contextualStrings = ["Coucou", "OK Coucou", "okay Coucou", "hey Coucou"]
preroll.forEach { req.append($0) }
- recognizer = r
- request = req
- active = true
- phase = .wake
- recognizerSnap = r
- requestSnap = req
+ recognizer = r
+ request = req
+ active = true
+ phase = .wake
+ partialCount = 0
+ rSnap = r
+ reqSnap = req
+ }
+
+ if let refusal {
+ switch refusal {
+ case .alreadyActive:
+ appendAppLog("nb.log", "[WakeSpotter] task refused (already active)")
+ case .unavailable:
+ appendAppLog("nb.log", "[WakeSpotter] task refused (unavailable)")
+ }
+ return false
}
- guard let r = recognizerSnap, let req = requestSnap else { return }
+ guard let r = rSnap, let req = reqSnap else { return false }
- // Start the task outside the lock (Apple's callback is always async).
+ appendAppLog("nb.log", "[WakeSpotter] task start")
let t = r.recognitionTask(with: req) { [weak self] result, error in
self?.handleResult(result, error: error)
}
lock.withLock { task = t }
+ return true
}
- /// Append an audio buffer (audio tap thread).
func feed(_ buffer: AVAudioPCMBuffer) {
- // Get the request reference under lock; append outside (append is thread-safe).
lock.withLock { request }?.append(buffer)
}
- /// Close the window without firing any callback.
func endWindow() {
lock.withLock {
request?.endAudio()
task?.cancel()
- request = nil
- task = nil
- recognizer = nil
- active = false
- phase = .wake
+ request = nil
+ task = nil
+ recognizer = nil
+ active = false
+ phase = .wake
+ partialCount = 0
}
}
// MARK: - Recognition callback
- private enum Action {
+ private enum RecogAction {
case woke(String)
case commandUpdate(String)
case commandEnd
- case wakeWindowEnded
+ case wakeWindowEnded(wasError: Bool)
}
private func handleResult(_ result: SFSpeechRecognitionResult?, error: Error?) {
- let action: Action? = lock.withLock { () -> Action? in
+ var logMsg: String? = nil
+
+ let action: RecogAction? = lock.withLock { () -> RecogAction? in
guard active else { return nil }
if let transcript = result?.bestTranscription.formattedString {
+ partialCount += 1
switch phase {
case .wake:
let r = WakePhrase.split(transcript)
@@ -124,24 +139,33 @@ final class WakeSpotter: @unchecked Sendable {
}
case .command:
let r = WakePhrase.split(transcript)
- // In command phase, split always finds the wake prefix; fall back to full transcript.
return .commandUpdate(r.matched ? r.command : transcript)
}
}
if result?.isFinal == true || error != nil {
let wasCommand = phase == .command
- request = nil
- task = nil
- recognizer = nil
- active = false
- phase = .wake
- return wasCommand ? .commandEnd : .wakeWindowEnded
+ let n = partialCount
+ let wasError = error != nil
+ request = nil
+ task = nil
+ recognizer = nil
+ active = false
+ phase = .wake
+ partialCount = 0
+ if let err = error as NSError? {
+ logMsg = "[WakeSpotter] task end: error \(err.domain)/\(err.code), partials \(n)"
+ } else {
+ logMsg = "[WakeSpotter] task end: final, partials \(n)"
+ }
+ return wasCommand ? .commandEnd : .wakeWindowEnded(wasError: wasError)
}
return nil
}
+ if let msg = logMsg { appendAppLog("nb.log", msg) }
guard let action else { return }
+
switch action {
case .woke(let t):
DispatchQueue.main.async { [weak self] in self?.onWake?(t) }
@@ -149,8 +173,8 @@ final class WakeSpotter: @unchecked Sendable {
DispatchQueue.main.async { [weak self] in self?.onCommandUpdate?(s) }
case .commandEnd:
DispatchQueue.main.async { [weak self] in self?.onCommandEnd?() }
- case .wakeWindowEnded:
- DispatchQueue.main.async { [weak self] in self?.onWakeWindowEnded?() }
+ case .wakeWindowEnded(let wasError):
+ DispatchQueue.main.async { [weak self] in self?.onWakeWindowEnded?(wasError) }
}
}
}
diff --git a/NotchBuddy/Sources/App/Voice/WakeWindowBackoff.swift b/NotchBuddy/Sources/App/Voice/WakeWindowBackoff.swift
new file mode 100644
index 00000000..ecca36d8
--- /dev/null
+++ b/NotchBuddy/Sources/App/Voice/WakeWindowBackoff.swift
@@ -0,0 +1,64 @@
+import Foundation
+
+// MARK: - WakeWindowBackoff
+//
+// Pure value-type backoff controller for wake-window reopening.
+// No AppKit dependency — testable with standalone swiftc.
+//
+// Usage:
+// var backoff = WakeWindowBackoff()
+// switch backoff.windowEnded(elapsed: elapsed, wasError: wasError) {
+// case .open: openWakeWindow()
+// case .delay(let d): schedule(openWakeWindow, after: d)
+// case .stop: waitForNextVADSegment()
+// }
+// backoff.reset() // call on new VAD segment or successful wake
+
+struct WakeWindowBackoff {
+
+ enum Action: Equatable {
+ case open
+ case delay(TimeInterval)
+ case stop
+ }
+
+ // Tunables (kept in sync with scripts/test-voice-backoff.sh expectations)
+ let fastThreshold: TimeInterval // window lifetime < this → "fast fail"
+ let maxFastFails: Int // max consecutive fast fails before .stop
+ let base: TimeInterval // first backoff delay (streak = 1)
+ let maxDelay: TimeInterval // cap
+
+ private(set) var streak: Int = 0
+
+ init(fastThreshold: TimeInterval = 1.0,
+ maxFastFails: Int = 3,
+ base: TimeInterval = 0.5,
+ maxDelay: TimeInterval = 5.0) {
+ self.fastThreshold = fastThreshold
+ self.maxFastFails = maxFastFails
+ self.base = base
+ self.maxDelay = maxDelay
+ }
+
+ /// Call when a wake window ends without detecting a wake word.
+ /// `elapsed` = wall time since the window was opened.
+ /// `wasError` = the session ended with an error (not a clean final result).
+ mutating func windowEnded(elapsed: TimeInterval, wasError: Bool) -> Action {
+ let fast = elapsed < fastThreshold
+ guard fast else {
+ // Normal-length window → reset streak, reopen immediately.
+ streak = 0
+ return .open
+ }
+ streak += 1
+ guard streak < maxFastFails else {
+ // Too many rapid failures this VAD segment.
+ return .stop
+ }
+ let delay = min(base * pow(2.0, Double(streak - 1)), maxDelay)
+ return .delay(delay)
+ }
+
+ /// Reset on new VAD segment or successful wake detection.
+ mutating func reset() { streak = 0 }
+}
diff --git a/scripts/test-voice-backoff.sh b/scripts/test-voice-backoff.sh
new file mode 100644
index 00000000..8ba3d21f
--- /dev/null
+++ b/scripts/test-voice-backoff.sh
@@ -0,0 +1,7 @@
+#!/usr/bin/env bash
+set -e
+echo "Running WakeWindowBackoff tests…"
+swiftc -o /tmp/voice-backoff-tests \
+ NotchBuddy/Sources/App/Voice/WakeWindowBackoff.swift \
+ tests/WakeWindowBackoffTests.swift
+/tmp/voice-backoff-tests
diff --git a/tests/WakeWindowBackoffTests.swift b/tests/WakeWindowBackoffTests.swift
new file mode 100644
index 00000000..27f61c6b
--- /dev/null
+++ b/tests/WakeWindowBackoffTests.swift
@@ -0,0 +1,84 @@
+import Foundation
+
+// MARK: - WakeWindowBackoff tests
+//
+// Pure test — no AppKit, no VoiceEngine. Compiles with:
+// swiftc -o /tmp/voice-backoff-tests \
+// NotchBuddy/Sources/App/Voice/WakeWindowBackoff.swift \
+// tests/WakeWindowBackoffTests.swift
+
+@main
+enum WakeWindowBackoffTests {
+
+ static var pass = 0
+ static var fail = 0
+
+ static func main() {
+ let cfg = WakeWindowBackoff(fastThreshold: 1.0, maxFastFails: 3, base: 0.5, maxDelay: 5.0)
+
+ // ── Backoff delays grow exponentially, capped at maxDelay ─────────────
+ var b = cfg
+ let r1 = b.windowEnded(elapsed: 0.1, wasError: true)
+ check("streak 1 → delay 0.50s", r1, .delay(0.5))
+ check("streak after 1st fast", b.streak, 1)
+
+ let r2 = b.windowEnded(elapsed: 0.1, wasError: true)
+ check("streak 2 → delay 1.00s", r2, .delay(1.0))
+
+ let r3 = b.windowEnded(elapsed: 0.1, wasError: true)
+ check("streak 3 → stop", r3, .stop)
+
+ // ── Normal-length window resets streak ────────────────────────────────
+ var b2 = cfg
+ _ = b2.windowEnded(elapsed: 0.1, wasError: true)
+ _ = b2.windowEnded(elapsed: 0.1, wasError: true)
+ let rNorm = b2.windowEnded(elapsed: 2.0, wasError: false) // normal duration
+ check("normal end → open", rNorm, .open)
+ check("streak reset after normal", b2.streak, 0)
+
+ // ── reset() clears streak ─────────────────────────────────────────────
+ var b3 = cfg
+ _ = b3.windowEnded(elapsed: 0.1, wasError: true)
+ _ = b3.windowEnded(elapsed: 0.1, wasError: true)
+ b3.reset()
+ check("streak after reset", b3.streak, 0)
+ let rAfterReset = b3.windowEnded(elapsed: 0.1, wasError: true)
+ check("first fail after reset → delay 0.50s", rAfterReset, .delay(0.5))
+
+ // ── maxDelay cap ──────────────────────────────────────────────────────
+ var b4 = WakeWindowBackoff(fastThreshold: 1.0, maxFastFails: 100, base: 0.5, maxDelay: 5.0)
+ for _ in 0..<9 { _ = b4.windowEnded(elapsed: 0.1, wasError: true) }
+ let rCap = b4.windowEnded(elapsed: 0.1, wasError: true)
+ // streak 10 → 0.5 * 2^9 = 256 → capped at 5.0
+ check("delay capped at maxDelay", rCap, .delay(5.0))
+
+ // ── Rapid fast-fails: at most maxFastFails opens before .stop ─────────
+ // Simulate a spotter that always fails instantly. Count how many .open/.delay
+ // actions are returned before .stop (== how many windows would be opened).
+ var b5 = cfg
+ var opens = 0
+ for _ in 0..<20 {
+ let action = b5.windowEnded(elapsed: 0.05, wasError: true)
+ switch action {
+ case .open: opens += 1
+ case .delay: opens += 1 // a delayed open still opens
+ case .stop: break
+ }
+ if case .stop = action { break }
+ }
+ // First call: streak becomes 1 → .delay (1 open scheduled)
+ // Second call: streak becomes 2 → .delay (1 more open scheduled)
+ // Third call: streak becomes 3 → .stop (no more)
+ // Total opens before stop: 2 (streak 1 and 2 each produce a delayed open)
+ check("at most maxFastFails-1 delayed opens before stop", opens, 2)
+
+ let total = pass + fail
+ if fail == 0 { print("\n\(total)/\(total) passed.") }
+ else { print("\n\(fail) FAILED / \(total) total"); exit(1) }
+ }
+
+ 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 }
+ }
+}