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 a chat task finishes in the background (#97)
Durganshucc852229cd31
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex fc1a9d9..0ee71b9 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -49,6 +49,7 @@ import com.gotcha.data.SettingsRepositoryimport com.gotcha.data.computeFeedbackStatsimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClient+import com.gotcha.notifications.ChatCompletionNotifierimport com.gotcha.notifications.NotificationDispatcherimport com.gotcha.notifications.NotificationPayloadimport com.gotcha.notifications.ServerMessages@@ -131,6 +132,9 @@ class MainActivity : ComponentActivity() {/** Set when launched from the assistive ball's "Open Chat" option. */private var openChatRequested by mutableStateOf(false)+ /** Chat to open, set when a task-finished notification is tapped (issue #97). */+ private var openSessionRequested by mutableStateOf<String?>(null)+/** Set when brought to front by the assistive ball (Operator-origin chats). */private var openedFromBall by mutableStateOf(false)@@ -247,6 +251,16 @@ class MainActivity : ComponentActivity() {}}+ /**+ * The one-time notification ask raised when a request is sent (issue #97).+ * Unlike [runtimePermissionLauncher] nothing waits on it: a denial only+ * means the task-finished notification stays off.+ */+ private val notificationPermissionLauncher =+ registerForActivityResult(ActivityResultContracts.RequestPermission()) { granted ->+ chatViewModel.onNotificationPermissionResult(granted)+ }+override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)lifecycleOwner = this@@ -478,6 +492,11 @@ class MainActivity : ComponentActivity() {}private fun handleNotificationIntent(intent: Intent?) {+ intent?.getStringExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID)?.let { id ->+ openSessionRequested = id+ // Consumed: a later recreation must not reopen this chat over the user's choice.+ intent.removeExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID)+ }val title = intent?.getStringExtra(NotificationDispatcher.EXTRA_NOTIFICATION_TITLE)val body = intent?.getStringExtra(NotificationDispatcher.EXTRA_NOTIFICATION_BODY)if (!title.isNullOrBlank() || !body.isNullOrBlank()) {@@ -664,6 +683,15 @@ class MainActivity : ComponentActivity() {}}+ // A tapped task-finished notification: show exactly that chat.+ LaunchedEffect(openSessionRequested) {+ openSessionRequested?.let { id ->+ currentRoute = Route.HOME+ chatViewModel.openSessionFromNotification(id)+ openSessionRequested = null+ }+ }+// Honor the assistive ball's "Open Chat" option.LaunchedEffect(openChatRequested) {if (openChatRequested) {@@ -1012,6 +1040,15 @@ class MainActivity : ComponentActivity() {)}+ if (state.askNotificationPermission) {+ val ask = remember { runtimePermissionAsk(android.Manifest.permission.POST_NOTIFICATIONS) }+ PermissionRationaleDialog(+ ask = ask,+ onAllow = { notificationPermissionLauncher.launch(ask.permission) },+ onDeny = { chatViewModel.onNotificationPermissionResult(false) }+ )+ }+blockedPermissionAsk?.let { ask ->PermissionBlockedDialog(ask = ask,diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 05b4e56..6f3a3e2 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -5,6 +5,7 @@ import android.content.ContentResolverimport android.graphics.Bitmapimport android.graphics.BitmapFactoryimport android.net.Uri+import android.os.Buildimport android.provider.OpenableColumnsimport androidx.lifecycle.AndroidViewModelimport androidx.lifecycle.viewModelScope@@ -28,6 +29,8 @@ import com.gotcha.llm.attachmentsUserMessageimport com.gotcha.marketing.PosterRendererimport com.gotcha.marketing.PosterStatsBuilderimport com.gotcha.marketing.ShareCardClient+import com.gotcha.notifications.ChatCompletionNotifier+import com.gotcha.notifications.RunOutcomeimport com.gotcha.tools.AgentModeimport com.gotcha.tools.DocumentErrorimport com.gotcha.tools.DocumentParser@@ -123,12 +126,14 @@ internal val ATTACHMENT_PLACEHOLDERS = setOf("(image attached)", "(document atta/*** The "you can leave Gotcha" hint shown while a run works. It only promises the- * signal the user will actually get: the buzz and chime are opt-in, and there is- * no system notification yet (issue #103).+ * signal the user will actually get: [notify] is true only when a task-finished+ * notification is switched on and Android allows it (issue #97); otherwise the+ * opt-in buzz and chime are all there is.*/-internal fun backgroundHintText(vibrate: Boolean, chime: Boolean): String {+internal fun backgroundHintText(vibrate: Boolean, chime: Boolean, notify: Boolean = false): String {val base = "Gotcha is working in the background. You can use another app while it works"val signal = when {+ notify -> "Gotcha will notify you when the task is finished"vibrate && chime -> "your phone will buzz and chime when it's done"vibrate -> "your phone will buzz when it's done"chime -> "your phone will chime when it's done"@@ -196,6 +201,12 @@ data class ChatUiState(* run, never in the transcript, so returning to the app can't repeat it.*/val backgroundHint: String? = null,+ /**+ * True while the one-time "allow notifications?" ask is on screen. Asked the+ * first time a request is sent without the permission, so the user learns a+ * task can notify them; the run does not wait on the answer.+ */+ val askNotificationPermission: Boolean = false,val contextUsagePercent: Float = 0f,val tokenCount: Int = 0,val maxContextTokens: Int = 0,@@ -222,6 +233,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aprivate val settingsRepository = SettingsRepository(application)private val historyRepository = ChatHistoryRepository(application)private val confirmationOverlay = ConfirmationOverlay(application)+ private val completionNotifier = ChatCompletionNotifier(application)private var settings: Settings = Settings()private var client: LLMClient? = null@@ -330,6 +342,14 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Areturn title.isBlank() || title == fallback}+ /**+ * Startup: the fresh session, the chat-directory migration and the sample+ * seeding. Anything that loads a saved chat on the user's behalf before the+ * UI is up (a notification tap) waits for it, or the migration could move+ * the chat out from under the load.+ */+ private val initJob: Job+private val _uiState = MutableStateFlow(ChatUiState())val uiState: StateFlow<ChatUiState> = _uiState.asStateFlow()@@ -361,7 +381,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AScreenPerception.appContext = applicationcom.gotcha.agent.skills.SkillRegistry.init(application)refreshSettings()- viewModelScope.launch {+ initJob = viewModelScope.launch {// Always start on a fresh session so the home screen greets with an// empty chat; past sessions remain one tap away in the drawer.agentEngine.sessionId = java.util.UUID.randomUUID().toString()@@ -683,16 +703,16 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), AisBusy = true,runningSessionId = runningId,runningSessionTitle = runningTitle,- backgroundHint = backgroundHintText(- vibrate = settings.notifyVibrationEnabled,- chime = settings.notifyChimeEnabled- )+ backgroundHint = currentBackgroundHint(),+ askNotificationPermission = it.askNotificationPermission || claimNotificationPermissionAsk())}runHadError = false+ var stopped = falsetry {agentEngine.run(agent)} catch (_: CancellationException) {+ stopped = trueappendEngineUi(MessageKind.ERROR, "Agent was interrupted by the user.")// The interrupt may have orphaned an assistant with tool_calls but no// matching tool results. Repair it in NonCancellable before the next@@ -708,6 +728,14 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A// own sanitize still gets repaired here before persisting.agentEngine.sanitizeLastOrphanedAssistant()agentEngine.saveCurrentSession()+ notifyRunFinished(+ sessionId = runningId,+ outcome = when {+ stopped -> RunOutcome.STOPPED+ runHadError -> RunOutcome.FAILED+ else -> RunOutcome.DONE+ }+ )_uiState.update {it.copy(isBusy = false,@@ -724,6 +752,73 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}}+ private fun currentBackgroundHint(): String = backgroundHintText(+ vibrate = settings.notifyVibrationEnabled,+ chime = settings.notifyChimeEnabled,+ notify = settings.chatCompletionNotificationsEnabled && completionNotifier.canPost()+ )++ /**+ * The run in [sessionId] just ended. Posts the task-finished notification+ * when the user is away from Gotcha; in the foreground the reply buzz is+ * enough. Called once per run, from [executeRun]'s cleanup, so a run never+ * produces two — the engine reports text mid-run too, which is why this is+ * not driven by [onAssistantReply].+ */+ private fun notifyRunFinished(sessionId: String, outcome: RunOutcome) {+ if (appInForeground || !settings.chatCompletionNotificationsEnabled) return+ val reply = engineTranscript.lastOrNull {+ it.kind == MessageKind.ASSISTANT || it.kind == MessageKind.ERROR+ }?.text+ completionNotifier.notify(+ sessionId = sessionId,+ chatTitle = agentEngine.currentTitle(),+ outcome = outcome,+ reply = reply,+ preview = settings.chatCompletionPreview+ )+ }++ /**+ * True, once per install, when the user should be asked for notification+ * permission: they want task-finished notifications, Android 13+ blocks+ * them, and they are here to see the ask. Claimed as it is shown, so+ * "Not now" is final — the Notifications settings page can still ask.+ */+ private fun claimNotificationPermissionAsk(): Boolean {+ if (!appInForeground || !settings.chatCompletionNotificationsEnabled) return false+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return false+ if (completionNotifier.canPost()) return false+ val prefs = settingsRepository.prefs+ if (prefs.getBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, false)) return false+ prefs.edit().putBoolean(KEY_NOTIFICATION_PERMISSION_ASKED, true).apply()+ return true+ }++ /**+ * The answer to [ChatUiState.askNotificationPermission]. A grant mid-run+ * upgrades the hint on screen to the notification promise it can now keep.+ */+ fun onNotificationPermissionResult(granted: Boolean) {+ _uiState.update {+ it.copy(+ askNotificationPermission = false,+ backgroundHint = if (granted && it.backgroundHint != null) currentBackgroundHint() else it.backgroundHint+ )+ }+ }++ /**+ * Opens [id] from a tapped task-finished notification. Waits for startup,+ * which would otherwise replace the chat with the fresh one it opens.+ */+ fun openSessionFromNotification(id: String) {+ viewModelScope.launch {+ initJob.join()+ openSession(id)+ }+ }+/*** Replaces the user message [targetId] with [newText] and [attachments]; a* null [attachments] keeps the ones the original message was sent with. The target's whole turn and@@ -1060,6 +1155,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A/** Called from the Activity's onStart/onStop so confirmations know if they'd be hidden. */fun setForeground(foreground: Boolean) {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)}/** Speak the given text aloud using the configured TTS provider. */@@ -1398,6 +1496,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}fun openSession(id: String?) {+ id?.let(completionNotifier::cancel)lastInputWasVoice = falsecurrentRunIsVoice = falseviewModelScope.launch {@@ -1756,6 +1855,9 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aprivate companion object {const val GATE_TIMEOUT_MS = 120_000L+ /** Set once the one-time notification-permission ask has been shown. */+ const val KEY_NOTIFICATION_PERMISSION_ASKED = "chat_notification_permission_asked"+/** Starts each document section in a user message; see [documentPromptText]. */const val ATTACHED_FILE_MARKER = "\n[Attached file:"const val MIGRATED_CHAT_DIRS_KEY = "migrated_chat_dirs_v1"diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex e16b146..9e1c41d 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -14,6 +14,18 @@ import com.gotcha.i18n.Language* inference. These modes trade how much of the day that happens for where the* user is most likely to want a hands-free trigger.*/+/** How much of the reply a task-finished notification shows (issue #97). */+enum class CompletionPreview {+ /** Only the chat title and whether the task finished, failed or stopped. */+ NONE,++ /** The first lines of the reply. */+ SHORT,++ /** The whole reply, readable by expanding the notification. */+ FULL+}+enum class WakeWordListeningMode {/** Listen regardless of screen state — the original always-on behaviour. */ALWAYS,@@ -113,6 +125,13 @@ data class Settings(val notifyVibrationEnabled: Boolean = true,/** Chime when a reply arrives. Off by default — audible in a way a buzz is not. */val notifyChimeEnabled: Boolean = false,+ /**+ * Post a system notification when a chat run ends while Gotcha is in the+ * background (issue #97). On by default: without it a finished task is only+ * a buzz the user may not feel.+ */+ val chatCompletionNotificationsEnabled: Boolean = true,+ val chatCompletionPreview: CompletionPreview = CompletionPreview.SHORT,val assistiveBallEnabled: Boolean = false,val wakeWordEnabled: Boolean = false,val wakeWordSensitivity: Float = 0.75f,@@ -500,6 +519,10 @@ class SettingsRepository(context: Context) : SettingsStore {autoReadReplies = prefs.getBoolean(KEY_AUTO_READ, false),notifyVibrationEnabled = prefs.getBoolean(KEY_NOTIFY_VIBRATION, true),notifyChimeEnabled = prefs.getBoolean(KEY_NOTIFY_CHIME, false),+ chatCompletionNotificationsEnabled = prefs.getBoolean(KEY_CHAT_COMPLETION_NOTIFICATIONS, true),+ chatCompletionPreview = runCatching {+ CompletionPreview.valueOf(string(KEY_CHAT_COMPLETION_PREVIEW, "SHORT"))+ }.getOrDefault(CompletionPreview.SHORT),assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false),wakeWordEnabled = prefs.getBoolean(KEY_WAKE_WORD_ENABLED, false),wakeWordSensitivity = prefs.getFloat(KEY_WAKE_WORD_SENSITIVITY, 0.75f),@@ -575,6 +598,8 @@ class SettingsRepository(context: Context) : SettingsStore {.putBoolean(KEY_AUTO_READ, settings.autoReadReplies).putBoolean(KEY_NOTIFY_VIBRATION, settings.notifyVibrationEnabled).putBoolean(KEY_NOTIFY_CHIME, settings.notifyChimeEnabled)+ .putBoolean(KEY_CHAT_COMPLETION_NOTIFICATIONS, settings.chatCompletionNotificationsEnabled)+ .putString(KEY_CHAT_COMPLETION_PREVIEW, settings.chatCompletionPreview.name).putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled).putBoolean(KEY_WAKE_WORD_ENABLED, settings.wakeWordEnabled).putFloat(KEY_WAKE_WORD_SENSITIVITY, settings.wakeWordSensitivity)@@ -688,6 +713,8 @@ class SettingsRepository(context: Context) : SettingsStore {const val KEY_AUTO_READ = "auto_read"const val KEY_NOTIFY_VIBRATION = "notify_vibration"const val KEY_NOTIFY_CHIME = "notify_chime"+ const val KEY_CHAT_COMPLETION_NOTIFICATIONS = "chat_completion_notifications"+ const val KEY_CHAT_COMPLETION_PREVIEW = "chat_completion_preview"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"diff --git a/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt b/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.ktnew file mode 100644index 0000000..6267b5b--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt@@ -0,0 +1,161 @@+package com.gotcha.notifications++import android.Manifest+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat+import com.gotcha.data.CompletionPreview++/** How a chat run ended, as the task-finished notification reports it. */+enum class RunOutcome { DONE, FAILED, STOPPED }++/**+ * Posts the "task finished" notification for a chat run that ended while Gotcha+ * was in the background (issue #97). One slot per chat: a newer run in the same+ * chat replaces the older notification instead of stacking beside it, and+ * opening the chat clears it.+ *+ * Kept apart from [NotificationDispatcher], which owns server messages: the two+ * have separate channels so either can be silenced without the other.+ */+class ChatCompletionNotifier(private val context: Context) {++ /** True when Android will actually show what [notify] posts. */+ fun canPost(): Boolean {+ if (!NotificationManagerCompat.from(context).areNotificationsEnabled()) return false+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true+ return ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) ==+ PackageManager.PERMISSION_GRANTED+ }++ /**+ * Posts the notification for [sessionId]. [reply] is the run's last assistant+ * message (or error text); [preview] decides how much of it is shown.+ * Returns false when nothing was posted.+ */+ @Suppress("MissingPermission") // canPost() checks it.+ fun notify(+ sessionId: String,+ chatTitle: String,+ outcome: RunOutcome,+ reply: String?,+ preview: CompletionPreview+ ): Boolean {+ if (!canPost()) return false+ ensureChannel()+ val notifyId = notificationId(sessionId)+ val title = notificationTitle(chatTitle, outcome)+ val body = previewText(reply, preview) ?: defaultBody(outcome)++ val builder = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)+ .setContentTitle(title)+ .setContentText(body)+ .setCategory(NotificationCompat.CATEGORY_STATUS)+ // Replies 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()+ )+ .setAutoCancel(true)+ .setContentIntent(openChatIntent(sessionId, notifyId))+ if (preview == CompletionPreview.FULL) {+ builder.setStyle(NotificationCompat.BigTextStyle().bigText(body))+ }+ NotificationManagerCompat.from(context).notify(notifyId, builder.build())+ return true+ }++ /** Clears [sessionId]'s notification, e.g. once the user has opened that chat. */+ fun cancel(sessionId: String) {+ NotificationManagerCompat.from(context).cancel(notificationId(sessionId))+ }++ private fun openChatIntent(sessionId: String, requestCode: Int): PendingIntent {+ val intent = Intent(context, com.gotcha.MainActivity::class.java).apply {+ action = ACTION_OPEN_CHAT_SESSION+ putExtra(EXTRA_OPEN_SESSION_ID, sessionId)+ flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+ }+ return PendingIntent.getActivity(+ context,+ requestCode,+ 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, "Task finished", NotificationManager.IMPORTANCE_DEFAULT).apply {+ description = "When a chat task finishes while you are in another app"+ }+ )+ }++ companion object {+ const val CHANNEL_ID = "gotcha_chat_completion"+ const val ACTION_OPEN_CHAT_SESSION = "com.gotcha.ACTION_OPEN_CHAT_SESSION"+ const val EXTRA_OPEN_SESSION_ID = "com.gotcha.OPEN_SESSION_ID"+ private const val PUBLIC_TITLE = "Gotcha finished a task"+ private const val SHORT_PREVIEW_CHARS = 140++ /** Stable per chat, so a later run's notification replaces the earlier one. */+ internal fun notificationId(sessionId: String): Int = "chat:$sessionId".hashCode() and 0x7FFF_FFFF++ internal fun notificationTitle(chatTitle: String, outcome: RunOutcome): String {+ val chat = chatTitle.ifBlank { "Chat" }+ return when (outcome) {+ RunOutcome.DONE -> "Done: $chat"+ RunOutcome.FAILED -> "Failed: $chat"+ RunOutcome.STOPPED -> "Stopped: $chat"+ }+ }++ internal fun defaultBody(outcome: RunOutcome): String = when (outcome) {+ RunOutcome.DONE -> "Gotcha finished your task. Tap to see the reply."+ RunOutcome.FAILED -> "Gotcha couldn't finish your task. Tap to see what happened."+ RunOutcome.STOPPED -> "The task was stopped. Tap to open the chat."+ }++ /**+ * The reply as the notification shows it, or null when [preview] hides it+ * or there is nothing to show. Replies are Markdown; the notification is+ * plain text, so the common markers are dropped.+ */+ internal fun previewText(reply: String?, preview: CompletionPreview): String? {+ if (preview == CompletionPreview.NONE) return null+ val plain = reply?.let(::plainText)?.takeIf { it.isNotBlank() } ?: return null+ if (preview == CompletionPreview.FULL) return plain+ // A collapsed notification shows one line, so a short preview flows as one.+ val oneLine = plain.replace('\n', ' ')+ if (oneLine.length <= SHORT_PREVIEW_CHARS) return oneLine+ return oneLine.take(SHORT_PREVIEW_CHARS).trimEnd() + "…"+ }++ private fun plainText(markdown: String): String =+ markdown.lines()+ .map { it.trim() }+ // Dividers (---, ***) carry nothing in plain text.+ .filterNot { it.matches(Regex("[-*_]{3,}")) }+ .map { line ->+ line.replace(Regex("^#{1,6}\\s+"), "")+ .replace(Regex("^[-*+]\\s+"), "• ")+ .replace(Regex("\\*\\*|__|`"), "")+ }+ .filter { it.isNotEmpty() }+ .joinToString("\n")+ }+}diff --git a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt b/app/src/main/java/com/gotcha/ui/NotificationsScreen.ktindex afc9773..8acbda7 100644--- a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt@@ -1,15 +1,23 @@package com.gotcha.ui+import android.content.Intentimport android.content.pm.PackageManagerimport android.os.Buildimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Column+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.Buttonimport androidx.compose.material3.MaterialTheme+import androidx.compose.material3.RadioButtonimport androidx.compose.material3.Text+import androidx.compose.material3.TextButtonimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValue@@ -17,15 +25,20 @@ import androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.rememberimport androidx.compose.runtime.rememberCoroutineScopeimport 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.unit.dpimport androidx.core.content.ContextCompatimport com.gotcha.BuildConfigimport com.gotcha.audio.CompletionFeedback+import com.gotcha.data.CompletionPreviewimport com.gotcha.data.Settings+import com.gotcha.notifications.ChatCompletionNotifierimport kotlinx.coroutines.launch+import android.provider.Settings as AndroidSettings/*** The Notifications page: what the phone does the moment a reply arrives@@ -47,19 +60,23 @@ fun NotificationsScreen(val initial = remember { load() }var notifyVibration by remember { mutableStateOf(initial.notifyVibrationEnabled) }var notifyChime by remember { mutableStateOf(initial.notifyChimeEnabled) }+ var taskFinished by remember { mutableStateOf(initial.chatCompletionNotificationsEnabled) }+ var taskPreview by remember { mutableStateOf(initial.chatCompletionPreview) }var serverMessagesEnabled by remember { mutableStateOf(initial.serverMessagesEnabled) }var lastFetched by remember { mutableStateOf(initial.serverMessagesLastFetchedAt) }var isSyncing by remember { mutableStateOf(false) }val overlay = rememberSettingsOverlayState()val localContext = LocalContext.current+ // Re-read after the permission prompt, so the "blocked" note clears on a grant.+ var canPost by remember { mutableStateOf(ChatCompletionNotifier(localContext).canPost()) }val scope = rememberCoroutineScope()// Asked for when server messages are switched on, not at first launch —// a notification permission is only meaningful once something wants to post.val notificationPermissionLauncher = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()- ) { /* declining just means no status-bar alert; the setting still holds */ }+ ) { canPost = ChatCompletionNotifier(localContext).canPost() }// Sync only when the user toggles server messages ON, not on the// initial composition — `onResume` already covers the first-arrival case.@@ -100,6 +117,65 @@ fun NotificationsScreen(switchTestTag = "settings_notify_chime")+ Spacer(Modifier.height(16.dp))+ Text(+ "Task finished",+ style = MaterialTheme.typography.titleMedium+ )+ Text(+ "A notification when a chat task finishes while you are in another app. " ++ "Tap it to open that chat. On the lock screen it only says a task finished.",+ style = MaterialTheme.typography.bodySmall+ )+ SettingsToggleRow(+ label = "Notify when a task finishes",+ checked = taskFinished,+ onCheckedChange = {+ taskFinished = it+ onSave { s -> s.copy(chatCompletionNotificationsEnabled = it) }+ if (it && !canPost && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ notificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)+ }+ },+ isLarge = true,+ switchTestTag = "settings_task_finished_enabled"+ )+ if (taskFinished) {+ Text("Show the reply", style = MaterialTheme.typography.bodyMedium)+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .selectableGroup()+ .testTag("settings_task_finished_preview")+ ) {+ CompletionPreview.entries.forEach { preview ->+ CompletionPreviewRow(+ preview = preview,+ selected = taskPreview == preview,+ onSelect = {+ taskPreview = preview+ onSave { s -> s.copy(chatCompletionPreview = preview) }+ }+ )+ }+ }+ if (!canPost) {+ Text(+ "Notifications are blocked for Gotcha, so none will be shown.",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error+ )+ TextButton(+ onClick = {+ localContext.startActivity(+ Intent(AndroidSettings.ACTION_APP_NOTIFICATION_SETTINGS)+ .putExtra(AndroidSettings.EXTRA_APP_PACKAGE, localContext.packageName)+ )+ }+ ) { Text("Open notification settings") }+ }+ }+Spacer(Modifier.height(16.dp))Text("Server messages",@@ -153,6 +229,37 @@ fun NotificationsScreen(}}+/** One selectable row of the "Show the reply" group. */+@Composable+private fun CompletionPreviewRow(+ preview: CompletionPreview,+ selected: Boolean,+ onSelect: () -> Unit+) {+ val (label, summary) = when (preview) {+ CompletionPreview.NONE -> "Don't show it" to "Only the chat's name and whether the task finished."+ CompletionPreview.SHORT -> "A short preview" to "The first line or two of the reply."+ CompletionPreview.FULL -> "The whole reply" to "Expand the notification to read all of it."+ }+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .selectable(selected = selected, role = Role.RadioButton, onClick = onSelect)+ .testTag("settings_task_finished_preview_${preview.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)+ )+ }+}+private fun formatRelative(epochMillis: Long): String {if (epochMillis <= 0L) return "never"val deltaMin = (System.currentTimeMillis() - epochMillis) / 60_000Ldiff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.ktindex b2d7953..12e2f22 100644--- a/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.kt+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelBackgroundHintTest.kt@@ -91,6 +91,10 @@ class ChatViewModelBackgroundHintTest {backgroundHintText(vibrate = true, chime = true))assertEquals("$base.", backgroundHintText(vibrate = false, chime = false))+ assertEquals(+ "$base — Gotcha will notify you when the task is finished.",+ backgroundHintText(vibrate = true, chime = true, notify = true)+ )}@Testdiff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.ktnew file mode 100644index 0000000..c6a2392--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelCompletionNotificationTest.kt@@ -0,0 +1,168 @@+package com.gotcha.agent++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.LlmProvider+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import com.gotcha.notifications.ChatCompletionNotifier+import com.gotcha.testsupport.FakeAndroidKeyStore+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+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+import org.robolectric.shadows.ShadowLooper++/**+ * Task-finished notifications from [ChatViewModel] (issue #97): one per run that+ * ends while Gotcha is in the background, none in the foreground or when the+ * setting is off. The LLM base URL refuses connections, so every run here ends+ * quickly as a failure.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ChatViewModelCompletionNotificationTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private val manager = application.getSystemService(NotificationManager::class.java)+ private lateinit var settingsRepository: SettingsRepository+ private lateinit var viewModel: ChatViewModel++ private fun start(enabled: Boolean = true, granted: Boolean = true) {+ FakeAndroidKeyStore.setUp()+ if (granted) shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)+ settingsRepository = SettingsRepository(application)+ settingsRepository.save(+ Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ apiKey = "test-key",+ baseUrl = "http://127.0.0.1:1/v1",+ chatCompletionNotificationsEnabled = enabled+ )+ )+ viewModel = ChatViewModel(application)+ ShadowLooper.idleMainLooper()+ }++ @Before+ fun clearTray() {+ manager.cancelAll()+ }++ private fun waitForRunToFinish() {+ val deadline = System.currentTimeMillis() + 5_000+ ShadowLooper.idleMainLooper()+ while (System.currentTimeMillis() < deadline && viewModel.uiState.value.isBusy) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(10)+ }+ ShadowLooper.idleMainLooper()+ }++ private fun posted() = shadowOf(manager).allNotifications++ @Test+ fun `a run that ends in the background posts one notification for that chat`() {+ start()+ viewModel.sendMessage("Hello")+ viewModel.setForeground(false)+ waitForRunToFinish()++ val notification = posted().single()+ assertTrue(notification.extras.getString(NotificationCompat.EXTRA_TITLE)!!.startsWith("Failed: "))+ val tap = shadowOf(notification.contentIntent).savedIntent+ assertEquals(+ viewModel.uiState.value.activeSessionId,+ tap.getStringExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID)+ )+ }++ @Test+ fun `a run that ends in the foreground posts nothing`() {+ start()+ viewModel.sendMessage("Hello")+ waitForRunToFinish()++ assertTrue(posted().isEmpty())+ }++ @Test+ fun `nothing is posted when the setting is off`() {+ start(enabled = false)+ viewModel.sendMessage("Hello")+ viewModel.setForeground(false)+ waitForRunToFinish()++ assertTrue(posted().isEmpty())+ }++ @Test+ fun `returning to the chat clears its notification`() {+ start()+ viewModel.sendMessage("Hello")+ viewModel.setForeground(false)+ waitForRunToFinish()+ assertEquals(1, posted().size)++ viewModel.setForeground(true)++ assertTrue(posted().isEmpty())+ }++ @Test+ fun `hint promises a notification when one can be posted`() {+ start()+ viewModel.sendMessage("Hello")+ ShadowLooper.idleMainLooper()++ assertEquals(+ backgroundHintText(vibrate = true, chime = false, notify = true),+ viewModel.uiState.value.backgroundHint+ )+ waitForRunToFinish()+ }++ @Test+ fun `permission is asked once, on the first request, and never blocks the run`() {+ start(granted = false)+ viewModel.sendMessage("First")+ ShadowLooper.idleMainLooper()+ assertTrue(viewModel.uiState.value.askNotificationPermission)+ waitForRunToFinish()+ // The run finished while the ask was still unanswered.+ assertFalse(viewModel.uiState.value.isBusy)++ viewModel.onNotificationPermissionResult(false)+ viewModel.sendMessage("Second")+ ShadowLooper.idleMainLooper()++ assertFalse(viewModel.uiState.value.askNotificationPermission)+ waitForRunToFinish()+ }++ @Test+ fun `granting mid-run upgrades the hint`() {+ start(granted = false)+ viewModel.sendMessage("Hello")+ ShadowLooper.idleMainLooper()+ assertEquals(backgroundHintText(vibrate = true, chime = false), viewModel.uiState.value.backgroundHint)++ shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)+ viewModel.onNotificationPermissionResult(true)++ assertEquals(+ backgroundHintText(vibrate = true, chime = false, notify = true),+ viewModel.uiState.value.backgroundHint+ )+ assertFalse(viewModel.uiState.value.askNotificationPermission)+ waitForRunToFinish()+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/ChatCompletionNotifierTest.kt b/app/src/test/java/com/gotcha/notifications/ChatCompletionNotifierTest.ktnew file mode 100644index 0000000..3284c24--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/ChatCompletionNotifierTest.kt@@ -0,0 +1,115 @@+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ChatCompletionNotifierTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private val manager = application.getSystemService(NotificationManager::class.java)+ private val notifier = ChatCompletionNotifier(application)++ @Before+ fun setUp() {+ shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)+ }++ private fun posted() = shadowOf(manager).allNotifications++ @Test+ fun `posts on its own channel with a tap that opens the chat`() {+ assertTrue(+ notifier.notify("s1", "Trip to Japan", RunOutcome.DONE, "Here is the plan.", CompletionPreview.SHORT)+ )++ val notification = posted().single()+ assertEquals(ChatCompletionNotifier.CHANNEL_ID, notification.channelId)+ assertEquals("Done: Trip to Japan", notification.extras.getString(NotificationCompat.EXTRA_TITLE))+ assertEquals("Here is the plan.", notification.extras.getCharSequence(NotificationCompat.EXTRA_TEXT).toString())+ 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 `a later run in the same chat replaces the earlier notification`() {+ notifier.notify("s1", "Chat", RunOutcome.DONE, "first", CompletionPreview.SHORT)+ notifier.notify("s1", "Chat", RunOutcome.FAILED, "second", CompletionPreview.SHORT)+ notifier.notify("s2", "Other", RunOutcome.DONE, "other", CompletionPreview.SHORT)++ assertEquals(2, posted().size)+ notifier.cancel("s1")+ assertEquals("Done: Other", posted().single().extras.getString(NotificationCompat.EXTRA_TITLE))+ }++ @Test+ fun `nothing is posted without permission`() {+ shadowOf(application).denyPermissions(Manifest.permission.POST_NOTIFICATIONS)++ assertFalse(notifier.canPost())+ assertFalse(notifier.notify("s1", "Chat", RunOutcome.DONE, "reply", CompletionPreview.SHORT))+ assertTrue(posted().isEmpty())+ }++ @Test+ fun `title says how the run ended`() {+ assertEquals("Done: Chat", ChatCompletionNotifier.notificationTitle("Chat", RunOutcome.DONE))+ assertEquals("Failed: Chat", ChatCompletionNotifier.notificationTitle("Chat", RunOutcome.FAILED))+ assertEquals("Stopped: Chat", ChatCompletionNotifier.notificationTitle("Chat", RunOutcome.STOPPED))+ assertEquals("Done: Chat", ChatCompletionNotifier.notificationTitle(" ", RunOutcome.DONE))+ }++ @Test+ fun `preview follows the setting and drops markdown`() {+ val reply = "## Plan\n\n- **Tokyo** first\n- `Kyoto` next"++ assertNull(ChatCompletionNotifier.previewText(reply, CompletionPreview.NONE))+ assertEquals(+ "Plan • Tokyo first • Kyoto next",+ ChatCompletionNotifier.previewText(reply, CompletionPreview.SHORT)+ )+ assertEquals(+ "Plan\n• Tokyo first\n• Kyoto next",+ ChatCompletionNotifier.previewText(reply, CompletionPreview.FULL)+ )+ assertNull(ChatCompletionNotifier.previewText(" ", CompletionPreview.SHORT))+ assertEquals(+ "Summary: One",+ ChatCompletionNotifier.previewText("Summary:\n\n---\n\nOne\n***", CompletionPreview.SHORT)+ )+ }++ @Test+ fun `short preview is cut to one line with an ellipsis`() {+ val short = ChatCompletionNotifier.previewText("word ".repeat(100), CompletionPreview.SHORT)!!++ assertTrue(short.endsWith("…"))+ assertTrue(short.length <= 141)+ }++ @Test+ fun `hidden preview falls back to a line about the outcome`() {+ notifier.notify("s1", "Chat", RunOutcome.FAILED, "secret reply", CompletionPreview.NONE)++ val text = posted().single().extras.getCharSequence(NotificationCompat.EXTRA_TEXT).toString()+ assertEquals(ChatCompletionNotifier.defaultBody(RunOutcome.FAILED), text)+ }+}