Repository navigation
Fix cli login - #14658
Fix cli login#14658
Conversation
Signed-off-by: Jin Hai <[email protected]>
📝 WalkthroughWalkthroughThis PR refactors the HTTP request API across the CLI by removing the per-call ChangesHTTP Client Refactoring: Remove useAPIBase Parameter
Independent Changes
🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 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 |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (8)
internal/cli/filesystem/file.go (1)
545-579:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winInconsistent auth kind for DELETE:
DeleteFileuses"api"while all other/filesoperations use"auto".Every other
/filescall in this provider (lines 282) and across the codebase uses"auto"for GET and POST requests. TheDeleteFilemethod hardcodes"api"instead. If the Python backend's DELETE endpoint requires explicit API-token authentication (and"auto"would fall back to"web"when no API token is configured), add a brief comment explaining that requirement. Otherwise, change line 551 to use"auto"for consistency with the rest of the codebase.🤖 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/filesystem/file.go` around lines 545 - 579, DeleteFile uses p.httpClient.Request(..., "api", ...) which is inconsistent with other /files calls that use "auto"; update the auth kind in DeleteFile to "auto" for consistency (change the auth argument passed to p.httpClient.Request in the DeleteFile function) and run tests; if the DELETE endpoint truly requires an explicit API token instead of the "auto" fallback, keep "api" but add a brief comment above DeleteFile explaining why DELETE must force "api" auth so future readers understand the deviation.internal/cli/common_command.go (1)
204-231:⚠️ Potential issue | 🔴 Critical | ⚡ Quick winNon-admin
Logoutpath will 404 after this PR.In line 179, the non-admin login path was migrated from
/user/loginto/auth/login. However,Logoutat line 213 still calls/user/logout.The
BuildURLmethod (http_client.go:73) always prependsAPIBase()(line 64), which returns/api/{version}(e.g.,/api/v1). This means:
/auth/loginresolves to/api/v1/auth/login✓ (registered at router.go:108)/user/logoutresolves to/api/v1/user/logout✗ (not registered)The router's non-admin logout endpoint is now at
/api/v1/auth/logout(router.go:138). The legacy/v1/user/logoutendpoint (router.go:96) is registered at the root level without the/api/prefix and will not be reached.Align the logout path with login:
🔧 Proposed fix
var path string if c.ServerType == "admin" { path = "/admin/logout" } else { - path = "/user/logout" + path = "/auth/logout" }🤖 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 204 - 231, The non-admin Logout currently uses "/user/logout" which, due to BuildURL and APIBase behavior, resolves to a non-existent /api/.../user/logout and causes 404s; update the path selection in RAGFlowClient.Logout so that when ServerType != "admin" it uses "/auth/logout" (keep "/admin/logout" for admin), ensuring the request hits the router's registered /api/v1/auth/logout endpoint; locate the path logic in the Logout method and change the non-admin branch to "/auth/logout".internal/cli/admin_command.go (1)
27-93:⚠️ Potential issue | 🟠 Major | 💤 Low valueShowAdminVersion should use
"admin"authKind, not"web".The
/admin/versionendpoint is protected byAuthMiddleware()in the server's route setup (internal/admin/router.go:110), requiring a valid authorization token. The/admin/pingendpoint correctly uses"web"because it's in the "Public routes" section (router.go:44), butShowAdminVersionmust use"admin"to correctly indicate that authentication is required. Although both currently attach the LoginToken identically, using"web"misrepresents the endpoint's authentication requirement and will cause runtime failures if the token is unavailable.🤖 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_command.go` around lines 27 - 93, ShowAdminVersion is using the wrong authKind ("web") for the protected /admin/version endpoint; update both calls to c.HTTPClient.RequestWithIterations and c.HTTPClient.Request inside ShowAdminVersion to use "admin" (leave PingAdmin as "web"), so the request attaches/represents admin auth correctly and prevents runtime auth failures.internal/cli/user_command.go (4)
1601-1603:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winWrong error message:
"images not provided"whenvideosparam is missing.-return nil, fmt.Errorf("images not provided") +return nil, fmt.Errorf("videos not provided")Same copy-paste issue on Line 1627 for
files:-return nil, fmt.Errorf("images not provided") +return nil, fmt.Errorf("files not provided")🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@internal/cli/user_command.go` around lines 1601 - 1603, The error message is incorrect for missing params: when extracting videos via videos, ok := cmd.Params["videos"].([]string) return the correct error string ("videos not provided") instead of "images not provided"; likewise locate the analogous extraction for files (files, ok := cmd.Params["files"].([]string) around the mentioned copy-paste and change its error to "files not provided". Update the error fmt.Errorf calls for the videos and files parameter checks to the appropriate param name so logs and errors accurately reflect the missing parameter.
769-880: 🛠️ Refactor suggestion | 🟠 Major | ⚡ Quick win
CreateDatasetandCreateDatasetInDocEngineare byte-for-byte duplicates — consolidate.Both functions share identical validation, payload construction, HTTP call, and response parsing. Keeping two copies risks the two diverging silently.
♻️ Proposed fix
func (c *RAGFlowClient) CreateDataset(cmd *Command) (ResponseIf, error) { - // ... (full duplicate body) + return c.CreateDatasetInDocEngine(cmd) }🤖 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 769 - 880, Both CreateDataset and CreateDatasetInDocEngine are identical; extract the shared logic into a single helper (e.g., createDatasetTable or createDatasetInDocEngineHelper) that performs param validation (dataset_name, vector_size), calls getDatasetID, builds payload, invokes c.HTTPClient.Request("POST", "/kb/doc_engine_table", ...), parses resp.JSON(), converts code to SimpleResponse and returns it, then have CreateDataset and CreateDatasetInDocEngine delegate to that helper (or remove one and forward to the other) to avoid duplication and keep getDatasetID, HTTPClient.Request, and SimpleResponse usage centralized.
1773-1779:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winCopy-paste error messages in non-stream
ChatToModelpath refer to"list instance models".-return nil, fmt.Errorf("failed to list instance models: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) +return nil, fmt.Errorf("failed to chat with model: HTTP %d, body: %s", resp.StatusCode, string(resp.Body)) ... -return nil, fmt.Errorf("failed to list instance models: invalid JSON (%w)", err) +return nil, fmt.Errorf("failed to chat with model: invalid JSON (%w)", err)🤖 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 1773 - 1779, The error messages in the non-stream ChatToModel path wrongly mention "list instance models" — update the strings in the ChatToModel handler (where resp and result NonStreamResponse are used) to reference "chat to model" (or "ChatToModel") instead: change the HTTP error fmt.Errorf("failed to list instance models: HTTP %d, body: %s", ...) and the JSON error fmt.Errorf("failed to list instance models: invalid JSON (%w)", err) to descriptive messages like "failed to chat to model: HTTP %d, body: %s" and "failed to chat to model: invalid JSON (%w)", respectively so the errors reflect the correct operation.
355-367:⚠️ Potential issue | 🟠 Major | ⚡ Quick win
authKindoverride silently ignores an explicitly set API token when a login token is also present.The second
if c.HTTPClient.LoginToken != ""block unconditionally resetsauthKindback to"web", overriding the"api"value that was just set becauseuseAPIToken == true. When both are present, the API token is silently skipped.The intended precedence (login token wins over API token) should be expressed without the misleading intermediate assignment:
🐛 Proposed fix
-authKind := "web" -if c.HTTPClient.useAPIToken { - authKind = "api" -} - -if c.HTTPClient.LoginToken != "" { - authKind = "web" +authKind := "api" +if c.HTTPClient.LoginToken != "" { + authKind = "web" // login session takes precedence over API token }🤖 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 355 - 367, The authKind logic currently sets authKind = "api" when c.HTTPClient.useAPIToken is true then unconditionally overwrites it to "web" if c.HTTPClient.LoginToken != ""; change the logic to express precedence explicitly by checking c.HTTPClient.LoginToken first and setting authKind = "web" if present, otherwise set authKind = "api" when c.HTTPClient.useAPIToken is true (or leave as default "web" if neither), removing the redundant final if that overrides the API selection; update the block that references authKind, c.HTTPClient.LoginToken and c.HTTPClient.useAPIToken in user_command.go accordingly.internal/cli/http_client.go (1)
183-191:⚠️ Potential issue | 🟠 Major | ⚡ Quick winSingle-iteration benchmark path always counts a successful request as a failure.
response.Code = resp.StatusCodesetsCodeto the HTTP status (e.g.,200), soif response.Code == 0is never true for a live HTTP response. Every successful single-iteration benchmark request is incorrectly recorded inFailureCount. The multi-iteration path (line 254) correctly checksresp.StatusCode == 200.🐛 Proposed fix
response.Code = resp.StatusCode response.Duration = totalDuration -if response.Code == 0 { +if resp.StatusCode == 200 { response.SuccessCount = 1 } else { response.FailureCount = 1 }🤖 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/http_client.go` around lines 183 - 191, The single-iteration branch incorrectly treats any non-zero response.Code as failure; change the check to evaluate the actual HTTP status (resp.StatusCode) like the multi-iteration path does (e.g., treat status 200 as success or use a 2xx range) so that response.SuccessCount/FailureCount are set based on resp.StatusCode rather than response.Code; update the block that sets response.Code, response.Duration and then sets SuccessCount/FailureCount (referencing response.Code, resp.StatusCode) to use resp.StatusCode == 200 (or resp.StatusCode >=200 && resp.StatusCode <300) for success.
🧹 Nitpick comments (9)
internal/cli/user_parser.go (1)
65-110: 💤 Low valueLGTM — token consumption sequence is correct.
The refactored
parseRegisterCommandfollows the samenextToken-before-check /nextToken-after-parse-quoted-string contract that every other parser in this file uses. The full token walk forREGISTER USER 'email' AS 'nickname' PASSWORD 'pass'is correct with no off-by-one or double-advance issues.One nit: the comment on line 78 says
// consume Email, but the value is stored asuser_name. Consider// consume user_namefor consistency with the param key.✏️ Suggested comment tweak
- p.nextToken() // consume Email + p.nextToken() // consume user_name🤖 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 65 - 110, Update the inline comment in parseRegisterCommand to accurately reflect the consumed token name: change the comment that currently reads "// consume Email" to something like "// consume user_name" (or "// consume USER token / user_name") so it matches the param key cmd.Params["user_name"] and the behavior in the function.internal/cli/filesystem/dataset.go (1)
326-327: 💤 Low valueStale
useAPIBase=falsecomment.The accompanying comment still references the removed
useAPIBaseflag while the call now passes"auto". Same issue at Line 610. Update or drop the comments so they don't mislead future readers about how routing/auth is selected.🤖 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/filesystem/dataset.go` around lines 326 - 327, The comment above the HTTP call to p.httpClient.Request (the POST to "/chunk/retrieval_test") is stale because it mentions a removed useAPIBase flag while the request now passes "auto"; update or remove that comment (and the similar one near the second occurrence around Line 610) so it accurately reflects current behavior — either explain that routing/auth selection is handled by the client when "auto" is passed or drop the misleading note entirely; locate the call sites by the p.httpClient.Request("POST", "/chunk/retrieval_test", "auto", ...) invocations and edit the comments accordingly.internal/cli/common_command.go (2)
30-40: 💤 Low valueStale
useAPIBasereferences in comments.The comments at Lines 32-33 and 96-97 still describe routing in terms of the removed
useAPIBase=true/falseargument. Worth updating to the newauthKindmodel.🤖 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 30 - 40, Comments inside the LoginUserInteractive function reference the removed useAPIBase flag; update them to reflect the new authKind model by replacing references to "useAPIBase=true/false" with the current auth routing terminology (e.g., authKind "admin" vs "user" or similar) and ensure the comment explains that ServerType determines the ping path ("/admin/ping" for admin, "/system/ping" for user) and how authKind is chosen/used elsewhere; check symbols LoginUserInteractive and ServerType and adjust any other stale comments in that function to reference authKind consistently.
175-202: 💤 Low valueUse an explicit
authKindvalue instead of empty string for code clarity.The empty
authKindat line 182 works correctly—theHeaders()method matches no cases for"", returning an empty map, which correctly omits the Authorization header on login requests. However, this stands out as the sole use of""among 10+ otherRequest()calls that all explicitly pass"web". Using an explicit, self-documenting value (e.g.,"web"or a dedicated"none") would align with the rest of the codebase and make the intent clearer.🤖 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 175 - 202, The Request call currently passes an empty authKind ("") which is legal but inconsistent; update the call to c.HTTPClient.Request("POST", path, "web", nil, payload) (or "none" if you prefer an explicit no-auth token) so the third argument is an explicit authKind string matching the rest of the codebase; change the call in the login flow where resp, err := c.HTTPClient.Request("POST", path, "", nil, payload) to use the chosen explicit value and keep the rest of the function (result unmarshalling, Authorization header read) unchanged.internal/router/router.go (1)
92-112: 💤 Low valueDuplicate registration of the register endpoint.
POST /v1/user/register(Line 93) andPOST /api/v1/users(Line 111) both bindr.userHandler.Register. Same applies tosystem/configsbeing available at both/v1/system/configs(Line 92) and/api/v1/system/configsvia the authorized group at Line 281 (the latter requires auth, the former does not — also worth confirming intentional).If the legacy
/v1/...paths exist purely for backward compatibility while the CLI migrates to/api/v1/..., consider adding a brief comment noting that, and plan to remove the legacy ones in a follow-up.🤖 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/router/router.go` around lines 92 - 112, The routes file currently registers duplicate endpoints: r.userHandler.Register is bound both at POST /v1/user/register and POST /api/v1/users, and /v1/system/configs duplicates /api/v1/system/configs (the latter under auth). Decide whether to remove the legacy /v1 routes or keep them for compatibility; if keeping, add a clear comment above the legacy registrations stating they are kept for backward compatibility and schedule removal, and ensure the auth semantics are explicit (i.e., confirm whether r.systemHandler.GetConfigs on /v1/system/configs should be unauthenticated or should require auth like the /api/v1 variant), otherwise delete the duplicate legacy registrations (remove the engine.GET("/v1/system/configs", ...) and engine.POST("/v1/user/register", ...) lines) so each handler (e.g., r.userHandler.Register, r.systemHandler.GetConfigs) is only registered once.internal/cli/filesystem/skill.go (1)
38-49: 💤 Low valueStale doc comment references the removed
useAPIBaseflag.The block mentioning
Uses Go backend API (useAPIBase=true)no longer reflects the API after this refactor; consider updating or removing it to avoid confusing future readers.🤖 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/filesystem/skill.go` around lines 38 - 49, The doc comment on top of SkillProvider still references the removed useAPIBase flag; update the comment in internal/cli/filesystem/skill.go (the SkillProvider header block) to remove or reword the "Uses Go backend API (useAPIBase=true)" line so it no longer references the deprecated flag, and instead describe the current endpoints being used (or omit the flag mention entirely) while keeping the path and API list accurate for functions/methods that implement listing/searching/indexing skills.internal/cli/filesystem/file.go (1)
26-38: 💤 Low valueStale
useAPIBase=truedoc comment.The header comment still refers to the removed
useAPIBaseflag. Consider rephrasing in terms of the newauthKindparameter so the file documentation reflects the actual API.🤖 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/filesystem/file.go` around lines 26 - 38, The top-of-file comment referencing the removed useAPIBase flag is stale; update the FileProvider header to remove mentions of useAPIBase and instead document the new authKind parameter and how it affects API calls (e.g., which authKind values are supported and how they change endpoints/headers), and adjust the API list to reflect current endpoints used by FileProvider; refer to the FileProvider type and any constructor or functions that accept authKind so readers can find the implementation details.internal/cli/http_client.go (2)
217-221: ⚡ Quick win
json.Marshalerror silently ignored in benchmark loop.The
_discard is the only error suppression here; ifjsonBodysomehow becomes un-marshallable between the pre-loop marshal and this iteration, the request is sent with anilbody silently.♻️ Proposed fix
-jsonData, _ := json.Marshal(jsonBody) +jsonData, err := json.Marshal(jsonBody) +if err != nil { + return nil, fmt.Errorf("failed to marshal request body on iteration %d: %w", i, err) +} reqBody = bytes.NewReader(jsonData)🤖 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/http_client.go` around lines 217 - 221, In the loop that re-creates reqBody you currently ignore json.Marshal's error (json.Marshal(jsonBody)), which can lead to sending a nil body; update the block in internal/cli/http_client.go to check the error from json.Marshal(jsonBody) into (jsonData, err) and handle it (return the error from the enclosing function or propagate/wrap it, or at minimum log and continue) before calling bytes.NewReader(jsonData); refer to the variables jsonBody, jsonData, reqBody and the surrounding request-building logic to ensure failures are handled consistently with the function's error flow.
274-316: ⚡ Quick win
UploadMultipartinlines auth header logic instead of going throughHeaders().Lines 285–289 duplicate the authorization logic that
Headers()already encapsulates, and diverge from it (e.g.,Headers("api", ...)falls back toLoginTokenas a Bearer token but this inline code only usesLoginTokenraw). A future change toHeaders()won't apply here.♻️ Proposed fix
func (c *HTTPClient) UploadMultipart(path string, contentType string, body io.Reader) error { url := c.BuildURL(path) req, err := http.NewRequest("POST", url, body) if err != nil { return err } req.Header.Set("Content-Type", contentType) - if c.APIToken != "" { - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", c.APIToken)) - } else if c.LoginToken != "" { - req.Header.Set("Authorization", c.LoginToken) - } + for k, v := range c.Headers("api", nil) { + req.Header.Set(k, v) + }🤖 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/http_client.go` around lines 274 - 316, UploadMultipart duplicates and diverges from the client's auth header logic; remove the inline Authorization handling in UploadMultipart and use the existing Headers(...) helper so behavior stays consistent with other requests. Replace the manual req.Header.Set calls for auth with a loop that applies the map returned by c.Headers(...) (ensure you still set Content-Type from the contentType parameter if Headers doesn't), and keep using c.client.Do(req) and the existing response handling unchanged; reference UploadMultipart and Headers() to locate where to swap the header logic.
🤖 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/filesystem/skill.go`:
- Around line 1175-1180: The call in getDefaultEmbdID is using authKind "web"
which deviates from other /skills/* calls; update the httpClient.Request
invocation inside the getDefaultEmbdID function to use "auto" for the authKind
argument instead of "web" so it follows the same API-token vs session selection
behavior as the other skill endpoints (locate the Request call in
getDefaultEmbdID and change the third parameter from "web" to "auto").
In `@internal/cli/user_command.go`:
- Line 686: In SetToken (in internal/cli/user_command.go) the HTTPClient.Request
call is using the wrong path "/tokens"; update the endpoint string passed to
c.HTTPClient.Request to "/system/tokens" so it matches the server route (router
defines /system/tokens). Locate the call to c.HTTPClient.Request(...) in
SetToken and replace the "/tokens" argument with "/system/tokens" to fix the
incorrect endpoint.
---
Outside diff comments:
In `@internal/cli/admin_command.go`:
- Around line 27-93: ShowAdminVersion is using the wrong authKind ("web") for
the protected /admin/version endpoint; update both calls to
c.HTTPClient.RequestWithIterations and c.HTTPClient.Request inside
ShowAdminVersion to use "admin" (leave PingAdmin as "web"), so the request
attaches/represents admin auth correctly and prevents runtime auth failures.
In `@internal/cli/common_command.go`:
- Around line 204-231: The non-admin Logout currently uses "/user/logout" which,
due to BuildURL and APIBase behavior, resolves to a non-existent
/api/.../user/logout and causes 404s; update the path selection in
RAGFlowClient.Logout so that when ServerType != "admin" it uses "/auth/logout"
(keep "/admin/logout" for admin), ensuring the request hits the router's
registered /api/v1/auth/logout endpoint; locate the path logic in the Logout
method and change the non-admin branch to "/auth/logout".
In `@internal/cli/filesystem/file.go`:
- Around line 545-579: DeleteFile uses p.httpClient.Request(..., "api", ...)
which is inconsistent with other /files calls that use "auto"; update the auth
kind in DeleteFile to "auto" for consistency (change the auth argument passed to
p.httpClient.Request in the DeleteFile function) and run tests; if the DELETE
endpoint truly requires an explicit API token instead of the "auto" fallback,
keep "api" but add a brief comment above DeleteFile explaining why DELETE must
force "api" auth so future readers understand the deviation.
In `@internal/cli/http_client.go`:
- Around line 183-191: The single-iteration branch incorrectly treats any
non-zero response.Code as failure; change the check to evaluate the actual HTTP
status (resp.StatusCode) like the multi-iteration path does (e.g., treat status
200 as success or use a 2xx range) so that response.SuccessCount/FailureCount
are set based on resp.StatusCode rather than response.Code; update the block
that sets response.Code, response.Duration and then sets
SuccessCount/FailureCount (referencing response.Code, resp.StatusCode) to use
resp.StatusCode == 200 (or resp.StatusCode >=200 && resp.StatusCode <300) for
success.
In `@internal/cli/user_command.go`:
- Around line 1601-1603: The error message is incorrect for missing params: when
extracting videos via videos, ok := cmd.Params["videos"].([]string) return the
correct error string ("videos not provided") instead of "images not provided";
likewise locate the analogous extraction for files (files, ok :=
cmd.Params["files"].([]string) around the mentioned copy-paste and change its
error to "files not provided". Update the error fmt.Errorf calls for the videos
and files parameter checks to the appropriate param name so logs and errors
accurately reflect the missing parameter.
- Around line 769-880: Both CreateDataset and CreateDatasetInDocEngine are
identical; extract the shared logic into a single helper (e.g.,
createDatasetTable or createDatasetInDocEngineHelper) that performs param
validation (dataset_name, vector_size), calls getDatasetID, builds payload,
invokes c.HTTPClient.Request("POST", "/kb/doc_engine_table", ...), parses
resp.JSON(), converts code to SimpleResponse and returns it, then have
CreateDataset and CreateDatasetInDocEngine delegate to that helper (or remove
one and forward to the other) to avoid duplication and keep getDatasetID,
HTTPClient.Request, and SimpleResponse usage centralized.
- Around line 1773-1779: The error messages in the non-stream ChatToModel path
wrongly mention "list instance models" — update the strings in the ChatToModel
handler (where resp and result NonStreamResponse are used) to reference "chat to
model" (or "ChatToModel") instead: change the HTTP error fmt.Errorf("failed to
list instance models: HTTP %d, body: %s", ...) and the JSON error
fmt.Errorf("failed to list instance models: invalid JSON (%w)", err) to
descriptive messages like "failed to chat to model: HTTP %d, body: %s" and
"failed to chat to model: invalid JSON (%w)", respectively so the errors reflect
the correct operation.
- Around line 355-367: The authKind logic currently sets authKind = "api" when
c.HTTPClient.useAPIToken is true then unconditionally overwrites it to "web" if
c.HTTPClient.LoginToken != ""; change the logic to express precedence explicitly
by checking c.HTTPClient.LoginToken first and setting authKind = "web" if
present, otherwise set authKind = "api" when c.HTTPClient.useAPIToken is true
(or leave as default "web" if neither), removing the redundant final if that
overrides the API selection; update the block that references authKind,
c.HTTPClient.LoginToken and c.HTTPClient.useAPIToken in user_command.go
accordingly.
---
Nitpick comments:
In `@internal/cli/common_command.go`:
- Around line 30-40: Comments inside the LoginUserInteractive function reference
the removed useAPIBase flag; update them to reflect the new authKind model by
replacing references to "useAPIBase=true/false" with the current auth routing
terminology (e.g., authKind "admin" vs "user" or similar) and ensure the comment
explains that ServerType determines the ping path ("/admin/ping" for admin,
"/system/ping" for user) and how authKind is chosen/used elsewhere; check
symbols LoginUserInteractive and ServerType and adjust any other stale comments
in that function to reference authKind consistently.
- Around line 175-202: The Request call currently passes an empty authKind ("")
which is legal but inconsistent; update the call to c.HTTPClient.Request("POST",
path, "web", nil, payload) (or "none" if you prefer an explicit no-auth token)
so the third argument is an explicit authKind string matching the rest of the
codebase; change the call in the login flow where resp, err :=
c.HTTPClient.Request("POST", path, "", nil, payload) to use the chosen explicit
value and keep the rest of the function (result unmarshalling, Authorization
header read) unchanged.
In `@internal/cli/filesystem/dataset.go`:
- Around line 326-327: The comment above the HTTP call to p.httpClient.Request
(the POST to "/chunk/retrieval_test") is stale because it mentions a removed
useAPIBase flag while the request now passes "auto"; update or remove that
comment (and the similar one near the second occurrence around Line 610) so it
accurately reflects current behavior — either explain that routing/auth
selection is handled by the client when "auto" is passed or drop the misleading
note entirely; locate the call sites by the p.httpClient.Request("POST",
"/chunk/retrieval_test", "auto", ...) invocations and edit the comments
accordingly.
In `@internal/cli/filesystem/file.go`:
- Around line 26-38: The top-of-file comment referencing the removed useAPIBase
flag is stale; update the FileProvider header to remove mentions of useAPIBase
and instead document the new authKind parameter and how it affects API calls
(e.g., which authKind values are supported and how they change
endpoints/headers), and adjust the API list to reflect current endpoints used by
FileProvider; refer to the FileProvider type and any constructor or functions
that accept authKind so readers can find the implementation details.
In `@internal/cli/filesystem/skill.go`:
- Around line 38-49: The doc comment on top of SkillProvider still references
the removed useAPIBase flag; update the comment in
internal/cli/filesystem/skill.go (the SkillProvider header block) to remove or
reword the "Uses Go backend API (useAPIBase=true)" line so it no longer
references the deprecated flag, and instead describe the current endpoints being
used (or omit the flag mention entirely) while keeping the path and API list
accurate for functions/methods that implement listing/searching/indexing skills.
In `@internal/cli/http_client.go`:
- Around line 217-221: In the loop that re-creates reqBody you currently ignore
json.Marshal's error (json.Marshal(jsonBody)), which can lead to sending a nil
body; update the block in internal/cli/http_client.go to check the error from
json.Marshal(jsonBody) into (jsonData, err) and handle it (return the error from
the enclosing function or propagate/wrap it, or at minimum log and continue)
before calling bytes.NewReader(jsonData); refer to the variables jsonBody,
jsonData, reqBody and the surrounding request-building logic to ensure failures
are handled consistently with the function's error flow.
- Around line 274-316: UploadMultipart duplicates and diverges from the client's
auth header logic; remove the inline Authorization handling in UploadMultipart
and use the existing Headers(...) helper so behavior stays consistent with other
requests. Replace the manual req.Header.Set calls for auth with a loop that
applies the map returned by c.Headers(...) (ensure you still set Content-Type
from the contentType parameter if Headers doesn't), and keep using
c.client.Do(req) and the existing response handling unchanged; reference
UploadMultipart and Headers() to locate where to swap the header logic.
In `@internal/cli/user_parser.go`:
- Around line 65-110: Update the inline comment in parseRegisterCommand to
accurately reflect the consumed token name: change the comment that currently
reads "// consume Email" to something like "// consume user_name" (or "//
consume USER token / user_name") so it matches the param key
cmd.Params["user_name"] and the behavior in the function.
In `@internal/router/router.go`:
- Around line 92-112: The routes file currently registers duplicate endpoints:
r.userHandler.Register is bound both at POST /v1/user/register and POST
/api/v1/users, and /v1/system/configs duplicates /api/v1/system/configs (the
latter under auth). Decide whether to remove the legacy /v1 routes or keep them
for compatibility; if keeping, add a clear comment above the legacy
registrations stating they are kept for backward compatibility and schedule
removal, and ensure the auth semantics are explicit (i.e., confirm whether
r.systemHandler.GetConfigs on /v1/system/configs should be unauthenticated or
should require auth like the /api/v1 variant), otherwise delete the duplicate
legacy registrations (remove the engine.GET("/v1/system/configs", ...) and
engine.POST("/v1/user/register", ...) lines) so each handler (e.g.,
r.userHandler.Register, r.systemHandler.GetConfigs) is only registered once.
🪄 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: 8799a6d0-bb64-473b-bde0-3fbf9b26c0f7
📒 Files selected for processing (11)
internal/cli/admin_command.gointernal/cli/benchmark.gointernal/cli/client.gointernal/cli/common_command.gointernal/cli/filesystem/dataset.gointernal/cli/filesystem/file.gointernal/cli/filesystem/skill.gointernal/cli/http_client.gointernal/cli/user_command.gointernal/cli/user_parser.gointernal/router/router.go
| func (p *SkillProvider) getDefaultEmbdID(ctx stdctx.Context, spaceID string) (string, error) { | ||
| resp, err := p.httpClient.Request("GET", | ||
| fmt.Sprintf("/skills/config?embd_id=&space_id=%s", url.QueryEscape(spaceID)), | ||
| true, "web", nil, nil) | ||
| "web", nil, nil) | ||
| if err != nil { | ||
| return "", nil |
There was a problem hiding this comment.
Inconsistent authKind for /skills/config.
All other /skills/* calls in this file use "auto", but getDefaultEmbdID hardcodes "web". With "web" the request will use the login/session token even when an API token is set, which can fail (or behave differently) compared to all other skill calls in API-token contexts. Unless there is a specific reason for this divergence, prefer "auto" for consistency.
♻️ Suggested change
resp, err := p.httpClient.Request("GET",
fmt.Sprintf("/skills/config?embd_id=&space_id=%s", url.QueryEscape(spaceID)),
- "web", nil, nil)
+ "auto", nil, nil)📝 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 (p *SkillProvider) getDefaultEmbdID(ctx stdctx.Context, spaceID string) (string, error) { | |
| resp, err := p.httpClient.Request("GET", | |
| fmt.Sprintf("/skills/config?embd_id=&space_id=%s", url.QueryEscape(spaceID)), | |
| true, "web", nil, nil) | |
| "web", nil, nil) | |
| if err != nil { | |
| return "", nil | |
| func (p *SkillProvider) getDefaultEmbdID(ctx stdctx.Context, spaceID string) (string, error) { | |
| resp, err := p.httpClient.Request("GET", | |
| fmt.Sprintf("/skills/config?embd_id=&space_id=%s", url.QueryEscape(spaceID)), | |
| "auto", nil, nil) | |
| if err != nil { | |
| return "", 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/filesystem/skill.go` around lines 1175 - 1180, The call in
getDefaultEmbdID is using authKind "web" which deviates from other /skills/*
calls; update the httpClient.Request invocation inside the getDefaultEmbdID
function to use "auto" for the authKind argument instead of "web" so it follows
the same API-token vs session selection behavior as the other skill endpoints
(locate the Request call in getDefaultEmbdID and change the third parameter from
"web" to "auto").
|
|
||
| // Validate token by calling list tokens API | ||
| resp, err := c.HTTPClient.Request("GET", "/tokens", true, "api", nil, nil) | ||
| resp, err := c.HTTPClient.Request("GET", "/tokens", "api", nil, nil) |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find server-side route definitions for both paths
rg -n '"/tokens"' --type go
rg -n '"/system/tokens"' --type goRepository: infiniflow/ragflow
Length of output: 454
🏁 Script executed:
# Check the router implementation around line 290
sed -n '280,300p' internal/router/router.goRepository: infiniflow/ragflow
Length of output: 688
🏁 Script executed:
# Look for the actual HTTP handlers for these routes
rg -B5 -A10 'tokens.*:=' internal/router/router.goRepository: infiniflow/ragflow
Length of output: 559
🏁 Script executed:
# Check the functions SetToken and ListTokens for context
sed -n '680,690p' internal/cli/user_command.go
sed -n '610,620p' internal/cli/user_command.goRepository: infiniflow/ragflow
Length of output: 798
🏁 Script executed:
# Search for all route definitions for tokens endpoints
rg -n 'tokens|"/tokens"' internal/router/ --type go | head -30Repository: infiniflow/ragflow
Length of output: 618
🏁 Script executed:
# Get more context around SetToken to understand the intent
sed -n '670,690p' internal/cli/user_command.goRepository: infiniflow/ragflow
Length of output: 675
🏁 Script executed:
# Verify no other /tokens routes exist outside system group
rg -n '\.GET.*tokens|\.POST.*tokens|\.DELETE.*tokens|\.PUT.*tokens' internal/router/ --type goRepository: infiniflow/ragflow
Length of output: 44
Fix incorrect endpoint: SetToken calls non-existent /tokens endpoint instead of /system/tokens.
Line 686 calls GET /tokens, but the server only defines /system/tokens (under the system route group in router.go:290). Change the endpoint to /system/tokens to match the actual server route that exists.
🤖 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 686, In SetToken (in
internal/cli/user_command.go) the HTTPClient.Request call is using the wrong
path "/tokens"; update the endpoint string passed to c.HTTPClient.Request to
"/system/tokens" so it matches the server route (router defines /system/tokens).
Locate the call to c.HTTPClient.Request(...) in SetToken and replace the
"/tokens" argument with "/system/tokens" to fix the incorrect endpoint.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #14658 +/- ##
=======================================
Coverage 94.16% 94.16%
=======================================
Files 10 10
Lines 703 703
Branches 112 112
=======================================
Hits 662 662
Misses 25 25
Partials 16 16 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
### What problem does this PR solve? Since API is updated, CLI login failed. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) Signed-off-by: Jin Hai <[email protected]>
### What problem does this PR solve? Since API is updated, CLI login failed. ### Type of change - [x] Bug Fix (non-breaking change which fixes an issue) Signed-off-by: Jin Hai <[email protected]>
What problem does this PR solve?
Since API is updated, CLI login failed.
Type of change