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.
fix: surface STT/TTS failures during call mode instead of swallowing them
Rishabh Bajpai95be7bf1db95
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0fe0301..f66155d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,28 @@ All notable changes to Gotcha are documented here.## [Unreleased]+### Fixed — Call mode no longer swallows STT/TTS failures (#23)++- **A failed mic tap is now visible.** When `startMic` can't start the+ recognizer (busy, MediaRecorder failure, provider unavailable), the call shows+ "Couldn't start the microphone — tap again to retry." instead of silently doing+ nothing; the mic stays ready for another tap.+- **Hands-free STT failures are no longer mistaken for silence.** The wake-word+ listen loop now tells a real recognition failure apart from "No speech+ detected": genuine errors (network, permissions, recognizer busy, ...) are+ surfaced with the existing error card + vibration and end the call with an+ explanation, while silence keeps its quiet retry-and-auto-end behaviour. Only+ silence counts toward the auto-end strikes.+- **Tool-progress narration TTS failures surface too.** A failed narration shows+ the shared "Couldn't play voice audio — check your Text-to-Speech settings."+ card once per call (repeats are logged), instead of being fire-and-forget.+- **In-call error line.** The two floating call buttons now show a transient+ error line above them, so an in-call error is visible right where the user's+ eyes are even when the overlay card is off-screen. The overlay card remains+ the persistent mid-call surface.+- Hands-free loop also hands control back to the pre-listen state after a blank+ listen, so retry (and answering an agent question in place) works as intended.+### Fixed — Malformed tool call no longer bricks the chat (#13)- **A tool call with invalid `arguments` JSON can no longer poison a chat.** Whendiff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.ktindex 32fb909..1fe4cc3 100644--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt@@ -609,6 +609,23 @@ class SttEngine(/** Hard cap on a single hands-free VAD recording (90 s). */private const val MAX_VAD_RECORDING_MS = 90_000L++ /**+ * True when [error] is the benign "the user stayed quiet" outcome rather+ * than a real STT failure (network, permissions, recognizer busy, ...).+ * A hands-free listen loop must treat silence as a quiet retry signal and+ * surface genuine failures to the user instead of silently dying.+ */+ fun isBenignSttError(error: Throwable?): Boolean {+ if (error == null) return true+ val message = error.message ?: return false+ if (message == NO_SPEECH_DETECTED) return true+ val code = message.removePrefix(SPEECH_FAILED_PREFIX).toIntOrNull()+ return code != null && SttOutcome.Error(code).isBenign+ }++ private const val NO_SPEECH_DETECTED = "No speech detected"+ private const val SPEECH_FAILED_PREFIX = "Speech recognition failed: "}}diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 1229c9f..5ad5012 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -204,7 +204,13 @@ class AssistiveBallService : Service() {isCallActive = { callController.isActive() }}- callController.onError = { overlay.showError(it) }+ callController.onError = { message ->+ // The overlay card is the persistent mid-call surface; the call+ // window also shows a transient line so the error is visible right+ // where the user's eyes are, even if the card is off-screen.+ overlay.showError(message)+ chatWindow.showError(message)+ }callController.onActionRingColor = { color -> chatWindow.setActionRingColor(color) }callController.onCaptureChrome = { hide ->if (hide) {diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 7ed034e..8bfee52 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -2,6 +2,7 @@ package com.gotcha.serviceimport android.content.Contextimport android.content.pm.PackageManager+import android.util.Logimport androidx.core.content.ContextCompatimport com.gotcha.agent.AgentEngineimport com.gotcha.agent.AgentEvents@@ -105,6 +106,13 @@ class CallSessionController(/** Set only for a call started by the wake word. */private var autoEndOnReply = false+ /**+ * True once a narration TTS failure has been surfaced in the current call,+ * so a broken Text-to-Speech setup shows one error card instead of a fresh+ * one for every narrated tool step (repeats are only logged).+ */+ private var narrationErrorReported = false+/*** Hands-free mode for wake-word calls: the mic opens by itself once the* call-started announcement is done and a VAD stops it after ~3 s of@@ -202,6 +210,7 @@ class CallSessionController(newEngine.promptCacheKey = CALL_PROMPT_CACHE_KEYnewEngine.setupWorkingDir()engine = newEngine+ narrationErrorReported = false_state.value = CallState.STARTINGscope.launch {val language = Language.fromLabel(s.preferredLanguage)@@ -237,6 +246,10 @@ class CallSessionController(var silentStrikes = 0while (isActive && handsFree && [email protected]()) {if (awaitHandsFreeInput()) {+ // Remember why the mic opened so a blank listen can hand+ // control back to the same place (fresh turn vs. a pending+ // agent question) and the loop can listen again.+ val listeningFrom = _state.value_state.value = CallState.LISTENINGval s = settingsRepository.load()val outcome = sttEngine.listenForUtterance(@@ -250,28 +263,39 @@ class CallSessionController(})val text = outcome.getOrNull().orEmpty()- if (text.isBlank()) {- // Silence or a transient STT error is normal while the- // user is quiet; retry a couple of times, then end.+ if (text.isNotBlank()) {+ silentStrikes = 0+ if (listeningFrom == CallState.WAITING_USER) {+ // The agent is awaiting an answer: complete its gate in+ // place without touching the running turn job.+ finishTurn(text)+ } else {+ // Fresh turn: run it in its own job so this loop stays+ // free to re-listen if the agent asks a question.+ questionGate = null // drop any stale gate from a timed-out question+ currentTurnJob?.cancel()+ currentTurnJob = scope.launch { finishTurn(text) }+ }+ } else {+ // Distinguish a real STT failure from plain silence. Only+ // silence counts toward the auto-end strikes and stays+ // quiet; genuine failures are surfaced and end the call+ // with an explanation instead of looking like the user+ // never spoke.+ val error = outcome.exceptionOrNull()+ if (error != null && !SttEngine.isBenignSttError(error)) {+ reportError(friendlyAgentError(error as? Exception ?: Exception(error.message)))+ endCall()+ break+ }silentStrikes+++ _state.value = listeningFromif (silentStrikes >= HANDS_FREE_SILENT_STRIKES) {endCall()break}continue}- silentStrikes = 0- if (_state.value == CallState.WAITING_USER) {- // The agent is awaiting an answer: complete its gate in- // place without touching the running turn job.- finishTurn(text)- } else {- // Fresh turn: run it in its own job so this loop stays- // free to re-listen if the agent asks a question.- questionGate = null // drop any stale gate from a timed-out question- currentTurnJob?.cancel()- currentTurnJob = scope.launch { finishTurn(text) }- }} else {break}@@ -389,9 +413,22 @@ class CallSessionController()if (started) {_state.value = CallState.LISTENING+ } else {+ // The recognizer refused to start (busy, MediaRecorder failure,+ // provider unavailable). Tell the user instead of swallowing the+ // tap; the state stays put so another tap can retry.+ onMicStartFailed()}}+ /**+ * Failure path for a mic tap: surface a short message and leave the state+ * untouched (still [READY] / [WAITING_USER]) so the user can tap again.+ */+ internal fun onMicStartFailed() {+ reportError("Couldn't start the microphone — tap again to retry.")+ }+/** Stop the mic and send the recording for transcription + agent processing. */fun stopMic() {if (handsFree) return@@ -789,7 +826,22 @@ class CallSessionController(} else {""}- ttsEngine.speak(text, s.ttsProvider, s.ttsApiModel, voice, language)+ val spoke = ttsEngine.speak(text, s.ttsProvider, s.ttsApiModel, voice, language)+ if (!spoke) onNarrationTtsFailed()+ }+ }++ /**+ * Narration is auxiliary, so a broken TTS setup must not spam the user: the+ * first failure in a call is surfaced like every other TTS failure and any+ * repeats are logged only.+ */+ internal fun onNarrationTtsFailed() {+ if (!narrationErrorReported) {+ narrationErrorReported = true+ reportError("Couldn't play voice audio — check your Text-to-Speech settings.")+ } else {+ Log.w(TAG, "TTS narration failed during a call (already reported once)")}}@@ -822,6 +874,7 @@ class CallSessionController(private fun triggerErrorVibration() = CompletionFeedback.error(appContext)companion object {+ private const val TAG = "CallSessionController"private const val NARRATION_THROTTLE_MS = 3_000Lprivate const val CONFIRM_TIMEOUT_MS = 90_000Lval CALLS_WORKING_ROOT: String get() = com.gotcha.data.GotchaStorage.callsRoot().absolutePathdiff --git a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt b/app/src/main/java/com/gotcha/ui/CallChatWindow.ktindex 6493fcb..55a992c 100644--- a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt+++ b/app/src/main/java/com/gotcha/ui/CallChatWindow.kt@@ -58,6 +58,16 @@ class CallChatWindow(context: Context) {private var endBtn: View? = nullprivate var endWrapper: View? = null+ /** The horizontal button row (action + end), kept so touch hit-tests don't+ * have to walk the root's children (the error label lives above it). */+ private var buttonsRow: LinearLayout? = null++ /** Transient error line shown above the buttons while an in-call error is fresh. */+ private var errorLabel: TextView? = null+ private val errorLabelHideRunnable = Runnable {+ errorLabel?.visibility = View.GONE+ }+// Ring as a separate overlay window (not inside the layout)private var ringOverlayView: View? = nullprivate var ringOverlayAnimator: ValueAnimator? = null@@ -120,6 +130,7 @@ class CallChatWindow(context: Context) {fun hide() {mainHandler.post {mainHandler.removeCallbacks(endLongPressRunnable)+ mainHandler.removeCallbacks(errorLabelHideRunnable)rotationWatcher.stop()stopBreathe()swapAnimator?.cancel()@@ -134,6 +145,8 @@ class CallChatWindow(context: Context) {actionBtn = nullendBtn = nullendWrapper = null+ buttonsRow = null+ errorLabel = null}}@@ -166,6 +179,23 @@ class CallChatWindow(context: Context) {}}+ /**+ * Minimal in-call text error surface: a transient line above the buttons so+ * a failure stays visible even if the user isn't looking at the overlay+ * card. Auto-hides after [ERROR_LABEL_SHOW_MS]. No-op when the window isn't+ * showing (e.g. start-call failures that fire before the buttons appear).+ */+ fun showError(message: String) {+ mainHandler.post {+ if (rootView == null) return@post+ val label = errorLabel ?: return@post+ mainHandler.removeCallbacks(errorLabelHideRunnable)+ label.text = message+ label.visibility = View.VISIBLE+ mainHandler.postDelayed(errorLabelHideRunnable, ERROR_LABEL_SHOW_MS)+ }+ }+// ---- Rendering ----/** (emoji, glass tint) for the action button in a given call state. */@@ -353,8 +383,30 @@ class CallChatWindow(context: Context) {actionBtn?.let { row.addView(it) }(actionBtn?.layoutParams as? LinearLayout.LayoutParams)?.setMargins(0, 0, (6 * density).toInt(), 0)row.addView(wrapper)+ buttonsRow = row- return row+ errorLabel = TextView(appContext).apply {+ visibility = View.GONE+ textSize = 12f+ gravity = Gravity.CENTER+ setTextColor(Color.WHITE)+ maxWidth = dp(240f)+ setPadding(dp(12f), dp(6f), dp(12f), dp(6f))+ background = GradientDrawable().apply {+ shape = GradientDrawable.RECTANGLE+ cornerRadius = 8f * density+ setColor(Color.parseColor("#CC1F1F1F"))+ }+ }++ // Vertical wrapper: the transient error label above the button row. The+ // touch listener stays on [row] so hit-testing and drag co-ordinates are+ // unchanged — the label is purely informational and never interactive.+ return LinearLayout(appContext).apply {+ orientation = LinearLayout.VERTICAL+ errorLabel?.let { addView(it) }+ addView(row)+ }}private fun glassButton(emoji: String, size: Int, isEnd: Boolean): View {@@ -692,10 +744,9 @@ class CallChatWindow(context: Context) {}private fun handleActionUp(x: Float, y: Float) {- val root = rootView as? LinearLayout ?: return- val count = root.childCount- for (i in 0 until count) {- val child = root.getChildAt(i)+ val row = buttonsRow ?: return+ for (i in 0 until row.childCount) {+ val child = row.getChildAt(i)if (child.visibility != View.VISIBLE) continueif (x >= child.left && x <= child.right &&y >= child.top && y <= child.bottom@@ -879,6 +930,9 @@ class CallChatWindow(context: Context) {const val BTN_SIZE_DP = 44const val END_LONG_PRESS_MS = 2000L+ /** How long the transient in-call error line stays above the buttons. */+ const val ERROR_LABEL_SHOW_MS = 4000L+// Glass tints per action state. Three of these are semantic and stay// fixed: amber, coral and red have to keep meaning the same thing in// every theme, the way the context meter's warning colour does. Onlydiff --git a/app/src/test/java/com/gotcha/audio/SttEngineTest.kt b/app/src/test/java/com/gotcha/audio/SttEngineTest.ktnew file mode 100644index 0000000..53ee66e--- /dev/null+++ b/app/src/test/java/com/gotcha/audio/SttEngineTest.kt@@ -0,0 +1,56 @@+package com.gotcha.audio++import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import java.io.IOException++/**+ * Covers [SttEngine.isBenignSttError] — the classification a hands-free listen+ * loop uses to tell "the user stayed quiet" apart from a genuine STT failure.+ */+class SttEngineTest {++ // Android SpeechRecognizer.ERROR_* values (kept as literals so this pure+ // unit test never touches the android.jar stubs).+ private val errorSpeechTimeout = 6+ private val errorNoMatch = 7+ private val errorClient = 5+ private val errorRecognizerBusy = 8+ private val errorInsufficientPermissions = 9++ @Test+ fun `a blank success result is benign silence`() {+ assertTrue(SttEngine.isBenignSttError(null))+ }++ @Test+ fun `no speech detected is benign silence`() {+ assertTrue(SttEngine.isBenignSttError(Exception("No speech detected")))+ }++ @Test+ fun `recognizer no-match and speech-timeout errors are benign silence`() {+ assertTrue(SttEngine.isBenignSttError(Exception("Speech recognition failed: $errorSpeechTimeout")))+ assertTrue(SttEngine.isBenignSttError(Exception("Speech recognition failed: $errorNoMatch")))+ }++ @Test+ fun `real recognizer errors are not benign`() {+ assertFalse(SttEngine.isBenignSttError(Exception("Speech recognition failed: $errorClient")))+ assertFalse(SttEngine.isBenignSttError(Exception("Speech recognition failed: $errorRecognizerBusy")))+ assertFalse(SttEngine.isBenignSttError(Exception("Speech recognition failed: $errorInsufficientPermissions")))+ }++ @Test+ fun `api and network failures are not benign`() {+ assertFalse(SttEngine.isBenignSttError(Exception("API not configured")))+ assertFalse(SttEngine.isBenignSttError(IOException("Network problem: could not reach the server")))+ assertFalse(SttEngine.isBenignSttError(Exception("HTTP 401 Authentication failed")))+ }++ @Test+ fun `an error without a message is not benign`() {+ assertFalse(SttEngine.isBenignSttError(Exception()))+ }+}diff --git a/app/src/test/java/com/gotcha/service/CallSessionControllerTest.kt b/app/src/test/java/com/gotcha/service/CallSessionControllerTest.ktindex 4c2a6e7..93feb1f 100644--- a/app/src/test/java/com/gotcha/service/CallSessionControllerTest.kt+++ b/app/src/test/java/com/gotcha/service/CallSessionControllerTest.kt@@ -2,6 +2,7 @@ package com.gotcha.serviceimport android.app.Applicationimport androidx.test.core.app.ApplicationProvider+import com.gotcha.agent.MessageKindimport com.gotcha.audio.AudioProviderimport com.gotcha.audio.SttEngineimport com.gotcha.audio.TtsEngine@@ -12,6 +13,7 @@ import com.gotcha.testsupport.FakeAndroidKeyStoreimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.SupervisorJob+import org.junit.Assert.assertEqualsimport org.junit.Assert.assertFalseimport org.junit.Assert.assertTrueimport org.junit.Before@@ -249,4 +251,43 @@ class CallSessionControllerTest {assertFalse(controller.awaitingHandsFreeInput(CallState.THINKING, questionPending = true))assertFalse(controller.awaitingHandsFreeInput(CallState.SPEAKING, questionPending = true))}++ @Test+ fun `mic start failure surfaces an error and records it in the transcript`() {+ val errors = mutableListOf<String>()+ controller.onError = { errors.add(it) }++ controller.onMicStartFailed()++ assertEquals(1, errors.size)+ assertTrue(+ "expected a mic-start message but got: ${errors.firstOrNull()}",+ errors.firstOrNull()?.contains("Couldn't start the microphone") == true+ )+ assertTrue(+ "mic-start failure must be recorded as an error transcript entry",+ controller.transcript.value.any {+ it.kind == MessageKind.ERROR && it.text.contains("Couldn't start the microphone")+ }+ )+ }++ @Test+ fun `narration tts failure is reported once per call, repeats are not surfaced`() {+ val errors = mutableListOf<String>()+ controller.onError = { errors.add(it) }++ controller.onNarrationTtsFailed()+ controller.onNarrationTtsFailed()++ assertEquals(+ "a broken narration TTS must not spam the user with repeated cards",+ 1,+ errors.size+ )+ assertTrue(+ "expected the shared TTS wording but got: ${errors.firstOrNull()}",+ errors.firstOrNull()?.contains("check your Text-to-Speech settings") == true+ )+ }}