oficina / base Public

Ask Markdown: Fable's review (S2-S6, italics, nits)

Tests: TestPersonText (Go), TestAskPersonMarkdown (Chromium, script and
server against the same samples), testThePersonsMarkdownMatchesTheWeb and
testThePersonsPlainWordsStayPlain (app), paste.json gains Fable's VS Code
HTML, Xcode RTF, a Word sample and inline code; testHostileClipboardsOnA
SmallStack (512 KB thread: 100,000 nested elements, 2,000 nested lists,
20,000 stray end tags, a 2 MB bound); TestAskPasteIsBounded (50,000 items
converted under 200 ms, 5,000 levels); TypeTests checks every italic
instance. The six person-markdown baselines are re-recorded with real
italics, the Assistant's reply in that screen now has one too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Summary

S4: the person's messages follow the web's little subset everywhere, with emphasis only at word boundaries (personText/strictEmphasis on the server, rich(strict) in ask.js, a native port PersonMarkdown instead of CommonMark): 2*3*4, a*b + c*d, x**2 + y**2, __init__.py stay literal; no indented code, headings, quotes or entities; a numbered list keeps its start, 1986. is no list. Shared samples internal/web/testdata/person.json checked by Go, the browser and the app. Assistant replies keep their rules (the same arithmetic bug is there; not changed). Ordered lists natively count from their start, the Assistant's too. S2: code pastes stay plain (monospace font-family, pre/code/tt/samp/kbd dominant, fixed-pitch RTF). S3: only font-weight/font-style declarations count, never mso-bidi-*. S5: native HTML nesting capped at 32 (flattened, end tags still matched), 2 MB HTML bound, walk stops at 16,000 characters; web the same. S6: the web converter builds its output once. Italics: Timeless Sans italic instances by name for both roles (DM Sans/system slant). N2: href trimmed/escaped natively, labels over 300 characters as text with address, UTF-16 HTML on iPhone.
claude agent, operated by paul@keymail.dev 3e36271b3e6a3787ac104912b3bcebca6d3db611 parent 41a646e
25 files changed, +695 −132
  • internal/browsertest/paste_test.go +67 −14
  • internal/browsertest/testdata/paste.json +20 −0
  • internal/look/static/ask.js +106 −37
  • internal/web/ask_cards.go +66 −4
  • internal/web/rich_internal_test.go +28 −1
  • internal/web/templates/partials/chat.html +1 −1
  • internal/web/testdata/person.json +66 −0
  • native/apple/Sources/BaseKit/Ask/Composer.swift +1 −1
  • native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift +27 −10
  • native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift +9 −11
  • native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift +2 −2
  • native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift +127 −0
  • native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift +73 −28
  • native/apple/Sources/BaseKit/Ask/Thread.swift +5 −5
  • native/apple/Sources/BaseKit/Look/Type.swift +17 −9
  • native/apple/Tests/BaseKitTests/AskViewTests.swift +41 −6
  • native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift +35 −2
  • native/apple/Tests/BaseKitTests/TypeTests.swift +3 −0
  • native/apple/Tests/BaseSnapshots/AskSnapshots.swift +1 −1
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png binary
  • native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png binary

CI passed — run details

CI log
=== build ===
CGO_ENABLED=0 go build ./...
=== vet ===
go vet ./...
=== fmt-check ===
=== staticcheck ===
go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./...
=== govulncheck ===
go run golang.org/x/vuln/cmd/govulncheck@v1.8.0 ./...
No vulnerabilities found.
=== gitleaks ===
11:33AM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
11:33AM INF 1 commits scanned.
11:33AM INF scanned ~2485198 bytes (2.49 MB) in 289ms
11:33AM INF no leaks found
=== budget ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget size
budget size: 22 directories within budget
=== script-test ===
scripts/prepare-apps_test.sh
ok   releases lookup failure stops before ship
ok   app owned elsewhere stops the script
ok   apps listing failure stops before create
ok   ambiguous release dir is refused
ok   explicit version resolves the ambiguity
ok   releases match is exact, not substring
ok   shipped version is only promoted, existing app not created
ok   fresh account creates, ships, promotes to edge, enables
ok   failing promote stops the script
ok   ship is retried while uploads are rate limited
all passed
hack/fonts_test.sh
fonts_test: ok
=== test ===
go run amadan.net/rastrillo/rastrillo/cmd/rastrillo budget test -count=1 ./...

receipt: test step 8.168s against a 60s target (the gate's other steps are not in this figure)
receipt: 16 packages ran, 0 cached, 6 without tests, 0 failed
receipt: slow package 6.69s amadan.net/oficina/base/internal/webtest
receipt: slow package 780ms amadan.net/oficina/base/internal/issuer
receipt: slow package 619ms amadan.net/oficina/base/internal/operations
receipt: slow package 234ms amadan.net/oficina/base/internal/consumer
receipt: slow package 187ms amadan.net/oficina/base/internal/web
receipt: slow test 1.52s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.1s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 520ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
receipt: slow test 380ms amadan.net/oficina/base/internal/issuer TestAuthorizeRefusals
receipt: slow test 350ms amadan.net/oficina/base/internal/issuer TestAuthorizeSignsForInstalledApp
=== native ===
strings: copy review's strings.json is not here (git-ignored); its comparison skipped
strings: 119 in the catalog, 116 used
worktree-lib_test: ok
diff --git a/internal/browsertest/paste_test.go b/internal/browsertest/paste_test.go
index 24704d0..56b2ada 100644
--- a/internal/browsertest/paste_test.go
+++ b/internal/browsertest/paste_test.go
@@ -19,7 +19,7 @@ import (
// app's PasteMarkdownTests check the same samples.
type pasteSample struct {
Name string `json:"name"`
- HTML string `json:"html"`
+ HTML string `json:"html"` // "" for the app's RTF samples
Markdown *string `json:"markdown"`
}
@@ -60,6 +60,9 @@ func TestAskPasteMarkdown(t *testing.T) {
return r
}
for _, s := range samples {
+ if s.HTML == "" {
+ continue
+ }
got := paste("", s.HTML)
switch {
case s.Markdown == nil && (got.Prevented || got.Value != ""):
@@ -77,15 +80,63 @@ func TestAskPasteMarkdown(t *testing.T) {
}
}
+// Fable's S5 and S6: a big or hostile paste never freezes the tab. The
+// walk is linear and stops once the Markdown passes the field's 16,000
+// characters; nesting past 32 levels is flattened.
+func TestAskPasteIsBounded(t *testing.T) {
+ rig, _ := askBase(t)
+ openPanel(t, rig)
+ // The conversion alone: the field's own insert of 16,000 characters
+ // is the browser's, timed apart.
+ got := harness.Evaluate[string](rig, `(() => {
+ const f = document.querySelector("#ask-text");
+ const insert = document.execCommand;
+ let typed = null;
+ document.execCommand = (command, ui, text) => { typed = text; return true; };
+ const run = (html) => {
+ f.focus(); typed = null;
+ const data = new DataTransfer();
+ data.setData("text/html", html);
+ const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true });
+ const t0 = performance.now();
+ f.dispatchEvent(e);
+ return { ms: performance.now() - t0, value: typed || "" };
+ };
+ const out = [];
+ try {
+ const items = run("<ul>" + "<li><b>item</b></li>".repeat(50000) + "</ul>");
+ if (items.ms > 200) out.push("50,000 items took " + Math.round(items.ms) + " ms");
+ if (!items.value.startsWith("- **item**\n- **item**") || items.value.length > 16100) out.push("items pasted " + items.value.length + " characters");
+ const deep = run("<div><b>".repeat(5000) + "deep" + "</b></div>".repeat(5000));
+ if (deep.ms > 500) out.push("5,000 levels took " + Math.round(deep.ms) + " ms");
+ if (deep.value !== "**deep**") out.push("deep pasted " + JSON.stringify(deep.value.slice(0, 40)));
+ } finally {
+ document.execCommand = insert;
+ }
+ return out.join("; ");
+ })()`)
+ if got != "" {
+ t.Error(got)
+ }
+}
+
// The person's own messages are drawn in the Assistant's little Markdown,
-// by the script and the server alike; plain words stay plain text, and
-// unsafe links stay text.
+// with emphasis only at word boundaries, by the script and the server
+// alike (internal/web/testdata/person.json, which the server's and the
+// app's tests check too); plain words stay plain text, and unsafe links
+// stay text.
func TestAskPersonMarkdown(t *testing.T) {
- said := []string{
- "**Bold** and *it*",
- "Two lines\nhere, 2*3 and a_b_c",
- "Shopping:\n- [Menu](https://fennel.example/menu)\n- [x](javascript:alert(1))",
- "1. One\n2. Two",
+ raw, err := os.ReadFile("../web/testdata/person.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cases []struct{ Text, HTML string }
+ if err := json.Unmarshal(raw, &cases); err != nil {
+ t.Fatal(err)
+ }
+ said := make([]string, len(cases))
+ for i, c := range cases {
+ said[i] = c.Text
}
rig, _ := askBase(t)
openPanel(t, rig)
@@ -110,12 +161,14 @@ func TestAskPersonMarkdown(t *testing.T) {
if got != "" {
t.Errorf("the script and the server draw differently:\n%s", got)
}
- if got := harness.Evaluate[string](rig, `[...document.querySelectorAll("#ask-panel .msg.person")].map(m => m.innerHTML).join("\n")`); got !=
- "<strong>Bold</strong> and <em>it</em>\n"+
- "Two lines\nhere, 2*3 and a_b_c\n"+
- `Shopping:<ul><li><a href="https://fennel.example/menu" target="_blank" rel="noopener">Menu</a></li><li>[x](javascript:alert(1))</li></ul>`+"\n"+
- "<ol><li>One</li><li>Two</li></ol>" {
- t.Errorf("the person's messages:\n%s", got)
+ var drawn []string
+ if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, `JSON.stringify([...document.querySelectorAll("#ask-panel .msg.person")].map(m => m.innerHTML))`)), &drawn); err != nil {
+ t.Fatal(err)
+ }
+ for i, c := range cases {
+ if i < len(drawn) && drawn[i] != c.HTML {
+ t.Errorf("%q drawn\n %s\nwant %s", c.Text, drawn[i], c.HTML)
+ }
}
// Their links keep the bubble's ink; their lists have markers.
if got := harness.Evaluate[string](rig, `(() => {
diff --git a/internal/browsertest/testdata/paste.json b/internal/browsertest/testdata/paste.json
index d96f54c..d7f7e49 100644
--- a/internal/browsertest/testdata/paste.json
+++ b/internal/browsertest/testdata/paste.json
@@ -48,5 +48,25 @@
"name": "A link whose text is its address",
"html": "<a href=\"https://fennel.example/menu\">https://fennel.example/menu</a>",
"markdown": "https://fennel.example/menu"
+ },
+ {
+ "name": "Fable's S2: VS Code, with an italic comment, is code: the plain text is pasted",
+ "html": "<meta charset=\"utf-8\"><div style=\"color: #cccccc;background-color: #1f1f1f;font-family: Menlo, Monaco, 'Courier New', monospace;font-weight: normal;font-size: 12px;line-height: 18px;white-space: pre;\"><div><span style=\"color: #569cd6;\">func</span><span style=\"color: #cccccc;\"> </span><span style=\"color: #dcdcaa;\">greet</span><span style=\"color: #cccccc;\">() {</span></div><div><span style=\"color: #cccccc;\"> </span><span style=\"color: #6a9955;font-style: italic;\">// say *hi*</span></div><div><span style=\"color: #cccccc;\"> </span><span style=\"color: #c586c0;\">return</span><span style=\"color: #cccccc;\"> </span><span style=\"color: #b5cea8;\">2</span><span style=\"color: #d4d4d4;\">*</span><span style=\"color: #b5cea8;\">3</span></div><div><span style=\"color: #cccccc;\">}</span></div></div>",
+ "markdown": null
+ },
+ {
+ "name": "A little inline code in prose stays text",
+ "html": "<p>Run <code>make ci</code> then <b>push</b>.</p>",
+ "markdown": "Run make ci then **push**."
+ },
+ {
+ "name": "Fable's S3: Word's mso-bidi-* and other prefixed weights are not font-weight",
+ "html": "<html xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:w=\"urn:schemas-microsoft-com:office:word\" xmlns=\"http://www.w3.org/TR/REC-html40\"><head><meta http-equiv=Content-Type content=\"text/html; charset=utf-8\"><meta name=Generator content=\"Microsoft Word 15\"><style><!-- p.MsoNormal {margin:0cm; font-size:12.0pt; font-family:\"Aptos\",sans-serif;} --></style></head><body lang=EN-IE style='tab-interval:36.0pt;word-wrap:break-word'><!--StartFragment--><p class=MsoNormal><b style='mso-bidi-font-weight:normal'>Bold</b> and <i style='mso-bidi-font-style:normal'>italic</i>, <span style='mso-bidi-font-weight:bold'>plain in Latin</span>, <span style='--tw-font-weight:700'>plain too</span>, and <a href=\"https://fennel.example/word\">a link</a><o:p></o:p></p><p class=MsoListParagraphCxSpFirst style='text-indent:-18.0pt;mso-list:l0 level1 lfo1'><![if !supportLists]><span style='font-family:Symbol'>·<span style='font:7.0pt \"Times New Roman\"'>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span></span><![endif]>Rye<o:p></o:p></p><!--EndFragment--></body></html>",
+ "markdown": "**Bold** and *italic*, plain in Latin, plain too, and [a link](https://fennel.example/word)\n\n· Rye"
+ },
+ {
+ "name": "Fable's S2: Xcode's RTF (bold keywords in Menlo) is code (the app only: the web has no RTF)",
+ "rtf": "{\\rtf1\\ansi\\ansicpg1252\\cocoartf2822\n\\cocoatextscaling0\\cocoaplatform0{\\fonttbl\\f0\\fnil\\fcharset0 Menlo-Bold;\\f1\\fnil\\fcharset0 Menlo-Regular;}\n{\\colortbl;\\red255\\green255\\blue255;\\red155\\green35\\blue147;}\n\\pard\\tx593\\pardeftab593\\pardirnatural\\partightenfactor0\n\n\\f0\\b\\fs24 \\cf2 func\n\\f1\\b0 \\cf0 greet() \\{\\\n \n\\f0\\b \\cf2 let\n\\f1\\b0 \\cf0 x = 2*3\\\n \n\\f0\\b \\cf2 return\n\\f1\\b0 \\cf0 x\\\n\\}}",
+ "markdown": null
}
]
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index d1473e5..919b90c 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -110,8 +110,9 @@ function start(root) {
li.dataset.id = m.id;
if (m.role !== "person" && m.turn_id) li.dataset.turn = m.turn_id;
// The person's own words take the same little Markdown as the
- // Assistant's (rich), under the same rules.
- rich(li, m.text);
+ // Assistant's (rich), with emphasis only at word boundaries
+ // (strictEmphasis).
+ rich(li, m.text, m.role === "person");
const draft = m.role !== "person" && (item("data-draft", m.turn_id) || bubbles.get(m.turn_id));
if (draft && draft.querySelector(":scope > .think-line")) become(draft, li);
else if (draft) draft.replaceWith(li);
@@ -280,7 +281,7 @@ function start(root) {
}
// 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) {
+ function rich(el, text, strict = false) {
el.replaceChildren();
const lines = text.replace(/\r\n?/g, "\n").replaceAll("\0", "").split("\n");
for (let i = 0; i < lines.length; ) {
@@ -288,7 +289,7 @@ function start(root) {
if (!first) {
let j = i + 1;
while (j < lines.length && !listLine(lines[j])) j++;
- inline(el, lines.slice(i, j).join("\n"));
+ inline(el, lines.slice(i, j).join("\n"), strict);
i = j;
continue;
}
@@ -296,7 +297,7 @@ function start(root) {
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);
+ inline(li, l.item, strict);
list.append(li);
}
el.append(list);
@@ -304,7 +305,8 @@ function start(root) {
}
// inline appends text with its safe links, and bold and italics between
// them.
- function inline(el, text) {
+ function inline(el, text, strict) {
+ const emphasis = strict ? strictEmphasis : looseEmphasis;
let last = 0;
for (const m of text.matchAll(linkRE)) {
let end = m.index + m[0].length, label = m[1], target = m[2];
@@ -325,7 +327,7 @@ function start(root) {
// 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) {
+ function looseEmphasis(el, text) {
let last = 0;
const put = (tag, at, x, next) => {
if (at > last) el.append(text.slice(last, at));
@@ -355,6 +357,36 @@ function start(root) {
}
if (text.length > last) el.append(text.slice(last));
}
+ // strictEmphasis is emphasis for the person's words: a run of markers
+ // opens only at the start or after a character that is no word's, closes
+ // only at the end or before one, and is exactly one * or _, or two *, so
+ // 2*3*4, x**2 + y**2 and __init__.py stay as written (strictEmphasis in
+ // ask_cards.go). Linear: each run looks only to the next of its marker.
+ function strictEmphasis(el, text) {
+ let last = 0;
+ const run = (at) => { let n = 1; while (text[at + n] === text[at]) n++; return n; };
+ for (let i = 0; i < text.length; ) {
+ const c = text[i];
+ if (c !== "*" && c !== "_") { i++; continue; }
+ const n = run(i);
+ if ((i === 0 || !wordUnit(text.charCodeAt(i - 1))) && (n === 1 || (n === 2 && c === "*"))) {
+ const j = text.indexOf(c, i + n);
+ if (j >= 0) {
+ const end = j + run(j), x = text.slice(i + n, j);
+ if (end - j === n && emphasized(x) && (end === text.length || !wordUnit(text.charCodeAt(end)))) {
+ if (i > last) el.append(text.slice(last, i));
+ const e = document.createElement(n === 2 ? "strong" : "em");
+ e.textContent = x;
+ el.append(e);
+ i = last = end;
+ continue;
+ }
+ }
+ }
+ i += n;
+ }
+ 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
@@ -1664,23 +1696,41 @@ function start(root) {
// (**x**), italics (*x*), links ([text](url), http(s) only, as webURL),
// bullet and numbered lists (nested by indent), headings (# x), and line
// breaks and paragraphs. Everything else is its text. It is null when the
- // HTML formats nothing, so a plain paste stays exactly as copied. The
- // HTML is parsed into an inert document (nothing runs or loads) and only
- // walked; the app's MarkdownPaste does the same (keep them in step: the
- // samples in internal/browsertest/testdata/paste.json check both).
+ // HTML formats nothing, or is mostly code (a monospace font, or pre,
+ // code, tt, samp, kbd), so a plain paste or code stays exactly as
+ // copied. The HTML is parsed into an inert document (nothing runs or
+ // loads) and walked once: elements deeper than 32 are flattened, the
+ // walk stops once the Markdown passes the field's 16,000 characters, and
+ // more than 2 MB of HTML is left plain. The app's PasteMarkdown does the
+ // same (keep them in step: the samples in
+ // internal/browsertest/testdata/paste.json check both).
function pasteMarkdown(html) {
+ if (html.length > 2000000) return null;
const doc = new DOMParser().parseFromString(html, "text/html");
+ const maxDepth = 32, maxOut = 16000;
const skip = new Set(["SCRIPT", "STYLE", "HEAD", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME", "OBJECT", "EMBED", "SVG", "MATH", "CANVAS", "VIDEO", "AUDIO", "PICTURE", "IMG", "BUTTON", "SELECT", "INPUT", "TEXTAREA"]);
+ const raw = new Set(["SCRIPT", "STYLE", "TEXTAREA", "TITLE", "TEMPLATE", "NOSCRIPT", "IFRAME"]);
const lines = new Set(["DIV", "SECTION", "ARTICLE", "HEADER", "FOOTER", "MAIN", "NAV", "ASIDE", "BLOCKQUOTE", "FIGURE", "FIGCAPTION", "ADDRESS", "CENTER", "DETAILS", "SUMMARY", "FORM", "FIELDSET", "TABLE", "THEAD", "TBODY", "TFOOT", "TR", "CAPTION", "DL", "DT", "DD", "HR"]);
+ const code = new Set(["PRE", "CODE", "TT", "SAMP", "KBD"]);
+ const monoFont = /monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console/i;
+ // The output, built once: its pieces, its length, and how many line
+ // breaks it ends with.
const out = [];
- let runs = [], open = false, marker = null, indent = "", formatted = false;
+ let length = 0, breaks = 0;
+ const put = (s) => {
+ if (!s) return;
+ out.push(s);
+ length += s.length;
+ const m = /\n*$/.exec(s)[0].length;
+ breaks = m === s.length ? breaks + m : m;
+ };
+ let runs = [], open = false, marker = null, indent = "", formatted = false, chars = 0, mono = 0;
const lists = [];
- const text = () => out.join("");
const flush = () => {
const s = inline(runs).replace(/^ +/, "");
runs = [];
if (!s) return;
- out.push(open ? s : (marker !== null ? marker : indent) + s);
+ put(open ? s : (marker !== null ? marker : indent) + s);
if (!open && marker !== null) formatted = true;
marker = null;
open = true;
@@ -1688,21 +1738,32 @@ function start(root) {
const ensure = (n) => {
flush();
open = false;
- const t = text();
- if (!t) return;
- let have = 0;
- for (let i = t.length - 1; i >= 0 && t[i] === "\n"; i--) have++;
- for (; have < n; have++) out.push("\n");
+ if (!length) return;
+ for (let have = breaks; have < n; have++) put("\n");
+ };
+ const lineBreak = () => {
+ flush();
+ if (length) { put("\n"); open = false; }
+ };
+ // A declaration's value in a style attribute (never mso-bidi-font-weight
+ // and the like).
+ const declared = (style, name) => {
+ const m = new RegExp("(?:^|;)\\s*" + name + "\\s*:\\s*([^;]*)", "i").exec(style);
+ return m ? m[1].trim() : null;
};
- const walk = (node, st) => {
+ const walk = (node, st, depth) => {
+ if (length > maxOut) return;
if (node.nodeType === 3) {
+ const counted = node.data.replace(/\s+/g, "").length;
+ chars += counted;
+ if (st.mono) mono += counted;
let t = st.pre ? node.data : node.data.replace(/[ \t\n\r\f\u00a0]+/g, " ");
// One space between words, whichever side of a tag it was.
if (!st.pre && t[0] === " " && runs.length && runs[runs.length - 1].text.endsWith(" ")) t = t.slice(1);
if (st.pre) {
const parts = t.split(/\r\n?|\n/);
parts.forEach((part, i) => {
- if (i) { flush(); out.push("\n"); open = false; }
+ if (i) { flush(); put("\n"); open = false; }
if (part) runs.push({ text: part, bold: false, italic: false, href: "" });
});
} else if (t) runs.push({ text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href });
@@ -1710,22 +1771,27 @@ function start(root) {
}
if (node.nodeType !== 1) return;
const tag = node.tagName.toUpperCase();
- if (skip.has(tag)) return;
- if (tag === "BR") {
- flush();
- if (text()) { out.push("\n"); open = false; }
+ if (tag === "BR") return lineBreak();
+ // Too deep: its text and line breaks only, as the app's tree has it.
+ if (depth >= maxDepth) {
+ if (raw.has(tag)) return;
+ for (const c of node.childNodes) walk(c, st, depth);
return;
}
+ if (skip.has(tag)) return;
const next = { ...st };
if (tag === "B" || tag === "STRONG") next.bold = true;
if (tag === "I" || tag === "EM") next.italic = true;
+ if (code.has(tag)) next.mono = true;
const style = node.getAttribute("style") || "";
- const weight = /font-weight\s*:\s*([a-z0-9]+)/i.exec(style);
- if (weight) next.bold = /^(bold|bolder|[6-9]00)$/i.test(weight[1]);
- const slant = /font-style\s*:\s*([a-z]+)/i.exec(style);
- if (slant) next.italic = /^(italic|oblique)$/i.test(slant[1]);
- if (tag === "A" && !st.href) next.href = webURL(node.getAttribute("href") || "");
- const children = () => { for (const c of node.childNodes) walk(c, next); };
+ const weight = declared(style, "font-weight");
+ if (weight !== null) next.bold = /^(bold|bolder|[6-9]00)$/i.test(weight);
+ const slant = declared(style, "font-style");
+ if (slant !== null) next.italic = /^(italic|oblique)/i.test(slant);
+ const family = declared(style, "font-family");
+ if (family !== null) next.mono = monoFont.test(family);
+ if (tag === "A" && !st.href) next.href = webURL((node.getAttribute("href") || "").trim());
+ const children = () => { for (const c of node.childNodes) walk(c, next, depth + 1); };
const level = /^H([1-6])$/.exec(tag);
if (level) {
ensure(2);
@@ -1770,7 +1836,7 @@ function start(root) {
if (tag === "P") {
if (lists.length) {
flush();
- if (open) { out.push("\n"); open = false; }
+ if (open) { put("\n"); open = false; }
children();
return;
}
@@ -1800,7 +1866,8 @@ function start(root) {
children();
};
// inline is a line's runs as Markdown: neighbours alike are one run,
- // and a run's outer spaces stand outside its marks.
+ // and a run's outer spaces stand outside its marks. A label the chat
+ // can't draw as a link (over 300 characters) is text with its address.
const inline = (rs) => {
const merged = [];
for (const r of rs) {
@@ -1816,7 +1883,7 @@ function start(root) {
if (r.href) {
const label = core.replace(/[\[\]]/g, "");
const href = r.href.replace(/\(/g, "%28").replace(/\)/g, "%29");
- s += lead + (label === r.href ? href : "[" + label + "](" + href + ")") + trail;
+ s += lead + (label === r.href ? href : label.length > 300 ? label + " (" + href + ")" : "[" + label + "](" + href + ")") + trail;
formatted = true;
} else if (r.bold || r.italic) {
const mark = r.bold ? "**" : "*";
@@ -1828,11 +1895,13 @@ function start(root) {
}
return s.replace(/ +$/, "");
};
- walk(doc.body, { bold: false, italic: false, href: "", heading: false, pre: false });
+ // The body is depth -1: 32 levels under it are kept, as in the app.
+ walk(doc.body, { bold: false, italic: false, href: "", heading: false, pre: false, mono: false }, -1);
flush();
- if (!formatted) return null;
- return text().split("\n").map((l) => l.replace(/[ \t]+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\n+$/g, "");
+ if (!formatted || mono * 2 > chars) return null;
+ return out.join("").split("\n").map((l) => l.replace(/[ \t]+$/, "")).join("\n").replace(/\n{3,}/g, "\n\n").replace(/^\n+|\n+$/g, "");
}
+
cancel.addEventListener("submit", (e) => {
e.preventDefault();
post(cancel);
diff --git a/internal/web/ask_cards.go b/internal/web/ask_cards.go
index 03d7f77..e20f534 100644
--- a/internal/web/ask_cards.go
+++ b/internal/web/ask_cards.go
@@ -23,7 +23,16 @@ var linkRE = regexp.MustCompile(`\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|htt
// 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 {
+func richText(text string) template.HTML { return richMarkdown(text, false) }
+
+// personText is the person's own message as HTML: richText's little
+// Markdown, but stricter about emphasis (strictEmphasis), since people
+// write arithmetic, file names and code: 2*3*4, x**2 and __init__.py stay
+// as written. ask.js (rich, strict) and the app (PersonMarkdown) do the
+// same.
+func personText(text string) template.HTML { return richMarkdown(text, true) }
+
+func richMarkdown(text string, strict bool) template.HTML {
var b strings.Builder
lines := strings.Split(asPageReads.Replace(text), "\n")
for i := 0; i < len(lines); {
@@ -33,7 +42,7 @@ func richText(text string) template.HTML {
for j < len(lines) && !isListLine(lines[j]) {
j++
}
- inline(&b, strings.Join(lines[i:j], "\n"))
+ inline(&b, strings.Join(lines[i:j], "\n"), strict)
i = j
continue
}
@@ -48,7 +57,7 @@ func richText(text string) template.HTML {
break
}
b.WriteString("<li>")
- inline(&b, item)
+ inline(&b, item, strict)
b.WriteString("</li>")
}
b.WriteString("</" + kind + ">")
@@ -79,7 +88,11 @@ 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) {
+func inline(b *strings.Builder, text string, strict bool) {
+ emphasis := emphasis
+ if strict {
+ emphasis = strictEmphasis
+ }
last := 0
for _, m := range linkRE.FindAllStringSubmatchIndex(text, -1) {
end, label, target := m[1], "", ""
@@ -130,6 +143,52 @@ func emphasis(b *strings.Builder, text string) {
b.WriteString(html.EscapeString(text[last:]))
}
+// strictEmphasis is emphasis for the person's words: **x** and *x* or _x_
+// only at word boundaries. A run of markers opens only at the start or
+// after a character that is no word's (a space, punctuation), closes only
+// at the end or before one, and is exactly one * or _, or two *: so
+// 2*3*4, a*b + c*d, x**2 + y**2 and __init__.py stay as written. x is as
+// in emphasis. Each run looks only as far as the next of its marker, so it
+// is linear.
+func strictEmphasis(b *strings.Builder, text string) {
+ last := 0
+ for i := 0; i < len(text); {
+ c := text[i]
+ if c != '*' && c != '_' {
+ i++
+ continue
+ }
+ run := markerRun(text, i)
+ if (i == 0 || !wordByte(text[i-1])) && (run == 1 || run == 2 && c == '*') {
+ from := i + run
+ if k := strings.IndexByte(text[from:], c); k >= 0 {
+ j := from + k
+ end := j + markerRun(text, j)
+ if x := text[from:j]; end-j == run && emphasized(x) && (end == len(text) || !wordByte(text[end])) {
+ tag := "em"
+ if run == 2 {
+ tag = "strong"
+ }
+ b.WriteString(html.EscapeString(text[last:i]) + "<" + tag + ">" + html.EscapeString(x) + "</" + tag + ">")
+ i, last = end, end
+ continue
+ }
+ }
+ }
+ i += run
+ }
+ b.WriteString(html.EscapeString(text[last:]))
+}
+
+// markerRun is how many of text[i] follow one another from i.
+func markerRun(text string, i int) int {
+ n := 1
+ for i+n < len(text) && text[i+n] == text[i] {
+ n++
+ }
+ return n
+}
+
// 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 {
@@ -146,3 +205,6 @@ func wordByte(c byte) bool {
// Rich is an Assistant's line with its links (richText), for templates.
func (v askView) Rich(text string) template.HTML { return richText(text) }
+
+// RichPerson is the person's own message (personText), for templates.
+func (v askView) RichPerson(text string) template.HTML { return personText(text) }
diff --git a/internal/web/rich_internal_test.go b/internal/web/rich_internal_test.go
index 78fe013..e7b1cbb 100644
--- a/internal/web/rich_internal_test.go
+++ b/internal/web/rich_internal_test.go
@@ -1,6 +1,10 @@
package web
-import "testing"
+import (
+ "encoding/json"
+ "os"
+ "testing"
+)
// Equipo's lines may carry Markdown links. Base links only web addresses;
// everything else, raw HTML included, stays text.
@@ -64,3 +68,26 @@ func TestRichTextMarkdown(t *testing.T) {
}
}
}
+
+// The person's own words (Paul, 2026-11-26; Fable's S4): the Assistant's
+// little Markdown, with emphasis only at word boundaries. The samples are
+// the app's too (PersonMarkdownTests) and the script's (TestAskPersonMarkdown).
+func TestPersonText(t *testing.T) {
+ raw, err := os.ReadFile("testdata/person.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var cases []struct{ Text, HTML string }
+ if err := json.Unmarshal(raw, &cases); err != nil {
+ t.Fatal(err)
+ }
+ for _, c := range cases {
+ if got := string(personText(c.Text)); got != c.HTML {
+ t.Errorf("personText(%q)\n got %s\nwant %s", c.Text, got, c.HTML)
+ }
+ }
+ // The Assistant's replies keep their rules.
+ if got := string(richText("2*3*4")); got != "2<em>3</em>4" {
+ t.Errorf("richText changed: %s", got)
+ }
+}
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html
index c05454b..5bc96d1 100644
--- a/internal/web/templates/partials/chat.html
+++ b/internal/web/templates/partials/chat.html
@@ -43,7 +43,7 @@
</div>
<div class="ask-chat" data-when="ready norunner oldrunner"{{if not (.Shows "ready norunner oldrunner")}} hidden{{end}}>
<div class="log"><ol class="thread" role="log" aria-label="Conversation"{{with .Zone}} data-zone="{{.}}"{{end}} data-mark="{{asset "static/oficina/equipo.svg"}}">
-{{range .Messages}}{{if eq .Role "person"}}<li class="msg person" data-id="{{.ID}}">{{$.Rich .Text}}</li>{{else}}<li class="msg coordinator" data-id="{{.ID}}">{{$.Rich .Text}}{{range $.OffersAt .ID}}<div class="connect-offer" data-card="{{.ID}}" data-revision="{{.Revision}}">{{template "ask-offer" .}}</div>{{end}}</li>{{end}}
+{{range .Messages}}{{if eq .Role "person"}}<li class="msg person" data-id="{{.ID}}">{{$.RichPerson .Text}}</li>{{else}}<li class="msg coordinator" data-id="{{.ID}}">{{$.Rich .Text}}{{range $.OffersAt .ID}}<div class="connect-offer" data-card="{{.ID}}" data-revision="{{.Revision}}">{{template "ask-offer" .}}</div>{{end}}</li>{{end}}
{{end}}{{with .Notice}}<li class="ask-notice" data-after="{{$.NoticeAfter}}">{{.}}</li>
{{end}}{{range .Jobs}}{{template "ask-job" .}}
{{end}}{{range .LooseCards}}{{template "ask-card" .}}
diff --git a/internal/web/testdata/person.json b/internal/web/testdata/person.json
new file mode 100644
index 0000000..b55cf2d
--- /dev/null
+++ b/internal/web/testdata/person.json
@@ -0,0 +1,66 @@
+[
+ {
+ "text": "**Bold** and *it*",
+ "html": "<strong>Bold</strong> and <em>it</em>"
+ },
+ {
+ "text": "*soon*, _later_ and **now**!",
+ "html": "<em>soon</em>, <em>later</em> and <strong>now</strong>!"
+ },
+ {
+ "text": "Two lines\nhere, 2*3 and a_b_c",
+ "html": "Two lines\nhere, 2*3 and a_b_c"
+ },
+ {
+ "text": "2*3*4",
+ "html": "2*3*4"
+ },
+ {
+ "text": "2*3 and 4*5, a*b + c*d",
+ "html": "2*3 and 4*5, a*b + c*d"
+ },
+ {
+ "text": "x**2 + y**2",
+ "html": "x**2 + y**2"
+ },
+ {
+ "text": "__init__.py and my_file_name.txt",
+ "html": "__init__.py and my_file_name.txt"
+ },
+ {
+ "text": "f(*args) and g(*rest)",
+ "html": "f(*args) and g(*rest)"
+ },
+ {
+ "text": "word*not*emphasis and *also*not",
+ "html": "word*not*emphasis and *also*not"
+ },
+ {
+ "text": "_private_ var and **kwargs",
+ "html": "<em>private</em> var and **kwargs"
+ },
+ {
+ "text": "1986. A great year",
+ "html": "1986. A great year"
+ },
+ {
+ "text": "3. Third\n4. Fourth",
+ "html": "<ol start=\"3\"><li>Third</li><li>Fourth</li></ol>"
+ },
+ {
+ "text": "Not code:\n indented four\n\tand a tab",
+ "html": "Not code:\n indented four\n\tand a tab"
+ },
+ {
+ "text": "# Not a heading\n> not a quote\n---\n+ not a bullet\nAT&amp;T <b>x</b>",
+ "html": "# Not a heading\n&gt; not a quote\n---\n+ not a bullet\nAT&amp;amp;T &lt;b&gt;x&lt;/b&gt;"
+ },
+ {
+ "text": "Shopping:\n- [Menu](https://fennel.example/menu)\n- [x](javascript:alert(1))",
+ "html": "Shopping:<ul><li><a href=\"https://fennel.example/menu\" target=\"_blank\" rel=\"noopener\">Menu</a></li><li>[x](javascript:alert(1))</li></ul>"
+ },
+ {
+ "text": "See https://fennel.example/menu.",
+ "html": "See <a href=\"https://fennel.example/menu\" target=\"_blank\" rel=\"noopener\">https://fennel.example/menu</a>."
+ }
+]
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift
index 5e6c107..62d393b 100644
--- a/native/apple/Sources/BaseKit/Ask/Composer.swift
+++ b/native/apple/Sources/BaseKit/Ask/Composer.swift
@@ -226,7 +226,7 @@ final class ComposerPaste: NSObject, UITextPasteDelegate {
func textPasteConfigurationSupporting(_ textPasteConfigurationSupporting: any UITextPasteConfigurationSupporting, transform item: UITextPasteItem) {
let provider = item.itemProvider
nonisolated(unsafe) let item = item
- for (type, convert) in [(UTType.html, { (data: Data) in String(data: data, encoding: .utf8).flatMap(PasteMarkdown.fromHTML) }),
+ for (type, convert) in [(UTType.html, { (data: Data) in PasteMarkdown.html(data).flatMap(PasteMarkdown.fromHTML) }),
(UTType.rtf, PasteMarkdown.fromRTF)] where provider.hasItemConformingToTypeIdentifier(type.identifier) {
provider.loadDataRepresentation(forTypeIdentifier: type.identifier) { data, _ in
if let markdown = data.flatMap(convert) { item.setResult(string: markdown) } else { item.setDefaultResult() }
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
index aa57725..e279fc9 100644
--- a/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
@@ -27,14 +27,24 @@ struct BaseMarkdownView: View {
initial.complete ? initial.tree : stream.visible(for: request) ?? initial.tree
}
- init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript, person: Bool = false) {
+ init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript) {
self.draft = draft
- self.person = person
+ person = false
request = MarkdownRenderCache.Request(messageID: id, text: text, draft: draft)
initial = MarkdownRenderCache.shared.initial(request)
stream = transcript.renderer(for: id)
}
+ /// Base: the person's own message, already in the web's little subset
+ /// (PersonMarkdown), never streamed.
+ init(person nodes: [ChatMarkdownNode], id: String, transcript: MarkdownTranscript) {
+ draft = false
+ person = true
+ request = MarkdownRenderCache.Request(messageID: "person:" + id, text: "", draft: false)
+ initial = MarkdownRenderCache.Result(tree: nodes, complete: true)
+ stream = transcript.renderer(for: "person:" + id)
+ }
+
var body: some View {
let p = Palette(scheme)
MarkdownRows(nodes: nodes)
@@ -43,8 +53,8 @@ struct BaseMarkdownView: View {
.tint(person ? p[.frost] : p[.focus])
.environment(\.markdownKeepsLines, person)
.textSelection(.enabled)
- .onAppear { stream.submit(request, needsParsing: !initial.complete) }
- .onChange(of: request) { stream.submit(request, needsParsing: !initial.complete) }
+ .onAppear { if !person { stream.submit(request, needsParsing: !initial.complete) } }
+ .onChange(of: request) { if !person { stream.submit(request, needsParsing: !initial.complete) } }
.environment(\.openURL, OpenURLAction { url in
guard let original = MarkdownActions.originalTarget(url, in: nodes),
case .external(let target)? = MarkdownActions.destination(original, origin: url) else { return .discarded }
@@ -71,8 +81,9 @@ private struct MarkdownRows: View {
}
extension EnvironmentValues {
- /// Base: a line break inside a paragraph stays one (the person's
- /// messages), where the Assistant's run on as Markdown's do.
+ /// Base: the text is as typed (the person's messages), where the
+ /// Assistant's runs of space and line breaks are one space, as
+ /// Markdown's are.
@Entry var markdownKeepsLines = false
}
@@ -90,10 +101,9 @@ private struct MarkdownBlock: View {
}
private func prose(_ text: String) -> String {
- if keepsLines {
- return text.replacingOccurrences(of: #"[ \t\f]*[\r\n][ \t\r\n\f]*"#, with: "\n", options: .regularExpression)
- .replacingOccurrences(of: #"[ \t\f]+"#, with: " ", options: .regularExpression)
- }
+ // Base: the person's words are as typed, spaces and lines and all,
+ // as the web's pre-wrap draws them.
+ if keepsLines { return text }
return text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression)
}
@@ -116,6 +126,13 @@ private struct MarkdownBlock: View {
if work.bold { intent.insert(.stronglyEmphasized) }
if work.italic { intent.insert(.emphasized) }
part.inlinePresentationIntent = intent
+ // Base: italics by the face's italic instance, which the
+ // emphasized intent can't find (it lands on another cut), so
+ // the run is set in that font alone (BaseFont.body).
+ if work.italic, node.kind != "code" {
+ part.font = BaseFont.body(15, work.bold ? .bold : .regular, italic: true)
+ part.inlinePresentationIntent = nil
+ }
if let target = work.link, ChatMarkdown.allowsLink(target) {
part.link = MarkdownActions.linkURL(target)
part.underlineStyle = .single
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
index cca98c7..3a99710 100644
--- a/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
@@ -8,9 +8,9 @@ import cmark_gfm
struct ChatMarkdownNode: Codable, Equatable, Sendable {
// Source anchors survive appended chunks and a fence's closing line.
var sourceOffset = 0
- enum CodingKeys: String, CodingKey { case kind, text, target, label, copy, copied, wrap, copyEnabled, children }
+ enum CodingKeys: String, CodingKey { case kind, text, target, label, copy, copied, wrap, copyEnabled, start, children }
static func == (lhs: Self, rhs: Self) -> Bool {
- lhs.kind == rhs.kind && lhs.text == rhs.text && lhs.target == rhs.target && lhs.label == rhs.label && lhs.copy == rhs.copy && lhs.copied == rhs.copied && lhs.wrap == rhs.wrap && lhs.copyEnabled == rhs.copyEnabled && lhs.children == rhs.children
+ lhs.kind == rhs.kind && lhs.text == rhs.text && lhs.target == rhs.target && lhs.label == rhs.label && lhs.copy == rhs.copy && lhs.copied == rhs.copied && lhs.wrap == rhs.wrap && lhs.copyEnabled == rhs.copyEnabled && lhs.start == rhs.start && lhs.children == rhs.children
}
var kind: String
var text: String?
@@ -20,6 +20,8 @@ struct ChatMarkdownNode: Codable, Equatable, Sendable {
var copied: String?
var wrap: Bool?
var copyEnabled: Bool?
+ /// Base: an ordered list's first number, when it isn't 1.
+ var start: Int?
var children: [ChatMarkdownNode] = []
}
@@ -100,14 +102,6 @@ enum ChatMarkdown {
return parse(source, draft: draft)
}
- /// Base: whether a tree is only words (paragraphs of text and line
- /// breaks): the person's message is then drawn exactly as written.
- static func isPlain(_ nodes: [ChatMarkdownNode]) -> Bool {
- nodes.allSatisfy { node in
- node.kind == "plain" || node.kind == "paragraph" && node.children.allSatisfy { $0.kind == "text" || $0.kind == "break" }
- }
- }
-
static func allowsLink(_ destination: String) -> Bool {
// Base: only absolute http(s) links, as ask.js's webURL and
// equipo.WebURL (Equipo's MarkdownLinks also allows its own paths
@@ -376,7 +370,11 @@ private struct MarkdownProjection {
case "heading": return [ChatMarkdownNode(kind: "paragraph", children: children(node))]
case "emph": return [ChatMarkdownNode(kind: "emphasis", children: children(node))]
case "strong": return [ChatMarkdownNode(kind: "strong", children: children(node))]
- case "list": return [ChatMarkdownNode(kind: cmark_node_get_list_type(node) == CMARK_ORDERED_LIST ? "ordered" : "unordered", children: children(node))]
+ case "list":
+ // Base: an ordered list keeps its first number.
+ let ordered = cmark_node_get_list_type(node) == CMARK_ORDERED_LIST
+ let start = Int(cmark_node_get_list_start(node))
+ return [ChatMarkdownNode(kind: ordered ? "ordered" : "unordered", start: ordered && start != 1 ? start : nil, children: children(node))]
case "item": return [ChatMarkdownNode(kind: "item", children: children(node))]
case "link":
// Goldmark's AutoLink is outside Render's vocabulary.
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift
index 98f51e3..0b3146e 100644
--- a/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/MarkdownPresentation.swift
@@ -3,7 +3,7 @@
// marked "Base:"; keep the rest in step with Equipo's.
import Foundation
-/// A flat list of layout rows. Depth changes indentation, never view nesting.
+/// A flat list of layout rows. Base: an ordered list counts from its start. Depth changes indentation, never view nesting.
/// Indentation stops at four levels so deeply nested replies remain readable
/// at phone width; every item and all of its content are still present.
enum MarkdownPresentation {
@@ -33,7 +33,7 @@ enum MarkdownPresentation {
let children = groups(item.children)
for (offset, child) in children.enumerated().reversed() {
stack.append(Row(node: child, indentation: row.indentation + 1,
- marker: offset == 0 ? (row.node.kind == "ordered" ? "\(index + 1)." : "•") : nil))
+ marker: offset == 0 ? (row.node.kind == "ordered" ? "\((row.node.start ?? 1) + index)." : "•") : nil))
}
}
} else {
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
new file mode 100644
index 0000000..e9db975
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/PersonMarkdown.swift
@@ -0,0 +1,127 @@
+import Foundation
+
+/// Base: the person's own message as the chat's Markdown tree, in the web's
+/// little subset (richText and personText in ask_cards.go, rich and
+/// strictEmphasis in ask.js), not CommonMark: runs of "- " or "* " lines
+/// are a bulleted list, runs of "1. " or "1) " lines (1 to 3 digits) a
+/// numbered one from its first number, 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 to an http(s) address, and
+/// between links **x** is bold and *x* or _x_ italic, only at word
+/// boundaries. Nothing else is Markdown: headings, quotes, rules, escapes,
+/// entities and indented code are text as typed. The samples in
+/// internal/web/testdata/person.json check the three agree.
+enum PersonMarkdown {
+ static func parse(_ text: String) -> [ChatMarkdownNode] {
+ var builder = Builder()
+ let lines = text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n")
+ .replacingOccurrences(of: "\0", with: "").components(separatedBy: "\n")
+ var out: [ChatMarkdownNode] = []
+ var i = 0
+ while i < lines.count {
+ guard let first = listLine(lines[i]) else {
+ var j = i + 1
+ while j < lines.count, listLine(lines[j]) == nil { j += 1 }
+ let inline = builder.inline(lines[i..<j].joined(separator: "\n"))
+ if !inline.isEmpty { out.append(builder.node("paragraph", children: inline)) }
+ i = j
+ continue
+ }
+ var items: [ChatMarkdownNode] = []
+ while i < lines.count, let line = listLine(lines[i]), line.ordered == first.ordered {
+ items.append(builder.node("item", children: builder.inline(line.item)))
+ i += 1
+ }
+ var list = builder.node(first.ordered ? "ordered" : "unordered", children: items)
+ if first.ordered, first.n != 1 { list.start = first.n }
+ out.append(list)
+ }
+ return out
+ }
+
+ /// Whether a tree is only words: the message is then drawn exactly as
+ /// written.
+ static func isPlain(_ nodes: [ChatMarkdownNode]) -> Bool {
+ nodes.allSatisfy { $0.kind == "paragraph" && $0.children.allSatisfy { $0.kind == "text" } }
+ }
+
+ private static let number = try! NSRegularExpression(pattern: #"^([0-9]{1,3})[.)] "#)
+
+ /// A line's list (numbered or not, its number) and the item after the
+ /// marker, which is never empty.
+ static func listLine(_ line: String) -> (ordered: Bool, n: Int, item: String)? {
+ let u = Array(line.utf8)
+ if u.count > 2, u[0] == UInt8(ascii: "-") || u[0] == UInt8(ascii: "*"), u[1] == UInt8(ascii: " ") {
+ return (false, 0, String(decoding: u[2...], as: UTF8.self))
+ }
+ if let m = number.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)),
+ let whole = Range(m.range, in: line), let digits = Range(m.range(at: 1), in: line), whole.upperBound < line.endIndex {
+ return (true, Int(line[digits]) ?? 1, String(line[whole.upperBound...]))
+ }
+ return nil
+ }
+
+ private static let link = try! NSRegularExpression(pattern: #"\[([^\[\]\n]{1,300})\]\(([^()\s]{1,1000})\)|https?://[^\s<>()\[\]"']+"#)
+
+ private struct Builder {
+ var offset = 0
+ /// Every node its own offset: the rows are told apart by it.
+ mutating func node(_ kind: String, text: String? = nil, target: String? = nil, children: [ChatMarkdownNode] = []) -> ChatMarkdownNode {
+ offset += 1
+ return ChatMarkdownNode(sourceOffset: offset, kind: kind, text: text, target: target, children: children)
+ }
+
+ mutating func inline(_ text: String) -> [ChatMarkdownNode] {
+ var out: [ChatMarkdownNode] = []
+ let ns = text as NSString
+ var last = 0
+ for m in PersonMarkdown.link.matches(in: text, range: NSRange(location: 0, length: ns.length)) {
+ var end = NSMaxRange(m.range), label: String, target: String
+ if m.range(at: 1).location != NSNotFound {
+ label = ns.substring(with: m.range(at: 1)); target = ns.substring(with: m.range(at: 2))
+ } else {
+ var bare = ns.substring(with: m.range)
+ while let c = bare.last, ".,;:!?".contains(c) { bare.removeLast() }
+ target = bare; label = bare; end = m.range.location + (bare as NSString).length
+ }
+ guard ChatMarkdown.allowsLink(target) else { continue }
+ out += emphasis(ns.substring(with: NSRange(location: last, length: m.range.location - last)))
+ out.append(node("link", target: target, children: [node("text", text: label)]))
+ last = end
+ }
+ out += emphasis(ns.substring(from: last))
+ return out
+ }
+
+ /// strictEmphasis in ask_cards.go, over Unicode scalars (a scalar
+ /// beyond ASCII is a word's, as any byte of one is there).
+ mutating func emphasis(_ text: String) -> [ChatMarkdownNode] {
+ let s = Array(text.unicodeScalars)
+ var out: [ChatMarkdownNode] = []
+ func str(_ r: Range<Int>) -> String { String(String.UnicodeScalarView(s[r])) }
+ func word(_ c: Unicode.Scalar) -> Bool { c.value >= 0x80 || c == "_" || ("0"..."9").contains(c) || ("a"..."z").contains(c) || ("A"..."Z").contains(c) }
+ func run(_ at: Int) -> Int { var n = 1; while at + n < s.count, s[at + n] == s[at] { n += 1 }; return n }
+ func emphasized(_ r: Range<Int>) -> Bool {
+ !r.isEmpty && !s[r].contains("\n") && s[r.lowerBound] != " " && s[r.lowerBound] != "\t" && s[r.upperBound - 1] != " " && s[r.upperBound - 1] != "\t"
+ }
+ var last = 0, i = 0
+ while i < s.count {
+ let c = s[i]
+ guard c == "*" || c == "_" else { i += 1; continue }
+ let n = run(i)
+ if i == 0 || !word(s[i - 1]), n == 1 || (n == 2 && c == "*"), let j = s[(i + n)...].firstIndex(of: c) {
+ let end = j + run(j)
+ if end - j == n, emphasized((i + n)..<j), end == s.count || !word(s[end]) {
+ if i > last { out.append(node("text", text: str(last..<i))) }
+ out.append(node(n == 2 ? "strong" : "emphasis", children: [node("text", text: str((i + n)..<j))]))
+ i = end; last = end
+ continue
+ }
+ }
+ i += n
+ }
+ if s.count > last { out.append(node("text", text: str(last..<s.count))) }
+ return out
+ }
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift
index 74c0a76..ac060fe 100644
--- a/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift
+++ b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift
@@ -9,17 +9,30 @@ import UIKit
/// bold (**x**), italics (*x*), links ([text](url), http(s) only, as
/// BaseJSON.webURL), bullet and numbered lists (nested by indent), headings
/// (# x), and line breaks and paragraphs. Everything else is its text. Nil
-/// when the paste formats nothing, so a plain paste stays exactly as
-/// copied. HTML is only tokenised here and walked (nothing loads or runs);
-/// RTF is read by Foundation, which loads nothing either. ask.js's
-/// pasteMarkdown is the same walk (keep them in step: the samples in
+/// when the paste formats nothing, or is mostly code (a monospace font, or
+/// pre, code, tt, samp, kbd; RTF in a fixed-pitch font), so a plain paste
+/// or code stays exactly as copied. HTML is only tokenised here and walked
+/// (nothing loads or runs): elements deeper than 32 are flattened, the
+/// walk stops once the Markdown passes the composer's 16,000 characters,
+/// and more than 2 MB of HTML is left plain. RTF is read by Foundation,
+/// which loads nothing either. ask.js's pasteMarkdown is the same walk
+/// (keep them in step: the samples in
/// internal/browsertest/testdata/paste.json check both).
enum PasteMarkdown {
+ static let maxDepth = 32, maxOut = 16_000, maxHTML = 2_000_000
+
static func fromHTML(_ html: String) -> String? {
+ guard html.utf16.count <= maxHTML else { return nil }
var walker = Walker()
return walker.markdown(HTMLTree.parse(html))
}
+ /// A clipboard's HTML bytes as text: UTF-8, or UTF-16 with its mark.
+ static func html(_ data: Data) -> String? {
+ if data.starts(with: [0xFF, 0xFE]) || data.starts(with: [0xFE, 0xFF]) { return String(data: data, encoding: .utf16) }
+ return String(data: data, encoding: .utf8)
+ }
+
static func fromRTF(_ data: Data) -> String? {
guard let text = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil) else { return nil }
return fromAttributed(text)
@@ -50,6 +63,10 @@ struct HTMLTree: Equatable {
static func parse(_ html: String) -> HTMLTree {
let s = Array(html.unicodeScalars)
var stack = [HTMLTree(tag: "body")]
+ // Elements opened past the depth cap: not in the tree (their text
+ // and line breaks go to the deepest one that is), but their end
+ // tags still match them.
+ var dropped: [String] = []
var at = 0
func appendText(_ t: String) {
guard !t.isEmpty else { return }
@@ -118,7 +135,7 @@ struct HTMLTree: Equatable {
at = min(s.count, cursor + 1)
appendText(text); text = ""
if closing {
- if let index = open(name), index > 0 { close(index) }
+ if dropped.last == name { dropped.removeLast() } else if let index = open(name), index > 0 { close(index) }
continue
}
if closesP.contains(name), let p = open("p"), !(stack[(p + 1)...].contains { $0.tag == "li" || $0.tag == "td" || $0.tag == "th" }) { close(p) }
@@ -142,6 +159,8 @@ struct HTMLTree: Equatable {
}
if void.contains(name) || selfClosing {
stack[stack.count - 1].children.append(element)
+ } else if stack.count > PasteMarkdown.maxDepth {
+ dropped.append(name)
} else {
stack.append(element)
}
@@ -183,9 +202,10 @@ struct HTMLTree: Equatable {
let href = (link as? URL)?.absoluteString ?? (link as? String) ?? ""
node = HTMLTree(tag: "a", attributes: ["href": href], children: [node])
}
- let (bold, italic) = traits(attributes)
+ let (bold, italic, mono) = traits(attributes)
if italic { node = HTMLTree(tag: "i", children: [node]) }
if bold { node = HTMLTree(tag: "b", children: [node]) }
+ if mono { node = HTMLTree(tag: "code", children: [node]) }
line.children.append(node)
}
} else if textLists.isEmpty {
@@ -212,17 +232,17 @@ struct HTMLTree: Equatable {
!["disc", "circle", "square", "box", "check", "diamond", "hyphen"].contains { list.markerFormat.rawValue.contains($0) }
}
- private static func traits(_ attributes: [NSAttributedString.Key: Any]) -> (bold: Bool, italic: Bool) {
+ private static func traits(_ attributes: [NSAttributedString.Key: Any]) -> (bold: Bool, italic: Bool, mono: Bool) {
#if os(macOS)
- guard let font = attributes[.font] as? NSFont else { return (false, false) }
+ guard let font = attributes[.font] as? NSFont else { return (false, false, false) }
let t = font.fontDescriptor.symbolicTraits
- return (t.contains(.bold), t.contains(.italic))
+ return (t.contains(.bold), t.contains(.italic), t.contains(.monoSpace) || font.isFixedPitch)
#elseif os(iOS)
- guard let font = attributes[.font] as? UIFont else { return (false, false) }
+ guard let font = attributes[.font] as? UIFont else { return (false, false, false) }
let t = font.fontDescriptor.symbolicTraits
- return (t.contains(.traitBold), t.contains(.traitItalic))
+ return (t.contains(.traitBold), t.contains(.traitItalic), t.contains(.traitMonoSpace))
#else
- return (false, false)
+ return (false, false, false)
#endif
}
}
@@ -230,7 +250,10 @@ struct HTMLTree: Equatable {
/// ask.js's pasteMarkdown walk, line for line.
private struct Walker {
struct Run { var text: String; var bold: Bool; var italic: Bool; var href: String }
- struct Style { var bold = false, italic = false, href = "", heading = false, pre = false }
+ struct Style { var bold = false, italic = false, href = "", heading = false, pre = false, mono = false }
+ static let code: Set<String> = ["pre", "code", "tt", "samp", "kbd"]
+ static let raw: Set<String> = ["script", "style", "textarea", "title", "template", "noscript", "iframe"]
+ static let monoFont = try! NSRegularExpression(pattern: "monospace|menlo|monaco|consolas|courier|sf ?mono|fira (code|mono)|jetbrains|source code|cascadia|ubuntu mono|dejavu sans mono|roboto mono|plex mono|andale mono|lucida console", options: .caseInsensitive)
final class List { let ordered: Bool; var n: Int; let indent: String; var inner: String
init(ordered: Bool, n: Int, indent: String) { self.ordered = ordered; self.n = n; self.indent = indent; inner = indent }
}
@@ -244,11 +267,13 @@ private struct Walker {
var indent = ""
var formatted = false
var lists: [List] = []
+ /// Characters of text (not spaces), and how many of them are code's.
+ var chars = 0, mono = 0
mutating func markdown(_ tree: HTMLTree) -> String? {
- walk(tree, Style())
+ walk(tree, Style(), depth: -1)
flush()
- guard formatted else { return nil }
+ guard formatted, mono * 2 <= chars else { return nil }
let trimmed = out.components(separatedBy: "\n").map { line in
var line = line
while line.last == " " || line.last == "\t" { line.removeLast() }
@@ -282,8 +307,12 @@ private struct Walker {
while have < n { out += "\n"; have += 1 }
}
- mutating func walk(_ node: HTMLTree, _ st: Style) {
+ mutating func walk(_ node: HTMLTree, _ st: Style, depth: Int) {
+ if out.utf16.count > PasteMarkdown.maxOut { return }
if node.tag.isEmpty {
+ let counted = node.text.unicodeScalars.reduce(0) { $0 + ($1.properties.isWhitespace ? 0 : $1.utf16.count) }
+ chars += counted
+ if st.mono { mono += counted }
if st.pre {
let parts = node.text.replacingOccurrences(of: "\r\n", with: "\n").replacingOccurrences(of: "\r", with: "\n").components(separatedBy: "\n")
for (i, part) in parts.enumerated() {
@@ -299,24 +328,30 @@ private struct Walker {
return
}
let tag = node.tag
- if Self.skip.contains(tag) { return }
if tag == "br" {
flush()
if !out.isEmpty { out += "\n"; open = false }
return
}
+ // (The body is depth -1; its children 0. HTMLTree.parse never makes
+ // anything deeper than the cap.)
+ if Self.skip.contains(tag) { return }
var next = st
if tag == "b" || tag == "strong" { next.bold = true }
if tag == "i" || tag == "em" { next.italic = true }
+ if Self.code.contains(tag) { next.mono = true }
let style = node.attributes["style"] ?? ""
- if let weight = Self.first(#"(?i)font-weight\s*:\s*([a-z0-9]+)"#, in: style) {
+ if let weight = Self.declared(style, "font-weight") {
next.bold = weight.range(of: "^(bold|bolder|[6-9]00)$", options: [.regularExpression, .caseInsensitive]) != nil
}
- if let slant = Self.first(#"(?i)font-style\s*:\s*([a-z]+)"#, in: style) {
- next.italic = slant.range(of: "^(italic|oblique)$", options: [.regularExpression, .caseInsensitive]) != nil
+ if let slant = Self.declared(style, "font-style") {
+ next.italic = slant.range(of: "^(italic|oblique)", options: [.regularExpression, .caseInsensitive]) != nil
+ }
+ if let family = Self.declared(style, "font-family") {
+ next.mono = Self.monoFont.firstMatch(in: family, range: NSRange(family.startIndex..., in: family)) != nil
}
- if tag == "a", st.href.isEmpty { next.href = BaseJSON.webURL(node.attributes["href"] ?? "")?.absoluteString ?? "" }
- func children(_ w: inout Walker) { for c in node.children { w.walk(c, next) } }
+ if tag == "a", st.href.isEmpty { next.href = Self.link(node.attributes["href"] ?? "") }
+ func children(_ w: inout Walker) { for c in node.children { w.walk(c, next, depth: depth + 1) } }
if tag.count == 2, tag.first == "h", let level = Int(String(tag.last!)), (1...6).contains(level) {
ensure(2)
@@ -408,7 +443,7 @@ private struct Walker {
if !r.href.isEmpty {
let label = core.replacingOccurrences(of: "[", with: "").replacingOccurrences(of: "]", with: "")
let href = r.href.replacingOccurrences(of: "(", with: "%28").replacingOccurrences(of: ")", with: "%29")
- s += lead + (label == r.href ? href : "[\(label)](\(href))") + trail
+ s += lead + (label == r.href ? href : label.utf16.count > 300 ? "\(label) (\(href))" : "[\(label)](\(href))") + trail
formatted = true
} else if r.bold || r.italic {
let mark = r.bold ? "**" : "*"
@@ -422,10 +457,20 @@ private struct Walker {
return s
}
- static func first(_ pattern: String, in text: String) -> String? {
- guard let re = try? NSRegularExpression(pattern: pattern),
- let m = re.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)), m.numberOfRanges > 1,
- let r = Range(m.range(at: 1), in: text) else { return nil }
- return String(text[r])
+ /// A declaration's value in a style attribute (never
+ /// mso-bidi-font-weight and the like).
+ static func declared(_ style: String, _ name: String) -> String? {
+ guard let re = try? NSRegularExpression(pattern: "(?:^|;)\\s*\(name)\\s*:\\s*([^;]*)", options: .caseInsensitive),
+ let m = re.firstMatch(in: style, range: NSRange(style.startIndex..., in: style)),
+ let r = Range(m.range(at: 1), in: style) else { return nil }
+ return style[r].trimmingCharacters(in: .whitespaces)
+ }
+
+ /// An href as a page reads it (spaces at its ends go, tabs and line
+ /// breaks in it go, other spaces are escaped), if it is http(s).
+ static func link(_ href: String) -> String {
+ let cleaned = href.trimmingCharacters(in: .whitespacesAndNewlines).filter { $0 != "\t" && $0 != "\n" && $0 != "\r" }
+ guard let url = URL(string: cleaned, encodingInvalidCharacters: true) else { return "" }
+ return BaseJSON.webURL(url.absoluteString)?.absoluteString ?? ""
}
}
diff --git a/native/apple/Sources/BaseKit/Ask/Thread.swift b/native/apple/Sources/BaseKit/Ask/Thread.swift
index f57fb05..4d8d9d1 100644
--- a/native/apple/Sources/BaseKit/Ask/Thread.swift
+++ b/native/apple/Sources/BaseKit/Ask/Thread.swift
@@ -87,12 +87,12 @@ struct AskThread: View {
switch entry {
case .message(let m):
Bubble(person: m.isPerson, maxWidth: bubbleWidth) {
- // The person's own words take the Assistant's little
- // Markdown too; with none, they are exactly as written.
- if m.isPerson, ChatMarkdown.isPlain(MarkdownRenderCache.shared.initial(.init(messageID: m.id, text: m.text, draft: false)).tree) {
- Text(verbatim: m.text).font(BaseFont.body(15)).fixedSize(horizontal: false, vertical: true)
+ // The person's own words take the web's little Markdown
+ // (PersonMarkdown); with none, they are exactly as written.
+ if m.isPerson, case let nodes = PersonMarkdown.parse(m.text), !PersonMarkdown.isPlain(nodes) {
+ BaseMarkdownView(person: nodes, id: m.id, transcript: transcript)
} else if m.isPerson {
- BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript, person: true)
+ Text(verbatim: m.text).font(BaseFont.body(15)).fixedSize(horizontal: false, vertical: true)
} else {
BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript)
}
diff --git a/native/apple/Sources/BaseKit/Look/Type.swift b/native/apple/Sources/BaseKit/Look/Type.swift
index c97d903..c37c162 100644
--- a/native/apple/Sources/BaseKit/Look/Type.swift
+++ b/native/apple/Sources/BaseKit/Look/Type.swift
@@ -55,9 +55,12 @@ public enum BaseFonts {
/// The PostScript name of a named instance: Timeless Sans's cuts and
/// weights, or DM Sans's.
- static func postScriptName(grotesk: Bool, weight: BaseFont.Weight, face: Face) -> String? {
+ static func postScriptName(grotesk: Bool, weight: BaseFont.Weight, face: Face, italic: Bool = false) -> String? {
switch face {
- case .timeless: return "TimelessSans-\(grotesk ? "Grotesk" : "Sans")\(weight.timeless)"
+ // Timeless Sans's italics are named instances on its ital axis
+ // (TimelessSans-SansRegularItalic and its siblings); none carries
+ // the italic trait, so SwiftUI's own italic never finds them.
+ case .timeless: return "TimelessSans-\(grotesk ? "Grotesk" : "Sans")\(weight.timeless)\(italic ? "Italic" : "")"
case .dmSans: return "DMSans-9ptRegular_\(weight.dmSans)"
case .system: return nil
}
@@ -85,15 +88,20 @@ public enum BaseFont {
font(size, weight, grotesk: true, style)
}
- /// The Sans cut: everything else.
- public static func body(_ size: CGFloat, _ weight: Weight = .regular, relativeTo style: Font.TextStyle = .body) -> Font {
- font(size, weight, grotesk: false, style)
+ /// The Sans cut: everything else. `italic`: Timeless Sans's own
+ /// italic instance; DM Sans, which has none bundled, and the system
+ /// face slant as SwiftUI's italic does.
+ public static func body(_ size: CGFloat, _ weight: Weight = .regular, italic: Bool = false, relativeTo style: Font.TextStyle = .body) -> Font {
+ font(size, weight, grotesk: false, style, italic: italic)
}
- static func font(_ size: CGFloat, _ weight: Weight, grotesk: Bool, _ style: Font.TextStyle) -> Font {
- guard let name = BaseFonts.postScriptName(grotesk: grotesk, weight: weight, face: BaseFonts.face) else {
- return .system(size: size, weight: weight.system)
+ static func font(_ size: CGFloat, _ weight: Weight, grotesk: Bool, _ style: Font.TextStyle, italic: Bool = false) -> Font {
+ let face = BaseFonts.face
+ guard let name = BaseFonts.postScriptName(grotesk: grotesk, weight: weight, face: face, italic: italic) else {
+ let system = Font.system(size: size, weight: weight.system)
+ return italic ? system.italic() : system
}
- return .custom(name, size: size, relativeTo: style)
+ let font = Font.custom(name, size: size, relativeTo: style)
+ return italic && face != .timeless ? font.italic() : font
}
}
diff --git a/native/apple/Tests/BaseKitTests/AskViewTests.swift b/native/apple/Tests/BaseKitTests/AskViewTests.swift
index 566b464..b061b0b 100644
--- a/native/apple/Tests/BaseKitTests/AskViewTests.swift
+++ b/native/apple/Tests/BaseKitTests/AskViewTests.swift
@@ -78,14 +78,49 @@ extension AskViewTests {
}
extension AskViewTests {
- /// The person's messages take the Assistant's Markdown (2026-11-26);
- /// words with none are drawn exactly as written.
+ /// The person's messages take the web's little Markdown (2026-11-26);
+ /// words with none are drawn exactly as written (Fable's S4).
func testThePersonsPlainWordsStayPlain() {
- for plain in ["What's on tomorrow?", "2*3 and a_b_c", "Two lines\nhere", "# Not a heading here", "Gap\n\nbetween", " indented"] {
- XCTAssertTrue(ChatMarkdown.isPlain(ChatMarkdown.parse(plain, draft: false)), plain)
+ for plain in ["What's on tomorrow?", "2*3 and a_b_c", "2*3*4", "a*b + c*d", "x**2 + y**2", "__init__.py", "f(*args) and g(*rest)",
+ "Two lines\nhere", "# Not a heading", "> not a quote", "Gap\n\nbetween", " indented", "1986. A great year", "+ item", "AT&amp;T \\*x"] {
+ XCTAssertTrue(PersonMarkdown.isPlain(PersonMarkdown.parse(plain)), plain)
}
- for rich in ["**Bold**", "*it*", "- a\n- b", "1. One", "[Menu](https://fennel.example/menu)"] {
- XCTAssertFalse(ChatMarkdown.isPlain(ChatMarkdown.parse(rich, draft: false)), rich)
+ for rich in ["**Bold**", "*it*", "_it_", "- a\n- b", "1. One", "[Menu](https://fennel.example/menu)", "https://fennel.example/menu"] {
+ XCTAssertFalse(PersonMarkdown.isPlain(PersonMarkdown.parse(rich)), rich)
}
}
+
+ /// The web's server draws each of these (TestPersonText); the app's
+ /// tree, written out the same way, must be the same.
+ func testThePersonsMarkdownMatchesTheWeb() throws {
+ struct Case: Decodable { let text: String; let html: String }
+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let cases = try JSONDecoder().decode([Case].self, from: Data(contentsOf: root.appendingPathComponent("internal/web/testdata/person.json")))
+ XCTAssertGreaterThan(cases.count, 10)
+ func escape(_ s: String) -> String {
+ s.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;").replacingOccurrences(of: ">", with: "&gt;")
+ .replacingOccurrences(of: "'", with: "&#39;").replacingOccurrences(of: "\"", with: "&#34;")
+ }
+ func html(_ nodes: [ChatMarkdownNode]) -> String {
+ nodes.map { n in
+ switch n.kind {
+ case "text": escape(n.text ?? "")
+ case "strong": "<strong>\(html(n.children))</strong>"
+ case "emphasis": "<em>\(html(n.children))</em>"
+ case "link": "<a href=\"\(escape(n.target ?? ""))\" target=\"_blank\" rel=\"noopener\">\(html(n.children))</a>"
+ case "unordered": "<ul>\(html(n.children))</ul>"
+ case "ordered": (n.start.map { "<ol start=\"\($0)\">" } ?? "<ol>") + html(n.children) + "</ol>"
+ case "item": "<li>\(html(n.children))</li>"
+ default: html(n.children)
+ }
+ }.joined()
+ }
+ for c in cases {
+ XCTAssertEqual(html(PersonMarkdown.parse(c.text)), c.html, c.text)
+ }
+ // A numbered list counts from its first number, the Assistant's too.
+ XCTAssertEqual(MarkdownPresentation.rows(PersonMarkdown.parse("3. Third\n4. Fourth")).map(\.marker), ["3.", "4."])
+ XCTAssertEqual(MarkdownPresentation.rows(ChatMarkdown.parse("3. Third\n4. Fourth", draft: false)).map(\.marker), ["3.", "4."])
+ }
}
diff --git a/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift b/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift
index 4545511..7a9446d 100644
--- a/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift
+++ b/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift
@@ -11,7 +11,7 @@ import UIKit
/// samples are the web's too (internal/browsertest/testdata/paste.json,
/// TestAskPasteMarkdown): both converters must agree on every one.
final class PasteMarkdownTests: XCTestCase {
- struct Sample: Decodable { let name: String; let html: String; let markdown: String? }
+ struct Sample: Decodable { let name: String; let html: String?; let rtf: String?; let markdown: String? }
func testTheSharedSamples() throws {
let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
@@ -20,10 +20,43 @@ final class PasteMarkdownTests: XCTestCase {
let samples = try JSONDecoder().decode([Sample].self, from: data)
XCTAssertGreaterThan(samples.count, 5)
for sample in samples {
- XCTAssertEqual(PasteMarkdown.fromHTML(sample.html), sample.markdown, sample.name)
+ if let html = sample.html { XCTAssertEqual(PasteMarkdown.fromHTML(html), sample.markdown, sample.name) }
+ if let rtf = sample.rtf { XCTAssertEqual(PasteMarkdown.fromRTF(Data(rtf.utf8)), sample.markdown, sample.name) }
}
}
+ /// Fable's S5: a hostile clipboard (a page's copy handler can put any
+ /// HTML there) never crashes or stalls the paste, even on the iPhone's
+ /// 512 KB item-provider thread: nesting is flattened past 32 levels
+ /// and the walk stops at the field's 16,000 characters.
+ func testHostileClipboardsOnASmallStack() {
+ func onSmallStack(_ work: @escaping @Sendable () -> Void) {
+ let done = DispatchSemaphore(value: 0)
+ let thread = Thread { work(); done.signal() }
+ thread.stackSize = 512 * 1024
+ thread.start()
+ XCTAssertEqual(done.wait(timeout: .now() + 20), .success, "the paste stalled")
+ }
+ onSmallStack {
+ let deep = String(repeating: "<div><b>", count: 100_000) + "deep" + String(repeating: "</b></div>", count: 100_000)
+ XCTAssertEqual(PasteMarkdown.fromHTML(deep), "**deep**")
+ }
+ onSmallStack {
+ let lists = String(repeating: "<ul><li>item", count: 2_000)
+ let out = PasteMarkdown.fromHTML(lists) ?? ""
+ XCTAssertTrue(out.hasPrefix("- item\n - item"), String(out.prefix(40)))
+ XCTAssertLessThan(out.utf16.count, 16_000 + 200, "bounded")
+ }
+ onSmallStack {
+ let start = Date()
+ let stray = String(repeating: "<b>", count: 20_000) + "x" + String(repeating: "</i>", count: 20_000)
+ XCTAssertEqual(PasteMarkdown.fromHTML(stray), "**x**")
+ XCTAssertLessThan(Date().timeIntervalSince(start), 2)
+ }
+ let huge = "<b>x</b>" + String(repeating: "y", count: PasteMarkdown.maxHTML)
+ XCTAssertNil(PasteMarkdown.fromHTML(huge), "over 2 MB of HTML is pasted plain")
+ }
+
func testPlainHTMLIsLeftAlone() {
XCTAssertNil(PasteMarkdown.fromHTML("<p>Just words, 2*3 and *stars*</p><p>Two lines</p>"))
XCTAssertNil(PasteMarkdown.fromHTML(""))
diff --git a/native/apple/Tests/BaseKitTests/TypeTests.swift b/native/apple/Tests/BaseKitTests/TypeTests.swift
index 3fdf35a..538f63b 100644
--- a/native/apple/Tests/BaseKitTests/TypeTests.swift
+++ b/native/apple/Tests/BaseKitTests/TypeTests.swift
@@ -30,6 +30,9 @@ final class TypeTests: XCTestCase {
XCTAssertEqual(CTFontCopyFamilyName(font) as String, "Timeless Sans")
// Grotesk is STYL 0, Sans STYL 100 (app.css's font-variation-settings).
if let value = axis(name, styl) { XCTAssertEqual(value, grotesk ? 0 : 100, name) }
+ // Fable's N4: each has its italic, by name.
+ let italic = try XCTUnwrap(BaseFonts.postScriptName(grotesk: grotesk, weight: weight, face: .timeless, italic: true))
+ XCTAssertEqual(CTFontCopyPostScriptName(CTFontCreateWithName(italic as CFString, 16, nil)) as String, italic, "\(italic) does not resolve")
}
}
}
diff --git a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
index 0a46d47..365d5f2 100644
--- a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
+++ b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
@@ -158,7 +158,7 @@ struct AskFrame<Content: View>: View {
static func personMarkdown() -> AskModel {
model(state: "ready", extra: #"""
{"id":"m1","role":"person","text":"**Christmas menu** for the bakery, *draft two*:\n- Mince pies, [see the recipe](https://fennel.example/menu/pies)\n- **Stollen**\n\nAna signs it off\non Friday.","turn_id":"t1"},
- {"id":"m2","role":"assistant","text":"Got it. I'll add **both** to the menu.","turn_id":"t1"},
+ {"id":"m2","role":"assistant","text":"Got it. I'll add **both** to the *Christmas* menu.","turn_id":"t1"},
{"id":"m3","role":"person","text":"Two lines,\n2*3 and a_b_c stay as typed.","turn_id":"t2"}
"""#)
}
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png
index 267b702..c7dcefc 100644
Binary files a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png
index 70880b4..457261b 100644
Binary files a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png
index fbac551..d4868e1 100644
Binary files a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-ax3.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png
index 6b4114d..31b9ef1 100644
Binary files a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/iphone/person-markdown-light-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png
index 0ae8453..b3539c1 100644
Binary files a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-dark-default.png differ
diff --git a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png
index b471977..60058eb 100644
Binary files a/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png differ