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 (ongoing): implement optional wake word functionality using Vosk
Durganshu Mishrac6027d0c51d3
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex ffc35d5..089920e 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -367,6 +367,10 @@ dependencies {implementation("androidx.camera:camera-lifecycle:$cameraxVersion")implementation("androidx.camera:camera-view:$cameraxVersion")+ // Open-source, on-device speech recognition used for the optional wake word.+ // The acoustic model is supplied in app/src/main/assets (see docs/wake-word.md).+ implementation("com.alphacephei:vosk-android:0.3.47")+// Static analysisdetektPlugins("io.gitlab.arturbosch.detekt:detekt-formatting:1.23.6")diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 8e24c9a..8cf6ad2 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -232,6 +232,14 @@</intent-filter></receiver>+ <receiver+ android:name=".tools.WakeWordBootReceiver"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ </intent-filter>+ </receiver>+<!-- Tier 3: Device Admin — lock screen, password policy, disable camera. --><receiverandroid:name=".service.GotchaDeviceAdminReceiver"diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex 10364a9..8d51d14 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -52,6 +52,8 @@ data class Settings(/** Chime when a reply arrives. Off by default — audible in a way a buzz is not. */val notifyChimeEnabled: Boolean = false,val assistiveBallEnabled: Boolean = false,+ val wakeWordEnabled: Boolean = false,+ val wakeWordSensitivity: Float = 0.75f,/** 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. */@@ -343,6 +345,8 @@ class SettingsRepository(context: Context) {notifyVibrationEnabled = prefs.getBoolean(KEY_NOTIFY_VIBRATION, true),notifyChimeEnabled = prefs.getBoolean(KEY_NOTIFY_CHIME, false),assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false),+ wakeWordEnabled = prefs.getBoolean(KEY_WAKE_WORD_ENABLED, false),+ wakeWordSensitivity = prefs.getFloat(KEY_WAKE_WORD_SENSITIVITY, 0.75f),serverMessagesEnabled = prefs.getBoolean(KEY_SERVER_MESSAGES_ENABLED, true),serverMessagesLastFetchedAt = prefs.getLong(KEY_SERVER_MESSAGES_LAST_FETCHED, 0L),serverMessagesEtag = string(KEY_SERVER_MESSAGES_ETAG),@@ -400,6 +404,8 @@ class SettingsRepository(context: Context) {.putBoolean(KEY_NOTIFY_VIBRATION, settings.notifyVibrationEnabled).putBoolean(KEY_NOTIFY_CHIME, settings.notifyChimeEnabled).putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled)+ .putBoolean(KEY_WAKE_WORD_ENABLED, settings.wakeWordEnabled)+ .putFloat(KEY_WAKE_WORD_SENSITIVITY, settings.wakeWordSensitivity).putBoolean(KEY_SERVER_MESSAGES_ENABLED, settings.serverMessagesEnabled).putLong(KEY_SERVER_MESSAGES_LAST_FETCHED, settings.serverMessagesLastFetchedAt).putString(KEY_SERVER_MESSAGES_ETAG, settings.serverMessagesEtag)@@ -502,6 +508,8 @@ class SettingsRepository(context: Context) {const val KEY_NOTIFY_VIBRATION = "notify_vibration"const val KEY_NOTIFY_CHIME = "notify_chime"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_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 9c808b0..4db643a 100644--- a/app/src/main/java/com/gotcha/service/AssistiveBallService.kt+++ b/app/src/main/java/com/gotcha/service/AssistiveBallService.kt@@ -64,6 +64,7 @@ class AssistiveBallService : Service() {private lateinit var overlay: com.gotcha.ui.AssistiveBallOverlayprivate lateinit var chatWindow: CallChatWindowprivate lateinit var callController: CallSessionController+ private lateinit var wakeWordDetector: WakeWordDetectorprivate lateinit var screenCompanionController: ScreenCompanionControllerprivate lateinit var screenCompanionPanel: com.gotcha.ui.ScreenCompanionPanelOverlayprivate lateinit var screenLensController: ScreenLensController@@ -119,6 +120,20 @@ class AssistiveBallService : Service() {sttEngine = sttEngine,ttsEngine = ttsEngine)+ wakeWordDetector = WakeWordDetector(+ context = applicationContext,+ scope = scope,+ onDetected = {+ wakeWordDetector.stop()+ val s = settingsRepository.load()+ com.gotcha.audio.CompletionFeedback.replyArrived(+ this,+ vibrate = s.notifyVibrationEnabled,+ chime = false+ )+ callController.startWakeWordCall()+ }+ )// Floating call buttons (shown during a call, hidden otherwise)chatWindow = CallChatWindow(this).apply {@@ -180,6 +195,11 @@ class AssistiveBallService : Service() {scope.launch {callController.state.collect { state ->val active = state != CallState.IDLE && state != CallState.ENDING+ if (active) {+ wakeWordDetector.stop()+ } else if (state == CallState.IDLE) {+ maybeStartWakeWord()+ }if (active) {chatWindow.show()} else if (state == CallState.IDLE) {@@ -796,6 +816,15 @@ class AssistiveBallService : Service() {android.Manifest.permission.RECORD_AUDIO) == android.content.pm.PackageManager.PERMISSION_GRANTED+ private fun maybeStartWakeWord() {+ val settings = settingsRepository.load()+ if (settings.wakeWordEnabled && settings.assistiveBallEnabled && hasMicPermission()) {+ wakeWordDetector.start()+ } else {+ wakeWordDetector.stop()+ }+ }+override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {when (intent?.action) {ACTION_STOP -> {@@ -806,6 +835,7 @@ class AssistiveBallService : Service() {startAsForeground()overlay.show()_isRunning.value = true+ maybeStartWakeWord()}}return START_STICKY@@ -816,6 +846,7 @@ class AssistiveBallService : Service() {override fun onDestroy() {if (instance === this) instance = null_isRunning.value = false+ wakeWordDetector.stop()callController.endCall()chatWindow.hide()screenCompanionPanel.dismiss()@@ -895,6 +926,7 @@ class AssistiveBallService : Service() {// ---- Lifecycle helpers ----private fun stopBall() {+ wakeWordDetector.stop()callController.endCall()chatWindow.hide()screenCompanionPanel.dismiss()diff --git a/app/src/main/java/com/gotcha/service/CallSessionController.kt b/app/src/main/java/com/gotcha/service/CallSessionController.ktindex 079aa5a..691c33d 100644--- a/app/src/main/java/com/gotcha/service/CallSessionController.kt+++ b/app/src/main/java/com/gotcha/service/CallSessionController.kt@@ -98,6 +98,9 @@ class CallSessionController(private var lastNarrationTimeMs = 0Lprivate var lastNarratedCategory: Category? = null+ /** Set only for a call started by the wake word. */+ private var autoEndOnReply = false+private val _state = MutableStateFlow(CallState.IDLE)val state: StateFlow<CallState> = _state.asStateFlow()@@ -180,6 +183,13 @@ class CallSessionController(return true}+ fun startWakeWordCall(): Boolean {+ autoEndOnReply = true+ if (startCall()) return true+ autoEndOnReply = false+ return false+ }+/*** Stop/interrupt the current turn. Cancels the agent, stops TTS/STT,* completes any pending question, and returns to [READY].@@ -204,6 +214,7 @@ class CallSessionController(/** End the call and delete its chat session + working directory. */fun endCall() {+ autoEndOnReply = falseval endingEngine = engine ?: return_state.value = CallState.ENDINGnarrationJob?.cancel()@@ -326,7 +337,7 @@ class CallSessionController(reportError("Couldn't play the voice reply — check your Text-to-Speech settings.")}onActionRingColor(null)- _state.value = CallState.READY+ if (autoEndOnReply) endCall() else _state.value = CallState.READY}}diff --git a/app/src/main/java/com/gotcha/service/WakeWordDetector.kt b/app/src/main/java/com/gotcha/service/WakeWordDetector.ktnew file mode 100644index 0000000..968f8e9--- /dev/null+++ b/app/src/main/java/com/gotcha/service/WakeWordDetector.kt@@ -0,0 +1,147 @@+package com.gotcha.service++import android.Manifest+import android.content.Context+import android.content.pm.PackageManager+import android.media.AudioFormat+import android.media.AudioRecord+import android.media.MediaRecorder+import androidx.core.content.ContextCompat+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import org.json.JSONObject+import org.vosk.Model+import org.vosk.Recognizer+import java.io.File+import java.util.concurrent.atomic.AtomicBoolean++/** On-device Vosk keyword listener. It owns the microphone only while running. */+class WakeWordDetector(+ context: Context,+ private val scope: CoroutineScope,+ private val onDetected: () -> Unit,+ private val modelAssetPath: String = MODEL_ASSET_PATH,+ private val phrase: String = WAKE_PHRASE+) {+ private val appContext = context.applicationContext+ private val running = AtomicBoolean(false)+ private var job: Job? = null+ private var recorder: AudioRecord? = null+ private var model: Model? = null+ private var recognizer: Recognizer? = null++ @Synchronized+ fun start(): Boolean {+ if (running.get()) return true+ if (ContextCompat.checkSelfPermission(appContext, Manifest.permission.RECORD_AUDIO) !=+ PackageManager.PERMISSION_GRANTED+ ) return false++ return try {+ val modelDir = copyModelToCache()+ val createdModel = Model(modelDir.absolutePath)+ val createdRecognizer = Recognizer(createdModel, SAMPLE_RATE)+ val bufferSize = AudioRecord.getMinBufferSize(+ SAMPLE_RATE.toInt(),+ AudioFormat.CHANNEL_IN_MONO,+ AudioFormat.ENCODING_PCM_16BIT+ ).coerceAtLeast(SAMPLE_RATE.toInt())+ val createdRecorder = AudioRecord(+ MediaRecorder.AudioSource.VOICE_RECOGNITION,+ SAMPLE_RATE.toInt(),+ AudioFormat.CHANNEL_IN_MONO,+ AudioFormat.ENCODING_PCM_16BIT,+ bufferSize+ )+ if (createdRecorder.state != AudioRecord.STATE_INITIALIZED) {+ createdRecorder.release()+ createdRecognizer.close()+ createdModel.close()+ return false+ }+ model = createdModel+ recognizer = createdRecognizer+ recorder = createdRecorder+ running.set(true)+ job = scope.launch(Dispatchers.IO) { listen(bufferSize) }+ true+ } catch (_: Exception) {+ stop()+ false+ }+ }++ @Synchronized+ fun stop() {+ running.set(false)+ recorder?.let {+ try { it.stop() } catch (_: IllegalStateException) { }+ it.release()+ }+ recorder = null+ recognizer?.close()+ recognizer = null+ model?.close()+ model = null+ job?.cancel()+ job = null+ }++ fun isRunning(): Boolean = running.get()++ private fun listen(bufferSize: Int) {+ val localRecorder = recorder ?: return+ val localRecognizer = recognizer ?: return+ val buffer = ByteArray(bufferSize)+ try {+ localRecorder.startRecording()+ while (running.get() && scope.isActive) {+ val count = localRecorder.read(buffer, 0, buffer.size)+ if (count > 0 && localRecognizer.acceptWaveForm(buffer, count)) {+ val text = JSONObject(localRecognizer.result).optString("text")+ if (containsPhrase(text)) {+ running.set(false)+ scope.launch(Dispatchers.Main) { onDetected() }+ return+ }+ }+ }+ } catch (_: Exception) {+ // A missing/incompatible model or a lost audio device must not kill the FGS.+ }+ }++ private fun containsPhrase(text: String): Boolean {+ val normalized = text.lowercase().trim()+ return normalized == phrase || normalized.contains(" $phrase ") ||+ normalized.startsWith("$phrase ") || normalized.endsWith(" $phrase")+ }++ private fun copyModelToCache(): File {+ val destination = File(appContext.cacheDir, "wake-word/$modelAssetPath")+ if (File(destination, ".ready").exists()) return destination+ destination.deleteRecursively()+ copyAssetTree(modelAssetPath, destination)+ File(destination, ".ready").createNewFile()+ return destination+ }++ private fun copyAssetTree(assetPath: String, destination: File) {+ val entries = appContext.assets.list(assetPath).orEmpty()+ destination.mkdirs()+ if (entries.isEmpty()) {+ appContext.assets.open(assetPath).use { input -> destination.outputStream().use(input::copyTo) }+ } else {+ entries.forEach { entry -> copyAssetTree("$assetPath/$entry", File(destination, entry)) }+ }+ }++ companion object {+ const val WAKE_PHRASE = "gotcha"+ const val MODEL_ASSET_PATH = "vosk-model-small-en-us-0.15"+ private const val SAMPLE_RATE = 16_000f+ }+}diff --git a/app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.kt b/app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.ktnew file mode 100644index 0000000..172ad0d--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.kt@@ -0,0 +1,23 @@+package com.gotcha.tools++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import androidx.core.content.ContextCompat+import com.gotcha.data.SettingsRepository+import com.gotcha.service.AssistiveBallService++/** Restores the user-enabled always-on listener after a device reboot. */+class WakeWordBootReceiver : BroadcastReceiver() {+ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action != Intent.ACTION_BOOT_COMPLETED) return+ val settings = SettingsRepository(context).load()+ if (!settings.assistiveBallEnabled || !settings.wakeWordEnabled) return+ runCatching {+ ContextCompat.startForegroundService(+ context,+ AssistiveBallService.startIntent(context)+ )+ }+ }+}diff --git a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.ktindex 1252083..7b7fa68 100644--- a/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt+++ b/app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt@@ -3,6 +3,11 @@ package com.gotcha.uiimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import com.gotcha.data.Settings/*** The Assistive Ball page: one switch that starts or stops the floating overlay,@@ -17,11 +22,15 @@ import androidx.compose.runtime.Composable*/@Composablefun AssistiveBallScreen(+ load: () -> Settings,+ onSave: ((Settings) -> Settings) -> Unit,enabled: Boolean,onToggle: (Boolean) -> Unit,onBack: () -> Unit) {val overlay = rememberSettingsOverlayState()+ val initial = remember { load() }+ var wakeWordEnabled by remember { mutableStateOf(initial.wakeWordEnabled) }SettingsScaffold(title = SettingsPage.ASSISTIVE_BALL.title, onBack = onBack, overlay = overlay) {SettingsToggleRow(@@ -43,6 +52,26 @@ fun AssistiveBallScreen(style = MaterialTheme.typography.bodySmall,color = MaterialTheme.colorScheme.onSurfaceVariant)+ SettingsToggleRow(+ label = "Wake word: Gotcha",+ checked = wakeWordEnabled,+ onCheckedChange = {+ wakeWordEnabled = it+ onSave { settings -> settings.copy(wakeWordEnabled = it) }+ },+ switchTestTag = "settings_wake_word",+ switchContentDescription = if (wakeWordEnabled) {+ "Turn off Gotcha wake word"+ } else {+ "Turn on Gotcha wake word"+ }+ )+ Text(+ "Uses the bundled Vosk model on-device while the assistive ball is on " ++ "and no call is active. Keep microphone permission enabled.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )Text("Needs the \"Display over other apps\" permission — turning this on the " +"first time takes you there to grant it.",diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 1adcaf0..f26437e 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -153,6 +153,8 @@ fun SettingsScreen(onBack = backToHome)SettingsPage.ASSISTIVE_BALL -> AssistiveBallScreen(+ load = load,+ onSave = onSave,enabled = assistiveBallEnabled,onToggle = onToggleAssistiveBall,onBack = backToHomediff --git a/docs/wake-word-handoff.md b/docs/wake-word-handoff.mdnew file mode 100644index 0000000..a1beca0--- /dev/null+++ b/docs/wake-word-handoff.md@@ -0,0 +1,88 @@+# Wake Word Handoff++## Goal+Add an optional wake word ("Gotcha") to the existing Assistive Ball flow using+Vosk instead of Porcupine, while reusing the current `CallSessionController`+voice-call path.++## Current status++### Implemented+- Added Vosk Android dependency in `app/build.gradle.kts`.+- Added `Settings.wakeWordEnabled` and `Settings.wakeWordSensitivity`, with+ persistence in `SettingsRepository`.+- Added `service/WakeWordDetector.kt`:+ - owns `AudioRecord` only while running;+ - copies a Vosk model from `assets/` into cache;+ - runs Vosk recognition on 16 kHz mono PCM;+ - stops itself and invokes the callback on the main thread when "gotcha" is+ recognized;+ - returns `false` instead of crashing when permission/model/audio init fails.+- Wired the detector into `service/AssistiveBallService.kt`:+ - starts only when Assistive Ball + wake word are enabled, mic permission is+ granted, and the call is idle;+ - stops whenever any call state becomes active;+ - stops in `stopBall()` and `onDestroy()`;+ - on detection, gives vibration feedback and starts the existing call flow+ via `callController.startWakeWordCall()`.+- Added `CallSessionController.startWakeWordCall()` and `autoEndOnReply` so a+ wake-word-triggered call ends after the spoken reply; ordinary calls keep the+ existing stay-open behavior.+- Added `tools/WakeWordBootReceiver.kt` and manifest registration to restart+ the ball service after reboot when Assistive Ball + wake word are enabled.+- Added a wake-word toggle to `ui/AssistiveBallScreen.kt` and updated+ `ui/SettingsScreen.kt` to pass `load`/`onSave`.+- Added `docs/wake-word.md` with the Vosk model asset contract.++### Important limitation+No Vosk model binary has been added to the repo. The implementation expects+the model directory at:+`app/src/main/assets/vosk-model-small-en-us-0.15`+Without that asset, `WakeWordDetector.start()` safely returns `false` and the+wake word simply stays non-functional.++## Files changed+- `app/build.gradle.kts`+- `app/src/main/AndroidManifest.xml`+- `app/src/main/java/com/gotcha/data/SettingsRepository.kt`+- `app/src/main/java/com/gotcha/service/AssistiveBallService.kt`+- `app/src/main/java/com/gotcha/service/CallSessionController.kt`+- `app/src/main/java/com/gotcha/service/WakeWordDetector.kt` (new)+- `app/src/main/java/com/gotcha/tools/WakeWordBootReceiver.kt` (new)+- `app/src/main/java/com/gotcha/ui/AssistiveBallScreen.kt`+- `app/src/main/java/com/gotcha/ui/SettingsScreen.kt`+- `docs/wake-word.md` (new)++## Verification state+- `git diff --stat` confirmed the patch shape.+- A first Gradle compile attempt was started:+ `./gradlew.bat :app:compileDebugKotlin`+ but it exceeded the 120s shell timeout in this environment, so compilation+ has **not** yet been verified to completion.++## Next steps for the next agent+1. Run `./gradlew.bat :app:compileDebugKotlin` and fix any compile issues.+2. Add the actual Vosk small English model under+ `app/src/main/assets/vosk-model-small-en-us-0.15/`, then run assemble/build.+3. Add or update unit tests:+ - settings persistence for `wakeWordEnabled` / `wakeWordSensitivity`;+ - `CallSessionController` wake-word auto-end behavior;+ - ideally a fakeable detector wrapper or gate test so service logic is+ testable without native Vosk.+4. Consider adding a runtime restart path when the wake-word setting changes:+ currently a running service does not re-read settings until call state goes+ back to idle or the service is restarted.+5. Decide whether to use `wakeWordSensitivity` (currently persisted but unused).+6. Add battery-optimization education/request flow if desired; the plan called+ for it, but no `REQUEST_IGNORE_BATTERY_OPTIMIZATIONS` flow has been added.+7. Update `app/src/main/assets/legal/privacy-data-retention.md` and/or+ `disclaimer.md` to mention the always-on wake-word listener explicitly.++## Risks / notes+- Vosk is Apache-2.0 and avoids Porcupine's commercial APK licensing concern.+- The detector is intentionally conservative: failure is silent and non-fatal.+- Mic contention is handled by the call-state idle gate, but it has not been+ runtime-tested on a device.+- `WakeWordDetector` uses full Vosk recognition and phrase filtering rather+ than a dedicated grammar-limited KWS configuration; recognition quality and+ false positives need device testing.diff --git a/docs/wake-word.md b/docs/wake-word.mdnew file mode 100644index 0000000..3113268--- /dev/null+++ b/docs/wake-word.md@@ -0,0 +1,15 @@+# Wake Word++Gotcha's optional wake word uses Vosk locally. No audio is sent anywhere while+the listener is waiting; only the existing voice call sends the spoken command+to the configured speech-to-text provider.++The Android build expects the Vosk model directory+`app/src/main/assets/vosk-model-small-en-us-0.15`. Download the corresponding+small English model from the official Vosk model distribution and place its+contents under that directory. The model is intentionally not committed to the+source repository because it is a large binary asset.++The listener is active only when both Assistive Ball and Wake word are enabled,+the microphone permission is granted, and the call state is idle. A missing+model or unavailable microphone disables detection without crashing the service.