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: refactor call session to push-to-talk model with provider-agnostic STT support
Rishabh Bajpai8056a1b31081
diff --git a/app/src/main/java/com/gotcha/audio/SttEngine.kt b/app/src/main/java/com/gotcha/audio/SttEngine.ktindex 06fbdaf..ea10e01 100644--- a/app/src/main/java/com/gotcha/audio/SttEngine.kt+++ b/app/src/main/java/com/gotcha/audio/SttEngine.kt@@ -206,18 +206,70 @@ class SttEngine(}}+ // ---- Provider-agnostic PTT ----++ /** Start listening with the current provider. Returns false on failure. */+ fun startListening(provider: AudioProvider): Boolean {+ return when (provider) {+ AudioProvider.ANDROID -> startAndroidListening()+ AudioProvider.API -> startRecording()+ AudioProvider.NONE -> false+ }+ }+/**- * Abort an in-flight [listenOnceAndroid] (pause/end of a call). Safe to- * call from any thread; a suspended caller unblocks with [ERROR_CANCELLED].+ * Stop listening and return the transcript. Provider-agnostic.+ * For ANDROID: returns the recognized text.+ * For API: stops the recorder, transcribes, returns the text or error.*/- fun cancelListening() {- onceGate?.complete(SttOutcome.Error(ERROR_CANCELLED))- mainHandler.post {- try {- currentRecognizer?.cancel()- currentRecognizer?.destroy()- } catch (_: Exception) { }- currentRecognizer = null+ suspend fun stopListeningAndTranscribe(provider: AudioProvider, model: String): Result<String> {+ return when (provider) {+ AudioProvider.ANDROID -> {+ val text = stopAndroidListening()+ if (text.isBlank()) {+ Result.failure(Exception("No speech detected"))+ } else {+ Result.success(text)+ }+ }+ AudioProvider.API -> {+ val file = stopRecording()+ if (file == null) {+ return Result.failure(Exception("Recording failed"))+ }+ transcribeApi(file, model)+ }+ AudioProvider.NONE -> Result.failure(Exception("STT not configured"))+ }+ }++ /**+ * Abort an active listen (pause/end of a call). Handles both providers.+ * Safe to call from any thread.+ */+ fun cancelListening(provider: AudioProvider) {+ when (provider) {+ AudioProvider.ANDROID -> {+ onceGate?.complete(SttOutcome.Error(ERROR_CANCELLED))+ mainHandler.post {+ try {+ currentRecognizer?.cancel()+ currentRecognizer?.destroy()+ } catch (_: Exception) { }+ currentRecognizer = null+ }+ }+ AudioProvider.API -> {+ try {+ currentRecorder?.apply {+ stop()+ release()+ }+ } catch (_: Exception) { }+ currentRecorder = null+ currentAudioFile = null+ }+ AudioProvider.NONE -> {}}}diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 57bfaef..97bf6c7 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -67,6 +67,13 @@ class AssistiveBallService : Service() {onStart = { startOrResumeCall() }onPause = { callController.pause() }onEnd = { endCall() }+ onMicClick = {+ if (callController.state.value == CallState.LISTENING) {+ callController.stopMic()+ } else {+ callController.startMic()+ }+ }}overlay = AssistiveBallOverlay(this).apply {onDismiss = { stopBall() }diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 3dc0543..6ee9d12 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -11,7 +11,6 @@ import com.gotcha.agent.ScreenSnapshotimport com.gotcha.agent.friendlyAgentErrorimport com.gotcha.audio.AudioProviderimport com.gotcha.audio.SttEngine-import com.gotcha.audio.SttOutcomeimport com.gotcha.audio.TtsEngineimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.SettingsRepository@@ -30,24 +29,22 @@ import kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.flow.first-import kotlinx.coroutines.isActiveimport kotlinx.coroutines.launchimport kotlinx.coroutines.withTimeoutOrNullimport kotlinx.serialization.json.JsonPrimitive-enum class CallState { IDLE, STARTING, LISTENING, THINKING, SPEAKING, WAITING_USER, PAUSED, ENDING }+enum class CallState { IDLE, STARTING, READY, LISTENING, THINKING, SPEAKING, WAITING_USER, PAUSED, ENDING }data class CallTranscriptItem(val id: Long, val kind: MessageKind, val text: String)/**- * A hands-free voice "call" with the full agent: mic listens (Android STT- * endpointing) → transcript + screen context go through [AgentEngine] with- * tools → the reply is spoken (TTS) → mic re-arms, until the call ends.+ * A push-to-talk voice "call" with the full agent. Mic is off by default.+ * User taps a mic button to start recording, taps again to stop and send.+ * The transcript goes through [AgentEngine] with tools, the reply is spoken+ * (TTS), and the mic returns to the off state — ready for the next tap.** Call sessions persist to a separate "calls" directory (never the main chat* list) and are deleted — history and working dir — when the call ends.- * The loop is strictly sequential so the mic never records our own speech.*/@Suppress("TooManyFunctions")class CallSessionController(@@ -68,6 +65,9 @@ class CallSessionController(private var loopJob: Job? = nullprivate var nextTranscriptId = 0L+ /** Gate for [awaitQuestionAnswer]: completed when the user taps mic stop. */+ private var questionGate: CompletableDeferred<String>? = null+@Volatileprivate var pendingReply: String? = null@@ -87,7 +87,7 @@ class CallSessionController(/** Set by the service: surface a start-call failure to the user. */var onError: (String) -> Unit = { }- fun isActive(): Boolean = _state.value != CallState.IDLE+ fun isActive(): Boolean = _state.value != CallState.IDLE && _state.value != CallState.ENDING/*** Start a new call. Returns false (after reporting through [onError])@@ -95,15 +95,10 @@ class CallSessionController(*/fun startCall(): Boolean {if (isActive()) return false- val settings = settingsRepository.load()if (buildClient() == null) {onError("Set up your API key in Gotcha first.")return false}- if (settings.sttProvider != AudioProvider.ANDROID) {- onError("Calls need Android speech recognition — switch the STT provider in Settings.")- return false- }val micGranted = ContextCompat.checkSelfPermission(appContext, android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED@@ -124,28 +119,26 @@ class CallSessionController(newEngine.setupWorkingDir()engine = newEngine_state.value = CallState.STARTING- loopJob = scope.launch {- try {- runCallLoop(newEngine)- } catch (_: CancellationException) {- // endCall() handles state + cleanup.- }+ scope.launch {+ speakText("Call started. I'm ready when you are.")+ _state.value = CallState.READY}return true}- /** Pause: stop speech and listening, park the loop until [resume]. */+ /** Pause: stop speech and listening, park state until [resume]. */fun pause() {if (_state.value == CallState.IDLE || _state.value == CallState.ENDING) return_state.value = CallState.PAUSEDttsEngine.stop()- sttEngine.cancelListening()+ val s = settingsRepository.load()+ sttEngine.cancelListening(s.sttProvider)}- /** Resume a paused call at the listening step. */+ /** Resume a paused call — goes to [READY] (mic off). */fun resume() {if (_state.value == CallState.PAUSED) {- _state.value = CallState.LISTENING+ _state.value = CallState.READY}}@@ -156,7 +149,10 @@ class CallSessionController(loopJob?.cancel()loopJob = nullttsEngine.stop()- sttEngine.cancelListening()+ val s = settingsRepository.load()+ sttEngine.cancelListening(s.sttProvider)+ questionGate?.complete("")+ questionGate = nullconfirmationOverlay.dismiss()engine = null@@ -175,40 +171,51 @@ class CallSessionController(}}- // ---- The call loop ----+ // ---- Push-to-talk: called from the UI ----- private suspend fun runCallLoop(engine: AgentEngine) {- var consecutiveFailures = 0- speakText("Call started. I'm listening.")- while (kotlinx.coroutines.currentCoroutineContext().isActive) {- awaitNotPaused()+ /**+ * Start the mic. User must tap [stopMic] to stop recording and send.+ * Works from [READY] (normal turn) or [WAITING_USER] (answering a question).+ */+ fun startMic() {+ val current = _state.value+ if (current != CallState.READY && current != CallState.WAITING_USER) return+ val s = settingsRepository.load()+ val started = sttEngine.startListening(s.sttProvider)+ if (started) {_state.value = CallState.LISTENING- _statusLine.value = null- val outcome = sttEngine.listenOnceAndroid()+ }+ }- if (outcome is SttOutcome.Error && outcome.code == SttEngine.ERROR_CANCELLED) {- continue // pause/end interrupted the mic; loop parks or dies above- }- val text = (outcome as? SttOutcome.Text)?.text?.trim().orEmpty()- if (text.isEmpty()) {- consecutiveFailures++- if (consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) {- consecutiveFailures = 0- speakText("I'll pause the call. Tap Start when you're ready.")- pause()- } else if (outcome is SttOutcome.Error && !outcome.isBenign) {- delay(ERROR_RETRY_DELAY_MS) // recognizer hiccup; brief backoff- }- continue+ /** Stop the mic and send the recording for transcription + agent processing. */+ fun stopMic() {+ if (_state.value != CallState.LISTENING) return+ scope.launch {+ _state.value = CallState.THINKING+ val s = settingsRepository.load()+ val result = sttEngine.stopListeningAndTranscribe(s.sttProvider, s.sttApiModel)+ val text = result.getOrDefault("")++ if (text.isBlank()) {+ _state.value = CallState.READY+ return@launch}- consecutiveFailures = 0addTranscript(MessageKind.USER, text)- _state.value = CallState.THINKING- engine.history += buildTurnMessage(text)++ // Answering an agent question?+ questionGate?.let { gate ->+ questionGate = null+ gate.complete(text)+ return@launch+ }++ // Normal turn+ val eng = engine ?: return@launch+ eng.history += buildTurnMessage(text)pendingReply = nulltry {- engine.run(AgentMode.OPERATOR)+ eng.run(AgentMode.OPERATOR)} catch (e: CancellationException) {throw e} catch (e: Exception) {@@ -217,18 +224,13 @@ class CallSessionController(pendingReply = msg}- val reply = pendingReply ?: continue- pendingReply = null- awaitNotPaused()+ val reply = pendingReply ?: return@launch_state.value = CallState.SPEAKINGspeakText(reply)+ _state.value = CallState.READY}}- private suspend fun awaitNotPaused() {- _state.first { it != CallState.PAUSED }- }-/*** Builds the user turn: current screen (screenshot + on-screen text via* the accessibility service, chrome hidden during capture) + what was said.@@ -308,7 +310,7 @@ class CallSessionController()}- /** The agent asked a question: speak it and take the answer by voice. */+ /** The agent asked a question: speak it and wait for a PTT answer. */override suspend fun awaitQuestionAnswer(question: PendingQuestion): String {_state.value = CallState.WAITING_USERval prompt = buildString {@@ -320,10 +322,11 @@ class CallSessionController(}addTranscript(MessageKind.ASSISTANT, prompt)speakText(prompt)- val outcome = withTimeoutOrNull(QUESTION_TIMEOUT_MS) { sttEngine.listenOnceAndroid() }- val answer = ((outcome as? SttOutcome.Text)?.text ?: "").trim()+ val gate = CompletableDeferred<String>()+ questionGate = gate+ val answer = withTimeoutOrNull(QUESTION_TIMEOUT_MS) { gate.await() } ?: ""if (answer.isNotBlank()) addTranscript(MessageKind.USER, answer)- _state.value = CallState.THINKING+ _state.value = CallState.READYreturn answer}@@ -388,8 +391,6 @@ class CallSessionController(companion object {const val CALLS_WORKING_ROOT = "/storage/emulated/0/Gotcha/calls"- const val MAX_CONSECUTIVE_FAILURES = 3- private const val ERROR_RETRY_DELAY_MS = 600Lprivate const val CAPTURE_SETTLE_MS = 350Lprivate const val QUESTION_TIMEOUT_MS = 30_000Lprivate const val CONFIRM_TIMEOUT_MS = 60_000Ldiff --git a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt b/app/src/main/java/com/gotcha/ui/CallChatWindow.ktindex 69820f3..9cfc8d6 100644--- a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt+++ b/app/src/main/java/com/gotcha/ui/CallChatWindow.kt@@ -37,9 +37,11 @@ class CallChatWindow(context: Context) {var onStart: () -> Unit = {}var onPause: () -> Unit = {}var onEnd: () -> Unit = {}+ var onMicClick: () -> Unit = {}private var rootView: View? = nullprivate var statusText: TextView? = null+ private var micButton: Button? = nullprivate var startButton: Button? = nullprivate var pauseButton: Button? = nullprivate var endButton: Button? = null@@ -75,6 +77,7 @@ class CallChatWindow(context: Context) {}rootView = nullstatusText = null+ micButton = nullstartButton = nullpauseButton = nullendButton = null@@ -114,13 +117,21 @@ class CallChatWindow(context: Context) {statusText?.text = when (state) {CallState.IDLE -> "No active call"CallState.STARTING -> "Starting…"- CallState.LISTENING -> "🎤 Listening…"+ CallState.READY -> "🎤 Tap mic to speak"+ CallState.LISTENING -> "🔴 Recording…"CallState.THINKING -> lastStatusLine ?: "Thinking…"CallState.SPEAKING -> "🔊 Speaking…"- CallState.WAITING_USER -> "Waiting for you…"+ CallState.WAITING_USER -> "🎤 Tap mic to answer"CallState.PAUSED -> "⏸ Paused"CallState.ENDING -> "Ending…"}+ micButton?.text = when (state) {+ CallState.LISTENING -> "⏹"+ else -> "🎤"+ }+ micButton?.isEnabled = state == CallState.READY ||+ state == CallState.WAITING_USER ||+ state == CallState.LISTENINGstartButton?.isEnabled = state == CallState.PAUSED || state == CallState.IDLEpauseButton?.isEnabled = state != CallState.IDLE && state != CallState.PAUSED && state != CallState.ENDINGendButton?.isEnabled = state != CallState.IDLE && state != CallState.ENDING@@ -208,10 +219,12 @@ class CallChatWindow(context: Context) {textSize = 13flayoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)}+ val mic = headerButton("🎤") { onMicClick() }val start = headerButton("▶") { onStart() }val pauseBtn = headerButton("⏸") { onPause() }val end = headerButton("⏹") { onEnd() }header.addView(status)+ header.addView(mic)header.addView(start)header.addView(pauseBtn)header.addView(end)@@ -233,6 +246,7 @@ class CallChatWindow(context: Context) {root.addView(scroll)statusText = status+ micButton = micstartButton = startpauseButton = pauseBtnendButton = enddiff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 25188f9..f75a04a 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -567,6 +567,13 @@ fun SettingsScreen(enabled = !refreshingModels && (ttsApiBaseUrl.isNotBlank() || sttApiBaseUrl.isNotBlank()),modifier = Modifier.fillMaxWidth()) { Text(if (refreshingModels) "Refreshing…" else "Refresh audio models") }+ Button(+ onClick = {+ onSave(currentSettings())+ status = "Saved."+ },+ modifier = Modifier.fillMaxWidth()+ ) { Text("Save Speech Settings") }}}