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: Messenger-bubble ball gestures, call chat window, service wiring

Durganshu Mishra5a65f43c9a5e
diff --git a/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt b/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt
deleted file mode 100644
index 9f32512..0000000
--- a/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt
+++ /dev/null
@@ -1,201 +0,0 @@
-package com.gotcha.agent
-
-import android.graphics.Bitmap
-import android.os.Build
-import com.gotcha.audio.AudioProvider
-import com.gotcha.audio.SttEngine
-import com.gotcha.audio.TtsEngine
-import com.gotcha.data.SettingsRepository
-import com.gotcha.llm.ChatMessage
-import com.gotcha.llm.LLMClient
-import com.gotcha.llm.visionUserMessage
-import com.gotcha.service.GotchaAccessibilityService
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.delay
-import kotlinx.coroutines.withContext
-import kotlinx.serialization.json.JsonPrimitive
-import java.io.ByteArrayOutputStream
-
-/**
- * A ViewModel-free, single-turn "quick ask" pipeline used by the assistive ball.
- *
- * Unlike [ChatViewModel]'s full agentic tool loop, this does exactly one round-trip:
- * transcribe speech → (optionally) capture the screen → one LLM call (no tools) →
- * speak the answer. It is intentionally stateless (no history is persisted).
- *
- * It reuses the same engines the chat UI uses: [SttEngine], [TtsEngine] and [LLMClient].
- * The [llmProvider] lambda lets the host rebuild the client after a settings change
- * (mirroring [ChatViewModel.refreshSettings]).
- */
-class QuickAskEngine(
- private val settingsRepository: SettingsRepository,
- private val sttEngine: SttEngine,
- private val ttsEngine: TtsEngine,
- private val llmProvider: () -> LLMClient?
-) {
- /** Stable session ID for prefix caching across consecutive quick-ask calls. */
- private val sessionId: String = "quickask_${java.util.UUID.randomUUID()}"
-
- private fun settings() = settingsRepository.load()
-
- /** True when speech input is available (a usable STT provider is configured). */
- fun canListen(): Boolean = when (settings().sttProvider) {
- AudioProvider.ANDROID -> true
- AudioProvider.API -> settings().sttApiBaseUrl.isNotBlank() && settings().sttApiModel.isNotBlank()
- AudioProvider.NONE -> false
- }
-
- /**
- * Begin capturing speech using the configured STT provider.
- * Returns false if recording could not be started.
- */
- fun startListening(): Boolean {
- return when (settings().sttProvider) {
- AudioProvider.ANDROID -> sttEngine.startAndroidListening()
- AudioProvider.API -> sttEngine.startRecording()
- AudioProvider.NONE -> false
- }
- }
-
- /**
- * Stop capturing speech and return the recognized transcript (empty on failure).
- * Mirrors the branching in [ChatViewModel.stopRecording].
- */
- suspend fun stopAndTranscribe(): String {
- return when (settings().sttProvider) {
- AudioProvider.ANDROID -> sttEngine.stopAndroidListening()
- AudioProvider.API -> {
- val audioFile = sttEngine.stopRecording() ?: return ""
- sttEngine.transcribeApi(audioFile, settings().sttApiModel).getOrDefault("")
- }
- AudioProvider.NONE -> ""
- }
- }
-
- /** True when the Gotcha accessibility service is enabled and bound. */
- fun isAccessibilityAvailable(): Boolean = GotchaAccessibilityService.instance != null
-
- /**
- * Capture the current screen as a downscaled JPEG base64 string via the
- * accessibility screenshot API (API 30+). Returns null if unavailable
- * (older API, service not bound, or capture failed).
- *
- * The accessibility screenshot API is rate-limited (roughly one call per second),
- * so a single failure is retried once after a short delay.
- */
- suspend fun captureScreenBase64(): String? {
- if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return null
- val service = GotchaAccessibilityService.instance ?: return null
- var bitmap = service.takeScreenshotBitmap()
- if (bitmap == null) {
- delay(1100) // clear the screenshot rate-limit window, then retry once
- bitmap = service.takeScreenshotBitmap()
- }
- if (bitmap == null) return null
- return withContext(Dispatchers.Default) {
- try {
- val maxDim = 1024
- val (w, h) = if (bitmap.width > maxDim || bitmap.height > maxDim) {
- val ratio = minOf(maxDim.toFloat() / bitmap.width, maxDim.toFloat() / bitmap.height)
- (bitmap.width * ratio).toInt() to (bitmap.height * ratio).toInt()
- } else {
- bitmap.width to bitmap.height
- }
- val scaled = Bitmap.createScaledBitmap(bitmap, w, h, true)
- if (scaled != bitmap) bitmap.recycle()
- val output = ByteArrayOutputStream()
- scaled.compress(Bitmap.CompressFormat.JPEG, 85, output)
- scaled.recycle()
- android.util.Base64.encodeToString(output.toByteArray(), android.util.Base64.NO_WRAP)
- } catch (_: Exception) {
- null
- }
- }
- }
-
- /** Read on-screen text via the accessibility service, or null if unavailable. */
- fun captureScreenText(limit: Int = 60): String? {
- val service = GotchaAccessibilityService.instance ?: return null
- val lines = service.dumpScreenText(limit)
- return if (lines.isEmpty()) null else lines.joinToString("\n") { "- $it" }
- }
-
- /**
- * Run a single LLM turn for [question], optionally grounded in a screenshot and/or
- * on-screen text. Returns the assistant's answer text, or throws on network/API error.
- *
- * When [screenRequested] is true but neither a screenshot nor screen text was captured,
- * the model is told it could not read the screen — so it says so plainly instead of
- * hallucinating a generic screen.
- */
- suspend fun ask(
- question: String,
- screenshotBase64: String?,
- screenText: String?,
- screenRequested: Boolean = false
- ): String {
- val llm = llmProvider() ?: error("Not configured")
-
- val noScreenCaptured = screenshotBase64 == null && screenText.isNullOrBlank()
- val systemText = if (screenRequested && noScreenCaptured) {
- SYSTEM_PROMPT + "\n\nNOTE: The user asked about their screen, but no screenshot or " +
- "on-screen text could be captured this time. Tell them briefly that you " +
- "couldn't read the screen right now, then help as best you can. Do NOT invent or " +
- "guess what is on the screen."
- } else {
- SYSTEM_PROMPT
- }
- val system = ChatMessage(role = "system", content = JsonPrimitive(systemText))
-
- val userText = buildString {
- if (!screenText.isNullOrBlank()) {
- append("Current screen text:\n")
- append(screenText)
- append("\n\n")
- }
- append("Question: ")
- append(question)
- }
-
- val user = if (screenshotBase64 != null) {
- visionUserMessage(userText, screenshotBase64, "jpeg")
- } else {
- ChatMessage(role = "user", content = JsonPrimitive(userText))
- }
-
- val response = llm.chat(listOf(system, user), sessionId = sessionId)
- return response.choices.firstOrNull()?.message?.textContent?.ifBlank { "(no reply)" }
- ?: "(no reply)"
- }
-
- /** Speak [text] with the configured TTS provider (no-op when provider is NONE). */
- suspend fun speak(text: String) {
- val s = settings()
- if (s.ttsProvider == AudioProvider.NONE) return
- 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 = text,
- provider = s.ttsProvider,
- apiModel = s.ttsApiModel,
- voice = voice
- )
- }
-
- fun stopSpeaking() {
- ttsEngine.stop()
- }
-
- private companion object {
- const val SYSTEM_PROMPT =
- "You are a helpful on-screen assistant running on the user's Android phone. " +
- "Answer the user's spoken question concisely and conversationally. " +
- "If they ask you to translate something, provide the translation. " +
- "When screen content is provided, base your answer on it. " +
- "Keep replies short since they will be read aloud."
- }
-}
diff --git a/app/src/main/java/com/gotcha/audio/TtsEngine.kt b/app/src/main/java/com/gotcha/audio/TtsEngine.kt
index 5c2613b..1372bb7 100644
--- a/app/src/main/java/com/gotcha/audio/TtsEngine.kt
+++ b/app/src/main/java/com/gotcha/audio/TtsEngine.kt
@@ -92,6 +92,7 @@ class TtsEngine(
override fun onStart(utteranceId: String?) {}
override fun onDone(utteranceId: String?) { gate.complete(true) }
override fun onError(utteranceId: String?) { gate.complete(false) }
+
// stop() interrupts the utterance; without this the gate never completes
// and a suspended speak() would hang (e.g. pausing a voice call).
override fun onStop(utteranceId: String?, interrupted: Boolean) { gate.complete(false) }
diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
index 3508c44..57bfaef 100644
--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt
@@ -11,29 +11,31 @@ import android.content.pm.ServiceInfo
import android.os.Build
import android.os.IBinder
import com.gotcha.MainActivity
-import com.gotcha.agent.QuickAskEngine
import com.gotcha.audio.SttEngine
import com.gotcha.audio.TtsEngine
+import com.gotcha.data.ChatHistoryRepository
import com.gotcha.data.SettingsRepository
-import com.gotcha.llm.LLMClient
import com.gotcha.ui.AssistiveBallOverlay
+import com.gotcha.ui.CallChatWindow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancel
-import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
+import java.io.File
/**
* Foreground service that hosts the floating assistive ball over other apps.
*
- * It owns its own copies of the STT/TTS engines and LLM client (the chat UI's
- * [com.gotcha.agent.ChatViewModel] dies when another app is foregrounded), and
- * drives the lightweight single-turn [QuickAskEngine] for the two "press & talk"
- * options. The third option simply relaunches [MainActivity] into the chat.
+ * The ball behaves like a Messenger bubble: long-press it (3s) to start a
+ * hands-free voice call with the agent ([CallSessionController]), tap it for
+ * Start/Pause/End controls (or, during a call, to expand the [CallChatWindow]
+ * transcript), long-press 5s during a call to end it, and drag it onto the ✕
+ * target to hide the ball. It owns its own STT/TTS engines because the chat
+ * UI's ViewModel dies when another app is foregrounded.
*
* Started/stopped from the in-app toggle via [ACTION_START] / [ACTION_STOP].
*/
@@ -45,11 +47,8 @@ class AssistiveBallService : Service() {
private lateinit var ttsEngine: TtsEngine
private lateinit var sttEngine: SttEngine
private lateinit var overlay: AssistiveBallOverlay
- private lateinit var quickAsk: QuickAskEngine
-
- @Volatile private var isBusy = false
-
- @Volatile private var listening = false
+ private lateinit var chatWindow: CallChatWindow
+ private lateinit var callController: CallSessionController
override fun onCreate() {
super.onCreate()
@@ -57,18 +56,52 @@ class AssistiveBallService : Service() {
val s = settingsRepository.load()
ttsEngine = TtsEngine(this, s.ttsApiBaseUrl, s.apiKey)
sttEngine = SttEngine(this, s.sttApiBaseUrl, s.apiKey)
- quickAsk = QuickAskEngine(
+ callController = CallSessionController(
+ appContext = applicationContext,
+ scope = scope,
settingsRepository = settingsRepository,
sttEngine = sttEngine,
- ttsEngine = ttsEngine,
- llmProvider = ::buildLlmClient
+ ttsEngine = ttsEngine
)
+ chatWindow = CallChatWindow(this).apply {
+ onStart = { startOrResumeCall() }
+ onPause = { callController.pause() }
+ onEnd = { endCall() }
+ }
overlay = AssistiveBallOverlay(this).apply {
- onOpenChat = { openChat() }
onDismiss = { stopBall() }
- onStartTalk = { withScreen -> startTalk(withScreen) }
- onStopTalk = { stopTalk() }
+ onStartCall = { startOrResumeCall() }
+ onPauseCall = { callController.pause() }
+ onEndCall = { endCall() }
+ onToggleChatWindow = { if (chatWindow.isShowing()) chatWindow.hide() else chatWindow.show() }
+ isCallActive = { callController.isActive() }
+ }
+ callController.onError = { overlay.showError(it) }
+ callController.onCaptureChrome = { hide ->
+ if (hide) {
+ overlay.hideChromeForCapture()
+ chatWindow.setVisibleForCapture(false)
+ } else {
+ overlay.showChromeAfterCapture()
+ chatWindow.setVisibleForCapture(true)
+ }
+ }
+
+ scope.launch {
+ callController.state.collect { state ->
+ overlay.setCallActive(state != CallState.IDLE)
+ chatWindow.setStatus(state, callController.statusLine.value)
+ if (state == CallState.IDLE) chatWindow.hide()
+ }
+ }
+ scope.launch {
+ callController.transcript.collect { chatWindow.setTranscript(it) }
+ }
+ scope.launch {
+ callController.statusLine.collect { chatWindow.setStatus(callController.state.value, it) }
}
+
+ sweepOrphanedCalls()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
@@ -90,139 +123,51 @@ class AssistiveBallService : Service() {
override fun onDestroy() {
_isRunning.value = false
+ callController.endCall()
+ chatWindow.hide()
overlay.dismiss()
ttsEngine.shutdown()
scope.cancel()
super.onDestroy()
}
- // ---- Option 3: open chat ----
+ // ---- Call control ----
- private fun openChat() {
- android.util.Log.d("AssistiveBall", "openChat requested")
- val intent = packageManager.getLaunchIntentForPackage(packageName)?.apply {
- addFlags(
- Intent.FLAG_ACTIVITY_NEW_TASK or
- Intent.FLAG_ACTIVITY_SINGLE_TOP or
- Intent.FLAG_ACTIVITY_CLEAR_TOP
- )
- putExtra(MainActivity.EXTRA_OPEN_CHAT, true)
- } ?: Intent(this, MainActivity::class.java).apply {
- setAction(Intent.ACTION_MAIN)
- addCategory(Intent.CATEGORY_LAUNCHER)
- addFlags(
- Intent.FLAG_ACTIVITY_NEW_TASK or
- Intent.FLAG_ACTIVITY_SINGLE_TOP or
- Intent.FLAG_ACTIVITY_CLEAR_TOP
- )
- putExtra(MainActivity.EXTRA_OPEN_CHAT, true)
- }
-
- try {
- val pendingIntent = PendingIntent.getActivity(
- this,
- 1,
- intent,
- PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
- )
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
- val options = android.app.ActivityOptions.makeBasic()
- options.pendingIntentBackgroundActivityStartMode =
- android.app.ActivityOptions.MODE_BACKGROUND_ACTIVITY_START_ALLOWED
- pendingIntent.send(this, 0, null, null, null, null, options.toBundle())
- android.util.Log.d("AssistiveBall", "PendingIntent sent with ActivityOptions")
- } else {
- pendingIntent.send()
- android.util.Log.d("AssistiveBall", "PendingIntent sent")
- }
- } catch (e: Exception) {
- android.util.Log.e("AssistiveBall", "PendingIntent.send() failed", e)
- try {
- startActivity(intent)
- android.util.Log.d("AssistiveBall", "startActivity() called as fallback")
- } catch (e2: Exception) {
- android.util.Log.e("AssistiveBall", "startActivity() also failed", e2)
- }
+ private fun startOrResumeCall() {
+ if (callController.state.value == CallState.PAUSED) {
+ callController.resume()
+ } else {
+ callController.startCall()
}
}
- // ---- Options 1 & 2: press & talk ----
-
- private var pendingWithScreen = false
-
- private fun startTalk(withScreen: Boolean) {
- if (isBusy) return
- if (buildLlmClient() == null) {
- overlay.showError("Set up your API key in Gotcha first.")
- return
- }
- if (!quickAsk.canListen()) {
- overlay.showError("No speech-to-text provider is configured. Enable one in Settings.")
- return
- }
- val started = quickAsk.startListening()
- if (!started) {
- overlay.showError("Couldn't start listening. Check the microphone permission.")
- return
- }
- listening = true
- pendingWithScreen = withScreen
- overlay.showListening()
+ private fun endCall() {
+ callController.endCall()
+ chatWindow.hide()
}
- private fun stopTalk() {
- if (!listening) return
- listening = false
- val withScreen = pendingWithScreen
- isBusy = true
- scope.launch {
+ /**
+ * Call sessions are deleted when a call ends; anything still on disk is
+ * left over from a crash or process kill, so clear it on startup.
+ */
+ private fun sweepOrphanedCalls() {
+ scope.launch(Dispatchers.IO) {
+ val repo = ChatHistoryRepository(applicationContext, "calls")
+ repo.listSessions().forEach { repo.deleteSession(it.id) }
try {
- val question = quickAsk.stopAndTranscribe()
- if (question.isBlank()) {
- overlay.showError("I didn't catch that. Try again.")
- return@launch
- }
-
- var screenshot: String? = null
- var screenText: String? = null
- if (withScreen) {
- // Screen questions require the accessibility service (it provides both
- // the screenshot and the on-screen text). Guide the user if it's off.
- if (!quickAsk.isAccessibilityAvailable()) {
- overlay.showError(
- "I can't see your screen yet. Turn on Gotcha under " +
- "Settings ▸ Accessibility, then use Screen Share again. " +
- "(For a screen-free question, use the Talk option.)"
- )
- return@launch
- }
- // Hide our own overlays so they aren't captured, and let the compositor
- // paint a clean frame of the underlying app before we grab it.
- overlay.hideChromeForCapture()
- delay(350)
- screenshot = quickAsk.captureScreenBase64()
- screenText = quickAsk.captureScreenText()
- overlay.showChromeAfterCapture()
- }
-
- overlay.showThinking()
- val answer = quickAsk.ask(question, screenshot, screenText, screenRequested = withScreen)
- overlay.showAnswer(answer)
- quickAsk.speak(answer)
- } catch (e: Exception) {
- overlay.showError(friendlyError(e))
- } finally {
- isBusy = false
- }
+ File(CallSessionController.CALLS_WORKING_ROOT).deleteRecursively()
+ } catch (_: Exception) { }
}
}
// ---- Lifecycle helpers ----
private fun stopBall() {
- // Keep the persisted toggle in sync when the ball is hidden from its own
- // menu (not just from the in-app toggle), so the app reopens with it off.
+ // Keep the persisted toggle in sync when the ball is hidden by the
+ // drag-to-✕ gesture (not just from the in-app toggle), so the app
+ // reopens with it off. An active call is ended (and deleted) first.
+ callController.endCall()
+ chatWindow.hide()
settingsRepository.save(settingsRepository.load().copy(assistiveBallEnabled = false))
_isRunning.value = false
overlay.dismiss()
@@ -230,21 +175,6 @@ class AssistiveBallService : Service() {
stopSelf()
}
- private fun buildLlmClient(): LLMClient? {
- val s = settingsRepository.load()
- return if (s.isConfigured) {
- LLMClient(
- apiKey = s.apiKey,
- baseUrl = s.baseUrl,
- model = s.model,
- context = applicationContext,
- apiTimeoutSeconds = s.apiTimeoutSeconds
- )
- } else {
- null
- }
- }
-
private fun startAsForeground() {
createChannel()
val tapIntent = PendingIntent.getActivity(
@@ -255,7 +185,7 @@ class AssistiveBallService : Service() {
)
val notification: Notification = Notification.Builder(this, CHANNEL_ID)
.setContentTitle("Gotcha assistive ball")
- .setContentText("Tap the floating ball to ask about your screen.")
+ .setContentText("Tap the ball for call controls. Long-press it to start a voice call.")
.setSmallIcon(android.R.drawable.ic_menu_compass)
.setContentIntent(tapIntent)
.setOngoing(true)
@@ -294,23 +224,13 @@ class AssistiveBallService : Service() {
}
}
- private fun friendlyError(e: Exception): String = when {
- e is retrofit2.HttpException && e.code() == 401 ->
- "The API rejected the key (401). Check your API key in settings."
- e is retrofit2.HttpException ->
- "The API returned an error (HTTP ${e.code()})."
- e is java.io.IOException ->
- "Network problem. Check your connection and try again."
- else -> "Something went wrong: ${e.message}"
- }
-
companion object {
const val ACTION_START = "com.gotcha.assistiveball.START"
const val ACTION_STOP = "com.gotcha.assistiveball.STOP"
private val _isRunning = MutableStateFlow(false)
- /** Live running state of the ball, so UI toggles can track "Hide ball" too. */
+ /** Live running state of the ball, so UI toggles can track hide gestures too. */
val isRunning: StateFlow<Boolean> = _isRunning.asStateFlow()
private const val CHANNEL_ID = "assistive_ball"
private const val NOTIFICATION_ID = 4711
diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
index 2064938..85039da 100644
--- a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt
@@ -11,6 +11,7 @@ import android.os.Handler
import android.os.Looper
import android.provider.Settings
import android.view.Gravity
+import android.view.HapticFeedbackConstants
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
@@ -23,21 +24,21 @@ import android.widget.ScrollView
import android.widget.TextView
import com.gotcha.R
import kotlin.math.abs
+import kotlin.math.hypot
/**
- * The floating "assistive ball" drawn over other apps via SYSTEM_ALERT_WINDOW.
+ * The floating "assistive ball" drawn over other apps via SYSTEM_ALERT_WINDOW,
+ * reworked into a Messenger-Bubbles-style call head:
+ *
+ * - Tap: Start / Pause / End menu when idle; toggles the call chat window
+ * during a call.
+ * - Long-press (3s idle / 5s during a call): start or end a voice call.
+ * - Drag: moves the ball; an ✕ target appears at the bottom of the screen
+ * and dropping the ball on it hides the ball (Messenger-style dismiss).
*
* Structurally modelled on [ConfirmationOverlay]: a [WindowManager] +
* [WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY] window, gated on
* [Settings.canDrawOverlays], with all window mutations posted to the main thread.
- *
- * It manages three independent windows:
- * - the draggable ball itself (always visible while the service runs),
- * - an expanded menu with the three options, and
- * - a status/answer card that reports listening/thinking/answer/error state.
- *
- * The ball is touchable (no FLAG_NOT_TOUCHABLE) so it can be dragged and tapped; the
- * two "talk" options are press-and-hold (down = start recording, up = stop & ask).
*/
@Suppress("TooManyFunctions")
class AssistiveBallOverlay(context: Context) {
@@ -49,14 +50,19 @@ class AssistiveBallOverlay(context: Context) {
private val touchSlop = ViewConfiguration.get(context).scaledTouchSlop
// Callbacks — set by the host service before [show].
- var onOpenChat: () -> Unit = {}
var onDismiss: () -> Unit = {}
- var onStartTalk: (withScreen: Boolean) -> Unit = {}
- var onStopTalk: () -> Unit = {}
+ var onStartCall: () -> Unit = {}
+ var onPauseCall: () -> Unit = {}
+ var onEndCall: () -> Unit = {}
+ var onToggleChatWindow: () -> Unit = {}
+
+ /** Queried per gesture: is a voice call active (any non-idle state)? */
+ var isCallActive: () -> Boolean = { false }
private var ballView: View? = null
private var menuView: View? = null
private var cardView: View? = null
+ private var dismissTargetView: View? = null
private val ballParams: WindowManager.LayoutParams by lazy { ballLayoutParams() }
@@ -81,16 +87,24 @@ class AssistiveBallOverlay(context: Context) {
mainHandler.post {
removeMenu()
removeCard()
+ removeDismissTarget()
ballView?.let { safeRemove(it) }
ballView = null
}
}
+ /** Tint the ball's rim green while a call is active so the 5s end gesture is discoverable. */
+ fun setCallActive(active: Boolean) {
+ mainHandler.post {
+ (ballView as? ImageView)?.foreground = ballRim(active)
+ }
+ }
+
// ---- Capture chrome ----
/**
* Hide all of our own overlay windows (menu, status card, and the ball) so they are
- * not baked into a screen capture taken for the "screen share" flow. Call
+ * not baked into a screen capture taken for the call's screen context. Call
* [showChromeAfterCapture] once the screenshot has been taken.
*/
fun hideChromeForCapture() {
@@ -101,18 +115,15 @@ class AssistiveBallOverlay(context: Context) {
}
}
- /** Restore the ball after a capture (the status card is shown separately). */
+ /** Restore the ball after a capture. */
fun showChromeAfterCapture() {
mainHandler.post {
ballView?.visibility = View.VISIBLE
}
}
- // ---- Status / answer card ----
+ // ---- Status card (errors only) ----
- fun showListening() = showCard("Listening… release to send", showClose = false)
- fun showThinking() = showCard("Thinking…", showClose = false)
- fun showAnswer(text: String) = showCard(text, showClose = true)
fun showError(text: String) = showCard(text, showClose = true)
// ---- Ball ----
@@ -129,21 +140,34 @@ class AssistiveBallOverlay(context: Context) {
}
}
clipToOutline = true
- // Subtle rim so the logo reads on any background.
- foreground = GradientDrawable().apply {
- shape = GradientDrawable.OVAL
- setStroke(dp(1), Color.parseColor("#66FFFFFF"))
- }
+ // Subtle rim so the logo reads on any background (green during calls).
+ foreground = ballRim(isCallActive())
setOnTouchListener(ballTouchListener())
}
}
+ private fun ballRim(callActive: Boolean) = GradientDrawable().apply {
+ shape = GradientDrawable.OVAL
+ if (callActive) {
+ setStroke(dp(2), Color.parseColor("#CC34C759"))
+ } else {
+ setStroke(dp(1), Color.parseColor("#66FFFFFF"))
+ }
+ }
+
+ @Suppress("CyclomaticComplexMethod")
private fun ballTouchListener(): View.OnTouchListener {
var startX = 0
var startY = 0
var touchDownRawX = 0f
var touchDownRawY = 0f
var dragging = false
+ var longPressFired = false
+ val longPressRunnable = Runnable {
+ longPressFired = true
+ ballView?.performHapticFeedback(HapticFeedbackConstants.LONG_PRESS)
+ if (isCallActive()) onEndCall() else onStartCall()
+ }
return View.OnTouchListener { _, event ->
when (event.action) {
MotionEvent.ACTION_DOWN -> {
@@ -152,14 +176,21 @@ class AssistiveBallOverlay(context: Context) {
touchDownRawX = event.rawX
touchDownRawY = event.rawY
dragging = false
+ longPressFired = false
+ mainHandler.postDelayed(
+ longPressRunnable,
+ if (isCallActive()) LONG_PRESS_END_MS else LONG_PRESS_START_MS
+ )
true
}
MotionEvent.ACTION_MOVE -> {
val dx = (event.rawX - touchDownRawX).toInt()
val dy = (event.rawY - touchDownRawY).toInt()
- if (!dragging && (abs(dx) > touchSlop || abs(dy) > touchSlop)) {
+ if (!dragging && !longPressFired && (abs(dx) > touchSlop || abs(dy) > touchSlop)) {
dragging = true
+ mainHandler.removeCallbacks(longPressRunnable)
removeMenu()
+ showDismissTarget()
}
if (dragging) {
ballParams.x = startX + dx
@@ -167,17 +198,29 @@ class AssistiveBallOverlay(context: Context) {
try {
windowManager.updateViewLayout(ballView, ballParams)
} catch (_: Exception) { }
+ updateDismissTargetHighlight(isOverDismissTarget())
}
true
}
MotionEvent.ACTION_UP -> {
- if (dragging) {
- clampBallIntoBounds()
- } else {
- toggleMenu()
+ mainHandler.removeCallbacks(longPressRunnable)
+ val droppedOnTarget = dragging && isOverDismissTarget()
+ removeDismissTarget()
+ when {
+ longPressFired -> { /* handled by the runnable */ }
+ droppedOnTarget -> onDismiss()
+ dragging -> clampBallIntoBounds()
+ isCallActive() -> onToggleChatWindow()
+ else -> toggleMenu()
}
true
}
+ MotionEvent.ACTION_CANCEL -> {
+ mainHandler.removeCallbacks(longPressRunnable)
+ removeDismissTarget()
+ if (dragging) clampBallIntoBounds()
+ true
+ }
else -> false
}
}
@@ -185,8 +228,8 @@ class AssistiveBallOverlay(context: Context) {
private fun clampBallIntoBounds() {
val metrics = appContext.resources.displayMetrics
- val maxX = metrics.widthPixels - dp(56)
- val maxY = metrics.heightPixels - dp(56)
+ val maxX = metrics.widthPixels - dp(BALL_SIZE_DP)
+ val maxY = metrics.heightPixels - dp(BALL_SIZE_DP)
ballParams.x = ballParams.x.coerceIn(0, maxX.coerceAtLeast(0))
ballParams.y = ballParams.y.coerceIn(0, maxY.coerceAtLeast(0))
try {
@@ -194,13 +237,70 @@ class AssistiveBallOverlay(context: Context) {
} catch (_: Exception) { }
}
- // ---- Expanded menu ----
+ // ---- Dismiss target (drag the ball onto the ✕ to hide it) ----
+
+ private fun showDismissTarget() {
+ if (dismissTargetView != null) return
+ val target = TextView(appContext).apply {
+ text = "✕"
+ textSize = 22f
+ setTextColor(Color.WHITE)
+ gravity = Gravity.CENTER
+ background = GradientDrawable().apply {
+ shape = GradientDrawable.OVAL
+ setColor(Color.parseColor("#CC222222"))
+ setStroke(dp(2), Color.parseColor("#66FFFFFF"))
+ }
+ }
+ val params = WindowManager.LayoutParams(
+ dp(DISMISS_TARGET_SIZE_DP),
+ dp(DISMISS_TARGET_SIZE_DP),
+ overlayType(),
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or
+ WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
+ PixelFormat.TRANSLUCENT
+ ).apply {
+ gravity = Gravity.BOTTOM or Gravity.CENTER_HORIZONTAL
+ y = dp(DISMISS_TARGET_MARGIN_DP)
+ }
+ try {
+ windowManager.addView(target, params)
+ dismissTargetView = target
+ } catch (_: Exception) {
+ dismissTargetView = null
+ }
+ }
+
+ private fun removeDismissTarget() {
+ dismissTargetView?.let { safeRemove(it) }
+ dismissTargetView = null
+ }
+
+ private fun updateDismissTargetHighlight(hovering: Boolean) {
+ val scale = if (hovering) 1.25f else 1f
+ dismissTargetView?.scaleX = scale
+ dismissTargetView?.scaleY = scale
+ }
+
+ /** True when the ball's centre is within snapping distance of the ✕ target's centre. */
+ private fun isOverDismissTarget(): Boolean {
+ if (dismissTargetView == null) return false
+ val metrics = appContext.resources.displayMetrics
+ val ballCenterX = ballParams.x + dp(BALL_SIZE_DP) / 2f
+ val ballCenterY = ballParams.y + dp(BALL_SIZE_DP) / 2f
+ val targetCenterX = metrics.widthPixels / 2f
+ val targetCenterY = metrics.heightPixels -
+ dp(DISMISS_TARGET_MARGIN_DP) - dp(DISMISS_TARGET_SIZE_DP) / 2f
+ val distance = hypot(ballCenterX - targetCenterX, ballCenterY - targetCenterY)
+ return distance <= dp(DISMISS_SNAP_RADIUS_DP)
+ }
+
+ // ---- Expanded menu (idle only; taps during a call toggle the chat window) ----
private fun toggleMenu() {
if (menuView != null) removeMenu() else showMenu()
}
- @SuppressLint("ClickableViewAccessibility")
private fun showMenu() {
removeMenu()
val container = LinearLayout(appContext).apply {
@@ -213,19 +313,25 @@ class AssistiveBallOverlay(context: Context) {
}
}
- container.addView(menuTitle("Gotcha"))
- container.addView(talkButton("🖥 Screen Share — hold & talk", withScreen = true))
- container.addView(talkButton("🎤 Talk — hold & talk", withScreen = false))
+ val active = isCallActive()
+ container.addView(menuTitle("Gotcha Call"))
container.addView(
- tapButton("💬 Open Chat") {
+ tapButton("▶ Start") {
removeMenu()
- onOpenChat()
- }
+ onStartCall()
+ }.apply { isEnabled = !active }
)
container.addView(
- tapButton("✕ Hide ball") {
- onDismiss()
- }
+ tapButton("⏸ Pause") {
+ removeMenu()
+ onPauseCall()
+ }.apply { isEnabled = active }
+ )
+ container.addView(
+ tapButton("⏹ End") {
+ removeMenu()
+ onEndCall()
+ }.apply { isEnabled = active }
)
val params = menuLayoutParams()
@@ -244,32 +350,6 @@ class AssistiveBallOverlay(context: Context) {
setPadding(dp(4), 0, dp(4), dp(8))
}
- @SuppressLint("ClickableViewAccessibility")
- private fun talkButton(label: String, withScreen: Boolean): Button {
- return Button(appContext).apply {
- text = label
- isAllCaps = false
- // Press-and-hold. The menu (and thus this button) must stay attached until
- // ACTION_UP, otherwise the button would never receive the release event.
- setOnTouchListener { v, event ->
- when (event.action) {
- MotionEvent.ACTION_DOWN -> {
- v.isPressed = true
- onStartTalk(withScreen)
- true
- }
- MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
- v.isPressed = false
- onStopTalk()
- removeMenu()
- true
- }
- else -> false
- }
- }
- }
- }
-
private fun tapButton(label: String, onClick: () -> Unit): Button {
return Button(appContext).apply {
text = label
@@ -358,8 +438,8 @@ class AssistiveBallOverlay(context: Context) {
private fun ballLayoutParams(): WindowManager.LayoutParams =
WindowManager.LayoutParams(
- dp(56),
- dp(56),
+ dp(BALL_SIZE_DP),
+ dp(BALL_SIZE_DP),
overlayType(),
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
@@ -397,4 +477,13 @@ class AssistiveBallOverlay(context: Context) {
private fun dp(value: Int): Int =
(value * appContext.resources.displayMetrics.density).toInt()
+
+ private companion object {
+ const val BALL_SIZE_DP = 56
+ const val LONG_PRESS_START_MS = 3000L
+ const val LONG_PRESS_END_MS = 5000L
+ const val DISMISS_TARGET_SIZE_DP = 64
+ const val DISMISS_TARGET_MARGIN_DP = 32
+ const val DISMISS_SNAP_RADIUS_DP = 56
+ }
}
diff --git a/app/src/main/java/com/gotcha/ui/CallChatWindow.kt b/app/src/main/java/com/gotcha/ui/CallChatWindow.kt
new file mode 100644
index 0000000..69820f3
--- /dev/null
+++ b/app/src/main/java/com/gotcha/ui/CallChatWindow.kt
@@ -0,0 +1,278 @@
+package com.gotcha.ui
+
+import android.content.Context
+import android.graphics.Color
+import android.graphics.PixelFormat
+import android.graphics.drawable.GradientDrawable
+import android.os.Build
+import android.os.Handler
+import android.os.Looper
+import android.view.Gravity
+import android.view.View
+import android.view.WindowManager
+import android.widget.Button
+import android.widget.LinearLayout
+import android.widget.ScrollView
+import android.widget.TextView
+import com.gotcha.agent.MessageKind
+import com.gotcha.service.CallState
+import com.gotcha.service.CallTranscriptItem
+
+/**
+ * Messenger-style expanded chat window for an active voice call, drawn as a
+ * bottom-anchored overlay (same SYSTEM_ALERT_WINDOW pattern as
+ * [AssistiveBallOverlay]). Shows the live transcript plus a header with the
+ * call status and Start / Pause / End controls. Voice-only: there is no text
+ * input row, so the window never needs focus (FLAG_NOT_FOCUSABLE throughout).
+ */
+@Suppress("TooManyFunctions")
+class CallChatWindow(context: Context) {
+
+ private val appContext = context.applicationContext
+ private val mainHandler = Handler(Looper.getMainLooper())
+ private val windowManager: WindowManager
+ get() = appContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
+
+ // Callbacks — set by the host service before [show].
+ var onStart: () -> Unit = {}
+ var onPause: () -> Unit = {}
+ var onEnd: () -> Unit = {}
+
+ private var rootView: View? = null
+ private var statusText: TextView? = null
+ private var startButton: Button? = null
+ private var pauseButton: Button? = null
+ private var endButton: Button? = null
+ private var listContainer: LinearLayout? = null
+ private var scrollView: ScrollView? = null
+
+ // Last known state so a freshly (re)built window renders current data.
+ private var lastState: CallState = CallState.IDLE
+ private var lastStatusLine: String? = null
+ private var lastItems: List<CallTranscriptItem> = emptyList()
+
+ fun show() {
+ mainHandler.post {
+ if (rootView != null) return@post
+ val root = buildWindow()
+ try {
+ windowManager.addView(root, layoutParams())
+ rootView = root
+ renderStatus()
+ renderTranscript()
+ } catch (_: Exception) {
+ rootView = null
+ }
+ }
+ }
+
+ fun hide() {
+ mainHandler.post {
+ rootView?.let {
+ try {
+ windowManager.removeView(it)
+ } catch (_: Exception) { }
+ }
+ rootView = null
+ statusText = null
+ startButton = null
+ pauseButton = null
+ endButton = null
+ listContainer = null
+ scrollView = null
+ }
+ }
+
+ fun isShowing(): Boolean = rootView != null
+
+ /** Temporarily hide the window so it is not baked into a screen capture. */
+ fun setVisibleForCapture(visible: Boolean) {
+ mainHandler.post {
+ rootView?.visibility = if (visible) View.VISIBLE else View.GONE
+ }
+ }
+
+ fun setStatus(state: CallState, statusLine: String?) {
+ mainHandler.post {
+ lastState = state
+ lastStatusLine = statusLine
+ renderStatus()
+ }
+ }
+
+ fun setTranscript(items: List<CallTranscriptItem>) {
+ mainHandler.post {
+ lastItems = items
+ renderTranscript()
+ }
+ }
+
+ // ---- Rendering ----
+
+ private fun renderStatus() {
+ val state = lastState
+ statusText?.text = when (state) {
+ CallState.IDLE -> "No active call"
+ CallState.STARTING -> "Starting…"
+ CallState.LISTENING -> "🎤 Listening…"
+ CallState.THINKING -> lastStatusLine ?: "Thinking…"
+ CallState.SPEAKING -> "🔊 Speaking…"
+ CallState.WAITING_USER -> "Waiting for you…"
+ CallState.PAUSED -> "⏸ Paused"
+ CallState.ENDING -> "Ending…"
+ }
+ startButton?.isEnabled = state == CallState.PAUSED || state == CallState.IDLE
+ pauseButton?.isEnabled = state != CallState.IDLE && state != CallState.PAUSED && state != CallState.ENDING
+ endButton?.isEnabled = state != CallState.IDLE && state != CallState.ENDING
+ }
+
+ private fun renderTranscript() {
+ val container = listContainer ?: return
+ container.removeAllViews()
+ for (item in lastItems) {
+ container.addView(bubbleFor(item))
+ }
+ scrollView?.post { scrollView?.fullScroll(View.FOCUS_DOWN) }
+ }
+
+ private fun bubbleFor(item: CallTranscriptItem): View {
+ val row = LinearLayout(appContext).apply {
+ orientation = LinearLayout.HORIZONTAL
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ LinearLayout.LayoutParams.WRAP_CONTENT
+ ).apply { setMargins(0, dp(3), 0, dp(3)) }
+ }
+ val bubble = TextView(appContext).apply {
+ text = if (item.kind == MessageKind.SUBAGENT) "◆ ${item.text}" else item.text
+ setPadding(dp(12), dp(8), dp(12), dp(8))
+ maxWidth = (appContext.resources.displayMetrics.widthPixels * MAX_BUBBLE_WIDTH_FRACTION).toInt()
+ }
+ when (item.kind) {
+ MessageKind.USER -> {
+ row.gravity = Gravity.END
+ bubble.setTextColor(Color.WHITE)
+ bubble.textSize = 14f
+ bubble.background = bubbleBackground("#6750A4")
+ }
+ MessageKind.ASSISTANT, MessageKind.SUBAGENT -> {
+ row.gravity = Gravity.START
+ bubble.setTextColor(Color.parseColor("#EEEEEE"))
+ bubble.textSize = 14f
+ bubble.background = bubbleBackground("#2A2A2A")
+ }
+ MessageKind.TOOL -> {
+ row.gravity = Gravity.START
+ bubble.setTextColor(Color.parseColor("#9A9A9A"))
+ bubble.textSize = 11f
+ bubble.background = null
+ }
+ MessageKind.ERROR -> {
+ row.gravity = Gravity.START
+ bubble.setTextColor(Color.parseColor("#CF6679"))
+ bubble.textSize = 12f
+ bubble.background = null
+ }
+ }
+ row.addView(bubble)
+ return row
+ }
+
+ private fun bubbleBackground(color: String) = GradientDrawable().apply {
+ cornerRadius = dp(16).toFloat()
+ setColor(Color.parseColor(color))
+ }
+
+ // ---- Window construction ----
+
+ private fun buildWindow(): View {
+ val root = LinearLayout(appContext).apply {
+ orientation = LinearLayout.VERTICAL
+ setPadding(dp(16), dp(12), dp(16), dp(12))
+ background = GradientDrawable().apply {
+ cornerRadii = floatArrayOf(
+ dp(20).toFloat(), dp(20).toFloat(), dp(20).toFloat(), dp(20).toFloat(),
+ 0f, 0f, 0f, 0f
+ )
+ setColor(Color.parseColor("#1E1E1E"))
+ setStroke(dp(1), Color.parseColor("#3A3A3A"))
+ }
+ }
+
+ val header = LinearLayout(appContext).apply {
+ orientation = LinearLayout.HORIZONTAL
+ gravity = Gravity.CENTER_VERTICAL
+ }
+ val status = TextView(appContext).apply {
+ setTextColor(Color.parseColor("#EADDFF"))
+ textSize = 13f
+ layoutParams = LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
+ }
+ val start = headerButton("▶") { onStart() }
+ val pauseBtn = headerButton("⏸") { onPause() }
+ val end = headerButton("⏹") { onEnd() }
+ header.addView(status)
+ header.addView(start)
+ header.addView(pauseBtn)
+ header.addView(end)
+
+ val scroll = ScrollView(appContext).apply {
+ isVerticalScrollBarEnabled = true
+ layoutParams = LinearLayout.LayoutParams(
+ LinearLayout.LayoutParams.MATCH_PARENT,
+ 0,
+ 1f
+ ).apply { setMargins(0, dp(8), 0, 0) }
+ }
+ val list = LinearLayout(appContext).apply {
+ orientation = LinearLayout.VERTICAL
+ }
+ scroll.addView(list)
+
+ root.addView(header)
+ root.addView(scroll)
+
+ statusText = status
+ startButton = start
+ pauseButton = pauseBtn
+ endButton = end
+ listContainer = list
+ scrollView = scroll
+ return root
+ }
+
+ private fun headerButton(label: String, onClick: () -> Unit) = Button(appContext).apply {
+ text = label
+ isAllCaps = false
+ minWidth = dp(48)
+ minimumWidth = dp(48)
+ setOnClickListener { onClick() }
+ }
+
+ private fun layoutParams(): WindowManager.LayoutParams {
+ val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
+ } else {
+ @Suppress("DEPRECATION")
+ WindowManager.LayoutParams.TYPE_PHONE
+ }
+ val metrics = appContext.resources.displayMetrics
+ return WindowManager.LayoutParams(
+ WindowManager.LayoutParams.MATCH_PARENT,
+ (metrics.heightPixels * WINDOW_HEIGHT_FRACTION).toInt(),
+ type,
+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
+ PixelFormat.TRANSLUCENT
+ ).apply {
+ gravity = Gravity.BOTTOM
+ }
+ }
+
+ private fun dp(value: Int): Int =
+ (value * appContext.resources.displayMetrics.density).toInt()
+
+ private companion object {
+ const val WINDOW_HEIGHT_FRACTION = 0.65f
+ const val MAX_BUBBLE_WIDTH_FRACTION = 0.78f
+ }
+}