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): behaviour-based reminders and an in-app inbox (#100)
Durganshu74e729fdf965
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 28c9a6f..f4fe73b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,24 @@ All notable changes to Gotcha are documented here.## [Unreleased]### Added+- **Gotcha's own notifications, and a list of them** (#100). Gotcha now works+ out from your chats, on the phone, when a notification would actually help,+ and nothing about how you use it is uploaded to decide. It reminds you about a+ chat left unfinished (a task that failed or was stopped, or a question you+ didn't answer, a few hours on); suggests a request you make regularly once+ it's due again, opening a new chat with it ready to send; and nudges you after+ a quiet spell (four days by default), offering your last chat back. A new+ "Gotcha notifications" section in Settings → Notifications turns each of these+ and the daily tip on or off, sets the quiet spell, quiet hours (22:00–08:00 by+ default), and how many a day (two by default), and whether notifications may+ name chats. The same occasion is never notified twice, one of a kind a day at+ most, and the lock screen never shows the chat. A bell on the chat screen opens+ the last 30 days of notifications — reminders, tips, finished tasks and+ messages from Samosa AI — each opening where its notification did, and the+ history can be cleared. A chat's new ⋮ menu (which also holds Export and the+ share card) keeps it out of notifications altogether; Doctor chats start that+ way. Task-finished notifications for such chats, or with naming off, say only+ that a task finished.- **Daily tips** (#101). Once a day, at 10:00 by default, Gotcha sends anotification suggesting one thing to try: reading your screen, catching upon notifications, texting someone, planning the day. Tapping it opens a newdiff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 527a68f..3f32267 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -250,17 +250,21 @@</intent-filter></receiver>- <!-- Daily tip (issue #101). The alarm receiver posts the tip; it is not exported,- as only Gotcha's own PendingIntent fires it. -->+ <!-- Gotcha's own proactive notifications (issues #100, #101). The daily tip alarm and+ the periodic reminder check post them; neither is exported, as only Gotcha's own+ PendingIntents fire them. --><receiverandroid:name=".notifications.DailyTipAlarmReceiver"android:exported="false" />+ <receiver+ android:name=".notifications.ReminderCheckReceiver"+ android:exported="false" />- <!-- Re-arms the daily tip alarm, which a reboot, an app update or a clock change- would otherwise lose or misplace. All four broadcasts are protected and exempt- from the implicit-broadcast limits. -->+ <!-- Re-arms those alarms, which a reboot, an app update or a clock change would+ otherwise lose or misplace. All four broadcasts are protected and exempt from the+ implicit-broadcast limits. --><receiver- android:name=".notifications.DailyTipReceiver"+ android:name=".notifications.NotificationRescheduleReceiver"android:exported="true"><intent-filter><action android:name="android.intent.action.BOOT_COMPLETED" />diff --git a/app/src/main/assets/app/about-gotcha.md b/app/src/main/assets/app/about-gotcha.mdindex 81f2d21..320af88 100644--- a/app/src/main/assets/app/about-gotcha.md+++ b/app/src/main/assets/app/about-gotcha.md@@ -75,7 +75,7 @@ Everything below is reached from **Settings** in the navigation drawer.| Proactive Assistance | Master switch for proactive offers, OTP/code detection, auto-copy OTP, and what may be scanned (screen content, notifications, clipboard) || Assistive Ball and Wake Word | The floating ball over other apps, hands-free voice calls, the "Hey Gotcha" wake word, when it listens, and detection sensitivity || Appearance | Theme |-| Notifications | Reply chime, vibration, and server messages |+| Notifications | Reply chime and vibration; the task-finished notification and its reply preview; Gotcha notifications (reminders about unfinished chats, routines that are due and quiet spells, the daily tip, quiet hours, a daily cap, whether chats may be named, clearing the history); and server messages. The bell on the chat screen opens the list of recent notifications, and a chat's ⋮ menu keeps that chat out of notifications || About | Samosa AI, other products, legal, contact || About > About Samosa AI | Mission, products, pricing, developers || About > Legal | Terms, disclaimer, data retention |diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex d48e273..d2482fb 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -50,15 +50,18 @@ import com.gotcha.data.computeFeedbackStatsimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClientimport com.gotcha.notifications.ChatCompletionNotifier-import com.gotcha.notifications.DAILY_TIPS-import com.gotcha.notifications.DailyTip-import com.gotcha.notifications.DailyTipNotifier-import com.gotcha.notifications.DailyTipScheduler+import com.gotcha.notifications.InboxEntry+import com.gotcha.notifications.LocalNotificationScheduler+import com.gotcha.notifications.LocalNotificationStore+import com.gotcha.notifications.LocalNotifier+import com.gotcha.notifications.NotificationCategoryimport com.gotcha.notifications.NotificationDispatcherimport com.gotcha.notifications.NotificationPayload+import com.gotcha.notifications.NotificationTargetimport com.gotcha.notifications.ServerMessagesimport com.gotcha.service.AssistiveBallServiceimport com.gotcha.service.GotchaDeviceAdminReceiver+import com.gotcha.tools.AgentModeimport com.gotcha.tools.ScreenPerceptionimport com.gotcha.tools.TermuxToolimport com.gotcha.tools.ToolResult@@ -66,6 +69,7 @@ import com.gotcha.ui.AppDrawerContentimport com.gotcha.ui.ChatScreenimport com.gotcha.ui.ConnectorsScreenimport com.gotcha.ui.FeedbackSheet+import com.gotcha.ui.InboxScreenimport com.gotcha.ui.NotificationDetailDialogimport com.gotcha.ui.PermissionAskimport com.gotcha.ui.PermissionBlockedDialog@@ -92,7 +96,7 @@ import kotlinx.coroutines.withContextimport kotlinx.serialization.json.JsonPrimitiveimport android.provider.Settings as AndroidSettings-enum class Route { HOME, SETTINGS, CONNECTORS }+enum class Route { HOME, SETTINGS, CONNECTORS, INBOX }/*** Where the user is, in the tour's vocabulary. Null means somewhere the tour has@@ -139,8 +143,15 @@ class MainActivity : ComponentActivity() {/** Chat to open, set when a task-finished notification is tapped (issue #97). */private var openSessionRequested by mutableStateOf<String?>(null)- /** Tip whose prompt a new chat should open with, set when a daily tip is tapped (issue #101). */- private var openTipRequested by mutableStateOf<DailyTip?>(null)+ /**+ * Prompt and mode a new chat should open with, set when a notification+ * offering one is tapped: a daily tip (issue #101) or a routine (#100).+ */+ private var openDraftRequested by mutableStateOf<NotificationTarget.Draft?>(null)++ /** Gotcha's own notification history: the inbox, its unread count, per-chat privacy (issue #100). */+ private val localNotificationStore by lazy { LocalNotificationStore(applicationContext) }+ private var inboxUnread by mutableStateOf(0)/** Set when brought to front by the assistive ball (Operator-origin chats). */private var openedFromBall by mutableStateOf(false)@@ -296,10 +307,10 @@ class MainActivity : ComponentActivity() {openedFromBall = intent?.getBooleanExtra(EXTRA_FROM_ASSISTIVE_BALL, false) == truehandleNotificationIntent(intent)- // A fresh install has had no boot or update broadcast yet, so the daily- // tip alarm is armed here too. Re-arming is idempotent.+ // A fresh install has had no boot or update broadcast yet, so the+ // notification alarms are armed here too. Re-arming is idempotent.lifecycleScope.launch(Dispatchers.IO) {- runCatching { DailyTipScheduler.schedule(applicationContext) }+ runCatching { LocalNotificationScheduler.scheduleAll(applicationContext) }}// Tools report what they need the moment they need it. A special-access@@ -526,11 +537,20 @@ class MainActivity : ComponentActivity() {// Consumed: a later recreation must not reopen this chat over the user's choice.intent.removeExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID)}- intent?.getStringExtra(DailyTipNotifier.EXTRA_DAILY_TIP_ID)?.let { id ->- // An id from an older version that no longer exists just opens the app.- openTipRequested = DAILY_TIPS.firstOrNull { it.id == id }+ intent?.getStringExtra(LocalNotifier.EXTRA_DRAFT_PROMPT)?.let { prompt ->+ val mode = runCatching {+ AgentMode.valueOf(intent.getStringExtra(LocalNotifier.EXTRA_DRAFT_MODE).orEmpty())+ }.getOrDefault(AgentMode.MONITOR)+ openDraftRequested = NotificationTarget.Draft(prompt, mode)// Consumed, as above: a recreation must not open another chat.- intent.removeExtra(DailyTipNotifier.EXTRA_DAILY_TIP_ID)+ intent.removeExtra(LocalNotifier.EXTRA_DRAFT_PROMPT)+ }+ intent?.getStringExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID)?.let { entryId ->+ intent.removeExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID)+ lifecycleScope.launch(Dispatchers.IO) {+ localNotificationStore.markRead(entryId)+ inboxUnread = localNotificationStore.unreadCount()+ }}val title = intent?.getStringExtra(NotificationDispatcher.EXTRA_NOTIFICATION_TITLE)val body = intent?.getStringExtra(NotificationDispatcher.EXTRA_NOTIFICATION_BODY)@@ -557,8 +577,31 @@ class MainActivity : ComponentActivity() {com.gotcha.data.settingsChangeNotifier(this).registerOnSharedPreferenceChangeListener(appearanceListener)}+ /**+ * Goes where an inbox entry points (issue #100): its chat, a new chat with+ * its prompt drafted, or home. A server message reopens in the same dialog+ * its system notification opens.+ */+ private fun openInboxEntry(entry: InboxEntry, goTo: (Route) -> Unit) {+ goTo(Route.HOME)+ if (entry.categoryOrNull == NotificationCategory.SERVER) {+ notificationPayload = NotificationPayload(id = -1, title = entry.title, body = entry.body, url = entry.url)+ return+ }+ when (val target = entry.target) {+ is NotificationTarget.Chat -> openSessionRequested = target.sessionId+ is NotificationTarget.Draft -> openDraftRequested = target+ NotificationTarget.Home -> Unit+ }+ }+override fun onResume() {super.onResume()+ // What the inactivity reminder counts from, and the inbox badge (issue #100).+ lifecycleScope.launch(Dispatchers.IO) {+ localNotificationStore.setLastOpenedAt(System.currentTimeMillis())+ inboxUnread = localNotificationStore.unreadCount()+ }// Server-driven notifications — fetch fresh if the cached value is// older than 6h. The dispatcher itself no-ops when the user has the// toggle off, so calling it on every resume is safe.@@ -732,11 +775,11 @@ class MainActivity : ComponentActivity() {}// A tapped daily tip: a new chat, in the tip's mode, with its prompt drafted.- LaunchedEffect(openTipRequested) {- openTipRequested?.let { tip ->+ LaunchedEffect(openDraftRequested) {+ openDraftRequested?.let { draft ->currentRoute = Route.HOME- chatViewModel.startChatFromTip(tip.prompt, tip.agent)- openTipRequested = null+ chatViewModel.startChatFromTip(draft.prompt, draft.mode)+ openDraftRequested = null}}@@ -927,6 +970,19 @@ class MainActivity : ComponentActivity() {onPageChange = { settingsPage = it })}+ Route.INBOX -> {+ BackHandler { currentRoute = Route.HOME }+ InboxScreen(+ load = { localNotificationStore.entries() },+ onOpened = {+ localNotificationStore.markAllRead()+ inboxUnread = 0+ },+ onClear = { localNotificationStore.clearHistory() },+ onOpenEntry = { entry -> openInboxEntry(entry) { currentRoute = it } },+ onBack = { currentRoute = Route.HOME }+ )+ }Route.CONNECTORS -> {// refreshSettings() on the way out, like every other route: the// enable/disable toggles write disabledConnectors, and the agent@@ -944,6 +1000,13 @@ class MainActivity : ComponentActivity() {BackHandler(enabled = state.messages.isNotEmpty() && !state.isBusy) {chatViewModel.openSession(null)}+ // Bumped when the user flips the switch, so the menu re-reads it.+ var privacyVersion by remember { mutableStateOf(0) }+ val chatKeptOut = remember(state.activeSessionId, state.activePersonaId, privacyVersion) {+ state.activeSessionId+ ?.let { chatViewModel.isChatKeptOutOfNotifications(it, state.activePersonaId) }+ ?: false+ }ChatScreen(state = state,onSend = { text, attachments, isVoiceInput ->@@ -961,6 +1024,13 @@ class MainActivity : ComponentActivity() {onSwitchAgent = chatViewModel::switchAgent,onSetAgent = chatViewModel::setAgent,onSetPersona = chatViewModel::setPersona,+ unreadNotifications = inboxUnread,+ onOpenInbox = { currentRoute = Route.INBOX },+ chatKeptOutOfNotifications = chatKeptOut,+ onSetChatKeptOutOfNotifications = { keptOut ->+ state.activeSessionId?.let { chatViewModel.setChatKeptOutOfNotifications(it, keptOut) }+ privacyVersion+++ },onComposerDraftConsumed = chatViewModel::consumeComposerDraft,onSpeak = chatViewModel::speak,onStopSpeaking = chatViewModel::stopSpeaking,diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex 4c59785..69992aa 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -30,6 +30,9 @@ import com.gotcha.marketing.PosterRendererimport com.gotcha.marketing.PosterStatsBuilderimport com.gotcha.marketing.ShareCardClientimport com.gotcha.notifications.ChatCompletionNotifier+import com.gotcha.notifications.LocalNotificationStore+import com.gotcha.notifications.NotificationCategory+import com.gotcha.notifications.NotificationTargetimport com.gotcha.notifications.RunOutcomeimport com.gotcha.tools.AgentModeimport com.gotcha.tools.DocumentError@@ -241,6 +244,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Aprivate val historyRepository = ChatHistoryRepository(application)private val confirmationOverlay = ConfirmationOverlay(application)private val completionNotifier = ChatCompletionNotifier(application)+ private val localNotificationStore = LocalNotificationStore(application)private var settings: Settings = Settings()private var client: LLMClient? = null@@ -790,15 +794,33 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A*/private fun notifyRunFinished(sessionId: String, outcome: RunOutcome) {if (appInForeground || !settings.chatCompletionNotificationsEnabled) return+ if (!completionNotifier.canPost()) returnval reply = engineTranscript.lastOrNull {it.kind == MessageKind.ASSISTANT || it.kind == MessageKind.ERROR}?.text+ // Issue #100: a chat kept out of notifications, or chats not to be named+ // at all, get a notification that says only that a task finished.+ val named = settings.notificationsMentionChats &&+ !localNotificationStore.isChatSensitive(sessionId, agentEngine.sessionPersonaId)+ val title = if (named) {+ ChatCompletionNotifier.notificationTitle(agentEngine.currentTitle(), outcome)+ } else {+ ChatCompletionNotifier.anonymousTitle(outcome)+ }+ val entryId = localNotificationStore.addEntry(+ category = NotificationCategory.TASK_FINISHED,+ title = title,+ body = ChatCompletionNotifier.defaultBody(outcome),+ target = NotificationTarget.Chat(sessionId)+ )completionNotifier.notify(sessionId = sessionId,chatTitle = agentEngine.currentTitle(),outcome = outcome,reply = reply,- preview = settings.chatCompletionPreview+ preview = settings.chatCompletionPreview,+ named = named,+ inboxEntryId = entryId)}@@ -859,6 +881,19 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A}}+ /**+ * Whether chat [sessionId] is kept out of notifications (issue #100): the+ * user's own choice, else true for a Doctor-persona chat.+ */+ fun isChatKeptOutOfNotifications(sessionId: String, personaId: String?): Boolean =+ localNotificationStore.isChatSensitive(sessionId, personaId)++ fun setChatKeptOutOfNotifications(sessionId: String, keptOut: Boolean) {+ localNotificationStore.setChatKeptOut(sessionId, keptOut)+ // A notification already in the tray may name the chat.+ if (keptOut) completionNotifier.cancel(sessionId)+ }+/** The composer has taken [ChatUiState.composerDraft]. */fun consumeComposerDraft() {_uiState.update { it.copy(composerDraft = null) }@@ -1629,6 +1664,7 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), Acom.gotcha.data.GotchaStorage.archiveChatDir(id)}historyRepository.deleteSession(id)+ localNotificationStore.forgetChat(id)if (agentEngine.sessionId == id) {clearChat()}diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex edd72e3..f4dcf12 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -52,6 +52,16 @@ const val DEFAULT_MAX_CONTEXT_TOKENS = 256_000/** Daily tip time for a fresh install: 10:00, in minutes after midnight. */const val DEFAULT_DAILY_TIP_MINUTE = 10 * 60+/** Days without opening Gotcha before the inactivity reminder, as the issue (#100) suggests. */+const val DEFAULT_INACTIVITY_DAYS = 4++/** Quiet hours for a fresh install: 22:00 to 08:00. */+const val DEFAULT_QUIET_START_MINUTE = 22 * 60+const val DEFAULT_QUIET_END_MINUTE = 8 * 60++/** Proactive notifications a day: room for the tip and one reminder. */+const val DEFAULT_MAX_LOCAL_NOTIFICATIONS_PER_DAY = 2+/*** The budget before [DEFAULT_MAX_CONTEXT_TOKENS] was raised. A stored copy of* exactly this value is lifted once by [SettingsRepository.resolvedMaxContextTokens];@@ -143,6 +153,30 @@ data class Settings(val dailyTipsEnabled: Boolean = true,/** When the daily tip arrives, as minutes after local midnight. */val dailyTipMinuteOfDay: Int = DEFAULT_DAILY_TIP_MINUTE,+ /**+ * Master switch for Gotcha's own proactive notifications (issue #100):+ * reminders about unfinished chats, routines and quiet spells, and the daily+ * tip. Task-finished notifications and server messages have their own.+ */+ val localNotificationsEnabled: Boolean = true,+ /** Remind the user after [inactivityDays] without opening Gotcha. */+ val inactivityRemindersEnabled: Boolean = true,+ val inactivityDays: Int = DEFAULT_INACTIVITY_DAYS,+ /** Remind about a chat whose task failed, was stopped or ended on a question. */+ val unfinishedChatRemindersEnabled: Boolean = true,+ /** Suggest a request the user makes regularly when it is due again. */+ val routineSuggestionsEnabled: Boolean = true,+ /** No proactive notification between these times (minutes after midnight). */+ val quietHoursEnabled: Boolean = true,+ val quietHoursStartMinute: Int = DEFAULT_QUIET_START_MINUTE,+ val quietHoursEndMinute: Int = DEFAULT_QUIET_END_MINUTE,+ /** At most this many proactive notifications a day. */+ val maxLocalNotificationsPerDay: Int = DEFAULT_MAX_LOCAL_NOTIFICATIONS_PER_DAY,+ /**+ * Whether notifications may name chats and requests. Off, they stay generic.+ * Chats kept out of notifications are never named either way.+ */+ val notificationsMentionChats: Boolean = true,val assistiveBallEnabled: Boolean = false,val wakeWordEnabled: Boolean = false,val wakeWordSensitivity: Float = 0.75f,@@ -536,6 +570,16 @@ class SettingsRepository(context: Context) : SettingsStore {}.getOrDefault(CompletionPreview.SHORT),dailyTipsEnabled = prefs.getBoolean(KEY_DAILY_TIPS, true),dailyTipMinuteOfDay = prefs.getInt(KEY_DAILY_TIP_MINUTE, DEFAULT_DAILY_TIP_MINUTE),+ localNotificationsEnabled = prefs.getBoolean(KEY_LOCAL_NOTIFICATIONS, true),+ inactivityRemindersEnabled = prefs.getBoolean(KEY_INACTIVITY_REMINDERS, true),+ inactivityDays = prefs.getInt(KEY_INACTIVITY_DAYS, DEFAULT_INACTIVITY_DAYS),+ unfinishedChatRemindersEnabled = prefs.getBoolean(KEY_UNFINISHED_REMINDERS, true),+ routineSuggestionsEnabled = prefs.getBoolean(KEY_ROUTINE_SUGGESTIONS, true),+ quietHoursEnabled = prefs.getBoolean(KEY_QUIET_HOURS, true),+ quietHoursStartMinute = prefs.getInt(KEY_QUIET_START, DEFAULT_QUIET_START_MINUTE),+ quietHoursEndMinute = prefs.getInt(KEY_QUIET_END, DEFAULT_QUIET_END_MINUTE),+ maxLocalNotificationsPerDay = prefs.getInt(KEY_MAX_LOCAL_PER_DAY, DEFAULT_MAX_LOCAL_NOTIFICATIONS_PER_DAY),+ notificationsMentionChats = prefs.getBoolean(KEY_MENTION_CHATS, true),assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false),wakeWordEnabled = prefs.getBoolean(KEY_WAKE_WORD_ENABLED, false),wakeWordSensitivity = prefs.getFloat(KEY_WAKE_WORD_SENSITIVITY, 0.75f),@@ -615,6 +659,16 @@ class SettingsRepository(context: Context) : SettingsStore {.putString(KEY_CHAT_COMPLETION_PREVIEW, settings.chatCompletionPreview.name).putBoolean(KEY_DAILY_TIPS, settings.dailyTipsEnabled).putInt(KEY_DAILY_TIP_MINUTE, settings.dailyTipMinuteOfDay)+ .putBoolean(KEY_LOCAL_NOTIFICATIONS, settings.localNotificationsEnabled)+ .putBoolean(KEY_INACTIVITY_REMINDERS, settings.inactivityRemindersEnabled)+ .putInt(KEY_INACTIVITY_DAYS, settings.inactivityDays)+ .putBoolean(KEY_UNFINISHED_REMINDERS, settings.unfinishedChatRemindersEnabled)+ .putBoolean(KEY_ROUTINE_SUGGESTIONS, settings.routineSuggestionsEnabled)+ .putBoolean(KEY_QUIET_HOURS, settings.quietHoursEnabled)+ .putInt(KEY_QUIET_START, settings.quietHoursStartMinute)+ .putInt(KEY_QUIET_END, settings.quietHoursEndMinute)+ .putInt(KEY_MAX_LOCAL_PER_DAY, settings.maxLocalNotificationsPerDay)+ .putBoolean(KEY_MENTION_CHATS, settings.notificationsMentionChats).putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled).putBoolean(KEY_WAKE_WORD_ENABLED, settings.wakeWordEnabled).putFloat(KEY_WAKE_WORD_SENSITIVITY, settings.wakeWordSensitivity)@@ -732,6 +786,16 @@ class SettingsRepository(context: Context) : SettingsStore {const val KEY_CHAT_COMPLETION_PREVIEW = "chat_completion_preview"const val KEY_DAILY_TIPS = "daily_tips_enabled"const val KEY_DAILY_TIP_MINUTE = "daily_tip_minute_of_day"+ const val KEY_LOCAL_NOTIFICATIONS = "local_notifications_enabled"+ const val KEY_INACTIVITY_REMINDERS = "inactivity_reminders_enabled"+ const val KEY_INACTIVITY_DAYS = "inactivity_days"+ const val KEY_UNFINISHED_REMINDERS = "unfinished_chat_reminders_enabled"+ const val KEY_ROUTINE_SUGGESTIONS = "routine_suggestions_enabled"+ const val KEY_QUIET_HOURS = "quiet_hours_enabled"+ const val KEY_QUIET_START = "quiet_hours_start_minute"+ const val KEY_QUIET_END = "quiet_hours_end_minute"+ const val KEY_MAX_LOCAL_PER_DAY = "max_local_notifications_per_day"+ const val KEY_MENTION_CHATS = "notifications_mention_chats"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.ktindex 6267b5b..5c8f0aa 100644--- a/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt+++ b/app/src/main/java/com/gotcha/notifications/ChatCompletionNotifier.kt@@ -38,7 +38,10 @@ class ChatCompletionNotifier(private val context: Context) {/*** 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.+ * With [named] false — a chat kept out of notifications, or chats not to be+ * mentioned at all (issue #100) — neither the chat nor the reply appears.+ * [inboxEntryId] is the inbox entry a tap marks read. Returns false when+ * nothing was posted.*/@Suppress("MissingPermission") // canPost() checks it.fun notify(@@ -46,13 +49,16 @@ class ChatCompletionNotifier(private val context: Context) {chatTitle: String,outcome: RunOutcome,reply: String?,- preview: CompletionPreview+ preview: CompletionPreview,+ named: Boolean = true,+ inboxEntryId: String? = null): Boolean {if (!canPost()) return falseensureChannel()val notifyId = notificationId(sessionId)- val title = notificationTitle(chatTitle, outcome)- val body = previewText(reply, preview) ?: defaultBody(outcome)+ val title = if (named) notificationTitle(chatTitle, outcome) else anonymousTitle(outcome)+ val shown = if (named) preview else CompletionPreview.NONE+ val body = previewText(reply, shown) ?: defaultBody(outcome)val builder = NotificationCompat.Builder(context, CHANNEL_ID).setSmallIcon(com.gotcha.R.drawable.ic_notification)@@ -68,8 +74,8 @@ class ChatCompletionNotifier(private val context: Context) {.build()).setAutoCancel(true)- .setContentIntent(openChatIntent(sessionId, notifyId))- if (preview == CompletionPreview.FULL) {+ .setContentIntent(openChatIntent(sessionId, notifyId, inboxEntryId))+ if (shown == CompletionPreview.FULL) {builder.setStyle(NotificationCompat.BigTextStyle().bigText(body))}NotificationManagerCompat.from(context).notify(notifyId, builder.build())@@ -81,10 +87,11 @@ class ChatCompletionNotifier(private val context: Context) {NotificationManagerCompat.from(context).cancel(notificationId(sessionId))}- private fun openChatIntent(sessionId: String, requestCode: Int): PendingIntent {+ private fun openChatIntent(sessionId: String, requestCode: Int, inboxEntryId: String?): PendingIntent {val intent = Intent(context, com.gotcha.MainActivity::class.java).apply {action = ACTION_OPEN_CHAT_SESSIONputExtra(EXTRA_OPEN_SESSION_ID, sessionId)+ inboxEntryId?.let { putExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID, it) }flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP}return PendingIntent.getActivity(@@ -124,6 +131,13 @@ class ChatCompletionNotifier(private val context: Context) {}}+ /** The title when the chat may not be named. */+ internal fun anonymousTitle(outcome: RunOutcome): String = when (outcome) {+ RunOutcome.DONE -> "Task finished"+ RunOutcome.FAILED -> "Task failed"+ RunOutcome.STOPPED -> "Task stopped"+ }+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."diff --git a/app/src/main/java/com/gotcha/notifications/DailyTipNotifier.kt b/app/src/main/java/com/gotcha/notifications/DailyTipNotifier.ktdeleted file mode 100644index ce3f01c..0000000--- a/app/src/main/java/com/gotcha/notifications/DailyTipNotifier.kt+++ /dev/null@@ -1,72 +0,0 @@-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--/**- * Posts the daily tip (issue #101): one use case a day, and a tap opens a new- * chat with its prompt in the composer. One slot, so a tip left unread is- * replaced by the next day's rather than stacking beside it.- *- * Its own low-importance channel, so tips can be silenced from Android's- * settings without touching task-finished or server notifications.- */-class DailyTipNotifier(private val context: Context) {-- /** True when Android will actually show what [notify] posts. */- fun canPost(): Boolean = ChatCompletionNotifier(context).canPost()-- @Suppress("MissingPermission") // canPost() checks it.- fun notify(tip: DailyTip): Boolean {- if (!canPost()) return false- ensureChannel()- val notification = NotificationCompat.Builder(context, CHANNEL_ID)- .setSmallIcon(com.gotcha.R.drawable.ic_notification)- .setContentTitle(tip.title)- .setContentText(tip.body)- .setStyle(NotificationCompat.BigTextStyle().bigText(tip.body))- .setCategory(NotificationCompat.CATEGORY_RECOMMENDATION)- .setPriority(NotificationCompat.PRIORITY_LOW)- .setAutoCancel(true)- .setContentIntent(openTipIntent(tip))- .build()- NotificationManagerCompat.from(context).notify(NOTIFICATION_ID, notification)- return true- }-- private fun openTipIntent(tip: DailyTip): PendingIntent {- val intent = Intent(context, com.gotcha.MainActivity::class.java).apply {- action = ACTION_OPEN_DAILY_TIP- putExtra(EXTRA_DAILY_TIP_ID, tip.id)- 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, "Daily tips", NotificationManager.IMPORTANCE_LOW).apply {- description = "One thing to try with Gotcha each day"- }- )- }-- companion object {- const val CHANNEL_ID = "gotcha_daily_tips"- const val ACTION_OPEN_DAILY_TIP = "com.gotcha.ACTION_OPEN_DAILY_TIP"- const val EXTRA_DAILY_TIP_ID = "com.gotcha.DAILY_TIP_ID"- private const val NOTIFICATION_ID = 0x7101- }-}diff --git a/app/src/main/java/com/gotcha/notifications/DailyTipScheduler.kt b/app/src/main/java/com/gotcha/notifications/DailyTipScheduler.ktdeleted file mode 100644index f022c92..0000000--- a/app/src/main/java/com/gotcha/notifications/DailyTipScheduler.kt+++ /dev/null@@ -1,136 +0,0 @@-package com.gotcha.notifications--import android.app.AlarmManager-import android.app.PendingIntent-import android.content.BroadcastReceiver-import android.content.Context-import android.content.Intent-import android.util.Log-import com.gotcha.data.ChatHistoryRepository-import com.gotcha.data.SettingsRepository-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.launch-import java.time.ZoneId--/**- * Keeps one inexact alarm armed for the next daily tip (issue #101).- *- * The alarm stays armed whether or not tips are on: [DailyTipAlarmReceiver] checks- * the setting when it fires, so switching tips on or off (from Settings or- * through the assistant) needs no rescheduling. Only a new time does.- */-object DailyTipScheduler {-- /** How late Android may deliver the tip; a window keeps it off the exact-alarm permission. */- private const val WINDOW_MS = 30L * 60L * 1000L-- /** Arms the alarm for the next [minuteOfDay], replacing any earlier one. */- fun schedule(context: Context, minuteOfDay: Int) {- val alarm = context.getSystemService(AlarmManager::class.java) ?: return- val at = nextDailyTipAt(System.currentTimeMillis(), minuteOfDay, ZoneId.systemDefault())- alarm.setWindow(AlarmManager.RTC_WAKEUP, at, WINDOW_MS, fireIntent(context))- }-- /** Arms the alarm for the stored time. Reads encrypted prefs, so call it off the main thread. */- fun schedule(context: Context) {- schedule(context, SettingsRepository(context).load().dailyTipMinuteOfDay)- }-- private fun fireIntent(context: Context): PendingIntent =- PendingIntent.getBroadcast(- context,- 0,- Intent(context, DailyTipAlarmReceiver::class.java),- PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE- )-}--/**- * Re-arms the alarm after a reboot, an app update or a clock change — none of- * which an alarm survives at the right time. Exported only because those- * broadcasts come from the system; it never posts a tip itself.- */-class DailyTipReceiver : BroadcastReceiver() {-- override fun onReceive(context: Context, intent: Intent) {- if (intent.action !in RESCHEDULE_ACTIONS) return- val app = context.applicationContext- val pending = goAsync()- CoroutineScope(Dispatchers.IO).launch {- try {- DailyTipScheduler.schedule(app)- } catch (e: Exception) {- Log.w(TAG, "Daily tip reschedule failed", e)- } finally {- pending.finish()- }- }- }-- private companion object {- const val TAG = "DailyTipReceiver"- val RESCHEDULE_ACTIONS = setOf(- Intent.ACTION_BOOT_COMPLETED,- Intent.ACTION_MY_PACKAGE_REPLACED,- Intent.ACTION_TIMEZONE_CHANGED,- Intent.ACTION_TIME_CHANGED- )- }-}--/** Posts the day's tip when the alarm fires, then arms tomorrow's. Not exported. */-class DailyTipAlarmReceiver : BroadcastReceiver() {-- override fun onReceive(context: Context, intent: Intent) {- val app = context.applicationContext- val pending = goAsync()- CoroutineScope(Dispatchers.IO).launch {- try {- // Re-arm first, so a failure below can't end the daily chain.- DailyTipScheduler.schedule(app)- postDailyTip(app)- } catch (e: Exception) {- Log.w(TAG, "Daily tip failed", e)- } finally {- pending.finish()- }- }- }-- private companion object {- const val TAG = "DailyTipAlarmReceiver"- }-}--private const val KEY_RECENT_TIPS = "daily_tip_recent_ids"--/**- * Posts today's tip unless tips are off, notifications are blocked or Gotcha- * has already been used today. Returns the tip posted, or null.- */-internal suspend fun postDailyTip(context: Context, now: Long = System.currentTimeMillis()): DailyTip? {- val repo = SettingsRepository(context)- if (!repo.load().dailyTipsEnabled) return null- val notifier = DailyTipNotifier(context)- if (!notifier.canPost()) return null-- // The chats on disk are the usage record: which tools have run, and when- // Gotcha was last used. Seeded samples are demos, not the user's own use.- val runs = ChatHistoryRepository(context).listSessions()- .filterNot { it.isSample }- .flatMap { it.runSummaries }- // Someone who has already used Gotcha today doesn't need a nudge.- if (usedToday(runs.maxOfOrNull { it.endedAt }, now, ZoneId.systemDefault())) return null-- val recent = repo.prefs.getString(KEY_RECENT_TIPS, null)- ?.split(',')?.filter { it.isNotBlank() }.orEmpty()- val usedTools = runs.flatMap { run -> run.toolCalls.map { it.name } }.toSet()- val tip = pickDailyTip(DAILY_TIPS, recent, usedTools) ?: return null- if (!notifier.notify(tip)) return null- repo.prefs.edit()- .putString(KEY_RECENT_TIPS, rememberShownTip(recent, tip.id).joinToString(","))- // commit, not apply: the process may go as soon as the receiver finishes.- .commit()- return tip-}diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.ktnew file mode 100644index 0000000..10cc76c--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt@@ -0,0 +1,198 @@+package com.gotcha.notifications++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.util.Log+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.SettingsRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import java.time.ZoneId++/**+ * Keeps the two alarms behind Gotcha's proactive notifications armed (issues+ * #100, #101): one at the daily tip time, and a check every few hours for+ * reminders. Both stay armed whatever the settings say, because the check reads+ * them when it runs, so switching things on or off needs no rescheduling. Only+ * a new tip time does.+ */+object LocalNotificationScheduler {++ /** How late Android may deliver the tip; a window keeps it off the exact-alarm permission. */+ private const val TIP_WINDOW_MS = 30L * 60L * 1000L++ /** How often reminders are checked for. Inexact, so Android batches it with other wake-ups. */+ private const val CHECK_INTERVAL_MS = 4L * HOUR_MS++ /** Arms the tip alarm for the next [tipMinuteOfDay], replacing any earlier one. */+ fun scheduleTip(context: Context, tipMinuteOfDay: Int) {+ val alarm = context.getSystemService(AlarmManager::class.java) ?: return+ val at = nextDailyTipAt(System.currentTimeMillis(), tipMinuteOfDay, ZoneId.systemDefault())+ alarm.setWindow(+ AlarmManager.RTC_WAKEUP,+ at,+ TIP_WINDOW_MS,+ broadcast(context, DailyTipAlarmReceiver::class.java)+ )+ }++ /** Arms both alarms from the stored settings. Reads encrypted prefs, so call it off the main thread. */+ fun scheduleAll(context: Context) {+ scheduleTip(context, SettingsRepository(context).load().dailyTipMinuteOfDay)+ val alarm = context.getSystemService(AlarmManager::class.java) ?: return+ alarm.setInexactRepeating(+ AlarmManager.RTC_WAKEUP,+ System.currentTimeMillis() + CHECK_INTERVAL_MS,+ CHECK_INTERVAL_MS,+ broadcast(context, ReminderCheckReceiver::class.java)+ )+ }++ private fun broadcast(context: Context, receiver: Class<out BroadcastReceiver>): PendingIntent =+ PendingIntent.getBroadcast(+ context,+ 0,+ Intent(context, receiver),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+}++/** Runs [block] off the main thread for a receiver, keeping it alive until done. */+private fun BroadcastReceiver.runAsync(tag: String, block: suspend () -> Unit) {+ val pending = goAsync()+ CoroutineScope(Dispatchers.IO).launch {+ try {+ block()+ } catch (e: Exception) {+ Log.w(tag, "Local notification work failed", e)+ } finally {+ pending.finish()+ }+ }+}++/**+ * Re-arms the alarms after a reboot, an app update or a clock change — none of+ * which an alarm survives at the right time. Exported only because those+ * broadcasts come from the system; it never posts anything itself.+ */+class NotificationRescheduleReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action !in RESCHEDULE_ACTIONS) return+ val app = context.applicationContext+ runAsync(TAG) { LocalNotificationScheduler.scheduleAll(app) }+ }++ private companion object {+ const val TAG = "NotificationReschedule"+ val RESCHEDULE_ACTIONS = setOf(+ Intent.ACTION_BOOT_COMPLETED,+ Intent.ACTION_MY_PACKAGE_REPLACED,+ Intent.ACTION_TIMEZONE_CHANGED,+ Intent.ACTION_TIME_CHANGED+ )+ }+}++/** The daily tip time: the best notification of the day, a reminder or else the tip. Not exported. */+class DailyTipAlarmReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ val app = context.applicationContext+ runAsync("DailyTipAlarm") {+ // Re-arm first, so a failure below can't end the daily chain.+ LocalNotificationScheduler.scheduleTip(app, SettingsRepository(app).load().dailyTipMinuteOfDay)+ runLocalNotificationCheck(app, includeTip = true)+ }+ }+}++/** The periodic reminder check. Not exported. */+class ReminderCheckReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ val app = context.applicationContext+ runAsync("ReminderCheck") { runLocalNotificationCheck(app, includeTip = false) }+ }+}++private const val KEY_RECENT_TIPS = "daily_tip_recent_ids"++/**+ * Decides whether to send a proactive notification now, and sends at most one.+ * Reminders come first (an unfinished chat, a routine that is due, a quiet+ * spell), then, at the tip time, the day's tip. Each has to pass the rules in+ * [blockReason]: the switches, quiet hours, deduplication, the cooldown and the+ * daily cap. Everything is decided on the phone from the chats already saved+ * there. Returns what was sent, or null.+ */+internal suspend fun runLocalNotificationCheck(+ context: Context,+ now: Long = System.currentTimeMillis(),+ includeTip: Boolean+): LocalCandidate? {+ val repo = SettingsRepository(context)+ val settings = repo.load()+ if (!settings.localNotificationsEnabled) return null+ val notifier = LocalNotifier(context)+ if (!notifier.canPost()) return null+ val store = LocalNotificationStore(context)+ val zone = ZoneId.systemDefault()++ // Seeded samples are demos, not the user's own use.+ val sessions = ChatHistoryRepository(context).listSessions().filterNot { it.isSample }+ val chats = sessions.map { session ->+ ChatDigest(+ id = session.id,+ title = session.title,+ sensitive = store.isChatSensitive(session.id, session.personaId),+ runs = session.runSummaries+ )+ }+ val lastOpenedAt = store.lastOpenedAt()++ var tip: DailyTip? = null+ val candidates = buildList {+ // Someone using Gotcha right now needs no reminder.+ if (now - lastOpenedAt >= RECENTLY_OPENED_MS) {+ addAll(+ behaviorCandidates(+ chats,+ lastOpenedAt,+ settings.inactivityDays,+ settings.notificationsMentionChats,+ now,+ zone+ )+ )+ }+ // Nor, on a day they have already used it, a tip.+ val lastRun = sessions.flatMap { it.runSummaries }.maxOfOrNull { it.endedAt }+ if (includeTip && !usedToday(lastRun, now, zone)) {+ val usedTools = sessions.flatMap { s -> s.runSummaries.flatMap { run -> run.toolCalls.map { it.name } } }+ tip = pickDailyTip(DAILY_TIPS, recentTips(repo), usedTools.toSet())+ tip?.let { add(tipCandidate(it, now, zone)) }+ }+ }++ val sent = store.sent()+ val chosen = candidates.firstOrNull { blockReason(it, settings, sent, now, zone) == null } ?: return null+ if (!notifier.post(chosen, store)) return null+ store.recordSent(chosen, now)+ val shownTip = tip+ if (chosen.category == NotificationCategory.DAILY_TIP && shownTip != null) {+ repo.prefs.edit()+ .putString(KEY_RECENT_TIPS, rememberShownTip(recentTips(repo), shownTip.id).joinToString(","))+ // commit, not apply: the process may go as soon as the receiver finishes.+ .commit()+ }+ return chosen+}++private fun recentTips(repo: SettingsRepository): List<String> =+ repo.prefs.getString(KEY_RECENT_TIPS, null)?.split(',')?.filter { it.isNotBlank() }.orEmpty()diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotificationStore.kt b/app/src/main/java/com/gotcha/notifications/LocalNotificationStore.ktnew file mode 100644index 0000000..555357f--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/LocalNotificationStore.kt@@ -0,0 +1,188 @@+package com.gotcha.notifications++import android.content.Context+import android.content.SharedPreferences+import com.gotcha.data.SafeEncryptedSharedPreferences+import com.gotcha.tools.AgentMode+import kotlinx.serialization.Serializable+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.json.Json+import java.util.UUID++/** One notification as the in-app inbox lists it (issue #100). */+@Serializable+data class InboxEntry(+ val id: String,+ val category: String,+ val title: String,+ val body: String,+ val postedAt: Long,+ val read: Boolean = false,+ /** Chat to open, for a [NotificationTarget.Chat]. */+ val sessionId: String? = null,+ /** Prompt and mode for a new chat, for a [NotificationTarget.Draft]. */+ val prompt: String? = null,+ val agentMode: String? = null,+ /** Link a server message carries. */+ val url: String? = null+) {+ val categoryOrNull: NotificationCategory?+ get() = NotificationCategory.entries.firstOrNull { it.name == category }++ val target: NotificationTarget+ get() = when {+ sessionId != null -> NotificationTarget.Chat(sessionId)+ prompt != null -> NotificationTarget.Draft(+ prompt,+ runCatching { AgentMode.valueOf(agentMode.orEmpty()) }.getOrDefault(AgentMode.MONITOR)+ )+ else -> NotificationTarget.Home+ }+}++/**+ * The on-device memory behind Gotcha's own notifications (issue #100): the+ * inbox, the log of proactive notifications that drives deduplication and the+ * daily cap, when Gotcha was last opened, and which chats are kept out of+ * notifications. Encrypted, like settings, because titles and prompts are+ * personal. Nothing here leaves the phone.+ */+class LocalNotificationStore internal constructor(private val prefs: SharedPreferences) {++ constructor(context: Context) : this(SafeEncryptedSharedPreferences.create(context, PREFS_FILE))++ private val json = Json { ignoreUnknownKeys = true }+ private val entrySerializer = ListSerializer(InboxEntry.serializer())+ private val sentSerializer = ListSerializer(SentRecord.serializer())++ // ---- inbox ----++ /** Newest first. */+ fun entries(): List<InboxEntry> = decode(KEY_ENTRIES, entrySerializer).sortedByDescending { it.postedAt }++ fun unreadCount(): Int = entries().count { !it.read }++ /** Adds a notification to the inbox and returns its id, which its tap intent carries. */+ fun addEntry(+ category: NotificationCategory,+ title: String,+ body: String,+ target: NotificationTarget,+ url: String? = null,+ now: Long = System.currentTimeMillis()+ ): String {+ val entry = InboxEntry(+ id = UUID.randomUUID().toString(),+ category = category.name,+ title = title,+ body = body,+ postedAt = now,+ sessionId = (target as? NotificationTarget.Chat)?.sessionId,+ prompt = (target as? NotificationTarget.Draft)?.prompt,+ agentMode = (target as? NotificationTarget.Draft)?.mode?.name,+ url = url+ )+ val kept = (listOf(entry) + entries())+ .filter { now - it.postedAt < KEEP_MS }+ .take(MAX_ENTRIES)+ encode(KEY_ENTRIES, entrySerializer, kept)+ return entry.id+ }++ fun markRead(id: String) {+ val all = entries()+ if (all.none { it.id == id && !it.read }) return+ encode(KEY_ENTRIES, entrySerializer, all.map { if (it.id == id) it.copy(read = true) else it })+ }++ fun markAllRead() {+ val all = entries()+ if (all.all { it.read }) return+ encode(KEY_ENTRIES, entrySerializer, all.map { it.copy(read = true) })+ }++ /**+ * Empties the inbox. The sent log is kept on purpose: clearing what you+ * have read must not bring back reminders that were already sent.+ */+ fun clearHistory() {+ prefs.edit().remove(KEY_ENTRIES).commit()+ }++ // ---- proactive notifications sent ----++ fun sent(): List<SentRecord> = decode(KEY_SENT, sentSerializer)++ fun recordSent(candidate: LocalCandidate, now: Long = System.currentTimeMillis()) {+ val kept = (sent() + SentRecord(candidate.dedupKey, candidate.category.name, now))+ .filter { now - it.at < KEEP_MS }+ encode(KEY_SENT, sentSerializer, kept)+ }++ // ---- when Gotcha was last opened ----++ fun lastOpenedAt(): Long = prefs.getLong(KEY_LAST_OPENED, 0L)++ fun setLastOpenedAt(value: Long) {+ prefs.edit().putLong(KEY_LAST_OPENED, value).apply()+ }++ // ---- chats kept out of notifications ----++ /** The user's own choice for [sessionId]: true kept out, false allowed, null not chosen. */+ fun chatChoice(sessionId: String): Boolean? = when (sessionId) {+ in stringSet(KEY_KEPT_OUT) -> true+ in stringSet(KEY_ALLOWED) -> false+ else -> null+ }++ fun isChatSensitive(sessionId: String, personaId: String?): Boolean =+ isChatSensitive(personaId, chatChoice(sessionId))++ fun setChatKeptOut(sessionId: String, keptOut: Boolean) {+ val out = stringSet(KEY_KEPT_OUT).toMutableSet()+ val allowed = stringSet(KEY_ALLOWED).toMutableSet()+ if (keptOut) {+ out += sessionId+ allowed -= sessionId+ } else {+ out -= sessionId+ allowed += sessionId+ }+ prefs.edit().putStringSet(KEY_KEPT_OUT, out).putStringSet(KEY_ALLOWED, allowed).apply()+ }++ /** Forgets a deleted chat's choice. */+ fun forgetChat(sessionId: String) {+ prefs.edit()+ .putStringSet(KEY_KEPT_OUT, stringSet(KEY_KEPT_OUT) - sessionId)+ .putStringSet(KEY_ALLOWED, stringSet(KEY_ALLOWED) - sessionId)+ .apply()+ }++ private fun stringSet(key: String): Set<String> = prefs.getStringSet(key, emptySet()).orEmpty().toSet()++ private fun <T> decode(key: String, serializer: kotlinx.serialization.KSerializer<List<T>>): List<T> =+ prefs.getString(key, null)+ ?.let { runCatching { json.decodeFromString(serializer, it) }.getOrNull() }+ .orEmpty()++ private fun <T> encode(key: String, serializer: kotlinx.serialization.KSerializer<List<T>>, value: List<T>) {+ // commit, not apply: receivers write here just before their process may go.+ prefs.edit().putString(key, json.encodeToString(serializer, value)).commit()+ }++ companion object {+ private const val PREFS_FILE = "gotcha_local_notifications"+ private const val KEY_ENTRIES = "inbox_entries"+ private const val KEY_SENT = "sent_records"+ private const val KEY_LAST_OPENED = "last_opened_at"+ private const val KEY_KEPT_OUT = "chats_kept_out"+ private const val KEY_ALLOWED = "chats_allowed"+ private const val KEEP_MS = 30L * DAY_MS+ private const val MAX_ENTRIES = 100++ /** Carried by every tap intent Gotcha posts, so opening one marks its inbox entry read. */+ const val EXTRA_INBOX_ENTRY_ID = "com.gotcha.INBOX_ENTRY_ID"+ }+}diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt b/app/src/main/java/com/gotcha/notifications/LocalNotifications.ktnew file mode 100644index 0000000..c6b7e12--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/LocalNotifications.kt@@ -0,0 +1,299 @@+package com.gotcha.notifications++import com.gotcha.data.RunSummary+import com.gotcha.data.Settings+import com.gotcha.tools.AgentMode+import java.time.Instant+import java.time.LocalDate+import java.time.ZoneId+import java.time.temporal.ChronoUnit++/**+ * What a notification in Gotcha is about (issue #100). The first four are+ * proactive: Gotcha decides to send them from on-device behaviour, so they share+ * the master switch, quiet hours and the daily cap. Task-finished and server+ * messages answer something already asked for or sent, and only appear here so+ * the inbox can list them.+ */+enum class NotificationCategory(val label: String, val proactive: Boolean) {+ UNFINISHED_CHAT("Unfinished chat", proactive = true),+ ROUTINE("Routine", proactive = true),+ INACTIVITY("Reminder", proactive = true),+ DAILY_TIP("Daily tip", proactive = true),+ TASK_FINISHED("Task finished", proactive = false),+ SERVER("From Samosa AI", proactive = false)+}++/** Where tapping a notification (or its inbox entry) goes. */+sealed interface NotificationTarget {+ /** Gotcha's home screen: there is no more specific place. */+ data object Home : NotificationTarget++ /** An existing chat. */+ data class Chat(val sessionId: String) : NotificationTarget++ /** A new chat in [mode], with [prompt] in the composer and not sent. */+ data class Draft(val prompt: String, val mode: AgentMode) : NotificationTarget+}++/**+ * A notification Gotcha could send. [dedupKey] names the occasion — this+ * failed run, this inactive spell, today's tip — so the same occasion is never+ * notified twice.+ */+data class LocalCandidate(+ val category: NotificationCategory,+ val dedupKey: String,+ val title: String,+ val body: String,+ val target: NotificationTarget+)++/** One chat, as the triggers see it. Sample chats are left out before this is built. */+data class ChatDigest(+ val id: String,+ val title: String,+ val sensitive: Boolean,+ val runs: List<RunSummary>+)++/** A proactive notification that was sent: the memory behind the daily cap and deduplication. */+data class SentRecord(val key: String, val category: String, val at: Long)++internal const val HOUR_MS = 3_600_000L+internal const val DAY_MS = 24L * HOUR_MS++/** A chat is only called unfinished once the user has had this long to come back to it. */+internal const val UNFINISHED_MIN_AGE_MS = 2L * HOUR_MS++/** ...and not once it is this old: by then it has been left, not forgotten. */+internal const val UNFINISHED_MAX_AGE_MS = 3L * DAY_MS++/** Someone who opened Gotcha this recently is using it, and needs no reminder. */+internal const val RECENTLY_OPENED_MS = 2L * HOUR_MS++/** One proactive notification per category in this window, whatever the cap allows. */+internal const val CATEGORY_COOLDOWN_MS = 20L * HOUR_MS++/** A request asked on this many different days is a routine. */+internal const val ROUTINE_MIN_DAYS = 3++/**+ * True when [minuteOfDay] falls inside quiet hours from [start] to [end]+ * (minutes after midnight). A window that crosses midnight, like the default+ * 22:00–08:00, wraps; equal ends mean no quiet hours at all.+ */+internal fun inQuietHours(minuteOfDay: Int, start: Int, end: Int): Boolean = when {+ start == end -> false+ start < end -> minuteOfDay in start until end+ else -> minuteOfDay >= start || minuteOfDay < end+}++/**+ * Why [candidate] may not be sent now, or null when it may. Pure, so every+ * anti-spam rule is unit tested:+ * - the master switch and the candidate's own category switch;+ * - quiet hours;+ * - deduplication: an occasion already notified is never notified again;+ * - a cooldown per category, and a cap on proactive notifications per day.+ */+internal fun blockReason(+ candidate: LocalCandidate,+ settings: Settings,+ sent: List<SentRecord>,+ now: Long,+ zone: ZoneId+): String? {+ if (!settings.localNotificationsEnabled) return "off"+ if (!categoryEnabled(candidate.category, settings)) return "category_off"+ val local = Instant.ofEpochMilli(now).atZone(zone)+ if (settings.quietHoursEnabled &&+ inQuietHours(local.hour * 60 + local.minute, settings.quietHoursStartMinute, settings.quietHoursEndMinute)+ ) {+ return "quiet_hours"+ }+ if (sent.any { it.key == candidate.dedupKey }) return "duplicate"+ if (sent.any { it.category == candidate.category.name && now - it.at < CATEGORY_COOLDOWN_MS }) {+ return "cooldown"+ }+ val today = local.toLocalDate()+ val sentToday = sent.count { Instant.ofEpochMilli(it.at).atZone(zone).toLocalDate() == today }+ if (sentToday >= settings.maxLocalNotificationsPerDay) return "daily_cap"+ return null+}++private fun categoryEnabled(category: NotificationCategory, settings: Settings): Boolean = when (category) {+ NotificationCategory.UNFINISHED_CHAT -> settings.unfinishedChatRemindersEnabled+ NotificationCategory.ROUTINE -> settings.routineSuggestionsEnabled+ NotificationCategory.INACTIVITY -> settings.inactivityRemindersEnabled+ NotificationCategory.DAILY_TIP -> settings.dailyTipsEnabled+ NotificationCategory.TASK_FINISHED -> settings.chatCompletionNotificationsEnabled+ NotificationCategory.SERVER -> settings.serverMessagesEnabled+}++/**+ * The behaviour-based notifications worth sending now, best first: a chat left+ * unfinished, then a routine that is due, then a reminder after a quiet spell.+ * Sensitive chats are never used. With [mention] off, the text stays generic+ * and names no chat or request; the tap still goes to the same place.+ */+internal fun behaviorCandidates(+ chats: List<ChatDigest>,+ lastOpenedAt: Long,+ inactivityDays: Int,+ mention: Boolean,+ now: Long,+ zone: ZoneId+): List<LocalCandidate> {+ val usable = chats.filterNot { it.sensitive }+ return listOfNotNull(+ unfinishedChat(usable, mention, now),+ dueRoutine(usable, mention, now, zone),+ inactivityReminder(usable, lastOpenedAt, inactivityDays, mention, now)+ )+}++/**+ * The most recent chat whose last run failed, was stopped, or ended on a+ * question to the user — between [UNFINISHED_MIN_AGE_MS] and+ * [UNFINISHED_MAX_AGE_MS] ago.+ */+internal fun unfinishedChat(chats: List<ChatDigest>, mention: Boolean, now: Long): LocalCandidate? {+ val (chat, run) = chats+ .mapNotNull { chat -> chat.runs.maxByOrNull { it.endedAt }?.let { chat to it } }+ .filter { (_, run) -> now - run.endedAt in UNFINISHED_MIN_AGE_MS..UNFINISHED_MAX_AGE_MS }+ .filter { (_, run) -> !run.succeeded || run.finalReply.trimEnd().endsWith("?") }+ .maxByOrNull { (_, run) -> run.endedAt }+ ?: return null+ val asked = run.succeeded+ val body = when {+ !mention -> "A chat was left unfinished. Tap to pick it up."+ asked -> "Gotcha asked you something in “${chat.title}”. Tap to answer."+ else -> "“${chat.title}” stopped before it was done. Tap to pick it up."+ }+ return LocalCandidate(+ category = NotificationCategory.UNFINISHED_CHAT,+ dedupKey = "unfinished:${chat.id}:${run.endedAt}",+ title = if (asked) "Gotcha is waiting for you" else "Finish what you started",+ body = body,+ target = NotificationTarget.Chat(chat.id)+ )+}++/**+ * A request the user makes regularly that is due again: asked on at least+ * [ROUTINE_MIN_DAYS] different days, and as many days have passed since the+ * last time as usually do (the median gap), but no more than two beyond it —+ * a routine long abandoned is not nagged about.+ */+internal fun dueRoutine(chats: List<ChatDigest>, mention: Boolean, now: Long, zone: ZoneId): LocalCandidate? {+ val today = Instant.ofEpochMilli(now).atZone(zone).toLocalDate()+ fun day(millis: Long): LocalDate = Instant.ofEpochMilli(millis).atZone(zone).toLocalDate()+ val runs = chats.flatMap { it.runs }.filter { it.succeeded && routineKey(it.userPrompt).isNotEmpty() }+ return runs.groupBy { routineKey(it.userPrompt) }+ .mapNotNull { (key, group) ->+ val days = group.map { day(it.endedAt) }.distinct().sorted()+ if (days.size < ROUTINE_MIN_DAYS) return@mapNotNull null+ val gaps = days.zipWithNext { a, b -> ChronoUnit.DAYS.between(a, b) }.sorted()+ val usualGap = gaps[gaps.size / 2]+ val sinceLast = ChronoUnit.DAYS.between(days.last(), today)+ if (sinceLast < usualGap || sinceLast > usualGap + 2) return@mapNotNull null+ val latest = group.maxBy { it.endedAt }+ Triple(key, latest, days.size)+ }+ // The most established routine wins.+ .maxByOrNull { it.third }+ ?.let { (key, latest, _) ->+ val prompt = latest.userPrompt.trim()+ val preview = if (prompt.length > ROUTINE_PREVIEW_CHARS) {+ prompt.take(ROUTINE_PREVIEW_CHARS).trimEnd() + "…"+ } else {+ prompt+ }+ LocalCandidate(+ category = NotificationCategory.ROUTINE,+ dedupKey = "routine:${key.hashCode()}:${day(latest.endedAt)}",+ title = "Time for your usual?",+ body = if (mention) {+ "You often ask: “$preview”. Tap to ask again."+ } else {+ "One of your regular requests may be due. Tap to see it."+ },+ target = NotificationTarget.Draft(+ prompt = prompt,+ mode = runCatching { AgentMode.valueOf(latest.agentMode) }.getOrDefault(AgentMode.MONITOR)+ )+ )+ }+}++private const val ROUTINE_PREVIEW_CHARS = 80++/**+ * What makes two requests "the same" for routine detection: case, digits+ * (dates, times, amounts) and punctuation are ignored. Too short a request is+ * not a routine.+ */+internal fun routineKey(prompt: String): String {+ val key = prompt.lowercase()+ // A time or amount ("7:30", "2.5") is one number, not two.+ .replace(Regex("\\d+([:.,]\\d+)*"), "#")+ .replace(Regex("[^\\p{L}#]+"), " ")+ .trim()+ .take(ROUTINE_KEY_CHARS)+ return if (key.count { it.isLetter() } < ROUTINE_MIN_LETTERS) "" else key+}++private const val ROUTINE_KEY_CHARS = 80+private const val ROUTINE_MIN_LETTERS = 8++/**+ * A nudge once Gotcha has not been opened for [inactivityDays]. One per quiet+ * spell: the key is the last time it was opened. With [mention] on it offers+ * the most recent chat back.+ */+internal fun inactivityReminder(+ chats: List<ChatDigest>,+ lastOpenedAt: Long,+ inactivityDays: Int,+ mention: Boolean,+ now: Long+): LocalCandidate? {+ if (lastOpenedAt <= 0L || now - lastOpenedAt < inactivityDays * DAY_MS) return null+ val recent = chats+ .mapNotNull { chat -> chat.runs.maxOfOrNull { it.endedAt }?.let { chat to it } }+ .maxByOrNull { it.second }+ ?.first+ ?.takeIf { mention }+ return LocalCandidate(+ category = NotificationCategory.INACTIVITY,+ dedupKey = "inactive:$lastOpenedAt",+ title = if (recent != null) "Pick up where you left off" else "Anything Gotcha can do for you?",+ body = if (recent != null) {+ "Your last chat was “${recent.title}”. Tap to open it."+ } else {+ "Ask Gotcha to handle something on your phone. Tap to open."+ },+ target = recent?.let { NotificationTarget.Chat(it.id) } ?: NotificationTarget.Home+ )+}++/** The daily tip as a candidate: at most one a day. */+internal fun tipCandidate(tip: DailyTip, now: Long, zone: ZoneId): LocalCandidate = LocalCandidate(+ category = NotificationCategory.DAILY_TIP,+ dedupKey = "tip:${Instant.ofEpochMilli(now).atZone(zone).toLocalDate()}",+ title = tip.title,+ body = tip.body,+ target = NotificationTarget.Draft(tip.prompt, tip.agent)+)++/**+ * Whether a chat is kept out of notifications. The user's own choice wins;+ * otherwise chats with the Doctor persona are, since health is private.+ */+internal fun isChatSensitive(personaId: String?, choice: Boolean?): Boolean =+ choice ?: (personaId in SENSITIVE_PERSONAS)++/** Personas whose chats are kept out of notifications unless the user says otherwise. */+internal val SENSITIVE_PERSONAS = setOf("doctor")diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotifier.kt b/app/src/main/java/com/gotcha/notifications/LocalNotifier.ktnew file mode 100644index 0000000..5a6f110--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/LocalNotifier.kt@@ -0,0 +1,110 @@+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++/**+ * Posts Gotcha's proactive notifications (issues #100, #101) and files each in+ * the inbox. Daily tips keep their own low-importance channel; reminders+ * (unfinished chats, routines, quiet spells) share another, so either can be+ * silenced from Android's settings without the other.+ *+ * One slot per category: an unread reminder is replaced by the next of its+ * kind rather than stacking beside it.+ */+class LocalNotifier(private val context: Context) {++ /** True when Android will actually show what [post] posts. */+ fun canPost(): Boolean = ChatCompletionNotifier(context).canPost()++ @Suppress("MissingPermission") // canPost() checks it.+ fun post(candidate: LocalCandidate, store: LocalNotificationStore): Boolean {+ if (!canPost()) return false+ val tip = candidate.category == NotificationCategory.DAILY_TIP+ val channel = if (tip) TIP_CHANNEL_ID else REMINDER_CHANNEL_ID+ ensureChannels()+ val entryId = store.addEntry(candidate.category, candidate.title, candidate.body, candidate.target)+ val notifyId = notificationId(candidate.category)+ val builder = NotificationCompat.Builder(context, channel)+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)+ .setContentTitle(candidate.title)+ .setContentText(candidate.body)+ .setStyle(NotificationCompat.BigTextStyle().bigText(candidate.body))+ .setCategory(if (tip) NotificationCompat.CATEGORY_RECOMMENDATION else NotificationCompat.CATEGORY_REMINDER)+ .setAutoCancel(true)+ .setContentIntent(tapIntent(candidate.target, entryId, notifyId))+ if (!tip) {+ // A reminder may name a chat: the lock screen gets a generic line only.+ builder.setVisibility(NotificationCompat.VISIBILITY_PRIVATE)+ .setPublicVersion(+ NotificationCompat.Builder(context, channel)+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)+ .setContentTitle(PUBLIC_TITLE)+ .build()+ )+ }+ NotificationManagerCompat.from(context).notify(notifyId, builder.build())+ return true+ }++ private fun tapIntent(target: NotificationTarget, entryId: String, requestCode: Int): PendingIntent {+ val intent = Intent(context, com.gotcha.MainActivity::class.java).apply {+ action = ACTION_OPEN_LOCAL_NOTIFICATION+ putExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID, entryId)+ putTargetExtras(target)+ 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 ensureChannels() {+ val mgr = context.getSystemService(NotificationManager::class.java) ?: return+ if (mgr.getNotificationChannel(TIP_CHANNEL_ID) == null) {+ mgr.createNotificationChannel(+ NotificationChannel(TIP_CHANNEL_ID, "Daily tips", NotificationManager.IMPORTANCE_LOW).apply {+ description = "One thing to try with Gotcha each day"+ }+ )+ }+ if (mgr.getNotificationChannel(REMINDER_CHANNEL_ID) == null) {+ mgr.createNotificationChannel(+ NotificationChannel(REMINDER_CHANNEL_ID, "Reminders", NotificationManager.IMPORTANCE_DEFAULT).apply {+ description = "Unfinished chats, routines that are due, and a nudge after a quiet spell"+ }+ )+ }+ }++ companion object {+ const val TIP_CHANNEL_ID = "gotcha_daily_tips"+ const val REMINDER_CHANNEL_ID = "gotcha_reminders"+ const val ACTION_OPEN_LOCAL_NOTIFICATION = "com.gotcha.ACTION_OPEN_LOCAL_NOTIFICATION"+ const val EXTRA_DRAFT_PROMPT = "com.gotcha.DRAFT_PROMPT"+ const val EXTRA_DRAFT_MODE = "com.gotcha.DRAFT_MODE"+ private const val PUBLIC_TITLE = "Gotcha has a suggestion"++ internal fun notificationId(category: NotificationCategory): Int = 0x7100 + category.ordinal++ /** The extras that tell MainActivity where a tap should go. */+ fun Intent.putTargetExtras(target: NotificationTarget): Intent = apply {+ when (target) {+ is NotificationTarget.Chat -> putExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID, target.sessionId)+ is NotificationTarget.Draft -> {+ putExtra(EXTRA_DRAFT_PROMPT, target.prompt)+ putExtra(EXTRA_DRAFT_MODE, target.mode.name)+ }+ NotificationTarget.Home -> Unit+ }+ }+ }+}diff --git a/app/src/main/java/com/gotcha/notifications/NotificationDispatcher.kt b/app/src/main/java/com/gotcha/notifications/NotificationDispatcher.ktindex 559b19f..bb45f80 100644--- a/app/src/main/java/com/gotcha/notifications/NotificationDispatcher.kt+++ b/app/src/main/java/com/gotcha/notifications/NotificationDispatcher.kt@@ -36,6 +36,8 @@ class NotificationDispatcher(private val api: NotificationApi,private val store: NotificationStore,private val versionName: String,+ /** Where delivered messages are listed in the app (issue #100); null leaves them out. */+ private val inbox: LocalNotificationStore? = null,@Suppress("UnusedPrivateProperty")private val openIntent: (url: String) -> Intent = { url ->Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(@@ -128,8 +130,17 @@ class NotificationDispatcher(@Suppress("MissingPermission") // hasPostPermission() is enforced in deliver().private fun postOne(msg: NotificationMessage) {val notifyId = stableNotifyId(msg.id)+ val safeUrl = msg.url?.takeIf { it.startsWith("https://") }+ val entryId = inbox?.addEntry(+ NotificationCategory.SERVER,+ msg.title,+ msg.body,+ NotificationTarget.Home,+ safeUrl+ )val tapIntent = Intent(context, com.gotcha.MainActivity::class.java).apply {action = ACTION_SHOW_NOTIFICATION+ entryId?.let { putExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID, it) }putExtra(EXTRA_NOTIFICATION_ID, notifyId)putExtra(EXTRA_NOTIFICATION_TITLE, msg.title)putExtra(EXTRA_NOTIFICATION_BODY, msg.body)diff --git a/app/src/main/java/com/gotcha/notifications/ServerMessages.kt b/app/src/main/java/com/gotcha/notifications/ServerMessages.ktindex 2c339d5..ed6c9bb 100644--- a/app/src/main/java/com/gotcha/notifications/ServerMessages.kt+++ b/app/src/main/java/com/gotcha/notifications/ServerMessages.kt@@ -27,7 +27,8 @@ object ServerMessages {context = context,api = api,store = NotificationStore(context),- versionName = versionName+ versionName = versionName,+ inbox = LocalNotificationStore(context))}diff --git a/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.ktindex 40ab76d..4b63b80 100644--- a/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt+++ b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt@@ -149,7 +149,7 @@ object GotchaSettingsUpdate {const val FOLLOW_REPLY_LANGUAGE = "same_as_replies"private fun specs(catalog: SettingsCatalog): List<Spec> =- notificationSpecs() + voiceSpecs() + appearanceSpecs(catalog) + proactiveSpecs() + wakeWordSpecs()+ notificationSpecs() + localNotificationSpecs() + voiceSpecs() + appearanceSpecs(catalog) + proactiveSpecs() + wakeWordSpecs()private fun notificationSpecs(): List<Spec> = listOf(boolSpec(@@ -183,13 +183,6 @@ object GotchaSettingsUpdate {{ it.chatCompletionPreview },{ s, v -> s.copy(chatCompletionPreview = v) }),- boolSpec(- "daily_tips",- "A daily tip with something to try",- setOf(SettingImpact.NOTIFICATIONS),- { it.dailyTipsEnabled },- { s, v -> s.copy(dailyTipsEnabled = v) }- ),boolSpec("server_messages","Messages from Samosa AI",@@ -199,6 +192,77 @@ object GotchaSettingsUpdate {))+ /** Gotcha's own proactive notifications (issue #100). */+ private fun localNotificationSpecs(): List<Spec> = listOf(+ boolSpec(+ "local_notifications",+ "Gotcha's own reminders and tips",+ setOf(SettingImpact.NOTIFICATIONS),+ { it.localNotificationsEnabled },+ { s, v -> s.copy(localNotificationsEnabled = v) }+ ),+ boolSpec(+ "unfinished_chat_reminders",+ "Remind me about unfinished chats",+ setOf(SettingImpact.NOTIFICATIONS),+ { it.unfinishedChatRemindersEnabled },+ { s, v -> s.copy(unfinishedChatRemindersEnabled = v) }+ ),+ boolSpec(+ "routine_suggestions",+ "Suggest routines when they're due",+ setOf(SettingImpact.NOTIFICATIONS),+ { it.routineSuggestionsEnabled },+ { s, v -> s.copy(routineSuggestionsEnabled = v) }+ ),+ boolSpec(+ "inactivity_reminders",+ "Remind me after a quiet spell",+ setOf(SettingImpact.NOTIFICATIONS),+ { it.inactivityRemindersEnabled },+ { s, v -> s.copy(inactivityRemindersEnabled = v) }+ ),+ choiceSpec(+ "inactivity_days",+ "Days without Gotcha before a reminder",+ setOf(SettingImpact.NOTIFICATIONS),+ listOf(2, 3, 4, 7, 14).associateBy { it.toString() },+ { it.toString() },+ { it.inactivityDays },+ { s, v -> s.copy(inactivityDays = v) }+ ),+ boolSpec(+ "quiet_hours",+ "Quiet hours for reminders and tips",+ setOf(SettingImpact.NOTIFICATIONS),+ { it.quietHoursEnabled },+ { s, v -> s.copy(quietHoursEnabled = v) }+ ),+ choiceSpec(+ "max_notifications_per_day",+ "Most reminders and tips a day",+ setOf(SettingImpact.NOTIFICATIONS),+ listOf(1, 2, 3).associateBy { it.toString() },+ { it.toString() },+ { it.maxLocalNotificationsPerDay },+ { s, v -> s.copy(maxLocalNotificationsPerDay = v) }+ ),+ boolSpec(+ "notifications_name_chats",+ "Name chats in notifications",+ setOf(SettingImpact.NOTIFICATIONS, SettingImpact.PRIVACY),+ { it.notificationsMentionChats },+ { s, v -> s.copy(notificationsMentionChats = v) }+ ),+ boolSpec(+ "daily_tips",+ "A daily tip with something to try",+ setOf(SettingImpact.NOTIFICATIONS),+ { it.dailyTipsEnabled },+ { s, v -> s.copy(dailyTipsEnabled = v) }+ )+ )+private fun voiceSpecs(): List<Spec> = listOf(boolSpec("auto_read_replies",diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.ktindex 322bb96..11f1583 100644--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt@@ -35,13 +35,17 @@ import androidx.compose.material.icons.automirrored.rounded.VolumeUpimport androidx.compose.material.icons.filled.Editimport androidx.compose.material.icons.filled.Menuimport androidx.compose.material.icons.filled.Mic-import androidx.compose.material.icons.filled.Share+import androidx.compose.material.icons.filled.MoreVertimport androidx.compose.material.icons.filled.Stopimport androidx.compose.material.icons.filled.TouchAppimport androidx.compose.material.icons.outlined.Info+import androidx.compose.material.icons.outlined.Notificationsimport androidx.compose.material.icons.outlined.Visibility+import androidx.compose.material3.Badge+import androidx.compose.material3.BadgedBoximport androidx.compose.material3.Buttonimport androidx.compose.material3.ButtonDefaults+import androidx.compose.material3.Checkboximport androidx.compose.material3.CircularProgressIndicatorimport androidx.compose.material3.DropdownMenuItemimport androidx.compose.material3.ExperimentalMaterial3Api@@ -115,7 +119,11 @@ fun ChatScreen(onCreateShareCard: () -> Unit = {},onEditMessage: (Long, String, List<ComposerAttachment>) -> Unit = { _, _, _ -> },onRevertMessage: (Long) -> Unit = { _ -> },- onComposerDraftConsumed: () -> Unit = {}+ onComposerDraftConsumed: () -> Unit = {},+ unreadNotifications: Int = 0,+ onOpenInbox: () -> Unit = {},+ chatKeptOutOfNotifications: Boolean = false,+ onSetChatKeptOutOfNotifications: (Boolean) -> Unit = {}) {val skin = LocalSkin.currentval isHome = state.messages.isEmpty()@@ -206,8 +214,9 @@ fun ChatScreen(}},actions = {- // The home screen carries no actions: its top bar is the menu- // and the title only. Everything here belongs to an open chat.+ // The inbox (issue #100) is the one action on the home screen+ // too; everything after it belongs to an open chat.+ InboxButton(unread = unreadNotifications, onClick = onOpenInbox)if (!isHome) {// Operator can change the device, Monitor cannot. Both// badges name their own mode so that distinction is never@@ -271,10 +280,12 @@ fun ChatScreen()}}- ChatShareMenu(+ ChatOptionsMenu(onExportChat = onExportChat,onCreateShareCard = onCreateShareCard,- enabled = !state.isBusy+ shareEnabled = !state.isBusy,+ keptOutOfNotifications = chatKeptOutOfNotifications,+ onSetKeptOutOfNotifications = onSetChatKeptOutOfNotifications)}}@@ -833,24 +844,46 @@ fun ChatScreen(}/**- * Share menu in the chat top bar, reached from a single share icon: the- * markdown chat export plus the "Create share card" (whole-chat aggregation)- * entry point for the marketing poster.+ * The inbox bell (issue #100), with the number of unread notifications on it.*/@Composable-private fun ChatShareMenu(+private fun InboxButton(unread: Int, onClick: () -> Unit) {+ IconButton(onClick = onClick, modifier = Modifier.testTag("inbox_button")) {+ BadgedBox(+ badge = {+ if (unread > 0) Badge { Text(if (unread > 9) "9+" else unread.toString()) }+ }+ ) {+ Icon(+ Icons.Outlined.Notifications,+ contentDescription = if (unread > 0) "Notifications, $unread unread" else "Notifications"+ )+ }+ }+}++/**+ * The open chat's menu: the markdown chat export and the "Create share card"+ * (whole-chat aggregation) entry point for the marketing poster, plus whether+ * Gotcha's notifications may use this chat (issue #100).+ */+@Composable+private fun ChatOptionsMenu(onExportChat: () -> Unit,onCreateShareCard: () -> Unit,- enabled: Boolean+ shareEnabled: Boolean,+ keptOutOfNotifications: Boolean,+ onSetKeptOutOfNotifications: (Boolean) -> Unit) {var expanded by remember { mutableStateOf(false) }Box {- IconButton(onClick = { expanded = true }, enabled = enabled) {- Icon(Icons.Default.Share, contentDescription = "Share chat")+ IconButton(onClick = { expanded = true }, modifier = Modifier.testTag("chat_options")) {+ Icon(Icons.Default.MoreVert, contentDescription = "Chat options")}SkinDropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {DropdownMenuItem(text = { Text("Export chat") },+ enabled = shareEnabled,onClick = {expanded = falseonExportChat()@@ -858,11 +891,18 @@ private fun ChatShareMenu()DropdownMenuItem(text = { Text("Create share card") },+ enabled = shareEnabled,onClick = {expanded = falseonCreateShareCard()})+ DropdownMenuItem(+ text = { Text("Keep out of notifications") },+ trailingIcon = { Checkbox(checked = keptOutOfNotifications, onCheckedChange = null) },+ onClick = { onSetKeptOutOfNotifications(!keptOutOfNotifications) },+ modifier = Modifier.testTag("chat_keep_out_of_notifications")+ )}}}diff --git a/app/src/main/java/com/gotcha/ui/InboxScreen.kt b/app/src/main/java/com/gotcha/ui/InboxScreen.ktnew file mode 100644index 0000000..9038e22--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/InboxScreen.kt@@ -0,0 +1,154 @@+package com.gotcha.ui++import androidx.compose.foundation.clickable+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.shape.CircleShape+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Surface+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.text.style.TextOverflow+import androidx.compose.ui.unit.dp+import com.gotcha.notifications.InboxEntry++/**+ * The in-app notification inbox (issue #100): everything Gotcha has notified+ * about in the last 30 days — its own reminders and tips, finished tasks and+ * messages from Samosa AI — newest first. Tapping an entry goes where its+ * notification would have gone.+ *+ * Opening the inbox counts as reading it, so the badge clears; the entries+ * that were unread keep their dot for this visit.+ */+@Composable+fun InboxScreen(+ load: () -> List<InboxEntry>,+ onOpened: () -> Unit,+ onClear: () -> Unit,+ onOpenEntry: (InboxEntry) -> Unit,+ onBack: () -> Unit+) {+ var entries by remember { mutableStateOf(load()) }+ var confirmClear by remember { mutableStateOf(false) }+ val overlay = rememberSettingsOverlayState()+ LaunchedEffect(Unit) { onOpened() }++ SettingsScaffold(+ title = "Notifications",+ onBack = onBack,+ overlay = overlay,+ header = if (entries.isEmpty()) {+ null+ } else {+ {+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {+ TextButton(+ onClick = { confirmClear = true },+ modifier = Modifier.testTag("inbox_clear")+ ) { Text("Clear history") }+ }+ }+ }+ ) {+ if (entries.isEmpty()) {+ Text(+ "Nothing here yet. Reminders, daily tips, finished tasks and messages from " ++ "Samosa AI are listed here for 30 days.",+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ modifier = Modifier.testTag("inbox_empty")+ )+ }+ entries.forEach { entry -> InboxRow(entry, onClick = { onOpenEntry(entry) }) }+ }++ if (confirmClear) {+ AlertDialog(+ onDismissRequest = { confirmClear = false },+ title = { Text("Clear notification history?") },+ text = {+ Text("This empties the list. Reminders Gotcha has already sent won't be sent again.")+ },+ confirmButton = {+ TextButton(+ onClick = {+ onClear()+ entries = emptyList()+ confirmClear = false+ },+ modifier = Modifier.testTag("inbox_clear_confirm")+ ) { Text("Clear") }+ },+ dismissButton = { TextButton(onClick = { confirmClear = false }) { Text("Cancel") } }+ )+ }+}++@Composable+private fun InboxRow(entry: InboxEntry, onClick: () -> Unit) {+ val scheme = MaterialTheme.colorScheme+ Surface(+ shape = RoundedCornerShape(16.dp),+ color = scheme.surfaceVariant.copy(alpha = 0.5f),+ modifier = Modifier+ .fillMaxWidth()+ .clickable(onClick = onClick)+ .testTag("inbox_entry")+ ) {+ Row(modifier = Modifier.padding(14.dp), verticalAlignment = Alignment.Top) {+ Box(modifier = Modifier.padding(top = 6.dp, end = 10.dp).size(8.dp)) {+ if (!entry.read) {+ Surface(shape = CircleShape, color = scheme.primary, modifier = Modifier.size(8.dp)) {}+ }+ }+ Column(modifier = Modifier.weight(1f)) {+ Text(+ "${entry.categoryOrNull?.label ?: "Notification"} · ${inboxTime(entry.postedAt)}",+ style = MaterialTheme.typography.labelSmall,+ color = scheme.onSurfaceVariant+ )+ Text(+ entry.title,+ style = MaterialTheme.typography.titleSmall,+ maxLines = 2,+ overflow = TextOverflow.Ellipsis+ )+ Text(+ entry.body,+ style = MaterialTheme.typography.bodySmall,+ color = scheme.onSurfaceVariant,+ maxLines = 3,+ overflow = TextOverflow.Ellipsis+ )+ }+ }+ }+}++/** "just now", "5m ago", "3h ago", "2d ago". */+internal fun inboxTime(epochMillis: Long, now: Long = System.currentTimeMillis()): String {+ val minutes = (now - epochMillis) / 60_000L+ return when {+ minutes < 1L -> "just now"+ minutes < 60L -> "${minutes}m ago"+ minutes < 24L * 60L -> "${minutes / 60L}h ago"+ else -> "${minutes / (24L * 60L)}d ago"+ }+}diff --git a/app/src/main/java/com/gotcha/ui/LocalNotificationsSection.kt b/app/src/main/java/com/gotcha/ui/LocalNotificationsSection.ktnew file mode 100644index 0000000..1189df4--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/LocalNotificationsSection.kt@@ -0,0 +1,285 @@+package com.gotcha.ui++import android.app.TimePickerDialog+import android.content.Context+import android.text.format.DateFormat+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.foundation.layout.size+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Check+import androidx.compose.material3.AlertDialog+import androidx.compose.material3.FilterChip+import androidx.compose.material3.FilterChipDefaults+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import 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 androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.unit.dp+import com.gotcha.data.Settings+import com.gotcha.notifications.LocalNotificationScheduler+import com.gotcha.notifications.LocalNotificationStore+import com.gotcha.notifications.inQuietHours+import java.time.LocalTime+import java.time.format.DateTimeFormatter+import java.time.format.FormatStyle++/** Choices offered for the inactivity reminder, in days. */+private val INACTIVITY_DAY_CHOICES = listOf(2, 3, 4, 7, 14)++/** Choices offered for the daily cap. */+private val DAILY_CAP_CHOICES = listOf(1, 2, 3)++/**+ * "Gotcha notifications" on the Notifications page (issue #100): the proactive+ * notifications Gotcha decides to send from what happens on the phone —+ * reminders about unfinished chats, routines and quiet spells, and the daily+ * tip (#101) — with quiet hours, a daily cap, whether they may name chats, and+ * clearing the history. Server messages stay a section of their own.+ *+ * Every control saves as it changes, like the rest of the page.+ */+@OptIn(ExperimentalLayoutApi::class)+@Composable+internal fun LocalNotificationsSection(+ initial: Settings,+ onSave: ((Settings) -> Settings) -> Unit,+ canPost: Boolean,+ requestPermission: () -> Unit+) {+ val context = LocalContext.current+ var enabled by remember { mutableStateOf(initial.localNotificationsEnabled) }+ var unfinished by remember { mutableStateOf(initial.unfinishedChatRemindersEnabled) }+ var routines by remember { mutableStateOf(initial.routineSuggestionsEnabled) }+ var inactivity by remember { mutableStateOf(initial.inactivityRemindersEnabled) }+ var inactivityDays by remember { mutableStateOf(initial.inactivityDays) }+ var tips by remember { mutableStateOf(initial.dailyTipsEnabled) }+ var tipMinute by remember { mutableStateOf(initial.dailyTipMinuteOfDay) }+ var quiet by remember { mutableStateOf(initial.quietHoursEnabled) }+ var quietStart by remember { mutableStateOf(initial.quietHoursStartMinute) }+ var quietEnd by remember { mutableStateOf(initial.quietHoursEndMinute) }+ var cap by remember { mutableStateOf(initial.maxLocalNotificationsPerDay) }+ var mention by remember { mutableStateOf(initial.notificationsMentionChats) }+ var confirmClear by remember { mutableStateOf(false) }+ var cleared by remember { mutableStateOf(false) }++ /** A switch that also asks for the notification permission when turned on without it. */+ @Composable+ fun Toggle(label: String, checked: Boolean, tag: String, onChange: (Boolean) -> Unit) {+ SettingsToggleRow(+ label = label,+ checked = checked,+ onCheckedChange = {+ onChange(it)+ if (it && !canPost) requestPermission()+ },+ isLarge = true,+ switchTestTag = tag+ )+ }++ Text("Gotcha notifications", style = MaterialTheme.typography.titleMedium)+ Text(+ "Reminders and tips Gotcha decides to send, worked out on this phone from your chats. " ++ "Nothing about how you use Gotcha is uploaded to decide them.",+ style = MaterialTheme.typography.bodySmall+ )+ Toggle("Send Gotcha notifications", enabled, "settings_local_notifications_enabled") {+ enabled = it+ onSave { s -> s.copy(localNotificationsEnabled = it) }+ }+ if (!enabled) return++ Toggle("Unfinished chats", unfinished, "settings_unfinished_reminders") {+ unfinished = it+ onSave { s -> s.copy(unfinishedChatRemindersEnabled = it) }+ }+ Hint("When a task failed, was stopped, or Gotcha asked you something and you didn't answer.")++ Toggle("Routines", routines, "settings_routine_suggestions") {+ routines = it+ onSave { s -> s.copy(routineSuggestionsEnabled = it) }+ }+ Hint("When something you ask regularly is due again. Tap to ask it again, edited first if you like.")++ Toggle("After a quiet spell", inactivity, "settings_inactivity_reminders") {+ inactivity = it+ onSave { s -> s.copy(inactivityRemindersEnabled = it) }+ }+ if (inactivity) {+ Hint("When you haven't opened Gotcha for:")+ ChoiceChips(INACTIVITY_DAY_CHOICES, inactivityDays, { "$it days" }, "settings_inactivity_days") {+ inactivityDays = it+ onSave { s -> s.copy(inactivityDays = it) }+ }+ }++ Toggle("Daily tip", tips, "settings_daily_tips_enabled") {+ tips = it+ onSave { s -> s.copy(dailyTipsEnabled = it) }+ }+ Hint(+ "One thing to try each day, picked from what you haven't used yet. Tap it to start a chat " ++ "with the prompt ready to edit or send. Skipped on days you've already used Gotcha."+ )+ if (tips) {+ TimeButton("Time", tipMinute, "settings_daily_tip_time") {+ tipMinute = it+ onSave { s -> s.copy(dailyTipMinuteOfDay = it) }+ LocalNotificationScheduler.scheduleTip(context, it)+ }+ if (quiet && inQuietHours(tipMinute, quietStart, quietEnd)) {+ Warning("This time is inside your quiet hours, so no tip will arrive.")+ }+ }++ Spacer(Modifier.height(8.dp))+ Toggle("Quiet hours", quiet, "settings_quiet_hours") {+ quiet = it+ onSave { s -> s.copy(quietHoursEnabled = it) }+ }+ if (quiet) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ TimeButton("From", quietStart, "settings_quiet_start") {+ quietStart = it+ onSave { s -> s.copy(quietHoursStartMinute = it) }+ }+ TimeButton("To", quietEnd, "settings_quiet_end") {+ quietEnd = it+ onSave { s -> s.copy(quietHoursEndMinute = it) }+ }+ }+ }++ Text("At most a day", style = MaterialTheme.typography.bodyMedium)+ ChoiceChips(DAILY_CAP_CHOICES, cap, { it.toString() }, "settings_daily_cap") {+ cap = it+ onSave { s -> s.copy(maxLocalNotificationsPerDay = it) }+ }+ Hint("Tips and reminders count; finished tasks and server messages don't.")++ Toggle("Name chats in notifications", mention, "settings_mention_chats") {+ mention = it+ onSave { s -> s.copy(notificationsMentionChats = it) }+ }+ Hint(+ "Off, notifications only say that something needs you, never which chat or request. " ++ "Chats kept out of notifications (from a chat's ⋮ menu, and Doctor chats unless you change it) " ++ "are never named, and the lock screen never shows either."+ )++ if (!canPost) {+ Warning("Notifications are blocked for Gotcha, so none will be shown.")+ }++ TextButton(+ onClick = { confirmClear = true },+ enabled = !cleared,+ modifier = Modifier.testTag("settings_clear_notification_history")+ ) { Text(if (cleared) "Notification history cleared" else "Clear notification history") }++ if (confirmClear) {+ AlertDialog(+ onDismissRequest = { confirmClear = false },+ title = { Text("Clear notification history?") },+ text = {+ Text(+ "This empties the list behind the bell on the home screen. Reminders Gotcha has " ++ "already sent won't be sent again."+ )+ },+ confirmButton = {+ TextButton(onClick = {+ LocalNotificationStore(context).clearHistory()+ cleared = true+ confirmClear = false+ }) { Text("Clear") }+ },+ dismissButton = { TextButton(onClick = { confirmClear = false }) { Text("Cancel") } }+ )+ }+}++@Composable+private fun Hint(text: String) {+ Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+}++@Composable+private fun Warning(text: String) {+ Text(text, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun <T> ChoiceChips(+ choices: List<T>,+ selected: T,+ label: (T) -> String,+ tag: String,+ onSelect: (T) -> Unit+) {+ FlowRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth().testTag(tag)+ ) {+ choices.forEach { choice ->+ val isSelected = choice == selected+ FilterChip(+ selected = isSelected,+ onClick = { onSelect(choice) },+ label = { Text(label(choice)) },+ leadingIcon = if (isSelected) {+ { Icon(Icons.Default.Check, contentDescription = null, modifier = Modifier.size(18.dp)) }+ } else {+ null+ },+ // Solid, like the switches: the default selected fill is translucent on+ // the glass skins and reads as unselected.+ colors = FilterChipDefaults.filterChipColors(+ selectedContainerColor = MaterialTheme.colorScheme.primary,+ selectedLabelColor = MaterialTheme.colorScheme.onPrimary,+ selectedLeadingIconColor = MaterialTheme.colorScheme.onPrimary+ )+ )+ }+ }+}++@Composable+private fun TimeButton(label: String, minuteOfDay: Int, tag: String, onPick: (Int) -> Unit) {+ val context = LocalContext.current+ TextButton(+ onClick = { showTimePicker(context, minuteOfDay, onPick) },+ modifier = Modifier.testTag(tag)+ ) { Text("$label: ${formatMinuteOfDay(minuteOfDay)}") }+}++private fun showTimePicker(context: Context, minuteOfDay: Int, onPick: (Int) -> Unit) {+ TimePickerDialog(+ context,+ { _, hour, minute -> onPick(hour * 60 + minute) },+ minuteOfDay / 60,+ minuteOfDay % 60,+ DateFormat.is24HourFormat(context)+ ).show()+}++private val TIME_FORMAT: DateTimeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)++internal fun formatMinuteOfDay(minuteOfDay: Int): String =+ LocalTime.of(minuteOfDay / 60 % 24, minuteOfDay % 60).format(TIME_FORMAT)diff --git a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt b/app/src/main/java/com/gotcha/ui/NotificationsScreen.ktindex 0e1201b..1d5a561 100644--- a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt@@ -1,10 +1,8 @@package com.gotcha.ui-import android.app.TimePickerDialogimport android.content.Intentimport android.content.pm.PackageManagerimport android.os.Build-import android.text.format.DateFormatimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContractsimport androidx.compose.foundation.layout.Column@@ -39,17 +37,13 @@ import com.gotcha.audio.CompletionFeedbackimport com.gotcha.data.CompletionPreviewimport com.gotcha.data.Settingsimport com.gotcha.notifications.ChatCompletionNotifier-import com.gotcha.notifications.DailyTipSchedulerimport kotlinx.coroutines.launch-import java.time.LocalTime-import java.time.format.DateTimeFormatter-import java.time.format.FormatStyleimport android.provider.Settings as AndroidSettings/*** The Notifications page: what the phone does the moment a reply arrives- * (vibration/chime), the task-finished and daily tip notifications, and- * server-driven messages from the Samosa team (updates, tips, maintenance).+ * (vibration/chime), the task-finished notification, Gotcha's own reminders+ * and tips ([LocalNotificationsSection]), and server-driven messages from the Samosa team (updates, tips, maintenance).** The vibration/chime page has no Save button, and deliberately so —* switching one on plays it once, which is the whole point. A preview that@@ -68,8 +62,6 @@ fun NotificationsScreen(var notifyChime by remember { mutableStateOf(initial.notifyChimeEnabled) }var taskFinished by remember { mutableStateOf(initial.chatCompletionNotificationsEnabled) }var taskPreview by remember { mutableStateOf(initial.chatCompletionPreview) }- var dailyTips by remember { mutableStateOf(initial.dailyTipsEnabled) }- var dailyTipMinute by remember { mutableStateOf(initial.dailyTipMinuteOfDay) }var serverMessagesEnabled by remember { mutableStateOf(initial.serverMessagesEnabled) }var lastFetched by remember { mutableStateOf(initial.serverMessagesLastFetchedAt) }var isSyncing by remember { mutableStateOf(false) }@@ -185,57 +177,16 @@ fun NotificationsScreen(}Spacer(Modifier.height(16.dp))- Text(- "Daily tips",- style = MaterialTheme.typography.titleMedium- )- Text(- "One thing to try with Gotcha each day, picked from what you haven't used yet. " +- "Tap it to start a chat with the prompt ready to edit or send. " +- "Skipped on days you've already used Gotcha.",- style = MaterialTheme.typography.bodySmall- )- SettingsToggleRow(- label = "Send a daily tip",- checked = dailyTips,- onCheckedChange = {- dailyTips = it- onSave { s -> s.copy(dailyTipsEnabled = it) }- if (it && !canPost && Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ LocalNotificationsSection(+ initial = initial,+ onSave = onSave,+ canPost = canPost,+ requestPermission = {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {notificationPermissionLauncher.launch(android.Manifest.permission.POST_NOTIFICATIONS)}- },- isLarge = true,- switchTestTag = "settings_daily_tips_enabled"- )- if (dailyTips) {- TextButton(- onClick = {- TimePickerDialog(- localContext,- { _, hour, minute ->- val picked = hour * 60 + minute- dailyTipMinute = picked- onSave { s -> s.copy(dailyTipMinuteOfDay = picked) }- DailyTipScheduler.schedule(localContext, picked)- },- dailyTipMinute / 60,- dailyTipMinute % 60,- DateFormat.is24HourFormat(localContext)- ).show()- },- modifier = Modifier.testTag("settings_daily_tip_time")- ) {- Text("Time: ${LocalTime.of(dailyTipMinute / 60, dailyTipMinute % 60).format(TIME_FORMAT)}")}- if (!canPost) {- Text(- "Notifications are blocked for Gotcha, so no tips will be shown.",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.error- )- }- }+ )Spacer(Modifier.height(16.dp))Text(@@ -321,8 +272,6 @@ private fun CompletionPreviewRow(}}-private val TIME_FORMAT: DateTimeFormatter = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)-private fun formatRelative(epochMillis: Long): String {if (epochMillis <= 0L) return "never"val deltaMin = (System.currentTimeMillis() - epochMillis) / 60_000Ldiff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.ktindex e243335..d483555 100644--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt@@ -160,7 +160,7 @@ enum class SettingsPage(),NOTIFICATIONS("Notifications",- "How you're alerted when a reply arrives",+ "Replies, finished tasks, reminders and tips","settings_notifications_row"),ABOUT(diff --git a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.ktindex c2b7ffc..0730ff1 100644--- a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt@@ -112,7 +112,8 @@ private fun keywordsFor(page: SettingsPage): List<String> = when (page) {SettingsPage.NOTIFICATIONS -> words("""alerts, sound, vibrate, server messages, announcements, sync,- daily tip, tips, suggestions, ideas, reminder+ daily tip, tips, suggestions, ideas, reminder, reminders, unfinished, routine,+ inactivity, quiet hours, do not disturb, history, inbox, privacy""")SettingsPage.ABOUT -> words(diff --git a/app/src/test/java/com/gotcha/notifications/DailyTipNotifierTest.kt b/app/src/test/java/com/gotcha/notifications/DailyTipNotifierTest.ktdeleted file mode 100644index d2d256d..0000000--- a/app/src/test/java/com/gotcha/notifications/DailyTipNotifierTest.kt+++ /dev/null@@ -1,59 +0,0 @@-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 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--@RunWith(RobolectricTestRunner::class)-@Config(sdk = [34])-class DailyTipNotifierTest {-- private val application: Application = ApplicationProvider.getApplicationContext()- private val manager = application.getSystemService(NotificationManager::class.java)- private val tip = DAILY_TIPS.first()-- @Before- fun clearTray() {- manager.cancelAll()- }-- @Test- fun `posts the tip on its own channel, opening it on tap`() {- shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)- assertTrue(DailyTipNotifier(application).notify(tip))-- val notification = shadowOf(manager).allNotifications.single()- assertEquals(DailyTipNotifier.CHANNEL_ID, notification.channelId)- assertEquals(tip.title, notification.extras.getString(NotificationCompat.EXTRA_TITLE))- assertEquals(tip.body, notification.extras.getString(NotificationCompat.EXTRA_TEXT))- val intent = shadowOf(notification.contentIntent).savedIntent- assertEquals(tip.id, intent.getStringExtra(DailyTipNotifier.EXTRA_DAILY_TIP_ID))- }-- @Test- fun `a newer tip replaces the unread one`() {- shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)- DailyTipNotifier(application).notify(DAILY_TIPS[0])- DailyTipNotifier(application).notify(DAILY_TIPS[1])- val notification = shadowOf(manager).allNotifications.single()- assertEquals(DAILY_TIPS[1].title, notification.extras.getString(NotificationCompat.EXTRA_TITLE))- }-- @Test- fun `nothing is posted without the permission`() {- shadowOf(application).denyPermissions(Manifest.permission.POST_NOTIFICATIONS)- assertFalse(DailyTipNotifier(application).notify(tip))- assertTrue(shadowOf(manager).allNotifications.isEmpty())- }-}diff --git a/app/src/test/java/com/gotcha/notifications/LocalNotificationCheckTest.kt b/app/src/test/java/com/gotcha/notifications/LocalNotificationCheckTest.ktnew file mode 100644index 0000000..4df5d03--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/LocalNotificationCheckTest.kt@@ -0,0 +1,151 @@+package com.gotcha.notifications++import android.Manifest+import android.app.Application+import android.app.NotificationManager+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.ChatSession+import com.gotcha.data.RunSummary+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import com.gotcha.data.ToolSummary+import com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.coroutines.runBlocking+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotEquals+import org.junit.Assert.assertNotNull+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+import java.time.LocalDate+import java.time.ZoneId++/** What the alarms do when they fire: [runLocalNotificationCheck] (issues #100, #101). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LocalNotificationCheckTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private val manager = application.getSystemService(NotificationManager::class.java)+ private val zone = ZoneId.systemDefault()+ private val noon = LocalDate.now(zone).atTime(12, 0).atZone(zone).toInstant().toEpochMilli()++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ manager.cancelAll()+ shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)+ SettingsRepository(application).save(Settings())+ // Opened a week ago: long enough that reminders are allowed, and inactivity is due.+ LocalNotificationStore(application).setLastOpenedAt(noon - 7 * DAY_MS)+ }++ private fun chat(+ id: String,+ endedAt: Long,+ tools: List<String> = emptyList(),+ succeeded: Boolean = true,+ sample: Boolean = false,+ persona: String? = null+ ) = runBlocking {+ val run = RunSummary(+ startedAt = endedAt - 1_000,+ endedAt = endedAt,+ userPrompt = "p",+ finalReply = "r",+ model = "m",+ agentMode = "MONITOR",+ delegated = false,+ succeeded = succeeded,+ toolCalls = tools.map { ToolSummary(it, success = true, result = "") }+ )+ ChatHistoryRepository(application).saveSession(+ ChatSession(+ id = id,+ title = "Chat $id",+ lastModified = endedAt,+ messages = emptyList(),+ runSummaries = listOf(run),+ isSample = sample,+ personaId = persona+ ),+ touch = false+ )+ }++ private fun check(now: Long = noon, includeTip: Boolean = true) =+ runBlocking { runLocalNotificationCheck(application, now, includeTip) }++ @Test+ fun `sends one thing, files it in the inbox, and never the same tip twice running`() {+ LocalNotificationStore(application).setLastOpenedAt(noon - HOUR_MS * 3)+ val first = check()+ val second = check(noon + DAY_MS)+ assertEquals(NotificationCategory.DAILY_TIP, first?.category)+ assertNotEquals(first?.title, second?.title)+ assertEquals(2, LocalNotificationStore(application).entries().size)+ }++ @Test+ fun `nothing when turned off`() {+ SettingsRepository(application).save(Settings(localNotificationsEnabled = false))+ assertNull(check())+ assertTrue(shadowOf(manager).allNotifications.isEmpty())+ }++ @Test+ fun `an unfinished chat comes before the tip, on the reminders channel`() {+ chat("a", endedAt = noon - 3 * HOUR_MS, succeeded = false)+ // A run earlier today also means no tip.+ val sent = check()+ assertEquals(NotificationCategory.UNFINISHED_CHAT, sent?.category)+ assertEquals(NotificationTarget.Chat("a"), sent?.target)+ assertEquals(LocalNotifier.REMINDER_CHANNEL_ID, shadowOf(manager).allNotifications.single().channelId)+ }++ @Test+ fun `a doctor chat is never the subject of a reminder`() {+ chat("a", endedAt = noon - 3 * HOUR_MS, succeeded = false, persona = "doctor")+ // What's left is the inactivity nudge, which may not name the chat either.+ val sent = check()+ assertEquals(NotificationCategory.INACTIVITY, sent?.category)+ assertEquals(NotificationTarget.Home, sent?.target)+ }++ @Test+ fun `no reminders while Gotcha is in use`() {+ chat("a", endedAt = noon - 3 * HOUR_MS, succeeded = false)+ LocalNotificationStore(application).setLastOpenedAt(noon - HOUR_MS)+ assertNull(check())+ }++ @Test+ fun `nothing during quiet hours`() {+ val night = LocalDate.now(zone).atTime(23, 0).atZone(zone).toInstant().toEpochMilli()+ assertNull(check(night))+ }++ @Test+ fun `the daily cap holds across alarms`() {+ SettingsRepository(application).save(Settings(maxLocalNotificationsPerDay = 1))+ assertNotNull(check())+ chat("a", endedAt = noon - 3 * HOUR_MS, succeeded = false)+ assertNull(check(noon + HOUR_MS, includeTip = false))+ }++ @Test+ fun `tips favour tools not tried yet, and samples don't count as use`() {+ LocalNotificationStore(application).setLastOpenedAt(noon - HOUR_MS * 3)+ chat("sample", endedAt = noon - 1_000, sample = true)+ val tried = DAILY_TIPS.filter { it.id != "podcast" }.flatMap { it.tools }+ chat("old", endedAt = noon - 3 * DAY_MS, tools = tried)+ val podcast = DAILY_TIPS.single { it.id == "podcast" }+ assertEquals(podcast.title, check()?.title)+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/LocalNotificationStoreTest.kt b/app/src/test/java/com/gotcha/notifications/LocalNotificationStoreTest.ktnew file mode 100644index 0000000..8a53306--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/LocalNotificationStoreTest.kt@@ -0,0 +1,80 @@+package com.gotcha.notifications++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.tools.AgentMode+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LocalNotificationStoreTest {++ private val store = LocalNotificationStore(+ ApplicationProvider.getApplicationContext<Context>().getSharedPreferences("test_local", Context.MODE_PRIVATE)+ )+ private val now = 1_790_000_000_000L++ @Test+ fun `entries are listed newest first with their targets`() {+ store.addEntry(+ NotificationCategory.DAILY_TIP,+ "Tip",+ "b",+ NotificationTarget.Draft("p", AgentMode.OPERATOR),+ now = now+ )+ store.addEntry(NotificationCategory.TASK_FINISHED, "Done", "b", NotificationTarget.Chat("s"), now = now + 1)+ val entries = store.entries()+ assertEquals(listOf("Done", "Tip"), entries.map { it.title })+ assertEquals(NotificationTarget.Chat("s"), entries[0].target)+ assertEquals(NotificationTarget.Draft("p", AgentMode.OPERATOR), entries[1].target)+ assertEquals(NotificationCategory.DAILY_TIP, entries[1].categoryOrNull)+ }++ @Test+ fun `reading entries clears the unread count`() {+ val id = store.addEntry(NotificationCategory.SERVER, "a", "b", NotificationTarget.Home, now = now)+ store.addEntry(NotificationCategory.SERVER, "c", "d", NotificationTarget.Home, now = now)+ assertEquals(2, store.unreadCount())+ store.markRead(id)+ assertEquals(1, store.unreadCount())+ store.markAllRead()+ assertEquals(0, store.unreadCount())+ }++ @Test+ fun `entries older than 30 days drop out`() {+ store.addEntry(NotificationCategory.SERVER, "old", "b", NotificationTarget.Home, now = now - 31 * DAY_MS)+ store.addEntry(NotificationCategory.SERVER, "new", "b", NotificationTarget.Home, now = now)+ assertEquals(listOf("new"), store.entries().map { it.title })+ }++ @Test+ fun `clearing history keeps what was sent`() {+ val c = LocalCandidate(NotificationCategory.INACTIVITY, "k", "t", "b", NotificationTarget.Home)+ store.addEntry(c.category, c.title, c.body, c.target, now = now)+ store.recordSent(c, now)+ store.clearHistory()+ assertTrue(store.entries().isEmpty())+ assertEquals(listOf("k"), store.sent().map { it.key })+ }++ @Test+ fun `a chat choice overrides the persona default, and is forgotten with the chat`() {+ assertNull(store.chatChoice("s"))+ assertTrue(store.isChatSensitive("s", "doctor"))+ store.setChatKeptOut("s", false)+ assertFalse(store.isChatSensitive("s", "doctor"))+ store.setChatKeptOut("s", true)+ assertTrue(store.isChatSensitive("s", null))+ store.forgetChat("s")+ assertNull(store.chatChoice("s"))+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/LocalNotificationsTest.kt b/app/src/test/java/com/gotcha/notifications/LocalNotificationsTest.ktnew file mode 100644index 0000000..7f89853--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/LocalNotificationsTest.kt@@ -0,0 +1,248 @@+package com.gotcha.notifications++import com.gotcha.data.RunSummary+import com.gotcha.data.Settings+import com.gotcha.tools.AgentMode+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.time.ZoneId+import java.time.ZonedDateTime++/** The pure rules behind Gotcha's proactive notifications (issue #100). */+class LocalNotificationsTest {++ private val zone = ZoneId.of("Europe/Berlin")+ private val now = at(2026, 9, 24, 12)++ private fun at(y: Int, mo: Int, d: Int, h: Int, mi: Int = 0) =+ ZonedDateTime.of(y, mo, d, h, mi, 0, 0, zone).toInstant().toEpochMilli()++ private fun run(+ endedAt: Long,+ prompt: String = "p",+ reply: String = "Done.",+ succeeded: Boolean = true,+ mode: String = "MONITOR"+ ) = RunSummary(+ startedAt = endedAt - 1_000,+ endedAt = endedAt,+ userPrompt = prompt,+ finalReply = reply,+ model = "m",+ agentMode = mode,+ delegated = false,+ succeeded = succeeded+ )++ private fun chat(id: String, vararg runs: RunSummary, sensitive: Boolean = false) =+ ChatDigest(id = id, title = "Chat $id", sensitive = sensitive, runs = runs.toList())++ private fun candidate(category: NotificationCategory = NotificationCategory.ROUTINE, key: String = "k") =+ LocalCandidate(category, key, "t", "b", NotificationTarget.Home)++ // ---- quiet hours ----++ @Test+ fun `quiet hours wrap past midnight`() {+ assertTrue(inQuietHours(23 * 60, 22 * 60, 8 * 60))+ assertTrue(inQuietHours(7 * 60 + 59, 22 * 60, 8 * 60))+ assertFalse(inQuietHours(8 * 60, 22 * 60, 8 * 60))+ assertFalse(inQuietHours(12 * 60, 22 * 60, 8 * 60))+ }++ @Test+ fun `quiet hours within a day, and equal ends mean none`() {+ assertTrue(inQuietHours(13 * 60, 12 * 60, 14 * 60))+ assertFalse(inQuietHours(14 * 60, 12 * 60, 14 * 60))+ assertFalse(inQuietHours(3 * 60, 9 * 60, 9 * 60))+ }++ // ---- the gate ----++ @Test+ fun `an allowed candidate passes`() {+ assertNull(blockReason(candidate(), Settings(), emptyList(), now, zone))+ }++ @Test+ fun `the master and category switches block`() {+ assertEquals(+ "off",+ blockReason(candidate(), Settings(localNotificationsEnabled = false), emptyList(), now, zone)+ )+ assertEquals(+ "category_off",+ blockReason(candidate(), Settings(routineSuggestionsEnabled = false), emptyList(), now, zone)+ )+ }++ @Test+ fun `quiet hours block, unless turned off`() {+ val night = at(2026, 9, 24, 23)+ assertEquals("quiet_hours", blockReason(candidate(), Settings(), emptyList(), night, zone))+ assertNull(blockReason(candidate(), Settings(quietHoursEnabled = false), emptyList(), night, zone))+ }++ @Test+ fun `the same occasion is never sent twice`() {+ val sent = listOf(SentRecord("k", NotificationCategory.INACTIVITY.name, now - 10 * DAY_MS))+ assertEquals("duplicate", blockReason(candidate(key = "k"), Settings(), sent, now, zone))+ }++ @Test+ fun `one per category within the cooldown`() {+ val sent = listOf(SentRecord("other", NotificationCategory.ROUTINE.name, now - 5 * HOUR_MS))+ assertEquals("cooldown", blockReason(candidate(), Settings(), sent, now, zone))+ val old = listOf(SentRecord("other", NotificationCategory.ROUTINE.name, now - 21 * HOUR_MS))+ assertNull(blockReason(candidate(), Settings(), old, now, zone))+ }++ @Test+ fun `the daily cap counts today's sends across categories`() {+ val sent = listOf(+ SentRecord("a", NotificationCategory.DAILY_TIP.name, at(2026, 9, 24, 10)),+ SentRecord("b", NotificationCategory.INACTIVITY.name, at(2026, 9, 24, 11))+ )+ assertEquals("daily_cap", blockReason(candidate(), Settings(), sent, now, zone))+ assertNull(blockReason(candidate(), Settings(maxLocalNotificationsPerDay = 3), sent, now, zone))+ // Yesterday's don't count.+ val yesterday = sent.map { it.copy(at = it.at - DAY_MS) }+ assertNull(blockReason(candidate(), Settings(), yesterday, now, zone))+ }++ // ---- unfinished chats ----++ @Test+ fun `a failed run from a few hours ago is unfinished`() {+ val c = unfinishedChat(listOf(chat("a", run(now - 3 * HOUR_MS, succeeded = false))), mention = true, now)!!+ assertEquals(NotificationCategory.UNFINISHED_CHAT, c.category)+ assertEquals(NotificationTarget.Chat("a"), c.target)+ assertTrue(c.body.contains("Chat a"))+ }++ @Test+ fun `a reply ending on a question is unfinished`() {+ val c = unfinishedChat(listOf(chat("a", run(now - 3 * HOUR_MS, reply = "Which Priya?"))), true, now)!!+ assertEquals("Gotcha is waiting for you", c.title)+ }++ @Test+ fun `too fresh, too old, finished or superseded is not unfinished`() {+ assertNull(unfinishedChat(listOf(chat("a", run(now - HOUR_MS, succeeded = false))), true, now))+ assertNull(unfinishedChat(listOf(chat("a", run(now - 4 * DAY_MS, succeeded = false))), true, now))+ assertNull(unfinishedChat(listOf(chat("a", run(now - 3 * HOUR_MS))), true, now))+ // Only the chat's last run counts: a later success finished it.+ val later = chat("a", run(now - 5 * HOUR_MS, succeeded = false), run(now - 3 * HOUR_MS))+ assertNull(unfinishedChat(listOf(later), true, now))+ }++ @Test+ fun `without mentions the text names no chat`() {+ val c = unfinishedChat(listOf(chat("a", run(now - 3 * HOUR_MS, succeeded = false))), mention = false, now)!!+ assertFalse(c.body.contains("Chat a"))+ assertEquals(NotificationTarget.Chat("a"), c.target)+ }++ // ---- routines ----++ private fun weekly(prompt: String, weeksAgo: List<Int>, mode: String = "MONITOR") =+ weeksAgo.map { run(now - it * 7 * DAY_MS - HOUR_MS, prompt = prompt, mode = mode) }++ @Test+ fun `a weekly request is due a week after the last`() {+ val runs = weekly("Summarise my unread emails from 9 to 5", listOf(1, 2, 3), mode = "OPERATOR")+ val c = dueRoutine(listOf(chat("a", *runs.toTypedArray())), mention = true, now, zone)!!+ assertEquals(NotificationCategory.ROUTINE, c.category)+ assertEquals(+ NotificationTarget.Draft("Summarise my unread emails from 9 to 5", AgentMode.OPERATOR),+ c.target+ )+ assertTrue(c.body.contains("Summarise my unread emails"))+ }++ @Test+ fun `numbers don't stop requests matching`() {+ val runs = listOf(+ run(now - 7 * DAY_MS, prompt = "Set an alarm for 7am"),+ run(now - 14 * DAY_MS, prompt = "set an alarm for 6am!"),+ run(now - 21 * DAY_MS, prompt = "Set an alarm for 7:30am")+ )+ assertTrue(dueRoutine(listOf(chat("a", *runs.toTypedArray())), true, now, zone) != null)+ }++ @Test+ fun `not due early, not nagged when long abandoned, not from two days`() {+ // Weekly, but the last time was only four days ago.+ val early = listOf(4, 11, 18).map { run(now - it * DAY_MS, prompt = "Summarise my unread emails") }+ assertNull(dueRoutine(listOf(chat("a", *early.toTypedArray())), true, now, zone))+ val stale = weekly("Summarise my unread emails", listOf(4, 5, 6))+ assertNull(dueRoutine(listOf(chat("a", *stale.toTypedArray())), true, now, zone))+ val twice = weekly("Summarise my unread emails", listOf(1, 2))+ assertNull(dueRoutine(listOf(chat("a", *twice.toTypedArray())), true, now, zone))+ }++ @Test+ fun `short requests are not routines`() {+ assertEquals("", routineKey("hi"))+ assertEquals("", routineKey("What's 2+2?"))+ }++ // ---- inactivity ----++ @Test+ fun `a reminder after the chosen number of days, once per spell`() {+ val opened = now - 5 * DAY_MS+ val c = inactivityReminder(listOf(chat("a", run(opened))), opened, 4, mention = true, now)!!+ assertEquals("inactive:$opened", c.dedupKey)+ assertEquals(NotificationTarget.Chat("a"), c.target)+ assertNull(inactivityReminder(emptyList(), now - 3 * DAY_MS, 4, true, now))+ assertNull(inactivityReminder(emptyList(), 0L, 4, true, now))+ }++ @Test+ fun `without mentions the reminder goes home`() {+ val opened = now - 5 * DAY_MS+ val c = inactivityReminder(listOf(chat("a", run(opened))), opened, 4, mention = false, now)!!+ assertEquals(NotificationTarget.Home, c.target)+ assertFalse(c.body.contains("Chat a"))+ }++ // ---- ordering and sensitive chats ----++ @Test+ fun `unfinished beats routine beats inactivity`() {+ val opened = now - 5 * DAY_MS+ val chats = listOf(+ chat("u", run(now - 3 * HOUR_MS, succeeded = false)),+ chat("r", *weekly("Summarise my unread emails", listOf(1, 2, 3)).toTypedArray())+ )+ val all = behaviorCandidates(chats, opened, 4, true, now, zone)+ assertEquals(+ listOf(NotificationCategory.UNFINISHED_CHAT, NotificationCategory.ROUTINE, NotificationCategory.INACTIVITY),+ all.map { it.category }+ )+ }++ @Test+ fun `sensitive chats are never used`() {+ val opened = now - 5 * DAY_MS+ val chats = listOf(+ chat("u", run(now - 3 * HOUR_MS, succeeded = false), sensitive = true),+ chat("r", *weekly("Summarise my unread emails", listOf(1, 2, 3)).toTypedArray(), sensitive = true)+ )+ val all = behaviorCandidates(chats, opened, 4, true, now, zone)+ assertEquals(listOf(NotificationCategory.INACTIVITY), all.map { it.category })+ assertEquals(NotificationTarget.Home, all.single().target)+ }++ @Test+ fun `doctor chats are sensitive unless the user says otherwise`() {+ assertTrue(isChatSensitive("doctor", null))+ assertFalse(isChatSensitive("doctor", false))+ assertFalse(isChatSensitive("chef", null))+ assertTrue(isChatSensitive(null, true))+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/LocalNotifierTest.kt b/app/src/test/java/com/gotcha/notifications/LocalNotifierTest.ktnew file mode 100644index 0000000..34c1295--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/LocalNotifierTest.kt@@ -0,0 +1,79 @@+package com.gotcha.notifications++import android.Manifest+import android.app.Application+import android.app.Notification+import android.app.NotificationManager+import androidx.core.app.NotificationCompat+import androidx.test.core.app.ApplicationProvider+import com.gotcha.testsupport.FakeAndroidKeyStore+import com.gotcha.tools.AgentMode+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++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class LocalNotifierTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private val manager = application.getSystemService(NotificationManager::class.java)+ private lateinit var store: LocalNotificationStore++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ manager.cancelAll()+ store = LocalNotificationStore(application)+ }++ private fun grant() = shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)++ @Test+ fun `a tip opens a drafted chat and marks its inbox entry read`() {+ grant()+ val tip = DAILY_TIPS.single { it.id == "do_not_disturb" }+ assertTrue(LocalNotifier(application).post(tipCandidate(tip, 0L, java.time.ZoneOffset.UTC), store))++ val notification = shadowOf(manager).allNotifications.single()+ assertEquals(LocalNotifier.TIP_CHANNEL_ID, notification.channelId)+ assertEquals(tip.title, notification.extras.getString(NotificationCompat.EXTRA_TITLE))+ val intent = shadowOf(notification.contentIntent).savedIntent+ assertEquals(tip.prompt, intent.getStringExtra(LocalNotifier.EXTRA_DRAFT_PROMPT))+ assertEquals(AgentMode.OPERATOR.name, intent.getStringExtra(LocalNotifier.EXTRA_DRAFT_MODE))+ assertEquals(store.entries().single().id, intent.getStringExtra(LocalNotificationStore.EXTRA_INBOX_ENTRY_ID))+ }++ @Test+ fun `a reminder opens its chat and stays private on the lock screen`() {+ grant()+ val reminder = LocalCandidate(+ NotificationCategory.UNFINISHED_CHAT,+ "k",+ "Finish what you started",+ "“Plan” stopped",+ NotificationTarget.Chat("s")+ )+ LocalNotifier(application).post(reminder, store)+ val notification = shadowOf(manager).allNotifications.single()+ assertEquals(LocalNotifier.REMINDER_CHANNEL_ID, notification.channelId)+ assertEquals(Notification.VISIBILITY_PRIVATE, notification.visibility)+ val intent = shadowOf(notification.contentIntent).savedIntent+ assertEquals("s", intent.getStringExtra(ChatCompletionNotifier.EXTRA_OPEN_SESSION_ID))+ }++ @Test+ fun `nothing is posted or filed without the permission`() {+ shadowOf(application).denyPermissions(Manifest.permission.POST_NOTIFICATIONS)+ val tip = tipCandidate(DAILY_TIPS.first(), 0L, java.time.ZoneOffset.UTC)+ assertFalse(LocalNotifier(application).post(tip, store))+ assertTrue(shadowOf(manager).allNotifications.isEmpty())+ assertTrue(store.entries().isEmpty())+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/PostDailyTipTest.kt b/app/src/test/java/com/gotcha/notifications/PostDailyTipTest.ktdeleted file mode 100644index 6b713e8..0000000--- a/app/src/test/java/com/gotcha/notifications/PostDailyTipTest.kt+++ /dev/null@@ -1,101 +0,0 @@-package com.gotcha.notifications--import android.Manifest-import android.app.Application-import android.app.NotificationManager-import androidx.test.core.app.ApplicationProvider-import com.gotcha.data.ChatHistoryRepository-import com.gotcha.data.ChatSession-import com.gotcha.data.RunSummary-import com.gotcha.data.Settings-import com.gotcha.data.SettingsRepository-import com.gotcha.data.ToolSummary-import com.gotcha.testsupport.FakeAndroidKeyStore-import kotlinx.coroutines.runBlocking-import org.junit.Assert.assertEquals-import org.junit.Assert.assertNotEquals-import org.junit.Assert.assertNotNull-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--/** What the alarm does when it fires: [postDailyTip] (issue #101). */-@RunWith(RobolectricTestRunner::class)-@Config(sdk = [34])-class PostDailyTipTest {-- private val application: Application = ApplicationProvider.getApplicationContext()- private val manager = application.getSystemService(NotificationManager::class.java)- private val day = 24L * 3600_000L- private val now = System.currentTimeMillis()-- @Before- fun setUp() {- FakeAndroidKeyStore.setUp()- manager.cancelAll()- shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)- SettingsRepository(application).save(Settings())- }-- private fun chat(id: String, endedAt: Long, tools: List<String>, sample: Boolean = false) = runBlocking {- val run = RunSummary(- startedAt = endedAt - 1_000,- endedAt = endedAt,- userPrompt = "p",- finalReply = "r",- model = "m",- agentMode = "MONITOR",- delegated = false,- succeeded = true,- toolCalls = tools.map { ToolSummary(it, success = true, result = "") }- )- ChatHistoryRepository(application).saveSession(- ChatSession(- id = id,- title = id,- lastModified = endedAt,- messages = emptyList(),- runSummaries = listOf(run),- isSample = sample- ),- touch = false- )- }-- @Test- fun `posts a tip and remembers it, so the next day's differs`() = runBlocking {- val first = postDailyTip(application, now)- val second = postDailyTip(application, now + day)- assertNotNull(first)- assertNotNull(second)- assertNotEquals(first?.id, second?.id)- assertEquals(1, shadowOf(manager).allNotifications.size)- }-- @Test- fun `nothing when tips are off`() = runBlocking {- SettingsRepository(application).save(Settings(dailyTipsEnabled = false))- assertNull(postDailyTip(application, now))- assertTrue(shadowOf(manager).allNotifications.isEmpty())- }-- @Test- fun `nothing on a day Gotcha was already used`() = runBlocking {- chat("today", endedAt = now - 1_000, tools = listOf("read_screen"))- assertNull(postDailyTip(application, now))- }-- @Test- fun `a sample chat is not use, and tools used before are passed over`() = runBlocking {- chat("sample", endedAt = now - 1_000, tools = emptyList(), sample = true)- // Every tool but the podcast ones has been run, long ago.- val tried = DAILY_TIPS.filter { it.id != "podcast" }.flatMap { it.tools }- chat("old", endedAt = now - 7 * day, tools = tried)- assertEquals("podcast", postDailyTip(application, now)?.id)- }-}