Files
LLeMbas/src/lembas/services/markdown.py
T
Jaroslav Beneš 439f1a5d84 The menu that never appeared, and the reason it never did
composer.js built its menu lazily inside show(), and refresh() wrote
list.innerHTML before calling it. `list` is null until build() has run, so the
first `/` or `@` ever typed threw a TypeError and took the handler with it. The
menu has never appeared in any browser. That is why /compact "isn't there":
nothing was. I shipped it having only run `node --check`, which parses the file
happily.

So this also brings the thing that catches it: a DOM stub driven under node --
not committed, hard rule 1 stands, it is an instrument like curl. It reproduced
the crash in one run and immediately found two more: choosing a command from the
menu left `/help` sitting in the box so the next Enter ran it again, and Tab
completed nothing. Tab now completes and Enter runs, which is the split that
matters for a command taking an argument.

`.select--sm` was used three times and defined nowhere. I deleted the copy in
chat.css and left a comment saying it "is defined once, in app.css", where it
did not exist -- so those selects fell back to plain `.select`: width 100% in a
flex row where four siblings wanted the same, all of them shrinking together
until each was a few characters wide, and half a rem taller than everything
beside them. That was the whole of "the connection switch needs to be wider".

The connection and directory move to the topbar. They cannot change -- update_chat
refuses both with a 409 -- so they are facts about the chat, of a kind with the
Temporary badge, not controls on the message. The mode stays by the box.

Compaction says it is working. It makes a model call that takes seconds and had
no indicator anywhere: `hx-indicator` appears nowhere in this codebase, and the
Generation.status channel that says "Summarising earlier messages…" for the
automatic path cannot be borrowed, because it lives in the streaming bubble and
this endpoint refuses to run while any message is unfinished. The overflow menu
now runs the same code as /compact rather than posting for itself, so there is
one implementation, one spinner, and one place the endpoint's four carefully
written 409s finally reach somebody.

/effort, low medium high, per chat with a per-model default. It goes out twice
because there is no field that works everywhere: OpenAI and vLLM read
reasoning_effort, llama.cpp's own docs say other values "have no effect" and its
maintainer says the field "simply gets dropped without error or logging" -- what
reaches gpt-oss behind it is chat_template_kwargs. Both are sent, and only once
an effort has been chosen, so a provider strict about unknown parameters sees
exactly the request it always did until somebody opts in. The control appears
only on a model marked `reasoning`, a flag that has existed since the beginning
with no reader at all.

Mentions and recognised commands are marked as you type -- a mirror behind the
textarea holding the same text with every character transparent, contributing
nothing but a rounded rectangle, so a pixel of drift is a misplaced rectangle
rather than a doubled glyph. A command is marked only when it resolves, so
`/thoughts on this` visibly is not one before you send it. And again in the
transcript, where user turns had no render step at all and now escape before
they inject.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-02 18:17:04 +02:00

204 lines
7.7 KiB
Python

