Skip to content

Go: merge functions - #16622

Merged
JinHai-CN merged 21 commits into
infiniflow:mainfrom
JinHai-CN:fix519
Jul 6, 2026
Merged

JinHai-CN merged 21 commits into
infiniflow:mainfrom
JinHai-CN:fix519

Conversation

@JinHai-CN

@JinHai-CN JinHai-CN commented Jul 3, 2026 •

Copy link
Copy Markdown
Member

Summary

Merge HTTP response functions into common/response.go

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

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds shared response helpers, a new error code, and broad handler refactors to use standardized response envelopes and HTTP/status handling. It also renames the ClawHub progress logger success method.

Changes

Shared response helper migration

Layer / File(s) Summary
Core helpers and shared error wiring
internal/common/response.go, internal/common/error_code.go, internal/service/openai_chat.go, internal/handler/error.go, internal/handler/components.go, internal/handler/admin_runtime.go, internal/handler/oauth_login.go, internal/handler/stats.go
Adds the shared response helpers, introduces CodeNotImplemented, and routes generic helper/error paths through the new response envelope functions.
Admin and enterprise admin handlers
internal/admin/enterprise_handler.go, internal/admin/handler.go
Migrates admin and enterprise admin endpoints to shared response helpers for roles, models, providers, users, services, queues, ingestion, licenses, reports, and runtime flows.
Agent handlers and tests
internal/handler/agent*.go
Updates agent CRUD, sessions, logs, component, webhook, upload/download, and test code paths to the shared helpers, including the fail-closed document-service check in RerunAgent.
Chat, dataset, document, chunk, and retrieval handlers
internal/handler/chat*.go, internal/handler/chunk.go, internal/handler/dataset.go, internal/handler/document.go, internal/handler/dify_retrieval_handler.go, internal/handler/components.go
Standardizes chat, dataset, document, chunk, retrieval, and component response handling across validation, service, and success paths.
File, connector, provider, MCP, and API handlers
internal/handler/file*.go, internal/handler/connector.go, internal/handler/providers.go, internal/handler/mcp*.go, internal/handler/models.go, internal/handler/plugin.go, internal/handler/llm.go, internal/handler/langfuse.go, internal/handler/api_token.go, internal/handler/openai_chat.go, internal/handler/auth.go
Moves file, connector, provider, MCP, model, plugin, token, OAuth, OpenAI chat, and auth paths to the shared helpers.
Memory, search, skill, and bot handlers
internal/handler/memory.go, internal/handler/search.go, internal/handler/searchbot.go, internal/handler/skill_search.go, internal/handler/bot*.go
Standardizes memory, search, skill-search, and bot response formatting and validation errors.
Tenant, user, system, and runtime handlers
internal/handler/tenant.go, internal/handler/user.go, internal/handler/system.go, internal/handler/stats.go, internal/handler/admin_runtime.go
Updates tenant, user, system, stats, and runtime responses to use the shared helpers.
ClawHub CLI logger rename
internal/cli/filesystem/skill_hub/source/clawhub.go
Renames the progress logger success method to SuccessWithData and updates callers.

Estimated code review effort: 5 (Critical) | ~120 minutes

Possibly related PRs

Suggested labels: ☯️ refactor, ci, size:XXL

Suggested reviewers: yingfeng, yuzhichang

Poem

