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 screen-aware wake-word listening modes and sync wake-word state with assistive ball toggle
Rishabh Bajpai3b2362324efa
diff --git a/.gitignore b/.gitignoreindex ecf5345..57dfb0f 100644--- a/.gitignore+++ b/.gitignore@@ -118,3 +118,4 @@ MARKETING_PLAYBOOK.mddocs/benchmarkdocs/WAKE_WORD_PLAN.md.freebuff+scripts/wake_battery_idle.sh\ No newline at end of filediff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 067e64d..5b67359 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -518,7 +518,16 @@ class MainActivity : ComponentActivity() {private fun persistAssistiveBall(enabled: Boolean) {val current = settingsRepository.load()- settingsRepository.save(current.copy(assistiveBallEnabled = enabled))+ // The wake word runs inside the ball service, so switching the ball off+ // must also switch the wake word off — otherwise the wake-word setting+ // stays on and silently inert while the ball is off.+ settingsRepository.save(+ if (enabled) {+ current.copy(assistiveBallEnabled = true)+ } else {+ current.copy(assistiveBallEnabled = false, wakeWordEnabled = false)+ }+ )}/** Any Samosa 401 (LLM or audio) clears the session and refreshes thediff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 1cb213a..28771c4 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -5,6 +5,32 @@ import android.content.SharedPreferencesimport com.gotcha.BuildConfigimport com.gotcha.audio.AudioProvider+/**+ * When the wake-word listener is allowed to run, relative to the screen state.+ *+ * The listener's idle cost (issue #37, `docs/benchmark/wake-word-idle.md`) is+ * dominated by holding the microphone — the `AudioIn` wake lock, not the+ * inference. These modes trade how much of the day that happens for where the+ * user is most likely to want a hands-free trigger.+ */+enum class WakeWordListeningMode {+ /** Listen regardless of screen state — the original always-on behaviour. */+ ALWAYS,++ /** Listen only while the screen is on, so the mic LED is off when it is not. */+ SCREEN_ON,++ /** Listen only while the screen is off, for hands-free use away from the app. */+ SCREEN_OFF;++ /** Whether the listener should run given the current screen interactivity. */+ fun allows(screenInteractive: Boolean): Boolean = when (this) {+ ALWAYS -> true+ SCREEN_ON -> screenInteractive+ SCREEN_OFF -> !screenInteractive+ }+}+data class Settings(// Which LLM backend is active. Defaults to the Samosa AI flow.val provider: LlmProvider = LlmProvider.SAMOSA_AI,@@ -54,6 +80,7 @@ data class Settings(val assistiveBallEnabled: Boolean = false,val wakeWordEnabled: Boolean = false,val wakeWordSensitivity: Float = 0.75f,+ val wakeWordListeningMode: WakeWordListeningMode = WakeWordListeningMode.ALWAYS,/** Server-driven notifications from `<SAMOSA_API_URL>/v1/gotcha/notifications`. */val serverMessagesEnabled: Boolean = true,/** Epoch millis of the last successful server-messages fetch. 0 = never. */@@ -356,6 +383,9 @@ class SettingsRepository(context: Context) : SettingsStore {assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false),wakeWordEnabled = prefs.getBoolean(KEY_WAKE_WORD_ENABLED, false),wakeWordSensitivity = prefs.getFloat(KEY_WAKE_WORD_SENSITIVITY, 0.75f),+ wakeWordListeningMode = runCatching {+ WakeWordListeningMode.valueOf(string(KEY_WAKE_WORD_LISTENING_MODE, "ALWAYS"))+ }.getOrDefault(WakeWordListeningMode.ALWAYS),serverMessagesEnabled = prefs.getBoolean(KEY_SERVER_MESSAGES_ENABLED, true),serverMessagesLastFetchedAt = prefs.getLong(KEY_SERVER_MESSAGES_LAST_FETCHED, 0L),serverMessagesEtag = string(KEY_SERVER_MESSAGES_ETAG),@@ -417,6 +447,7 @@ class SettingsRepository(context: Context) : SettingsStore {.putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled).putBoolean(KEY_WAKE_WORD_ENABLED, settings.wakeWordEnabled).putFloat(KEY_WAKE_WORD_SENSITIVITY, settings.wakeWordSensitivity)+ .putString(KEY_WAKE_WORD_LISTENING_MODE, settings.wakeWordListeningMode.name).putBoolean(KEY_SERVER_MESSAGES_ENABLED, settings.serverMessagesEnabled).putLong(KEY_SERVER_MESSAGES_LAST_FETCHED, settings.serverMessagesLastFetchedAt).putString(KEY_SERVER_MESSAGES_ETAG, settings.serverMessagesEtag)@@ -523,6 +554,7 @@ class SettingsRepository(context: Context) : SettingsStore {const val KEY_ASSISTIVE_BALL = "assistive_ball_enabled"const val KEY_WAKE_WORD_ENABLED = "wake_word_enabled"const val KEY_WAKE_WORD_SENSITIVITY = "wake_word_sensitivity"+ const val KEY_WAKE_WORD_LISTENING_MODE = "wake_word_listening_mode"const val KEY_SERVER_MESSAGES_ENABLED = "server_messages_enabled"const val KEY_SERVER_MESSAGES_LAST_FETCHED = "server_messages_last_fetched"const val KEY_SERVER_MESSAGES_ETAG = "server_messages_etag"diff --git a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt b/app/src/main/java/com/gotcha/service/AssistiveBallService.ktindex d27b52f..6302cf6 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -5,18 +5,23 @@ import android.app.NotificationChannelimport android.app.NotificationManagerimport android.app.PendingIntentimport android.app.Service+import android.content.BroadcastReceiverimport android.content.Contextimport android.content.Intent+import android.content.IntentFilterimport android.content.SharedPreferencesimport android.content.pm.ServiceInfoimport android.os.Buildimport android.os.IBinder+import android.os.PowerManager+import androidx.core.content.ContextCompatimport com.gotcha.MainActivityimport com.gotcha.audio.AudioProviderimport com.gotcha.audio.SttEngineimport com.gotcha.audio.TtsEngineimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.SettingsRepository+import com.gotcha.data.WakeWordListeningModeimport com.gotcha.data.settingsChangeNotifierimport com.gotcha.i18n.Languageimport com.gotcha.ui.AssistiveBallOverlay@@ -83,16 +88,39 @@ class AssistiveBallService : Service() {return@OnSharedPreferenceChangeListener}// The key arrives encrypted; compare the value read back instead (see- // settingsChangeNotifier's note). Restarting with a new threshold only- // makes sense while idle — the state collector stops the detector- // whenever a call becomes active anyway.- if (s.wakeWordSensitivity != appliedWakeWordSensitivity &&- callController.state.value == CallState.IDLE- ) {+ // settingsChangeNotifier's note). Restarting with a new threshold or a+ // new listening mode only makes sense while idle — the state collector+ // stops the detector whenever a call becomes active anyway.+ val settingsChanged = s.wakeWordSensitivity != appliedWakeWordSensitivity ||+ s.wakeWordListeningMode != appliedWakeWordMode+ if (settingsChanged && callController.state.value == CallState.IDLE) {maybeStartWakeWord()}}private var appliedWakeWordSensitivity: Float? = null+ private var appliedWakeWordMode: WakeWordListeningMode? = null++ /**+ * Re-evaluates the listener when the screen toggles, so the SCREEN_ON /+ * SCREEN_OFF listening modes track the display instead of waiting for a+ * settings edit or a call transition to re-arm.+ *+ * Guarded like the call-state and TTS collectors: a screen toggle must+ * never re-arm the listener while a call is active or the app is speaking+ * — those pauses are deliberate, and an unconditional re-arm here would+ * grab the microphone out from under the call's STT or from the app's own+ * voice.+ */+ private val screenStateReceiver = object : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ when (intent.action) {+ Intent.ACTION_SCREEN_ON, Intent.ACTION_SCREEN_OFF ->+ if (callController.state.value == CallState.IDLE && !ttsEngine.isSpeaking.value) {+ maybeStartWakeWord()+ }+ }+ }+ }private lateinit var screenCompanionController: ScreenCompanionControllerprivate lateinit var screenCompanionPanel: com.gotcha.ui.ScreenCompanionPanelOverlayprivate lateinit var screenLensController: ScreenLensController@@ -159,6 +187,7 @@ class AssistiveBallService : Service() {settingsPrefs = settingsChangeNotifier(applicationContext)settingsPrefs.registerOnSharedPreferenceChangeListener(wakeWordSettingsWatcher)+ registerScreenStateReceiver()// Floating call buttons (shown during a call, hidden otherwise)chatWindow = CallChatWindow(this).apply {@@ -909,7 +938,9 @@ class AssistiveBallService : Service() {private fun maybeStartWakeWord() {val settings = settingsRepository.load()- if (settings.wakeWordEnabled && settings.assistiveBallEnabled && hasMicPermission()) {+ if (settings.wakeWordEnabled && settings.assistiveBallEnabled && hasMicPermission() &&+ settings.wakeWordListeningMode.allows(isScreenInteractive())+ ) {// A running detector skips its own start() (see WakeWordDetector),// so a live sensitivity change would otherwise never reach the// matcher. Stop first to force a rebuild whenever the threshold@@ -920,13 +951,38 @@ class AssistiveBallService : Service() {wakeWordDetector.pause()}appliedWakeWordSensitivity = settings.wakeWordSensitivity+ appliedWakeWordMode = settings.wakeWordListeningModewakeWordDetector.start()} else {- // Switched off, or no mic grant: give the models back.+ // Switched off, no mic grant, or the listening mode does not allow+ // the current screen state: give the models back.wakeWordDetector.release()}}+ /** Whether the display is on and usable. Defaults to true when unknown. */+ private fun isScreenInteractive(): Boolean {+ val powerManager = getSystemService(PowerManager::class.java) ?: return true+ return powerManager.isInteractive+ }++ /**+ * Screen on/off re-arm for the SCREEN_ON / SCREEN_OFF listening modes.+ * Registered once in [onCreate] and unregistered alongside the settings+ * watcher in [stopBall] and [onDestroy].+ */+ private fun registerScreenStateReceiver() {+ ContextCompat.registerReceiver(+ this,+ screenStateReceiver,+ IntentFilter().apply {+ addAction(Intent.ACTION_SCREEN_ON)+ addAction(Intent.ACTION_SCREEN_OFF)+ },+ ContextCompat.RECEIVER_NOT_EXPORTED+ )+ }+override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {when (intent?.action) {ACTION_STOP -> {@@ -952,6 +1008,7 @@ class AssistiveBallService : Service() {if (::settingsPrefs.isInitialized) {settingsPrefs.unregisterOnSharedPreferenceChangeListener(wakeWordSettingsWatcher)}+ runCatching { unregisterReceiver(screenStateReceiver) }callController.endCall()chatWindow.hide()screenCompanionPanel.dismiss()@@ -1035,10 +1092,13 @@ class AssistiveBallService : Service() {if (::settingsPrefs.isInitialized) {settingsPrefs.unregisterOnSharedPreferenceChangeListener(wakeWordSettingsWatcher)}+ runCatching { unregisterReceiver(screenStateReceiver) }callController.endCall()chatWindow.hide()screenCompanionPanel.dismiss()- settingsRepository.save(settingsRepository.load().copy(assistiveBallEnabled = false))+ settingsRepository.save(+ settingsRepository.load().copy(assistiveBallEnabled = false, wakeWordEnabled = false)+ )_isRunning.value = falseoverlay.dismiss()stopForeground(STOP_FOREGROUND_REMOVE)diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.ktindex b024a9c..438ad7c 100644--- a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt@@ -202,7 +202,7 @@ class WakeWordDetector(@SuppressLint("MissingPermission")private suspend fun initializeAndListen(generation: Int) {val env = OrtEnvironment.getEnvironment()- /** Sessions this run holds a use-claim on; released in the finally. */+ // Sessions this run holds a use-claim on; released in the finally.var claimed: Sessions? = nullvar createdRecorder: AudioRecord? = nulltry {diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.ktindex 40441c2..317b733 100644--- a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt@@ -10,21 +10,29 @@ import androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.Spacerimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.selection.selectable+import androidx.compose.foundation.selection.selectableGroupimport androidx.compose.material3.MaterialTheme+import androidx.compose.material3.RadioButtonimport androidx.compose.material3.Sliderimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.setValue+import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContextimport androidx.compose.ui.platform.testTag+import androidx.compose.ui.semantics.Roleimport androidx.compose.ui.semantics.contentDescriptionimport androidx.compose.ui.semantics.semanticsimport androidx.compose.ui.unit.dpimport com.gotcha.data.Settings+import com.gotcha.data.WakeWordListeningModeimport android.provider.Settings as AndroidSettings/**@@ -48,8 +56,22 @@ fun AssistiveBallScreen() {val overlay = rememberSettingsOverlayState()val initial = remember { load() }+ val ballEnabled = enabledvar wakeWordEnabled by remember { mutableStateOf(initial.wakeWordEnabled) }var wakeWordSensitivity by remember { mutableStateOf(initial.wakeWordSensitivity) }+ var wakeWordListeningMode by remember { mutableStateOf(initial.wakeWordListeningMode) }++ // The wake word runs inside the ball service, so it cannot be on while the+ // ball is off. When the ball is switched off here (or this screen is opened+ // with the ball already off and a leftover ON), reset the wake word to off+ // in both the local state and the saved setting — not merely disable the+ // toggle, which would leave it visually on but inert.+ LaunchedEffect(ballEnabled) {+ if (!ballEnabled && wakeWordEnabled) {+ wakeWordEnabled = false+ onSave { settings -> settings.copy(wakeWordEnabled = false) }+ }+ }SettingsScaffold(title = SettingsPage.ASSISTIVE_BALL.title, onBack = onBack, overlay = overlay) {SettingsToggleRow(@@ -74,6 +96,11 @@ fun AssistiveBallScreen(SettingsToggleRow(label = "Wake word: Hey Gotcha",checked = wakeWordEnabled,+ // The listener runs inside the Assistive Ball service, so the wake+ // word cannot be turned on while the ball is off. Turning the ball+ // off also switches the wake word off (see LaunchedEffect above),+ // so this toggle is simply locked to the ball state.+ enabled = ballEnabled,onCheckedChange = {wakeWordEnabled = itonSave { settings -> settings.copy(wakeWordEnabled = it) }@@ -85,6 +112,14 @@ fun AssistiveBallScreen("Turn on Hey Gotcha wake word"})+ if (!ballEnabled) {+ Text(+ "The wake word requires the Assistive Ball to be on — turn on " ++ "\"Show Assistive Ball\" to use it.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ }Text("Says \"Hey Gotcha\" — the bundled OpenWakeWord model runs on-device while " +"the assistive ball is on and no call is active. Keep microphone " +@@ -93,6 +128,35 @@ fun AssistiveBallScreen(color = MaterialTheme.colorScheme.onSurfaceVariant)if (wakeWordEnabled) {+ Spacer(modifier = Modifier.height(8.dp))+ Text(+ "When to listen",+ style = MaterialTheme.typography.bodyMedium+ )+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .selectableGroup()+ .testTag("settings_wake_word_mode")+ ) {+ WakeWordListeningMode.entries.forEach { mode ->+ WakeWordModeRow(+ mode = mode,+ selected = wakeWordListeningMode == mode,+ onSelect = {+ wakeWordListeningMode = mode+ onSave { settings -> settings.copy(wakeWordListeningMode = mode) }+ }+ )+ }+ }+ Text(+ "The listener is only active while the screen matches the chosen " ++ "state, so the microphone and its indicator are off the rest of " ++ "the time.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )Spacer(modifier = Modifier.height(8.dp))Row(modifier = Modifier.fillMaxWidth()@@ -154,6 +218,52 @@ private fun sensitivityLabel(sensitivity: Float): String = when {else -> "High sensitivity"}+/** One selectable row of the "When to listen" wake-word mode group. */+@Composable+private fun WakeWordModeRow(+ mode: WakeWordListeningMode,+ selected: Boolean,+ onSelect: () -> Unit+) {+ val label: String+ val summary: String+ when (mode) {+ WakeWordListeningMode.ALWAYS -> {+ label = "Always"+ summary = "Listen with the screen on or off. Full hands-free, highest battery use."+ }+ WakeWordListeningMode.SCREEN_ON -> {+ label = "Only while the screen is on"+ summary = "Saves battery — the microphone and its indicator are off while the screen is off."+ }+ WakeWordListeningMode.SCREEN_OFF -> {+ label = "Only while the screen is off"+ summary = "Hands-free when you are not already looking at the phone; the screen being on means the mic is off."+ }+ }+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .selectable(+ selected = selected,+ role = Role.RadioButton,+ onClick = onSelect+ )+ .testTag("settings_wake_word_mode_${mode.name.lowercase()}")+ ) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ RadioButton(selected = selected, onClick = null)+ Text(label, style = MaterialTheme.typography.bodyMedium)+ }+ Text(+ summary,+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.padding(start = 40.dp, bottom = 4.dp)+ )+ }+}+@Composableprivate fun BatteryOptimizationRow(context: Context) {val exempt = remember(context) {diff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.ktindex 24d0f04..b9d2bb5 100644--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt@@ -387,6 +387,10 @@ fun SamosaAuthSection(* toggleable and no-op silently. [switchContentDescription] names the `Switch`* for the same reason — it is what a UiAutomator/Maestro flow, which cannot see* test tags, has to aim at.+ *+ * [enabled] disables the `Switch` (greyed out, no tap effect) for a row whose+ * action depends on a prerequisite the user has not met yet; the caller should+ * also explain the prerequisite nearby.*/@Composablefun SettingsToggleRow(@@ -394,6 +398,7 @@ fun SettingsToggleRow(checked: Boolean,onCheckedChange: (Boolean) -> Unit,isLarge: Boolean = false,+ enabled: Boolean = true,switchTestTag: String? = null,switchContentDescription: String? = null,modifier: Modifier = Modifier@@ -405,11 +410,17 @@ fun SettingsToggleRow() {Text(label,- style = if (isLarge) MaterialTheme.typography.bodyLarge else MaterialTheme.typography.bodyMedium+ style = if (isLarge) MaterialTheme.typography.bodyLarge else MaterialTheme.typography.bodyMedium,+ color = if (enabled) {+ MaterialTheme.colorScheme.onSurface+ } else {+ MaterialTheme.colorScheme.onSurfaceVariant+ })Switch(checked = checked,onCheckedChange = onCheckedChange,+ enabled = enabled,modifier = Modifier.then(if (switchTestTag != null) Modifier.testTag(switchTestTag) else Modifier).then(diff --git a/app/src/test/java/com/gotcha/data/SettingsTest.kt b/app/src/test/java/com/gotcha/data/SettingsTest.ktindex 4e0b311..876f787 100644--- a/app/src/test/java/com/gotcha/data/SettingsTest.kt+++ b/app/src/test/java/com/gotcha/data/SettingsTest.kt@@ -2,6 +2,8 @@ package com.gotcha.dataimport com.gotcha.audio.AudioProviderimport org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrueimport org.junit.Testclass SettingsTest {@@ -325,4 +327,35 @@ class SettingsTest {// Untouched fields stay at their defaults.assertEquals(false, enabled.assistiveBallEnabled)}++ @Test+ fun `wake word listening mode defaults to always`() {+ val defaults = Settings()+ assertEquals(WakeWordListeningMode.ALWAYS, defaults.wakeWordListeningMode)+ }++ @Test+ fun `wake word listening mode is an independent field on copy`() {+ val defaults = Settings()+ val screenOn = defaults.copy(wakeWordListeningMode = WakeWordListeningMode.SCREEN_ON)+ assertEquals(WakeWordListeningMode.SCREEN_ON, screenOn.wakeWordListeningMode)+ // Untouched fields stay at their defaults.+ assertEquals(false, screenOn.wakeWordEnabled)+ assertEquals(0.75f, screenOn.wakeWordSensitivity, 0.001f)+ }++ @Test+ fun `wake word listening mode gates on screen interactivity`() {+ val always = WakeWordListeningMode.ALWAYS+ assertTrue(always.allows(screenInteractive = true))+ assertTrue(always.allows(screenInteractive = false))++ val screenOn = WakeWordListeningMode.SCREEN_ON+ assertTrue(screenOn.allows(screenInteractive = true))+ assertFalse(screenOn.allows(screenInteractive = false))++ val screenOff = WakeWordListeningMode.SCREEN_OFF+ assertFalse(screenOff.allows(screenInteractive = true))+ assertTrue(screenOff.allows(screenInteractive = false))+ }}