Skip to content

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

fix(agent): preserve empty switch input evaluation (#19953)

Sbaaoui Idriss4bb69edc3e55
diff --git a/internal/agent/canvas/interrupt_resume.go b/internal/agent/canvas/interrupt_resume.go
index f5d91dcc25..db87d3c2a6 100644
--- a/internal/agent/canvas/interrupt_resume.go
+++ b/internal/agent/canvas/interrupt_resume.go
@@ -169,6 +169,12 @@ func buildUserFillUpResumeOutput(cpnID string, inputSpec map[string]any, data an
}
if len(fields) == 1 {
for name := range fields {
+ if values, ok := data.(map[string]any); ok {
+ if value, exists := values[name]; exists {
+ out[name] = value
+ return out
+ }
+ }
out[name] = data
}
return out
diff --git a/internal/agent/canvas/interrupt_resume_test.go b/internal/agent/canvas/interrupt_resume_test.go
index 3d3b8c45c9..04cb3b87a8 100644
--- a/internal/agent/canvas/interrupt_resume_test.go
+++ b/internal/agent/canvas/interrupt_resume_test.go
@@ -350,6 +350,18 @@ func TestBuildUserFillUpResumeOutput_SingleFieldUsesFieldName(t *testing.T) {
}
}
+func TestBuildUserFillUpResumeOutput_SingleNamedFieldUsesMapValue(t *testing.T) {
+ out := buildUserFillUpResumeOutput("UserFillUp:Menu", map[string]any{
+ "inputs": map[string]any{
+ "demo": map[string]any{"type": "options"},
+ },
+ }, map[string]any{"demo": "loop"})
+
+ if out["demo"] != "loop" {
+ t.Fatalf("demo = %v, want loop", out["demo"])
+ }
+}
+
func TestBuildUserFillUpResumeOutput_MapResumeUsesMatchingFields(t *testing.T) {
out := buildUserFillUpResumeOutput("UserFillUp:Form", map[string]any{
"inputs": map[string]any{
diff --git a/internal/agent/component/begin_test.go b/internal/agent/component/begin_test.go
index 922af59564..370abfb65d 100644
--- a/internal/agent/component/begin_test.go
+++ b/internal/agent/component/begin_test.go
@@ -141,6 +141,28 @@ func TestBegin_PreservesStarterInputAcrossQueries(t *testing.T) {
}
}
+func TestBegin_ExplicitNamedInputUpdatesStarterValue(t *testing.T) {
+ c, _ := NewBeginComponent(map[string]any{
+ "inputs": map[string]any{"name": map[string]any{}},
+ })
+ state := canvas.NewCanvasState("run-explicit-update", "task-explicit-update")
+ ctx := canvas.WithState(t.Context(), state)
+
+ if _, err := c.Invoke(ctx, nil, map[string]any{"query": map[string]any{"name": "Alice"}}); err != nil {
+ t.Fatalf("first Invoke: %v", err)
+ }
+ out, err := c.Invoke(ctx, nil, map[string]any{"query": map[string]any{"name": "Bob"}})
+ if err != nil {
+ t.Fatalf("second Invoke: %v", err)
+ }
+ if out["name"] != "Bob" {
+ t.Fatalf("name = %v, want Bob", out["name"])
+ }
+ if value, ok := state.GetGlobal("begin@name"); !ok || value != "Bob" {
+ t.Fatalf("begin@name = %v, %v; want Bob, true", value, ok)
+ }
+}
+
func TestBegin_InitializesNilGlobalsAfterRestore(t *testing.T) {
c, _ := NewBeginComponent(map[string]any{
"inputs": map[string]any{"name": map[string]any{}},
diff --git a/internal/agent/component/switch.go b/internal/agent/component/switch.go
index e804938c12..8b947edd67 100644
--- a/internal/agent/component/switch.go
+++ b/internal/agent/component/switch.go
@@ -353,10 +353,10 @@ func evaluateClause(clause map[string]any, state *runtime.CanvasState) (bool, er
// "empty" / "not empty" don't read `right`.
if op == "empty" {
- return isEmptyValue(leftValue(left, state)), nil
+ return isEmptyValue(leftValueForEmpty(left, state)), nil
}
if op == "not empty" {
- return !isEmptyValue(leftValue(left, state)), nil
+ return !isEmptyValue(leftValueForEmpty(left, state)), nil
}
right := clause["right"]
@@ -437,6 +437,21 @@ func leftValue(left string, state *runtime.CanvasState) any {
return resolved
}
+func leftValueForEmpty(left string, state *runtime.CanvasState) any {
+ if !runtime.VarRefPattern.MatchString(left) {
+ return left
+ }
+ match := runtime.VarRefPattern.FindStringSubmatch(left)
+ if len(match) < 2 {
+ return left
+ }
+ value, err := state.GetVar(match[1])
+ if err != nil {
+ return left
+ }
+ return value
+}
+
// equalValues compares two any values with a forgiving type coercion
// (string ↔ fmt-rendered, int ↔ float64). Returns false on type
// mismatches that don't coerce cleanly.
diff --git a/internal/agent/component/switch_operators_test.go b/internal/agent/component/switch_operators_test.go
index a414d5873c..0139d10de9 100644
--- a/internal/agent/component/switch_operators_test.go
+++ b/internal/agent/component/switch_operators_test.go
@@ -90,13 +90,9 @@ func TestSwitch_Operators_NotEmpty(t *testing.T) {
if matched := runOp(t, "{{sys.body}}", "not empty", nil, map[string]any{"body": ""}); matched {
t.Errorf("not empty on '' should NOT match")
}
- // When a var ref fails to resolve, leftValue returns the raw
- // template literal (e.g. "{{sys.absent}}") so that == / != can
- // still operate and a misconfigured ref doesn't crash the run.
- // The raw literal is non-empty, so `not empty` evaluates to
- // true. This is documented in leftValue's comment.
- if matched := runOp(t, "{{sys.absent}}", "not empty", nil, map[string]any{}); !matched {
- t.Errorf("not empty on unresolved var ref (raw literal) should match (raw is non-empty)")
+ // A missing sys value resolves to nil for unary emptiness checks.
+ if matched := runOp(t, "{{sys.absent}}", "not empty", nil, map[string]any{}); matched {
+ t.Errorf("not empty on missing var should not match")
}
}
@@ -136,3 +132,99 @@ func TestSwitch_Operators_EqualFolded(t *testing.T) {
t.Errorf("== should be case-insensitive: 'HELLO' == 'hello' should match")
}
}
+
+func TestSwitch_OperatorMatrix(t *testing.T) {
+ tests := []struct {
+ name string
+ left any
+ op string
+ right any
+ wantMatch bool
+ }{
+ {name: "empty", left: "", op: "empty", wantMatch: true},
+ {name: "not empty", left: "hello", op: "not empty", wantMatch: true},
+ {name: "equals", left: "hello", op: "==", right: "hello", wantMatch: true},
+ {name: "not equals", left: "hello", op: "!=", right: "world", wantMatch: true},
+ {name: "contains", left: "hello world", op: "contains", right: "world", wantMatch: true},
+ {name: "not contains", left: "hello world", op: "not contains", right: "absent", wantMatch: true},
+ {name: "starts with", left: "hello world", op: "start with", right: "hello", wantMatch: true},
+ {name: "ends with", left: "hello world", op: "end with", right: "world", wantMatch: true},
+ {name: "greater than", left: 6, op: ">", right: 5, wantMatch: true},
+ {name: "greater or equal", left: 5, op: ">=", right: 5, wantMatch: true},
+ {name: "less than", left: 4, op: "<", right: 5, wantMatch: true},
+ {name: "less or equal", left: 5, op: "<=", right: 5, wantMatch: true},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ state := canvas.NewCanvasState("operator-matrix", tc.name)
+ state.Sys["left"] = tc.left
+ if matched := runOp(t, "{{sys.left}}", tc.op, tc.right, state.Sys); matched != tc.wantMatch {
+ t.Fatalf("matching case = %v, want %v", matched, tc.wantMatch)
+ }
+
+ rejectLeft, rejectRight := tc.left, tc.right
+ switch tc.op {
+ case "empty":
+ rejectLeft = "hello"
+ case "not empty":
+ rejectLeft = ""
+ case "==":
+ rejectRight = "world"
+ case "!=":
+ rejectRight = "hello"
+ case "contains":
+ rejectRight = "absent"
+ case "not contains":
+ rejectRight = "world"
+ case "start with":
+ rejectRight = "world"
+ case "end with":
+ rejectRight = "hello"
+ case ">", ">=":
+ rejectLeft = 4
+ case "<", "<=":
+ rejectLeft = 6
+ }
+ state.Sys["left"] = rejectLeft
+ if matched := runOp(t, "{{sys.left}}", tc.op, rejectRight, state.Sys); matched {
+ t.Fatalf("non-matching case = %v, want false", matched)
+ }
+ })
+ }
+}
+
+func TestSwitch_EmptyValueTypes(t *testing.T) {
+ tests := []struct {
+ name string
+ value any
+ want bool
+ }{
+ {name: "nil", value: nil, want: true},
+ {name: "empty string", value: "", want: true},
+ {name: "whitespace", value: " ", want: false},
+ {name: "zero", value: 0, want: false},
+ {name: "false", value: false, want: false},
+ {name: "empty array", value: []any{}, want: true},
+ {name: "non-empty array", value: []any{"x"}, want: false},
+ {name: "empty object", value: map[string]any{}, want: true},
+ {name: "non-empty object", value: map[string]any{"x": 1}, want: false},
+ }
+
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := isEmptyValue(tc.value); got != tc.want {
+ t.Fatalf("isEmptyValue(%#v) = %v, want %v", tc.value, got, tc.want)
+ }
+ })
+ }
+}
+
+func TestSwitch_EmptyResolvedNil(t *testing.T) {
+ state := canvas.NewCanvasState("empty-nil", "empty-nil")
+ state.SetVar("begin", "a", nil)
+ matched, err := evaluateClause(map[string]any{"left": "{{begin@a}}", "op": "empty"}, state)
+ if err != nil || !matched {
+ t.Fatalf("empty resolved nil = %v, %v; want true, nil", matched, err)
+ }
+}
diff --git a/internal/agent/component/switch_test.go b/internal/agent/component/switch_test.go
index b9109295ef..7c5613af98 100644
--- a/internal/agent/component/switch_test.go
+++ b/internal/agent/component/switch_test.go
@@ -240,6 +240,51 @@ func TestSwitch_LegacyConditionsAndArrayTo(t *testing.T) {
}
}
+func TestSwitch_EmptyConditionUsesLatestExplicitBeginInput(t *testing.T) {
+ begin, _ := NewBeginComponent(map[string]any{
+ "inputs": map[string]any{"a": map[string]any{}},
+ })
+ switchNode, _ := NewSwitchComponent(map[string]any{
+ "conditions": []any{
+ map[string]any{
+ "logical_operator": "and",
+ "items": []any{
+ map[string]any{"cpn_id": "begin@a", "operator": "empty"},
+ },
+ "to": []any{"if_target"},
+ },
+ },
+ "end_cpn_ids": []any{"else_target"},
+ })
+ state := canvas.NewCanvasState("run-begin-switch", "task-begin-switch")
+ ctx := withStateForTest(t.Context(), state)
+
+ for _, tc := range []struct {
+ name string
+ value string
+ want string
+ }{
+ {name: "non-empty", value: "hello", want: "else_target"},
+ {name: "empty", value: "", want: "if_target"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ beginOut, err := begin.Invoke(ctx, nil, map[string]any{"query": map[string]any{"a": tc.value}})
+ if err != nil {
+ t.Fatalf("Begin.Invoke: %v", err)
+ }
+ state.SetVar("begin", "a", beginOut["a"])
+ out, err := switchNode.Invoke(ctx, nil, nil)
+ if err != nil {
+ t.Fatalf("Switch.Invoke: %v", err)
+ }
+ targets := nextTargets(out)
+ if len(targets) != 1 || targets[0] != tc.want {
+ t.Fatalf("_next = %v, want [%q]", targets, tc.want)
+ }
+ })
+ }
+}
+
// TestSwitch_NilUpstreamContainsEmptyNeedleMatches ports the
// regression covered by python PR #16320: when an upstream
// component yields nil and the configured value is the empty
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index 007851fb1d..44dcbd6159 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -1110,30 +1110,31 @@ func extractUserInputFromFormInputs(inputs map[string]interface{}) interface{} {
if len(inputs) == 0 {
return nil
}
- if len(inputs) == 1 {
- for _, raw := range inputs {
- if field, ok := raw.(map[string]interface{}); ok {
- if v, ok := field["value"]; ok {
- return v
- }
- }
- return raw
- }
- }
out := make(map[string]any, len(inputs))
for name, raw := range inputs {
- if field, ok := raw.(map[string]interface{}); ok {
- if v, ok := field["value"]; ok {
- out[name] = v
- continue
- }
- }
- out[name] = raw
+ out[name] = unwrapFormInput(raw)
}
return out
}
+func unwrapFormInput(raw any) any {
+ field, ok := raw.(map[string]interface{})
+ if !ok {
+ return raw
+ }
+ if value, exists := field["value"]; exists {
+ return value
+ }
+ // Frontend form state can omit an untouched optional value. A field
+ // descriptor without a submitted value represents nil, not the
+ // descriptor itself (which would make Switch's `empty` fail).
+ if _, descriptor := field["type"]; descriptor {
+ return nil
+ }
+ return raw
+}
+
func countInputValues(inputs map[string]interface{}) int {
count := 0
for _, raw := range inputs {
@@ -1470,13 +1471,7 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {
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[name] = unwrapFormInput(raw)
}
values["query"] = query
return values
diff --git a/internal/handler/agent_test.go b/internal/handler/agent_test.go
index 00df11b28e..9ed0eb87b4 100644
--- a/internal/handler/agent_test.go
+++ b/internal/handler/agent_test.go
@@ -1002,10 +1002,10 @@ func TestAgentChatCompletions_DerivesUserInputFromMessages(t *testing.T) {
}
}
-// TestAgentChatCompletions_DerivesUserInputFromInputs covers the wait-for-user
-// resume path used by the front-end: the follow-up submit posts `inputs`
-// instead of a top-level `query`. The handler must lift the nested field value
-// and pass it through as the resumed user input.
+// TestAgentChatCompletions_DerivesUserInputFromInputs covers the form-submit
+// path used by the front-end: named inputs must keep their field names even
+// when only one field is present, so Begin can distinguish an explicit update
+// from ordinary conversational query text.
func TestAgentChatCompletions_DerivesUserInputFromInputs(t *testing.T) {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
@@ -1021,8 +1021,32 @@ func TestAgentChatCompletions_DerivesUserInputFromInputs(t *testing.T) {
h := &AgentHandler{chatRunner: runner}
h.AgentChatCompletions(c)
- if captured != "a b c d e" {
- t.Errorf("userInput = %#v, want %q (nested inputs.value)", captured, "a b c d e")
+ got, ok := captured.(map[string]any)
+ if !ok || got["text"] != "a b c d e" {
+ t.Errorf("userInput = %#v, want named text input", captured)
+ }
+}
+
+func TestAgentChatCompletions_MissingOptionalInputValueIsNil(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","inputs":{"a":{"name":"a","type":"line","optional":true}}}`))
+ 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 {
+ t.Fatalf("userInput type = %T, want map[string]any", captured)
+ }
+ if value, exists := got["a"]; !exists || value != nil {
+ t.Fatalf("userInput[a] = %#v, exists=%v, want nil", value, exists)
}
}