Skip to content

Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.

feat(notifications): notify when Gotcha is waiting for your answer (#108)

Durganshufcce479189ea
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 05e0dde..0be4309 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -697,7 +697,7 @@ class MainActivity : ComponentActivity() {
override fun onStop() {
super.onStop()
- chatViewModel.setForeground(false)
+ chatViewModel.setForeground(false, recreating = isChangingConfigurations)
com.gotcha.data.settingsChangeNotifier(this).unregisterOnSharedPreferenceChangeListener(appearanceListener)
}
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 52eaf13..3c90e24 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -35,6 +35,8 @@ import com.gotcha.llm.attachmentsUserMessage
import com.gotcha.marketing.PosterRenderer
import com.gotcha.marketing.PosterStatsBuilder
import com.gotcha.marketing.ShareCardClient
+import com.gotcha.notifications.AttentionKind
+import com.gotcha.notifications.AttentionNotifier
import com.gotcha.notifications.ChatCompletionNotifier
import com.gotcha.notifications.LocalNotificationStore
import com.gotcha.notifications.NotificationCategory
@@ -259,6 +261,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private val confirmationOverlay = ConfirmationOverlay(application)
private val foregroundControlIndicator = ForegroundControlIndicator(application)
private val completionNotifier = ChatCompletionNotifier(application)
+ private val attentionNotifier = AttentionNotifier(application)
private val localNotificationStore = LocalNotificationStore(application)
private var settings: Settings = Settings()
@@ -533,16 +536,24 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
}
+ /**
+ * Pauses the run on the agent's question. Answering often means leaving
+ * Gotcha first (to run a command in Termux, say), so the question waits
+ * [QUESTION_TIMEOUT_MS] rather than the other gates' two minutes, and a
+ * notification says so whenever Gotcha is out of sight (issue #108).
+ */
override suspend fun awaitQuestionAnswer(question: PendingQuestion): String {
val gate = CompletableDeferred<String>()
questionGate = gate
_uiState.update { it.copy(activity = null, pendingQuestion = question) }
-
- val answer = withTimeoutOrNull(GATE_TIMEOUT_MS) { gate.await() } ?: ""
-
- _uiState.update { it.copy(pendingQuestion = null) }
- questionGate = null
- return answer
+ if (!appInForeground) notifyNeedsInput()
+ return try {
+ withTimeoutOrNull(QUESTION_TIMEOUT_MS) { gate.await() } ?: ""
+ } finally {
+ attentionNotifier.cancel()
+ _uiState.update { it.copy(pendingQuestion = null) }
+ questionGate = null
+ }
}
override suspend fun awaitConfirmation(toolNames: List<String>, description: String): Boolean {
@@ -551,12 +562,41 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
_uiState.update {
it.copy(activity = null, pendingConfirmation = PendingConfirmation(toolNames, description))
}
+ if (!appInForeground) notifyNeedsInput()
+ return try {
+ withTimeoutOrNull(GATE_TIMEOUT_MS) { gate.await() } ?: false
+ } finally {
+ attentionNotifier.cancel()
+ confirmationOverlay.dismiss()
+ _uiState.update { it.copy(pendingConfirmation = null) }
+ confirmationGate = null
+ }
+ }
- val approved = withTimeoutOrNull(GATE_TIMEOUT_MS) { gate.await() } ?: false
- confirmationOverlay.dismiss()
- _uiState.update { it.copy(pendingConfirmation = null) }
- confirmationGate = null
- return approved
+ /**
+ * Tells the user, out of the app, that the run is paused on a question or
+ * confirmation they can't see (issue #108). The foreground-control ask
+ * needs none: it is drawn over whatever app is in front.
+ */
+ private fun notifyNeedsInput() {
+ val state = _uiState.value
+ val kind = when {
+ state.pendingQuestion != null -> AttentionKind.QUESTION
+ state.pendingConfirmation != null -> AttentionKind.CONFIRMATION
+ else -> return
+ }
+ val sessionId = state.runningSessionId ?: agentEngine.sessionId ?: return
+ // Issue #100: a chat kept out of notifications is not named, nor is its question.
+ val named = settings.notificationsMentionChats &&
+ !localNotificationStore.isChatSensitive(sessionId, agentEngine.sessionPersonaId)
+ attentionNotifier.notify(
+ sessionId = sessionId,
+ kind = kind,
+ chatTitle = agentEngine.currentTitle(),
+ question = state.pendingQuestion?.question,
+ preview = settings.chatCompletionPreview,
+ named = named
+ )
}
/**
@@ -1275,12 +1315,22 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
questionGate = null
}
- /** Called from the Activity's onStart/onStop so confirmations know if they'd be hidden. */
- fun setForeground(foreground: Boolean) {
+ /**
+ * Called from the Activity's onStart/onStop so confirmations know if they'd be hidden.
+ * [recreating] is an onStop for a rotation or other configuration change, which is
+ * back within a moment and should not raise a notification.
+ */
+ fun setForeground(foreground: Boolean, recreating: Boolean = false) {
appInForeground = foreground
// Back in the app on a chat whose task finished: that chat's
// notification has done its job.
if (foreground) _uiState.value.activeSessionId?.let(completionNotifier::cancel)
+ // A question or confirmation left on screen is out of sight now; back
+ // in the app, its dialog is showing again.
+ when {
+ foreground -> attentionNotifier.cancel()
+ !recreating -> notifyNeedsInput()
+ }
}
/** Speak the given text aloud using the configured TTS provider. */
@@ -2029,6 +2079,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
private companion object {
const val GATE_TIMEOUT_MS = 120_000L
+ /** How long a question waits; see [awaitQuestionAnswer]. */
+ const val QUESTION_TIMEOUT_MS = 600_000L
+
/** Set once the one-time notification-permission ask has been shown. */
const val KEY_NOTIFICATION_PERMISSION_ASKED = "chat_notification_permission_asked"
diff --git a/app/src/main/java/com/gotcha/notifications/AttentionNotifier.kt b/app/src/main/java/com/gotcha/notifications/AttentionNotifier.kt
new file mode 100644
index 0000000..9701055
--- /dev/null
+++ b/app/src/main/java/com/gotcha/notifications/AttentionNotifier.kt
@@ -0,0 +1,129 @@
+package com.gotcha.notifications
+
+import android.app.NotificationChannel
+import android.app.NotificationManager
+import android.app.PendingIntent
+import android.content.Context
+import android.content.Intent
+import androidx.core.app.NotificationCompat
+import androidx.core.app.NotificationManagerCompat
+import com.gotcha.data.CompletionPreview
+
+/** What a paused run is waiting on. */
+enum class AttentionKind { QUESTION, CONFIRMATION }
+
+/**
+ * Posts "Gotcha needs your answer" while a run is paused on the user — a
+ * question from the agent or an "Allow these actions?" confirmation — and they
+ * are not in Gotcha to see the dialog (issue #108). Without it the run just
+ * sits there: the dialog is the only other sign it is waiting.
+ *
+ * Only one run goes at a time, so there is one slot: a newer ask replaces the
+ * older one. Its own high-importance channel, apart from task-finished
+ * notifications, because the run is blocked until the user answers.
+ */
+class AttentionNotifier(private val context: Context) {
+
+ /** True when Android will actually show what [notify] posts. */
+ fun canPost(): Boolean = ChatCompletionNotifier(context).canPost()
+
+ /**
+ * Posts the notification for the run in [sessionId]. [question] is the
+ * agent's question (Markdown), shown as [preview] allows. With [named] false
+ * (issue #100) neither the chat nor the question appears. Returns false when
+ * nothing was posted.
+ */
+ @Suppress("MissingPermission") // canPost() checks it.
+ fun notify(
+ sessionId: String,
+ kind: AttentionKind,
+ chatTitle: String,
+ question: String?,
+ preview: CompletionPreview,
+ named: Boolean = true
+ ): Boolean {
+ if (!canPost()) return false
+ ensureChannel()
+ val shown = if (named && kind == AttentionKind.QUESTION) preview else CompletionPreview.NONE
+ val body = questionPreview(question, shown) ?: defaultBody(kind)
+
+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setContentTitle(title(kind))
+ .setContentText(body)
+ .setCategory(NotificationCompat.CATEGORY_REMINDER)
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
+ // A question can be personal: the lock screen gets a generic line only.
+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)
+ .setPublicVersion(
+ NotificationCompat.Builder(context, CHANNEL_ID)
+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)
+ .setContentTitle(PUBLIC_TITLE)
+ .build()
+ )
+ .setOnlyAlertOnce(true)
+ .setAutoCancel(true)
+ .setContentIntent(openChatIntent(sessionId))
+ if (named) builder.setSubText(chatTitle.ifBlank { null })
+ if (shown == CompletionPreview.FULL) {
+ builder.setStyle(NotificationCompat.BigTextStyle().bigText(body))
+ }
+ NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, builder.build())
+ return true
+ }
+
+ /** Clears the notification: the ask was answered, skipped, timed out or the run stopped. */
+ fun cancel() {
+ NotificationManagerCompat.from(context).cancel(NOTIFICATION_ID)
+ }
+
+ private fun openChatIntent(sessionId: String): PendingIntent {
+ val intent = Intent(context, com.gotcha.MainActivity::class.java).apply {
+ action = ChatCompletionNotifier.ACTION_OPEN_CHAT_SESSION
+ putExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID, sessionId)
+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
+ }
+ return PendingIntent.getActivity(
+ context,
+ NOTIFICATION_ID,
+ intent,
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
+ )
+ }
+
+ private fun ensureChannel() {
+ val mgr = context.getSystemService(NotificationManager::class.java) ?: return
+ if (mgr.getNotificationChannel(CHANNEL_ID) != null) return
+ mgr.createNotificationChannel(
+ NotificationChannel(CHANNEL_ID, "Waiting for your answer", NotificationManager.IMPORTANCE_HIGH).apply {
+ description = "When Gotcha has paused a task to ask you something while you are in another app"
+ }
+ )
+ }
+
+ companion object {
+ const val CHANNEL_ID = "gotcha_needs_input"
+ private const val NOTIFICATION_ID = 0x4A77_E7
+ private const val PUBLIC_TITLE = "Gotcha is waiting for you"
+ private val FENCE_LINE = Regex("^\\s*(```|~~~).*$")
+
+ internal fun title(kind: AttentionKind): String = when (kind) {
+ AttentionKind.QUESTION -> "Gotcha has a question"
+ AttentionKind.CONFIRMATION -> "Gotcha is waiting for your OK"
+ }
+
+ internal fun defaultBody(kind: AttentionKind): String = when (kind) {
+ AttentionKind.QUESTION -> "Your task is paused until you answer. Tap to open it."
+ AttentionKind.CONFIRMATION -> "Your task is paused until you allow or deny its next step. Tap to open it."
+ }
+
+ /**
+ * The question as the notification shows it, or null when [preview]
+ * hides it. Fence lines are dropped so a command inside shows as itself.
+ */
+ internal fun questionPreview(question: String?, preview: CompletionPreview): String? {
+ val text = question?.lines()?.filterNot { FENCE_LINE.matches(it) }?.joinToString("\n")
+ return ChatCompletionNotifier.previewText(text, preview)
+ }
+ }
+}
diff --git a/app/src/test/java/com/gotcha/notifications/AttentionNotifierTest.kt b/app/src/test/java/com/gotcha/notifications/AttentionNotifierTest.kt
new file mode 100644
index 0000000..18a80f9
--- /dev/null
+++ b/app/src/test/java/com/gotcha/notifications/AttentionNotifierTest.kt
@@ -0,0 +1,113 @@
+package com.gotcha.notifications
+
+import android.Manifest
+import android.app.Application
+import android.app.NotificationManager
+import androidx.core.app.NotificationCompat
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.CompletionPreview
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.Shadows.shadowOf
+import org.robolectric.annotation.Config
+
+/** The "Gotcha needs your answer" notification for a paused run (issue #108). */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class AttentionNotifierTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+ private val manager = application.getSystemService(NotificationManager::class.java)
+ private val notifier = AttentionNotifier(application)
+
+ @Before
+ fun setUp() {
+ shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)
+ }
+
+ private fun posted() = shadowOf(manager).allNotifications
+
+ private fun text(n: android.app.Notification) = n.extras.getCharSequence(NotificationCompat.EXTRA_TEXT).toString()
+
+ @Test
+ fun `a question posts on its own high-importance channel with a tap that opens the chat`() {
+ assertTrue(
+ notifier.notify("s1", AttentionKind.QUESTION, "Build", "Which folder?", CompletionPreview.SHORT)
+ )
+
+ val notification = posted().single()
+ assertEquals(AttentionNotifier.CHANNEL_ID, notification.channelId)
+ assertEquals(
+ NotificationManager.IMPORTANCE_HIGH,
+ manager.getNotificationChannel(AttentionNotifier.CHANNEL_ID).importance
+ )
+ assertEquals("Gotcha has a question", notification.extras.getString(NotificationCompat.EXTRA_TITLE))
+ assertEquals("Which folder?", text(notification))
+ assertEquals("Build", notification.extras.getString(NotificationCompat.EXTRA_SUB_TEXT))
+ assertEquals(NotificationCompat.VISIBILITY_PRIVATE, notification.visibility)
+
+ val tap = shadowOf(notification.contentIntent).savedIntent
+ assertEquals("s1", tap.getStringExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID))
+ assertEquals(ChatCompletionNotifier.ACTION_OPEN_CHAT_SESSION, tap.action)
+ }
+
+ @Test
+ fun `one slot - a newer ask replaces the older one, and cancel clears it`() {
+ notifier.notify("s1", AttentionKind.QUESTION, "Chat", "first?", CompletionPreview.SHORT)
+ notifier.notify("s1", AttentionKind.CONFIRMATION, "Chat", null, CompletionPreview.SHORT)
+
+ val title = posted().single().extras.getString(NotificationCompat.EXTRA_TITLE)
+ assertEquals("Gotcha is waiting for your OK", title)
+ notifier.cancel()
+ assertTrue(posted().isEmpty())
+ }
+
+ @Test
+ fun `a chat that may not be named shows neither the chat nor the question`() {
+ notifier.notify(
+ "s1",
+ AttentionKind.QUESTION,
+ "Doctor chat",
+ "Any allergies?",
+ CompletionPreview.FULL,
+ named = false
+ )
+
+ val notification = posted().single()
+ assertEquals(AttentionNotifier.defaultBody(AttentionKind.QUESTION), text(notification))
+ assertNull(notification.extras.getString(NotificationCompat.EXTRA_SUB_TEXT))
+ }
+
+ @Test
+ fun `a confirmation never shows the actions, only that it is waiting`() {
+ notifier.notify("s1", AttentionKind.CONFIRMATION, "Chat", "Delete 3 files", CompletionPreview.FULL)
+
+ assertEquals(AttentionNotifier.defaultBody(AttentionKind.CONFIRMATION), text(posted().single()))
+ }
+
+ @Test
+ fun `nothing is posted without permission`() {
+ shadowOf(application).denyPermissions(Manifest.permission.POST_NOTIFICATIONS)
+
+ assertFalse(notifier.notify("s1", AttentionKind.QUESTION, "Chat", "q?", CompletionPreview.SHORT))
+ assertTrue(posted().isEmpty())
+ }
+
+ @Test
+ fun `the preview drops code fences and follows the preview setting`() {
+ val question = "In Termux, run:\n\n```bash\necho hi\n```\n\nDone?"
+
+ val short = AttentionNotifier.questionPreview(question, CompletionPreview.SHORT)
+ val full = AttentionNotifier.questionPreview(question, CompletionPreview.FULL)
+ assertEquals("In Termux, run: echo hi Done?", short)
+ assertEquals("In Termux, run:\necho hi\nDone?", full)
+ assertNull(AttentionNotifier.questionPreview(question, CompletionPreview.NONE))
+ assertNull(AttentionNotifier.questionPreview(null, CompletionPreview.SHORT))
+ }
+}