Repository navigation
Go CLI: refactor - #16299
Go CLI: refactor#16299
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughCLI command types are split into ChangesCLI command namespace refactor and API key surface
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 2 | ❌ 3❌ Failed checks (2 warnings, 1 inconclusive)
✅ Passed checks (2 passed)
✏️ 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. Comment |
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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
📒 Files selected for processing (10)
internal/cli/admin_parser.gointernal/cli/benchmark.gointernal/cli/cli.gointernal/cli/cli_http.gointernal/cli/parser.gointernal/cli/response.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/handler/document.gointernal/service/chat.go
| 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) |
There was a problem hiding this comment.
🎯 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.
| 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) |
There was a problem hiding this comment.
🎯 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.
| 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) |
There was a problem hiding this comment.
🗄️ 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.
| 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() | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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 Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>
There was a problem hiding this comment.
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 winPreserve the created key in the CLI response.
APICreateAPIKeyCommandsuccessfully parsesCommonDataResponse, but then dropscreateResult.Dataand returns only a success banner. That makesCREATE KEYunable 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 winFinish the payload rename for the
/keysAPI.
APIKeyResponsestill serializes the secret asjson:"token", so the new/api/v1/system/keysendpoints 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
📒 Files selected for processing (8)
internal/cli/cli_http.gointernal/cli/response.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/handler/api_token.gointernal/handler/document.gointernal/router/router.gointernal/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
Uh oh!
There was an error while loading. Please reload this page.