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: add visual and audio feedback to voice calls during tool execution by classifying tool categories and updating a mic-button ring overlay.
Rishabh Bajpaib9384acfcbdb
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 900d8d7..6d68f24 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -66,6 +66,9 @@ class AgentEngine(var sessionId: String? = nullvar tokenCount: Int = 0+ /** When true, the system prompt includes a voice-call brevity reminder. */+ var callMode: Boolean = false+lateinit var toolExecutor: ToolExecutorprivate set@@ -793,6 +796,13 @@ class AgentEngine("You are in OPERATOR mode. You are permitted to inspect, create, modify, and " +"delete on the device using the provided tools. Be careful with destructive " +"actions — confirm with the user when the result seems significant.\n" ++ if (callMode) {+ "\nThis is a VOICE CALL — everything you say is read aloud via TTS.\n" ++ "Keep responses to 1-2 short sentences. No markdown, no lists, no code blocks.\n" ++ "Do not ask follow-up questions unless absolutely necessary.\n"+ } else {+ ""+ } +"</system-reminder>"}return listOf(diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex 266daad..f43a40d 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -92,6 +92,7 @@ class AssistiveBallService : Service() {}callController.onError = { overlay.showError(it) }+ callController.onActionRingColor = { color -> chatWindow.setActionRingColor(color) }callController.onCaptureChrome = { hide ->if (hide) {overlay.hideChromeForCapture()diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 91519cb..b33e63f 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -2,6 +2,9 @@ package com.gotcha.serviceimport android.content.Contextimport android.content.pm.PackageManager+import android.os.Build+import android.os.VibrationEffect+import android.os.Vibratorimport androidx.core.content.ContextCompatimport com.gotcha.agent.AgentEngineimport com.gotcha.agent.AgentEvents@@ -11,6 +14,7 @@ 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@@ -18,6 +22,8 @@ import com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClientimport com.gotcha.llm.visionUserMessageimport com.gotcha.tools.AgentMode+import com.gotcha.tools.Category+import com.gotcha.tools.ToolCategoriesimport com.gotcha.ui.ConfirmationOverlayimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.CompletableDeferred@@ -72,6 +78,11 @@ class CallSessionController(@Volatileprivate var pendingReply: String? = null+ /** Fire-and-forget TTS narration for tool progress (preemptible). */+ private var narrationJob: Job? = null+ private var lastNarrationTimeMs = 0L+ private var lastNarratedCategory: Category? = null+private val _state = MutableStateFlow(CallState.IDLE)val state: StateFlow<CallState> = _state.asStateFlow()@@ -88,6 +99,9 @@ class CallSessionController(/** Set by the service: surface a start-call failure to the user. */var onError: (String) -> Unit = { }+ /** Set by the service: update the mic-button ring color during tool execution. */+ var onActionRingColor: (Int?) -> Unit = { }+fun isActive(): Boolean = _state.value != CallState.IDLE && _state.value != CallState.ENDING/**@@ -117,6 +131,7 @@ class CallSessionController(workingDirRoot = CALLS_WORKING_ROOT)newEngine.sessionId = java.util.UUID.randomUUID().toString()+ newEngine.callMode = truenewEngine.setupWorkingDir()engine = newEngine_state.value = CallState.STARTING@@ -134,6 +149,8 @@ class CallSessionController(*/fun stopAgent() {if (!isActive() || _state.value == CallState.ENDING) return+ narrationJob?.cancel()+ narrationJob = nullcurrentTurnJob?.cancel()currentTurnJob = nullttsEngine.stop()@@ -142,6 +159,7 @@ class CallSessionController(questionGate?.complete("")questionGate = nullpendingReply = null+ onActionRingColor(null)_state.value = CallState.READY}@@ -149,6 +167,8 @@ class CallSessionController(fun endCall() {val endingEngine = engine ?: return_state.value = CallState.ENDING+ narrationJob?.cancel()+ narrationJob = nullloopJob?.cancel()loopJob = nullcurrentTurnJob?.cancel()@@ -224,6 +244,11 @@ class CallSessionController(val eng = engine ?: return@launcheng.history += buildTurnMessage(cleanedText)pendingReply = null++ // Narrate start-of-turn to give the user immediate feedback+ narrate("Let me look into that")+ onActionRingColor(Category.FOREGROUND.ringColorArgb)+try {eng.run(AgentMode.OPERATOR)} catch (e: CancellationException) {@@ -237,6 +262,8 @@ class CallSessionController(val reply = pendingReply ?: return@launch_state.value = CallState.SPEAKINGspeakText(reply)+ triggerEndVibration()+ onActionRingColor(null)_state.value = CallState.READY}}@@ -297,6 +324,18 @@ class CallSessionController(override fun onActivity(activity: String?) {_statusLine.value = activity+ if (_state.value != CallState.THINKING) return+ val toolName = activity?.removePrefix("Running:")?.removeSuffix("…")?.trim()+ if (toolName != null && toolName != "Thinking") {+ val category = ToolCategories.classify(toolName)+ onActionRingColor(category.ringColorArgb)+ if (category.isNarratable && canNarrate(category)) {+ val msg = category.narration ?: return+ narrate(msg)+ lastNarrationTimeMs = System.currentTimeMillis()+ lastNarratedCategory = category+ }+ }}override fun onTokenCount(totalTokens: Int) {@@ -311,6 +350,17 @@ class CallSessionController(_statusLine.value = running?.let { r ->if (currentAction.isNullOrBlank()) r else "$r — $currentAction"}+ // Narration for sub-agent steps (throttled, category-based)+ if (running != null && _state.value == CallState.THINKING) {+ val inferredTool = currentAction?.substringBefore("(")?.trim() ?: running+ val category = ToolCategories.classify(inferredTool)+ onActionRingColor(category.ringColorArgb)+ if (category.isNarratable && canNarrate(category) && !currentAction.isNullOrBlank()) {+ narrate(currentAction.take(60))+ lastNarrationTimeMs = System.currentTimeMillis()+ lastNarratedCategory = category+ }+ }}override fun onPermissionRequest(marker: String) {@@ -341,20 +391,49 @@ class CallSessionController(}/**- * Destructive actions still require a deliberate visual tap (not a- * possibly-misheard "yes"): reuse the over-other-apps ConfirmationOverlay.+ * Try voice confirmation first, fall back to visual overlay on silence.*/override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean {_state.value = CallState.WAITING_USERaddTranscript(MessageKind.ASSISTANT, "Confirmation needed: $description")- speakText("I need a confirmation — check the dialog on your screen.")++ // Always show visual overlay as fallbackval gate = CompletableDeferred<Boolean>()confirmationOverlay.show(summary = description,onAllow = { gate.complete(true) },onDeny = { gate.complete(false) })- val approved = withTimeoutOrNull(CONFIRM_TIMEOUT_MS) { gate.await() } ?: false++ // Phase 1: Voice confirmation (fast path)+ speakText("I'm about to $description. Say yes or no.")+ delay(200)+ val voiceAnswer = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ withTimeoutOrNull(VOICE_CONFIRM_TIMEOUT_MS) {+ val outcome = sttEngine.listenOnceAndroid()+ when (outcome) {+ is SttOutcome.Text -> outcome.text.lowercase().trim()+ is SttOutcome.Error -> null+ }+ }+ } else {+ null+ }++ if (voiceAnswer != null) {+ if (isAffirmative(voiceAnswer)) {+ addTranscript(MessageKind.USER, "Yes")+ } else if (isNegative(voiceAnswer)) {+ addTranscript(MessageKind.USER, "No")+ return false.also { confirmationOverlay.dismiss() }+ }+ }++ // Phase 2: Visual fallback+ if (voiceAnswer == null) {+ speakText("I didn't catch that. Tap Allow or Deny on the screen.")+ }+ val approved = withTimeoutOrNull(VISUAL_CONFIRM_TIMEOUT_MS) { gate.await() } ?: falseconfirmationOverlay.dismiss()_state.value = CallState.THINKINGreturn approved@@ -399,11 +478,57 @@ class CallSessionController(}}+ private fun narrate(text: String) {+ if (text.isBlank() || _state.value != CallState.THINKING) return+ val s = settingsRepository.load()+ if (s.ttsProvider == AudioProvider.NONE) return+ narrationJob?.cancel()+ narrationJob = scope.launch {+ val voice = if (s.ttsProvider == AudioProvider.API) {+ if (ttsEngine.apiTtsModels.isEmpty()) ttsEngine.refreshApiModels()+ ttsEngine.apiTtsModels.firstOrNull { it.id == s.ttsApiModel }?.defaultVoice ?: "af_heart"+ } else {+ ""+ }+ ttsEngine.speak(text, s.ttsProvider, s.ttsApiModel, voice)+ }+ }++ private fun canNarrate(category: Category): Boolean {+ val now = System.currentTimeMillis()+ return category != lastNarratedCategory || (now - lastNarrationTimeMs) > NARRATION_THROTTLE_MS+ }++ private fun triggerEndVibration() {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return+ val vibrator = appContext.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator+ if (vibrator?.hasVibrator() == true) {+ vibrator.vibrate(+ VibrationEffect.createWaveform(+ longArrayOf(0, 50, 100, 50),+ -1+ )+ )+ }+ }++ private fun isAffirmative(text: String): Boolean = text in setOf(+ "yes", "yeah", "yep", "sure", "go ahead", "okay", "ok",+ "confirm", "do it", "allow", "true", "please"+ )++ private fun isNegative(text: String): Boolean = text in setOf(+ "no", "nope", "nah", "cancel", "stop", "deny",+ "don't", "dont", "never", "false", "nay"+ )+companion object {+ private const val NARRATION_THROTTLE_MS = 3_000L+ private const val VOICE_CONFIRM_TIMEOUT_MS = 5_000L+ private const val VISUAL_CONFIRM_TIMEOUT_MS = 55_000Lconst val CALLS_WORKING_ROOT = "/storage/emulated/0/Gotcha/calls"private const val CAPTURE_SETTLE_MS = 350Lprivate const val QUESTION_TIMEOUT_MS = 30_000L- private const val CONFIRM_TIMEOUT_MS = 60_000Lprivate const val TOOL_TEXT_LIMIT = 300}}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktnew file mode 100644index 0000000..3ddd0e5--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -0,0 +1,45 @@+package com.gotcha.tools++enum class Category(val ringColorArgb: Int?, val narration: String?, val isNarratable: Boolean) {+ FOREGROUND(0xFF4A90D9.toInt(), "Looking at the screen", true),+ BACKGROUND(0xFFFF6B35.toInt(), "Making a change", true),+ INFO(null, null, false)+}++object ToolCategories {++ private val foregroundTools = setOf(+ "tap", "tap_index", "long_press", "long_press_index",+ "swipe", "input_text", "press_key",+ "global_action", "open_app",+ "read_screen", "read_screen_raw",+ "navigate_app", "task",+ "dial_number"+ )++ private val backgroundTools = setOf(+ "edit", "write_file", "make_directory", "delete_file",+ "uninstall_app", "delete_calendar_event", "delete_alarm",+ "delete_timer", "edit_alarm",+ "toggle_wifi", "toggle_torch",+ "set_volume", "set_ringer_mode", "set_dnd", "set_brightness",+ "set_wallpaper", "set_clipboard",+ "call_number", "send_sms", "add_contact",+ "create_calendar_event", "edit_calendar_event",+ "set_alarm", "set_timer",+ "take_photo",+ "start_audio_recording", "stop_audio_recording",+ "pause_audio_recording", "resume_audio_recording",+ "run_command", "run_root_command",+ "show_overlay", "hide_overlay",+ "lock_screen", "disable_camera", "set_password_policy",+ "dismiss_notifications", "media_control",+ "vibrate", "write_secure_settings"+ )++ fun classify(toolName: String): Category = when {+ foregroundTools.contains(toolName) -> Category.FOREGROUND+ backgroundTools.contains(toolName) -> Category.BACKGROUND+ else -> Category.INFO+ }+}diff --git a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt b/app/src/main/java/com/gotcha/ui/CallChatWindow.ktindex c82d372..c1dfb4b 100644--- a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt+++ b/app/src/main/java/com/gotcha/ui/CallChatWindow.kt@@ -53,6 +53,10 @@ class CallChatWindow(context: Context) {private var ringOverlayView: View? = nullprivate var ringOverlayAnimator: ValueAnimator? = null+ // Action button ring overlay (static colored ring during tool execution)+ private var actionRingOverlayView: View? = null+ private var actionRingDrawable: RingDrawable? = null+private var currentState: CallState = CallState.IDLE// Drag state@@ -91,6 +95,7 @@ class CallChatWindow(context: Context) {mainHandler.post {mainHandler.removeCallbacks(endLongPressRunnable)removeRingOverlay()+ removeActionRingOverlay()rootView?.let {try { windowManager.removeView(it) } catch (_: Exception) { }}@@ -260,9 +265,9 @@ class CallChatWindow(context: Context) {windowManager.addView(view, params)ringOverlayView = view- val btnPx = dp(BTN_SIZE_DP.toFloat())- val minRadius = btnPx * 0.50f- val maxRadius = btnPx * 1.60f+ val btnSizeDp = dp(BTN_SIZE_DP.toFloat())+ val minRadius = btnSizeDp * 0.50f+ val maxRadius = btnSizeDp * 1.60fval strokePx = 2.5f * densityval fillBase = Color.parseColor("#FF6B6B")val strokeBase = Color.parseColor("#FF6B6B")@@ -291,6 +296,71 @@ class CallChatWindow(context: Context) {}}+ /** Show or hide a thin static ring around the action (mic) button. */+ fun setActionRingColor(color: Int?) {+ mainHandler.post {+ if (color == null) {+ removeActionRingOverlay()+ return@post+ }+ val density = appContext.resources.displayMetrics.density+ val paddingPx = (8 * density).toInt()+ val btnPx = (BTN_SIZE_DP * density).toInt()+ val cx = (rootParams?.x ?: 0) + paddingPx + btnPx / 2+ val cy = (rootParams?.y ?: 0) + btnPx / 2++ if (actionRingOverlayView != null) {+ // Update existing ring color+ actionRingDrawable?.strokeColor = color+ return@post+ }++ val ringSize = (BTN_SIZE_DP * 1.5f * density).toInt()+ val drawable = RingDrawable().apply {+ ringRadius = btnPx * 0.65f+ strokeWidth = 2.5f * density+ strokeColor = color+ fillColor = android.graphics.Color.TRANSPARENT+ }+ actionRingDrawable = drawable++ val view = View(appContext).apply { background = drawable }+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY+ } else {+ @Suppress("DEPRECATION")+ WindowManager.LayoutParams.TYPE_PHONE+ }+ val params = WindowManager.LayoutParams(+ ringSize,+ ringSize,+ type,+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or+ WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or+ WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,+ PixelFormat.TRANSLUCENT+ ).apply {+ gravity = Gravity.TOP or Gravity.START+ x = cx - ringSize / 2+ y = cy - ringSize / 2+ }+ try {+ windowManager.addView(view, params)+ actionRingOverlayView = view+ } catch (_: Exception) {+ actionRingOverlayView = null+ }+ }+ }++ private fun removeActionRingOverlay() {+ actionRingOverlayView?.let {+ try { windowManager.removeView(it) } catch (_: Exception) { }+ actionRingOverlayView = null+ actionRingDrawable = null+ }+ }+private fun removeRingOverlay() {ringOverlayAnimator?.cancel()ringOverlayAnimator = null