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.

Merge branch 'development' into opencode/issue21-20260806045724

Rishabh Bajpaie468111e0609
diff --cc CHANGELOG.md
index 41d147a,8e6d0c4..b2fffdd
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -4,21 -4,43 +4,58 @@@ All notable changes to Gotcha are docum
## [Unreleased]
+### Added — Home Assistant MCP connector (#21)
+
+- **Gotcha can now control and query your smart home through Home Assistant's
+ Model Context Protocol server** (Settings ▸ Devices & Services ▸ Model Context
+ Protocol Server). Connect with your Home Assistant URL plus a long-lived access
+ token (profile ▸ Security ▸ Long-lived access tokens).
+- **The tools come from your server, not a fixed list.** On connect, the app
+ calls the MCP `tools/list` endpoint and registers exactly the tools Home
+ Assistant exposes for the entities you share with Assist — e.g. `HassTurnOn`,
+ `HassGetState`, `GetLiveContext` — so the agent can toggle a light or read a
+ sensor state in the same way the built-in connectors work.
+- **Monitor/Operator split is preserved.** Read-only HA tools (state/context
+ reads) are offered to Monitor; everything else is Operator-only. Disconnect —
+ or switching the connector off — hides the tools again from the model.
+
+ ### Changed — Wake word & call-mode feel (#25)
+
+ - **The wake-word acknowledgment is now one short word.** Saying "Hey Gotcha"
+ used to reply with the full "Call started. I'm ready when you are." sentence,
+ which made the wake word feel ignored and delayed the mic opening. It now
+ answers with a single "Yes?" (translated per language) and the mic opens
+ sooner. Normal long-press calls get a tighter "Call started. Go ahead."
+ - **The ball now visibly reacts when the wake word fires.** It gives a quick
+ scale bounce while an accent ring radiates from it on its own overlay window,
+ so the pulse still plays after the ball is hidden by the call window. Respects
+ the system "remove animations" preference.
+ - **Long-press to start a call is 1 second instead of 2.** The hold-to-call
+ gesture on the floating ball was reduced from 2000 ms to 1000 ms; the
+ expanding ring that previews it stays in sync.
+
+ ### Fixed — Call mode no longer swallows STT/TTS failures (#23)
+
+ - **A failed mic tap is now visible.** When `startMic` can't start the
+ recognizer (busy, MediaRecorder failure, provider unavailable), the call shows
+ "Couldn't start the microphone — tap again to retry." instead of silently doing
+ nothing; the mic stays ready for another tap.
+ - **Hands-free STT failures are no longer mistaken for silence.** The wake-word
+ listen loop now tells a real recognition failure apart from "No speech
+ detected": genuine errors (network, permissions, recognizer busy, ...) are
+ surfaced with the existing error card + vibration and end the call with an
+ explanation, while silence keeps its quiet retry-and-auto-end behaviour. Only
+ silence counts toward the auto-end strikes.
+ - **Tool-progress narration TTS failures surface too.** A failed narration shows
+ the shared "Couldn't play voice audio — check your Text-to-Speech settings."
+ card once per call (repeats are logged), instead of being fire-and-forget.
+ - **In-call error line.** The two floating call buttons now show a transient
+ error line above them, so an in-call error is visible right where the user's
+ eyes are even when the overlay card is off-screen. The overlay card remains
+ the persistent mid-call surface.
+ - Hands-free loop also hands control back to the pre-listen state after a blank
+ listen, so retry (and answering an agent question in place) works as intended.
+
### Fixed — Malformed tool call no longer bricks the chat (#13)
- **A tool call with invalid `arguments` JSON can no longer poison a chat.** When
diff --cc app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
index e0e49c6,3eb9fca..87fc4eb
--- a/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
+++ b/app/src/main/java/com/gotcha/connectors/google/GoogleConnector.kt
@@@ -1,5 -1,5 +1,6 @@@
package com.gotcha.connectors.google
++import android.util.Log
import com.gotcha.connectors.Connector
import com.gotcha.connectors.CredentialStore
import com.gotcha.connectors.mail.EmailFull
@@@ -110,21 -110,6 +111,22 @@@ class GoogleConnector
else -> "Connected as ${credentials?.accountEmail}"
}
+ override suspend fun refreshTools(): String {
+ val creds = credentials ?: return "Not connected"
+ if (creds.needsReconnect) return statusLine()
+ return try {
+ val tok = token(forceRefresh = true)
+ val email = api.profileEmail(tok)
+ if (email != creds.accountEmail) {
+ persist(creds.copy(accountEmail = email))
+ }
+ statusLine()
+ } catch (e: Exception) {
++ Log.w("GoogleConnector", "refreshTools failed; keeping current credentials", e)
+ statusLine()
+ }
+ }
+
override fun disconnect() {
// Best-effort revoke so the grant disappears from the user's Google account.
credentials?.refreshToken?.let { revokeQuietly(it) }
diff --cc app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt
index a09351f,7df7aec..5239913
--- a/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt
+++ b/app/src/main/java/com/gotcha/connectors/microsoft/MicrosoftConnector.kt
@@@ -1,5 -1,5 +1,6 @@@
package com.gotcha.connectors.microsoft
++import android.util.Log
import com.gotcha.connectors.Connector
import com.gotcha.connectors.CredentialStore
import com.gotcha.connectors.mail.EmailFull
@@@ -121,21 -121,6 +122,22 @@@ class MicrosoftConnector
else -> "Connected as ${credentials?.accountEmail}"
}
+ override suspend fun refreshTools(): String {
+ val creds = credentials ?: return "Not connected"
+ if (creds.needsReconnect) return statusLine()
+ return try {
+ val tok = token(forceRefresh = true)
+ val email = api.me(tok)
+ if (email != creds.accountEmail) {
+ persist(creds.copy(accountEmail = email))
+ }
+ statusLine()
+ } catch (e: Exception) {
++ Log.w("MicrosoftConnector", "refreshTools failed; keeping current credentials", e)
+ statusLine()
+ }
+ }
+
override fun disconnect() {
store.clear(id)
credentials = null
diff --cc app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
index d48af18,1d64ab8..51a7b67
--- a/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
+++ b/app/src/main/java/com/gotcha/ui/ConnectorsSection.kt
@@@ -116,130 -68,6 +116,134 @@@ fun ConnectorsSection()
}
}
+@Composable
+private fun AutoRefreshHeader(
+ intervalMinutes: Int,
+ lastRefreshedAt: Long,
+ onIntervalChange: (Int) -> Unit,
+ onRefreshAll: suspend () -> Map<String, String>
+) {
+ val scope = rememberCoroutineScope()
+ var isRefreshing by remember { mutableStateOf(false) }
+ var syncFeedback by remember { mutableStateOf("") }
+ var tick by remember { mutableStateOf(0) }
+
+ // Live recomposition ticker for "X min ago" display
+ LaunchedEffect(lastRefreshedAt) {
+ while (isActive) {
+ delay(10_000L)
+ tick++
+ }
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text("Auto Tool Sync", style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.Medium)
+ // Accessing `tick` forces recomposition when time passes
+ val minutesAgo = if (lastRefreshedAt > 0 && tick >= 0) {
+ ((System.currentTimeMillis() - lastRefreshedAt) / 60_000L).coerceAtLeast(0)
- } else null
++ } else {
++ null
++ }
+
+ Text(
+ if (minutesAgo != null) {
+ if (minutesAgo == 0L) "Last sync: Just now" else "Last sync: $minutesAgo min ago"
- } else "Last sync: Never",
++ } else {
++ "Last sync: Never"
++ },
+ style = MaterialTheme.typography.bodySmall
+ )
+ }
+
+ TextButton(
+ onClick = {
+ if (!isRefreshing) {
+ isRefreshing = true
+ scope.launch {
+ val results = onRefreshAll()
+ isRefreshing = false
+ syncFeedback = if (results.isEmpty()) {
+ "All active connectors are up to date."
+ } else {
+ "Refreshed ${results.size} connector(s): ${results.keys.joinToString(", ")}"
+ }
+ }
+ }
+ },
+ enabled = !isRefreshing
+ ) {
+ Text(if (isRefreshing) "Syncing…" else "Refresh All")
+ }
+ }
+
+ if (syncFeedback.isNotBlank()) {
+ Text(syncFeedback, style = MaterialTheme.typography.bodySmall)
+ }
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text("Interval:", style = MaterialTheme.typography.bodyMedium)
+ val intervals = listOf(0 to "Off", 15 to "15m", 30 to "30m", 120 to "2h")
+ intervals.forEach { (mins, label) ->
+ FilterChip(
+ selected = intervalMinutes == mins,
+ onClick = { onIntervalChange(mins) },
+ label = { Text(label) }
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun HomeAssistantCard(
+ homeAssistant: HomeAssistantConnector,
+ enabled: Boolean,
+ onEnabledChange: (Boolean) -> Unit
+) {
+ val saved = homeAssistant.credentials()
+ val url = rememberTokenField(
+ "Home Assistant URL",
+ saved?.baseUrl ?: "",
+ keyboard = KeyboardType.Uri
+ )
+ val token = rememberTokenField("Long-lived access token", "", secret = true)
+
+ TokenConnectorCard(
+ title = "Home Assistant",
+ statusLine = homeAssistant::statusLine,
+ isConnected = homeAssistant::isConnected,
+ fields = listOf(url, token),
+ headerTestTag = "connector_header_homeassistant",
+ blurb = "Control and query your smart home through Home Assistant's Model Context " +
+ "Protocol server. Its tools are defined by your server and scoped to the entities " +
+ "you expose to Assist.",
+ steps = listOf(
+ "1. In Home Assistant, add the \"Model Context Protocol Server\" integration " +
+ "(Settings ▸ Devices & services ▸ Add integration).",
+ "2. Create a long-lived access token: your profile ▸ Security ▸ Long-lived " +
+ "access tokens ▸ Create token.",
+ "3. Paste your Home Assistant URL (e.g. http://192.168.1.10:8123) and the token below.",
+ "4. Expose the devices you want the assistant to control: Settings ▸ Voice " +
+ "assistants ▸ Expose entities."
+ ),
+ onConnect = { homeAssistant.connect(url.value, token.value) },
+ onDisconnect = homeAssistant::disconnect,
+ onRefresh = homeAssistant::refreshTools,
+ enabled = enabled,
+ onEnabledChange = onEnabledChange
+ )
+}
+
@Composable
private fun NotionCard(
notion: NotionConnector,
diff --cc app/src/test/java/com/gotcha/connectors/ConnectorRefreshTest.kt
index 32cd0cc,0000000..9366282
mode 100644,000000..100644
--- a/app/src/test/java/com/gotcha/connectors/ConnectorRefreshTest.kt
+++ b/app/src/test/java/com/gotcha/connectors/ConnectorRefreshTest.kt
@@@ -1,154 -1,0 +1,164 @@@
+package com.gotcha.connectors
+
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsStore
+import kotlinx.coroutines.test.runTest
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.util.concurrent.atomic.AtomicInteger
+
+private class MockTestConnector(
+ override val id: String,
+ override val displayName: String,
+ private val connected: Boolean = true,
+ private val refreshOutcome: String = "Refreshed $id"
+) : Connector {
+ override val description = "Test connector"
+ override val toolNames = emptySet<String>()
+ override val spec = ConnectorSpec(id, displayName, emptySet())
+ val refreshCount = AtomicInteger(0)
+
+ override fun isConnected(): Boolean = connected
+ override fun statusLine(): String = if (connected) "Connected" else "Not connected"
+ override fun disconnect() {}
+ override suspend fun refreshTools(): String {
+ refreshCount.incrementAndGet()
+ return refreshOutcome
+ }
+}
+
+private class FakeSettingsStore(
+ initialSettings: Settings = Settings()
+) : SettingsStore {
+ private var currentSettings = initialSettings
+
+ override fun load(): Settings = currentSettings
+
+ override fun save(settings: Settings) {
+ currentSettings = settings
+ }
+}
+
+class ConnectorRefreshTest {
+
+ @Test
+ fun `refreshTools interface default method returns statusLine`() = runTest {
+ val connector = MockTestConnector("test", "Test Connector")
+ assertEquals("Refreshed test", connector.refreshTools())
+ assertEquals(1, connector.refreshCount.get())
+ }
+
+ @Test
+ fun `refreshAllActive runs refreshTools concurrently on active connectors`() = runTest {
+ val active1 = MockTestConnector("active1", "Active 1")
+ val active2 = MockTestConnector("active2", "Active 2")
+ val inactive = MockTestConnector("inactive", "Inactive", connected = false)
+
+ val activeConnectors = listOf(active1, active2)
+ val disabled = setOf("inactive")
+
+ val results = activeConnectors.filter { it.isActive(disabled) }
+ .associate { it.id to it.refreshTools() }
+
+ assertEquals(2, results.size)
+ assertEquals("Refreshed active1", results["active1"])
+ assertEquals("Refreshed active2", results["active2"])
+ assertEquals(1, active1.refreshCount.get())
+ assertEquals(1, active2.refreshCount.get())
+ assertEquals(0, inactive.refreshCount.get())
+ }
+
+ @Test
+ fun `scheduler skips refresh when interval is 0 and force is false`() = runTest {
+ var refreshExecuted = false
+ val store = FakeSettingsStore(Settings(connectorAutoRefreshIntervalMinutes = 0, connectorLastRefreshedAt = 0))
+ val scheduler = ConnectorRefreshScheduler(
+ context = null,
+ store = store,
+ clock = { 100_000L },
+ refreshAction = {
+ refreshExecuted = true
+ mapOf("ha" to "ok")
+ }
+ )
+
+ val results = scheduler.refreshIfNeeded(force = false)
+ assertTrue(results.isEmpty())
+ assertFalse(refreshExecuted)
+ }
+
+ @Test
+ fun `scheduler skips refresh when elapsed time is less than interval`() = runTest {
+ var refreshExecuted = false
+ val lastRefreshed = 100_000L
+ val currentTime = lastRefreshed + (10 * 60_000L) // 10 minutes elapsed (interval = 30 min)
- val store = FakeSettingsStore(Settings(connectorAutoRefreshIntervalMinutes = 30, connectorLastRefreshedAt = lastRefreshed))
++ val store = FakeSettingsStore(
++ Settings(
++ connectorAutoRefreshIntervalMinutes = 30,
++ connectorLastRefreshedAt = lastRefreshed
++ )
++ )
+ val scheduler = ConnectorRefreshScheduler(
+ context = null,
+ store = store,
+ clock = { currentTime },
+ refreshAction = {
+ refreshExecuted = true
+ mapOf("ha" to "ok")
+ }
+ )
+
+ val results = scheduler.refreshIfNeeded(force = false)
+ assertTrue(results.isEmpty())
+ assertFalse(refreshExecuted)
+ }
+
+ @Test
+ fun `scheduler executes refresh when elapsed time equals or exceeds interval`() = runTest {
+ var refreshExecuted = false
+ val lastRefreshed = 100_000L
+ val currentTime = lastRefreshed + (35 * 60_000L) // 35 minutes elapsed (interval = 30 min)
- val store = FakeSettingsStore(Settings(connectorAutoRefreshIntervalMinutes = 30, connectorLastRefreshedAt = lastRefreshed))
++ val store = FakeSettingsStore(
++ Settings(
++ connectorAutoRefreshIntervalMinutes = 30,
++ connectorLastRefreshedAt = lastRefreshed
++ )
++ )
+ val scheduler = ConnectorRefreshScheduler(
+ context = null,
+ store = store,
+ clock = { currentTime },
+ refreshAction = {
+ refreshExecuted = true
+ mapOf("homeassistant" to "3 tools available")
+ }
+ )
+
+ val results = scheduler.refreshIfNeeded(force = false)
+ assertEquals(1, results.size)
+ assertTrue(refreshExecuted)
+ assertEquals(currentTime, store.load().connectorLastRefreshedAt)
+ }
+
+ @Test
+ fun `scheduler executes refresh when force is true even if interval is disabled`() = runTest {
+ var refreshExecuted = false
+ val store = FakeSettingsStore(Settings(connectorAutoRefreshIntervalMinutes = 0, connectorLastRefreshedAt = 0))
+ val scheduler = ConnectorRefreshScheduler(
+ context = null,
+ store = store,
+ clock = { 500_000L },
+ refreshAction = {
+ refreshExecuted = true
+ mapOf("notion" to "Connected")
+ }
+ )
+
+ val results = scheduler.refreshIfNeeded(force = true)
+ assertEquals(1, results.size)
+ assertTrue(refreshExecuted)
+ assertEquals(500_000L, store.load().connectorLastRefreshedAt)
+ }
+}