Repository navigation
Go CLI: Add create and drop commands - #16430
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughAdds ChangesCLI memories and drop command expansion
Build script strip flag
Sequence Diagram(s)sequenceDiagram
participant Parser as user_parser.go
participant CLI as user_command.go
participant Response as response.go
Parser->>CLI: api_list_memories / api_drop_* command
CLI->>Response: build ListMemoriesResponse or HandleSimpleResponse
Response-->>CLI: formatted output or error response
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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]>
There was a problem hiding this comment.
Actionable comments posted: 6
🤖 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 `@build.sh`:
- Around line 426-435: Normalize the parsed argv before dispatch in main so
every branch uses the filtered argument list consistently. The current args
handling reads args[0] for command selection but the --test path still relies on
the original positional parameters and shift logic, which can preserve --strip
or mis-handle forwarded test args. Update the main argument flow around the args
array and the --test case so it rebases positional parameters or otherwise
consumes args exclusively before branching.
In `@internal/cli/common_command.go`:
- Around line 1618-1624: The lookup helpers are asserting the wrong response
type: APIListAgentsCommand returns *ListAgentsResponse and APIListChatsCommand
returns *ListChatsResponse, so the current *CommonResponse casts in the
agent/chat drop flow always fail. Update the type assertions in the relevant
lookup logic used by DROP AGENT and DROP CHAT to match the actual list response
types, then continue scanning the returned Items for the matching ID before
returning the selected name.
In `@internal/cli/response.go`:
- Around line 311-320: The ListMemoriesResponse.PrintOut method always prints a
human-readable Total line before calling PrintTableSimpleByFormat, which breaks
OutputFormatJSON. Update PrintOut to branch on r.OutputFormat (or equivalent) so
JSON mode emits only valid JSON and skips the Total prefix, while preserving the
existing table-style output for non-JSON formats. Use
ListMemoriesResponse.PrintOut, PrintTableSimpleByFormat, and OutputFormatJSON to
locate the change.
In `@internal/cli/user_command.go`:
- Around line 1779-1787: The DROP handlers are still using copied CREATE labels
in their error paths, which makes failures point to the wrong operation. Update
the error messages in the relevant delete/drop command functions (including the
code paths around APIDropDatasetCommand and the other DROP handlers mentioned in
the review) so they say “failed to delete/drop …” instead of “failed to create
…”, and pass the correct delete/drop operation name into HandleSimpleResponse
rather than “create provider instance”.
- Line 1050: The request in the create/drop/search/memory handlers is still
using a hardcoded auth kind of web even when useAPIKey is supported, which
breaks API-key-only sessions. Update the request construction in the affected
command handlers to select the auth kind dynamically based on the session/auth
settings, following the same pattern already used by APIListMemoriesCommand.
Make this change in each affected handler so CREATE/DROP DATASET, SEARCH, and
MEMORY all pass the correct auth kind into httpClient.Request.
In `@internal/cli/user_parser.go`:
- Around line 1263-1277: The parseAPICreateDataset flow currently only parses
dataset_name, which removes support for existing dataset-create options. Update
the Parser’s parseAPICreateDataset and the api_create_dataset Command parameter
handling to accept and preserve the full set of fields still supported by
internal/service/dataset.go, including embedding_model, chunk_method/parser_id,
pipeline_id, and parser_config. Make sure the CLI parser can express the same
dataset creation options as before instead of narrowing the command to a single
quoted name.
🪄 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: 15614317-e01b-4fba-a17f-fff7800c4f57
📒 Files selected for processing (11)
build.shinternal/cli/admin_parser.gointernal/cli/cli_http.gointernal/cli/common_command.gointernal/cli/lexer.gointernal/cli/response.gointernal/cli/types.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/development.mdinternal/service/dataset.go
💤 Files with no reviewable changes (1)
- internal/cli/admin_parser.go
| # Parse --strip / -s before other arguments | ||
| local args=() | ||
| for arg in "$@"; do | ||
| case "$arg" in | ||
| --strip|-s) STRIP_SYMBOLS="1" ;; | ||
| *) args+=("$arg") ;; | ||
| esac | ||
| done | ||
|
|
||
| case "${args[0]:-}" in |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Normalize the filtered argv before dispatch.
main() now selects the command from args[0], but the --test branch still reads ${2} / shifts the original $@. That breaks forwarding for combinations like ./build.sh --strip --test -- -run TestFoo and can leak --strip into go test when it appears after the command. Rebind $@ to the filtered array (or use args consistently) before the case.
Suggested fix
main() {
# Parse --strip / -s before other arguments
local args=()
+ local passthrough=0
for arg in "$@"; do
- case "$arg" in
- --strip|-s) STRIP_SYMBOLS="1" ;;
- *) args+=("$arg") ;;
- esac
+ if [ "$passthrough" -eq 1 ]; then
+ args+=("$arg")
+ continue
+ fi
+ case "$arg" in
+ --) passthrough=1; args+=("$arg") ;;
+ --strip|-s) STRIP_SYMBOLS="1" ;;
+ *) args+=("$arg") ;;
+ esac
done
+ set -- "${args[@]}"
- case "${args[0]:-}" in
+ case "${1:-}" in📝 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.
| # Parse --strip / -s before other arguments | |
| local args=() | |
| for arg in "$@"; do | |
| case "$arg" in | |
| --strip|-s) STRIP_SYMBOLS="1" ;; | |
| *) args+=("$arg") ;; | |
| esac | |
| done | |
| case "${args[0]:-}" in | |
| # Parse --strip / -s before other arguments | |
| local args=() | |
| local passthrough=0 | |
| for arg in "$@"; do | |
| if [ "$passthrough" -eq 1 ]; then | |
| args+=("$arg") | |
| continue | |
| fi | |
| case "$arg" in | |
| --) passthrough=1; args+=("$arg") ;; | |
| --strip|-s) STRIP_SYMBOLS="1" ;; | |
| *) args+=("$arg") ;; | |
| esac | |
| done | |
| set -- "${args[@]}" | |
| case "${1:-}" in |
🤖 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 `@build.sh` around lines 426 - 435, Normalize the parsed argv before dispatch
in main so every branch uses the filtered argument list consistently. The
current args handling reads args[0] for command selection but the --test path
still relies on the original positional parameters and shift logic, which can
preserve --strip or mis-handle forwarded test args. Update the main argument
flow around the args array and the --test case so it rebases positional
parameters or otherwise consumes args exclusively before branching.
| response, err := c.APIListAgentsCommand(nil) | ||
| if err != nil { | ||
| return "", err | ||
| } | ||
| commonResponse, ok := response.(*CommonResponse) | ||
| if !ok { | ||
| return "", fmt.Errorf("invalid response") |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Use the actual list response types in these lookups.
APIListAgentsCommand returns *ListAgentsResponse and APIListChatsCommand returns *ListChatsResponse, so these *CommonResponse assertions always fail. DROP AGENT and DROP CHAT therefore never reach the ID scan and always error with invalid response.
Also applies to: 1654-1660
🤖 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 1618 - 1624, The lookup helpers
are asserting the wrong response type: APIListAgentsCommand returns
*ListAgentsResponse and APIListChatsCommand returns *ListChatsResponse, so the
current *CommonResponse casts in the agent/chat drop flow always fail. Update
the type assertions in the relevant lookup logic used by DROP AGENT and DROP
CHAT to match the actual list response types, then continue scanning the
returned Items for the matching ID before returning the selected name.
| func (r *ListMemoriesResponse) PrintOut() { | ||
| if r.Code == 0 { | ||
| total := r.Data["total_count"].(float64) | ||
| fmt.Printf("Total: %0.0f\n", total) | ||
| docs := r.Data["memory_list"].([]interface{}) | ||
| table := make([]map[string]interface{}, 0) | ||
| for _, doc := range docs { | ||
| table = append(table, doc.(map[string]interface{})) | ||
| } | ||
| PrintTableSimpleByFormat(table, r.OutputFormat) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Keep LIST MEMORIES JSON output valid.
Line 314 always prints a human-readable Total: line before PrintTableSimpleByFormat, so OutputFormatJSON can never produce valid JSON here. That breaks scripted consumers of the JSON mode.
Suggested fix
func (r *ListMemoriesResponse) PrintOut() {
if r.Code == 0 {
total := r.Data["total_count"].(float64)
- fmt.Printf("Total: %0.0f\n", total)
+ if r.OutputFormat != OutputFormatJSON {
+ fmt.Printf("Total: %0.0f\n", total)
+ }
docs := r.Data["memory_list"].([]interface{})
table := make([]map[string]interface{}, 0)
for _, doc := range docs {
table = append(table, doc.(map[string]interface{}))
}📝 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.
| func (r *ListMemoriesResponse) PrintOut() { | |
| if r.Code == 0 { | |
| total := r.Data["total_count"].(float64) | |
| fmt.Printf("Total: %0.0f\n", total) | |
| docs := r.Data["memory_list"].([]interface{}) | |
| table := make([]map[string]interface{}, 0) | |
| for _, doc := range docs { | |
| table = append(table, doc.(map[string]interface{})) | |
| } | |
| PrintTableSimpleByFormat(table, r.OutputFormat) | |
| func (r *ListMemoriesResponse) PrintOut() { | |
| if r.Code == 0 { | |
| total := r.Data["total_count"].(float64) | |
| if r.OutputFormat != OutputFormatJSON { | |
| fmt.Printf("Total: %0.0f\n", total) | |
| } | |
| docs := r.Data["memory_list"].([]interface{}) | |
| table := make([]map[string]interface{}, 0) | |
| for _, doc := range docs { | |
| table = append(table, doc.(map[string]interface{})) | |
| } | |
| PrintTableSimpleByFormat(table, r.OutputFormat) |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@internal/cli/response.go` around lines 311 - 320, The
ListMemoriesResponse.PrintOut method always prints a human-readable Total line
before calling PrintTableSimpleByFormat, which breaks OutputFormatJSON. Update
PrintOut to branch on r.OutputFormat (or equivalent) so JSON mode emits only
valid JSON and skips the Total prefix, while preserving the existing table-style
output for non-JSON formats. Use ListMemoriesResponse.PrintOut,
PrintTableSimpleByFormat, and OutputFormatJSON to locate the change.
| var createResult CommonDataResponse | ||
| if err = json.Unmarshal(resp.Body, &createResult); err != nil { | ||
| return nil, fmt.Errorf("create dataset failed: invalid JSON (%w)", err) | ||
| resp, err := httpClient.Request("POST", "/datasets", "web", nil, payload) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Don't hardcode web in commands that explicitly support API-key auth.
These handlers all allow useAPIKey, but the request still goes out with authKind == "web". In API-key-only sessions, CREATE/DROP DATASET, SEARCH, and MEMORY will fail even though the local authorization check passed. APIListMemoriesCommand right above already shows the correct auth-kind selection pattern.
Suggested fix pattern
+ authKind := "web"
+ if httpClient.useAPIKey {
+ authKind = "api"
+ }
+ if httpClient.LoginToken != nil {
+ authKind = "web"
+ }
- resp, err := httpClient.Request("DELETE", "/datasets", "web", nil, payload)
+ resp, err := httpClient.Request("DELETE", "/datasets", authKind, nil, payload)Apply the same pattern to each changed create/drop handler above.
Also applies to: 1157-1157, 1203-1203, 1778-1778, 1817-1817, 1856-1856, 1892-1892, 1928-1928
🤖 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` at line 1050, The request in the
create/drop/search/memory handlers is still using a hardcoded auth kind of web
even when useAPIKey is supported, which breaks API-key-only sessions. Update the
request construction in the affected command handlers to select the auth kind
dynamically based on the session/auth settings, following the same pattern
already used by APIListMemoriesCommand. Make this change in each affected
handler so CREATE/DROP DATASET, SEARCH, and MEMORY all pass the correct auth
kind into httpClient.Request.
| // CREATE DATASET 'abc'; | ||
| func (p *Parser) parseAPICreateDataset() (*Command, error) { | ||
| p.nextToken() // consume DATASET | ||
| datasetName, err := p.parseQuotedString() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| p.nextToken() | ||
| if p.curToken.Type != TokenWith { | ||
| return nil, fmt.Errorf("expected WITH") | ||
| } | ||
| p.nextToken() | ||
| if p.curToken.Type != TokenEmbedding { | ||
| return nil, fmt.Errorf("expected EMBEDDING") | ||
| } | ||
| p.nextToken() | ||
|
|
||
| embedding, err := p.parseQuotedString() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
|
|
||
| p.nextToken() | ||
| cmd := NewCommand("api_create_dataset") | ||
| cmd.Params["dataset_name"] = datasetName | ||
| cmd.Params["embedding"] = embedding | ||
|
|
||
| if p.curToken.Type == TokenParser { | ||
| p.nextToken() | ||
| var parserType string | ||
| parserType, err = p.parseQuotedString() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| cmd.Params["parser_type"] = parserType | ||
| p.nextToken() | ||
| } else if p.curToken.Type == TokenPipeline { | ||
| p.nextToken() | ||
| var pipeline string | ||
| pipeline, err = p.parseQuotedString() | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| cmd.Params["pipeline"] = pipeline | ||
| p.nextToken() | ||
| } else { | ||
| return nil, fmt.Errorf("expected PARSER or PIPELINE") | ||
| } | ||
|
|
||
| // Semicolon is optional | ||
| if p.curToken.Type == TokenSemicolon { | ||
| p.nextToken() | ||
| } | ||
|
|
||
| cmd := NewCommand("api_create_dataset") | ||
| cmd.Params["dataset_name"] = datasetName |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | 🏗️ Heavy lift
This narrows CREATE DATASET into a breaking regression.
The parser now only accepts a dataset name, but internal/service/dataset.go still supports dataset-create fields such as embedding_model, chunk_method/parser_id, pipeline_id, and parser_config. Existing CLI flows that relied on those options can no longer be expressed, so this is a behavior removal rather than a refactor.
🤖 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 1263 - 1277, The
parseAPICreateDataset flow currently only parses dataset_name, which removes
support for existing dataset-create options. Update the Parser’s
parseAPICreateDataset and the api_create_dataset Command parameter handling to
accept and preserve the full set of fields still supported by
internal/service/dataset.go, including embedding_model, chunk_method/parser_id,
pipeline_id, and parser_config. Make sure the CLI parser can express the same
dataset creation options as before instead of narrowing the command to a single
quoted name.
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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/user_command.go`:
- Line 3699: The response label passed from the document parse command is
incorrect and causes misleading helper errors. Update the call in the document
parse flow to use the parse operation name instead of "list documents", keeping
the existing HandleSimpleResponse path but aligning the operation string with
the endpoint being invoked.
🪄 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: 5d5d5544-fa34-4854-b828-0ae867125d72
📒 Files selected for processing (1)
internal/cli/user_command.go
| result.Duration = resp.Duration | ||
|
|
||
| return &result, nil | ||
| return HandleSimpleResponse(resp, "list documents") |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
Use the parse operation name here.
This command posts to the document parse endpoint, so "list documents" will produce misleading helper errors such as invalid-JSON failures.
Proposed fix
- return HandleSimpleResponse(resp, "list documents")
+ return HandleSimpleResponse(resp, "parse documents")📝 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.
| return HandleSimpleResponse(resp, "list documents") | |
| return HandleSimpleResponse(resp, "parse documents") |
🤖 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` at line 3699, The response label passed from
the document parse command is incorrect and causes misleading helper errors.
Update the call in the document parse flow to use the parse operation name
instead of "list documents", keeping the existing HandleSimpleResponse path but
aligning the operation string with the endpoint being invoked.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16430 +/- ##
=======================================
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:
|
What problem does this PR solve?
Type of change