diff --git a/Cargo.lock b/Cargo.lock index 21e3d2b..3bb1a4f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -696,6 +696,15 @@ dependencies = [ "slab", ] +[[package]] +name = "getopts" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df" +dependencies = [ + "unicode-width", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1433,6 +1442,34 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "pulldown-cmark" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" +dependencies = [ + "bitflags", + "getopts", + "memchr", + "pulldown-cmark-escape", + "unicase", +] + +[[package]] +name = "pulldown-cmark-escape" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae" + +[[package]] +name = "pulldown-latex" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cf850381ae0dbb131f36e31d6090f55363d079ab3e518ad0323b9cb6a96d115" +dependencies = [ + "bumpalo", +] + [[package]] name = "pxfm" version = "0.1.30" @@ -1928,6 +1965,8 @@ dependencies = [ "http-body-util", "image", "minijinja", + "pulldown-cmark", + "pulldown-latex", "rusqlite", "rust-embed", "serde", diff --git a/Cargo.toml b/Cargo.toml index ed770c5..f86902f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,8 @@ tracing-subscriber = { version = "0.3.23", features = ["env-filter"] } rusqlite = { version = "0.32", features = ["bundled"] } # Embeds the web/ GUI assets into the binary (single-binary, offline-capable). rust-embed = "8" +pulldown-cmark = "0.13.6" +pulldown-latex = "0.8.0" [dev-dependencies] http-body-util = "0.1.5" diff --git a/src/api/sessions.rs b/src/api/sessions.rs index ab22ec3..df6b01d 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -26,6 +26,7 @@ use crate::agent::shell::{HostShell, ShellRunner}; use crate::agent::{self, AgentEvent}; use crate::i18n::t; use crate::name; +use crate::render; use crate::store::{NewMessage, Session, SessionSettings, Stats, Store, StoredMessage}; use tokio_stream::wrappers::UnboundedReceiverStream; @@ -183,11 +184,33 @@ pub(crate) async fn put_defaults( Ok(StatusCode::OK) } +/// A stored message plus, for assistant turns, server-rendered safe HTML +/// (`content_html`) so the GUI can show Markdown/LaTeX without a JS toolchain. +#[derive(Serialize)] +pub(crate) struct MessageView { + #[serde(flatten)] + msg: StoredMessage, + #[serde(skip_serializing_if = "Option::is_none")] + content_html: Option, +} + pub(crate) async fn get_messages( State(st): State, Path(id): Path, -) -> Result>, Error> { - Ok(Json(with_store(&st, move |s| s.messages(&id)).await?)) +) -> Result>, Error> { + let msgs = with_store(&st, move |s| s.messages(&id)).await?; + let views = msgs + .into_iter() + .map(|m| { + let content_html = (m.role == "assistant" && !m.content.is_empty()) + .then(|| render::markdown_to_safe_html(&m.content)); + MessageView { + msg: m, + content_html, + } + }) + .collect(); + Ok(Json(views)) } /// The stats dashboard payload: persistent history aggregates (from the store) @@ -653,11 +676,33 @@ pub(crate) async fn session_chat( } }); let events = UnboundedReceiverStream::new(rx) - .map(|ev| match Event::default().json_data(&ev) { - Ok(e) => Ok::<_, std::convert::Infallible>(e), - Err(e) => { - tracing::error!(error = %e, "failed to serialize agent event"); - Ok(Event::default().data("{}")) + .map(|ev| { + let mut val = match serde_json::to_value(&ev) { + Ok(v) => v, + Err(e) => { + tracing::error!(error = %e, "failed to serialize agent event"); + return Ok(Event::default().data("{}")); + } + }; + // The final answer carries server-rendered safe HTML so the GUI + // can swap the streamed plain text for Markdown/LaTeX at the end. + if let AgentEvent::Final { response } = &ev { + let html = response + .choices + .first() + .and_then(|c| c.message.text()) + .filter(|t| !t.is_empty()) + .map(render::markdown_to_safe_html); + if let (Some(html), Some(obj)) = (html, val.as_object_mut()) { + obj.insert("content_html".to_string(), serde_json::Value::String(html)); + } + } + match Event::default().json_data(&val) { + Ok(e) => Ok::<_, std::convert::Infallible>(e), + Err(e) => { + tracing::error!(error = %e, "failed to serialize agent event"); + Ok(Event::default().data("{}")) + } } }) .chain(futures::stream::once(async { diff --git a/src/lib.rs b/src/lib.rs index 83a3c76..aacc05d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -5,6 +5,7 @@ //! completion service, axum routes). //! - [`store`]: persistent session/context store for the web GUI (SQLite behind //! a swappable `Store` trait). +//! - [`render`]: safe Markdown + LaTeX → HTML for assistant messages. pub mod agent; pub mod api; @@ -13,4 +14,5 @@ pub mod engine; pub mod i18n; pub mod inkling; pub mod name; +pub mod render; pub mod store; diff --git a/src/render.rs b/src/render.rs new file mode 100644 index 0000000..e77816c --- /dev/null +++ b/src/render.rs @@ -0,0 +1,211 @@ +//! Safe Markdown + LaTeX rendering for assistant messages. +//! +//! The model writes Markdown with `$…$` / `$$…$$` math. We turn it into HTML on +//! the server so the GUI can inject it directly, keeping the browser free of any +//! Markdown/MathJax toolchain (single-binary philosophy). Two safety guarantees: +//! +//! - **No raw HTML**: pulldown-cmark always parses raw HTML (it is core +//! CommonMark, with no opt-out flag), so we rewrite every `Html`/`InlineHtml` +//! event into escaped text — the model's HTML is shown literally, never run. +//! - **No dangerous URLs**: link/image destinations pass a scheme allowlist, so +//! `javascript:`, `data:`, `vbscript:` (and friends) are stripped. +//! +//! Math becomes native **MathML Core** via `pulldown-latex` — no JavaScript and +//! no web fonts needed for correctness (optional CSS only refines the look). + +use pulldown_cmark::{html, Event, Options, Parser, Tag}; +use pulldown_latex::{config::DisplayMode, push_mathml, RenderConfig, Storage}; + +/// Convert model Markdown (with LaTeX math) into sanitized HTML ready for +/// `innerHTML`. Only assistant output is rendered this way; user text stays +/// plain (`textContent`) on the frontend. +pub fn markdown_to_safe_html(text: &str) -> String { + let mut opts = Options::empty(); + opts.insert(Options::ENABLE_TABLES); + opts.insert(Options::ENABLE_STRIKETHROUGH); + opts.insert(Options::ENABLE_MATH); + + let events = Parser::new_ext(text, opts).map(|ev| match ev { + Event::InlineMath(src) => Event::Html(render_math(&src, false).into()), + Event::DisplayMath(src) => Event::Html(render_math(&src, true).into()), + Event::Start(Tag::Link { + link_type, + dest_url, + title, + id, + }) => Event::Start(Tag::Link { + link_type, + dest_url: safe_url(&dest_url).into(), + title, + id, + }), + Event::Start(Tag::Image { + link_type, + dest_url, + title, + id, + }) => Event::Start(Tag::Image { + link_type, + dest_url: safe_url(&dest_url).into(), + title, + id, + }), + // Raw HTML is core CommonMark (no opt-out flag): escape it to text so + // nothing the model writes can inject live markup. + Event::Html(s) | Event::InlineHtml(s) => Event::Text(s), + other => other, + }); + + let mut out = String::new(); + html::push_html(&mut out, events); + out +} + +/// Render a LaTeX fragment to MathML. `display` selects block (`$$…$$`) vs inline +/// (`$…$`) mode. On the rare writer error we fall back to escaped source in a +/// `` so nothing is lost; invalid LaTeX is flagged inline by the crate. +fn render_math(latex: &str, display: bool) -> String { + let storage = Storage::new(); + let parser = pulldown_latex::Parser::new(latex, &storage); + let config = RenderConfig { + display_mode: if display { + DisplayMode::Block + } else { + DisplayMode::Inline + }, + ..RenderConfig::default() + }; + let mut out = String::new(); + match push_mathml(&mut out, parser, config) { + Ok(()) => out, + Err(_) => format!("{}", escape_html(latex)), + } +} + +/// Filter a link/image destination to a safe scheme. Scheme-less URLs (relative +/// paths, `#anchors`, queries) are allowed; a present scheme must be http/https/ +/// mailto. ASCII control chars are stripped first because browsers ignore them +/// inside URLs, so `java\tscript:` can't smuggle a blocked scheme past the check. +fn safe_url(url: &str) -> String { + let cleaned: String = url.chars().filter(|c| !c.is_control()).collect(); + let trimmed = cleaned.trim(); + if let Some(colon) = trimmed.find(':') { + let scheme = &trimmed[..colon]; + let looks_like_scheme = scheme + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic()) + && scheme + .chars() + .all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')); + if looks_like_scheme { + return match scheme.to_ascii_lowercase().as_str() { + "http" | "https" | "mailto" => trimmed.to_string(), + _ => String::new(), + }; + } + } + trimmed.to_string() +} + +/// Minimal HTML escaping for the math fallback path. +fn escape_html(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '&' => out.push_str("&"), + '<' => out.push_str("<"), + '>' => out.push_str(">"), + '"' => out.push_str("""), + '\'' => out.push_str("'"), + _ => out.push(c), + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn markdown_basics() { + let html = markdown_to_safe_html("# Title\n\n**bold** and *italic*"); + assert!(html.contains("

"), "{html}"); + assert!(html.contains("bold"), "{html}"); + assert!(html.contains("italic"), "{html}"); + } + + #[test] + fn inline_math_becomes_mathml() { + let html = markdown_to_safe_html("Energy is $E=mc^2$ here."); + assert!(html.contains(""), "{html}"); + assert!( + !html.contains('$'), + "math delimiters should be gone: {html}" + ); + } + + #[test] + fn display_math_is_block() { + let html = markdown_to_safe_html("$$\\int_0^1 x\\,dx$$"); + assert!(html.contains("display=\"block\""), "{html}"); + } + + #[test] + fn raw_html_is_escaped() { + let html = markdown_to_safe_html(""); + assert!(!html.contains("