Skip to content

Add show / set role default models - #16240

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
JinHai-CN:fix477
Jun 22, 2026
Merged

JinHai-CN merged 3 commits into
infiniflow:mainfrom
JinHai-CN:fix477

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jun 22, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(admin)> show role 'user' default models;
+--------------------------+-----------------------------------------------------------------+-----------+
| command                  | error                                                           | role_name |
+--------------------------+-----------------------------------------------------------------+-----------+
| show_role_default_models | 'show role default models' is implemented in enterprise edition | user      |
+--------------------------+-----------------------------------------------------------------+-----------+

RAGFlow(admin)> set role 'user' default chat 'glm4.5@test@zhipu-ai';
+------------+---------------------------------------------------------------+
| field      | value                                                         |
+------------+---------------------------------------------------------------+
| model_id   |                                                               |
| model_type | chat                                                          |
| role_name  | user                                                          |
| command    | set_role_default_model                                        |
| error      | 'set role default model' is implemented in enterprise edition |
+------------+---------------------------------------------------------------+

RAGFlow(admin)> reset role 'user' default chat;
+------------+-----------------------------------------------------------------+
| field      | value                                                           |
+------------+-----------------------------------------------------------------+
| command    | reset_role_default_model                                        |
| error      | 'reset role default model' is implemented in enterprise edition |
| model_type | chat                                                            |
| role_name  | user                                                            |
+------------+-----------------------------------------------------------------+

@coderabbitai

coderabbitai Bot commented Jun 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Provider/model listing handlers are relocated from handler.go to enterprise_handler.go. Three new role-scoped default model endpoints (show, set, reset) are added with service stubs and router wiring. The CLI gains matching parser grammar and command implementations. TokenStartup and DefaultModelResponse are removed.

Changes

Role Default Model Management

Layer / File(s) Summary
Remove TokenStartup and DefaultModelResponse
internal/cli/types.go, internal/cli/lexer.go, internal/service/tenant.go
TokenStartup is deleted from the token iota sequence and its lookupIdent case is removed, shifting subsequent token IDs. DefaultModelResponse struct is deleted from the tenant service.
Relocate provider/model handlers to enterprise_handler.go
internal/admin/handler.go, internal/admin/enterprise_handler.go, internal/admin/router.go
ListProviders, ShowProvider, ListModels, and ShowModel are removed from handler.go (dropping dao/strings imports) and added to enterprise_handler.go (adding dao/strings imports). The old /providers route group is removed from its earlier position in router.go and reintroduced later under a "Providers and models" section.
Role default model HTTP handlers, service stubs, and router wiring
internal/admin/enterprise_handler.go, internal/admin/enterprise_service.go, internal/admin/router.go
ShowRoleDefaultModels, SetRoleDefaultModel, and ResetRoleDefaultModel handlers are added with their request types. Corresponding Service methods return enterprise-edition stub payloads. Routes are registered under /roles/:role_name/default-models (GET, PATCH, DELETE).
CLI parser grammar for role-scoped default model commands
internal/cli/admin_parser.go, internal/cli/parser.go
parseAdminShowCommand is renamed to parseAdminShowCommands. parseAdminShowRole gains a DEFAULT MODELS branch emitting admin_show_role_default_models. parseAdminSetDefault is replaced by parseAdminSetRoleDefaultModel (role-scoped). parseAdminResetCommand is updated to require ROLE <role_name> before DEFAULT. Parser dispatch is updated to call the renamed show method.
CLI command implementations and dispatch
internal/cli/admin_command.go, internal/cli/cli_http.go
AdminSetRoleDefaultModelsCommand, AdminResetRoleDefaultModelsCommand, and AdminShowRoleDefaultModelsCommand are implemented, each enforcing admin auth checks and issuing the respective HTTP method to /admin/roles/{role_name}/default-models. ExecuteAdminCommand is extended with three new routing cases.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Suggested labels

💞 feature, size:L

Poem

🐰 Hop hop! A role now has its own model throne,
The providers moved to enterprise's home,
The parser speaks new words: ROLE, DEFAULT, SET,
The CLI commands are ready, no need to fret!
TokenStartup hops away, quietly gone—
The rabbit's work is done, the feature lives on! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides concrete examples of the commands being added but lacks structured explanation required by the template. It is missing a clear 'What problem does this PR solve' narrative and doesn't specify the type of change. Add context explaining why role default models are needed, provide a clear narrative in the 'What problem does this PR solve' section, and select the appropriate change type (appears to be 'New Feature').
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and specifically summarizes the main changes: adding show/set role default models functionality, which aligns with the primary additions across handler, service, CLI, and parser files.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 marked this pull request as ready for review June 22, 2026 10:33
@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 22, 2026
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 22, 2026

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

🤖 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 232-233: The success message "Role default model set successfully"
is being used for multiple operations including show and reset handlers on lines
232 and 291, but this message is only semantically correct for the set
operation. Replace the success message on line 232 and line 291 with
operation-specific messages that accurately describe what each handler does,
such as using appropriate messages for show and reset operations instead of the
generic set message.
- Around line 303-320: The handler function is missing a response when the
keywords parameter is not equal to "true", causing the function to fall through
and return an empty 200 response body instead of a proper JSON response. Add a
fallback response after the if block that checks if keywords equals "true" to
handle the case when this condition is false, ensuring that a properly formatted
JSON response with the standard {code, message, data} envelope is always
returned to the client, similar to the success response structure already
present in the ListProviders handler.

In `@internal/admin/enterprise_service.go`:
- Around line 146-154: The SetRoleDefaultModel function signature only accepts
modelID as a parameter, but downstream command flow can send modelName instead,
causing valid requests to be rejected at the boundary. Update the
SetRoleDefaultModel method to accept both modelID and modelName as parameters,
and implement one-of validation to ensure at least one is provided.
Additionally, update the request binding and validation in enterprise_handler.go
to extract both fields from the incoming request and pass them to the
SetRoleDefaultModel service call with proper one-of validation logic.

In `@internal/cli/admin_command.go`:
- Around line 1097-1107: The PATCH payload being constructed in the
admin_command.go code is setting model_name when a composite_model_name is
provided, but the server's SetRoleDefaultModelRequest struct in
internal/admin/enterprise_handler.go only binds model_id and model_type, causing
the model selection to be lost. Either update the SetRoleDefaultModelRequest
struct to accept and handle model_name in addition to model_id and model_type,
ensuring the service layer properly resolves the model by name, or remove the
composite_model_name parsing logic entirely and only support model_id in this
command path. Choose the approach that aligns with your system's long-term
design goals.

In `@internal/cli/admin_parser.go`:
- Around line 544-566: The switch statement in parseAdminShowRole currently only
creates the admin_show_role command when TokenSemicolon is encountered, which
breaks the optional semicolon behavior. To fix this, move the admin_show_role
command creation from the TokenSemicolon case to the default case so that when
no special keywords (PERMISSION or DEFAULT) follow the role name, the bare
admin_show_role command is emitted regardless of whether a semicolon is present.
This preserves backward compatibility with commands like SHOW ROLE 'user' that
don't require a trailing semicolon.
🪄 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: 562ca665-80fa-4698-9b31-1ad608104d50

📥 Commits

Reviewing files that changed from the base of the PR and between 9eb7cee and af8418c.

📒 Files selected for processing (11)
  • internal/admin/enterprise_handler.go
  • internal/admin/enterprise_service.go
  • internal/admin/handler.go
  • internal/admin/router.go
  • internal/cli/admin_command.go
  • internal/cli/admin_parser.go
  • internal/cli/cli_http.go
  • internal/cli/lexer.go
  • internal/cli/parser.go
  • internal/cli/types.go
  • internal/service/tenant.go