A rabbit hopped through helper code,
And tidied every response road.
With envelopes neat and logs in tune,
The handlers now can sing in June.
🐇✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Title check ❓ Inconclusive The title is vague and generic; it doesn't clearly describe the main change. Rename it to something specific like "Consolidate HTTP response helpers into common/response.go".
✅ Passed checks (4 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.
Description check ✅ Passed The description matches the required Summary section and clearly states the PR's purpose.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@JinHai-CN
JinHai-CN marked this pull request as ready for review July 6, 2026 06:50
@dosubot dosubot Bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Jul 6, 2026
@JinHai-CN
JinHai-CN marked this pull request as draft July 6, 2026 06:51
@JinHai-CN
JinHai-CN marked this pull request as ready for review July 6, 2026 06:51

@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: 11

Caution

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

⚠️ Outside diff range comments (5)
internal/handler/dify_retrieval_handler.go (1)

165-215: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Return non-200 errors from the Dify retrieval endpoint
common.ErrorWithCode always emits HTTP 200 with {code, message}, so Dify can treat validation/auth/not-found failures as successful retrievals. Return a failure status here and match Dify’s error_code / error_msg error schema.

🤖 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/handler/dify_retrieval_handler.go` around lines 165 - 215, The Dify
retrieval handler is using common.ErrorWithCode in validation, auth, and
not-found paths, which returns HTTP 200 instead of a failure response. Update
difyRetrievalHandler to return non-200 status codes for these branches and emit
Dify’s error schema with error_code and error_msg rather than the current
code/message payload. Keep the changes localized around the request parsing,
kbSvc.GetByID lookup, and Accessible authorization checks so all early exits
follow the same error format.
internal/handler/memory.go (2)

525-575: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Inconsistent error code for empty authenticated-user ID.

Lines 532-536 return common.CodeArgumentError for an empty currentUserID (derived from the authenticated user.ID, not request input). Every other handler performing the identical check — GetMemoryMessages (429-433), UpdateMessage (663-667), GetMessageContent (719-723), SearchMessage (768-770), GetMessages (837-839) — uses common.CodeAuthenticationError for this exact case. This is a real authentication failure, not a malformed argument; using a different code here breaks the contract for clients that branch on error code.

🔧 Proposed fix
 	currentUserID := strings.TrimSpace(user.ID)
 	if currentUserID == "" {
-		common.ResponseWithCodeData(c, common.CodeArgumentError, nil, "user_id is required")
+		common.ResponseWithCodeData(c, common.CodeAuthenticationError, nil, "user id is required")
 		return
 	}
🤖 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/handler/memory.go` around lines 525 - 575, The empty
authenticated-user ID check in MemoryHandler.AddMessage is using the wrong error
code. Update the currentUserID validation in AddMessage to return
common.CodeAuthenticationError, matching the same check used in
GetMemoryMessages, UpdateMessage, GetMessageContent, SearchMessage, and
GetMessages, so the handler treats this as an auth failure rather than an
argument error.

257-282: 🔒 Security & Privacy | 🔴 Critical | ⚡ Quick win

Add ownership scoping to DeleteMemory and GetMemoryConfig
Both paths still act on memory_id alone: the handler doesn’t resolve the current user, and MemoryService/MemoryDAO lookups are unscoped. A caller with a known ID can delete or read another tenant’s memory. Thread user.ID or tenant scope through these calls, or enforce the ownership check in the service.

🤖 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/handler/memory.go` around lines 257 - 282, `DeleteMemory` is
operating only on `memory_id`, so it can affect records outside the caller’s
ownership scope. Update `MemoryHandler.DeleteMemory` to resolve the current user
from `gin.Context` and pass that identity/tenant scope into
`memoryService.DeleteMemory`, then enforce the ownership check in
`MemoryService` and `MemoryDAO` so only the owner’s memory can be deleted. Make
the same scoping change for `GetMemoryConfig` and use the existing symbols
`MemoryHandler`, `DeleteMemory`, `GetMemoryConfig`, `MemoryService`, and
`MemoryDAO` to thread the user context through all memory lookups.
internal/handler/agent_webhook.go (1)

189-204: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

common.ResponseWithCodeData cannot produce HTTP 501 — always writes HTTP 200.

common.ResponseWithCodeData is defined as:

func ResponseWithCodeData(c *gin.Context, code ErrorCode, data interface{}, message string) {
	c.JSON(http.StatusOK, response{...})
}

It unconditionally responds with http.StatusOK — the code argument only populates the JSON body's code field, it does not set the actual HTTP status. Passing http.StatusNotImplemented here (Line 195) therefore now returns HTTP 200, not 501, silently breaking the documented "HTTP 501 for multipart uploads" contract and failing TestWebhook_MultipartReturns501, which explicitly asserts w.Code == http.StatusNotImplemented.

Use a raw c.JSON (or c.Status + c.JSON) here to preserve the real HTTP status instead of the common helper, which is hard-coded to 200.

🐛 Proposed fix
 		case errors.Is(parseErr, ErrWebhookMultipartNotSupported):
 			// 501 — multipart/form-data uploads are not yet
 			// supported. Body is short so operators see exactly what
 			// is missing.
-			common.ResponseWithCodeData(c, http.StatusNotImplemented, false, parseErr.Error())
+			c.JSON(http.StatusNotImplemented, gin.H{
+				"code":    common.CodeDataError,
+				"data":    false,
+				"message": parseErr.Error(),
+			})
 			return
🤖 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/handler/agent_webhook.go` around lines 189 - 204,
`common.ResponseWithCodeData` in the webhook parse error handling always returns
HTTP 200, so the multipart-not-supported path is not actually sending 501.
Update the `parseErr` switch in `agent_webhook.go` to use `c.JSON` or `c.Status`
plus `c.JSON` for the `ErrWebhookMultipartNotSupported` case so the real HTTP
status is preserved, while keeping the existing helper for the other error cases
if appropriate. Refer to `ErrWebhookMultipartNotSupported`,
`ErrWebhookContentTypeMismatch`, and `common.ResponseWithCodeData` when making
the change.
internal/handler/file.go (1)

76-84: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Page validation silently allows page=0/negative to fall through.

Unlike the page_size block right below (lines 87-99), which explicitly rejects ps < 1, this page block has no else for the case err == nil && p < 1 (e.g. page=0 or page=-1). It silently keeps the default page = 1 instead of returning the "must be a positive integer" error the message promises.

🐛 Proposed fix
 	if pageStr := c.Query("page"); pageStr != "" {
-		if p, err := strconv.Atoi(pageStr); err == nil && p >= 1 {
+		if p, err := strconv.Atoi(pageStr); err == nil && p >= 1 {
 			page = p
-		} else if err != nil {
+		} else if err != nil || p < 1 {
 			common.ResponseWithCodeData(c, common.CodeParamError, nil, "Invalid page parameter: must be a positive integer")
 			return
 		}
 	}
🤖 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/handler/file.go` around lines 76 - 84, The page parsing in the file
handler silently accepts non-positive values because the strconv.Atoi branch
only errors on parse failures, not when p < 1. Update the page validation in the
page/query handling block of the handler method to explicitly reject zero and
negative values with the same parameter error used for invalid input, matching
the stricter validation already applied in the page_size logic. Use the existing
page variable and common.ResponseWithCodeData flow so page=0 and page=-1 return
an error instead of falling back to the default page.
🧹 Nitpick comments (11)
internal/cli/filesystem/skill_hub/source/clawhub.go (1)

49-51: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Naming collision with common.SuccessWithData may confuse readers.

This is an unrelated internal progressLogger method (Printf-style CLI logging) but now shares its name with the newly introduced common.SuccessWithData(c, data, message) Gin response helper from this same PR stack. Consider keeping a name that reflects its actual purpose (e.g. logSuccess) to avoid confusion during future greps/refactors.

🤖 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_hub/source/clawhub.go` around lines 49 - 51,
The `progressLogger.SuccessWithData` method name collides conceptually with the
new `common.SuccessWithData` helper and can confuse future reads and searches.
Rename the `progressLogger` method in `clawhub.go` to something that reflects
CLI logging behavior, such as `logSuccess`, and update any internal call sites
so the `progressLogger` type remains clearly distinct from the Gin response
helper.
internal/common/response.go (1)

71-85: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: code parameter type inconsistency between ErrorWithCode (int) and ResponseWithCodeData (ErrorCode).

Both functions serve the same conceptual purpose (custom code + message/data), but one takes int and the other ErrorCode, forcing callers to int(code)-cast in one path and pass raw ErrorCode in the other (as seen in the migrated handler call-sites). Unifying the parameter type would reduce caller friction.

🤖 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/common/response.go` around lines 71 - 85, The custom response
helpers use inconsistent code types: ErrorWithCode accepts int while
ResponseWithCodeData accepts ErrorCode, which forces unnecessary casting at call
sites. Make the parameter type consistent across both helpers in response.go by
updating ErrorWithCode to use ErrorCode as well (or otherwise align both on the
same type) and adjust the JSON payload conversion inside the helper if needed.
Keep the behavior of ErrorWithCode and ResponseWithCodeData unchanged aside from
the unified signature, so migrated handlers can pass ErrorCode values directly
without int(code) casts.
internal/handler/document.go (1)

337-344: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Inconsistent error envelope: UpdateDocument success uses the shared helper but its service-error path still emits raw c.JSON(http.StatusInternalServerError, ...).

After this change the success path returns the HTTP 200 code-envelope (SuccessWithMessage), while the error path returns HTTP 500 with a bare {"error": ...} body. Clients parsing the standardized {code, message} shape will mishandle this error. Align it with the rest of the migrated handlers.

♻️ Proposed change
 	if err = h.documentService.UpdateDocument(id, &req); err != nil {
-		c.JSON(http.StatusInternalServerError, gin.H{
-			"error": err.Error(),
-		})
+		common.ErrorWithCode(c, int(common.CodeServerError), err.Error())
 		return
 	}
🤖 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/handler/document.go` around lines 337 - 344, The UpdateDocument
handler still returns a raw JSON error body from the
h.documentService.UpdateDocument path, which breaks the shared response envelope
used elsewhere. Update the error branch in the UpdateDocument method to use the
same standardized helper pattern as the success path, returning the common
{code, message} shape instead of c.JSON with {"error": ...}. Keep the existing
service call and success handling intact, and align this handler with the rest
of the migrated response helpers in internal/handler/document.go.
internal/admin/enterprise_handler.go (1)

649-653: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Debug artifact: builtin println with unsupported format verbs.

Go's builtin println does not interpret %v/%T; this writes literal verb text plus pointer addresses to stderr. Remove it or use the structured logger already used elsewhere in this package. The same leftover appears in several sibling handlers (SetSystemLicense, ShowUserActivity, ListUsersQuota, PurgeOrphanData, etc.).

♻️ Proposed change
 	if err := c.ShouldBindJSON(&req); err != nil {
-		println("JSON bind error: %v (type: %T)", err, err)
 		common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
 		return
 	}
🤖 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/admin/enterprise_handler.go` around lines 649 - 653, The JSON bind
error path in the enterprise handlers still uses builtin println with
unsupported format verbs, so replace it with the package’s structured logging or
remove it entirely. Update the ShouldBindJSON failure handling in this handler
and the sibling handlers mentioned in the review (such as SetSystemLicense,
ShowUserActivity, ListUsersQuota, and PurgeOrphanData) to log errors
consistently using the existing logger instead of println.
internal/handler/bot.go (1)

64-92: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Success response not migrated to shared helper.

The error path was migrated to common.ResponseWithCodeData (67, 78), but the success path (81-91) still manually builds c.JSON(200, gin.H{"code": ..., "data": ..., "message": "success"}). This is the same {code, data, message} shape common.SuccessWithData produces, so this looks like leftover/incomplete migration rather than an intentional exception (unlike the SSE streaming endpoints, which genuinely can't use the single-shot helper). Same applies to AgentbotInputs (115-125) and GetAgentbotLogs (318-322).

♻️ Proposed fix
-	c.JSON(200, gin.H{
-		"code": common.CodeSuccess,
-		"data": gin.H{
-			"title":          title,
-			"avatar":         avatar,
-			"prologue":       prologue,
-			"has_tavily_key": hasTavily,
-			"llm_id":         llmID,
-		},
-		"message": "success",
-	})
+	common.SuccessWithData(c, gin.H{
+		"title":          title,
+		"avatar":         avatar,
+		"prologue":       prologue,
+		"has_tavily_key": hasTavily,
+		"llm_id":         llmID,
+	}, "success")
🤖 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/handler/bot.go` around lines 64 - 92, The success response in
BotHandler.ChatbotInfo is still manually constructing the standard {code, data,
message} payload instead of using the shared helper. Replace the final c.JSON
block with common.SuccessWithData so this endpoint matches the migrated error
path and the same pattern can be applied consistently in AgentbotInputs and
GetAgentbotLogs.
internal/handler/search.go (1)

120-136: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Magic numbers instead of named error-code constants.

common.ErrorWithCode(c, 400, err.Error()) and common.ErrorWithCode(c, 500, err.Error()) use raw integers where the rest of the migrated codebase (including elsewhere in this same file, e.g. common.CodeBadRequest at line 166) uses named common.ErrorCode constants. This is easy to get subtly wrong on future edits and obscures intent.

♻️ Proposed fix
 		if err := c.ShouldBindJSON(&req); err != nil {
-			common.ErrorWithCode(c, 400, err.Error())
+			common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
 			return
 		}
 		ownerIDs = req.OwnerIDs
 	}

 	// List search apps with filtering
 	result, err := h.searchService.ListSearches(userID, keywords, page, pageSize, orderby, desc, ownerIDs)
 	if err != nil {
-		common.ErrorWithCode(c, 500, err.Error())
+		common.ErrorWithCode(c, int(common.CodeServerError), err.Error())
 		return
 	}
🤖 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/handler/search.go` around lines 120 - 136, The search handler is
using raw numeric HTTP error codes instead of the existing named
`common.ErrorCode` constants. Update the error paths in `search.go` within the
request-binding and `h.searchService.ListSearches` handling to call
`common.ErrorWithCode` with the appropriate constants (for example the same
`common.CodeBadRequest` style used elsewhere in `SearchApps`) instead of `400`
and `500`, so the `ListSearches` flow stays consistent with the rest of the
file.
internal/handler/agent.go (1)

130-135: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Inconsistent error envelope shape across endpoints (ErrorWithCode vs ResponseWithCodeData).

Several endpoints use common.ErrorWithCode (envelope {code, message}, no data key) for the exact same "GetUser auth failure" case that most other endpoints in this file handle via common.ResponseWithCodeData(c, code, nil, msg) (envelope {code, data:null, message}). E.g. ListAgents (Line 133), CreateAgent (Line 244), ListTemplates (Line 358), ListAgentSessions/CreateAgentSession/GetAgentSession/DeleteAgentSession all use ErrorWithCode, while GetAgent, UpdateAgent, DeleteAgent, RunAgent, CancelAgent, PublishAgent, etc. use ResponseWithCodeData.

Given this PR's explicit purpose is to merge/standardize HTTP response construction, consider using ResponseWithCodeData(c, code, nil, msg) uniformly so every agent endpoint returns the same envelope shape (with a data key present) for equivalent error conditions.

Also applies to: 244-246, 358-360, 683-688, 725-726, 754-758, 774-779, 1129-1133

🤖 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/handler/agent.go` around lines 130 - 135, Standardize the
auth-failure response shape in AgentHandler so all endpoints use the same
envelope. In functions like ListAgents, CreateAgent, ListTemplates, and the
AgentSession handlers, replace ErrorWithCode with ResponseWithCodeData(c, code,
nil, msg) to match the other agent endpoints that already return {code,
data:null, message}. Keep the change consistent across the identified methods in
AgentHandler so the GetUser failure path uses one shared response format
everywhere.
internal/handler/agent_component.go (1)

75-79: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Incomplete migration: two success paths still hand-build the envelope.

GetComponentInputForm (Line 75-79) and DebugComponent (Line 230-234) still use c.JSON(200, gin.H{"code": ..., "data": ..., "message": "success"}) instead of common.SuccessWithData(c, ..., "success"), unlike every error path in this file which was migrated. Output is equivalent today, but leaving this un-migrated defeats the goal of centralizing the response envelope and risks future drift if the envelope shape changes.

♻️ Proposed fix
-	c.JSON(200, gin.H{
-		"code":    common.CodeSuccess,
-		"data":    form,
-		"message": "success",
-	})
+	common.SuccessWithData(c, form, "success")
-	c.JSON(200, gin.H{
-		"code":    common.CodeSuccess,
-		"data":    outputs,
-		"message": "success",
-	})
+	common.SuccessWithData(c, outputs, "success")

Also applies to: 230-234

🤖 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/handler/agent_component.go` around lines 75 - 79, The two remaining
success responses in GetComponentInputForm and DebugComponent still hand-build
the JSON envelope instead of using the centralized helper. Replace the inline
c.JSON(200, gin.H{...}) success payloads with common.SuccessWithData(c, ...,
"success") so these paths match the rest of the file’s response handling. Use
the existing symbols GetComponentInputForm and DebugComponent to find both call
sites and keep the response shape centralized.
internal/handler/agent_upload.go (1)

119-131: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Incomplete migration: success responses still hand-built.

Both success paths in UploadAgentFile — the URL-import branch (Line 125-129) and the normal multi-file branch (Line 152-156) — still use c.JSON(200, gin.H{"code":..., "data":..., "message":"success"}) instead of common.SuccessWithData, while every error path in this handler was migrated. Same envelope today, but inconsistent with the rest of the migration.

♻️ Proposed fix
-		c.JSON(200, gin.H{
-			"code":    common.CodeSuccess,
-			"data":    uploaded,
-			"message": "success",
-		})
+		common.SuccessWithData(c, uploaded, "success")
-	c.JSON(200, gin.H{
-		"code":    common.CodeSuccess,
-		"data":    payload,
-		"message": "success",
-	})
+	common.SuccessWithData(c, payload, "success")

Also applies to: 133-157

🤖 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/handler/agent_upload.go` around lines 119 - 131, The success
responses in UploadAgentFile are still being built manually, which leaves the
handler inconsistent with the migration. Update both the URL-import branch and
the normal multi-file branch to use common.SuccessWithData instead of c.JSON
with a hand-built gin.H envelope, and keep the existing uploaded response
payload and success message behavior aligned with the rest of the handler.
internal/handler/mcp.go (1)

280-292: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Unbounded request body read in ImportMCPServers.

io.ReadAll(c.Request.Body) has no size limit here, whereas mcp_server.go's HandleMCP (same PR/cohort) wraps the reader with http.MaxBytesReader to cap it at 1 MiB. Without a similar cap, a large payload can exhaust memory on this authenticated endpoint.

🛡️ Proposed fix
+	const maxImportBodyBytes = 1 << 20 // 1 MiB, consistent with HandleMCP
+	c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxImportBodyBytes)
 	body, err := io.ReadAll(c.Request.Body)
 	if err != nil {
 		common.ResponseWithCodeData(c, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
 		return
 	}
🤖 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/handler/mcp.go` around lines 280 - 292, ImportMCPServers reads the
request body with io.ReadAll without any size cap, which can allow unbounded
memory usage. Add a request body limit in ImportMCPServers before reading, using
the same approach as HandleMCP in mcp_server.go (for example, wrap the body with
http.MaxBytesReader via the Gin context’s ResponseWriter and request), then keep
the existing JSON parsing and Invalid request body handling intact.
internal/handler/auth.go (1)

130-130: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Inconsistent use of literal 401 vs. named error-code constants.

Line 130 uses the literal 401 while line 150 (same function) uses int(common.CodeForbidden). For consistency and to avoid the kind of silent code-value drift possible in a large mechanical migration (as seen elsewhere in this PR), prefer the named constant.

♻️ Proposed fix
 		token := c.GetHeader("Authorization")
 		if token == "" {
-			common.ErrorWithCode(c, 401, "Missing Authorization header")
+			common.ErrorWithCode(c, int(common.CodeUnauthorized), "Missing Authorization header")
 			c.Abort()
 			return
 		}

Also applies to: 142-153

🤖 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/handler/auth.go` at line 130, In the auth handler, replace the
hardcoded HTTP status literals in the affected branch with the existing named
error-code constant style used elsewhere in the same function. Update the calls
around the Missing Authorization header and the other authorization checks in
the same block to use the appropriate common.Code* constants consistently,
matching the pattern already used by common.ErrorWithCode and avoiding mixed
literal/constant usage.
🤖 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/admin/enterprise_handler.go`:
- Around line 1475-1480: In ListUsersIndex, the strconv.Atoi error path for
parsing topStr reports a 400 via common.ErrorWithCode but then continues
execution. Add an immediate return in that error branch so the handler exits
before reaching the service call and success response, and keep the fix
localized around the top parsing logic in ListUsersIndex.
- Around line 1431-1436: The `ListUsersDocuments` handler is missing a return
after the `top` parsing error path, so execution continues into the service call
and success response. Update the `topStr`/`strconv.Atoi` error branch in
`ListUsersDocuments` to return immediately after `common.ErrorWithCode(c, 400,
"Top must be an integer")`, matching the behavior in `ListUsersStorage`.
- Around line 1531-1536: The ListUsersQuota handler’s `topStr` parse-error
branch is missing an early exit after writing the 400 response. Update the `top`
parsing block in `enterprise_handler.go` so that after `common.ErrorWithCode(c,
400, "Top must be an integer")` the function immediately returns, preventing a
second response write. Use the `ListUsersQuota`/`topStr`/`common.ErrorWithCode`
block as the target location.
- Around line 1387-1392: The top parsing branch in enterprise_handler.go is
missing a return after common.ErrorWithCode in the topStr handling, so the
handler continues into h.service.ListUsersStorage with a zero top and may write
a second response. Add an immediate return in the same top parsing block used by
the page/page_size branches so the function exits right after the "Top must be
an integer" error is sent.

In `@internal/admin/handler.go`:
- Around line 1120-1123: The error path in the Get all tasks handler is falling
through after common.ErrorWithCode, causing a second success response to be
written. Update the handler in internal/admin/handler.go so that when err !=
nil, it exits immediately after sending the error response, and only calls
common.SuccessWithData for the successful path; use the surrounding task-listing
logic in the same handler to place the return right after the error branch.

In `@internal/handler/api_token.go`:
- Line 47: The tenant-not-found error message has an accidental leading colon in
api_token handling, so update the message text used by the relevant handlers to
remove it. Fix all three occurrences in the api_token flow by changing the
string passed to common.ErrorWithCode in the affected functions so it
consistently reads Tenant not found, and verify the same wording is used
wherever the migrated message is referenced.
- Around line 33-47: The API key error branches in api_token.go are using
common.ErrorWithCode in a way that still returns 200 OK, so update the handler
to emit the real HTTP status codes for the unauthorized, invalid user, and
tenant-not-found paths. Fix the error handling in the API token handler around
the userModel and userTenantDAO.GetByUserIDAndRole checks by using a helper that
sets the response status (or by setting the status directly) instead of relying
on common.ErrorWithCode. Also correct the tenant-not-found message text in that
branch to remove the accidental leading colon.

In `@internal/handler/mcp_server.go`:
- Around line 79-85: The MCP request-body read error in the mcpServer handler is
using a hardcoded error code that diverges from the shared bad-request path.
Update the error handling in the request body read block to use
common.CodeBadRequest instead of 1, keeping the same common.ErrorWithCode call
so malformed bodies consistently return the standard parse-failure code.

In `@internal/handler/openai_chat.go`:
- Around line 47-51: The empty chat_id branch in OpenAIChat handling uses an
ownership error message even when the parameter is missing, which is misleading.
Update the guard around c.Param("chat_id") in the chat handler to return a
dedicated empty-parameter validation message instead of concatenating chatID
into "You don't own the chat ", and keep the response path in the same handler
using common.ResponseWithCodeData.

In `@internal/handler/providers.go`:
- Around line 593-610: The AddModel success branch is using the error response
helper instead of the standard success path, so the response shape is
inconsistent with the rest of providers.go. In the handler that calls
h.modelProviderService.AddModel, replace the final common.ErrorWithCode(...,
"success") with the appropriate success helper used elsewhere in this file, such
as common.SuccessWithMessage or common.SuccessWithData, while keeping the
existing code value and message semantics intact.

In `@internal/handler/searchbot.go`:
- Around line 169-175: `SearchBotHandler.RetrievalTest` handles `GetUser`
failures with a different response helper than the sibling handlers, causing an
inconsistent auth-failure JSON envelope. Update the `GetUser` error branch in
`RetrievalTest` to match `Handle`, `Ask`, and `MindMap` by using
`common.ErrorWithCode(c, int(errorCode), errorMessage)` instead of
`common.ResponseWithCodeData(...)`, so all auth failures return the same shape.

---

Outside diff comments:
In `@internal/handler/agent_webhook.go`:
- Around line 189-204: `common.ResponseWithCodeData` in the webhook parse error
handling always returns HTTP 200, so the multipart-not-supported path is not
actually sending 501. Update the `parseErr` switch in `agent_webhook.go` to use
`c.JSON` or `c.Status` plus `c.JSON` for the `ErrWebhookMultipartNotSupported`
case so the real HTTP status is preserved, while keeping the existing helper for
the other error cases if appropriate. Refer to
`ErrWebhookMultipartNotSupported`, `ErrWebhookContentTypeMismatch`, and
`common.ResponseWithCodeData` when making the change.

In `@internal/handler/dify_retrieval_handler.go`:
- Around line 165-215: The Dify retrieval handler is using common.ErrorWithCode
in validation, auth, and not-found paths, which returns HTTP 200 instead of a
failure response. Update difyRetrievalHandler to return non-200 status codes for
these branches and emit Dify’s error schema with error_code and error_msg rather
than the current code/message payload. Keep the changes localized around the
request parsing, kbSvc.GetByID lookup, and Accessible authorization checks so
all early exits follow the same error format.

In `@internal/handler/file.go`:
- Around line 76-84: The page parsing in the file handler silently accepts
non-positive values because the strconv.Atoi branch only errors on parse
failures, not when p < 1. Update the page validation in the page/query handling
block of the handler method to explicitly reject zero and negative values with
the same parameter error used for invalid input, matching the stricter
validation already applied in the page_size logic. Use the existing page
variable and common.ResponseWithCodeData flow so page=0 and page=-1 return an
error instead of falling back to the default page.

In `@internal/handler/memory.go`:
- Around line 525-575: The empty authenticated-user ID check in
MemoryHandler.AddMessage is using the wrong error code. Update the currentUserID
validation in AddMessage to return common.CodeAuthenticationError, matching the
same check used in GetMemoryMessages, UpdateMessage, GetMessageContent,
SearchMessage, and GetMessages, so the handler treats this as an auth failure
rather than an argument error.
- Around line 257-282: `DeleteMemory` is operating only on `memory_id`, so it
can affect records outside the caller’s ownership scope. Update
`MemoryHandler.DeleteMemory` to resolve the current user from `gin.Context` and
pass that identity/tenant scope into `memoryService.DeleteMemory`, then enforce
the ownership check in `MemoryService` and `MemoryDAO` so only the owner’s
memory can be deleted. Make the same scoping change for `GetMemoryConfig` and
use the existing symbols `MemoryHandler`, `DeleteMemory`, `GetMemoryConfig`,
`MemoryService`, and `MemoryDAO` to thread the user context through all memory
lookups.

---

Nitpick comments:
In `@internal/admin/enterprise_handler.go`:
- Around line 649-653: The JSON bind error path in the enterprise handlers still
uses builtin println with unsupported format verbs, so replace it with the
package’s structured logging or remove it entirely. Update the ShouldBindJSON
failure handling in this handler and the sibling handlers mentioned in the
review (such as SetSystemLicense, ShowUserActivity, ListUsersQuota, and
PurgeOrphanData) to log errors consistently using the existing logger instead of
println.

In `@internal/cli/filesystem/skill_hub/source/clawhub.go`:
- Around line 49-51: The `progressLogger.SuccessWithData` method name collides
conceptually with the new `common.SuccessWithData` helper and can confuse future
reads and searches. Rename the `progressLogger` method in `clawhub.go` to
something that reflects CLI logging behavior, such as `logSuccess`, and update
any internal call sites so the `progressLogger` type remains clearly distinct
from the Gin response helper.

In `@internal/common/response.go`:
- Around line 71-85: The custom response helpers use inconsistent code types:
ErrorWithCode accepts int while ResponseWithCodeData accepts ErrorCode, which
forces unnecessary casting at call sites. Make the parameter type consistent
across both helpers in response.go by updating ErrorWithCode to use ErrorCode as
well (or otherwise align both on the same type) and adjust the JSON payload
conversion inside the helper if needed. Keep the behavior of ErrorWithCode and
ResponseWithCodeData unchanged aside from the unified signature, so migrated
handlers can pass ErrorCode values directly without int(code) casts.

In `@internal/handler/agent_component.go`:
- Around line 75-79: The two remaining success responses in
GetComponentInputForm and DebugComponent still hand-build the JSON envelope
instead of using the centralized helper. Replace the inline c.JSON(200,
gin.H{...}) success payloads with common.SuccessWithData(c, ..., "success") so
these paths match the rest of the file’s response handling. Use the existing
symbols GetComponentInputForm and DebugComponent to find both call sites and
keep the response shape centralized.

In `@internal/handler/agent_upload.go`:
- Around line 119-131: The success responses in UploadAgentFile are still being
built manually, which leaves the handler inconsistent with the migration. Update
both the URL-import branch and the normal multi-file branch to use
common.SuccessWithData instead of c.JSON with a hand-built gin.H envelope, and
keep the existing uploaded response payload and success message behavior aligned
with the rest of the handler.

In `@internal/handler/agent.go`:
- Around line 130-135: Standardize the auth-failure response shape in
AgentHandler so all endpoints use the same envelope. In functions like
ListAgents, CreateAgent, ListTemplates, and the AgentSession handlers, replace
ErrorWithCode with ResponseWithCodeData(c, code, nil, msg) to match the other
agent endpoints that already return {code, data:null, message}. Keep the change
consistent across the identified methods in AgentHandler so the GetUser failure
path uses one shared response format everywhere.

In `@internal/handler/auth.go`:
- Line 130: In the auth handler, replace the hardcoded HTTP status literals in
the affected branch with the existing named error-code constant style used
elsewhere in the same function. Update the calls around the Missing
Authorization header and the other authorization checks in the same block to use
the appropriate common.Code* constants consistently, matching the pattern
already used by common.ErrorWithCode and avoiding mixed literal/constant usage.

In `@internal/handler/bot.go`:
- Around line 64-92: The success response in BotHandler.ChatbotInfo is still
manually constructing the standard {code, data, message} payload instead of
using the shared helper. Replace the final c.JSON block with
common.SuccessWithData so this endpoint matches the migrated error path and the
same pattern can be applied consistently in AgentbotInputs and GetAgentbotLogs.

In `@internal/handler/document.go`:
- Around line 337-344: The UpdateDocument handler still returns a raw JSON error
body from the h.documentService.UpdateDocument path, which breaks the shared
response envelope used elsewhere. Update the error branch in the UpdateDocument
method to use the same standardized helper pattern as the success path,
returning the common {code, message} shape instead of c.JSON with {"error":
...}. Keep the existing service call and success handling intact, and align this
handler with the rest of the migrated response helpers in
internal/handler/document.go.

In `@internal/handler/mcp.go`:
- Around line 280-292: ImportMCPServers reads the request body with io.ReadAll
without any size cap, which can allow unbounded memory usage. Add a request body
limit in ImportMCPServers before reading, using the same approach as HandleMCP
in mcp_server.go (for example, wrap the body with http.MaxBytesReader via the
Gin context’s ResponseWriter and request), then keep the existing JSON parsing
and Invalid request body handling intact.

In `@internal/handler/search.go`:
- Around line 120-136: The search handler is using raw numeric HTTP error codes
instead of the existing named `common.ErrorCode` constants. Update the error
paths in `search.go` within the request-binding and
`h.searchService.ListSearches` handling to call `common.ErrorWithCode` with the
appropriate constants (for example the same `common.CodeBadRequest` style used
elsewhere in `SearchApps`) instead of `400` and `500`, so the `ListSearches`
flow stays consistent with the rest of the file.
🪄 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: 457eff38-6d76-4a2a-8ce1-ce5b0124f887

📥 Commits

Reviewing files that changed from the base of the PR and between 290ab55 and 9e13886.

📒 Files selected for processing (48)
  • internal/admin/enterprise_handler.go
  • internal/admin/handler.go
  • internal/cli/filesystem/skill_hub/source/clawhub.go
  • internal/common/response.go
  • internal/handler/admin_runtime.go
  • internal/handler/agent.go
  • internal/handler/agent_attachment.go
  • internal/handler/agent_component.go
  • internal/handler/agent_download.go
  • internal/handler/agent_test.go
  • internal/handler/agent_upload.go
  • internal/handler/agent_wait_for_user_test.go
  • internal/handler/agent_webhook.go
  • internal/handler/api_token.go
  • internal/handler/auth.go
  • internal/handler/bot.go
  • internal/handler/bot_test.go
  • internal/handler/chat.go
  • internal/handler/chat_channel.go
  • internal/handler/chat_recommendation.go
  • internal/handler/chat_session.go
  • internal/handler/chunk.go
  • internal/handler/components.go
  • internal/handler/connector.go
  • internal/handler/dataset.go
  • internal/handler/dify_retrieval_handler.go
  • internal/handler/document.go
  • internal/handler/error.go
  • internal/handler/file.go
  • internal/handler/file_commit.go
  • internal/handler/langfuse.go
  • internal/handler/llm.go
  • internal/handler/mcp.go
  • internal/handler/mcp_server.go
  • internal/handler/memory.go
  • internal/handler/models.go
  • internal/handler/oauth_login.go
  • internal/handler/openai_chat.go
  • internal/handler/plugin.go
  • internal/handler/providers.go
  • internal/handler/search.go
  • internal/handler/searchbot.go
  • internal/handler/skill_search.go
  • internal/handler/stats.go
  • internal/handler/system.go
  • internal/handler/tenant.go
  • internal/handler/user.go
  • internal/service/openai_chat.go

Comment on lines 1387 to 1392
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
errorResponse(c, "Top must be an integer", 400)
common.ErrorWithCode(c, 400, "Top must be an integer")
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Missing return after the "Top must be an integer" error.

Unlike the page/page_size branches above, the top parse-error branch does not return. On a bad top value this writes an error response, then continues to call h.service.ListUsersStorage(..., top) with top == 0 and finally writes a second (success) response — a double WriteHeader and a wrong result.

🐛 Proposed fix
 		top, err = strconv.Atoi(topStr)
 		if err != nil {
 			common.ErrorWithCode(c, 400, "Top must be an integer")
+			return
 		}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
errorResponse(c, "Top must be an integer", 400)
common.ErrorWithCode(c, 400, "Top must be an integer")
}
}
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
common.ErrorWithCode(c, 400, "Top must be an integer")
return
}
}
🤖 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/admin/enterprise_handler.go` around lines 1387 - 1392, The top
parsing branch in enterprise_handler.go is missing a return after
common.ErrorWithCode in the topStr handling, so the handler continues into
h.service.ListUsersStorage with a zero top and may write a second response. Add
an immediate return in the same top parsing block used by the page/page_size
branches so the function exits right after the "Top must be an integer" error is
sent.

Comment on lines 1431 to 1436
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
errorResponse(c, "Top must be an integer", 400)
common.ErrorWithCode(c, 400, "Top must be an integer")
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Same missing return as ListUsersStorage.

The top parse-error branch in ListUsersDocuments falls through to the service call and success response. Add return after common.ErrorWithCode(c, 400, "Top must be an integer").

🤖 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/admin/enterprise_handler.go` around lines 1431 - 1436, The
`ListUsersDocuments` handler is missing a return after the `top` parsing error
path, so execution continues into the service call and success response. Update
the `topStr`/`strconv.Atoi` error branch in `ListUsersDocuments` to return
immediately after `common.ErrorWithCode(c, 400, "Top must be an integer")`,
matching the behavior in `ListUsersStorage`.

Comment on lines 1475 to 1480
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
errorResponse(c, "Top must be an integer", 400)
common.ErrorWithCode(c, 400, "Top must be an integer")
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Same missing return in ListUsersIndex.

The top parse-error branch does not return; execution continues to the service call and success response. Add return after the error.

🤖 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/admin/enterprise_handler.go` around lines 1475 - 1480, In
ListUsersIndex, the strconv.Atoi error path for parsing topStr reports a 400 via
common.ErrorWithCode but then continues execution. Add an immediate return in
that error branch so the handler exits before reaching the service call and
success response, and keep the fix localized around the top parsing logic in
ListUsersIndex.

Comment on lines 1531 to 1536
if topStr != "" {
top, err = strconv.Atoi(topStr)
if err != nil {
errorResponse(c, "Top must be an integer", 400)
common.ErrorWithCode(c, 400, "Top must be an integer")
}
}

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Same missing return in ListUsersQuota.

The top parse-error branch lacks return, causing a double response write. Add return after common.ErrorWithCode(c, 400, "Top must be an integer").

🤖 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/admin/enterprise_handler.go` around lines 1531 - 1536, The
ListUsersQuota handler’s `topStr` parse-error branch is missing an early exit
after writing the 400 response. Update the `top` parsing block in
`enterprise_handler.go` so that after `common.ErrorWithCode(c, 400, "Top must be
an integer")` the function immediately returns, preventing a second response
write. Use the `ListUsersQuota`/`topStr`/`common.ErrorWithCode` block as the
target location.

Comment thread internal/admin/handler.go
Comment on lines 1120 to +1123
if err != nil {
errorResponse(c, err.Error(), 500)
common.ErrorWithCode(c, 500, err.Error())
}
success(c, tasks, "Get all tasks")
common.SuccessWithData(c, tasks, "Get all tasks")

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Missing return after the error response.

When err != nil, common.ErrorWithCode(c, 500, ...) runs but execution falls through to common.SuccessWithData(c, tasks, "Get all tasks"), producing two response writes and returning a success envelope on failure.

🐛 Proposed fix
 	if err != nil {
 		common.ErrorWithCode(c, 500, err.Error())
+		return
 	}
 	common.SuccessWithData(c, tasks, "Get all tasks")
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err != nil {
errorResponse(c, err.Error(), 500)
common.ErrorWithCode(c, 500, err.Error())
}
success(c, tasks, "Get all tasks")
common.SuccessWithData(c, tasks, "Get all tasks")
if err != nil {
common.ErrorWithCode(c, 500, err.Error())
return
}
common.SuccessWithData(c, tasks, "Get all tasks")
🤖 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/admin/handler.go` around lines 1120 - 1123, The error path in the
Get all tasks handler is falling through after common.ErrorWithCode, causing a
second success response to be written. Update the handler in
internal/admin/handler.go so that when err != nil, it exits immediately after
sending the error response, and only calls common.SuccessWithData for the
successful path; use the surrounding task-listing logic in the same handler to
place the return right after the error branch.

Comment thread internal/handler/api_token.go Resolved
Comment thread internal/handler/mcp_server.go Resolved
Comment on lines 47 to 51
chatID := c.Param("chat_id")
if chatID == "" {
jsonError(c, common.CodeDataError, "You don't own the chat "+chatID)
common.ResponseWithCodeData(c, common.CodeDataError, nil, "You don't own the chat "+chatID)
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Confusing/malformed message for empty chat_id.

When chatID == "", the message becomes "You don't own the chat " (trailing space, no id), which misrepresents an empty-parameter case as an ownership failure.

✏️ Proposed fix
-	if chatID == "" {
-		common.ResponseWithCodeData(c, common.CodeDataError, nil, "You don't own the chat "+chatID)
-		return
-	}
+	if chatID == "" {
+		common.ResponseWithCodeData(c, common.CodeDataError, nil, "chat_id is required")
+		return
+	}
📝 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
chatID := c.Param("chat_id")
if chatID == "" {
jsonError(c, common.CodeDataError, "You don't own the chat "+chatID)
common.ResponseWithCodeData(c, common.CodeDataError, nil, "You don't own the chat "+chatID)
return
}
chatID := c.Param("chat_id")
if chatID == "" {
common.ResponseWithCodeData(c, common.CodeDataError, nil, "chat_id is required")
return
}
🤖 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/handler/openai_chat.go` around lines 47 - 51, The empty chat_id
branch in OpenAIChat handling uses an ownership error message even when the
parameter is missing, which is misleading. Update the guard around
c.Param("chat_id") in the chat handler to return a dedicated empty-parameter
validation message instead of concatenating chatID into "You don't own the chat
", and keep the response path in the same handler using
common.ResponseWithCodeData.

Comment thread internal/handler/providers.go Outdated
Comment on lines +593 to +610
common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
return
}

if err := prepareAddModelRequest(&req, c.Param("provider_name"), c.Param("instance_name")); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": common.CodeBadRequest,
"message": err.Error(),
})
common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
return
}

userID := c.GetString("user_id")

code, err := h.modelProviderService.AddModel(&req, userID)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": code,
"message": err.Error(),
})
common.ErrorWithCode(c, int(code), err.Error())
return
}

c.JSON(http.StatusOK, gin.H{
"code": code,
"message": "success",
})
common.ErrorWithCode(c, int(code), "success")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

AddModel success path uses ErrorWithCode instead of a success helper.

After h.modelProviderService.AddModel(...) succeeds (err == nil), the handler calls common.ErrorWithCode(c, int(code), "success"). ErrorWithCode serializes via errorResponse{Code, Message} — it has no data field, unlike every other success response in this file (SuccessWithMessage/SuccessWithData). This both breaks the response-shape contract for API consumers expecting a data key and is semantically confusing (reporting success through an "Error" helper).

🐛 Proposed fix
 	code, err := h.modelProviderService.AddModel(&req, userID)
 	if err != nil {
 		common.ErrorWithCode(c, int(code), err.Error())
 		return
 	}
 
-	common.ErrorWithCode(c, int(code), "success")
+	common.SuccessWithMessage(c, "success")
 }
📝 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
common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
return
}
if err := prepareAddModelRequest(&req, c.Param("provider_name"), c.Param("instance_name")); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"code": common.CodeBadRequest,
"message": err.Error(),
})
common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
return
}
userID := c.GetString("user_id")
code, err := h.modelProviderService.AddModel(&req, userID)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"code": code,
"message": err.Error(),
})
common.ErrorWithCode(c, int(code), err.Error())
return
}
c.JSON(http.StatusOK, gin.H{
"code": code,
"message": "success",
})
common.ErrorWithCode(c, int(code), "success")
common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
return
}
if err := prepareAddModelRequest(&req, c.Param("provider_name"), c.Param("instance_name")); err != nil {
common.ErrorWithCode(c, int(common.CodeBadRequest), err.Error())
return
}
userID := c.GetString("user_id")
code, err := h.modelProviderService.AddModel(&req, userID)
if err != nil {
common.ErrorWithCode(c, int(code), err.Error())
return
}
common.SuccessWithMessage(c, "success")
🤖 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/handler/providers.go` around lines 593 - 610, The AddModel success
branch is using the error response helper instead of the standard success path,
so the response shape is inconsistent with the rest of providers.go. In the
handler that calls h.modelProviderService.AddModel, replace the final
common.ErrorWithCode(..., "success") with the appropriate success helper used
elsewhere in this file, such as common.SuccessWithMessage or
common.SuccessWithData, while keeping the existing code value and message
semantics intact.

Comment on lines 169 to 175
func (h *SearchBotHandler) RetrievalTest(c *gin.Context) {
user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
c.JSON(http.StatusUnauthorized, gin.H{"code": errorCode, "data": nil, "message": errorMessage})
common.ResponseWithCodeData(c, errorCode, nil, errorMessage)
return
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

Inconsistent auth-failure envelope vs. sibling handlers.

Line 172 uses common.ResponseWithCodeData(c, errorCode, nil, errorMessage) for the GetUser failure, while Handle (135), Ask (227), and MindMap (318) all use common.ErrorWithCode(c, int(errorCode), errorMessage) for the identical check. This produces a different JSON shape (data: null present vs. absent) for the exact same auth-failure condition depending on which endpoint is hit, undermining the standardization goal of this migration.

🔧 Proposed fix
 	user, errorCode, errorMessage := GetUser(c)
 	if errorCode != common.CodeSuccess {
-		common.ResponseWithCodeData(c, errorCode, nil, errorMessage)
+		common.ErrorWithCode(c, int(errorCode), errorMessage)
 		return
 	}
📝 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 (h *SearchBotHandler) RetrievalTest(c *gin.Context) {
user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
c.JSON(http.StatusUnauthorized, gin.H{"code": errorCode, "data": nil, "message": errorMessage})
common.ResponseWithCodeData(c, errorCode, nil, errorMessage)
return
}
func (h *SearchBotHandler) RetrievalTest(c *gin.Context) {
user, errorCode, errorMessage := GetUser(c)
if errorCode != common.CodeSuccess {
common.ErrorWithCode(c, int(errorCode), errorMessage)
return
}
🤖 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/handler/searchbot.go` around lines 169 - 175,
`SearchBotHandler.RetrievalTest` handles `GetUser` failures with a different
response helper than the sibling handlers, causing an inconsistent auth-failure
JSON envelope. Update the `GetUser` error branch in `RetrievalTest` to match
`Handle`, `Ask`, and `MindMap` by using `common.ErrorWithCode(c, int(errorCode),
errorMessage)` instead of `common.ResponseWithCodeData(...)`, so all auth
failures return the same shape.

JinHai-CN added 2 commits July 6, 2026 15:50
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

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

⚠️ Outside diff range comments (1)
internal/handler/auth.go (1)

160-160: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Preserve the service-unavailable status here.

This branch handles admin/license unavailability, not bad credentials. The previous behavior returned HTTP 503, but common.CodeUnauthorized makes clients treat a temporary service state as an auth failure.

Proposed fix
-			common.ResponseWithCodeData(c, common.CodeUnauthorized, "No", errMsg)
+			common.ResponseWithHttpCodeData(c, http.StatusServiceUnavailable, http.StatusServiceUnavailable, "No", errMsg)
🤖 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/handler/auth.go` at line 160, The auth failure branch in the handler
should keep returning service-unavailable semantics instead of unauthorized.
Update the response in the admin/license-unavailable path in auth.go to use the
existing service-unavailable code constant rather than common.CodeUnauthorized,
so clients still see a temporary availability issue. Use the surrounding auth
handling logic and the ResponseWithCodeData call to locate and adjust this
branch.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@internal/handler/auth.go`:
- Line 160: The auth failure branch in the handler should keep returning
service-unavailable semantics instead of unauthorized. Update the response in
the admin/license-unavailable path in auth.go to use the existing
service-unavailable code constant rather than common.CodeUnauthorized, so
clients still see a temporary availability issue. Use the surrounding auth
handling logic and the ResponseWithCodeData call to locate and adjust this
branch.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 576bdcb3-159f-4384-8f63-d8798ce4948a

📥 Commits

Reviewing files that changed from the base of the PR and between 9e13886 and 7b76398.

📒 Files selected for processing (3)
  • internal/common/response.go
  • internal/handler/auth.go
  • internal/handler/components.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/common/response.go
  • internal/handler/components.go

JinHai-CN added 2 commits July 6, 2026 16:04
Signed-off-by: Jin Hai <[email protected]>
Signed-off-by: Jin Hai <[email protected]>

@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: 3

Caution

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

⚠️ Outside diff range comments (1)
internal/admin/handler.go (1)

1191-1196: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Success path incorrectly returns an error response.

When errCode == common.CodeLicenseValid (the success case), the handler falls through to common.ErrorWithCode(c, int(errCode), message), so a valid heartbeat is reported as an error. Both branches call ErrorWithCode with identical arguments, making the if a no-op. The success case should emit a success envelope.

🐛 Proposed fix
 	errCode, message := h.service.HandleHeartbeat(&req)
 	if errCode != common.CodeLicenseValid {
 		common.ErrorWithCode(c, int(errCode), message)
 		return
 	}
-	common.ErrorWithCode(c, int(errCode), message)
+	common.SuccessNoData(c, message)
🤖 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/admin/handler.go` around lines 1191 - 1196, The license heartbeat
handler currently returns an error response even when errCode equals
common.CodeLicenseValid, because both branches call common.ErrorWithCode and the
success path falls through to the same error response. Update the handler logic
so the success case emits the proper success envelope instead of ErrorWithCode,
and keep the error branch using common.ErrorWithCode; use the surrounding
license/heartbeat handler code and the errCode check to locate the fix.
🧹 Nitpick comments (1)
internal/admin/handler.go (1)

719-746: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Use common.CodeNotImplemented for these 501 placeholders
internal/admin/handler.go:720-746 returns HTTP 501 with common.CodeBadRequest, so the JSON body still reports 400. Switch these method not implemented responses to common.CodeNotImplemented to keep the payload aligned with the status code.

🤖 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/admin/handler.go` around lines 719 - 746, The placeholder handlers
in Handler.GetFingerprint, Handler.SetLicense, Handler.UpdateLicenseConfig, and
Handler.ShowLicense return HTTP 501 but still use common.CodeBadRequest in the
response payload. Update these “method not implemented” responses to use
common.CodeNotImplemented so the JSON body matches the 501 status code
consistently.
🤖 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/admin/handler.go`:
- Line 843: The TestSandboxConnection error response is using a misleading
copy-paste message instead of the real failure. In the handler logic around
common.ResponseWithHttpCodeData, replace the hardcoded "Invalid access token"
text with the actual error details from the sandbox connection failure (for
example, the err returned by the test) so the response reflects the real cause.
- Line 869: Guard the user superuser check in the admin handler before
dereferencing the pointer: the `user.IsSuperuser` field is a `*bool`, so
`!*user.IsSuperuser` can panic when it is nil. Update the conditional in
`internal/admin/handler.go` to follow the same nil-safe pattern used in
`internal/handler/auth.go`, and keep the existing authorization logic unchanged
for non-nil values.
- Around line 869-872: The permission check in the Gin middleware currently
returns a 403 response but does not stop the handler chain, so the next handler
can still execute; update the authorization block around the superuser check to
call c.Abort() immediately after common.ResponseWithHttpCodeData and before
returning. Keep the fix localized to the middleware that handles the
user.IsSuperuser guard so the request is fully terminated once forbidden access
is detected.

---

Outside diff comments:
In `@internal/admin/handler.go`:
- Around line 1191-1196: The license heartbeat handler currently returns an
error response even when errCode equals common.CodeLicenseValid, because both
branches call common.ErrorWithCode and the success path falls through to the
same error response. Update the handler logic so the success case emits the
proper success envelope instead of ErrorWithCode, and keep the error branch
using common.ErrorWithCode; use the surrounding license/heartbeat handler code
and the errCode check to locate the fix.

---

Nitpick comments:
In `@internal/admin/handler.go`:
- Around line 719-746: The placeholder handlers in Handler.GetFingerprint,
Handler.SetLicense, Handler.UpdateLicenseConfig, and Handler.ShowLicense return
HTTP 501 but still use common.CodeBadRequest in the response payload. Update
these “method not implemented” responses to use common.CodeNotImplemented so the
JSON body matches the 501 status code consistently.
🪄 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: 9e43527d-ef96-42c3-946e-48ef2ae895c6

📥 Commits

Reviewing files that changed from the base of the PR and between 7b76398 and 19b165c.

📒 Files selected for processing (6)
  • internal/admin/enterprise_handler.go
  • internal/admin/handler.go
  • internal/common/error_code.go
  • internal/handler/agent_webhook.go
  • internal/handler/api_token.go
  • internal/handler/auth.go
✅ Files skipped from review due to trivial changes (1)
  • internal/common/error_code.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/handler/agent_webhook.go
  • internal/admin/enterprise_handler.go

Comment thread internal/admin/handler.go
"code": common.CodeBadRequest,
"message": "Invalid access token",
})
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid access token")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Misleading error message in TestSandboxConnection.

The message "Invalid access token" is unrelated to a sandbox connection test failure and looks like a copy-paste artifact. Surface the actual failure (e.g., err.Error()).

✏️ Proposed fix
-		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid access token")
+		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, err.Error())
📝 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
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid access token")
common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, err.Error())
🤖 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/admin/handler.go` at line 843, The TestSandboxConnection error
response is using a misleading copy-paste message instead of the real failure.
In the handler logic around common.ResponseWithHttpCodeData, replace the
hardcoded "Invalid access token" text with the actual error details from the
sandbox connection failure (for example, the err returned by the test) so the
response reflects the real cause.

