Modern Apps git

← Modern-Apps.git

news: feed from server news.json; on-device search

Commit
f65b1c7fcd47fc4fc125bd8d4d40dde779ad4d3e
Author
Vayun Mathur <[email protected]>
When
2026-11-23 17:31 UTC (12 days ago)
Parents
2fcda9b
Primary feed is now one GET api.maproj.org/news.json
through Networking, filtered client-side to enabled
sources and merged into Room; the per-source sitemap
crawl remains as a failure fallback only. Article
reading stays on device. Search is fully local
(CommonSearchBar, 250ms debounce): title > source/
keyword > downloaded-body hits over the Room cache,
newest-first per tier, with the scale ceiling
documented (FTS is the next step at 10x cache).

Contract assumptions for the server side: source as
catalog id or exact display name, ISO/RFC1123/epoch
published_at, image_url optional, metered advisory
(not persisted; catalog badges cover it).

Verified: 24 tests green incl. server-primary,
fallback decision, ranking; lint green.

Diff

news/AGENTS.md
diff --git a/news/AGENTS.md b/news/AGENTS.mdindex 02a2818c93..74b1a2a9a8 100644--- a/news/AGENTS.md+++ b/news/AGENTS.md@@ -11,9 +11,15 @@ _Install: ./install news_ - Rust: no / screenshotTest: no  ## Overview-**Purpose:** Sitemap-driven news reader. Everything is on-device: feeds and-articles are fetched directly from publisher sites, parsed and extracted-locally. There is no backend and no account.+**Purpose:** News reader. Primary feed is our server's `GET /news.json`+(`https://api.maproj.org/news.json`, see `domain/ServerFeedParser` for the+contract + assumptions), merged into Room and filtered client-side by the+enabled sources. If the server fetch fails/times out/parses empty, refresh+falls back to the on-device per-source sitemap/RSS crawl of enabled sources+(cached feed stays visible either way). Article reading is always on-device:+publisher HTML is fetched directly and extracted locally. No account.+On-device search (feed screen) runs over the local corpus only — titles,+source names, sitemap keywords, downloaded bodies (`domain/NewsSearch`). **Key features:** - Built-in source catalog (`domain/SourceCatalog`) — Google News sitemaps   where a verified one exists, RSS only where no sitemap verifies (NPR, DW,@@ -47,8 +53,9 @@ Japan Times (sitemap URL serves HTML, not XML). `data/NewsRepository` (Room via `library/room`) + `data/NewsPrefs` (DataStore owner) → `network/Networking` (the single networking entry point, `NetworkClient` with `TrustBundle.SYSTEM` — publisher hosts are-arbitrary, so no reduced bundle can cover them) → `domain/` parsers and-extractor (pure, no Android imports).+arbitrary, so no reduced bundle can cover them; SYSTEM also covers+api.maproj.org, whereas FIRST_PARTY would break publisher fetches) →+`domain/` parsers and extractor (pure, no Android imports).  ## Entry points + reading order `Route` (`Feed` / `Reader(url)` / `Sources` / `Saved`) → `MainActivity.kt`
news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.ktindex 2a49953ab5..3df50fbf47 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt@@ -54,6 +54,26 @@ interface NewsDao {     @Query("SELECT * FROM CachedBody WHERE url = :url")     suspend fun body(url: String): CachedBody? +    // --- On-device search candidates (see NewsSearch for ranking/ceiling) ---++    /** Stubs whose title or sitemap keywords contain [term] (LIKE, case-insensitive for ASCII). */+    @Query(+        "SELECT * FROM CachedArticle WHERE title LIKE '%' || :term || '%' " ++            "OR keywords LIKE '%' || :term || '%' ORDER BY publishedAtMillis DESC LIMIT 200",+    )+    suspend fun searchStubHits(term: String): List<CachedArticle>++    /** All stubs from [sourceIds] (source-name search resolves names to ids in the repository). */+    @Query("SELECT * FROM CachedArticle WHERE sourceId IN (:sourceIds) ORDER BY publishedAtMillis DESC LIMIT 200")+    suspend fun articlesForSources(sourceIds: List<String>): List<CachedArticle>++    /** URLs whose downloaded body text contains [term] (blocksJson holds the paragraph text). */+    @Query("SELECT url FROM CachedBody WHERE blocksJson LIKE '%' || :term || '%' LIMIT 200")+    suspend fun bodyHitUrls(term: String): List<String>++    @Query("SELECT * FROM CachedArticle WHERE url IN (:urls)")+    suspend fun articlesByUrls(urls: List<String>): List<CachedArticle>+     @Upsert     suspend fun upsertArticles(articles: List<CachedArticle>) 
news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.ktindex 5c06a3b928..e8cc9f3762 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt@@ -8,8 +8,11 @@ import com.vayunmathur.news.domain.ArticleExtractor import com.vayunmathur.news.domain.ExtractedArticle import com.vayunmathur.news.domain.FeedArticle import com.vayunmathur.news.domain.FeedMerger+import com.vayunmathur.news.domain.NewsSearch import com.vayunmathur.news.domain.NewsSource+import com.vayunmathur.news.domain.ServerFeedParser import com.vayunmathur.news.domain.SitemapParser+import com.vayunmathur.news.domain.SourceCatalog import com.vayunmathur.news.network.Networking import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineDispatcher@@ -58,11 +61,55 @@ class NewsRepository internal constructor(         dao.setBookmarked(url, bookmarked)      /**-     * Fetches every enabled source in parallel; each source publishes-     * to Room as soon as it lands. Returns the names of sources that-     * failed or timed out (a failing source never fails the refresh).+     * Primary path: one fetch of the server's `news.json`, filtered+     * client-side to [sources] (the enabled sources) and merged into+     * Room exactly like a crawl result.+     *+     * Fallback decision: if the server fetch throws, times out, or+     * parses to zero articles, refresh falls back to the on-device+     * per-source sitemap/RSS crawl of the same enabled sources+     * ([refreshFromSources]). The cached Room feed stays visible+     * throughout either way. Returns failed source names from whichever+     * path ran; a successful server fetch (or a fully successful+     * fallback) returns an empty list.      */-    suspend fun refresh(sources: List<NewsSource>): List<String> = coroutineScope {+    suspend fun refresh(sources: List<NewsSource>): List<String> {+        val serverArticles = fetchServerFeed()+        if (serverArticles != null) {+            val enabledIds = sources.map { it.id }.toSet()+            val filtered = serverArticles.filter { it.sourceId in enabledIds }+            val capped = FeedMerger.merge(listOf(filtered), limit = MAX_CACHED_ARTICLES)+            if (capped.isNotEmpty()) publish(capped)+            if (sources.isNotEmpty()) dao.pruneArticles(keep = MAX_CACHED_ARTICLES)+            Log.dev(TAG, "refresh server feed landed articles=${capped.size} (pre-filter=${serverArticles.size})")+            return emptyList()+        }+        Log.dev(TAG, "refresh server feed unavailable; falling back to on-device source crawl")+        return refreshFromSources(sources)+    }++    /** Server feed articles, or null on transport failure / timeout / empty parse. */+    private suspend fun fetchServerFeed(): List<FeedArticle>? {+        val articles = try {+            withTimeoutOrNull(sourceTimeoutMs) {+                withContext(feedDispatcher) { ServerFeedParser.parse(fetch(Networking.SERVER_FEED_URL)) }+            }+        } catch (e: CancellationException) {+            throw e+        } catch (e: Exception) {+            Log.dev(TAG, "server feed failed ${e.javaClass.simpleName}")+            null+        }+        return articles?.takeIf { it.isNotEmpty() }+    }++    /**+     * Fallback crawl: fetches every enabled source in parallel; each+     * source publishes to Room as soon as it lands. Returns the names+     * of sources that failed or timed out (a failing source never+     * fails the refresh).+     */+    suspend fun refreshFromSources(sources: List<NewsSource>): List<String> = coroutineScope {         val failed = sources.map { source ->             async { fetchAndPublish(source) }         }.awaitAll().filterNotNull()@@ -70,6 +117,45 @@ class NewsRepository internal constructor(         failed     } +    /**+     * On-device search over the local corpus only (no server search):+     * titles, source names, sitemap keywords, and the full text of+     * already-downloaded bodies. Ranked by [NewsSearch] (title hits+     * first, then source/keyword, then body-only); see its ceiling doc.+     */+    suspend fun search(query: String): List<CachedArticle> {+        val terms = query.trim().lowercase().split(Regex("\\s+")).filter { it.length >= 2 }+        if (terms.isEmpty()) return emptyList()+        val stubsByUrl = LinkedHashMap<String, CachedArticle>()+        val bodyHits = mutableSetOf<String>()+        for (term in terms) {+            dao.searchStubHits(term).forEach { stubsByUrl[it.url] = it }+            bodyHits += dao.bodyHitUrls(term)+        }+        // Source-name hits: resolve matching catalog names/ids, then pull their stubs.+        val matchingSourceIds = SourceCatalog.sources+            .filter { source -> terms.any { source.name.lowercase().contains(it) || source.id.contains(it) } }+            .map { it.id }+        if (matchingSourceIds.isNotEmpty()) {+            dao.articlesForSources(matchingSourceIds).forEach { stubsByUrl[it.url] = it }+        }+        // Body-only hits may be stubs the title/keyword queries missed.+        val missingBodyUrls = bodyHits.filter { it !in stubsByUrl }+        if (missingBodyUrls.isNotEmpty()) {+            dao.articlesByUrls(missingBodyUrls).forEach { stubsByUrl[it.url] = it }+        }+        val candidates = stubsByUrl.values.map { article ->+            NewsSearch.Candidate(+                article = article.toFeedArticle(),+                sourceName = SourceCatalog.byId(article.sourceId)?.name ?: article.sourceId,+                bodyHit = article.url in bodyHits,+            )+        }+        val rankedUrls = NewsSearch.rank(query, candidates).map { it.url }+        val byUrl = stubsByUrl.toMap()+        return rankedUrls.mapNotNull { byUrl[it] }+    }+     /** Fetches + publishes one source; returns its name on failure/timeout, else null. */     private suspend fun fetchAndPublish(source: NewsSource): String? {         val startedNanos = System.nanoTime()@@ -165,6 +251,12 @@ class NewsRepository internal constructor(     } } +internal fun CachedArticle.toFeedArticle(): FeedArticle = FeedArticle(+    url = url, sourceId = sourceId, title = title, publishedAtMillis = publishedAtMillis,+    imageUrl = imageUrl,+    keywords = keywords.split(",").map { it.trim() }.filter { it.isNotEmpty() },+)+ internal fun ExtractedArticle.toCached(json: Json): CachedBody = CachedBody(     url = url, title = title, byline = byline, publishedAtMillis = publishedAtMillis,     heroImageUrl = heroImageUrl,
news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt b/news/src/main/java/com/vayunmathur/news/domain/FeedModels.ktindex e9678d33e8..04e3e79855 100644--- a/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/FeedModels.kt@@ -10,6 +10,8 @@ data class FeedArticle(     val publishedAtMillis: Long,     val imageUrl: String? = null,     val keywords: List<String> = emptyList(),+    /** Server-feed only: source meters this article. Not persisted (catalog badges cover it). */+    val metered: Boolean = false, )  /** One block of an extracted article body, in reading order. */
news/src/main/java/com/vayunmathur/news/domain/NewsSearch.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/NewsSearch.kt b/news/src/main/java/com/vayunmathur/news/domain/NewsSearch.ktnew file mode 100644index 0000000000..7f5cd0b03c--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/NewsSearch.kt@@ -0,0 +1,46 @@+package com.vayunmathur.news.domain++/**+ * On-device search ranking over the local corpus. Pure and total.+ *+ * Corpus + ceiling: this ranks candidates the repository already pulled+ * from Room with `LIKE` queries (titles / keywords / source ids on the+ * stubs, `blocksJson` on downloaded bodies). The cache is pruned to+ * ~500 stubs and bodies exist only for articles the user has opened,+ * so a `LIKE` scan is a few hundred rows / a few MB of JSON at most —+ * no FTS index is warranted at this scale. If the cache cap ever grows+ * by an order of magnitude, move bodies to an FTS table instead.+ *+ * Ranking tiers (newest first inside a tier):+ * 0. title matches, 1. source-name / keyword matches, 2. body-only matches.+ */+object NewsSearch {++    /** One searchable stub: a [FeedArticle] plus whether its cached body matched. */+    data class Candidate(+        val article: FeedArticle,+        val sourceName: String,+        val bodyHit: Boolean,+    )++    fun rank(query: String, candidates: List<Candidate>, limit: Int = 50): List<FeedArticle> {+        val phrase = query.trim().lowercase()+        if (phrase.isEmpty()) return emptyList()+        val terms = phrase.split(Regex("\\s+")).filter { it.isNotEmpty() }+        fun String.matches(): Boolean =+            lowercase().let { text -> text.contains(phrase) || terms.any { text.contains(it) } }+        return candidates.mapNotNull { candidate ->+            val article = candidate.article+            val tier = when {+                article.title.matches() -> 0+                candidate.sourceName.matches() || article.keywords.any { it.matches() } -> 1+                candidate.bodyHit -> 2+                else -> return@mapNotNull null+            }+            tier to article+        }.sortedWith(+            compareBy<Pair<Int, FeedArticle>> { it.first }+                .thenByDescending { it.second.publishedAtMillis },+        ).take(limit).map { it.second }+    }+}
news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt b/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.ktnew file mode 100644index 0000000000..d97dcd1563--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt@@ -0,0 +1,81 @@+package com.vayunmathur.news.domain++import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.contentOrNull+import kotlinx.serialization.json.jsonArray+import kotlinx.serialization.json.jsonObject++/**+ * Parser for the location_share_server `GET /news.json` contract:+ *+ * ```+ * { "generated_at": ..., "articles": [+ *     { "title": ..., "url": ..., "source": ..., "published_at": ...,+ *       "image_url": ..., "metered": false } ] }+ * ```+ *+ * Contract assumptions (flagged for reconciliation with the server agent):+ * - `source` is a [SourceCatalog] id (`bbc`) or its exact display name+ *   (`BBC News`); both resolve to the catalog id. Anything else is kept+ *   verbatim as the sourceId — such articles are then dropped by the+ *   repository's enabled-source filter, so an unrecognised source value+ *   degrades to "that source is missing", never to wrong attribution.+ * - `published_at` is an ISO-8601/RFC-1123 string (parsed by+ *   [DateParsing]) or epoch seconds/millis as a JSON number.+ * - `image_url` may be absent/null; `metered` may be absent (defaults+ *   false). `metered` is carried on [FeedArticle] but not persisted:+ *   the catalog already badges metered sources in the Sources screen.+ *+ * Pure and non-throwing: malformed documents/articles yield an empty or+ * partial list, which the repository treats as server-feed failure and+ * falls back to the on-device sitemap crawl.+ */+object ServerFeedParser {+    private val json = Json { ignoreUnknownKeys = true }++    fun parse(text: String): List<FeedArticle> {+        val root = runCatching { json.parseToJsonElement(text).jsonObject }.getOrNull() ?: return emptyList()+        val articles: JsonArray = root["articles"]?.let {+            runCatching { it.jsonArray }.getOrNull()+        } ?: return emptyList()+        return articles.mapNotNull { element ->+            val obj = runCatching { element.jsonObject }.getOrNull() ?: return@mapNotNull null+            parseArticle(obj)+        }+    }++    private fun parseArticle(obj: JsonObject): FeedArticle? {+        val url = obj.string("url")?.takeIf { it.startsWith("http") } ?: return null+        val title = obj.string("title")?.takeIf { it.isNotBlank() } ?: return null+        val sourceRaw = obj.string("source")?.takeIf { it.isNotBlank() } ?: return null+        return FeedArticle(+            url = url,+            sourceId = resolveSourceId(sourceRaw),+            title = title,+            publishedAtMillis = parsePublishedAt(obj["published_at"]),+            imageUrl = obj.string("image_url"),+            metered = (obj["metered"] as? JsonPrimitive)?.contentOrNull?.toBooleanStrictOrNull() ?: false,+        )+    }++    /** Catalog id for a catalog id or exact catalog name; otherwise [raw] verbatim. */+    fun resolveSourceId(raw: String): String {+        val trimmed = raw.trim()+        SourceCatalog.byId(trimmed)?.let { return it.id }+        return SourceCatalog.sources.firstOrNull { it.name.equals(trimmed, ignoreCase = true) }?.id ?: trimmed+    }++    private fun parsePublishedAt(element: kotlinx.serialization.json.JsonElement?): Long {+        val primitive = element as? JsonPrimitive ?: return 0L+        if (primitive.isString) return DateParsing.parseMillis(primitive.contentOrNull) ?: 0L+        val value = primitive.contentOrNull?.toLongOrNull() ?: return 0L+        // < 10^10 is epoch seconds (year 2286 in millis terms); else millis.+        return if (value in 1 until 10_000_000_000L) value * 1_000L else value+    }++    private fun JsonObject.string(key: String): String? =+        (this[key] as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf { it.isNotEmpty() }+}
news/src/main/java/com/vayunmathur/news/network/Networking.kt
diff --git a/news/src/main/java/com/vayunmathur/news/network/Networking.kt b/news/src/main/java/com/vayunmathur/news/network/Networking.ktindex 511ae756ed..90298aa54e 100644--- a/news/src/main/java/com/vayunmathur/news/network/Networking.kt+++ b/news/src/main/java/com/vayunmathur/news/network/Networking.kt@@ -6,11 +6,22 @@ import java.io.IOException /**  * The news app's single networking entry point. Owns the client, the  * browser-like request headers publisher CDNs expect, and status mapping.- * Every fetch is a direct GET of a publisher URL — there is no backend.- * Trust is SYSTEM, initialised in MainActivity, because publisher hosts- * are arbitrary public sites (see TrustBundle docs).+ *+ * Feed primary path is our server's `GET /news.json` at [SERVER_FEED_URL]+ * — `https://api.maproj.org`, the same API host findfamily/everysync use+ * (root AGENTS.md: "The server's canonical API host is api.maproj.org").+ * Article bodies and the offline sitemap/RSS fallback still fetch+ * publisher URLs directly on-device.+ *+ * Trust stays SYSTEM (initialised in MainActivity), not FIRST_PARTY:+ * FIRST_PARTY pins only cover api.maproj.org and would break every+ * publisher fetch, while SYSTEM (platform roots, incl. the public CA+ * chain api.maproj.org serves) covers both. Narrowing would need a+ * per-host client, which NetworkClient does not offer.  */ object Networking {+    /** Server feed (location_share_server `GET /news.json`); see ServerFeedParser for the contract. */+    const val SERVER_FEED_URL = "https://api.maproj.org/news.json"     private val headers = mapOf(         "User-Agent" to "Mozilla/5.0 (Linux; Android 14) NewsReader",         "Accept" to "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt
diff --git a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.ktindex b07f4f4417..03d29e7b85 100644--- a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt+++ b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt@@ -37,6 +37,29 @@ class NewsViewModel(     private val _sourceFilter = MutableStateFlow(FILTER_ALL)     val sourceFilter: StateFlow<String> = _sourceFilter.asStateFlow() +    private val _searchQuery = MutableStateFlow("")+    val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()+    private val _searchResults = MutableStateFlow<List<CachedArticle>>(emptyList())+    val searchResults: StateFlow<List<CachedArticle>> = _searchResults.asStateFlow()+    private var searchJob: kotlinx.coroutines.Job? = null++    /** Debounced on-device search (local corpus only); blank query clears results. */+    fun setSearchQuery(query: String) {+        _searchQuery.value = query+        searchJob?.cancel()+        if (query.isBlank()) {+            _searchResults.value = emptyList()+            return+        }+        searchJob = viewModelScope.launch {+            kotlinx.coroutines.delay(SEARCH_DEBOUNCE_MS)+            val results = runCatching { repository.search(query) }.getOrDefault(emptyList())+            if (_searchQuery.value == query) {+                _searchResults.value = results.filter { it.sourceId !in disabledSourceIds.value }+            }+        }+    }+     val disabledSourceIds: StateFlow<Set<String>> = prefs.disabledSourceIds         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet()) @@ -121,6 +144,10 @@ class NewsViewModel(     fun setReaderSerif(serif: Boolean) {         viewModelScope.launch { prefs.setReaderSerif(serif) }     }++    companion object {+        const val SEARCH_DEBOUNCE_MS = 250L+    } }  /** Factory wiring the repository and prefs owners into [NewsViewModel]. */
news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.ktindex 13a5a73df3..d5fa6d4dca 100644--- a/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt@@ -13,6 +13,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold+import com.vayunmathur.library.ui.CommonSearchBar import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.IconBookmark import com.vayunmathur.library.ui.IconButton@@ -36,6 +37,10 @@ fun FeedScreen(     val refreshFailed by viewModel.refreshFailed.collectAsState()     val filter by viewModel.sourceFilter.collectAsState()     val disabled by viewModel.disabledSourceIds.collectAsState()+    val searchQuery by viewModel.searchQuery.collectAsState()+    val searchResults by viewModel.searchResults.collectAsState()+    val searching = searchQuery.isNotBlank()+    val shownArticles = if (searching) searchResults else articles     AppScaffold(         title = stringResource(R.string.feed_title),         isRefreshing = isRefreshing,@@ -46,6 +51,12 @@ fun FeedScreen(         },     ) { padding ->         Column(modifier = Modifier.fillMaxSize().padding(padding)) {+            CommonSearchBar(+                value = searchQuery,+                onValueChange = viewModel::setSearchQuery,+                placeholder = stringResource(R.string.feed_search_placeholder),+            )+            if (!searching) {             LazyRow(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {                 item {                     FilterChip(@@ -63,20 +74,21 @@ fun FeedScreen(                     )                 }             }-            if (refreshFailed) {+            }+            if (refreshFailed && !searching) {                 Text(                     stringResource(R.string.feed_refresh_failed),                     modifier = Modifier.padding(horizontal = 16.dp, vertical = 4.dp),                 )             }-            if (articles.isEmpty() && !isRefreshing) {+            if (shownArticles.isEmpty() && !isRefreshing) {                 Text(-                    stringResource(R.string.feed_empty),+                    stringResource(if (searching) R.string.feed_search_empty else R.string.feed_empty),                     modifier = Modifier.padding(16.dp),                 )             }             LazyColumn(modifier = Modifier.fillMaxSize()) {-                items(articles, key = { it.url }) { article ->+                items(shownArticles, key = { it.url }) { article ->                     ArticleRow(                         article = article,                         onClick = { onOpenArticle(article.url) },
news/src/main/res/values/strings.xml
diff --git a/news/src/main/res/values/strings.xml b/news/src/main/res/values/strings.xmlindex be73fc4242..5a52769f57 100644--- a/news/src/main/res/values/strings.xml+++ b/news/src/main/res/values/strings.xml@@ -6,6 +6,8 @@     <string name="feed_empty">No articles yet. Pull to refresh.</string>     <string name="feed_all_sources">All</string>     <string name="feed_refresh_failed">Could not refresh all sources; showing the cached feed.</string>+    <string name="feed_search_placeholder">Search downloaded news</string>+    <string name="feed_search_empty">No downloaded articles match. Search covers titles and articles you have opened.</string>     <!-- ReaderScreen -->     <string name="reader_title">Article</string>     <string name="reader_text_smaller">Smaller text</string>@@ -15,7 +17,7 @@     <string name="reader_loading_failed">Could not load this article.</string>     <!-- SourcesScreen -->     <string name="sources_title">Sources</string>-    <string name="sources_note">Articles are fetched directly from each publisher. No account and no server of ours is involved.</string>+    <string name="sources_note">The feed comes from our news server; turning a source off filters it out here. If the server is unreachable, the app crawls the sources left on directly. Article pages are always read directly from the publisher. No account is involved.</string>     <!-- SavedScreen -->     <string name="saved_title">Saved for later</string>     <string name="saved_empty">Nothing saved yet. Save an article from the reader to read it offline later.</string>
news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt b/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.ktnew file mode 100644index 0000000000..cc7a319514--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.news.data++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.news.domain.SourceCatalog+import com.vayunmathur.news.network.Networking+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import kotlinx.coroutines.withTimeout+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Server-primary refresh, fallback decision, source filtering, and on-device search. */+@RunWith(RobolectricTestRunner::class)+class NewsServerFeedTest {+    @org.junit.Before fun setUp() { com.vayunmathur.news.seedNewsDb(ApplicationProvider.getApplicationContext()) }++    private val serverJson = """+        {"generated_at":"2026-11-23T12:00:00Z","articles":[+          {"title":"Server Alpha Volcano","url":"https://srv.example/alpha","source":"bbc",+           "published_at":"2026-11-23T10:00:00Z"},+          {"title":"Server Beta","url":"https://srv.example/beta","source":"guardian",+           "published_at":"2026-11-23T09:00:00Z"}+        ]}+    """.trimIndent()++    private val fallbackUrlset = """+        <urlset><url><loc>https://srv.example/fallback-story</loc>+        <news:title>Fallback Story</news:title></url></urlset>+    """.trimIndent()++    private val articleHtml = """+        <html><head><meta property="og:title" content="Server Beta"/></head><body><article>+        <p>Deep inside this downloaded body there is a quixotic paragraph about tides and harbours.</p>+        <p>Second paragraph keeps the extraction comfortably above the minimum block count here.</p>+        </article></body></html>+    """.trimIndent()++    @Test fun refreshPrefersServerFeedAndDoesNotCrawl() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Context>()+        val calls = mutableListOf<String>()+        val repo = NewsRepository(context, fetch = { url -> calls += url; serverJson })+        val failed = repo.refresh(SourceCatalog.sources)+        assertTrue(failed.isEmpty())+        assertEquals(listOf(Networking.SERVER_FEED_URL), calls, "primary path must be the single server fetch")+        val cached = withTimeout(10_000) { repo.articles.first { a -> a.any { it.url == "https://srv.example/alpha" } } }+        assertTrue(cached.any { it.title == "Server Alpha Volcano" })+    }++    @Test fun refreshFiltersServerFeedToEnabledSources() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Context>()+        val filterJson = """+            {"generated_at":"2026-11-23T12:00:00Z","articles":[+              {"title":"Filter Kept","url":"https://srv.example/filter-kept","source":"bbc",+               "published_at":"2026-11-23T10:00:00Z"},+              {"title":"Filter Dropped","url":"https://srv.example/filter-dropped","source":"guardian",+               "published_at":"2026-11-23T09:00:00Z"}+            ]}+        """.trimIndent()+        val repo = NewsRepository(context, fetch = { filterJson })+        // Only BBC enabled: the Guardian server article must be filtered client-side.+        val failed = repo.refresh(listOf(SourceCatalog.byId("bbc")!!))+        assertTrue(failed.isEmpty())+        val cached = withTimeout(10_000) { repo.articles.first { a -> a.any { it.url == "https://srv.example/filter-kept" } } }+        assertTrue(cached.none { it.url == "https://srv.example/filter-dropped" })+    }++    @Test fun serverFailureFallsBackToSourceCrawl() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Context>()+        val calls = mutableListOf<String>()+        val repo = NewsRepository(context, fetch = { url ->+            calls += url+            if (url == Networking.SERVER_FEED_URL) throw IOException("server unreachable")+            fallbackUrlset+        })+        val bbc = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://srv.example/fallback.xml")+        val failed = repo.refresh(listOf(bbc))+        assertTrue(failed.isEmpty(), "fallback crawl success must not report failure")+        assertTrue(calls.first() == Networking.SERVER_FEED_URL, "server must be tried first")+        assertTrue(calls.any { it.endsWith("fallback.xml") }, "fallback must crawl the enabled source")+        val cached = withTimeout(10_000) { repo.articles.first { a -> a.any { it.title == "Fallback Story" } } }+        assertTrue(cached.any { it.title == "Fallback Story" })+    }++    @Test fun searchRanksTitleHitBeforeDownloadedBodyHit() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Context>()+        val repo = NewsRepository(context, fetch = { url ->+            when {+                url == Networking.SERVER_FEED_URL -> serverJson+                url.endsWith("/beta") -> articleHtml+                else -> serverJson+            }+        })+        repo.refresh(SourceCatalog.sources)+        withTimeout(10_000) { repo.articles.first { a -> a.any { it.url == "https://srv.example/beta" } } }+        // Title hit: "volcano" is only in Alpha's title.+        val titleResults = repo.search("volcano")+        assertEquals("https://srv.example/alpha", titleResults.firstOrNull()?.url)+        // Body hit: download Beta's body, then a body-only term must find it,+        // ranked after a title hit for a shared term is covered in NewsSearchTest.+        repo.articleBody("https://srv.example/beta")+        val bodyResults = repo.search("quixotic")+        assertEquals(listOf("https://srv.example/beta"), bodyResults.map { it.url }.filter { it.endsWith("/beta") })+        // Source-name search finds that source's stubs.+        val sourceResults = repo.search("guardian")+        assertTrue(sourceResults.any { it.url == "https://srv.example/beta" })+    }+}
news/src/test/java/com/vayunmathur/news/domain/NewsSearchTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/NewsSearchTest.kt b/news/src/test/java/com/vayunmathur/news/domain/NewsSearchTest.ktnew file mode 100644index 0000000000..1897c4f1e3--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/domain/NewsSearchTest.kt@@ -0,0 +1,33 @@+package com.vayunmathur.news.domain++import kotlin.test.Test+import kotlin.test.assertEquals++class NewsSearchTest {+    private fun candidate(url: String, title: String, published: Long, bodyHit: Boolean = false, source: String = "BBC News") =+        NewsSearch.Candidate(FeedArticle(url, "bbc", title, published), source, bodyHit)++    @Test fun titleHitsRankBeforeBodyHits() {+        val ranked = NewsSearch.rank(+            "volcano",+            listOf(+                candidate("https://e/newer-body", "Unrelated title", 300, bodyHit = true),+                candidate("https://e/older-title", "Volcano erupts", 100),+                candidate("https://e/no-hit", "Other news", 400),+            ),+        )+        assertEquals(listOf("https://e/older-title", "https://e/newer-body"), ranked.map { it.url })+    }++    @Test fun withinTierNewestFirstAndBlankQueryEmpty() {+        val ranked = NewsSearch.rank(+            "election",+            listOf(+                candidate("https://e/old", "Election one", 100),+                candidate("https://e/new", "Election two", 200),+            ),+        )+        assertEquals(listOf("https://e/new", "https://e/old"), ranked.map { it.url })+        assertEquals(emptyList(), NewsSearch.rank("  ", listOf(candidate("https://e/x", "Election", 1))))+    }+}
news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.kt b/news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.ktnew file mode 100644index 0000000000..13d2d4ad3a--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/domain/ServerFeedParserTest.kt@@ -0,0 +1,37 @@+package com.vayunmathur.news.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class ServerFeedParserTest {+    private val fixture = """+        {"generated_at":"2026-11-23T12:00:00Z","articles":[+          {"title":"Server Story","url":"https://example.com/a","source":"bbc",+           "published_at":"2026-11-23T10:00:00Z","image_url":"https://example.com/a.jpg","metered":true},+          {"title":"Named Source","url":"https://example.com/b","source":"The Guardian",+           "published_at":1795420000},+          {"title":"No Image","url":"https://example.com/c","source":"npr",+           "published_at":"2026-11-23T08:00:00+00:00"}+        ]}+    """.trimIndent()++    @Test fun parsesContractFixture() {+        val articles = ServerFeedParser.parse(fixture)+        assertEquals(3, articles.size)+        val first = articles[0]+        assertEquals("bbc", first.sourceId)+        assertEquals("https://example.com/a.jpg", first.imageUrl)+        assertTrue(first.metered)+        assertTrue(first.publishedAtMillis > 0)+        assertEquals("guardian", articles[1].sourceId, "exact catalog name must resolve to catalog id")+        assertEquals(1_795_420_000_000L, articles[1].publishedAtMillis, "epoch seconds must become millis")+        assertEquals(null, articles[2].imageUrl)+    }++    @Test fun malformedInputIsEmptyNotThrowing() {+        assertTrue(ServerFeedParser.parse("not json").isEmpty())+        assertTrue(ServerFeedParser.parse("""{"articles":[{"title":"x"}]}""").isEmpty())+        assertTrue(ServerFeedParser.parse("""{}""").isEmpty())+    }+}