Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat(chatwoot): preserve readable formatting in WhatsApp agent replies (#915)

gobeyondpty664df058abd7
diff --git a/docs/chatwoot.md b/docs/chatwoot.md
index 0b3bedb7..23630668 100644
--- a/docs/chatwoot.md
+++ b/docs/chatwoot.md
@@ -574,6 +574,30 @@ Text formatting is translated in both directions so emphasis survives the bridge
As in WhatsApp, a WhatsApp-side pair only counts at word boundaries and never inside links, so URLs such as `/_docs_/` or `?utm_source=wa&utm_medium=cta` and `snake_case` ids reach Chatwoot unchanged.
+Chatwoot hands an API-channel inbox the agent's reply as stored Markdown, and WhatsApp has no syntax for most of it. Replies sent from Chatwoot are therefore also flattened so the customer does not read raw Markdown:
+
+| Chatwoot reply | Delivered to WhatsApp |
+|----------------|-----------------------|
+| `[Our site](https://example.com/)` | `Our site: https://example.com/` |
+| `[**https://example.com/**](https://example.com/)` (the label is the URL) | `https://example.com/` |
+| `**https://example.com/**: https://example.com/` (how the reply box stores a canned reply holding such a link) | `https://example.com/` |
+| `<https://example.com/>`, `<[email protected]>`, `<tel:+15550100>` | `https://example.com/`, `[email protected]`, `+15550100` |
+| `[Write us](mailto:[email protected])`, `[Call](tel:+15550100)` | `Write us: [email protected]`, `Call: +15550100` |
+| `R\&D`, `snake\_case`, `1\.`, `https://example.com/?a=1\&b=2` | `R&D`, `snake_case`, `1.`, `https://example.com/?a=1&b=2` |
+| `***bold italic***` | `*_bold italic_*` |
+| `2 * 3 * 4`, `30*40*50 cm`, `* a bullet`, `Price* ... *Terms`, `****1234` | unchanged |
+| a last line holding only `--` | removed |
+
+- A delimiter only formats when it touches the text on its inner side, as in Markdown itself: `** spaced **` and arithmetic such as `2 * 3 * 4` are delivered as written. A single `*` additionally needs a word boundary on its outer side, because WhatsApp does not format inside a word: `30*40*50` stays as typed instead of becoming `30_40_50`.
+- URLs are never formatted: `*`, `_` and `~` inside a link (query strings, `snake_case` paths) are delivered as written, also when the link sits inside bold or italic text.
+ The markers that close bold, italic or strikethrough end the link when punctuation follows them, so `**https://example.com**!Thanks` is delivered as `*https://example.com*!Thanks`.
+- A link label counts as the URL only when it is the same address: scheme and host are compared without regard to case, the rest exactly. `[https://example.com/Invoice_A](https://example.com/invoicea)` keeps its label and is delivered as `https://example.com/Invoice_A: https://example.com/invoicea`.
+- An escaped delimiter (`\*`, `\~`) is delivered as the plain character and does not start formatting.
+- Inline code and fenced code blocks are delivered unchanged; WhatsApp renders both.
+- Lists (`- item`, `1. item`), line breaks, emoji and right-to-left text are delivered as written.
+- The `--` line is the separator Chatwoot appends when an agent sends with the signature switch on but has no signature text. A separator followed by a signature is kept. When nothing but the separator is left, no text message is sent; an attachment on the same reply still goes out, without a caption.
+- With `CHATWOOT_SIGN_MSG=true` the conversion applies to the agent's body; the agent name is added afterwards.
+
### Edits & deletions
- **Edits**: when a WhatsApp user edits a message, the new text is mirrored into Chatwoot as a threaded `✏️ **Edited:** …` note (controlled by `CHATWOOT_FORWARD_EDITS`, default on).
diff --git a/src/pkg/utils/chatwoot.go b/src/pkg/utils/chatwoot.go
index 4db6c2df..62c3eec9 100644
--- a/src/pkg/utils/chatwoot.go
+++ b/src/pkg/utils/chatwoot.go
@@ -2,6 +2,7 @@ package utils
import (
"regexp"
+ "strconv"
"strings"
)
@@ -68,6 +69,28 @@ func IsNewsletterJID(jid string) bool {
// (/_docs_/, ?utm_source=a&utm_medium=b) and snake_case ids pass through
// untouched. Sentinel runes guard the bold pass from being re-matched by the
// italic pass.
+//
+// On the Chatwoot side a delimiter only counts when it hugs the text it
+// formats, as in CommonMark: an opening run is not followed by whitespace and
+// a closing run is not preceded by it, so "2 * 3 * 4", "* a bullet" and
+// "Price* ... *Terms" stay as written. A single "*" must also sit at a word
+// boundary: WhatsApp would not render "30_40_50" as italic, so "30*40*50" is
+// better left alone than rewritten.
+//
+// Chatwoot -> WhatsApp additionally flattens the Markdown that WhatsApp has
+// no syntax for, because an API-channel inbox hands over the agent's message
+// as stored Markdown and the customer would otherwise read it raw:
+//
+// [label](url) -> label: url (just the url when the label is the url)
+// <https://x.example/> -> https://x.example/
+// \& \_ \* \. \- \( ... -> the bare character, never read as formatting
+// ***bold italic*** -> *_bold italic_*
+// **url**: url -> url (how Chatwoot's reply box stores a
+// canned reply holding such a link)
+// trailing "--" line -> dropped (signature separator, empty signature)
+//
+// Code spans, link targets and bare URLs are set aside before the emphasis
+// passes and put back verbatim afterwards.
const (
mdBoldSentinel = "\x01"
@@ -76,9 +99,20 @@ const (
)
var (
- reCwBold = regexp.MustCompile(`\*\*(.+?)\*\*`)
- reCwStrike = regexp.MustCompile(`~~(.+?)~~`)
- reCwItalic = regexp.MustCompile(`\*(.+?)\*`)
+ // Chatwoot-side emphasis. The text between a pair starts and ends with a
+ // character that is neither whitespace nor the delimiter, which is what
+ // keeps "2 * 3 * 4" and a masked "******" from pairing. The inner part is
+ // lazy ("??") so the pair closes at the first run that can close it.
+ //
+ // Bold may hold a nested italic at either end, where the runs touch:
+ // "**a *b***" (first alternative: the text ends with a whole "*b*") and
+ // "***a* b**" (second alternative: the text starts with "*"). The italic
+ // pass pairs the inner asterisks afterwards.
+ reCwBold = regexp.MustCompile(`\*\*((?:[^\s*][^*\n]*)?\*[^\s*](?:[^*\n]*[^\s*])?\*|(?:\*[^\s*]|[^\s*])(?:.*?[^\s*])??)\*\*`)
+ reCwStrike = regexp.MustCompile(`~~([^\s~](?:.*?[^\s~])??)~~`)
+ // Italic also needs a word boundary on both outer sides, captured as
+ // groups 1 and 3 because RE2 has no lookaround (see replaceWhatsAppPairs).
+ reCwItalic = regexp.MustCompile(`(^|[^\p{L}\p{N}*])\*([^\s*](?:.*?[^\s*])??)\*($|[^\p{L}\p{N}*])`)
// The link sentinel counts as a word character: a link starts with one.
reWaBold = regexp.MustCompile(`(^|[^\p{L}\p{N}*\x03])\*([^\s*](?:[^*\n]*[^\s*])?)\*($|[^\p{L}\p{N}*\x03])`)
reWaItalic = regexp.MustCompile(`(^|[^\p{L}\p{N}_\x03])_([^\s_](?:[^_\n]*[^\s_])?)_($|[^\p{L}\p{N}_\x03])`)
@@ -86,6 +120,31 @@ var (
// A trailing delimiter or punctuation stays outside the link, so
// "*https://x.com*!" still pairs.
reWaLink = regexp.MustCompile(`(?i:https?://|www\.)\S*[^\s*_~.,;:!?)\]'"]`)
+
+ // Text the Chatwoot -> WhatsApp passes must not read as Markdown: fenced
+ // and inline code, and backslash escapes. One left-to-right alternation, so
+ // an escaped backtick is consumed as an escape and cannot open a code span.
+ reCwLiteral = regexp.MustCompile("(?s)```.*?```|`[^`\\n]+`|" + `\\[!-/:-@\[-` + "`{-~]")
+ // [label](target "title"), optionally an image. Escapes are already hidden
+ // by reCwLiteral, so neither class needs to know about backslashes. The
+ // target may hold one level of balanced parentheses (Wikipedia-style).
+ reCwInlineLink = regexp.MustCompile(`(?i)!?\[([^\[\]\n]*)\]\(\s*<?((?:https?://|mailto:|tel:)(?:[^()\s<>]|\([^()\s<>]*\))*)>?(?:\s+"[^"\n]*")?\s*\)`)
+ reCwAutolink = regexp.MustCompile(`(?i)<((?:https?://|mailto:|tel:)[^<>\s]+)>`)
+ // The link sentinel is allowed in the local part: an escaped "_" is hidden.
+ reCwEmailAutolink = regexp.MustCompile(`<([A-Za-z0-9._%+\x03-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,})>`)
+ reCwBoldItalic = regexp.MustCompile(`\*\*\*([^\s*](?:[^*\n]*[^\s*])?)\*\*\*`)
+ reCwHidden = regexp.MustCompile(`\x03(\d+)\x03`)
+ reCwLinkScheme = regexp.MustCompile(`(?i)^(?:mailto|tel):`)
+ reCwLinkPrefix = regexp.MustCompile(`(?i)^(?:https?://|mailto:|tel:)`)
+ // Where a bare link starts; cwBareLinks finds where it ends.
+ reCwBareLinkStart = regexp.MustCompile(`(?i)https?://|www\.`)
+)
+
+// Characters that never end a bare link (the last class of reWaLink), and the
+// punctuation among them.
+const (
+ cwLinkTrailing = "*_~.,;:!?)]'\""
+ cwLinkPunctuation = ".,;:!?)]'\""
)
// stripMarkdownSentinels removes any pre-existing guard runes from input so
@@ -99,23 +158,283 @@ func stripMarkdownSentinels(s string) string {
return strings.NewReplacer(mdBoldSentinel, "", mdStrikeSentinel, "", mdLinkSentinel, "").Replace(s)
}
-// ChatwootToWhatsAppMarkdown rewrites Chatwoot/GFM markdown to WhatsApp's
-// formatting syntax: **bold**->*bold*, *italic*->_italic_, ~~strike~~->~strike~.
+// cwHidden holds text taken out of a Chatwoot message while it is converted,
+// so that later passes cannot read it as Markdown. Each piece is replaced by
+// its index between two link sentinels; input sentinels are stripped first, so
+// every sentinel in the working text is one of ours.
+type cwHidden struct{ parts []string }
+
+// hide stores text and returns its placeholder. text must already be expanded,
+// which keeps expand a single pass.
+func (h *cwHidden) hide(text string) string {
+ h.parts = append(h.parts, text)
+ return mdLinkSentinel + strconv.Itoa(len(h.parts)-1) + mdLinkSentinel
+}
+
+func (h *cwHidden) expand(s string) string {
+ if len(h.parts) == 0 || !strings.Contains(s, mdLinkSentinel) {
+ return s
+ }
+ return reCwHidden.ReplaceAllStringFunc(s, func(m string) string {
+ if i, err := strconv.Atoi(m[1 : len(m)-1]); err == nil && i < len(h.parts) {
+ return h.parts[i]
+ }
+ return ""
+ })
+}
+
+// ChatwootToWhatsAppMarkdown rewrites the Markdown of a Chatwoot agent message
+// to text WhatsApp displays as intended: **bold**->*bold*, *italic*->_italic_,
+// ~~strike~~->~strike~, ***both***->*_both_*, links and autolinks flattened to
+// plain URLs, backslash escapes removed, and the dangling "--" of an empty
+// Chatwoot signature dropped. Code and URLs pass through untouched. It returns
+// "" when nothing is left to send.
func ChatwootToWhatsAppMarkdown(s string) string {
- if s == "" || !strings.ContainsAny(s, "*~") {
+ if s == "" {
return s
}
- s = stripMarkdownSentinels(s)
+ if strings.ContainsAny(s, "*~[<\\") || strings.Contains(s, "://") {
+ s = convertChatwootMarkdown(stripMarkdownSentinels(s))
+ }
+ return dropEmptyChatwootSignature(s)
+}
+
+// convertChatwootMarkdown runs a fixed number of linear passes; none repeats
+// until stable, so the cost stays proportional to the message length.
+func convertChatwootMarkdown(s string) string {
+ hidden := &cwHidden{}
+ s = reCwLiteral.ReplaceAllStringFunc(s, func(m string) string {
+ if m[0] == '\\' {
+ return hidden.hide(m[1:])
+ }
+ return hidden.hide(m)
+ })
+ s = reCwInlineLink.ReplaceAllStringFunc(s, func(m string) string {
+ groups := reCwInlineLink.FindStringSubmatch(m)
+ label, target := strings.TrimSpace(groups[1]), hidden.expand(groups[2])
+ url := hidden.hide(reCwLinkScheme.ReplaceAllString(target, ""))
+ if label == "" || linkLabelRepeatsTarget(label, target, hidden) {
+ return url
+ }
+ return label + ": " + url
+ })
+ s = reCwAutolink.ReplaceAllStringFunc(s, func(m string) string {
+ return hidden.hide(reCwLinkScheme.ReplaceAllString(hidden.expand(m[1:len(m)-1]), ""))
+ })
+ s = reCwEmailAutolink.ReplaceAllStringFunc(s, func(m string) string {
+ return hidden.hide(hidden.expand(m[1 : len(m)-1]))
+ })
+ s = hideChatwootBareLinks(s, hidden)
+
// Bold first so its asterisks are hidden from the italic pass.
+ s = reCwBoldItalic.ReplaceAllString(s, mdBoldSentinel+"_${1}_"+mdBoldSentinel)
s = reCwBold.ReplaceAllString(s, mdBoldSentinel+"$1"+mdBoldSentinel)
s = reCwStrike.ReplaceAllString(s, mdStrikeSentinel+"$1"+mdStrikeSentinel)
- // "${1}" (braced) is required: a bare "$1_" parses as the named group "1_"
- // (underscore is a legal $name char), which would drop the capture and
- // collapse *italic* to a lone "_".
- s = reCwItalic.ReplaceAllString(s, "_${1}_")
+ s = replaceWhatsAppPairs(reCwItalic, s, "_")
s = strings.ReplaceAll(s, mdBoldSentinel, "*")
s = strings.ReplaceAll(s, mdStrikeSentinel, "~")
- return s
+ return hidden.expand(s)
+}
+
+// linkLabelRepeatsTarget reports whether a link's label shows the address the
+// link points to, as in "[**https://x/**](https://x/)", so that the address is
+// emitted once. label is still unexpanded: its escaped characters are hidden,
+// which is what tells the emphasis around a label from a literal "_", "*" or
+// "~" inside it.
+func linkLabelRepeatsTarget(label, target string, hidden *cwHidden) bool {
+ // Emphasis wraps the label in matching markers; anything else is text.
+ for len(label) >= 2 && strings.IndexByte("*_~", label[0]) >= 0 && label[len(label)-1] == label[0] {
+ label = label[1 : len(label)-1]
+ }
+ text := hidden.expand(label)
+ // A label that is one code span shows its content.
+ if reCwHidden.FindString(label) == label && len(text) >= 2 && text[0] == '`' {
+ text = strings.Trim(text, "`")
+ }
+ return comparableLinkText(text) == comparableLinkText(target)
+}
+
+// comparableLinkText reduces an address to what decides where it leads, for
+// comparing a link's label with its target. The scheme is dropped and the host
+// lowercased, because neither changes the destination a reader sees; so is the
+// lone slash after a host. Path, query and fragment are case-sensitive and may
+// hold any character, so they are compared as written.
+func comparableLinkText(s string) string {
+ s = strings.TrimSpace(s)
+ s = s[len(reCwLinkPrefix.FindString(s)):]
+ host, rest := s, ""
+ if i := strings.IndexAny(s, "/?#"); i >= 0 {
+ host, rest = s[:i], s[i:]
+ }
+ if rest == "/" {
+ rest = ""
+ }
+ return strings.ToLower(host) + rest
+}
+
+// cwBareLinks walks the plain URLs of a Chatwoot message from left to right.
+// It finds the same links as reWaLink, except that a link also ends at the
+// markers closing an emphasis that was opened before it, when punctuation
+// follows them: "**https://x.example**!Thanks" is a bold link and "!Thanks",
+// not one address. Without an open emphasis, or with more of the address after
+// the markers ("/a**b"), they stay part of the link.
+type cwBareLinks struct {
+ s string
+ pos int
+ // open holds the emphasis runs seen an odd number of times in the text
+ // before pos on its line, indexed by emphasisRun. Emphasis does not span
+ // lines.
+ open [4]bool
+}
+
+// emphasisRun indexes the marker runs Chatwoot reads as emphasis.
+func emphasisRun(run string) int {
+ switch run {
+ case "*":
+ return 0
+ case "**":
+ return 1
+ case "***":
+ return 2
+ case "~~":
+ return 3
+ }
+ return -1
+}
+
+// next returns the bounds of the next link and moves past it. Every byte is
+// read a bounded number of times, however the links are laid out.
+func (l *cwBareLinks) next() (start, end int, ok bool) {
+ for l.pos < len(l.s) {
+ loc := reCwBareLinkStart.FindStringIndex(l.s[l.pos:])
+ if loc == nil {
+ l.pos = len(l.s)
+ break
+ }
+ start = l.pos + loc[0]
+ body := l.pos + loc[1]
+ l.note(l.s[l.pos:start])
+ l.pos = body
+ if end = l.end(body); end > body {
+ l.pos = end
+ return start, end, true
+ }
+ // Only punctuation follows the scheme: not a link.
+ }
+ return 0, 0, false
+}
+
+// note records the emphasis runs of text that lies between two links.
+func (l *cwBareLinks) note(text string) {
+ for i := 0; i < len(text); {
+ c := text[i]
+ if c == '\n' {
+ l.open = [4]bool{}
+ }
+ if c != '*' && c != '~' {
+ i++
+ continue
+ }
+ j := i + 1
+ for j < len(text) && text[j] == c {
+ j++
+ }
+ if k := emphasisRun(text[i:j]); k >= 0 {
+ l.open[k] = !l.open[k]
+ }
+ i = j
+ }
+}
+
+// end returns where the link whose address starts at body ends, or body when
+// it has no address.
+func (l *cwBareLinks) end(body int) int {
+ s := l.s
+ i := body
+ for i < len(s) && !isRegexpSpace(s[i]) {
+ c := s[i]
+ if c != '*' && c != '~' {
+ i++
+ continue
+ }
+ j := i + 1
+ for j < len(s) && s[j] == c {
+ j++
+ }
+ if k := emphasisRun(s[i:j]); k >= 0 && l.open[k] &&
+ j < len(s) && strings.IndexByte(cwLinkPunctuation, s[j]) >= 0 {
+ if end := body + len(strings.TrimRight(s[body:i], cwLinkTrailing)); end > body {
+ return end
+ }
+ }
+ i = j
+ }
+ return body + len(strings.TrimRight(s[body:i], cwLinkTrailing))
+}
+
+// isRegexpSpace reports what \s matches in a Go regular expression.
+func isRegexpSpace(c byte) bool {
+ return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r'
+}
+
+// hideChatwootBareLinks sets every plain URL aside so its asterisks,
+// underscores and tildes survive the emphasis passes. A URL followed by ": "
+// and the same URL again is Chatwoot's reply box having flattened a link whose
+// label was the URL ("**https://x/**: https://x/"); it is emitted once.
+func hideChatwootBareLinks(s string, hidden *cwHidden) string {
+ links := cwBareLinks{s: s}
+ start, end, ok := links.next()
+ if !ok {
+ return s
+ }
+ var b strings.Builder
+ last := 0
+ for ok {
+ url := hidden.expand(s[start:end])
+ nextStart, nextEnd, nextOK := links.next()
+ if nextOK {
+ marker, dup := duplicatedLinkMarker(s[last:start], s[end:nextStart])
+ if dup && hidden.expand(s[nextStart:nextEnd]) == url {
+ start -= len(marker)
+ end = nextEnd
+ nextStart, nextEnd, nextOK = links.next()
+ }
+ }
+ b.WriteString(s[last:start])
+ b.WriteString(hidden.hide(url))
+ last = end
+ start, end, ok = nextStart, nextEnd, nextOK
+ }
+ b.WriteString(s[last:])
+ return b.String()
+}
+
+// duplicatedLinkMarker reports whether between (the text separating two URLs)
+// is ": " after an optional closing emphasis marker of up to three characters
+// that also precedes the first URL, and returns that marker.
+func duplicatedLinkMarker(before, between string) (string, bool) {
+ marker, ok := strings.CutSuffix(between, ": ")
+ if !ok || len(marker) > 3 || strings.Trim(marker, "*_~") != "" {
+ return "", false
+ }
+ return marker, strings.HasSuffix(before, marker)
+}
+
+// dropEmptyChatwootSignature removes a last line holding only "--". Chatwoot
+// appends "\n\n--\n\n<signature>" for an agent who sends with signature; with
+// an empty signature only the separator arrives. A separator that is followed
+// by signature text, and "--" inside a sentence, are left alone.
+func dropEmptyChatwootSignature(s string) string {
+ const blank = " \t\r\n"
+ body, ok := strings.CutSuffix(strings.TrimRight(s, blank), "--")
+ if !ok {
+ return s
+ }
+ body = strings.TrimRight(body, " \t")
+ if body != "" && !strings.HasSuffix(body, "\n") {
+ return s
+ }
+ return strings.TrimRight(body, blank)
}
// WhatsAppToChatwootMarkdown rewrites WhatsApp formatting to Chatwoot/GFM
@@ -150,11 +469,15 @@ func WhatsAppToChatwootMarkdown(s string) string {
return b.String()
}
-// replaceWhatsAppPairs swaps the delimiters of every re match for marker. It
-// runs twice because adjacent pairs ("*a* *b*") share the boundary character
+// replaceWhatsAppPairs swaps the delimiters of every re match for marker. re
+// captures the boundary before the pair, its text and the boundary after it.
+// It runs twice because adjacent pairs ("*a* *b*") share the boundary character
// between them, which a single pass consumes. It must not loop until stable:
// each extra pass unwraps another nesting level, so crafted input would cost
// one pass per level.
+//
+// The braced "${2}" matters: a bare "$2_" would be read as the group named
+// "2_" and drop the text.
func replaceWhatsAppPairs(re *regexp.Regexp, s, marker string) string {
repl := "${1}" + marker + "${2}" + marker + "${3}"
return re.ReplaceAllString(re.ReplaceAllString(s, repl), repl)
diff --git a/src/pkg/utils/chatwoot_test.go b/src/pkg/utils/chatwoot_test.go
index 8e8b4963..645fbcf3 100644
--- a/src/pkg/utils/chatwoot_test.go
+++ b/src/pkg/utils/chatwoot_test.go
@@ -3,6 +3,7 @@ package utils
import (
"strings"
"testing"
+ "time"
)
func TestMatchesIgnoredJID(t *testing.T) {
@@ -207,15 +208,15 @@ func TestChatwootToWhatsAppMarkdown(t *testing.T) {
want: "",
},
{
- // Plain text with no * or ~ takes the ContainsAny fast path and is
- // returned byte-for-byte unchanged.
+ // Plain text with nothing that could be Markdown skips the
+ // conversion and is returned byte-for-byte unchanged.
name: "PlainTextNoMarkersFastPath",
in: "hello world",
want: "hello world",
},
{
// Underscores alone are not a Chatwoot marker here, so the fast path
- // returns them untouched (no * or ~ present).
+ // returns them untouched.
name: "UnderscoresUntouchedFastPath",
in: "a_b_c",
want: "a_b_c",
@@ -234,9 +235,9 @@ func TestChatwootToWhatsAppMarkdown(t *testing.T) {
want: "*x*",
},
{
- // *italic* -> _italic_. The braced "${1}" template terminates the
- // group reference before the trailing underscore, so the capture is
- // preserved (a bare "$1_" would parse "1_" as a named group and drop it).
+ // *italic* -> _italic_. The replacement template braces its group
+ // reference: a bare "$2_" would be read as the group named "2_" and
+ // drop the text.
name: "ItalicAlone",
in: "*italic*",
want: "_italic_",
@@ -280,6 +281,522 @@ func TestChatwootToWhatsAppMarkdown(t *testing.T) {
in: "\x01**bold**\x02",
want: "*bold*",
},
+ {
+ name: "MixedEmphasisInSentence",
+ in: "Dear **Dana**, your *cabin* is ~~12A~~ **14B**.",
+ want: "Dear *Dana*, your _cabin_ is ~12A~ *14B*.",
+ },
+ {
+ // ***x*** used to come out as "_x*_".
+ name: "BoldItalic",
+ in: "***Cancun, Mexico***\n**Total**",
+ want: "*_Cancun, Mexico_*\n*Total*",
+ },
+ {
+ name: "MultiLine",
+ in: "line one\n\n**line two**\nline *three*",
+ want: "line one\n\n*line two*\nline _three_",
+ },
+ {
+ name: "EmojiAndBold",
+ in: "🌴 **Welcome** 🚢 see you ~~soon~~ *now* 👍🏽",
+ want: "🌴 *Welcome* 🚢 see you ~soon~ _now_ 👍🏽",
+ },
+ {
+ name: "RightToLeftText",
+ in: "**שלום** לכולם, *תודה* רבה: [האתר שלנו](https://x.example/he)",
+ want: "*שלום* לכולם, _תודה_ רבה: האתר שלנו: https://x.example/he",
+ },
+ {
+ // Bullets and numbering are plain text on WhatsApp; Chatwoot
+ // escapes the dot of a typed "1." to keep it from becoming a list.
+ name: "ListsPreserved",
+ in: "Options:\n- **Balcony** cabin\n- Inside cabin\n\n1. Pay deposit\n2. Send passports\n3\\. Done",
+ want: "Options:\n- *Balcony* cabin\n- Inside cabin\n\n1. Pay deposit\n2. Send passports\n3. Done",
+ },
+ {
+ name: "InlineLink",
+ in: "- [Symphony of the Seas](https://x.example/royal/symphony-of-the-seas/jan-24-2027/) ",
+ want: "- Symphony of the Seas: https://x.example/royal/symphony-of-the-seas/jan-24-2027/ ",
+ },
+ {
+ // A canned reply whose link label is the URL: one URL, not
+ // "url: url" and not the raw brackets.
+ name: "InlineLinkLabelIsBoldURL",
+ in: "form: [**https://x.example/events/registration/**](https://x.example/events/registration/)",
+ want: "form: https://x.example/events/registration/",
+ },
+ {
+ name: "InlineLinkLabelIsURLAfterEmoji",
+ in: "🌐 [**https://x.example/**](https://x.example/)",
+ want: "🌐 https://x.example/",
+ },
+ {
+ name: "InlineLinkLabelIsURLIgnoringTrailingSlashAndCase",
+ in: "[_HTTPS://X.example_](https://x.example/)",
+ want: "https://x.example/",
+ },
+ {
+ // The escaped "&" used to end the link on the phone.
+ name: "InlineLinkEscapedAmpersandInTarget",
+ in: "[https://x.example/a?shareId=5&asset=1](https://x.example/a?shareId=5\\&asset=1)",
+ want: "https://x.example/a?shareId=5&asset=1",
+ },
+ {
+ name: "InlineLinkMailto",
+ in: "email: [**[email protected]**](mailto:[email protected])",
+ want: "email: [email protected]",
+ },
+ {
+ name: "InlineLinkTel",
+ in: "[Call us](tel:+15550100)",
+ want: "Call us: +15550100",
+ },
+ {
+ // The label keeps its emphasis; the title is dropped.
+ name: "InlineLinkBoldLabelAndTitle",
+ in: "see [**Splash Academy**](https://www.x.example/kids \"Kids\") now",
+ want: "see *Splash Academy*: https://www.x.example/kids now",
+ },
+ {
+ name: "InlineLinkBalancedParentheses",
+ in: "[wiki](https://x.example/wiki/Mercury_(planet)) ok",
+ want: "wiki: https://x.example/wiki/Mercury_(planet) ok",
+ },
+ {
+ name: "InlineLinkEmptyLabel",
+ in: "[](https://x.example/a) [ ](<https://x.example/b>)",
+ want: "https://x.example/a https://x.example/b",
+ },
+ {
+ // Emphasis around a whole link still converts; the target's own
+ // delimiters do not take part.
+ name: "InlineLinkInsideBoldWithDelimitersInTarget",
+ in: "**[Book *now*](https://x.example/a_b/*c*/?utm_source=cw&utm_medium=~x~)**",
+ want: "*Book _now_: https://x.example/a_b/*c*/?utm_source=cw&utm_medium=~x~*",
+ },
+ {
+ name: "TwoInlineLinksOnOneLine",
+ in: "[A](https://x.example/a) and [B](https://x.example/b)",
+ want: "A: https://x.example/a and B: https://x.example/b",
+ },
+ {
+ name: "MessageThatIsOnlyALink",
+ in: "https://x.example/t?utm_source=wa&utm_medium=tpl",
+ want: "https://x.example/t?utm_source=wa&utm_medium=tpl",
+ },
+ {
+ name: "MessageThatIsOnlyAMarkdownLink",
+ in: "[https://x.example/](https://x.example/)",
+ want: "https://x.example/",
+ },
+ {
+ name: "NotALink",
+ in: "2 < 3 and [not a link] (really), [relative](/path), a[0](x)",
+ want: "2 < 3 and [not a link] (really), [relative](/path), a[0](x)",
+ },
+ {
+ // An escaped bracket is literal text, not the start of a link.
+ name: "EscapedBracketsAreNotALink",
+ in: "\\[label\\](https://x.example/)",
+ want: "[label](https://x.example/)",
+ },
+ {
+ name: "Autolink",
+ in: "here: <https://x.example/3qdiakdIIl0?si=4_xh80NjuF5HdWea>",
+ want: "here: https://x.example/3qdiakdIIl0?si=4_xh80NjuF5HdWea",
+ },
+ {
+ name: "AutolinkMailtoAndEmail",
+ in: "write <[email protected]> or <mailto:first\\[email protected]>, <not an autolink>",
+ want: "write [email protected] or [email protected], <not an autolink>",
+ },
+ {
+ name: "BackslashEscapes",
+ in: "a \\- b 1\\. c snake\\_case R\\&D \\(x\\) \\#1 \\+ \\! \\\\ \\[y\\]",
+ want: "a - b 1. c snake_case R&D (x) #1 + ! \\ [y]",
+ },
+ {
+ // A backslash before a letter or digit is not an escape.
+ name: "BackslashBeforeAlphanumericKept",
+ in: "C:\\temp\\1 and a trailing \\",
+ want: "C:\\temp\\1 and a trailing \\",
+ },
+ {
+ // Escaped delimiters are literal: they must not pair up.
+ name: "EscapedDelimitersDoNotFormat",
+ in: "5 \\* 3 \\* 2 and \\~x\\~ and **b\\*b**",
+ want: "5 * 3 * 2 and ~x~ and *b*b*",
+ },
+ {
+ name: "EscapedAmpersandInBareURL",
+ in: "https://x.example/q?a=1\\&b=2\\&c\\_d=3 ok",
+ want: "https://x.example/q?a=1&b=2&c_d=3 ok",
+ },
+ {
+ name: "BareURLQueryUnchanged",
+ in: "plain https://x.example/q?a=2&t=0&c=0&i=0&f=1&it=1",
+ want: "plain https://x.example/q?a=2&t=0&c=0&i=0&f=1&it=1",
+ },
+ {
+ // The two asterisks in the URL used to pair as italic.
+ name: "BareURLWithAsterisksUnchanged",
+ in: "https://x.example/search?q=*summer*&sort=~price~ and www.x.example/*a*/~b~",
+ want: "https://x.example/search?q=*summer*&sort=~price~ and www.x.example/*a*/~b~",
+ },
+ {
+ name: "BareURLWithUnderscoresNextToItalic",
+ in: "*see* https://x.example/snake_case_path/_docs_/?utm_source=cw *now*",
+ want: "_see_ https://x.example/snake_case_path/_docs_/?utm_source=cw _now_",
+ },
+ {
+ name: "BoldBareURL",
+ in: "**https://x.example/manual-payment**",
+ want: "*https://x.example/manual-payment*",
+ },
+ {
+ name: "EmphasisSpanningBareURL",
+ in: "**pay at https://x.example/a*b*c today** and ~~https://x.example/~old/x~~",
+ want: "*pay at https://x.example/a*b*c today* and ~https://x.example/~old/x~",
+ },
+ {
+ // What Chatwoot's reply box stores when a canned reply holding
+ // [**url**](url) is inserted.
+ name: "DuplicatedLinkFromCannedReply",
+ in: "form: **https://x.example/events/registration/**: https://x.example/events/registration/\n\nTo help",
+ want: "form: https://x.example/events/registration/\n\nTo help",
+ },
+ {
+ name: "DuplicatedLinkWithoutEmphasis",
+ in: "https://x.example/a_b: https://x.example/a_b",
+ want: "https://x.example/a_b",
+ },
+ {
+ name: "DuplicatedLinkTwice",
+ in: "*https://x.example/a*: https://x.example/a and https://x.example/b: https://x.example/b",
+ want: "https://x.example/a and https://x.example/b",
+ },
+ {
+ name: "DifferentLinksAreNotDuplicates",
+ in: "https://x.example/x: https://x.example/xy, Site https://x.example/x: https://y.example/y, https://x.example/x - https://x.example/x",
+ want: "https://x.example/x: https://x.example/xy, Site https://x.example/x: https://y.example/y, https://x.example/x - https://x.example/x",
+ },
+ {
+ // The opening marker is missing, so this is not the reply box's
+ // flattened link; keep both.
+ name: "UnbalancedMarkerIsNotADuplicate",
+ in: "https://x.example/x**: https://x.example/x",
+ want: "https://x.example/x**: https://x.example/x",
+ },
+ {
+ name: "InlineCodeUntouched",
+ in: "run `**not bold** [a](https://x.example/) \\_ <https://x.example/>` then **bold**",
+ want: "run `**not bold** [a](https://x.example/) \\_ <https://x.example/>` then *bold*",
+ },
+ {
+ name: "CodeBlockUntouched",
+ in: "**before**\n```\n**a** *b* ~~c~~ \\* [l](https://x.example/)\n--\n```\n*after*",
+ want: "*before*\n```\n**a** *b* ~~c~~ \\* [l](https://x.example/)\n--\n```\n_after_",
+ },
+ {
+ // An escaped backtick is a literal backtick, not a code span.
+ name: "EscapedBacktickIsNotCode",
+ in: "\\`**bold**\\`",
+ want: "`*bold*`",
+ },
+ {
+ // Signature switch on, signature empty: Chatwoot appends only the
+ // separator.
+ name: "EmptySignatureSeparatorDropped",
+ in: "Thanks **a lot**\n\n\n--\n\n",
+ want: "Thanks *a lot*",
+ },
+ {
+ name: "EmptySignatureSeparatorDroppedPlainText",
+ in: "Thanks\r\n\r\n -- \t\r\n",
+ want: "Thanks",
+ },
+ {
+ name: "OnlySignatureSeparatorPadded",
+ in: "\n\n--\n\n",
+ want: "",
+ },
+ {
+ name: "OnlySignatureSeparator",
+ in: "--",
+ want: "",
+ },
+ {
+ name: "EscapedSignatureSeparator",
+ in: "ok\n\n\\-\\-",
+ want: "ok",
+ },
+ {
+ name: "SignatureWithTextKept",
+ in: "Thanks\n\n--\nDana\nAcme Travel",
+ want: "Thanks\n\n--\nDana\nAcme Travel",
+ },
+ {
+ name: "DashesInSentenceKept",
+ in: "prices -- as agreed\nsee you --",
+ want: "prices -- as agreed\nsee you --",
+ },
+ {
+ name: "LongerDashLineKept",
+ in: "above\n---",
+ want: "above\n---",
+ },
+ {
+ // Trailing whitespace is only trimmed together with a separator.
+ name: "TrailingWhitespaceKept",
+ in: "hello \n",
+ want: "hello \n",
+ },
+ {
+ // Arithmetic is not emphasis: a delimiter has to hug the text.
+ name: "SpacedAsterisksUnchanged",
+ in: "2 * 3 * 4 = 24 and 10 * 20",
+ want: "2 * 3 * 4 = 24 and 10 * 20",
+ },
+ {
+ // Dimensions: WhatsApp would show "30_40_50" literally, so a
+ // mid-word asterisk pair is left as typed.
+ name: "MidWordAsterisksUnchanged",
+ in: "Box 30*40*50 cm, un*believ*able",
+ want: "Box 30*40*50 cm, un*believ*able",
+ },
+ {
+ name: "FootnoteAsterisksUnchanged",
+ in: "Price* includes tax, rated 5* and 4*.\n*Subject to change",
+ want: "Price* includes tax, rated 5* and 4*.\n*Subject to change",
+ },
+ {
+ // A "*" bullet used to pair with the emphasis on its own line.
+ name: "AsteriskBulletsWithEmphasis",
+ in: "* cabin with *balcony*\n* **inside** cabin\n* plain",
+ want: "* cabin with _balcony_\n* *inside* cabin\n* plain",
+ },
+ {
+ name: "MaskedDigitsUnchanged",
+ in: "Card ending ****1234, PIN ******, code ~~~~",
+ want: "Card ending ****1234, PIN ******, code ~~~~",
+ },
+ {
+ name: "SpacedPairsUnchanged",
+ in: "~~ a ~~ and ** b ** and * c * and *** d ***",
+ want: "~~ a ~~ and ** b ** and * c * and *** d ***",
+ },
+ {
+ // A closing run preceded by a space cannot close; the next one can.
+ name: "CloserMustHugText",
+ in: "**a ** b** and *c * d* and ~~e ~~ f~~",
+ want: "*a ** b* and _c * d_ and ~e ~~ f~",
+ },
+ {
+ name: "AdjacentPairs",
+ in: "*a* *b* *c*, **d** **e**, ~~f~~ ~~g~~, *h*,*i*,*j*",
+ want: "_a_ _b_ _c_, *d* *e*, ~f~ ~g~, _h_,_i_,_j_",
+ },
+ {
+ name: "ItalicNextToPunctuation",
+ in: "(*a*) \"*b*\" *c*, *d*. *e*! *f*? [*g*] *h*:",
+ want: "(_a_) \"_b_\" _c_, _d_. _e_! _f_? [_g_] _h_:",
+ },
+ {
+ // Italic at either end of bold, as the reply editor writes it.
+ name: "ItalicNestedInBold",
+ in: "***it* bold** and **bold *it*** and **a *b* c**",
+ want: "*_it_ bold* and *bold _it_* and *a _b_ c*",
+ },
+ {
+ name: "BoldNestedInItalic",
+ in: "*it **bold*** and *a **b** c*",
+ want: "_it *bold*_ and _a *b* c_",
+ },
+ {
+ name: "BoldThenItalicWithoutSpace",
+ in: "**a***b* and **a****b**",
+ want: "*a*_b_ and *a**b*",
+ },
+ {
+ name: "PricesTimesAndPhones",
+ in: "$1,200 - $1,500 per person (10:30 - 11:45), call +1 (555) 010-9999 or +972-50-123-4567 ~ 5 min",
+ want: "$1,200 - $1,500 per person (10:30 - 11:45), call +1 (555) 010-9999 or +972-50-123-4567 ~ 5 min",
+ },
+ {
+ name: "PriceInBold",
+ in: "Total: **$1,200 - $1,500**/person* (~10% off)",
+ want: "Total: *$1,200 - $1,500*/person* (~10% off)",
+ },
+ {
+ name: "EmailAddresses",
+ },
+ {
+ name: "FileNamesWithUnderscores",
+ in: "see report_final_v2.pdf, my\\_file\\_name.pdf and *price_list_2027.xlsx*",
+ want: "see report_final_v2.pdf, my_file_name.pdf and _price_list_2027.xlsx_",
+ },
+ {
+ name: "HebrewNextToURL",
+ in: "**ראו:** https://x.example/דף?a_b=1 *תודה* (<https://x.example/he_il>)",
+ want: "*ראו:* https://x.example/דף?a_b=1 _תודה_ (https://x.example/he_il)",
+ },
+ {
+ name: "ArabicNextToURL",
+ in: "مرحبا **بكم** في [موقعنا](https://x.example/ar_page) و https://x.example/a*b*.",
+ want: "مرحبا *بكم* في موقعنا: https://x.example/ar_page و https://x.example/a*b*.",
+ },
+ {
+ name: "SeveralLinksInOneMessage",
+ in: "[a](https://a.example/x_y) and [b](https://b.example/*z*), also https://c.example/~w~! <https://d.example/>",
+ want: "a: https://a.example/x_y and b: https://b.example/*z*, also https://c.example/~w~! https://d.example/",
+ },
+ {
+ name: "NumberedAndBulletedLists",
+ in: "1. **First**\n2. *Second*\n3. ~~Third~~\n- a\n+ b\n* c\n\n1) d\n10\\. e",
+ want: "1. *First*\n2. _Second_\n3. ~Third~\n- a\n+ b\n* c\n\n1) d\n10. e",
+ },
+ {
+ name: "URLInParentheses",
+ in: "our site (https://x.example/a_b) and (see *https://x.example/c_d*).",
+ want: "our site (https://x.example/a_b) and (see _https://x.example/c_d_).",
+ },
+ {
+ name: "URLFollowedByPeriod",
+ in: "Visit https://x.example/a_b. Or [here](https://x.example/c_d). Thanks",
+ want: "Visit https://x.example/a_b. Or here: https://x.example/c_d. Thanks",
+ },
+ {
+ name: "URLWithParentheses",
+ in: "https://x.example/wiki/Foo_(bar) and [w](https://x.example/wiki/Foo_(bar))",
+ want: "https://x.example/wiki/Foo_(bar) and w: https://x.example/wiki/Foo_(bar)",
+ },
+ {
+ name: "ImageLink",
+ in: "![logo](https://x.example/logo_small.png)",
+ want: "logo: https://x.example/logo_small.png",
+ },
+ {
+ name: "AutolinkTel",
+ in: "call <tel:+15550100>",
+ want: "call +15550100",
+ },
+ {
+ name: "AngleBracketsThatAreNotLinks",
+ in: "a < b and c > d, <3, <b>x</b>, <not a link>",
+ want: "a < b and c > d, <3, <b>x</b>, <not a link>",
+ },
+ {
+ name: "BracketsThatAreNotLinks",
+ in: "[x] (https://x.example/a) and [x](not a link) and [1] and [a\nb](https://x.example/b)",
+ want: "[x] (https://x.example/a) and [x](not a link) and [1] and [a\nb](https://x.example/b)",
+ },
+ {
+ name: "BackslashesInPaths",
+ in: "C:\\Users\\name and C:\\\\temp\\\\x, 50\\% off \\#1",
+ want: "C:\\Users\\name and C:\\temp\\x, 50% off #1",
+ },
+ {
+ // A link sentinel in the input must not be read as a placeholder.
+ name: "PreExistingLinkSentinelStripped",
+ in: "\x030\x03 **a** \x03 https://x.example/",
+ want: "0 *a* https://x.example/",
+ },
+ {
+ // A label that differs from the target only by a literal "_" and
+ // by path case names another address; it is kept.
+ name: "LinkLabelDifferingByUnderscoreAndPathCaseKept",
+ in: "[https://x.example/Invoice_A](https://x.example/invoicea)",
+ want: "https://x.example/Invoice_A: https://x.example/invoicea",
+ },
+ {
+ // Paths are case-sensitive.
+ name: "LinkLabelDifferingByPathCaseKept",
+ in: "[https://x.example/Invoice](https://x.example/invoice)",
+ want: "https://x.example/Invoice: https://x.example/invoice",
+ },
+ {
+ // So are queries and fragments.
+ name: "LinkLabelDifferingByQueryOrFragmentCaseKept",
+ in: "[https://x.example/a?Id=1](https://x.example/a?id=1) [https://x.example/a#Top](https://x.example/a#top)",
+ want: "https://x.example/a?Id=1: https://x.example/a?id=1 https://x.example/a#Top: https://x.example/a#top",
+ },
+ {
+ // "_", "*" and "~" inside an address are part of it.
+ name: "LinkLabelDifferingByLiteralFormattingCharactersKept",
+ in: "[https://x.example/a_b](https://x.example/ab) [https://x.example/a\\*b](https://x.example/ab) [https://x.example/~u](https://x.example/u)",
+ want: "https://x.example/a_b: https://x.example/ab https://x.example/a*b: https://x.example/ab https://x.example/~u: https://x.example/u",
+ },
+ {
+ // A trailing "_" that has no opening partner is not formatting.
+ name: "LinkLabelDifferingByTrailingUnderscoreKept",
+ in: "[https://x.example/a_](https://x.example/a)",
+ want: "https://x.example/a_: https://x.example/a",
+ },
+ {
+ // Only a slash after the host is ignored, not one that ends a path.
+ name: "LinkLabelDifferingByPathTrailingSlashKept",
+ in: "[https://x.example/a](https://x.example/a/)",
+ want: "https://x.example/a: https://x.example/a/",
+ },
+ {
+ // Scheme and host are case-insensitive, and the formatting around
+ // the label is not part of it: same address, emitted once.
+ name: "LinkLabelSameAddressDifferentHostCaseCollapsed",
+ in: "[**HTTPS://X.Example/Invoice_A**](https://x.example/Invoice_A) [*~~https://X.EXAMPLE~~*](https://x.example/)",
+ want: "https://x.example/Invoice_A https://x.example/",
+ },
+ {
+ // The label may repeat the address with its "_" escaped or as code.
+ name: "LinkLabelEscapedOrCodeSameAddressCollapsed",
+ in: "[https://x.example/a\\_b](https://x.example/a_b) [`https://x.example/c_d`](https://x.example/c_d)",
+ want: "https://x.example/a_b https://x.example/c_d",
+ },
+ {
+ // The closing markers end the link even when text follows them
+ // without a space.
+ name: "BoldBareURLFollowedByPunctuationAndText",
+ in: "**https://x.example**!Thanks",
+ want: "*https://x.example*!Thanks",
+ },
+ {
+ name: "EmphasisedBareURLsFollowedByPunctuationAndText",
+ in: "*https://x.example/a_b*,ok ~~https://x.example/c~~.gone ***https://x.example/d***;e",
+ want: "_https://x.example/a_b_,ok ~https://x.example/c~.gone *_https://x.example/d_*;e",
+ },
+ {
+ // The emphasis may open before the link.
+ name: "BoldSentenceEndingInURLFollowedByPunctuationAndText",
+ in: "**see https://x.example/a**!Thanks",
+ want: "*see https://x.example/a*!Thanks",
+ },
+ {
+ name: "AdjacentBoldURLsWithoutSpaces",
+ in: "**https://a.example**,**https://b.example**!x",
+ want: "*https://a.example*,*https://b.example*!x",
+ },
+ {
+ // With no emphasis open, the same characters belong to the address.
+ name: "URLWithLiteralAsterisksAndNoOpenEmphasis",
+ in: "https://x.example/a**!b and **bold** https://x.example/c**!d",
+ want: "https://x.example/a**!b and *bold* https://x.example/c**!d",
+ },
+ {
+ // Inside emphasis, a marker followed by more of the address stays
+ // in the address.
+ name: "URLWithLiteralAsterisksInsideEmphasis",
+ in: "**see https://x.example/a**b/c now**",
+ want: "*see https://x.example/a**b/c now*",
+ },
+ {
+ // Emphasis does not span lines, so an unclosed opener on an
+ // earlier line does not cut an address.
+ name: "UnclosedEmphasisOnEarlierLineDoesNotCutURL",
+ in: "**open\nhttps://x.example/a**!b",
+ want: "**open\nhttps://x.example/a**!b",
+ },
}
for _, tt := range tests {
@@ -447,6 +964,61 @@ func TestWhatsAppToChatwootMarkdown(t *testing.T) {
}
}
+// TestChatwootToWhatsAppMarkdownHostileInput feeds the converter large inputs
+// built to make a careless implementation backtrack or re-scan. Go's regexp
+// never backtracks, but ReplaceAll starts a new search after every match, so
+// an opener that stays alive across many short matches would still cost one
+// scan per match; the inputs below try exactly that for every pattern. Each
+// takes about 0.1s (2s under the race detector), where a quadratic pass would
+// take minutes, so the bound leaves a loaded CI runner plenty of room.
+func TestChatwootToWhatsAppMarkdownHostileInput(t *testing.T) {
+ // Chatwoot caps a message at 150,000 characters.
+ const size = 150 * 1024
+ repeat := func(unit string) string { return strings.Repeat(unit, size/len(unit)) }
+ inputs := map[string]string{
+ "OpenBrackets": repeat("["),
+ "CloseBrackets": repeat("]("),
+ "OpenParentheses": repeat("("),
+ "NestedBrackets": repeat("[") + repeat("]"),
+ "UnclosedLinks": repeat("[a](https://x.example/("),
+ "LinkInsideOpenLink": repeat("[x](https://a[y](https://b)"),
+ "LinkInsideTitle": repeat("[x](https://a \"[y](https://b)"),
+ "LinkThenSpaces": repeat("[x]( "),
+ "ValidLinks": repeat("[a](https://x.example/) "),
+ "Backslashes": repeat("\\"),
+ "Escapes": repeat("\\*"),
+ "OpenFenceEscapes": "```" + repeat("\\*"),
+ "OpenCodeLines": repeat("`" + strings.Repeat("\\*", 50) + "\n"),
+ "Backticks": repeat("`a"),
+ "Asterisks": repeat("*"),
+ "Tildes": repeat("~"),
+ "TripleNesting": repeat("***a "),
+ "BoldOpeners": repeat("**a "),
+ "ItalicOpeners": repeat(" *a"),
+ "ItalicPairs": repeat("*a*"),
+ "MixedEmphasis": repeat("*a **b* ~~c "),
+ "AngleBrackets": repeat("<"),
+ "OpenAutolinks": repeat("<https://"),
+ "OpenEmailAutolinks": repeat("<a@b"),
+ "URLStarts": repeat("http://"),
+ "DuplicateLinks": repeat("https://x.example/a: "),
+ "ClosedBoldURLs": repeat("**https://x.example/a**!"),
+ "ReopenedBoldURLs": "**" + repeat("https://x.example/a**!x**"),
+ "OpenBoldURLRun": "**" + repeat("https://x.example/a**"),
+ "DashLines": repeat("--\n"),
+ }
+ for name, in := range inputs {
+ t.Run(name, func(t *testing.T) {
+ start := time.Now()
+ got := ChatwootToWhatsAppMarkdown(in)
+ if elapsed := time.Since(start); elapsed > 30*time.Second {
+ t.Fatalf("conversion of %d bytes took %s", len(in), elapsed)
+ }
+ assertNoMarkdownSentinels(t, got)
+ })
+ }
+}
+
// TestChatwootMarkdownRoundTrip is a sanity check that simple WhatsApp-flavored
// strings survive a WhatsApp -> Chatwoot -> WhatsApp round trip intact.
func TestChatwootMarkdownRoundTrip(t *testing.T) {
@@ -471,11 +1043,12 @@ func TestChatwootMarkdownRoundTrip(t *testing.T) {
}
}
-// assertNoMarkdownSentinels fails if the markdown bridge leaked either of the
-// internal guard runes (\x01 bold, \x02 strike) into a user-visible string.
+// assertNoMarkdownSentinels fails if the markdown bridge leaked any of the
+// internal guard runes (\x01 bold, \x02 strike, \x03 link) into a
+// user-visible string.
func assertNoMarkdownSentinels(t *testing.T, out string) {
t.Helper()
- if strings.ContainsAny(out, "\x01\x02") {
+ if strings.ContainsAny(out, "\x01\x02\x03") {
t.Fatalf("output leaked a markdown sentinel rune: %q", out)
}
}
diff --git a/src/ui/rest/chatwoot.go b/src/ui/rest/chatwoot.go
index e533f716..76286770 100644
--- a/src/ui/rest/chatwoot.go
+++ b/src/ui/rest/chatwoot.go
@@ -44,10 +44,12 @@ func NewChatwootHandler(
}
// composeOutgoingText prepares a Chatwoot agent reply for WhatsApp delivery:
-// it translates Chatwoot/GFM markdown (**bold**, *italic*, ~~strike~~) into
-// WhatsApp's syntax, and — when CHATWOOT_SIGN_MSG is enabled — prefixes the
-// agent's name (joined by CHATWOOT_SIGN_DELIMITER, with literal "\n" escapes
-// expanded). Returns "" when the reply has no text body.
+// it translates Chatwoot/GFM markdown (**bold**, *italic*, ~~strike~~, links,
+// backslash escapes) into what WhatsApp displays, and — when CHATWOOT_SIGN_MSG
+// is enabled — prefixes the agent's name (joined by CHATWOOT_SIGN_DELIMITER,
+// with literal "\n" escapes expanded). Returns "" when the reply has no text
+// body, which includes a message holding only Chatwoot's "--" signature
+// separator; callers must not send an empty text.
func composeOutgoingText(payload chatwoot.WebhookPayload) string {
text := utils.ChatwootToWhatsAppMarkdown(payload.Content)
if config.ChatwootSignMsg && text != "" {
diff --git a/src/ui/rest/chatwoot_test.go b/src/ui/rest/chatwoot_test.go
index b15fda0c..09ee51c5 100644
--- a/src/ui/rest/chatwoot_test.go
+++ b/src/ui/rest/chatwoot_test.go
@@ -1,6 +1,7 @@
package rest
import (
+ "context"
"errors"
"net/http"
"net/http/httptest"
@@ -9,7 +10,9 @@ import (
"github.com/aldinokemal/go-whatsapp-web-multidevice/config"
domainChatStorage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chatstorage"
+ domainSend "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/send"
"github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/chatwoot"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
"github.com/gofiber/fiber/v3"
)
@@ -174,9 +177,40 @@ func TestComposeOutgoingText(t *testing.T) {
sender: " Agent Smith ",
want: "*Agent Smith*\n\nhello",
},
+ {
+ // Links are flattened in the agent's body; the signature is added
+ // around the converted text.
+ name: "sign enabled flattens markdown link in body",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "see [**https://x.example/**](https://x.example/) and [docs](https://x.example/a_b?c=1\\&d=2)",
+ sender: "Bob",
+ want: "*Bob*\n\nsee https://x.example/ and docs: https://x.example/a_b?c=1&d=2",
+ },
+ {
+ // Chatwoot's own "send with signature" switch with an empty
+ // signature leaves a dangling separator line; it is dropped.
+ name: "dangling chatwoot signature separator dropped",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "Thanks\n\n--\n\n",
+ sender: "Bob",
+ want: "*Bob*\n\nThanks",
+ },
+ {
+ // A message that is only the separator has no body: nothing is
+ // sent as text (an attachment then goes out without a caption),
+ // and no lone agent name either.
+ name: "only chatwoot signature separator returns empty",
+ signMsg: true,
+ delimiter: "\n\n",
+ content: "\n\n--\n\n",
+ sender: "Bob",
+ want: "",
+ },
{
// Plain text with no markdown delimiters is passed through unchanged
- // (the markdown translator short-circuits when no * ~ are present).
+ // (the markdown translator skips text that holds no Markdown).
name: "plain text no markdown unchanged",
signMsg: false,
delimiter: "\n\n",
@@ -387,3 +421,121 @@ func TestChatwootLinkChatJID(t *testing.T) {
})
}
}
+
+// chatwootReplySendStub records what an agent reply makes the webhook send.
+// The embedded interface is nil, so any send the tests do not expect panics.
+type chatwootReplySendStub struct {
+ domainSend.ISendUsecase
+ texts []string
+ captions []string // one entry per attachment sent, in order
+}
+
+func (s *chatwootReplySendStub) SendText(_ context.Context, request domainSend.MessageRequest) (domainSend.GenericResponse, error) {
+ s.texts = append(s.texts, request.Message)
+ return domainSend.GenericResponse{Status: "ok"}, nil
+}
+
+func (s *chatwootReplySendStub) SendImage(_ context.Context, request domainSend.ImageRequest) (domainSend.GenericResponse, error) {
+ s.captions = append(s.captions, "image:"+request.Caption)
+ return domainSend.GenericResponse{Status: "ok"}, nil
+}
+
+func (s *chatwootReplySendStub) SendFile(_ context.Context, request domainSend.FileRequest) (domainSend.GenericResponse, error) {
+ s.captions = append(s.captions, "file:"+request.Caption)
+ return domainSend.GenericResponse{Status: "ok"}, nil
+}
+
+// TestChatwootWebhookEmptyReplyText drives the webhook end to end with a stub
+// send usecase: a reply whose text comes out empty (nothing, or only Chatwoot's
+// "--" signature separator) must not be sent as a text message, and must not
+// become the caption of its attachments, which are still delivered.
+func TestChatwootWebhookEmptyReplyText(t *testing.T) {
+ const attachments = `[{"id":1,"file_type":"image","data_url":"https://chat.example/a.png"},{"id":2,"file_type":"file","data_url":"https://chat.example/b.pdf"}]`
+ tests := []struct {
+ name string
+ content string
+ attachments string
+ wantTexts []string
+ wantCaptions []string
+ }{
+ {
+ name: "separator only sends nothing",
+ content: `\n\n--\n\n`,
+ },
+ {
+ name: "bare separator sends nothing",
+ content: `--`,
+ },
+ {
+ name: "empty content sends nothing",
+ content: ``,
+ },
+ {
+ // Control: the same route does send a reply that has a body, with
+ // the dangling separator dropped and the agent's name added.
+ name: "body with dangling separator is sent as text",
+ content: `Thanks\n\n--\n\n`,
+ wantTexts: []string{"*Bob*\n\nThanks"},
+ },
+ {
+ name: "separator only with attachments sends them without caption",
+ content: `\n\n--\n\n`,
+ attachments: attachments,
+ wantCaptions: []string{"image:", "file:"},
+ },
+ {
+ name: "empty content with attachments sends them without caption",
+ content: ``,
+ attachments: attachments,
+ wantCaptions: []string{"image:", "file:"},
+ },
+ {
+ // Control: a body rides on the first attachment only.
+ name: "body with attachments captions the first one",
+ content: `Thanks\n\n--\n\n`,
+ attachments: attachments,
+ wantCaptions: []string{"image:*Bob*\n\nThanks", "file:"},
+ },
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ // Signing is on: an empty body must not go out as a lone agent name.
+ withSignConfig(t, true, "\n\n")
+ prevDevice := config.ChatwootDeviceID
+ config.ChatwootDeviceID = "reply-device"
+ t.Cleanup(func() { config.ChatwootDeviceID = prevDevice })
+ chatwoot.InitClientRegistry(nil)
+ t.Cleanup(func() { chatwoot.InitClientRegistry(nil) })
+
+ manager := whatsapp.NewDeviceManager(nil, nil, nil)
+ manager.AddDevice(whatsapp.NewDeviceInstance("reply-device", nil, nil))
+ stub := &chatwootReplySendStub{}
+ handler := &ChatwootHandler{SendUsecase: stub, DeviceManager: manager}
+ app := fiber.New()
+ app.Post("/chatwoot/webhook", handler.HandleWebhook)
+
+ body := `{"event":"message_created","message_type":"outgoing","content":"` + tt.content + `",` +
+ `"sender":{"name":"Bob"},"account":{"id":1},` +
+ `"conversation":{"id":5,"inbox_id":9,"meta":{"sender":{"phone_number":"+628123456789"}}}`
+ if tt.attachments != "" {
+ body += `,"attachments":` + tt.attachments
+ }
+ body += `}`
+ req := httptest.NewRequest(http.MethodPost, "/chatwoot/webhook", strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := app.Test(req)
+ if err != nil {
+ t.Fatalf("app.Test: %v", err)
+ }
+ if resp.StatusCode != fiber.StatusOK {
+ t.Fatalf("status = %d, want 200", resp.StatusCode)
+ }
+ if strings.Join(stub.texts, "|") != strings.Join(tt.wantTexts, "|") || len(stub.texts) != len(tt.wantTexts) {
+ t.Errorf("SendText messages = %q, want %q", stub.texts, tt.wantTexts)
+ }
+ if strings.Join(stub.captions, "|") != strings.Join(tt.wantCaptions, "|") || len(stub.captions) != len(tt.wantCaptions) {
+ t.Errorf("attachments sent = %q, want %q", stub.captions, tt.wantCaptions)
+ }
+ })
+ }
+}