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: implement remote notification fetching, client-side delivery deduplication, and app settings integration
Rishabh Bajpaida2bfc70e8f2
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex a0ac737..0c0df70 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -41,6 +41,7 @@ import com.gotcha.data.Settingsimport com.gotcha.data.SettingsRepositoryimport com.gotcha.llm.ChatMessageimport com.gotcha.llm.LLMClient+import com.gotcha.notifications.ServerMessagesimport com.gotcha.service.AssistiveBallServiceimport com.gotcha.service.GotchaDeviceAdminReceiverimport com.gotcha.tools.ScreenPerception@@ -303,6 +304,38 @@ class MainActivity : ComponentActivity() {chatViewModel.setForeground(true)}+ override fun onResume() {+ super.onResume()+ // 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.+ lifecycleScope.launch {+ try {+ val settings = settingsRepository.load()+ val dispatcher = ServerMessages.create(+ context = this@MainActivity,+ settings = settings,+ onUnauthorized = { onSamosaUnauthorized() }+ )+ ServerMessages.syncIfStale(+ dispatcher = dispatcher,+ enabled = settings.serverMessagesEnabled+ )+ // Persist the store's lastFetchedAt so Settings → Notifications+ // shows a correct "Last synced: …" line on next open, even if+ // the user never tapped Sync now.+ val fresh = dispatcher.lastFetchedAt()+ if (fresh > 0L && fresh != settings.serverMessagesLastFetchedAt) {+ settingsRepository.save(settings.copy(serverMessagesLastFetchedAt = fresh))+ }+ } catch (e: kotlinx.coroutines.CancellationException) {+ throw e+ } catch (_: Exception) {+ // Server messages are best-effort; never surface errors.+ }+ }+ }+/*** Start or stop the assistive-ball foreground service. Returns the resulting* enabled state. When enabling without the overlay permission, deep-links the user@@ -540,6 +573,25 @@ class MainActivity : ComponentActivity() {samosaAuthManager.signOut()chatViewModel.refreshSettings()},+ onSyncServerMessages = {+ val s = settingsRepository.load()+ if (!s.serverMessagesEnabled) return@SettingsScreen null+ val dispatcher = ServerMessages.create(+ context = this@MainActivity,+ settings = s,+ onUnauthorized = { onSamosaUnauthorized() }+ )+ dispatcher.fetchAndDeliver()+ // Persist the fresh last-fetched-at so a future+ // Settings reload reads the same value the screen+ // is showing, and so a process kill + relaunch+ // starts from this point.+ val updated = s.copy(+ serverMessagesLastFetchedAt = dispatcher.lastFetchedAt()+ )+ settingsRepository.save(updated)+ dispatcher.lastFetchedAt()+ },onTestVoice = { language -> chatViewModel.testAndroidTts(language) },packageName = packageName,assistiveBallEnabled = assistiveBallOn,diff --git a/app/src/main/java/com/gotcha/data/SettingsRepository.kt b/app/src/main/java/com/gotcha/data/SettingsRepository.ktindex d8b9e9e..3b2dbda 100644--- a/app/src/main/java/com/gotcha/data/SettingsRepository.kt+++ b/app/src/main/java/com/gotcha/data/SettingsRepository.kt@@ -51,6 +51,12 @@ data class Settings(/** Chime when a reply arrives. Off by default — audible in a way a buzz is not. */val notifyChimeEnabled: Boolean = false,val assistiveBallEnabled: Boolean = false,+ /** Server-driven notifications from `api.samosa-ai.example/v1/gotcha/notifications`. */+ val serverMessagesEnabled: Boolean = true,+ /** Epoch millis of the last successful server-messages fetch. 0 = never. */+ val serverMessagesLastFetchedAt: Long = 0L,+ /** Last seen ETag from the notifications endpoint; round-tripped in `If-None-Match`. */+ val serverMessagesEtag: String = "",// ---- Appearance (Settings ▸ Appearance) ----/*** Which skin is painted. Stored as the id string rather than an enum so a@@ -94,7 +100,7 @@ data class Settings(val userResponseStyle: String = "",val preferredLanguage: String = "English",val preferredCurrency: String = "USD",- val communitySkillHosts: Set<String> = setOf("samosa-ai.example", "samosa.ai")+ val communitySkillHosts: Set<String> = setOf("samosa-ai.example")) {/** True when the active provider has everything it needs to make requests. */val isConfigured: Boolean@@ -292,6 +298,9 @@ class SettingsRepository(context: Context) {notifyVibrationEnabled = prefs.getBoolean(KEY_NOTIFY_VIBRATION, true),notifyChimeEnabled = prefs.getBoolean(KEY_NOTIFY_CHIME, false),assistiveBallEnabled = prefs.getBoolean(KEY_ASSISTIVE_BALL, false),+ serverMessagesEnabled = prefs.getBoolean(KEY_SERVER_MESSAGES_ENABLED, true),+ serverMessagesLastFetchedAt = prefs.getLong(KEY_SERVER_MESSAGES_LAST_FETCHED, 0L),+ serverMessagesEtag = string(KEY_SERVER_MESSAGES_ETAG),skinId = resolvedSkinId(),disabledSkills = stringSet(KEY_DISABLED_SKILLS),disabledConnectors = stringSet(KEY_DISABLED_CONNECTORS),@@ -342,6 +351,9 @@ class SettingsRepository(context: Context) {.putBoolean(KEY_NOTIFY_VIBRATION, settings.notifyVibrationEnabled).putBoolean(KEY_NOTIFY_CHIME, settings.notifyChimeEnabled).putBoolean(KEY_ASSISTIVE_BALL, settings.assistiveBallEnabled)+ .putBoolean(KEY_SERVER_MESSAGES_ENABLED, settings.serverMessagesEnabled)+ .putLong(KEY_SERVER_MESSAGES_LAST_FETCHED, settings.serverMessagesLastFetchedAt)+ .putString(KEY_SERVER_MESSAGES_ETAG, settings.serverMessagesEtag).putString(KEY_SKIN_ID, settings.skinId).putStringSet(KEY_DISABLED_SKILLS, settings.disabledSkills).putStringSet(KEY_DISABLED_CONNECTORS, settings.disabledConnectors)@@ -408,6 +420,9 @@ class SettingsRepository(context: Context) {const val KEY_NOTIFY_VIBRATION = "notify_vibration"const val KEY_NOTIFY_CHIME = "notify_chime"const val KEY_ASSISTIVE_BALL = "assistive_ball_enabled"+ const val KEY_SERVER_MESSAGES_ENABLED = "server_messages_enabled"+ const val KEY_SERVER_MESSAGES_LAST_FETCHED = "server_messages_last_fetched"+ const val KEY_SERVER_MESSAGES_ETAG = "server_messages_etag"const val KEY_SKIN_ID = "skin_id"/** Only read by [migrateSkinId]; never written any more. */@@ -429,6 +444,6 @@ class SettingsRepository(context: Context) {const val KEY_PREFERRED_LANGUAGE = "preferred_language"const val KEY_PREFERRED_CURRENCY = "preferred_currency"const val KEY_COMMUNITY_SKILL_HOSTS = "community_skill_hosts"- val defaultCommunitySkillHosts: Set<String> = setOf("samosa-ai.example", "samosa.ai")+ val defaultCommunitySkillHosts: Set<String> = setOf("samosa-ai.example")}}diff --git a/app/src/main/java/com/gotcha/notifications/NotificationApi.kt b/app/src/main/java/com/gotcha/notifications/NotificationApi.ktnew file mode 100644index 0000000..e777840--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/NotificationApi.kt@@ -0,0 +1,134 @@+package com.gotcha.notifications++import android.util.Log+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject+import kotlinx.serialization.json.jsonPrimitive+import okhttp3.OkHttpClient+import okhttp3.Request+import okhttp3.logging.HttpLoggingInterceptor+import java.util.concurrent.TimeUnit++/**+ * HTTP client for `GET https://api.samosa-ai.example/v1/gotcha/notifications`.+ *+ * Mirrors the [com.gotcha.audio.AudioApi] pattern (OkHttp directly, no+ * Retrofit). Surfaces a 304 via [NotificationsApiResult.NotModified] so the+ * dispatcher can short-circuit without re-parsing. A 401 fires the existing+ * Samosa session-invalidation path — v1 doesn't expect it (the public route+ * is unauthenticated) but the wiring is in place for a future signed-in feed.+ *+ * [fetch] is `open` so tests can subclass with a stub implementation and+ * skip the HTTP client entirely.+ */+open class NotificationApi(+ private val baseUrl: String = DEFAULT_BASE_URL,+ private val bearerToken: String = "",+ private val onUnauthorized: () -> Unit = {},+ private val timeoutSeconds: Long = 15L+) {+ private val client: OkHttpClient+ private val jsonParser = Json {+ ignoreUnknownKeys = true+ isLenient = true+ }++ init {+ val logging = HttpLoggingInterceptor().apply {+ level = HttpLoggingInterceptor.Level.BASIC+ }+ client = OkHttpClient.Builder()+ .connectTimeout(timeoutSeconds, TimeUnit.SECONDS)+ .readTimeout(timeoutSeconds * 2, TimeUnit.SECONDS)+ .addInterceptor { chain ->+ val request = chain.request().newBuilder()+ if (bearerToken.isNotBlank()) {+ request.addHeader("Authorization", "Bearer $bearerToken")+ }+ chain.proceed(request.build())+ }+ .addInterceptor(logging)+ .build()+ }++ open suspend fun fetch(ifNoneMatch: String?): NotificationsApiResult = withContext(Dispatchers.IO) {+ fetchBlocking(ifNoneMatch)+ }++ /** Blocking fetch — must be called off the main thread (e.g. inside+ * [fetch], which switches to [Dispatchers.IO]). Open for tests that want+ * to skip the dispatcher hop. */+ internal open fun fetchBlocking(ifNoneMatch: String?): NotificationsApiResult {+ val url = "${baseUrl.trimEnd('/')}/v1/gotcha/notifications"+ val request = Request.Builder().url(url).get().apply {+ if (!ifNoneMatch.isNullOrBlank()) {+ addHeader("If-None-Match", "\"$ifNoneMatch\"")+ }+ }.build()+ return try {+ client.newCall(request).execute().use { response ->+ when {+ response.code == 304 -> NotificationsApiResult.NotModified+ response.code == 401 -> {+ onUnauthorized()+ NotificationsApiResult.Error(401)+ }+ !response.isSuccessful -> NotificationsApiResult.Error(response.code)+ else -> {+ val body = response.body?.string().orEmpty()+ val etag = response.header("ETag")?.trim('"') ?: ""+ parse(body, etag)+ }+ }+ }+ } catch (e: Exception) {+ try { Log.w(TAG, "Notifications fetch failed", e) } catch (_: Throwable) {}+ NotificationsApiResult.NetworkError+ }+ }++ private fun parse(body: String, etag: String): NotificationsApiResult {+ return try {+ val obj = jsonParser.parseToJsonElement(body).jsonObject+ val messagesArray = obj["messages"]?.jsonArray ?: return NotificationsApiResult.Parsed(+ NotificationsEnvelope(messages = emptyList(), etag = etag)+ )+ // Deserialize via kotlinx.serialization for shape fidelity; fall back to+ // empty envelope if a single message is malformed so one bad entry+ // doesn't sink the whole feed.+ val messages = messagesArray.mapNotNull { element ->+ runCatching {+ jsonParser.decodeFromJsonElement(+ NotificationMessage.serializer(),+ element+ )+ }.getOrNull()+ }+ val envelopeEtag = obj["etag"]?.jsonPrimitive?.content ?: etag+ NotificationsApiResult.Parsed(+ NotificationsEnvelope(messages = messages, etag = envelopeEtag)+ )+ } catch (e: Exception) {+ try { Log.w(TAG, "Notifications parse failed", e) } catch (_: Throwable) {}+ NotificationsApiResult.Error(-1)+ }+ }++ companion object {+ private const val TAG = "NotificationApi"++ /** OpenAI-compatible proxy exposed by Samosa AI backend; reused as the+ * notifications host so a single network identity covers LLM/audio/notifications. */+ const val DEFAULT_BASE_URL = "https://api.samosa-ai.example"+ }+}++sealed interface NotificationsApiResult {+ data class Parsed(val envelope: NotificationsEnvelope) : NotificationsApiResult+ data object NotModified : NotificationsApiResult+ data class Error(val httpStatus: Int) : NotificationsApiResult+ data object NetworkError : NotificationsApiResult+}diff --git a/app/src/main/java/com/gotcha/notifications/NotificationDispatcher.kt b/app/src/main/java/com/gotcha/notifications/NotificationDispatcher.ktnew file mode 100644index 0000000..2e8f4d5--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/NotificationDispatcher.kt@@ -0,0 +1,226 @@+package com.gotcha.notifications++import android.Manifest+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.net.Uri+import android.os.Build+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import androidx.core.content.ContextCompat++/**+ * Pulls the latest envelope from [NotificationApi], filters/dedupes against+ * [NotificationStore], and posts surviving messages to the system tray.+ *+ * Filter rules (see plan §6):+ * 1. id already delivered >= max_deliveries+ * 2. expires_at in the past+ * 3. ttl elapsed since expires_at (or since fetch time, if no expires_at)+ * 4. BuildConfig.VERSION_NAME < min_app_version+ * 5. title or body blank+ * 6. url present but not https+ *+ * The dispatcher is intentionally small; persistence is owned by the store,+ * and posting is split into a single suspend entry point so callers (the+ * activity, the Samosa sign-in flow, a future background worker) don't have+ * to know the details.+ */+class NotificationDispatcher(+ private val context: Context,+ private val api: NotificationApi,+ private val store: NotificationStore,+ private val versionName: String,+ private val openIntent: (url: String) -> Intent = { url ->+ Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(+ Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP+ )+ }+) {++ suspend fun fetchAndDeliver(+ now: Long = System.currentTimeMillis()+ ): DispatchResult {+ val result = api.fetch(ifNoneMatch = store.etag().takeIf { it.isNotBlank() })+ return when (result) {+ is NotificationsApiResult.NotModified -> {+ store.setLastFetchedAt(now)+ DispatchResult.UpToDate+ }+ is NotificationsApiResult.Error -> DispatchResult.Failed+ NotificationsApiResult.NetworkError -> DispatchResult.Failed+ is NotificationsApiResult.Parsed -> {+ deliver(result.envelope, now)+ }+ }+ }++ /** Last time a successful fetch happened. Surfaced for the on-resume+ * freshness gate so a fetch done via Settings → Sync now is honoured. */+ fun lastFetchedAt(): Long = store.lastFetchedAt()++ private fun deliver(envelope: NotificationsEnvelope, now: Long): DispatchResult {+ if (envelope.etag.isNotBlank()) store.setEtag(envelope.etag)+ store.setLastFetchedAt(now)++ val channelEnsured = ensureChannel()+ if (!channelEnsured) return DispatchResult.Skipped("channel")++ if (!hasPostPermission()) return DispatchResult.Skipped("permission")++ var posted = 0+ var suppressed = 0++ envelope.messages.forEach { msg ->+ val reason = skipReason(msg, now)+ if (reason != null) {+ suppressed+++ return@forEach+ }+ try {+ postOne(msg)+ store.recordDelivery(msg.id)+ posted+++ } catch (e: Exception) {+ try { Log.w(TAG, "Failed to post notification id=${msg.id}", e) } catch (_: Throwable) {}+ suppressed+++ }+ }++ store.prune(now)+ return DispatchResult.Delivered(posted = posted, suppressed = suppressed)+ }++ internal fun shouldDeliver(msg: NotificationMessage, now: Long): Boolean =+ skipReason(msg, now) == null++ /** Returns null when the message should be posted; otherwise the reason+ * for skipping. Surfaced so the dispatcher can log why a message was+ * dropped, which is useful when investigating "why didn't this fire?". */+ private fun skipReason(msg: NotificationMessage, now: Long): String? {+ val count = store.deliveryCount(msg.id)+ if (count >= msg.maxDeliveries) return "max_deliveries"+ if (msg.title.isBlank() || msg.body.isBlank()) return "blank"+ if (msg.url != null && !msg.url.startsWith("https://")) return "non_https_url"++ if (msg.expiresAt != null) {+ val expiry = parseIsoToMillis(msg.expiresAt)+ if (expiry != null && expiry < now) return "expired"+ if (expiry != null && msg.ttlSeconds != null && (now - expiry) > msg.ttlSeconds * 1000L) {+ return "ttl_after_expiry"+ }+ } else if (msg.ttlSeconds != null && now - store.lastFetchedAt() > msg.ttlSeconds * 1000L) {+ return "ttl_after_fetch"+ }++ if (msg.minAppVersion != null && compareSemver(versionName, msg.minAppVersion) < 0) {+ return "below_min_version"+ }+ return null+ }++ @Suppress("MissingPermission") // hasPostPermission() is enforced in deliver().+ private fun postOne(msg: NotificationMessage) {+ val notifyId = stableNotifyId(msg.id)+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(com.gotcha.R.drawable.ic_notification)+ .setContentTitle(msg.title)+ .setContentText(msg.body)+ .setPriority(msg.androidPriority)+ .setCategory(NotificationCompat.CATEGORY_MESSAGE)+ .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)+ .setAutoCancel(true)+ if (!msg.url.isNullOrBlank() && msg.url.startsWith("https://")) {+ val intent = openIntent(msg.url)+ val pending = PendingIntent.getActivity(+ context,+ notifyId,+ intent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ builder.setContentIntent(pending)+ }+ NotificationManagerCompat.from(context).notify(notifyId, builder.build())+ }++ /** Non-negative 31-bit id derived from the message id. Used both as the+ * system-tray notification id and the PendingIntent request code so the+ * same message always maps to the same slot (no silent overwrite by a+ * different message with a hash collision) and so the notification can be+ * cancelled/replaced deterministically. */+ private fun stableNotifyId(messageId: String): Int =+ messageId.hashCode() and 0x7FFF_FFFF++ private fun ensureChannel(): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return true+ val mgr = context.getSystemService(NotificationManager::class.java) ?: return false+ val existing = mgr.getNotificationChannel(CHANNEL_ID)+ if (existing != null) return true+ return try {+ val channel = NotificationChannel(+ CHANNEL_ID,+ "Server messages",+ NotificationManager.IMPORTANCE_DEFAULT+ ).apply {+ description = "Updates, tips, and maintenance notices from Gotcha"+ }+ mgr.createNotificationChannel(channel)+ true+ } catch (e: Exception) {+ try { Log.w(TAG, "Failed to create notification channel", e) } catch (_: Throwable) {}+ false+ }+ }++ private fun hasPostPermission(): Boolean {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU) return true+ return ContextCompat.checkSelfPermission(+ context,+ Manifest.permission.POST_NOTIFICATIONS+ ) == PackageManager.PERMISSION_GRANTED+ }++ /**+ * Compares two semver-style strings `MAJOR.MINOR.PATCH` component by+ * component. Tolerant of trailing build metadata: anything after `+` is+ * ignored. Returns positive if [a] > [b], negative if [a] < [b], 0 on+ * equality.+ */+ private fun compareSemver(a: String, b: String): Int {+ val pa = a.substringBefore('+').split('.').map { it.toIntOrNull() ?: 0 }+ val pb = b.substringBefore('+').split('.').map { it.toIntOrNull() ?: 0 }+ for (i in 0 until maxOf(pa.size, pb.size)) {+ val ai = pa.getOrElse(i) { 0 }+ val bi = pb.getOrElse(i) { 0 }+ if (ai != bi) return ai - bi+ }+ return 0+ }++ private fun parseIsoToMillis(iso: String): Long? = try {+ // Accept both `…Z` (Instant) and full `±HH:MM` offsets (OffsetDateTime).+ val normalized = iso.trim()+ runCatching { java.time.Instant.parse(normalized).toEpochMilli() }.getOrNull()+ ?: runCatching { java.time.OffsetDateTime.parse(normalized).toInstant().toEpochMilli() }+ .getOrNull()+ } catch (_: Exception) {+ null+ }++ companion object {+ const val CHANNEL_ID = "gotcha_messages"+ private const val TAG = "NotificationDispatcher"+ }+}++sealed interface DispatchResult {+ data class Delivered(val posted: Int, val suppressed: Int) : DispatchResult+ data object UpToDate : DispatchResult+ data object Failed : DispatchResult+ data class Skipped(val reason: String) : DispatchResult+}diff --git a/app/src/main/java/com/gotcha/notifications/NotificationStore.kt b/app/src/main/java/com/gotcha/notifications/NotificationStore.ktnew file mode 100644index 0000000..f997a5b--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/NotificationStore.kt@@ -0,0 +1,87 @@+package com.gotcha.notifications++import android.content.Context+import com.gotcha.data.SafeEncryptedSharedPreferences++/**+ * Local delivery log + ETag store for server-driven notifications.+ *+ * Backed by [SafeEncryptedSharedPreferences] so it survives the same KeyStore+ * failure modes as the settings store. The delivery log is a `Set<String>` of+ * message ids and a parallel `Map<String, Int>` of per-id counts — together+ * they answer the only question the dispatcher asks: "has this id been+ * delivered enough times?".+ */+class NotificationStore(context: Context) {++ private val prefs = SafeEncryptedSharedPreferences.create(context, PREFS_FILE)++ fun deliveredIds(): Set<String> = prefs.getStringSet(KEY_DELIVERED_IDS, emptySet())+ .orEmpty()+ .toSet()++ fun deliveryCount(id: String): Int = prefs.getInt("$KEY_DELIVERED_COUNT_PREFIX$id", 0)++ fun recordDelivery(id: String, at: Long = System.currentTimeMillis()) {+ val count = deliveryCount(id) + 1+ val updated = deliveredIds().toMutableSet().apply { add(id) }+ prefs.edit()+ .putStringSet(KEY_DELIVERED_IDS, updated)+ .putInt("$KEY_DELIVERED_COUNT_PREFIX$id", count)+ .putLong("$KEY_DELIVERED_LAST_PREFIX$id", at)+ .apply()+ }++ fun etag(): String = prefs.getString(KEY_ETAG, "").orEmpty()++ fun setEtag(value: String) {+ prefs.edit().putString(KEY_ETAG, value).apply()+ }++ fun lastFetchedAt(): Long = prefs.getLong(KEY_LAST_FETCHED, 0L)++ fun setLastFetchedAt(value: Long) {+ prefs.edit().putLong(KEY_LAST_FETCHED, value).apply()+ }++ /**+ * Drop delivery-log entries that are old enough that they can never+ * affect a future fetch (the server's `expires_at` is at most ~30 days+ * out, so anything older than that is dead weight).+ *+ * Counts are kept only for ids still in [deliveredIds]; this stops the+ * count map from leaking entries for messages no longer remembered.+ */+ fun prune(now: Long) {+ val cutoff = now - PRUNE_AFTER_MS+ val ids = deliveredIds()+ if (ids.isEmpty()) return+ val survivors = mutableSetOf<String>()+ val editor = prefs.edit()+ ids.forEach { id ->+ val lastDelivered = prefs.getLong("$KEY_DELIVERED_LAST_PREFIX$id", 0L)+ if (lastDelivered in 1L until cutoff) {+ editor.remove("$KEY_DELIVERED_COUNT_PREFIX$id")+ editor.remove("$KEY_DELIVERED_LAST_PREFIX$id")+ } else {+ survivors.add(id)+ }+ }+ if (survivors.size != ids.size) {+ // Write the survivor set once after the loop so partial writes+ // don't overwrite each other.+ editor.putStringSet(KEY_DELIVERED_IDS, survivors)+ }+ editor.apply()+ }++ private companion object {+ const val PREFS_FILE = "gotcha_notifications"+ const val KEY_DELIVERED_IDS = "delivered_ids"+ const val KEY_ETAG = "etag"+ const val KEY_LAST_FETCHED = "last_fetched"+ const val KEY_DELIVERED_COUNT_PREFIX = "count:"+ const val KEY_DELIVERED_LAST_PREFIX = "last:"+ const val PRUNE_AFTER_MS = 30L * 24L * 60L * 60L * 1000L+ }+}diff --git a/app/src/main/java/com/gotcha/notifications/NotificationsModels.kt b/app/src/main/java/com/gotcha/notifications/NotificationsModels.ktnew file mode 100644index 0000000..2db43d7--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/NotificationsModels.kt@@ -0,0 +1,44 @@+package com.gotcha.notifications++import kotlinx.serialization.SerialName+import kotlinx.serialization.Serializable++/**+ * Wire DTOs for `GET /v1/gotcha/notifications` on `api.samosa-ai.example`.+ *+ * The server is stateless w.r.t. per-device delivery: all dedupe is enforced+ * on the client against [NotificationStore.deliveredIds] and the per-id+ * counter. [NotificationMessage.maxDeliveries] is a server hint, not a+ * server-side counter.+ */+@Serializable+data class NotificationsEnvelope(+ val messages: List<NotificationMessage> = emptyList(),+ val etag: String = ""+)++@Serializable+data class NotificationMessage(+ val id: String,+ val title: String,+ val body: String,+ val url: String? = null,+ val category: String? = null,+ @SerialName("max_deliveries")+ val maxDeliveries: Int = 1,+ @SerialName("ttl_seconds")+ val ttlSeconds: Long? = null,+ @SerialName("min_app_version")+ val minAppVersion: String? = null,+ @SerialName("expires_at")+ val expiresAt: String? = null,+ val priority: String? = null+) {+ /** Lower-case priority mapped to Android importance; defaults to default-importance. */+ val androidPriority: Int+ get() = when (priority?.lowercase()?.trim()) {+ "high" -> 4 // NotificationCompat.PRIORITY_HIGH+ "low" -> 1 // NotificationCompat.PRIORITY_LOW+ else -> 0 // NotificationCompat.PRIORITY_DEFAULT+ }+}diff --git a/app/src/main/java/com/gotcha/notifications/ServerMessages.kt b/app/src/main/java/com/gotcha/notifications/ServerMessages.ktnew file mode 100644index 0000000..2c339d5--- /dev/null+++ b/app/src/main/java/com/gotcha/notifications/ServerMessages.kt@@ -0,0 +1,47 @@+package com.gotcha.notifications++import android.content.Context+import com.gotcha.data.Settings++/**+ * Top-level orchestrator for server-driven notifications. One entry point,+ * one builder — keeps `MainActivity` thin and gives the dispatcher a single+ * construction site so its dependencies can be swapped for tests.+ */+object ServerMessages {++ private const val ON_RESUME_FETCH_INTERVAL_MS = 6L * 60L * 60L * 1000L++ fun create(context: Context, settings: Settings, onUnauthorized: () -> Unit): NotificationDispatcher {+ val versionName = try {+ context.packageManager.getPackageInfo(context.packageName, 0).versionName ?: ""+ } catch (_: Exception) {+ ""+ }+ val api = NotificationApi(+ baseUrl = NotificationApi.DEFAULT_BASE_URL,+ bearerToken = settings.samosaSessionToken,+ onUnauthorized = onUnauthorized+ )+ return NotificationDispatcher(+ context = context,+ api = api,+ store = NotificationStore(context),+ versionName = versionName+ )+ }++ /**+ * Called on `onResume`; fetches only if the cached value in the store is+ * stale. Reads from the live [NotificationStore] — not the [Settings]+ * snapshot — so a recent fetch done elsewhere is honoured.+ */+ suspend fun syncIfStale(dispatcher: NotificationDispatcher, enabled: Boolean) {+ if (!enabled) return+ val now = System.currentTimeMillis()+ val lastFetched = dispatcher.lastFetchedAt()+ if (lastFetched == 0L || now - lastFetched > ON_RESUME_FETCH_INTERVAL_MS) {+ dispatcher.fetchAndDeliver(now = now)+ }+ }+}diff --git a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt b/app/src/main/java/com/gotcha/ui/NotificationsScreen.ktindex c9bf2e8..5270346 100644--- a/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/NotificationsScreen.kt@@ -1,35 +1,64 @@package com.gotcha.ui+import androidx.compose.foundation.layout.Spacer+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.height+import androidx.compose.material3.Buttonimport androidx.compose.material3.MaterialThemeimport androidx.compose.material3.Textimport androidx.compose.runtime.Composable+import androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValue+import androidx.compose.ui.Modifierimport androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.unit.dpimport com.gotcha.audio.CompletionFeedbackimport com.gotcha.data.Settings+import kotlinx.coroutines.launch/**- * The Notifications page: what the phone does the moment a reply arrives.+ * 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).*- * The only page with no Save button, and deliberately so — switching one on- * plays it once, which is the whole point. A preview that had to be saved first- * would be feedback about a setting the user had already committed to.+ * 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+ * had to be saved first would be feedback about a setting the user had+ * already committed to.*/@Composablefun NotificationsScreen(load: () -> Settings,onSave: ((Settings) -> Settings) -> Unit,- onBack: () -> Unit+ onBack: () -> Unit,+ onSyncServerMessages: suspend () -> Long? = { null }) {val initial = remember { load() }var notifyVibration by remember { mutableStateOf(initial.notifyVibrationEnabled) }var notifyChime by remember { mutableStateOf(initial.notifyChimeEnabled) }+ var serverMessagesEnabled by remember { mutableStateOf(initial.serverMessagesEnabled) }+ var lastFetched by remember { mutableStateOf(initial.serverMessagesLastFetchedAt) }+ var isSyncing by remember { mutableStateOf(false) }val overlay = rememberSettingsOverlayState()val localContext = LocalContext.current+ val scope = rememberCoroutineScope()++ // Sync only when the user toggles server messages ON, not on the+ // initial composition — `onResume` already covers the first-arrival case.+ var skipInitialServerMessagesSync by remember { mutableStateOf(true) }+ LaunchedEffect(serverMessagesEnabled) {+ if (skipInitialServerMessagesSync) {+ skipInitialServerMessagesSync = false+ return@LaunchedEffect+ }+ if (serverMessagesEnabled) onSyncServerMessages()+ }SettingsScaffold(title = SettingsPage.NOTIFICATIONS.title, onBack = onBack, overlay = overlay) {Text(@@ -58,5 +87,56 @@ fun NotificationsScreen(isLarge = true,switchTestTag = "settings_notify_chime")++ Spacer(Modifier.height(16.dp))+ Text(+ "Server messages",+ style = MaterialTheme.typography.titleMedium+ )+ Text(+ "Updates, tips and maintenance notices from Gotcha, fetched from api.samosa-ai.example. " ++ "Each message shows at most the number of times the server asks; re-deliveries are suppressed automatically.",+ style = MaterialTheme.typography.bodySmall+ )+ SettingsToggleRow(+ label = "Enable server messages",+ checked = serverMessagesEnabled,+ onCheckedChange = {+ serverMessagesEnabled = it+ onSave { s -> s.copy(serverMessagesEnabled = it) }+ },+ isLarge = true,+ switchTestTag = "settings_server_messages_enabled"+ )+ Button(+ onClick = {+ isSyncing = true+ scope.launch {+ try {+ val ts = onSyncServerMessages()+ if (ts != null) lastFetched = ts+ } finally {+ isSyncing = false+ }+ }+ },+ enabled = !isSyncing && serverMessagesEnabled,+ modifier = Modifier.fillMaxWidth().testTag("settings_server_messages_sync")+ ) { Text(if (isSyncing) "Syncing…" else "Sync now") }+ Text(+ "Last synced: ${formatRelative(lastFetched)}",+ style = MaterialTheme.typography.bodySmall+ )+ }+}++private fun formatRelative(epochMillis: Long): String {+ if (epochMillis <= 0L) return "never"+ val deltaMin = (System.currentTimeMillis() - epochMillis) / 60_000L+ return when {+ deltaMin < 1L -> "just now"+ deltaMin < 60L -> "${deltaMin}m ago"+ deltaMin < 24L * 60L -> "${deltaMin / 60L}h ago"+ else -> "${deltaMin / (24L * 60L)}d ago"}}diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex a91504e..0c782d9 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -53,6 +53,13 @@ fun SettingsScreen(},/** Logs out of Samosa (clears JWT + Google state). */onSamosaSignOut: suspend () -> Unit = {},+ /**+ * Forces a fetch of the server-messages feed (notifications). Bypasses+ * the 6h gate. Returns the new last-fetched-at timestamp (ms), or null+ * if the sync failed. The screen uses this to refresh its "Last synced"+ * label without an extra round-trip through the Settings repo.+ */+ onSyncServerMessages: suspend () -> Long? = { null },/*** Speaks the call-started phrase through the host's TTS engine and reports* whether the requested language was actually used. Returning null means@@ -139,7 +146,8 @@ fun SettingsScreen(SettingsPage.NOTIFICATIONS -> NotificationsScreen(load = load,onSave = onSave,- onBack = backToHome+ onBack = backToHome,+ onSyncServerMessages = onSyncServerMessages)null -> SettingsHome(onBack = onBack,diff --git a/app/src/main/res/drawable/ic_notification.xml b/app/src/main/res/drawable/ic_notification.xmlnew file mode 100644index 0000000..eb917de--- /dev/null+++ b/app/src/main/res/drawable/ic_notification.xml@@ -0,0 +1,11 @@+<?xml version="1.0" encoding="utf-8"?>+<vector xmlns:android="http://schemas.android.com/apk/res/android"+ android:width="24dp"+ android:height="24dp"+ android:viewportWidth="24"+ android:viewportHeight="24"+ android:tint="?attr/colorControlNormal">+ <path+ android:fillColor="#FFFFFFFF"+ android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2zM13,17h-2v-2h2v2zM13,13h-2L11,7h2v6z" />+</vector>diff --git a/app/src/test/java/com/gotcha/notifications/NotificationApiTest.kt b/app/src/test/java/com/gotcha/notifications/NotificationApiTest.ktnew file mode 100644index 0000000..cb0a66a--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/NotificationApiTest.kt@@ -0,0 +1,137 @@+package com.gotcha.notifications++import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test++class NotificationApiTest {++ private lateinit var server: MockWebServer+ private lateinit var api: NotificationApi++ @Before+ fun setUp() {+ server = MockWebServer()+ server.start()+ api = NotificationApi(+ baseUrl = server.url("/").toString().trimEnd('/'),+ bearerToken = ""+ )+ }++ @After+ fun tearDown() {+ server.shutdown()+ }++ @Test+ fun `fetch returns parsed envelope with etag from header`() {+ server.enqueue(+ MockResponse().setResponseCode(200)+ .setHeader("ETag", "\"abc123\"")+ .setBody(+ """+ {+ "messages": [+ {"id": "m1", "title": "T", "body": "B"}+ ],+ "etag": "abc123"+ }+ """.trimIndent()+ )+ )++ val result = api.fetchBlocking(ifNoneMatch = null)+ assertTrue(result is NotificationsApiResult.Parsed)+ val parsed = (result as NotificationsApiResult.Parsed).envelope+ assertEquals(1, parsed.messages.size)+ assertEquals("m1", parsed.messages[0].id)+ assertEquals("abc123", parsed.etag)+ }++ @Test+ fun `fetch returns NotModified on 304`() {+ server.enqueue(MockResponse().setResponseCode(304))+ val result = api.fetchBlocking(ifNoneMatch = "abc123")+ assertEquals(NotificationsApiResult.NotModified, result)+ }++ @Test+ fun `fetch sends If-None-Match when supplied`() {+ server.enqueue(MockResponse().setResponseCode(304))+ api.fetchBlocking(ifNoneMatch = "abc123")+ val recorded = server.takeRequest()+ assertEquals("\"abc123\"", recorded.getHeader("If-None-Match"))+ }++ @Test+ fun `fetch fires onUnauthorized on 401`() {+ var fired = 0+ val authed = NotificationApi(+ baseUrl = server.url("/").toString().trimEnd('/'),+ bearerToken = "bearer",+ onUnauthorized = { fired++ }+ )+ server.enqueue(MockResponse().setResponseCode(401))+ val result = authed.fetchBlocking(ifNoneMatch = null)+ assertEquals(1, fired)+ assertEquals(NotificationsApiResult.Error(401), result)+ }++ @Test+ fun `fetch attaches Bearer header when token set`() {+ val authed = NotificationApi(+ baseUrl = server.url("/").toString().trimEnd('/'),+ bearerToken = "the-token"+ )+ server.enqueue(+ MockResponse().setResponseCode(200)+ .setBody("""{"messages":[],"etag":""}""")+ )+ authed.fetchBlocking(ifNoneMatch = null)+ val recorded = server.takeRequest()+ assertEquals("Bearer the-token", recorded.getHeader("Authorization"))+ }++ @Test+ fun `fetch returns NetworkError on connection failure`() {+ val dead = NotificationApi(+ baseUrl = "http://127.0.0.1:1/" // unreachable+ )+ val result = dead.fetchBlocking(ifNoneMatch = null)+ assertEquals(NotificationsApiResult.NetworkError, result)+ }++ @Test+ fun `malformed message entries are skipped without sinking the parse`() {+ // id is the only required field on NotificationMessage; the first+ // entry is missing it and the third is missing title — both should be+ // dropped, while the second good one survives.+ val body = """+ {+ "messages": [+ {"title": "no id"},+ {"id": "good", "title": "T", "body": "B"},+ {"id": "no-title", "body": "B"}+ ],+ "etag": "etag-1"+ }+ """.trimIndent()+ server.enqueue(+ MockResponse().setResponseCode(200)+ .setHeader("ETag", "\"etag-1\"")+ .setBody(body)+ )++ val result = api.fetchBlocking(ifNoneMatch = null)+ assertTrue(result is NotificationsApiResult.Parsed)+ val envelope = (result as NotificationsApiResult.Parsed).envelope+ assertEquals(1, envelope.messages.size)+ assertEquals("good", envelope.messages[0].id)+ assertEquals("etag-1", envelope.etag)+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/NotificationDispatcherTest.kt b/app/src/test/java/com/gotcha/notifications/NotificationDispatcherTest.ktnew file mode 100644index 0000000..c81cdf4--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/NotificationDispatcherTest.kt@@ -0,0 +1,206 @@+package com.gotcha.notifications++import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class NotificationDispatcherTest {++ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ private val store by lazy { NotificationStore(ctx) }++ private fun dispatcher(versionName: String = "2.0.0"): NotificationDispatcher =+ NotificationDispatcher(+ context = ctx,+ api = FakeApi(),+ store = store,+ versionName = versionName+ )++ @Test+ fun `survives already-delivered messages`() {+ // m1 has max_deliveries=1; record a delivery and confirm shouldDeliver returns false.+ store.recordDelivery("m1")+ val d = dispatcher()+ assertFalse(d.shouldDeliver(msg("m1", maxDeliveries = 1), now = 1_000_000L))+ }++ @Test+ fun `allows delivery up to max_deliveries`() {+ val d = dispatcher()+ val m = msg("m1", maxDeliveries = 2)+ assertTrue(d.shouldDeliver(m, now = 1_000L))+ store.recordDelivery("m1")+ assertTrue(d.shouldDeliver(m, now = 2_000L))+ store.recordDelivery("m1")+ assertFalse(d.shouldDeliver(m, now = 3_000L))+ }++ @Test+ fun `drops messages whose expires_at is in the past`() {+ val d = dispatcher()+ val past = msg("m_past", expiresAt = "2020-01-01T00:00:00Z")+ assertFalse(d.shouldDeliver(past, now = 1_700_000_000_000L))+ val future = msg("m_future", expiresAt = "2026-01-01T00:00:00Z")+ assertTrue(d.shouldDeliver(future, now = 1_700_000_000_000L))+ }++ @Test+ fun `drops messages whose ttl has elapsed since expires_at`() {+ val d = dispatcher()+ val now = 1_700_000_000_000L+ val expiresAt = java.time.Instant.ofEpochMilli(now - 60_000L).toString()+ val m = msg("m1", expiresAt = expiresAt, ttlSeconds = 10)+ assertFalse(d.shouldDeliver(m, now = now))+ }++ @Test+ fun `honours min_app_version semver gate`() {+ assertFalse(+ dispatcher(versionName = "0.9.0").shouldDeliver(+ msg("m1", minAppVersion = "2.0.0"),+ now = 1_000L+ )+ )+ assertTrue(+ dispatcher(versionName = "2.0.1").shouldDeliver(+ msg("m1", minAppVersion = "2.0.0"),+ now = 1_000L+ )+ )+ assertTrue(+ dispatcher(versionName = "3.0.0").shouldDeliver(+ msg("m1", minAppVersion = "2.0.0"),+ now = 1_000L+ )+ )+ }++ @Test+ fun `drops messages with blank title or body`() {+ val d = dispatcher()+ assertFalse(d.shouldDeliver(msg("m1", title = "", body = "b"), 1L))+ assertFalse(d.shouldDeliver(msg("m1", title = "t", body = " "), 1L))+ }++ @Test+ fun `drops non-https urls`() {+ val d = dispatcher()+ assertFalse(d.shouldDeliver(msg("m1", url = "http://example.com"), 1L))+ assertFalse(d.shouldDeliver(msg("m1", url = "javascript:alert(1)"), 1L))+ assertTrue(d.shouldDeliver(msg("m1", url = "https://example.com"), 1L))+ }++ @Test+ fun `fetchAndDeliver records delivery and persists etag on success`() = kotlinx.coroutines.test.runTest {+ val now = 1_700_000_000_000L+ val api = ScriptedApi(+ mutableListOf(+ NotificationsApiResult.Parsed(+ NotificationsEnvelope(+ messages = listOf(msg("m1")),+ etag = "etag-1"+ )+ )+ )+ )+ val d = NotificationDispatcher(+ context = ctx,+ api = api,+ store = store,+ versionName = "2.0.0"+ )++ val result = d.fetchAndDeliver(now = now)++ // Without POST_NOTIFICATIONS on Robolectric the post path returns+ // Skipped("permission") — the parts we care about are still asserted:+ // the etag and lastFetchedAt are persisted even when no notification+ // is posted, so a follow-up resume won't re-fetch the same envelope.+ assertTrue(result is DispatchResult.Skipped && result.reason == "permission")+ assertEquals("etag-1", store.etag())+ assertEquals(now, store.lastFetchedAt())+ // shouldDeliver still gates the message correctly afterwards.+ // With maxDeliveries=1 and the recordDelivery that the dispatcher+ // performs, the message is now at its cap.+ // (In Robolectric the post path is skipped, so the recordDelivery+ // call doesn't run; we only assert the etag/lastFetched persistence.)+ }++ @Test+ fun `fetchAndDeliver returns UpToDate on 304 without re-parsing`() = kotlinx.coroutines.test.runTest {+ store.setEtag("etag-1")+ store.setLastFetchedAt(1_000L)+ val api = ScriptedApi(mutableListOf(NotificationsApiResult.NotModified))+ val d = NotificationDispatcher(+ context = ctx,+ api = api,+ store = store,+ versionName = "2.0.0"+ )++ val result = d.fetchAndDeliver(now = 2_000L)++ assertEquals(DispatchResult.UpToDate, result)+ // lastFetchedAt was updated so the 6h on-resume gate is satisfied.+ assertEquals(2_000L, store.lastFetchedAt())+ }++ @Test+ fun `fetchAndDeliver returns Failed on network and does not touch the store`() = kotlinx.coroutines.test.runTest {+ store.setEtag("etag-1")+ store.setLastFetchedAt(1_000L)+ val api = ScriptedApi(mutableListOf(NotificationsApiResult.NetworkError))+ val d = NotificationDispatcher(+ context = ctx,+ api = api,+ store = store,+ versionName = "2.0.0"+ )++ val result = d.fetchAndDeliver(now = 2_000L)++ assertEquals(DispatchResult.Failed, result)+ assertEquals("etag-1", store.etag())+ assertEquals(1_000L, store.lastFetchedAt())+ }++ private fun msg(+ id: String,+ title: String = "T",+ body: String = "B",+ url: String? = null,+ maxDeliveries: Int = 1,+ ttlSeconds: Long? = null,+ minAppVersion: String? = null,+ expiresAt: String? = null+ ): NotificationMessage = NotificationMessage(+ id = id,+ title = title,+ body = body,+ url = url,+ maxDeliveries = maxDeliveries,+ ttlSeconds = ttlSeconds,+ minAppVersion = minAppVersion,+ expiresAt = expiresAt+ )++ private class FakeApi : NotificationApi(baseUrl = "http://unused/") {+ override fun fetchBlocking(ifNoneMatch: String?): NotificationsApiResult =+ NotificationsApiResult.Parsed(+ NotificationsEnvelope(messages = emptyList(), etag = "")+ )+ }++ private class ScriptedApi(+ private val responses: MutableList<NotificationsApiResult>+ ) : NotificationApi(baseUrl = "http://unused/") {+ override fun fetchBlocking(ifNoneMatch: String?): NotificationsApiResult =+ responses.removeAt(0)+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/NotificationMessageTest.kt b/app/src/test/java/com/gotcha/notifications/NotificationMessageTest.ktnew file mode 100644index 0000000..06fc3df--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/NotificationMessageTest.kt@@ -0,0 +1,49 @@+package com.gotcha.notifications++import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Test++class NotificationMessageTest {++ @Test+ fun `androidPriority maps high default low`() {+ assertEquals(4, NotificationMessage(id = "x", title = "t", body = "b", priority = "high").androidPriority)+ assertEquals(4, NotificationMessage(id = "x", title = "t", body = "b", priority = "HIGH").androidPriority)+ assertEquals(1, NotificationMessage(id = "x", title = "t", body = "b", priority = "low").androidPriority)+ assertEquals(0, NotificationMessage(id = "x", title = "t", body = "b", priority = null).androidPriority)+ assertEquals(0, NotificationMessage(id = "x", title = "t", body = "b", priority = "garbage").androidPriority)+ }++ @Test+ fun `deserializes the canonical envelope`() {+ val json = """+ {+ "messages": [+ {+ "id": "2026-08-01-free-models-on-samosa-ai",+ "title": "Free models on Samosa AI",+ "body": "Enjoy free models from Samosa AI to start your Gotchas journey.",+ "category": "general",+ "max_deliveries": 1,+ "expires_at": "2026-08-26T05:00:00Z",+ "priority": "default"+ }+ ],+ "etag": "abc123"+ }+ """.trimIndent()+ val envelope = kotlinx.serialization.json.Json {+ ignoreUnknownKeys = true+ isLenient = true+ }.decodeFromString(NotificationsEnvelope.serializer(), json)+ assertEquals(1, envelope.messages.size)+ val m = envelope.messages[0]+ assertEquals("2026-08-01-free-models-on-samosa-ai", m.id)+ assertEquals(1, m.maxDeliveries)+ assertEquals("general", m.category)+ assertEquals(0, m.androidPriority)+ assertTrue(m.url == null)+ assertEquals("abc123", envelope.etag)+ }+}diff --git a/app/src/test/java/com/gotcha/notifications/NotificationStoreTest.kt b/app/src/test/java/com/gotcha/notifications/NotificationStoreTest.ktnew file mode 100644index 0000000..634a682--- /dev/null+++ b/app/src/test/java/com/gotcha/notifications/NotificationStoreTest.kt@@ -0,0 +1,76 @@+package com.gotcha.notifications++import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertTrue+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++@RunWith(RobolectricTestRunner::class)+class NotificationStoreTest {++ private val ctx get() = ApplicationProvider.getApplicationContext<android.content.Context>()+ private val store get() = NotificationStore(ctx)++ private val pruneAfterMs = 30L * 24L * 60L * 60L * 1000L++ @Test+ fun `recordDelivery writes id, count and timestamp`() {+ store.recordDelivery("m1")+ assertTrue(store.deliveredIds().contains("m1"))+ assertEquals(1, store.deliveryCount("m1"))+ // The store doesn't expose lastDelivered publicly, but the prune+ // test below exercises it indirectly.+ val now = System.currentTimeMillis() + pruneAfterMs + 1L+ store.prune(now)+ assertFalse(store.deliveredIds().contains("m1"))+ assertEquals(0, store.deliveryCount("m1"))+ }++ @Test+ fun `prune removes only ids whose last delivery is older than the cutoff`() {+ store.recordDelivery("old", at = 1_000L)+ store.recordDelivery("recent", at = 1_000_000_000_000L)++ // Cutoff older than `old` but newer than `recent`'s timestamp.+ val now = 1_000L + pruneAfterMs + 1L+ store.prune(now)++ assertFalse("old should be pruned", store.deliveredIds().contains("old"))+ assertEquals(0, store.deliveryCount("old"))+ assertTrue("recent should survive", store.deliveredIds().contains("recent"))+ assertEquals(1, store.deliveryCount("recent"))+ }++ @Test+ fun `prune preserves the entire deliveredIds set when nothing is stale`() {+ store.recordDelivery("a")+ store.recordDelivery("b")+ store.recordDelivery("c")+ val now = System.currentTimeMillis() // everything is fresh+ store.prune(now)+ assertEquals(setOf("a", "b", "c"), store.deliveredIds())+ }++ @Test+ fun `prune handles multiple stale ids without corrupting the set`() {+ // Regression: the old code wrote KEY_DELIVERED_IDS inside the loop, so+ // the last-written set won and earlier survivors were dropped. Pruning+ // several at once should leave the survivors in place.+ store.recordDelivery("old-1", at = 1_000L)+ store.recordDelivery("keep", at = 1_000_000_000_000L)+ store.recordDelivery("old-2", at = 1_000L)+ store.recordDelivery("keep-2", at = 1_000_000_000_000L)++ val now = 1_000L + pruneAfterMs + 1L+ store.prune(now)++ assertEquals(setOf("keep", "keep-2"), store.deliveredIds())+ assertEquals(0, store.deliveryCount("old-1"))+ assertEquals(0, store.deliveryCount("old-2"))+ assertEquals(1, store.deliveryCount("keep"))+ assertEquals(1, store.deliveryCount("keep-2"))+ }+}