Spaces:
Paused

File size: 5,765 Bytes
bc9f3e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
// 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/<name> endpoint. The report's
// markdown references them by BARE filename (`![Sales](Sales_by_Product.png)`
// 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 <img src="/api/data/chart/…"> tags bypass the markdown
 * renderer and arrive without the token β€” and an <img> 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 `![alt](file.png)` 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(
    `<div id="__wrap">${html}</div>`,
    "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;
}