Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(telegram): emit strictly nested HTML for combined emphasis, links, and code fences (#11321)
T Mohan Aditya22b1f0aa8451
diff --git a/server/internal/integrations/telegram/markdown.go b/server/internal/integrations/telegram/markdown.goindex 84f8886907..5f94151ff2 100644--- a/server/internal/integrations/telegram/markdown.go+++ b/server/internal/integrations/telegram/markdown.go@@ -3,7 +3,10 @@ package telegramimport ("html""regexp"+ "sort""strings"+ "unicode"+ "unicode/utf8")// This file converts the agent's standard Markdown to Telegram HTML parse@@ -15,39 +18,39 @@ import (// rather than risking a rejected message.var (- reBold = regexp.MustCompile(`\*\*(.+?)\*\*`)- reItalic = regexp.MustCompile(`(^|[^*])\*([^*]+?)\*`)- reStrike = regexp.MustCompile(`~~(.+?)~~`)- reInlineCode = regexp.MustCompile("`([^`]+)`")- reLink = regexp.MustCompile(`\[([^\]]+)\]\(([^)\s]+)\)`)- reHeading = regexp.MustCompile(`^#{1,6}\s+(.*)$`)- reBullet = regexp.MustCompile(`^(\s*)[-*]\s+`)+ reHeading = regexp.MustCompile(`^#{1,6}\s+(.*)$`)+ reBullet = regexp.MustCompile(`^(\s*)[-*]\s+`))// formatHTML renders markdown text as Telegram HTML. Code blocks are handled// first (their content must stay verbatim, only entity-escaped); the rest is// converted line by line.func formatHTML(md string) string {+ md = strings.ReplaceAll(md, "\r\n", "\n")var out strings.Builderlines := strings.Split(md, "\n")inCode := false+ var fenceChar byte+ var fenceLen intvar codeLang stringvar codeBuf []stringfor _, line := range lines {trimmed := strings.TrimSpace(line)- if strings.HasPrefix(trimmed, "```") {- if inCode {+ if inCode {+ if isFenceClose(trimmed, fenceChar, fenceLen) {out.WriteString(renderCodeBlock(codeLang, codeBuf))out.WriteString("\n")- inCode, codeBuf, codeLang = false, nil, ""- } else {- inCode = true- codeLang = strings.TrimPrefix(trimmed, "```")+ inCode, fenceChar, fenceLen, codeLang, codeBuf = false, 0, 0, "", nil+ continue}+ codeBuf = append(codeBuf, line)continue}- if inCode {- codeBuf = append(codeBuf, line)+ if ch, n, lang, ok := parseFenceOpen(trimmed); ok {+ inCode = true+ fenceChar = ch+ fenceLen = n+ codeLang = langcontinue}out.WriteString(formatLine(line))@@ -62,6 +65,44 @@ func formatHTML(md string) string {return strings.TrimRight(out.String(), "\n")}+func parseFenceOpen(trimmed string) (byte, int, string, bool) {+ if len(trimmed) < 3 {+ return 0, 0, "", false+ }+ ch := trimmed[0]+ if ch != '`' && ch != '~' {+ return 0, 0, "", false+ }+ n := 0+ for n < len(trimmed) && trimmed[n] == ch {+ n+++ }+ if n < 3 {+ return 0, 0, "", false+ }+ info := strings.TrimSpace(trimmed[n:])+ if ch == '`' && strings.ContainsRune(info, '`') {+ return 0, 0, "", false+ }+ lang := ""+ if fields := strings.Fields(info); len(fields) > 0 {+ lang = fields[0]+ }+ return ch, n, lang, true+}++func isFenceClose(trimmed string, fenceChar byte, fenceLen int) bool {+ if len(trimmed) < fenceLen {+ return false+ }+ for i := 0; i < len(trimmed); i++ {+ if trimmed[i] != fenceChar {+ return false+ }+ }+ return true+}+func renderCodeBlock(lang string, lines []string) string {body := html.EscapeString(strings.Join(lines, "\n"))if lang != "" {@@ -70,9 +111,6 @@ func renderCodeBlock(lang string, lines []string) string {return "<pre>" + body + "</pre>"}-// formatLine converts one non-code line: escape first, then re-introduce the-// allowed tags by pattern. Placeholders guard inline code spans from the-// styling passes.func formatLine(line string) string {if m := reHeading.FindStringSubmatch(line); m != nil {return "<b>" + formatInline(m[1]) + "</b>"@@ -84,36 +122,674 @@ func formatLine(line string) string {}func formatInline(s string) string {- // Extract inline code spans before escaping/styling so their content is- // untouched by the emphasis passes.- type span struct{ content string }- var spans []span- s = reInlineCode.ReplaceAllStringFunc(s, func(m string) string {- content := strings.Trim(m, "`")- spans = append(spans, span{content})- return "\x00CODE\x00"- })-- // Links: capture before escaping so the URL survives untouched.- type link struct{ label, url string }- var links []link- s = reLink.ReplaceAllStringFunc(s, func(m string) string {- g := reLink.FindStringSubmatch(m)- links = append(links, link{g[1], g[2]})- return "\x00LINK\x00"- })-- s = html.EscapeString(s)- s = reBold.ReplaceAllString(s, "<b>$1</b>")- s = reItalic.ReplaceAllString(s, "$1<i>$2</i>")- s = reStrike.ReplaceAllString(s, "<s>$1</s>")-- for _, l := range links {- tag := `<a href="` + html.EscapeString(l.url) + `">` + html.EscapeString(l.label) + `</a>`- s = strings.Replace(s, "\x00LINK\x00", tag, 1)- }- for _, c := range spans {- s = strings.Replace(s, "\x00CODE\x00", "<code>"+html.EscapeString(c.content)+"</code>", 1)- }- return s+ if !strings.ContainsAny(s, "`[*~") {+ return html.EscapeString(s)+ }+ return renderInline(s, true)+}++func renderInline(s string, allowLink bool) string {+ if !strings.ContainsAny(s, "`[*~") {+ return html.EscapeString(s)+ }+ idx := newInlineIndex(s, allowLink)+ var out strings.Builder+ out.Grow(len(s))+ idx.render(&out, 0, len(s), 0, len(idx.stars))+ return out.String()+}++type starRun struct {+ pos int32+ k uint8+ canOpen bool+ canClose bool+}++const noStarMatch int32 = -1++// starLookup answers findStarClose queries for want in {1, 2} in O(1) time+// after a linear precomputation over the line's star runs.+// direct entries encode: >= 0 for a state-0 match at index v, <= -2 for a+// state-1 match at index -v-2, and -1 for no direct match.+type starLookup struct {+ built bool+ want int+ other int+ direct0 []int32+ direct1 []int32+ nextFallback []int32+ nextConst1 []int32+ flipPrefix []int32+ lastReset []int32+ lastExit []int32+}++func buildStarLookup(stars []starRun, want int) starLookup {+ m := len(stars)+ other := 3 - want+ n := m + 1+ buf := make([]int32, 7*n)+ sl := starLookup{+ built: true,+ want: want,+ other: other,+ direct0: buf[0*n : 1*n],+ direct1: buf[1*n : 2*n],+ nextFallback: buf[2*n : 3*n],+ nextConst1: buf[3*n : 4*n],+ flipPrefix: buf[4*n : 5*n],+ lastReset: buf[5*n : 6*n],+ lastExit: buf[6*n : 7*n],+ }++ wantU := uint8(want)+ otherU := uint8(other)+ sl.direct0[m] = noStarMatch+ sl.direct1[m] = noStarMatch+ sl.nextFallback[m] = -1+ sl.nextConst1[m] = -1+ for i := m - 1; i >= 0; i-- {+ r := stars[i]+ if (r.k == wantU || r.k == 3) && r.canClose {+ sl.direct0[i] = int32(i)+ } else if r.k == otherU && r.canOpen {+ sl.direct0[i] = sl.direct1[i+1]+ } else {+ sl.direct0[i] = sl.direct0[i+1]+ }++ if r.k == 3 && r.canClose {+ sl.direct1[i] = int32(-i - 2)+ } else if r.k == otherU && r.canClose {+ sl.direct1[i] = sl.direct0[i+1]+ } else {+ sl.direct1[i] = sl.direct1[i+1]+ }++ if r.k == wantU && r.canClose {+ sl.nextFallback[i] = int32(i)+ } else {+ sl.nextFallback[i] = sl.nextFallback[i+1]+ }++ if r.k == otherU && r.canOpen && !r.canClose {+ sl.nextConst1[i] = int32(i)+ } else {+ sl.nextConst1[i] = sl.nextConst1[i+1]+ }+ }++ sl.lastReset[0] = -1+ sl.lastExit[0] = -1+ for i := 0; i < m; i++ {+ r := stars[i]+ sl.flipPrefix[i+1] = sl.flipPrefix[i]+ sl.lastReset[i+1] = sl.lastReset[i]+ sl.lastExit[i+1] = sl.lastExit[i]+ if r.k == otherU {+ if r.canOpen && r.canClose {+ sl.flipPrefix[i+1]+++ }+ if r.canOpen != r.canClose {+ sl.lastReset[i+1] = int32(i)+ }+ if r.canClose {+ sl.lastExit[i+1] = int32(i)+ }+ }+ }+ return sl+}++func (sl *starLookup) query(stars []starRun, startIdx, endIdx, from, end, initState int) (int, int, int, bool) {+ if startIdx > endIdx {+ return 0, 0, 0, false+ }+ if startIdx < endIdx {+ var dm int32+ if initState == 0 {+ dm = sl.direct0[startIdx]+ } else {+ dm = sl.direct1[startIdx]+ }+ if dm >= 0 {+ idx := int(dm)+ if idx < endIdx {+ pos := int(stars[idx].pos)+ return pos, pos + sl.want, idx, true+ }+ } else if dm <= -2 {+ idx := int(-dm - 2)+ if idx < endIdx {+ pos := int(stars[idx].pos)+ return pos + sl.other, pos + 3, idx, true+ }+ }+ }++ // No direct match in unclipped stars[startIdx:endIdx]; compute end state+ // and earliest surviving fallback for the last state-1 interval reaching endIdx.+ stateAtEnd := 0+ fallbackIdx := -1+ if startIdx == endIdx {+ stateAtEnd = initState+ } else {+ intervalStart := -1+ le := int(sl.lastExit[endIdx])+ if le < startIdx {+ if initState == 1 {+ intervalStart = startIdx+ } else if c1 := int(sl.nextConst1[startIdx]); c1 >= 0 && c1 < endIdx {+ intervalStart = c1 + 1+ }+ } else {+ lr := int(sl.lastReset[le+1])+ var sAfter int+ if lr >= startIdx {+ base := 0+ if stars[lr].canOpen {+ base = 1+ }+ flips := int(sl.flipPrefix[le+1] - sl.flipPrefix[lr+1])+ sAfter = base ^ (flips & 1)+ } else {+ flips := int(sl.flipPrefix[le+1] - sl.flipPrefix[startIdx])+ sAfter = initState ^ (flips & 1)+ }+ if sAfter == 1 {+ intervalStart = le + 1+ } else if c1 := int(sl.nextConst1[le+1]); c1 >= 0 && c1 < endIdx {+ intervalStart = c1 + 1+ }+ }+ if intervalStart >= 0 {+ stateAtEnd = 1+ if fb := int(sl.nextFallback[intervalStart]); fb >= 0 && fb < endIdx {+ fallbackIdx = fb+ }+ }+ }++ // A trailing "***" run sliced by end appears as "*" or "**" inside [from, end).+ if endIdx < len(stars) {+ tailPos := int(stars[endIdx].pos)+ if tailPos > from && tailPos < end {+ tailK := end - tailPos+ tailCanClose := stars[endIdx].canClose+ if tailK == sl.other && tailCanClose && stateAtEnd == 1 {+ stateAtEnd = 0+ fallbackIdx = -1+ } else if tailK == sl.want && tailCanClose {+ if stateAtEnd == 0 {+ return tailPos, tailPos + sl.want, endIdx, true+ }+ if fallbackIdx < 0 {+ fallbackIdx = endIdx+ }+ }+ }+ }++ if fallbackIdx >= 0 {+ pos := int(stars[fallbackIdx].pos)+ return pos, pos + sl.want, fallbackIdx, true+ }+ return 0, 0, 0, false+}++// inlineIndex precomputes delimiter matches for a single line in O(N) time so+// unclosed markers never trigger repeated scans across the rest of the line.+type inlineIndex struct {+ s string+ allowLink bool+ codeEnd []int+ nextMark []int+ nextRightBracket []int+ nextGT []int+ parenClose map[int]int+ strikeCloses []int+ stars []starRun+ hasClose1 bool+ hasClose2 bool+ hasClose3 bool+ nextClose3 []int32+ star1 starLookup+ star2 starLookup+}++func newInlineIndex(s string, allowLink bool) *inlineIndex {+ idx := &inlineIndex{s: s, allowLink: allowLink}++ // 1. Precompute the end of the code span starting at every backtick byte.+ // Starting inside a longer run is possible when a scan skips an escaped+ // byte, so the index covers every byte, not just maximal run starts.+ if strings.IndexByte(s, '`') >= 0 {+ type tickRun struct{ start, end int }+ var runs []tickRun+ for i := 0; i < len(s); {+ if s[i] != '`' {+ i+++ continue+ }+ j := i + 1+ for j < len(s) && s[j] == '`' {+ j+++ }+ runs = append(runs, tickRun{i, j})+ i = j+ }+ idx.codeEnd = make([]int, len(s))+ nearestByLen := make(map[int]int)+ for r := len(runs) - 1; r >= 0; r-- {+ run := runs[r]+ for p := run.start; p < run.end; p++ {+ k := run.end - p+ if closeStart, ok := nearestByLen[k]; ok {+ idx.codeEnd[p] = closeStart + k+ }+ }+ nearestByLen[run.end-run.start] = run.start+ }+ }++ // 2. Precompute jumps to the bytes that can affect link parsing. Ordinary+ // text is skipped in one step so an unclosed label cannot rescan the line.+ if allowLink && strings.IndexByte(s, '[') >= 0 && strings.IndexByte(s, ']') >= 0 {+ n := len(s)+ idx.nextMark = make([]int, n+1)+ idx.nextRightBracket = make([]int, n+1)+ idx.nextGT = make([]int, n+1)+ idx.nextMark[n], idx.nextRightBracket[n], idx.nextGT[n] = -1, -1, -1+ for i := n - 1; i >= 0; i-- {+ idx.nextMark[i] = idx.nextMark[i+1]+ idx.nextRightBracket[i] = idx.nextRightBracket[i+1]+ idx.nextGT[i] = idx.nextGT[i+1]+ switch s[i] {+ case '`', '[', ']', '\\':+ idx.nextMark[i] = i+ }+ if s[i] == ']' {+ idx.nextRightBracket[i] = i+ }+ if s[i] == '>' {+ idx.nextGT[i] = i+ }+ }+ var parens []int+ for i := 0; i < len(s); i++ {+ switch s[i] {+ case ' ', '\t':+ parens = parens[:0]+ case '(':+ parens = append(parens, i)+ case ')':+ if len(parens) > 0 {+ open := parens[len(parens)-1]+ parens = parens[:len(parens)-1]+ if idx.parenClose == nil {+ idx.parenClose = make(map[int]int)+ }+ idx.parenClose[open] = i+ }+ }+ }+ }++ // 3. Collect emphasis star runs and closing strikethrough runs outside code+ // spans (and outside valid links when allowLink is true).+ if strings.IndexByte(s, '*') >= 0 || strings.IndexByte(s, '~') >= 0 {+ for i := 0; i < len(s); {+ switch s[i] {+ case '`':+ _, next, _ := idx.parseCodeSpan(i, len(s))+ i = next+ continue+ case '[':+ if allowLink {+ if _, _, next, ok := idx.parseLink(i, len(s)); ok {+ i = next+ continue+ }+ }+ case '*':+ runEnd := i + 1+ for runEnd < len(s) && s[runEnd] == '*' {+ runEnd+++ }+ k := runEnd - i+ if k <= 3 {+ canClose := i > 0 && !endsWithSpace(s[:i])+ idx.stars = append(idx.stars, starRun{+ pos: int32(i),+ k: uint8(k),+ canOpen: !startsWithSpace(s[runEnd:]),+ canClose: canClose,+ })+ if canClose {+ switch k {+ case 1:+ idx.hasClose1 = true+ case 2:+ idx.hasClose2 = true+ case 3:+ idx.hasClose3 = true+ }+ }+ }+ i = runEnd+ continue+ case '~':+ runEnd := i + 1+ for runEnd < len(s) && s[runEnd] == '~' {+ runEnd+++ }+ if runEnd-i == 2 && i > 0 && !endsWithSpace(s[:i]) {+ idx.strikeCloses = append(idx.strikeCloses, i)+ }+ i = runEnd+ continue+ }+ i+++ }+ }++ return idx+}++func (idx *inlineIndex) render(out *strings.Builder, start, end, startStarIdx, endStarIdx int) {+ s := idx.s+ starCur := startStarIdx+ for i := start; i < end; {+ switch s[i] {+ case '`':+ content, next, ok := idx.parseCodeSpan(i, end)+ if ok {+ out.WriteString("<code>")+ out.WriteString(html.EscapeString(content))+ out.WriteString("</code>")+ } else {+ out.WriteString(s[i:next])+ }+ i = next+ continue+ case '[':+ if idx.allowLink {+ if label, dest, next, ok := idx.parseLink(i, end); ok {+ out.WriteString(`<a href="`)+ out.WriteString(html.EscapeString(dest))+ out.WriteString(`">`)+ out.WriteString(renderInline(label, false))+ out.WriteString("</a>")+ i = next+ continue+ }+ }+ case '*':+ runEnd := i + 1+ for runEnd < end && s[runEnd] == '*' {+ runEnd+++ }+ runLen := runEnd - i+ if runLen <= 3 && !startsWithSpace(s[runEnd:end]) {+ for starCur < endStarIdx && int(idx.stars[starCur].pos) < runEnd {+ starCur+++ }+ switch runLen {+ case 3:+ if innerEnd, next, matchIdx, ok := idx.findStarClose(starCur, endStarIdx, runEnd, end, 3, 0); ok {+ out.WriteString("<b><i>")+ idx.render(out, runEnd, innerEnd, starCur, matchIdx)+ out.WriteString("</i></b>")+ i = next+ starCur = matchIdx+ continue+ }+ if innerEnd, next, matchIdx, ok := idx.findStarClose(starCur, endStarIdx, runEnd, end, 1, 1); ok {+ out.WriteString("<i>")+ idx.render(out, i+1, innerEnd, starCur, matchIdx)+ out.WriteString("</i>")+ i = next+ starCur = matchIdx+ continue+ }+ if innerEnd, next, matchIdx, ok := idx.findStarClose(starCur, endStarIdx, runEnd, end, 2, 1); ok {+ out.WriteString("<b>")+ idx.render(out, i+2, innerEnd, starCur, matchIdx)+ out.WriteString("</b>")+ i = next+ starCur = matchIdx+ continue+ }+ case 2:+ if innerEnd, next, matchIdx, ok := idx.findStarClose(starCur, endStarIdx, runEnd, end, 2, 0); ok {+ out.WriteString("<b>")+ idx.render(out, runEnd, innerEnd, starCur, matchIdx)+ out.WriteString("</b>")+ i = next+ starCur = matchIdx+ continue+ }+ case 1:+ if innerEnd, next, matchIdx, ok := idx.findStarClose(starCur, endStarIdx, runEnd, end, 1, 0); ok {+ out.WriteString("<i>")+ idx.render(out, runEnd, innerEnd, starCur, matchIdx)+ out.WriteString("</i>")+ i = next+ starCur = matchIdx+ continue+ }+ }+ }+ out.WriteString(s[i:runEnd])+ i = runEnd+ continue+ case '~':+ runEnd := i + 1+ for runEnd < end && s[runEnd] == '~' {+ runEnd+++ }+ if runEnd-i == 2 && !startsWithSpace(s[runEnd:end]) {+ if closeIdx, ok := idx.findStrikeClose(runEnd, end); ok {+ for starCur < endStarIdx && int(idx.stars[starCur].pos) < runEnd {+ starCur+++ }+ subEndStarIdx := starCur+ if starCur < endStarIdx {+ subEndStarIdx = starCur + sort.Search(endStarIdx-starCur, func(k int) bool {+ r := idx.stars[starCur+k]+ return int(r.pos)+int(r.k) > closeIdx+ })+ }+ out.WriteString("<s>")+ idx.render(out, runEnd, closeIdx, starCur, subEndStarIdx)+ out.WriteString("</s>")+ i = closeIdx + 2+ starCur = subEndStarIdx+ continue+ }+ }+ out.WriteString(s[i:runEnd])+ i = runEnd+ continue+ }+ plainStart := i+ needsEscape := false+ for i < end {+ c := s[i]+ if i > plainStart && (c == '`' || c == '[' || c == '*' || c == '~') {+ break+ }+ if c == '&' || c == '<' || c == '>' || c == '"' || c == '\'' {+ needsEscape = true+ }+ i+++ }+ if needsEscape {+ out.WriteString(html.EscapeString(s[plainStart:i]))+ } else {+ out.WriteString(s[plainStart:i])+ }+ }+}++func (idx *inlineIndex) parseCodeSpan(start, end int) (string, int, bool) {+ s := idx.s+ n := 0+ for start+n < end && s[start+n] == '`' {+ n+++ }+ if closeEnd := idx.codeEnd[start]; closeEnd > 0 && closeEnd <= end {+ raw := s[start+n : closeEnd-n]+ if len(raw) >= 2 && raw[0] == ' ' && raw[len(raw)-1] == ' ' && strings.Trim(raw, " ") != "" {+ raw = raw[1 : len(raw)-1]+ }+ return raw, closeEnd, true+ }+ return "", start + n, false+}++func (idx *inlineIndex) parseLink(start, end int) (string, string, int, bool) {+ s := idx.s+ if !idx.allowLink || start >= end || s[start] != '[' || idx.nextRightBracket == nil {+ return "", "", 0, false+ }+ depth := 1+ var label string+ i := start + 1+ for i < end {+ j := idx.nextMark[i]+ if j < 0 || j >= end {+ return "", "", 0, false+ }+ i = j+ switch s[i] {+ case '\\':+ if i+1 < end {+ i += 2+ } else {+ i+++ }+ case '`':+ _, next, _ := idx.parseCodeSpan(i, end)+ i = next+ case '[':+ depth+++ i+++ case ']':+ depth--+ if depth == 0 {+ label = s[start+1 : i]+ i+++ goto parseDest+ }+ i+++ }+ }+ return "", "", 0, false++parseDest:+ if label == "" || i >= end || s[i] != '(' {+ return "", "", 0, false+ }+ i+++ if i >= end {+ return "", "", 0, false+ }+ if s[i] == '<' {+ closeAngle := idx.nextGT[i+1]+ if closeAngle < 0 || closeAngle >= end {+ return "", "", 0, false+ }+ closeParen := closeAngle + 1+ if closeParen >= end || s[closeParen] != ')' {+ return "", "", 0, false+ }+ dest := s[i+1 : closeAngle]+ if dest == "" {+ return "", "", 0, false+ }+ return label, dest, closeParen + 1, true+ }+ openParen := i - 1+ closeParen, ok := idx.parenClose[openParen]+ if !ok || closeParen >= end {+ return "", "", 0, false+ }+ dest := s[i:closeParen]+ if dest == "" {+ return "", "", 0, false+ }+ return label, dest, closeParen + 1, true+}++func (idx *inlineIndex) findStarClose(startIdx, endStarIdx, from, end, want, initState int) (int, int, int, bool) {+ switch want {+ case 3:+ if !idx.hasClose3 || startIdx >= endStarIdx {+ return 0, 0, 0, false+ }+ if idx.nextClose3 == nil {+ m := len(idx.stars)+ idx.nextClose3 = make([]int32, m+1)+ idx.nextClose3[m] = -1+ for i := m - 1; i >= 0; i-- {+ if idx.stars[i].k == 3 && idx.stars[i].canClose {+ idx.nextClose3[i] = int32(i)+ } else {+ idx.nextClose3[i] = idx.nextClose3[i+1]+ }+ }+ }+ if m := int(idx.nextClose3[startIdx]); m >= 0 && m < endStarIdx {+ pos := int(idx.stars[m].pos)+ return pos, pos + 3, m, true+ }+ return 0, 0, 0, false+ case 2:+ if !idx.hasClose2 && !idx.hasClose3 {+ return 0, 0, 0, false+ }+ if !idx.star2.built {+ idx.star2 = buildStarLookup(idx.stars, 2)+ }+ return idx.star2.query(idx.stars, startIdx, endStarIdx, from, end, initState)+ case 1:+ if !idx.hasClose1 && !idx.hasClose3 {+ return 0, 0, 0, false+ }+ if !idx.star1.built {+ idx.star1 = buildStarLookup(idx.stars, 1)+ }+ return idx.star1.query(idx.stars, startIdx, endStarIdx, from, end, initState)+ default:+ return 0, 0, 0, false+ }+}++func (idx *inlineIndex) findStrikeClose(from, end int) (int, bool) {+ if len(idx.strikeCloses) == 0 {+ return 0, false+ }+ pos := sort.SearchInts(idx.strikeCloses, from+1)+ if pos < len(idx.strikeCloses) && idx.strikeCloses[pos]+2 <= end {+ return idx.strikeCloses[pos], true+ }+ return 0, false+}++func startsWithSpace(s string) bool {+ if s == "" {+ return true+ }+ r, _ := utf8.DecodeRuneInString(s)+ return unicode.IsSpace(r)+}++func endsWithSpace(s string) bool {+ if s == "" {+ return true+ }+ r, _ := utf8.DecodeLastRuneInString(s)+ return unicode.IsSpace(r)}diff --git a/server/internal/integrations/telegram/markdown_test.go b/server/internal/integrations/telegram/markdown_test.gonew file mode 100644index 0000000000..595ab9c282--- /dev/null+++ b/server/internal/integrations/telegram/markdown_test.go@@ -0,0 +1,318 @@+package telegram++import (+ "encoding/xml"+ "io"+ "strings"+ "testing"+ "time"+)++func assertValidTelegramHTML(t *testing.T, rendered string) {+ t.Helper()+ dec := xml.NewDecoder(strings.NewReader("<root>" + rendered + "</root>"))+ var stack []string+ for {+ tok, err := dec.Token()+ if err == io.EOF {+ break+ }+ if err != nil {+ t.Fatalf("invalid Telegram HTML %q: %v", rendered, err)+ }+ switch el := tok.(type) {+ case xml.StartElement:+ name := el.Name.Local+ parent := ""+ if len(stack) > 0 {+ parent = stack[len(stack)-1]+ }+ switch name {+ case "root":+ case "b", "i", "s", "a", "code", "pre":+ if parent == "code" {+ t.Fatalf("nested tag <%s> inside <code> in %q", name, rendered)+ }+ if parent == "pre" && name != "code" {+ t.Fatalf("nested tag <%s> inside <pre> in %q", name, rendered)+ }+ if name == "a" {+ for _, ancestor := range stack {+ if ancestor == "a" {+ t.Fatalf("nested <a> inside <a> in %q", rendered)+ }+ }+ }+ if name == "code" {+ for _, attr := range el.Attr {+ if attr.Name.Local == "class" && strings.ContainsAny(attr.Value, " \t\r\n") {+ t.Fatalf("code class attribute contains whitespace %q in %q", attr.Value, rendered)+ }+ }+ }+ default:+ t.Fatalf("unexpected tag <%s> in %q", name, rendered)+ }+ stack = append(stack, name)+ case xml.EndElement:+ stack = stack[:len(stack)-1]+ }+ }+}++func TestFormatHTMLStrictNestingAndEdgeCases(t *testing.T) {+ cases := []struct {+ name string+ in string+ want string+ }{+ {+ name: "bold italic triple stars nests cleanly",+ in: "***bold italic***",+ want: "<b><i>bold italic</i></b>",+ },+ {+ name: "italic nested inside bold closing together",+ in: "**bold *and italic***",+ want: "<b>bold <i>and italic</i></b>",+ },+ {+ name: "bold nested inside italic closing together",+ in: "*italic **and bold***",+ want: "<i>italic <b>and bold</b></i>",+ },+ {+ name: "bold closing inside italic opening together",+ in: "***bold** and italic*",+ want: "<i><b>bold</b> and italic</i>",+ },+ {+ name: "italic closing inside bold opening together",+ in: "***italic* and bold**",+ want: "<b><i>italic</i> and bold</b>",+ },+ {+ name: "crossing bold and strikethrough stays validly nested",+ in: "**bold ~~both** strike~~",+ want: "<b>bold ~~both</b> strike~~",+ },+ {+ name: "crossing italic and strikethrough stays validly nested",+ in: "*italic ~~both* strike~~",+ want: "<i>italic ~~both</i> strike~~",+ },+ {+ name: "space-surrounded asterisks are not italic",+ in: "2 * 3 * 4 = 24",+ want: "2 * 3 * 4 = 24",+ },+ {+ name: "markdown link with balanced parentheses in URL",+ in: "[Go](https://en.wikipedia.org/wiki/Go_(programming_language))",+ want: `<a href="https://en.wikipedia.org/wiki/Go_(programming_language)">Go</a>`,+ },+ {+ name: "markdown link with inline code and bold inside label",+ in: "[**read** `doc`](https://example.com/a)",+ want: `<a href="https://example.com/a"><b>read</b> <code>doc</code></a>`,+ },+ {+ name: "multi-backtick inline code preserves inner backticks",+ in: "use ``a `b` c`` here",+ want: "use <code>a `b` c</code> here",+ },+ {+ name: "inline triple-backtick code span does not open fenced block",+ in: "```foo``` and **bold**",+ want: "<code>foo</code> and <b>bold</b>",+ },+ {+ name: "four-backtick fence preserves inner triple-backtick fence",+ in: "````markdown\n```go\nx < 1\n```\n````\nafter **bold**",+ want: "<pre><code class=\"language-markdown\">```go\nx < 1\n```</code></pre>\nafter <b>bold</b>",+ },+ {+ name: "closing fence with info string stays inside code block",+ in: "```\n```go\n```\nafter",+ want: "<pre>```go</pre>\nafter",+ },+ {+ name: "fence info string uses first language token only",+ in: "```go title=\"main.go\"\nx < 1\n```",+ want: `<pre><code class="language-go">x < 1</code></pre>`,+ },+ {+ name: "tilde code fence renders pre block",+ in: "~~~sh\necho a & b\n~~~",+ want: `<pre><code class="language-sh">echo a & b</code></pre>`,+ },+ {+ name: "unterminated fence closes cleanly mid-stream",+ in: "```go\nfmt.Println(1 < 2)",+ want: `<pre><code class="language-go">fmt.Println(1 < 2)</code></pre>`,+ },+ {+ name: "CRLF input leaves no carriage returns in HTML",+ in: "# Title\r\n- **item**\r\n```go\r\nx := 1\r\n```\r\n",+ want: "<b>Title</b>\n• <b>item</b>\n<pre><code class=\"language-go\">x := 1</code></pre>",+ },+ {+ name: "literal placeholder-like strings do not collide with code or link spans",+ in: "before \x00CODE\x00 \x00LINK\x00 and `real` and [x](https://e.co)",+ want: "before \x00CODE\x00 \x00LINK\x00 and <code>real</code> and <a href=\"https://e.co\">x</a>",+ },+ {+ name: "bold containing code span with stars stays balanced",+ in: "**bold `x ** y` end**",+ want: "<b>bold <code>x ** y</code> end</b>",+ },+ {+ name: "unclosed inner italic does not break enclosing bold",+ in: "**bold *unclosed**",+ want: "<b>bold *unclosed</b>",+ },+ {+ name: "unclosed inner bold does not break enclosing italic",+ in: "*italic **unclosed*",+ want: "<i>italic **unclosed</i>",+ },+ {+ name: "crossing strikethrough and bold stays validly nested",+ in: "~~strike **cross~~ bold**",+ want: "<s>strike **cross</s> bold**",+ },+ {+ name: "angle-bracketed link URL with spaces",+ in: "[doc](<https://example.com/a b>)",+ want: `<a href="https://example.com/a b">doc</a>`,+ },+ {+ name: "link label containing code span with closing bracket",+ in: "[`a]b`](https://example.com)",+ want: `<a href="https://example.com"><code>a]b</code></a>`,+ },+ {+ name: "nested markdown link inside link label does not emit nested anchor tags",+ in: "[see [inner](https://a.example)](https://b.example)",+ want: `<a href="https://b.example">see [inner](https://a.example)</a>`,+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := formatHTML(tc.in)+ if !strings.Contains(tc.in, "\x00") {+ assertValidTelegramHTML(t, got)+ }+ if got != tc.want {+ t.Errorf("formatHTML(%q)\n got: %q\nwant: %q", tc.in, got, tc.want)+ }+ })+ }+}++func unfinishedMarkdownLine(targetLen int) string {+ const pattern = "***a [b ~~c `d "+ n := (targetLen + len(pattern) - 1) / len(pattern)+ return strings.Repeat(pattern, n)[:targetLen]+}++func distinctBackticksLine(targetLen int) string {+ var b strings.Builder+ for n := 1; b.Len()+n+2 <= targetLen; n++ {+ b.WriteString(strings.Repeat("`", n))+ b.WriteString("a ")+ }+ return b.String()+}++func TestFormatHTMLUnfinishedMarkdown(t *testing.T) {+ const maxRenderTime = 100 * time.Millisecond++ cases := []struct {+ name string+ in string+ want string+ }{+ {+ name: "mixed unfinished emphasis links strike and code",+ in: unfinishedMarkdownLine(3500),+ },+ {+ name: "repeated unclosed single stars",+ in: strings.Repeat("*a ", 1167),+ want: strings.Repeat("*a ", 1167),+ },+ {+ name: "repeated unclosed triple stars with links",+ in: strings.Repeat("***a [b ", 438),+ want: strings.Repeat("***a [b ", 438),+ },+ {+ name: "repeated unclosed strikethrough with links",+ in: strings.Repeat("~~a [b ", 500),+ want: strings.Repeat("~~a [b ", 500),+ },+ {+ name: "repeated unclosed distinct-length backtick runs",+ in: distinctBackticksLine(3500),+ want: distinctBackticksLine(3500),+ },+ {+ name: "repeated unclosed link destinations",+ in: strings.Repeat("[a](b", 700),+ want: strings.Repeat("[a](b", 700),+ },+ {+ name: "repeated unclosed angle-bracket destinations",+ in: strings.Repeat("[a](<b", 584),+ want: strings.Repeat("[a](<b", 584),+ },+ {+ name: "repeated escaped open brackets with single closing bracket",+ in: strings.Repeat(`\[`, 1750) + "]",+ want: strings.Repeat(`\[`, 1750) + "]",+ },+ {+ name: "unclosed bold before many closed italics",+ in: strings.Repeat("**a ", 437) + strings.Repeat("*b* ", 438),+ want: strings.Repeat("**a ", 437) + strings.Repeat("<i>b</i> ", 438),+ },+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ start := time.Now()+ got := formatHTML(tc.in)+ if elapsed := time.Since(start); elapsed > maxRenderTime {+ t.Fatalf("formatHTML took %v, want at most %v", elapsed, maxRenderTime)+ }+ assertValidTelegramHTML(t, got)+ if tc.want != "" && got != tc.want {+ t.Errorf("formatHTML(%s) mismatch:\n got len=%d\nwant len=%d", tc.name, len(got), len(tc.want))+ }+ })+ }+}++func BenchmarkFormatHTMLUnfinishedMarkdown(b *testing.B) {+ cases := []struct {+ name string+ in string+ }{+ {name: "mixed_3500", in: unfinishedMarkdownLine(3500)},+ {name: "stars_links_3500", in: strings.Repeat("*a [b ", 584)[:3500]},+ {name: "triple_stars_links_3500", in: strings.Repeat("***a [b ", 438)[:3500]},+ {name: "unclosed_link_dest_3500", in: strings.Repeat("[a](b", 700)},+ {name: "unclosed_strike_3500", in: strings.Repeat("~~a ", 875)},+ {name: "bold_before_italics_3500", in: strings.Repeat("**a ", 437) + strings.Repeat("*b* ", 438)},+ }+ for _, tc := range cases {+ b.Run(tc.name, func(b *testing.B) {+ b.ReportAllocs()+ for b.Loop() {+ _ = formatHTML(tc.in)+ }+ })+ }+}