Comment thread internal/admin/handler.go
return
}

if !*user.IsSuperuser {

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

set -e
printf 'Files:\n'
git ls-files internal/admin/handler.go internal/handler/auth.go
printf '\nOutline admin handler:\n'
ast-grep outline internal/admin/handler.go --view expanded | sed -n '1,220p'
printf '\nOutline auth handler:\n'
ast-grep outline internal/handler/auth.go --view expanded | sed -n '1,220p'

Repository: infiniflow/ragflow

Length of output: 6819


🏁 Script executed:

set -e
echo '--- internal/admin/handler.go around line 869 ---'
sed -n '830,900p' internal/admin/handler.go
echo
echo '--- internal/handler/auth.go around superuser guard ---'
rg -n "IsSuperuser != nil|!\\*user.IsSuperuser|IsSuperuser" internal/handler/auth.go internal/admin/handler.go
sed -n '1,220p' internal/handler/auth.go

Repository: infiniflow/ragflow

Length of output: 8375


🏁 Script executed:

set -e
echo '--- internal/admin/handler.go:840-885 ---'
nl -ba internal/admin/handler.go | sed -n '840,885p'
echo
echo '--- internal/handler/auth.go:1-220 ---'
nl -ba internal/handler/auth.go | sed -n '1,220p'
echo
echo '--- references to IsSuperuser across repo ---'
rg -n "IsSuperuser" .

Repository: infiniflow/ragflow

Length of output: 1925


🏁 Script executed:

set -e
echo '--- internal/admin/handler.go:860-878 ---'
nl -ba internal/admin/handler.go | sed -n '860,878p'
echo
echo '--- internal/handler/auth.go:1-120 ---'
nl -ba internal/handler/auth.go | sed -n '1,120p'
echo
echo '--- all IsSuperuser usages ---'
rg -n "IsSuperuser" internal | sed -n '1,200p'

Repository: infiniflow/ragflow

Length of output: 1868


Guard user.IsSuperuser before dereferencing it at internal/admin/handler.go:869. IsSuperuser is a *bool, so !*user.IsSuperuser will panic when it is nil. Use the same nil check as internal/handler/auth.go.

🤖 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/admin/handler.go` at line 869, Guard the user superuser check in the
admin handler before dereferencing the pointer: the `user.IsSuperuser` field is
a `*bool`, so `!*user.IsSuperuser` can panic when it is nil. Update the
conditional in `internal/admin/handler.go` to follow the same nil-safe pattern
used in `internal/handler/auth.go`, and keep the existing authorization logic
unchanged for non-nil values.

Comment thread internal/admin/handler.go Resolved
@JinHai-CN
JinHai-CN merged commit b3d536c into infiniflow:main Jul 6, 2026
3 checks passed

@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: 4

Caution

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

⚠️ Outside diff range comments (2)
internal/handler/mcp.go (1)

324-330: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Wrong error code for a server-side import failure.

HTTP status is 500 (correct for a service-layer failure), but the body code is common.CodeBadRequest. This should be common.CodeServerError to keep the status and code consistent, matching the pattern used correctly elsewhere in this file (e.g., ListMCPServers, line 120).

🔧 Proposed fix
-		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, err.Error())
+		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeServerError, nil, err.Error())
🤖 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/handler/mcp.go` around lines 324 - 330, The ImportServers error
response in mcp.go uses a server-side HTTP 500 but returns the wrong body code.
Update the error handling in the ImportServers path to use
common.CodeServerError instead of common.CodeBadRequest when
h.mcpService.ImportServers fails, matching the existing pattern used by
ListMCPServers and keeping the status/code consistent.
internal/handler/search.go (1)

155-185: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Two status/code mismatches in CreateSearch.

  1. Line 167 — binding failure (client's fault) returns HTTP 500 instead of 400. UpdateSearch (line 316) handles the identical case correctly with http.StatusBadRequest.
  2. Line 179 — a genuine service failure is reported with common.CodeBadRequest instead of common.CodeServerError, even though the HTTP status (500) is already correct.
🔧 Proposed fix
 	var req CreateSearchRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
-		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
+		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
 		return
 	}

 	if err := common.ValidateName(req.Name); err != nil {
 		common.ErrorWithCode(c, int(common.CodeDataError), err.Error())
 		return
 	}

 	// Create search (same as Python SearchService.save within DB.atomic())
 	result, err := h.searchService.CreateSearch(userID, req.Name, req.Description)
 	if err != nil {
-		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, err.Error())
+		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeServerError, nil, err.Error())
 		return
 	}
