Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
Improve wake-word reliability by synchronizing detector state with TTS playback, refining sensitivity thresholds, and adding hands-free UI modes.
Rishabh Bajpai2c8bc0e565f1
diff --git a/.github/workflows/chanakya.yml b/.github/workflows/chanakya.ymlindex 08c76bf..0caa1c8 100644--- a/.github/workflows/chanakya.yml+++ b/.github/workflows/chanakya.yml@@ -146,7 +146,7 @@ jobs:run: |COMMENT_BODY="${{ github.event.comment.body }}"# Extract branch name after "wrt" keyword (supports alphanumeric, underscores, hyphens, slashes)- if [[ "$COMMENT_BODY" =~ wrt[[:space:]]+([a-zA-Z0-9_/-]+) ]]; then+ if [[ "$COMMENT_BODY" =~ wrt[[:space:]]+([a-zA-Z0-9._/-]+) ]]; thenecho "branch=${BASH_REMATCH[1]}" >> $GITHUB_OUTPUTelseecho "branch=" >> $GITHUB_OUTPUTdiff --git a/.gitignore b/.gitignoreindex f720aff..4ec4030 100644--- a/.gitignore+++ b/.gitignore@@ -114,4 +114,4 @@ MARKETING_PLAYBOOK.md.vscode/docs/benchmarkdocs/WAKE_WORD_PLAN.md-.freebuff\ No newline at end of file+.freebuffdiff --git a/app/src/main/java/com/gotcha/audio/SilenceDetector.kt b/app/src/main/java/com/gotcha/audio/SilenceDetector.ktindex 33d2f95..35e9922 100644--- a/app/src/main/java/com/gotcha/audio/SilenceDetector.kt+++ b/app/src/main/java/com/gotcha/audio/SilenceDetector.kt@@ -1,15 +1,23 @@package com.gotcha.audio/**- * A small noise-floor-adaptive voice-activity detector used by the hands-free+ * A noise-floor-adaptive voice-activity detector used by the hands-free* wake-word call flow.*- * It is fed one RMS (dBFS) value per audio window. Speech is any window above- * `noiseFloor + margin` (never below an absolute floor); the noise floor is a- * slow exponential average of windows that are *below* the threshold, so the- * detector adapts to quiet and loud rooms. Once speech has been detected, the- * detector reports [Decision.STOP] after [silenceTimeoutMs] of trailing- * silence; if the user never spoke, it reports [Decision.STOP_NO_SPEECH] after+ * It is fed one RMS (dBFS) value per audio window. The noise floor is a+ * low-percentile estimate over a rolling window of recent RMS values, so it+ * can both fall and rise: in a loud room the floor climbs toward the ambient+ * level instead of permanently classifying ambient as speech. The rolling+ * window only records windows heard before speech is accepted, so sustained+ * speech can never drag the floor up mid-utterance. Speech is any window+ * above `noiseFloor + margin` (never below an absolute floor). A window must+ * stay above the threshold for [ACCEPT_STREAK] consecutive windows before it+ * counts as speech, so a one-window transient (door slam, cough) is ignored.+ *+ * Once speech has been accepted, the detector reports [Decision.STOP] after+ * [silenceTimeoutMs] of trailing silence — the clock only starts after genuine+ * speech, so a user who pauses before beginning to speak is not cut off. If+ * the user never spoke, it reports [Decision.STOP_NO_SPEECH] after* [noSpeechTimeoutMs].*/internal class SilenceDetector(@@ -21,22 +29,40 @@ internal class SilenceDetector(var speechDetected: Boolean = falseprivate set- private var noiseFloorDb = INITIAL_NOISE_FLOOR_DB+ private val recentRms = FloatArray(FLOOR_WINDOW)+ private var recentCount = 0+ private var recentStart = 0+ private var aboveThresholdStreak = 0private var startMs = -1Lprivate var lastSpeechAtMs = -1L/** The RMS level (dBFS) a window must exceed to count as speech. */val thresholdDb: Float- get() = maxOf(absoluteFloorDb, noiseFloorDb + speechMarginDb)+ get() = maxOf(absoluteFloorDb, noiseFloorEstimate + speechMarginDb)fun update(windowRmsDb: Float, nowMs: Long): Decision {if (startMs < 0) startMs = nowMs+ // Only pre-speech windows inform the floor, so the estimate keeps+ // reflecting ambient even while the user talks over it.+ if (!speechDetected) {+ recentRms[recentStart] = windowRmsDb+ recentStart = (recentStart + 1) % FLOOR_WINDOW+ if (recentCount < FLOOR_WINDOW) recentCount+++ }+if (windowRmsDb > thresholdDb) {- speechDetected = true+ aboveThresholdStreak+++ // Only accept speech once the floor window is primed — otherwise a+ // loud first window would be accepted against the initial floor+ // before the ambient level has been learned.+ if (!speechDetected && recentCount >= FLOOR_WINDOW &&+ aboveThresholdStreak >= ACCEPT_STREAK+ ) {+ speechDetected = true+ }lastSpeechAtMs = nowMs} else {- // Slide the floor toward whatever is quieter than speech.- noiseFloorDb = 0.95f * noiseFloorDb + 0.05f * windowRmsDb+ aboveThresholdStreak = 0}if (speechDetected && nowMs - lastSpeechAtMs >= silenceTimeoutMs) {return Decision.STOP@@ -47,6 +73,20 @@ internal class SilenceDetector(return Decision.CONTINUE}+ /**+ * Low-percentile of the recent RMS windows, in dBFS. Using a percentile+ * rather than the running minimum makes the floor robust to a single quiet+ * outlier, and letting it rise tracks louder rooms without treating the+ * ambient level as speech.+ */+ private val noiseFloorEstimate: Float+ get() {+ if (recentCount < FLOOR_WINDOW) return INITIAL_NOISE_FLOOR_DB+ val sorted = recentRms.copyOf(FLOOR_WINDOW).apply { sort() }+ val idx = (sorted.size * FLOOR_QUANTILE).toInt()+ return maxOf(sorted[idx.coerceIn(0, sorted.lastIndex)], absoluteFloorDb)+ }+enum class Decision { CONTINUE, STOP, STOP_NO_SPEECH }companion object {@@ -55,6 +95,15 @@ internal class SilenceDetector(private const val ABSOLUTE_FLOOR_DB = -50fprivate const val INITIAL_NOISE_FLOOR_DB = -60f+ /** Consecutive above-threshold windows required before accepting speech. */+ private const val ACCEPT_STREAK = 3++ /** Number of recent RMS windows the floor percentile is computed over. */+ private const val FLOOR_WINDOW = 12++ /** Fraction of recent windows that are background noise (low percentile). */+ private const val FLOOR_QUANTILE = 0.25f+/** RMS of [count] 16-bit PCM samples in dBFS (clamped to [ABSOLUTE_FLOOR_DB]). */fun rmsDb(samples: ShortArray, count: Int): Float {if (count <= 0) return ABSOLUTE_FLOOR_DBdiff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.ktindex 5eeb70b..32fb909 100644--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt@@ -249,7 +249,10 @@ class SttEngine(if (detector.speechDetected && pcm.size() > 0) {result = writeWav(context.cacheDir, pcm.toByteArray(), sampleRate)}- } catch (_: Exception) {+ } catch (e: Exception) {+ // A permissions/security failure, OOM, or recorder error must not+ // look like "no speech" without a trace — log it for debugging.+ Log.w(TAG, "VAD recording failed; treating as no speech", e)result = null} finally {try {diff --git a/app/src/main/java/com/gotcha/audio/TtsEngine.kt b/app/src/main/java/com/gotcha/audio/TtsEngine.ktindex 94b55e2..77dab80 100644--- a/app/src/main/java/com/gotcha/audio/TtsEngine.kt+++ b/app/src/main/java/com/gotcha/audio/TtsEngine.kt@@ -9,6 +9,9 @@ import android.speech.tts.UtteranceProgressListenerimport com.gotcha.i18n.Languageimport kotlinx.coroutines.CompletableDeferredimport kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutOrNullimport java.util.Locale@@ -39,11 +42,11 @@ class TtsEngine(@Volatileprivate var playbackGate: CompletableDeferred<Unit>? = null+ private val _isSpeaking = MutableStateFlow(false)+/** True while [speak] is playing audio — used to avoid the wake word hearing* the app's own speech and re-triggering itself. */- @Volatile- var isSpeaking: Boolean = false- private set+ val isSpeaking: StateFlow<Boolean> = _isSpeaking.asStateFlow()/** The models available from the API (empty if provider is Android). */var apiTtsModels: List<AudioModel> = emptyList()@@ -95,7 +98,7 @@ class TtsEngine(val sanitized = SpeechTextSanitizer.sanitize(text)if (sanitized.isBlank()) return@withContext truetry {- isSpeaking = true+ _isSpeaking.value = truewhen {provider == AudioProvider.ANDROID -> speakAndroid(sanitized, language)provider.isApiBased() -> speakApi(sanitized, apiModel, voice, language)@@ -104,7 +107,7 @@ class TtsEngine(} catch (_: Exception) {false} finally {- isSpeaking = false+ _isSpeaking.value = false}}diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 1d6dd1d..1229c9f 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -231,10 +231,26 @@ class AssistiveBallService : Service() {chatWindow.hide()}chatWindow.setState(state)+ chatWindow.setHandsFree(callController.isHandsFree)overlay.setCallActive(active)}}+ // Proactively pause the wake-word listener while the app's own TTS is+ // playing (e.g. a companion-panel read-aloud that says "gotcha"). The+ // post-detection isSpeaking guard in onWakeWordDetected is a second+ // line of defence against self-triggering, but stopping the listener+ // here closes the race at the source — see privacy-data-retention.md §10.3.+ scope.launch {+ ttsEngine.isSpeaking.collect { speaking ->+ if (speaking) {+ wakeWordDetector.stop()+ } else if (callController.state.value == CallState.IDLE) {+ maybeStartWakeWord()+ }+ }+ }+sweepOrphanedCalls()}@@ -843,7 +859,7 @@ class AssistiveBallService : Service() {private fun onWakeWordDetected() {wakeWordDetector.stop()- if (ttsEngine.isSpeaking) {+ if (ttsEngine.isSpeaking.value) {// The app was reading something aloud (e.g. a screen read-aloud that// happened to contain "gotcha") — never start a call from our own// voice. Resume listening instead.@@ -862,6 +878,15 @@ class AssistiveBallService : Service() {private fun maybeStartWakeWord() {val settings = settingsRepository.load()if (settings.wakeWordEnabled && settings.assistiveBallEnabled && hasMicPermission()) {+ // A running detector skips its own start() (see WakeWordDetector),+ // so a live sensitivity change would otherwise never reach the+ // matcher. Stop first to force a rebuild whenever the threshold+ // needs to move, then re-arm with the fresh value.+ if (appliedWakeWordSensitivity != settings.wakeWordSensitivity &&+ wakeWordDetector.isRunning()+ ) {+ wakeWordDetector.stop()+ }appliedWakeWordSensitivity = settings.wakeWordSensitivitywakeWordDetector.start()} else {diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex eb088cd..9679dff 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -113,6 +113,10 @@ class CallSessionController(@Volatileprivate var handsFree = false+ /** True while the active call is hands-free (wake-word started). */+ val isHandsFree: Boolean+ get() = handsFree+/** Drives hands-free listening; null when no hands-free call is active. */private var handsFreeAutoListen: Job? = null@@ -272,14 +276,29 @@ class CallSessionController(*/private suspend fun awaitHandsFreeInput(): Boolean {while (currentCoroutineContext().isActive && handsFree && [email protected]()) {- val waitingForInput = _state.value == CallState.READY ||- _state.value == CallState.WAITING_USER- if (waitingForInput && !ttsEngine.isSpeaking) return true+ // WAITING_USER only counts as "waiting for spoken input" when a+ // question is actually pending. During a confirmation overlay the+ // user answers by tapping Allow/Deny — opening the mic and falling+ // through finishTurn's gate check would start a *second* agent turn+ // while the first is still suspended in awaitConfirmation.+ if (awaitingHandsFreeInput(_state.value, questionGate != null) &&+ !ttsEngine.isSpeaking.value+ ) {+ return true+ }delay(100)}return false}+ /**+ * Whether the hands-free loop should treat [state] as "awaiting spoken+ * input". [questionPending] is true only while [awaitQuestionAnswer] holds+ * its gate — a confirmation overlay is deliberately excluded.+ */+ internal fun awaitingHandsFreeInput(state: CallState, questionPending: Boolean): Boolean =+ state == CallState.READY || (state == CallState.WAITING_USER && questionPending)+/*** Stop/interrupt the current turn. Cancels the agent, stops TTS/STT,* completes any pending question, and returns to [READY].@@ -439,7 +458,15 @@ class CallSessionController(pendingReply = msg}- val reply = pendingReply ?: return+ val reply = pendingReply ?: run {+ // The engine returned neither a reply nor an error. In PTT the user+ // could simply talk again, but a hands-free call has no mic button —+ // leaving the state in THINKING would hang it until manual End, so+ // fall back to READY (which the hands-free loop reads as "re-open+ // the mic").+ _state.value = CallState.READY+ return+ }_state.value = CallState.SPEAKINGif (speakText(reply, language)) {triggerEndVibration()diff --git a/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.ktindex 2105f58..dace43d 100644--- a/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt+++ b/app/src/main/java/com/gotcha/service/OnnxWakeWordPipeline.kt@@ -22,9 +22,12 @@ import java.nio.FloatBuffer* The first [WARMUP_FRAMES] scored frames are ignored so the feature buffers* fill up before anything can be detected.*- * All hot-path arrays are pre-allocated once and reused to keep this listener- * allocation-free at steady state (an always-on service cannot tolerate- * per-frame GC pressure).+ * The hot path avoids per-frame GC pressure: the raw PCM ring buffer, the+ * combined feed buffer, the frame buffer, and the mel window are all+ * pre-allocated once and reused. The per-row mel arrays, `toList()` snapshots,+ * and ONNX tensor inputs are still allocated each frame (~37.5/s), which is+ * acceptable — keep this from drifting into the comment-free "zero allocation"+ * territory that a profiler would disprove.*/@Suppress("UNCHECKED_CAST")internal class OnnxWakeWordPipeline(@@ -51,6 +54,9 @@ internal class OnnxWakeWordPipeline(/** Reused destination for each extracted 80 ms frame. */private val frame = ShortArray(FRAME_SIZE)+ /** Reused mel window (raw PCM → floats); filled up to [rawCount] per frame. */+ private val melWindow = FloatArray(MEL_WINDOW)+private val melBuffer = ArrayDeque<FloatArray>()private val featureBuffer = ArrayDeque<FloatArray>()@@ -129,20 +135,19 @@ internal class OnnxWakeWordPipeline(// rawCount <= MEL_WINDOW; the oldest sample lives at rawStart// (modulo the ring) once rawCount == MEL_WINDOW.val length = rawCount.coerceAtMost(MEL_WINDOW)- val window = FloatArray(length)val start = if (rawCount < MEL_WINDOW) {0} else {rawStart // when full, rawStart points at the oldest sample}for (i in 0 until length) {- window[i] = rawSamples[(start + i) % MEL_WINDOW].toFloat()+ melWindow[i] = rawSamples[(start + i) % MEL_WINDOW].toFloat()}val tensor = OnnxTensor.createTensor(env,- FloatBuffer.wrap(window),- longArrayOf(1L, window.size.toLong())+ FloatBuffer.wrap(melWindow, 0, length),+ longArrayOf(1L, length.toLong()))val rows = try {melSession.run(mapOf(melSession.inputNames.first() to tensor)).use { result ->diff --git a/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt b/app/src/main/java/com/gotcha/service/WakeWordMatcher.ktindex b1a2e73..48274ea 100644--- a/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt+++ b/app/src/main/java/com/gotcha/service/WakeWordMatcher.kt@@ -7,12 +7,15 @@ package com.gotcha.service* 0.50 for balanced behavior, 0.65 for high precision and 0.35 for high* sensitivity. The sensitivity slider is mapped onto that range:*- * threshold = 0.70 - 0.27 * sensitivity (clamped to [0.10, 0.90])+ * threshold = 0.70 - 0.27 * sensitivity*- * so the default sensitivity of 0.75 lands on 0.50. A single 80 ms frame above- * the threshold is not enough to trust — [PATIENCE] consecutive qualifying- * frames are required, which rejects the occasional one-frame spike without- * adding meaningful latency.+ * so the default sensitivity of 0.75 lands on 0.50. Because the slider only+ * spans sensitivity 0..1, the reachable threshold range is [0.43, 0.70] — the+ * model card's 0.35 high-sensitivity endpoint sits below the slider's floor+ * and is intentionally unreachable. A single 80 ms frame above the threshold+ * is not enough to trust — [PATIENCE] consecutive qualifying frames are+ * required, which rejects the occasional one-frame spike without adding+ * meaningful latency.*/internal class WakeWordMatcher(sensitivity: Float@@ -43,8 +46,12 @@ internal class WakeWordMatcher(const val DEFAULT_SENSITIVITY = 0.75fprivate const val BASE_THRESHOLD = 0.70fprivate const val SENSITIVITY_RANGE = 0.27f- private const val MIN_THRESHOLD = 0.10f- private const val MAX_THRESHOLD = 0.90f++ // Reachable range for sensitivity in [0, 1]: 0.70 - 0.27 = 0.43 at the+ // most sensitive end. Bounds are defensive; the formula already stays+ // inside them after the sensitivity clamp.+ private const val MIN_THRESHOLD = 0.43f+ private const val MAX_THRESHOLD = 0.70f// 2 frames × 80 ms = 160 ms: enough to reject a one-frame audio spike,// small enough to feel snappy. The Python reference also uses shortdiff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.ktindex 98bb750..c40f7f3 100644--- a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt@@ -142,13 +142,13 @@ fun AssistiveBallScreen(}// Labels mirror the model card's three recommended thresholds (0.65 / 0.50 /-// 0.35). Split points on the slider are derived from the inverse of+// 0.35). Split points on the slider are the inverse of// `threshold = 0.70 - 0.27 * sensitivity`:// threshold 0.65 → sensitivity ~0.185 (high-precision end)// threshold 0.50 → sensitivity ~0.741 (balanced, also the default)private fun sensitivityLabel(sensitivity: Float): String = when {- sensitivity < 0.30f -> "High precision"- sensitivity < 0.70f -> "Balanced"+ sensitivity < 0.185f -> "High precision"+ sensitivity < 0.741f -> "Balanced"else -> "High sensitivity"}diff --git a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt b/app/src/main/java/com/gotcha/ui/CallChatWindow.ktindex 884508b..6493fcb 100644--- a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt+++ b/app/src/main/java/com/gotcha/ui/CallChatWindow.kt@@ -81,6 +81,9 @@ class CallChatWindow(context: Context) {private var currentState: CallState = CallState.IDLE+ /** When true, the mic action button is hidden (hands-free wake-word call). */+ private var handsFreeMode = false+// Drag stateprivate var dragging = falseprivate var startX = 0@@ -151,6 +154,18 @@ class CallChatWindow(context: Context) {}}+ /**+ * Hands-free (wake-word) calls have no push-to-talk — the mic opens itself+ * and startMic/stopMic are no-ops — so the mic button is suppressed and the+ * chat window only shows the End control.+ */+ fun setHandsFree(enabled: Boolean) {+ mainHandler.post {+ handsFreeMode = enabled+ renderButtons()+ }+ }+// ---- Rendering ----/** (emoji, glass tint) for the action button in a given call state. */@@ -164,7 +179,10 @@ class CallChatWindow(context: Context) {@Suppress("SetTextI18n")private fun renderButtons() {val s = currentState- val appearance = actionAppearance(s)+ // During hands-free calls the mic is automatic — no push-to-talk — so+ // the action button (mic/stop/interrupt) is suppressed entirely. Only+ // the End control remains, which is rendered below.+ val appearance = if (handsFreeMode) null else actionAppearance(s)val btn = actionBtn as? TextViewif (appearance == null) {// Fade + shrink out, then hide.@@ -678,6 +696,7 @@ class CallChatWindow(context: Context) {val count = root.childCountfor (i in 0 until count) {val child = root.getChildAt(i)+ if (child.visibility != View.VISIBLE) continueif (x >= child.left && x <= child.right &&y >= child.top && y <= child.bottom) {@@ -689,6 +708,7 @@ class CallChatWindow(context: Context) {/** Fire the action bound to the mic button for the current call state. */private fun performMicAction() {+ if (handsFreeMode) return // mic is automatic — no push-to-talkwhen (currentState) {CallState.READY, CallState.WAITING_USER -> onStartMic()CallState.LISTENING -> onStopMic()diff --git a/app/src/test/java/com/gotcha/audio/SilenceDetectorTest.kt b/app/src/test/java/com/gotcha/audio/SilenceDetectorTest.ktindex bc2f29a..302f0aa 100644--- a/app/src/test/java/com/gotcha/audio/SilenceDetectorTest.kt+++ b/app/src/test/java/com/gotcha/audio/SilenceDetectorTest.kt@@ -9,20 +9,45 @@ class SilenceDetectorTest {private val start = 1_000_000L+ private fun primeFloor(detector: SilenceDetector, ambientDb: Float = -65f) {+ var now = start+ repeat(12) {+ assertEquals(+ SilenceDetector.Decision.CONTINUE,+ detector.update(windowRmsDb = ambientDb, nowMs = now)+ )+ now += 200+ }+ }+@Testfun `stops after the configured trailing silence once speech was heard`() {val detector = SilenceDetector(silenceTimeoutMs = 3_000L)- detector.update(windowRmsDb = -20f, nowMs = start)+ primeFloor(detector)+ detector.update(windowRmsDb = -20f, nowMs = start + 3_000)+ detector.update(windowRmsDb = -20f, nowMs = start + 3_200)+ assertFalse(detector.speechDetected) // acceptance needs 3 consecutive windows+ detector.update(windowRmsDb = -20f, nowMs = start + 3_400)assertTrue(detector.speechDetected)- assertEquals(SilenceDetector.Decision.CONTINUE, detector.update(windowRmsDb = -65f, nowMs = start + 1_000))- assertEquals(SilenceDetector.Decision.CONTINUE, detector.update(windowRmsDb = -65f, nowMs = start + 2_000))- assertEquals(SilenceDetector.Decision.STOP, detector.update(windowRmsDb = -65f, nowMs = start + 3_000))+ assertEquals(+ SilenceDetector.Decision.CONTINUE,+ detector.update(windowRmsDb = -65f, nowMs = start + 4_000)+ )+ assertEquals(+ SilenceDetector.Decision.CONTINUE,+ detector.update(windowRmsDb = -65f, nowMs = start + 5_000)+ )+ assertEquals(+ SilenceDetector.Decision.STOP,+ detector.update(windowRmsDb = -65f, nowMs = start + 6_400)+ )}@Testfun `keeps listening while speech continues`() {val detector = SilenceDetector(silenceTimeoutMs = 3_000L)- var now = start+ primeFloor(detector)+ var now = start + 3_000repeat(10) {assertEquals(SilenceDetector.Decision.CONTINUE, detector.update(windowRmsDb = -20f, nowMs = now))now += 200@@ -56,6 +81,62 @@ class SilenceDetectorTest {assertFalse("a silently recording user must not trigger STOP", detector.speechDetected)}+ @Test+ fun `single loud transient is rejected - the streak resets before acceptance`() {+ val detector = SilenceDetector(silenceTimeoutMs = 3_000L)+ primeFloor(detector)+ detector.update(windowRmsDb = -20f, nowMs = start + 3_000)+ detector.update(windowRmsDb = -65f, nowMs = start + 3_200)+ assertFalse(detector.speechDetected)+ detector.update(windowRmsDb = -20f, nowMs = start + 3_400)+ detector.update(windowRmsDb = -20f, nowMs = start + 3_600)+ assertFalse("the transient must break the streak", detector.speechDetected)+ }++ @Test+ fun `loud room is adapted to - ambient is not treated as speech`() {+ val detector = SilenceDetector(silenceTimeoutMs = 3_000L)+ // Moderately loud room (~ -45 dBFS), well above the initial threshold+ // of -50. The floor must rise above the ambient so it is never speech.+ primeFloor(detector, ambientDb = -45f)+ repeat(20) { i ->+ assertEquals(+ "ambient must never be accepted as speech",+ SilenceDetector.Decision.CONTINUE,+ detector.update(windowRmsDb = -45f, nowMs = start + 3_000 + i * 200)+ )+ }+ assertFalse(detector.speechDetected)+ }++ @Test+ fun `slow-starting user in a loud room is not cut off`() {+ val detector = SilenceDetector(silenceTimeoutMs = 3_000L)+ primeFloor(detector, ambientDb = -45f)+ // The user pauses several seconds before speaking. The trailing-silence+ // clock must not have started, so no STOP fires during the pause.+ repeat(20) { i ->+ assertEquals(+ SilenceDetector.Decision.CONTINUE,+ detector.update(windowRmsDb = -45f, nowMs = start + 3_000 + i * 200)+ )+ }+ detector.update(windowRmsDb = -20f, nowMs = start + 7_000)+ detector.update(windowRmsDb = -20f, nowMs = start + 7_200)+ detector.update(windowRmsDb = -20f, nowMs = start + 7_400)+ assertTrue(detector.speechDetected)+ // Speech accepted at ~7_400; silence afterwards should not STOP before+ // the 3 s trailing window has elapsed.+ assertEquals(+ SilenceDetector.Decision.CONTINUE,+ detector.update(windowRmsDb = -45f, nowMs = start + 9_000)+ )+ assertEquals(+ SilenceDetector.Decision.STOP,+ detector.update(windowRmsDb = -45f, nowMs = start + 10_400)+ )+ }+@Testfun `rmsDb is near the floor for digital silence and higher for loud samples`() {val silent = ShortArray(100)diff --git a/app/src/test/java/com/gotcha/audio/TtsEngineIsSpeakingTest.kt b/app/src/test/java/com/gotcha/audio/TtsEngineIsSpeakingTest.ktnew file mode 100644index 0000000..053cf11--- /dev/null+++ b/app/src/test/java/com/gotcha/audio/TtsEngineIsSpeakingTest.kt@@ -0,0 +1,48 @@+package com.gotcha.audio++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class TtsEngineIsSpeakingTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private lateinit var ttsEngine: TtsEngine++ @Before+ fun setUp() {+ ttsEngine = TtsEngine(application)+ }++ @Test+ fun `isSpeaking is false when idle and toggles true then false around a speak call`() = runBlocking {+ assertFalse("the StateFlow must start idle", ttsEngine.isSpeaking.value)++ // The NONE provider is a no-op playback (returns false), but it still+ // drives the speaking flag true → false around the call, which is the+ // contract the wake-word self-trigger guard relies on.+ val result = ttsEngine.speak(+ text = "Hello world",+ provider = AudioProvider.NONE+ )+ assertFalse(result)+ assertFalse("the flag must be reset when playback finishes", ttsEngine.isSpeaking.value)+ }++ @Test+ fun `isSpeaking is exposed as a StateFlow`() {+ assertEquals(false, ttsEngine.isSpeaking.value)+ val flow = ttsEngine.isSpeaking+ assertTrue(flow is kotlinx.coroutines.flow.StateFlow<*>)+ }+}diff --git a/app/src/test/java/com/gotcha/service/CallSessionControllerTest.kt b/app/src/test/java/com/gotcha/service/CallSessionControllerTest.ktindex 766b207..4c2a6e7 100644--- a/app/src/test/java/com/gotcha/service/CallSessionControllerTest.kt+++ b/app/src/test/java/com/gotcha/service/CallSessionControllerTest.kt@@ -228,4 +228,25 @@ class CallSessionControllerTest {)assertTrue(failed.contains("could not be captured"))}++ @Test+ fun `hands-free input waits for a pending question and never for a confirmation overlay`() {+ // Call-started announcement done → READY means "awaiting spoken input".+ assertTrue(controller.awaitingHandsFreeInput(CallState.READY, questionPending = false))+ assertTrue(controller.awaitingHandsFreeInput(CallState.READY, questionPending = true))++ // Agent question pending → the gate is held, so the mic opens.+ assertTrue(controller.awaitingHandsFreeInput(CallState.WAITING_USER, questionPending = true))++ // A destructive-action confirmation prompt also sets WAITING_USER, but+ // holds no questionGate — the mic must NOT auto-open (opening it and+ // letting finishTurn fall through to a fresh turn would run two agent+ // turns concurrently while awaitConfirmation is still suspended).+ assertFalse(controller.awaitingHandsFreeInput(CallState.WAITING_USER, questionPending = false))++ // Agent is busy answering / speaking → not awaiting input.+ assertFalse(controller.awaitingHandsFreeInput(CallState.THINKING, questionPending = false))+ assertFalse(controller.awaitingHandsFreeInput(CallState.THINKING, questionPending = true))+ assertFalse(controller.awaitingHandsFreeInput(CallState.SPEAKING, questionPending = true))+ }}diff --git a/app/src/test/java/com/gotcha/service/WakeWordMatcherTest.kt b/app/src/test/java/com/gotcha/service/WakeWordMatcherTest.ktindex 6778f77..473b634 100644--- a/app/src/test/java/com/gotcha/service/WakeWordMatcherTest.kt+++ b/app/src/test/java/com/gotcha/service/WakeWordMatcherTest.kt@@ -34,6 +34,15 @@ class WakeWordMatcherTest {assertEquals(0.43f, huge.threshold(), 0.001f)}+ @Test+ fun `reachable threshold range matches the documented clamp bounds`() {+ // The slider spans sensitivity 0..1, so the reachable threshold range+ // is [0.43, 0.70] — the model card's 0.35 high-sensitivity endpoint is+ // deliberately below the slider floor.+ assertEquals(0.70f, WakeWordMatcher(0f).threshold(), 0.001f)+ assertEquals(0.43f, WakeWordMatcher(1f).threshold(), 0.001f)+ }+@Testfun `single frame above threshold does not fire`() {val matcher = WakeWordMatcher(WakeWordMatcher.DEFAULT_SENSITIVITY)