Skip to content

feat(go-api): implement GET /api/v1/agents list endpoint (issue #15328) - #15329

Merged
JinHai-CN merged 2 commits into
infiniflow:mainfrom
Lobster-0429:feat/go-api-agent-list
May 28, 2026
Merged

JinHai-CN merged 2 commits into
infiniflow:mainfrom
Lobster-0429:feat/go-api-agent-list

Conversation

@Lobster-0429

@Lobster-0429 Lobster-0429 commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Closes: #15328

  • Implements GET /api/v1/agents — the agent/canvas listing endpoint needed to complete the Home dashboard tile in web/src/pages/home/.
  • Mirrors Python api/apps/restful_apis/agent_api.py::list_agents exactly: tenant-join auth, optional owner_ids guard, keyword filter, pagination, ordering, and canvas_category filter (default: agent_canvas).
  • Scope: read-only list only. Full agent CRUD and canvas runtime are explicitly out of scope (separate slice of [Feature] Implement API of RAGFlow server in Go #15240).

Changes

File Change
internal/dao/user_canvas.go Add ListByTenantIDs — paginated, filtered query over joined tenant IDs
internal/service/agent.go New AgentService.ListAgents with tenant-auth guard
internal/handler/agent.go New AgentHandler.ListAgents — parses query params, calls service
internal/handler/agent_test.go Unit test for handler success path
internal/router/router.go Register GET /api/v1/agents under auth group; add agentHandler to Router
cmd/server_main.go Wire AgentService → AgentHandler → NewRouter

Query parameters

Param Type Default Description
keywords string — Title substring filter
page int 0 Page number (0 = no pagination)
page_size int 0 Items per page (0 = no pagination)
orderby string create_time Sort field
desc bool true Descending sort
owner_ids string (all authorised) Comma-separated owner IDs
canvas_category string agent_canvas Canvas category filter

Response

{
  "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_agents exactly:

  • Calls GetTenantIDsByUserID to build the authorised owner set (same as TenantService.get_joined_tenants_by_user_id).
  • If owner_ids is supplied, validates each against the authorised set and returns CodeOperatingError for any unauthorised entry.
  • Defaults to querying all authorised tenant IDs when owner_ids is omitted.
  • Defaults canvas_category to "agent_canvas" when not specified.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)
  • New Feature (non-breaking change which adds functionality)
  • Documentation Update
  • Refactoring
  • Performance Improvement
  • Other (please describe):

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels May 28, 2026
@coderabbitai

coderabbitai Bot commented May 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3d91341f-9c4e-4356-9cf3-80741425882e

📥 Commits

Reviewing files that changed from the base of the PR and between 860a944 and b650075.

📒 Files selected for processing (2)
  • cmd/server_main.go
  • internal/router/router.go
💤 Files with no reviewable changes (1)
  • internal/router/router.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • cmd/server_main.go

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Agent Canvas Listing API

Layer / File(s) Summary
DAO pagination and filtering
internal/dao/user_canvas.go
ListByTenantIDs fetches canvases accessible to a set of owner IDs and a user, with optional category filtering, keyword search, dynamic ordering, and pagination.
Service authorization and business logic
internal/service/agent.go
AgentService builds authorized tenant owner set, validates caller-supplied owner IDs, defaults to authorized owners when none provided, maps UserCanvas to AgentItem, and delegates listing to the DAO.
HTTP handler endpoint
internal/handler/agent.go
AgentHandler.ListAgents extracts current user, parses query parameters (keywords, canvas_category, page, page_size, orderby, desc, owner_ids), calls the service, and returns JSON error/success payloads.
Handler unit tests
internal/handler/agent_test.go
Fake service, testable handler wrapper, test router setup, and TestListAgents_Success asserting HTTP 200 and JSON response code and data.total.
Router endpoint registration
internal/router/router.go
Router gains agentHandler field; NewRouter accepts and stores it; Setup registers authenticated GET /api/v1/agents routed to agentHandler.ListAgents.
Server initialization and wiring
cmd/server_main.go
startServer creates AgentService and AgentHandler and passes the handler into router.NewRouter(...) so agent endpoints are registered at startup.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

A rabbit scampers through tenant rows,
Counting canvases where soft wind blows.
Filters set, owners all checked right,
The agent list hops into sight.
🐇📜✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 42.86% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(go-api): implement GET /api/v1/agents list endpoint (issue #15328)' clearly and specifically summarizes the main change: implementing a new HTTP endpoint for listing agents.
Description check ✅ Passed The description provides comprehensive coverage with problem statement, scope clarification, detailed changes table, query parameters, response format, and Python parity notes. The required 'Type of change' section is properly filled.
Linked Issues check ✅ Passed All coding requirements from issue #15328 are met: read-only GET /api/v1/agents endpoint is implemented with tenant-join authorization, optional owner_ids validation, keyword filtering, pagination, ordering, canvas_category filtering, and metadata-only responses. Handler unit test is included.
Out of Scope Changes check ✅ Passed All changes are within scope: DAO query for tenant-filtered canvases, service with auth validation, handler with parameter parsing, test coverage, router registration, and server wiring. No full agent CRUD or runtime execution is implemented, as correctly excluded.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @Haruko386 ,
Could you please review this PR?

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
internal/handler/agent_test.go (1)

45-62: 🏗️ Heavy lift

Test currently bypasses AgentHandler.ListAgents implementation.

The wrapper duplicates handler behavior, so regressions in real query parsing/response flow won’t be caught. Consider refactoring AgentHandler to depend on an interface and invoke the real ListAgents in 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

📥 Commits

Reviewing files that changed from the base of the PR and between 0aff6a3 and 860a944.

📒 Files selected for processing (6)
  • cmd/server_main.go
  • internal/dao/user_canvas.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/router/router.go
  • internal/service/agent.go

Comment on lines +155 to +162
order := orderby
if desc {
order += " DESC"
} else {
order += " ASC"
}
query := base.Order(order)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

🧩 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.

Suggested change
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.

Comment thread internal/handler/agent.go
Comment on lines +106 to +110
c.JSON(http.StatusOK, gin.H{
"code": code,
"data": false,
"message": err.Error(),
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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 Haruko386 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@web-dev0521 LGTM
Thank you for your contribution

@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label May 28, 2026
@Haruko386 Haruko386 added the ci Continue Integration label May 28, 2026
@Haruko386
Haruko386 marked this pull request as draft May 28, 2026 05:20
@Haruko386
Haruko386 marked this pull request as ready for review May 28, 2026 05:20
@codecov

codecov Bot commented May 28, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (b7d88f0) to head (b650075).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN ,
Could you please review this PR?

@JinHai-CN

Copy link
Copy Markdown
Member

@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.
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Hi, @JinHai-CN , Done!
All tests are passed successfully.

@JinHai-CN
JinHai-CN merged commit 0a7662c into infiniflow:main May 28, 2026
1 check passed
@Lobster-0429

Copy link
Copy Markdown
Contributor Author

Thank you @JinHai-CN !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. lgtm This PR has been approved by a maintainer size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Subtask]: Go API — Welcome / Home dashboard page (agent & application listing gap)

3 participants