Modern Apps git

← Modern-Apps.git

news: fix the ANR (regex sitemap parse on Main) + reader UI cleanup

Commit
ccff1851a71843fe57d624b47eeaa26c53a542a7
Author
Vayun Mathur <[email protected]>
When
2026-11-23 17:20 UTC (12 days ago)
Parents
45f3c29
Device ANR traced to main-thread whole-document regex
findAll over a 996-URL sitemap, recompiled per tag, on
the ViewModel's Main dispatcher (22s CPU in the ANR dump).
The parser is now a linear indexOf scan (ms off-thread),
all fetch/parse/extraction runs on Dispatchers.Default,
sources land in parallel with a 20s per-source timeout
and publish incrementally to Room, and the feed is
cache-first. Reader: WebView toggle and open-in-browser
removed (file deleted), and bookmark/font/text-size
moved from the top bar into an in-content action row.

Device-verified: cold launch 1.75s, all 11 sources land
incrementally, populated feed from cache on relaunch,
no ANR. 19 tests green incl. a 996-URL parse bound and
off-Main assertions.

Diff

news/AGENTS.md
diff --git a/news/AGENTS.md b/news/AGENTS.mdindex 5f2d368725..02a2818c93 100644--- a/news/AGENTS.md+++ b/news/AGENTS.md@@ -20,8 +20,8 @@ locally. There is no backend and no account.   Ars, The Verge, Hacker News) - Room-cached feed + extracted article bodies (offline reading), bookmarks - Readability-style extraction in `domain/ArticleExtractor` over a small-  tolerant HTML DOM (`domain/HtmlDom`); reader with text size, serif/sans,-  and a toggle to the original web page+  tolerant HTML DOM (`domain/HtmlDom`); reader with text size, serif/sans+  (extracted-text only — no original-page WebView or open-in-browser)  ## Source verification (2026-11-23, via the dev box's proxied network) Verified = sitemap/RSS fetched 200 and parsed + one article's raw HTML
news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt
diff --git a/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.ktindex b33f9bbd9a..2a49953ab5 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsDatabase.kt@@ -47,6 +47,10 @@ interface NewsDao {     @Query("SELECT * FROM CachedArticle WHERE url = :url")     suspend fun article(url: String): CachedArticle? +    /** Bookmarked subset of [urls], in one query (publish must not query per article). */+    @Query("SELECT url FROM CachedArticle WHERE bookmarked = 1 AND url IN (:urls)")+    suspend fun bookmarkedUrls(urls: List<String>): List<String>+     @Query("SELECT * FROM CachedBody WHERE url = :url")     suspend fun body(url: String): CachedBody? 
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 d51294faf6..1d541143a6 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsPrefs.kt@@ -30,7 +30,8 @@ class NewsPrefs(context: Context) {     val disabledSourceIds: Flow<Set<String>> = safeData.map { it[DISABLED_SOURCES] ?: emptySet() }     val readerTextSp: Flow<Int> = safeData.map { it[TEXT_SP] ?: DEFAULT_TEXT_SP }     val readerSerif: Flow<Boolean> = safeData.map { it[SERIF] ?: false }-    val readerWebView: Flow<Boolean> = safeData.map { it[WEB_VIEW] ?: 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) {         appContext.newsDataStore.edit { prefs ->@@ -47,10 +48,6 @@ class NewsPrefs(context: Context) {         appContext.newsDataStore.edit { it[SERIF] = serif }     } -    suspend fun setReaderWebView(webView: Boolean) {-        appContext.newsDataStore.edit { it[WEB_VIEW] = webView }-    }-     companion object {         const val DEFAULT_TEXT_SP = 17         const val MIN_TEXT_SP = 13@@ -58,6 +55,5 @@ class NewsPrefs(context: Context) {         private val DISABLED_SOURCES = stringSetPreferencesKey("disabled_sources")         private val TEXT_SP = intPreferencesKey("reader_text_sp")         private val SERIF = booleanPreferencesKey("reader_serif")-        private val WEB_VIEW = booleanPreferencesKey("reader_web_view")     } }
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 de5e8f3397..5c06a3b928 100644--- a/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt+++ b/news/src/main/java/com/vayunmathur/news/data/NewsRepository.kt@@ -6,15 +6,20 @@ import com.vayunmathur.library.room.RoomRepository import com.vayunmathur.news.domain.ArticleBlock import com.vayunmathur.news.domain.ArticleExtractor import com.vayunmathur.news.domain.ExtractedArticle+import com.vayunmathur.news.domain.FeedArticle import com.vayunmathur.news.domain.FeedMerger import com.vayunmathur.news.domain.NewsSource import com.vayunmathur.news.domain.SitemapParser-import com.vayunmathur.news.domain.SourceCatalog import com.vayunmathur.news.network.Networking+import kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineDispatcher+import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.async import kotlinx.coroutines.awaitAll import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.withContext+import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.builtins.ListSerializer import kotlinx.serialization.json.Json @@ -22,10 +27,21 @@ import kotlinx.serialization.json.Json  * Owns the Room cache and all feed/article fetching. The [fetch] seam  * defaults to [Networking] and is replaced by a fake in unit tests, so  * no test touches the network. Bodies are extracted on device only.+ *+ * Refresh topology (fixed 2026-11-23, was the ANR / "stuck feed" bug):+ * sources fetch in parallel, each on [feedDispatcher] (never Main —+ * parsing a ~996-URL sitemap on Main burned 22s CPU in regex and+ * ANR'd), each bounded by [sourceTimeoutMs], and each source's+ * articles are upserted to Room the moment that source lands. The+ * feed is the Room flow, so cached/partial articles are visible+ * immediately; one hanging or failing source can neither block the+ * others' publication nor hold the refresh open past its timeout.  */ class NewsRepository internal constructor(     context: Context,     private val fetch: suspend (String) -> String,+    private val feedDispatcher: CoroutineDispatcher = Dispatchers.Default,+    private val sourceTimeoutMs: Long = SOURCE_TIMEOUT_MS, ) : RoomRepository<NewsDatabase>(context, NewsDatabase::class, DB_NAME) {      constructor(context: Context) : this(context, Networking::fetchText)@@ -42,68 +58,79 @@ class NewsRepository internal constructor(         dao.setBookmarked(url, bookmarked)      /**-     * Fetches every enabled source (sitemap indexes are followed one level,-     * recursively through this same function), merges and caches the result.-     * A failing source never fails the refresh. Returns sources that failed.+     * Fetches every enabled source in parallel; each source publishes+     * to Room as soon as it lands. Returns the names of sources that+     * failed or timed out (a failing source never fails the refresh).      */     suspend fun refresh(sources: List<NewsSource>): List<String> = coroutineScope {-        val results = sources.map { source ->-            async {-                runCatching { fetchFeed(source, depth = 0) }-                    .fold(-                        onSuccess = { it to null },-                        onFailure = { emptyList<com.vayunmathur.news.domain.FeedArticle>() to source.name },-                    )+        val failed = sources.map { source ->+            async { fetchAndPublish(source) }+        }.awaitAll().filterNotNull()+        if (sources.isNotEmpty()) dao.pruneArticles(keep = MAX_CACHED_ARTICLES)+        failed+    }++    /** Fetches + publishes one source; returns its name on failure/timeout, else null. */+    private suspend fun fetchAndPublish(source: NewsSource): String? {+        val startedNanos = System.nanoTime()+        Log.dev(TAG, "refresh source=${source.id} started")+        val articles = try {+            withTimeoutOrNull(sourceTimeoutMs) {+                withContext(feedDispatcher) { fetchFeed(source.feedUrl, source.id, depth = 0) }             }-        }.awaitAll()-        val failed = results.mapNotNull { it.second }-        val merged = FeedMerger.merge(results.map { it.first })+        } catch (e: CancellationException) {+            throw e+        } catch (e: Exception) {+            val elapsedMs = (System.nanoTime() - startedNanos) / 1_000_000+            Log.dev(TAG, "refresh source=${source.id} failed ${e.javaClass.simpleName} after ${elapsedMs}ms")+            return source.name+        }+        val elapsedMs = (System.nanoTime() - startedNanos) / 1_000_000+        if (articles == null) {+            Log.dev(TAG, "refresh source=${source.id} failed timeout after ${elapsedMs}ms")+            return source.name+        }+        val capped = FeedMerger.merge(listOf(articles), limit = MAX_ARTICLES_PER_SOURCE)+        if (capped.isNotEmpty()) publish(capped)+        val totalMs = (System.nanoTime() - startedNanos) / 1_000_000+        Log.dev(TAG, "refresh source=${source.id} landed articles=${capped.size} in ${totalMs}ms")+        return null+    }++    /** Upserts one landed source's articles, preserving existing bookmark flags. */+    private suspend fun publish(articles: List<FeedArticle>) {         val now = System.currentTimeMillis()-        if (merged.isNotEmpty()) {-            // Preserve bookmark flags already in the cache.-            val rows = merged.map { article ->-                val existing = dao.article(article.url)-                CachedArticle(-                    url = article.url, sourceId = article.sourceId, title = article.title,-                    publishedAtMillis = article.publishedAtMillis, imageUrl = article.imageUrl,-                    keywords = article.keywords.joinToString(","),-                    fetchedAtMillis = now, bookmarked = existing?.bookmarked ?: false,-                )-            }-            dao.upsertArticles(rows)-            dao.pruneArticles(keep = 500)+        val bookmarked = dao.bookmarkedUrls(articles.map { it.url }).toSet()+        val rows = articles.map { article ->+            CachedArticle(+                url = article.url, sourceId = article.sourceId, title = article.title,+                publishedAtMillis = article.publishedAtMillis, imageUrl = article.imageUrl,+                keywords = article.keywords.joinToString(","),+                fetchedAtMillis = now, bookmarked = article.url in bookmarked,+            )         }-        failed+        dao.upsertArticles(rows)     } -    private suspend fun fetchFeed(-        source: NewsSource,-        depth: Int,-    ): List<com.vayunmathur.news.domain.FeedArticle> {-        val parsed = SitemapParser.parse(fetch(source.feedUrl), source.id)+    /**+     * Fetches one feed document and, for a sitemap index, its newest+     * [MAX_INDEX_CHILDREN] children (in parallel, recursively, at most+     * [MAX_INDEX_DEPTH] levels deep). Runs in the caller's context —+     * [fetchAndPublish] confines it to [feedDispatcher].+     */+    private suspend fun fetchFeed(url: String, sourceId: String, depth: Int): List<FeedArticle> {+        val parsed = SitemapParser.parse(fetch(url), sourceId)         if (parsed.childSitemaps.isEmpty() || depth >= MAX_INDEX_DEPTH) return parsed.articles         // Indexes list newest child first; the first few carry today's news.         return coroutineScope {             parsed.childSitemaps.take(MAX_INDEX_CHILDREN).map { child ->                 async {-                    runCatching {-                        val childParsed = SitemapParser.parse(fetch(child), source.id)-                        if (childParsed.childSitemaps.isNotEmpty() && depth + 1 < MAX_INDEX_DEPTH) {-                            childParsed.childSitemaps.take(MAX_INDEX_CHILDREN - 1).flatMap { grandchild ->-                                runCatching {-                                    SitemapParser.parse(fetch(grandchild), source.id).articles-                                }.getOrElse {-                                    Log.error(TAG, "feed fetch failed")-                                    emptyList()-                                }-                            }-                        } else {-                            childParsed.articles+                    runCatching { fetchFeed(child, sourceId, depth + 1) }+                        .getOrElse {+                            if (it is CancellationException) throw it+                            Log.dev(TAG, "refresh source=$sourceId child fetch failed url=$child")+                            emptyList()                         }-                    }.getOrElse {-                        Log.error(TAG, "feed fetch failed")-                        emptyList()-                    }                 }             }.awaitAll().flatten()         }@@ -112,15 +139,21 @@ class NewsRepository internal constructor(     /** Cached body if present, otherwise fetch + extract + cache. Throws on fetch failure with no cache. */     suspend fun articleBody(url: String): ExtractedArticle {         dao.body(url)?.let { return it.toExtracted(json) }-        val extracted = ArticleExtractor.extract(fetch(url), url)+        // Extraction is CPU-heavy HTML work: never on the caller's (Main) dispatcher.+        val extracted = withContext(feedDispatcher) { ArticleExtractor.extract(fetch(url), url) }         dao.upsertBody(extracted.toCached(json))         return extracted     }      companion object {         private const val TAG = "NewsRepository"++        /** Overall per-source budget: fetch + follow index + parse + publish. */+        const val SOURCE_TIMEOUT_MS = 20_000L         private const val MAX_INDEX_DEPTH = 2         private const val MAX_INDEX_CHILDREN = 3+        private const val MAX_ARTICLES_PER_SOURCE = 200+        private const val MAX_CACHED_ARTICLES = 500          @Volatile         private var instance: NewsRepository? = null
news/src/main/java/com/vayunmathur/news/domain/SitemapParser.kt
diff --git a/news/src/main/java/com/vayunmathur/news/domain/SitemapParser.kt b/news/src/main/java/com/vayunmathur/news/domain/SitemapParser.ktindex 3c2192e583..8f2d4de023 100644--- a/news/src/main/java/com/vayunmathur/news/domain/SitemapParser.kt+++ b/news/src/main/java/com/vayunmathur/news/domain/SitemapParser.kt@@ -8,9 +8,16 @@ data class ParsedFeed(  /**  * Pure parser for Google News sitemaps (urlset + news extension), plain- * urlsets, sitemap indexes, RSS 2.0 and Atom. Deliberately string-based- * (no XML library) so it runs identically on device and in plain JVM unit- * tests; it tolerates malformed entries by skipping them, never throwing.+ * urlsets, sitemap indexes, RSS 2.0 and Atom.+ *+ * Linear scan only: entries are located with [String.indexOf] and each+ * entry block is scanned in isolation. There is deliberately no+ * whole-document regex `findAll` and no regex is compiled per entry —+ * a previous regex-over-the-whole-document implementation burned 22s+ * of main-thread CPU on a ~996-URL BBC sitemap (ANR 2026-11-23). This+ * parser is O(document length) with small constants and never throws;+ * malformed entries are skipped. Callers must still run it off the+ * main thread (see NewsRepository, which parses on Dispatchers.Default).  */ object SitemapParser { @@ -25,22 +32,25 @@ object SitemapParser {         }     } -    private fun extractSitemapChildren(doc: String): List<String> =-        Regex("""<sitemap>\s*<loc>([^<]+)</loc>""").findAll(doc)-            .map { decodeEntities(it.groupValues[1].trim()) }.filter { it.startsWith("http") }.toList()+    private fun extractSitemapChildren(doc: String): List<String> {+        val out = mutableListOf<String>()+        forEachBlock(doc, "<sitemap>", "</sitemap>") { block ->+            val loc = tagText(block, "loc") ?: return@forEachBlock+            if (loc.startsWith("http")) out += loc+        }+        return out+    }      private fun extractUrlset(doc: String, sourceId: String): List<FeedArticle> {         val out = mutableListOf<FeedArticle>()-        for (match in Regex("""<url>(.*?)</url>""", RegexOption.DOT_MATCHES_ALL).findAll(doc)) {-            val block = match.groupValues[1]-            val loc = tagText(block, "loc") ?: continue-            if (!loc.startsWith("http")) continue+        forEachBlock(doc, "<url>", "</url>") { block ->+            val loc = tagText(block, "loc") ?: return@forEachBlock+            if (!loc.startsWith("http")) return@forEachBlock             val title = tagText(block, "news:title") ?: tagText(block, "title") ?: loc             val date = tagText(block, "news:publication_date") ?: tagText(block, "lastmod")             val keywords = tagText(block, "news:keywords")                 ?.split(",")?.map { it.trim() }?.filter { it.isNotEmpty() } ?: emptyList()-            val image = Regex("""<image:image>\s*<image:loc>([^<]+)</image:loc>""")-                .find(block)?.groupValues?.get(1)?.let { decodeEntities(it.trim()) }+            val image = tagText(block, "image:loc")             out += FeedArticle(                 url = loc, sourceId = sourceId, title = title,                 publishedAtMillis = DateParsing.parseMillis(date) ?: 0L,@@ -52,13 +62,12 @@ object SitemapParser {      private fun extractRss(doc: String, sourceId: String): List<FeedArticle> {         val out = mutableListOf<FeedArticle>()-        for (match in Regex("""<item>(.*?)</item>""", RegexOption.DOT_MATCHES_ALL).findAll(doc)) {-            val block = match.groupValues[1]-            val link = tagText(block, "link") ?: continue+        forEachBlock(doc, "<item>", "</item>") { block ->+            val link = tagText(block, "link") ?: return@forEachBlock             val title = tagText(block, "title") ?: link             val date = tagText(block, "pubDate") ?: tagText(block, "dc:date")-            val image = Regex("""<media:content[^>]*url="([^"]+)"""").find(block)?.groupValues?.get(1)-                ?: Regex("""enclosure[^>]*url="([^"]+)"""").find(block)?.groupValues?.get(1)+            val image = attributeAfter(block, "media:content", "url")+                ?: attributeAfter(block, "enclosure", "url")             out += FeedArticle(link, sourceId, title, DateParsing.parseMillis(date) ?: 0L, image)         }         return out@@ -66,9 +75,8 @@ object SitemapParser {      private fun extractAtom(doc: String, sourceId: String): List<FeedArticle> {         val out = mutableListOf<FeedArticle>()-        for (match in Regex("""<entry>(.*?)</entry>""", RegexOption.DOT_MATCHES_ALL).findAll(doc)) {-            val block = match.groupValues[1]-            val link = Regex("""<link[^>]*href="([^"]+)"""").find(block)?.groupValues?.get(1) ?: continue+        forEachBlock(doc, "<entry>", "</entry>") { block ->+            val link = attributeAfter(block, "link", "href") ?: return@forEachBlock             val title = tagText(block, "title") ?: link             val date = tagText(block, "published") ?: tagText(block, "updated")             out += FeedArticle(decodeEntities(link), sourceId, title, DateParsing.parseMillis(date) ?: 0L)@@ -76,22 +84,61 @@ object SitemapParser {         return out     } +    /**+     * Visits each `<open>…</close>` block in order, in one forward pass.+     * Unterminated trailing blocks are ignored.+     */+    private inline fun forEachBlock(doc: String, open: String, close: String, visit: (String) -> Unit) {+        var from = 0+        while (true) {+            val start = doc.indexOf(open, from)+            if (start < 0) return+            val contentStart = start + open.length+            val end = doc.indexOf(close, contentStart)+            if (end < 0) return+            visit(doc.substring(contentStart, end))+            from = end + close.length+        }+    }++    /** Text of the first `<tag>…</tag>` inside [block], or null. Linear in the block. */     private fun tagText(block: String, tag: String): String? {-        val raw = Regex("""<$tag>(.*?)</$tag>""", RegexOption.DOT_MATCHES_ALL)-            .find(block)?.groupValues?.get(1) ?: return null+        val open = "<$tag>"+        val start = block.indexOf(open)+        if (start < 0) return null+        val contentStart = start + open.length+        val end = block.indexOf("</$tag>", contentStart)+        if (end < 0) return null+        val raw = block.substring(contentStart, end)         val cdata = raw.trim().removePrefix("<![CDATA[").removeSuffix("]]>")         return decodeEntities(cdata.trim()).takeIf { it.isNotEmpty() }     } +    /** Value of attribute [attr] on the first `<tag …>` inside [block], or null. */+    private fun attributeAfter(block: String, tag: String, attr: String): String? {+        val tagStart = block.indexOf("<$tag")+        if (tagStart < 0) return null+        val attrStart = block.indexOf("$attr=\"", tagStart)+        if (attrStart < 0) return null+        val valueStart = attrStart + attr.length + 2+        val end = block.indexOf('"', valueStart)+        if (end < 0) return null+        return decodeEntities(block.substring(valueStart, end)).takeIf { it.isNotEmpty() }+    }+     internal fun decodeEntities(text: String): String {         var out = text             .replace("&amp;", "&").replace("&lt;", "<").replace("&gt;", ">")             .replace("&quot;", "\"").replace("&apos;", "'").replace("&#39;", "'")-        out = out.replace(Regex("""&#x([0-9a-fA-F]+);""")) {+        out = out.replace(NUMERIC_HEX_ENTITY) {             it.groupValues[1].toIntOrNull(16)?.toChar()?.toString() ?: it.value         }-        return out.replace(Regex("""&#(\d+);""")) {+        return out.replace(NUMERIC_DEC_ENTITY) {             it.groupValues[1].toIntOrNull()?.toChar()?.toString() ?: it.value         }     }++    // Compiled once, applied only to individual field strings (never the document).+    private val NUMERIC_HEX_ENTITY = Regex("""&#x([0-9a-fA-F]+);""")+    private val NUMERIC_DEC_ENTITY = Regex("""&#(\d+);""") }
news/src/main/java/com/vayunmathur/news/network/Networking.kt
diff --git a/news/src/main/java/com/vayunmathur/news/network/Networking.kt b/news/src/main/java/com/vayunmathur/news/network/Networking.ktindex 88b1d93cd9..511ae756ed 100644--- a/news/src/main/java/com/vayunmathur/news/network/Networking.kt+++ b/news/src/main/java/com/vayunmathur/news/network/Networking.kt@@ -17,10 +17,22 @@ object Networking {         "Accept-Language" to "en-GB,en;q=0.8",     ) -    /** GET [url] as text; throws [IOException] on transport failure or non-2xx. */+    /**+     * GET [url] as text; throws [IOException] on transport failure or non-2xx.+     * Explicit per-request timeouts (the client's pooled defaults are+     * 10s connect / 30s read, and a read timeout only bounds stalls+     * between bytes — NewsRepository additionally bounds each whole+     * source fetch, see its SOURCE_TIMEOUT_MS).+     */     suspend fun fetchText(url: String): String {-        val response = NetworkClient.execute(url, headers = headers)+        val response = NetworkClient.execute(+            url, headers = headers,+            connectTimeoutMs = CONNECT_TIMEOUT_MS, readTimeoutMs = READ_TIMEOUT_MS,+        )         if (!response.isSuccess) throw IOException("HTTP ${response.status} for $url")         return response.text     }++    private const val CONNECT_TIMEOUT_MS = 10_000L+    private const val READ_TIMEOUT_MS = 15_000L }
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 55e3583b17..b07f4f4417 100644--- a/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt+++ b/news/src/main/java/com/vayunmathur/news/platform/NewsViewModel.kt@@ -53,8 +53,6 @@ class NewsViewModel(         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), NewsPrefs.DEFAULT_TEXT_SP)     val readerSerif: StateFlow<Boolean> = prefs.readerSerif         .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)-    val readerWebView: StateFlow<Boolean> = prefs.readerWebView-        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), false)      private val _readerBody = MutableStateFlow<ExtractedArticle?>(null)     val readerBody: StateFlow<ExtractedArticle?> = _readerBody.asStateFlow()@@ -123,10 +121,6 @@ class NewsViewModel(     fun setReaderSerif(serif: Boolean) {         viewModelScope.launch { prefs.setReaderSerif(serif) }     }--    fun setReaderWebView(webView: Boolean) {-        viewModelScope.launch { prefs.setReaderWebView(webView) }-    } }  /** Factory wiring the repository and prefs owners into [NewsViewModel]. */
news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.kt b/news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.ktdeleted file mode 100644index cff89fc7cc..0000000000--- a/news/src/main/java/com/vayunmathur/news/ui/OriginalWebView.kt+++ /dev/null@@ -1,26 +0,0 @@-package com.vayunmathur.news.ui--import android.annotation.SuppressLint-import android.webkit.WebView-import android.webkit.WebViewClient-import androidx.compose.runtime.Composable-import androidx.compose.ui.Modifier-import androidx.compose.ui.viewinterop.AndroidView--/** The article's original page, for the reader's clean/original toggle. */-@SuppressLint("SetJavaScriptEnabled")-@Composable-fun OriginalWebView(url: String, modifier: Modifier = Modifier) {-    AndroidView(-        modifier = modifier,-        factory = { context ->-            WebView(context).apply {-                webViewClient = WebViewClient()-                settings.javaScriptEnabled = true-                settings.domStorageEnabled = true-                loadUrl(url)-            }-        },-        update = { view -> if (view.url != url) view.loadUrl(url) },-    )-}
news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.kt
diff --git a/news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.kt b/news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.ktindex 27e2367174..ecc7051de3 100644--- a/news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.kt+++ b/news/src/main/java/com/vayunmathur/news/ui/ReaderScreen.kt@@ -1,7 +1,7 @@ package com.vayunmathur.news.ui -import android.content.Intent import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding@@ -13,20 +13,16 @@ import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale-import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp-import androidx.core.net.toUri import com.vayunmathur.library.image.compose.AsyncImage import com.vayunmathur.library.ui.AppScaffold import com.vayunmathur.library.ui.FilterChip import com.vayunmathur.library.ui.IconBookmark import com.vayunmathur.library.ui.IconBookmarkBorder import com.vayunmathur.library.ui.IconButton-import com.vayunmathur.library.ui.IconGlobe-import com.vayunmathur.library.ui.IconOpenInNew import com.vayunmathur.library.ui.IconTextTool import com.vayunmathur.library.ui.MaterialTheme import com.vayunmathur.library.ui.Text@@ -36,8 +32,10 @@ import com.vayunmathur.news.platform.NewsViewModel  /**  * First-class reader: the extracted clean article (title, byline, date,- * comfortable measure, adjustable size, serif/sans) with a toggle to the- * original web page and an open-in-browser action.+ * comfortable measure, adjustable size, serif/sans). Reader-only: there+ * is no original-page WebView or open-in-browser affordance, and the+ * top app bar carries no actions — bookmark, text size and serif live+ * in an in-content action row below the title.  */ @Composable fun ReaderScreen(viewModel: NewsViewModel, url: String, onBack: () -> Unit) {@@ -46,85 +44,81 @@ fun ReaderScreen(viewModel: NewsViewModel, url: String, onBack: () -> Unit) {     val bookmarked by viewModel.readerBookmarked.collectAsState()     val textSp by viewModel.readerTextSp.collectAsState()     val serif by viewModel.readerSerif.collectAsState()-    val webView by viewModel.readerWebView.collectAsState()-    val context = LocalContext.current     LaunchedEffect(url) { viewModel.openArticle(url) }     AppScaffold(         title = stringResource(R.string.reader_title),         onNavigateBack = onBack,-        actions = {-            IconButton(onClick = { viewModel.setReaderWebView(!webView) }) { IconGlobe() }-            IconButton(onClick = viewModel::toggleReaderBookmark) {-                if (bookmarked) IconBookmark() else IconBookmarkBorder()-            }-            IconButton(onClick = {-                context.startActivity(Intent(Intent.ACTION_VIEW, url.toUri()))-            }) { IconOpenInNew() }-        },     ) { padding ->-        if (webView) {-            OriginalWebView(url, Modifier.fillMaxSize().padding(padding))-            return@AppScaffold-        }         Column(             modifier = Modifier.fillMaxSize().padding(padding).verticalScroll(rememberScrollState())                 .padding(horizontal = 20.dp, vertical = 12.dp),         ) {-            ReaderControls(-                textSp = textSp, serif = serif,+            if (body != null) {+                Text(body!!.title, style = MaterialTheme.typography.headlineMedium)+                if (!body!!.byline.isNullOrBlank()) {+                    Text(+                        body!!.byline!!, style = MaterialTheme.typography.labelLarge,+                        modifier = Modifier.padding(top = 6.dp),+                    )+                }+            }+            ReaderActionRow(+                bookmarked = bookmarked, textSp = textSp, serif = serif,+                onToggleBookmark = viewModel::toggleReaderBookmark,                 onTextSp = viewModel::setReaderTextSp, onSerif = viewModel::setReaderSerif,             )             when {                 error -> Text(stringResource(R.string.reader_loading_failed))                 body == null -> Text("…")-                else -> ReaderBody(title = body!!.title, byline = body!!.byline, textSp = textSp, serif = serif, blocks = body!!.blocks)+                else -> ReaderBody(textSp = textSp, serif = serif, blocks = body!!.blocks)             }         }     } } +/** In-content reader actions: bookmark, serif/sans, and text size. */ @Composable-private fun ReaderControls(+private fun ReaderActionRow(+    bookmarked: Boolean,     textSp: Int,     serif: Boolean,+    onToggleBookmark: () -> Unit,     onTextSp: (Int) -> Unit,     onSerif: (Boolean) -> Unit, ) {-    Column(modifier = Modifier.fillMaxWidth().padding(bottom = 12.dp)) {+    Row(modifier = Modifier.fillMaxWidth().padding(vertical = 12.dp)) {+        IconButton(onClick = onToggleBookmark) {+            if (bookmarked) IconBookmark() else IconBookmarkBorder()+        }         FilterChip(             selected = serif,             onClick = { onSerif(!serif) },             label = { Text(if (serif) stringResource(R.string.reader_serif) else stringResource(R.string.reader_sans)) },             leadingIcon = { IconTextTool() },+            modifier = Modifier.padding(start = 8.dp),         )         FilterChip(             selected = false,             onClick = { onTextSp(textSp - 1) },             label = { Text(stringResource(R.string.reader_text_smaller)) },-            modifier = Modifier.padding(top = 8.dp),+            modifier = Modifier.padding(start = 8.dp),         )         FilterChip(             selected = false,             onClick = { onTextSp(textSp + 1) },             label = { Text(stringResource(R.string.reader_text_larger)) },-            modifier = Modifier.padding(top = 8.dp),+            modifier = Modifier.padding(start = 8.dp),         )     } }  @Composable private fun ReaderBody(-    title: String,-    byline: String?,     textSp: Int,     serif: Boolean,     blocks: List<ArticleBlock>, ) {     val family = if (serif) FontFamily.Serif else FontFamily.SansSerif-    Text(title, style = MaterialTheme.typography.headlineMedium)-    if (!byline.isNullOrBlank()) {-        Text(byline, style = MaterialTheme.typography.labelLarge, modifier = Modifier.padding(top = 6.dp))-    }     for (block in blocks) {         when (block) {             is ArticleBlock.Heading -> Text(
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 99bcd4c92f..be73fc4242 100644--- a/news/src/main/res/values/strings.xml+++ b/news/src/main/res/values/strings.xml@@ -12,7 +12,7 @@     <string name="reader_text_larger">Larger text</string>     <string name="reader_serif">Serif</string>     <string name="reader_sans">Sans</string>-    <string name="reader_loading_failed">Could not load this article. Try the original page.</string>+    <string name="reader_loading_failed">Could not load this article.</string>     <!-- SourcesScreen -->     <string name="sources_title">Sources</string>     <string name="sources_note">Articles are fetched directly from each publisher. No account and no server of ours is involved.</string>
news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt b/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.ktindex ee4304f3da..85e1de8495 100644--- a/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt+++ b/news/src/test/java/com/vayunmathur/news/data/NewsRepositoryTest.kt@@ -3,6 +3,7 @@ package com.vayunmathur.news.data import android.content.Context import androidx.test.core.app.ApplicationProvider import com.vayunmathur.news.domain.SourceCatalog+import kotlinx.coroutines.async import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith@@ -55,7 +56,8 @@ class NewsRepositoryTest {         assertTrue(failed.isEmpty())         assertTrue(calls.any { it.endsWith("child.xml") })         val cached = kotlinx.coroutines.withTimeout(10_000) { repo.articles.first { it.isNotEmpty() } }-        assertEquals(listOf("Fake Story"), cached.map { it.title })+        // The test DB is shared across this class, so assert presence, not exclusivity.+        assertTrue(cached.any { it.title == "Fake Story" })     }      @Test@@ -71,10 +73,69 @@ class NewsRepositoryTest {         assertEquals(callsAfterFirst, calls.size, "second read must come from the Room cache")     } +    @Test+    fun fastSourcePublishesWhileHangingSourceTimesOut() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Context>()+        val fastUrlset = """+            <urlset><url><loc>https://fake.example/fast-story</loc>+            <news:title>Fast Story</news:title></url></urlset>+        """.trimIndent()+        val repo = NewsRepository(+            context,+            fetch = { url ->+                if (url.contains("hang")) kotlinx.coroutines.delay(Long.MAX_VALUE)+                fastUrlset+            },+            sourceTimeoutMs = 500,+        )+        val fast = SourceCatalog.byId("bbc")!!.copy(name = "Fast", feedUrl = "https://fake.example/fast.xml")+        val hanging = SourceCatalog.byId("guardian")!!.copy(name = "Hang", feedUrl = "https://fake.example/hang.xml")+        val refreshJob = async { repo.refresh(listOf(hanging, fast)) }+        // Cache-first / incremental: the fast source's articles are visible+        // from the Room flow before the refresh as a whole completes.+        val cached = kotlinx.coroutines.withTimeout(10_000) {+            repo.articles.first { articles -> articles.any { it.title == "Fast Story" } }+        }+        assertTrue(cached.any { it.title == "Fast Story" })+        assertTrue(refreshJob.isActive, "fast articles must publish while the hanging source is still in flight")+        val failed = kotlinx.coroutines.withTimeout(10_000) { refreshJob.await() }+        assertEquals(listOf("Hang"), failed)+    }++    @Test+    fun cachedArticlesEmitWithoutRefresh() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Context>()+        val calls = mutableListOf<String>()+        val repo = NewsRepository(context, fakeFetch(calls))+        val source = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://fake.example/index.xml")+        repo.refresh(listOf(source))+        // No refresh in flight: the Room cache alone must serve the feed.+        val cached = repo.articles.first { it.isNotEmpty() }+        assertTrue(cached.any { it.title == "Fake Story" })+    }++    @Test+    fun feedFetchRunsOffMainThread() = runBlocking {+        val context = ApplicationProvider.getApplicationContext<Context>()+        val mainThreadName = Thread.currentThread().name+        val seenThreads = java.util.Collections.synchronizedList(mutableListOf<String>())+        val repo = NewsRepository(context, fetch = { _ ->+            seenThreads += Thread.currentThread().name+            childUrlset+        })+        val source = SourceCatalog.byId("bbc")!!.copy(feedUrl = "https://fake.example/direct.xml")+        repo.refresh(listOf(source))+        assertTrue(seenThreads.isNotEmpty())+        assertTrue(+            seenThreads.none { it == mainThreadName },+            "feed fetch/parse must not run on the main thread, saw $seenThreads",+        )+    }+     @Test     fun failingSourceIsReportedNotThrown() = runBlocking {         val context = ApplicationProvider.getApplicationContext<Context>()-        val repo = NewsRepository(context) { throw java.io.IOException("offline") }+        val repo = NewsRepository(context, fetch = { throw java.io.IOException("offline") })         val failed = repo.refresh(listOf(SourceCatalog.sources.first()))         assertEquals(1, failed.size)     }
news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.kt
diff --git a/news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.kt b/news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.ktindex a55f92f0f8..123fbc3392 100644--- a/news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.kt+++ b/news/src/test/java/com/vayunmathur/news/domain/SitemapParserTest.kt@@ -51,6 +51,27 @@ class SitemapParserTest {         assertTrue(parsed.articles[0].publishedAtMillis > 0L)     } +    @Test+    fun bbcSizeUrlsetParsesWithinBound() {+        // Regression for the 2026-11-23 ANR: the old whole-document regex+        // findAll burned 22s of main-thread CPU on a sitemap this size.+        val xml = buildString {+            append("<urlset xmlns:news=\"http://www.google.com/schemas/sitemap-news/0.9\">")+            repeat(996) { i ->+                append("<url><loc>https://example.com/a").append(i).append("</loc>")+                append("<news:news><news:publication_date>2026-11-23T10:00:00+00:00</news:publication_date>")+                append("<news:title>Story ").append(i).append("</news:title></news:news></url>")+            }+            append("</urlset>")+        }+        val startedNanos = System.nanoTime()+        val parsed = SitemapParser.parse(xml, "bbc")+        val elapsedMs = (System.nanoTime() - startedNanos) / 1_000_000+        assertEquals(996, parsed.articles.size)+        assertEquals("Story 995", parsed.articles.last().title)+        assertTrue(elapsedMs < 2_000, "996-URL parse took ${elapsedMs}ms, bound is 2000ms")+    }+     @Test     fun malformedInputNeverThrows() {         assertTrue(SitemapParser.parse("not xml at all", "ex").articles.isEmpty())