Skip to content

Go CLI: fix api commands - #16457

Merged
JinHai-CN merged 3 commits into
infiniflow:mainfrom
JinHai-CN:fix506
Jun 29, 2026
Merged

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

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

As title.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

CLI command handler methods across common_command.go and user_command.go are renamed to add API/Dev prefixes and Command suffixes. Parser functions in user_parser.go and dev_parser.go are renamed and emitted command type strings are updated to api_*/dev_* forms. A new dev_chunk command is added with parser and dispatch wiring.

CLI Method Rename and dev_chunk Feature

Layer / File(s) Summary
Handler method renames
internal/cli/common_command.go, internal/cli/user_command.go
Exported CLI handler methods are renamed to API*/Dev*-prefixed *Command-suffixed forms (e.g. ChatToModel → APIChatToModelCommand, ChunkCommand → DevChunkCommand). Implementation bodies are unchanged except dataset_id becomes an optional *string in APIListIngestionTasks.
Dispatch wiring
internal/cli/cli_http.go
ExecuteAdminCommand and ExecuteUserCommand switch cases are updated to call the renamed handler methods. A new "dev_chunk" case dispatching to DevChunkCommand is inserted in ExecuteUserCommand.
Parser dispatch and user_parser.go refactor
internal/cli/parser.go, internal/cli/user_parser.go, internal/cli/user_parser_test.go
parseUserCommand token switch routes tokens to renamed parseAPI*/parseDev* methods; parseFileSystemCommand is renamed to parseFileSystemCommands. user_parser.go is extensively refactored: emitted command type strings are updated to api_* across LIST/SHOW/CREATE/DROP/ADD/DELETE/SET/RESET/RETRIEVE/PARSE/chat/embed/rerank/tts/asr/ocr/openai-chat handlers; new parseAPIThink, parseAPICheck, parseAPIUseCommands, and parseOpenaiChat entry points are added. Test updated to expect api_chat_to_model.
New dev parsers and metadata comment
internal/cli/dev_parser.go, internal/engine/infinity/metadata.go
parseGetCommand, parseSetMeta, parseCreateMetadataStore are renamed to parseDevGetCommand, parseDevSetMeta, parseDevCreateMetadataStore. New parseGetMetadata, parseDevExplain, and parseDevChunk functions are added to parse GET METADATA, EXPLAIN CHUNK, and CHUNK … WITH … syntax into dev_chunk commands. A comment in metadata.go is updated to reference parseDevSetMeta.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#16447: Refactors the same internal/cli/* command wiring and handler dispatch for api_*/dev_* chunk/metadata and provider/server operations.
  • infiniflow/ragflow#16430: Adds CREATE/DROP command support hooking into the same CLI dispatcher/handlers modified here.
  • infiniflow/ragflow#16299: Refactors the same CLI API-style command parsing/dispatching in internal/cli/cli_http.go and internal/cli/user_parser.go.

Suggested labels

☯️ refactor

Suggested reviewers

  • yuzhichang

Poem

🐇 Hop, hop, the names have changed,
ChatToModel rearranged!
API prefix, Command at the end,
Every handler found a trend.
dev_chunk joins the fray today —
The parser hops a cleaner way! 🎉

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description is too generic and only repeats the title, without the required summary context from the template. Expand the Summary with the PR purpose, background context, and a short description of the main API CLI command changes.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main change: updates and fixes to Go CLI API command handling.
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.

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.

@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 29, 2026
@JinHai-CN
JinHai-CN marked this pull request as ready for review June 29, 2026 10:44
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jun 29, 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: 2

Caution

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

⚠️ Outside diff range comments (4)
internal/cli/user_command.go (2)

4074-4103: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve the explain result in DevChunkCommand.

The explain branch assigns the explanation to result.Message, but Line 4102 overwrites it with the generic success text, so dev_chunk ... explain never returns the actual plan.

Suggested fix
 	if explain {
@@
 		result.Message = explanation
 	} else {
@@
 		for _, resultChunk := range chunkContext.ResultChunks {
 			fmt.Printf("Chunk index: %d\n", resultChunk.Index)
 			fmt.Printf("Chunk size: %d\n", resultChunk.Size)
 			fmt.Printf("Chunk content: \n%s\n", resultChunk.Content)
 		}
+		result.Message = fmt.Sprintf("Success to chunk %s", filename)
 	}
 
 	result.Duration = time.Since(start).Seconds()
 	result.Code = 0
-	result.Message = fmt.Sprintf("Success to chunk %s", filename)
 	return &result, nil
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cli/user_command.go` around lines 4074 - 4103, The explain output in
DevChunkCommand is being overwritten before return, so the actual plan from
engine.Explain is lost. Update the DevChunkCommand flow in user_command.go so
the explain branch preserves result.Message when explain is true, and only set
the generic success message for the non-explain path; use the existing result,
engine.Explain, and result.Message assignment to locate the fix.

3791-3798: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

LIST INGESTION TASKS FROM ... currently drops the dataset filter.

The parser still stores dataset_id as a plain string, but this handler now asserts *string, so the FROM clause always falls back to nil and the request is sent unfiltered.

Suggested fix
-	datasetID, ok := cmd.Params["dataset_id"].(*string)
-	if !ok {
-		datasetID = nil
-	}
-
-	payload := map[string]interface{}{
-		"dataset_id": datasetID,
-	}
+	payload := map[string]interface{}{}
+	if datasetID, ok := cmd.Params["dataset_id"].(string); ok && datasetID != "" {
+		payload["dataset_id"] = datasetID
+	}
🤖 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 3791 - 3798, The LIST INGESTION
TASKS FROM handler is reading cmd.Params["dataset_id"] with the wrong type, so
the dataset filter is always lost. Update the dataset_id extraction in the
relevant CLI handler in user_command.go to match how the parser stores it as a
plain string, then pass that value through unchanged when building the payload
map. Keep the fix scoped to the LIST INGESTION TASKS flow and the
datasetID/payload construction so the FROM clause is preserved.
internal/cli/user_parser.go (1)

2820-2853: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Fix EFFORT/VERBOSITY parsing in parseAPIChat.

Two problems here: VERBOSITY MEDIUM is serialized as "median", and both branches break optionsLoop, so a command like THINK CHAT ... EFFORT high VERBOSITY high stops parsing after the first option instead of capturing both values.

Suggested fix
 		case TokenEffort:
 			p.nextToken() // pass Effort
@@
 			}
 			p.nextToken()
-			break optionsLoop
+			continue
 		case TokenVerbosity:
 			p.nextToken() // pass VERBOSITY
 			switch p.curToken.Type {
 			case TokenLow:
 				verbosity = "low"
 			case TokenMedium:
-				verbosity = "median"
+				verbosity = "medium"
 			case TokenHigh:
 				verbosity = "high"
 			default:
 				return nil, fmt.Errorf("invalid verbosity level")
 			}
 			p.nextToken()
-			break optionsLoop
+			continue
🤖 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_parser.go` around lines 2820 - 2853, The parseAPIChat
option handling has two issues: TokenVerbosity maps TokenMedium to the wrong
value and both TokenEffort and TokenVerbosity exit optionsLoop too early. Update
the effort/verbosity parsing in user_parser.go so TokenVerbosity assigns
"medium" for TokenMedium, and change the control flow in parseAPIChat to
continue parsing additional options after handling one recognized option instead
of breaking out of optionsLoop; use the existing TokenEffort and TokenVerbosity
branches as the fix points.
internal/cli/common_command.go (1)

935-952: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Accept model_id in APISetDefaultModelCommand.

parseAPISetDefault now emits model_id for UUID inputs, but this handler only reads composite_model_name. As a result, SET DEFAULT ... MODEL '<uuid>' fails locally with "model_name not provided" instead of sending the PATCH.

Suggested fix
 func (c *CLI) APISetDefaultModelCommand(cmd *Command) (ResponseIf, error) {
@@
-	compositeModelName, ok := cmd.Params["composite_model_name"].(string)
-	if !ok {
-		return nil, fmt.Errorf("model_name not provided")
-	}
-
-	var providerName, instanceName, modelName string
-	var err error
-	modelName, instanceName, providerName, err = common.ExtractCompositeName(compositeModelName)
-	if err != nil {
-		return nil, err
-	}
-
-	payload := map[string]interface{}{
-		"model_type":     modelType,
-		"model_provider": providerName,
-		"model_instance": instanceName,
-		"model_name":     modelName,
-	}
+	payload := map[string]interface{}{
+		"model_type": modelType,
+	}
+	if compositeModelName, ok := cmd.Params["composite_model_name"].(string); ok {
+		modelName, instanceName, providerName, err := common.ExtractCompositeName(compositeModelName)
+		if err != nil {
+			return nil, err
+		}
+		payload["model_provider"] = providerName
+		payload["model_instance"] = instanceName
+		payload["model_name"] = modelName
+	} else if modelID, ok := cmd.Params["model_id"].(string); ok {
+		payload["model_id"] = modelID
+	} else {
+		return nil, fmt.Errorf("model identifier not provided")
+	}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cli/common_command.go` around lines 935 - 952,
APISetDefaultModelCommand currently only reads composite_model_name, so
UUID-based defaults emitted as model_id by parseAPISetDefault are rejected with
a misleading model_name not provided error. Update the handler in
common_command.go to accept model_id as an alternate input, branch on whichever
field is present, and only call common.ExtractCompositeName for composite names
while allowing raw UUIDs to pass through to the PATCH payload. Keep the existing
payload shape and ensure the command still sets model_type, model_provider,
model_instance, and model_name appropriately for composite inputs.
🤖 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/dev_parser.go`:
- Around line 734-743: The DSL parsing in the CHUNK/EXPLAIN CHUNK path is
checking for an optional semicolon before advancing past the quoted DSL token,
so the trailing ';' remains unconsumed. Update the parser logic in the relevant
DSL parse function (the block using parseQuotedString and p.nextToken) to
consume the DSL token first, then check for TokenSemicolon, matching the
behavior of neighboring parsers and allowing semicolon-terminated statements to
parse consistently.

In `@internal/engine/infinity/metadata.go`:
- Line 228: The inline reference in the metadata comment points to the wrong
file; update the `parseDevSetMeta` reference so it directs readers to
`internal/cli/dev_parser.go` instead of `internal/cli/user_parser.go`. Locate
the comment near the `metadata.go` change and fix the user-facing path text to
match the actual location of `parseDevSetMeta`.

---

Outside diff comments:
In `@internal/cli/common_command.go`:
- Around line 935-952: APISetDefaultModelCommand currently only reads
composite_model_name, so UUID-based defaults emitted as model_id by
parseAPISetDefault are rejected with a misleading model_name not provided error.
Update the handler in common_command.go to accept model_id as an alternate
input, branch on whichever field is present, and only call
common.ExtractCompositeName for composite names while allowing raw UUIDs to pass
through to the PATCH payload. Keep the existing payload shape and ensure the
command still sets model_type, model_provider, model_instance, and model_name
appropriately for composite inputs.

In `@internal/cli/user_command.go`:
- Around line 4074-4103: The explain output in DevChunkCommand is being
overwritten before return, so the actual plan from engine.Explain is lost.
Update the DevChunkCommand flow in user_command.go so the explain branch
preserves result.Message when explain is true, and only set the generic success
message for the non-explain path; use the existing result, engine.Explain, and
result.Message assignment to locate the fix.
- Around line 3791-3798: The LIST INGESTION TASKS FROM handler is reading
cmd.Params["dataset_id"] with the wrong type, so the dataset filter is always
lost. Update the dataset_id extraction in the relevant CLI handler in
user_command.go to match how the parser stores it as a plain string, then pass
that value through unchanged when building the payload map. Keep the fix scoped
to the LIST INGESTION TASKS flow and the datasetID/payload construction so the
FROM clause is preserved.

In `@internal/cli/user_parser.go`:
- Around line 2820-2853: The parseAPIChat option handling has two issues:
TokenVerbosity maps TokenMedium to the wrong value and both TokenEffort and
TokenVerbosity exit optionsLoop too early. Update the effort/verbosity parsing
in user_parser.go so TokenVerbosity assigns "medium" for TokenMedium, and change
the control flow in parseAPIChat to continue parsing additional options after
handling one recognized option instead of breaking out of optionsLoop; use the
existing TokenEffort and TokenVerbosity branches as the fix points.
🪄 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: 70b6b0cd-d064-43b3-87ff-f4eb29550abc

📥 Commits

Reviewing files that changed from the base of the PR and between 98323e7 and 7cd38b0.

📒 Files selected for processing (8)
  • internal/cli/cli_http.go
  • internal/cli/common_command.go
  • internal/cli/dev_parser.go
  • internal/cli/parser.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/cli/user_parser_test.go
  • internal/engine/infinity/metadata.go

Comment on lines +734 to +743
dsl, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected DSL: %w", err)
}

// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
p.nextToken()

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Consume the token after the DSL before checking for ;.

Right now the semicolon branch is checked while p.curToken is still the quoted DSL token, so CHUNK ... WITH 'dsl'; returns with ; still unconsumed. That makes the new command inconsistent with the neighboring parsers and can break semicolon-terminated CHUNK / EXPLAIN CHUNK statements.

Proposed fix
 	dsl, err := p.parseQuotedString()
 	if err != nil {
 		return nil, fmt.Errorf("expected DSL: %w", err)
 	}
+	p.nextToken()
 
 	// Semicolon is optional
 	if p.curToken.Type == TokenSemicolon {
 		p.nextToken()
 	}
-	p.nextToken()
 
 	cmd := NewCommand("dev_chunk")
📝 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
dsl, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected DSL: %w", err)
}
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
p.nextToken()
dsl, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected DSL: %w", err)
}
p.nextToken()
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
cmd := NewCommand("dev_chunk")
🤖 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/dev_parser.go` around lines 734 - 743, The DSL parsing in the
CHUNK/EXPLAIN CHUNK path is checking for an optional semicolon before advancing
past the quoted DSL token, so the trailing ';' remains unconsumed. Update the
parser logic in the relevant DSL parse function (the block using
parseQuotedString and p.nextToken) to consume the DSL token first, then check
for TokenSemicolon, matching the behavior of neighboring parsers and allowing
semicolon-terminated statements to parse consistently.

// that user-driven metadata edits compose with auto-extracted fields
// produced by the LLM extraction pipeline. See the CLI parser in
// internal/cli/user_parser.go (parseSetMeta) for the user-facing
// internal/cli/user_parser.go (parseDevSetMeta) for the user-facing

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Point this reference at internal/cli/dev_parser.go.

parseDevSetMeta is defined in internal/cli/dev_parser.go in this PR, so the new comment sends readers to the wrong file.

🤖 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/engine/infinity/metadata.go` at line 228, The inline reference in
the metadata comment points to the wrong file; update the `parseDevSetMeta`
reference so it directs readers to `internal/cli/dev_parser.go` instead of
`internal/cli/user_parser.go`. Locate the comment near the `metadata.go` change
and fix the user-facing path text to match the actual location of
`parseDevSetMeta`.

@codecov

codecov Bot commented Jun 29, 2026

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16457   +/-   ##
=======================================
  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 7c1edca into infiniflow:main Jun 29, 2026
3 checks 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