Render assistant Markdown and LaTeX as sanitized HTML with native MathML

Server-side rendering keeps the browser free of any Markdown/MathJax toolchain (single-binary). New src/render.rs: pulldown-cmark (tables/strikethrough/math) + pulldown-latex -> MathML Core. Safety: raw HTML events are escaped to text (pulldown-cmark 0.13 has no ENABLE_HTML opt-out) and link/image URLs pass a scheme allowlist (javascript:/data:/vbscript: stripped, control chars removed). content_html is added to get_messages (assistant only) and to the agent Final SSE event; the GUI injects it via innerHTML for assistant bubbles (history + live) while user text stays textContent. CSS styles Markdown and native MathML; block math must not override display (UA block math layout) or it collapses to vertical stacks. 10 render unit tests incl. XSS; 136 tests green, clippy/fmt clean; verified live + visually.
This commit is contained in:
adm committed 2026-11-25 20:58:20 +01:00
1 parent d1b56d2c23
commit 7dd66ea138
7 files changed
+386 -13

No files matched your search

+52 -7
View File
@@ -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<String>,
}
pub(crate) async fn get_messages(
State(st): State<AppState>,
Path(id): Path<String>,
) -> Result<Json<Vec<StoredMessage>>, Error> {
Ok(Json(with_store(&st, move |s| s.messages(&id)).await?))
) -> Result<Json<Vec<MessageView>>, 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 {