oficina / base Public

Ask: the person's messages in Markdown, and rich paste as Markdown

One converter, written twice (ask.js pasteMarkdown, PasteMarkdown.swift),
checked against the same real-world samples in
internal/browsertest/testdata/paste.json: a Google Docs fragment, a Docs
nested list, a web page, Apple Mail, nested lists, javascript: and
userinfo links dropped, headings, spacing, editor code (null), a bare link.

Tests: TestAskPasteMarkdown and TestAskPersonMarkdown (Chromium),
TestAskPersonMessagesAreMarkdown (server), PasteMarkdownTests (samples +
RTF), ComposerKeyTests.testARichPasteIsMarkdown (hosted field, private
pasteboard, Undo/Redo), testThePersonsPlainWordsStayPlain, and the
person-markdown snapshot (Mac and iPhone, light/dark, AX3).

No new user-facing strings.

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

Summary

The person's own messages are drawn with the Assistant's little Markdown and safe-link rules: on the web the server's $.Rich and ask.js's rich for both roles (person links keep the bubble's ink); natively BaseMarkdownView with the person's line breaks kept, and plain words (no Markdown in the parsed tree) still Text(verbatim:), so every existing snapshot is unchanged. A rich paste (HTML, or RTF natively) into the composer becomes Markdown: bold, italics, http(s) links, nested bullet/numbered lists, headings, lines and paragraphs; a paste that formats nothing is left as copied. Web: a paste handler with a DOMParser walk, inserted with insertText (Undo works). Mac: the field pastes plain text with no hook before it, so a text-change observer swaps the just-pasted plain text for the Markdown in the same undo group. iPhone/iPad: a UITextPasteDelegate on the field's text view.
claude agent, operated by paul@keymail.dev cbb287333b07367622a7796875ae85282a488db3 parent e700f1d
21 files changed, +1,089 −18
  • internal/browsertest/paste_test.go +131 −0
  • internal/browsertest/testdata/paste.json +52 −0
  • internal/look/static/app.css +7 −4
  • internal/look/static/ask.js +197 −9
  • internal/web/templates/partials/chat.html +1 −1
  • internal/webtest/ask_test.go +25 −0
  • native/apple/Sources/BaseKit/Ask/Composer.swift +82 −0
  • native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift +19 −3
  • native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift +8 −0
  • native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift +431 −0
  • native/apple/Sources/BaseKit/Ask/Thread.swift +5 −1
  • native/apple/Tests/BaseKitTests/AskViewTests.swift +13 −0
  • native/apple/Tests/BaseKitTests/ComposerTests.swift +37 −0
  • native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift +67 −0
  • native/apple/Tests/BaseSnapshots/AskSnapshots.swift +14 −0
  • 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 ===
10:10AM INF Unknown SCM platform. Use --platform to include links in findings. host=amadan.net
10:10AM INF 1 commits scanned.
10:10AM INF scanned ~2449889 bytes (2.45 MB) in 237ms
10:10AM 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 7.277s 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.076s amadan.net/oficina/base/internal/webtest
receipt: slow package 594ms amadan.net/oficina/base/internal/operations
receipt: slow package 343ms amadan.net/oficina/base/internal/issuer
receipt: slow package 202ms amadan.net/oficina/base/internal/consumer
receipt: slow package 161ms amadan.net/oficina/base/internal/web
receipt: slow test 1.51s amadan.net/oficina/base/internal/webtest TestHomeDoesNotWaitOnAStalledSnapshot
receipt: slow test 1.08s amadan.net/oficina/base/internal/webtest TestAskZoneIsToldOnce
receipt: slow test 510ms amadan.net/oficina/base/internal/operations TestOperationsRefusals
receipt: slow test 260ms amadan.net/oficina/base/internal/issuer TestAuthorizeRefusals
receipt: slow test 220ms amadan.net/oficina/base/internal/webtest TestAskZoneAgainOnANewConnection
=== 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
new file mode 100644
index 0000000..24704d0
--- /dev/null
+++ b/internal/browsertest/paste_test.go
@@ -0,0 +1,131 @@
+//go:build browser
+
+package browsertest
+
+import (
+ "encoding/json"
+ "os"
+ "strconv"
+ "testing"
+ "time"
+
+ "github.com/chromedp/chromedp"
+
+ "amadan.net/rastrillo/rastrillo/harness"
+)
+
+// pasteSample is one of testdata/paste.json's clipboards: its HTML and the
+// Markdown it pastes as (null: the plain text, left to the browser). The
+// app's PasteMarkdownTests check the same samples.
+type pasteSample struct {
+ Name string `json:"name"`
+ HTML string `json:"html"`
+ Markdown *string `json:"markdown"`
+}
+
+// A rich paste into the composer becomes the Markdown the chat draws (Paul,
+// 2026-11-26), and Undo takes it back; a paste whose HTML formats nothing
+// is the browser's own.
+func TestAskPasteMarkdown(t *testing.T) {
+ raw, err := os.ReadFile("testdata/paste.json")
+ if err != nil {
+ t.Fatal(err)
+ }
+ var samples []pasteSample
+ if err := json.Unmarshal(raw, &samples); err != nil {
+ t.Fatal(err)
+ }
+ rig, _ := askBase(t)
+ openPanel(t, rig)
+ type result struct {
+ Prevented bool `json:"prevented"`
+ Value string `json:"value"`
+ }
+ paste := func(before, html string) result {
+ t.Helper()
+ js := `(() => {
+ const f = document.querySelector("#ask-text");
+ f.focus(); f.value = ` + strconv.Quote(before) + `; f.setSelectionRange(f.value.length, f.value.length);
+ const data = new DataTransfer();
+ data.setData("text/html", ` + strconv.Quote(html) + `);
+ data.setData("text/plain", "plain");
+ const e = new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true });
+ f.dispatchEvent(e);
+ return JSON.stringify({ prevented: e.defaultPrevented, value: f.value });
+ })()`
+ var r result
+ if err := json.Unmarshal([]byte(harness.Evaluate[string](rig, js)), &r); err != nil {
+ t.Fatal(err)
+ }
+ return r
+ }
+ for _, s := range samples {
+ got := paste("", s.HTML)
+ switch {
+ case s.Markdown == nil && (got.Prevented || got.Value != ""):
+ t.Errorf("%s: pasted %q, want the browser's own paste", s.Name, got.Value)
+ case s.Markdown != nil && (!got.Prevented || got.Value != *s.Markdown):
+ t.Errorf("%s:\n got %q\nwant %q", s.Name, got.Value, *s.Markdown)
+ }
+ }
+ // At the cursor, after what is there; and Undo takes the paste back.
+ if got := paste("Note: ", samples[0].HTML); got.Value != "Note: "+*samples[0].Markdown {
+ t.Errorf("pasted after text: %q", got.Value)
+ }
+ if got := harness.Evaluate[string](rig, `(document.execCommand("undo"), document.querySelector("#ask-text").value)`); got != "Note: " {
+ t.Errorf("after Undo: %q", 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.
+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",
+ }
+ rig, _ := askBase(t)
+ openPanel(t, rig)
+ for i, s := range said {
+ drive(t, rig, chromedp.Evaluate[chromedp.Void](`(() => { const f = document.querySelector("#ask-text"); f.value = `+strconv.Quote(s)+`;
+ f.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector("#ask-panel form.composer").requestSubmit() })()`))
+ n := strconv.Itoa(i + 1)
+ drive(t, rig, chromedp.Poll[chromedp.Void](`document.querySelectorAll("#ask-panel .msg.person").length === `+n+
+ ` && document.querySelectorAll("#ask-panel .msg.coordinator").length === `+n+` && document.querySelector("#ask-panel button.stop").hidden`,
+ 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.person")) {
+ const s = page.querySelector('.msg.person[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 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)
+ }
+ // Their links keep the bubble's ink; their lists have markers.
+ if got := harness.Evaluate[string](rig, `(() => {
+ const a = document.querySelector("#ask-panel .msg.person a"), p = [];
+ if (getComputedStyle(a).color !== getComputedStyle(a.closest(".msg")).color) p.push("link colour " + getComputedStyle(a).color);
+ for (const l of document.querySelectorAll("#ask-panel .msg.person ul, #ask-panel .msg.person ol"))
+ if (!/^(disc|decimal)$/.test(getComputedStyle(l).listStyleType)) p.push(l.tagName + " " + getComputedStyle(l).listStyleType);
+ return p.join("; ");
+ })()`); got != "" {
+ t.Errorf("person styles: %s", got)
+ }
+ rig.Screen("#ask-panel", "the person's messages in simple Markdown")
+}
diff --git a/internal/browsertest/testdata/paste.json b/internal/browsertest/testdata/paste.json
new file mode 100644
index 0000000..d96f54c
--- /dev/null
+++ b/internal/browsertest/testdata/paste.json
@@ -0,0 +1,52 @@
+[
+ {
+ "name": "Google Docs: spans, a link and a list",
+ "html": "<meta charset=\"utf-8\"><b style=\"font-weight:normal;\" id=\"docs-internal-guid-1a2b3c4d-7fff-1234-5678-9abcdef01234\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:700;font-style:normal;\">Christmas menu</span><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\"> for the bakery, </span><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:italic;\">draft two</span></p><br><ul style=\"margin-top:0;margin-bottom:0;padding-inline-start:48px;\"><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\">Mince pies, </span><a href=\"https://fennel.example/menu/pies\" style=\"text-decoration:none;\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#1155cc;background-color:transparent;font-variant:normal;text-decoration:underline;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\">see the recipe</span></a></p></li><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:700;font-style:normal;\">Stollen</span></p></li></ul><br><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;font-style:normal;\">Ana signs it off on Friday.</span></p></b><br class=\"Apple-interchange-newline\">",
+ "markdown": "**Christmas menu** for the bakery, *draft two*\n\n- Mince pies, [see the recipe](https://fennel.example/menu/pies)\n- **Stollen**\n\nAna signs it off on Friday."
+ },
+ {
+ "name": "Google Docs: a nested list, flat as Docs writes it",
+ "html": "<meta charset=\"utf-8\"><b style=\"font-weight:normal;\" id=\"docs-internal-guid-2b\"><ul style=\"margin-top:0;margin-bottom:0;\"><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;\">Bread</span></p></li><ul style=\"margin-top:0;margin-bottom:0;\"><li dir=\"ltr\" style=\"list-style-type:circle;\" aria-level=\"2\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;\">Rye</span></p></li></ul><li dir=\"ltr\" style=\"list-style-type:disc;font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-weight:400;font-style:normal;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;\" aria-level=\"1\"><p dir=\"ltr\" style=\"line-height:1.38;margin-top:0pt;margin-bottom:0pt;\" role=\"presentation\"><span style=\"font-size:11pt;font-family:Arial,sans-serif;color:#000000;background-color:transparent;font-variant:normal;text-decoration:none;vertical-align:baseline;white-space:pre;white-space:pre-wrap;font-weight:400;\">Cakes</span></p></li></ul></b>",
+ "markdown": "- Bread\n - Rye\n- Cakes"
+ },
+ {
+ "name": "A web page: a heading, links (one relative, one mailto) and a list from 3",
+ "html": "<meta charset='utf-8'><h2 style=\"font-family: Georgia; color: rgb(30, 36, 64);\">Opening hours</h2><p style=\"margin: 0px 0px 1em;\">We bake every day from <strong>7am</strong>. See <a href=\"https://fennel.example/hours\" style=\"color: blue;\">our hours page</a> or <a href=\"/contact\">contact us</a>.</p>\n<ol start=\"3\">\n <li>Order by noon</li>\n <li>Collect after 4pm</li>\n</ol>\n<p>Questions? Email <a href=\"mailto:hello@fennel.example\">hello@fennel.example</a>.</p>",
+ "markdown": "## Opening hours\n\nWe bake every day from **7am**. See [our hours page](https://fennel.example/hours) or contact us.\n\n3. Order by noon\n4. Collect after 4pm\n\nQuestions? Email hello@fennel.example."
+ },
+ {
+ "name": "Apple Mail: lines, a blank line, bold, italics and a numbered list",
+ "html": "<html><head><meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\"></head><body style=\"overflow-wrap: break-word; -webkit-nbsp-mode: space; line-break: after-white-space;\"><div>Hi Ana,</div><div><br></div><div>The <b>flour delivery</b> moves to <i>Thursday</i>.<br>Can you&nbsp;check the order?</div><div><br></div><div><ol class=\"MailOutline\"><li>Two sacks of rye</li><li>One of spelt</li></ol><div>Thanks,</div></div><div>Paul</div></body></html>",
+ "markdown": "Hi Ana,\n\nThe **flour delivery** moves to *Thursday*.\nCan you check the order?\n\n1. Two sacks of rye\n2. One of spelt\n\nThanks,\nPaul"
+ },
+ {
+ "name": "Nested lists, bullets in bullets in numbers",
+ "html": "<ul><li>Bread<ul><li>Sourdough</li><li>Rye<ol><li>Light</li><li>Dark</li></ol></li></ul></li><li>Cakes</li></ul>",
+ "markdown": "- Bread\n - Sourdough\n - Rye\n 1. Light\n 2. Dark\n- Cakes"
+ },
+ {
+ "name": "A javascript: link and one with a password are text; scripts and images go",
+ "html": "<p>Click <a href=\"javascript:alert(1)\">here</a> or <a href=\"https://user:pw@fennel.example/x\">there</a> for <b>details</b>.</p><script>alert(2)</script><img src=\"https://tracker.example/p.gif\" alt=\"pixel\"><style>p { color: red }</style>",
+ "markdown": "Click here or there for **details**."
+ },
+ {
+ "name": "Headings, emphasis inside them dropped",
+ "html": "<h1 dir=\"ltr\"><span style=\"font-weight:700\">Weekly plan</span></h1><h3>Monday</h3><p><span style=\"font-style:italic\">Bake</span> only.</p>",
+ "markdown": "# Weekly plan\n\n### Monday\n\n*Bake* only."
+ },
+ {
+ "name": "Spaces stand outside the marks, one between words",
+ "html": "<p><b>Bold </b>then <i> spaced </i>words, and a link: <a href=\"https://fennel.example/a_(b)\">the [menu]</a></p>",
+ "markdown": "**Bold** then *spaced* words, and a link: [the menu](https://fennel.example/a_%28b%29)"
+ },
+ {
+ "name": "Code from an editor formats nothing: the plain text is pasted",
+ "html": "<meta charset=\"utf-8\"><div style=\"color: #d4d4d4;background-color: #1e1e1e;font-family: Menlo, Monaco, monospace;white-space: pre;\"><div><span style=\"color: #569cd6;\">let</span><span style=\"color: #d4d4d4;\"> x = 2*3</span></div></div>",
+ "markdown": null
+ },
+ {
+ "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"
+ }
+]
diff --git a/internal/look/static/app.css b/internal/look/static/app.css
index 0db5708..34e5135 100644
--- a/internal/look/static/app.css
+++ b/internal/look/static/app.css
@@ -557,10 +557,11 @@ 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; }
+/* The simple lists in a message, the Assistant's or the person's: the
+ thread's own list-style is none. */
+.msg ul, .msg ol { margin: 4px 0; padding-left: 20px; }
+.msg ul { list-style: disc; }
+.msg 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); }
@@ -568,6 +569,8 @@ aside.ask-panel { position: absolute; top: 16px; right: 16px; bottom: 16px; widt
.choices { display: flex; flex-wrap: wrap; gap: 8px; }
.msg.card p + p { margin-top: -4px; }
.card-link, .msg.coordinator a { color: var(--focus); text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; }
+/* The person's links keep their bubble's ink, underlined. */
+.msg.person a { color: inherit; text-decoration: underline; text-underline-offset: 3px; overflow-wrap: anywhere; }
.card-link { display: inline-flex; align-items: center; min-height: 44px; font-weight: 500; }
.msg.card .card-state { margin: 0; color: var(--haze); font-size: 14px; }
.msg.card .choices + .card-state { margin-top: 10px; }
diff --git a/internal/look/static/ask.js b/internal/look/static/ask.js
index 4b2c735..d1473e5 100644
--- a/internal/look/static/ask.js
+++ b/internal/look/static/ask.js
@@ -109,8 +109,9 @@ function start(root) {
li.className = "msg " + (m.role === "person" ? "person" : "coordinator");
li.dataset.id = m.id;
if (m.role !== "person" && m.turn_id) li.dataset.turn = m.turn_id;
- if (m.role === "person") li.textContent = m.text;
- else rich(li, m.text);
+ // The person's own words take the same little Markdown as the
+ // Assistant's (rich), under the same rules.
+ rich(li, m.text);
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);
@@ -1637,14 +1638,201 @@ function start(root) {
field.addEventListener("keydown", (e) => {
if (e.key !== "Enter" || e.isComposing || e.keyCode === 229 || e.shiftKey) return;
e.preventDefault();
- if (!e.altKey) {
- composer.requestSubmit();
- } else if (!document.execCommand("insertText", false, "\n")) {
- // Where insertText isn't offered: at the cursor, without undo.
- field.setRangeText("\n", field.selectionStart, field.selectionEnd, "end");
- field.dispatchEvent(new Event("input", { bubbles: true }));
- }
+ if (!e.altKey) composer.requestSubmit();
+ else typeIn("\n");
+ });
+ // A rich paste (a web page, Docs, Mail) comes in as the Markdown the
+ // chat draws (pasteMarkdown); a plain one, or one whose HTML carries no
+ // formatting, is left to the browser.
+ field.addEventListener("paste", (e) => {
+ const html = e.clipboardData && e.clipboardData.getData("text/html");
+ const md = html ? pasteMarkdown(html) : null;
+ if (md === null) return;
+ e.preventDefault();
+ typeIn(md);
});
+ // typeIn puts text in place of the field's selection as typing would,
+ // so Undo takes it back; where insertText isn't offered, at the cursor
+ // without undo.
+ function typeIn(text) {
+ if (document.execCommand("insertText", false, text)) return;
+ field.setRangeText(text, field.selectionStart, field.selectionEnd, "end");
+ field.dispatchEvent(new Event("input", { bubbles: true }));
+ }
+
+ // pasteMarkdown is a clipboard's HTML as the chat's Markdown: bold
+ // (**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).
+ function pasteMarkdown(html) {
+ const doc = new DOMParser().parseFromString(html, "text/html");
+ 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 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 out = [];
+ let runs = [], open = false, marker = null, indent = "", formatted = false;
+ 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);
+ if (!open && marker !== null) formatted = true;
+ marker = null;
+ open = true;
+ };
+ 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");
+ };
+ const walk = (node, st) => {
+ if (node.nodeType === 3) {
+ 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 (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 });
+ return;
+ }
+ 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; }
+ return;
+ }
+ const next = { ...st };
+ if (tag === "B" || tag === "STRONG") next.bold = true;
+ if (tag === "I" || tag === "EM") next.italic = 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 level = /^H([1-6])$/.exec(tag);
+ if (level) {
+ ensure(2);
+ marker = "#".repeat(Number(level[1])) + " ";
+ next.heading = true;
+ const before = formatted;
+ children();
+ flush();
+ if (marker !== null) { marker = null; formatted = before; }
+ ensure(2);
+ return;
+ }
+ if (tag === "UL" || tag === "OL") {
+ const top = lists.length === 0;
+ const parent = lists[lists.length - 1];
+ ensure(top ? 2 : 1);
+ const start = parseInt(node.getAttribute("start"), 10);
+ lists.push({ ordered: tag === "OL", n: Number.isNaN(start) ? 1 : Math.max(0, start),
+ indent: parent ? parent.inner : indent, inner: parent ? parent.inner : indent });
+ const saved = indent;
+ children();
+ lists.pop();
+ indent = saved;
+ ensure(top ? 2 : 1);
+ return;
+ }
+ if (tag === "LI") {
+ ensure(1);
+ const list = lists[lists.length - 1] || { ordered: false, n: 0, indent: "", inner: "" };
+ const m = list.ordered ? list.n++ + ". " : "- ";
+ marker = list.indent + m;
+ list.inner = list.indent + " ".repeat(m.length);
+ const saved = indent;
+ indent = list.inner;
+ children();
+ flush();
+ marker = null;
+ indent = saved;
+ ensure(1);
+ return;
+ }
+ if (tag === "P") {
+ if (lists.length) {
+ flush();
+ if (open) { out.push("\n"); open = false; }
+ children();
+ return;
+ }
+ ensure(2);
+ children();
+ ensure(2);
+ return;
+ }
+ if (tag === "PRE") {
+ ensure(2);
+ next.pre = true;
+ children();
+ ensure(2);
+ return;
+ }
+ if (lines.has(tag)) {
+ ensure(1);
+ children();
+ ensure(1);
+ return;
+ }
+ if (tag === "TD" || tag === "TH") {
+ children();
+ runs.push({ text: " ", bold: false, italic: false, href: "" });
+ return;
+ }
+ children();
+ };
+ // inline is a line's runs as Markdown: neighbours alike are one run,
+ // and a run's outer spaces stand outside its marks.
+ const inline = (rs) => {
+ const merged = [];
+ for (const r of rs) {
+ const last = merged[merged.length - 1];
+ if (last && last.href === r.href && (r.href || (last.bold === r.bold && last.italic === r.italic))) last.text += r.text;
+ else merged.push({ ...r });
+ }
+ let s = "";
+ for (const r of merged) {
+ const lead = /^ */.exec(r.text)[0], trail = / *$/.exec(r.text)[0];
+ const core = r.text.slice(lead.length, r.text.length - trail.length);
+ if (!core) { s += r.text; continue; }
+ 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;
+ formatted = true;
+ } else if (r.bold || r.italic) {
+ const mark = r.bold ? "**" : "*";
+ s += lead + mark + core + mark + trail;
+ formatted = true;
+ } else {
+ s += r.text;
+ }
+ }
+ return s.replace(/ +$/, "");
+ };
+ walk(doc.body, { bold: false, italic: false, href: "", heading: false, pre: false });
+ 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, "");
+ }
cancel.addEventListener("submit", (e) => {
e.preventDefault();
post(cancel);
diff --git a/internal/web/templates/partials/chat.html b/internal/web/templates/partials/chat.html
index 117c7b9..c05454b 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}}">{{.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}}">{{$.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}}
{{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/webtest/ask_test.go b/internal/webtest/ask_test.go
index 4e77482..6cf608f 100644
--- a/internal/webtest/ask_test.go
+++ b/internal/webtest/ask_test.go
@@ -2011,3 +2011,28 @@ func TestAskTeamUpdateTurnIsQuiet(t *testing.T) {
page = a.get("/ask").Body
expect(t, "/ask with the person's turn", page, `<p class="ask-status" role="status">(.*?)</p>`, "Thinking…")
}
+
+// The person's own messages are drawn in the Assistant's little Markdown,
+// under its rules (Paul, 2026-11-26): bold, lists and safe links; raw HTML
+// and unsafe links stay text, and plain words are exactly as written.
+func TestAskPersonMessagesAreMarkdown(t *testing.T) {
+ a, f := newAskApp(t)
+ a.connectEquipo(f)
+ for _, text := range []string{
+ "**Bold** and <b>x</b>:\n- [Menu](https://fennel.example/menu)\n- [x](javascript:alert(1))",
+ "Two lines\nhere, 2*3 and a_b_c",
+ } {
+ a.post("/ask/messages", url.Values{"text": {text}})
+ }
+ page := a.get("/ask").Body
+ person := regexp.MustCompile(`(?s)<li class="msg person" data-id="[^"]+">(.*?)</li>\n`).FindAllStringSubmatch(page, -1)
+ if len(person) != 2 {
+ t.Fatalf("person messages: %d\n%s", len(person), page)
+ }
+ if want := `<strong>Bold</strong> and &lt;b&gt;x&lt;/b&gt;:<ul><li><a href="https://fennel.example/menu" target="_blank" rel="noopener">Menu</a></li><li>[x](javascript:alert(1))</li></ul>`; person[0][1] != want {
+ t.Errorf("Markdown:\n got %s\nwant %s", person[0][1], want)
+ }
+ if want := "Two lines\nhere, 2*3 and a_b_c"; person[1][1] != want {
+ t.Errorf("plain words:\n got %q\nwant %q", person[1][1], want)
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Composer.swift b/native/apple/Sources/BaseKit/Ask/Composer.swift
index b5171c8..c1eb285 100644
--- a/native/apple/Sources/BaseKit/Ask/Composer.swift
+++ b/native/apple/Sources/BaseKit/Ask/Composer.swift
@@ -3,6 +3,7 @@ import SwiftUI
import AppKit
#elseif os(iOS)
import UIKit
+import UniformTypeIdentifiers
#endif
/// The composer (chat.html `.composer`): one field that grows to a few
@@ -48,6 +49,8 @@ public struct Composer: View {
case .pass: return .ignored
}
}
+ // A rich paste comes in as Markdown (ComposerInput.richPaste).
+ .onChange(of: focused, initial: true) { _, now in input.focused = now }
#if os(iOS)
// The iPhone's on-screen keyboard: its Send key.
.onSubmit(send)
@@ -103,6 +106,53 @@ enum ComposerReturn: Equatable {
weak var anchor: NSView?
/// A Mac field's editor.
var editor: NSTextView? { anchor?.window?.firstResponder as? NSTextView }
+ /// Whether the field has the keyboard (its FocusState).
+ var focused = false
+ /// Where pastes come from (tests give their own).
+ static var pasteboard = NSPasteboard.general
+ private var converting = false
+ private var observer: NSObjectProtocol?
+
+ init() {
+ observer = NotificationCenter.default.addObserver(forName: NSText.didChangeNotification, object: nil, queue: nil) { [weak self] note in
+ // Text changes are posted on the main thread.
+ nonisolated(unsafe) let changed = note.object as AnyObject?
+ MainActor.assumeIsolated { self?.richPaste(in: changed) }
+ }
+ }
+
+ isolated deinit { observer.map(NotificationCenter.default.removeObserver) }
+
+ /// A rich paste (HTML or RTF on the pasteboard) as Markdown. The Mac
+ /// field pastes the plain text itself and has no hook before it, so
+ /// this follows: when the field's text has just taken the pasteboard's
+ /// plain text, ending at the cursor, that is put back as one edit with
+ /// the paste (one Undo takes both). Typing, an input method, Undo and
+ /// Paste and Match Style are left alone.
+ func richPaste(in changed: AnyObject?) {
+ guard focused, !converting, let editor, changed === editor,
+ editor.undoManager?.isUndoing != true, editor.undoManager?.isRedoing != true else { return }
+ if let event = NSApp.currentEvent, event.type == .keyDown {
+ let keys = event.modifierFlags.intersection(.deviceIndependentFlagsMask)
+ guard keys.contains(.command), !keys.isSuperset(of: [.option, .shift]) else { return }
+ }
+ let board = Self.pasteboard
+ guard let plain = board.string(forType: .string), !plain.isEmpty else { return }
+ let markdown = board.string(forType: .html).flatMap(PasteMarkdown.fromHTML)
+ ?? board.data(forType: .rtf).flatMap(PasteMarkdown.fromRTF)
+ guard let markdown else { return }
+ let text = editor.string as NSString, length = (plain as NSString).length
+ let selection = editor.selectedRange()
+ let pasted = NSRange(location: selection.location - length, length: length)
+ guard selection.length == 0, pasted.location >= 0, text.substring(with: pasted) == plain,
+ editor.shouldChangeText(in: pasted, replacementString: markdown) else { return }
+ converting = true
+ defer { converting = false }
+ editor.replaceCharacters(in: pasted, with: markdown)
+ editor.setSelectedRange(NSRange(location: pasted.location + (markdown as NSString).length, length: 0))
+ editor.didChangeText()
+ editor.breakUndoCoalescing()
+ }
var composing: Bool { editor?.hasMarkedText() ?? false }
/// A new line in place of the selection, as Option Return in any Mac
/// field: one undoable edit, the cursor after it.
@@ -114,6 +164,18 @@ enum ComposerReturn: Equatable {
#elseif os(iOS)
weak var anchor: UIView?
var editor: (UIView & UITextInput)? { anchor?.window.flatMap(Self.firstResponder) }
+ private let paste = ComposerPaste()
+ /// Whether the field has the keyboard; once it has, its text view
+ /// takes rich pastes as Markdown (ComposerPaste).
+ var focused = false {
+ didSet {
+ guard focused else { return }
+ Task { @MainActor [weak self] in
+ guard let self, let view = self.editor as? UITextView, view.pasteDelegate !== self.paste else { return }
+ view.pasteDelegate = self.paste
+ }
+ }
+ }
var composing: Bool { editor?.markedTextRange != nil }
func insertNewline() -> Bool {
guard let editor, let range = editor.selectedTextRange else { return false }
@@ -126,11 +188,31 @@ enum ComposerReturn: Equatable {
return nil
}
#else
+ var focused = false
var composing: Bool { false }
func insertNewline() -> Bool { false }
#endif
}
+#if os(iOS)
+/// The iPhone and iPad field's paste: HTML or RTF becomes Markdown, in
+/// place of the selection as any paste; anything else is pasted as is.
+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) }),
+ (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() }
+ }
+ return
+ }
+ item.setDefaultResult()
+ }
+}
+#endif
+
/// An empty view behind the field, so the composer knows its window.
#if os(macOS)
struct ComposerAnchor: NSViewRepresentable {
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
index a512933..aa57725 100644
--- a/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/BaseMarkdownView.swift
@@ -12,8 +12,11 @@ import UIKit
/// The Assistant's prose: the little Markdown it writes (lists, links,
/// bold, italics), parsed off the main thread as it streams. The source is
/// untrusted text; only absolute http(s) links are actionable.
+/// Base: the person's own messages too (`person`), which keep each line
+/// they typed and whose links keep the bubble's ink, as on the web.
struct BaseMarkdownView: View {
private let draft: Bool
+ private let person: Bool
private let stream: MarkdownStreamRenderer
private let request: MarkdownRenderCache.Request
private let initial: MarkdownRenderCache.Result
@@ -24,8 +27,9 @@ struct BaseMarkdownView: View {
initial.complete ? initial.tree : stream.visible(for: request) ?? initial.tree
}
- init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript) {
+ init(_ text: String, draft: Bool, id: String, transcript: MarkdownTranscript, person: Bool = false) {
self.draft = draft
+ self.person = person
request = MarkdownRenderCache.Request(messageID: id, text: text, draft: draft)
initial = MarkdownRenderCache.shared.initial(request)
stream = transcript.renderer(for: id)
@@ -36,7 +40,8 @@ struct BaseMarkdownView: View {
MarkdownRows(nodes: nodes)
.font(BaseFont.body(15))
.foregroundStyle(p[.frost])
- .tint(p[.focus])
+ .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) }
@@ -65,8 +70,15 @@ 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.
+ @Entry var markdownKeepsLines = false
+}
+
private struct MarkdownBlock: View {
let node: ChatMarkdownNode
+ @Environment(\.markdownKeepsLines) private var keepsLines
var body: some View {
switch node.kind {
case "paragraph", "inlineGroup": Text(inline(node.children)).fixedSize(horizontal: false, vertical: true)
@@ -78,7 +90,11 @@ private struct MarkdownBlock: View {
}
private func prose(_ text: String) -> String {
- text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression)
+ 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)
+ }
+ return text.replacingOccurrences(of: #"[ \t\r\n\f]+"#, with: " ", options: .regularExpression)
}
private func inline(_ nodes: [ChatMarkdownNode]) -> AttributedString {
diff --git a/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
index b51346c..cca98c7 100644
--- a/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
+++ b/native/apple/Sources/BaseKit/Ask/Markdown/ChatMarkdown.swift
@@ -100,6 +100,14 @@ 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
diff --git a/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift
new file mode 100644
index 0000000..74c0a76
--- /dev/null
+++ b/native/apple/Sources/BaseKit/Ask/PasteMarkdown.swift
@@ -0,0 +1,431 @@
+import Foundation
+#if os(macOS)
+import AppKit
+#elseif os(iOS)
+import UIKit
+#endif
+
+/// A rich paste (a web page, Docs, Mail) as the Markdown the chat draws:
+/// 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
+/// internal/browsertest/testdata/paste.json check both).
+enum PasteMarkdown {
+ static func fromHTML(_ html: String) -> String? {
+ var walker = Walker()
+ return walker.markdown(HTMLTree.parse(html))
+ }
+
+ 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)
+ }
+
+ /// An attributed string's paragraphs as lines (lists by their text
+ /// lists), its runs bold, italic or linked by their attributes: the
+ /// same tree HTML makes, so the same walk.
+ static func fromAttributed(_ text: NSAttributedString) -> String? {
+ var walker = Walker()
+ return walker.markdown(HTMLTree.from(text))
+ }
+}
+
+/// Just enough HTML: elements with their attributes, and text. Tags that
+/// are never closed close with their parent; a stray end tag is dropped.
+struct HTMLTree: Equatable {
+ var tag = "" // "" is text
+ var attributes: [String: String] = [:]
+ var text = ""
+ var children: [HTMLTree] = []
+
+ static let void: Set<String> = ["br", "img", "hr", "input", "meta", "link", "area", "base", "col", "embed", "source", "track", "wbr", "param"]
+ static let raw: Set<String> = ["script", "style", "textarea", "title", "template", "noscript", "iframe", "xmp", "plaintext"]
+ /// What a new block closes when it opens, as a page would.
+ static let closesP: Set<String> = ["p", "div", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "pre", "table", "blockquote", "section", "article", "header", "footer", "hr", "dl", "form"]
+
+ static func parse(_ html: String) -> HTMLTree {
+ let s = Array(html.unicodeScalars)
+ var stack = [HTMLTree(tag: "body")]
+ var at = 0
+ func appendText(_ t: String) {
+ guard !t.isEmpty else { return }
+ stack[stack.count - 1].children.append(HTMLTree(text: MarkdownEntities.link(t)))
+ }
+ func close(_ index: Int) {
+ while stack.count > index {
+ let done = stack.removeLast()
+ stack[stack.count - 1].children.append(done)
+ }
+ }
+ func open(_ name: String) -> Int? { stack.lastIndex { $0.tag == name } }
+ var text = ""
+ while at < s.count {
+ guard s[at] == "<" else { text.unicodeScalars.append(s[at]); at += 1; continue }
+ // A comment, doctype or processing instruction: skipped.
+ if at + 3 < s.count, s[at + 1] == "!", s[at + 2] == "-", s[at + 3] == "-" {
+ appendText(text); text = ""
+ var end = at + 4
+ while end + 2 < s.count, !(s[end] == "-" && s[end + 1] == "-" && s[end + 2] == ">") { end += 1 }
+ at = min(s.count, end + 3)
+ continue
+ }
+ if at + 1 < s.count, s[at + 1] == "!" || s[at + 1] == "?" {
+ appendText(text); text = ""
+ while at < s.count, s[at] != ">" { at += 1 }
+ at += 1
+ continue
+ }
+ let closing = at + 1 < s.count && s[at + 1] == "/"
+ var cursor = at + (closing ? 2 : 1)
+ var name = ""
+ while cursor < s.count, s[cursor].properties.isAlphabetic || ("0"..."9").contains(s[cursor]) || s[cursor] == "-" || s[cursor] == ":" {
+ name.unicodeScalars.append(s[cursor]); cursor += 1
+ }
+ guard !name.isEmpty else { text.unicodeScalars.append(s[at]); at += 1; continue }
+ name = name.lowercased()
+ // The attributes, to the tag's end.
+ var attributes: [String: String] = [:]
+ var selfClosing = false
+ while cursor < s.count, s[cursor] != ">" {
+ if s[cursor] == "/" { selfClosing = true; cursor += 1; continue }
+ if s[cursor].properties.isWhitespace { cursor += 1; continue }
+ selfClosing = false
+ var key = ""
+ while cursor < s.count, !s[cursor].properties.isWhitespace, !"=>/".unicodeScalars.contains(s[cursor]) {
+ key.unicodeScalars.append(s[cursor]); cursor += 1
+ }
+ while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 }
+ var value = ""
+ if cursor < s.count, s[cursor] == "=" {
+ cursor += 1
+ while cursor < s.count, s[cursor].properties.isWhitespace { cursor += 1 }
+ if cursor < s.count, s[cursor] == "\"" || s[cursor] == "'" {
+ let quote = s[cursor]; cursor += 1
+ while cursor < s.count, s[cursor] != quote { value.unicodeScalars.append(s[cursor]); cursor += 1 }
+ cursor += 1
+ } else {
+ while cursor < s.count, !s[cursor].properties.isWhitespace, s[cursor] != ">" { value.unicodeScalars.append(s[cursor]); cursor += 1 }
+ }
+ }
+ if key.isEmpty { cursor += 1; continue }
+ let k = key.lowercased()
+ if attributes[k] == nil { attributes[k] = MarkdownEntities.link(value) }
+ }
+ at = min(s.count, cursor + 1)
+ appendText(text); text = ""
+ if closing {
+ 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) }
+ if name == "li", let li = open("li"), !stack[(li + 1)...].contains(where: { $0.tag == "ul" || $0.tag == "ol" }) { close(li) }
+ let element = HTMLTree(tag: name, attributes: attributes)
+ if raw.contains(name) {
+ // Its content is text to its end tag; none of it is kept
+ // (the walk skips all of these).
+ var end = at
+ let closer = Array("</\(name)".unicodeScalars)
+ while end < s.count {
+ if s[end] == "<", end + closer.count <= s.count,
+ String(String.UnicodeScalarView(s[end..<end + closer.count])).lowercased() == "</\(name)" { break }
+ end += 1
+ }
+ stack[stack.count - 1].children.append(element)
+ at = end
+ while at < s.count, s[at] != ">" { at += 1 }
+ at += 1
+ continue
+ }
+ if void.contains(name) || selfClosing {
+ stack[stack.count - 1].children.append(element)
+ } else {
+ stack.append(element)
+ }
+ }
+ appendText(text)
+ close(1)
+ return stack[0]
+ }
+
+ /// The tree an attributed string's paragraphs and runs make.
+ static func from(_ text: NSAttributedString) -> HTMLTree {
+ var body = HTMLTree(tag: "body")
+ // The open lists: each the list node path from body.
+ var lists: [(ordered: Bool, node: HTMLTree)] = []
+ func closeLists(to depth: Int) {
+ while lists.count > depth {
+ let done = lists.removeLast().node
+ if lists.isEmpty {
+ body.children.append(done)
+ } else {
+ lists[lists.count - 1].node.children.append(done)
+ }
+ }
+ }
+ let string = text.string as NSString
+ string.enumerateSubstrings(in: NSRange(location: 0, length: string.length), options: [.byParagraphs, .substringNotRequired]) { _, content, _, _ in
+ let style = content.length > 0 ? text.attribute(.paragraphStyle, at: content.location, effectiveRange: nil) as? NSParagraphStyle : nil
+ let textLists = style?.textLists ?? []
+ var line = HTMLTree(tag: textLists.isEmpty ? "div" : "li")
+ var runsFrom = content.location
+ if !textLists.isEmpty, let marker = Self.listMarker.firstMatch(in: text.string, range: content) {
+ // A list's marker is in the text ("\t•\t", "\t1.\t"): it goes.
+ runsFrom += marker.range.length
+ }
+ if runsFrom < NSMaxRange(content) {
+ text.enumerateAttributes(in: NSRange(location: runsFrom, length: NSMaxRange(content) - runsFrom)) { attributes, run, _ in
+ var node = HTMLTree(text: string.substring(with: run))
+ if let link = attributes[.link] {
+ let href = (link as? URL)?.absoluteString ?? (link as? String) ?? ""
+ node = HTMLTree(tag: "a", attributes: ["href": href], children: [node])
+ }
+ let (bold, italic) = traits(attributes)
+ if italic { node = HTMLTree(tag: "i", children: [node]) }
+ if bold { node = HTMLTree(tag: "b", children: [node]) }
+ line.children.append(node)
+ }
+ } else if textLists.isEmpty {
+ line.children.append(HTMLTree(tag: "br"))
+ }
+ // The paragraph's lists, outermost first.
+ let depth = textLists.count
+ var shared = 0
+ while shared < min(depth, lists.count), lists[shared].ordered == ordered(textLists[shared]) { shared += 1 }
+ closeLists(to: shared)
+ while lists.count < depth {
+ let ordered = ordered(textLists[lists.count])
+ lists.append((ordered, HTMLTree(tag: ordered ? "ol" : "ul")))
+ }
+ if depth == 0 { body.children.append(line) } else { lists[lists.count - 1].node.children.append(line) }
+ }
+ closeLists(to: 0)
+ return body
+ }
+
+ private static let listMarker = try! NSRegularExpression(pattern: #"\G\t?[^\t\n]{0,12}\t"#)
+
+ private static func ordered(_ list: NSTextList) -> Bool {
+ !["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) {
+ #if os(macOS)
+ guard let font = attributes[.font] as? NSFont else { return (false, false) }
+ let t = font.fontDescriptor.symbolicTraits
+ return (t.contains(.bold), t.contains(.italic))
+ #elseif os(iOS)
+ guard let font = attributes[.font] as? UIFont else { return (false, false) }
+ let t = font.fontDescriptor.symbolicTraits
+ return (t.contains(.traitBold), t.contains(.traitItalic))
+ #else
+ return (false, false)
+ #endif
+ }
+}
+
+/// 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 }
+ 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 }
+ }
+ static let skip: Set<String> = ["script", "style", "head", "title", "template", "noscript", "iframe", "object", "embed", "svg", "math", "canvas", "video", "audio", "picture", "img", "button", "select", "input", "textarea"]
+ static let lines: Set<String> = ["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"]
+
+ var out = ""
+ var runs: [Run] = []
+ var open = false
+ var marker: String?
+ var indent = ""
+ var formatted = false
+ var lists: [List] = []
+
+ mutating func markdown(_ tree: HTMLTree) -> String? {
+ walk(tree, Style())
+ flush()
+ guard formatted else { return nil }
+ let trimmed = out.components(separatedBy: "\n").map { line in
+ var line = line
+ while line.last == " " || line.last == "\t" { line.removeLast() }
+ return line
+ }.joined(separator: "\n")
+ var result = trimmed.replacingOccurrences(of: #"\n{3,}"#, with: "\n\n", options: .regularExpression)
+ while result.first == "\n" { result.removeFirst() }
+ while result.last == "\n" { result.removeLast() }
+ return result
+ }
+
+ mutating func flush() {
+ var s = inline(runs)
+ runs = []
+ while s.first == " " { s.removeFirst() }
+ guard !s.isEmpty else { return }
+ if open { out += s } else {
+ out += (marker ?? indent) + s
+ if marker != nil { formatted = true }
+ }
+ marker = nil
+ open = true
+ }
+
+ mutating func ensure(_ n: Int) {
+ flush()
+ open = false
+ guard !out.isEmpty else { return }
+ var have = 0
+ for c in out.reversed() { if c == "\n" { have += 1 } else { break } }
+ while have < n { out += "\n"; have += 1 }
+ }
+
+ mutating func walk(_ node: HTMLTree, _ st: Style) {
+ if node.tag.isEmpty {
+ 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() {
+ if i > 0 { flush(); out += "\n"; open = false }
+ if !part.isEmpty { runs.append(Run(text: part, bold: false, italic: false, href: "")) }
+ }
+ } else {
+ var t = node.text.replacingOccurrences(of: "[ \\t\\n\\r\\f\u{00a0}]+", with: " ", options: .regularExpression)
+ // One space between words, whichever side of a tag it was.
+ if t.first == " ", runs.last?.text.last == " " { t.removeFirst() }
+ if !t.isEmpty { runs.append(Run(text: t, bold: st.heading ? false : st.bold, italic: st.heading ? false : st.italic, href: st.href)) }
+ }
+ return
+ }
+ let tag = node.tag
+ if Self.skip.contains(tag) { return }
+ if tag == "br" {
+ flush()
+ if !out.isEmpty { out += "\n"; open = false }
+ return
+ }
+ var next = st
+ if tag == "b" || tag == "strong" { next.bold = true }
+ if tag == "i" || tag == "em" { next.italic = true }
+ let style = node.attributes["style"] ?? ""
+ if let weight = Self.first(#"(?i)font-weight\s*:\s*([a-z0-9]+)"#, in: style) {
+ 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 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.count == 2, tag.first == "h", let level = Int(String(tag.last!)), (1...6).contains(level) {
+ ensure(2)
+ marker = String(repeating: "#", count: level) + " "
+ next.heading = true
+ let before = formatted
+ children(&self)
+ flush()
+ if marker != nil { marker = nil; formatted = before }
+ ensure(2)
+ return
+ }
+ if tag == "ul" || tag == "ol" {
+ let top = lists.isEmpty
+ let parent = lists.last
+ ensure(top ? 2 : 1)
+ let start = Int(node.attributes["start"]?.trimmingCharacters(in: .whitespaces) ?? "")
+ lists.append(List(ordered: tag == "ol", n: tag == "ol" ? max(0, start ?? 1) : 0, indent: parent?.inner ?? indent))
+ let saved = indent
+ children(&self)
+ lists.removeLast()
+ indent = saved
+ ensure(top ? 2 : 1)
+ return
+ }
+ if tag == "li" {
+ ensure(1)
+ let list = lists.last ?? List(ordered: false, n: 0, indent: "")
+ let m = list.ordered ? "\(list.n). " : "- "
+ if list.ordered { list.n += 1 }
+ marker = list.indent + m
+ list.inner = list.indent + String(repeating: " ", count: m.count)
+ let saved = indent
+ indent = list.inner
+ children(&self)
+ flush()
+ marker = nil
+ indent = saved
+ ensure(1)
+ return
+ }
+ if tag == "p" {
+ if !lists.isEmpty {
+ flush()
+ if open { out += "\n"; open = false }
+ children(&self)
+ return
+ }
+ ensure(2); children(&self); ensure(2)
+ return
+ }
+ if tag == "pre" {
+ ensure(2)
+ next.pre = true
+ children(&self)
+ ensure(2)
+ return
+ }
+ if Self.lines.contains(tag) {
+ ensure(1); children(&self); ensure(1)
+ return
+ }
+ if tag == "td" || tag == "th" {
+ children(&self)
+ runs.append(Run(text: " ", bold: false, italic: false, href: ""))
+ return
+ }
+ children(&self)
+ }
+
+ /// A line's runs as Markdown: neighbours alike are one run, and a run's
+ /// outer spaces stand outside its marks.
+ mutating func inline(_ rs: [Run]) -> String {
+ var merged: [Run] = []
+ for r in rs {
+ if let last = merged.last, last.href == r.href, !r.href.isEmpty || (last.bold == r.bold && last.italic == r.italic) {
+ merged[merged.count - 1].text += r.text
+ } else {
+ merged.append(r)
+ }
+ }
+ var s = ""
+ for r in merged {
+ let lead = String(r.text.prefix { $0 == " " })
+ let rest = r.text.dropFirst(lead.count)
+ let trail = String(rest.reversed().prefix { $0 == " " })
+ let core = String(rest.dropLast(trail.count))
+ if core.isEmpty { s += r.text; continue }
+ 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
+ formatted = true
+ } else if r.bold || r.italic {
+ let mark = r.bold ? "**" : "*"
+ s += lead + mark + core + mark + trail
+ formatted = true
+ } else {
+ s += r.text
+ }
+ }
+ while s.last == " " { s.removeLast() }
+ 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])
+ }
+}
diff --git a/native/apple/Sources/BaseKit/Ask/Thread.swift b/native/apple/Sources/BaseKit/Ask/Thread.swift
index 0c6fcd3..f57fb05 100644
--- a/native/apple/Sources/BaseKit/Ask/Thread.swift
+++ b/native/apple/Sources/BaseKit/Ask/Thread.swift
@@ -87,8 +87,12 @@ struct AskThread: View {
switch entry {
case .message(let m):
Bubble(person: m.isPerson, maxWidth: bubbleWidth) {
- if m.isPerson {
+ // 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)
+ } else if m.isPerson {
+ BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript, person: true)
} else {
BaseMarkdownView(m.text, draft: false, id: m.id, transcript: transcript)
}
diff --git a/native/apple/Tests/BaseKitTests/AskViewTests.swift b/native/apple/Tests/BaseKitTests/AskViewTests.swift
index 6acfb8e..566b464 100644
--- a/native/apple/Tests/BaseKitTests/AskViewTests.swift
+++ b/native/apple/Tests/BaseKitTests/AskViewTests.swift
@@ -76,3 +76,16 @@ extension AskViewTests {
}
}
}
+
+extension AskViewTests {
+ /// The person's messages take the Assistant's Markdown (2026-11-26);
+ /// words with none are drawn exactly as written.
+ 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 rich in ["**Bold**", "*it*", "- a\n- b", "1. One", "[Menu](https://fennel.example/menu)"] {
+ XCTAssertFalse(ChatMarkdown.isPlain(ChatMarkdown.parse(rich, draft: false)), rich)
+ }
+ }
+}
diff --git a/native/apple/Tests/BaseKitTests/ComposerTests.swift b/native/apple/Tests/BaseKitTests/ComposerTests.swift
index 7d902c1..d97e14a 100644
--- a/native/apple/Tests/BaseKitTests/ComposerTests.swift
+++ b/native/apple/Tests/BaseKitTests/ComposerTests.swift
@@ -126,6 +126,43 @@ import AppKit
}
}
+extension ComposerKeyTests {
+ /// A rich paste comes in as Markdown at the cursor (2026-11-26), and
+ /// one Undo takes it all back; a plain one is pasted as it is. A
+ /// pasteboard of the test's own, never the person's.
+ func testARichPasteIsMarkdown() throws {
+ let board = NSPasteboard(name: .init("BaseKitTests.\(UUID().uuidString)"))
+ defer { board.releaseGlobally(); ComposerInput.pasteboard = .general }
+ ComposerInput.pasteboard = board
+ try type("Note: ")
+ let editor = try XCTUnwrap(editor)
+ board.clearContents()
+ board.setString("<p>The <b>flour</b> comes <i>Thursday</i>:</p><ul><li>Rye</li><li><a href=\"https://fennel.example/order\">The order</a></li></ul>", forType: .html)
+ board.setString("The flour comes Thursday:\nRye\nThe order", forType: .string)
+ XCTAssertTrue(editor.readSelection(from: board))
+ settle()
+ XCTAssertEqual(model.text, "Note: The **flour** comes *Thursday*:\n\n- Rye\n- [The order](https://fennel.example/order)")
+ XCTAssertEqual(editor.selectedRange().location, (model.text as NSString).length, "the cursor after the paste")
+ XCTAssertFalse(sent)
+ editor.undoManager?.undo()
+ settle()
+ // (The field's own text: a hosted field's binding misses an Undo
+ // here, any Undo, typing's too.)
+ XCTAssertEqual(editor.string, "Note: ", "one Undo takes the paste back")
+ editor.undoManager?.redo()
+ settle()
+ XCTAssertTrue(editor.string.contains("**flour**"), "and Redo brings it back")
+
+ board.clearContents()
+ board.setString("plain *as* copied", forType: .string)
+ editor.setSelectedRange(NSRange(location: (editor.string as NSString).length, length: 0))
+ XCTAssertTrue(editor.readSelection(from: board))
+ settle()
+ XCTAssertTrue(editor.string.hasSuffix("plain *as* copied"), editor.string)
+ XCTAssertTrue(model.text.hasSuffix("plain *as* copied"), model.text)
+ }
+}
+
private struct FocusedComposer: View {
let model: AskModel
@FocusState private var focused: Bool
diff --git a/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift b/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift
new file mode 100644
index 0000000..4545511
--- /dev/null
+++ b/native/apple/Tests/BaseKitTests/PasteMarkdownTests.swift
@@ -0,0 +1,67 @@
+@testable import BaseKit
+import Foundation
+import XCTest
+#if os(macOS)
+import AppKit
+#elseif os(iOS)
+import UIKit
+#endif
+
+/// A rich paste becomes the chat's Markdown (Paul, 2026-11-26). The HTML
+/// 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? }
+
+ func testTheSharedSamples() throws {
+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent()
+ .deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()
+ let data = try Data(contentsOf: root.appendingPathComponent("internal/browsertest/testdata/paste.json"))
+ 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)
+ }
+ }
+
+ func testPlainHTMLIsLeftAlone() {
+ XCTAssertNil(PasteMarkdown.fromHTML("<p>Just words, 2*3 and *stars*</p><p>Two lines</p>"))
+ XCTAssertNil(PasteMarkdown.fromHTML(""))
+ XCTAssertNil(PasteMarkdown.fromHTML("<b style=\"font-weight:normal\">not bold</b>"))
+ }
+
+ /// RTF (Mail, TextEdit, Notes, Safari): bold and italic faces, links,
+ /// and text lists.
+ func testRTF() throws {
+ #if os(macOS)
+ let body = NSFont(name: "Helvetica", size: 13)!
+ let bold = NSFontManager.shared.convert(body, toHaveTrait: .boldFontMask)
+ let italic = NSFontManager.shared.convert(body, toHaveTrait: .italicFontMask)
+ #else
+ let body = UIFont(name: "Helvetica", size: 13)!
+ let bold = UIFont(descriptor: body.fontDescriptor.withSymbolicTraits(.traitBold)!, size: 13)
+ let italic = UIFont(descriptor: body.fontDescriptor.withSymbolicTraits(.traitItalic)!, size: 13)
+ #endif
+ let text = NSMutableAttributedString()
+ func add(_ s: String, _ font: Any = body, link: String? = nil, list: NSTextList? = nil) {
+ var attributes: [NSAttributedString.Key: Any] = [.font: font]
+ if let link { attributes[.link] = URL(string: link)! }
+ if let list {
+ let style = NSMutableParagraphStyle()
+ style.textLists = [list]
+ attributes[.paragraphStyle] = style
+ }
+ text.append(NSAttributedString(string: s, attributes: attributes))
+ }
+ add("The "); add("flour", bold); add(" comes "); add("Thursday", italic); add(", see "); add("the order", link: "https://fennel.example/order"); add(".\n")
+ add("\n")
+ let bullets = NSTextList(markerFormat: .disc, options: 0)
+ add("\t•\tRye\n", list: bullets)
+ add("\t•\tSpelt\n", list: bullets)
+ add("Thanks")
+ let rtf = try text.data(from: NSRange(location: 0, length: text.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf])
+ XCTAssertEqual(PasteMarkdown.fromRTF(rtf), "The **flour** comes *Thursday*, see [the order](https://fennel.example/order).\n\n- Rye\n- Spelt\n\nThanks")
+ XCTAssertNil(PasteMarkdown.fromRTF(try NSAttributedString(string: "Plain\nlines", attributes: [.font: body])
+ .data(from: NSRange(location: 0, length: 11), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtf])))
+ }
+}
diff --git a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
index cedbd47..0a46d47 100644
--- a/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
+++ b/native/apple/Tests/BaseSnapshots/AskSnapshots.swift
@@ -47,6 +47,12 @@ final class AskSnapshots: XCTestCase {
JobView(job: AskFixtures.pausedJob, timeZone: AskFixtures.zone, close: {}, now: SnapshotSettings.now,
carryOnError: BaseText.text("ask.not_sent"))
},
+ // The person's own words in the Assistant's little Markdown
+ // (2026-11-26): bold, italics, a list with a link, lines kept;
+ // and a plain message, exactly as written.
+ SnapshotScreen("person-markdown", mac: .fixed(width: 640, height: 520), iphone: .fixed(width: 402, height: 620)) {
+ AskFrame { AskView(model: AskFixtures.personMarkdown(), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) }
+ },
SnapshotScreen("norunner", mac: .fixed(width: 640, height: 420), iphone: .fixed(width: 402, height: 520)) {
AskFrame { AskView(model: AskFixtures.model(state: "norunner", extra: AskFixtures.shortThread), layout: frameLayout, timeZone: AskFixtures.zone, actions: AskActions {}) }
},
@@ -149,6 +155,14 @@ struct AskFrame<Content: View>: View {
return m
}
+ 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":"m3","role":"person","text":"Two lines,\n2*3 and a_b_c stay as typed.","turn_id":"t2"}
+ """#)
+ }
+
/// A paused job that offers Carry on now, a stopped one and one working.
static func paused() -> AskModel {
let m = model(state: "ready", extra: #"{"id":"m1","role":"person","text":"Can you put together a simple website for the bakery?","turn_id":"t1"}"#)
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
new file mode 100644
index 0000000..267b702
Binary files /dev/null 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
new file mode 100644
index 0000000..70880b4
Binary files /dev/null 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
new file mode 100644
index 0000000..fbac551
Binary files /dev/null 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
new file mode 100644
index 0000000..6b4114d
Binary files /dev/null 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
new file mode 100644
index 0000000..0ae8453
Binary files /dev/null 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
new file mode 100644
index 0000000..b471977
Binary files /dev/null and b/native/apple/Tests/BaseSnapshots/__Snapshots__/base-ask/mac/person-markdown-light-default.png differ