Modern Apps git

← Modern-Apps.git

openassistant: read web pages on device

Commit
f3cf6c1f6006333544d0a5b02ccd9842b3806ec6
Author
Vayun Mathur <[email protected]>
When
2026-11-26 00:51 UTC (10 days ago)
Parents
20ffa6d
web_read now fetches the page from the device and extracts readable text locally with the new pure domain/WebPageExtractor (title/og:title/h1 fallback; paragraphs, headings, and list items under main/article/body; script/style/nav/header/footer stripped), paged at 6000 chars with character offsets exactly as the server version behaved. On-device policy: http/https only with URL validation, 10 s timeouts, 2M-char body cap, HTML/plain-text only (other types get the typed unsupported_content_type error), redirects re-checked. No /assistant/v1/* references remain in the app. Web search is unchanged: the app already calls GET /api/search directly and reshapes text results on device.

The extractor is a small deliberate duplicate of the readability idea; news's richer ArticleExtractor is module-private to news. Tool names and model-visible behaviour are unchanged.

Verified: :openassistant:testDevUnitTest and :openassistant:lint green (new WebPageExtractorTest plus re-fixtured read tests: blocked URL, unsupported type, HTTP error, paging); :openassistant:metadata green.

Diff

openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex efb89b522f..34a0e1dff2 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -39,7 +39,7 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/service/OpenAssistantVoiceInteractionService.kt - com/vayunmathur/openassistant/service/StubRecognitionService.kt — placeholder recognizer hook ### network/ — web tools-- com/vayunmathur/openassistant/network/AssistantWebTools.kt+- com/vayunmathur/openassistant/network/AssistantWebTools.kt — the app's networking entry point for web tools: `web_search` calls the server's `GET /api/search` (type=text/news) through `NetworkClient` (FIRST_PARTY bundle inited in MainActivity) and reshapes results on device into {title,url,snippet} hits (n<=10); `web_read`/`web_read_result` fetch the page on device (per-request system trust, since page hosts are arbitrary) and extract readable text locally via `domain/WebPageExtractor` — http/https only, localhost/.local/private IP literals refused, 10s timeouts, 2M-char body cap, 6000-char pages paged by character offset. Tool failures are typed `Error: ...` strings, never silent empties ### data/ — chats + repository - com/vayunmathur/openassistant/data/Database.kt - com/vayunmathur/openassistant/data/OpenAssistantRepository.kt@@ -60,6 +60,7 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/domain/A2uiBlocks.kt — split/restore ```a2ui blocks, streaming-safe - com/vayunmathur/openassistant/domain/A2uiEnvelope.kt — block → A2UI protocol messages, action → user turn - com/vayunmathur/openassistant/domain/ModelLoadFailure.kt — missing vs incomplete vs refused model load, for the error text+- com/vayunmathur/openassistant/domain/WebPageExtractor.kt — on-device readable-text extraction (title + block text, chrome stripped) and the web_read URL policy; a small tolerant duplicate of the readability idea (news's richer extractor is module-private to news) ### platform/ — ViewModel, engine + tool registry - com/vayunmathur/openassistant/platform/AssistantViewModel.kt - com/vayunmathur/openassistant/platform/MamlChatEngine.kt
openassistant/src/main/java/com/vayunmathur/openassistant/domain/WebPageExtractor.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WebPageExtractor.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WebPageExtractor.ktnew file mode 100644index 0000000000..8f96369a37--- /dev/null+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/WebPageExtractor.kt@@ -0,0 +1,207 @@+package com.vayunmathur.openassistant.domain++/**+ * On-device readable-text extraction for web_read (pure, unit-tested).+ *+ * Minimal tolerant extractor mirroring the old server reader's shape:+ * title (title tag, then og:title, then first h1) plus block text from+ * paragraphs/headings/list items/pre/blockquote under <main>, <article>+ * or <body>, with script/style/nav and other chrome stripped. It is a+ * deliberate small duplicate of the readability idea (news has its own+ * richer ArticleExtractor, module-private to news, so it is not reused).+ */+object WebPageExtractor {++    /** Extracted page: [title] may be blank, [text] is the readable body. */+    data class ExtractedPage(val title: String, val text: String)++    private val stripTags = listOf(+        "script", "style", "nav", "header", "footer", "aside", "form",+        "noscript", "iframe", "svg", "button", "select", "textarea",+    )++    fun extract(html: String): ExtractedPage {+        val withoutComments = html.replace(Regex("<!--.*?-->", RegexOption.DOT_MATCHES_ALL), " ")+        val stripped = stripChromeBlocks(withoutComments)+        val title = extractTitle(stripped)+        val root = rootInner(stripped)+        val blocks = blockTexts(root)+        val text = if (blocks.isNotEmpty()) {+            blocks.joinToString("\n\n")+        } else {+            collapseWs(stripTags(root))+        }+        return ExtractedPage(title, text)+    }++    /** Plain-text pages: body is the text itself, title is its first line. */+    fun extractPlainText(body: String): ExtractedPage {+        val title = body.lineSequence().firstOrNull()?.trim()?.take(200).orEmpty()+        return ExtractedPage(title, body)+    }++    private fun stripChromeBlocks(html: String): String {+        var out = html+        for (tag in stripTags) {+            out = out.replace(+                Regex("<$tag\\b[^>]*>.*?</$tag\\s*>", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)),+                " ",+            )+            // Unclosed chrome opener: drop from the tag to end of input.+            out = out.replace(+                Regex("<$tag\\b[^>]*>.*\\z", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL)),+                " ",+            )+        }+        return out+    }++    private fun extractTitle(html: String): String {+        val titleTag = Regex("<title\\b[^>]*>(.*?)</title\\s*>", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))+            .find(html)?.groupValues?.get(1)?.let { collapseWs(stripTags(it)) }.orEmpty()+        if (titleTag.isNotBlank()) return titleTag+        val og = Regex(+            "<meta\\b[^>]*property\\s*=\\s*\"og:title\"[^>]*>",+            RegexOption.IGNORE_CASE,+        ).find(html)?.value?.let { attrValue(it, "content") }.orEmpty()+        if (og.isNotBlank()) return collapseWs(og)+        val h1 = Regex("<h1\\b[^>]*>(.*?)</h1\\s*>", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))+            .find(html)?.groupValues?.get(1)?.let { collapseWs(stripTags(it)) }.orEmpty()+        return h1+    }++    private fun attrValue(tag: String, name: String): String? {+        val m = Regex("$name\\s*=\\s*\"([^\"]*)\"|$name\\s*=\\s*'([^']*)'", RegexOption.IGNORE_CASE).find(tag)+            ?: return null+        return m.groupValues.drop(1).firstOrNull { it.isNotEmpty() }+    }++    /** Inner HTML of <main>, else <article>, else <body>, else the whole input. */+    private fun rootInner(html: String): String {+        for (tag in listOf("main", "article", "body")) {+            val m = Regex(+                "<$tag\\b[^>]*>(.*)</$tag\\s*>",+                setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),+            ).find(html)+            if (m != null) return m.groupValues[1]+        }+        return html+    }++    private fun blockTexts(root: String): List<String> {+        val blockRe = Regex(+            "<(p|h1|h2|h3|h4|h5|h6|li|pre|blockquote)\\b[^>]*>(.*?)</\\1\\s*>",+            setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),+        )+        return blockRe.findAll(root).mapNotNull { m ->+            collapseWs(stripTags(m.groupValues[2])).takeIf { it.isNotEmpty() }+        }.toList()+    }++    fun stripTags(fragment: String): String =+        decodeEntities(fragment.replace(Regex("<[^>]*>"), " "))++    fun collapseWs(text: String): String = text.split(Regex("\\s+")).filter { it.isNotEmpty() }.joinToString(" ")++    fun decodeEntities(text: String): String {+        var out = text+            .replace("&nbsp;", " ")+            .replace("&lt;", "<")+            .replace("&gt;", ">")+            .replace("&quot;", "\"")+            .replace("&#39;", "'")+            .replace("&apos;", "'")+        out = Regex("&#x([0-9a-fA-F]+);").replace(out) { m ->+            m.groupValues[1].toIntOrNull(16)?.takeIf { it in 0..0x10FFFF }?.let { Character.toChars(it).concatToString() } ?: m.value+        }+        out = Regex("&#(\\d+);").replace(out) { m ->+            m.groupValues[1].toIntOrNull()?.takeIf { it in 0..0x10FFFF }?.let { Character.toChars(it).concatToString() } ?: m.value+        }+        // &amp; last so &amp;lt; stays a literal &lt; text, not a tag char.+        return out.replace("&amp;", "&")+    }+}++/** Why a tool-supplied URL was refused on device, as a stable error code. */+data class UrlRefusal(val code: String, val message: String)++/**+ * Proportionate on-device URL sanity for web_read: http/https only, a real+ * host, and no localhost / .local / private-or-reserved IP-literal targets.+ * (Unlike the old server fetcher there is no DNS pinning on device: the+ * user's own assistant fetches a URL the model chose, so scheme + literal+ * checks plus size/timeout caps in the fetcher are the proportionate bar.)+ */+/** Outcome of [WebReadUrlPolicy.validate]: the usable URL, or why it was refused. */+sealed interface UrlCheck {+    data class Ok(val url: String) : UrlCheck+    data class Refused(val refusal: UrlRefusal) : UrlCheck+}++object WebReadUrlPolicy {++    fun validate(raw: String): UrlCheck {+        val trimmed = raw.trim()+        if (trimmed.isEmpty()) return UrlCheck.Refused(UrlRefusal("invalid_url", "empty url"))+        val uri = try {+            java.net.URI(trimmed)+        } catch (expected: Exception) {+            return UrlCheck.Refused(UrlRefusal("invalid_url", "unparseable url"))+        }+        val scheme = uri.scheme?.lowercase()+        if (scheme != "http" && scheme != "https") {+            return UrlCheck.Refused(UrlRefusal("unsupported_scheme", "unsupported scheme: ${scheme ?: "none"}"))+        }+        val host = uri.host?.lowercase()?.trimEnd('.')+            ?: return UrlCheck.Refused(UrlRefusal("invalid_url", "url has no host"))+        if (host == "localhost" || host.endsWith(".local")) {+            return UrlCheck.Refused(UrlRefusal("blocked_url", "internal hostnames are not allowed"))+        }+        val literal = host.removePrefix("[").removeSuffix("]")+        if (isIpv4Literal(literal) && !isPublicIpv4(literal)) {+            return UrlCheck.Refused(UrlRefusal("blocked_url", "host is a non-public address"))+        }+        if (literal.contains(':') && !isPublicIpv6(literal)) {+            return UrlCheck.Refused(UrlRefusal("blocked_url", "host is a non-public address"))+        }+        return UrlCheck.Ok(trimmed)+    }++    /** Refusal for [url], or null when it passes — for the fetcher's final-URL recheck. */+    fun refusalFor(url: String): UrlRefusal? = when (val r = validate(url)) {+        is UrlCheck.Ok -> null+        is UrlCheck.Refused -> r.refusal+    }++    private fun isIpv4Literal(host: String): Boolean =+        host.split('.').let { it.size == 4 && it.all { p -> p.isNotEmpty() && p.all(Char::isDigit) } }++    private fun isPublicIpv4(host: String): Boolean {+        val o = host.split('.').map { it.toIntOrNull() ?: return false }+        if (o.any { it !in 0..255 }) return false+        if (o[0] == 0 || o[0] == 10 || o[0] == 127) return false+        if (o[0] == 172 && o[1] in 16..31) return false+        if (o[0] == 192 && o[1] == 168) return false+        if (o[0] == 169 && o[1] == 254) return false+        if (o[0] == 100 && o[1] in 64..127) return false+        if (o[0] == 192 && o[1] == 0 && o[2] == 2) return false+        if (o[0] == 198 && o[1] == 51 && o[2] == 100) return false+        if (o[0] == 203 && o[1] == 0 && o[2] == 113) return false+        if (o[0] == 198 && (o[1] == 18 || o[1] == 19)) return false+        if (o[0] >= 224) return false+        return true+    }++    private fun isPublicIpv6(host: String): Boolean {+        val h = host.lowercase()+        if (h == "::" || h == "::1") return false+        if (h.startsWith("fe8") || h.startsWith("fe9") || h.startsWith("fea") || h.startsWith("feb")) return false+        if (h.startsWith("fc") || h.startsWith("fd")) return false+        if (h.startsWith("2001:db8")) return false+        if (h.startsWith("ff")) return false+        // IPv4-mapped: judge by the embedded v4 tail.+        val tail = h.substringAfterLast(':')+        if (isIpv4Literal(tail)) return isPublicIpv4(tail)+        return true+    }+}
openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.ktindex ac36c13305..4834b93c6e 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/network/AssistantWebTools.kt@@ -2,6 +2,9 @@ package com.vayunmathur.openassistant.network  import com.vayunmathur.library.network.NetworkClient import com.vayunmathur.library.network.Urls+import com.vayunmathur.openassistant.domain.UrlCheck+import com.vayunmathur.openassistant.domain.WebPageExtractor+import com.vayunmathur.openassistant.domain.WebReadUrlPolicy import com.vayunmathur.openassistant.platform.A2uiTemplates import com.vayunmathur.openassistant.platform.SearchResultItem import kotlinx.coroutines.CancellationException@@ -13,6 +16,9 @@ import java.net.URI /**  * Wire contract for GET https://api.maproj.org/api/search  * (copied from web/data/WebSearch.kt shapes; openassistant must not depend on the web app).+ * Search stays server-backed via /api/search (also used by the Web app);+ * results are reshaped on device into the {title,url,snippet} hits the+ * tools consume. Page reading is fully on-device (see [webRead]).  */ @Serializable data class WebSearchResponse(@@ -51,14 +57,12 @@ data class WebSearchNewsItem(     val source: String = "", ) -/** Wire contract for GET https://api.maproj.org/assistant/v1/read. */-@Serializable-data class WebReadResponse(-    val title: String = "",-    val url: String = "",-    val text: String = "",-    val truncated: Boolean = false,-    @SerialName("next_offset") val nextOffset: Int? = null,+/** A page fetched on device for [AssistantWebTools.webRead]. */+data class FetchedPage(+    val body: String,+    val contentType: String? = null,+    val finalUrl: String = "",+    val status: Int = 200, )  /** One stored search hit (host-side only; index is 1-based for the model). */@@ -71,14 +75,23 @@ data class WebHit( )  /**- * Web search + page reading (Phase W). All READ tools.+ * Web search + page reading. All READ tools.  *- * Transport seam for tests: [transport] fetches a URL and returns the body text.- * Production defaults to a [NetworkClient] GET (FIRST_PARTY, inited in MainActivity).- * Never throws to the model: failures come back as clean "Error: ..." strings.+ * Search calls the server's GET /api/search directly (type=text, or+ * type=news for the news kind) through [NetworkClient] (FIRST_PARTY, inited+ * in MainActivity) and reshapes the text results on device. Read fetches+ * the page from the device and extracts readable text locally with+ * [WebPageExtractor]; arbitrary web hosts need system trust, so the page+ * fetch passes useSystemTrust per request while search keeps FIRST_PARTY.+ *+ * Transport seams for tests: [transport] fetches the search URL and returns+ * the body text; [pageTransport] fetches a page URL. Neither hits the live+ * network in tests. Never throws to the model: failures come back as clean+ * typed "Error: ..." strings (no silent empty results).  */ class AssistantWebTools(     private val transport: suspend (url: String) -> String = { url -> defaultTransport(url) },+    private val pageTransport: suspend (url: String) -> FetchedPage = { url -> defaultPageTransport(url) },     private val nowMillis: () -> Long = { System.currentTimeMillis() }, ) {     private var lastHits: List<WebHit> = emptyList()@@ -145,34 +158,43 @@ class AssistantWebTools(         return formatSearchResults(hits)     } +    /**+     * Reads [url] on device: validates it ([WebReadUrlPolicy]), fetches it+     * with size/timeout caps, then extracts and pages the readable text+     * locally. [offset] is a character offset into the extracted text.+     */     suspend fun webRead(url: String, offset: Int = 0): String {-        if (url.isBlank()) return "Error: could not read page: empty url"-        val full = Urls.appendQuery(-            READ_URL,-            buildMap {-                put("url", url)-                if (offset > 0) put("offset", offset.toString())-            },-        )-        val body = try {-            transport(full)+        val checked = when (val c = WebReadUrlPolicy.validate(url)) {+            is UrlCheck.Ok -> c.url+            is UrlCheck.Refused -> return "Error: could not read page: ${c.refusal.code}: ${c.refusal.message}"+        }+        val fetched = try {+            pageTransport(checked)         } catch (e: CancellationException) {             throw e         } catch (expected: Exception) {-            return "Error: could not read page: ${expected.message ?: "network error"}"+            return "Error: could not read page: fetch_failed: ${expected.message ?: "network error"}"         }-        val parsed = try {-            json.decodeFromString<WebReadResponse>(body)-        } catch (expected: Exception) {-            return "Error: could not read page: could not parse reader response"+        if (fetched.status !in 200..299) {+            return "Error: could not read page: fetch_failed: HTTP ${fetched.status}"         }-        return formatReadResult(-            parsed.title,-            parsed.url.ifBlank { url },-            parsed.text,-            parsed.truncated,-            parsed.nextOffset,-        )+        if (fetched.body.length > MAX_BODY_CHARS) {+            return "Error: could not read page: too_large: page is larger than the read limit"+        }+        val finalUrl = fetched.finalUrl.ifBlank { checked }+        // A redirect may have landed somewhere the policy refuses; recheck.+        WebReadUrlPolicy.refusalFor(finalUrl)?.let {+            return "Error: could not read page: ${it.code}: ${it.message}"+        }+        val kind = contentKind(fetched.contentType, fetched.body)+        val page = when (kind) {+            ContentKind.Unsupported ->+                return "Error: could not read page: unsupported_content_type: only HTML and plain-text pages can be read"+            ContentKind.PlainText -> WebPageExtractor.extractPlainText(fetched.body)+            ContentKind.Html -> WebPageExtractor.extract(fetched.body)+        }+        val (slice, truncated, nextOffset) = paginate(page.text, offset.coerceAtLeast(0))+        return formatReadResult(page.title, finalUrl, slice, truncated, nextOffset)     }      suspend fun webReadResult(index: Int, offset: Int = 0): String {@@ -182,9 +204,7 @@ class AssistantWebTools(         }         val hit = hits.firstOrNull { it.index == index }             ?: return "Error: no result at index $index in the last search"-        val body = webRead(hit.url, offset)-        // webRead already formats title/url; keep its clean error strings untouched.-        return body+        return webRead(hit.url, offset)     }      /** Formatted extraction for the ViewModel host-intercept (same caps as [webReadResult]). */@@ -206,10 +226,12 @@ class AssistantWebTools(     /** Endpoints, limits, and shared search state for [AssistantWebTools]. */     companion object {         const val SEARCH_URL = "https://api.maproj.org/api/search"-        const val READ_URL = "https://api.maproj.org/assistant/v1/read"         const val EXPIRY_MILLIS: Long = 30 * 60_000L         const val MAX_SEARCH_CHARS = 3000         const val MAX_READ_CHARS = 6000+        /** Hard cap on the fetched page body we will extract from (chars). */+        const val MAX_BODY_CHARS = 2 * 1024 * 1024+        const val FETCH_TIMEOUT_MS = 10_000L          private val json = Json { ignoreUnknownKeys = true; isLenient = true } @@ -242,9 +264,58 @@ class AssistantWebTools(             return response.body         } +        /**+         * Fetches an arbitrary web page. useSystemTrust is required: the+         * page host is not a first-party host, so the narrow FIRST_PARTY+         * bundle (set in MainActivity for /api/search) cannot validate it.+         */+        suspend fun defaultPageTransport(url: String): FetchedPage {+            val response = NetworkClient.execute(+                url,+                headers = mapOf(+                    "User-Agent" to "Mozilla/5.0 (X11; Linux x86_64; rv:133.0) Gecko/20100101 Firefox/133.0",+                    "Accept" to "text/html,application/xhtml+xml,text/plain",+                    "Accept-Language" to "en-US,en;q=0.9",+                ),+                followRedirects = true,+                connectTimeoutMs = FETCH_TIMEOUT_MS,+                readTimeoutMs = FETCH_TIMEOUT_MS,+                useSystemTrust = true,+            )+            return FetchedPage(+                body = response.text,+                contentType = response.header("Content-Type"),+                finalUrl = response.url,+                status = response.status,+            )+        }+         fun domainOf(url: String): String =             runCatching { URI(url).host.orEmpty().removePrefix("www.") }.getOrNull().orEmpty() +        /** Coarse content classification from the response Content-Type (sniffing as fallback). */+        fun contentKind(contentType: String?, body: String): ContentKind {+            val ct = contentType?.substringBefore(';')?.trim()?.lowercase().orEmpty()+            return when (ct) {+                "text/html", "application/xhtml+xml" -> ContentKind.Html+                "text/plain" -> ContentKind.PlainText+                "" -> {+                    val head = body.trimStart().take(512).lowercase()+                    if (head.startsWith("<!doctype html") || head.startsWith("<html")) ContentKind.Html+                    else ContentKind.PlainText+                }+                else -> ContentKind.Unsupported+            }+        }++        /** One page of [text] from char [offset]: (slice, truncated, next_offset). Page = one shown cap. */+        fun paginate(text: String, offset: Int): Triple<String, Boolean, Int?> {+            val start = offset.coerceIn(0, text.length)+            val end = minOf(start + MAX_READ_CHARS, text.length)+            val truncated = end < text.length+            return Triple(text.substring(start, end), truncated, if (truncated) end else null)+        }+         /** Numbered, host-capped rendering of [hits] for the model. */         fun formatSearchResults(hits: List<WebHit>): String {             val out = StringBuilder()@@ -256,7 +327,7 @@ class AssistantWebTools(             return out.toString().trimEnd()         } -        /** Host-capped page rendering; appends a truncation note when the server says so. */+        /** Host-capped page rendering; appends a truncation note when paging remains. */         fun formatReadResult(title: String, url: String, text: String, truncated: Boolean, nextOffset: Int?): String {             val capped = text.take(MAX_READ_CHARS)             val header = listOf(title.takeIf { it.isNotBlank() }, url).mapNotNull { it }.joinToString("\n")@@ -269,4 +340,6 @@ class AssistantWebTools(             return body + note         }     }++    enum class ContentKind { Html, PlainText, Unsupported } }
openassistant/src/screenshotTest/kotlin/com/vayunmathur/openassistant/ui/MetadataPreviews.kt
diff --git a/openassistant/src/screenshotTest/kotlin/com/vayunmathur/openassistant/ui/MetadataPreviews.kt b/openassistant/src/screenshotTest/kotlin/com/vayunmathur/openassistant/ui/MetadataPreviews.ktindex bde982e42e..ce4517170e 100644--- a/openassistant/src/screenshotTest/kotlin/com/vayunmathur/openassistant/ui/MetadataPreviews.kt+++ b/openassistant/src/screenshotTest/kotlin/com/vayunmathur/openassistant/ui/MetadataPreviews.kt@@ -36,7 +36,7 @@ class MetadataPreviews {         Message(conversationId = 1, text = text, role = role, id = id)      @PreviewTest-    @Preview(name = "1-chat", device = PHONE, group = "phone", showSystemUi = true)+    @Preview(name = "1-conversation-page", device = PHONE, group = "phone", showSystemUi = true)     @Composable     fun Preview1Chat() {         DynamicTheme(darkTheme = true) {@@ -104,7 +104,7 @@ class MetadataPreviews {     }      @PreviewTest-    @Preview(name = "3-memories", device = PHONE, group = "phone", showSystemUi = true)+    @Preview(name = "3-settings-page", device = PHONE, group = "phone", showSystemUi = true)     @Composable     fun Preview3Memories() {         DynamicTheme(darkTheme = true) {
openassistant/src/test/java/com/vayunmathur/openassistant/domain/WebPageExtractorTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/WebPageExtractorTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/WebPageExtractorTest.ktnew file mode 100644index 0000000000..38b3098aab--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/WebPageExtractorTest.kt@@ -0,0 +1,82 @@+package com.vayunmathur.openassistant.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** On-device extraction + URL policy against fixtures (no live network). */+class WebPageExtractorTest {++    private val samplePage = """+        <!doctype html>+        <html><head>+        <title>  Sample Page Title </title>+        <meta property="og:title" content="OG Title Should Not Win">+        <style>body { color: red; }</style>+        <script>var secret = "scripttext";</script>+        </head><body>+        <nav><p>Navigation chrome</p></nav>+        <header><p>Header chrome</p></header>+        <main>+        <h1>Heading One</h1>+        <p>First paragraph of readable text.</p>+        <p>Second   paragraph+        with whitespace.</p>+        <ul><li>List item one</li><li>List item two</li></ul>+        <script>evil()</script>+        </main>+        <footer><p>Footer chrome</p></footer>+        </body></html>+    """.trimIndent()++    @Test fun extractsTitleAndMainText() {+        val page = WebPageExtractor.extract(samplePage)+        assertEquals("Sample Page Title", page.title)+        assertTrue(page.text.contains("Heading One"), page.text)+        assertTrue(page.text.contains("First paragraph of readable text."))+        assertTrue(page.text.contains("Second paragraph with whitespace."))+        assertTrue(page.text.contains("List item one"))+        assertFalse(page.text.contains("Navigation chrome"), page.text)+        assertFalse(page.text.contains("Header chrome"), page.text)+        assertFalse(page.text.contains("Footer chrome"), page.text)+        assertFalse(page.text.contains("scripttext"), page.text)+        assertFalse(page.text.contains("evil"), page.text)+    }++    @Test fun titleFallsBackToOgThenH1() {+        val og = """<html><head><meta property="og:title" content="OG Wins"></head>+            <body><main><p>body text here</p></main></body></html>"""+        assertEquals("OG Wins", WebPageExtractor.extract(og).title)+        val h1 = "<html><head></head><body><h1>H1 Wins</h1><p>x</p></body></html>"+        assertEquals("H1 Wins", WebPageExtractor.extract(h1).title)+    }++    @Test fun decodesEntitiesAndStripsInlineTags() {+        val html = "<html><head><title>T &amp; C</title></head><body><main>" ++            "<p>Tom &amp; Jerry &lt;3 &#8212; <b>bold</b> text</p></main></body></html>"+        val page = WebPageExtractor.extract(html)+        assertEquals("T & C", page.title)+        assertTrue(page.text.contains("Tom & Jerry <3 — bold text"), page.text)+    }++    @Test fun plainTextUsesFirstLineAsTitle() {+        val page = WebPageExtractor.extractPlainText("Hello title\n\nbody line")+        assertEquals("Hello title", page.title)+        assertTrue(page.text.contains("body line"))+    }++    @Test fun urlPolicyAllowsPublicAndBlocksLocal() {+        assertTrue(WebReadUrlPolicy.validate("https://example.com/page") is UrlCheck.Ok)+        assertTrue(WebReadUrlPolicy.validate("http://example.com/") is UrlCheck.Ok)+        assertTrue(WebReadUrlPolicy.validate("https://8.8.8.8/") is UrlCheck.Ok)+        for (bad in listOf(+            "ftp://example.com/", "file:///etc/passwd", "https://127.0.0.1/admin",+            "https://10.1.2.3/", "https://192.168.1.1/", "https://172.16.0.5/",+            "https://169.254.169.254/latest", "https://[::1]/", "https://localhost:8080/",+            "https://printer.local/", "not a url", "",+        )) {+            assertTrue(WebReadUrlPolicy.validate(bad) is UrlCheck.Refused, bad)+        }+    }+}
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktindex e935c60261..4e33234eb8 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -194,12 +194,16 @@ class AssistantToolsInvokeTest {     @Test fun webToolsRunThroughHandlersWithFakeTransport() {         val ctx = ApplicationProvider.getApplicationContext<android.content.Context>()         val fake = com.vayunmathur.openassistant.network.AssistantWebTools(-            transport = { url ->-                if (url.contains("/api/search")) {-                    """{"type":"text","query":"sushi","text":[{"title":"Sushi Guide","url":"https://example.com/sushi","snippet":"All about sushi"}]}"""-                } else {-                    """{"title":"Sushi Guide","url":"https://example.com/sushi","text":"Raw fish, explained.","truncated":false}"""-                }+            transport = {+                """{"type":"text","query":"sushi","text":[{"title":"Sushi Guide","url":"https://example.com/sushi","snippet":"All about sushi"}]}"""+            },+            pageTransport = { url ->+                com.vayunmathur.openassistant.network.FetchedPage(+                    body = "<html><head><title>Sushi Guide</title></head><body><main>" ++                        "<p>Raw fish, explained.</p></main></body></html>",+                    contentType = "text/html",+                    finalUrl = url,+                )             },             nowMillis = { 1_000L },         )
openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.ktindex fce64a2e1a..9648df4a9c 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/AssistantWebToolsTest.kt@@ -89,35 +89,87 @@ class AssistantWebToolsTest {         assertEquals("Error: search unavailable: down", tools.webSearch("q"))     } +    private fun htmlPage(title: String, bodyText: String): String =+        "<html><head><title>$title</title></head><body><main><p>$bodyText</p></main></body></html>"+     @Test fun webReadSuccessAndCaps() = runBlocking {         val longText = "a".repeat(9_000)-        val body = """{"title":"Page Title","url":"https://example.com/a","text":"$longText","truncated":true,"next_offset":6000}"""-        val tools = AssistantWebTools(transport = { body }, nowMillis = { 1_000L })+        val tools = AssistantWebTools(+            transport = { searchJson(1) },+            pageTransport = { url ->+                com.vayunmathur.openassistant.network.FetchedPage(+                    body = htmlPage("Page Title", longText),+                    contentType = "text/html; charset=utf-8",+                    finalUrl = url,+                )+            },+            nowMillis = { 1_000L },+        )         val out = tools.webRead("https://example.com/a")         assertTrue(out.startsWith("Page Title\nhttps://example.com/a"), out.take(80))         assertTrue(out.contains("[truncated - continue with offset 6000]"), out.takeLast(80))         // Header + capped text + note stays near the cap.         assertTrue(out.length <= AssistantWebTools.MAX_READ_CHARS + 120, "len=${out.length}")+        // Paging continues from the reported offset.+        val page2 = tools.webRead("https://example.com/a", offset = 6000)+        assertTrue(page2.contains("a".repeat(100)) && !page2.contains("[truncated"), page2.takeLast(80))     }      @Test fun webReadFailureIsClean() = runBlocking {         val tools = AssistantWebTools(-            transport = { throw java.io.IOException("no route") },+            transport = { searchJson(1) },+            pageTransport = { throw java.io.IOException("no route") },             nowMillis = { 1_000L },         )-        assertEquals("Error: could not read page: no route", tools.webRead("https://x.example/"))-        assertTrue(tools.webRead("").startsWith("Error: could not read page:"))+        assertEquals(+            "Error: could not read page: fetch_failed: no route",+            tools.webRead("https://x.example/"),+        )+        assertTrue(tools.webRead("").startsWith("Error: could not read page: invalid_url"))+        assertTrue(tools.webRead("ftp://example.com/x").startsWith("Error: could not read page: unsupported_scheme"))+        assertTrue(tools.webRead("https://127.0.0.1/admin").startsWith("Error: could not read page: blocked_url"))+        assertTrue(tools.webRead("https://localhost:8080/").startsWith("Error: could not read page: blocked_url"))+    }++    @Test fun webReadRejectsUnsupportedAndErrorStatus() = runBlocking {+        val pdf = AssistantWebTools(+            transport = { searchJson(1) },+            pageTransport = {+                com.vayunmathur.openassistant.network.FetchedPage(+                    body = "%PDF-1.4 fake", contentType = "application/pdf", finalUrl = it,+                )+            },+            nowMillis = { 1_000L },+        )+        assertTrue(+            pdf.webRead("https://example.com/doc.pdf")+                .startsWith("Error: could not read page: unsupported_content_type"),+        )+        val failing = AssistantWebTools(+            transport = { searchJson(1) },+            pageTransport = {+                com.vayunmathur.openassistant.network.FetchedPage(+                    body = "nope", contentType = "text/html", finalUrl = it, status = 503,+                )+            },+            nowMillis = { 1_000L },+        )+        assertEquals(+            "Error: could not read page: fetch_failed: HTTP 503",+            failing.webRead("https://example.com/down"),+        )     }      @Test fun webReadResultResolvesAndValidates() = runBlocking {         var now = 1_000L         val tools = AssistantWebTools(-            transport = { url ->-                if (url.contains("/api/search")) {-                    searchJson(2)-                } else {-                    """{"title":"T","url":"https://example2.com/page2","text":"hello page","truncated":false}"""-                }+            transport = { searchJson(2) },+            pageTransport = { url ->+                com.vayunmathur.openassistant.network.FetchedPage(+                    body = htmlPage("T", "hello page"),+                    contentType = "text/html",+                    finalUrl = url,+                )             },             nowMillis = { now },         )