Skip to content

Go CLI: refactor - #16299

Merged
JinHai-CN merged 10 commits into
infiniflow:mainfrom
JinHai-CN:fix488
Jun 24, 2026
Merged

JinHai-CN merged 10 commits into
infiniflow:mainfrom
JinHai-CN:fix488

Conversation

@JinHai-CN

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

Copy link
Copy Markdown
Member
RAGFlow(api/default)> list dataset 'e93ab2c04ad111f1b17438a74640adcc' documents;
Total: 1

RAGFlow(api/default)> list datasets;


RAGFlow(api/default)> list chats;
Total: 2

RAGFlow(api/default)> list agents;
Total: 1

RAGFlow(api/default)> list searches;
Total: 1

RAGFlow(api/default)> list keys;
+----------------------------------+---------------+----------------------------------+-----------------------------------------------------+---------------+
| beta                             | create_time   | tenant_id                        | token                                               | update_time   |
+----------------------------------+---------------+----------------------------------+-----------------------------------------------------+---------------+
| GKsLEdSUkl76gJz1k_4fJpSQRIlWsiki | 1782285917523 | 2ba4881420fa11f19e9c38a74640adcc | ragflow-JgnarFSCUiV99oOvvMDei7ZzZg1cVlqGd1AMHrHeKE4 | 1782285917523 |
+----------------------------------+---------------+----------------------------------+-----------------------------------------------------+---------------+
RAGFlow(api/default)> create key;
SUCCESS

RAGFlow(api/default)> drop key 'ragflow-aA4R7AuUD158yh2LDh7IDBiqwOKFDKeTwUSQSLVdPdM';
SUCCESS

Signed-off-by: Jin Hai <[email protected]>
@JinHai-CN JinHai-CN added the ci Continue Integration label Jun 24, 2026
@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

CLI command types are split into admin_* and api_* namespaces. API list commands, API key commands, and matching parser, dispatch, response, service, handler, and route updates are added. ListChatsResponse gains Total, and ListDocuments returns a more specific dataset access error.

Changes

CLI command namespace refactor and API key surface

Layer / File(s) Summary
Admin command names and startup auth
internal/cli/admin_parser.go, internal/cli/cli.go
Admin login, logout, and ping parsers emit admin_* command names; parseAdminUserStatement is removed; parseAdminStartService is introduced; NewVerifyAuth is removed; VerifyAuth now uses login_user_on_startup and LoginUserByCommand.
API parser routing and dispatch
internal/cli/user_parser.go, internal/cli/parser.go, internal/cli/cli_http.go, internal/cli/benchmark.go
User parsing routes to api_* command names for auth and list statements; API LIST targets include configs, datasets, dataset documents, agents, chats, searches, and keys; CREATE KEY and DROP KEY route to API-key handlers; command dispatch and benchmark dataset checks use the new command names.
API list commands and list responses
internal/cli/user_command.go, internal/cli/response.go, internal/service/chat.go, internal/handler/document.go
ListDatasets becomes APIListDatasetsCommand; dataset document, agents, chats, and searches list commands are added; new CLI response types render agent/chat/search tables; ListChatsResponse gets Total; ListDocuments returns a more specific access error.
API key commands and routes
internal/cli/user_command.go, internal/handler/api_token.go, internal/router/router.go, internal/service/api_token.go
Token-named create/list/delete commands, handlers, service methods, request/response types, and routes are renamed to API key equivalents; /tokens wiring uses key-based handlers and /keys is added with the same key endpoints.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • infiniflow/ragflow#16213: Overlaps on the same admin command-name and dispatch updates in internal/cli/admin_parser.go and internal/cli/cli_http.go.
  • infiniflow/ragflow#16226: Adds related admin_start_service parsing and service-start wiring that matches the new admin parser branch here.

Suggested labels

☯️ refactor

🐇 I hopped through prefixes, neat and clean,
admin_ and api_ now gleam.
Chats, searches, keys line up in rows,
And totals bloom where the table shows.
A tidy burrow for commands to stay —
Hop-hop, the CLI found a clearer way.

🚥 Pre-merge checks | ✅ 2 | ❌ 3

❌ Failed checks (2 warnings, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description doesn't follow the required template and lacks the 'What problem does this PR solve?' and 'Type of change' sections. Add the template sections with a brief problem statement and select the appropriate change type checkbox.
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.
Title check ❓ Inconclusive The title is related to the CLI changes, but it is too generic to convey the main refactor. Rename it to something specific, e.g. 'Refactor Go CLI to add API-prefixed list and key commands'.
✅ Passed checks (2 passed)
Check name Status Explanation
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.

@JinHai-CN
JinHai-CN marked this pull request as ready for review June 24, 2026 06:31
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 24, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 5

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

Inline comments:
In `@internal/cli/benchmark.go`:
- Around line 240-242: The api_list_datasets benchmark branch is still calling
the legacy admin-only endpoint instead of the command’s current behavior. Update
the `case "api_list_datasets"` path in `benchmark.go` to mirror
`APIListDatasetsCommand` by using `GET /datasets` with the same user/api auth
flow and remove the old `user_name`-based `/admin/users/%s/datasets` request so
the benchmark exercises the correct command.

In `@internal/cli/response.go`:
- Around line 263-265: ListSearchesResponse.Type currently returns the chat
response identifier, which causes search-list responses to be misclassified.
Update the Type method on ListSearchesResponse in response.go to return the
correct searches response type string, and verify any downstream code using
ResponseIf.Type() will now route list-search results correctly.

In `@internal/cli/user_command.go`:
- Around line 400-409: The LIST DATASET DOCUMENTS handler is treating the parsed
dataset_name as a dataset_id, which can break requests when the display name
differs from the internal ID. Update the logic in the user command handler that
builds the /datasets/%s/documents URL to either resolve the provided dataset
name to its real ID before formatting the path, or change the parser/command
contract in user_parser.go so the parameter is explicitly a dataset ID and the
naming is consistent end to end.
- Around line 394-412: The dataset-document listing handler is still using the
wrong auth kind when API-token auth is enabled. Update the request path in the
api_list_dataset_documents flow so it chooses the auth kind the same way as the
other api_list_* handlers in user_command.go: use the API-token auth when
httpClient.useAPIToken is true, and only fall back to "web" for normal login
sessions before calling httpClient.Request.

In `@internal/cli/user_parser.go`:
- Around line 204-214: The parser in user_parser.go is not advancing past the
DOCUMENTS token before checking for an optional semicolon, so LIST DATASET ...
DOCUMENTS; leaves p.curToken stuck on TokenDocuments. Update the parsing flow in
the command-building logic around NewCommand("api_list_dataset_documents") to
consume DOCUMENTS with p.nextToken() immediately after validating it, then
perform the optional TokenSemicolon check so the parser ends in the correct
state.
🪄 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: 64b196ed-b99a-4956-ba9d-6ae2da563e19

📥 Commits

Reviewing files that changed from the base of the PR and between 68d2ca0 and 78188bf.

📒 Files selected for processing (10)
  • internal/cli/admin_parser.go
  • internal/cli/benchmark.go
  • internal/cli/cli.go
  • internal/cli/cli_http.go
  • internal/cli/parser.go
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/handler/document.go
  • internal/service/chat.go

Comment thread internal/cli/benchmark.go
Comment on lines +240 to 242
case "api_list_datasets":
userName, _ := cmd.Params["user_name"].(string)
resp, err = httpClient.Request("GET", fmt.Sprintf("/admin/users/%s/datasets", userName), "admin", 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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Benchmarking api_list_datasets still uses the old admin endpoint.

APIListDatasetsCommand now executes GET /datasets with user/api auth, but this benchmark path still calls GET /admin/users/%s/datasets with "admin" auth and an optional user_name. That no longer exercises the command being benchmarked, so the benchmark will report failures or measure the wrong endpoint.

🤖 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/benchmark.go` around lines 240 - 242, The api_list_datasets
benchmark branch is still calling the legacy admin-only endpoint instead of the
command’s current behavior. Update the `case "api_list_datasets"` path in
`benchmark.go` to mirror `APIListDatasetsCommand` by using `GET /datasets` with
the same user/api auth flow and remove the old `user_name`-based
`/admin/users/%s/datasets` request so the benchmark exercises the correct
command.

Comment thread internal/cli/response.go Resolved
Comment on lines +394 to +412
httpClient := c.APIServerClientMap[c.Config.APIClientConfig.CurrentAPIServer]
// Determine auth kind based on whether API token is being used
if httpClient.LoginToken == nil && !httpClient.useAPIToken {
return nil, fmt.Errorf("no authorization")
}

datasetID, ok := cmd.Params["dataset_id"].(string)
if !ok {
return nil, fmt.Errorf("no dataset id")
}

page := 1
pageSize := 10
keywords := ""
returnEmptyMetadata := "true"
url := fmt.Sprintf("/datasets/%s/documents?page=%d&page_size=%d&keywords=%s&return_empty_metadata=%s", datasetID, page, pageSize, keywords, returnEmptyMetadata)

// Normal mode
resp, err := httpClient.Request("GET", url, "web", 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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Honor API-token auth for dataset-document listing.

This handler allows useAPIToken, but Line 412 still hardcodes "web". In an API-token-only session, api_list_dataset_documents will always call the endpoint with the wrong auth kind, unlike the other new api_list_* handlers in this 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/cli/user_command.go` around lines 394 - 412, The dataset-document
listing handler is still using the wrong auth kind when API-token auth is
enabled. Update the request path in the api_list_dataset_documents flow so it
chooses the auth kind the same way as the other api_list_* handlers in
user_command.go: use the API-token auth when httpClient.useAPIToken is true, and
only fall back to "web" for normal login sessions before calling
httpClient.Request.

Comment on lines +400 to +409
datasetID, ok := cmd.Params["dataset_id"].(string)
if !ok {
return nil, fmt.Errorf("no dataset id")
}

page := 1
pageSize := 10
keywords := ""
returnEmptyMetadata := "true"
url := fmt.Sprintf("/datasets/%s/documents?page=%d&page_size=%d&keywords=%s&return_empty_metadata=%s", datasetID, page, pageSize, keywords, returnEmptyMetadata)

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.

🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift

The parser passes a dataset name, but this handler uses it as a dataset ID.

internal/cli/user_parser.go defines the grammar as LIST DATASET 'dataset_name' DOCUMENTS;, yet this code inserts that value directly into /datasets/%s/documents. Unless the API path accepts names, any dataset whose display name differs from its internal ID will fail here. Either resolve the name to an ID before issuing the request, or change the command contract to require an ID explicitly.

🤖 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 400 - 409, The LIST DATASET
DOCUMENTS handler is treating the parsed dataset_name as a dataset_id, which can
break requests when the display name differs from the internal ID. Update the
logic in the user command handler that builds the /datasets/%s/documents URL to
either resolve the provided dataset name to its real ID before formatting the
path, or change the parser/command contract in user_parser.go so the parameter
is explicitly a dataset ID and the naming is consistent end to end.

Comment on lines +204 to 214
if p.curToken.Type != TokenDocuments {
return nil, fmt.Errorf("expected DOCUMENTS")
}

cmd := NewCommand("api_list_dataset_documents")
cmd.Params["dataset_id"] = datasetID

// Semicolon is optional for UNSET TOKEN
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 | 🟠 Major | ⚡ Quick win

Consume DOCUMENTS before checking for the semicolon.

After Line 204 succeeds, p.curToken is still TokenDocuments. Because this function never advances past that token, Line 212 can never see TokenSemicolon, so LIST DATASET 'x' DOCUMENTS; returns with the parser left on DOCUMENTS.

Suggested fix
 	if p.curToken.Type != TokenDocuments {
 		return nil, fmt.Errorf("expected DOCUMENTS")
 	}
+	p.nextToken() // consume DOCUMENTS
 
 	cmd := NewCommand("api_list_dataset_documents")
 	cmd.Params["dataset_id"] = datasetID
📝 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 p.curToken.Type != TokenDocuments {
return nil, fmt.Errorf("expected DOCUMENTS")
}
cmd := NewCommand("api_list_dataset_documents")
cmd.Params["dataset_id"] = datasetID
// Semicolon is optional for UNSET TOKEN
if p.curToken.Type == TokenSemicolon {
p.nextToken()
}
if p.curToken.Type != TokenDocuments {
return nil, fmt.Errorf("expected DOCUMENTS")
}
p.nextToken() // consume DOCUMENTS
cmd := NewCommand("api_list_dataset_documents")
cmd.Params["dataset_id"] = datasetID
// Semicolon is optional for UNSET TOKEN
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/user_parser.go` around lines 204 - 214, The parser in
user_parser.go is not advancing past the DOCUMENTS token before checking for an
optional semicolon, so LIST DATASET ... DOCUMENTS; leaves p.curToken stuck on
TokenDocuments. Update the parsing flow in the command-building logic around
NewCommand("api_list_dataset_documents") to consume DOCUMENTS with p.nextToken()
immediately after validating it, then perform the optional TokenSemicolon check
so the parser ends in the correct state.

@codecov

codecov Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (a8651e7) to head (9f132dd).

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

@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.

Caution

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

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

933-946: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Preserve the created key in the CLI response.

APICreateAPIKeyCommand successfully parses CommonDataResponse, but then drops createResult.Data and returns only a success banner. That makes CREATE KEY unable to show the generated secret on creation.

Suggested fix
 	var createResult CommonDataResponse
 	if err = json.Unmarshal(resp.Body, &createResult); err != nil {
 		return nil, fmt.Errorf("create key failed: invalid JSON (%w)", err)
 	}

 	if createResult.Code != 0 {
 		return nil, fmt.Errorf("%s", createResult.Message)
 	}

-	var result SimpleResponse
-	result.Code = 0
-	result.Message = "API Key created successfully"
-	result.Duration = resp.Duration
-	return &result, nil
+	createResult.Duration = resp.Duration
+	return &createResult, 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 933 - 946, APICreateAPIKeyCommand
currently discards the generated key by parsing CommonDataResponse and then
returning only a SimpleResponse success message. Update this flow to preserve
createResult.Data in the returned response so the CLI can display the newly
created secret, while keeping the existing success status, duration, and error
handling around json.Unmarshal and createResult.Code.
internal/service/api_token.go (1)

25-33: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Finish the payload rename for the /keys API.

APIKeyResponse still serializes the secret as json:"token", so the new /api/v1/system/keys endpoints return token-shaped payloads even though the route, handler, and CLI contract were renamed to keys. That leaves the API surface half-renamed for clients.

Suggested fix
 type APIKeyResponse struct {
 	TenantID   string  `json:"tenant_id"`
-	Token      string  `json:"token"`
+	Token      string  `json:"key"`
 	DialogID   *string `json:"dialog_id,omitempty"`
 	Source     *string `json:"source,omitempty"`
 	Beta       *string `json:"beta,omitempty"`
 	CreateTime *int64  `json:"create_time,omitempty"`
 	UpdateTime *int64  `json:"update_time,omitempty"`
 }
🤖 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/api_token.go` around lines 25 - 33, The
`/api/v1/system/keys` payload is only partially renamed because `APIKeyResponse`
still exposes the secret field as `Token`. Update the response struct to use the
new keys-oriented JSON name consistently, and make sure any code that constructs
or consumes `APIKeyResponse` is aligned with that renamed field so the API,
handler, and CLI contract all return key-shaped payloads. Use `APIKeyResponse`
and its JSON tags as the main place to locate and complete the rename.
🤖 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.

Outside diff comments:
In `@internal/cli/user_command.go`:
- Around line 933-946: APICreateAPIKeyCommand currently discards the generated
key by parsing CommonDataResponse and then returning only a SimpleResponse
success message. Update this flow to preserve createResult.Data in the returned
response so the CLI can display the newly created secret, while keeping the
existing success status, duration, and error handling around json.Unmarshal and
createResult.Code.

In `@internal/service/api_token.go`:
- Around line 25-33: The `/api/v1/system/keys` payload is only partially renamed
because `APIKeyResponse` still exposes the secret field as `Token`. Update the
response struct to use the new keys-oriented JSON name consistently, and make
sure any code that constructs or consumes `APIKeyResponse` is aligned with that
renamed field so the API, handler, and CLI contract all return key-shaped
payloads. Use `APIKeyResponse` and its JSON tags as the main place to locate and
complete the rename.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: a9e3727a-00bd-4199-a429-2f6b32d8f20e

📥 Commits

Reviewing files that changed from the base of the PR and between 78188bf and 9f132dd.

📒 Files selected for processing (8)
  • internal/cli/cli_http.go
  • internal/cli/response.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/handler/api_token.go
  • internal/handler/document.go
  • internal/router/router.go
  • internal/service/api_token.go
✅ Files skipped from review due to trivial changes (1)
  • internal/handler/document.go
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/cli/cli_http.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant