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 Starter values beside query inputs (#19420)
Sbaaoui Idriss11f4d11920cc
diff --git a/internal/agent/component/begin.go b/internal/agent/component/begin.goindex c071dbb139..68dcd9b16e 100644--- a/internal/agent/component/begin.go+++ b/internal/agent/component/begin.go@@ -103,8 +103,22 @@ func (b *BeginComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[strout := make(map[string]any, len(inputs))mapsCopy(out, inputs)for _, field := range b.inputFields {+ if _, direct := inputs[field]; !direct {+ if query, scalar := inputs["query"].(string); scalar {+ if value, initialized := state.GetGlobal("begin@" + field); initialized {+ out[field] = value+ continue+ }+ out[field] = query+ state.SetGlobal("begin@"+field, query)+ continue+ }+ }if value, ok := beginInputValue(inputs, field); ok {out[field] = value+ state.SetGlobal("begin@"+field, value)+ } else if value, ok := state.GetGlobal("begin@" + field); ok {+ out[field] = value}}return out, nil@@ -150,6 +164,9 @@ func beginInputValue(inputs map[string]any, field string) (any, bool) {}return unwrapBeginInputValue(value), true}+ // A scalar query is the legacy way to submit a single Starter field.+ // Once that field has been initialized, later conversational queries must+ // not overwrite it.return query, true}diff --git a/internal/agent/component/begin_test.go b/internal/agent/component/begin_test.goindex d8be4657ac..922af59564 100644--- a/internal/agent/component/begin_test.go+++ b/internal/agent/component/begin_test.go@@ -18,6 +18,7 @@ package componentimport ("context"+ "encoding/json""reflect""testing"@@ -96,6 +97,71 @@ func TestBegin_MapsNamedQueryInputs(t *testing.T) {}}+func TestBegin_SeparatesNamedInputFromQuery(t *testing.T) {+ c, _ := NewBeginComponent(map[string]any{+ "inputs": map[string]any{"name": map[string]any{}},+ })+ state := canvas.NewCanvasState("run-separated", "task-separated")+ out, err := c.Invoke(canvas.WithState(t.Context(), state), nil, map[string]any{+ "name": "Alice",+ "query": "Hello",+ })+ if err != nil {+ t.Fatalf("Invoke: %v", err)+ }+ if out["name"] != "Alice" || state.Sys["query"] != "Hello" {+ t.Fatalf("outputs = %#v, sys.query = %v", out, state.Sys["query"])+ }+}++func TestBegin_PreservesStarterInputAcrossQueries(t *testing.T) {+ c, _ := NewBeginComponent(map[string]any{+ "inputs": map[string]any{"name": map[string]any{}},+ })+ state := canvas.NewCanvasState("run-persistent", "task-persistent")+ ctx := canvas.WithState(t.Context(), state)++ first, err := c.Invoke(ctx, nil, map[string]any{"query": "Alice"})+ if err != nil {+ t.Fatalf("first Invoke: %v", err)+ }+ if first["name"] != "Alice" || state.Sys["query"] != "Alice" {+ t.Fatalf("first values = %#v, sys.query=%v", first, state.Sys["query"])+ }++ second, err := c.Invoke(ctx, nil, map[string]any{"query": "Hello"})+ if err != nil {+ t.Fatalf("second Invoke: %v", err)+ }+ if second["name"] != "Alice" {+ t.Fatalf("name = %v, want Alice", second["name"])+ }+ if state.Sys["query"] != "Hello" {+ t.Fatalf("sys.query = %v, want Hello", state.Sys["query"])+ }+}++func TestBegin_InitializesNilGlobalsAfterRestore(t *testing.T) {+ c, _ := NewBeginComponent(map[string]any{+ "inputs": map[string]any{"name": map[string]any{}},+ })+ var state canvas.CanvasState+ if err := json.Unmarshal([]byte(`{"sys":{}}`), &state); err != nil {+ t.Fatalf("Unmarshal: %v", err)+ }++ out, err := c.Invoke(canvas.WithState(t.Context(), &state), nil, map[string]any{"query": "Alice"})+ if err != nil {+ t.Fatalf("Invoke: %v", err)+ }+ if out["name"] != "Alice" {+ t.Fatalf("name = %v, want Alice", out["name"])+ }+ if value, ok := state.GetGlobal("begin@name"); !ok || value != "Alice" {+ t.Fatalf("begin@name = %v, %v; want Alice, true", value, ok)+ }+}+// TestBegin_PassesThroughInputs asserts the full inputs map — including// arbitrary keys beyond query / user_id — is returned unchanged as// outputs. This is the contract downstream components rely on to accessdiff --git a/internal/handler/agent.go b/internal/handler/agent.goindex d17cd84729..047dcd3ac3 100644--- a/internal/handler/agent.go+++ b/internal/handler/agent.go@@ -1260,11 +1260,15 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {}}- // Real canvas run — derive userInput from `query` first, then fall- // back to the last user message (covers the front-end that posts- // running_hint_text without a top-level `query`).- var userInput any = req.Query- if req.Query == "" {+ // Real canvas run. The editor sends the conversational query alongside+ // named Begin inputs; preserve both so a custom Starter field cannot be+ // replaced by sys.query before it reaches the runtime.+ var userInput any+ if req.Query != "" && len(req.Inputs) > 0 {+ userInput = extractUserInputWithQuery(req.Inputs, req.Query)+ } else if req.Query != "" {+ userInput = req.Query+ } else {if extracted := extractUserInputFromFormInputs(req.Inputs); extracted != nil {userInput = extracted} else if extracted := extractLastUserContent(req.Messages); extracted != "" {@@ -1475,6 +1479,21 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {common.SuccessWithData(c, result, "success")}+func extractUserInputWithQuery(inputs map[string]interface{}, query string) map[string]any {+ values := make(map[string]any, len(inputs)+1)+ for name, raw := range inputs {+ if field, ok := raw.(map[string]interface{}); ok {+ if value, exists := field["value"]; exists {+ values[name] = value+ continue+ }+ }+ values[name] = raw+ }+ values["query"] = query+ return values+}+// RerunAgent POST /api/v1/agents/rerun — requires id, dsl, and// component_id. The front-end dataflow "view result" page sends the// pipeline operation LOG id plus the edited DSL (webdiff --git a/internal/handler/agent_test.go b/internal/handler/agent_test.goindex 803028d110..3e3b5b5555 100644--- a/internal/handler/agent_test.go+++ b/internal/handler/agent_test.go@@ -999,6 +999,26 @@ func TestAgentChatCompletions_DerivesUserInputFromInputs(t *testing.T) {}}+func TestAgentChatCompletions_PreservesNamedInputsAlongsideQuery(t *testing.T) {+ gin.SetMode(gin.TestMode)+ w := httptest.NewRecorder()+ c, _ := gin.CreateTestContext(w)+ c.Request = httptest.NewRequest("POST", "/api/v1/agents/chat/completions",+ strings.NewReader(`{"agent_id":"a1","query":"Hello","inputs":{"name":{"name":"name","value":"Alice","type":"line"}}}`))+ c.Request.Header.Set("Content-Type", "application/json")+ c.Set("user", &entity.User{ID: "u1"})+ c.Set("user_id", "u1")++ var captured any+ h := &AgentHandler{chatRunner: &captureChatRunner{captured: &captured}}+ h.AgentChatCompletions(c)++ got, ok := captured.(map[string]any)+ if !ok || got["name"] != "Alice" || got["query"] != "Hello" {+ t.Fatalf("userInput = %#v, want name=Alice query=Hello", captured)+ }+}+func TestAgentChatCompletions_DerivesStructuredUserInputFromInputs(t *testing.T) {gin.SetMode(gin.TestMode)w := httptest.NewRecorder()diff --git a/internal/service/agent.go b/internal/service/agent.goindex 3c5cc5a583..3b79271d60 100644--- a/internal/service/agent.go+++ b/internal/service/agent.go@@ -21,6 +21,7 @@ import ("encoding/json""errors""fmt"+ "maps""ragflow/internal/service/file""ragflow/internal/utility""reflect"@@ -2021,9 +2022,10 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv}state.SetMemory(c.Memory)state.EnsureSysDate()- state.Sys["query"] = userInput- state.AppendCurrentUser(userInput)- state.AppendSysHistory("user: " + renderUserHistoryValue(userInput))+ query := agentRunQuery(userInput)+ state.Sys["query"] = query+ state.AppendCurrentUser(query)+ state.AppendSysHistory("user: " + renderUserHistoryValue(query))if uid, ok := root["user_id"].(string); ok && uid != "" {state.Sys["user_id"] = uid}@@ -2127,11 +2129,11 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv// previously-paused branch would be silently dropped (the// "second input doesn't resume" symptom reported for// categorize / iteration / code / wait_input etc.).- wfInput := userInput+ wfInput := agentWorkflowInput(userInput)if isResume && resumeID != "" {- wfInput = ""+ wfInput = map[string]any{"query": ""}}- workflowOutput, invokeErr := cc.Workflow.Invoke(ctx2, map[string]any{"query": wfInput}, invokeOpts...)+ workflowOutput, invokeErr := cc.Workflow.Invoke(ctx2, wfInput, invokeOpts...)err = invokeErrif errors.Is(err, context.Canceled) || errors.Is(ctx2.Err(), context.Canceled) {// A user stop or client disconnect must not be turned into a@@ -2447,7 +2449,7 @@ func (s *AgentService) persistAgentRunSession(}messages := parseAgentSessionMessages(session.Message)now := time.Now().Unix()- if text := stringifyAgentUserInput(userInput); text != "" {+ if text := stringifyAgentUserInput(agentRunQuery(userInput)); text != "" {messages = append(messages, map[string]interface{}{"role": "user", "content": text, "id": utility.GenerateToken(), "created_at": now})}if appendAssistantMessage {@@ -2500,6 +2502,11 @@ func buildPersistedAgentDSL(runDSL map[string]any, state *canvas.CanvasState) en}}}+ for key, value := range globalValues {+ if strings.HasPrefix(key, "begin@") {+ globals[key] = value+ }+ }for _, key := range []string{"query", "user_id", "conversation_turns", "files", "history", "date"} {if value, exists := sysValues[key]; exists {globals["sys."+key] = value@@ -2542,6 +2549,20 @@ func stringifyAgentUserInput(userInput any) string {}}+func agentRunQuery(userInput any) any {+ if values, ok := userInput.(map[string]any); ok {+ return values["query"]+ }+ return userInput+}++func agentWorkflowInput(userInput any) map[string]any {+ if values, ok := userInput.(map[string]any); ok {+ return maps.Clone(values)+ }+ return map[string]any{"query": userInput}+}+func appendAssistantHistory(state *canvas.CanvasState, payload map[string]any) {if state == nil {returndiff --git a/internal/service/agent_test.go b/internal/service/agent_test.goindex fd63f2a4ef..45e75b39be 100644--- a/internal/service/agent_test.go+++ b/internal/service/agent_test.go@@ -2362,6 +2362,13 @@ func TestAgentHistoryRenderingMatchesPythonShapes(t *testing.T) {}}+func TestAgentRunQueryUsesConversationQueryFromNamedInputs(t *testing.T) {+ query := agentRunQuery(map[string]any{"name": "Alice", "query": "Hello"})+ if query != "Hello" {+ t.Fatalf("query = %v, want Hello", query)+ }+}+func TestOpenAICompatPriorHistoryPreservesConversation(t *testing.T) {messages := []map[string]interface{}{{"role": "system", "content": "Be concise."},