From 32eeb8792236f8fc0a5e4aeb2919fb7b6cf19ab6 Mon Sep 17 00:00:00 2001 From: sharmis-tp Date: Fri, 27 Nov 2026 01:20:59 +0000 Subject: [PATCH 1/4] Fall back to the whole page when the article is a small part of it, and leave script and style out of it --- crates/plugin-web/src/response.rs | 184 ++++++++++++++++++++++++++---- 1 file changed, 164 insertions(+), 20 deletions(-) diff --git a/crates/plugin-web/src/response.rs b/crates/plugin-web/src/response.rs index b5a2c66..140daab 100644 --- a/crates/plugin-web/src/response.rs +++ b/crates/plugin-web/src/response.rs @@ -20,8 +20,22 @@ use url::Url; use crate::error::{FetchError, SafeUrl}; use crate::url_policy::MAX_URL_CHARS; -/// The minimum extracted length below which the whole-page fallback fires. -const MIN_CONTENT_LEN: usize = 100; +/// The length in characters below which an extracted article is replaced by +/// the whole page, however much of the page it is. +const MIN_ARTICLE_CHARS: usize = 250; + +/// The length in characters below which an extracted article is replaced by +/// the whole page when it is also under [`MIN_ARTICLE_SHARE`] of it. +const SHORT_ARTICLE_CHARS: usize = 3_000; + +/// The share of the whole page, as `1 / MIN_ARTICLE_SHARE`, under which a short +/// article is replaced by the whole page: 5 for 20%. +const MIN_ARTICLE_SHARE: usize = 5; + +/// The elements the whole-page rendering leaves out, because their text is +/// code or style rules rather than content of the page. `noscript` stays, +/// because some sites, such as Discourse forums, serve their content in it. +const SKIPPED_TAGS: [&str; 2] = ["script", "style"]; /// How a response body was turned into the returned text. /// @@ -140,12 +154,15 @@ pub(crate) fn decode_body( /// Renders an HTML page to markdown, reporting how it was produced. /// -/// When `raw` is true the whole document is converted with [`htmd::convert`] and -/// the mode is [`Extraction::RawHtml`], skipping article extraction entirely. -/// Otherwise [`readabilityrs`] isolates the main article; if that yields fewer -/// than [`MIN_CONTENT_LEN`] characters, the whole document is converted instead -/// and the mode is [`Extraction::RawHtml`]. Rendering never fails: the worst -/// case is an empty string when even the whole-page conversion produces no text. +/// When `raw` is true the whole document is rendered by [`whole_page`] and the +/// mode is [`Extraction::RawHtml`], skipping article extraction entirely. +/// Otherwise [`readabilityrs`] isolates the main article, and the whole page +/// is returned in its place, with the mode [`Extraction::RawHtml`], when the +/// article is under [`MIN_ARTICLE_CHARS`] characters, or under +/// [`SHORT_ARTICLE_CHARS`] and under a fifth of the whole page: such an +/// article is a fragment of a page that is not an article, such as a profile +/// or a list of links. Rendering never fails: the worst case is an empty +/// string when even the whole-page rendering produces no text. /// /// Each relative link and image source in what is rendered is made absolute /// against `base_url`, the URL the page was served from, as [`absolutize`] @@ -158,18 +175,16 @@ pub(crate) fn extract_html(html: &str, base_url: Option<&Url>, raw: bool) -> (St .as_ref() .zip(base_url) .and_then(|(document, page_url)| LinkBase::of(document, page_url)); - let whole_page = |document: Option| { - document + let render_whole_page = |document: Option| { + let html = document .zip(base.as_ref()) .and_then(|(document, base)| absolutize(document, base, html.len())) - .unwrap_or_else(|| html.to_owned()) + .unwrap_or_else(|| html.to_owned()); + whole_page(&html) }; if raw { - return ( - htmd::convert(&whole_page(document)).unwrap_or_default(), - Extraction::RawHtml, - ); + return (render_whole_page(document), Extraction::RawHtml); } let options = ReadabilityOptions::default(); @@ -193,14 +208,28 @@ pub(crate) fn extract_html(html: &str, base_url: Option<&Url>, raw: bool) -> (St }) .unwrap_or_default(); - if article_markdown.trim().len() >= MIN_CONTENT_LEN { + let article_chars = article_markdown.trim().chars().count(); + if article_chars >= SHORT_ARTICLE_CHARS { + return (article_markdown, Extraction::Readability); + } + let page_markdown = render_whole_page(document); + let page_chars = page_markdown.trim().chars().count(); + if article_chars >= MIN_ARTICLE_CHARS && article_chars * MIN_ARTICLE_SHARE >= page_chars { + return (article_markdown, Extraction::Readability); + } + if page_chars == 0 { return (article_markdown, Extraction::Readability); } + (page_markdown, Extraction::RawHtml) +} - ( - htmd::convert(&whole_page(document)).unwrap_or(article_markdown), - Extraction::RawHtml, - ) +/// Renders a whole HTML document to markdown, leaving out [`SKIPPED_TAGS`]. +fn whole_page(html: &str) -> String { + htmd::HtmlToMarkdown::builder() + .skip_tags(SKIPPED_TAGS.to_vec()) + .build() + .convert(html) + .unwrap_or_default() } /// Parses `html` into the tree `htmd` renders from. @@ -418,6 +447,8 @@ pub(crate) fn truncate_to_chars(text: &str, max_chars: usize) -> (&str, bool) { #[cfg(test)] mod tests { + use std::fmt::Write as _; + use url::Url; use super::{Extraction, LinkBase, absolutize, extract_html, parse}; @@ -710,4 +741,117 @@ mod tests { ); } } + + const PROFILE: &str = r#" + + + Jane Doe + + + + + +
+

Jane Doe

+ +
+
+

Pinned

+
    +
  1. +

    Neon: Serverless Postgres. We separated storage and compute to offer autoscaling, code-like database branching, and scale to zero.

    +
  2. +
+
+ +"#; + + #[test] + fn default_result_keeps_the_profile() { + let (markdown, mode) = extract_html(PROFILE, None, false); + + assert!( + markdown.contains("Jane Doe") && markdown.contains("Turku, Finland"), + "mode {mode:?}, got: {markdown}" + ); + } + + #[test] + fn raw_result_holds_no_script_or_style_text() { + let (markdown, _mode) = extract_html(PROFILE, None, true); + + assert!( + !markdown.contains("color: red") && !markdown.contains("featureFlags"), + "got: {markdown}" + ); + } + + /// A page with an article of `prose_repeats` copies of one sentence, about + /// 90 characters each, and a list of `links` stories outside it. + fn article_beside_a_list(prose_repeats: usize, links: usize) -> String { + let prose = + "This sentence belongs to the article, which a reader came to the page to read. " + .repeat(prose_repeats); + let mut list = String::new(); + for i in 0..links { + write!( + list, + r#"
  • Story number {i}, with a title of some length
  • "# + ) + .expect("writing to a String cannot fail"); + } + format!( + "T
      {list}
    \ +

    Title

    {prose}

    " + ) + } + + #[test] + fn a_short_article_under_a_fifth_of_the_page_gives_way_to_the_whole_page() { + let html = article_beside_a_list(5, 100); + + let (markdown, mode) = extract_html(&html, None, false); + + assert_eq!(mode, Extraction::RawHtml, "got: {markdown}"); + assert!(markdown.contains("Story number 99"), "got: {markdown}"); + assert!( + markdown.contains("belongs to the article"), + "got: {markdown}" + ); + } + + #[test] + fn a_short_article_that_is_most_of_the_page_stays_the_result() { + let html = article_beside_a_list(5, 3); + + let (markdown, mode) = extract_html(&html, None, false); + + assert_eq!(mode, Extraction::Readability, "got: {markdown}"); + assert!(!markdown.contains("Story number"), "got: {markdown}"); + } + + #[test] + fn the_whole_page_skips_script_and_style_and_keeps_noscript() { + let html = r#" + + +

    Status: up.

    "#; + + for raw in [false, true] { + let (markdown, mode) = extract_html(html, None, raw); + + assert_eq!(mode, Extraction::RawHtml, "raw {raw}: {markdown}"); + assert!( + !markdown.contains("color: red") && !markdown.contains("window.boot"), + "raw {raw}: {markdown}" + ); + assert!( + markdown.contains("The topic list") && markdown.contains("Status: up."), + "raw {raw}: {markdown}" + ); + } + } } From 150e1708c501d104b711ecc20c3fca8f7de6ac7d Mon Sep 17 00:00:00 2001 From: sharmis-tp Date: Wed, 2 Dec 2026 01:41:06 +0000 Subject: [PATCH 2/4] Keep the article when the whole page would be cut at max_chars --- crates/plugin-web/src/fetch.rs | 5 +-- crates/plugin-web/src/fetch/tests-body.rs | 43 +++++++++++++++++++++++ crates/plugin-web/src/fetch/tests.rs | 21 +++++++++++ crates/plugin-web/src/lib.rs | 6 ++-- crates/plugin-web/src/response.rs | 36 ++++++++++++++++--- 5 files changed, 102 insertions(+), 9 deletions(-) diff --git a/crates/plugin-web/src/fetch.rs b/crates/plugin-web/src/fetch.rs index 12ce6ed..83185a1 100644 --- a/crates/plugin-web/src/fetch.rs +++ b/crates/plugin-web/src/fetch.rs @@ -185,8 +185,9 @@ impl FetchClient { Err(e) => return soft_or_hard(&e), }; let base_url = final_url.clone(); - let rendering = - on_blocking_thread(move || extract_html(&decoded, Some(&base_url), raw)); + let rendering = on_blocking_thread(move || { + extract_html(&decoded, Some(&base_url), raw, max_chars) + }); let Some((markdown, extraction)) = rendering.await else { return Err(did_not_finish()); }; diff --git a/crates/plugin-web/src/fetch/tests-body.rs b/crates/plugin-web/src/fetch/tests-body.rs index 27da9a5..81ed739 100644 --- a/crates/plugin-web/src/fetch/tests-body.rs +++ b/crates/plugin-web/src/fetch/tests-body.rs @@ -73,6 +73,49 @@ async fn gzip_bomb_refused_on_decompressed_count() { assert!(result.contains("exceeds"), "got: {result}"); } +/// The whole page is over the default `max_chars`, so falling back to it would +/// return only the menu at its top. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_short_article_below_a_long_menu_is_returned_and_raw_returns_the_menu() { + let (port, _hits) = spawn_server().await; + let tool = loopback_tool(port); + let url = format!("http://localhost:{port}/archive"); + + let out = tool + .call(serde_json::json!({ "url": url })) + .await + .expect("an archive fetch must succeed") + .text() + .to_owned(); + let (header, body) = split_header(&out); + assert!( + header.contains("extraction: readability") && header.contains("truncated: false"), + "got: {header}" + ); + assert!( + body.contains("The article a reader came for"), + "got: {body}" + ); + assert!(!body.contains("Archive entry"), "got: {body}"); + + let out = tool + .call(serde_json::json!({ "url": url, "raw": true })) + .await + .expect("a raw archive fetch must succeed") + .text() + .to_owned(); + let (header, body) = split_header(&out); + assert!( + header.contains("extraction: raw-html") && header.contains("truncated: true"), + "got: {header}" + ); + assert!(body.contains("Archive entry number 0"), "got: {body}"); + assert!( + !body.contains("The article a reader came for"), + "got: {body}" + ); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn text_over_max_chars_is_truncated_on_char_boundary() { let (port, _hits) = spawn_server().await; diff --git a/crates/plugin-web/src/fetch/tests.rs b/crates/plugin-web/src/fetch/tests.rs index e243bbe..ee7dd75 100644 --- a/crates/plugin-web/src/fetch/tests.rs +++ b/crates/plugin-web/src/fetch/tests.rs @@ -6,6 +6,7 @@ //! the body tests (size caps, truncation, content types, charsets) sit in //! the child modules and share these fixtures. +use std::fmt::Write as _; use std::io::Write; use std::net::{IpAddr, SocketAddr}; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -158,6 +159,25 @@ async fn large() -> Html { Html(format!("

    {filler}

    ")) } +/// A short article below an archive menu longer than the default +/// `max_chars`. +async fn archive() -> Html { + let mut menu = String::new(); + for i in 0..1_500 { + write!( + menu, + r#"
  • Archive entry number {i}
  • "# + ) + .expect("writing to a String cannot fail"); + } + let prose = + "

    The article a reader came for, which says one thing in plain words.

    ".repeat(5); + Html(format!( + "T\ +

    The article

    {prose}
    " + )) +} + async fn gzip_bomb() -> impl IntoResponse { let raw = "A".repeat(200_000); let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); @@ -310,6 +330,7 @@ async fn spawn_server() -> (u16, Arc) { .route("/target", get(target)) .route("/unicode", get(unicode)) .route("/large", get(large)) + .route("/archive", get(archive)) .route("/gzip", get(gzip_bomb)) .route("/liar", get(liar_content_length)) .route("/table", get(table)) diff --git a/crates/plugin-web/src/lib.rs b/crates/plugin-web/src/lib.rs index af4c0a7..3249f8f 100644 --- a/crates/plugin-web/src/lib.rs +++ b/crates/plugin-web/src/lib.rs @@ -31,8 +31,10 @@ //! extraction. The tool sends one GET request and chooses how to render //! the response from its `Content-Type`. For an HTML page, it extracts //! the main article with `readabilityrs` and renders it to markdown. -//! When a page yields too little article text, or the call asks for -//! `raw`, `htmd` converts the whole page to markdown. Any other text +//! When the call asks for `raw`, `htmd` converts the whole page to +//! markdown. It also does so in place of the article when the article is +//! too small a part of the page and the whole page fits in `max_chars`. +//! Any other text //! body, such as JSON, XML, or plain text, is decoded and returned //! verbatim. The tool refuses every other type, and a response that //! declares none. diff --git a/crates/plugin-web/src/response.rs b/crates/plugin-web/src/response.rs index 140daab..1ad053a 100644 --- a/crates/plugin-web/src/response.rs +++ b/crates/plugin-web/src/response.rs @@ -161,15 +161,22 @@ pub(crate) fn decode_body( /// article is under [`MIN_ARTICLE_CHARS`] characters, or under /// [`SHORT_ARTICLE_CHARS`] and under a fifth of the whole page: such an /// article is a fragment of a page that is not an article, such as a profile -/// or a list of links. Rendering never fails: the worst case is an empty -/// string when even the whole-page rendering produces no text. +/// or a list of links. The whole page takes its place only when it is at most +/// `max_chars` characters, the most a fetch returns: a longer page would be +/// cut, and the cut could drop the article. Rendering never fails: the worst +/// case is an empty string when even the whole-page rendering produces no text. /// /// Each relative link and image source in what is rendered is made absolute /// against `base_url`, the URL the page was served from, as [`absolutize`] /// says, so a model can fetch what the markdown links to. On the readability /// path this happens after `readabilityrs` has picked each image's source, /// which may come from `data-src` or `srcset` rather than `src`. -pub(crate) fn extract_html(html: &str, base_url: Option<&Url>, raw: bool) -> (String, Extraction) { +pub(crate) fn extract_html( + html: &str, + base_url: Option<&Url>, + raw: bool, + max_chars: usize, +) -> (String, Extraction) { let document = base_url.and_then(|_| parse(html)); let base = document .as_ref() @@ -217,7 +224,7 @@ pub(crate) fn extract_html(html: &str, base_url: Option<&Url>, raw: bool) -> (St if article_chars >= MIN_ARTICLE_CHARS && article_chars * MIN_ARTICLE_SHARE >= page_chars { return (article_markdown, Extraction::Readability); } - if page_chars == 0 { + if page_chars == 0 || page_chars > max_chars { return (article_markdown, Extraction::Readability); } (page_markdown, Extraction::RawHtml) @@ -451,9 +458,14 @@ mod tests { use url::Url; - use super::{Extraction, LinkBase, absolutize, extract_html, parse}; + use super::{Extraction, LinkBase, absolutize, parse}; use crate::url_policy::MAX_URL_CHARS; + /// [`super::extract_html`] with no cap on the length of the result. + fn extract_html(html: &str, base_url: Option<&Url>, raw: bool) -> (String, Extraction) { + super::extract_html(html, base_url, raw, usize::MAX) + } + /// Parses `s` into a [`Url`], panicking with context on failure. fn url(s: &str) -> Url { Url::parse(s).expect("test url must parse") @@ -833,6 +845,20 @@ mod tests { assert!(!markdown.contains("Story number"), "got: {markdown}"); } + #[test] + fn a_short_article_stays_the_result_when_the_whole_page_is_over_max_chars() { + let html = article_beside_a_list(5, 100); + let (page, _mode) = extract_html(&html, None, true); + let page_chars = page.trim().chars().count(); + + let (fits, mode) = super::extract_html(&html, None, false, page_chars); + assert_eq!(mode, Extraction::RawHtml, "got: {fits}"); + + let (markdown, mode) = super::extract_html(&html, None, false, page_chars - 1); + assert_eq!(mode, Extraction::Readability, "got: {markdown}"); + assert!(!markdown.contains("Story number"), "got: {markdown}"); + } + #[test] fn the_whole_page_skips_script_and_style_and_keeps_noscript() { let html = r#" From 325db79825f04963c7befd6866c51914b040b90c Mon Sep 17 00:00:00 2001 From: sharmis-tp Date: Wed, 2 Dec 2026 16:52:04 +0000 Subject: [PATCH 3/4] Return the whole page when Readability finds no article, even over max_chars --- crates/plugin-web/src/fetch/tests-body.rs | 23 +++++++++++++++++++++ crates/plugin-web/src/fetch/tests.rs | 18 ++++++++++++++++ crates/plugin-web/src/lib.rs | 7 +++---- crates/plugin-web/src/response.rs | 25 ++++++++++++++++++----- 4 files changed, 64 insertions(+), 9 deletions(-) diff --git a/crates/plugin-web/src/fetch/tests-body.rs b/crates/plugin-web/src/fetch/tests-body.rs index 81ed739..6e3d1e4 100644 --- a/crates/plugin-web/src/fetch/tests-body.rs +++ b/crates/plugin-web/src/fetch/tests-body.rs @@ -116,6 +116,29 @@ async fn a_short_article_below_a_long_menu_is_returned_and_raw_returns_the_menu( ); } +/// `readabilityrs` finds no article, so the whole page is returned and cut +/// at `max_chars`, though it is over it. +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn a_page_with_no_article_over_max_chars_returns_the_cut_whole_page() { + let (port, _hits) = spawn_server().await; + let tool = loopback_tool(port); + let url = format!("http://localhost:{port}/topics"); + + let out = tool + .call(serde_json::json!({ "url": url })) + .await + .expect("a topics fetch must succeed") + .text() + .to_owned(); + let (header, body) = split_header(&out); + + assert!( + header.contains("extraction: raw-html") && header.contains("truncated: true"), + "got: {header}" + ); + assert!(body.contains("Forum topic number 0"), "got: {body}"); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn text_over_max_chars_is_truncated_on_char_boundary() { let (port, _hits) = spawn_server().await; diff --git a/crates/plugin-web/src/fetch/tests.rs b/crates/plugin-web/src/fetch/tests.rs index ee7dd75..ba0924a 100644 --- a/crates/plugin-web/src/fetch/tests.rs +++ b/crates/plugin-web/src/fetch/tests.rs @@ -178,6 +178,23 @@ async fn archive() -> Html { )) } +/// A forum topic list, longer than the default `max_chars`, served only +/// inside `