Files
Memoh/internal/channel/adapters/matrix/markdown.go
T
AlexMa233 609ca49cf5 feat: matrix support (part 1) (#242)
* feat(channel): add Matrix adapter support

* fix(channel): prevent reasoning leaks in Matrix replies

* fix(channel): persist Matrix sync cursors

* fix(channel): improve Matrix markdown rendering

* fix(channel): support Matrix attachments and multimodal history

* fix(channel): expand Matrix reply media context

* fix(handlers): allow media downloads for chat-access bots

* fix(channel): classify Matrix DMs as direct chats

* fix(channel): auto-join Matrix room invites

* fix(channel): resolve Matrix room aliases for outbound send

* fix(web): use Matrix brand icon in channel badges

Replace the generic Matrix hashtag badge with the official brand asset so channel badges feel recognizable and fit the circular mask cleanly.

* fix(channel): add Matrix room whitelist controls

Let Matrix bots decide whether to auto-join invites and restrict inbound activity to allowed rooms or aliases. Expose the new controls in the web settings UI with line-based whitelist input so access rules stay explicit.

* fix(channel): stabilize Matrix multimodal follow-ups and settings

* fix(flow): avoid gosec panic on byte decoding

* fix: fix golangci-lint

* fix(channel): remove Matrix built-in ACL

* fix(channel): preserve Matrix image captions

* fix(channel): validate Matrix homeserver and sync access

Fail Matrix connections early when the homeserver, access token, or /sync capability is misconfigured so bot health checks surface actionable errors.

* fix(channel): preserve optional toggles and relax Matrix startup validation

* fix(channel): tighten Matrix mention fallback parsing

* fix(flow): skip structured assistant tool-call outputs

* fix(flow): resolve merged resolver duplication

Keep the internal agent resolver implementation after merging main so split helper files do not redeclare flow symbols. Restore user message normalization in sanitize and persistence paths to keep flow tests and command packages building.

* fix(flow): remove unused merged resolver helper

Drop the leftover truncate helper and import from the resolver merge fix so golangci-lint passes again without affecting flow behavior.

---------

Co-authored-by: Acbox Liu <acbox0328@gmail.com>
2026-03-22 21:55:34 +08:00

148 lines
3.4 KiB
Go

package matrix
import (
"bytes"
"regexp"
"strings"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/renderer/html"
"github.com/memohai/memoh/internal/channel"
)
const matrixHTMLFormat = "org.matrix.custom.html"
var matrixMarkdownRenderer = goldmark.New(
goldmark.WithExtensions(extension.GFM),
goldmark.WithRendererOptions(
html.WithHardWraps(),
),
)
type matrixFormattedMessage struct {
Body string
FormattedBody string
HasHTML bool
}
var (
matrixTaskListPattern = regexp.MustCompile(`^(\s*(?:[-*+]\s+|\d+\.\s+))\[( |x|X)\]\s+(.*)$`)
matrixTableAlignCell = regexp.MustCompile(`^:?-{3,}:?$`)
)
func formatMatrixMessage(msg channel.Message) matrixFormattedMessage {
body := strings.TrimSpace(msg.PlainText())
formatted := matrixFormattedMessage{Body: body}
if msg.Format != channel.MessageFormatMarkdown || body == "" {
return formatted
}
body = normalizeMatrixMarkdown(body)
formatted.Body = body
htmlBody, err := renderMatrixMarkdown(body)
if err != nil || strings.TrimSpace(htmlBody) == "" {
return formatted
}
formatted.FormattedBody = htmlBody
formatted.HasHTML = true
return formatted
}
func renderMatrixMarkdown(text string) (string, error) {
text = strings.TrimSpace(text)
if text == "" {
return "", nil
}
var buf bytes.Buffer
if err := matrixMarkdownRenderer.Convert([]byte(text), &buf); err != nil {
return "", err
}
return strings.TrimSpace(buf.String()), nil
}
func normalizeMatrixMarkdown(text string) string {
text = strings.TrimSpace(text)
if text == "" {
return ""
}
lines := strings.Split(text, "\n")
result := make([]string, 0, len(lines))
inFence := false
for i := 0; i < len(lines); i++ {
line := lines[i]
trimmed := strings.TrimSpace(line)
if isFenceLine(trimmed) {
inFence = !inFence
result = append(result, line)
continue
}
if !inFence && i+1 < len(lines) && isMarkdownTableHeader(line, lines[i+1]) {
block := []string{line, lines[i+1]}
i += 2
for i < len(lines) && isMarkdownTableRow(lines[i]) {
block = append(block, lines[i])
i++
}
i--
result = append(result, "```text")
result = append(result, block...)
result = append(result, "```")
continue
}
if !inFence {
line = normalizeMatrixTaskListLine(line)
}
result = append(result, line)
}
return strings.TrimSpace(strings.Join(result, "\n"))
}
func normalizeMatrixTaskListLine(line string) string {
matches := matrixTaskListPattern.FindStringSubmatch(line)
if len(matches) != 4 {
return line
}
box := "☐"
if strings.EqualFold(matches[2], "x") {
box = "☑"
}
return matches[1] + box + " " + matches[3]
}
func isFenceLine(line string) bool {
return strings.HasPrefix(line, "```") || strings.HasPrefix(line, "~~~")
}
func isMarkdownTableHeader(headerLine, delimiterLine string) bool {
if !strings.Contains(headerLine, "|") {
return false
}
return isMarkdownTableDelimiter(delimiterLine)
}
func isMarkdownTableDelimiter(line string) bool {
trimmed := strings.TrimSpace(line)
if !strings.Contains(trimmed, "|") {
return false
}
parts := strings.Split(trimmed, "|")
validCells := 0
for _, part := range parts {
cell := strings.TrimSpace(part)
if cell == "" {
continue
}
if !matrixTableAlignCell.MatchString(cell) {
return false
}
validCells++
}
return validCells >= 1
}
func isMarkdownTableRow(line string) bool {
trimmed := strings.TrimSpace(line)
return trimmed != "" && strings.Contains(trimmed, "|")
}