💤 Files with no reviewable changes (4)
  • internal/cli/types.go
  • internal/cli/lexer.go
  • internal/service/tenant.go
  • internal/admin/handler.go

Comment on lines +232 to +233
success(c, result, "Role default model set successfully")
}

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

Use operation-specific success messages for show/reset handlers.

Line 232 and Line 291 both return "Role default model set successfully", which is misleading for show and reset operations.

💡 Proposed fix
- success(c, result, "Role default model set successfully")
+ success(c, result, "Role default models retrieved successfully")
...
- success(c, result, "Role default model set successfully")
+ success(c, result, "Role default model reset successfully")

Also applies to: 291-292

🤖 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 232 - 233, The success
message "Role default model set successfully" is being used for multiple
operations including show and reset handlers on lines 232 and 291, but this
message is only semantically correct for the set operation. Replace the success
message on line 232 and line 291 with operation-specific messages that
accurately describe what each handler does, such as using appropriate messages
for show and reset operations instead of the generic set message.

Comment on lines +303 to +320
if keywords == "true" {
// list pool providers
providers, err := dao.GetModelProviderManager().ListProviders()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": common.CodeNotFound,
"message": err.Error(),
})
return
}

c.JSON(http.StatusOK, gin.H{
"code": 0,
"message": "success",
"data": providers,
})
}
}

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

ListProviders can return an empty HTTP 200 response body.

When available is missing or not "true", execution falls through without writing any response. This creates a non-JSON 200 response that can break callers expecting the standard {code,message,data} envelope.

