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: Implement assistive ball feature with speech recognition and screen sharing
Durganshu Mishradc2642dcd70b
diff --git a/.gitignore b/.gitignoreindex 3189d8d..154d7ec 100644--- a/.gitignore+++ b/.gitignore@@ -3,6 +3,10 @@*.ap_*.aab+# Signing keys — never commit these+*.jks+*.keystore+# Files for the ART/Dalvik VM*.dexdiff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 17b3e13..219d303 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -1,9 +1,17 @@+import java.util.Properties+plugins {id("com.android.application")id("org.jetbrains.kotlin.android")id("org.jetbrains.kotlin.plugin.serialization")}+// Load signing credentials from local.properties (gitignored), if present.+val keystoreProps = Properties().apply {+ val f = rootProject.file("local.properties")+ if (f.exists()) f.inputStream().use { load(it) }+}+android {namespace = "com.gotcha"compileSdk = 34@@ -21,9 +29,23 @@ android {}}+ signingConfigs {+ // Only wired up when release signing keys are provided in local.properties.+ if (keystoreProps.containsKey("RELEASE_STORE_FILE")) {+ create("release") {+ storeFile = file(keystoreProps.getProperty("RELEASE_STORE_FILE"))+ storePassword = keystoreProps.getProperty("RELEASE_STORE_PASSWORD")+ keyAlias = keystoreProps.getProperty("RELEASE_KEY_ALIAS")+ keyPassword = keystoreProps.getProperty("RELEASE_KEY_PASSWORD")+ }+ }+ }+buildTypes {release {isMinifyEnabled = false+ // Use the release signing config only if it was configured above.+ signingConfig = signingConfigs.findByName("release")proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"),"proguard-rules.pro"diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 4b2a499..1e7856e 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -40,6 +40,13 @@android:name="android.permission.MANAGE_EXTERNAL_STORAGE"tools:ignore="ScopedStorage" /><uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <!-- Assistive ball: records audio (STT) from the foreground service and runs as a+ floating overlay assistant. -->+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MICROPHONE" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_SPECIAL_USE" />+ <!-- Android 13+: shows the assistive-ball foreground-service notification (service runs+ regardless of grant). -->+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /><!-- Needed on API 30+ so open_app can see other launchable apps. --><queries>@@ -93,6 +100,17 @@android:resource="@xml/accessibility_service_config" /></service>+ <!-- Assistive ball: floating overlay assistant hosted in a foreground service.+ Records audio for STT (microphone type) and is a persistent overlay (specialUse). -->+ <service+ android:name=".service.AssistiveBallService"+ android:exported="false"+ android:foregroundServiceType="microphone|specialUse">+ <property+ android:name="android.app.PROPERTY_SPECIAL_USE_FGS_SUBTYPE"+ android:value="floating_assistant_overlay" />+ </service>+<!-- Tier 3: NotificationListenerService — reads/dismisses notifications, media control. --><serviceandroid:name=".service.GotchaNotificationListenerService"diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex fc5f8c0..2af1460 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -36,6 +36,7 @@ import kotlinx.coroutines.withContextimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClientimport kotlinx.serialization.json.JsonPrimitive+import com.gotcha.service.AssistiveBallServiceimport com.gotcha.service.GotchaDeviceAdminReceiverimport com.gotcha.tools.ToolResultimport com.gotcha.ui.ChatScreen@@ -51,6 +52,9 @@ class MainActivity : ComponentActivity() {private val chatViewModel: ChatViewModel by viewModels()private lateinit var settingsRepository: SettingsRepository+ /** Set when launched from the assistive ball's "Open Chat" option. */+ private var openChatRequested by mutableStateOf(false)+private val permissionLauncher =registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->Toast.makeText(@@ -64,6 +68,7 @@ class MainActivity : ComponentActivity() {override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)settingsRepository = SettingsRepository(this)+ openChatRequested = intent?.getBooleanExtra(EXTRA_OPEN_CHAT, false) == true// Phase 7: tools report missing permissions; request them here on first use.// "special:*" markers map to per-access Settings deep-links; anything else is a@@ -137,11 +142,56 @@ class MainActivity : ComponentActivity() {}}+ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ setIntent(intent)+ if (intent.getBooleanExtra(EXTRA_OPEN_CHAT, false)) {+ openChatRequested = true+ }+ }+override fun onStart() {super.onStart()chatViewModel.setForeground(true)}+ /**+ * Start or stop the assistive-ball foreground service. Returns the resulting+ * enabled state. When enabling without the overlay permission, deep-links the user+ * to grant it and leaves the ball disabled (they can toggle again afterwards).+ */+ private fun setAssistiveBall(enabled: Boolean): Boolean {+ if (enabled) {+ if (!AndroidSettings.canDrawOverlays(this)) {+ startActivity(+ Intent(+ AndroidSettings.ACTION_MANAGE_OVERLAY_PERMISSION,+ Uri.parse("package:$packageName")+ )+ )+ Toast.makeText(+ this,+ "Allow \"Display over other apps\", then turn the ball on again.",+ Toast.LENGTH_LONG+ ).show()+ persistAssistiveBall(false)+ return false+ }+ startForegroundService(AssistiveBallService.startIntent(this))+ persistAssistiveBall(true)+ return true+ } else {+ startService(AssistiveBallService.stopIntent(this))+ persistAssistiveBall(false)+ return false+ }+ }++ private fun persistAssistiveBall(enabled: Boolean) {+ val current = settingsRepository.load()+ settingsRepository.save(current.copy(assistiveBallEnabled = enabled))+ }+override fun onStop() {super.onStop()chatViewModel.setForeground(false)@@ -156,9 +206,18 @@ class MainActivity : ComponentActivity() {mutableStateOf(if (settingsRepository.load().isConfigured) Route.SESSIONS else Route.SETTINGS)}var previousRoute by remember { mutableStateOf(Route.SESSIONS) }+ var assistiveBallOn by remember { mutableStateOf(settingsRepository.load().assistiveBallEnabled) }LaunchedEffect(Unit) { chatViewModel.refreshSettings() }+ // Honor the assistive ball's "Open Chat" option.+ LaunchedEffect(openChatRequested) {+ if (openChatRequested) {+ currentRoute = Route.CHAT+ openChatRequested = false+ }+ }+when (currentRoute) {Route.SETTINGS -> {BackHandler { currentRoute = previousRoute }@@ -196,7 +255,7 @@ class MainActivity : ComponentActivity() {Route.SESSIONS -> {SessionsScreen(sessions = sessions,- onSessionClick = { id ->+ onSessionClick = { id ->chatViewModel.openSession(id)currentRoute = Route.CHAT},@@ -208,6 +267,10 @@ class MainActivity : ComponentActivity() {onOpenSettings = {previousRoute = Route.SESSIONScurrentRoute = Route.SETTINGS+ },+ assistiveBallEnabled = assistiveBallOn,+ onToggleAssistiveBall = { enabled ->+ assistiveBallOn = setAssistiveBall(enabled)})}@@ -255,4 +318,9 @@ class MainActivity : ComponentActivity() {)response.choices.firstOrNull()?.message?.textContent?.take(60) ?: "empty response"}++ companion object {+ /** Intent extra: when true, launch straight into the chat screen. */+ const val EXTRA_OPEN_CHAT = "com.gotcha.OPEN_CHAT"+ }}diff --git a/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt b/app/src/main/java/com/gotcha/agent/QuickAskEngine.ktnew file mode 100644index 0000000..c5dc7cd--- /dev/null+++ b/app/src/main/java/com/gotcha/agent/QuickAskEngine.kt@@ -0,0 +1,163 @@+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.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?+) {+ 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 -> ""+ }+ }++ /**+ * 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).+ */+ suspend fun captureScreenBase64(): String? {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return null+ val service = GotchaAccessibilityService.instance ?: return null+ val bitmap = service.takeScreenshotBitmap() ?: 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.+ */+ suspend fun ask(question: String, screenshotBase64: String?, screenText: String?): String {+ val llm = llmProvider() ?: throw IllegalStateException("Not configured")+ val system = ChatMessage(role = "system", content = JsonPrimitive(SYSTEM_PROMPT))++ 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))+ 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/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 3864459..d9a5632 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -21,7 +21,8 @@ data class Settings(val sttProvider: AudioProvider = AudioProvider.NONE,val sttApiBaseUrl: String = "",val sttApiModel: String = "",- val autoReadReplies: Boolean = false+ val autoReadReplies: Boolean = false,+ val assistiveBallEnabled: Boolean = false) {val isConfigured: Boolean get() = apiKey.isNotBlank() && baseUrl.isNotBlank()@@ -62,7 +63,8 @@ class SettingsRepository(context: Context) {sttProvider = AudioProvider.valueOf(prefs.getString(KEY_STT_PROVIDER, "NONE") ?: "NONE"),sttApiBaseUrl = prefs.getString(KEY_STT_API_URL, "") ?: "",sttApiModel = prefs.getString(KEY_STT_API_MODEL, "") ?: "",- autoReadReplies = prefs.getBoolean(KEY_AUTO_READ, false)+ autoReadReplies = prefs.getBoolean(KEY_AUTO_READ, false),+ assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false))fun save(settings: Settings) {@@ -81,6 +83,7 @@ class SettingsRepository(context: Context) {.putString(KEY_STT_API_URL, settings.sttApiBaseUrl).putString(KEY_STT_API_MODEL, settings.sttApiModel).putBoolean(KEY_AUTO_READ, settings.autoReadReplies)+ .putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled).apply()}@@ -99,5 +102,6 @@ class SettingsRepository(context: Context) {const val KEY_STT_API_URL = "stt_api_url"const val KEY_STT_API_MODEL = "stt_api_model"const val KEY_AUTO_READ = "auto_read"+ const val KEY_ASSISTIVE_BALL = "assistive_ball_enabled"}}diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktnew file mode 100644index 0000000..6ded73f--- /dev/null+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -0,0 +1,254 @@+package com.gotcha.service++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+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.SettingsRepository+import com.gotcha.llm.LLMClient+import com.gotcha.ui.AssistiveBallOverlay+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.launch++/**+ * 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.+ *+ * Started/stopped from the in-app toggle via [ACTION_START] / [ACTION_STOP].+ */+class AssistiveBallService : Service() {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)++ private lateinit var settingsRepository: SettingsRepository+ 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++ override fun onCreate() {+ super.onCreate()+ settingsRepository = SettingsRepository(this)+ val s = settingsRepository.load()+ ttsEngine = TtsEngine(this, s.ttsApiBaseUrl, s.apiKey)+ sttEngine = SttEngine(this, s.sttApiBaseUrl, s.apiKey)+ quickAsk = QuickAskEngine(+ settingsRepository = settingsRepository,+ sttEngine = sttEngine,+ ttsEngine = ttsEngine,+ llmProvider = ::buildLlmClient+ )+ overlay = AssistiveBallOverlay(this).apply {+ onOpenChat = { openChat() }+ onDismiss = { stopBall() }+ onStartTalk = { withScreen -> startTalk(withScreen) }+ onStopTalk = { stopTalk() }+ }+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ when (intent?.action) {+ ACTION_STOP -> {+ stopBall()+ return START_NOT_STICKY+ }+ else -> {+ startAsForeground()+ overlay.show()+ }+ }+ return START_STICKY+ }++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onDestroy() {+ overlay.dismiss()+ ttsEngine.shutdown()+ scope.cancel()+ super.onDestroy()+ }++ // ---- Option 3: open chat ----++ private fun openChat() {+ val intent = Intent(this, MainActivity::class.java)+ .addFlags(+ Intent.FLAG_ACTIVITY_NEW_TASK or+ Intent.FLAG_ACTIVITY_SINGLE_TOP or+ Intent.FLAG_ACTIVITY_CLEAR_TOP+ )+ .putExtra(MainActivity.EXTRA_OPEN_CHAT, true)+ startActivity(intent)+ }++ // ---- 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 stopTalk() {+ if (!listening) return+ listening = false+ val withScreen = pendingWithScreen+ isBusy = true+ scope.launch {+ try {+ val question = quickAsk.stopAndTranscribe()+ if (question.isBlank()) {+ overlay.showError("I didn't catch that. Try again.")+ return@launch+ }+ overlay.showThinking()++ var screenshot: String? = null+ var screenText: String? = null+ if (withScreen) {+ // If neither a screenshot (API 30+) nor on-screen text (accessibility)+ // is available, we degrade gracefully to a plain question.+ screenshot = quickAsk.captureScreenBase64()+ screenText = quickAsk.captureScreenText()+ }++ val answer = quickAsk.ask(question, screenshot, screenText)+ overlay.showAnswer(answer)+ quickAsk.speak(answer)+ } catch (e: Exception) {+ overlay.showError(friendlyError(e))+ } finally {+ isBusy = false+ }+ }+ }++ // ---- Lifecycle helpers ----++ private fun stopBall() {+ overlay.dismiss()+ stopForeground(STOP_FOREGROUND_REMOVE)+ 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(+ this, 0,+ Intent(this, MainActivity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),+ PendingIntent.FLAG_IMMUTABLE+ )+ val notification: Notification = Notification.Builder(this, CHANNEL_ID)+ .setContentTitle("Gotcha assistive ball")+ .setContentText("Tap the floating ball to ask about your screen.")+ .setSmallIcon(android.R.drawable.ic_menu_compass)+ .setContentIntent(tapIntent)+ .setOngoing(true)+ .build()++ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ startForeground(+ NOTIFICATION_ID,+ notification,+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE or+ ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE+ )+ } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ startForeground(+ NOTIFICATION_ID,+ notification,+ ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE+ )+ } else {+ startForeground(NOTIFICATION_ID, notification)+ }+ }++ private fun createChannel() {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {+ val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager+ if (manager.getNotificationChannel(CHANNEL_ID) == null) {+ manager.createNotificationChannel(+ NotificationChannel(+ CHANNEL_ID,+ "Assistive ball",+ NotificationManager.IMPORTANCE_LOW+ ).apply { description = "Keeps the floating assistive ball running." }+ )+ }+ }+ }++ 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 const val CHANNEL_ID = "assistive_ball"+ private const val NOTIFICATION_ID = 4711++ fun startIntent(context: Context): Intent =+ Intent(context, AssistiveBallService::class.java).setAction(ACTION_START)++ fun stopIntent(context: Context): Intent =+ Intent(context, AssistiveBallService::class.java).setAction(ACTION_STOP)+ }+}diff --git a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.ktindex b25e5cf..47701d3 100644--- a/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt+++ b/app/src/main/java/com/gotcha/service/GotchaAccessibilityService.kt@@ -2,10 +2,15 @@ package com.gotcha.serviceimport android.accessibilityservice.AccessibilityServiceimport android.accessibilityservice.GestureDescription+import android.graphics.Bitmapimport android.graphics.Pathimport android.os.Build+import android.view.Displayimport android.view.accessibility.AccessibilityEventimport android.view.accessibility.AccessibilityNodeInfo+import androidx.annotation.RequiresApi+import kotlinx.coroutines.suspendCancellableCoroutine+import kotlin.coroutines.resume/*** Tier 3 — AccessibilityService.@@ -43,6 +48,41 @@ class GotchaAccessibilityService : AccessibilityService() {// ---- Capabilities used by AccessibilityTool ----+ /**+ * Capture a screenshot of the default display via the AccessibilityService screenshot+ * API (API 30+, non-root). Returns a software [Bitmap] or null on failure. The caller+ * is responsible for downscaling/compressing. Used by the assistive-ball "screen share"+ * flow to give the LLM vision context alongside [dumpScreenText].+ */+ @RequiresApi(Build.VERSION_CODES.R)+ suspend fun takeScreenshotBitmap(): Bitmap? = suspendCancellableCoroutine { cont ->+ try {+ takeScreenshot(+ Display.DEFAULT_DISPLAY,+ mainExecutor,+ object : AccessibilityService.TakeScreenshotCallback {+ override fun onSuccess(screenshot: AccessibilityService.ScreenshotResult) {+ val bitmap = try {+ Bitmap.wrapHardwareBuffer(screenshot.hardwareBuffer, screenshot.colorSpace)+ ?.copy(Bitmap.Config.ARGB_8888, false)+ } catch (_: Exception) {+ null+ } finally {+ screenshot.hardwareBuffer.close()+ }+ if (cont.isActive) cont.resume(bitmap)+ }++ override fun onFailure(errorCode: Int) {+ if (cont.isActive) cont.resume(null)+ }+ }+ )+ } catch (_: Exception) {+ if (cont.isActive) cont.resume(null)+ }+ }+/** Recursively collect visible, non-blank text/content-descriptions from the active window. */fun dumpScreenText(limit: Int = 200): List<String> {val root = rootInActiveWindow ?: return emptyList()diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.ktnew file mode 100644index 0000000..644b5f4--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallOverlay.kt@@ -0,0 +1,360 @@+package com.gotcha.ui++import android.annotation.SuppressLint+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.provider.Settings+import android.view.Gravity+import android.view.MotionEvent+import android.view.View+import android.view.ViewConfiguration+import android.view.WindowManager+import android.widget.Button+import android.widget.LinearLayout+import android.widget.ScrollView+import android.widget.TextView+import kotlin.math.abs++/**+ * The floating "assistive ball" drawn over other apps via SYSTEM_ALERT_WINDOW.+ *+ * 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).+ */+class AssistiveBallOverlay(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+ 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 = {}++ private var ballView: View? = null+ private var menuView: View? = null+ private var cardView: View? = null++ private val ballParams: WindowManager.LayoutParams by lazy { ballLayoutParams() }++ /** Whether we currently hold the "Display over other apps" permission. */+ fun canShow(): Boolean =+ Build.VERSION.SDK_INT < Build.VERSION_CODES.M || Settings.canDrawOverlays(appContext)++ fun show() {+ mainHandler.post {+ if (ballView != null) return@post+ val ball = buildBall()+ try {+ windowManager.addView(ball, ballParams)+ ballView = ball+ } catch (_: Exception) {+ ballView = null+ }+ }+ }++ fun dismiss() {+ mainHandler.post {+ removeMenu()+ removeCard()+ ballView?.let { safeRemove(it) }+ ballView = null+ }+ }++ // ---- Status / answer card ----++ 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 ----++ @SuppressLint("ClickableViewAccessibility")+ private fun buildBall(): View {+ val size = dp(56)+ return TextView(appContext).apply {+ text = "AI"+ gravity = Gravity.CENTER+ setTextColor(Color.WHITE)+ textSize = 16f+ width = size+ height = size+ background = GradientDrawable().apply {+ shape = GradientDrawable.OVAL+ setColor(Color.parseColor("#6750A4"))+ setStroke(dp(2), Color.parseColor("#EADDFF"))+ }+ setOnTouchListener(ballTouchListener())+ }+ }++ private fun ballTouchListener(): View.OnTouchListener {+ var startX = 0+ var startY = 0+ var touchDownRawX = 0f+ var touchDownRawY = 0f+ var dragging = false+ return View.OnTouchListener { _, event ->+ when (event.action) {+ MotionEvent.ACTION_DOWN -> {+ startX = ballParams.x+ startY = ballParams.y+ touchDownRawX = event.rawX+ touchDownRawY = event.rawY+ dragging = false+ true+ }+ MotionEvent.ACTION_MOVE -> {+ val dx = (event.rawX - touchDownRawX).toInt()+ val dy = (event.rawY - touchDownRawY).toInt()+ if (!dragging && (abs(dx) > touchSlop || abs(dy) > touchSlop)) {+ dragging = true+ removeMenu()+ }+ if (dragging) {+ ballParams.x = startX + dx+ ballParams.y = startY + dy+ try {+ windowManager.updateViewLayout(ballView, ballParams)+ } catch (_: Exception) { }+ }+ true+ }+ MotionEvent.ACTION_UP -> {+ if (dragging) {+ clampBallIntoBounds()+ } else {+ toggleMenu()+ }+ true+ }+ else -> false+ }+ }+ }++ private fun clampBallIntoBounds() {+ val metrics = appContext.resources.displayMetrics+ val maxX = metrics.widthPixels - dp(56)+ val maxY = metrics.heightPixels - dp(56)+ ballParams.x = ballParams.x.coerceIn(0, maxX.coerceAtLeast(0))+ ballParams.y = ballParams.y.coerceIn(0, maxY.coerceAtLeast(0))+ try {+ windowManager.updateViewLayout(ballView, ballParams)+ } catch (_: Exception) { }+ }++ // ---- Expanded menu ----++ private fun toggleMenu() {+ if (menuView != null) removeMenu() else showMenu()+ }++ @SuppressLint("ClickableViewAccessibility")+ private fun showMenu() {+ removeMenu()+ val container = LinearLayout(appContext).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(dp(12), dp(12), dp(12), dp(12))+ background = GradientDrawable().apply {+ cornerRadius = dp(16).toFloat()+ setColor(Color.parseColor("#1E1E1E"))+ setStroke(dp(1), Color.parseColor("#3A3A3A"))+ }+ }++ container.addView(menuTitle("Gotcha"))+ container.addView(talkButton("🖥 Screen Share — hold & talk", withScreen = true))+ container.addView(talkButton("🎤 Talk — hold & talk", withScreen = false))+ container.addView(tapButton("💬 Open Chat") {+ removeMenu()+ onOpenChat()+ })+ container.addView(tapButton("✕ Hide ball") {+ onDismiss()+ })++ val params = menuLayoutParams()+ try {+ windowManager.addView(container, params)+ menuView = container+ } catch (_: Exception) {+ menuView = null+ }+ }++ private fun menuTitle(text: String) = TextView(appContext).apply {+ this.text = text+ setTextColor(Color.parseColor("#EADDFF"))+ textSize = 13f+ 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+ isAllCaps = false+ setOnClickListener { onClick() }+ }+ }++ private fun removeMenu() {+ menuView?.let { safeRemove(it) }+ menuView = null+ }++ // ---- Card ----++ private fun showCard(message: String, showClose: Boolean) {+ mainHandler.post {+ removeCard()+ val container = LinearLayout(appContext).apply {+ orientation = LinearLayout.VERTICAL+ setPadding(dp(20), dp(16), dp(20), dp(16))+ background = GradientDrawable().apply {+ cornerRadius = dp(16).toFloat()+ setColor(Color.parseColor("#1E1E1E"))+ setStroke(dp(1), Color.parseColor("#3A3A3A"))+ }+ }+ val scroll = ScrollView(appContext).apply {+ addView(TextView(appContext).apply {+ text = message+ setTextColor(Color.parseColor("#EEEEEE"))+ textSize = 14f+ })+ layoutParams = LinearLayout.LayoutParams(+ LinearLayout.LayoutParams.MATCH_PARENT,+ dp(240)+ )+ }+ container.addView(scroll)+ if (showClose) {+ container.addView(Button(appContext).apply {+ text = "Close"+ isAllCaps = false+ setOnClickListener { hideCard() }+ })+ }+ try {+ windowManager.addView(container, cardLayoutParams())+ cardView = container+ } catch (_: Exception) {+ cardView = null+ }+ }+ }++ fun hideCard() {+ mainHandler.post { removeCard() }+ }++ private fun removeCard() {+ cardView?.let { safeRemove(it) }+ cardView = null+ }++ // ---- Helpers ----++ private fun safeRemove(view: View) {+ try {+ windowManager.removeView(view)+ } catch (_: Exception) {+ // Already detached; ignore.+ }+ }++ private fun overlayType(): Int =+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)+ WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY+ else @Suppress("DEPRECATION") WindowManager.LayoutParams.TYPE_PHONE++ private fun ballLayoutParams(): WindowManager.LayoutParams =+ WindowManager.LayoutParams(+ WindowManager.LayoutParams.WRAP_CONTENT,+ WindowManager.LayoutParams.WRAP_CONTENT,+ overlayType(),+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,+ PixelFormat.TRANSLUCENT+ ).apply {+ gravity = Gravity.TOP or Gravity.START+ x = dp(16)+ y = dp(160)+ }++ private fun menuLayoutParams(): WindowManager.LayoutParams =+ WindowManager.LayoutParams(+ dp(240),+ WindowManager.LayoutParams.WRAP_CONTENT,+ overlayType(),+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,+ PixelFormat.TRANSLUCENT+ ).apply {+ gravity = Gravity.TOP or Gravity.START+ // Anchor near the ball, clamped so the menu stays on screen.+ val metrics = appContext.resources.displayMetrics+ x = (ballParams.x).coerceIn(0, (metrics.widthPixels - dp(240)).coerceAtLeast(0))+ y = (ballParams.y + dp(64)).coerceIn(0, (metrics.heightPixels - dp(260)).coerceAtLeast(0))+ }++ private fun cardLayoutParams(): WindowManager.LayoutParams =+ WindowManager.LayoutParams(+ dp(320),+ WindowManager.LayoutParams.WRAP_CONTENT,+ overlayType(),+ WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,+ PixelFormat.TRANSLUCENT+ ).apply {+ gravity = Gravity.CENTER+ }++ private fun dp(value: Int): Int =+ (value * appContext.resources.displayMetrics.density).toInt()+}diff --git a/app/src/main/java/com/gotcha/ui/SessionsScreen.kt b/app/src/main/java/com/gotcha/ui/SessionsScreen.ktindex 7bc58d2..7223379 100644--- a/app/src/main/java/com/gotcha/ui/SessionsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SessionsScreen.kt@@ -8,6 +8,7 @@ import androidx.compose.material.icons.Iconsimport androidx.compose.material.icons.filled.Addimport androidx.compose.material.icons.filled.Deleteimport androidx.compose.material.icons.filled.Settings+import androidx.compose.material.icons.outlined.Adjustimport androidx.compose.material3.*import androidx.compose.runtime.*import androidx.compose.ui.Alignment@@ -26,7 +27,9 @@ fun SessionsScreen(onSessionClick: (String) -> Unit,onDeleteSession: (String) -> Unit,onNewChat: () -> Unit,- onOpenSettings: () -> Unit+ onOpenSettings: () -> Unit,+ assistiveBallEnabled: Boolean = false,+ onToggleAssistiveBall: (Boolean) -> Unit = {}) {var sessionToDelete by remember { mutableStateOf<String?>(null) }@@ -35,6 +38,16 @@ fun SessionsScreen(TopAppBar(title = { Text("Chats") },actions = {+ IconButton(onClick = { onToggleAssistiveBall(!assistiveBallEnabled) }) {+ Icon(+ Icons.Outlined.Adjust,+ contentDescription = if (assistiveBallEnabled)+ "Turn off assistive ball" else "Turn on assistive ball",+ tint = if (assistiveBallEnabled)+ MaterialTheme.colorScheme.primary+ else MaterialTheme.colorScheme.onSurfaceVariant+ )+ }IconButton(onClick = onOpenSettings) {Icon(Icons.Default.Settings, contentDescription = "Settings")}diff --git a/app/src/main/res/xml/accessibility_service_config.xml b/app/src/main/res/xml/accessibility_service_config.xmlindex 8db913b..c41bbb9 100644--- a/app/src/main/res/xml/accessibility_service_config.xml+++ b/app/src/main/res/xml/accessibility_service_config.xml@@ -5,5 +5,6 @@android:accessibilityFlags="flagDefault|flagRetrieveInteractiveWindows"android:canPerformGestures="true"android:canRetrieveWindowContent="true"+ android:canTakeScreenshot="true"android:description="@string/accessibility_service_description"android:notificationTimeout="100" />