Skip to content

Fix cli login - #14658

Merged
JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix416
May 8, 2026
Merged

JinHai-CN merged 1 commit into
infiniflow:mainfrom
JinHai-CN:fix416

Conversation

@JinHai-CN

Copy link
Copy Markdown
Member

What problem does this PR solve?

Since API is updated, CLI login failed.

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

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

coderabbitai Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR refactors the HTTP request API across the CLI by removing the per-call useAPIBase boolean parameter and replacing it with explicit authKind strings ("web", "admin", "auto", "api"). The core HTTPClient methods are simplified, and all ~70 call sites are updated consistently. Additionally, the user parser token consumption is refactored and router endpoints are reorganized under a /api/v1 group.

Changes

HTTP Client Refactoring: Remove useAPIBase Parameter

Layer / File(s) Summary
Core HTTP API
internal/cli/http_client.go
BuildURL, Request, RequestWithIterations, RequestJSON, RequestStream, and UploadMultipart methods remove useAPIBase bool parameter. BuildURL is simplified to always call APIBase() and conditionally prefix http:// or https:// based on VerifySSL.
Adapter and Interfaces
internal/cli/client.go, internal/cli/filesystem/dataset.go
httpClientAdapter.Request and HTTPClientInterface.Request signatures updated to remove useAPIBase bool and accept only authKind string.
Admin Commands
internal/cli/admin_command.go, internal/cli/benchmark.go
25+ admin command functions and benchmark handlers updated to pass "web" for ping/version endpoints and "admin" for all other /admin/* endpoints, replacing boolean flags.
Benchmark Execution
internal/cli/benchmark.go
Benchmark switch cases for ping, list_user_datasets, list_datasets, and search_on_datasets updated to use authKind strings instead of boolean arguments.
Common Commands
internal/cli/common_command.go
Login/logout, provider, and model management functions updated to pass "web" authKind instead of boolean flags in HTTP requests.
User Commands
internal/cli/user_command.go
40+ user command functions updated throughout to use explicit "web", "admin", or "api" authKind strings in Request, RequestWithIterations, and RequestStream calls.
Filesystem Implementations
internal/cli/filesystem/file.go, internal/cli/filesystem/dataset.go, internal/cli/filesystem/skill.go
Dataset, file, and skill operations updated to use "auto" or "api" authKind for Python backend API calls, replacing boolean parameters across 30+ call sites.

Independent Changes

Layer / File(s) Summary
User Parser
internal/cli/user_parser.go
parseRegisterCommand refactored to explicitly consume tokens after each parsing step (USER, user_name, AS, nickname, PASSWORD, password) for clearer grammar alignment, while preserving command parameter assignment and optional semicolon handling.
Router Endpoints
internal/router/router.go
Unauthenticated endpoints (system ping/config/version, login, user registration, auth endpoints) are consolidated under a dedicated engine.Group("/api/v1") route group with explicit GET/POST registrations, replacing prior direct engine routing.

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#13956: Modifies router.go's Setup method to reorganize endpoints under /api/v1 and change system/version route registration, overlapping with the router refactoring in this PR.

🐰 A Refactoring Tale

Boolean flags once cluttered the call site,
Now authKind strings make requests bright!
From true and false to "web", "admin" clear,
The API signature shines crystal dear.
Router endpoints find their rightful place—
Under /api/v1 in grouped space! ✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is largely incomplete, with only a minimal problem statement and type selection. Required details about the implementation approach, scope of changes, and testing are missing. Expand the description to explain the root cause (API base URL handling change), the solution (removing useAPIBase parameter and using authKind strings), affected files/components, and any testing performed or migration notes.
Title check ❓ Inconclusive The title 'Fix cli login' is vague and generic, using non-descriptive terms that don't convey meaningful information about the specific changes or the scope of the refactoring involved. Improve the title to be more specific about the core change, such as 'Refactor HTTP client request signatures to remove useAPIBase parameter' or 'Update CLI to use authKind string instead of boolean for API requests'.
✅ Passed checks (3 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 and usage tips.

@JinHai-CN
JinHai-CN marked this pull request as ready for review May 8, 2026 05:18
@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label May 8, 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: 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 win

Inconsistent auth kind for DELETE: DeleteFile uses "api" while all other /files operations use "auto".

Every other /files call in this provider (lines 282) and across the codebase uses "auto" for GET and POST requests. The DeleteFile method 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 win

Non-admin Logout path will 404 after this PR.

In line 179, the non-admin login path was migrated from /user/login to /auth/login. However, Logout at line 213 still calls /user/logout.

The BuildURL method (http_client.go:73) always prepends APIBase() (line 64), which returns /api/{version} (e.g., /api/v1). This means:

  • /auth/login resolves to /api/v1/auth/login ✓ (registered at router.go:108)
  • /user/logout resolves 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/logout endpoint (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 value

ShowAdminVersion should use "admin" authKind, not "web".

The /admin/version endpoint is protected by AuthMiddleware() in the server's route setup (internal/admin/router.go:110), requiring a valid authorization token. The /admin/ping endpoint correctly uses "web" because it's in the "Public routes" section (router.go:44), but ShowAdminVersion must 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 win

Wrong error message: "images not provided" when videos param 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

CreateDataset and CreateDatasetInDocEngine are 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 win

Copy-paste error messages in non-stream ChatToModel path 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

authKind override silently ignores an explicitly set API token when a login token is also present.

The second if c.HTTPClient.LoginToken != "" block unconditionally resets authKind back to "web", overriding the "api" value that was just set because useAPIToken == 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 win

Single-iteration benchmark path always counts a successful request as a failure.

response.Code = resp.StatusCode sets Code to the HTTP status (e.g., 200), so if response.Code == 0 is never true for a live HTTP response. Every successful single-iteration benchmark request is incorrectly recorded in FailureCount. The multi-iteration path (line 254) correctly checks resp.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 value

LGTM — token consumption sequence is correct.

The refactored parseRegisterCommand follows the same nextToken-before-check / nextToken-after-parse-quoted-string contract that every other parser in this file uses. The full token walk for REGISTER 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 as user_name. Consider // consume user_name for 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 value

Stale useAPIBase=false comment.

The accompanying comment still references the removed useAPIBase flag 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 value

Stale useAPIBase references in comments.

The comments at Lines 32-33 and 96-97 still describe routing in terms of the removed useAPIBase=true/false argument. Worth updating to the new authKind model.

🤖 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 value

Use an explicit authKind value instead of empty string for code clarity.

The empty authKind at line 182 works correctly—the Headers() 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+ other Request() 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 value

Duplicate registration of the register endpoint.

POST /v1/user/register (Line 93) and POST /api/v1/users (Line 111) both bind r.userHandler.Register. Same applies to system/configs being available at both /v1/system/configs (Line 92) and /api/v1/system/configs via 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 value

Stale doc comment references the removed useAPIBase flag.

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 value

Stale useAPIBase=true doc comment.

The header comment still refers to the removed useAPIBase flag. Consider rephrasing in terms of the new authKind parameter 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.Marshal error silently ignored in benchmark loop.

The _ discard is the only error suppression here; if jsonBody somehow becomes un-marshallable between the pre-loop marshal and this iteration, the request is sent with a nil body 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

UploadMultipart inlines auth header logic instead of going through Headers().

Lines 285–289 duplicate the authorization logic that Headers() already encapsulates, and diverge from it (e.g., Headers("api", ...) falls back to LoginToken as a Bearer token but this inline code only uses LoginToken raw). A future change to Headers() 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

📥 Commits

Reviewing files that changed from the base of the PR and between 412fae7 and 2e6e6f7.

📒 Files selected for processing (11)
  • internal/cli/admin_command.go
  • internal/cli/benchmark.go
  • internal/cli/client.go
  • internal/cli/common_command.go
  • internal/cli/filesystem/dataset.go
  • internal/cli/filesystem/file.go
  • internal/cli/filesystem/skill.go
  • internal/cli/http_client.go
  • internal/cli/user_command.go
  • internal/cli/user_parser.go
  • internal/router/router.go

Comment on lines 1175 to 1180
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

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.

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

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.

Suggested change
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)

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.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find server-side route definitions for both paths
rg -n '"/tokens"' --type go
rg -n '"/system/tokens"' --type go

Repository: infiniflow/ragflow

Length of output: 454


🏁 Script executed:

# Check the router implementation around line 290
sed -n '280,300p' internal/router/router.go

Repository: infiniflow/ragflow

Length of output: 688


🏁 Script executed:

# Look for the actual HTTP handlers for these routes
rg -B5 -A10 'tokens.*:=' internal/router/router.go

Repository: 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.go

Repository: 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 -30

Repository: 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.go

Repository: 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 go

Repository: 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

codecov Bot commented May 8, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.16%. Comparing base (412fae7) to head (2e6e6f7).
⚠️ Report is 1 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@JinHai-CN
JinHai-CN merged commit 731c887 into infiniflow:main May 8, 2026
1 check passed
pekar9781 pushed a commit to pekar9781/ragflow that referenced this pull request May 8, 2026
### 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]>
@coderabbitai coderabbitai Bot mentioned this pull request Jun 9, 2026
1 task done
Ricardo-M-L pushed a commit to Ricardo-M-L/ragflow that referenced this pull request Aug 17, 2026
### 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant