Skip to content

Go: new CLI command, list all models and show model - #15786

Merged
JinHai-CN merged 5 commits into
infiniflow:mainfrom
JinHai-CN:fix447
Jun 8, 2026
Merged

JinHai-CN merged 5 commits into
infiniflow:mainfrom
JinHai-CN:fix447

Conversation

@JinHai-CN

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

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(user)> list models;
+---------------------------+------------+-------------+--------------------+---------------------------------------------+
| alias                     | max_tokens | model_types | name               | thinking                                    |
+---------------------------+------------+-------------+--------------------+---------------------------------------------+
|                           | 1048576    | [chat]      | deepseek-v4-flash  | map[clear_thinking:true default_value:true] |
|                           | 1048576    | [chat]      | deepseek-v4-pro    | map[clear_thinking:true default_value:true] |
|                           | 1024000    | [chat]      | minimax-m3         | map[clear_thinking:true default_value:true] |
|                           | 64000      | [vision]    | glm-4.5v           | map[clear_thinking:true default_value:true] |
| [baai/bge-m3]             | 8192       | [embedding] | bge-m3             |                                             |
| [baai/bge-reranker-v2-m3] | 1024       | [rerank]    | bge-reranker-v2-m3 |                                             |
|                           |            | [tts]       | step-audio-tts-3b  |                                             |
| [qwen/qwen3-asr-1.7b]     |            | [asr]       | qwen3-asr-1.7b     |                                             |
| [paddleocr-vl-1.5]        |            | [ocr]       | paddleocr-vl-0.9b  |                                             |
+---------------------------+------------+-------------+--------------------+---------------------------------------------+
RAGFlow(user)> show model 'minimax-m3';
+--------------+---------------------------------------------+
| field        | value                                       |
+--------------+---------------------------------------------+
| name         | minimax-m3                                  |
| max_tokens   | 1024000                                     |
| model_types  | [chat]                                      |
| thinking     | map[clear_thinking:true default_value:true] |
| class        |                                             |
| alias        |                                             |
| ModelTypeMap |                                             |
+--------------+---------------------------------------------+
RAGFlow(user)> show model 'baai/bge-m3';
+--------------+---------------+
| field        | value         |
+--------------+---------------+
| model_types  | [embedding]   |
| thinking     |               |
| class        |               |
| alias        | [baai/bge-m3] |
| ModelTypeMap |               |
| name         | bge-m3        |
| max_tokens   | 8192          |
+--------------+---------------+

@coderabbitai

coderabbitai Bot commented Jun 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a global model catalog loaded from conf/all_models.json, exposes ListAllModels and ShowModel in the service layer, adds a ModelHandler and protected GET /api/v1/models/all-models route, updates CLI parsing/execution for LIST/SHOW MODEL, wires modelHandler into server startup, and refactors AddModel variable shadowing.

Changes

Global Model Catalog Feature

Layer / File(s) Summary
Model catalog schema and configuration loading
internal/entity/model.go, conf/all_models.json, conf/models/minimax.json
Model gains Alias []string; ProviderManager loads global catalog into AllModels and builds Alias2ModelIndex from conf/all_models.json; MiniMax-M3 max_tokens raised to 1024000.
Service methods and AddModel fixes
internal/service/model_service.go, internal/entity/model.go
ModelProviderService.ListAllModels() and ShowModel() added; AddModel refactored to avoid variable shadowing and reuse outer err/modelID assignments.
HTTP handler for models
internal/handler/models.go
New ModelHandler and ListAllModels Gin endpoint bind ShowModelRequest and return either paginated model lists or a single model by name.
Router wiring and endpoint
internal/router/router.go
Router now accepts and stores modelHandler; GET /api/v1/models/all-models added and delegates to modelHandler.ListAllModels.
CLI parsing changes
internal/cli/user_parser.go
parseShowModel branches on FROM; parseListAllModels added; LIST MODELS without FROM now returns list_all_models.
CLI execution and routing
internal/cli/common_command.go, internal/cli/client.go
ShowModel renamed to ShowProviderModel; new ListAllModels command queries /all-models; ExecuteAdminCommand/ExecuteUserCommand route new command types.
Server initialization
cmd/server_main.go
Server initializes modelHandler via handler.NewModelHandler(service.NewModelProviderService()) and passes it into router.NewRouter().
CI workflow
.github/workflows/tests.yml
Test resource preparation and Go test steps were commented out, disabling those workflow steps.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

💞 feature

Suggested reviewers

  • Haruko386

Poem

🐰 A catalog blooms, models gathered one by one,
LIST and SHOW now call them out beneath the sun,
Configs loaded, handlers set to run,
A rabbit cheers — the model list is done! 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description provides only example command outputs without explaining the problem, solution, or change type required by the template. Add a brief explanation of what problem this PR solves and select the appropriate type of change (New Feature) from the template checklist.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main changes: adding new CLI commands for listing all models and showing model details.
Docstring Coverage ✅ Passed Docstring coverage is 80.00% which is sufficient. The required threshold is 80.00%.
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 self-assigned this Jun 8, 2026
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 8, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 8, 2026 12:40
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jun 8, 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: 4

🧹 Nitpick comments (4)
internal/service/model_service.go (1)

2426-2437: 💤 Low value

Consider case-insensitive model name matching for consistency.

Line 2432 uses exact string comparison (model["name"] == modelName). The rest of the codebase—FindProvider (line 675–676 in model.go) and findModel (line 685–686)—uses strings.EqualFold for case-insensitive matching. Applying the same convention here would make SHOW MODEL behavior consistent with provider/model lookups elsewhere.

♻️ Suggested consistency fix
 	for _, model := range models {
-		if model["name"] == modelName {
+		if name, ok := model["name"].(string); ok && strings.EqualFold(name, modelName) {
 			return model, 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/service/model_service.go` around lines 2426 - 2437, ShowModel
currently uses exact comparison (model["name"] == modelName) which is
inconsistent with FindProvider/findModel; change ShowModel to perform
case-insensitive matching using strings.EqualFold on the model name (e.g.,
extract the name from model["name"] as a string and call
strings.EqualFold(nameStr, modelName)). Ensure you handle the type assertion
safely (check that model["name"] is a string before comparing) and add the
strings import if not already present.
internal/entity/model.go (1)

367-369: ⚡ Quick win

Prefer returning an empty array over an error when no models are found.

Returning fmt.Errorf("no models found") at line 368 when the catalog is empty forces callers to distinguish between operational failures and "no data" states. Standard REST practice is to return a 200 OK with an empty array [] when a query succeeds but yields no results.

♻️ Suggested refactor
 	}
 
-	if len(modelList) == 0 {
-		return nil, fmt.Errorf("no models found")
-	}
-
 	return modelList, 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/entity/model.go` around lines 367 - 369, The function currently
returns an error when modelList is empty; change it to return an empty slice and
nil error instead so callers get a successful result with no items. Replace the
fmt.Errorf("no models found") return with a return of an empty slice matching
the function's model type (e.g., return []Model{}, nil or return modelList, nil
if modelList is already an empty slice) in the function that references
modelList so callers receive [] rather than an error.
internal/cli/common_command.go (2)

512-548: ⚡ Quick win

Consider using query parameters instead of request body for GET request.

Line 529 sends a GET request with a JSON payload body (page and page_size). While this may work, it's non-standard HTTP practice—GET requests typically use query parameters for filtering/pagination. Many HTTP clients, proxies, and servers treat GET request bodies as undefined behavior per RFC 7231.

Consider refactoring to use query parameters:

endPoint := fmt.Sprintf("/all-models?page=%d&page_size=%d", page, pageSize)
resp, err := c.HTTPClient.Request("GET", endPoint, "web", nil, nil)

Also verify that page=0 and page_size=0 produce the expected API behavior (e.g., return all results or use server defaults) when pagination parameters are not explicitly 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/common_command.go` around lines 512 - 548, In ListAllModels,
move pagination values page and pageSize out of the request body and put them
into the GET URL query string (build an endpoint like
"/all-models?page=<page>&page_size=<pageSize>") and call c.HTTPClient.Request
with nil payload instead of sending a JSON body; keep handling of resp, error,
JSON unmarshal (CommonResponse) and result checks the same, and confirm how
page=0 and page_size=0 should behave with the API (omit params or rely on server
defaults if needed).

550-580: ⚡ Quick win

Consider using query parameters for GET request.

Line 561 sends a GET request with model_name in the request body. As noted in ListAllModels, GET requests with body payloads are non-standard. Consider using query parameters:

endPoint := fmt.Sprintf("/all-models?model_name=%s", url.QueryEscape(modelName))
resp, err := c.HTTPClient.Request("GET", endPoint, "web", nil, nil)

Also note that this method expects CommonDataResponse (single model) while ListAllModels expects CommonResponse (model list), yet both query the same /all-models endpoint. Verify that the API endpoint correctly returns different response structures based on whether model_name is 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/common_command.go` around lines 550 - 580, ShowModel is sending
model_name in the GET body (non-standard) and expects CommonDataResponse while
ListAllModels hits the same /all-models endpoint with a different response type;
change ShowModel to put model_name into the URL query (build endPoint using
url.QueryEscape(modelName)) and call c.HTTPClient.Request("GET", endPoint,
"web", nil, nil) so the body is nil, then keep unmarshalling into
CommonDataResponse; also verify the API actually returns a single-model
CommonDataResponse when model_name is present and adjust the expected response
type (CommonDataResponse vs CommonResponse) accordingly in ShowModel or
ListAllModels if needed.
🤖 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 `@conf/all_models.json`:
- Around line 25-35: The model name casing in conf/all_models.json
("minimax-m3") doesn't match conf/models/minimax.json and
conf/llm_factories.json ("MiniMax-M3"), causing ShowModel (the model lookup
path) to fail due to exact string equality; fix by either updating the name in
conf/all_models.json to "MiniMax-M3" to match the provider configs, or make the
ShowModel lookup case-insensitive (use strings.EqualFold) so model["name"]
comparisons match regardless of case—update references to the "minimax-m3" entry
and the ShowModel function accordingly.

In `@internal/entity/model.go`:
- Around line 288-307: NewProviderManager is reading a hardcoded runtime file
path ("conf/all_models.json"), which fails if the working directory changes;
change it to load models from a non-relative source by either (A) using the
embed package to embed conf/all_models.json at build time (declare a
package-level variable via //go:embed conf/all_models.json and use that data
instead of os.ReadFile) or (B) accept a file path or io.Reader argument in
NewProviderManager (e.g., add a parameter modelsJSONPath string or modelsReader
io.Reader) and use that to read/parse the JSON; update the JSON unmarshalling
code (type AllModels/var allModels) to use the embedded bytes or passed reader,
and update any callers/tests of NewProviderManager to pass the embedded data or
explicit path accordingly.

In `@internal/router/router.go`:
- Around line 378-381: The route for listing models is registered on the v1
group (v1.Group("/all-models")) which yields /api/v1/all-models but the CLI
calls /all-models; fix by moving the allModels registration out of the v1 group
into the parent authorized group (register allModels :=
authorized.Group("/all-models") and call allModels.GET("",
r.modelHandler.ListAllModels)) so the endpoint path matches the CLI, or
alternatively update the CLI to request /api/v1/all-models; ensure you modify
the registration that creates allModels and keep the handler
r.modelHandler.ListAllModels unchanged.

In `@internal/service/model_service.go`:
- Around line 2415-2424: In ListAllModels, the code slices models with
models[pageIndex*pageSize:(pageIndex+1)*pageSize] without bounds checks which
can panic; validate and clamp indices: ensure pageIndex and pageSize are
non-negative, compute start = pageIndex * pageSize and end = start + pageSize,
clamp start = min(max(start, 0), len(models)) and end = min(max(end, 0),
len(models)), if start >= len(models) return an empty slice, otherwise return
models[start:end]; keep existing behavior of returning models when pageSize <=
0.

---

Nitpick comments:
In `@internal/cli/common_command.go`:
- Around line 512-548: In ListAllModels, move pagination values page and
pageSize out of the request body and put them into the GET URL query string
(build an endpoint like "/all-models?page=<page>&page_size=<pageSize>") and call
c.HTTPClient.Request with nil payload instead of sending a JSON body; keep
handling of resp, error, JSON unmarshal (CommonResponse) and result checks the
same, and confirm how page=0 and page_size=0 should behave with the API (omit
params or rely on server defaults if needed).
- Around line 550-580: ShowModel is sending model_name in the GET body
(non-standard) and expects CommonDataResponse while ListAllModels hits the same
/all-models endpoint with a different response type; change ShowModel to put
model_name into the URL query (build endPoint using url.QueryEscape(modelName))
and call c.HTTPClient.Request("GET", endPoint, "web", nil, nil) so the body is
nil, then keep unmarshalling into CommonDataResponse; also verify the API
actually returns a single-model CommonDataResponse when model_name is present
and adjust the expected response type (CommonDataResponse vs CommonResponse)
accordingly in ShowModel or ListAllModels if needed.

In `@internal/entity/model.go`:
- Around line 367-369: The function currently returns an error when modelList is
empty; change it to return an empty slice and nil error instead so callers get a
successful result with no items. Replace the fmt.Errorf("no models found")
return with a return of an empty slice matching the function's model type (e.g.,
return []Model{}, nil or return modelList, nil if modelList is already an empty
slice) in the function that references modelList so callers receive [] rather
than an error.

In `@internal/service/model_service.go`:
- Around line 2426-2437: ShowModel currently uses exact comparison
(model["name"] == modelName) which is inconsistent with FindProvider/findModel;
change ShowModel to perform case-insensitive matching using strings.EqualFold on
the model name (e.g., extract the name from model["name"] as a string and call
strings.EqualFold(nameStr, modelName)). Ensure you handle the type assertion
safely (check that model["name"] is a string before comparing) and add the
strings import if not already present.
🪄 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: d83b83ac-bf75-4cd0-9f33-f979f12941d3

📥 Commits

Reviewing files that changed from the base of the PR and between f2aadd3 and 62677f0.

📒 Files selected for processing (9)
  • cmd/server_main.go
  • conf/all_models.json
  • conf/models/minimax.json
  • internal/cli/client.go
  • internal/cli/common_command.go
  • internal/cli/user_parser.go
  • internal/entity/model.go
  • internal/router/router.go
  • internal/service/model_service.go

Comment thread conf/all_models.json Resolved
Comment thread internal/entity/model.go
Comment on lines +288 to 307
// Read the file
var data []byte
data, err = os.ReadFile("conf/all_models.json")
if err != nil {
return nil, fmt.Errorf("error reading file 'conf/all_models.json': %w", err)
}

// Parse JSON
type AllModels struct {
Models []Model `json:"models"`
}
var allModels AllModels
if err = json.Unmarshal(data, &allModels); err != nil {
return nil, fmt.Errorf("error parsing JSON from file 'conf/all_models.json': %w", err)
}

return &ProviderManager{
Providers: providers,
AllModels: allModels.Models,
}, 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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify that conf/all_models.json exists and is valid JSON
if [ -f "conf/all_models.json" ]; then
  echo "✓ conf/all_models.json exists"
  jq empty conf/all_models.json 2>/dev/null && echo "✓ Valid JSON" || echo "✗ Invalid JSON"
else
  echo "✗ conf/all_models.json is missing"
fi

Repository: infiniflow/ragflow

Length of output: 105


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Show the exact code around the referenced lines
echo "=== internal/entity/model.go (around 270-330) ==="
nl -ba internal/entity/model.go | sed -n '260,340p'

# Find all references to conf/all_models.json
echo
echo "=== References to conf/all_models.json ==="
rg -n "conf/all_models\.json" -S .

# Search for ProviderManager/NewProviderManager context (best effort)
echo
echo "=== References to NewProviderManager / ProviderManager in internal/entity/model.go ==="
rg -n "NewProviderManager|ProviderManager" internal/entity/model.go

Repository: infiniflow/ragflow

Length of output: 173


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE="internal/entity/model.go"
if [ ! -f "$FILE" ]; then
  echo "Missing $FILE"
  exit 1
fi

echo "=== $FILE (around 270-340) ==="
# Use cat -n to include line numbers (nl is unavailable)
cat -n "$FILE" | sed -n '270,340p'

echo
echo "=== References to conf/all_models.json ==="
rg -n "conf/all_models\.json" -S .

echo
echo "=== References to NewProviderManager / ProviderManager in $FILE ==="
rg -n "NewProviderManager|type ProviderManager|ProviderManager" "$FILE"

Repository: infiniflow/ragflow

Length of output: 4208


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== conf/ directory (top-level) ==="
ls -la conf || true
echo
find conf -maxdepth 2 -type f -print || true

echo
echo "=== References to NewProviderManager(...) across repo ==="
rg -n "NewProviderManager\s*\(" -S .

echo
echo "=== internal/entity/model.go: function header + nearby code for NewProviderManager ==="
# Print a larger chunk around function definition using sed range
cat -n internal/entity/model.go | sed -n '150,340p'

Repository: infiniflow/ragflow

Length of output: 10439


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== internal/dao/database.go (around 130-220) ==="
cat -n internal/dao/database.go | sed -n '130,220p'

echo
echo "=== References to os.ReadFile(\"conf/\" in repo ==="
rg -n "os\.ReadFile\(\s*\"conf/" -S .

echo
echo "=== References to \"conf/\" paths in repo (high signal) ==="
rg -n "\"conf/[^\"\\n]+\"" -S internal | head -n 50

Repository: infiniflow/ragflow

Length of output: 4225


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== internal/service/user.go around 620-700 ==="
cat -n internal/service/user.go | sed -n '620,700p'

echo
echo "=== internal/admin/password.go around 160-240 ==="
cat -n internal/admin/password.go | sed -n '160,240p'

echo
echo "=== internal/engine/elasticsearch/chunk.go references to conf/skill_es_mapping.json (around 1860-1910) ==="
cat -n internal/engine/elasticsearch/chunk.go | sed -n '1860,1910p'

Repository: infiniflow/ragflow

Length of output: 7866


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "=== internal/entity/model_test.go (relevant parts) ==="
rg -n "NewProviderManager\(" internal/entity/model_test.go
echo
cat -n internal/entity/model_test.go | sed -n '1,120p'
echo
cat -n internal/entity/model_test.go | sed -n '120,260p'
echo
cat -n internal/entity/model_test.go | sed -n '260,360p'

Repository: infiniflow/ragflow

Length of output: 13307


Fix hardcoded relative dependency for conf/all_models.json

conf/all_models.json is present in the repo and contains valid JSON, so the “missing/malformed in-repo” concern doesn’t apply. However, NewProviderManager still hardcodes a relative runtime path (os.ReadFile("conf/all_models.json")) and will log.Fatal on any read/parse failure, so startup can break if the working directory at runtime isn’t the repo root or if conf/ isn’t deployed alongside the binary.

🤖 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/entity/model.go` around lines 288 - 307, NewProviderManager is
reading a hardcoded runtime file path ("conf/all_models.json"), which fails if
the working directory changes; change it to load models from a non-relative
source by either (A) using the embed package to embed conf/all_models.json at
build time (declare a package-level variable via //go:embed conf/all_models.json
and use that data instead of os.ReadFile) or (B) accept a file path or io.Reader
argument in NewProviderManager (e.g., add a parameter modelsJSONPath string or
modelsReader io.Reader) and use that to read/parse the JSON; update the JSON
unmarshalling code (type AllModels/var allModels) to use the embedded bytes or
passed reader, and update any callers/tests of NewProviderManager to pass the
embedded data or explicit path accordingly.

Comment thread internal/router/router.go
Comment on lines +378 to +381
allModels := v1.Group("/all-models")
{
allModels.GET("", r.modelHandler.ListAllModels)
}

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

Path mismatch: endpoint registered at /api/v1/all-models but CLI expects /all-models.

The new route is registered under the v1 group (line 179: /api/v1) as /all-models, yielding the full path /api/v1/all-models. However, the CLI client in internal/cli/common_command.go:516 requests GET /all-models directly. This mismatch will cause all CLI LIST MODELS commands to return 404. Either:

  • Change line 378 to register outside the v1 group (under authorized directly), or
  • Update the CLI to call /api/v1/all-models
🔧 Option 1: Move endpoint outside v1 group
 			model := v1.Group("/models")
 			{
 				model.GET("/", r.tenantHandler.GetModels)
 				model.PATCH("/", r.tenantHandler.SetModels)
 			}
 
-			allModels := v1.Group("/all-models")
+		}
+		
+		// Global model catalog (no /api/v1 prefix to match CLI expectation)
+		allModels := authorized.Group("/all-models")
+		{
-			{
 				allModels.GET("", r.modelHandler.ListAllModels)
-			}
+		}
 
+		v1 := authorized.Group("/api/v1")
+		{
 			// Agent routes
🔧 Option 2: Update CLI to use /api/v1/all-models

In internal/cli/common_command.go:

-	resp, err := c.HTTPClient.Request("GET", "/all-models", "web", nil, payload)
+	resp, err := c.HTTPClient.Request("GET", "/api/v1/all-models", "web", nil, payload)
🤖 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/router/router.go` around lines 378 - 381, The route for listing
models is registered on the v1 group (v1.Group("/all-models")) which yields
/api/v1/all-models but the CLI calls /all-models; fix by moving the allModels
registration out of the v1 group into the parent authorized group (register
allModels := authorized.Group("/all-models") and call allModels.GET("",
r.modelHandler.ListAllModels)) so the endpoint path matches the CLI, or
alternatively update the CLI to request /api/v1/all-models; ensure you modify
the registration that creates allModels and keep the handler
r.modelHandler.ListAllModels unchanged.

Comment on lines +2415 to +2424
func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) {
models, err := dao.GetModelProviderManager().ListAllModels()
if err != nil {
return nil, err
}
if pageSize > 0 {
return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil
}
return models, 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 | 🔴 Critical | ⚡ Quick win

Add bounds checking before slicing the models array.

Lines 2420–2421 perform unchecked slice operations: models[pageIndex*pageSize : (pageIndex+1)*pageSize]. If pageIndex or pageSize are out of range, this will panic at runtime. Validate inputs and clamp the slice indices to prevent crashes.

🛡️ Proposed bounds checking
 func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) {
 	models, err := dao.GetModelProviderManager().ListAllModels()
 	if err != nil {
 		return nil, err
 	}
-	if pageSize > 0 {
-		return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil
+	if pageSize > 0 && pageIndex >= 0 {
+		start := pageIndex * pageSize
+		end := start + pageSize
+		if start >= len(models) {
+			return []map[string]interface{}{}, nil
+		}
+		if end > len(models) {
+			end = len(models)
+		}
+		return models[start:end], nil
 	}
 	return models, 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
func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) {
models, err := dao.GetModelProviderManager().ListAllModels()
if err != nil {
return nil, err
}
if pageSize > 0 {
return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil
}
return models, nil
}
func (m *ModelProviderService) ListAllModels(pageIndex, pageSize int) ([]map[string]interface{}, error) {
models, err := dao.GetModelProviderManager().ListAllModels()
if err != nil {
return nil, err
}
if pageSize > 0 && pageIndex >= 0 {
start := pageIndex * pageSize
end := start + pageSize
if start >= len(models) {
return []map[string]interface{}{}, nil
}
if end > len(models) {
end = len(models)
}
return models[start:end], nil
}
return models, 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/service/model_service.go` around lines 2415 - 2424, In
ListAllModels, the code slices models with
models[pageIndex*pageSize:(pageIndex+1)*pageSize] without bounds checks which
can panic; validate and clamp indices: ensure pageIndex and pageSize are
non-negative, compute start = pageIndex * pageSize and end = start + pageSize,
clamp start = min(max(start, 0), len(models)) and end = min(max(end, 0),
len(models)), if start >= len(models) return an empty slice, otherwise return
models[start:end]; keep existing behavior of returning models when pageSize <=
0.

JinHai-CN added 2 commits June 8, 2026 20:53
Signed-off-by: Jin Hai <[email protected]>
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: 4

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

45-98: ⚖️ Poor tradeoff

Consider splitting list and show operations into separate handler methods.

The method ListAllModels handles two distinct operations based on the presence of ModelName in the request body. This couples two responsibilities in one handler and makes the API less discoverable.

Consider refactoring into separate methods and routes:

  • ListAllModels for listing (POST /api/v1/models/all-models with pagination in body)
  • ShowModel for single model (GET /api/v1/models/all-models/:name)

Or keep one endpoint but rename the method to better reflect its dual purpose (e.g., HandleModelsQuery).

🤖 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/models.go` around lines 45 - 98, The ListAllModels handler
currently does two jobs (list vs. show) based on req.ModelName; split
responsibilities by creating two handlers: keep ListAllModels to only handle
pagination listing (remove the req.ModelName branch, bind a pagination request
struct, call h.modelProviderService.ListAllModels(page, pageSize) and return
models), and add a new ShowModel handler that reads the model name from the URL
(e.g., path param), calls h.modelProviderService.ShowModel(name) and returns the
single model; update routing to expose POST /api/v1/models/all-models
(ListAllModels) and GET /api/v1/models/all-models/:name (ShowModel) or, if you
prefer a single endpoint, rename ListAllModels to HandleModelsQuery and keep the
existing conditional logic — ensure you update request binding and remove the
mixed logic from ListAllModels so each handler has a single responsibility.
🤖 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/handler/models.go`:
- Line 27: Update the incorrect doc comments that refer to "ProviderHandler" so
they match the actual type name "ModelHandler": change any comment above the
ModelHandler struct and its related constructor/factory function (e.g.,
NewModelHandler or similar) to reference ModelHandler instead of
ProviderHandler, ensuring the comment text and any // ProviderHandler or
ProviderHandler... occurrences are replaced with // ModelHandler and mention the
correct symbol names.
- Line 49: Remove the debug println call that uses printf-style formatting
(println("JSON bind error: %v (type: %T)", err, err)) and replace it with a
structured log call using your project's logger (e.g., processLogger, logger, or
standard log) so the error and its type are recorded properly; reference the
existing error variable err and ensure the message is descriptive (e.g., "JSON
bind error") while passing err as structured context instead of using println.
- Around line 59-60: Validate and sanitize pagination before calling the
service: ensure req.Page and req.PageSize are positive integers (e.g., default
to 1 and a sane max like 100 if zero/negative or out-of-range) and compute
pageIndex = page - 1 only after validation; if values are invalid return a 4xx
error instead of forwarding them. In short, check req.Page and req.PageSize
(variables page and pageSize in the handler), enforce page >= 1 and pageSize > 0
(and optionally cap pageSize), and only call the service method that slices
models with these validated values to prevent the slice bounds panic.
- Around line 50-54: Handlers in internal/handler/models.go currently always
return http.StatusOK for errors (using c.JSON(http.StatusOK,...)) which is
inconsistent with connector.go; pick a single convention—prefer using proper
HTTP status codes—and update the error responses in models.go to return the
matching 4xx/5xx status (e.g., http.StatusBadRequest or
http.StatusInternalServerError) when sending JSON with
common.CodeBadRequest/common.CodeInternalError, update the c.JSON(...) calls
(the ones that currently pass http.StatusOK) to the appropriate http status, and
ensure the same convention is applied across internal/handler/llm.go and
internal/handler/connector.go for consistency.

---

Nitpick comments:
In `@internal/handler/models.go`:
- Around line 45-98: The ListAllModels handler currently does two jobs (list vs.
show) based on req.ModelName; split responsibilities by creating two handlers:
keep ListAllModels to only handle pagination listing (remove the req.ModelName
branch, bind a pagination request struct, call
h.modelProviderService.ListAllModels(page, pageSize) and return models), and add
a new ShowModel handler that reads the model name from the URL (e.g., path
param), calls h.modelProviderService.ShowModel(name) and returns the single
model; update routing to expose POST /api/v1/models/all-models (ListAllModels)
and GET /api/v1/models/all-models/:name (ShowModel) or, if you prefer a single
endpoint, rename ListAllModels to HandleModelsQuery and keep the existing
conditional logic — ensure you update request binding and remove the mixed logic
from ListAllModels so each handler has a single responsibility.
🪄 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: c292bc99-6f59-4e9b-8952-08435045b1e4

📥 Commits

Reviewing files that changed from the base of the PR and between 62677f0 and e7b5e41.

📒 Files selected for processing (1)
  • internal/handler/models.go

"github.com/gin-gonic/gin"
)

// ProviderHandler provider handler

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

Fix documentation comments to match actual type names.

Lines 27 and 32 reference "ProviderHandler" but the actual type is ModelHandler. Update the comments to match the struct and function names.

📝 Proposed fix
-// ProviderHandler provider handler
+// ModelHandler model handler
 type ModelHandler struct {
 	modelProviderService *service.ModelProviderService
 }
 
-// NewProviderHandler create provider handler
+// NewModelHandler create model handler
 func NewModelHandler(modelProviderService *service.ModelProviderService) *ModelHandler {

Also applies to: 32-32

🤖 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/models.go` at line 27, Update the incorrect doc comments
that refer to "ProviderHandler" so they match the actual type name
"ModelHandler": change any comment above the ModelHandler struct and its related
constructor/factory function (e.g., NewModelHandler or similar) to reference
ModelHandler instead of ProviderHandler, ensuring the comment text and any //
ProviderHandler or ProviderHandler... occurrences are replaced with //
ModelHandler and mention the correct symbol names.


var req ShowModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
println("JSON bind error: %v (type: %T)", err, err)

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

Remove debug println statement.

The println call with format string syntax appears to be debug code. Remove it or replace with structured logging (e.g., using a logger instance) for production observability.

🧹 Proposed fix
 	var req ShowModelRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
-		println("JSON bind error: %v (type: %T)", err, err)
 		c.JSON(http.StatusOK, gin.H{
📝 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
println("JSON bind error: %v (type: %T)", err, err)
var req ShowModelRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusOK, gin.H{
🤖 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/models.go` at line 49, Remove the debug println call that
uses printf-style formatting (println("JSON bind error: %v (type: %T)", err,
err)) and replace it with a structured log call using your project's logger
(e.g., processLogger, logger, or standard log) so the error and its type are
recorded properly; reference the existing error variable err and ensure the
message is descriptive (e.g., "JSON bind error") while passing err as structured
context instead of using println.

Comment on lines +50 to +54
c.JSON(http.StatusOK, gin.H{
"code": common.CodeBadRequest,
"message": err.Error(),
})
return

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Check HTTP status code usage pattern in other handlers

# Search for c.JSON calls in handler files to see status code patterns
rg -n -A3 -B1 'c\.JSON\(' --type=go -g 'internal/handler/*.go' | head -100

Repository: infiniflow/ragflow

Length of output: 5329


🏁 Script executed:

#!/bin/bash
# Inspect the exact status-code usage in internal/handler/models.go around the reported lines
sed -n '1,140p' internal/handler/models.go | nl -ba | sed -n '35,110p'

# Show all c.JSON(http.Status*...) occurrences in internal/handler/models.go
rg -n 'c\.JSON\((http\.Status[A-Za-z0-9_]+)' internal/handler/models.go

Repository: infiniflow/ragflow

Length of output: 293


Align HTTP status codes with the handlers’ established error contract.

internal/handler/models.go returns http.StatusOK for both success and error paths (reported at lines 50-54, 65-69, 82-86, 90-94) while signaling failures via the JSON code/message fields. This matches internal/handler/llm.go, but internal/handler/connector.go uses http.StatusBadRequest and http.StatusInternalServerError in some error cases, so the convention is inconsistent across handlers. Pick one approach (either “always 200 + JSON code” and document it, or use proper 4xx/5xx status codes) and apply it consistently.

🤖 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/models.go` around lines 50 - 54, Handlers in
internal/handler/models.go currently always return http.StatusOK for errors
(using c.JSON(http.StatusOK,...)) which is inconsistent with connector.go; pick
a single convention—prefer using proper HTTP status codes—and update the error
responses in models.go to return the matching 4xx/5xx status (e.g.,
http.StatusBadRequest or http.StatusInternalServerError) when sending JSON with
common.CodeBadRequest/common.CodeInternalError, update the c.JSON(...) calls
(the ones that currently pass http.StatusOK) to the appropriate http status, and
ensure the same convention is applied across internal/handler/llm.go and
internal/handler/connector.go for consistency.

Comment thread internal/handler/models.go Resolved

@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

♻️ Duplicate comments (1)
internal/service/model_service.go (1)

2420-2421: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Incomplete bounds check allows out-of-range panic.

Line 2420 validates the start index but not the end. When (pageIndex+1)*pageSize exceeds len(models), line 2421 panics. For example, with len(models)=10, pageIndex=0, pageSize=20: the condition 0*20 < 10 passes, but models[0:20] panics.

🛡️ Proposed fix
-	if pageSize > 0 && pageIndex >= 0 && pageIndex*pageSize < len(models) {
-		return models[pageIndex*pageSize : (pageIndex+1)*pageSize], nil
+	if pageSize > 0 && pageIndex >= 0 {
+		start := pageIndex * pageSize
+		if start >= len(models) {
+			return []map[string]interface{}{}, nil
+		}
+		end := start + pageSize
+		if end > len(models) {
+			end = len(models)
+		}
+		return models[start:end], 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/service/model_service.go` around lines 2420 - 2421, The current
bounds check only ensures the start index but not the end, causing a panic when
(pageIndex+1)*pageSize > len(models); update the logic that slices the models
slice (using pageSize, pageIndex, models) to compute a safe end index (e.g. end
:= min((pageIndex+1)*pageSize, len(models))) and return
models[pageIndex*pageSize:end], or change the condition to require
(pageIndex+1)*pageSize <= len(models) before slicing so the end index never
exceeds len(models).
🤖 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 @.github/workflows/tests.yml:
- Around line 144-161: Uncomment and restore the CI steps that prepare test
resources and run Go tests: re-enable the "Prepare test resources" block that
clones the resource repo, checks out the pinned ref, creates
/usr/share/infinity/resource and symlinks resource/wordnet, and re-enable the
"Test Go packages" step that computes packages via packages=$(go list
./internal/... | grep -vE '/storage(/|$)') and runs CGO_ENABLED=1 with GOPROXY
to execute go test -count=1 ${packages}; ensure both blocks (names "Prepare test
resources" and "Test Go packages") are present and use the original env and
commands so CLI/model-catalog regressions and tokenizer/resource-dependent flows
are validated.

In `@internal/service/model_service.go`:
- Around line 2426-2428: The ShowModel method currently returns (nil, nil) when
dao.GetModelProviderManager().GetModelByNameOrAlias(modelName) yields nil;
update ShowModel to check the returned model and return a non-nil error when
it's not found (e.g., return nil and fmt.Errorf("model %s not found", modelName)
or a package-level sentinel error) so callers can distinguish "not found" from
success; keep the signature of ShowModel unchanged and reference
dao.GetModelProviderManager().GetModelByNameOrAlias and ShowModel in your
change.

---

Duplicate comments:
In `@internal/service/model_service.go`:
- Around line 2420-2421: The current bounds check only ensures the start index
but not the end, causing a panic when (pageIndex+1)*pageSize > len(models);
update the logic that slices the models slice (using pageSize, pageIndex,
models) to compute a safe end index (e.g. end := min((pageIndex+1)*pageSize,
len(models))) and return models[pageIndex*pageSize:end], or change the condition
to require (pageIndex+1)*pageSize <= len(models) before slicing so the end index
never exceeds len(models).
🪄 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: e74af033-eadf-465f-a1f1-6acc7b55832b

📥 Commits

Reviewing files that changed from the base of the PR and between e7b5e41 and b73c251.

📒 Files selected for processing (3)
  • .github/workflows/tests.yml
  • internal/entity/model.go
  • internal/service/model_service.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/entity/model.go

Comment on lines +144 to +161
# - name: Prepare test resources
# run: |
# RESOURCE_REPO=https://github.com/infiniflow/resource.git
# RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e
# rm -rf /tmp/resource
# git clone "${RESOURCE_REPO}" /tmp/resource
# git -C /tmp/resource checkout "${RESOURCE_REF}"
# sudo mkdir -p /usr/share/infinity
# sudo ln -sf /tmp/resource /usr/share/infinity/resource
# mkdir -p resource
# ln -sf /tmp/resource/wordnet resource/wordnet
#
# - name: Test Go packages
# run: |
# set -euo pipefail
# packages=$(go list ./internal/... | grep -vE '/storage(/|$)')
# CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \
# go test -count=1 ${packages}

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

Re-enable Go test execution; current workflow now skips Go regression coverage.

At Line 156 onward, commenting out Test Go packages removes CI validation for ./internal/... while this PR series introduces Go CLI/model-catalog changes. Also, the commented resource setup at Line 144 previously prepared /usr/share/infinity/resource, which is a known runtime default path for tokenizer/resource-dependent flows. This combination materially increases regression risk.

Suggested fix
-#      - name: Prepare test resources
-#        run: |
-#          RESOURCE_REPO=https://github.com/infiniflow/resource.git
-#          RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e
-#          rm -rf /tmp/resource
-#          git clone "${RESOURCE_REPO}" /tmp/resource
-#          git -C /tmp/resource checkout "${RESOURCE_REF}"
-#          sudo mkdir -p /usr/share/infinity
-#          sudo ln -sf /tmp/resource /usr/share/infinity/resource
-#          mkdir -p resource
-#          ln -sf /tmp/resource/wordnet resource/wordnet
-#
-#      - name: Test Go packages
-#        run: |
-#          set -euo pipefail
-#          packages=$(go list ./internal/... | grep -vE '/storage(/|$)')
-#          CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \
-#            go test -count=1 ${packages}
+      - name: Prepare test resources
+        run: |
+          RESOURCE_REPO=https://github.com/infiniflow/resource.git
+          RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e
+          rm -rf /tmp/resource
+          git clone "${RESOURCE_REPO}" /tmp/resource
+          git -C /tmp/resource checkout "${RESOURCE_REF}"
+          sudo mkdir -p /usr/share/infinity
+          sudo ln -sf /tmp/resource /usr/share/infinity/resource
+          mkdir -p resource
+          ln -sf /tmp/resource/wordnet resource/wordnet
+
+      - name: Test Go packages
+        run: |
+          set -euo pipefail
+          packages=$(go list ./internal/... | grep -vE '/storage(/|$)')
+          CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \
+            go test -count=1 ${packages}
📝 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
# - name: Prepare test resources
# run: |
# RESOURCE_REPO=https://github.com/infiniflow/resource.git
# RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e
# rm -rf /tmp/resource
# git clone "${RESOURCE_REPO}" /tmp/resource
# git -C /tmp/resource checkout "${RESOURCE_REF}"
# sudo mkdir -p /usr/share/infinity
# sudo ln -sf /tmp/resource /usr/share/infinity/resource
# mkdir -p resource
# ln -sf /tmp/resource/wordnet resource/wordnet
#
# - name: Test Go packages
# run: |
# set -euo pipefail
# packages=$(go list ./internal/... | grep -vE '/storage(/|$)')
# CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \
# go test -count=1 ${packages}
- name: Prepare test resources
run: |
RESOURCE_REPO=https://github.com/infiniflow/resource.git
RESOURCE_REF=549feaaf998954d65b668667f009125bc84a9c5e
rm -rf /tmp/resource
git clone "${RESOURCE_REPO}" /tmp/resource
git -C /tmp/resource checkout "${RESOURCE_REF}"
sudo mkdir -p /usr/share/infinity
sudo ln -sf /tmp/resource /usr/share/infinity/resource
mkdir -p resource
ln -sf /tmp/resource/wordnet resource/wordnet
- name: Test Go packages
run: |
set -euo pipefail
packages=$(go list ./internal/... | grep -vE '/storage(/|$)')
CGO_ENABLED=1 GOPROXY=${GOPROXY:-https://goproxy.cn,https://proxy.golang.org,direct} \
go test -count=1 ${packages}
🤖 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 @.github/workflows/tests.yml around lines 144 - 161, Uncomment and restore
the CI steps that prepare test resources and run Go tests: re-enable the
"Prepare test resources" block that clones the resource repo, checks out the
pinned ref, creates /usr/share/infinity/resource and symlinks resource/wordnet,
and re-enable the "Test Go packages" step that computes packages via
packages=$(go list ./internal/... | grep -vE '/storage(/|$)') and runs
CGO_ENABLED=1 with GOPROXY to execute go test -count=1 ${packages}; ensure both
blocks (names "Prepare test resources" and "Test Go packages") are present and
use the original env and commands so CLI/model-catalog regressions and
tokenizer/resource-dependent flows are validated.

Comment on lines +2426 to +2428
func (m *ModelProviderService) ShowModel(modelName string) (*entity.Model, error) {
return dao.GetModelProviderManager().GetModelByNameOrAlias(modelName), 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 | ⚡ Quick win

Return an error when model is not found.

GetModelByNameOrAlias likely returns nil when the model doesn't exist, but this method always returns error = nil. Callers receive (nil, nil) and cannot distinguish "not found" from success, risking nil-pointer dereferences downstream.

🐛 Proposed fix
 func (m *ModelProviderService) ShowModel(modelName string) (*entity.Model, error) {
-	return dao.GetModelProviderManager().GetModelByNameOrAlias(modelName), nil
+	model := dao.GetModelProviderManager().GetModelByNameOrAlias(modelName)
+	if model == nil {
+		return nil, fmt.Errorf("model %q not found", modelName)
+	}
+	return model, 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/service/model_service.go` around lines 2426 - 2428, The ShowModel
method currently returns (nil, nil) when
dao.GetModelProviderManager().GetModelByNameOrAlias(modelName) yields nil;
update ShowModel to check the returned model and return a non-nil error when
it's not found (e.g., return nil and fmt.Errorf("model %s not found", modelName)
or a package-level sentinel error) so callers can distinguish "not found" from
success; keep the signature of ShowModel unchanged and reference
dao.GetModelProviderManager().GetModelByNameOrAlias and ShowModel in your
change.

@codecov

codecov Bot commented Jun 8, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15786   +/-   ##
=======================================
  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 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.

@JinHai-CN
JinHai-CN merged commit 55abf4f into infiniflow:main Jun 8, 2026
1 check passed
@coderabbitai coderabbitai Bot mentioned this pull request Jun 9, 2026
1 task done
xugangqiang added a commit to xugangqiang/ragflow that referenced this pull request Jun 9, 2026
The Go test steps were commented out by infiniflow#15786 (due to resource clone
failures).  Re-enable with run-scoped resource path to prevent cross-run
deletion races on self-hosted runners.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant