Repository navigation
feat(go-api): implement GET /api/v1/agents list endpoint (issue #15328) - #15329
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (2)
💤 Files with no reviewable changes (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds a read-only GET /api/v1/agents endpoint: DAO listing by tenant/owner IDs with pagination and filtering, a service enforcing tenant-based owner validation and mapping, an HTTP handler parsing query params, unit tests, router registration, and server wiring. ChangesAgent Canvas Listing API
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Hi, @Haruko386 , |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
internal/handler/agent_test.go (1)
45-62: 🏗️ Heavy liftTest currently bypasses
AgentHandler.ListAgentsimplementation.The wrapper duplicates handler behavior, so regressions in real query parsing/response flow won’t be caught. Consider refactoring
AgentHandlerto depend on an interface and invoke the realListAgentsin tests.Also applies to: 79-110
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/handler/agent_test.go` around lines 45 - 62, The test wrapper agentHandlerTestable currently duplicates the handler logic and bypasses the real AgentHandler.ListAgents path; update tests to exercise the real handler by refactoring AgentHandler to accept an agentServiceIface (or add a constructor that injects agentServiceIface) and then in tests instantiate AgentHandler with a mock implementing agentServiceIface and call AgentHandler.ListAgents (instead of agentHandlerTestable.listAgents); ensure the test imports and uses AgentHandler.ListAgents so query parsing, auth flow (GetUser) and response JSON path are exercised end-to-end.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/dao/user_canvas.go`:
- Around line 155-162: The code builds an SQL ORDER clause by concatenating the
raw request-supplied variable orderby with ASC/DESC and passing it into
base.Order(order), which allows SQL injection; change this to validate/ordermap
the incoming orderby against an explicit allowlist of permitted sort keys (e.g.,
map request keys like "create_time", "name", "updated_at" to their safe column
identifiers) and use a safe default if not found, then append " ASC" or " DESC"
based on desc and pass that constructed string to base.Order; update the logic
around the orderby variable, desc handling, and the call to base.Order(order) in
internal/dao/user_canvas.go to perform the mapping/validation before calling
base.Order.
In `@internal/handler/agent.go`:
- Around line 106-110: The error response in the c.JSON call returns "data:
false" which breaks the project's consistent error envelope; change the "data"
field to nil (Go nil) or, better, replace this manual c.JSON call with the
existing jsonError helper so the handler in agent.go returns the same schema as
other handlers (locate the c.JSON(...) block around the handler where
err.Error() is used and swap "data: false" for data: nil or call jsonError(c,
http.StatusOK, err)).
---
Nitpick comments:
In `@internal/handler/agent_test.go`:
- Around line 45-62: The test wrapper agentHandlerTestable currently duplicates
the handler logic and bypasses the real AgentHandler.ListAgents path; update
tests to exercise the real handler by refactoring AgentHandler to accept an
agentServiceIface (or add a constructor that injects agentServiceIface) and then
in tests instantiate AgentHandler with a mock implementing agentServiceIface and
call AgentHandler.ListAgents (instead of agentHandlerTestable.listAgents);
ensure the test imports and uses AgentHandler.ListAgents so query parsing, auth
flow (GetUser) and response JSON path are exercised end-to-end.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 680d3a4e-9ca6-4748-85bc-8d55feb14b9a
📒 Files selected for processing (6)
cmd/server_main.gointernal/dao/user_canvas.gointernal/handler/agent.gointernal/handler/agent_test.gointernal/router/router.gointernal/service/agent.go
| order := orderby | ||
| if desc { | ||
| order += " DESC" | ||
| } else { | ||
| order += " ASC" | ||
| } | ||
| query := base.Order(order) | ||
|
|
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Verify request-controlled `orderby` flows to DAO `Order(...)` without allowlisting.
rg -n -C2 --type=go 'DefaultQuery\("orderby"|ListAgents\(|ListByTenantIDs\(|order \+=|Order\(order\)'Repository: infiniflow/ragflow
Length of output: 7787
Allowlist orderby before building the GORM Order(...) clause (SQL injection risk).
In internal/dao/user_canvas.go (lines 155-162), order := orderby is concatenated with only " ASC"/" DESC" and passed directly to base.Order(order) as a raw SQL order-by fragment, with no allowlist/sanitization. orderby is sourced from the request query (e.g., internal/handler/agent.go uses c.DefaultQuery("orderby", "create_time")).
🔒 Proposed fix
- order := orderby
+ allowedOrderBy := map[string]struct{}{
+ "create_time": {},
+ "update_time": {},
+ "title": {},
+ }
+ if _, ok := allowedOrderBy[orderby]; !ok {
+ orderby = "create_time"
+ }
+ order := orderby
if desc {
order += " DESC"
} else {
order += " ASC"
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| order := orderby | |
| if desc { | |
| order += " DESC" | |
| } else { | |
| order += " ASC" | |
| } | |
| query := base.Order(order) | |
| allowedOrderBy := map[string]struct{}{ | |
| "create_time": {}, | |
| "update_time": {}, | |
| "title": {}, | |
| } | |
| if _, ok := allowedOrderBy[orderby]; !ok { | |
| orderby = "create_time" | |
| } | |
| order := orderby | |
| if desc { | |
| order += " DESC" | |
| } else { | |
| order += " ASC" | |
| } | |
| query := base.Order(order) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/dao/user_canvas.go` around lines 155 - 162, The code builds an SQL
ORDER clause by concatenating the raw request-supplied variable orderby with
ASC/DESC and passing it into base.Order(order), which allows SQL injection;
change this to validate/ordermap the incoming orderby against an explicit
allowlist of permitted sort keys (e.g., map request keys like "create_time",
"name", "updated_at" to their safe column identifiers) and use a safe default if
not found, then append " ASC" or " DESC" based on desc and pass that constructed
string to base.Order; update the logic around the orderby variable, desc
handling, and the call to base.Order(order) in internal/dao/user_canvas.go to
perform the mapping/validation before calling base.Order.
| c.JSON(http.StatusOK, gin.H{ | ||
| "code": code, | ||
| "data": false, | ||
| "message": err.Error(), | ||
| }) |
There was a problem hiding this comment.
Keep error envelope shape consistent (data should be nil).
This branch returns data: false, but other handlers use data: nil via jsonError(...). Keep one consistent error schema for clients.
✅ Proposed fix
if err != nil {
- c.JSON(http.StatusOK, gin.H{
- "code": code,
- "data": false,
- "message": err.Error(),
- })
+ jsonError(c, code, err.Error())
return
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| c.JSON(http.StatusOK, gin.H{ | |
| "code": code, | |
| "data": false, | |
| "message": err.Error(), | |
| }) | |
| if err != nil { | |
| jsonError(c, code, err.Error()) | |
| return | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/handler/agent.go` around lines 106 - 110, The error response in the
c.JSON call returns "data: false" which breaks the project's consistent error
envelope; change the "data" field to nil (Go nil) or, better, replace this
manual c.JSON call with the existing jsonError helper so the handler in agent.go
returns the same schema as other handlers (locate the c.JSON(...) block around
the handler where err.Error() is used and swap "data: false" for data: nil or
call jsonError(c, http.StatusOK, err)).
Haruko386
left a comment
There was a problem hiding this comment.
@web-dev0521 LGTM
Thank you for your contribution
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #15329 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
|
Hi, @JinHai-CN , |
|
@web-dev0521 Would you please fix the conflicts? |
Resolve the single conflict in cmd/server_main.go: upstream added mcpHandler to the router.NewRouter call (PR infiniflow#15260) while this branch added agentHandler. Both must be passed. internal/router/router.go auto-merged with the union of fields and parameters (memoryHandler, mcpHandler, skillSearchHandler, providerHandler, agentHandler), so the caller in cmd/server_main.go is updated to match that signature.
|
Hi, @JinHai-CN , Done! |
|
Thank you @JinHai-CN ! |
Summary
Closes: #15328
GET /api/v1/agents— the agent/canvas listing endpoint needed to complete the Home dashboard tile inweb/src/pages/home/.api/apps/restful_apis/agent_api.py::list_agentsexactly: tenant-join auth, optionalowner_idsguard, keyword filter, pagination, ordering, andcanvas_categoryfilter (default:agent_canvas).Changes
internal/dao/user_canvas.goListByTenantIDs— paginated, filtered query over joined tenant IDsinternal/service/agent.goAgentService.ListAgentswith tenant-auth guardinternal/handler/agent.goAgentHandler.ListAgents— parses query params, calls serviceinternal/handler/agent_test.gointernal/router/router.goGET /api/v1/agentsunder auth group; addagentHandlertoRoutercmd/server_main.goAgentService→AgentHandler→NewRouterQuery parameters
keywordspagepage_sizeorderbycreate_timedesctrueowner_idscanvas_categoryagent_canvasResponse
{ "code": 0, "data": { "canvas": [ { "id": "...", "title": "My Agent", "avatar": null, "permission": "me", "canvas_type": null, "canvas_category": "agent_canvas", "create_time": 1716800000000, "update_time": 1716800000000 } ], "total": 1 }, "message": "success" }Scope guard
Only the list (id, title, avatar, permission, canvas_type, canvas_category, create_time, update_time) is returned. Full agent CRUD and canvas runtime/execution are explicitly out of scope — they are a separate, larger slice of #15240.
Python parity
Mirrors
api/apps/restful_apis/agent_api.py::list_agentsexactly:GetTenantIDsByUserIDto build the authorised owner set (same asTenantService.get_joined_tenants_by_user_id).owner_idsis supplied, validates each against the authorised set and returnsCodeOperatingErrorfor any unauthorised entry.owner_idsis omitted.canvas_categoryto"agent_canvas"when not specified.Type of change