Skip to content

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.

feat(wake-word): add hands-free calls with VAD mic auto-stop

Rishabh Bajpai7d5aa4c5ef56
diff --git a/app/src/main/java/com/gotcha/agent/ScreenSnapshot.kt b/app/src/main/java/com/gotcha/agent/ScreenSnapshot.kt
index cf9498b..d9a8cc2 100644
--- a/app/src/main/java/com/gotcha/agent/ScreenSnapshot.kt
+++ b/app/src/main/java/com/gotcha/agent/ScreenSnapshot.kt
@@ -1,6 +1,7 @@
package com.gotcha.agent
import android.graphics.Bitmap
+import android.graphics.BitmapFactory
import com.gotcha.service.GotchaAccessibilityService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
@@ -53,4 +54,62 @@ object ScreenSnapshot {
val lines = service.dumpScreenText(limit)
return if (lines.isEmpty()) null else lines.joinToString("\n") { "- $it" }
}
+
+ /**
+ * True when the JPEG base64 is essentially a solid black frame — the usual
+ * result of capturing while the screen is off or blank. A black screenshot
+ * carries no information for the model (and can look like a "vision" input
+ * that never resolves), so callers should drop it. A dark app with content
+ * has enough bright pixels / variance to fail this check.
+ *
+ * The frame is decoded as a small thumbnail ([SAMPLE_SIZE]) rather than at
+ * full resolution — the luminance statistics are what matter, not the
+ * pixels — so an off-screen capture costs ~1/64 of the memory.
+ */
+ fun isMostlyBlack(jpegBase64: String, blackRatio: Float = 0.99f): Boolean {
+ val bytes = try {
+ android.util.Base64.decode(jpegBase64, android.util.Base64.DEFAULT)
+ } catch (_: Exception) {
+ return false
+ }
+ val options = BitmapFactory.Options().apply { inSampleSize = SAMPLE_SIZE }
+ val bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) ?: return false
+ try {
+ return classifyBlackness(bitmap, blackRatio)
+ } finally {
+ bitmap.recycle()
+ }
+ }
+
+ /**
+ * Samples [bitmap] and reports whether it is essentially solid black. Kept
+ * separate from [isMostlyBlack] so the classification logic is testable on
+ * an in-memory bitmap without going through a JPEG decode.
+ */
+ internal fun classifyBlackness(bitmap: Bitmap, blackRatio: Float = 0.99f): Boolean {
+ val width = bitmap.width
+ val height = bitmap.height
+ if (width <= 0 || height <= 0) return false
+ var sampled = 0
+ var dark = 0
+ var sumLuma = 0.0
+ for (y in 0 until height) {
+ for (x in 0 until width) {
+ val pixel = bitmap.getPixel(x, y)
+ val r = (pixel shr 16) and 0xFF
+ val g = (pixel shr 8) and 0xFF
+ val b = pixel and 0xFF
+ val luma = 0.2126 * r + 0.7152 * g + 0.0722 * b
+ sumLuma += luma
+ if (luma < 8.0) dark++
+ sampled++
+ }
+ }
+ if (sampled == 0) return false
+ val meanLuma = sumLuma / sampled
+ val darkRatio = dark.toDouble() / sampled
+ return meanLuma < 10.0 && darkRatio >= blackRatio
+ }
+
+ private const val SAMPLE_SIZE = 8
}
diff --git a/app/src/main/java/com/gotcha/audio/AudioApi.kt b/app/src/main/java/com/gotcha/audio/AudioApi.kt
index 0ce5025..4bf0ba5 100644
--- a/app/src/main/java/com/gotcha/audio/AudioApi.kt
+++ b/app/src/main/java/com/gotcha/audio/AudioApi.kt
@@ -124,7 +124,12 @@ class AudioApi(
}
/** Speech-to-text: upload audio and return transcription. */
- fun transcribe(audioFile: File, model: String, language: String? = null): Result<String> = runCatching {
+ fun transcribe(
+ audioFile: File,
+ model: String,
+ language: String? = null,
+ contentType: String = "audio/m4a"
+ ): Result<String> = runCatching {
val url = "${baseUrl.trimEnd('/')}/audio/transcriptions"
val boundary = "Boundary-${System.currentTimeMillis()}"
val extraFields = mutableMapOf("model" to model)
@@ -135,7 +140,7 @@ class AudioApi(
boundary,
audioFile,
"file",
- "audio/m4a",
+ contentType,
extraFields
)
val request = Request.Builder()
diff --git a/app/src/main/java/com/gotcha/audio/SilenceDetector.kt b/app/src/main/java/com/gotcha/audio/SilenceDetector.kt
new file mode 100644
index 0000000..33d2f95
--- /dev/null
+++ b/app/src/main/java/com/gotcha/audio/SilenceDetector.kt
@@ -0,0 +1,72 @@
+package com.gotcha.audio
+
+/**
+ * A small 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
+ * [noSpeechTimeoutMs].
+ */
+internal class SilenceDetector(
+ private val silenceTimeoutMs: Long,
+ private val noSpeechTimeoutMs: Long = NO_SPEECH_TIMEOUT_DEFAULT_MS,
+ private val speechMarginDb: Float = SPEECH_MARGIN_DB,
+ private val absoluteFloorDb: Float = ABSOLUTE_FLOOR_DB
+) {
+ var speechDetected: Boolean = false
+ private set
+
+ private var noiseFloorDb = INITIAL_NOISE_FLOOR_DB
+ private var startMs = -1L
+ private var lastSpeechAtMs = -1L
+
+ /** The RMS level (dBFS) a window must exceed to count as speech. */
+ val thresholdDb: Float
+ get() = maxOf(absoluteFloorDb, noiseFloorDb + speechMarginDb)
+
+ fun update(windowRmsDb: Float, nowMs: Long): Decision {
+ if (startMs < 0) startMs = nowMs
+ if (windowRmsDb > thresholdDb) {
+ speechDetected = true
+ lastSpeechAtMs = nowMs
+ } else {
+ // Slide the floor toward whatever is quieter than speech.
+ noiseFloorDb = 0.95f * noiseFloorDb + 0.05f * windowRmsDb
+ }
+ if (speechDetected && nowMs - lastSpeechAtMs >= silenceTimeoutMs) {
+ return Decision.STOP
+ }
+ if (!speechDetected && nowMs - startMs >= noSpeechTimeoutMs) {
+ return Decision.STOP_NO_SPEECH
+ }
+ return Decision.CONTINUE
+ }
+
+ enum class Decision { CONTINUE, STOP, STOP_NO_SPEECH }
+
+ companion object {
+ private const val NO_SPEECH_TIMEOUT_DEFAULT_MS = 15_000L
+ private const val SPEECH_MARGIN_DB = 10f
+ private const val ABSOLUTE_FLOOR_DB = -50f
+ private const val INITIAL_NOISE_FLOOR_DB = -60f
+
+ /** 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_DB
+ var sum = 0L
+ for (i in 0 until count) {
+ val sample = samples[i].toInt()
+ sum += sample.toLong() * sample
+ }
+ val rms = kotlin.math.sqrt(sum.toDouble() / count)
+ if (rms <= 0.0) return ABSOLUTE_FLOOR_DB
+ val db = 20.0 * kotlin.math.log10(rms / 32768.0)
+ return maxOf(db, ABSOLUTE_FLOOR_DB.toDouble()).toFloat()
+ }
+ }
+}
diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.kt
index f0ffe0e..5eeb70b 100644
--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt
+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt
@@ -1,8 +1,11 @@
package com.gotcha.audio
+import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
+import android.media.AudioFormat
import android.media.AudioManager
+import android.media.AudioRecord
import android.media.MediaRecorder
import android.os.Bundle
import android.os.Handler
@@ -16,6 +19,7 @@ import com.gotcha.util.HumanReadableError
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
+import java.io.ByteArrayOutputStream
import java.io.File
/** Result of a single hands-free listening turn ([SttEngine.listenOnceAndroid]). */
@@ -51,6 +55,10 @@ class SttEngine(
private var currentRecorder: MediaRecorder? = null
private var currentAudioFile: File? = null
+ /** Set by [cancelListening] to abort an in-flight VAD (hands-free) recording. */
+ @Volatile
+ private var vadStopRequested = false
+
// Audio muting state
private val audioManager = context.getSystemService(Context.AUDIO_SERVICE) as android.media.AudioManager
private var isMutedForRestart = false
@@ -132,20 +140,129 @@ class SttEngine(
suspend fun transcribeApi(
audioFile: File,
model: String,
- language: String = ""
+ language: String = "",
+ contentType: String = "audio/m4a"
): Result<String> = withContext(Dispatchers.IO) {
val api = audioApi ?: return@withContext Result.failure(Exception("API not configured"))
try {
api.transcribe(
audioFile = audioFile,
model = model,
- language = language
+ language = language,
+ contentType = contentType
)
} finally {
audioFile.delete()
}
}
+ /**
+ * Listen for a single hands-free utterance and return its transcript.
+ *
+ * Unlike the push-to-talk path ([startListening] / [stopListeningAndTranscribe]),
+ * this ends on its own once the user has finished speaking:
+ *
+ * - Android provider: the platform's [SpeechRecognizer] endpoints on end of
+ * speech (with a best-effort silence hint of [silenceTimeoutMs]).
+ * - API provider: raw PCM is captured via [AudioRecord] and a local
+ * [SilenceDetector] stops the recording after [silenceTimeoutMs] of
+ * trailing silence; the resulting WAV is transcribed through the API.
+ */
+ suspend fun listenForUtterance(
+ provider: AudioProvider,
+ model: String,
+ language: Language = Language.ENGLISH,
+ silenceTimeoutMs: Long
+ ): Result<String> = when {
+ provider == AudioProvider.ANDROID -> {
+ when (val outcome = listenOnceAndroid(language, silenceTimeoutMs)) {
+ is SttOutcome.Text ->
+ if (outcome.text.isNotBlank()) {
+ Result.success(outcome.text)
+ } else {
+ Result.failure(Exception("No speech detected"))
+ }
+ is SttOutcome.Error -> Result.failure(Exception("Speech recognition failed: ${outcome.code}"))
+ }
+ }
+ provider.isApiBased() -> withContext(Dispatchers.IO) {
+ val wav = recordPcmWithVad(silenceTimeoutMs)
+ if (wav == null) {
+ Result.failure(Exception("No speech detected"))
+ } else {
+ transcribeApi(wav, model, language.iso639, contentType = "audio/wav")
+ }
+ }
+ else -> Result.failure(Exception("STT not configured"))
+ }
+
+ /**
+ * Records up to [silenceTimeoutMs] of trailing silence after speech using
+ * [AudioRecord] (16 kHz mono PCM-16) and returns a WAV file, or null when
+ * the user never spoke. Aborts when [cancelListening] is called.
+ */
+ @SuppressLint("MissingPermission")
+ private fun recordPcmWithVad(silenceTimeoutMs: Long): File? {
+ val sampleRate = 16_000
+ val windowShorts = 3_200 // 200 ms windows
+ val minBuffer = AudioRecord.getMinBufferSize(
+ sampleRate,
+ AudioFormat.CHANNEL_IN_MONO,
+ AudioFormat.ENCODING_PCM_16BIT
+ )
+ val recorder = AudioRecord(
+ MediaRecorder.AudioSource.VOICE_RECOGNITION,
+ sampleRate,
+ AudioFormat.CHANNEL_IN_MONO,
+ AudioFormat.ENCODING_PCM_16BIT,
+ maxOf(minBuffer, windowShorts * 2)
+ )
+ if (recorder.state != AudioRecord.STATE_INITIALIZED) return null
+
+ vadStopRequested = false
+ val detector = SilenceDetector(silenceTimeoutMs)
+ val shortBuf = ShortArray(windowShorts)
+ val byteBuf = ByteArray(windowShorts * 2)
+ val pcm = ByteArrayOutputStream()
+ val startMs = System.currentTimeMillis()
+ var result: File? = null
+ try {
+ recorder.startRecording()
+ while (!vadStopRequested) {
+ val count = recorder.read(shortBuf, 0, shortBuf.size)
+ if (count < 0) break
+ if (count == 0) continue
+ for (i in 0 until count) {
+ val sample = shortBuf[i].toInt()
+ byteBuf[i * 2] = (sample and 0xFF).toByte()
+ byteBuf[i * 2 + 1] = ((sample shr 8) and 0xFF).toByte()
+ }
+ pcm.write(byteBuf, 0, count * 2)
+ val now = System.currentTimeMillis()
+ val decision = detector.update(SilenceDetector.rmsDb(shortBuf, count), now)
+ if (decision != SilenceDetector.Decision.CONTINUE ||
+ now - startMs > MAX_VAD_RECORDING_MS
+ ) {
+ break
+ }
+ }
+ if (detector.speechDetected && pcm.size() > 0) {
+ result = writeWav(context.cacheDir, pcm.toByteArray(), sampleRate)
+ }
+ } catch (_: Exception) {
+ result = null
+ } finally {
+ try {
+ recorder.stop()
+ } catch (_: Exception) {
+ // Never started or already stopped.
+ }
+ recorder.release()
+ vadStopRequested = false
+ }
+ return result
+ }
+
// ---- Android STT (SpeechRecognizer) ----
/** Start Android SpeechRecognizer. User speaks, then calls stopAndroidListening(). */
@@ -322,7 +439,10 @@ class SttEngine(
* its own (no stop call needed) and this returns the transcript or the
* SpeechRecognizer error code. Used by the voice-call loop.
*/
- suspend fun listenOnceAndroid(language: Language = Language.ENGLISH): SttOutcome {
+ suspend fun listenOnceAndroid(
+ language: Language = Language.ENGLISH,
+ silenceTimeoutMs: Long = 2000L
+ ): SttOutcome {
if (currentRecognizer != null || onceGate != null) {
return SttOutcome.Error(SpeechRecognizer.ERROR_RECOGNIZER_BUSY)
}
@@ -361,6 +481,8 @@ class SttEngine(
val intent = Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH).apply {
putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM)
putExtra(RecognizerIntent.EXTRA_LANGUAGE, language.bcp47)
+ // Best-effort end-of-speech hint; the platform may ignore it.
+ putExtra(RecognizerIntent.EXTRA_SPEECH_INPUT_COMPLETE_SILENCE_LENGTH_MILLIS, silenceTimeoutMs)
}
recognizer.startListening(intent)
} catch (_: Exception) {
@@ -438,6 +560,7 @@ class SttEngine(
}
}
provider.isApiBased() -> {
+ vadStopRequested = true
try {
currentRecorder?.apply {
stop()
@@ -480,5 +603,60 @@ class SttEngine(
/** Synthetic error code: listening was cancelled by pause/end, not by the recognizer. */
const val ERROR_CANCELLED = -100
+
+ /** Hard cap on a single hands-free VAD recording (90 s). */
+ private const val MAX_VAD_RECORDING_MS = 90_000L
+ }
+}
+
+private fun writeWav(cacheDir: File, pcm: ByteArray, sampleRate: Int): File {
+ // UUID suffix so two recordings created in the same millisecond never collide.
+ val file = File(
+ cacheDir,
+ "stt_hands_free_${System.currentTimeMillis()}_${java.util.UUID.randomUUID().toString().take(8)}.wav"
+ )
+ file.outputStream().use { out ->
+ val dataSize = pcm.size
+ val header = ByteArray(44)
+ header[0] = 'R'.code.toByte()
+ header[1] = 'I'.code.toByte()
+ header[2] = 'F'.code.toByte()
+ header[3] = 'F'.code.toByte()
+ writeIntLittleEndian(header, 4, 36 + dataSize)
+ header[8] = 'W'.code.toByte()
+ header[9] = 'A'.code.toByte()
+ header[10] = 'V'.code.toByte()
+ header[11] = 'E'.code.toByte()
+ header[12] = 'f'.code.toByte()
+ header[13] = 'm'.code.toByte()
+ header[14] = 't'.code.toByte()
+ header[15] = ' '.code.toByte()
+ writeIntLittleEndian(header, 16, 16)
+ writeShortLittleEndian(header, 20, 1)
+ writeShortLittleEndian(header, 22, 1)
+ writeIntLittleEndian(header, 24, sampleRate)
+ writeIntLittleEndian(header, 28, sampleRate * 2)
+ writeShortLittleEndian(header, 32, 2)
+ writeShortLittleEndian(header, 34, 16)
+ header[36] = 'd'.code.toByte()
+ header[37] = 'a'.code.toByte()
+ header[38] = 't'.code.toByte()
+ header[39] = 'a'.code.toByte()
+ writeIntLittleEndian(header, 40, dataSize)
+ out.write(header)
+ out.write(pcm)
}
+ return file
+}
+
+private fun writeIntLittleEndian(bytes: ByteArray, offset: Int, value: Int) {
+ bytes[offset] = (value and 0xFF).toByte()
+ bytes[offset + 1] = ((value shr 8) and 0xFF).toByte()
+ bytes[offset + 2] = ((value shr 16) and 0xFF).toByte()
+ bytes[offset + 3] = ((value shr 24) and 0xFF).toByte()
+}
+
+private fun writeShortLittleEndian(bytes: ByteArray, offset: Int, value: Int) {
+ bytes[offset] = (value and 0xFF).toByte()
+ bytes[offset + 1] = ((value shr 8) and 0xFF).toByte()
}
diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.kt
index 691c33d..31495cb 100644
--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt
+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt
@@ -31,10 +31,12 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.serialization.json.JsonPrimitive
@@ -101,6 +103,19 @@ class CallSessionController(
/** Set only for a call started by the wake word. */
private var autoEndOnReply = 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
+ * silence. Normal (long-press) calls leave this false and keep PTT.
+ * Written on the main thread, read by the [handsFreeAutoListen] loop on a
+ * background dispatcher — volatile so both observe the same value.
+ */
+ @Volatile
+ private var handsFree = false
+
+ /** Drives hands-free listening; null when no hands-free call is active. */
+ private var handsFreeAutoListen: Job? = null
+
private val _state = MutableStateFlow(CallState.IDLE)
val state: StateFlow<CallState> = _state.asStateFlow()
@@ -184,9 +199,84 @@ class CallSessionController(
}
fun startWakeWordCall(): Boolean {
+ handsFree = true
autoEndOnReply = true
- if (startCall()) return true
- autoEndOnReply = false
+ if (!startCall()) {
+ handsFree = false
+ autoEndOnReply = false
+ return false
+ }
+ startHandsFreeAutoListen()
+ return true
+ }
+
+ /**
+ * Auto-opens the mic whenever the agent is waiting for input (after the
+ * call-started announcement, or when it asks a question) and stops it once
+ * the user has finished speaking. Every decision past the mic stop reuses
+ * the exact same downstream as push-to-talk ([finishTurn]).
+ */
+ private fun startHandsFreeAutoListen() {
+ handsFreeAutoListen?.cancel()
+ handsFreeAutoListen = scope.launch {
+ var silentStrikes = 0
+ while (isActive && handsFree && [email protected]()) {
+ if (awaitHandsFreeInput()) {
+ _state.value = CallState.LISTENING
+ val s = settingsRepository.load()
+ val outcome = sttEngine.listenForUtterance(
+ provider = s.sttProvider,
+ model = s.sttApiModel,
+ language = currentLanguage(),
+ silenceTimeoutMs = if (s.sttProvider == AudioProvider.ANDROID) {
+ ANDROID_SILENCE_MS
+ } else {
+ HANDS_FREE_SILENCE_MS
+ }
+ )
+ 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.
+ silentStrikes++
+ if (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
+ }
+ }
+ handsFreeAutoListen = null
+ }
+ }
+
+ /**
+ * Suspends until the agent is waiting for spoken input (call-started
+ * announcement done, or a question pending) and the app's own TTS has
+ * stopped. Returns false when the hands-free call has ended.
+ */
+ 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
+ delay(100)
+ }
return false
}
@@ -214,6 +304,9 @@ class CallSessionController(
/** End the call and delete its chat session + working directory. */
fun endCall() {
+ handsFree = false
+ handsFreeAutoListen?.cancel()
+ handsFreeAutoListen = null
autoEndOnReply = false
val endingEngine = engine ?: return
_state.value = CallState.ENDING
@@ -252,8 +345,10 @@ class CallSessionController(
/**
* Start the mic. User must tap [stopMic] to stop recording and send.
* Works from [READY] (normal turn) or [WAITING_USER] (answering a question).
+ * No-op during a hands-free wake-word call, which owns the mic.
*/
fun startMic() {
+ if (handsFree) return
val current = _state.value
if (current != CallState.READY && current != CallState.WAITING_USER) return
val s = settingsRepository.load()
@@ -269,6 +364,7 @@ class CallSessionController(
/** Stop the mic and send the recording for transcription + agent processing. */
fun stopMic() {
+ if (handsFree) return
if (_state.value != CallState.LISTENING) return
currentTurnJob?.cancel()
currentTurnJob = scope.launch {
@@ -290,55 +386,68 @@ class CallSessionController(
_state.value = CallState.READY
return@launch
}
+ finishTurn(text)
+ }
+ }
- // API STT (Whisper-class) output is already punctuated and cased —
- // cleanText is redundant there and would cost an extra LLM round-trip.
- val cleanedText = if (s.sttProvider == AudioProvider.ANDROID) {
- val llmClient = buildClient()
- val navModel = s.navigatorModel.ifEmpty { s.model }
- llmClient?.cleanText(text, navModel, language) ?: text
- } else {
- text
- }
+ /**
+ * The shared turn body: clean the transcript, record it, answer an
+ * in-flight agent question or run a full agent turn, speak the reply, and
+ * apply the auto-end rule. Used by both push-to-talk ([stopMic]) and the
+ * hands-free loop so the two flows behave identically after transcription.
+ */
+ private suspend fun finishTurn(text: String) {
+ val s = settingsRepository.load()
+ val language = Language.fromLabel(s.preferredLanguage)
+ _state.value = CallState.THINKING
- addTranscript(MessageKind.USER, cleanedText)
+ // API STT (Whisper-class) output is already punctuated and cased —
+ // cleanText is redundant there and would cost an extra LLM round-trip.
+ val cleanedText = if (s.sttProvider == AudioProvider.ANDROID) {
+ val llmClient = buildClient()
+ val navModel = s.navigatorModel.ifEmpty { s.model }
+ llmClient?.cleanText(text, navModel, language) ?: text
+ } else {
+ text
+ }
- // Answering an agent question?
- questionGate?.let { gate ->
- questionGate = null
- gate.complete(cleanedText)
- return@launch
- }
+ addTranscript(MessageKind.USER, cleanedText)
- // Normal turn
- val eng = engine ?: return@launch
- eng.history += buildTurnMessage(cleanedText)
- pendingReply = null
+ // Answering an agent question?
+ questionGate?.let { gate ->
+ questionGate = null
+ gate.complete(cleanedText)
+ return
+ }
- // Narrate start-of-turn to give the user immediate feedback
- narrate(pickTurnStartPhrase(language), language)
- onActionRingColor(Category.FOREGROUND.ringColorArgb)
-
- try {
- eng.run(AgentMode.OPERATOR)
- } catch (e: CancellationException) {
- throw e
- } catch (e: Exception) {
- val msg = friendlyAgentError(e)
- reportError(msg)
- pendingReply = msg
- }
+ // Normal turn
+ val eng = engine ?: return
+ eng.history += buildTurnMessage(cleanedText)
+ pendingReply = null
- val reply = pendingReply ?: return@launch
- _state.value = CallState.SPEAKING
- if (speakText(reply, language)) {
- triggerEndVibration()
- } else {
- reportError("Couldn't play the voice reply — check your Text-to-Speech settings.")
- }
- onActionRingColor(null)
- if (autoEndOnReply) endCall() else _state.value = CallState.READY
+ // Narrate start-of-turn to give the user immediate feedback
+ narrate(pickTurnStartPhrase(language), language)
+ onActionRingColor(Category.FOREGROUND.ringColorArgb)
+
+ try {
+ eng.run(AgentMode.OPERATOR)
+ } catch (e: CancellationException) {
+ throw e
+ } catch (e: Exception) {
+ val msg = friendlyAgentError(e)
+ reportError(msg)
+ pendingReply = msg
+ }
+
+ val reply = pendingReply ?: return
+ _state.value = CallState.SPEAKING
+ if (speakText(reply, language)) {
+ triggerEndVibration()
+ } else {
+ reportError("Couldn't play the voice reply — check your Text-to-Speech settings.")
}
+ onActionRingColor(null)
+ if (autoEndOnReply) endCall() else _state.value = CallState.READY
}
/**
@@ -348,10 +457,17 @@ class CallSessionController(
private suspend fun buildTurnMessage(text: String): ChatMessage {
var screenshot: String? = null
var screenText: String? = null
+ var blankScreen = false
if (ScreenSnapshot.isAvailable()) {
onCaptureChrome(true)
delay(CAPTURE_SETTLE_MS)
screenshot = ScreenSnapshot.captureScreenBase64()
+ if (screenshot != null && ScreenSnapshot.isMostlyBlack(screenshot)) {
+ // A blank/off screen (common during wake-word calls) is pure
+ // noise for the model — never inject a black frame.
+ screenshot = null
+ blankScreen = true
+ }
screenText = ScreenSnapshot.captureScreenText()
onCaptureChrome(false)
// The model reads the screen from this per-turn capture on every
@@ -361,12 +477,14 @@ class CallSessionController(
onScreenReadDone()
}
val userText = buildString {
- if (!screenText.isNullOrBlank()) {
- append("Current screen text:\n")
- append(screenText)
- append("\n\n")
- } else {
- append("(The current screen could not be captured this turn.)\n\n")
+ when {
+ !screenText.isNullOrBlank() -> {
+ append("Current screen text:\n")
+ append(screenText)
+ append("\n\n")
+ }
+ blankScreen -> append("(The screen was blank or off — no screenshot was sent.)\n\n")
+ else -> append("(The current screen could not be captured this turn.)\n\n")
}
append("User said (voice call — reply briefly, it will be read aloud): ")
append(text)
@@ -480,7 +598,10 @@ class CallSessionController(
questionGate = gate
val answer = withTimeoutOrNull(QUESTION_TIMEOUT_MS) { gate.await() } ?: ""
if (answer.isNotBlank()) addTranscript(MessageKind.USER, answer)
- _state.value = CallState.READY
+ // The agent is still processing the answer — stay in THINKING rather
+ // than READY so the hands-free loop doesn't mistake the post-question
+ // processing window for "waiting for input".
+ _state.value = CallState.THINKING
return answer
}
@@ -665,5 +786,14 @@ class CallSessionController(
private const val CAPTURE_SETTLE_MS = 350L
private const val QUESTION_TIMEOUT_MS = 30_000L
private const val TOOL_TEXT_LIMIT = 300
+
+ /** Trailing silence (API STT) before the hands-free mic auto-stops. */
+ private const val HANDS_FREE_SILENCE_MS = 3_000L
+
+ /** Trailing silence hint for the Android recognizer (best effort). */
+ private const val ANDROID_SILENCE_MS = 2_000L
+
+ /** Blank-listens before a hands-free call ends on its own. */
+ private const val HANDS_FREE_SILENT_STRIKES = 2
}
}
diff --git a/app/src/test/java/com/gotcha/agent/ScreenSnapshotTest.kt b/app/src/test/java/com/gotcha/agent/ScreenSnapshotTest.kt
new file mode 100644
index 0000000..ec4fd97
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/ScreenSnapshotTest.kt
@@ -0,0 +1,72 @@
+package com.gotcha.agent
+
+import android.graphics.Bitmap
+import android.graphics.Color
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+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 ScreenSnapshotTest {
+
+ @Test
+ fun `a solid black frame is mostly black`() {
+ assertTrue(ScreenSnapshot.isMostlyBlack(encode(SolidBitmap(Color.BLACK))))
+ }
+
+ @Test
+ fun `a solid white frame is not mostly black`() {
+ assertFalse(ScreenSnapshot.isMostlyBlack(encode(SolidBitmap(Color.WHITE))))
+ }
+
+ @Test
+ fun `a near-black frame is still mostly black`() {
+ assertTrue(ScreenSnapshot.isMostlyBlack(encode(SolidBitmap(Color.rgb(5, 5, 5)))))
+ }
+
+ @Test
+ fun `a dark frame with visible content is not blank`() {
+ val bitmap = Bitmap.createBitmap(128, 128, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(Color.BLACK)
+ for (y in 40 until 88) {
+ for (x in 40 until 88) {
+ bitmap.setPixel(x, y, Color.WHITE)
+ }
+ }
+ // Classification runs directly on the bitmap because Robolectric's
+ // BitmapFactory does not faithfully reproduce per-pixel content when
+ // decoding a JPEG.
+ assertFalse("content on a black screen must not be dropped", ScreenSnapshot.classifyBlackness(bitmap))
+ bitmap.recycle()
+ }
+
+ @Test
+ fun `an evenly split black and white frame is not mostly black`() {
+ val bitmap = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(Color.BLACK)
+ for (y in 0 until 64) {
+ for (x in 0 until 32) {
+ bitmap.setPixel(x, y, Color.WHITE)
+ }
+ }
+ assertFalse(ScreenSnapshot.classifyBlackness(bitmap))
+ bitmap.recycle()
+ }
+
+ private fun SolidBitmap(color: Int): Bitmap {
+ val bitmap = Bitmap.createBitmap(64, 64, Bitmap.Config.ARGB_8888)
+ bitmap.eraseColor(color)
+ return bitmap
+ }
+
+ private fun encode(bitmap: Bitmap): String {
+ val stream = java.io.ByteArrayOutputStream()
+ bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream)
+ bitmap.recycle()
+ return android.util.Base64.encodeToString(stream.toByteArray(), android.util.Base64.DEFAULT)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/audio/SilenceDetectorTest.kt b/app/src/test/java/com/gotcha/audio/SilenceDetectorTest.kt
new file mode 100644
index 0000000..bc2f29a
--- /dev/null
+++ b/app/src/test/java/com/gotcha/audio/SilenceDetectorTest.kt
@@ -0,0 +1,83 @@
+package com.gotcha.audio
+
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+
+class SilenceDetectorTest {
+
+ private val start = 1_000_000L
+
+ @Test
+ fun `stops after the configured trailing silence once speech was heard`() {
+ val detector = SilenceDetector(silenceTimeoutMs = 3_000L)
+ detector.update(windowRmsDb = -20f, nowMs = start)
+ 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))
+ }
+
+ @Test
+ fun `keeps listening while speech continues`() {
+ val detector = SilenceDetector(silenceTimeoutMs = 3_000L)
+ var now = start
+ repeat(10) {
+ assertEquals(SilenceDetector.Decision.CONTINUE, detector.update(windowRmsDb = -20f, nowMs = now))
+ now += 200
+ }
+ assertTrue(detector.speechDetected)
+ }
+
+ @Test
+ fun `reports no speech after the no-speech timeout`() {
+ val detector = SilenceDetector(silenceTimeoutMs = 3_000L, noSpeechTimeoutMs = 15_000L)
+ assertEquals(SilenceDetector.Decision.CONTINUE, detector.update(windowRmsDb = -65f, nowMs = start))
+ assertFalse(detector.speechDetected)
+ assertEquals(
+ SilenceDetector.Decision.CONTINUE,
+ detector.update(windowRmsDb = -65f, nowMs = start + 14_000)
+ )
+ assertEquals(
+ SilenceDetector.Decision.STOP_NO_SPEECH,
+ detector.update(windowRmsDb = -65f, nowMs = start + 15_000)
+ )
+ }
+
+ @Test
+ fun `silence does not stop before speech is heard`() {
+ val detector = SilenceDetector(silenceTimeoutMs = 3_000L)
+ var now = start
+ repeat(30) {
+ assertEquals(SilenceDetector.Decision.CONTINUE, detector.update(windowRmsDb = -65f, nowMs = now))
+ now += 200
+ }
+ assertFalse("a silently recording user must not trigger STOP", detector.speechDetected)
+ }
+
+ @Test
+ fun `rmsDb is near the floor for digital silence and higher for loud samples`() {
+ val silent = ShortArray(100)
+ val quiet = ShortArray(100) { 300 }
+ val loud = ShortArray(100) { 20000 }
+ val silentDb = SilenceDetector.rmsDb(silent, silent.size)
+ val quietDb = SilenceDetector.rmsDb(quiet, quiet.size)
+ val loudDb = SilenceDetector.rmsDb(loud, loud.size)
+ assertTrue(silentDb <= -50f)
+ assertTrue(quietDb > silentDb)
+ assertTrue(loudDb > quietDb)
+ // 20000/32768 ≈ -4.3 dBFS.
+ assertTrue(loudDb in -10f..0f)
+ }
+
+ @Test
+ fun `rmsDb ignores trailing zeros beyond count`() {
+ val samples = ShortArray(200)
+ for (i in 0 until 100) samples[i] = 20000
+ val full = SilenceDetector.rmsDb(samples, 100)
+ val truncated = SilenceDetector.rmsDb(samples, 50)
+ assertTrue(full > -10f)
+ assertTrue(truncated > -10f)
+ }
+}