Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

fix(agent): restore message download button when output file type is selected (#18955)

euvrebba1b9d91bca
diff --git a/internal/agent/canvas/runner.go b/internal/agent/canvas/runner.go
index b75790100c..2a1af77f4c 100644
--- a/internal/agent/canvas/runner.go
+++ b/internal/agent/canvas/runner.go
@@ -119,10 +119,13 @@ type MessageEvent struct {
}
// MessageEndEvent is the JSON payload for Type=="message_end" frames.
+// Attachment mirrors Python's _build_message_end: the {doc_id, format,
+// file_name} descriptor of a Message-component file export, present
+// only when one was produced.
type MessageEndEvent struct {
- Status *string `json:"status,omitempty"`
- Attachment []interface{} `json:"attachment,omitempty"`
- Reference interface{} `json:"reference,omitempty"`
+ Status *string `json:"status,omitempty"`
+ Attachment map[string]any `json:"attachment,omitempty"`
+ Reference interface{} `json:"reference,omitempty"`
}
// WaitingForUserEvent is the JSON payload for Type=="waiting_for_user"
diff --git a/internal/agent/component/io/xlsx_writer.go b/internal/agent/component/io/xlsx_writer.go
new file mode 100644
index 0000000000..0973bc2b90
--- /dev/null
+++ b/internal/agent/component/io/xlsx_writer.go
@@ -0,0 +1,284 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+// Package io — XLSX writer for the Message component's "Excel" export
+// format.
+//
+// It mirrors Python agent/component/message.py's xlsx branch: every
+// Markdown table found in the content becomes its own sheet (named
+// after the closest preceding title line, sanitized to Excel's 31-char
+// sheet-name rules), numeric-looking cells are coerced to native
+// numbers, and content without any table falls back to a single
+// "Data" sheet holding the whole text.
+
+package io
+
+import (
+ "bytes"
+ "fmt"
+ "regexp"
+ "strconv"
+ "strings"
+
+ "github.com/xuri/excelize/v2"
+)
+
+// XLSXOptions is the public contract for the XLSX writer. Reserved for
+// future header/footer support; the Python xlsx branch has none.
+type XLSXOptions struct{}
+
+var (
+ thousandSepRe = regexp.MustCompile(`^[+-]?\d{1,3}(,\d{3})+(\.\d+)?$`)
+ intRe = regexp.MustCompile(`^[+-]?\d+$`)
+ floatRe = regexp.MustCompile(`^[+-]?(\d+\.\d+|\d+\.|\.\d+)([eE][+-]?\d+)?$`)
+ floatExpRe = regexp.MustCompile(`^[+-]?\d+[eE][+-]?\d+$`)
+ leadingZeroRe = regexp.MustCompile(`^[+-]?0\d+$`)
+)
+
+// xlsxCell mirrors Python's _coerce_excel_cell_type: convert cell text
+// to a native numeric type when it is safe, so Excel stores real number
+// cells instead of text. Values with leading zeros ("00123") stay text
+// to avoid losing information, and thousand separators ("1,234.5")
+// are stripped before numeric detection.
+func xlsxCell(cell string) any {
+ value := strings.TrimSpace(cell)
+ if value == "" {
+ return ""
+ }
+ if leadingZeroRe.MatchString(value) {
+ return cell
+ }
+ candidate := value
+ if thousandSepRe.MatchString(value) {
+ candidate = strings.ReplaceAll(value, ",", "")
+ }
+ if intRe.MatchString(candidate) {
+ if n, err := strconv.Atoi(candidate); err == nil {
+ return n
+ }
+ return cell
+ }
+ if floatRe.MatchString(candidate) || floatExpRe.MatchString(candidate) {
+ if f, err := strconv.ParseFloat(candidate, 64); err == nil {
+ return f
+ }
+ return cell
+ }
+ return cell
+}
+
+type xlsxTable struct {
+ sheetName string
+ header []string
+ rows [][]any
+}
+
+// parseMarkdownTables splits content into markdown tables. Title
+// candidates (lines starting with "table", markdown headings, or
+// containing ':') directly preceding a table name its sheet.
+func parseMarkdownTables(content string) []xlsxTable {
+ type rawTable struct {
+ title string
+ lines []string
+ }
+ var tables []rawTable
+ var current []string
+ var pendingTitle string
+ inTable := false
+
+ appendTable := func() {
+ if len(current) > 0 {
+ tables = append(tables, rawTable{title: pendingTitle, lines: current})
+ }
+ current = nil
+ }
+ titleCandidate := func(stripped string) string {
+ lower := strings.ToLower(stripped)
+ if strings.HasPrefix(lower, "table") || strings.HasPrefix(stripped, "#") || strings.Contains(stripped, ":") {
+ return strings.TrimSpace(strings.TrimLeft(stripped, "#"))
+ }
+ return ""
+ }
+
+ for _, line := range strings.Split(strings.TrimSpace(content), "\n") {
+ stripped := strings.TrimSpace(line)
+ if !inTable && stripped != "" && !strings.HasPrefix(stripped, "|") {
+ pendingTitle = titleCandidate(stripped)
+ }
+ if strings.HasPrefix(stripped, "|") && strings.Contains(stripped[1:], "|") {
+ cleaned := strings.NewReplacer(" ", "", "|", "", "-", "", ":", "").Replace(stripped)
+ if cleaned == "" {
+ continue // separator line like |---|---|
+ }
+ if !inTable {
+ inTable = true
+ current = nil
+ }
+ current = append(current, stripped)
+ continue
+ }
+ if inTable {
+ appendTable()
+ inTable = false
+ pendingTitle = ""
+ if stripped != "" {
+ pendingTitle = titleCandidate(stripped)
+ }
+ }
+ }
+ if inTable {
+ appendTable()
+ }
+
+ out := make([]xlsxTable, 0, len(tables))
+ kept := 0
+ for _, t := range tables {
+ var header []string
+ var rows [][]any
+ for i, line := range t.lines {
+ cells := strings.Split(line, "|")
+ // Python drops empty cells ([c for c in cells if c]);
+ // mirror that.
+ kept := make([]string, 0, len(cells))
+ for _, c := range cells {
+ c = strings.TrimSpace(c)
+ if c != "" {
+ kept = append(kept, c)
+ }
+ }
+ if i == 0 {
+ header = kept
+ continue
+ }
+ row := make([]any, len(kept))
+ for j, c := range kept {
+ row[j] = xlsxCell(c)
+ }
+ rows = append(rows, row)
+ }
+ // A header-only table with no data rows yields no sheet: the
+ // parsed table is empty and is dropped, so the sheet-number
+ // fallback below only counts tables that actually land in the
+ // workbook.
+ if len(rows) == 0 {
+ continue
+ }
+ kept++
+ out = append(out, xlsxTable{sheetName: sanitizeSheetName(t.title, kept-1), header: header, rows: rows})
+ }
+ return out
+}
+
+// sanitizeSheetName clamps a title to Excel's sheet-name rules
+// (max 31 characters, no / \ * ? [ ] :) and falls back to "Table_N".
+func sanitizeSheetName(title string, index int) string {
+ name := title
+ if name == "" {
+ name = fmt.Sprintf("Table_%d", index+1)
+ }
+ if runes := []rune(name); len(runes) > 31 {
+ name = string(runes[:31])
+ }
+ name = strings.NewReplacer("/", "_", "\\", "_", "*", "", "?", "", "[", "", "]", "", ":", "").Replace(name)
+ if strings.TrimSpace(name) == "" {
+ name = fmt.Sprintf("Table_%d", index+1)
+ }
+ return name
+}
+
+// WriteXLSX converts Markdown content into an Excel workbook: each
+// Markdown table lands on its own sheet; when the content has no
+// table at all, a single "Data" sheet holds the whole text.
+func WriteXLSX(content string, _ XLSXOptions) ([]byte, error) {
+ f := excelize.NewFile()
+ defer f.Close()
+
+ tables := parseMarkdownTables(content)
+ if len(tables) == 0 {
+ tables = []xlsxTable{{sheetName: "Data", rows: [][]any{{content}}}}
+ }
+ used := make(map[string]bool)
+ for _, t := range tables {
+ name := t.sheetName
+ // Ensure unique sheet names: on collision append _1, _2, ...
+ // to the original name, truncating it in characters so the
+ // final name stays within the 31-character limit. Keys are
+ // lowercased because Excel and Excelize resolve sheet names
+ // case-insensitively: with a case-sensitive map, "Report"
+ // followed by "report" would alias to the same sheet and the
+ // second table would overwrite the first.
+ key := strings.ToLower(name)
+ original := []rune(name)
+ for counter := 1; used[key]; counter++ {
+ suffix := "_" + strconv.Itoa(counter)
+ trim := 31 - len(suffix)
+ if trim < 1 {
+ trim = 1
+ }
+ base := original
+ if len(base) > trim {
+ base = base[:trim]
+ }
+ name = string(base) + suffix
+ key = strings.ToLower(name)
+ }
+ used[key] = true
+ if _, err := f.NewSheet(name); err != nil {
+ return nil, fmt.Errorf("xlsx: new sheet %q: %w", name, err)
+ }
+
+ row := 1
+ if len(t.header) > 0 {
+ header := make([]any, len(t.header))
+ for i, h := range t.header {
+ header[i] = h
+ }
+ if err := writeXLSXRow(f, name, row, header); err != nil {
+ return nil, err
+ }
+ row++
+ }
+ for _, r := range t.rows {
+ if err := writeXLSXRow(f, name, row, r); err != nil {
+ return nil, err
+ }
+ row++
+ }
+ }
+ // Drop the default sheet; the workbook always has real sheets here.
+ if err := f.DeleteSheet("Sheet1"); err != nil {
+ return nil, fmt.Errorf("xlsx: delete default sheet: %w", err)
+ }
+
+ var buf bytes.Buffer
+ if err := f.Write(&buf); err != nil {
+ return nil, fmt.Errorf("xlsx: write workbook: %w", err)
+ }
+ return buf.Bytes(), nil
+}
+
+func writeXLSXRow(f *excelize.File, sheet string, row int, cells []any) error {
+ for col, v := range cells {
+ cell, err := excelize.CoordinatesToCellName(col+1, row)
+ if err != nil {
+ return fmt.Errorf("xlsx: cell name (%d,%d): %w", col+1, row, err)
+ }
+ if err := f.SetCellValue(sheet, cell, v); err != nil {
+ return fmt.Errorf("xlsx: set %s!%s: %w", sheet, cell, err)
+ }
+ }
+ return nil
+}
diff --git a/internal/agent/component/io/xlsx_writer_test.go b/internal/agent/component/io/xlsx_writer_test.go
new file mode 100644
index 0000000000..171a6fabe8
--- /dev/null
+++ b/internal/agent/component/io/xlsx_writer_test.go
@@ -0,0 +1,236 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package io
+
+import (
+ "strings"
+ "testing"
+ "unicode/utf8"
+
+ "github.com/xuri/excelize/v2"
+)
+
+func TestWriteXLSX_ParsesTablesIntoSheets(t *testing.T) {
+ content := "Intro line.\n\nTable 1: Sales\n\n| Name | Amount |\n|---|---|\n| Alice | 1,234 |\n| Bob | 00123 |\n\n## Report\n\n| Q | Revenue |\n|---|---|\n| Q1 | 42.5 |\n"
+ payload, err := WriteXLSX(content, XLSXOptions{})
+ if err != nil {
+ t.Fatalf("WriteXLSX: %v", err)
+ }
+ f, err := excelize.OpenReader(strings.NewReader(string(payload)))
+ if err != nil {
+ t.Fatalf("open workbook: %v", err)
+ }
+ defer f.Close()
+
+ sheets := f.GetSheetList()
+ if len(sheets) != 2 {
+ t.Fatalf("sheets = %v, want 2", sheets)
+ }
+ wantSheets := map[string]bool{"Table 1 Sales": false, "Report": false}
+ for _, s := range sheets {
+ if _, ok := wantSheets[s]; ok {
+ wantSheets[s] = true
+ }
+ }
+ for name, found := range wantSheets {
+ if !found {
+ t.Errorf("sheet %q missing, got %v", name, sheets)
+ }
+ }
+
+ // Numeric coercion: "1,234" → 1234 (number), "00123" stays text.
+ sales := sheets[0]
+ if v, err := f.GetCellValue(sales, "B2"); err != nil || v != "1234" {
+ t.Errorf("B2 = %q (%v), want 1234", v, err)
+ }
+ if v, err := f.GetCellValue(sales, "B3"); err != nil || v != "00123" {
+ t.Errorf("B3 = %q (%v), want 00123 kept as text", v, err)
+ }
+ report := sheets[1]
+ if v, err := f.GetCellValue(report, "B2"); err != nil || v != "42.5" {
+ t.Errorf("report B2 = %q (%v), want 42.5", v, err)
+ }
+}
+
+func TestWriteXLSX_NoTableFallsBackToDataSheet(t *testing.T) {
+ payload, err := WriteXLSX("Just plain text\nwithout tables", XLSXOptions{})
+ if err != nil {
+ t.Fatalf("WriteXLSX: %v", err)
+ }
+ f, err := excelize.OpenReader(strings.NewReader(string(payload)))
+ if err != nil {
+ t.Fatalf("open workbook: %v", err)
+ }
+ defer f.Close()
+
+ sheets := f.GetSheetList()
+ if len(sheets) != 1 || sheets[0] != "Data" {
+ t.Fatalf("sheets = %v, want [Data]", sheets)
+ }
+ v, err := f.GetCellValue("Data", "A1")
+ if err != nil || !strings.Contains(v, "Just plain text") {
+ t.Errorf("A1 = %q (%v), want the whole content", v, err)
+ }
+}
+
+func TestWriteXLSX_SheetNameTruncatesByCharacters(t *testing.T) {
+ // A CJK title (3 bytes per character) must be clamped to 31
+ // characters, not 31 bytes: byte slicing would split a rune and
+ // produce a garbled sheet name.
+ title := "## " + strings.Repeat("销", 40)
+ content := title + "\n\n| 列一 | 列二 |\n|---|---|\n| 值 | 1 |\n"
+
+ payload, err := WriteXLSX(content, XLSXOptions{})
+ if err != nil {
+ t.Fatalf("WriteXLSX: %v", err)
+ }
+ f, err := excelize.OpenReader(strings.NewReader(string(payload)))
+ if err != nil {
+ t.Fatalf("open workbook: %v", err)
+ }
+ defer f.Close()
+
+ sheets := f.GetSheetList()
+ if len(sheets) != 1 {
+ t.Fatalf("sheets = %v, want 1", sheets)
+ }
+ name := sheets[0]
+ if !utf8.ValidString(name) {
+ t.Errorf("sheet name %q is not valid UTF-8", name)
+ }
+ if got := utf8.RuneCountInString(name); got != 31 {
+ t.Errorf("sheet name %q has %d characters, want 31", name, got)
+ }
+ if want := strings.Repeat("销", 31); !strings.HasPrefix(name, want) {
+ t.Errorf("sheet name = %q, want the first 31 characters of the title (%q...)", name, want)
+ }
+ if v, err := f.GetCellValue(name, "A2"); err != nil || v != "值" {
+ t.Errorf("A2 = %q (%v), want 值", v, err)
+ }
+}
+
+func TestWriteXLSX_DuplicateSheetNamesGetUnderscoreSuffix(t *testing.T) {
+ content := "## Report\n\n| A |\n|---|\n| 1 |\n\n## Report\n\n| B |\n|---|\n| 2 |\n"
+
+ payload, err := WriteXLSX(content, XLSXOptions{})
+ if err != nil {
+ t.Fatalf("WriteXLSX: %v", err)
+ }
+ f, err := excelize.OpenReader(strings.NewReader(string(payload)))
+ if err != nil {
+ t.Fatalf("open workbook: %v", err)
+ }
+ defer f.Close()
+
+ sheets := f.GetSheetList()
+ if len(sheets) != 2 {
+ t.Fatalf("sheets = %v, want 2", sheets)
+ }
+ want := map[string]bool{"Report": false, "Report_1": false}
+ for _, s := range sheets {
+ if _, ok := want[s]; ok {
+ want[s] = true
+ }
+ }
+ for name, found := range want {
+ if !found {
+ t.Errorf("sheet %q missing, got %v", name, sheets)
+ }
+ }
+}
+
+func TestWriteXLSX_EmptyTablesAreDropped(t *testing.T) {
+ // A header-only table with no data rows produces no sheet.
+ content := "## Empty\n\n| A | B |\n|---|---|\n\n## Full\n\n| C |\n|---|\n| 2 |\n"
+
+ payload, err := WriteXLSX(content, XLSXOptions{})
+ if err != nil {
+ t.Fatalf("WriteXLSX: %v", err)
+ }
+ f, err := excelize.OpenReader(strings.NewReader(string(payload)))
+ if err != nil {
+ t.Fatalf("open workbook: %v", err)
+ }
+ defer f.Close()
+
+ sheets := f.GetSheetList()
+ if len(sheets) != 1 || sheets[0] != "Full" {
+ t.Fatalf("sheets = %v, want [Full] (header-only table dropped)", sheets)
+ }
+}
+
+func TestWriteXLSX_AllTablesEmptyFallsBackToDataSheet(t *testing.T) {
+ content := "| A |\n|---|\n"
+
+ payload, err := WriteXLSX(content, XLSXOptions{})
+ if err != nil {
+ t.Fatalf("WriteXLSX: %v", err)
+ }
+ f, err := excelize.OpenReader(strings.NewReader(string(payload)))
+ if err != nil {
+ t.Fatalf("open workbook: %v", err)
+ }
+ defer f.Close()
+
+ sheets := f.GetSheetList()
+ if len(sheets) != 1 || sheets[0] != "Data" {
+ t.Fatalf("sheets = %v, want [Data]", sheets)
+ }
+ v, err := f.GetCellValue("Data", "A1")
+ if err != nil || !strings.Contains(v, "| A |") {
+ t.Errorf("A1 = %q (%v), want the whole content", v, err)
+ }
+}
+
+func TestWriteXLSX_SheetNameCollisionCaseInsensitive(t *testing.T) {
+ // Excelize resolves sheet names case-insensitively (EqualFold), so
+ // "Report" and "report" must not land on the same sheet: the second
+ // table would silently overwrite the first one's rows.
+ content := "## Report\n\n| A | B |\n|---|---|\n| 1 | 2 |\n\n## report\n\n| C | D |\n|---|---|\n| 3 | 4 |\n"
+
+ payload, err := WriteXLSX(content, XLSXOptions{})
+ if err != nil {
+ t.Fatalf("WriteXLSX: %v", err)
+ }
+ f, err := excelize.OpenReader(strings.NewReader(string(payload)))
+ if err != nil {
+ t.Fatalf("open workbook: %v", err)
+ }
+ defer f.Close()
+
+ sheets := f.GetSheetList()
+ if len(sheets) != 2 {
+ t.Fatalf("sheets = %v, want 2 distinct sheets", sheets)
+ }
+ if sheets[0] != "Report" || sheets[1] != "report_1" {
+ t.Errorf("sheets = %v, want [Report report_1] (case-insensitive collision suffixed)", sheets)
+ }
+ // Both tables' data must survive; before the fix the second table
+ // overwrote the first sheet's rows.
+ if v, err := f.GetCellValue("Report", "A2"); err != nil || v != "1" {
+ t.Errorf("Report A2 = %q (%v), want 1", v, err)
+ }
+ if v, err := f.GetCellValue("Report", "B2"); err != nil || v != "2" {
+ t.Errorf("Report B2 = %q (%v), want 2", v, err)
+ }
+ if v, err := f.GetCellValue("report_1", "A2"); err != nil || v != "3" {
+ t.Errorf("report_1 A2 = %q (%v), want 3", v, err)
+ }
+ if v, err := f.GetCellValue("report_1", "B2"); err != nil || v != "4" {
+ t.Errorf("report_1 B2 = %q (%v), want 4", v, err)
+ }
+}
diff --git a/internal/agent/component/message.go b/internal/agent/component/message.go
index 578fe762ef..14b9f1e831 100644
--- a/internal/agent/component/message.go
+++ b/internal/agent/component/message.go
@@ -243,6 +243,22 @@ func (m *MessageComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[s
"downloads": downloads,
}
+ // File export (the "Download file type" selector). Python's
+ // _convert_content receives the resolved, un-rendered content and
+ // converts it via pypandoc/pandas; each format writer owns its own
+ // markdown handling. Exporting the format-rendered string instead
+ // would double-process the body (html export would ship the escaped
+ // text as literal content). Failures are logged, never fatal —
+ // mirroring Python's try/except around the conversion.
+ if exportFmt := messageExportFormat(string(format)); exportFmt != "" && resolved != "" {
+ attachment, exportErr := exportMessageAttachment(ctx, exportFmt, resolved)
+ if exportErr != nil {
+ common.Error("Message: export attachment failed", exportErr)
+ } else if attachment != nil {
+ out["attachment"] = attachment
+ }
+ }
+
// auto_play TTS dispatch. The audio bytes are returned under
// outputs["audio"] as a structured envelope; the SSE layer
// can choose to forward them on a separate event channel.
@@ -561,7 +577,7 @@ func (m *MessageComponent) Inputs() map[string]string {
"stream": "When true, the resolved content is delivered as an SSE stream.",
"memory_save": "When true, persist the message via the registered MemorySaver (default stub returns ErrMemoryServiceMissing).",
"memory_ids": "List of memory-store IDs to persist into (used when memory_save=true).",
- "output_format": "'html' | 'markdown' | 'plain'. Default 'plain' when unset.",
+ "output_format": "'html' | 'markdown' | 'plain' rendering; file formats (markdown/md, html, docx, xlsx, pdf) additionally export the content as a downloadable attachment.",
"auto_play": "When truthy, dispatch the resolved text through the audio.Synthesizer.",
"voice": "TTS voice hint (engine-specific).",
"lang": "TTS language tag (BCP-47, e.g. 'en' or 'zh-CN').",
@@ -573,6 +589,7 @@ func (m *MessageComponent) Outputs() map[string]string {
return map[string]string{
"content": "Resolved and rendered message body.",
"downloads": "Extracted download descriptors ({doc_id, filename, mime_type, url}).",
+ "attachment": "{doc_id, format, file_name} descriptor for the exported file when output_format selects a file format.",
"audio": "{media_type, data_b64} envelope populated when auto_play is wired and a TTS engine succeeds.",
"audio_error": "Surfaced when TTS dispatch fails; the textual content is still returned.",
"memory_error": "Surfaced when memory persistence fails; the textual content is still returned.",
diff --git a/internal/agent/component/message_export.go b/internal/agent/component/message_export.go
new file mode 100644
index 0000000000..0026a0a954
--- /dev/null
+++ b/internal/agent/component/message_export.go
@@ -0,0 +1,143 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+// Message attachment export — the Go port of Python message.py's
+// `_convert_content`: when the Message component declares a file
+// `output_format` (the "Download file type" selector in the UI), the
+// resolved content is converted to that format, uploaded to the
+// agent attachment storage, and surfaced as outputs["attachment"]
+// ({doc_id, format, file_name}). The front-end renders the message
+// download button from that descriptor.
+
+package component
+
+import (
+ "bytes"
+ "context"
+ "fmt"
+ "strings"
+
+ "github.com/google/uuid"
+ "github.com/yuin/goldmark"
+ gmhtml "github.com/yuin/goldmark/renderer/html"
+
+ iow "ragflow/internal/agent/component/io"
+ "ragflow/internal/common"
+)
+
+// messageExportFormat normalizes the raw output_format value to a
+// supported export format. It returns "" when the value only selects a
+// text rendering style (plain / empty) or is not a file format, in
+// which case no attachment is exported. This deliberately deviates
+// from the Python runtime, which coerces any unrecognized non-empty
+// format to markdown: a plain rendering should not fabricate a
+// download, so only explicit file formats produce an attachment.
+func messageExportFormat(raw string) string {
+ switch strings.ToLower(strings.TrimSpace(raw)) {
+ case "markdown", "md":
+ return "markdown"
+ case "html":
+ return "html"
+ case "docx":
+ return "docx"
+ case "xlsx":
+ return "xlsx"
+ case "pdf":
+ return "pdf"
+ default:
+ return ""
+ }
+}
+
+// exportMessageAttachment converts the resolved (un-rendered) markdown
+// content to the requested format, stores it via the agent attachment
+// storage, and returns the attachment descriptor consumed by the
+// front-end download button (group-button.tsx reads {doc_id, format,
+// file_name}). Each format writer owns its own markdown handling, the
+// same contract as Python's pypandoc/pandas conversion.
+//
+// Errors are returned to the caller, which logs them and continues —
+// a failed export must not break the message itself (Python wraps the
+// whole conversion in try/except).
+func exportMessageAttachment(ctx context.Context, format, content string) (map[string]any, error) {
+ exported := strings.TrimSpace(common.StripThinkTrailing(content))
+ if exported == "" {
+ return nil, nil
+ }
+
+ var payload []byte
+ var err error
+ switch format {
+ case "html":
+ // Convert the markdown body to an HTML fragment first, as
+ // pypandoc does (format="markdown" → html); WriteHTML only
+ // adds the document wrapper around the fragment.
+ payload = iow.WriteHTML(markdownToHTML(exported), iow.HTMLOptions{
+ FontSize: defaultDocsFontSize,
+ FontFamily: defaultHTMLFontFamily,
+ })
+ case "docx":
+ payload, err = iow.WriteDOCX(exported, iow.DOCXOptions{
+ FontSize: defaultDocsFontSize,
+ CJKFontFamily: defaultDOCXFontFamily,
+ })
+ case "pdf":
+ payload, err = iow.WritePDF(exported, iow.PDFOptions{
+ FontSize: defaultDocsFontSize,
+ FontFamily: defaultPDFFontFamily,
+ AddPageNumbers: true,
+ })
+ case "xlsx":
+ payload, err = iow.WriteXLSX(exported, iow.XLSXOptions{})
+ default: // markdown
+ payload = iow.WriteMarkdown(exported, iow.MarkdownOptions{})
+ }
+ if err != nil {
+ return nil, fmt.Errorf("convert to %s: %w", format, err)
+ }
+
+ docID := uuid.New().String()
+ stored, err := storeAgentAttachment(ctx, docID, payload)
+ if err != nil {
+ return nil, fmt.Errorf("store attachment: %w", err)
+ }
+ if !stored {
+ // No tenant/storage context (e.g. unit tests): nothing was
+ // persisted, so do not advertise a download that would 404.
+ return nil, nil
+ }
+ return map[string]any{
+ "doc_id": docID,
+ "format": format,
+ "file_name": fmt.Sprintf("%s.%s", docID[:8], format),
+ }, nil
+}
+
+// markdownToHTML renders markdown source to an HTML fragment, the Go
+// counterpart of pypandoc's markdown→html conversion in Python's
+// _convert_content: headings, emphasis and tables keep their structure
+// in the exported file instead of shipping as literal text. Raw HTML
+// in the source passes through (pandoc's raw_html default). On a
+// conversion error the plain content is kept rather than dropping the
+// export.
+func markdownToHTML(content string) string {
+ var buf bytes.Buffer
+ md := goldmark.New(goldmark.WithRendererOptions(gmhtml.WithUnsafe()))
+ if err := md.Convert([]byte(content), &buf); err != nil {
+ return content
+ }
+ return buf.String()
+}
diff --git a/internal/agent/component/message_export_test.go b/internal/agent/component/message_export_test.go
new file mode 100644
index 0000000000..8b034a465a
--- /dev/null
+++ b/internal/agent/component/message_export_test.go
@@ -0,0 +1,199 @@
+//
+// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+
+package component
+
+import (
+ "strings"
+ "testing"
+
+ "ragflow/internal/agent/canvas"
+ "ragflow/internal/storage"
+)
+
+// TestMessage_ExportAttachment mirrors the regression behind the
+// "download file type selected but no download button" report: a
+// Message with output_format=md must surface outputs["attachment"]
+// with {doc_id, format, file_name} and persist the file in the
+// tenant-downloads bucket, exactly like Python's _convert_content.
+func TestMessage_ExportAttachment(t *testing.T) {
+ storageFactory := storage.GetStorageFactory()
+ prevStorage := storageFactory.GetStorage()
+ memStorage := storage.NewMemoryStorage()
+ storageFactory.SetStorage(memStorage)
+ t.Cleanup(func() { storageFactory.SetStorage(prevStorage) })
+
+ c, err := New(componentNameMessage, map[string]any{
+ "text": "# Report\n\nHello **world**",
+ "output_format": "md",
+ })
+ if err != nil {
+ t.Fatalf("New(Message): %v", err)
+ }
+ state := canvas.NewCanvasState("run-1", "task-1")
+ state.Sys["tenant_id"] = "tenant-1"
+ ctx := canvas.WithState(t.Context(), state)
+
+ out, err := c.Invoke(ctx, nil, map[string]any{"stream": false})
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ attachment, ok := out["attachment"].(map[string]any)
+ if !ok {
+ t.Fatalf("attachment = %#v, want a descriptor map (download button depends on it)", out["attachment"])
+ }
+ docID, _ := attachment["doc_id"].(string)
+ if docID == "" {
+ t.Fatalf("attachment doc_id empty: %#v", attachment)
+ }
+ if attachment["format"] != "markdown" {
+ t.Errorf("format = %v, want markdown (md is normalized)", attachment["format"])
+ }
+ fileName, _ := attachment["file_name"].(string)
+ if !strings.HasPrefix(fileName, docID[:8]+".markdown") {
+ t.Errorf("file_name = %q, want <docID[:8]>.markdown", fileName)
+ }
+
+ blob, err := memStorage.Get(ctx, "tenant-1-downloads", docID)
+ if err != nil {
+ t.Fatalf("stored blob missing: %v", err)
+ }
+ if !strings.Contains(string(blob), "Hello **world**") {
+ t.Errorf("stored blob = %q, want the exported markdown content", string(blob))
+ }
+}
+
+// TestMessage_ExportAttachmentXlsx covers the Excel branch: markdown
+// tables land in sheets inside the stored workbook.
+func TestMessage_ExportAttachmentXlsx(t *testing.T) {
+ storageFactory := storage.GetStorageFactory()
+ prevStorage := storageFactory.GetStorage()
+ memStorage := storage.NewMemoryStorage()
+ storageFactory.SetStorage(memStorage)
+ t.Cleanup(func() { storageFactory.SetStorage(prevStorage) })
+
+ c, err := New(componentNameMessage, map[string]any{
+ "text": "| K | V |\n|---|---|\n| a | 1 |",
+ "output_format": "xlsx",
+ })
+ if err != nil {
+ t.Fatalf("New(Message): %v", err)
+ }
+ state := canvas.NewCanvasState("run-1", "task-1")
+ state.Sys["tenant_id"] = "tenant-1"
+ ctx := canvas.WithState(t.Context(), state)
+
+ out, err := c.Invoke(ctx, nil, map[string]any{"stream": false})
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ attachment, ok := out["attachment"].(map[string]any)
+ if !ok {
+ t.Fatalf("attachment = %#v, want a descriptor map", out["attachment"])
+ }
+ docID, _ := attachment["doc_id"].(string)
+ if attachment["format"] != "xlsx" {
+ t.Errorf("format = %v, want xlsx", attachment["format"])
+ }
+ blob, err := memStorage.Get(ctx, "tenant-1-downloads", docID)
+ if err != nil {
+ t.Fatalf("stored blob missing: %v", err)
+ }
+ // XLSX workbooks are ZIP archives and start with the PK magic.
+ if len(blob) < 4 || string(blob[:2]) != "PK" {
+ t.Errorf("stored blob is not a ZIP/XLSX payload (first bytes: %x)", blob[:4])
+ }
+}
+
+// TestMessage_ExportAttachmentHTML pins the html branch conversion
+// contract: the exported file is produced from the resolved markdown
+// (converted to an HTML fragment, as pypandoc does in Python), not
+// from the already-escaped output_format rendering — headings and
+// emphasis must survive as real HTML instead of literal text.
+func TestMessage_ExportAttachmentHTML(t *testing.T) {
+ storageFactory := storage.GetStorageFactory()
+ prevStorage := storageFactory.GetStorage()
+ memStorage := storage.NewMemoryStorage()
+ storageFactory.SetStorage(memStorage)
+ t.Cleanup(func() { storageFactory.SetStorage(prevStorage) })
+
+ c, err := New(componentNameMessage, map[string]any{
+ "text": "# Report\n\nHello **world**",
+ "output_format": "html",
+ })
+ if err != nil {
+ t.Fatalf("New(Message): %v", err)
+ }
+ state := canvas.NewCanvasState("run-1", "task-1")
+ state.Sys["tenant_id"] = "tenant-1"
+ ctx := canvas.WithState(t.Context(), state)
+
+ out, err := c.Invoke(ctx, nil, map[string]any{"stream": false})
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ attachment, ok := out["attachment"].(map[string]any)
+ if !ok {
+ t.Fatalf("attachment = %#v, want a descriptor map", out["attachment"])
+ }
+ if attachment["format"] != "html" {
+ t.Errorf("format = %v, want html", attachment["format"])
+ }
+ docID, _ := attachment["doc_id"].(string)
+ if docID == "" {
+ t.Fatalf("attachment doc_id empty: %#v", attachment)
+ }
+
+ blob, err := memStorage.Get(ctx, "tenant-1-downloads", docID)
+ if err != nil {
+ t.Fatalf("stored blob missing: %v", err)
+ }
+ html := string(blob)
+ if !strings.Contains(html, "<!DOCTYPE html>") {
+ t.Errorf("exported blob is not a full HTML document")
+ }
+ for _, want := range []string{"<h1>Report</h1>", "<strong>world</strong>"} {
+ if !strings.Contains(html, want) {
+ t.Errorf("exported html = %q, want it to contain %q (markdown converted, not literal text)", html, want)
+ }
+ }
+ for _, banned := range []string{"&lt;h1&gt;", "&lt;strong&gt;", "# Report"} {
+ if strings.Contains(html, banned) {
+ t.Errorf("exported html = %q, must not contain escaped/literal markdown %q", html, banned)
+ }
+ }
+}
+
+// TestMessage_NoExportWithoutFileFormat ensures plain/markdown text
+// rendering formats do not fabricate attachments.
+func TestMessage_NoExportWithoutFileFormat(t *testing.T) {
+ c, err := New(componentNameMessage, map[string]any{
+ "text": "plain hello",
+ })
+ if err != nil {
+ t.Fatalf("New(Message): %v", err)
+ }
+ state := canvas.NewCanvasState("run-1", "task-1")
+ ctx := withStateForTest(t.Context(), state)
+
+ out, err := c.Invoke(ctx, nil, map[string]any{"stream": false})
+ if err != nil {
+ t.Fatalf("Invoke: %v", err)
+ }
+ if _, ok := out["attachment"]; ok {
+ t.Errorf("attachment = %#v, want absent for plain rendering", out["attachment"])
+ }
+}
diff --git a/internal/service/agent.go b/internal/service/agent.go
index ad0589ea9b..3c5cc5a583 100644
--- a/internal/service/agent.go
+++ b/internal/service/agent.go
@@ -2151,6 +2151,7 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv
var thinking string
var legacyReference []interface{}
var downloads any
+ var attachment map[string]any
now := float64(time.Now().UnixNano()) / 1e9
for _, bucket := range state.Snapshot() {
if v, ok := bucket["answer"].(string); ok && v != "" {
@@ -2173,9 +2174,12 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv
if v, ok := bucket["downloads"]; ok && !emptyDownloadValue(v) {
downloads = v
}
+ if v, ok := bucket["attachment"].(map[string]any); ok && len(v) > 0 {
+ attachment = v
+ }
}
referencePayload := agentRunReferencePayload(state, legacyReference)
- assistantOutput := terminalCanvasOutput(c, state, workflowOutput, answer, downloads)
+ assistantOutput := terminalCanvasOutput(c, state, workflowOutput, answer, downloads, attachment)
// Release any deferred Agent node that was not consumed because the
// downstream Message was skipped by an exception/branch path.
runtime.CompleteAllDeferredNodes(ctx2)
@@ -2198,7 +2202,7 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv
_ = s.runTracker.MarkWaiting(ctx2, runID)
}
if answer != "" {
- appendAssistantHistory(state, partialAssistantOutput(answer, downloads))
+ appendAssistantHistory(state, partialAssistantOutput(answer, downloads, attachment))
}
if persistErr := s.persistAgentRunSession(ctx, canvasID, userID, sessionID, messageID, userInput, answer, thinking, referencePayload, dsl, state, answer != ""); persistErr != nil {
return nil, canvas.NewInternalRunError(
@@ -2211,7 +2215,8 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv
}
meData, _ := json.Marshal(canvas.MessageEndEvent{
- Reference: referencePayload,
+ Attachment: attachment,
+ Reference: referencePayload,
})
emit("message_end", string(meData))
}
@@ -2231,14 +2236,15 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv
if shouldEmitMessage {
meData, _ := json.Marshal(canvas.MessageEndEvent{
- Reference: referencePayload,
+ Attachment: attachment,
+ Reference: referencePayload,
})
emit("message_end", string(meData))
}
wfPayload := map[string]interface{}{
"inputs": map[string]any{"query": userInput},
- "outputs": workflowOutputs(answer, downloads),
+ "outputs": workflowOutputs(answer, downloads, attachment),
"elapsed_time": now - startedAt,
"created_at": now,
}
@@ -2269,7 +2275,8 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv
if shouldEmitMessage {
meData, _ := json.Marshal(canvas.MessageEndEvent{
- Reference: referencePayload,
+ Attachment: attachment,
+ Reference: referencePayload,
})
emit("message_end", string(meData))
}
@@ -2278,7 +2285,7 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv
// per-run token usage across all LLM calls in this turn.
wfPayload := map[string]interface{}{
"inputs": map[string]any{"query": userInput},
- "outputs": workflowOutputs(answer, downloads),
+ "outputs": workflowOutputs(answer, downloads, attachment),
"elapsed_time": now - startedAt,
"created_at": now,
}
@@ -2376,14 +2383,31 @@ func runIDFor(canvasID string, root map[string]any) string {
return canvasID
}
-func workflowOutputs(content string, downloads any) any {
- if emptyDownloadValue(downloads) {
+func workflowOutputs(content string, downloads, attachment any) any {
+ if emptyDownloadValue(downloads) && emptyAttachmentValue(attachment) {
return content
}
- return map[string]any{
- "content": content,
- "downloads": downloads,
+ out := map[string]any{"content": content}
+ if !emptyDownloadValue(downloads) {
+ out["downloads"] = downloads
+ }
+ if !emptyAttachmentValue(attachment) {
+ out["attachment"] = attachment
}
+ return out
+}
+
+// emptyAttachmentValue reports whether an attachment descriptor is
+// absent or empty (nil or an empty map), matching the omitempty
+// semantics of the message_end frame.
+func emptyAttachmentValue(value any) bool {
+ if value == nil {
+ return true
+ }
+ if m, ok := value.(map[string]any); ok {
+ return len(m) == 0
+ }
+ return false
}
func emptyDownloadValue(value any) bool {
@@ -2526,11 +2550,14 @@ func appendAssistantHistory(state *canvas.CanvasState, payload map[string]any) {
state.AppendSysHistory("assistant: " + pythonHistoryRepr(payload))
}
-func partialAssistantOutput(answer string, downloads any) map[string]any {
+func partialAssistantOutput(answer string, downloads, attachment any) map[string]any {
output := map[string]any{"content": answer}
if !emptyDownloadValue(downloads) {
output["downloads"] = downloads
}
+ if !emptyAttachmentValue(attachment) {
+ output["attachment"] = attachment
+ }
return output
}
@@ -2540,6 +2567,7 @@ func terminalCanvasOutput(
workflowOutput map[string]any,
answer string,
downloads any,
+ attachment any,
) map[string]any {
terminalIDs := make([]string, 0)
if c != nil {
@@ -2570,6 +2598,9 @@ func terminalCanvasOutput(
if !emptyDownloadValue(downloads) {
fallback["downloads"] = downloads
}
+ if !emptyAttachmentValue(attachment) {
+ fallback["attachment"] = attachment
+ }
return fallback
}
diff --git a/internal/service/agent_test.go b/internal/service/agent_test.go
index b7d64adfe1..c3e3de4b83 100644
--- a/internal/service/agent_test.go
+++ b/internal/service/agent_test.go
@@ -371,9 +371,9 @@ func TestWorkflowOutputs_WithDownloads(t *testing.T) {
},
}
- out, ok := workflowOutputs("", downloads).(map[string]any)
+ out, ok := workflowOutputs("", downloads, nil).(map[string]any)
if !ok {
- t.Fatalf("workflowOutputs type = %T, want map", workflowOutputs("", downloads))
+ t.Fatalf("workflowOutputs type = %T, want map", workflowOutputs("", downloads, nil))
}
if out["content"] != "" {
t.Fatalf("content = %v, want empty string", out["content"])
@@ -381,14 +381,32 @@ func TestWorkflowOutputs_WithDownloads(t *testing.T) {
if got := out["downloads"]; !reflect.DeepEqual(got, downloads) {
t.Fatalf("downloads = %#v, want %#v", got, downloads)
}
+ if _, has := out["attachment"]; has {
+ t.Fatalf("attachment unexpectedly present: %#v", out["attachment"])
+ }
}
func TestWorkflowOutputs_NoDownloadsKeepsString(t *testing.T) {
- if got := workflowOutputs("answer", nil); got != "answer" {
+ if got := workflowOutputs("answer", nil, nil); got != "answer" {
t.Fatalf("workflowOutputs without downloads = %#v, want string answer", got)
}
}
+func TestWorkflowOutputs_WithAttachment(t *testing.T) {
+ attachment := map[string]any{"doc_id": "d2", "format": "markdown", "file_name": "d2.markdown"}
+
+ out, ok := workflowOutputs("answer", nil, attachment).(map[string]any)
+ if !ok {
+ t.Fatalf("workflowOutputs type = %T, want map", workflowOutputs("answer", nil, attachment))
+ }
+ if out["content"] != "answer" {
+ t.Fatalf("content = %v, want answer", out["content"])
+ }
+ if got := out["attachment"]; !reflect.DeepEqual(got, attachment) {
+ t.Fatalf("attachment = %#v, want %#v", got, attachment)
+ }
+}
+
// TestGetVersion_Success verifies getting a specific version by ID.
func TestGetVersion_Success(t *testing.T) {
testDB := setupServiceTestDB(t)