oficina / base Public

Render simple Markdown in the Assistant's messages

richText and ask.js's rich draw plan decision D16's subset: bullet and
numbered lists, **bold**, *italics* and _italics_ at word boundaries,
with links under the existing safe-link rules. Everything else stays
escaped text. Both read line breaks as a page does (CR and CRLF are LF,
NUL goes) so the script's DOM and the server's HTML are the same, which
TestAskMarkdownMatchesServer checks in the browser.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev b066b9c4c75219cf374a63a42e8d8d2f1920e8f2 parent dd8e5ec
5 files changed, +285 −15
  • internal/browsertest/ask_test.go +58 −0
  • internal/look/static/app.css +4 −0
  • internal/look/static/ask.js +82 −6
  • internal/web/ask_cards.go +111 −9
  • internal/web/rich_internal_test.go +30 −0
diff --git a/internal/browsertest/ask_test.go b/internal/browsertest/ask_test.go
index acaacbf..20859d0 100644
--- a/internal/browsertest/ask_test.go
+++ b/internal/browsertest/ask_test.go
@@ -591,3 +591,61 @@ func TestAskDockSaveFails(t *testing.T) {
t.Errorf("posted and drawn %q, want the failed open, then open again, drawn open", got)
}
}
+
+// The Assistant's little Markdown (plan decision D16) is drawn the same by
+// the panel's script, for a line that arrives while it is open, as by the
+// server, for /ask: each message's HTML is the same, unsafe links and raw
+// HTML included. The last few lines are where a script and a server most
+// easily part: carriage returns and NULs (which an HTML page cannot
+// hold), letters beyond ASCII next to an _, and
+// lists of each kind back to back.
+func TestAskMarkdownMatchesServer(t *testing.T) {
+ said := []string{
+ "**Done.** Your site is up",
+ "*soon*",
+ "_soon_",
+ "a_b_c",
+ "**<b>x</b>**",
+ "Three things:\n- Docs\n- Sheets\n- [Calendar](https://cal.test/)",
+ "1. One\n2. Two",
+ "3) Three",
+ "- [x](javascript:alert(1))",
+ "** not bold **",
+ "# Heading",
+ "Line one\r\n- a *b*\r\n- **c**\r\nafter\r\n",
+ "é_x_ ü _ä_ _x_y 日本_語_ *😀* **😀 a** _😀_",
+ "- a\n\nb\n* c\n1. d\n0) e\n- f\n1000. g\n- \n",
+ "See https://a.test/_x_ and [*it*](https://b.test/?q=1&r=2) then *after* <img src=x onerror=alert(1)>",
+ "***x*** __y__ *a**b* **a*b** _a__b_ *\t*",
+ "A\rB\x00C\r\n\r\n- d\re",
+ }
+ rig, f := askBase(t)
+ openPanel(t, rig)
+ for _, s := range said {
+ f.Say(s)
+ }
+ drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.coordinator").length === `+strconv.Itoa(len(said)),
+ chromedp.WithPollingTimeout(10*time.Second)))
+ got := harness.Evaluate[string](rig, `(async () => {
+ const page = new DOMParser().parseFromString(await (await fetch("/ask")).text(), "text/html");
+ const out = [];
+ for (const m of document.querySelectorAll("#ask-panel .msg.coordinator")) {
+ const s = page.querySelector('.msg.coordinator[data-id="' + CSS.escape(m.dataset.id) + '"]');
+ if (!s) out.push(m.dataset.id + ": not on /ask");
+ else if (s.innerHTML !== m.innerHTML) out.push(JSON.stringify(m.textContent) + "\n script " + m.innerHTML + "\n server " + s.innerHTML);
+ }
+ return out.join("\n");
+ })()`, chromedp.EvalAwaitPromise)
+ if got != "" {
+ t.Errorf("the script and the server draw differently:\n%s", got)
+ }
+ if n := harness.Evaluate[int](rig, `document.querySelectorAll('#ask-panel .msg a[href^="javascript"], #ask-panel .msg img, #ask-panel .msg b').length`); n != 0 {
+ t.Errorf("unsafe markup drawn: %d", n)
+ }
+ // The thread is a list without markers; the Assistant's lists have them.
+ if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .msg ul, #ask-panel .msg ol")]
+ .map(l => l.tagName + "=" + getComputedStyle(l).listStyleType).filter(s => s !== "UL=disc" && s !== "OL=decimal").join(" ")`); got != "" {
+ t.Errorf("lists without their markers: %s", got)
+ }
+ rig.Screen("#ask-panel", "the Assistant's simple Markdown")
+}
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 5ad4cfd..30223b5 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -484,6 +484,10 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt
.msg { max-width: 86%; padding: 10px 14px; border-radius: 14px; white-space: pre-wrap; overflow-wrap: anywhere; font-size: 15px; line-height: 1.5; }
.msg.person { align-self: flex-end; background: var(--mine); box-shadow: inset 0 0 0 1px var(--mine-edge); border-bottom-right-radius: 4px; }
.msg.coordinator { align-self: flex-start; background: var(--theirs); box-shadow: inset 0 0 0 1px var(--theirs-edge); border-bottom-left-radius: 4px; }
+/* The Assistant's simple lists: the thread's own list-style is none. */
+.msg.coordinator ul, .msg.coordinator ol { margin: 4px 0; padding-left: 20px; }
+.msg.coordinator ul { list-style: disc; }
+.msg.coordinator ol { list-style: decimal; }
.msg.draft::after { content: ""; display: inline-block; width: 7px; height: 1em; margin-left: 3px; vertical-align: -2px; background: var(--signal); animation: caret 1s steps(2) infinite; }
@keyframes caret { 50% { opacity: 0; } }
.msg.card { align-self: stretch; max-width: none; background: var(--card); box-shadow: inset 0 0 0 1px var(--card-edge); }
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 8d2d776..bab33bb 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -108,10 +108,14 @@ function start(root) {
scroll();
}
- // Equipo's lines may carry Markdown links. Only http(s) addresses become
- // links (opening in a new tab); the rest, raw HTML and relative paths
- // included, is text. Base's server does the same (richText in
- // ask_cards.go).
+ // An Assistant's line, in the little Markdown it may write (plan
+ // decision D16): runs of "- " or "* " lines are a bulleted list, runs of
+ // "1. " or "1) " lines (1 to 3 digits) a numbered one, and every other
+ // line is text with its newlines (the one next to a list goes). In text
+ // and list items, only http(s) addresses become links (opening in a new
+ // tab), and between links **x** is bold, *x* and _x_ italic. The rest,
+ // raw HTML and relative paths included, is text. Base's server does the
+ // same (richText in ask_cards.go).
const linkRE = /\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?:\/\/[^\s<>()\[\]"']+/g;
// webURL is target if it is an absolute http(s) URL with a host and no
// user info, else "" (equipo.WebURL on the server).
@@ -131,8 +135,40 @@ function start(root) {
a.textContent = text;
return a;
}
+ // listLine is line's list ({kind: "ul" or "ol", n, item}), or null.
+ function listLine(line) {
+ if (line.length > 2 && (line[0] === "-" || line[0] === "*") && line[1] === " ") return { kind: "ul", n: 0, item: line.slice(2) };
+ const m = /^(\d{1,3})[.)] /.exec(line);
+ if (m && line.length > m[0].length) return { kind: "ol", n: Number(m[1]), item: line.slice(m[0].length) };
+ return null;
+ }
+ // Line breaks are read as a page reads them (\r\n and \r are \n, and a
+ // NUL goes), so the server's HTML and this draw the same.
function rich(el, text) {
el.replaceChildren();
+ const lines = text.replace(/\r\n?/g, "\n").replaceAll("\0", "").split("\n");
+ for (let i = 0; i < lines.length; ) {
+ const first = listLine(lines[i]);
+ if (!first) {
+ let j = i + 1;
+ while (j < lines.length && !listLine(lines[j])) j++;
+ inline(el, lines.slice(i, j).join("\n"));
+ i = j;
+ continue;
+ }
+ const list = document.createElement(first.kind);
+ if (first.kind === "ol" && first.n !== 1) list.start = first.n;
+ for (let l; i < lines.length && (l = listLine(lines[i])) && l.kind === first.kind; i++) {
+ const li = document.createElement("li");
+ inline(li, l.item);
+ list.append(li);
+ }
+ el.append(list);
+ }
+ }
+ // inline appends text with its safe links, and bold and italics between
+ // them.
+ function inline(el, text) {
let last = 0;
for (const m of text.matchAll(linkRE)) {
let end = m.index + m[0].length, label = m[1], target = m[2];
@@ -143,11 +179,51 @@ function start(root) {
}
const href = webURL(target);
if (!href) continue;
- el.append(text.slice(last, m.index), link(href, label));
+ emphasis(el, text.slice(last, m.index));
+ el.append(link(href, label));
last = end;
}
- el.append(text.slice(last));
+ emphasis(el, text.slice(last));
+ }
+ // emphasis appends text with **x** as <strong> and *x* or _x_ as <em>:
+ // x is the text up to the next same marker, not empty, on one line, and
+ // neither starting nor ending with a space; an _ also needs no word
+ // character just outside it. Nothing nests (emphasis in ask_cards.go).
+ function emphasis(el, text) {
+ let last = 0;
+ const put = (tag, at, x, next) => {
+ if (at > last) el.append(text.slice(last, at));
+ const e = document.createElement(tag);
+ e.textContent = x;
+ el.append(e);
+ last = next;
+ return next;
+ };
+ for (let i = 0; i < text.length; ) {
+ const c = text[i];
+ if (c === "*" && text[i + 1] === "*") {
+ const j = text.indexOf("**", i + 2);
+ if (j >= 0 && emphasized(text.slice(i + 2, j))) {
+ i = put("strong", i, text.slice(i + 2, j), j + 2);
+ continue;
+ }
+ }
+ if (c === "*" || (c === "_" && (i === 0 || !wordUnit(text.charCodeAt(i - 1))))) {
+ const j = text.indexOf(c, i + 1);
+ if (j >= 0 && emphasized(text.slice(i + 1, j)) && (c === "*" || j + 1 === text.length || !wordUnit(text.charCodeAt(j + 1)))) {
+ i = put("em", i, text.slice(i + 1, j), j + 1);
+ continue;
+ }
+ }
+ i++;
+ }
+ if (text.length > last) el.append(text.slice(last));
}
+ const space = (c) => c === " " || c === "\t";
+ const emphasized = (x) => x !== "" && !x.includes("\n") && !space(x[0]) && !space(x[x.length - 1]);
+ // A word's code unit: an ASCII letter, digit or _, or anything beyond
+ // ASCII (wordByte on the server sees the same in UTF-8).
+ const wordUnit = (u) => u >= 0x80 || u === 95 || (u >= 48 && u <= 57) || (u >= 97 && u <= 122) || (u >= 65 && u <= 90);
// A card, drawn from its fields alone as the server draws it (the
// ask-card template): the question, a link per link, a button per option
diff --git a/internal/web/ask_cards.go b/internal/web/ask_cards.go
index 459f603..5b46011 100644
--- a/internal/web/ask_cards.go
+++ b/internal/web/ask_cards.go
@@ -4,6 +4,7 @@ import (
"html"
"html/template"
"regexp"
+ "strconv"
"strings"
"amadan.net/carlos/base/internal/equipo"
@@ -12,17 +13,75 @@ import (
// linkRE finds a Markdown link [label](target), or a bare http(s) URL.
var linkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+`)
-// richText is an Assistant's line as HTML: every character escaped, and a
-// Markdown link or bare URL made a link only when it goes to an http(s)
-// address. Anything else, raw HTML and relative paths included, stays as
-// text. The panel's script does the same (ask.js, rich).
+// richText is an Assistant's line as HTML, in the little Markdown it may
+// write (plan decision D16): runs of "- " or "* " lines are a bulleted
+// list, runs of "1. " or "1) " lines (1 to 3 digits) a numbered one, and
+// every other line is text with its newlines (the one next to a list
+// goes). In text and list items, a Markdown link or bare URL is a link
+// only when it goes to an http(s) address, and between links **x** is
+// bold, *x* and _x_ italic. Every other character is escaped: raw HTML,
+// relative paths and any other Markdown stay text. The panel's script does
+// the same (ask.js, rich). Its line breaks are read as a page reads them
+// (\r\n and \r are \n, and a NUL goes), so the two draw the same.
func richText(text string) template.HTML {
var b strings.Builder
- last := 0
- for _, m := range linkRE.FindAllStringSubmatchIndex(text, -1) {
- if m[0] < last {
+ lines := strings.Split(asPageReads.Replace(text), "\n")
+ for i := 0; i < len(lines); {
+ kind, n, _ := listLine(lines[i])
+ if kind == "" {
+ j := i + 1
+ for j < len(lines) && !isListLine(lines[j]) {
+ j++
+ }
+ inline(&b, strings.Join(lines[i:j], "\n"))
+ i = j
continue
}
+ if kind == "ol" && n != 1 {
+ b.WriteString(`<ol start="` + strconv.Itoa(n) + `">`)
+ } else {
+ b.WriteString("<" + kind + ">")
+ }
+ for ; i < len(lines); i++ {
+ k, _, item := listLine(lines[i])
+ if k != kind {
+ break
+ }
+ b.WriteString("<li>")
+ inline(&b, item)
+ b.WriteString("</li>")
+ }
+ b.WriteString("</" + kind + ">")
+ }
+ return template.HTML(b.String())
+}
+
+var asPageReads = strings.NewReplacer("\r\n", "\n", "\r", "\n", "\x00", "")
+
+// numberRE is a numbered list line's start: 1 to 3 digits, "." or ")",
+// a space.
+var numberRE = regexp.MustCompile(`^(\d{1,3})[.)] `)
+
+// listLine is line's list ("ul" or "ol", else ""), its number for "ol",
+// and the item after the marker, which is never empty.
+func listLine(line string) (kind string, n int, item string) {
+ if len(line) > 2 && (line[0] == '-' || line[0] == '*') && line[1] == ' ' {
+ return "ul", 0, line[2:]
+ }
+ if m := numberRE.FindStringSubmatch(line); m != nil && len(line) > len(m[0]) {
+ n, _ := strconv.Atoi(m[1])
+ return "ol", n, line[len(m[0]):]
+ }
+ return "", 0, ""
+}
+
+func isListLine(line string) bool { k, _, _ := listLine(line); return k != "" }
+
+// inline writes text with its safe links, and bold and italics between
+// them.
+func inline(b *strings.Builder, text string) {
+ last := 0
+ for _, m := range linkRE.FindAllStringSubmatchIndex(text, -1) {
end, label, target := m[1], "", ""
if m[2] >= 0 {
label, target = text[m[2]:m[3]], text[m[4]:m[5]]
@@ -34,12 +93,55 @@ func richText(text string) template.HTML {
if href == "" {
continue
}
- b.WriteString(html.EscapeString(text[last:m[0]]))
+ emphasis(b, text[last:m[0]])
b.WriteString(`<a href="` + html.EscapeString(href) + `" target="_blank" rel="noopener">` + html.EscapeString(label) + `</a>`)
last = end
}
+ emphasis(b, text[last:])
+}
+
+// emphasis writes text escaped, with **x** as <strong> and *x* or _x_ as
+// <em>: x is the text up to the next same marker, not empty, on one line,
+// and neither starting nor ending with a space; an _ also needs no word
+// character just outside it, so snake_case stays as it is. Nothing nests.
+func emphasis(b *strings.Builder, text string) {
+ last := 0
+ for i := 0; i < len(text); {
+ c := text[i]
+ if c == '*' && strings.HasPrefix(text[i+1:], "*") {
+ if j := strings.Index(text[i+2:], "**"); j >= 0 && emphasized(text[i+2:i+2+j]) {
+ b.WriteString(html.EscapeString(text[last:i]) + "<strong>" + html.EscapeString(text[i+2:i+2+j]) + "</strong>")
+ i += j + 4
+ last = i
+ continue
+ }
+ }
+ if c == '*' || c == '_' && (i == 0 || !wordByte(text[i-1])) {
+ j := strings.IndexByte(text[i+1:], c)
+ if j >= 0 && emphasized(text[i+1:i+1+j]) && (c == '*' || i+2+j == len(text) || !wordByte(text[i+2+j])) {
+ b.WriteString(html.EscapeString(text[last:i]) + "<em>" + html.EscapeString(text[i+1:i+1+j]) + "</em>")
+ i += j + 2
+ last = i
+ continue
+ }
+ }
+ i++
+ }
b.WriteString(html.EscapeString(text[last:]))
- return template.HTML(b.String())
+}
+
+// emphasized is whether x may be bold or italic: not empty, on one line,
+// with no space at either end.
+func emphasized(x string) bool {
+ return x != "" && !strings.Contains(x, "\n") && !space(x[0]) && !space(x[len(x)-1])
+}
+
+func space(c byte) bool { return c == ' ' || c == '\t' }
+
+// wordByte is whether c is part of a word: an ASCII letter, digit or _, or
+// any byte of a character beyond ASCII (ask.js sees the same in UTF-16).
+func wordByte(c byte) bool {
+ return c >= 0x80 || c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
}
// Rich is an Assistant's line with its links (richText), for templates.
diff --git a/internal/web/rich_internal_test.go b/internal/web/rich_internal_test.go
index 43ef364..78fe013 100644
--- a/internal/web/rich_internal_test.go
+++ b/internal/web/rich_internal_test.go
@@ -34,3 +34,33 @@ func TestRichTextHasNoTaskLinks(t *testing.T) {
}
}
}
+
+// The Assistant writes a little Markdown (plan decision D16): bold,
+// italics, bullet and numbered lists. Anything else stays text, links keep
+// their rules inside lists, and what is bold is still escaped.
+func TestRichTextMarkdown(t *testing.T) {
+ for _, c := range []struct{ in, want string }{
+ {"**Done.** Your site is up", `<strong>Done.</strong> Your site is up`},
+ {"*soon*", `<em>soon</em>`},
+ {"_soon_", `<em>soon</em>`},
+ {"a_b_c", `a_b_c`},
+ {"**<b>x</b>**", `<strong>&lt;b&gt;x&lt;/b&gt;</strong>`},
+ {"Three things:\n- Docs\n- Sheets\n- [Calendar](https://cal.test/)", `Three things:<ul><li>Docs</li><li>Sheets</li><li><a href="https://cal.test/" target="_blank" rel="noopener">Calendar</a></li></ul>`},
+ {"1. One\n2. Two", `<ol><li>One</li><li>Two</li></ol>`},
+ {"3) Three", `<ol start="3"><li>Three</li></ol>`},
+ {"- [x](javascript:alert(1))", `<ul><li>[x](javascript:alert(1))</li></ul>`},
+ {"** not bold **", `** not bold **`},
+ {"# Heading", `# Heading`},
+ // The newline next to a list goes; the others stay.
+ {"- a\n\nb\n* c\n1. d\n", "<ul><li>a</li></ul>\nb<ul><li>c</li></ul><ol><li>d</li></ol>"},
+ {"*a\nb* and _x_y and é_x_ and - not a list", "*a\nb* and _x_y and é_x_ and - not a list"},
+ {"*", `*`},
+ // As a page would hold it: line breaks are \n, and NULs go.
+ {"A\r\n- b\r\n- c\rD\x00E", "A<ul><li>b</li><li>c</li></ul>DE"},
+ {"- \n1.\n1000. x", "<ul><li> </li></ul>1.\n1000. x"},
+ } {
+ if got := string(richText(c.in)); got != c.want {
+ t.Errorf("richText(%q)\n got %s\nwant %s", c.in, got, c.want)
+ }
+ }
+}