Skip to content

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

feat(notifications): send a daily tip that opens a pre-filled chat (#101)

Durganshuf92ab21b6f4e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4f35c48..28c9a6f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,15 @@ All notable changes to Gotcha are documented here.
## [Unreleased]
### Added
+- **Daily tips** (#101). Once a day, at 10:00 by default, Gotcha sends a
+ notification suggesting one thing to try: reading your screen, catching up
+ on notifications, texting someone, planning the day. Tapping it opens a new
+ chat with the prompt already in the composer, to edit or send as it is. Tips
+ for tools you have never used come first, none repeats until ten others have
+ been shown, and no tip is sent on a day you have already used Gotcha. Tips for
+ device actions start the chat in Operator. On by default; Settings →
+ Notifications turns tips off or changes the time, and they have their own
+ "Daily tips" channel in Android's settings.
- **The assistant can change Gotcha's settings, with your approval every
time** (#99). Ask it to turn off the reply chime, switch the skin, stop
scanning the clipboard or turn a connector off, and it proposes the change
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml
index 219615f..527a68f 100644
--- a/app/src/main/AndroidManifest.xml
+++ b/app/src/main/AndroidManifest.xml
@@ -250,6 +250,26 @@
</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. -->
+ <receiver
+ android:name=".notifications.DailyTipAlarmReceiver"
+ 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. -->
+ <receiver
+ android:name=".notifications.DailyTipReceiver"
+ android:exported="true">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
+ <action android:name="android.intent.action.TIMEZONE_CHANGED" />
+ <action android:name="android.intent.action.TIME_SET" />
+ </intent-filter>
+ </receiver>
+
<receiver
android:name=".tools.WakeWordBootReceiver"
android:exported="true">
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.kt
index 87a8e10..d48e273 100644
--- a/app/src/main/java/com/gotcha/MainActivity.kt
+++ b/app/src/main/java/com/gotcha/MainActivity.kt
@@ -50,6 +50,10 @@ import com.gotcha.data.computeFeedbackStats
import com.gotcha.llm.ChatMessage
import com.gotcha.llm.LLMClient
import 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.NotificationDispatcher
import com.gotcha.notifications.NotificationPayload
import com.gotcha.notifications.ServerMessages
@@ -135,6 +139,9 @@ 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)
+
/** Set when brought to front by the assistive ball (Operator-origin chats). */
private var openedFromBall by mutableStateOf(false)
@@ -289,6 +296,12 @@ class MainActivity : ComponentActivity() {
openedFromBall = intent?.getBooleanExtra(EXTRA_FROM_ASSISTIVE_BALL, false) == true
handleNotificationIntent(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.
+ lifecycleScope.launch(Dispatchers.IO) {
+ runCatching { DailyTipScheduler.schedule(applicationContext) }
+ }
+
// Tools report what they need the moment they need it. A special-access
// marker opens the Settings screen that grants it; a runtime permission
// travels through the view model instead, as a pending ask the dialog in
@@ -513,6 +526,12 @@ 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 }
+ // Consumed, as above: a recreation must not open another chat.
+ intent.removeExtra(DailyTipNotifier.EXTRA_DAILY_TIP_ID)
+ }
val title = intent?.getStringExtra(NotificationDispatcher.EXTRA_NOTIFICATION_TITLE)
val body = intent?.getStringExtra(NotificationDispatcher.EXTRA_NOTIFICATION_BODY)
if (!title.isNullOrBlank() || !body.isNullOrBlank()) {
@@ -712,6 +731,15 @@ class MainActivity : ComponentActivity() {
}
}
+ // A tapped daily tip: a new chat, in the tip's mode, with its prompt drafted.
+ LaunchedEffect(openTipRequested) {
+ openTipRequested?.let { tip ->
+ currentRoute = Route.HOME
+ chatViewModel.startChatFromTip(tip.prompt, tip.agent)
+ openTipRequested = null
+ }
+ }
+
// Honor the assistive ball's "Open Chat" option.
LaunchedEffect(openChatRequested) {
if (openChatRequested) {
@@ -933,6 +961,7 @@ class MainActivity : ComponentActivity() {
onSwitchAgent = chatViewModel::switchAgent,
onSetAgent = chatViewModel::setAgent,
onSetPersona = chatViewModel::setPersona,
+ onComposerDraftConsumed = chatViewModel::consumeComposerDraft,
onSpeak = chatViewModel::speak,
onStopSpeaking = chatViewModel::stopSpeaking,
onStartListening = chatViewModel::startListening,
diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
index 9cf964d..4c59785 100644
--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt
@@ -223,7 +223,13 @@ data class ChatUiState(
* than in the composer's saved state: several base64 images would overflow
* the saved-instance Bundle.
*/
- val pendingAttachments: List<ComposerAttachment> = emptyList()
+ val pendingAttachments: List<ComposerAttachment> = emptyList(),
+ /**
+ * Text to put in the composer once, e.g. a tapped daily tip's prompt (issue
+ * #101). The composer owns its text, so this is a hand-off: the screen copies
+ * it in and calls [ChatViewModel.consumeComposerDraft]. Never sent by itself.
+ */
+ val composerDraft: String? = null
)
// In-app chat host: session/UI state, dialogs, and TTS/STT wiring. The agent
@@ -836,6 +842,28 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), A
}
}
+ /**
+ * Opens a new chat for a tapped daily tip (issue #101): in the tip's mode —
+ * a fresh chat has no earlier choice of mode to override — and with its
+ * prompt in the composer for the user to edit or send. Waits for startup
+ * like [openSessionFromNotification]. Without an API key the composer is
+ * disabled, so the chat opens without the draft.
+ */
+ fun startChatFromTip(prompt: String, mode: AgentMode) {
+ viewModelScope.launch {
+ initJob.join()
+ clearChat(mode)
+ if (_uiState.value.isConfigured) {
+ _uiState.update { it.copy(composerDraft = prompt) }
+ }
+ }
+ }
+
+ /** The composer has taken [ChatUiState.composerDraft]. */
+ fun consumeComposerDraft() {
+ _uiState.update { it.copy(composerDraft = null) }
+ }
+
/**
* Replaces the user message [targetId] with [newText] and [attachments]; a
* null [attachments] keeps the ones the original message was sent with. The target's whole turn and
diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
index 9e1c41d..edd72e3 100644
--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt
+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt
@@ -49,6 +49,9 @@ enum class WakeWordListeningMode {
*/
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
+
/**
* The budget before [DEFAULT_MAX_CONTEXT_TOKENS] was raised. A stored copy of
* exactly this value is lifted once by [SettingsRepository.resolvedMaxContextTokens];
@@ -132,6 +135,14 @@ data class Settings(
*/
val chatCompletionNotificationsEnabled: Boolean = true,
val chatCompletionPreview: CompletionPreview = CompletionPreview.SHORT,
+ /**
+ * A daily notification suggesting one thing to try, which opens a new chat
+ * with that prompt ready to send (issue #101). On by default; off in
+ * Settings → Notifications.
+ */
+ val dailyTipsEnabled: Boolean = true,
+ /** When the daily tip arrives, as minutes after local midnight. */
+ val dailyTipMinuteOfDay: Int = DEFAULT_DAILY_TIP_MINUTE,
val assistiveBallEnabled: Boolean = false,
val wakeWordEnabled: Boolean = false,
val wakeWordSensitivity: Float = 0.75f,
@@ -523,6 +534,8 @@ class SettingsRepository(context: Context) : SettingsStore {
chatCompletionPreview = runCatching {
CompletionPreview.valueOf(string(KEY_CHAT_COMPLETION_PREVIEW, "SHORT"))
}.getOrDefault(CompletionPreview.SHORT),
+ dailyTipsEnabled = prefs.getBoolean(KEY_DAILY_TIPS, true),
+ dailyTipMinuteOfDay = prefs.getInt(KEY_DAILY_TIP_MINUTE, DEFAULT_DAILY_TIP_MINUTE),
assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false),
wakeWordEnabled = prefs.getBoolean(KEY_WAKE_WORD_ENABLED, false),
wakeWordSensitivity = prefs.getFloat(KEY_WAKE_WORD_SENSITIVITY, 0.75f),
@@ -600,6 +613,8 @@ class SettingsRepository(context: Context) : SettingsStore {
.putBoolean(KEY_NOTIFY_CHIME, settings.notifyChimeEnabled)
.putBoolean(KEY_CHAT_COMPLETION_NOTIFICATIONS, settings.chatCompletionNotificationsEnabled)
.putString(KEY_CHAT_COMPLETION_PREVIEW, settings.chatCompletionPreview.name)
+ .putBoolean(KEY_DAILY_TIPS, settings.dailyTipsEnabled)
+ .putInt(KEY_DAILY_TIP_MINUTE, settings.dailyTipMinuteOfDay)
.putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled)
.putBoolean(KEY_WAKE_WORD_ENABLED, settings.wakeWordEnabled)
.putFloat(KEY_WAKE_WORD_SENSITIVITY, settings.wakeWordSensitivity)
@@ -715,6 +730,8 @@ class SettingsRepository(context: Context) : SettingsStore {
const val KEY_NOTIFY_CHIME = "notify_chime"
const val KEY_CHAT_COMPLETION_NOTIFICATIONS = "chat_completion_notifications"
const val KEY_CHAT_COMPLETION_PREVIEW = "chat_completion_preview"
+ const val KEY_DAILY_TIPS = "daily_tips_enabled"
+ const val KEY_DAILY_TIP_MINUTE = "daily_tip_minute_of_day"
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/DailyTip.kt b/app/src/main/java/com/gotcha/notifications/DailyTip.kt
new file mode 100644
index 0000000..39c8bd9
--- /dev/null
+++ b/app/src/main/java/com/gotcha/notifications/DailyTip.kt
@@ -0,0 +1,208 @@
+package com.gotcha.notifications
+
+import com.gotcha.tools.AgentMode
+import java.time.LocalDate
+import java.time.LocalTime
+import java.time.ZoneId
+import java.time.ZonedDateTime
+import kotlin.random.Random
+
+/**
+ * One use case the daily tip notification can suggest (issue #101).
+ *
+ * [title] and [body] are what the notification says; [prompt] is what lands in
+ * the composer of the new chat a tap opens. Like the home-screen starters it is
+ * a draft, not a request: the user edits and sends, so it may carry an unfilled
+ * `…` where a name or a message belongs.
+ *
+ * [tools] are the tools the use case leans on. A tip whose tools the user has
+ * never run is preferred, so the tip shows them something new. [agent] is the
+ * mode the new chat starts in: the device actions need Operator, and a fresh
+ * chat opened for them has no earlier choice of mode to override.
+ */
+data class DailyTip(
+ val id: String,
+ val title: String,
+ val body: String,
+ val prompt: String,
+ val tools: Set<String>,
+ val agent: AgentMode = AgentMode.MONITOR
+)
+
+/** The use cases a daily tip is drawn from. Ids are persisted, so keep them stable. */
+val DAILY_TIPS = listOf(
+ DailyTip(
+ id = "read_screen",
+ title = "Ask about your screen",
+ body = "Stuck on something? Gotcha can read your screen and explain it.",
+ prompt = "What's on my screen?",
+ tools = setOf("read_screen")
+ ),
+ DailyTip(
+ id = "catch_up",
+ title = "Catch up in seconds",
+ body = "Let Gotcha sum up your unread notifications.",
+ prompt = "Catch me up on my unread notifications",
+ tools = setOf("read_notifications")
+ ),
+ DailyTip(
+ id = "big_files",
+ title = "Free up some space",
+ body = "Gotcha can find your largest files and tell you what's safe to delete.",
+ prompt = "Find the largest files in my Downloads folder and tell me what's safe to delete",
+ tools = setOf("list_files", "get_storage_info")
+ ),
+ DailyTip(
+ id = "summarise_pdf",
+ title = "Summarise a PDF",
+ body = "No time to read it? Gotcha can summarise your latest PDF.",
+ prompt = "Read the most recent PDF in my Downloads and summarise it",
+ tools = setOf("read_file")
+ ),
+ DailyTip(
+ id = "calendar_today",
+ title = "Plan your day",
+ body = "Ask Gotcha what's on your calendar today.",
+ prompt = "What's on my calendar today?",
+ tools = setOf("list_calendar_events")
+ ),
+ DailyTip(
+ id = "calendar_add",
+ title = "Add to your calendar",
+ body = "Tell Gotcha about a plan and it goes straight into your calendar.",
+ prompt = "Add lunch with … on Friday at 1pm to my calendar",
+ tools = setOf("create_calendar_event"),
+ agent = AgentMode.OPERATOR
+ ),
+ DailyTip(
+ id = "set_alarm",
+ title = "Set an alarm by asking",
+ body = "Gotcha can set alarms and timers for you.",
+ prompt = "Set an alarm for 7am tomorrow",
+ tools = setOf("set_alarm", "set_timer"),
+ agent = AgentMode.OPERATOR
+ ),
+ DailyTip(
+ id = "send_whatsapp",
+ title = "Send a WhatsApp hands-free",
+ body = "Gotcha can open WhatsApp and send the message for you.",
+ prompt = "Send a WhatsApp to … saying …",
+ tools = setOf("navigate_app"),
+ agent = AgentMode.OPERATOR
+ ),
+ DailyTip(
+ id = "send_sms",
+ title = "Running late?",
+ body = "Gotcha can text someone for you.",
+ prompt = "Text … that I'm running 10 minutes late",
+ tools = setOf("send_sms"),
+ agent = AgentMode.OPERATOR
+ ),
+ DailyTip(
+ id = "recent_sms",
+ title = "Skim your messages",
+ body = "Gotcha can summarise your latest texts.",
+ prompt = "Summarise my latest text messages",
+ tools = setOf("read_recent_sms")
+ ),
+ DailyTip(
+ id = "missed_calls",
+ title = "Who called?",
+ body = "Ask Gotcha to go through your call log.",
+ prompt = "Who called me today?",
+ tools = setOf("read_call_log")
+ ),
+ DailyTip(
+ id = "battery",
+ title = "What's draining your battery?",
+ body = "Gotcha can check your battery and which apps use it most.",
+ prompt = "Check my battery and tell me which apps have been using the most",
+ tools = setOf("get_battery_info", "get_app_usage")
+ ),
+ DailyTip(
+ id = "screen_time",
+ title = "Check your screen time",
+ body = "Ask Gotcha how long you spent on your phone, and where.",
+ prompt = "How much time did I spend on my phone today, and on which apps?",
+ tools = setOf("get_app_usage")
+ ),
+ DailyTip(
+ id = "web_search",
+ title = "Research anything",
+ body = "Gotcha can search the web and sum up what it finds.",
+ prompt = "Search the web for … and summarise what you find",
+ tools = setOf("websearch", "webfetch")
+ ),
+ DailyTip(
+ id = "do_not_disturb",
+ title = "Need to focus?",
+ body = "Gotcha can turn on Do Not Disturb for you.",
+ prompt = "Turn on Do Not Disturb for the next hour",
+ tools = setOf("set_dnd"),
+ agent = AgentMode.OPERATOR
+ ),
+ DailyTip(
+ id = "wifi",
+ title = "Change settings by asking",
+ body = "Gotcha can find and flip settings for you, like Wi-Fi.",
+ prompt = "Open settings and turn on Wi-Fi",
+ tools = setOf("toggle_wifi", "open_setting"),
+ agent = AgentMode.OPERATOR
+ ),
+ DailyTip(
+ id = "podcast",
+ title = "Listen instead of reading",
+ body = "Gotcha can turn a document into a short podcast.",
+ prompt = "Turn the most recent PDF in my Downloads into a short podcast",
+ tools = setOf("synthesize_podcast", "synthesize_podcast_dialogue"),
+ agent = AgentMode.OPERATOR
+ )
+)
+
+/** How many recently shown tips are kept out of the draw. */
+internal const val RECENT_TIP_MEMORY = 10
+
+/**
+ * Chooses the day's tip. Pure, so the rules are unit tested:
+ * 1. tips in [recentIds] are skipped, so a week never repeats one;
+ * 2. of the rest, tips whose tools the user has never run ([usedTools]) win;
+ * 3. ties are broken at random.
+ * When every tip is recent, the draw starts over, still avoiding yesterday's.
+ */
+internal fun pickDailyTip(
+ tips: List<DailyTip>,
+ recentIds: List<String>,
+ usedTools: Set<String>,
+ random: Random = Random.Default
+): DailyTip? {
+ if (tips.isEmpty()) return null
+ val fresh = tips.filter { it.id !in recentIds }
+ .ifEmpty { tips.filter { it.id != recentIds.lastOrNull() } }
+ .ifEmpty { tips }
+ val untried = fresh.filter { tip -> tip.tools.none { it in usedTools } }
+ return untried.ifEmpty { fresh }.random(random)
+}
+
+/** [recentIds] with [shownId] appended, trimmed to the newest [RECENT_TIP_MEMORY]. */
+internal fun rememberShownTip(recentIds: List<String>, shownId: String): List<String> =
+ (recentIds.filter { it != shownId } + shownId).takeLast(RECENT_TIP_MEMORY)
+
+/**
+ * Epoch millis of the next [minuteOfDay] strictly after [now] in [zone]. Built
+ * from the local date and time rather than by adding 24 hours, so a daylight
+ * saving change keeps the tip at the same time on the clock.
+ */
+internal fun nextDailyTipAt(nowMillis: Long, minuteOfDay: Int, zone: ZoneId): Long {
+ val now = ZonedDateTime.ofInstant(java.time.Instant.ofEpochMilli(nowMillis), zone)
+ val time = LocalTime.of(minuteOfDay / 60 % 24, minuteOfDay % 60)
+ val today = ZonedDateTime.of(now.toLocalDate(), time, zone)
+ val next = if (today.isAfter(now)) today else ZonedDateTime.of(now.toLocalDate().plusDays(1), time, zone)
+ return next.toInstant().toEpochMilli()
+}
+
+/** True when [lastActiveMillis] falls on the same local day as [nowMillis]. */
+internal fun usedToday(lastActiveMillis: Long?, nowMillis: Long, zone: ZoneId): Boolean {
+ if (lastActiveMillis == null) return false
+ fun day(millis: Long): LocalDate = java.time.Instant.ofEpochMilli(millis).atZone(zone).toLocalDate()
+ return day(lastActiveMillis) == day(nowMillis)
+}
diff --git a/app/src/main/java/com/gotcha/notifications/DailyTipNotifier.kt b/app/src/main/java/com/gotcha/notifications/DailyTipNotifier.kt
new file mode 100644
index 0000000..ce3f01c
--- /dev/null
+++ b/app/src/main/java/com/gotcha/notifications/DailyTipNotifier.kt
@@ -0,0 +1,72 @@
+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.kt
new file mode 100644
index 0000000..f022c92
--- /dev/null
+++ b/app/src/main/java/com/gotcha/notifications/DailyTipScheduler.kt
@@ -0,0 +1,136 @@
+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/tools/GotchaSettingsUpdate.kt b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
index f40ecec..40ab76d 100644
--- a/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
+++ b/app/src/main/java/com/gotcha/tools/GotchaSettingsUpdate.kt
@@ -183,6 +183,13 @@ 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",
diff --git a/app/src/main/java/com/gotcha/ui/ChatScreen.kt b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
index b23bda9..322bb96 100644
--- a/app/src/main/java/com/gotcha/ui/ChatScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ChatScreen.kt
@@ -114,7 +114,8 @@ fun ChatScreen(
onReturnToRunning: () -> Unit = {},
onCreateShareCard: () -> Unit = {},
onEditMessage: (Long, String, List<ComposerAttachment>) -> Unit = { _, _, _ -> },
- onRevertMessage: (Long) -> Unit = { _ -> }
+ onRevertMessage: (Long) -> Unit = { _ -> },
+ onComposerDraftConsumed: () -> Unit = {}
) {
val skin = LocalSkin.current
val isHome = state.messages.isEmpty()
@@ -129,6 +130,15 @@ fun ChatScreen(
var editingMessageId by rememberSaveable { mutableStateOf<Long?>(null) }
// Id of the user message pending a revert confirmation.
var pendingRevertId by remember { mutableStateOf<Long?>(null) }
+ // A draft handed over by the view model (a tapped daily tip): fill, never send.
+ LaunchedEffect(state.composerDraft) {
+ state.composerDraft?.let { draft ->
+ input = draft
+ inputWasVoice = false
+ editingMessageId = null
+ onComposerDraftConsumed()
+ }
+ }
val listState = rememberLazyListState()
// Everything already in the transcript when this chat opened is history, and
diff --git a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt
index 8acbda7..0e1201b 100644
--- a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt
@@ -1,8 +1,10 @@
package com.gotcha.ui
+import android.app.TimePickerDialog
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Build
+import android.text.format.DateFormat
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Column
@@ -37,13 +39,17 @@ import com.gotcha.audio.CompletionFeedback
import com.gotcha.data.CompletionPreview
import com.gotcha.data.Settings
import com.gotcha.notifications.ChatCompletionNotifier
+import com.gotcha.notifications.DailyTipScheduler
import kotlinx.coroutines.launch
+import java.time.LocalTime
+import java.time.format.DateTimeFormatter
+import java.time.format.FormatStyle
import android.provider.Settings as AndroidSettings
/**
* The Notifications page: what the phone does the moment a reply arrives
- * (vibration/chime) plus server-driven messages from the Samosa team
- * (updates, tips, maintenance).
+ * (vibration/chime), the task-finished and daily tip notifications, 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
@@ -62,6 +68,8 @@ 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) }
@@ -176,6 +184,59 @@ 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) {
+ 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(
"Server messages",
@@ -260,6 +321,8 @@ 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_000L
diff --git a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
index b7233af..c2b7ffc 100644
--- a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
+++ b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt
@@ -111,7 +111,8 @@ private fun keywordsFor(page: SettingsPage): List<String> = when (page) {
)
SettingsPage.NOTIFICATIONS -> words(
"""
- alerts, sound, vibrate, server messages, announcements, sync
+ alerts, sound, vibrate, server messages, announcements, sync,
+ daily tip, tips, suggestions, ideas, reminder
"""
)
SettingsPage.ABOUT -> words(
diff --git a/app/src/test/java/com/gotcha/agent/ChatViewModelTipDraftTest.kt b/app/src/test/java/com/gotcha/agent/ChatViewModelTipDraftTest.kt
new file mode 100644
index 0000000..9b8fa7c
--- /dev/null
+++ b/app/src/test/java/com/gotcha/agent/ChatViewModelTipDraftTest.kt
@@ -0,0 +1,80 @@
+package com.gotcha.agent
+
+import android.app.Application
+import androidx.test.core.app.ApplicationProvider
+import com.gotcha.data.LlmProvider
+import com.gotcha.data.Settings
+import com.gotcha.data.SettingsRepository
+import com.gotcha.testsupport.FakeAndroidKeyStore
+import com.gotcha.tools.AgentMode
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertNotEquals
+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
+import org.robolectric.shadows.ShadowLooper
+
+/** A tapped daily tip opens a new chat with its prompt drafted, not sent (issue #101). */
+@RunWith(RobolectricTestRunner::class)
+@Config(sdk = [34])
+class ChatViewModelTipDraftTest {
+
+ private val application: Application = ApplicationProvider.getApplicationContext()
+
+ private fun viewModel(configured: Boolean = true): ChatViewModel {
+ FakeAndroidKeyStore.setUp()
+ SettingsRepository(application).save(
+ Settings(
+ provider = LlmProvider.OPENAI_COMPATIBLE,
+ apiKey = "test-key",
+ // An OpenAI-compatible provider counts as configured once it has a base URL.
+ baseUrl = if (configured) "http://127.0.0.1:1/v1" else ""
+ )
+ )
+ return ChatViewModel(application).also { ShadowLooper.idleMainLooper() }
+ }
+
+ private fun idleUntil(condition: () -> Boolean) {
+ val deadline = System.currentTimeMillis() + 5_000
+ ShadowLooper.idleMainLooper()
+ while (System.currentTimeMillis() < deadline && !condition()) {
+ ShadowLooper.idleMainLooper()
+ Thread.sleep(10)
+ }
+ }
+
+ @Test
+ fun `opens a new chat in the tip's mode with the prompt drafted`() {
+ val vm = viewModel()
+ idleUntil { vm.uiState.value.activeSessionId != null }
+ val before = vm.uiState.value.activeSessionId
+
+ vm.startChatFromTip("Turn on Do Not Disturb", AgentMode.OPERATOR)
+ idleUntil { vm.uiState.value.composerDraft != null }
+
+ val state = vm.uiState.value
+ assertEquals("Turn on Do Not Disturb", state.composerDraft)
+ assertEquals(AgentMode.OPERATOR, state.activeAgent)
+ assertTrue(state.messages.isEmpty())
+ assertNotEquals(before, state.activeSessionId)
+ // Drafted, never sent.
+ assertEquals(false, state.isBusy)
+
+ vm.consumeComposerDraft()
+ assertNull(vm.uiState.value.composerDraft)
+ }
+
+ @Test
+ fun `unconfigured, the chat opens without a draft`() {
+ val vm = viewModel(configured = false)
+ idleUntil { vm.uiState.value.activeSessionId != null }
+ val before = vm.uiState.value.activeSessionId
+ vm.startChatFromTip("What's on my screen?", AgentMode.MONITOR)
+ idleUntil { vm.uiState.value.activeSessionId != before }
+ assertNotEquals(before, vm.uiState.value.activeSessionId)
+ assertNull(vm.uiState.value.composerDraft)
+ }
+}
diff --git a/app/src/test/java/com/gotcha/notifications/DailyTipNotifierTest.kt b/app/src/test/java/com/gotcha/notifications/DailyTipNotifierTest.kt
new file mode 100644
index 0000000..d2d256d
--- /dev/null
+++ b/app/src/test/java/com/gotcha/notifications/DailyTipNotifierTest.kt
@@ -0,0 +1,59 @@
+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/DailyTipsTest.kt b/app/src/test/java/com/gotcha/notifications/DailyTipsTest.kt
new file mode 100644
index 0000000..7cc583f
--- /dev/null
+++ b/app/src/test/java/com/gotcha/notifications/DailyTipsTest.kt
@@ -0,0 +1,138 @@
+package com.gotcha.notifications
+
+import com.gotcha.tools.AgentMode
+import com.gotcha.tools.ToolDefinitions
+import com.gotcha.tools.ToolRegistry
+import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertNotEquals
+import org.junit.Assert.assertNull
+import org.junit.Assert.assertTrue
+import org.junit.Test
+import java.time.ZoneId
+import java.time.ZonedDateTime
+import kotlin.random.Random
+
+/** The daily tip catalog and the pure rules that choose and time a tip (issue #101). */
+class DailyTipsTest {
+
+ private val zone = ZoneId.of("Europe/Berlin")
+
+ private fun millis(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 tip(id: String, vararg tools: String) =
+ DailyTip(id = id, title = id, body = id, prompt = id, tools = tools.toSet())
+
+ // ---- catalog ----
+
+ @Test
+ fun `tip ids are unique`() {
+ val ids = DAILY_TIPS.map { it.id }
+ assertEquals(ids.size, ids.distinct().size)
+ // Ids are stored comma-separated.
+ ids.forEach { assertFalse("Comma in id $it", ',' in it) }
+ }
+
+ @Test
+ fun `there are more tips than the recent memory holds`() {
+ assertTrue(DAILY_TIPS.size > RECENT_TIP_MEMORY)
+ }
+
+ @Test
+ fun `every tip names real tools and has text`() {
+ val known = ToolDefinitions.all.map { it.function.name }.toSet()
+ DAILY_TIPS.forEach { tip ->
+ val texts = listOf(tip.title, tip.body, tip.prompt)
+ assertTrue("Blank text in ${tip.id}", texts.all { it.isNotBlank() })
+ assertTrue("${tip.id} lists no tools", tip.tools.isNotEmpty())
+ tip.tools.forEach { assertTrue("${tip.id} names unknown tool $it", it in known) }
+ }
+ }
+
+ @Test
+ fun `each tip starts in the mode its tools need`() {
+ DAILY_TIPS.forEach { tip ->
+ val readOnly = tip.tools.all { it in ToolRegistry.monitorTools }
+ val expected = if (readOnly) AgentMode.MONITOR else AgentMode.OPERATOR
+ assertEquals("Mode of ${tip.id}", expected, tip.agent)
+ }
+ }
+
+ // ---- picking ----
+
+ @Test
+ fun `recently shown tips are skipped`() {
+ val tips = listOf(tip("a", "x"), tip("b", "y"), tip("c", "z"))
+ repeat(20) { seed ->
+ assertEquals("c", pickDailyTip(tips, listOf("a", "b"), emptySet(), Random(seed))?.id)
+ }
+ }
+
+ @Test
+ fun `tips for untried tools win`() {
+ val tips = listOf(tip("used", "read_screen"), tip("new", "send_sms"))
+ repeat(20) { seed ->
+ assertEquals("new", pickDailyTip(tips, emptyList(), setOf("read_screen"), Random(seed))?.id)
+ }
+ }
+
+ @Test
+ fun `falls back to tried tools once every fresh tip is tried`() {
+ val tips = listOf(tip("a", "x"), tip("b", "y"))
+ assertEquals("b", pickDailyTip(tips, listOf("a"), setOf("x", "y"))?.id)
+ }
+
+ @Test
+ fun `starts over when every tip is recent, avoiding the last one`() {
+ val tips = listOf(tip("a", "x"), tip("b", "y"))
+ repeat(20) { seed ->
+ assertEquals("a", pickDailyTip(tips, listOf("a", "b"), emptySet(), Random(seed))?.id)
+ }
+ // A single tip is still offered.
+ assertEquals("a", pickDailyTip(listOf(tip("a", "x")), listOf("a"), emptySet())?.id)
+ }
+
+ @Test
+ fun `an empty catalog picks nothing`() {
+ assertNull(pickDailyTip(emptyList(), emptyList(), emptySet()))
+ }
+
+ @Test
+ fun `shown tips are remembered newest last and capped`() {
+ var recent = emptyList<String>()
+ (1..RECENT_TIP_MEMORY + 3).forEach { recent = rememberShownTip(recent, "t$it") }
+ assertEquals(RECENT_TIP_MEMORY, recent.size)
+ assertEquals("t${RECENT_TIP_MEMORY + 3}", recent.last())
+ assertEquals(listOf("b", "a"), rememberShownTip(listOf("a", "b"), "a"))
+ }
+
+ // ---- timing ----
+
+ @Test
+ fun `next tip is today when the time is still ahead`() {
+ assertEquals(millis(2026, 9, 23, 10), nextDailyTipAt(millis(2026, 9, 23, 8), 600, zone))
+ }
+
+ @Test
+ fun `next tip is tomorrow once the time has passed`() {
+ assertEquals(millis(2026, 9, 24, 10), nextDailyTipAt(millis(2026, 9, 23, 10), 600, zone))
+ assertEquals(millis(2026, 9, 24, 10), nextDailyTipAt(millis(2026, 9, 23, 22), 600, zone))
+ }
+
+ @Test
+ fun `the clock time holds across a daylight saving change`() {
+ // Berlin leaves summer time on 25 October 2026: that day is 25 hours long.
+ val next = nextDailyTipAt(millis(2026, 10, 24, 12), 600, zone)
+ assertEquals(millis(2026, 10, 25, 10), next)
+ assertNotEquals(millis(2026, 10, 24, 10) + 24L * 3600_000L, next)
+ }
+
+ @Test
+ fun `used today means the same local day`() {
+ val now = millis(2026, 9, 23, 10)
+ assertTrue(usedToday(millis(2026, 9, 23, 0, 30), now, zone))
+ assertFalse(usedToday(millis(2026, 9, 22, 23, 30), now, zone))
+ assertFalse(usedToday(null, now, zone))
+ }
+}
diff --git a/app/src/test/java/com/gotcha/notifications/PostDailyTipTest.kt b/app/src/test/java/com/gotcha/notifications/PostDailyTipTest.kt
new file mode 100644
index 0000000..6b713e8
--- /dev/null
+++ b/app/src/test/java/com/gotcha/notifications/PostDailyTipTest.kt
@@ -0,0 +1,101 @@
+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)
+ }
+}