"""Render assistant messages from Markdown to sanitised HTML.
Rendering happens on the server, in Python, so there is no JavaScript Markdown
library to vendor and the streamed and final views cannot disagree about how
something should look.
The output is sanitised with nh3 (Rust ammonia). Model output is untrusted
input: it routinely contains HTML, and a model can be talked into emitting a
script tag, so this is a real boundary and not a formality.
"""
from __future__ import annotations
import functools
import html
import re
import nh3
from markdown_it import MarkdownIt
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name, guess_lexer
from pygments.util import ClassNotFound
# Class-based highlighting; the colours come from theme tokens in chat.css, so
# code blocks follow the active theme instead of carrying their own palette.
_FORMATTER = HtmlFormatter(nowrap=True, classprefix="pg-")
ALLOWED_TAGS = {
"p", "br", "hr", "div", "span",
"strong", "em", "del", "sub", "sup", "mark",
"h1", "h2", "h3", "h4", "h5", "h6",
"ul", "ol", "li",
"blockquote", "pre", "code",
"table", "thead", "tbody", "tr", "th", "td",
"a", "img",
}
ALLOWED_ATTRIBUTES = {
# "rel" is intentionally absent: nh3 rejects it here when link_rel is set,
# because link_rel below is what writes it.
"a": {"href", "title", "target"},
"img": {"src", "alt", "title"},
"code": {"class"},
"pre": {"class"},
"span": {"class"},
"div": {"class"},
"td": {"align"},
"th": {"align"},
}
# javascript: and data: URLs are the obvious injection route through a link.
ALLOWED_URL_SCHEMES = {"http", "https", "mailto"}
def _render_fence(tokens, idx, _options, _env) -> str:
"""Render a fenced code block.
This replaces the renderer's `fence` rule outright rather than using
markdown-it's `highlight` option, because that option re-wraps whatever it
is given in <pre><code> unless the string already starts with "<pre" --
which would nest a second <pre> inside the wrapper this returns.
"""
token = tokens[idx]
code = token.content
language = (token.info or "").strip().split()[0] if token.info else ""
lexer = None
if language:
try:
lexer = get_lexer_by_name(language, stripall=False)
except (ClassNotFound, ValueError):
lexer = None
elif code.strip():
# Guessing is only worth it for a decent sample; on two lines of text
# Pygments guesses confidently and wrongly.
try:
lexer = guess_lexer(code) if len(code) > 80 else None
except (ClassNotFound, ValueError):
lexer = None
if lexer is None:
body = nh3.clean_text(code)
label = language
else:
body = highlight(code, lexer, _FORMATTER)
label = language or (lexer.aliases[0] if lexer.aliases else "")
label_html = (
f'<div class="code-block__label">{nh3.clean_text(label)}</div>' if label else ""
)
return (
f'<div class="code-block">{label_html}'
f'<pre class="code-block__pre"><code>{body}</code></pre></div>'
)
@functools.lru_cache(maxsize=1)
def _parser() -> MarkdownIt:
md = MarkdownIt("commonmark", {"linkify": True, "typographer": False})
md.enable(["table", "strikethrough", "linkify"])
md.renderer.rules["fence"] = _render_fence
return md
def render_markdown(text: str) -> str:
"""Markdown to safe HTML, ready to drop into a message bubble."""
if not text:
return ""
html = _parser().render(text)
return nh3.clean(
html,
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRIBUTES,
url_schemes=ALLOWED_URL_SCHEMES,
# Anything opened from a model's output is untrusted; noopener stops it
# reaching back through window.opener.
link_rel="nofollow noopener noreferrer",
)
# A mention is `@` followed by a run of non-space, claimed only at the start of
# the text or after whitespace. That last part is the whole rule: without it
# every email address in a message becomes a highlighted file reference, which
# is both wrong and ugly. It matches what composer.js recognises while typing,
# and the two must stay in step or the box and the transcript disagree.
_MENTION = re.compile(r"(?:(?<=\s)|^)@([^\s@]+)")
def highlight_tokens(text: str) -> str:
"""A user's own message, escaped, with `@mentions` marked.
User turns have no render step at all -- the template prints the column and
relies on `white-space: pre-wrap` -- so this is it, and it must escape
before it injects or it is an XSS hole in the one place a person controls
the bytes exactly.
Only mentions. A `/command` never survives to a message: commands are
intercepted in the composer and never posted, so anything beginning with a
slash in a transcript is text somebody meant as text, and marking it as a
command would be marking it as something it is not.
"""
if not text:
return ""
escaped = html.escape(text, quote=False)
# Applied to the *escaped* string, so the span is the only markup that can
# exist. `@` and the path characters are untouched by html.escape, and a
# `&amp;` it produced contains no whitespace -- which is why the pattern is
# anchored on whitespace rather than on a character class.
return _MENTION.sub(r'<span class="tok-mention">@\1</span>', escaped)
def escape_text(text: str) -> str:
"""Escape a plain-text run for insertion as HTML element content.
Used for user messages and for partial assistant text mid-stream, where the
content is not yet complete enough to parse as Markdown.
html.escape rather than nh3.clean_text: escaping the three structural
characters is all that is needed for a text node, and it escapes character
by character, so escaping a stream chunk-by-chunk gives the same result as
escaping the whole string at once. nh3.clean_text also escapes spaces and
slashes, which triples the size of a streamed token for no benefit.
"""
return html.escape(text, quote=False)
# Code blocks are dropped whole rather than read out. A speech model given a
# code fence pronounces every bracket and underscore, which is unlistenable and
# takes longer than the prose it was buried in.
#
# Matched on <pre> rather than on the .code-block wrapper: the wrapper also
# contains a label div, so a non-greedy match for its closing tag stops at the
# label's and leaves the code behind. <pre> cannot nest, so this is exact.
_CODE_BLOCK = re.compile(r"<pre\b[^>]*>.*?</pre>", re.DOTALL)
_CODE_LABEL = re.compile(r"<div class=\"code-block__label\">.*?</div>", re.DOTALL)
_TAG = re.compile(r"<[^>]+>")
_WHITESPACE = re.compile(r"[ \t]*\n\s*\n\s*")
# Speech endpoints reject or truncate very long inputs, and a reply long enough
# to hit this is not one anybody is listening to in full.
MAX_SPEAKABLE = 8000
def speakable_text(text: str) -> str:
"""Markdown reduced to something worth reading aloud.
Goes through the renderer rather than stripping the Markdown source
directly, so tables, lists and links come out as their text instead of as
punctuation, and there is one definition of what a message *says*.
"""
if not text:
return ""
rendered = _CODE_LABEL.sub(" ", _CODE_BLOCK.sub("\n", render_markdown(text)))
stripped = html.unescape(_TAG.sub(" ", rendered))
# Paragraph breaks survive as a single newline: speech models use them as a
# pause, and a wall of one line is read without any.
stripped = _WHITESPACE.sub("\n", stripped)
lines = [" ".join(line.split()) for line in stripped.splitlines()]
return "\n".join(line for line in lines if line)[:MAX_SPEAKABLE]