Skip to content

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

test(api): migrate REST API coverage to Go (#20991)

Sbaaoui Idriss1a5e82c74886
diff --git a/test/api/agent_api_test.go b/test/api/agent_api_test.go
new file mode 100644
index 0000000000..697e0823a7
--- /dev/null
+++ b/test/api/agent_api_test.go
@@ -0,0 +1,542 @@
+//go:build integration
+
+package api
+
+import (
+ "bytes"
+ "encoding/json/v2"
+ "net/http"
+ "os"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+func echoAgentDSL() apiObject {
+ return apiObject{
+ "components": apiObject{
+ "begin": apiObject{
+ "obj": apiObject{"component_name": "Begin", "params": apiObject{}},
+ "downstream": []any{"message"}, "upstream": []any{},
+ },
+ "message": apiObject{
+ "obj": apiObject{"component_name": "Message", "params": apiObject{"content": []any{"{sys.query}"}}},
+ "downstream": []any{}, "upstream": []any{"begin"},
+ },
+ },
+ "history": []any{}, "retrieval": []any{}, "path": []any{}, "variables": apiObject{},
+ "globals": apiObject{"sys.query": "", "sys.user_id": "", "sys.conversation_turns": 0, "sys.files": []any{}},
+ }
+}
+
+func createRESTAgent(t *testing.T, title string, dsl apiObject) string {
+ t.Helper()
+ response := restCall(t, TestConfig, http.MethodPost, "/agents", apiObject{"title": title, "dsl": dsl}, nil)
+ if data, ok := response.JSON["data"].(map[string]any); ok {
+ if id, ok := data["id"].(string); ok && id != "" {
+ cleanupResource(t, TestConfig, "agents", id)
+ }
+ }
+ envelope := restOK(t, response)
+ id, ok := object(t, envelope["data"])["id"].(string)
+ if !ok || id == "" {
+ t.Fatalf("created agent has no ID: %v", envelope)
+ }
+ return id
+}
+
+func createRESTAgentSession(t *testing.T, agentID, name string) string {
+ t.Helper()
+ path := "/agents/" + agentID + "/sessions"
+ response := restCall(t, TestConfig, http.MethodPost, path, apiObject{"name": name}, nil)
+ if data, ok := response.JSON["data"].(map[string]any); ok {
+ if id, ok := data["id"].(string); ok && id != "" {
+ t.Cleanup(func() {
+ restOK(t, restCall(t, TestConfig, http.MethodDelete, path+"/"+id, nil, nil))
+ })
+ }
+ }
+ envelope := restOK(t, response)
+ id, ok := object(t, envelope["data"])["id"].(string)
+ if !ok || id == "" {
+ t.Fatalf("created session has no ID: %v", envelope)
+ }
+ return id
+}
+
+func getRESTAgent(t *testing.T, id string) apiObject {
+ t.Helper()
+ return object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/agents/"+id, nil, nil))["data"])
+}
+
+func TestRESTAgentCRUD(t *testing.T) {
+ title := uniqueName("agent_crud")
+ id := createRESTAgent(t, title, echoAgentDSL())
+ path := "/agents/" + id
+ if got := getRESTAgent(t, id); got["id"] != id || got["title"] != title {
+ t.Fatalf("GET did not persist created agent: %v", got)
+ }
+ duplicateID := createRESTAgent(t, title, echoAgentDSL())
+ if got := getRESTAgent(t, duplicateID)["title"]; got != title+"(1)" {
+ t.Fatalf("duplicate title = %v, want %s(1)", got, title)
+ }
+
+ for _, tc := range []struct {
+ name string
+ query apiObject
+ want int
+ }{
+ {"keyword_filter", apiObject{"keywords": title, "canvas_category": "agent_canvas", "orderby": "title", "desc": false}, 2},
+ {"first_page", apiObject{"keywords": title, "canvas_category": "agent_canvas", "page": 1, "page_size": 1, "orderby": "title", "desc": false}, 1},
+ {"second_page", apiObject{"keywords": title, "canvas_category": "agent_canvas", "page": 2, "page_size": 1, "orderby": "title", "desc": false}, 1},
+ {"missing_keyword", apiObject{"keywords": uniqueName("missing_agent"), "canvas_category": "agent_canvas"}, 0},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/agents", nil, tc.query))["data"])
+ items := array(t, data["canvas"])
+ if len(items) != tc.want {
+ t.Fatalf("canvas count = %d, want %d; data=%v", len(items), tc.want, data)
+ }
+ wantTotal := float64(2)
+ if tc.want == 0 {
+ wantTotal = 0
+ }
+ if data["total"] != wantTotal {
+ t.Fatalf("filtered total = %v, want %v", data["total"], wantTotal)
+ }
+ if len(items) > 0 && tc.name != "second_page" && object(t, items[0])["id"] != id {
+ t.Fatalf("ascending title order first agent = %v, want %s", items[0], id)
+ }
+ if tc.name == "second_page" && object(t, items[0])["id"] != duplicateID {
+ t.Fatalf("second page = %v, want duplicate %s", items, duplicateID)
+ }
+ })
+ }
+
+ newTitle := uniqueName("agent_updated")
+ restOK(t, restCall(t, TestConfig, http.MethodPut, path, apiObject{"title": newTitle, "description": "persisted update"}, nil))
+ got := getRESTAgent(t, id)
+ if got["title"] != newTitle || got["description"] != "persisted update" {
+ t.Fatalf("partial update did not persist: %v", got)
+ }
+ if _, ok := got["dsl"].(map[string]any); !ok {
+ t.Fatalf("partial update discarded DSL: %v", got)
+ }
+ t.Run("duplicate_update_is_atomic", func(t *testing.T) {
+ restCode(t, restCall(t, TestConfig, http.MethodPut, path,
+ apiObject{"title": title + "(1)", "description": "must not persist"}, nil), http.StatusOK, 102)
+ after := getRESTAgent(t, id)
+ if after["title"] != newTitle || after["description"] != "persisted update" {
+ t.Fatalf("rejected duplicate update mutated agent: %v", after)
+ }
+ })
+ restOK(t, restCall(t, TestConfig, http.MethodDelete, path, nil, nil))
+ restCode(t, restCall(t, TestConfig, http.MethodGet, path, nil, nil), http.StatusOK, 103)
+ restCode(t, restCall(t, TestConfig, http.MethodDelete, path, nil, nil), http.StatusOK, 103)
+}
+
+func TestRESTAgentValidation(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ body apiObject
+ text string
+ }{
+ {"missing_dsl", apiObject{"title": uniqueName("no_dsl")}, "no dsl data"},
+ {"missing_title", apiObject{"dsl": echoAgentDSL()}, "no title"},
+ {"empty_title", apiObject{"title": "", "dsl": echoAgentDSL()}, "no title"},
+ {"whitespace_title", apiObject{"title": " \t ", "dsl": echoAgentDSL()}, "no title"},
+ {"null_dsl", apiObject{"title": uniqueName("null_dsl"), "dsl": nil}, "no dsl data"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ result := restCall(t, TestConfig, http.MethodPost, "/agents", tc.body, nil)
+ restCode(t, result, http.StatusOK, 101)
+ if message, _ := result.JSON["message"].(string); !strings.Contains(strings.ToLower(message), tc.text) {
+ t.Fatalf("validation message = %q, want %q", message, tc.text)
+ }
+ })
+ }
+ for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete} {
+ t.Run("missing_agent_"+method, func(t *testing.T) {
+ restCode(t, restCall(t, TestConfig, method, "/agents/"+uniqueName("missing"), apiObject{}, nil), http.StatusOK, 103)
+ })
+ }
+ id := createRESTAgent(t, uniqueName("invalid_dsl"), echoAgentDSL())
+ before := getRESTAgent(t, id)
+ restCode(t, restCall(t, TestConfig, http.MethodPut, "/agents/"+id, apiObject{"dsl": "invalid"}, nil), http.StatusOK, 102)
+ after := getRESTAgent(t, id)
+ if !reflect.DeepEqual(before["dsl"], after["dsl"]) {
+ t.Fatalf("rejected DSL update changed graph: before=%v after=%v", before["dsl"], after["dsl"])
+ }
+}
+
+func TestRESTAgentSessions(t *testing.T) {
+ id := createRESTAgent(t, uniqueName("agent_sessions"), echoAgentDSL())
+ otherID := createRESTAgent(t, uniqueName("other_agent"), echoAgentDSL())
+ sessionID := createRESTAgentSession(t, id, "first_session")
+ secondID := createRESTAgentSession(t, id, "second_session")
+ path := "/agents/" + id + "/sessions"
+ session := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, path+"/"+sessionID, nil, nil))["data"])
+ if session["id"] != sessionID || session["name"] != "first_session" {
+ t.Fatalf("session creation did not persist: %v", session)
+ }
+ envelope := restOK(t, restCall(t, TestConfig, http.MethodGet, path, nil, apiObject{"page": 1, "page_size": 1, "keywords": "first_session"}))
+ items := array(t, envelope["data"])
+ if len(items) != 1 || object(t, items[0])["id"] != sessionID || envelope["total"] != float64(1) {
+ t.Fatalf("session filtering/pagination did not isolate first session: %v", envelope)
+ }
+ restCode(t, restCall(t, TestConfig, http.MethodGet, "/agents/"+otherID+"/sessions/"+sessionID, nil, nil), http.StatusOK, 404)
+ wrongDelete := restOK(t, restCall(t, TestConfig, http.MethodDelete, "/agents/"+otherID+"/sessions/"+sessionID, nil, nil))
+ if wrongDelete["data"] != false {
+ t.Fatalf("cross-agent session delete must be a no-op: %v", wrongDelete)
+ }
+ restOK(t, restCall(t, TestConfig, http.MethodGet, path+"/"+sessionID, nil, nil))
+ deleted := restOK(t, restCall(t, TestConfig, http.MethodDelete, path+"/"+sessionID, nil, nil))
+ if deleted["data"] != true {
+ t.Fatalf("session deletion returned %v", deleted)
+ }
+ restCode(t, restCall(t, TestConfig, http.MethodGet, path+"/"+sessionID, nil, nil), http.StatusOK, 404)
+ repeated := restOK(t, restCall(t, TestConfig, http.MethodDelete, path+"/"+sessionID, nil, nil))
+ if repeated["data"] != false {
+ t.Fatalf("repeated deletion must be a no-op: %v", repeated)
+ }
+ restOK(t, restCall(t, TestConfig, http.MethodGet, path+"/"+secondID, nil, nil))
+ for _, tc := range []struct {
+ method string
+ code int
+ }{{http.MethodGet, 103}, {http.MethodPost, 103}, {http.MethodDelete, 102}} {
+ t.Run("missing_agent_"+tc.method, func(t *testing.T) {
+ restCode(t, restCall(t, TestConfig, tc.method, "/agents/"+uniqueName("missing")+"/sessions", apiObject{}, nil), http.StatusOK, tc.code)
+ })
+ }
+ t.Run("invalid_date_filter", func(t *testing.T) {
+ restCode(t, restCall(t, TestConfig, http.MethodGet, path, nil, apiObject{"from_date": "not-a-date"}), http.StatusOK, 101)
+ })
+}
+
+func TestRESTAgentCompletionValidation(t *testing.T) {
+ id := createRESTAgent(t, uniqueName("completion_validation"), echoAgentDSL())
+ for _, tc := range []struct {
+ name string
+ body apiObject
+ code int
+ }{
+ {"missing_agent", apiObject{"query": "hello", "stream": false}, 101},
+ {"empty_openai_messages", apiObject{"agent_id": id, "openai-compatible": true, "messages": []any{}}, 102},
+ {"unknown_agent", apiObject{"agent_id": uniqueName("missing"), "query": "hello"}, 103},
+ {"unknown_session", apiObject{"agent_id": id, "session_id": uniqueName("missing"), "query": "hello"}, 103},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ restCode(t, restCall(t, TestConfig, http.MethodPost, "/agents/chat/completions", tc.body, nil), http.StatusOK, tc.code)
+ })
+ }
+}
+
+func TestRESTAgentCompletions(t *testing.T) {
+ for _, mode := range []struct {
+ name string
+ openAI bool
+ stream bool
+ }{
+ {"native_nonstream", false, false},
+ {"native_stream", false, true},
+ {"openai_nonstream", true, false},
+ {"openai_stream", true, true},
+ } {
+ t.Run(mode.name, func(t *testing.T) {
+ id := createRESTAgent(t, uniqueName(mode.name), echoAgentDSL())
+ sessionID := createRESTAgentSession(t, id, mode.name)
+ query := uniqueName("echo")
+ body := apiObject{"agent_id": id, "session_id": sessionID, "stream": mode.stream}
+ if mode.openAI {
+ body["openai-compatible"] = true
+ body["model"] = "agent"
+ body["messages"] = []any{apiObject{"role": "user", "content": query}}
+ } else {
+ body["query"] = query
+ body["return_trace"] = true
+ }
+ result := restCall(t, TestConfig, http.MethodPost, "/agents/chat/completions", body, nil)
+ if mode.stream {
+ assertRESTAgentStream(t, result, sessionID, query, mode.openAI)
+ } else if mode.openAI {
+ if result.Status != http.StatusOK || result.JSON["object"] != "chat.completion" || result.JSON["id"] != sessionID {
+ t.Fatalf("invalid OpenAI completion: %s", result.Body)
+ }
+ choices := array(t, result.JSON["choices"])
+ if len(choices) != 1 {
+ t.Fatalf("choices = %v, want one", choices)
+ }
+ choice := object(t, choices[0])
+ message := object(t, choice["message"])
+ if choice["finish_reason"] != "stop" || message["role"] != "assistant" || message["content"] != query {
+ t.Fatalf("invalid OpenAI answer: %v", choice)
+ }
+ assertRESTAgentUsage(t, result.JSON["usage"])
+ } else {
+ data := object(t, restOK(t, result)["data"])
+ if data["session_id"] != sessionID || object(t, data["data"])["content"] != query {
+ t.Fatalf("invalid native answer: %v", data)
+ }
+ if data["event"] != "message_end" {
+ t.Fatalf("native final event = %v, want message_end", data["event"])
+ }
+ }
+ persisted := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/agents/"+id+"/sessions/"+sessionID, nil, nil))["data"])
+ messages := array(t, persisted["message"])
+ if len(messages) < 2 {
+ t.Fatalf("completion did not persist conversation: %v", messages)
+ }
+ last := object(t, messages[len(messages)-1])
+ if last["role"] != "assistant" || last["content"] != query {
+ t.Fatalf("persisted assistant output = %v, want %s", last, query)
+ }
+ })
+ }
+}
+
+func assertRESTAgentUsage(t *testing.T, value any) {
+ t.Helper()
+ usage := object(t, value)
+ prompt, pOK := usage["prompt_tokens"].(float64)
+ completion, cOK := usage["completion_tokens"].(float64)
+ total, tOK := usage["total_tokens"].(float64)
+ if !pOK || !cOK || !tOK || prompt <= 0 || completion <= 0 || total != prompt+completion {
+ t.Fatalf("invalid token usage: %v", usage)
+ }
+}
+
+func assertRESTAgentStream(t *testing.T, result restResult, sessionID, query string, openAI bool) {
+ t.Helper()
+ if result.Status != http.StatusOK || !strings.Contains(result.Header.Get("Content-Type"), "text/event-stream") {
+ t.Fatalf("expected SSE response, status=%d content-type=%s body=%s", result.Status, result.Header.Get("Content-Type"), result.Body)
+ }
+ events, err := parseSSE(bytes.NewReader(result.Body))
+ if err != nil {
+ t.Fatalf("parse SSE: %v", err)
+ }
+ if len(events) < 2 || events[len(events)-1].Data != "[DONE]" {
+ t.Fatalf("stream lacks final [DONE]: %v", events)
+ }
+ var output strings.Builder
+ finished, messageEnd := false, false
+ for i, event := range events[:len(events)-1] {
+ if event.Data == "[DONE]" {
+ t.Fatalf("premature [DONE] at frame %d", i)
+ }
+ var payload apiObject
+ if err := json.Unmarshal([]byte(event.Data), &payload); err != nil {
+ t.Fatalf("invalid JSON at SSE frame %d: %v", i, err)
+ }
+ if code, ok := payload["code"].(float64); ok && code != 0 {
+ t.Fatalf("SSE application error at frame %d: %v", i, payload)
+ }
+ if openAI {
+ if payload["object"] != "chat.completion.chunk" || payload["id"] != sessionID {
+ t.Fatalf("invalid OpenAI frame %d: %v", i, payload)
+ }
+ choices := array(t, payload["choices"])
+ if len(choices) != 1 {
+ t.Fatalf("invalid choices in frame %d: %v", i, payload)
+ }
+ choice := object(t, choices[0])
+ delta := object(t, choice["delta"])
+ if value, ok := delta["content"].(string); ok {
+ output.WriteString(value)
+ }
+ if choice["finish_reason"] == "stop" {
+ if i != len(events)-2 {
+ t.Fatalf("stop chunk is not final JSON frame: %d", i)
+ }
+ assertRESTAgentUsage(t, payload["usage"])
+ finished = true
+ }
+ } else {
+ if payload["session_id"] != sessionID {
+ t.Fatalf("frame %d lost session identity: %v", i, payload)
+ }
+ kind, ok := payload["event"].(string)
+ if !ok || kind == "" {
+ t.Fatalf("frame %d has no event type: %v", i, payload)
+ }
+ data := object(t, payload["data"])
+ if kind == "message" {
+ if value, ok := data["content"].(string); ok {
+ output.WriteString(value)
+ }
+ }
+ if kind == "message_end" {
+ messageEnd = true
+ }
+ if kind == "workflow_finished" {
+ finished = true
+ }
+ }
+ }
+ if !finished || (!openAI && !messageEnd) || output.String() != query {
+ t.Fatalf("incomplete stream: finished=%v message_end=%v content=%q want=%q", finished, messageEnd, output.String(), query)
+ }
+}
+
+func TestRESTAgentSupport(t *testing.T) {
+ id := createRESTAgent(t, uniqueName("support"), echoAgentDSL())
+ for _, tc := range []struct {
+ name string
+ path string
+ }{
+ {"prompts", "/agents/prompts"},
+ {"templates", "/agents/templates"},
+ {"versions", "/agents/" + id + "/versions"},
+ {"missing_logs", "/agents/" + id + "/logs/" + uniqueName("missing_message")},
+ {"webhook_empty", "/agents/" + id + "/webhook/logs"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ query := apiObject(nil)
+ if tc.name == "webhook_empty" {
+ query = apiObject{"since_ts": 0}
+ }
+ envelope := restOK(t, restCall(t, TestConfig, http.MethodGet, tc.path, nil, query))
+ switch tc.name {
+ case "prompts":
+ data := object(t, envelope["data"])
+ for _, key := range []string{"task_analysis", "output_format", "citation_guidelines", "few_shots_examples"} {
+ if value, ok := data[key].(string); !ok || value == "" {
+ t.Fatalf("prompt %s must be nonempty: %v", key, data)
+ }
+ }
+ case "templates", "versions":
+ array(t, envelope["data"])
+ case "missing_logs":
+ if len(object(t, envelope["data"])) != 0 {
+ t.Fatalf("missing message must return an empty object: %v", envelope)
+ }
+ case "webhook_empty":
+ data := object(t, envelope["data"])
+ if len(array(t, data["events"])) != 0 || data["finished"] != false {
+ t.Fatalf("fresh agent has webhook events: %v", data)
+ }
+ if _, ok := data["next_since_ts"].(float64); !ok {
+ t.Fatalf("missing numeric poll cursor: %v", data)
+ }
+ }
+ })
+ }
+ for _, suffix := range []string{"/versions", "/logs/missing"} {
+ t.Run("missing_agent"+suffix, func(t *testing.T) {
+ restCode(t, restCall(t, TestConfig, http.MethodGet, "/agents/"+uniqueName("missing")+suffix, nil, nil), http.StatusOK, 103)
+ })
+ }
+ restCode(t, restCall(t, TestConfig, http.MethodGet, "/agents/"+uniqueName("missing")+"/webhook/logs", nil, nil), http.StatusOK, 102)
+ for _, body := range []apiObject{{}, {"db_type": "mysql"}, {"db_type": "mysql", "host": "localhost", "port": 3306}} {
+ result := restCall(t, TestConfig, http.MethodPost, "/agents/test_db_connection", body, nil)
+ restCode(t, result, http.StatusOK, 101)
+ if message, _ := result.JSON["message"].(string); !strings.Contains(message, "required argument are missing") {
+ t.Fatalf("missing DB fields did not produce validation error: %v", result.JSON)
+ }
+ }
+}
+
+func TestRESTAgentAuthorization(t *testing.T) {
+ id := createRESTAgent(t, uniqueName("auth"), echoAgentDSL())
+ sessionID := createRESTAgentSession(t, id, "private_session")
+ anonymous := *TestConfig
+ anonymous.APIKey = ""
+ for _, tc := range []struct {
+ method string
+ path string
+ body apiObject
+ }{
+ {http.MethodGet, "/agents", nil},
+ {http.MethodPost, "/agents", apiObject{"title": uniqueName("denied"), "dsl": echoAgentDSL()}},
+ {http.MethodGet, "/agents/" + id, nil},
+ {http.MethodPut, "/agents/" + id, apiObject{"title": "denied"}},
+ {http.MethodDelete, "/agents/" + id, nil},
+ {http.MethodGet, "/agents/prompts", nil},
+ {http.MethodGet, "/agents/templates", nil},
+ {http.MethodGet, "/agents/" + id + "/versions", nil},
+ {http.MethodGet, "/agents/" + id + "/sessions", nil},
+ {http.MethodPost, "/agents/" + id + "/sessions", apiObject{"name": "denied"}},
+ {http.MethodGet, "/agents/" + id + "/sessions/" + sessionID, nil},
+ {http.MethodDelete, "/agents/" + id + "/sessions/" + sessionID, nil},
+ {http.MethodGet, "/agents/" + id + "/logs/missing", nil},
+ {http.MethodGet, "/agents/" + id + "/webhook/logs", nil},
+ {http.MethodPost, "/agents/test_db_connection", apiObject{}},
+ {http.MethodPost, "/agents/chat/completions", apiObject{"agent_id": id, "query": "denied"}},
+ } {
+ t.Run(tc.method+"_"+tc.path, func(t *testing.T) {
+ restCode(t, restCall(t, &anonymous, tc.method, tc.path, tc.body, nil), http.StatusUnauthorized, 401)
+ })
+ }
+ if got := getRESTAgent(t, id)["title"]; got == "denied" {
+ t.Fatal("unauthenticated update persisted")
+ }
+ t.Run("foreign_owner", func(t *testing.T) {
+ token := os.Getenv("RAGFLOW_TEST_OTHER_API_KEY")
+ if token == "" {
+ t.Skip("set RAGFLOW_TEST_OTHER_API_KEY for an unrelated user to test ownership")
+ }
+ other := *TestConfig
+ other.APIKey = token
+ for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete} {
+ restCode(t, restCall(t, &other, method, "/agents/"+id, apiObject{"title": "denied"}, nil), http.StatusOK, 103)
+ }
+ for _, method := range []string{http.MethodGet, http.MethodDelete} {
+ restCode(t, restCall(t, &other, method, "/agents/"+id+"/sessions/"+sessionID, nil, nil), http.StatusOK, 103)
+ }
+ restCode(t, restCall(t, &other, http.MethodPost, "/agents/"+id+"/sessions", apiObject{"name": "denied"}, nil), http.StatusOK, 103)
+ restCode(t, restCall(t, &other, http.MethodPost, "/agents/chat/completions", apiObject{"agent_id": id, "query": "denied"}, nil), http.StatusOK, 103)
+ restOK(t, restCall(t, TestConfig, http.MethodGet, "/agents/"+id+"/sessions/"+sessionID, nil, nil))
+ })
+}
+
+func TestRESTAgentV2DSLRoundTrip(t *testing.T) {
+ dsl := echoAgentDSL()
+ dsl["components"] = apiObject{
+ "begin": apiObject{
+ "obj": apiObject{"component_name": "Begin", "params": apiObject{}},
+ "downstream": []any{"answer:0"}, "upstream": []any{},
+ },
+ "answer:0": apiObject{
+ "obj": apiObject{"component_name": "Answer", "params": apiObject{}},
+ "downstream": []any{}, "upstream": []any{"begin"},
+ },
+ }
+ dsl["variables"] = []any{}
+ dsl["graph"] = apiObject{
+ "nodes": []any{
+ apiObject{"id": "begin", "type": "beginNode", "position": apiObject{"x": 50, "y": 200}, "data": apiObject{"label": "Begin", "name": "begin"}},
+ apiObject{"id": "answer:0", "type": "messageNode", "position": apiObject{"x": 400, "y": 200}, "data": apiObject{"label": "Answer", "name": "answer"}},
+ },
+ "edges": []any{apiObject{"id": "xy-edge__begin-answer:0", "source": "begin", "target": "answer:0", "sourceHandle": "end", "targetHandle": "start"}},
+ }
+ id := createRESTAgent(t, uniqueName("v2_dsl"), dsl)
+ assertGraph := func(t *testing.T, want apiObject) {
+ t.Helper()
+ got := object(t, getRESTAgent(t, id)["dsl"])
+ if _, exists := got["_layout"]; exists {
+ t.Fatalf("v2 DSL exposed obsolete _layout: %v", got)
+ }
+ // JSON-normalize expectations so integer coordinates compare with decoded numbers.
+ raw, err := json.Marshal(want)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var normalized apiObject
+ if err := json.Unmarshal(raw, &normalized); err != nil {
+ t.Fatal(err)
+ }
+ // NormalizeForCanvas intentionally repairs the Python fixture's inverted handles.
+ edge := object(t, array(t, object(t, normalized["graph"])["edges"])[0])
+ edge["sourceHandle"], edge["targetHandle"] = "start", "end"
+ for _, key := range []string{"graph", "components"} {
+ if !reflect.DeepEqual(got[key], normalized[key]) {
+ t.Fatalf("%s changed during v2 DSL round trip: got=%v want=%v", key, got[key], normalized[key])
+ }
+ }
+ }
+ assertGraph(t, dsl)
+ graph := object(t, dsl["graph"])
+ nodes := array(t, graph["nodes"])
+ object(t, nodes[0])["position"] = apiObject{"x": 777, "y": 888}
+ restOK(t, restCall(t, TestConfig, http.MethodPut, "/agents/"+id, apiObject{"dsl": dsl}, nil))
+ assertGraph(t, dsl)
+}
diff --git a/test/api/chat_api_test.go b/test/api/chat_api_test.go
new file mode 100644
index 0000000000..1e6ae1a903
--- /dev/null
+++ b/test/api/chat_api_test.go
@@ -0,0 +1,642 @@
+//go:build integration
+
+package api
+
+import (
+ "fmt"
+ "maps"
+ "math"
+ "net/http"
+ "os"
+ "reflect"
+ "slices"
+ "strings"
+ "testing"
+)
+
+func createRESTChat(t *testing.T, extra apiObject) apiObject {
+ t.Helper()
+ body := apiObject{"name": uniqueName("go_chat"), "dataset_ids": []string{}}
+ maps.Copy(body, extra)
+ response := restCall(t, TestConfig, http.MethodPost, "/chats", body, nil)
+ // Register cleanup before asserting the response contract.
+ if data, ok := response.JSON["data"].(map[string]any); ok {
+ if id, ok := data["id"].(string); ok && id != "" {
+ cleanupResource(t, TestConfig, "chats", id)
+ }
+ }
+ return object(t, restOK(t, response)["data"])
+}
+
+func getRESTChat(t *testing.T, id string) apiObject {
+ t.Helper()
+ return object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats/"+id, nil, nil))["data"])
+}
+
+func chatID(t *testing.T, chat apiObject) string {
+ t.Helper()
+ id, ok := chat["id"].(string)
+ if !ok || id == "" {
+ t.Fatal("chat response lacks a nonempty string id")
+ }
+ return id
+}
+
+func assertChatValue(t *testing.T, actual, expected any) {
+ t.Helper()
+ if !reflect.DeepEqual(actual, expected) {
+ t.Fatalf("value=%#v want=%#v", actual, expected)
+ }
+}
+
+func chatConfiguration(chat apiObject) apiObject {
+ result := maps.Clone(chat)
+ for _, key := range []string{"create_time", "create_date", "update_time", "update_date"} {
+ delete(result, key)
+ }
+ return result
+}
+
+func TestRESTChatAuthorization(t *testing.T) {
+ chat := createRESTChat(t, nil)
+ id := chatID(t, chat)
+ for _, token := range []string{"", "invalid-api-key"} {
+ config := *TestConfig
+ config.APIKey = token
+ for _, tc := range []struct {
+ method, path string
+ body any
+ }{
+ {http.MethodPost, "/chats", apiObject{"name": uniqueName("unauth")}},
+ {http.MethodGet, "/chats", nil},
+ {http.MethodGet, "/chats/" + id, nil},
+ {http.MethodPut, "/chats/" + id, apiObject{"name": "unauthorized"}},
+ {http.MethodPatch, "/chats/" + id, apiObject{"name": "unauthorized"}},
+ {http.MethodDelete, "/chats", apiObject{"ids": []string{id}}},
+ {http.MethodDelete, "/chats/" + id, nil},
+ } {
+ t.Run(fmt.Sprintf("%s/%s/%t", tc.method, tc.path, token == ""), func(t *testing.T) {
+ result := restCall(t, &config, tc.method, tc.path, tc.body, nil)
+ if result.Status != http.StatusUnauthorized {
+ t.Fatalf("HTTP=%d want=401", result.Status)
+ }
+ if result.JSON["code"] == nil || result.JSON["message"] == nil {
+ t.Fatal("authorization error lacks code or message")
+ }
+ })
+ }
+ }
+ if getRESTChat(t, id)["name"] != chat["name"] {
+ t.Fatal("unauthorized mutation changed chat")
+ }
+}
+
+func TestRESTChatCRUD(t *testing.T) {
+ chat := createRESTChat(t, nil)
+ id := chatID(t, chat)
+ other := createRESTChat(t, nil)
+ for _, query := range []apiObject{
+ {"id": id},
+ {"id": id, "keywords": other["name"]},
+ {"name": chat["name"], "keywords": other["name"]},
+ } {
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, query))["data"])
+ chats := array(t, data["chats"])
+ if len(chats) != 1 || object(t, chats[0])["id"] != id || data["total"] != float64(1) {
+ t.Fatalf("exact filter returned wrong chat or total: %v", data)
+ }
+ }
+ assertChatValue(t, getRESTChat(t, id)["name"], chat["name"])
+ for _, method := range []string{http.MethodPut, http.MethodPatch} {
+ name := uniqueName("changed")
+ result := object(t, restOK(t, restCall(t, TestConfig, method, "/chats/"+id, apiObject{"name": " " + name + " "}, nil))["data"])
+ assertChatValue(t, result["name"], name)
+ persisted := getRESTChat(t, id)
+ assertChatValue(t, persisted["name"], name)
+ assertChatValue(t, persisted["dataset_ids"], []any{})
+ }
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodDelete, "/chats", apiObject{"ids": []string{id}}, nil))["data"])
+ assertChatValue(t, data["success_count"], float64(1))
+ restCode(t, restCall(t, TestConfig, http.MethodGet, "/chats/"+id, nil, nil), 200, 404)
+ list := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"id": id}))["data"])
+ assertChatValue(t, list["chats"], []any{})
+ // Deletion must target only the requested chat.
+ assertChatValue(t, getRESTChat(t, chatID(t, other))["name"], other["name"])
+}
+
+func TestRESTChatNameValidation(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ value any
+ }{
+ {"missing", nil}, {"empty", ""}, {"whitespace", " \t\n"}, {"number", 1},
+ {"ascii_overflow", strings.Repeat("a", 256)}, {"utf8_overflow", strings.Repeat("界", 86)},
+ } {
+ t.Run("create/"+tc.name, func(t *testing.T) {
+ restCode(t, restCall(t, TestConfig, http.MethodPost, "/chats", apiObject{"name": tc.value, "dataset_ids": []string{}}, nil), 200, 102)
+ })
+ }
+ asciiPrefix := uniqueName("boundary_ascii")
+ boundaryNames := []string{asciiPrefix + strings.Repeat("a", 255-len(asciiPrefix))}
+ utf8Prefix := uniqueName("boundary_utf8")
+ utf8Padding := 255 - len(utf8Prefix)
+ boundaryNames = append(boundaryNames, utf8Prefix+strings.Repeat("界", utf8Padding/len("界"))+strings.Repeat("a", utf8Padding%len("界")))
+ for _, name := range boundaryNames {
+ t.Run(fmt.Sprintf("boundary/%d_bytes", len(name)), func(t *testing.T) {
+ chat := createRESTChat(t, apiObject{"name": name})
+ assertChatValue(t, chat["name"], name)
+ assertChatValue(t, getRESTChat(t, chatID(t, chat))["name"], name)
+ })
+ }
+ name := uniqueName("duplicate")
+ first := createRESTChat(t, apiObject{"name": name})
+ second := createRESTChat(t, apiObject{"name": name})
+ assertChatValue(t, second["name"], name+"(1)")
+ if first["id"] == second["id"] {
+ t.Fatal("duplicate create reused an id")
+ }
+ target := createRESTChat(t, nil)
+ id := chatID(t, target)
+ for _, method := range []string{http.MethodPut, http.MethodPatch} {
+ for _, value := range []any{"", " ", 1, strings.Repeat("a", 256), name, strings.ToUpper(name)} {
+ t.Run(fmt.Sprintf("%s/%v", method, value), func(t *testing.T) {
+ before := chatConfiguration(getRESTChat(t, id))
+ restCode(t, restCall(t, TestConfig, method, "/chats/"+id, apiObject{"name": value}, nil), 200, 102)
+ assertChatValue(t, chatConfiguration(getRESTChat(t, id)), before)
+ })
+ }
+ }
+}
+
+func TestRESTChatListing(t *testing.T) {
+ prefix := uniqueName("listing")
+ var ids []string
+ for index := range 5 {
+ chat := createRESTChat(t, apiObject{"name": fmt.Sprintf("%s_%d", prefix, index)})
+ ids = append(ids, chatID(t, chat))
+ }
+ list := func(t *testing.T, query apiObject) apiObject {
+ t.Helper()
+ params := apiObject{"keywords": prefix}
+ maps.Copy(params, query)
+ return object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, params))["data"])
+ }
+ for _, tc := range []struct {
+ name string
+ query apiObject
+ count int
+ }{
+ {"default", nil, 5}, {"unknown_param", apiObject{"a": "b"}, 5},
+ {"page_two", apiObject{"page": 2, "page_size": 2}, 2},
+ {"page_three", apiObject{"page": "3", "page_size": 2}, 1},
+ {"beyond_end", apiObject{"page": 99, "page_size": 2}, 0},
+ {"page_zero", apiObject{"page": 0, "page_size": 2}, 5},
+ {"page_negative", apiObject{"page": -1, "page_size": 2}, 5},
+ {"page_alpha", apiObject{"page": "a", "page_size": 2}, 5},
+ {"size_without_page", apiObject{"page_size": 1}, 5},
+ {"size_string_without_page", apiObject{"page_size": "1"}, 5},
+ {"size_six_without_page", apiObject{"page_size": 6}, 5},
+ {"size_zero", apiObject{"page": 1, "page_size": 0}, 5},
+ {"size_negative", apiObject{"page": 1, "page_size": -1}, 5},
+ {"size_alpha", apiObject{"page": 1, "page_size": "a"}, 5},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ data := list(t, tc.query)
+ if len(array(t, data["chats"])) != tc.count || data["total"] != float64(5) {
+ t.Fatalf("pagination count/total=%v want count=%d total=5", data, tc.count)
+ }
+ })
+ }
+ for _, desc := range []any{"false", "False", false, "true", "True", true, "unknown"} {
+ t.Run(fmt.Sprintf("name_order/%v", desc), func(t *testing.T) {
+ chats := array(t, list(t, apiObject{"orderby": "name", "desc": desc})["chats"])
+ wantIDs := slices.Clone(ids)
+ if !strings.EqualFold(fmt.Sprint(desc), "false") {
+ slices.Reverse(wantIDs)
+ }
+ for index, chat := range chats {
+ assertChatValue(t, object(t, chat)["id"], wantIDs[index])
+ }
+ })
+ }
+ for _, order := range []string{"create_time", "update_time"} {
+ t.Run(order, func(t *testing.T) {
+ chats := array(t, list(t, apiObject{"orderby": order})["chats"])
+ for index := 1; index < len(chats); index++ {
+ if object(t, chats[index-1])[order].(float64) < object(t, chats[index])[order].(float64) {
+ t.Fatalf("%s is not descending", order)
+ }
+ }
+ })
+ }
+ // Check page membership, not just length.
+ first := array(t, list(t, apiObject{"orderby": "name", "desc": false, "page": 1, "page_size": 2})["chats"])
+ second := array(t, list(t, apiObject{"orderby": "name", "desc": false, "page": 2, "page_size": 2})["chats"])
+ assertChatValue(t, object(t, first[0])["id"], ids[0])
+ assertChatValue(t, object(t, second[0])["id"], ids[2])
+ restCode(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"orderby": "unknown"}), 200, 101)
+ assertChatValue(t, list(t, apiObject{"keywords": uniqueName("unmatched")})["chats"], []any{})
+ assertChatValue(t, list(t, apiObject{"keywords": prefix + "_1"})["total"], float64(1))
+ // Empty and omitted keywords are equivalent; no assumption about unrelated tenant resources.
+ all := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, nil))["data"])
+ empty := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"keywords": ""}))["data"])
+ assertChatValue(t, empty["total"], all["total"])
+}
+
+func TestRESTChatDeletion(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ duplicates bool
+ missing string
+ }{
+ {"valid", false, ""}, {"duplicate_one", true, ""}, {"partial_invalid", false, "invalid_id"},
+ {"partial_punctuation", false, "!@#$%^&*()"}, {"duplicates_and_missing", true, "missing"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ id := chatID(t, createRESTChat(t, nil))
+ ids := []string{id}
+ if tc.duplicates {
+ ids = append(ids, id)
+ }
+ if tc.missing != "" {
+ ids = append(ids, tc.missing)
+ }
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodDelete, "/chats", apiObject{"ids": ids}, nil))["data"])
+ assertChatValue(t, data["success_count"], float64(1))
+ wantErrors := 0
+ if tc.duplicates {
+ wantErrors++
+ }
+ if tc.missing != "" {
+ wantErrors++
+ }
+ if wantErrors > 0 {
+ errors := array(t, data["errors"])
+ if len(errors) != wantErrors {
+ t.Fatalf("errors=%v want count=%d", errors, wantErrors)
+ }
+ if tc.duplicates && !slices.Contains(errors, any("Duplicate chat ids: "+id)) {
+ t.Fatal("missing duplicate-id diagnostic")
+ }
+ if tc.missing != "" && !slices.Contains(errors, any("Chat("+tc.missing+") not found.")) {
+ t.Fatal("missing unknown-id diagnostic")
+ }
+ }
+ restCode(t, restCall(t, TestConfig, http.MethodDelete, "/chats", apiObject{"ids": []string{id}}, nil), 200, 102)
+ restCode(t, restCall(t, TestConfig, http.MethodGet, "/chats/"+id, nil, nil), 200, 404)
+ })
+ }
+ for _, ids := range [][]string{{}, {"missing-1", "missing-2"}} {
+ result := restCall(t, TestConfig, http.MethodDelete, "/chats", apiObject{"ids": ids}, nil)
+ if len(ids) == 0 {
+ restOK(t, result)
+ } else {
+ restCode(t, result, 200, 102)
+ for _, id := range ids {
+ if !strings.Contains(fmt.Sprint(result.JSON["message"]), "Chat("+id+") not found.") {
+ t.Fatalf("missing individual deletion error for %q", id)
+ }
+ }
+ }
+ }
+ var ids []string
+ for range 100 {
+ ids = append(ids, chatID(t, createRESTChat(t, nil)))
+ }
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodDelete, "/chats", apiObject{"ids": ids}, nil))["data"])
+ assertChatValue(t, data["success_count"], float64(100))
+ for _, id := range ids {
+ result := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"id": id}))["data"])
+ assertChatValue(t, result["chats"], []any{})
+ }
+}
+
+func TestRESTChatConcurrentRequests(t *testing.T) {
+ prefix := uniqueName("concurrent")
+ var ids []string
+ for index := range 20 {
+ ids = append(ids, chatID(t, createRESTChat(t, apiObject{"name": fmt.Sprintf("%s_%02d", prefix, index)})))
+ }
+ // Independent reads and distinct resource deletions; shared configuration is immutable.
+ t.Run("reads", func(t *testing.T) {
+ for index := range 10 {
+ t.Run(fmt.Sprint(index), func(t *testing.T) {
+ t.Parallel()
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"keywords": prefix}))["data"])
+ if len(array(t, data["chats"])) != len(ids) {
+ t.Fatal("concurrent list did not return all isolated chats")
+ }
+ })
+ }
+ })
+ t.Run("deletes", func(t *testing.T) {
+ for _, id := range ids {
+ t.Run(id, func(t *testing.T) {
+ t.Parallel()
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodDelete, "/chats", apiObject{"ids": []string{id}}, nil))["data"])
+ assertChatValue(t, data["success_count"], float64(1))
+ })
+ }
+ })
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"keywords": prefix}))["data"])
+ assertChatValue(t, data["chats"], []any{})
+}
+
+func TestRESTChatConfigurationMatrices(t *testing.T) {
+ type scenario struct {
+ name, field string
+ value, want any
+ reject bool
+ }
+ var scenarios []scenario
+ for _, field := range []string{"temperature", "top_p", "presence_penalty", "frequency_penalty", "max_token"} {
+ values := []any{0, 1, -1, 10, "a"}
+ if field == "max_token" {
+ values[1] = 1024
+ }
+ for _, value := range values {
+ scenarios = append(scenarios, scenario{"llm/" + field + "/" + fmt.Sprint(value), "llm_setting", apiObject{field: value}, apiObject{field: normalizeChatNumber(value)}, false})
+ }
+ }
+ scenarios = append(scenarios, scenario{"llm/unknown_key", "llm_setting", apiObject{"unknown": "unknown"}, apiObject{"unknown": "unknown"}, false})
+ for _, field := range []string{"similarity_threshold", "top_n"} {
+ for _, value := range []any{0, 1, -1, 10, "a"} {
+ want := normalizeChatNumber(value)
+ if value == "a" {
+ want = float64(0)
+ }
+ scenarios = append(scenarios, scenario{field + "/" + fmt.Sprint(value), field, value, want, false})
+ }
+ }
+ for _, value := range []any{0, 1, 2, -9, -1, 10, "a"} {
+ valid := value == 0 || value == 1
+ scenarios = append(scenarios, scenario{"vector_similarity_weight/" + fmt.Sprint(value), "vector_similarity_weight", value, normalizeChatNumber(value), !valid})
+ }
+ for _, field := range []string{"empty_response", "prologue", "system"} {
+ values := []any{"Hello World", "", "!@#$%^&*()", "中文测试", 123, true, " "}
+ if field == "system" {
+ values = []any{"Hello World {knowledge}", "{knowledge}", "!@#$%^&*() {knowledge}", "中文测试 {knowledge}", "Hello World", 123, true}
+ }
+ for _, value := range values {
+ scenarios = append(scenarios, scenario{"prompt/" + field + "/" + fmt.Sprint(value), "prompt_config", apiObject{field: value}, apiObject{field: normalizeChatNumber(value)}, false})
+ }
+ }
+ for _, value := range []bool{true, false} {
+ scenarios = append(scenarios, scenario{"prompt/quote/" + fmt.Sprint(value), "prompt_config", apiObject{"quote": value}, apiObject{"quote": value}, false})
+ }
+ scenarios = append(scenarios,
+ scenario{"prompt/empty_parameters", "prompt_config", apiObject{"parameters": []any{}}, apiObject{"parameters": []any{}}, false},
+ scenario{"prompt/system_empty_parameters", "prompt_config", apiObject{"system": "Hello World", "parameters": []any{}}, apiObject{"system": "Hello World", "parameters": []any{}}, false},
+ scenario{"prompt/unknown_key", "prompt_config", apiObject{"unknown": "unknown"}, apiObject{"unknown": "unknown"}, false},
+ scenario{"icon", "icon", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=", "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=", false},
+ scenario{"icon/raw", "icon", "raw-avatar-value", "raw-avatar-value", false},
+ )
+ for _, mode := range []string{"create", http.MethodPut, http.MethodPatch} {
+ t.Run(mode, func(t *testing.T) {
+ for _, tc := range scenarios {
+ t.Run(tc.name, func(t *testing.T) {
+ body := apiObject{tc.field: tc.value}
+ var persisted apiObject
+ if mode == "create" {
+ body["name"] = uniqueName("matrix")
+ body["dataset_ids"] = []any{}
+ if tc.reject {
+ restCode(t, restCall(t, TestConfig, http.MethodPost, "/chats", body, nil), 200, 102)
+ return
+ }
+ persisted = createRESTChat(t, body)
+ persisted = getRESTChat(t, chatID(t, persisted))
+ } else {
+ chat := createRESTChat(t, nil)
+ id := chatID(t, chat)
+ before := chatConfiguration(getRESTChat(t, id))
+ result := restCall(t, TestConfig, mode, "/chats/"+id, body, nil)
+ // Creation converts invalid numeric strings to zero; updates
+ // forward them to typed SQL columns and reject them.
+ reject := tc.reject || (tc.value == "a" && (tc.field == "top_n" || tc.field == "similarity_threshold"))
+ if reject {
+ restCode(t, result, 200, 102)
+ assertChatValue(t, chatConfiguration(getRESTChat(t, id)), before)
+ return
+ }
+ restOK(t, result)
+ persisted = getRESTChat(t, id)
+ }
+ if tc.field == "vector_similarity_weight" {
+ if math.Abs(persisted["keywords_similarity_weight"].(float64)-(1-tc.want.(float64))) > 1e-9 {
+ t.Fatal("public keyword weight does not complement supplied vector weight")
+ }
+ if _, exists := persisted["vector_similarity_weight"]; exists {
+ t.Fatal("internal vector weight leaked in public response")
+ }
+ } else if expected, ok := tc.want.(map[string]any); ok && tc.field == "prompt_config" {
+ actual := object(t, persisted[tc.field])
+ for key, value := range expected {
+ assertChatValue(t, actual[key], value)
+ }
+ } else {
+ assertChatValue(t, persisted[tc.field], tc.want)
+ }
+ })
+ }
+ })
+ }
+}
+
+func normalizeChatNumber(value any) any {
+ if integer, ok := value.(int); ok {
+ return float64(integer)
+ }
+ return value
+}
+
+func TestRESTChatDefaultsAndUpdateSemantics(t *testing.T) {
+ chat := createRESTChat(t, nil)
+ id := chatID(t, chat)
+ persisted := getRESTChat(t, id)
+ for key, want := range (apiObject{"similarity_threshold": 0.1, "keywords_similarity_weight": 0.7, "top_n": float64(6), "rerank_id": ""}) {
+ assertChatValue(t, persisted[key], want)
+ }
+ prompt := object(t, persisted["prompt_config"])
+ for key, want := range (apiObject{
+ "system": "", "prologue": "Hi! I'm your assistant. What can I do for you?", "quote": true,
+ "empty_response": "Sorry! No relevant content was found in the knowledge base!",
+ "parameters": []any{apiObject{"key": "knowledge", "optional": false}},
+ }) {
+ assertChatValue(t, prompt[key], want)
+ }
+ // llm_id is a composite model name; tenant_llm_id is the configured row ID.
+ // Their representations differ and neither is fixed to the CI provider.
+ assertChatValue(t, persisted["llm_id"], chat["llm_id"])
+ restOK(t, restCall(t, TestConfig, http.MethodPatch, "/chats/"+id, apiObject{"prompt_config": apiObject{"quote": false}, "llm_setting": apiObject{"temperature": 0.2}}, nil))
+ restOK(t, restCall(t, TestConfig, http.MethodPatch, "/chats/"+id, apiObject{"prompt_config": apiObject{"prologue": "updated"}, "llm_setting": apiObject{"top_p": 0.4}}, nil))
+ persisted = getRESTChat(t, id)
+ assertChatValue(t, object(t, persisted["prompt_config"])["quote"], false)
+ assertChatValue(t, object(t, persisted["prompt_config"])["prologue"], "updated")
+ assertChatValue(t, persisted["llm_setting"], apiObject{"temperature": 0.2, "top_p": 0.4})
+ restOK(t, restCall(t, TestConfig, http.MethodPut, "/chats/"+id, apiObject{"prompt_config": apiObject{"system": "replacement"}, "llm_setting": apiObject{"temperature": 0.6}}, nil))
+ persisted = getRESTChat(t, id)
+ prompt = object(t, persisted["prompt_config"])
+ assertChatValue(t, prompt["system"], "replacement")
+ if _, exists := prompt["quote"]; exists {
+ t.Fatal("PUT merged the previous prompt instead of replacing it")
+ }
+ assertChatValue(t, persisted["llm_setting"], apiObject{"temperature": 0.6})
+ // Unknown top-level fields are ignored; unrelated persisted configuration survives.
+ before := chatConfiguration(persisted)
+ restOK(t, restCall(t, TestConfig, http.MethodPatch, "/chats/"+id, apiObject{"unknown": "unknown"}, nil))
+ assertChatValue(t, chatConfiguration(getRESTChat(t, id)), before)
+ restOK(t, restCall(t, TestConfig, http.MethodPatch, "/chats/"+id, apiObject{"prompt_config": apiObject{"system": "No required placeholder", "parameters": []any{apiObject{"key": "knowledge", "optional": false}}}}, nil))
+ prompt = object(t, getRESTChat(t, id)["prompt_config"])
+ assertChatValue(t, prompt["system"], "No required placeholder")
+ assertChatValue(t, prompt["parameters"], []any{apiObject{"key": "knowledge", "optional": false}})
+ t.Run("explicit_configured_model", func(t *testing.T) {
+ model, ok := chat["llm_id"].(string)
+ if !ok || model == "" {
+ t.Skip("tenant has no default chat model to exercise explicit configured model resolution")
+ }
+ created := createRESTChat(t, apiObject{"llm_id": model})
+ assertChatValue(t, getRESTChat(t, chatID(t, created))["llm_id"], model)
+ for _, method := range []string{http.MethodPut, http.MethodPatch} {
+ restOK(t, restCall(t, TestConfig, method, "/chats/"+id, apiObject{"llm_id": model}, nil))
+ assertChatValue(t, getRESTChat(t, id)["llm_id"], model)
+ }
+ })
+}
+
+func TestRESTChatRejectedMutations(t *testing.T) {
+ chat := createRESTChat(t, nil)
+ id := chatID(t, chat)
+ duplicateParameters := apiObject{"parameters": []any{apiObject{"key": "knowledge"}, apiObject{"key": "knowledge"}}}
+ for _, tc := range []struct {
+ name string
+ body apiObject
+ }{
+ {"unknown_llm", apiObject{"llm_id": uniqueName("missing_model")}},
+ {"unknown_rerank", apiObject{"rerank_id": uniqueName("missing_rerank")}},
+ {"duplicate_parameters", apiObject{"prompt_config": duplicateParameters}},
+ {"invalid_prompt", apiObject{"prompt_config": "invalid"}},
+ {"invalid_dataset_type", apiObject{"dataset_ids": "invalid"}},
+ {"unknown_dataset", apiObject{"dataset_ids": []string{uniqueName("missing_dataset")}}},
+ {"invalid_metadata", apiObject{"meta_data_filter": "invalid"}},
+ {"mismatched_weights", apiObject{"keywords_similarity_weight": 0.7, "vector_similarity_weight": 0.7}},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ createBody := maps.Clone(tc.body)
+ createBody["name"] = uniqueName("rejected")
+ restCode(t, restCall(t, TestConfig, http.MethodPost, "/chats", createBody, nil), 200, 102)
+ for _, method := range []string{http.MethodPut, http.MethodPatch} {
+ before := chatConfiguration(getRESTChat(t, id))
+ result := restCall(t, TestConfig, method, "/chats/"+id, tc.body, nil)
+ // Dataset authorization is normalized to a hidden 404 on update.
+ if tc.name == "unknown_dataset" {
+ restCode(t, result, 200, 404)
+ } else {
+ restCode(t, result, 200, 102)
+ }
+ assertChatValue(t, chatConfiguration(getRESTChat(t, id)), before)
+ }
+ })
+ }
+ for _, method := range []string{http.MethodPost, http.MethodPut} {
+ path := "/chats"
+ body := apiObject{"name": uniqueName("tenant_override"), "tenant_id": "forged"}
+ if method == http.MethodPut {
+ path += "/" + id
+ }
+ restCode(t, restCall(t, TestConfig, method, path, body, nil), 200, 102)
+ }
+ for _, method := range []string{http.MethodPut, http.MethodPatch, http.MethodGet, http.MethodDelete} {
+ restCode(t, restCall(t, TestConfig, method, "/chats/"+uniqueName("missing"), apiObject{"name": "missing"}, nil), 200, 404)
+ }
+}
+
+func TestRESTChatDatasetAssociations(t *testing.T) {
+ dataset := object(t, restOK(t, restCall(t, TestConfig, http.MethodPost, "/datasets", apiObject{"name": uniqueName("chat_dataset"), "parse_type": 1, "parser_id": "naive"}, nil))["data"])
+ id, ok := dataset["id"].(string)
+ if !ok || id == "" {
+ t.Fatal("dataset creation lacks id")
+ }
+ t.Cleanup(func() {
+ restCall(t, TestConfig, http.MethodDelete, "/datasets", apiObject{"ids": []string{id}}, nil)
+ })
+ chat := createRESTChat(t, nil)
+ targetID := chatID(t, chat)
+ for _, method := range []string{http.MethodPost, http.MethodPut, http.MethodPatch} {
+ t.Run(method+"/unparsed", func(t *testing.T) {
+ body := apiObject{"name": uniqueName("unparsed"), "dataset_ids": []string{id}}
+ path := "/chats"
+ if method != http.MethodPost {
+ path += "/" + targetID
+ }
+ before := chatConfiguration(getRESTChat(t, targetID))
+ result := restCall(t, TestConfig, method, path, body, nil)
+ restCode(t, result, 200, 102)
+ if !strings.Contains(fmt.Sprint(result.JSON["message"]), "doesn't own parsed file") {
+ t.Fatal("unparsed dataset rejection has incorrect explanation")
+ }
+ assertChatValue(t, chatConfiguration(getRESTChat(t, targetID)), before)
+ })
+ }
+ t.Run("parsed_dataset", func(t *testing.T) {
+ parsedID := os.Getenv("RAGFLOW_TEST_PARSED_DATASET_ID")
+ if parsedID == "" {
+ t.Skip("requires RAGFLOW_TEST_PARSED_DATASET_ID owned by this account with parsed chunks; ingestion is outside this suite")
+ }
+ created := createRESTChat(t, apiObject{"dataset_ids": []string{parsedID}})
+ createdID := chatID(t, created)
+ assertChatValue(t, getRESTChat(t, createdID)["dataset_ids"], []any{parsedID})
+ system := object(t, getRESTChat(t, createdID)["prompt_config"])["system"]
+ if text, ok := system.(string); !ok || !strings.Contains(text, "{knowledge}") {
+ t.Fatal("dataset-bound chat lacks default knowledge prompt")
+ }
+ for _, method := range []string{http.MethodPut, http.MethodPatch} {
+ for _, value := range []any{[]any{}, []string{parsedID}, nil} {
+ restOK(t, restCall(t, TestConfig, method, "/chats/"+createdID, apiObject{"dataset_ids": value}, nil))
+ want := []any{}
+ if ids, ok := value.([]string); ok {
+ want = []any{ids[0]}
+ }
+ assertChatValue(t, getRESTChat(t, createdID)["dataset_ids"], want)
+ }
+ }
+ })
+ t.Run("list_after_dataset_deletion", func(t *testing.T) {
+ disposableID := os.Getenv("RAGFLOW_TEST_DISPOSABLE_PARSED_DATASET_ID")
+ if disposableID == "" {
+ t.Skip("requires RAGFLOW_TEST_DISPOSABLE_PARSED_DATASET_ID owned by this account; this fixture is explicitly deleted")
+ }
+ cleanupResource(t, TestConfig, "datasets", disposableID)
+ created := createRESTChat(t, apiObject{"dataset_ids": []string{disposableID}})
+ createdID := chatID(t, created)
+ restOK(t, restCall(t, TestConfig, http.MethodDelete, "/datasets", apiObject{"ids": []string{disposableID}}, nil))
+ data := object(t, restOK(t, restCall(t, TestConfig, http.MethodGet, "/chats", nil, apiObject{"id": createdID}))["data"])
+ chats := array(t, data["chats"])
+ if len(chats) != 1 || object(t, chats[0])["id"] != createdID {
+ t.Fatal("deleting associated dataset removed or hid its chat")
+ }
+ assertChatValue(t, getRESTChat(t, createdID)["dataset_ids"], []any{})
+ })
+}
+
+func TestRESTChatOtherAccount(t *testing.T) {
+ key := os.Getenv("RAGFLOW_TEST_OTHER_API_KEY")
+ if key == "" {
+ t.Skip("requires RAGFLOW_TEST_OTHER_API_KEY for a separate account without shared access")
+ }
+ chat := createRESTChat(t, nil)
+ id := chatID(t, chat)
+ config := *TestConfig
+ config.APIKey = key
+ for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodPatch, http.MethodDelete} {
+ result := restCall(t, &config, method, "/chats/"+id, apiObject{"name": "forbidden"}, nil)
+ code := 403
+ if method == http.MethodGet || method == http.MethodDelete {
+ code = 404
+ }
+ restCode(t, result, 200, code)
+ }
+ data := object(t, restOK(t, restCall(t, &config, http.MethodGet, "/chats", nil, apiObject{"id": id}))["data"])
+ assertChatValue(t, data["chats"], []any{})
+ assertChatValue(t, getRESTChat(t, id)["name"], chat["name"])
+}
diff --git a/test/api/config.go b/test/api/config.go
index 911990fcee..b4c72c9cb6 100644
--- a/test/api/config.go
+++ b/test/api/config.go
@@ -20,6 +20,7 @@ package api
import (
"bytes"
+ "context"
"encoding/json"
"fmt"
"io"
@@ -28,6 +29,7 @@ import (
"os"
"strconv"
"strings"
+ "time"
)
var TestConfig *ServerTestConfig
@@ -81,16 +83,8 @@ func InitServerTestConfig() *ServerTestConfig {
}
zhipuAPIKey := os.Getenv("ZHIPU_AI_API_KEY")
- if zhipuAPIKey == "" {
- fmt.Fprintf(os.Stderr, "ZHIPU_AI_API_KEY is not set\n")
- return nil
- }
siliconFlowAPIKey := os.Getenv("SILICONFLOW_API_KEY")
- if siliconFlowAPIKey == "" {
- fmt.Fprintf(os.Stderr, "SILICONFLOW_API_KEY is not set\n")
- return nil
- }
email := os.Getenv("RAGFLOW_TEST_EMAIL")
if email == "" {
@@ -126,6 +120,7 @@ func InitServerTestConfig() *ServerTestConfig {
Priority: priority,
HostAddress: hostAddress,
APIVersion: "v1",
+ APIKey: os.Getenv("RAGFLOW_TEST_API_KEY"),
ZhipuAPIKey: zhipuAPIKey,
SiliconFlowAPIKey: siliconFlowAPIKey,
Email: email,
@@ -165,6 +160,10 @@ func (c *ServerTestConfig) buildHeaders(extra map[string]string) http.Header {
}
func (c *ServerTestConfig) RequestJSON(method, path string, body, params map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) {
+ return c.RequestJSONContext(context.Background(), method, path, body, params, extraHeaders)
+}
+
+func (c *ServerTestConfig) RequestJSONContext(ctx context.Context, method, path string, body any, params map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) {
var bodyReader io.Reader
if body != nil {
b, err := json.Marshal(body)
@@ -184,12 +183,12 @@ func (c *ServerTestConfig) RequestJSON(method, path string, body, params map[str
}
u.RawQuery = q.Encode()
- req, err := http.NewRequest(method, u.String(), bodyReader)
+ req, err := http.NewRequestWithContext(ctx, method, u.String(), bodyReader)
if err != nil {
return nil, err
}
req.Header = c.buildHeaders(extraHeaders)
- return http.DefaultClient.Do(req)
+ return (&http.Client{Timeout: 90 * time.Second}).Do(req)
}
func (c *ServerTestConfig) GetJSON(path string, params map[string]interface{}, extraHeaders map[string]string) (*http.Response, error) {
diff --git a/test/api/main_test.go b/test/api/main_test.go
index 9654df23a7..fd445eac9c 100644
--- a/test/api/main_test.go
+++ b/test/api/main_test.go
@@ -25,6 +25,9 @@ import (
)
func TestMain(m *testing.M) {
+ if TestConfig.APIKey != "" {
+ os.Exit(m.Run())
+ }
fmt.Fprintln(os.Stderr, "Login")
err := TestConfig.Login()
diff --git a/test/api/rest_helpers_test.go b/test/api/rest_helpers_test.go
new file mode 100644
index 0000000000..e3bc0dbf23
--- /dev/null
+++ b/test/api/rest_helpers_test.go
@@ -0,0 +1,186 @@
+package api
+
+import (
+ "bufio"
+ "encoding/json/v2"
+ "fmt"
+ "io"
+ "net/url"
+ "strings"
+ "testing"
+)
+
+type sseEvent struct{ Event, Data string }
+
+// parseSSE handles comments, CRLF, multiline data, and explicit event boundaries.
+func parseSSE(r io.Reader) ([]sseEvent, error) {
+ limited := &io.LimitedReader{R: r, N: 4<<20 + 1}
+ scanner := bufio.NewScanner(limited)
+ scanner.Buffer(make([]byte, 4096), 1<<20)
+ var events []sseEvent
+ var event sseEvent
+ var data []string
+ total := 0
+ for scanner.Scan() {
+ line := scanner.Text()
+ total += len(line) + 1
+ if total > 4<<20 {
+ return nil, fmt.Errorf("SSE exceeds 4 MiB")
+ }
+ if line == "" {
+ if len(data) > 0 {
+ event.Data = strings.Join(data, "\n")
+ events = append(events, event)
+ }
+ event = sseEvent{}
+ data = nil
+ continue
+ }
+ if strings.HasPrefix(line, ":") {
+ continue
+ }
+ key, value, _ := strings.Cut(line, ":")
+ value = strings.TrimPrefix(value, " ")
+ switch key {
+ case "event":
+ event.Event = value
+ case "data":
+ data = append(data, value)
+ }
+ }
+ if err := scanner.Err(); err != nil {
+ return nil, err
+ }
+ if limited.N == 0 {
+ return nil, fmt.Errorf("SSE exceeds 4 MiB")
+ }
+ if len(data) > 0 {
+ return nil, fmt.Errorf("unterminated SSE event")
+ }
+ return events, nil
+}
+
+func sensitiveKey(key string) bool {
+ key = strings.ToLower(key)
+ key = strings.ReplaceAll(key, "-", "_")
+ for _, part := range []string{"token", "authorization", "password", "secret", "api_key", "apikey", "credential"} {
+ if strings.Contains(key, part) {
+ return true
+ }
+ }
+ return false
+}
+
+func redactValue(v any) any {
+ switch value := v.(type) {
+ case map[string]any:
+ for key, item := range value {
+ if sensitiveKey(key) {
+ value[key] = "[REDACTED]"
+ } else {
+ value[key] = redactValue(item)
+ }
+ }
+ case []any:
+ for i, item := range value {
+ value[i] = redactValue(item)
+ }
+ }
+ return v
+}
+
+func diagnosticBody(body []byte, secrets ...string) string {
+ var value any
+ var text string
+ if json.Unmarshal(body, &value) == nil {
+ b, err := json.Marshal(redactValue(value))
+ if err == nil {
+ text = string(b)
+ }
+ } else {
+ text = "[non-JSON body omitted]"
+ }
+ for _, secret := range secrets {
+ if secret != "" {
+ text = strings.ReplaceAll(text, secret, "[REDACTED]")
+ }
+ }
+ if len(text) > 4096 {
+ text = text[:4096] + "...[truncated]"
+ }
+ return text
+}
+
+func diagnosticURL(raw string) string {
+ u, err := url.Parse(raw)
+ if err != nil {
+ return "[invalid URL]"
+ }
+ u.User = nil
+ q := u.Query()
+ for key := range q {
+ if sensitiveKey(key) {
+ q.Set(key, "[REDACTED]")
+ }
+ }
+ u.RawQuery = q.Encode()
+ return u.String()
+}
+
+func object(t *testing.T, value any) map[string]any {
+ t.Helper()
+ result, ok := value.(map[string]any)
+ if !ok {
+ t.Fatalf("expected object, got %T", value)
+ }
+ return result
+}
+func array(t *testing.T, value any) []any {
+ t.Helper()
+ result, ok := value.([]any)
+ if !ok {
+ t.Fatalf("expected array, got %T", value)
+ }
+ return result
+}
+
+func TestRESTHelperSSE(t *testing.T) {
+ for _, tc := range []struct {
+ name, input string
+ count int
+ bad bool
+ }{
+ {"multiline", ": heartbeat\r\nevent: message\r\ndata: first\r\ndata:second\r\n\r\ndata: [DONE]\n\n", 2, false},
+ {"missing boundary", "data: [DONE]\n", 0, true},
+ {"oversized event", "data: " + strings.Repeat("x", 1<<20) + "\n\n", 0, true},
+ {"empty", "", 0, false},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ events, err := parseSSE(strings.NewReader(tc.input))
+ if (err != nil) != tc.bad {
+ t.Fatalf("error=%v", err)
+ }
+ if len(events) != tc.count {
+ t.Fatalf("events=%d", len(events))
+ }
+ if tc.name == "multiline" && (events[0].Event != "message" || events[0].Data != "first\nsecond" || events[1].Data != "[DONE]") {
+ t.Fatalf("events=%v", events)
+ }
+ })
+ }
+}
+
+func TestRESTHelperRedaction(t *testing.T) {
+ body := diagnosticBody([]byte(`{"password":"p","nested":{"api_key":"k","X-API-Key":"hyphen-secret"},"content":"actual-token","items":[{"authorization":"a"}]}`), "actual-token")
+ for _, secret := range []string{`"p"`, `"k"`, `"a"`, "hyphen-secret", "actual-token"} {
+ if strings.Contains(body, secret) {
+ t.Fatalf("secret leaked: %s", body)
+ }
+ }
+ if strings.Contains(diagnosticURL("https://user:pass@host/chats?token=secret&page=2"), "secret") {
+ t.Fatal("URL secret leaked")
+ }
+ if strings.Contains(diagnosticBody([]byte("token=secret")), "secret") {
+ t.Fatal("raw body leaked")
+ }
+}
diff --git a/test/api/rest_request_test.go b/test/api/rest_request_test.go
new file mode 100644
index 0000000000..1b2c32cda3
--- /dev/null
+++ b/test/api/rest_request_test.go
@@ -0,0 +1,181 @@
+//go:build integration
+
+package api
+
+import (
+ "context"
+ "encoding/json/v2"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type apiObject = map[string]any
+
+type restResult struct {
+ Status int
+ JSON map[string]any
+ Body []byte
+ Header http.Header
+}
+
+var resourceSequence atomic.Uint64
+
+func uniqueName(prefix string) string {
+ return fmt.Sprintf("%s_%x_%d", prefix, time.Now().UnixNano(), resourceSequence.Add(1))
+}
+
+func restCall(t *testing.T, c *ServerTestConfig, method, path string, body any, query map[string]any) restResult {
+ t.Helper()
+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
+ defer cancel()
+ // Cleanup calls must remain usable after the test context has been canceled.
+ return restCallContext(t, ctx, c, method, path, body, query)
+}
+
+func restCallContext(t *testing.T, ctx context.Context, c *ServerTestConfig, method, path string, body any, query map[string]any) restResult {
+ t.Helper()
+ started := time.Now()
+ headers := map[string]string{"Authorization": "Bearer " + c.APIKey}
+ if c.APIKey == "" {
+ headers["Authorization"] = " "
+ }
+ requestBody, err := json.Marshal(body)
+ if err != nil {
+ t.Fatalf("marshal request: %v", err)
+ }
+ requestURL, err := url.Parse(c.apiBase() + "/" + strings.TrimLeft(path, "/"))
+ if err != nil {
+ t.Fatal("invalid API URL")
+ }
+ params := requestURL.Query()
+ for key, value := range query {
+ params.Set(key, fmt.Sprint(value))
+ }
+ requestURL.RawQuery = params.Encode()
+ resp, err := c.RequestJSONContext(ctx, method, path, body, query, headers)
+ if err != nil {
+ // url.Error includes the unsanitized URL; diagnostics already include its safe form.
+ if urlErr, ok := errors.AsType[*url.Error](err); ok {
+ err = urlErr.Err
+ }
+ t.Fatalf("%s %s payload=%s duration=%s transport error=%v", method, diagnosticURL(requestURL.String()), diagnosticBody(requestBody, c.APIKey, c.Password), time.Since(started), err)
+ }
+ defer resp.Body.Close()
+ result := restResult{Status: resp.StatusCode, Header: resp.Header}
+ result.Body, err = io.ReadAll(io.LimitReader(resp.Body, 4<<20+1))
+ if err != nil {
+ t.Fatalf("%s %s HTTP=%d duration=%s read: %v", method, diagnosticURL(resp.Request.URL.String()), resp.StatusCode, time.Since(started), err)
+ }
+ if len(result.Body) > 4<<20 {
+ t.Fatalf("%s %s response exceeds 4 MiB", method, diagnosticURL(resp.Request.URL.String()))
+ }
+ if !strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") {
+ _ = json.Unmarshal(result.Body, &result.JSON)
+ }
+ responseLog := diagnosticBody(result.Body, c.APIKey, c.Password)
+ if strings.Contains(resp.Header.Get("Content-Type"), "text/event-stream") {
+ events, parseErr := parseSSE(strings.NewReader(string(result.Body)))
+ preview := make([]any, 0, min(len(events), 5))
+ for _, event := range events[:min(len(events), 5)] {
+ var data any
+ if json.Unmarshal([]byte(event.Data), &data) == nil {
+ preview = append(preview, apiObject{"event": event.Event, "data": data})
+ } else if event.Data == "[DONE]" {
+ preview = append(preview, "[DONE]")
+ } else {
+ preview = append(preview, "[non-JSON SSE data omitted]")
+ }
+ }
+ encoded, _ := json.Marshal(preview)
+ responseLog = fmt.Sprintf("SSE bytes=%d events=%d parse_error=%v preview=%s", len(result.Body), len(events), parseErr, diagnosticBody(encoded, c.APIKey, c.Password))
+ }
+ t.Logf("%s %s payload=%s HTTP=%d code=%v response=%s duration=%s", method, diagnosticURL(resp.Request.URL.String()), diagnosticBody(requestBody, c.APIKey, c.Password), result.Status, result.JSON["code"], responseLog, time.Since(started))
+ return result
+}
+
+func restCode(t *testing.T, r restResult, status, code int) {
+ t.Helper()
+ if r.Status != status {
+ t.Fatalf("HTTP status=%d want=%d", r.Status, status)
+ }
+ actual, ok := r.JSON["code"].(float64)
+ if !ok || actual != float64(code) {
+ t.Fatalf("application code=%v want=%d (see request diagnostic)", r.JSON["code"], code)
+ }
+}
+func restOK(t *testing.T, r restResult) map[string]any {
+ t.Helper()
+ restCode(t, r, 200, 0)
+ return r.JSON
+}
+
+func cleanupResource(t *testing.T, c *ServerTestConfig, family, id string) {
+ t.Helper()
+ t.Cleanup(func() {
+ path := "/" + family + "/" + id
+ var body any
+ if family == "chats" || family == "datasets" {
+ path = "/" + family
+ body = apiObject{"ids": []string{id}}
+ }
+ r := restCall(t, c, http.MethodDelete, path, body, nil)
+ // Tests exercise deletion themselves; a subsequently missing resource is expected.
+ code, ok := r.JSON["code"].(float64)
+ if r.Status != 200 || !ok || (code != 0 && code != 102 && code != 103 && code != 404) {
+ t.Errorf("cleanup %s/%s failed (see diagnostic)", family, id)
+ }
+ // A bulk-delete envelope can report partial failures. Prove absence rather
+ // than treating a general error code as evidence that cleanup succeeded.
+ switch family {
+ case "agents":
+ restCode(t, restCall(t, c, http.MethodGet, "/agents/"+id, nil, nil), 200, 103)
+ case "chats":
+ restCode(t, restCall(t, c, http.MethodGet, "/chats/"+id, nil, nil), 200, 404)
+ case "datasets":
+ remaining := restOK(t, restCall(t, c, http.MethodGet, "/datasets", nil, apiObject{"id": id}))
+ if len(array(t, remaining["data"])) != 0 {
+ t.Errorf("cleanup left dataset %s present", id)
+ }
+ }
+ })
+}
+
+func TestRESTHelperTransport(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path == "/api/v1/cancel" {
+ <-r.Context().Done()
+ return
+ }
+ if r.Method != http.MethodPost || r.URL.Query().Get("keywords") != "hello & 中文" {
+ t.Errorf("method=%s query=%s", r.Method, r.URL.RawQuery)
+ }
+ if got := r.Header.Get("Authorization"); got != "Bearer test-secret" {
+ t.Errorf("unexpected authentication header")
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"code":0,"data":{"id":"created"}}`)
+ }))
+ defer server.Close()
+ c := &ServerTestConfig{HostAddress: server.URL, APIVersion: "v1", APIKey: "test-secret"}
+ r := restCall(t, c, http.MethodPost, "/echo", apiObject{"password": "not-for-logs"}, apiObject{"keywords": "hello & 中文"})
+ if object(t, restOK(t, r)["data"])["id"] != "created" {
+ t.Fatal("response object was lost")
+ }
+ ctx, cancel := context.WithTimeout(t.Context(), 20*time.Millisecond)
+ defer cancel()
+ resp, err := c.RequestJSONContext(ctx, http.MethodGet, "/cancel", nil, nil, nil)
+ if resp != nil {
+ resp.Body.Close()
+ }
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("cancellation error=%v", err)
+ }
+}