🤖 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/handler/search.go` around lines 155 - 185, In CreateSearch, align
the status/code mapping with the other handlers: the ShouldBindJSON validation
failure should return a client error using http.StatusBadRequest instead of
http.StatusInternalServerError, and the searchService.CreateSearch failure
should keep the 500 HTTP response but use common.CodeServerError rather than
common.CodeBadRequest. Update the error paths in SearchHandler.CreateSearch so
the response codes match the nature of the failure and stay consistent with
UpdateSearch and the shared response helpers.
🤖 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/handler/chunk.go`:
- Around line 583-602: The `UpdateChunk` error branch is writing the same
bad-request response twice, once via `common.ResponseWithHttpCodeData` and again
via `c.JSON`, which causes duplicate headers/body output. Remove the extra
manual `c.JSON` path in `UpdateChunk` and keep the shared helper call as the
only response writer for `common.CodeArgumentError`, `common.CodeBadRequest`,
and `common.CodeDataError` cases.
- Around line 380-384: The missing user_id validation in chunk.go is using the
wrong response code; update the userID empty-check in the handler to use the
same argument-validation code as the dataset_id and document_id checks instead
of common.CodeAuthenticationError. Keep the existing
common.ResponseWithHttpCodeData call and only swap the error code in the user ID
branch so clients see a required-field error rather than an auth error.

In `@internal/handler/mcp_server.go`:
- Around line 96-101: The error response in the MCP request handling branch uses
the wrong payload code, so update the server.HandleRequest error path in
mcp_server.go to send common.CodeServerError instead of common.CodeBadRequest
while keeping the 500 status and existing error message; this is the
server-error branch, so the body code must match that semantics for clients that
inspect the response payload.

In `@internal/handler/mcp.go`:
- Around line 285-296: In ImportMCPServers, cap the request body before reading
it by wrapping c.Request.Body with http.MaxBytesReader to match HandleMCP’s 1
MiB limit, then continue using io.ReadAll and json.Unmarshal on the bounded
body. Also update the ImportServers failure response so it uses
common.CodeServerError instead of common.CodeBadRequest when returning HTTP 500,
and keep the existing common.ResponseWithHttpCodeData flow intact.

---

Outside diff comments:
In `@internal/handler/mcp.go`:
- Around line 324-330: The ImportServers error response in mcp.go uses a
server-side HTTP 500 but returns the wrong body code. Update the error handling
in the ImportServers path to use common.CodeServerError instead of
common.CodeBadRequest when h.mcpService.ImportServers fails, matching the
existing pattern used by ListMCPServers and keeping the status/code consistent.

In `@internal/handler/search.go`:
- Around line 155-185: In CreateSearch, align the status/code mapping with the
other handlers: the ShouldBindJSON validation failure should return a client
error using http.StatusBadRequest instead of http.StatusInternalServerError, and
the searchService.CreateSearch failure should keep the 500 HTTP response but use
common.CodeServerError rather than common.CodeBadRequest. Update the error paths
in SearchHandler.CreateSearch so the response codes match the nature of the
failure and stay consistent with UpdateSearch and the shared response helpers.
🪄 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: 739e7835-e1e7-49ed-a66f-31872e52dbf0

📥 Commits

Reviewing files that changed from the base of the PR and between 19b165c and aa35f83.

📒 Files selected for processing (18)
  • internal/admin/handler.go
  • internal/handler/chat.go
  • internal/handler/chat_session.go
  • internal/handler/chunk.go
  • internal/handler/connector.go
  • internal/handler/dify_retrieval_handler.go
  • internal/handler/document.go
  • internal/handler/file.go
  • internal/handler/mcp.go
  • internal/handler/mcp_server.go
  • internal/handler/memory.go
  • internal/handler/oauth_login.go
  • internal/handler/providers.go
  • internal/handler/search.go
  • internal/handler/searchbot.go
  • internal/handler/system.go
  • internal/handler/tenant.go
  • internal/handler/user.go
🚧 Files skipped from review as they are similar to previous changes (11)
  • internal/handler/oauth_login.go
  • internal/handler/searchbot.go
  • internal/handler/system.go
  • internal/handler/dify_retrieval_handler.go
  • internal/handler/connector.go
  • internal/handler/tenant.go
  • internal/handler/memory.go
  • internal/handler/file.go
  • internal/handler/document.go
  • internal/handler/providers.go
  • internal/handler/user.go

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Caution

Inline review comments failed to post. This is likely due to GitHub's internal server error or limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 4

Caution

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

⚠️ Outside diff range comments (2)
internal/handler/mcp.go (1)

324-330: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Wrong error code for a server-side import failure.

HTTP status is 500 (correct for a service-layer failure), but the body code is common.CodeBadRequest. This should be common.CodeServerError to keep the status and code consistent, matching the pattern used correctly elsewhere in this file (e.g., ListMCPServers, line 120).

🔧 Proposed fix
-		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, err.Error())
+		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeServerError, nil, err.Error())
🤖 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/handler/mcp.go` around lines 324 - 330, The ImportServers error
response in mcp.go uses a server-side HTTP 500 but returns the wrong body code.
Update the error handling in the ImportServers path to use
common.CodeServerError instead of common.CodeBadRequest when
h.mcpService.ImportServers fails, matching the existing pattern used by
ListMCPServers and keeping the status/code consistent.
internal/handler/search.go (1)

155-185: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Two status/code mismatches in CreateSearch.

  1. Line 167 — binding failure (client's fault) returns HTTP 500 instead of 400. UpdateSearch (line 316) handles the identical case correctly with http.StatusBadRequest.
  2. Line 179 — a genuine service failure is reported with common.CodeBadRequest instead of common.CodeServerError, even though the HTTP status (500) is already correct.
🔧 Proposed fix
 	var req CreateSearchRequest
 	if err := c.ShouldBindJSON(&req); err != nil {
-		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
+		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeBadRequest, nil, "Invalid request body: "+err.Error())
 		return
 	}

 	if err := common.ValidateName(req.Name); err != nil {
 		common.ErrorWithCode(c, int(common.CodeDataError), err.Error())
 		return
 	}

 	// Create search (same as Python SearchService.save within DB.atomic())
 	result, err := h.searchService.CreateSearch(userID, req.Name, req.Description)
 	if err != nil {
-		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, err.Error())
+		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeServerError, nil, err.Error())
 		return
 	}
🤖 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/handler/search.go` around lines 155 - 185, In CreateSearch, align
the status/code mapping with the other handlers: the ShouldBindJSON validation
failure should return a client error using http.StatusBadRequest instead of
http.StatusInternalServerError, and the searchService.CreateSearch failure
should keep the 500 HTTP response but use common.CodeServerError rather than
common.CodeBadRequest. Update the error paths in SearchHandler.CreateSearch so
the response codes match the nature of the failure and stay consistent with
UpdateSearch and the shared response helpers.
🤖 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/handler/chunk.go`:
- Around line 583-602: The `UpdateChunk` error branch is writing the same
bad-request response twice, once via `common.ResponseWithHttpCodeData` and again
via `c.JSON`, which causes duplicate headers/body output. Remove the extra
manual `c.JSON` path in `UpdateChunk` and keep the shared helper call as the
only response writer for `common.CodeArgumentError`, `common.CodeBadRequest`,
and `common.CodeDataError` cases.
- Around line 380-384: The missing user_id validation in chunk.go is using the
wrong response code; update the userID empty-check in the handler to use the
same argument-validation code as the dataset_id and document_id checks instead
of common.CodeAuthenticationError. Keep the existing
common.ResponseWithHttpCodeData call and only swap the error code in the user ID
branch so clients see a required-field error rather than an auth error.

In `@internal/handler/mcp_server.go`:
- Around line 96-101: The error response in the MCP request handling branch uses
the wrong payload code, so update the server.HandleRequest error path in
mcp_server.go to send common.CodeServerError instead of common.CodeBadRequest
while keeping the 500 status and existing error message; this is the
server-error branch, so the body code must match that semantics for clients that
inspect the response payload.

In `@internal/handler/mcp.go`:
- Around line 285-296: In ImportMCPServers, cap the request body before reading
it by wrapping c.Request.Body with http.MaxBytesReader to match HandleMCP’s 1
MiB limit, then continue using io.ReadAll and json.Unmarshal on the bounded
body. Also update the ImportServers failure response so it uses
common.CodeServerError instead of common.CodeBadRequest when returning HTTP 500,
and keep the existing common.ResponseWithHttpCodeData flow intact.

---

Outside diff comments:
In `@internal/handler/mcp.go`:
- Around line 324-330: The ImportServers error response in mcp.go uses a
server-side HTTP 500 but returns the wrong body code. Update the error handling
in the ImportServers path to use common.CodeServerError instead of
common.CodeBadRequest when h.mcpService.ImportServers fails, matching the
existing pattern used by ListMCPServers and keeping the status/code consistent.

In `@internal/handler/search.go`:
- Around line 155-185: In CreateSearch, align the status/code mapping with the
other handlers: the ShouldBindJSON validation failure should return a client
error using http.StatusBadRequest instead of http.StatusInternalServerError, and
the searchService.CreateSearch failure should keep the 500 HTTP response but use
common.CodeServerError rather than common.CodeBadRequest. Update the error paths
in SearchHandler.CreateSearch so the response codes match the nature of the
failure and stay consistent with UpdateSearch and the shared response helpers.
🪄 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: 739e7835-e1e7-49ed-a66f-31872e52dbf0

📥 Commits

Reviewing files that changed from the base of the PR and between 19b165c and aa35f83.

📒 Files selected for processing (18)
  • internal/admin/handler.go
  • internal/handler/chat.go
  • internal/handler/chat_session.go
  • internal/handler/chunk.go
  • internal/handler/connector.go
  • internal/handler/dify_retrieval_handler.go
  • internal/handler/document.go
  • internal/handler/file.go
  • internal/handler/mcp.go
  • internal/handler/mcp_server.go
  • internal/handler/memory.go
  • internal/handler/oauth_login.go
  • internal/handler/providers.go
  • internal/handler/search.go
  • internal/handler/searchbot.go
  • internal/handler/system.go
  • internal/handler/tenant.go
  • internal/handler/user.go
🚧 Files skipped from review as they are similar to previous changes (11)
  • internal/handler/oauth_login.go
  • internal/handler/searchbot.go
  • internal/handler/system.go
  • internal/handler/dify_retrieval_handler.go
  • internal/handler/connector.go
  • internal/handler/tenant.go
  • internal/handler/memory.go
  • internal/handler/file.go
  • internal/handler/document.go
  • internal/handler/providers.go
  • internal/handler/user.go
🛑 Comments failed to post (4)
internal/handler/chunk.go (2)

380-384: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Wrong error code for a missing-user_id validation.

common.CodeAuthenticationError is used here, but this is a plain required-field validation (mirroring the dataset_id/document_id checks just below, which correctly use common.CodeArgumentError). Using the auth error code here can mislead clients that branch on error codes.

🔧 Proposed fix
-		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeAuthenticationError, nil, "user_id is required")
+		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeArgumentError, nil, "user_id is required")
📝 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.

	userID := strings.TrimSpace(user.ID)
	if userID == "" {
		common.ResponseWithHttpCodeData(c, http.StatusBadRequest, common.CodeArgumentError, nil, "user_id is required")
		return
	}
🤖 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/handler/chunk.go` around lines 380 - 384, The missing user_id
validation in chunk.go is using the wrong response code; update the userID
empty-check in the handler to use the same argument-validation code as the
dataset_id and document_id checks instead of common.CodeAuthenticationError.
Keep the existing common.ResponseWithHttpCodeData call and only swap the error
code in the user ID branch so clients see a required-field error rather than an
auth error.

583-602: 🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Duplicate response write in UpdateChunk's error branch.

common.ResponseWithHttpCodeData (line 591) already writes the JSON response, but the following c.JSON(http.StatusBadRequest, gin.H{...}) (lines 592-595) writes a second response for the same request — this is leftover manual-response code from before the migration to the shared helper. Gin will log "superfluous response.WriteHeader" and the client will receive two concatenated JSON payloads.

🐛 Proposed fix
 			case common.CodeArgumentError, common.CodeBadRequest, common.CodeDataError:
 				common.ResponseWithHttpCodeData(c, http.StatusBadRequest, coded.Code(), nil, err.Error())
-				c.JSON(http.StatusBadRequest, gin.H{
-					"code":    coded.Code(),
-					"message": err.Error(),
-				})
 				return
📝 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.

	err := h.chunkService.UpdateChunk(&req, user.ID)
	if err != nil {
		var coded interface {
			Code() common.ErrorCode
		}
		if errors.As(err, &coded) {
			switch coded.Code() {
			case common.CodeArgumentError, common.CodeBadRequest, common.CodeDataError:
				common.ResponseWithHttpCodeData(c, http.StatusBadRequest, coded.Code(), nil, err.Error())
				return
			}
		}

		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, 500, nil, err.Error())
		return
	}
🤖 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/handler/chunk.go` around lines 583 - 602, The `UpdateChunk` error
branch is writing the same bad-request response twice, once via
`common.ResponseWithHttpCodeData` and again via `c.JSON`, which causes duplicate
headers/body output. Remove the extra manual `c.JSON` path in `UpdateChunk` and
keep the shared helper call as the only response writer for
`common.CodeArgumentError`, `common.CodeBadRequest`, and `common.CodeDataError`
cases.
internal/handler/mcp_server.go (1)

96-101: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

code field doesn't match the intended server-error semantics.

HTTP status is http.StatusInternalServerError (500), but the body's error code is common.CodeBadRequest (400). Per the library context, this is meant to be the server-error branch, so the payload code should be common.CodeServerError, not CodeBadRequest. Clients that branch on the body code (rather than HTTP status) will misclassify this as a client error.

🔧 Proposed fix
-		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeBadRequest, nil, "MCP server error: "+err.Error())
+		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeServerError, nil, "MCP server error: "+err.Error())
📝 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.

	server := mcp.NewServer(connector)
	respBody, hasResponse, err := server.HandleRequest(body)
	if err != nil {
		common.ResponseWithHttpCodeData(c, http.StatusInternalServerError, common.CodeServerError, nil, "MCP server error: "+err.Error())
		return
	}
🤖 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/handler/mcp_server.go` around lines 96 - 101, The error response in
the MCP request handling branch uses the wrong payload code, so update the
server.HandleRequest error path in mcp_server.go to send common.CodeServerError
instead of common.CodeBadRequest while keeping the 500 status and existing error
message; this is the server-error branch, so the body code must match that
semantics for clients that inspect the response payload.
internal/handler/mcp.go (1)

285-296: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Locate the relevant files and inspect the surrounding code with line numbers.
git ls-files 'internal/handler/*.go' | sed -n '1,200p'
echo '--- internal/handler/mcp.go ---'
wc -l internal/handler/mcp.go
sed -n '240,360p' internal/handler/mcp.go
echo '--- internal/handler/mcp_server.go ---'
wc -l internal/handler/mcp_server.go
sed -n '1,220p' internal/handler/mcp_server.go

# Find all uses of ResponseWithHttpCodeData around the suspected mismatch.
rg -n "ResponseWithHttpCodeData\(" internal/handler/mcp.go internal/handler/mcp_server.go

Repository: infiniflow/ragflow

Length of output: 15569


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Check for any global request-size limits or middleware affecting this endpoint.
rg -n "MaxBytesReader|MaxMultipartMemory|http.MaxBytesReader|LimitReader|Request.Body|client_max_body_size|body size|RequestSize" internal cmd . -g'!**/vendor/**'

# Inspect the MCP route wiring to see what middleware applies.
rg -n "ImportMCPServers|HandleMCP|mcp/servers/import|/api/v1/mcp" internal -g'!**/vendor/**'

Repository: infiniflow/ragflow

Length of output: 11235


Bound the import body and fix the server-error code.

ImportMCPServers reads c.Request.Body without a size cap; wrap it with http.MaxBytesReader before io.ReadAll, matching HandleMCP’s 1 MiB limit. The ImportServers failure path also returns HTTP 500 with common.CodeBadRequest; use common.CodeServerError there.

🤖 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/handler/mcp.go` around lines 285 - 296, In ImportMCPServers, cap the
request body before reading it by wrapping c.Request.Body with
http.MaxBytesReader to match HandleMCP’s 1 MiB limit, then continue using
io.ReadAll and json.Unmarshal on the bounded body. Also update the ImportServers
failure response so it uses common.CodeServerError instead of
common.CodeBadRequest when returning HTTP 500, and keep the existing
common.ResponseWithHttpCodeData flow intact.

This was referenced Jul 10, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant