Skip to content

Go: add file parse command - #14892

Merged
JinHai-CN merged 17 commits into
infiniflow:mainfrom
JinHai-CN:fix430
May 15, 2026
Merged

JinHai-CN merged 17 commits into
infiniflow:mainfrom
JinHai-CN:fix430

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented May 13, 2026 •

Copy link
Copy Markdown
Member

What problem does this PR solve?

RAGFlow(user)> ocr with 'hunyuanocr@test@gitee' file './picture.png'
+----------------------------------------------------------+
| text                                                     |
+----------------------------------------------------------+
| 生活不是等待风暴过去,而是学会在雨中翩翩起舞。
——佚名                                                       |
+----------------------------------------------------------+

RAGFlow(user)> list 'test@gitee' tasks;
+---------+----------------------------------+
| status  | task_id                          |
+---------+----------------------------------+
| success | C3FX4MQNKY5MGC6ZFMIXIAMJKHCEBQB5 |
+---------+----------------------------------+
RAGFlow(user)> show 'test@gitee' task 'C3FX4MQNKY5MGC6ZFMIXIAMJKHCEBQB5';
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| content                                                                                                                                                                                                                                                          | index |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+
| # PDF 1: Purpose of RAGFlow  

RAGFlow is an open source Retrieval-Augmented Generation (RAG) engine designed to turn raw documents into reliable context for large language models.Its purpose is to make it practical to build an Al assistant that can ans... | 1     |
+------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+-------+

Type of change

  • New Feature (non-breaking change which adds functionality)

@coderabbitai

coderabbitai Bot commented May 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR extends RAGFlow with document parsing, task listing, and task status retrieval capabilities. It updates the ModelDriver interface with ParseFile, ListTasks, and ShowTask methods, implements these across all model drivers (mostly as unsupported stubs except Gitee's working implementation), orchestrates via service layer with tenant and instance resolution, exposes through HTTP handlers and routes, and provides end-to-end CLI support with parsing, command dispatch, and response formatting. Configuration updates include Gitee endpoint mappings for the new functionality and Minio backward-compatible settings migration.

Changes

Document parsing and task management implementation

Layer / File(s) Summary
ModelDriver interface and response type contracts
internal/entity/models/types.go
ModelDriver interface documentation updated. OCRResponse replaced with OCRFileResponse. New types: ParseFileResponse, ListTaskStatus, TaskSegment, TaskResponse, ParseFileConfig. URLSuffix extended with doc_parse, tasks, task endpoint mappings.
Driver implementations: stubs and OCRFile updates
internal/entity/models/*.go (28 driver files)
All 28 model drivers updated to add ParseFile, ListTasks, ShowTask stub methods returning "no such method" errors, and all OCRFile methods changed to return OCRFileResponse.
Gitee model driver: working implementation
internal/entity/models/gitee.go
ParseFile implemented with multipart upload, Gitee endpoint submission, and task polling. ListTasks and ShowTask implemented with task status projection and segment retrieval. OCRFile updated to return OCRFileResponse. Internal response DTOs and polling helper added.
Service layer orchestration
internal/service/model_service.go
New ListTasks, ShowTask, ParseFile methods added. Each resolves tenant/provider/instance, builds APIConfig from instance extra, optionally uses local driver for base_url deployments. OCRFile return type updated and model-type validation corrected.
HTTP handlers and routes
internal/handler/providers.go, internal/router/router.go
New handlers: ListTasks, ShowTask, ParseFile with parameter validation and service delegation. ParseFileRequest struct added. Routes registered for task and file operations.
CLI infrastructure
internal/cli/lexer.go, internal/cli/types.go, internal/cli/response.go, internal/cli/client.go
TokenTask lexer token and constant. SegmentResponse and TaskResponse types with table formatting. Command dispatch updated for new user commands.
CLI command parsing
internal/cli/user_parser.go
PARSE WITH <model> FILE|URL syntax via parseModelParseCommand. LIST <instance> TASKS and SHOW TASK <task_id> parsing via new helpers. Parser dispatch logic extended with token-based routing.
CLI user command handlers
internal/cli/user_command.go
Three handlers: ParseFileUserCommand (POST /file/parse), ListTasksUserCommand (GET tasks), ShowTaskUserCommand (GET task by ID). Credential validation, composite name resolution, HTTP dispatch, response unmarshalling.

Configuration, release notes, and cleanup

Layer / File(s) Summary
Gitee configuration and release notes
conf/models/gitee.json, docs/release_notes.md
Gitee url_suffix extended with endpoint mappings. MinerU2.5 model registered with doc_parse type. Release notes updated with parsing and S3 sync enhancements.
Minio backward compatibility and cleanup
internal/server/config.go, internal/handler/memory.go, internal/engine/elasticsearch/index.go, web/src/utils/api.ts
FromConfigFile supports new minio_0 configuration section. Memory handler JSON message formatting standardized. Minor whitespace adjustments in Elasticsearch and API files.

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#14891: Overlaps on Gitee OCR surface modification, updating the OCRFile contract and response types (OCRFileResponse vs OCRResponse) that CLI and handlers consume.
  • infiniflow/ragflow#14336: Introduces Gitee provider as a new driver; this PR extends Gitee integration with /file/parse and task endpoints plus URL suffix mappings.
  • infiniflow/ragflow#14203: Both PRs use per-instance region configuration via TenantModelInstance.Extra for task/parse APIConfig derivation.

Suggested labels

💞 feature, 🐖api

Suggested reviewers

  • wangq8
  • yingfeng

🐰 A rabbit hops through the code with glee,
Parse files, list tasks, make workflows flow free!
From Gitee's embrace to handlers so bright,
Document dreams are now in sight! ✨📄

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Go: add file parse command' accurately describes the main feature addition—implementing a file parse command in the Go CLI layer.
Description check ✅ Passed The PR description follows the required template with a problem statement (showing OCR, task listing, and task display examples) and clearly marks it as a new feature, but lacks detailed implementation context.
Docstring Coverage ✅ Passed Docstring coverage is 87.50% 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 marked this pull request as ready for review May 15, 2026 02:04
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label May 15, 2026
@JinHai-CN JinHai-CN added the ci Continue Integration label May 15, 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: 8

🧹 Nitpick comments (3)
internal/entity/models/baidu.go (1)

629-631: 💤 Low value

Consider consistent receiver naming.

The new methods use receiver name z while the existing OCRFile method (line 624) uses b. For consistency within the BaiduModel type, consider using the same receiver name throughout the file.

Also applies to: 697-703

🤖 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/models/baidu.go` around lines 629 - 631, The receiver name
for methods on BaiduModel is inconsistent: change the receiver from z to b in
the ParseFile method (func (z *BaiduModel) ParseFile...) and the other methods
referenced around lines 697-703 so they all use the same receiver identifier as
OCRFile (func (b *BaiduModel) OCRFile...), ensuring consistent receiver naming
(b) across BaiduModel methods like ParseFile and the ones near 697-703.
internal/entity/models/types.go (2)

156-157: 💤 Low value

Document the empty ParseFileConfig struct.

ParseFileConfig is currently an empty struct. Following the pattern of OCRConfig (also empty), this appears intentional for future configuration options. Adding a brief comment would clarify this design decision.

📝 Suggested documentation
+// ParseFileConfig holds configuration for file parsing operations.
+// Currently empty; reserved for future parsing parameters.
 type ParseFileConfig struct {
 }
🤖 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/models/types.go` around lines 156 - 157, Add a brief doc
comment above the empty ParseFileConfig struct to state it's intentionally empty
for future configuration (matching the existing pattern used for OCRConfig);
mention that it serves as a placeholder for future parsing options so readers
won't treat its emptiness as an oversight, and ensure the comment is placed
immediately above the ParseFileConfig declaration.

81-82: ⚡ Quick win

Document the empty ParseFileResponse struct.

ParseFileResponse is currently an empty struct with no fields. If this is intentional (e.g., reserved for future extension or the actual result is returned through a different mechanism like task IDs), please add a comment documenting this design choice. Otherwise, consider whether fields like TaskID string or Status string should be added now.

📝 Suggested documentation
+// ParseFileResponse is the response from ParseFile operations.
+// Currently empty as file parsing is asynchronous; callers should
+// use ListTasks and ShowTask to retrieve results.
 type ParseFileResponse struct {
 }
🤖 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/models/types.go` around lines 81 - 82, ParseFileResponse is
currently an empty struct; either document it as intentionally reserved or add
the expected response fields—add a Go doc comment above the ParseFileResponse
type explaining that it is intentionally empty/placeholder (e.g., "reserved for
future use" or "response communicated via task IDs elsewhere"), or if the
response should carry data, add explicit fields such as TaskID string and Status
string (and any other needed fields) to the ParseFileResponse struct so its
purpose is clear; update the type declaration for ParseFileResponse accordingly.
🤖 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/cli/response.go`:
- Around line 346-353: TaskResponse.PrintOut currently does unchecked
type-assert r.Data["segments"].([]interface{}) and v.(map[string]interface{})
which can panic on malformed responses; change it to safely validate types using
the "ok" comma-ok form: verify r.Data["segments"] exists and is a []interface{}
(assign to segmentsRaw with ok), and for each element check it is a
map[string]interface{} before appending to segments (skip or substitute an empty
map on failure). If the top-level key is missing or wrong type, treat segments
as empty slice (or log a warning) then call PrintTableSimpleByFormat(segments,
r.OutputFormat) as before. Ensure all references match TaskResponse.PrintOut,
r.Data["segments"], segmentsRaw and segments.

In `@internal/cli/user_command.go`:
- Around line 2423-2433: The current block in ShowTaskUserCommand
unconditionally returns an error if cmd.Params["composite_instance_name"] is
missing; change it to treat composite_instance_name as optional: if present
parse "instance@provider" into instanceName and providerName (keeping the
existing validation and error when format is invalid), but if absent do not
return an error—leave instanceName/providerName empty (or nil) so SHOW TASK
<task_id> can proceed; update any downstream usage to handle empty
providerName/instanceName accordingly.

In `@internal/entity/models/gitee.go`:
- Around line 813-821: The ParseFile path discards the upstream task/result by
creating and returning an empty ParseFileResponse instead of the data obtained
from g.getParseFile and the giteeParseFileResp; update the function to capture
and propagate the parsed result: call g.getParseFile (already invoked) and use
its returned data (or the final result from the poll using
giteeParseFileResp.TaskID) to populate and return a proper ParseFileResponse
rather than a zero-value; ensure you map fields from the upstream response into
ParseFileResponse and return that populated struct from the function.
- Around line 845-873: In getParseFile, remove the defer resp.Body.Close()
inside the retry loop (which leaks connections) and instead close the response
body explicitly after reading it each iteration; after reading and unmarshalling
the body (into result) evaluate the parsed status/result and return the
successful parsed value immediately (or an appropriate error) instead of falling
through to return nil, nil; ensure each loop iteration always closes resp.Body
even on errors and only sleeps/retries when a retry is warranted.
- Line 827: The code builds the polling URL with a hardcoded "/task/%s/status"
path (see the url := fmt.Sprintf(...) line using baseURL and taskID); change it
to use the provider-configured URL suffix contract instead of the literal
string—compose the URL by trimming baseURL and then appending the configured
URLSuffix (or calling the helper that formats URLSuffix with taskID) so
provider-specific suffixes are honored; update references around baseURL, taskID
and URLSuffix (or the existing URL-building helper) to format/replace the task
ID into the configured suffix rather than using the hardcoded path.

In `@internal/handler/providers.go`:
- Around line 1469-1507: The handler currently calls
h.modelProviderService.ParseFile without validating the parse source; add a
request-shape check before invoking ParseFile to ensure exactly one of
req.Content or req.URL is supplied (reject when both are missing or both are
present/empty). If validation fails, return a 400 JSON response (c.JSON) with a
clear message like "Either content or url must be provided, but not both" and
stop processing; perform the check just before the call to
h.modelProviderService.ParseFile so req.Content and req.URL are validated in the
same place where provider/instance/model are already checked.

In `@internal/server/config.go`:
- Around line 726-741: The minio_0 branch populates
globalConfig.StorageEngine.Minio but omits the Region field; update the
MinioConfig initialization in the minio_0 block to set Region:
minioConfig.GetString("region") (same as the existing minio block) and ensure
you reference MinioConfig, minioConfig, and globalConfig.StorageEngine.Minio;
additionally, add a simple guard or log/warning when both "minio" and "minio_0"
config sections are present so one does not silently overwrite the other (e.g.,
check v.IsSet("minio") && v.IsSet("minio_0") and emit a warning or decide
precedence).

In `@internal/service/model_service.go`:
- Around line 1801-1813: ParseFile currently selects the model driver
inconsistently and may call NewInstance with an empty base_url, producing a
broken instance; update the logic so both branches follow the same rule: only
construct a new instance via NewInstance when a non-empty base_url (or other
local override) is present, otherwise use providerInfo.ModelDriver.ParseFile
directly. Specifically, in ParseFile adjust the not-found branch to honor any
local base_url override (parse extra["base_url"] / base_url variable) instead of
skipping it, and in the active-instance branch guard the NewInstance call (and
assignment of apiConfig.ApiKey/Region) so it is only invoked when base_url is
non-empty; apply the same fix to the second occurrence around the other
ParseFile call (the 1833-1849 region) to keep behavior consistent.

---

Nitpick comments:
In `@internal/entity/models/baidu.go`:
- Around line 629-631: The receiver name for methods on BaiduModel is
inconsistent: change the receiver from z to b in the ParseFile method (func (z
*BaiduModel) ParseFile...) and the other methods referenced around lines 697-703
so they all use the same receiver identifier as OCRFile (func (b *BaiduModel)
OCRFile...), ensuring consistent receiver naming (b) across BaiduModel methods
like ParseFile and the ones near 697-703.

In `@internal/entity/models/types.go`:
- Around line 156-157: Add a brief doc comment above the empty ParseFileConfig
struct to state it's intentionally empty for future configuration (matching the
existing pattern used for OCRConfig); mention that it serves as a placeholder
for future parsing options so readers won't treat its emptiness as an oversight,
and ensure the comment is placed immediately above the ParseFileConfig
declaration.
- Around line 81-82: ParseFileResponse is currently an empty struct; either
document it as intentionally reserved or add the expected response fields—add a
Go doc comment above the ParseFileResponse type explaining that it is
intentionally empty/placeholder (e.g., "reserved for future use" or "response
communicated via task IDs elsewhere"), or if the response should carry data, add
explicit fields such as TaskID string and Status string (and any other needed
fields) to the ParseFileResponse struct so its purpose is clear; update the type
declaration for ParseFileResponse accordingly.
🪄 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: 4c689864-8b3c-47be-98f4-0efeb8a1ba44

📥 Commits

Reviewing files that changed from the base of the PR and between d887b57 and efface1.

📒 Files selected for processing (46)
  • conf/models/gitee.json
  • docs/release_notes.md
  • internal/cli/client.go
  • internal/cli/lexer.go
  • internal/cli/response.go
  • internal/cli/types.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/engine/elasticsearch/index.go
  • internal/entity/models/aliyun.go
  • internal/entity/models/baichuan.go
  • internal/entity/models/baidu.go
  • internal/entity/models/cohere.go
  • internal/entity/models/deepseek.go
  • internal/entity/models/dummy.go
  • internal/entity/models/fishaudio.go
  • internal/entity/models/gitee.go
  • internal/entity/models/google.go
  • internal/entity/models/huggingface.go
  • internal/entity/models/jina.go
  • internal/entity/models/lmstudio.go
  • internal/entity/models/localai.go
  • internal/entity/models/longcat.go
  • internal/entity/models/minimax.go
  • internal/entity/models/mistral.go
  • internal/entity/models/moonshot.go
  • internal/entity/models/novita.go
  • internal/entity/models/nvidia.go
  • internal/entity/models/ollama.go
  • internal/entity/models/openai.go
  • internal/entity/models/openrouter.go
  • internal/entity/models/siliconflow.go
  • internal/entity/models/stepfun.go
  • internal/entity/models/types.go
  • internal/entity/models/upstage.go
  • internal/entity/models/vllm.go
  • internal/entity/models/volcengine.go
  • internal/entity/models/voyage.go
  • internal/entity/models/xai.go
  • internal/entity/models/zhipu-ai.go
  • internal/handler/memory.go
  • internal/handler/providers.go
  • internal/router/router.go
  • internal/server/config.go
  • internal/service/model_service.go
  • web/src/utils/api.ts

Comment thread internal/cli/response.go
Comment on lines +346 to +353
func (r *TaskResponse) PrintOut() {
if r.Code == 0 {
segmentsRaw := r.Data["segments"].([]interface{})
segments := make([]map[string]interface{}, len(segmentsRaw))
for i, v := range segmentsRaw {
segments[i] = v.(map[string]interface{})
}
PrintTableSimpleByFormat(segments, r.OutputFormat)

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

Prevent panic in task output formatting.

On Line 348 and Line 351, unchecked assertions (r.Data["segments"].([]interface{}), v.(map[string]interface{})) can crash the CLI on malformed or partial responses.

Proposed fix
 func (r *TaskResponse) PrintOut() {
 	if r.Code == 0 {
-		segmentsRaw := r.Data["segments"].([]interface{})
-		segments := make([]map[string]interface{}, len(segmentsRaw))
-		for i, v := range segmentsRaw {
-			segments[i] = v.(map[string]interface{})
-		}
+		raw, ok := r.Data["segments"]
+		if !ok {
+			fmt.Println("ERROR")
+			fmt.Println("invalid task response: missing segments")
+			return
+		}
+		segmentsRaw, ok := raw.([]interface{})
+		if !ok {
+			fmt.Println("ERROR")
+			fmt.Println("invalid task response: segments is not an array")
+			return
+		}
+		segments := make([]map[string]interface{}, 0, len(segmentsRaw))
+		for _, v := range segmentsRaw {
+			item, ok := v.(map[string]interface{})
+			if !ok {
+				fmt.Println("ERROR")
+				fmt.Println("invalid task response: segment item is not an object")
+				return
+			}
+			segments = append(segments, item)
+		}
 		PrintTableSimpleByFormat(segments, r.OutputFormat)
 	} else {
 		fmt.Println("ERROR")
 		fmt.Printf("%d, %s\n", r.Code, r.Message)
 	}
 }
📝 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 (r *TaskResponse) PrintOut() {
if r.Code == 0 {
segmentsRaw := r.Data["segments"].([]interface{})
segments := make([]map[string]interface{}, len(segmentsRaw))
for i, v := range segmentsRaw {
segments[i] = v.(map[string]interface{})
}
PrintTableSimpleByFormat(segments, r.OutputFormat)
func (r *TaskResponse) PrintOut() {
if r.Code == 0 {
raw, ok := r.Data["segments"]
if !ok {
fmt.Println("ERROR")
fmt.Println("invalid task response: missing segments")
return
}
segmentsRaw, ok := raw.([]interface{})
if !ok {
fmt.Println("ERROR")
fmt.Println("invalid task response: segments is not an array")
return
}
segments := make([]map[string]interface{}, 0, len(segmentsRaw))
for _, v := range segmentsRaw {
item, ok := v.(map[string]interface{})
if !ok {
fmt.Println("ERROR")
fmt.Println("invalid task response: segment item is not an object")
return
}
segments = append(segments, item)
}
PrintTableSimpleByFormat(segments, r.OutputFormat)
} else {
fmt.Println("ERROR")
fmt.Printf("%d, %s\n", r.Code, r.Message)
}
}
🤖 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/response.go` around lines 346 - 353, TaskResponse.PrintOut
currently does unchecked type-assert r.Data["segments"].([]interface{}) and
v.(map[string]interface{}) which can panic on malformed responses; change it to
safely validate types using the "ok" comma-ok form: verify r.Data["segments"]
exists and is a []interface{} (assign to segmentsRaw with ok), and for each
element check it is a map[string]interface{} before appending to segments (skip
or substitute an empty map on failure). If the top-level key is missing or wrong
type, treat segments as empty slice (or log a warning) then call
PrintTableSimpleByFormat(segments, r.OutputFormat) as before. Ensure all
references match TaskResponse.PrintOut, r.Data["segments"], segmentsRaw and
segments.

Comment on lines +2423 to +2433
// Check if composite_instance_name is provided in command
if compositeModelName, ok := cmd.Params["composite_instance_name"].(string); ok && compositeModelName != "" {
names := strings.Split(compositeModelName, "@")
if len(names) != 2 {
return nil, fmt.Errorf("model name must be in format 'instance@provider'")
}
providerName = names[1]
instanceName = names[0]
} else {
return nil, fmt.Errorf("no provider name or instance name")
}

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

Handle SHOW TASK <task_id> without forcing composite instance input.

ShowTaskUserCommand currently hard-fails when composite_instance_name is absent. That breaks the parser path that emits only task_id for SHOW TASK ....

Proposed fix
-	// Check if composite_instance_name is provided in command
-	if compositeModelName, ok := cmd.Params["composite_instance_name"].(string); ok && compositeModelName != "" {
+	// Check if composite_instance_name is provided in command
+	if compositeModelName, ok := cmd.Params["composite_instance_name"].(string); ok && compositeModelName != "" {
 		names := strings.Split(compositeModelName, "@")
 		if len(names) != 2 {
 			return nil, fmt.Errorf("model name must be in format 'instance@provider'")
 		}
 		providerName = names[1]
 		instanceName = names[0]
+	} else if c.CurrentModel != nil {
+		// Fallback for SHOW TASK <task_id> when current model is set
+		providerName = c.CurrentModel.Provider
+		instanceName = c.CurrentModel.Instance
 	} else {
-		return nil, fmt.Errorf("no provider name or instance name")
+		return nil, fmt.Errorf("no provider/instance context; provide 'instance@provider' or run 'USE MODEL' first")
 	}
🤖 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/user_command.go` around lines 2423 - 2433, The current block in
ShowTaskUserCommand unconditionally returns an error if
cmd.Params["composite_instance_name"] is missing; change it to treat
composite_instance_name as optional: if present parse "instance@provider" into
instanceName and providerName (keeping the existing validation and error when
format is invalid), but if absent do not return an error—leave
instanceName/providerName empty (or nil) so SHOW TASK <task_id> can proceed;
update any downstream usage to handle empty providerName/instanceName
accordingly.

Comment on lines +813 to +821
_, err = g.getParseFile(&baseURL, apiConfig.ApiKey, &giteeParseFileResp.TaskID, 5*time.Second, 10)
if err != nil {
return nil, err
}

var parseFileResponse = ParseFileResponse{}

return &parseFileResponse, 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

ParseFile returns an empty payload even after successful submission/polling.

The method currently discards upstream task/result data and always returns an empty ParseFileResponse, which makes the new parse command effectively unusable for callers.

🤖 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/models/gitee.go` around lines 813 - 821, The ParseFile path
discards the upstream task/result by creating and returning an empty
ParseFileResponse instead of the data obtained from g.getParseFile and the
giteeParseFileResp; update the function to capture and propagate the parsed
result: call g.getParseFile (already invoked) and use its returned data (or the
final result from the poll using giteeParseFileResp.TaskID) to populate and
return a proper ParseFileResponse rather than a zero-value; ensure you map
fields from the upstream response into ParseFileResponse and return that
populated struct from the function.

}

func (g *GiteeModel) getParseFile(baseURL *string, apiKey, taskID *string, timeOut time.Duration, count int) (*giteeGetParseFileResponse, error) {
url := fmt.Sprintf("%s/task/%s/status", strings.TrimSuffix(*baseURL, "/"), *taskID)

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

Avoid hardcoded task status path; use configured URL suffix contract.

/task/%s/status is hardcoded, so any provider-specific path change in config will break polling even if URLSuffix is correct.

Suggested fix
-	url := fmt.Sprintf("%s/task/%s/status", strings.TrimSuffix(*baseURL, "/"), *taskID)
+	url := fmt.Sprintf("%s/%s/%s/status", strings.TrimSuffix(*baseURL, "/"), g.URLSuffix.Task, *taskID)
📝 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
url := fmt.Sprintf("%s/task/%s/status", strings.TrimSuffix(*baseURL, "/"), *taskID)
url := fmt.Sprintf("%s/%s/%s/status", strings.TrimSuffix(*baseURL, "/"), g.URLSuffix.Task, *taskID)
🤖 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/models/gitee.go` at line 827, The code builds the polling URL
with a hardcoded "/task/%s/status" path (see the url := fmt.Sprintf(...) line
using baseURL and taskID); change it to use the provider-configured URL suffix
contract instead of the literal string—compose the URL by trimming baseURL and
then appending the configured URLSuffix (or calling the helper that formats
URLSuffix with taskID) so provider-specific suffixes are honored; update
references around baseURL, taskID and URLSuffix (or the existing URL-building
helper) to format/replace the task ID into the configured suffix rather than
using the hardcoded path.

Comment on lines +845 to +873
for i := 0; i < count; i++ {
resp, err = g.httpClient.Do(req)
if err != nil {
return nil, fmt.Errorf("failed to send request: %w", err)
}
defer resp.Body.Close()

var body []byte
body, err = io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed to read response: %w", err)
}

if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("API request failed with status %d: %s", resp.StatusCode, string(body))
}

// Parse response
var result map[string]interface{}
if err = json.Unmarshal(body, &result); err != nil {
return nil, fmt.Errorf("failed to parse response: %w", err)
}

time.Sleep(timeOut)
}

// if resp show the file is ok, download it. otherwise, provide timeout info
return nil, 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

Polling helper never resolves completion and leaks response bodies across retries.

getParseFile defers resp.Body.Close() inside the retry loop and never evaluates parsed status/result before returning nil, nil. This can exhaust idle connections and always loses parse output.

Suggested fix
-	var resp *http.Response
 	for i := 0; i < count; i++ {
-		resp, err = g.httpClient.Do(req)
+		resp, err := g.httpClient.Do(req)
 		if err != nil {
 			return nil, fmt.Errorf("failed to send request: %w", err)
 		}
-		defer resp.Body.Close()

-		var body []byte
-		body, err = io.ReadAll(resp.Body)
+		body, err := io.ReadAll(resp.Body)
+		resp.Body.Close()
 		if err != nil {
 			return nil, fmt.Errorf("failed to read response: %w", err)
 		}
@@
-		// Parse response
+		// Parse response and break/return once terminal status is observed.
 		var result map[string]interface{}
 		if err = json.Unmarshal(body, &result); err != nil {
 			return nil, fmt.Errorf("failed to parse response: %w", err)
 		}
+		// TODO: inspect result["status"] and return parsed response when done.

 		time.Sleep(timeOut)
 	}

-	// if resp show the file is ok, download it. otherwise, provide timeout info
-	return nil, nil
+	return nil, fmt.Errorf("parse task %s did not reach terminal state after %d polls", *taskID, count)
🤖 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/models/gitee.go` around lines 845 - 873, In getParseFile,
remove the defer resp.Body.Close() inside the retry loop (which leaks
connections) and instead close the response body explicitly after reading it
each iteration; after reading and unmarshalling the body (into result) evaluate
the parsed status/result and return the successful parsed value immediately (or
an appropriate error) instead of falling through to return nil, nil; ensure each
loop iteration always closes resp.Body even on errors and only sleeps/retries
when a retry is warranted.

Comment on lines +1469 to +1507
if req.ProviderName == nil || *req.ProviderName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Provider name is required",
})
return
}

if req.InstanceName == nil || *req.InstanceName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Instance name is required",
})
return
}

if req.ModelName == nil || *req.ModelName == "" {
c.JSON(http.StatusBadRequest, gin.H{
"code": 400,
"message": "Model name is required",
})
return
}

userID := c.GetString("user_id")

apiConfig := models.APIConfig{
ApiKey: nil,
Region: nil,
}

parseFileConfig := models.ParseFileConfig{}

// Non-stream response
var response *models.ParseFileResponse
var errorCode common.ErrorCode
var err error

response, errorCode, err = h.modelProviderService.ParseFile(*req.ProviderName, *req.InstanceName, *req.ModelName, userID, req.Content, req.URL, &apiConfig, &parseFileConfig)

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.

🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win

Add request-shape validation for parse source fields.

ParseFile validates provider/instance/model but does not validate the parse source. On Line 1469 onward, requests with neither content nor url (or with both) are accepted and deferred to deeper layers.

Proposed fix
 func (h *ProviderHandler) ParseFile(c *gin.Context) {
 	var req ParseFileRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
@@
 	if req.ModelName == nil || *req.ModelName == "" {
 		c.JSON(http.StatusBadRequest, gin.H{
 			"code":    400,
 			"message": "Model name is required",
 		})
 		return
 	}
+
+	hasContent := len(req.Content) > 0
+	hasURL := req.URL != nil && strings.TrimSpace(*req.URL) != ""
+	if hasContent == hasURL {
+		c.JSON(http.StatusBadRequest, gin.H{
+			"code":    common.CodeBadRequest,
+			"message": "Exactly one of content or url must be provided",
+		})
+		return
+	}
 
 	userID := c.GetString("user_id")
🤖 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/providers.go` around lines 1469 - 1507, The handler
currently calls h.modelProviderService.ParseFile without validating the parse
source; add a request-shape check before invoking ParseFile to ensure exactly
one of req.Content or req.URL is supplied (reject when both are missing or both
are present/empty). If validation fails, return a 400 JSON response (c.JSON)
with a clear message like "Either content or url must be provided, but not both"
and stop processing; perform the check just before the call to
h.modelProviderService.ParseFile so req.Content and req.URL are validated in the
same place where provider/instance/model are already checked.

Comment thread internal/server/config.go
Comment on lines +726 to +741
if v.IsSet("minio_0") {
minioConfig := v.Sub("minio_0")
if minioConfig != nil {
if globalConfig.StorageEngine.Minio == nil {
globalConfig.StorageEngine.Minio = &MinioConfig{
Host: minioConfig.GetString("host"),
User: minioConfig.GetString("user"),
Password: minioConfig.GetString("password"),
Secure: minioConfig.GetBool("secure"),
PrefixPath: minioConfig.GetString("prefix_path"),
Verify: minioConfig.GetBool("verify"),
Bucket: minioConfig.GetString("bucket"),
}
}
}
}

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

The minio_0 block is missing Region field assignment.

The existing minio section (line 719) sets Region: minioConfig.GetString("region"), but the new minio_0 block omits this field. If minio_0 is intended for backward compatibility with older configs that lacked region support, this is acceptable; otherwise, Region should be set here too for consistency.

Additionally, if both minio and minio_0 sections exist in the config file, the last one processed silently overwrites globalConfig.StorageEngine.Minio with no validation or warning. Consider adding a check to prevent conflicting configuration sections or document the precedence order.

🔧 Proposed fix to add Region field
 		if v.IsSet("minio_0") {
 			minioConfig := v.Sub("minio_0")
 			if minioConfig != nil {
 				if globalConfig.StorageEngine.Minio == nil {
 					globalConfig.StorageEngine.Minio = &MinioConfig{
 						Host:       minioConfig.GetString("host"),
 						User:       minioConfig.GetString("user"),
 						Password:   minioConfig.GetString("password"),
 						Secure:     minioConfig.GetBool("secure"),
 						PrefixPath: minioConfig.GetString("prefix_path"),
 						Verify:     minioConfig.GetBool("verify"),
+						Region:     minioConfig.GetString("region"),
 						Bucket:     minioConfig.GetString("bucket"),
 					}
 				}
 			}
 		}
📝 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 v.IsSet("minio_0") {
minioConfig := v.Sub("minio_0")
if minioConfig != nil {
if globalConfig.StorageEngine.Minio == nil {
globalConfig.StorageEngine.Minio = &MinioConfig{
Host: minioConfig.GetString("host"),
User: minioConfig.GetString("user"),
Password: minioConfig.GetString("password"),
Secure: minioConfig.GetBool("secure"),
PrefixPath: minioConfig.GetString("prefix_path"),
Verify: minioConfig.GetBool("verify"),
Bucket: minioConfig.GetString("bucket"),
}
}
}
}
if v.IsSet("minio_0") {
minioConfig := v.Sub("minio_0")
if minioConfig != nil {
if globalConfig.StorageEngine.Minio == nil {
globalConfig.StorageEngine.Minio = &MinioConfig{
Host: minioConfig.GetString("host"),
User: minioConfig.GetString("user"),
Password: minioConfig.GetString("password"),
Secure: minioConfig.GetBool("secure"),
PrefixPath: minioConfig.GetString("prefix_path"),
Verify: minioConfig.GetBool("verify"),
Region: minioConfig.GetString("region"),
Bucket: minioConfig.GetString("bucket"),
}
}
}
}
🤖 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/server/config.go` around lines 726 - 741, The minio_0 branch
populates globalConfig.StorageEngine.Minio but omits the Region field; update
the MinioConfig initialization in the minio_0 block to set Region:
minioConfig.GetString("region") (same as the existing minio block) and ensure
you reference MinioConfig, minioConfig, and globalConfig.StorageEngine.Minio;
additionally, add a simple guard or log/warning when both "minio" and "minio_0"
config sections are present so one does not silently overwrite the other (e.g.,
check v.IsSet("minio") && v.IsSet("minio_0") and emit a warning or decide
precedence).

Comment on lines +1801 to +1813
var extra map[string]string
err = json.Unmarshal([]byte(instance.Extra), &extra)
if err != nil {
return nil, common.CodeServerError, err
}

region := extra["region"]
apiConfig.Region = &region
apiConfig.ApiKey = &instance.APIKey

var response *modelModule.ParseFileResponse
response, err = providerInfo.ModelDriver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)
if err != 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

ParseFile chooses the driver inconsistently and can construct a broken instance when base_url is empty.

In the not-found branch, ParseFile skips local base_url override entirely; in the active branch it always calls NewInstance even when base_url is empty. This diverges from the existing service pattern and can break parse calls for both local and hosted configs.

Suggested fix
+		driver := providerInfo.ModelDriver
+		if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
+			newURL := map[string]string{region: baseURL}
+			driver = driver.NewInstance(newURL)
+		}
@@
-		response, err = providerInfo.ModelDriver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)
+		response, err = driver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)
@@
-		newURL := map[string]string{
-			region: extra["base_url"],
-		}
-		newProviderInfo := providerInfo.ModelDriver.NewInstance(newURL)
+		driver := providerInfo.ModelDriver
+		if baseURL, ok := extra["base_url"]; ok && baseURL != "" {
+			newURL := map[string]string{region: baseURL}
+			driver = driver.NewInstance(newURL)
+		}
@@
-		response, err = newProviderInfo.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)
+		response, err = driver.ParseFile(&modelName, content, url, apiConfig, parseFileConfig)

Also applies to: 1833-1849

🤖 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 1801 - 1813, ParseFile
currently selects the model driver inconsistently and may call NewInstance with
an empty base_url, producing a broken instance; update the logic so both
branches follow the same rule: only construct a new instance via NewInstance
when a non-empty base_url (or other local override) is present, otherwise use
providerInfo.ModelDriver.ParseFile directly. Specifically, in ParseFile adjust
the not-found branch to honor any local base_url override (parse
extra["base_url"] / base_url variable) instead of skipping it, and in the
active-instance branch guard the NewInstance call (and assignment of
apiConfig.ApiKey/Region) so it is only invoked when base_url is non-empty; apply
the same fix to the second occurrence around the other ParseFile call (the
1833-1849 region) to keep behavior consistent.

@codecov

codecov Bot commented May 15, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #14892   +/-   ##
=======================================
  Coverage   94.16%   94.16%           
=======================================
  Files          10       10           
  Lines         703      703           
  Branches      112      112           
=======================================
  Hits          662      662           
  Misses         25       25           
  Partials       16       16           

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

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

@JinHai-CN
JinHai-CN merged commit 3a5df08 into infiniflow:main May 15, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 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