// Post-process server-produced bubble HTML: the raw markdown inside the
// answer/thinking/sources containers is rendered to HTML client-side
// (Gradio's Chatbot did this natively; this is the custom UI's equivalent).
import { marked } from "marked";
import { dataChartUrl, getSessionToken } from "./api.js";
marked.setOptions({ gfm: true, breaks: true });
// Charts saved by the Data Analysis agent live under DATA_OUTPUT_DIR and are
// served by the backend's /api/data/chart/ endpoint. The report's
// markdown references them by BARE filename (``
// or a Khmer stem like `លកបរភទផលតផល.png`), which as a relative URL would
// resolve against the SPA root and 404. Rewrite bare-filename image sources
// to the chart endpoint (dataChartUrl percent-encodes, so Khmer/space names
// survive); absolute / protocol-relative / root-relative / ./ ../ / data:
// / anchor sources are left untouched.
const _chartRenderer = new marked.Renderer();
const _baseImage = _chartRenderer.image.bind(_chartRenderer);
_chartRenderer.image = (token) => {
const href = String((token && token.href) || "");
if (href && !/^(?:[a-z][a-z0-9+.-]*:|\/\/|\/|#|\.)/i.test(href)) {
token = { ...token, href: dataChartUrl(href) };
}
return _baseImage(token);
};
function parseMarkdown(text) {
try {
return marked.parse(normalizeMarkdown(text), { renderer: _chartRenderer });
} catch {
return text;
}
}
const MARKDOWN_CONTAINERS = [
".answer-body",
".think-body",
".agent-thought-box",
".agent-plan-box",
".sources-block",
];
const cache = new Map();
/** Model-output leniency before markdown parsing: a heading run with NO
* space (`###Text`) is clearly meant as a heading, but CommonMark only
* recognizes ATX headings with a space after the `#`s. Normalize line-start
* `#` runs so headings render instead of leaking literal `#`s — but only
* OUTSIDE fenced code blocks (fence-tracking), and never lines that look
* like code (`#!` shebangs, `#1` numbering) or longer `#` runs. */
function normalizeMarkdown(text) {
const lines = String(text || "").split("\n");
let inFence = false;
for (let i = 0; i < lines.length; i++) {
if (/^\s*(`{3,}|~{3,})/.test(lines[i])) {
inFence = !inFence;
} else if (!inFence) {
lines[i] = lines[i].replace(/^(#{1,6})(?=[^\s#!\d])/, "$1 ");
}
}
return lines.join("\n");
}
/** The backend guards every /api/* route with the session token
* (X-Session-Token header on fetch calls; `?token=` query param on
* WebSockets). The Data Analysis chart gallery is SERVER-rendered raw
* HTML, so its
tags bypass the markdown
* renderer and arrive without the token — and an
tag cannot send a
* header, so without this every chart 401s and renders as a broken
* image. Append the token as a query param (the middleware already
* accepts it there); markdown `` refs are already
* tokenized by dataChartUrl above. Idempotent: already-tokenized srcs are
* skipped. No-op when the SPA has no session token. */
function _authorizeChartImages(wrap) {
const token = getSessionToken();
if (!token) return;
wrap.querySelectorAll('img[src^="/api/data/chart/"]').forEach((img) => {
const src = img.getAttribute("src");
if (src && !src.includes("token=")) {
img.setAttribute(
"src",
`${src}${src.includes("?") ? "&" : "?"}token=${encodeURIComponent(token)}`
);
}
});
}
/** Render raw Markdown (not HTML) — used by the About tab and other
* server-provided markdown blocks that arrive as plain text. Bare-filename
* image sources are rewritten to the chart endpoint (see _chartRenderer). */
export function renderMarkdown(text) {
if (!text) return "";
return parseMarkdown(text);
}
export function enhanceRichHtml(html) {
if (!html) return "";
const hit = cache.get(html);
if (hit !== undefined) return hit;
const doc = new DOMParser().parseFromString(
`${html}
`,
"text/html"
);
const wrap = doc.getElementById("__wrap");
if (wrap) {
wrap.querySelectorAll(MARKDOWN_CONTAINERS.join(",")).forEach((el) => {
el.innerHTML = parseMarkdown(el.innerHTML);
});
_authorizeChartImages(wrap);
// format_llm_response() only wraps the answer in .think-block /
// .final-answer-block when the model emitted a thinking tag; WITHOUT
// one it returns the raw markdown untouched (Gradio's Chatbot renders
// that natively, so the custom UI must too). Detect the unwrapped case
// and convert only the TOP-LEVEL text nodes — **bold**, * lists and
// ### headings render instead of leaking literal characters, while the
// structural divs (sources-block already converted above, response-
// footer) stay untouched (never re-parsed through marked).
if (!wrap.querySelector(".think-block, .final-answer-block")) {
let out = "";
let raw = "";
const flush = () => {
if (raw) out += parseMarkdown(raw);
raw = "";
};
for (const node of Array.from(wrap.childNodes)) {
if (node.nodeType === Node.TEXT_NODE) {
raw += node.textContent;
} else {
flush();
out += node.outerHTML;
}
}
flush();
wrap.innerHTML = out;
// The no-wrapper branch above re-parses top-level text through
// marked — re-run the token pass so chart imgs that landed inside
// converted text are authorized too (idempotent: already-tokenized
// srcs are skipped).
_authorizeChartImages(wrap);
}
}
const out = wrap ? wrap.innerHTML : html;
cache.set(html, out);
if (cache.size > 400) cache.clear();
return out;
}