Modern Apps git

← Modern-Apps.git

news: stories-only feed ordered by source count

Commit
7902af8dd565359aa771ae38abc7df8e9d1c41dd
Author
Vayun Mathur <[email protected]>
When
2026-11-25 20:10 UTC (10 days ago)
Parents
3d6ea49
The feed is now stories all the way down: the Top stories/Latest toggle, its persisted preference, the half-life scoring and diversity interleave are deleted. FeedRanking orders purely by descending distinct source count, then newest first, with a deterministic id tiebreak; search keeps its relevance order.

Story cards and the story header show only the source count ("1 source" / "N sources") instead of a lead-source name; per-article source attribution stays in the story member list. Singletons are story cards that open the same story view as multi-source stories.

Verified: :news:testDevUnitTest, :news:lint, and :news:metadata all pass; feed captures show no toggle and count-labelled cards.

Diff

metadata_data/photos/news/large-tablet/1.png
diff --git a/metadata_data/photos/news/large-tablet/1.png b/metadata_data/photos/news/large-tablet/1.pngindex 7c9713f901..c8651b81ae 100644Binary files a/metadata_data/photos/news/large-tablet/1.png and b/metadata_data/photos/news/large-tablet/1.png differ
metadata_data/photos/news/phone/1.png
diff --git a/metadata_data/photos/news/phone/1.png b/metadata_data/photos/news/phone/1.pngindex 0914643969..e17798b637 100644Binary files a/metadata_data/photos/news/phone/1.png and b/metadata_data/photos/news/phone/1.png differ
news/src/androidTest/java/com/vayunmathur/news/ui/CoreJourneyTest.kt
diff --git a/news/src/androidTest/java/com/vayunmathur/news/ui/CoreJourneyTest.kt b/news/src/androidTest/java/com/vayunmathur/news/ui/CoreJourneyTest.ktindex 67286f32e2..3fcd2f80fa 100644--- a/news/src/androidTest/java/com/vayunmathur/news/ui/CoreJourneyTest.kt+++ b/news/src/androidTest/java/com/vayunmathur/news/ui/CoreJourneyTest.kt@@ -34,16 +34,15 @@ class CoreJourneyTest {         val packageName = targetContext.packageName         grantAll(instrumentation.uiAutomation, targetContext.packageManager, packageName)         launch(packageName, device, targetContext)-        waitAny(device, "Search downloaded news", "Top stories", "No articles yet. Pull to refresh.")-        clickText(device, "Latest"); clickText(device, "Top stories")+        waitAny(device, "Search downloaded news", "No articles yet. Pull to refresh.")         // Try to open the first story: story rows are clickable cards below the chips.         Thread.sleep(3000)         val rows = device.findObjects(By.clickable(true))         val storyRow = rows.firstOrNull { it.visibleBounds.top > 300 && it.visibleBounds.height() > 60 }         if (storyRow != null) {             val b = storyRow.visibleBounds; device.click(b.centerX(), b.centerY())-            val landed = waitAny(device, "Summary", "How it developed", "This story is no longer in the downloaded feed.", "Search downloaded news")-            if (landed == "Summary" || landed == "How it developed") {+            val landed = waitAny(device, "Summary", "How it developed", "1 source", "This story is no longer in the downloaded feed.", "Search downloaded news")+            if (landed == "Summary" || landed == "How it developed" || landed == "1 source") {                 // Open the first article in the reader.                 val arts = device.findObjects(By.clickable(true))                 val art = arts.firstOrNull { it.visibleBounds.top > 400 }
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 5747d7a5a8..647cfc2121 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 feed across all sources (Top stories by default). */+    /** Merged story feed across all sources, ordered by source count. */     data object Feed : 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 24f8b0974d..71f7260d8c 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt@@ -7,7 +7,6 @@ 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@@ -16,9 +15,10 @@ import java.io.IOException private val Context.newsDataStore by preferencesDataStore(name = "news")  /**- * 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].+ * The app's only preferences owner. Reader settings and the Local+ * news location. A corrupt DataStore file reads as the documented+ * defaults (17sp sans, no location) 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@@ -34,10 +34,6 @@ class NewsPrefs(context: Context) {             if (e is IOException) emit(androidx.datastore.preferences.core.emptyPreferences()) else throw e         } -    /** 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 } @@ -49,14 +45,11 @@ class NewsPrefs(context: Context) {      */     val localLocation: Flow<String?> = safeData.map { it[LOCAL_LOCATION]?.takeIf { v -> v.isNotBlank() } } -    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. */+    /** Drops retired preference state, if an old install left any. */     suspend fun clearLegacySourcePrefs() {         appContext.newsDataStore.edit { prefs ->             if (prefs.contains(LEGACY_DISABLED_SOURCES)) prefs.remove(LEGACY_DISABLED_SOURCES)+            if (prefs.contains(LEGACY_FEED_SORT)) prefs.remove(LEGACY_FEED_SORT)         }     } @@ -81,7 +74,7 @@ class NewsPrefs(context: Context) {         const val MIN_TEXT_SP = 13         const val MAX_TEXT_SP = 24         private val LEGACY_DISABLED_SOURCES = stringSetPreferencesKey("disabled_sources")-        private val FEED_SORT = stringPreferencesKey("feed_sort")+        private val LEGACY_FEED_SORT = stringPreferencesKey("feed_sort")         private val LOCAL_LOCATION = stringPreferencesKey("local_location")         private val TEXT_SP = intPreferencesKey("reader_text_sp")         private val SERIF = booleanPreferencesKey("reader_serif")
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.ktindex 3abfa28d27..30b47ddb62 100644--- a/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/FeedRanking.kt@@ -1,179 +1,40 @@ package com.vayunmathur.news.domain -import kotlin.math.log2-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 other sources its server story carries. */-data class RankedArticle(-    val article: FeedArticle,-    /**-     * Extra distinct sources in the same server-grouped story-     * (0 = singleton or single-source story). Derived only from-     * actual server `storyId` membership — never from headline-     * similarity (there is no client-side grouping).-     */-    val alsoFromSources: Int = 0,-)- /**- * Client-side feed ranking over the merged corpus. The server's+ * Client-side feed ordering 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, see [score]):- * ```- * 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 article scores ~100–107, one 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.- *- * ## Stories (group before ranking — mechanically, by server id only)- *  * Stories come from [StoryGrouping]: articles sharing the exact  * server `storyId` form one story; every article without one is a- * singleton. Ranking only *orders* those stories — it never merges,- * splits, or otherwise influences membership. Each story keeps one- * representative: earliest `publishedAtMillis`, tie-broken by fuller- * metadata (image, then more keywords, then URL); the representative- * reports `distinct sources - 1` (actual server membership only) as- * [RankedArticle.alsoFromSources].+ * singleton story. Ranking only *orders* those stories — it never+ * merges, splits, or otherwise influences membership.  *- * ## Top stories for stories ([rankStories] / [storyScore])+ * The one feed ordering is source-count-first:  * ```- * ageHours = max(0, (now - story.latestMillis) / 3_600_000)- * score    = 100 * 0.5^(ageHours / 18)            // recency of latest update- *          + 5 if hero image present- *          + 2 if any member has keywords- *          + crossSourceBonus                     // see below, capped 30- * crossSourceBonus = 0 if 1 source else min(30, 10 * log2(sourceCount))+ * 1. descending distinct source count ([Story.sourceCount])+ * 2. descending recency ([Story.latestMillis], newest first)+ * 3. descending [Story.firstSeenMillis], then [Story.id], so the+ *    order is deterministic for equal-count, equal-time stories  * ```- * Cross-source breadth (counted only over actual server-story- * membership) is an honest prominence signal (independent outlets- * the server grouped into one story), folded in *alongside*- * recency: 2 sources +10, 4 sources +20, 8+ +30. It breaks ties- * between same-age stories and lifts a widely-covered day-old story- * (50+20) above a single-source half-day story (~71 vs ~75 — close),- * but a fresh single-source story (~100) still beats a 3-day-old- * wire everywhere (~6+30). Latest sorts by [Story.latestMillis].- *- * ## 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 of the same mechanical- * stories (one row per server story / singleton, in either order).+ * Every story is ranked by this rule, singletons included: a story+ * carried by five sources always precedes a fresher story carried+ * by one, and recency only breaks ties between stories with the+ * same source count.  */ 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-    /** Cap on the cross-source bonus in [storyScore]. */-    const val MAX_CROSS_SOURCE_BONUS = 30.0--    /** Rank [articles] for the feed; [nowMillis] is injected for tests. */-    fun rank(-        articles: List<FeedArticle>,-        sort: FeedSort,-        nowMillis: Long,-    ): List<RankedArticle> = rankStories(articles, sort, nowMillis).map {-        RankedArticle(it.representative, alsoFromSources = (it.sourceCount - 1).coerceAtLeast(0))-    }--    /** Group [articles] into stories and rank the stories for the feed. */-    fun rankStories(-        articles: List<FeedArticle>,-        sort: FeedSort,-        nowMillis: Long,-    ): List<Story> = rankGroupedStories(StoryGrouping.group(articles), sort, nowMillis)--    /** Rank already-grouped [stories] (grouping done once, ranking/filtering many times). */-    fun rankGroupedStories(-        stories: List<Story>,-        sort: FeedSort,-        nowMillis: Long,-    ): List<Story> {-        return when (sort) {-            FeedSort.LATEST -> stories.sortedWith(-                compareByDescending<Story> { it.latestMillis }-                    .thenByDescending { it.firstSeenMillis }-                    .thenBy { it.id },-            )-            FeedSort.TOP -> diversifyStories(stories, nowMillis)-        }-    }--    /** Top-stories score of a story (see KDoc formula). */-    fun storyScore(story: Story, nowMillis: Long): Double {-        if (story.latestMillis <= 0L) return 0.0-        val ageHours = ((nowMillis - story.latestMillis).coerceAtLeast(0L)) / 3_600_000.0-        var score = 100.0 * 0.5.pow(ageHours / HALF_LIFE_HOURS)-        if (story.heroImageUrl != null) score += IMAGE_BONUS-        if (story.articles.any { it.keywords.isNotEmpty() }) score += KEYWORD_BONUS-        if (story.sourceCount > 1) {-            score += minOf(MAX_CROSS_SOURCE_BONUS, 10.0 * log2(story.sourceCount.toDouble()))-        }-        return score-    }--    /** 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-    }+    /** Group [articles] into stories and order them for the feed. */+    fun rankStories(articles: List<FeedArticle>): List<Story> =+        rankGroupedStories(StoryGrouping.group(articles)) -    private fun diversifyStories(stories: List<Story>, nowMillis: Long): List<Story> {-        val remaining = stories.sortedWith(-            compareByDescending<Story> { storyScore(it, nowMillis) }+    /** Order already-grouped [stories] (grouping done once, ordering/filtering many times). */+    fun rankGroupedStories(stories: List<Story>): List<Story> =+        stories.sortedWith(+            compareByDescending<Story> { it.sourceCount }                 .thenByDescending { it.latestMillis }+                .thenByDescending { it.firstSeenMillis }                 .thenBy { it.id },-        ).toMutableList()-        val out = mutableListOf<Story>()-        while (remaining.isNotEmpty()) {-            val pick = if (out.size < FIRST_PAGE_SIZE) {-                val perSource = out.groupingBy { it.representative.sourceId }.eachCount()-                remaining.firstOrNull { (perSource[it.representative.sourceId] ?: 0) < FIRST_PAGE_PER_SOURCE }-                    ?: remaining.first()-            } else {-                val tail = out.takeLast(2)-                if (tail.size == 2 && tail.all { it.representative.sourceId == tail[0].representative.sourceId }) {-                    remaining.firstOrNull { it.representative.sourceId != tail[0].representative.sourceId }-                        ?: remaining.first()-                } else {-                    remaining.first()-                }-            }-            out += pick-            remaining.remove(pick)-        }-        return out-    }+        ) }
news/src/main/java/com/vayunmathur/news/domain/Story.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/Story.kt b/news/src/main/java/com/vayunmathur/news/domain/Story.ktindex 2cacd2a31a..baec15e41e 100644--- a/news/src/main/java/com/vayunmathur/news/domain/Story.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/Story.kt@@ -39,10 +39,9 @@ data class Story(         get() = articles.firstNotNullOfOrNull { it.serverStoryId?.takeIf { s -> s.isNotBlank() } }     /** Distinct source ids carrying this story, sorted. */     val sources: List<String> get() = articles.map { it.sourceId }.distinct().sorted()-    /** Distinct source display names (catalog name, else id), sorted. */-    val sourceNames: List<String>-        get() = sources.map { SourceCatalog.byId(it)?.name ?: it }.sorted()     val sourceCount: Int get() = sources.size+    /** Card/header label for [sourceCount]: "1 source" or "N sources". */+    val sourceCountLabel: String get() = if (sourceCount == 1) "1 source" else "$sourceCount sources"     val articleCount: Int get() = articles.size     /** Earliest known publication, or 0 when every member is unstamped. */     val firstSeenMillis: Long
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 a1fca53d95..5692b81b2a 100644--- a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt+++ b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt@@ -11,7 +11,6 @@ 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 com.vayunmathur.news.domain.LocalNews@@ -33,9 +32,9 @@ import kotlinx.coroutines.launch  * in-memory over the Room article cache per emission (the two server  * story columns are the only v2 addition). A null category filter is  * "All"; a story matches a category when ANY member does.- * [FeedRanking] only *orders* stories (Top folds cross-source- * breadth — counted over actual server membership — into recency;- * Latest is by latest update). Search hits surface their whole story.+ * [FeedRanking] only *orders* stories: descending source count,+ * then newest first. Search hits surface their whole story and keep+ * search relevance order.  */  /** UI state and actions for feed, reader and saved screens. */@@ -54,9 +53,6 @@ class NewsViewModel(     private val _categoryFilter = MutableStateFlow<NewsCategory?>(null)     val categoryFilter: StateFlow<NewsCategory?> = _categoryFilter.asStateFlow() -    val feedSort: StateFlow<FeedSort> = prefs.feedSort-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), FeedSort.TOP)-     /** Manually picked Local news location; null = unset (all locals equal). */     val localLocation: StateFlow<String?> = prefs.localLocation         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), null)@@ -66,11 +62,6 @@ class NewsViewModel(         .map { all -> StoryGrouping.group(all.map { it.toFeedArticle() }) }         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList()) -    /** Extra sources per feed-row URL, from actual server story membership only. */-    val clusterCounts: StateFlow<Map<String, Int>> = allStories-        .map { stories -> stories.associate { it.representative.url to (it.sourceCount - 1).coerceAtLeast(0) } }-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyMap())-     private val _searchQuery = MutableStateFlow("")     val searchQuery: StateFlow<String> = _searchQuery.asStateFlow()     private val _searchResults = MutableStateFlow<List<CachedArticle>>(emptyList())@@ -79,7 +70,7 @@ 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 exactly like the feed. Search order is its-     * relevance ranking regardless of the feed sort.+     * relevance ranking, not the feed's source-count order.      * 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.@@ -115,12 +106,12 @@ class NewsViewModel(         }     } -    /** Feed stories: mechanical grouping, category = any-member, ranked (order only). */+    /** Feed stories: mechanical grouping, category = any-member, ordered (order only). */     val stories: StateFlow<List<Story>> = combine(-        allStories, _categoryFilter, feedSort, localLocation,-    ) { grouped, category, sort, location ->+        allStories, _categoryFilter, localLocation,+    ) { grouped, category, location ->         val filtered = grouped.filter { it.matchesCategory(category) }-        val ranked = FeedRanking.rankGroupedStories(filtered, sort, System.currentTimeMillis())+        val ranked = FeedRanking.rankGroupedStories(filtered)         if (category == NewsCategory.LOCAL && !location.isNullOrBlank()) {             val (matching, rest) = ranked.partition { story ->                 story.articles.any { LocalNews.matches(SourceCatalog.regionOf(it.sourceId), location) }@@ -172,11 +163,6 @@ class NewsViewModel(         _categoryFilter.value = category     } -    /** Persists the feed order (Top stories / Latest). Search is unaffected. */-    fun setFeedSort(sort: FeedSort) {-        viewModelScope.launch { prefs.setFeedSort(sort) }-    }-     /** Persists the manual Local news location; null/blank clears it. */     fun setLocalLocation(location: String?) {         viewModelScope.launch { prefs.setLocalLocation(location) }
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 82f441ee66..8315a0a491 100644--- a/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/ArticleRow.kt@@ -10,6 +10,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.unit.dp+import com.vayunmathur.library.format.formatRelativeAge import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.ui.IconBookmark import com.vayunmathur.library.ui.IconBookmarkBorder@@ -25,14 +26,13 @@ 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)}" + if (alsoFromSources > 0) " · +$alsoFromSources sources" else "",+                text = "${SourceCatalog.byId(article.sourceId)?.name ?: article.sourceId} · ${relativeTime(article.publishedAtMillis)}",                 style = MaterialTheme.typography.labelMedium,                 color = MaterialTheme.colorScheme.primary,             )@@ -56,13 +56,5 @@ fun ArticleRow(     } } -internal fun relativeTime(millis: Long): String {-    if (millis <= 0L) return ""-    val minutes = ((System.currentTimeMillis() - millis) / 60_000L).coerceAtLeast(0L)-    return when {-        minutes < 1L -> "now"-        minutes < 60L -> "${minutes}m ago"-        minutes < 60L * 24L -> "${minutes / 60L}h ago"-        else -> "${minutes / (60L * 24L)}d ago"-    }-}+internal fun relativeTime(millis: Long): String =+    formatRelativeAge(millis, System.currentTimeMillis(), justNowLabel = "now")
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 755b1a911f..f743416493 100644--- a/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/FeedScreen.kt@@ -26,19 +26,19 @@ import com.vayunmathur.library.ui.IconSettings import com.vayunmathur.library.ui.Text import com.vayunmathur.news.R import com.vayunmathur.news.data.CachedArticle-import com.vayunmathur.news.domain.FeedSort import com.vayunmathur.news.domain.NewsCategory import com.vayunmathur.news.domain.SourceCatalog import com.vayunmathur.news.domain.Story import com.vayunmathur.news.platform.NewsViewModel  /**- * 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).+ * Merged story feed with category chips and pull-to-refresh. Every+ * story — multi-source or singleton — is a story card ordered by+ * descending source count, then newest first. 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(@@ -52,7 +52,6 @@ fun FeedScreen(     val isRefreshing by viewModel.isRefreshing.collectAsState()     val refreshFailed by viewModel.refreshFailed.collectAsState()     val categoryFilter by viewModel.categoryFilter.collectAsState()-    val feedSort by viewModel.feedSort.collectAsState()     val cachedByUrl by viewModel.cachedByUrl.collectAsState()     val localLocation by viewModel.localLocation.collectAsState()     val searchQuery by viewModel.searchQuery.collectAsState()@@ -64,12 +63,10 @@ fun FeedScreen(         isRefreshing = isRefreshing,         refreshFailed = refreshFailed,         categoryFilter = categoryFilter,-        feedSort = feedSort,         localLocation = localLocation,         searchQuery = searchQuery,         onSearchQueryChange = viewModel::setSearchQuery,         onRefresh = viewModel::refresh,-        onFeedSortChange = viewModel::setFeedSort,         onCategoryFilterChange = viewModel::setCategoryFilter,         onToggleBookmark = viewModel::toggleBookmark,         onOpenSaved = onOpenSaved,@@ -91,12 +88,10 @@ internal fun FeedContent(     isRefreshing: Boolean,     refreshFailed: Boolean,     categoryFilter: NewsCategory?,-    feedSort: FeedSort,     localLocation: String?,     searchQuery: String,     onSearchQueryChange: (String) -> Unit,     onRefresh: () -> Unit,-    onFeedSortChange: (FeedSort) -> Unit,     onCategoryFilterChange: (NewsCategory?) -> Unit,     onToggleBookmark: (CachedArticle) -> Unit,     onOpenSaved: () -> Unit,@@ -124,29 +119,11 @@ internal fun FeedContent(     ) { 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 = { onFeedSortChange(FeedSort.TOP) },-                        label = { Text(stringResource(R.string.feed_sort_top)) },-                    )-                }-                item {-                    FilterChip(-                        selected = feedSort == FeedSort.LATEST,-                        onClick = { onFeedSortChange(FeedSort.LATEST) },-                        label = { Text(stringResource(R.string.feed_sort_latest)) },-                        modifier = Modifier.padding(start = 8.dp),-                    )-                }-            }             // Category chips (single-select, "All" = no category filter).             val categories = (SourceCatalog.categoriesAmong(SourceCatalog.sources) +                 listOfNotNull(categoryFilter)).distinct()                 .sortedBy { it.ordinal }-            LazyRow(modifier = Modifier.padding(horizontal = 12.dp)) {+            LazyRow(modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)) {                 item {                     FilterChip(                         selected = categoryFilter == null,
news/src/main/java/com/vayunmathur/news/ui/StoryRow.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/StoryRow.kt b/news/src/main/java/com/vayunmathur/news/ui/StoryRow.ktindex 0665598cb3..a3e9893ca1 100644--- a/news/src/main/java/com/vayunmathur/news/ui/StoryRow.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/StoryRow.kt@@ -19,11 +19,11 @@ import com.vayunmathur.library.ui.Text import com.vayunmathur.news.domain.Story  /**- * One feed story card: representative headline, hero image, latest- * update time, and — only for multi-source stories — source count- * and names. Single-article stories render as a plain article row- * (no source-count chrome). [Story.oneLiner] is a server-generated- * summary, never extracted article text.+ * One feed story card: headline, hero image, latest update time and+ * the story's source count ("1 source" / "N sources"). No source is+ * named on the card — the count is the story's identity signal, for+ * multi-source and singleton stories alike. [Story.oneLiner] is a+ * server-generated summary, never extracted article text.  */ @Composable fun StoryRow(@@ -37,20 +37,12 @@ fun StoryRow(     ) {         Column(modifier = Modifier.weight(1f)) {             val meta = buildString {-                append(story.sourceNames.firstOrNull() ?: story.representative.sourceId)+                append(story.sourceCountLabel)                 val whenText = relativeTime(story.latestMillis)                 if (whenText.isNotEmpty()) append(" · $whenText")-                if (story.sourceCount > 1) append(" · ${story.sourceCount} sources")             }             Text(meta, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary)             Text(story.title, style = MaterialTheme.typography.titleMedium)-            if (story.sourceCount > 1) {-                Text(-                    story.sourceNames.joinToString(", "),-                    style = MaterialTheme.typography.labelMedium,-                    modifier = Modifier.padding(top = 4.dp),-                )-            }             if (story.oneLiner != null) {                 Text(                     story.oneLiner!!,
news/src/main/java/com/vayunmathur/news/ui/StoryScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/StoryScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/StoryScreen.ktindex f0185fd821..3e6f1e429a 100644--- a/news/src/main/java/com/vayunmathur/news/ui/StoryScreen.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/StoryScreen.kt@@ -26,12 +26,14 @@ import com.vayunmathur.news.domain.SourceCatalog import com.vayunmathur.news.platform.NewsViewModel  /**- * Story page: how one event developed, earliest → latest. Each- * article row (source, time, headline) opens the existing Reader- * (which fetches its body on-device). Single-article stories show- * just that article — no timeline/count/summary chrome.- * The server one-liner, when present, is shown as a labelled- * summary; no server-extracted article text is ever displayed.+ * Story page: how one event developed, earliest → latest. Every+ * story, singletons included, opens this page. The header identifies+ * the story by its source count, never by a lead source; each+ * article row (source, time, headline) keeps its own per-article+ * attribution and opens the existing Reader (which fetches its body+ * on-device). The server one-liner, when present, is shown as a+ * labelled summary; no server-extracted article text is ever+ * displayed.  */ @Composable fun StoryScreen(@@ -43,6 +45,28 @@ fun StoryScreen(     val allStories by viewModel.allStories.collectAsState()     val cachedByUrl by viewModel.cachedByUrl.collectAsState()     val story = allStories.firstOrNull { it.id == storyId }+    StoryContent(+        story = story,+        cachedByUrl = cachedByUrl,+        onOpenArticle = onOpenArticle,+        onToggleBookmark = viewModel::toggleBookmark,+        onBack = onBack,+    )+}++/**+ * Stateless story body behind [StoryScreen]: every value is a parameter, so+ * Compose previews (src/screenshotTest) render the real screen from literal+ * fixtures with no ViewModel or database.+ */+@Composable+internal fun StoryContent(+    story: com.vayunmathur.news.domain.Story?,+    cachedByUrl: Map<String, com.vayunmathur.news.data.CachedArticle>,+    onOpenArticle: (String) -> Unit,+    onToggleBookmark: (com.vayunmathur.news.data.CachedArticle) -> Unit,+    onBack: () -> Unit,+) {     AppScaffold(title = "", onNavigateBack = onBack) { padding ->         if (story == null) {             Text(@@ -57,28 +81,28 @@ fun StoryScreen(             item {                 Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) {                     Text(story.title, style = MaterialTheme.typography.headlineSmall)-                    if (!single) {-                        val range = buildString {-                            append(story.sourceNames.joinToString(", "))-                            val first = relativeTime(story.firstSeenMillis)-                            val latest = relativeTime(story.latestMillis)-                            if (first.isNotEmpty()) append(" · from $first")-                            if (latest.isNotEmpty() && latest != first) append(" · updated $latest")-                        }+                    val range = buildString {+                        append(story.sourceCountLabel)+                        val first = relativeTime(story.firstSeenMillis)+                        val latest = relativeTime(story.latestMillis)+                        if (first.isNotEmpty()) append(" · from $first")+                        if (latest.isNotEmpty() && latest != first) append(" · updated $latest")+                    }+                    Text(+                        range,+                        style = MaterialTheme.typography.labelMedium,+                        color = MaterialTheme.colorScheme.primary,+                        modifier = Modifier.padding(top = 6.dp),+                    )+                    if (story.oneLiner != null) {                         Text(-                            range,+                            stringResource(R.string.story_summary_label),                             style = MaterialTheme.typography.labelMedium,-                            color = MaterialTheme.colorScheme.primary,-                            modifier = Modifier.padding(top = 6.dp),+                            modifier = Modifier.padding(top = 10.dp),                         )-                        if (story.oneLiner != null) {-                            Text(-                                stringResource(R.string.story_summary_label),-                                style = MaterialTheme.typography.labelMedium,-                                modifier = Modifier.padding(top = 10.dp),-                            )-                            Text(story.oneLiner!!, style = MaterialTheme.typography.bodyMedium)-                        }+                        Text(story.oneLiner!!, style = MaterialTheme.typography.bodyMedium)+                    }+                    if (!single) {                         Text(                             stringResource(R.string.story_timeline_label),                             style = MaterialTheme.typography.labelLarge,@@ -102,7 +126,7 @@ fun StoryScreen(                         Text(article.title, style = MaterialTheme.typography.titleMedium)                     }                     if (cached != null) {-                        IconButton(onClick = { viewModel.toggleBookmark(cached) }) {+                        IconButton(onClick = { onToggleBookmark(cached) }) {                             if (cached.bookmarked) IconBookmark() else IconBookmarkBorder()                         }                     }
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 2bbf255e69..f03957f739 100644--- a/news/src/main/res/values/strings.xml+++ b/news/src/main/res/values/strings.xml@@ -6,8 +6,6 @@     <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 -->@@ -19,7 +17,7 @@     <string name="feed_local_with_location">Local · %1$s</string>     <!-- SettingsScreen -->     <string name="settings_title">Settings</string>-    <string name="settings_note">Feed order is chosen on the feed; reader text options are in the reader.</string>+    <string name="settings_note">Reader text options are in the reader.</string>     <!-- LocalLocationScreen / SettingsScreen setting -->     <string name="local_location_title">Local news location</string>     <string name="local_location_note">Choose where Local news should come from first. Sources from your location appear first in Local; other local sources still follow. This is only a preference — the app never uses your device location.</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.ktindex a95fe18fb3..f794958353 100644--- a/news/src/test/java/com/vayunmathur/news/data/NewsPrefsSortTest.kt+++ b/news/src/test/java/com/vayunmathur/news/data/NewsPrefsSortTest.kt@@ -2,7 +2,6 @@ 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@@ -11,20 +10,17 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull -/** Feed-sort persistence: defaults to Top stories and round-trips. */+/** Prefs: Local location persistence and retired-state cleanup. */ @RunWith(RobolectricTestRunner::class) class NewsPrefsSortTest { -    @Test fun feedSortDefaultsToTopAndPersists() = runBlocking {+    @Test fun legacyCleanupDropsRetiredStateWithoutCrashing() = 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.+        // Retired per-source / feed-sort state is dropped without crashing.         prefs.clearLegacySourcePrefs()-        assertEquals(FeedSort.TOP, prefs.feedSort.first())+        prefs.setLocalLocation("Chicago, Illinois, United States")+        assertEquals("Chicago, Illinois, United States", prefs.localLocation.first())     }      @Test fun localLocationDefaultsUnsetAndPersistsAndClears() = runBlocking {
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.ktindex 1a674678d9..f39de0ff76 100644--- a/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/FeedRankingTest.kt@@ -4,7 +4,7 @@ import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue -/** Top-stories ranking: decay, diversity cap, mechanical story order, Latest. */+/** Feed ordering: source-count-first, recency tiebreak, label logic. */ class FeedRankingTest {      private val now = 1_700_000_000_000L@@ -15,102 +15,98 @@ class FeedRankingTest {         url: String,         title: String = "Story $url",         published: Long,-        image: String? = null,-        keywords: List<String> = emptyList(),         serverStoryId: String? = null,-    ) = FeedArticle(url, source, title, published, image, keywords, serverStoryId = serverStoryId)+    ) = FeedArticle(url, source, title, published, serverStoryId = serverStoryId) -    @Test fun decayOrdersFreshBeforeDayOldBeforeThreeDaysOld() {-        val ranked = FeedRanking.rank(+    private fun story(id: String, sources: List<String>, latestHoursAgo: Double): Story {+        val articles = sources.mapIndexed { i, source ->+            article(source, "https://e/$id-$i", published = hoursAgo(latestHoursAgo + i))+        }+        return Story(+            id = id,+            representative = articles.first(),+            articles = articles,+        )+    }++    @Test fun moreSourcesBeatsFresherFewerSources() {+        val ranked = FeedRanking.rankGroupedStories(             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)),+                story("fresh-single", listOf("a"), latestHoursAgo = 0.5),+                story("old-five", listOf("a", "b", "c", "d", "e"), latestHoursAgo = 72.0),+                story("mid-two", listOf("a", "b"), latestHoursAgo = 1.0),             ),-            FeedSort.TOP, now,         )-        assertEquals(-            listOf("https://e/fresh", "https://e/day", "https://e/old"),-            ranked.map { it.article.url },+        assertEquals(listOf("old-five", "mid-two", "fresh-single"), ranked.map { it.id })+    }++    @Test fun recencyBreaksSourceCountTiesNewestFirst() {+        val ranked = FeedRanking.rankGroupedStories(+            listOf(+                story("older", listOf("a", "b"), latestHoursAgo = 10.0),+                story("newer", listOf("c", "d"), latestHoursAgo = 1.0),+                story("middle", listOf("e", "f"), latestHoursAgo = 5.0),+            ),         )-        // 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)+        assertEquals(listOf("newer", "middle", "older"), ranked.map { it.id })     } -    @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",+    @Test fun singletonsAreRankedStoriesToo() {+        val ranked = FeedRanking.rankStories(+            listOf(+                article("solo", "https://e/solo", published = hoursAgo(0.1)),+                article("bbc", "https://e/b1", published = hoursAgo(50.0), serverStoryId = "s1"),+                article("dw", "https://e/d1", published = hoursAgo(49.0), serverStoryId = "s1"),+            ),         )-        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)+        assertEquals(2, ranked.size)+        assertEquals("srv:s1", ranked[0].id)+        assertEquals(1, ranked[1].articles.size)+        assertEquals("1 source", ranked[1].sourceCountLabel)     }      @Test fun identicalHeadlinesWithoutStoryIdDoNotCollapse() {-        val ranked = FeedRanking.rank(+        val ranked = FeedRanking.rankStories(             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(4, ranked.size, "no storyId = no grouping, however similar the headlines")-        assertTrue(ranked.all { it.alsoFromSources == 0 })+        assertEquals(3, ranked.size, "no storyId = no grouping, however similar the headlines")+        assertTrue(ranked.all { it.sourceCount == 1 && it.sourceCountLabel == "1 source" })     } -    @Test fun sharedStoryIdCollapsesToEarliestRepresentative() {-        val ranked = FeedRanking.rank(-            listOf(-                article("bbc", "https://e/b1", title = "Storm hits coast as winds rise", published = hoursAgo(2.0), serverStoryId = "s1"),-                article("g1", "https://e/g1", title = "Different wording entirely", published = hoursAgo(5.0), serverStoryId = "s1"),-                article("dw", "https://e/d1", title = "Winds rise as storm hits coast", published = hoursAgo(1.0), serverStoryId = "s1"),-                article("npr", "https://e/n1", title = "Markets rally on jobs data", published = hoursAgo(1.0)),-            ),-            FeedSort.TOP, now,-        )-        assertEquals(2, ranked.size, "only the server-grouped articles collapse to one row")-        val storm = ranked.first { it.alsoFromSources == 2 }-        assertEquals("https://e/g1", storm.article.url, "representative is the earliest member")-        // Latest keeps the same mechanical membership.-        val latest = FeedRanking.rank(+    @Test fun sharedStoryIdCollapsesAndCountsDistinctSources() {+        val ranked = FeedRanking.rankStories(             listOf(-                article("bbc", "https://e/b1", title = "Same headline", published = hoursAgo(2.0), serverStoryId = "s1"),-                article("g1", "https://e/g1", title = "Same headline", published = hoursAgo(5.0), serverStoryId = "s1"),+                article("bbc", "https://e/b1", published = hoursAgo(2.0), serverStoryId = "s1"),+                article("bbc", "https://e/b2", published = hoursAgo(3.0), serverStoryId = "s1"),+                article("dw", "https://e/d1", published = hoursAgo(1.0), serverStoryId = "s1"),+                article("npr", "https://e/n1", published = hoursAgo(0.5)),             ),-            FeedSort.LATEST, now,         )-        assertEquals(1, latest.size)-        assertEquals(1, latest[0].alsoFromSources)+        assertEquals(2, ranked.size, "only the server-grouped articles collapse to one story")+        val grouped = ranked.first { it.id == "srv:s1" }+        // Two BBC articles + one DW article = 2 distinct sources, 3 articles.+        assertEquals(2, grouped.sourceCount)+        assertEquals(3, grouped.articleCount)+        assertEquals("2 sources", grouped.sourceCountLabel)+        assertEquals("srv:s1", ranked[0].id, "2-source story precedes fresher singleton")     } -    @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 })+    @Test fun sourceCountLabelSingularAndPlural() {+        assertEquals("1 source", story("one", listOf("a"), 1.0).sourceCountLabel)+        assertEquals("2 sources", story("two", listOf("a", "b"), 1.0).sourceCountLabel)+        assertEquals("5 sources", story("five", listOf("a", "b", "c", "d", "e"), 1.0).sourceCountLabel)+    }++    @Test fun equalCountAndTimeOrderIsDeterministicById() {+        val a = story("srv:b", listOf("a", "b"), latestHoursAgo = 1.0)+        val b = story("srv:a", listOf("c", "d"), latestHoursAgo = 1.0)+        // Same source count; latest/firstSeen also tie only if timestamps match —+        // story() offsets members by index, so both share the same instants.+        assertEquals(listOf("srv:a", "srv:b"), FeedRanking.rankGroupedStories(listOf(a, b)).map { it.id })+        assertEquals(listOf("srv:a", "srv:b"), FeedRanking.rankGroupedStories(listOf(b, a)).map { it.id })     } }
news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt b/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.ktindex 3fa8104f5d..816494b64a 100644--- a/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/StoryGroupingTest.kt@@ -137,23 +137,19 @@ class StoryGroupingTest {         val multi = (1..4).map { i ->             a("s$i", "https://e/m$i", "Storm hits coast as winds rise", h(24.0 - i), serverStoryId = "s1")         }-        val single = listOf(a("solo", "https://e/solo", "Obscure local council meets", h(20.0)))-        val top = FeedRanking.rankStories(multi + single, FeedSort.TOP, now)-        assertEquals(2, top.size, "ranking orders the 2 mechanical stories; it does not create or dissolve any")-        assertEquals(4, top.first { it.id == "srv:s1" }.articles.size)-        assertTrue(-            FeedRanking.storyScore(top.first { it.id == "srv:s1" }, now) >-                FeedRanking.storyScore(StoryGrouping.group(single).single(), now),-            "cross-source breadth (actual server membership) folds into Top ordering",-        )-        val latest = FeedRanking.rankStories(multi + single, FeedSort.LATEST, now)-        assertEquals(2, latest.size)-        assertEquals(multi.maxOf { it.publishedAtMillis }, latest.first().latestMillis)+        val single = listOf(a("solo", "https://e/solo", "Obscure local council meets", h(1.0)))+        val ranked = FeedRanking.rankStories(multi + single)+        assertEquals(2, ranked.size, "ranking orders the 2 mechanical stories; it does not create or dissolve any")+        assertEquals(4, ranked.first { it.id == "srv:s1" }.articles.size)+        // Source-count-first: the 4-source story precedes the fresher singleton.+        assertEquals("srv:s1", ranked[0].id)+        assertEquals("4 sources", ranked[0].sourceCountLabel)+        assertEquals("1 source", ranked[1].sourceCountLabel)         // Without a shared storyId the same headlines stay 5 separate ranked rows.         val ungrouped = (1..4).map { i ->             a("s$i", "https://e/u$i", "Storm hits coast as winds rise", h(24.0 - i))         }-        assertEquals(5, FeedRanking.rankStories(ungrouped + single, FeedSort.TOP, now).size)+        assertEquals(5, FeedRanking.rankStories(ungrouped + single).size)     }      @Test fun searchHitsSurfaceTheirStory() {
news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt b/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.ktindex 4f94a5e26e..fee4d9bd8f 100644--- a/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt+++ b/news/src/test/java/com/vayunmathur/news/ui/FeedScreenTest.kt@@ -71,6 +71,9 @@ class FeedScreenTest {             0,             rule.onAllNodesWithText("Sources").fetchSemanticsNodes().size,         )+        // No Latest / Top-stories mode switch exists any more.+        assertEquals(0, rule.onAllNodesWithText("Top stories").fetchSemanticsNodes().size)+        assertEquals(0, rule.onAllNodesWithText("Latest").fetchSemanticsNodes().size)     }      @Test fun typingShowsClear_clearRestoresFeed() {
news/src/test/java/com/vayunmathur/news/ui/StoryRowKeyboardTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/ui/StoryRowKeyboardTest.kt b/news/src/test/java/com/vayunmathur/news/ui/StoryRowKeyboardTest.ktindex b13e9b4b62..87d5c5614b 100644--- a/news/src/test/java/com/vayunmathur/news/ui/StoryRowKeyboardTest.kt+++ b/news/src/test/java/com/vayunmathur/news/ui/StoryRowKeyboardTest.kt@@ -2,9 +2,12 @@ package com.vayunmathur.news.ui  import androidx.compose.ui.input.key.Key import androidx.compose.ui.semantics.SemanticsActions+import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsFocused import androidx.compose.ui.test.hasClickAction import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onAllNodesWithText+import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performKeyInput import androidx.compose.ui.test.performSemanticsAction import androidx.compose.ui.test.pressKey@@ -59,4 +62,40 @@ class StoryRowKeyboardTest {         rule.waitForIdle()         assertEquals(1, toggles)     }++    @Test fun cardShowsSourceCountOnly_noLeadSourceName() {+        fun art(source: String, url: String) = FeedArticle(+            url = url, sourceId = source, title = "Headline $url", publishedAtMillis = 0L,+        )+        val articles = listOf(art("bbc", "https://e/1"), art("dw", "https://e/2"), art("npr", "https://e/3"))+        rule.setContent {+            StoryRow(+                story = Story(id = "srv:s1", representative = articles.first(), articles = articles),+                bookmarked = false,+                onClick = {},+                onToggleBookmark = {},+            )+        }+        rule.waitForIdle()+        rule.onNodeWithText("3 sources").assertIsDisplayed()+        // No source is named on the card, lead or otherwise.+        assertEquals(0, rule.onAllNodesWithText("BBC", substring = true).fetchSemanticsNodes().size)+        assertEquals(0, rule.onAllNodesWithText("NPR", substring = true).fetchSemanticsNodes().size)+    }++    @Test fun singletonCardShowsOneSource() {+        val article = FeedArticle(+            url = "https://example.com/a", sourceId = "bbc", title = "Solo story", publishedAtMillis = 0L,+        )+        rule.setContent {+            StoryRow(+                story = Story(id = "s1", representative = article, articles = listOf(article)),+                bookmarked = false,+                onClick = {},+                onToggleBookmark = {},+            )+        }+        rule.waitForIdle()+        rule.onNodeWithText("1 source").assertIsDisplayed()+    } }