💡 Proposed fix
 func (h *Handler) ListProviders(c *gin.Context) {
@@
 	keywords = strings.ToLower(keywords)
-	if keywords == "true" {
+	if keywords == "true" {
 		// list pool providers
 		providers, err := dao.GetModelProviderManager().ListProviders()
@@
 		c.JSON(http.StatusOK, gin.H{
 			"code":    0,
 			"message": "success",
 			"data":    providers,
 		})
+		return
 	}
+
+	c.JSON(http.StatusBadRequest, gin.H{
+		"code":    common.CodeBadRequest,
+		"message": "query parameter available=true is required",
+		"data":    nil,
+	})
 }
📝 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
if keywords == "true" {
// list pool providers
providers, err := dao.GetModelProviderManager().ListProviders()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": common.CodeNotFound,
"message": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"message": "success",
"data": providers,
})
}
}
if keywords == "true" {
// list pool providers
providers, err := dao.GetModelProviderManager().ListProviders()
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": common.CodeNotFound,
"message": err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"code": 0,
"message": "success",
"data": providers,
})
return
}
c.JSON(http.StatusBadRequest, gin.H{
"code": common.CodeBadRequest,
"message": "query parameter available=true is required",
"data": 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/admin/enterprise_handler.go` around lines 303 - 320, The handler
function is missing a response when the keywords parameter is not equal to
"true", causing the function to fall through and return an empty 200 response
body instead of a proper JSON response. Add a fallback response after the if
block that checks if keywords equals "true" to handle the case when this
condition is false, ensuring that a properly formatted JSON response with the
standard {code, message, data} envelope is always returned to the client,
similar to the success response structure already present in the ListProviders
handler.

Comment on lines +146 to +154
func (s *Service) SetRoleDefaultModel(roleName, modelID, modelType string) (map[string]interface{}, error) {
return map[string]interface{}{
"command": "set_role_default_model",
"role_name": roleName,
"model_id": modelID,
"model_type": modelType,
"error": "'set role default model' is implemented in enterprise edition",
}, nil
}

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 | 🏗️ Heavy lift

SetRoleDefaultModel contract drops model_name callers.

Line 146 only accepts modelID, but downstream command flow can send model_name instead of model_id. That payload cannot be represented through this method contract, so one valid request form is lost across the handler/service boundary.

💡 Proposed fix
- func (s *Service) SetRoleDefaultModel(roleName, modelID, modelType string) (map[string]interface{}, error) {
- 	return map[string]interface{}{
+ func (s *Service) SetRoleDefaultModel(roleName, modelID, modelName, modelType string) (map[string]interface{}, error) {
+ 	result := map[string]interface{}{
 		"command":    "set_role_default_model",
 		"role_name":  roleName,
-		"model_id":   modelID,
 		"model_type": modelType,
 		"error":      "'set role default model' is implemented in enterprise edition",
-	}, nil
+	}
+	if modelID != "" {
+		result["model_id"] = modelID
+	}
+	if modelName != "" {
+		result["model_name"] = modelName
+	}
+	return result, nil
 }

Also update internal/admin/enterprise_handler.go request binding/validation and service call to pass model_name (with one-of validation for model_id vs model_name).

🤖 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_service.go` around lines 146 - 154, The
SetRoleDefaultModel function signature only accepts modelID as a parameter, but
downstream command flow can send modelName instead, causing valid requests to be
rejected at the boundary. Update the SetRoleDefaultModel method to accept both
modelID and modelName as parameters, and implement one-of validation to ensure
at least one is provided. Additionally, update the request binding and
validation in enterprise_handler.go to extract both fields from the incoming
request and pass them to the SetRoleDefaultModel service call with proper one-of
validation logic.

Comment on lines +1097 to +1107
var modelName string
modelID, ok := cmd.Params["model_id"].(string)
if ok {
payload["model_id"] = modelID
} else {
modelName, ok = cmd.Params["composite_model_name"].(string)
if ok {
payload["model_name"] = modelName
} else {
return nil, fmt.Errorf("model_id or model_name not provided")
}

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 | 🏗️ Heavy lift

Align PATCH payload with server request contract.

Line 1104 sends model_name, but the PATCH handler binds only model_id and model_type (internal/admin/enterprise_handler.go SetRoleDefaultModelRequest). For composite-name inputs, the selected model is dropped at the API boundary.

💡 Suggested direction
-		modelName, ok = cmd.Params["composite_model_name"].(string)
-		if ok {
-			payload["model_name"] = modelName
-		} else {
+		modelName, ok = cmd.Params["composite_model_name"].(string)
+		if ok {
+			return nil, fmt.Errorf("composite_model_name is not supported by this endpoint; use model_id")
+		} else {
 			return nil, fmt.Errorf("model_id or model_name not provided")
 		}

Preferred long-term fix is to update the HTTP request contract to explicitly accept model name (and propagate it through service), or remove composite-name parsing for this command path.

📝 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
var modelName string
modelID, ok := cmd.Params["model_id"].(string)
if ok {
payload["model_id"] = modelID
} else {
modelName, ok = cmd.Params["composite_model_name"].(string)
if ok {
payload["model_name"] = modelName
} else {
return nil, fmt.Errorf("model_id or model_name not provided")
}
var modelName string
modelID, ok := cmd.Params["model_id"].(string)
if ok {
payload["model_id"] = modelID
} else {
modelName, ok = cmd.Params["composite_model_name"].(string)
if ok {
return nil, fmt.Errorf("composite_model_name is not supported by this endpoint; use model_id")
} else {
return nil, fmt.Errorf("model_id or model_name 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` around lines 1097 - 1107, The PATCH payload
being constructed in the admin_command.go code is setting model_name when a
composite_model_name is provided, but the server's SetRoleDefaultModelRequest
struct in internal/admin/enterprise_handler.go only binds model_id and
model_type, causing the model selection to be lost. Either update the
SetRoleDefaultModelRequest struct to accept and handle model_name in addition to
model_id and model_type, ensuring the service layer properly resolves the model
by name, or remove the composite_model_name parsing logic entirely and only
support model_id in this command path. Choose the approach that aligns with your
system's long-term design goals.

Comment on lines 544 to 566
var cmd *Command
if p.curToken.Type == TokenPermission {

switch p.curToken.Type {
case TokenPermission:
p.nextToken()
cmd = NewCommand("admin_show_role_permission")
cmd.Params["role_name"] = roleName
} else {
case TokenDefault:
p.nextToken()
if p.curToken.Type != TokenModels {
return nil, fmt.Errorf("expect MODELS after DEFAULT")
}
p.nextToken()
cmd = NewCommand("admin_show_role_default_models")
cmd.Params["role_name"] = roleName
case TokenSemicolon:
p.nextToken()
cmd = NewCommand("admin_show_role")
cmd.Params["role_name"] = roleName
default:
return nil, fmt.Errorf("invalid command %s", tokenTypeToString(p.curToken.Type))
}

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

Preserve semicolon-optional behavior for bare SHOW ROLE.

parseAdminShowRole now only emits admin_show_role when it sees TokenSemicolon (Line 559). That makes SHOW ROLE 'user' fail when no ; is present, which regresses the previous optional-terminator behavior.

💡 Suggested patch
 switch p.curToken.Type {
 case TokenPermission:
 	p.nextToken()
 	cmd = NewCommand("admin_show_role_permission")
 	cmd.Params["role_name"] = roleName
 case TokenDefault:
 	p.nextToken()
 	if p.curToken.Type != TokenModels {
 		return nil, fmt.Errorf("expect MODELS after DEFAULT")
 	}
 	p.nextToken()
 	cmd = NewCommand("admin_show_role_default_models")
 	cmd.Params["role_name"] = roleName
-case TokenSemicolon:
-	p.nextToken()
+case TokenSemicolon, TokenEOF:
 	cmd = NewCommand("admin_show_role")
 	cmd.Params["role_name"] = roleName
 default:
 	return nil, fmt.Errorf("invalid command %s", tokenTypeToString(p.curToken.Type))
 }
+
+if p.curToken.Type == TokenSemicolon {
+	p.nextToken()
+}
📝 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
var cmd *Command
if p.curToken.Type == TokenPermission {
switch p.curToken.Type {
case TokenPermission:
p.nextToken()
cmd = NewCommand("admin_show_role_permission")
cmd.Params["role_name"] = roleName
} else {
case TokenDefault:
p.nextToken()
if p.curToken.Type != TokenModels {
return nil, fmt.Errorf("expect MODELS after DEFAULT")
}
p.nextToken()
cmd = NewCommand("admin_show_role_default_models")
cmd.Params["role_name"] = roleName
case TokenSemicolon:
p.nextToken()
cmd = NewCommand("admin_show_role")
cmd.Params["role_name"] = roleName
default:
return nil, fmt.Errorf("invalid command %s", tokenTypeToString(p.curToken.Type))
}
var cmd *Command
switch p.curToken.Type {
case TokenPermission:
p.nextToken()
cmd = NewCommand("admin_show_role_permission")
cmd.Params["role_name"] = roleName
case TokenDefault:
p.nextToken()
if p.curToken.Type != TokenModels {
return nil, fmt.Errorf("expect MODELS after DEFAULT")
}
p.nextToken()
cmd = NewCommand("admin_show_role_default_models")
cmd.Params["role_name"] = roleName
case TokenSemicolon, TokenEOF:
cmd = NewCommand("admin_show_role")
cmd.Params["role_name"] = roleName
default:
return nil, fmt.Errorf("invalid command %s", tokenTypeToString(p.curToken.Type))
}
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
🤖 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_parser.go` around lines 544 - 566, The switch statement in
parseAdminShowRole currently only creates the admin_show_role command when
TokenSemicolon is encountered, which breaks the optional semicolon behavior. To
fix this, move the admin_show_role command creation from the TokenSemicolon case
to the default case so that when no special keywords (PERMISSION or DEFAULT)
follow the role name, the bare admin_show_role command is emitted regardless of
whether a semicolon is present. This preserves backward compatibility with
commands like SHOW ROLE 'user' that don't require a trailing semicolon.

@JinHai-CN
JinHai-CN merged commit 0e6b28a into infiniflow:main Jun 22, 2026
15 checks passed
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. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant