Skip to content

Go CLI: refactor commands - #16447

Merged
JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix505
Jun 29, 2026
Merged

JinHai-CN merged 7 commits into
infiniflow:mainfrom
JinHai-CN:fix505

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

Summary

  1. Move debug commands to dev file.
  2. Refactor some commands syntax

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors CLI command types and handler names into api_ and dev_ namespaces, introduces a new dev_parser.go file with 659 lines of dev-command parsers, renames AlterProviderInstanceRequest.ModelName to InstanceName across handlers and CLI, and replaces provider-name canonicalization helpers with simple strings.TrimSpace + strings.ToLower normalization in the model service.

Changes

CLI Namespace Split and Provider Contract Updates

Layer / File(s) Summary
Provider service normalization and AlterProviderInstance contract
internal/service/model_service.go, internal/handler/providers.go, internal/admin/enterprise_handler.go, internal/cli/common_command.go, internal/cli/admin_parser.go
Removes providerCatalogNameByCanonical, canonicalProviderName, and catalogProviderName helpers; normalizes providerName with trim+lowercase in AddModelProvider, ListSupportedModels, CreateProviderInstance, and ListProviderInstances; swaps DeleteModelProvider parameter order to (userID, providerName). Renames model_name/ModelName to instance_name/InstanceName in AlterProviderInstanceRequest across both HTTP handlers, the CLI common command, and the admin parser.
Handler function renames to Dev* and API* variants
internal/cli/user_command.go, internal/cli/common_command.go
Renames 18 handler methods to Dev* or API* variants; switches DevSetMetaCommand, DevDeleteMetaCommand, DevInsertChunksFromFileCommand, and DevInsertMetadataFromFileCommand to dev_-prefixed HTTP endpoints; removes explicit payload body from APIDeleteProviderCommand; renames ListAllModels to CommonListAllModels.
New dev_parser.go
internal/cli/dev_parser.go
Adds 659 lines of new parser methods: parseDevInsertCommand, file-backed insert parsers, parseGetChunk, parseDevUpdateCommand, parseSetMeta, parseDevDeleteMeta, parseDevRemoveTags, parseDevRemoveChunk, store drop/create parsers (parseDevDropChunkStore, parseDevDropMetadataStore, parseDevCreateChunkStore, parseCreateMetadataStore), and parseCreateRole.
Parser dispatch rewiring to api_/dev_ handlers
internal/cli/user_parser.go, internal/cli/parser.go, internal/cli/admin_parser.go, internal/cli/user_parser_test.go
Routes ADD/DELETE/ALTER/INSERT/UPDATE/REMOVE tokens to api_/dev_-prefixed parse functions; introduces parseAPIAddCommands, parseAPIDeleteCommands, parseAPIRemoveCommands, parseAPIAlterCommands, and parseAPIAlterInstance; renames delete-server parsers to parseAPIDelete*; changes emitted command types to api_add_custom_model, api_list_all_models, api_alter_provider_instance; removes parseInsertCommand; updates test fixture to expect api_add_custom_model.
HTTP dispatcher and CLI error prefix updates
internal/cli/cli_http.go, internal/cli/cli.go
Updates ExecuteAdminCommand to call CommonListAllModels; updates ExecuteUserCommand switch to use api_-prefixed command type strings, removes list_dataset_documents and bulk chunk/metadata CRUD cases, adds dev_* cases dispatching to Dev*Command methods; changes CLI error prefix from CLI error: to ragflow-cli error:.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • infiniflow/ragflow#16145: Modifies parseAddModel parsing logic in internal/cli/user_parser.go, directly overlapping with this PR's refactor of that function into parseAPIAddModel.
  • infiniflow/ragflow#16345: Modifies internal/cli/cli_http.go command dispatch routing for API key and server commands, overlapping with this PR's broader api_* routing changes in the same switch.
  • infiniflow/ragflow#16368: Modifies ExecuteUserCommand in internal/cli/cli_http.go to remap provider operations to api_* handlers, directly intersecting with this PR's provider command routing changes.

Poem

🐇 Hop hop, the names are new,
dev_ and api_ through and through!
instance_name replaced the old,
Canonical maps? Trimmed and scrolled.
Six hundred lines of parsers gleam—
A rabbit's tidy CLI dream! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title is related to the PR, but it's generic and doesn't identify the main refactor clearly. Use a concise, specific title that names the main change, such as moving debug commands to dev files and refactoring CLI syntax.
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The description matches the required Summary section and states the main intent, even though it is brief.
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 07:26
@dosubot dosubot Bot added size:XXL This PR changes 1000+ lines, ignoring generated files. ☯️ refactor Pull request that refactor/refine code labels 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: 4

Caution

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

⚠️ Outside diff range comments (6)
internal/service/model_service.go (3)

188-198: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Normalize providerName before deleting.

Providers are now created with trimmed/lowercased names, but delete still uses the raw input; deleting SiliconFlow can miss a row stored as siliconflow.

Proposed fix
 func (m *ModelProviderService) DeleteModelProvider(userID, providerName string) (common.ErrorCode, error) {
+	providerName = strings.ToLower(strings.TrimSpace(providerName))
+	if providerName == "" {
+		return common.CodeBadRequest, errors.New("provider name is required")
+	}
+
 	tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
🤖 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 188 - 198,
DeleteModelProvider should normalize providerName before lookup/delete, because
created provider names are stored trimmed and lowercased while this path still
uses raw input. Update the DeleteModelProvider flow in ModelProviderService to
apply the same normalization used on create/search before calling
modelProviderDAO.DeleteByTenantIDAndProviderName, so inputs like SiliconFlow
match stored values like siliconflow.

105-123: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject blank or unsupported providers before creating tenant rows.

After canonicalization was removed, any trimmed/lowercased string can be persisted. ListSupportedModels later requires FindProvider(providerName) to resolve a driver, so unsupported rows become broken tenant-provider state.

Proposed fix
 func (m *ModelProviderService) AddModelProvider(providerName, userID string) (common.ErrorCode, error) {
-	providerName = strings.TrimSpace(providerName)
-	providerName = strings.ToLower(providerName)
+	providerName = strings.ToLower(strings.TrimSpace(providerName))
+	if providerName == "" {
+		return common.CodeBadRequest, errors.New("provider name is required")
+	}
+	if dao.GetModelProviderManager().FindProvider(providerName) == nil {
+		return common.CodeNotFound, fmt.Errorf("provider %s not found", providerName)
+	}
 
 	tenants, err := m.userTenantDAO.GetByUserIDAndRole(userID, "owner")
🤖 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 105 - 123, Reject invalid
provider names in model_service.go before creating the TenantModelProvider row:
after the existing trim/lowercase normalization in the tenant-provider creation
flow, validate providerName against the supported providers list/registry used
by ListSupportedModels and FindProvider, and return an error for blank or
unsupported values instead of persisting them. Keep the check in the same path
that builds tenantModelProvider and inserts the tenant row so only resolvable
provider names can be stored.

207-233: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Don't lowercase provider names before DAO lookups. TenantModelProvider.ProviderName is stored and seeded as-is (for example, OpenAI), while GetByTenantIDAndProviderName matches provider_name = ? exactly. Lowercasing here will miss existing rows on case-sensitive stores/tests and break provider/instance lookups; normalize on write or query case-insensitively instead.

🤖 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 207 - 233, The provider
lookup in model_service should not force providerName to lowercase before
calling GetByTenantIDAndProviderName and GetByProviderIDAndInstanceName. Remove
the lowercase normalization in the provider lookup flow so the existing
TenantModelProvider.ProviderName values are matched as stored, or make the DAO
lookup case-insensitive instead; keep the trim if needed, but preserve the
original casing when resolving provider and instance records.
internal/cli/user_parser.go (3)

1716-1725: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Only include fields that are actually being altered.

CommonAlterProviderInstanceCommand adds payload fields based on key presence, so always setting new_instance_name and new_api_key can send empty instance_name or api_key when the user only changes one field.

Proposed fix
 	cmd := NewCommand("api_alter_provider_instance")
 	cmd.Params["provider_name"] = providerName
 	cmd.Params["instance_name"] = instanceName
-	cmd.Params["new_instance_name"] = newInstanceName
-	cmd.Params["new_api_key"] = newAPIKey
+	if newInstanceName != "" {
+		cmd.Params["new_instance_name"] = newInstanceName
+	}
+	if newAPIKey != "" {
+		cmd.Params["new_api_key"] = newAPIKey
+	}
 
-	p.nextToken()
 	// Semicolon is optional
 	if p.curToken.Type == TokenSemicolon {
 		p.nextToken()
+	} else if p.curToken.Type != TokenEOF {
+		return nil, fmt.Errorf("unexpected token after ALTER PROVIDER INSTANCE: %s", p.curToken.Value)
 	}
🤖 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 1716 - 1725,
`CommonAlterProviderInstanceCommand` is currently populating both
`new_instance_name` and `new_api_key` unconditionally in
`api_alter_provider_instance`, which can send empty values when only one field
is being changed. Update this parser path in `user_parser.go` so
`NewCommand("api_alter_provider_instance")` only sets `new_instance_name` when
the instance name is actually provided/changed, and only sets `new_api_key` when
the API key is actually provided/changed; keep the existing `provider_name` and
`instance_name` handling intact.

818-857: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Reject unknown provider-instance options instead of skipping them.

When the options loop stops on an unexpected token, Line 853 advances past it before checking for ;, so typos after KEY, REGION, or URL can be silently accepted.

Proposed fix
-	p.nextToken()
 	// Semicolon is optional
 	if p.curToken.Type == TokenSemicolon {
 		p.nextToken()
+	} else if p.curToken.Type != TokenEOF {
+		return nil, fmt.Errorf("unexpected token after provider instance options: %s", p.curToken.Value)
 	}
 	return cmd, 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_parser.go` around lines 818 - 857, The provider-instance
option parser in user_parser.go is silently consuming unexpected tokens after
the options loop, which can hide typos in api_add_provider_instance input.
Update the parsing flow around optionsLoop and the api_add_provider_instance
command setup so that only TokenRegion and TokenURL are accepted, and any other
token encountered before the optional semicolon causes an error instead of
calling p.nextToken() and skipping it. Use the existing parseQuotedString
handling and the cmd.Params population as the location to validate and reject
unknown options explicitly.

1468-1484: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Normalize model names and validate the statement terminator.

strings.Split(rawModels, " ") preserves empty model names for repeated spaces, and the extra p.nextToken() skips unexpected trailing tokens. Use strings.Fields and require ;/EOF after the quoted model list.

Proposed fix
-	modelNames := strings.Split(rawModels, " ")
+	modelNames := strings.Fields(rawModels)
+	if len(modelNames) == 0 {
+		return nil, fmt.Errorf("expected at least one model name")
+	}
 
 	cmd := NewCommand("api_delete_provider_instance_model")
 	cmd.Params["instance_name"] = instanceName
 	cmd.Params["provider_name"] = providerName
 	cmd.Params["model_names"] = modelNames
 
-	p.nextToken()
 	// Semicolon is optional
 	if p.curToken.Type == TokenSemicolon {
 		p.nextToken()
+	} else if p.curToken.Type != TokenEOF {
+		return nil, fmt.Errorf("unexpected token after model names: %s", p.curToken.Value)
 	}
🤖 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 1468 - 1484, The
`api_delete_provider_instance_model` parsing path in `parseQuotedString`
handling is too permissive: `strings.Split(rawModels, " ")` can produce empty
model names on repeated spaces, and the extra `p.nextToken()` can consume
unexpected trailing input. Replace the split logic with `strings.Fields` when
populating `cmd.Params["model_names"]`, and tighten the terminator handling so
the quoted model list must be followed only by `;` or EOF. Keep the validation
localized around the `api_delete_provider_instance_model` branch and the
existing `TokenSemicolon` check.
🤖 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/admin_parser.go`:
- Around line 1436-1445: The TokenName branch in the parser still reports
“expected model name” even though it now parses the replacement instance name.
Update the error text in the parse logic around parseQuotedString so it refers
to the instance name instead of the model name, keeping the rest of the error
wrapping and control flow unchanged.

In `@internal/cli/dev_parser.go`:
- Around line 410-419: After parseQuotedString() in the dataset_name handling
inside parse command parsing, advance the parser so curToken moves past the
quoted value before checking for an optional semicolon. The current flow leaves
curToken on the dataset name, so the TokenSemicolon branch in the parser logic
never matches; update the dataset_name parsing block to consume the next token
at the right point and preserve the existing cmd.Params["dataset_name"]
assignment and error handling.
- Around line 424-453: The parseDevRemoveChunk flow in Parser currently only
accepts space-separated chunk IDs and rejects the documented comma-separated
form, causing valid REMOVE CHUNKS input to fail. Update the chunk-collection
loop in parseDevRemoveChunk so it can consume TokenComma between quoted chunk
IDs, continuing to collect IDs until TokenFrom is reached, and keep the existing
parseQuotedString / TokenFrom handling intact. Ensure the final
params["chunk_ids"] contains all parsed IDs for both comma-separated and
space-separated inputs.

In `@internal/cli/user_command.go`:
- Around line 1655-1658: The new auth checks in the CLI path dereference the
selected client before verifying it exists, so first guard the lookup from
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer] in the same flow
used by Request and the related call sites. If the selected API server is
missing or the client is nil, return the existing “HTTP Client is nil” style
error instead of reading APIKey/LoginToken, and apply the same nil-safe check in
all affected blocks (including the ones in the other matching locations) before
accessing auth fields.

---

Outside diff comments:
In `@internal/cli/user_parser.go`:
- Around line 1716-1725: `CommonAlterProviderInstanceCommand` is currently
populating both `new_instance_name` and `new_api_key` unconditionally in
`api_alter_provider_instance`, which can send empty values when only one field
is being changed. Update this parser path in `user_parser.go` so
`NewCommand("api_alter_provider_instance")` only sets `new_instance_name` when
the instance name is actually provided/changed, and only sets `new_api_key` when
the API key is actually provided/changed; keep the existing `provider_name` and
`instance_name` handling intact.
- Around line 818-857: The provider-instance option parser in user_parser.go is
silently consuming unexpected tokens after the options loop, which can hide
typos in api_add_provider_instance input. Update the parsing flow around
optionsLoop and the api_add_provider_instance command setup so that only
TokenRegion and TokenURL are accepted, and any other token encountered before
the optional semicolon causes an error instead of calling p.nextToken() and
skipping it. Use the existing parseQuotedString handling and the cmd.Params
population as the location to validate and reject unknown options explicitly.
- Around line 1468-1484: The `api_delete_provider_instance_model` parsing path
in `parseQuotedString` handling is too permissive: `strings.Split(rawModels, "
")` can produce empty model names on repeated spaces, and the extra
`p.nextToken()` can consume unexpected trailing input. Replace the split logic
with `strings.Fields` when populating `cmd.Params["model_names"]`, and tighten
the terminator handling so the quoted model list must be followed only by `;` or
EOF. Keep the validation localized around the
`api_delete_provider_instance_model` branch and the existing `TokenSemicolon`
check.

In `@internal/service/model_service.go`:
- Around line 188-198: DeleteModelProvider should normalize providerName before
lookup/delete, because created provider names are stored trimmed and lowercased
while this path still uses raw input. Update the DeleteModelProvider flow in
ModelProviderService to apply the same normalization used on create/search
before calling modelProviderDAO.DeleteByTenantIDAndProviderName, so inputs like
SiliconFlow match stored values like siliconflow.
- Around line 105-123: Reject invalid provider names in model_service.go before
creating the TenantModelProvider row: after the existing trim/lowercase
normalization in the tenant-provider creation flow, validate providerName
against the supported providers list/registry used by ListSupportedModels and
FindProvider, and return an error for blank or unsupported values instead of
persisting them. Keep the check in the same path that builds tenantModelProvider
and inserts the tenant row so only resolvable provider names can be stored.
- Around line 207-233: The provider lookup in model_service should not force
providerName to lowercase before calling GetByTenantIDAndProviderName and
GetByProviderIDAndInstanceName. Remove the lowercase normalization in the
provider lookup flow so the existing TenantModelProvider.ProviderName values are
matched as stored, or make the DAO lookup case-insensitive instead; keep the
trim if needed, but preserve the original casing when resolving provider and
instance records.
🪄 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: e1d82fb3-db60-45d9-a622-405bd68fa7cf

📥 Commits

Reviewing files that changed from the base of the PR and between 9b726a5 and bf13079.

📒 Files selected for processing (12)
  • internal/admin/enterprise_handler.go
  • internal/cli/admin_parser.go
  • internal/cli/cli.go
  • 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/handler/providers.go
  • internal/service/model_service.go

Comment on lines +1436 to 1445
newInstanceName := ""
newAPIKey := ""
optionsLoop:
for {
switch p.curToken.Type {
case TokenName:
p.nextToken()
newModelName, err = p.parseQuotedString()
newInstanceName, err = p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected model name: %w", 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.

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

Update the stale parse error wording.

This branch now parses the replacement instance name, but the error still says “model name”.

Proposed fix
-				return nil, fmt.Errorf("expected model name: %w", err)
+				return nil, fmt.Errorf("expected instance name: %w", err)
📝 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
newInstanceName := ""
newAPIKey := ""
optionsLoop:
for {
switch p.curToken.Type {
case TokenName:
p.nextToken()
newModelName, err = p.parseQuotedString()
newInstanceName, err = p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected model name: %w", err)
newInstanceName := ""
newAPIKey := ""
optionsLoop:
for {
switch p.curToken.Type {
case TokenName:
p.nextToken()
newInstanceName, err = p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected instance name: %w", err)
🧰 Tools
🪛 ast-grep (0.44.0)

[warning] 1436-1436: A credential is hard-coded as a string literal. Secrets stored in source code, such as passwords, API keys, and tokens, can be leaked through version control or binaries and used by internal or external malicious actors. Rotate the exposed secret and load it at runtime from a secure secret vault, a Hardware Security Module (HSM), or an environment variable if permitted by your company policy (e.g. password := os.Getenv("APP_PASSWORD")).
Context: newAPIKey := ""
Note: [CWE-798] Use of Hard-coded Credentials.

(hardcoded-credentials-string-literal-go)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cli/admin_parser.go` around lines 1436 - 1445, The TokenName branch
in the parser still reports “expected model name” even though it now parses the
replacement instance name. Update the error text in the parse logic around
parseQuotedString so it refers to the instance name instead of the model name,
keeping the rest of the error wrapping and control flow unchanged.

Comment on lines +410 to +419
datasetName, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected dataset_name: %w", err)
}
cmd.Params["dataset_name"] = datasetName

// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
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 | 🟡 Minor | ⚡ Quick win

Advance after parsing dataset_name.

parseQuotedString() leaves curToken on the quoted dataset name in the surrounding parser pattern, so the semicolon check never sees the semicolon here.

Proposed fix
 cmd.Params["dataset_name"] = datasetName
 
+// Move past dataset_name before optional semicolon handling.
+p.nextToken()
+
 // Semicolon is optional
 if p.curToken.Type == TokenSemicolon {
 	p.nextToken()
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
datasetName, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected dataset_name: %w", err)
}
cmd.Params["dataset_name"] = datasetName
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
datasetName, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected dataset_name: %w", err)
}
cmd.Params["dataset_name"] = datasetName
// Move past dataset_name before optional semicolon handling.
p.nextToken()
// Semicolon is optional
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/cli/dev_parser.go` around lines 410 - 419, After parseQuotedString()
in the dataset_name handling inside parse command parsing, advance the parser so
curToken moves past the quoted value before checking for an optional semicolon.
The current flow leaves curToken on the dataset name, so the TokenSemicolon
branch in the parser logic never matches; update the dataset_name parsing block
to consume the next token at the right point and preserve the existing
cmd.Params["dataset_name"] assignment and error handling.

Comment on lines +424 to +453
// parseDevRemoveChunk parses:
// - REMOVE CHUNKS 'chunk_id1', 'chunk_id2' FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
// - REMOVE ALL CHUNKS FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
func (p *Parser) parseDevRemoveChunk() (*Command, error) {
cmd := NewCommand("dev_remove_chunks")

// Check if ALL CHUNKS - if we came here from TokenAll case, curToken is already ALL
if p.curToken.Type == TokenAll {
p.nextToken() // consume ALL
if p.curToken.Type != TokenChunks {
return nil, fmt.Errorf("expected CHUNKS after ALL")
}
p.nextToken() // consume CHUNKS
cmd.Params["delete_all"] = true
} else {
// curToken is TokenChunks, consume it first
p.nextToken()
// Multiple chunks: REMOVE CHUNKS 'id1' 'id2' FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name' (space-separated)
// Parse first chunk ID
chunkID, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected chunk_id: %w", err)
}
chunkIDs := []string{chunkID}

// Parse additional chunk IDs separated by spaces (each quoted)
for {
p.nextToken()
// Stop if we hit FROM or non-quoted token
if p.curToken.Type == TokenFrom || p.curToken.Type != TokenQuotedString {

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 | 🟡 Minor | ⚡ Quick win

Support the documented comma-separated chunk syntax.

The comment documents REMOVE CHUNKS 'chunk_id1', 'chunk_id2' ..., but the loop stops on TokenComma and then errors with “expected FROM after chunk(s)”.

Proposed fix
 	// Parse additional chunk IDs separated by spaces (each quoted)
 	for {
 		p.nextToken()
-		// Stop if we hit FROM or non-quoted token
-		if p.curToken.Type == TokenFrom || p.curToken.Type != TokenQuotedString {
+		if p.curToken.Type == TokenComma {
+			p.nextToken()
+		}
+		// Stop if we hit FROM or non-quoted token
+		if p.curToken.Type == TokenFrom || p.curToken.Type != TokenQuotedString {
 			break
 		}
 		chunkID, err := p.parseQuotedString()
📝 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
// parseDevRemoveChunk parses:
// - REMOVE CHUNKS 'chunk_id1', 'chunk_id2' FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
// - REMOVE ALL CHUNKS FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
func (p *Parser) parseDevRemoveChunk() (*Command, error) {
cmd := NewCommand("dev_remove_chunks")
// Check if ALL CHUNKS - if we came here from TokenAll case, curToken is already ALL
if p.curToken.Type == TokenAll {
p.nextToken() // consume ALL
if p.curToken.Type != TokenChunks {
return nil, fmt.Errorf("expected CHUNKS after ALL")
}
p.nextToken() // consume CHUNKS
cmd.Params["delete_all"] = true
} else {
// curToken is TokenChunks, consume it first
p.nextToken()
// Multiple chunks: REMOVE CHUNKS 'id1' 'id2' FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name' (space-separated)
// Parse first chunk ID
chunkID, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected chunk_id: %w", err)
}
chunkIDs := []string{chunkID}
// Parse additional chunk IDs separated by spaces (each quoted)
for {
p.nextToken()
// Stop if we hit FROM or non-quoted token
if p.curToken.Type == TokenFrom || p.curToken.Type != TokenQuotedString {
// parseDevRemoveChunk parses:
// - REMOVE CHUNKS 'chunk_id1', 'chunk_id2' FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
// - REMOVE ALL CHUNKS FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name';
func (p *Parser) parseDevRemoveChunk() (*Command, error) {
cmd := NewCommand("dev_remove_chunks")
// Check if ALL CHUNKS - if we came here from TokenAll case, curToken is already ALL
if p.curToken.Type == TokenAll {
p.nextToken() // consume ALL
if p.curToken.Type != TokenChunks {
return nil, fmt.Errorf("expected CHUNKS after ALL")
}
p.nextToken() // consume CHUNKS
cmd.Params["delete_all"] = true
} else {
// curToken is TokenChunks, consume it first
p.nextToken()
// Multiple chunks: REMOVE CHUNKS 'id1' 'id2' FROM DOCUMENT 'doc_id' IN DATASET 'dataset_name' (space-separated)
// Parse first chunk ID
chunkID, err := p.parseQuotedString()
if err != nil {
return nil, fmt.Errorf("expected chunk_id: %w", err)
}
chunkIDs := []string{chunkID}
// Parse additional chunk IDs separated by spaces (each quoted)
for {
p.nextToken()
if p.curToken.Type == TokenComma {
p.nextToken()
}
// Stop if we hit FROM or non-quoted token
if p.curToken.Type == TokenFrom || p.curToken.Type != TokenQuotedString {
🤖 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 424 - 453, The parseDevRemoveChunk
flow in Parser currently only accepts space-separated chunk IDs and rejects the
documented comma-separated form, causing valid REMOVE CHUNKS input to fail.
Update the chunk-collection loop in parseDevRemoveChunk so it can consume
TokenComma between quoted chunk IDs, continuing to collect IDs until TokenFrom
is reached, and keep the existing parseQuotedString / TokenFrom handling intact.
Ensure the final params["chunk_ids"] contains all parsed IDs for both
comma-separated and space-separated inputs.

Comment on lines +1655 to +1658
httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer]
if httpClient.APIKey == nil && httpClient.LoginToken == nil {
return nil, fmt.Errorf("API key not set. Please login first")
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Guard the selected API client before reading auth fields.

These new auth checks dereference httpClient directly. If CurrentAPIServer is missing from APIServerClientMap, the CLI panics instead of returning the existing “HTTP Client is nil” style error from Request.

Proposed fix
 httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer]
+if httpClient == nil {
+	return nil, fmt.Errorf("API server client not configured: %s", c.Config.APIClientConfig.CurrentAPIServer)
+}
 if httpClient.APIKey == nil && httpClient.LoginToken == nil {
 	return nil, fmt.Errorf("API key not set. Please login first")
 }

Also applies to: 1717-1720, 1937-1940

🤖 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 1655 - 1658, The new auth checks
in the CLI path dereference the selected client before verifying it exists, so
first guard the lookup from
c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer] in the same flow
used by Request and the related call sites. If the selected API server is
missing or the client is nil, return the existing “HTTP Client is nil” style
error instead of reading APIKey/LoginToken, and apply the same nil-safe check in
all affected blocks (including the ones in the other matching locations) before
accessing auth fields.

@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 (9b726a5) to head (bf13079).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16447   +/-   ##
=======================================
  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 3202ec6 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 ☯️ refactor Pull request that refactor/refine code size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant