RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agent): preserve attachment-only Message output (#20655)
Sbaaoui Idrissb03c3f6b75be
diff --git a/internal/agent/component/message.go b/internal/agent/component/message.goindex 9b07e17266..cd7c98b8ed 100644--- a/internal/agent/component/message.go+++ b/internal/agent/component/message.go@@ -180,12 +180,23 @@ func (m *MessageComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[sreturn nil, fmt.Errorf("Message: nil canvas state")}- text := extractMessageText(inputs)- if text == "" {+ // A configured Message template is authoritative. The canvas edge also+ // carries the upstream output map, whose generic `content` field must not+ // override an explicit attachment/result selection. An explicit runtime+ // `text` input remains an override for callers that use the component+ // dynamically.+ text, hasRuntimeText := "", false+ if _, ok := inputs["text"]; ok {+ text, hasRuntimeText = extractMessageText(inputs), true+ }+ if !hasRuntimeText && m.text != "" {text = m.text}+ if text == "" && !hasRuntimeText {+ text = extractMessageText(inputs)+ }if text == "" {- text = fallbackMessageText(inputs)+ text = formalizedContentFallback(inputs)}// A direct Agent→Message edge stores a lazy DeferredStream in the Agent@@ -378,7 +389,9 @@ func (m *MessageComponent) resolveDeferredTemplate(ctx context.Context, text strreturn text, false, nil}if _, err := runtime.ResolveTemplate(text, state); err != nil {- return "", false, err+ if !optionalMissingAttachmentRefs(text, state) {+ return "", false, err+ }}// Ordinary Message templates are rendered and emitted once by Invoke.// Only templates that actually reference a DeferredStream belong to the@@ -470,6 +483,23 @@ func (m *MessageComponent) resolveDeferredTemplate(ctx context.Context, text strreturn out.String(), streamed, nil}+// Attachment outputs are optional side-channel values. A Message that asks+// for an attachment must still be able to emit an empty text body when the+// upstream branch produced no file; ordinary missing references remain hard+// errors.+func optionalMissingAttachmentRefs(text string, state *runtime.CanvasState) bool {+ for _, ref := range runtime.ExtractRefs(text) {+ value, err := state.GetVar(ref)+ if err != nil || value != nil {+ continue+ }+ if !strings.HasSuffix(ref, "@attachment") && !strings.HasSuffix(ref, "@attachments") {+ return false+ }+ }+ return true+}+// extractMemoryIDs normalises a memory_ids value from inputs /// params. Accepts []string and []any[string].func extractMemoryIDs(inputs map[string]any) []string {@@ -495,7 +525,7 @@ func extractMemoryIDsFromAny(v any) []string {return nil}-func fallbackMessageText(inputs map[string]any) string {+func formalizedContentFallback(inputs map[string]any) string {if inputs == nil {return ""}@@ -503,38 +533,9 @@ func fallbackMessageText(inputs map[string]any) string {return text}- var only string- count := 0- for key, value := range inputs {- if isMessageInfraInput(key) {- continue- }- text, ok := value.(string)- if !ok || strings.TrimSpace(text) == "" {- continue- }- only = text- count++- if count > 1 {- return ""- }- }- if count == 1 {- return only- }return ""}-func isMessageInfraInput(key string) bool {- switch key {- case "state", "__cpn_id__", "__legacy_noop__", "_created_time", "_elapsed_time",- "output_format", "voice", "lang", "auto_play", "memory_save", "memory_ids", "user_id", "stream":- return true- default:- return false- }-}-// stringFromStateSys reads a sys-level state value. Returns ""// when state or the key is missing. Used by the memory-save path// to pull the user's original query.diff --git a/internal/agent/component/message_test.go b/internal/agent/component/message_test.goindex 16d6db09ba..433bf0595b 100644--- a/internal/agent/component/message_test.go+++ b/internal/agent/component/message_test.go@@ -452,7 +452,7 @@ func TestMessage_FormalizedContentFallback(t *testing.T) {}}-func TestMessage_SingleStringFallback(t *testing.T) {+func TestMessage_DoesNotUseUnconfiguredUpstreamResult(t *testing.T) {c, _ := NewMessageComponent(nil)state := canvas.NewCanvasState("run-6", "task-6")ctx := withStateForTest(t.Context(), state)@@ -464,8 +464,49 @@ func TestMessage_SingleStringFallback(t *testing.T) {if err != nil {t.Fatalf("Invoke: %v", err)}- if got, _ := out["content"].(string); got != "single upstream text" {- t.Errorf("content: got %q, want %q", got, "single upstream text")+ if got, _ := out["content"].(string); got != "" {+ t.Errorf("content: got %q, want empty content", got)+ }+}++func TestMessage_AttachmentOnlyDoesNotResurrectResult(t *testing.T) {+ c, _ := NewMessageComponent(map[string]any{"content": []any{"{{source@attachments}}"}})+ state := canvas.NewCanvasState("run-attachment-only", "task-attachment-only")+ state.SetVar("source", "attachments", []map[string]any{{+ "doc_id": "d-1", "filename": "report.md", "mime_type": "text/markdown",+ "url": "/api/v1/agents/attachments/d-1/download",+ }})+ ctx := withStateForTest(t.Context(), state)+ out, err := c.Invoke(ctx, nil, map[string]any{+ "content": "upstream content",+ "attachments": []any{map[string]any{"doc_id": "d-1", "filename": "report.md", "mime_type": "text/markdown", "url": "/api/v1/agents/attachments/d-1/download"}},+ "result": "upstream result",+ "stream": false,+ })+ if err != nil {+ t.Fatalf("Invoke: %v", err)+ }+ if got, _ := out["content"].(string); strings.Contains(got, "upstream result") || strings.Contains(got, "upstream content") {+ t.Fatalf("content = %q, must not contain unconfigured upstream text", got)+ }+ downloads, ok := out["downloads"].([]DownloadInfo)+ if !ok || len(downloads) != 1 || downloads[0].DocID != "d-1" {+ t.Fatalf("downloads = %#v, want attachment metadata", out["downloads"])+ }+}++func TestMessage_MissingAttachmentIsOptional(t *testing.T) {+ c, _ := NewMessageComponent(map[string]any{"content": []any{"{{source@attachments}}"}})+ state := canvas.NewCanvasState("run-missing-attachment", "task-missing-attachment")+ ctx := withStateForTest(t.Context(), state)+ out, err := c.Invoke(ctx, nil, map[string]any{+ "content": "upstream content", "result": "upstream result",+ })+ if err != nil {+ t.Fatalf("Invoke: %v", err)+ }+ if got, _ := out["content"].(string); got != "" {+ t.Fatalf("content = %q, want empty", got)}}diff --git a/internal/service/agent.go b/internal/service/agent.goindex ff5a2d9c45..14f647594c 100644--- a/internal/service/agent.go+++ b/internal/service/agent.go@@ -2282,6 +2282,20 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv}referencePayload := agentRunReferencePayload(c, state, legacyReference)assistantOutput := terminalCanvasOutput(c, state, workflowOutput, answer, downloads, attachment)+ // The terminal Message output is authoritative. Do not let a result or+ // content field from a non-terminal upstream node become the answer when+ // the Message intentionally selected attachments only.+ if terminalContent, ok := assistantOutput["content"].(string); ok {+ answer = terminalContent+ } else {+ answer = ""+ }+ downloads = assistantOutput["downloads"]+ if terminalAttachment, ok := assistantOutput["attachment"].(map[string]any); ok {+ attachment = terminalAttachment+ } else {+ attachment = nil+ }// Release any deferred Agent node that was not consumed because the// downstream Message was skipped by an exception/branch path.runtime.CompleteAllDeferredNodes(ctx2)