Skip to content

Go CLI: refactor commands - #16213

Merged
JinHai-CN merged 10 commits into
infiniflow:mainfrom
JinHai-CN:fix474
Jun 21, 2026
Merged

JinHai-CN merged 10 commits into
infiniflow:mainfrom
JinHai-CN:fix474

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

As title.

Type of change

  • Refactoring

Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
@coderabbitai

coderabbitai Bot commented Jun 20, 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: e53b51e9-45e0-4eef-bbc9-fa9c2bba48c5

📥 Commits

Reviewing files that changed from the base of the PR and between 9eda2b4 and 5561732.

📒 Files selected for processing (3)
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/cli/cli_http.go

📝 Walkthrough

Walkthrough

Adds ShowRole, ListAllModels, and GetModelByModelName admin endpoints (handler, service stub, router wiring). Renames CLI command handler functions to Common* and admin_show_* conventions, removes benchmark/iteration request paths, rewrites admin and user parser dispatch to emit updated command type strings (ping_server, admin_show_*, admin_list_*), and updates CLI HTTP routing accordingly.

Changes

Admin ShowRole and Models endpoints + CLI command rename refactor

Layer / File(s) Summary
Admin ShowRole and Models endpoints
internal/admin/enterprise_service.go, internal/admin/enterprise_handler.go, internal/admin/router.go, internal/admin/service.go
GetRole stub replaced by ShowRole; ListAllModels and GetModelByModelName service stubs added; ShowRole and ListModelsOrShowModel handlers wired; /all-models route registered; stale comment removed.
Common CLI command handler renames and model dispatch*
internal/cli/common_command.go
ShowProvider, ListModels, ShowProviderModel, ShowCommonCurrent, and ShowModel renamed to Common* variants; ListAllModels and CommonShowModel now select httpClient and apiURL by CLIMode (/admin/all-models vs /all-models).
Admin CLI command renames and benchmark removal
internal/cli/admin_command.go
Removes benchmark/iterations from AdminShowVersionCommand; deletes old ShowRole and AdminShowUserInfoCommand; adds AdminShowUserCommand and AdminShowRoleCommand; renames service and variable commands; removes ListAgents.
Admin parser refactor
internal/cli/admin_parser.go
Rewrites parseAdminListCommand and parseAdminShowCommand dispatch with new subparsers emitting admin_show_*/admin_list_* names; changes ping output to ping_server; adds parseAdminListServices, parseAdminListVariables, parseAdminListProvider, parseAdminListModels, and new parseAdminShow* implementations; removes TokenRegister dispatch.
User parser and main parser updates
internal/cli/user_parser.go, internal/cli/parser.go
Changes ping to ping_server; removes TokenService case from parseShowCommand and deletes parseShowService function; removes TokenRegister dispatch from main parser; adds grammar comments.
CLI HTTP routing updates
internal/cli/cli_http.go
ExecuteAdminCommand updated to match ping_server, admin_list_services, and admin_show_* command type strings and routes to Common*/AdminShow* handlers; ExecuteUserCommand updated to use ping_server and route provider/model commands to Common* handlers.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • infiniflow/ragflow#16119: Introduced the GetRole enterprise handler and service stub that this PR replaces with ShowRole.

Suggested reviewers

  • Haruko386

Poem

🐇 Hop, hop — the roles now show, not get,
The models list without benchmark fret.
ping_server rings where ping once played,
Common* names in a tidy cascade.
The parser speaks in admin_show_* tongue —
A cleaner warren for the young! 🌿

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is extremely minimal, containing only 'As title' without substantive detail about the refactoring scope, goals, or rationale. Provide specific details about which commands were refactored, what architectural improvements were made, and the rationale for these changes to help reviewers understand the scope and impact.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go CLI: refactor commands' clearly identifies the main change as CLI command refactoring.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 20, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 20, 2026 15:06
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 20, 2026
Signed-off-by: Jin Hai <[email protected]>

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
internal/cli/admin_command.go (1)

587-587: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate number before using it.

cmd.Params["number"].(int) panics if the parser or another caller omits the key or passes a non-int value.

🐛 Proposed fix
-	serviceIndex := cmd.Params["number"].(int)
+	serviceIndex, ok := cmd.Params["number"].(int)
+	if !ok {
+		return nil, fmt.Errorf("number not provided")
+	}
🤖 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/cli/admin_command.go` at line 587, The type assertion for
cmd.Params["number"].(int) will panic if the key is missing or the value is not
an int. Replace this unsafe assertion with the two-return-value form of type
assertion (value, ok := cmd.Params["number"].(int)) and add validation to check
if ok is true and the key exists in cmd.Params. If validation fails, return an
appropriate error or handle it gracefully instead of allowing a panic.
internal/cli/common_command.go (1)

616-626: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Initialize result.Data even when result already exists.

If GetAdminServerInfo/GetAPIServerInfo returns a CommonDataResponse with Data == nil, Line 623 panics when writing to the nil map.

🐛 Proposed fix
 	if result == nil {
 		result = &CommonDataResponse{}
-		if result.Data == nil {
-			result.Data = make(map[string]interface{})
-		}
+	}
+	if result.Data == nil {
+		result.Data = make(map[string]interface{})
 	}
🤖 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/cli/common_command.go` around lines 616 - 626, The current code only
initializes result.Data when result itself is nil, but if GetAdminServerInfo or
GetAPIServerInfo returns a CommonDataResponse with a non-nil result but nil Data
field, the subsequent assignments to result.Data on lines 623-626 will panic.
Move the nil check for result.Data outside of the if result == nil block so that
result.Data is always initialized before use, regardless of whether result was
originally nil.
🧹 Nitpick comments (2)
internal/cli/admin_command.go (1)

589-600: ⚡ Quick win

Remove the leftover benchmark branch.

This command still accepts iterations and returns RequestWithIterations, while the refactor scope says admin show commands now use a single request path.

♻️ Proposed cleanup
-	// Check for benchmark iterations
-	iterations := 1
-	if val, ok := cmd.Params["iterations"].(int); ok && val > 1 {
-		iterations = val
-	}
-
 	endPoint := fmt.Sprintf("/admin/services/%d", serviceIndex)
-
-	if iterations > 1 {
-		// Benchmark mode - return raw result for benchmark stats
-		return c.AdminServerClient.RequestWithIterations("GET", endPoint, "admin", nil, nil, iterations)
-	}
 
 	resp, err := c.AdminServerClient.Request("GET", endPoint, "admin", nil, nil)
🤖 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/cli/admin_command.go` around lines 589 - 600, Remove the benchmark
mode support from the admin command handler. Delete the iterations variable
declaration and the entire conditional block that checks if iterations > 1 and
calls RequestWithIterations. Replace this entire section with a single direct
request call using the standard request method instead, passing the same
endPoint, method, and other parameters but without the iterations parameter. The
code should make one straightforward GET request to the admin service endpoint
rather than supporting multiple benchmark iterations.
internal/admin/enterprise_handler.go (1)

225-229: ⚡ Quick win

Use the errorResponse helper for consistency.

This error response uses c.JSON(http.StatusBadRequest, gin.H{...}) directly, while the rest of the file uses the errorResponse(c, message, code) helper function. Maintaining a consistent error response pattern improves code maintainability.

♻️ Proposed fix
 	var req ListModelsOrShowModelRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
-		c.JSON(http.StatusBadRequest, gin.H{
-			"code":    400,
-			"message": "Invalid request body",
-		})
+		errorResponse(c, "Invalid request body", 400)
 		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/admin/enterprise_handler.go` around lines 225 - 229, The error
response in this section uses direct c.JSON(http.StatusBadRequest, gin.H{...})
instead of the errorResponse helper function used consistently throughout the
rest of the file. Replace this inline JSON response with a call to the
errorResponse(c, message, code) helper function, passing the context object, the
message "Invalid request body", and the code 400. This will standardize the
error response format and improve code maintainability.
🤖 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/admin/enterprise_handler.go`:
- Around line 222-252: The ListModelsOrShowModel handler function uses
c.ShouldBindJSON to bind a JSON request body on a GET endpoint, which violates
HTTP best practices since GET requests should use query parameters instead. To
fix this, change the request struct's field tags from json tags to form tags for
query parameter binding, replace c.ShouldBindJSON(&req) with
c.ShouldBindQuery(&req), and update the validation error handling to use the
errorResponse() helper function (currently it calls c.JSON() directly on lines
225-228) to maintain consistency with other handlers in the file, passing
appropriate parameters like c, "Invalid request parameters", and 400 to
errorResponse.

In `@internal/cli/admin_command.go`:
- Around line 1776-1778: In the admin_command.go file where role_name is
extracted and the endpoint is constructed, add validation for the role_name
parameter extraction to prevent panics from missing or incorrectly typed
parameters, and remove the trailing slash from the endpoint path construction in
the fmt.Sprintf call so that the generated path matches the registered route
`/admin/roles/:role_name` without the trailing slash.

In `@internal/cli/admin_parser.go`:
- Around line 356-360: In the parseAdminListModels function, add optional
semicolon handling after consuming the MODELS token and before returning the
command, similar to how parseAdminListProvider handles it. Check if the current
token is a semicolon using the parser's token checking method, and if present,
consume it by calling p.nextToken(). This will ensure the parser doesn't get
left in an inconsistent state when users include a trailing semicolon after LIST
MODELS.

---

Outside diff comments:
In `@internal/cli/admin_command.go`:
- Line 587: The type assertion for cmd.Params["number"].(int) will panic if the
key is missing or the value is not an int. Replace this unsafe assertion with
the two-return-value form of type assertion (value, ok :=
cmd.Params["number"].(int)) and add validation to check if ok is true and the
key exists in cmd.Params. If validation fails, return an appropriate error or
handle it gracefully instead of allowing a panic.

In `@internal/cli/common_command.go`:
- Around line 616-626: The current code only initializes result.Data when result
itself is nil, but if GetAdminServerInfo or GetAPIServerInfo returns a
CommonDataResponse with a non-nil result but nil Data field, the subsequent
assignments to result.Data on lines 623-626 will panic. Move the nil check for
result.Data outside of the if result == nil block so that result.Data is always
initialized before use, regardless of whether result was originally nil.

---

Nitpick comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 225-229: The error response in this section uses direct
c.JSON(http.StatusBadRequest, gin.H{...}) instead of the errorResponse helper
function used consistently throughout the rest of the file. Replace this inline
JSON response with a call to the errorResponse(c, message, code) helper
function, passing the context object, the message "Invalid request body", and
the code 400. This will standardize the error response format and improve code
maintainability.

In `@internal/cli/admin_command.go`:
- Around line 589-600: Remove the benchmark mode support from the admin command
handler. Delete the iterations variable declaration and the entire conditional
block that checks if iterations > 1 and calls RequestWithIterations. Replace
this entire section with a single direct request call using the standard request
method instead, passing the same endPoint, method, and other parameters but
without the iterations parameter. The code should make one straightforward GET
request to the admin service endpoint rather than supporting multiple benchmark
iterations.
🪄 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: 6e3b5b0c-a788-4fdc-956a-0cb4af594f88

📥 Commits

Reviewing files that changed from the base of the PR and between 1b712be and 9eda2b4.

📒 Files selected for processing (10)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/router.go
  • internal/admin/service.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/common_command.go
  • internal/cli/parser.go
  • internal/cli/user_parser.go
💤 Files with no reviewable changes (2)
  • internal/admin/service.go
  • internal/cli/parser.go

Comment on lines +222 to +252
func (h *Handler) ListModelsOrShowModel(c *gin.Context) {
var req ListModelsOrShowModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Invalid request body",
})
return
}

if req.ModelName == "" {
// List models
models, err := h.service.ListAllModels()
if err != nil {
errorResponse(c, err.Error(), 500)
return
}

success(c, models, "")
} else {
// Get model
model, err := h.service.GetModelByModelName(req.ModelName)
if err != nil {
errorResponse(c, err.Error(), 500)
return
}

success(c, model, "")
}
}

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 | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check httpClient.Request implementation to confirm GET body handling

# Find the Request method definition
ast-grep --pattern 'func ($_ *HTTPClient) Request($$$) ($$$) {
  $$$
}'

# Also search for how payload is processed in GET requests
rg -n -A 10 'func.*Request.*method.*string' internal/cli/http_client.go

Repository: infiniflow/ragflow

Length of output: 5236


🏁 Script executed:

#!/bin/bash
# Check the client code that calls the handler

# Find ListAllModels and CommonShowModel in common_command.go
rg -n -B 5 -A 15 "func.*ListAllModels|func.*CommonShowModel" internal/cli/common_command.go

# Check router.go line 176 to confirm the endpoint configuration
sed -n '170,185p' internal/admin/router.go

# Also check if there are multiple routers or if GET is definitely used
rg -n "all-models" internal/admin/router.go

Repository: infiniflow/ragflow

Length of output: 1799


🏁 Script executed:

#!/bin/bash
# Check what HTTP method is passed in the Request call for both functions

# Check ListAllModels method call
sed -n '920,945p' internal/cli/common_command.go

# Check CommonShowModel method call
sed -n '968,990p' internal/cli/common_command.go

Repository: infiniflow/ragflow

Length of output: 1513


🏁 Script executed:

#!/bin/bash
# Check the error response pattern in the handler file

# Look at the ListModelsOrShowModel handler lines 222-252
sed -n '222,252p' internal/admin/enterprise_handler.go

# Check how errorResponse is used elsewhere in the file
rg -n "errorResponse" internal/admin/enterprise_handler.go | head -20

# Check if c.JSON with StatusBadRequest is used elsewhere
rg -n 'c\.JSON.*StatusBadRequest' internal/admin/enterprise_handler.go | head -10

Repository: infiniflow/ragflow

Length of output: 1685


GET requests should not use JSON body binding.

The handler binds a JSON request body using c.ShouldBindJSON on a GET endpoint. This violates HTTP best practices:

  1. GET requests should use query parameters, not request bodies
  2. Many HTTP proxies and caches ignore or strip GET request bodies
  3. This pattern is non-standard and may fail with standard HTTP clients or infrastructure

The client code in internal/cli/common_command.go confirms both ListAllModels (line 929) and CommonShowModel (line 977) send GET requests with JSON payloads to this endpoint.

Additionally, lines 225-228 use c.JSON() directly for error handling, while all other handlers in this file use the errorResponse() helper function. For consistency, use errorResponse(c, "Invalid request parameters", 400).

Recommended fixes:

  • Change the request struct to use query parameter binding with form tags
  • Use c.ShouldBindQuery(&req) instead of c.ShouldBindJSON(&req)
  • Use the errorResponse() helper for the validation error
  • Alternatively, change the HTTP method to POST if a body is required
Proposed fix to use query parameters
 type ListModelsOrShowModelRequest struct {
-	ModelName string `json:"model_name"`
+	ModelName string `form:"model_name"`
 }
 
 func (h *Handler) ListModelsOrShowModel(c *gin.Context) {
 	var req ListModelsOrShowModelRequest
-	if err := c.ShouldBindJSON(&req); err != nil {
-		c.JSON(http.StatusBadRequest, gin.H{
-			"code":    400,
-			"message": "Invalid request body",
-		})
+	if err := c.ShouldBindQuery(&req); err != nil {
+		errorResponse(c, "Invalid request parameters", 400)
 		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/admin/enterprise_handler.go` around lines 222 - 252, The
ListModelsOrShowModel handler function uses c.ShouldBindJSON to bind a JSON
request body on a GET endpoint, which violates HTTP best practices since GET
requests should use query parameters instead. To fix this, change the request
struct's field tags from json tags to form tags for query parameter binding,
replace c.ShouldBindJSON(&req) with c.ShouldBindQuery(&req), and update the
validation error handling to use the errorResponse() helper function (currently
it calls c.JSON() directly on lines 225-228) to maintain consistency with other
handlers in the file, passing appropriate parameters like c, "Invalid request
parameters", and 400 to errorResponse.

Comment on lines +1776 to +1778
roleName := cmd.Params["role_name"].(string)

endPoint := fmt.Sprintf("/admin/roles/%s/", roleName)

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 | 🟠 Major | ⚡ Quick win

Validate role_name and match the registered route.

The unchecked assertion can panic on a missing/mis-typed param, and the built path adds a trailing slash while the admin router registers /roles/:role_name.

🐛 Proposed fix
-	roleName := cmd.Params["role_name"].(string)
+	roleName, ok := cmd.Params["role_name"].(string)
+	if !ok {
+		return nil, fmt.Errorf("role_name not provided")
+	}
 
-	endPoint := fmt.Sprintf("/admin/roles/%s/", roleName)
+	endPoint := fmt.Sprintf("/admin/roles/%s", roleName)
📝 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
roleName := cmd.Params["role_name"].(string)
endPoint := fmt.Sprintf("/admin/roles/%s/", roleName)
roleName, ok := cmd.Params["role_name"].(string)
if !ok {
return nil, fmt.Errorf("role_name not provided")
}
endPoint := fmt.Sprintf("/admin/roles/%s", roleName)
🤖 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/cli/admin_command.go` around lines 1776 - 1778, In the
admin_command.go file where role_name is extracted and the endpoint is
constructed, add validation for the role_name parameter extraction to prevent
panics from missing or incorrectly typed parameters, and remove the trailing
slash from the endpoint path construction in the fmt.Sprintf call so that the
generated path matches the registered route `/admin/roles/:role_name` without
the trailing slash.

Comment thread internal/cli/admin_parser.go Resolved
Signed-off-by: Jin Hai <[email protected]>
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. and removed size:XL This PR changes 500-999 lines, ignoring generated files. labels Jun 21, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft June 21, 2026 08:08
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 21, 2026 08:08
@dosubot dosubot Bot added the ☯️ refactor Pull request that refactor/refine code label Jun 21, 2026
Signed-off-by: Jin Hai <[email protected]>
@codecov

codecov Bot commented Jun 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (1b712be) to head (5561732).

Additional details and impacted files
@@            Coverage Diff             @@
##             main   #16213      +/-   ##
==========================================
- Coverage   94.56%   93.16%   -1.40%     
==========================================
  Files          10       10              
  Lines         717      717              
  Branches      118      118              
==========================================
- Hits          678      668      -10     
- Misses         25       29       +4     
- Partials       14       20       +6     

☔ View full report in Codecov by Harness.
📢 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.

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

Labels

ci Continue Integration ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant