Modern Apps git

← Modern-Apps.git

news: sources toggle removed; Top stories ranking

Commit
4979b4cba8333cc335fadd245f3712ea51458ce4
Author
Vayun Mathur <[email protected]>
When
2026-11-23 20:07 UTC (12 days ago)
Parents
86d761e
Per-source enable/disable is gone (legacy prefs key
cleaned on init); Sources is now a read-only directory
with cached counts. Default feed order is Top stories,
not latest-first: recency score with an 18h half-life
(+5 image, +2 keywords), story clustering across
outlets (normalised-title exact or Jaccard >= 0.85,
representative = earliest, row shows +N sources), and
a diversity cap (max 3 per source in the first 20).
Latest remains a persisted selector; search keeps its
own relevance ranking.

Verified: 42 news tests green incl. ranking, cluster
collapse, persistence, directory tests.

Diff

news/AGENTS.md
diff --git a/news/AGENTS.md b/news/AGENTS.mdindex 74b1a2a9a8..4471671602 100644--- a/news/AGENTS.md+++ b/news/AGENTS.md@@ -13,9 +13,12 @@ _Install: ./install news_ ## Overview **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+contract + assumptions), merged into Room. Every source is always in the+corpus (no per-source toggle; the Sources screen is a read-only+directory); category + search are the filters, and the persisted+Top stories / Latest sort (`domain/FeedRanking`) orders the feed+client-side. If the server fetch fails/times out/parses empty, refresh+falls back to the on-device per-source sitemap/RSS crawl of all 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,
news/src/main/java/com/vayunmathur/news/Route.kt
diff --git a/news/src/main/java/com/vayunmathur/news/Route.kt b/news/src/main/java/com/vayunmathur/news/Route.ktindex 7f0b2ebb6c..9d4fa3749d 100644--- a/news/src/main/java/com/vayunmathur/news/Route.kt+++ b/news/src/main/java/com/vayunmathur/news/Route.kt@@ -7,7 +7,7 @@ import kotlinx.serialization.Serializable /** Navigation destinations for the news app. */ sealed interface Route : NavKey {     @Serializable-    /** Merged, newest-first feed across enabled sources. */+    /** Merged feed across all sources (Top stories by default). */     data object Feed : Route      @Serializable@@ -15,7 +15,7 @@ sealed interface Route : NavKey {     data class Reader(val url: String) : Route      @Serializable-    /** Enable/disable built-in sources. */+    /** Read-only directory of built-in sources. */     data object Sources : Route      @Serializable
news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.ktindex 1d541143a6..942698f25c 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt@@ -4,8 +4,10 @@ import android.content.Context import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey+import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.core.stringSetPreferencesKey import androidx.datastore.preferences.preferencesDataStore+import com.vayunmathur.news.domain.FeedSort import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.catch import kotlinx.coroutines.flow.map@@ -14,9 +16,15 @@ import java.io.IOException private val Context.newsDataStore by preferencesDataStore(name = "news")  /**- * The app's only preferences owner. Enabled sources and reader settings.- * A corrupt DataStore file reads as the documented defaults (all sources- * enabled, 17sp sans) instead of crashing — see the catch in [safeData].+ * The app's only preferences owner. Feed sort and reader settings.+ * A corrupt DataStore file reads as the documented defaults (Top+ * stories, 17sp sans) instead of crashing — see the catch in [safeData].+ *+ * There is no per-source enable/disable any more: every source is+ * always in the corpus, and categories + search are the filters. The+ * legacy `disabled_sources` key (and the stale `reader_web_view` value)+ * is never read; [clearLegacySourcePrefs] removes it when present so+ * stale values cannot linger or crash anything.  */ class NewsPrefs(context: Context) {     private val appContext = context.applicationContext@@ -26,17 +34,21 @@ class NewsPrefs(context: Context) {             if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e         } -    /** Null means "never set": every source is enabled by default. */-    val disabledSourceIds: Flow<Set<String>> = safeData.map { it[DISABLED_SOURCES] ?: emptySet() }+    /** Persisted feed order; absent or unrecognised reads as Top stories. */+    val feedSort: Flow<FeedSort> = safeData.map { prefs ->+        FeedSort.entries.firstOrNull { it.name == prefs[FEED_SORT] } ?: FeedSort.TOP+    }     val readerTextSp: Flow<Int> = safeData.map { it[TEXT_SP] ?: DEFAULT_TEXT_SP }     val readerSerif: Flow<Boolean> = safeData.map { it[SERIF] ?: false }-    // A stale "reader_web_view" value from before the WebView toggle was-    // removed is simply never read again, so it is ignored safely. -    suspend fun setSourceEnabled(id: String, enabled: Boolean) {+    suspend fun setFeedSort(sort: FeedSort) {+        appContext.newsDataStore.edit { it[FEED_SORT] = sort.name }+    }++    /** Drops the retired per-source toggle state, if an old install left any. */+    suspend fun clearLegacySourcePrefs() {         appContext.newsDataStore.edit { prefs ->-            val current = prefs[DISABLED_SOURCES] ?: emptySet()-            prefs[DISABLED_SOURCES] = if (enabled) current - id else current + id+            if (prefs.contains(LEGACY_DISABLED_SOURCES)) prefs.remove(LEGACY_DISABLED_SOURCES)         }     } @@ -52,7 +64,8 @@ class NewsPrefs(context: Context) {         const val DEFAULT_TEXT_SP = 17         const val MIN_TEXT_SP = 13         const val MAX_TEXT_SP = 24-        private val DISABLED_SOURCES = stringSetPreferencesKey("disabled_sources")+        private val LEGACY_DISABLED_SOURCES = stringSetPreferencesKey("disabled_sources")+        private val FEED_SORT = stringPreferencesKey("feed_sort")         private val TEXT_SP = intPreferencesKey("reader_text_sp")         private val SERIF = booleanPreferencesKey("reader_serif")     }
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 8cc736a892..72a489b218 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt@@ -61,13 +61,15 @@ class NewsRepository internal constructor(         dao.setBookmarked(url, bookmarked)      /**-     * 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.+     * Primary path: one fetch of the server's `news.json`, merged into+     * Room exactly like a crawl result. Every source the server carries+     * is always included — there is no client-side enabled-source+     * filter; categories and search are the filters. [sources] only+     * drives the fallback crawl.      *      * 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+     * per-source sitemap/RSS crawl of [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@@ -76,12 +78,10 @@ class NewsRepository internal constructor(     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)+            val capped = FeedMerger.merge(listOf(serverArticles), 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})")+            dao.pruneArticles(keep = MAX_CACHED_ARTICLES)+            Log.dev(TAG, "refresh server feed landed articles=${capped.size}")             return emptyList()         }         Log.dev(TAG, "refresh server feed unavailable; falling back to on-device source crawl")@@ -104,7 +104,7 @@ class NewsRepository internal constructor(     }      /**-     * Fallback crawl: fetches every enabled source in parallel; each+     * Fallback crawl: fetches every 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).
news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt b/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.ktnew file mode 100644index 0000000000..c21f45c722--- /dev/null+++ b/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt@@ -0,0 +1,191 @@+package com.vayunmathur.news.domain++import kotlin.math.pow++/** Feed order, persisted by the prefs owner. Search ignores this (relevance wins). */+enum class FeedSort(val label: String) {+    TOP("Top stories"),+    LATEST("Latest"),+}++/** One ranked representative plus how many near-duplicate sources it collapsed. */+data class RankedArticle(+    val article: FeedArticle,+    /** Extra sources carrying the same story (0 = carried by one source only). */+    val alsoFromSources: Int = 0,+)++/**+ * Client-side feed ranking over the merged corpus. The server's+ * `news.json` stays newest-first; this is applied on device only, over+ * whatever category filter already narrowed the corpus. Search never+ * goes through here — it keeps its [NewsSearch] relevance ranking.+ *+ * ## Top stories formula (no popularity data exists, so on-device signals only)+ *+ * Score (per article, before clustering):+ * ```+ * ageHours = max(0, (now - publishedAtMillis) / 3_600_000)   // future stamps clamp to 0+ * score    = 100 * 0.5^(ageHours / 18)                       // 18 h half-life+ *          + 5 if imageUrl != null+ *          + 2 if keywords is non-empty+ * ```+ * So a fresh story scores ~100–107, a story 18 h old ~50, 36 h old ~25,+ * 3 days old ~6 — day-old sinks but does not vanish. An unknown+ * timestamp (`publishedAtMillis <= 0`) scores 0 and sinks to the end.+ * Ties break on newer `publishedAtMillis`, then URL, so the order is+ * total and deterministic.+ *+ * ## Story clustering (collapse before ranking)+ *+ * Titles are normalised (lower-case, punctuation dropped, whitespace+ * collapsed, a leading "source:" / "source -" prefix stripped) and+ * grouped: exact normalised-title matches always collapse, and two+ * titles also collapse when their token sets have Jaccard similarity+ * >= 0.85 and both have at least 4 tokens (union-find over the title+ * list; single-linkage, so A~B and B~C merge one story). Cluster size+ * is capped at [MAX_CLUSTER_INPUTS] compared pairs only for perf — the+ * corpus is ~500 stubs, so the O(n²) token comparison is trivial.+ * This threshold is deliberately conservative: it merges wire-copy+ * rewrites of one headline, not merely related coverage. Each cluster+ * keeps one representative: earliest `publishedAtMillis` (wire copy+ * originates once), tie-broken by fuller metadata (image, then more+ * keywords, then URL); the representative reports+ * `cluster size - 1` as [RankedArticle.alsoFromSources].+ *+ * ## Source diversity (interleave after scoring)+ *+ * Greedy fill in score order with a first-page cap: while the output+ * has fewer than [FIRST_PAGE_SIZE] (20) rows, one source may contribute+ * at most [FIRST_PAGE_PER_SOURCE] (3) of them; if every remaining+ * candidate is from a capped source the cap is relaxed for that pick+ * (a one-source corpus still fills the page). Past the first page the+ * cap lifts, but the same source never runs 3 times consecutively+ * while another source remains. Net effect: a high-volume wire+ * (BBC/G1 at ~100 items) can own at most 3 of the first 20 rows, and+ * the first screen always spans at least 7 sources when that many+ * have fresh stories.+ *+ * Latest is a plain newest-first sort with the same clustering+ * collapse (a duplicated wire story is one row in either order).+ */+object FeedRanking {++    const val HALF_LIFE_HOURS = 18.0+    const val IMAGE_BONUS = 5.0+    const val KEYWORD_BONUS = 2.0+    const val FIRST_PAGE_SIZE = 20+    const val FIRST_PAGE_PER_SOURCE = 3+    const val NEAR_DUPLICATE_JACCARD = 0.85+    const val MIN_TOKENS_FOR_NEAR_DUPLICATE = 4++    /** Rank [articles] for the feed; [nowMillis] is injected for tests. */+    fun rank(+        articles: List<FeedArticle>,+        sort: FeedSort,+        nowMillis: Long,+    ): List<RankedArticle> {+        val clusters = cluster(articles)+        return when (sort) {+            FeedSort.LATEST -> clusters.sortedWith(+                compareByDescending<RankedArticle> { it.article.publishedAtMillis }+                    .thenBy { it.article.url },+            )+            FeedSort.TOP -> diversify(clusters, nowMillis)+        }+    }++    /** Ranking score of one article under Top stories (see KDoc formula). */+    fun score(article: FeedArticle, nowMillis: Long): Double {+        if (article.publishedAtMillis <= 0L) return 0.0+        val ageHours = ((nowMillis - article.publishedAtMillis).coerceAtLeast(0L)) / 3_600_000.0+        var score = 100.0 * 0.5.pow(ageHours / HALF_LIFE_HOURS)+        if (article.imageUrl != null) score += IMAGE_BONUS+        if (article.keywords.isNotEmpty()) score += KEYWORD_BONUS+        return score+    }++    /** Normalised comparison form of a headline (see KDoc). */+    fun normaliseTitle(title: String): String {+        var text = title.trim().lowercase()+        // Strip a leading "source:" / "source -" wire prefix, if it is short.+        val separators = listOf(text.indexOf(": "), text.indexOf(" - ")).filter { it >= 0 }+        val prefixEnd = separators.minOrNull() ?: -1+        if (prefixEnd in 1..24) {+            val skip = if (text.startsWith(": ", prefixEnd)) 2 else 3+            text = text.substring(prefixEnd + skip).trim()+        }+        return text.replace(Regex("[^\\p{L}\\p{N}]+"), " ").trim().replace(Regex("\\s+"), " ")+    }++    private fun cluster(articles: List<FeedArticle>): List<RankedArticle> {+        if (articles.isEmpty()) return emptyList()+        val normalised = articles.map { normaliseTitle(it.title) }+        val tokens = normalised.map { if (it.isEmpty()) emptySet() else it.split(' ').toSet() }+        val parent = IntArray(articles.size) { it }+        fun find(x: Int): Int {+            var root = x+            while (parent[root] != root) root = parent[root]+            return root+        }+        fun union(a: Int, b: Int) {+            val ra = find(a); val rb = find(b)+            if (ra != rb) parent[maxOf(ra, rb)] = minOf(ra, rb)+        }+        for (i in articles.indices) {+            if (normalised[i].isEmpty()) continue+            for (j in i + 1 until articles.size) {+                if (normalised[j].isEmpty()) continue+                if (normalised[i] == normalised[j]) {+                    union(i, j)+                } else if (tokens[i].size >= MIN_TOKENS_FOR_NEAR_DUPLICATE &&+                    tokens[j].size >= MIN_TOKENS_FOR_NEAR_DUPLICATE+                ) {+                    val unionSize = (tokens[i] union tokens[j]).size+                    if (unionSize > 0 &&+                        (tokens[i] intersect tokens[j]).size.toDouble() / unionSize >= NEAR_DUPLICATE_JACCARD+                    ) {+                        union(i, j)+                    }+                }+            }+        }+        return articles.indices.groupBy { find(it) }.values.map { group ->+            val members = group.map { articles[it] }+            val representative = members.sortedWith(+                compareBy<FeedArticle> { it.publishedAtMillis }+                    .thenByDescending { it.imageUrl != null }+                    .thenByDescending { it.keywords.size }+                    .thenBy { it.url },+            ).first()+            RankedArticle(representative, alsoFromSources = members.size - 1)+        }+    }++    private fun diversify(clusters: List<RankedArticle>, nowMillis: Long): List<RankedArticle> {+        val remaining = clusters.sortedWith(+            compareByDescending<RankedArticle> { score(it.article, nowMillis) }+                .thenByDescending { it.article.publishedAtMillis }+                .thenBy { it.article.url },+        ).toMutableList()+        val out = mutableListOf<RankedArticle>()+        while (remaining.isNotEmpty()) {+            val pick = if (out.size < FIRST_PAGE_SIZE) {+                val perSource = out.groupingBy { it.article.sourceId }.eachCount()+                remaining.firstOrNull { (perSource[it.article.sourceId] ?: 0) < FIRST_PAGE_PER_SOURCE }+                    ?: remaining.first()+            } else {+                val tail = out.takeLast(2)+                if (tail.size == 2 && tail.all { it.article.sourceId == tail[0].article.sourceId }) {+                    remaining.firstOrNull { it.article.sourceId != tail[0].article.sourceId }+                        ?: remaining.first()+                } else {+                    remaining.first()+                }+            }+            out += pick+            remaining.remove(pick)+        }+        return out+    }+}
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.ktindex 1e01406cbc..328b7cfdba 100644--- a/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/ServerFeedParser.kt@@ -21,8 +21,8 @@ import kotlinx.serialization.json.jsonObject  * - `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.+ *   kept and shown under "All" only (no category), never re-attributed+ *   to a different source.  * - `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
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 0c96db918c..74186d6931 100644--- a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt+++ b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt@@ -8,7 +8,10 @@ import androidx.lifecycle.viewModelScope import com.vayunmathur.news.data.CachedArticle import com.vayunmathur.news.data.NewsPrefs import com.vayunmathur.news.data.NewsRepository+import com.vayunmathur.news.data.toFeedArticle import com.vayunmathur.news.domain.ExtractedArticle+import com.vayunmathur.news.domain.FeedRanking+import com.vayunmathur.news.domain.FeedSort import com.vayunmathur.news.domain.NewsCategory import com.vayunmathur.news.domain.SourceCatalog import kotlinx.coroutines.flow.MutableStateFlow@@ -16,16 +19,17 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine+import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.launch  /**- * Feed category filtering: a null category filter is "All" (every- * enabled source); a non-null [NewsCategory] keeps only articles whose- * source carries that catalog tag (see [SourceCatalog.matchesCategory]).- * Categories never enable/disable sources — that stays per-source in- * [NewsPrefs] via the Sources screen; the category filter only narrows- * the already-enabled corpus.+ * Feed filtering: every source is always in the corpus (no per-source+ * toggle). A null category filter is "All"; a non-null [NewsCategory]+ * keeps only articles whose source carries that catalog tag (see+ * [SourceCatalog.matchesCategory]). The persisted [FeedSort] then+ * orders the filtered corpus via [FeedRanking] (Top stories by+ * default); search keeps its own relevance ranking.  */  /** UI state and actions for feed, reader, sources and saved screens. */@@ -44,8 +48,17 @@ class NewsViewModel(     private val _categoryFilter = MutableStateFlow<NewsCategory?>(null)     val categoryFilter: StateFlow<NewsCategory?> = _categoryFilter.asStateFlow() -    val disabledSourceIds: StateFlow<Set<String>> = prefs.disabledSourceIds-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptySet())+    val feedSort: StateFlow<FeedSort> = prefs.feedSort+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), FeedSort.TOP)++    /** Extra sources per feed-row URL, from story clustering (see [FeedRanking]). */+    private val _clusterCounts = MutableStateFlow<Map<String, Int>>(emptyMap())+    val clusterCounts: StateFlow<Map<String, Int>> = _clusterCounts.asStateFlow()++    /** Cached-article count per source id, for the read-only Sources directory. */+    val sourceArticleCounts: StateFlow<Map<String, Int>> = repository.articles+        .map { all -> all.groupingBy { it.sourceId }.eachCount() }+        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())      private val _searchQuery = MutableStateFlow("")     val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()@@ -54,17 +67,16 @@ class NewsViewModel(     /**      * Search composes with the category filter: the repository search      * runs over the whole local corpus, and its results are then kept to-     * the selected category (and enabled sources) exactly like the feed.+     * the selected category exactly like the feed. Search order is its+     * relevance ranking regardless of the feed sort.      * So searching searches *within* the selected category, and changing      * the category while a query is active re-filters the visible      * results without a new search.      */     val searchResults: StateFlow<List<CachedArticle>> = combine(-        _searchResults, _categoryFilter, disabledSourceIds,-    ) { results, category, disabled ->-        results.filter {-            it.sourceId !in disabled && SourceCatalog.matchesCategory(it.sourceId, category)-        }+        _searchResults, _categoryFilter,+    ) { results, category ->+        results.filter { SourceCatalog.matchesCategory(it.sourceId, category) }     }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())     private var searchJob: kotlinx.coroutines.Job? = null @@ -86,9 +98,15 @@ class NewsViewModel(     }      val articles: StateFlow<List<CachedArticle>> = combine(-        repository.articles, _categoryFilter, disabledSourceIds,-    ) { all, category, disabled ->-        all.filter { it.sourceId !in disabled && SourceCatalog.matchesCategory(it.sourceId, category) }+        repository.articles, _categoryFilter, feedSort,+    ) { all, category, sort ->+        val filtered = all.filter { SourceCatalog.matchesCategory(it.sourceId, category) }+        val ranked = FeedRanking.rank(+            filtered.map { it.toFeedArticle() }, sort, System.currentTimeMillis(),+        )+        _clusterCounts.value = ranked.associate { it.article.url to it.alsoFromSources }+        val byUrl = filtered.associateBy { it.url }+        ranked.mapNotNull { byUrl[it.article.url] }     }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())      val bookmarked: StateFlow<List<CachedArticle>> = repository.bookmarked@@ -108,32 +126,31 @@ class NewsViewModel(     private var readerUrl: String? = null      init {+        viewModelScope.launch { prefs.clearLegacySourcePrefs() }         refresh()     } -    /** Single-select category filter; null is "All". Never enables/disables sources. */+    /** Single-select category filter; null is "All". */     fun setCategoryFilter(category: NewsCategory?) {         _categoryFilter.value = category     } +    /** Persists the feed order (Top stories / Latest). Search is unaffected. */+    fun setFeedSort(sort: FeedSort) {+        viewModelScope.launch { prefs.setFeedSort(sort) }+    }+     fun refresh() {         if (_isRefreshing.value) return         viewModelScope.launch {             _isRefreshing.value = true-            val enabled = SourceCatalog.sources.filter { it.id !in disabledSourceIds.value }-            val failed = runCatching { repository.refresh(enabled) }.getOrElse { listOf("all") }+            val failed = runCatching { repository.refresh(SourceCatalog.sources) }+                .getOrElse { listOf("all") }             _refreshFailed.value = failed.isNotEmpty()             _isRefreshing.value = false         }     } -    fun setSourceEnabled(id: String, enabled: Boolean) {-        viewModelScope.launch {-            prefs.setSourceEnabled(id, enabled)-            if (enabled) refresh()-        }-    }-     /** Loads (cached-first) the body for [url]; stale loads for other URLs are ignored. */     fun openArticle(url: String) {         readerUrl = url
news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt b/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.ktindex 3839592e1e..e0b7d4e9e2 100644--- a/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt@@ -25,13 +25,14 @@ fun ArticleRow(     article: CachedArticle,     onClick: () -> Unit,     onToggleBookmark: () -> Unit,+    alsoFromSources: Int = 0, ) {     Row(         modifier = Modifier.fillMaxWidth().clickable(onClick = onClick).padding(16.dp),     ) {         Column(modifier = Modifier.weight(1f)) {             Text(-                text = "${SourceCatalog.byId(article.sourceId)?.name ?: article.sourceId} · ${relativeTime(article.publishedAtMillis)}",+                text = "${SourceCatalog.byId(article.sourceId)?.name ?: article.sourceId} · ${relativeTime(article.publishedAtMillis)}" + if (alsoFromSources > 0) " · +$alsoFromSources sources" else "",                 style = MaterialTheme.typography.labelMedium,                 color = MaterialTheme.colorScheme.primary,             )
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 73ab9f39d5..c7d288a6b9 100644--- a/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt@@ -21,15 +21,17 @@ import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.Text import com.vayunmathur.news.R+import com.vayunmathur.news.domain.FeedSort import com.vayunmathur.news.domain.SourceCatalog import com.vayunmathur.news.platform.NewsViewModel  /**- * Merged newest-first feed with category filter chips and pull-to-refresh.- * The chip row is categories, not sources: chips are the categories of the- * enabled sources (plus the current selection, so it stays tappable), and- * per-source enable/disable lives only on the Sources screen. Selecting a- * category also narrows search results (see NewsViewModel.searchResults).+ * Merged feed with category chips, a Top stories / Latest sort selector+ * and pull-to-refresh. Every source is always in the corpus; chips are+ * the categories of all sources (plus the current selection, so it+ * stays tappable). Feed controls hide while searching — search keeps+ * its relevance order. Selecting a category also narrows search+ * results (see NewsViewModel.searchResults).  */ @Composable fun FeedScreen(@@ -42,7 +44,8 @@ fun FeedScreen(     val isRefreshing by viewModel.isRefreshing.collectAsState()     val refreshFailed by viewModel.refreshFailed.collectAsState()     val categoryFilter by viewModel.categoryFilter.collectAsState()-    val disabled by viewModel.disabledSourceIds.collectAsState()+    val feedSort by viewModel.feedSort.collectAsState()+    val clusterCounts by viewModel.clusterCounts.collectAsState()     val searchQuery by viewModel.searchQuery.collectAsState()     val searchResults by viewModel.searchResults.collectAsState()     val searching = searchQuery.isNotBlank()@@ -66,15 +69,29 @@ fun FeedScreen(     ) { padding ->         Column(modifier = Modifier.fillMaxSize().padding(padding)) {             if (!searching) {+            // Sort selector: persisted Top stories (ranked) / Latest.+            LazyRow(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {+                item {+                    FilterChip(+                        selected = feedSort == FeedSort.TOP,+                        onClick = { viewModel.setFeedSort(FeedSort.TOP) },+                        label = { Text(stringResource(R.string.feed_sort_top)) },+                    )+                }+                item {+                    FilterChip(+                        selected = feedSort == FeedSort.LATEST,+                        onClick = { viewModel.setFeedSort(FeedSort.LATEST) },+                        label = { Text(stringResource(R.string.feed_sort_latest)) },+                        modifier = Modifier.padding(start = 8.dp),+                    )+                }+            }             // Category chips (single-select, "All" = no category filter).-            // Categories come from the enabled sources only; the current-            // selection is kept in the row even if its sources were since-            // disabled, so the filter can always be changed back.-            val enabledSources = SourceCatalog.sources.filter { it.id !in disabled }-            val categories = (SourceCatalog.categoriesAmong(enabledSources) ++            val categories = (SourceCatalog.categoriesAmong(SourceCatalog.sources) +                 listOfNotNull(categoryFilter)).distinct()                 .sortedBy { it.ordinal }-            LazyRow(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {+            LazyRow(modifier = Modifier.padding(horizontal = 12.dp)) {                 item {                     FilterChip(                         selected = categoryFilter == null,@@ -110,6 +127,7 @@ fun FeedScreen(                         article = article,                         onClick = { onOpenArticle(article.url) },                         onToggleBookmark = { viewModel.toggleBookmark(article) },+                        alsoFromSources = if (searching) 0 else clusterCounts[article.url] ?: 0,                     )                 }             }
news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.ktindex 77512717b1..14c402bd50 100644--- a/news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/SourcesScreen.kt@@ -13,16 +13,20 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.ListItem-import com.vayunmathur.library.ui.Switch import com.vayunmathur.library.ui.Text import com.vayunmathur.news.R import com.vayunmathur.news.domain.SourceCatalog import com.vayunmathur.news.platform.NewsViewModel -/** Built-in source catalog with per-source enable switches. */+/**+ * Read-only source directory: every source is always in the corpus+ * (categories and search are the filters), so there is nothing to+ * toggle here — just name, language, metered badge and how many of its+ * articles are currently cached.+ */ @Composable fun SourcesScreen(viewModel: NewsViewModel, onBack: () -> Unit) {-    val disabled by viewModel.disabledSourceIds.collectAsState()+    val counts by viewModel.sourceArticleCounts.collectAsState()     AppScaffold(         title = stringResource(R.string.sources_title),         onNavigateBack = onBack,@@ -34,16 +38,23 @@ fun SourcesScreen(viewModel: NewsViewModel, onBack: () -> Unit) {             )             LazyColumn(modifier = Modifier.fillMaxSize()) {                 items(SourceCatalog.sources, key = { it.id }) { source ->+                    val count = counts[source.id] ?: 0                     ListItem(                         headlineContent = { Text(source.name) },                         supportingContent = {-                            Text(source.badge ?: source.feedUrl)+                            Column {+                                val detail = buildString {+                                    append(source.language)+                                    if (count > 0) append(" · $count cached")+                                }+                                Text(detail)+                                if (source.badge != null) Text(source.badge)+                            }                         },                         trailingContent = {-                            Switch(-                                checked = source.id !in disabled,-                                onCheckedChange = { viewModel.setSourceEnabled(source.id, it) },-                            )+                            if (source.badge?.startsWith("Metered") == true) {+                                Text(stringResource(R.string.sources_metered))+                            }                         },                     )                 }
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 83fee2302c..97e6f88807 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_categories">All</string>     <string name="feed_refresh_failed">Could not refresh all sources; showing the cached feed.</string>+    <string name="feed_sort_top">Top stories</string>+    <string name="feed_sort_latest">Latest</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 -->@@ -17,7 +19,8 @@     <string name="reader_loading_failed">Could not load this article.</string>     <!-- SourcesScreen -->     <string name="sources_title">Sources</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>+    <string name="sources_note">Every source below is always included. Use categories and search to filter the feed. If our news server is unreachable, the app crawls these sources directly. Article pages are always read directly from the publisher. No account is involved.</string>+    <string name="sources_metered">Metered</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/NewsPrefsSortTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/data/NewsPrefsSortTest.kt b/news/src/test/java/com/vayunmathur/news/data/NewsPrefsSortTest.ktnew file mode 100644index 0000000000..e5daa362a0--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/data/NewsPrefsSortTest.kt@@ -0,0 +1,28 @@+package com.vayunmathur.news.data++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.news.domain.FeedSort+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals++/** Feed-sort persistence: defaults to Top stories and round-trips. */+@RunWith(RobolectricTestRunner::class)+class NewsPrefsSortTest {++    @Test fun feedSortDefaultsToTopAndPersists() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Application>()+        val prefs = NewsPrefs(context)+        prefs.setFeedSort(FeedSort.LATEST)+        assertEquals(FeedSort.LATEST, prefs.feedSort.first())+        prefs.setFeedSort(FeedSort.TOP)+        assertEquals(FeedSort.TOP, prefs.feedSort.first())+        // Retired per-source toggle state is dropped without crashing.+        prefs.clearLegacySourcePrefs()+        assertEquals(FeedSort.TOP, prefs.feedSort.first())+    }+}
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.ktindex cc7a319514..7f097efff6 100644--- a/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt+++ b/news/src/test/java/com/vayunmathur/news/data/NewsServerFeedTest.kt@@ -14,7 +14,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue -/** Server-primary refresh, fallback decision, source filtering, and on-device search. */+/** Server-primary refresh, fallback decision, all-sources inclusion, and on-device search. */ @RunWith(RobolectricTestRunner::class) class NewsServerFeedTest {     @org.junit.Before fun setUp() { com.vayunmathur.news.seedNewsDb(ApplicationProvider.getApplicationContext()) }@@ -51,22 +51,23 @@ class NewsServerFeedTest {         assertTrue(cached.any { it.title == "Server Alpha Volcano" })     } -    @Test fun refreshFiltersServerFeedToEnabledSources() = runBlocking {+    @Test fun refreshIncludesServerArticlesFromEverySource() = 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",+              {"title":"Filter Also Kept","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.+        // No enabled-source filter exists: even though only BBC drives+        // the (unused) fallback list, the Guardian server article lands.         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" })+        assertTrue(cached.any { it.url == "https://srv.example/filter-dropped" })     }      @Test fun serverFailureFallsBackToSourceCrawl() = runBlocking {@@ -81,7 +82,7 @@ class NewsServerFeedTest {         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")+        assertTrue(calls.any { it.endsWith("fallback.xml") }, "fallback must crawl the given source")         val cached = withTimeout(10_000) { repo.articles.first { a -> a.any { it.title == "Fallback Story" } } }         assertTrue(cached.any { it.title == "Fallback Story" })     }
news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt b/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.ktnew file mode 100644index 0000000000..ad106e98ac--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt@@ -0,0 +1,102 @@+package com.vayunmathur.news.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Top-stories ranking: decay, diversity cap, cluster collapse, Latest. */+class FeedRankingTest {++    private val now = 1_700_000_000_000L+    private fun hoursAgo(hours: Double) = now - (hours * 3_600_000).toLong()++    private fun article(+        source: String,+        url: String,+        title: String = "Story $url",+        published: Long,+        image: String? = null,+        keywords: List<String> = emptyList(),+    ) = FeedArticle(url, source, title, published, image, keywords)++    @Test fun decayOrdersFreshBeforeDayOldBeforeThreeDaysOld() {+        val ranked = FeedRanking.rank(+            listOf(+                article("old-wire", "https://e/old", published = hoursAgo(72.0)),+                article("fresh-wire", "https://e/fresh", published = hoursAgo(1.0)),+                article("day-wire", "https://e/day", published = hoursAgo(24.0)),+            ),+            FeedSort.TOP, now,+        )+        assertEquals(+            listOf("https://e/fresh", "https://e/day", "https://e/old"),+            ranked.map { it.article.url },+        )+        // Day-old sinks but does not vanish: its score is still positive.+        assertTrue(FeedRanking.score(article("w", "https://e/x", published = hoursAgo(24.0)), now) > 20.0)+        assertTrue(FeedRanking.score(article("w", "https://e/x", published = 0L), now) == 0.0)+    }++    @Test fun firstPageCapsAnyOneSourceAtThree() {+        val flood = (1..30).map {+            article("bbc", "https://e/bbc-$it", published = hoursAgo(it * 0.1))+        }+        val others = (1..17).map { source ->+            article("wire-$source", "https://e/w$source", published = hoursAgo(6.0 + source))+        }+        val ranked = FeedRanking.rank(flood + others, FeedSort.TOP, now)+        val firstPage = ranked.take(FeedRanking.FIRST_PAGE_SIZE)+        assertEquals(20, firstPage.size)+        assertTrue(+            firstPage.groupingBy { it.article.sourceId }.eachCount().values.all {+                it <= FeedRanking.FIRST_PAGE_PER_SOURCE+            },+            "first page must cap a high-volume wire",+        )+        assertTrue(firstPage.map { it.article.sourceId }.distinct().size >= 7)+        // A one-source corpus still fills the page (cap relaxes).+        val solo = FeedRanking.rank(flood, FeedSort.TOP, now)+        assertEquals(20, solo.take(20).size)+        assertEquals(30, solo.size)+    }++    @Test fun exactAndNearDuplicateTitlesCollapseToEarliest() {+        val ranked = FeedRanking.rank(+            listOf(+                article("bbc", "https://e/b1", title = "Storm hits coast as winds rise", published = hoursAgo(2.0)),+                article("g1", "https://e/g1", title = "BBC: Storm hits coast as winds rise!", published = hoursAgo(5.0)),+                article("dw", "https://e/d1", title = "Winds rise as storm hits coast", published = hoursAgo(1.0)),+                article("npr", "https://e/n1", title = "Markets rally on jobs data", published = hoursAgo(1.0)),+            ),+            FeedSort.TOP, now,+        )+        assertEquals(2, ranked.size, "three tellings of the storm story must collapse to one row")+        val storm = ranked.first { it.article.title.contains("Storm") }+        assertEquals("https://e/g1", storm.article.url, "representative is the earliest telling")+        assertEquals(2, storm.alsoFromSources)+        // Latest keeps the same collapse.+        val latest = FeedRanking.rank(+            listOf(+                article("bbc", "https://e/b1", title = "Same headline", published = hoursAgo(2.0)),+                article("g1", "https://e/g1", title = "Same headline", published = hoursAgo(5.0)),+            ),+            FeedSort.LATEST, now,+        )+        assertEquals(1, latest.size)+        assertEquals(1, latest[0].alsoFromSources)+    }++    @Test fun latestIsNewestFirstAndIgnoresMetadataBonus() {+        val ranked = FeedRanking.rank(+            listOf(+                article("a", "https://e/newer-plain", published = hoursAgo(1.0)),+                article(+                    "b", "https://e/older-rich", published = hoursAgo(2.0),+                    image = "https://e/img", keywords = listOf("k"),+                ),+            ),+            FeedSort.LATEST, now,+        )+        assertEquals(listOf("https://e/newer-plain", "https://e/older-rich"), ranked.map { it.article.url })+    }+}
news/src/test/java/com/vayunmathur/news/domain/SourceCatalogCategoryTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/SourceCatalogCategoryTest.kt b/news/src/test/java/com/vayunmathur/news/domain/SourceCatalogCategoryTest.ktindex 4241fccd0a..381600da10 100644--- a/news/src/test/java/com/vayunmathur/news/domain/SourceCatalogCategoryTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/SourceCatalogCategoryTest.kt@@ -125,7 +125,7 @@ class SourceCatalogCategoryTest {             listOf(NewsCategory.WORLD),             SourceCatalog.categoriesAmong(listOf(SourceCatalog.byId("bbc")!!)),         )-        // Only STAT disabled would drop Science-primary, but Ars/Wired/MIT+        // Removing STAT alone would not drop Science: Ars/Wired/MIT         // still carry it as a secondary tag.         val noStat = SourceCatalog.sources.filter { it.id != "stat" }         assertTrue(NewsCategory.SCIENCE in SourceCatalog.categoriesAmong(noStat))
news/src/test/java/com/vayunmathur/news/ui/SourcesScreenTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/ui/SourcesScreenTest.kt b/news/src/test/java/com/vayunmathur/news/ui/SourcesScreenTest.ktnew file mode 100644index 0000000000..125f0ecc1d--- /dev/null+++ b/news/src/test/java/com/vayunmathur/news/ui/SourcesScreenTest.kt@@ -0,0 +1,43 @@+package com.vayunmathur.news.ui++import android.app.Application+import androidx.compose.ui.test.assertIsDisplayed+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.news.data.NewsPrefs+import com.vayunmathur.news.data.NewsRepository+import com.vayunmathur.news.platform.NewsViewModel+import com.vayunmathur.news.seedNewsDb+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Sources is now a read-only directory: source names and languages are+ * listed, there are no enable/disable switches anywhere on the screen.+ */+@RunWith(RobolectricTestRunner::class)+class SourcesScreenTest {+    @get:Rule val rule = createComposeRule()++    @Test fun directoryListsSourcesWithoutToggles() {+        val context = ApplicationProvider.getApplicationContext<Application>()+        seedNewsDb(context)+        val repository = NewsRepository(context, fetch = { throw IOException("offline") })+        val viewModel = NewsViewModel(context, repository, NewsPrefs(context))+        rule.setContent { SourcesScreen(viewModel = viewModel, onBack = {}) }+        rule.waitForIdle()+        rule.onNodeWithText("Sources").assertIsDisplayed()+        rule.onNodeWithText("BBC News").assertIsDisplayed()+        // No toggleable (switch) semantics on a read-only directory screen.+        assertEquals(+            0,+            rule.onAllNodes(androidx.compose.ui.test.isToggleable()).fetchSemanticsNodes().size,+        )+    }+}