Repository navigation
feat[Go]: port agent attachment download, chatbot + agentbot completion/info endpoints from Python - #16405
Conversation
…on/info endpoints from Python
Ports five Python agent APIs to Go under the v1 Gin router:
- GET /api/v1/agents/attachments/<attachment_id>/download
- POST /api/v1/chatbots/<dialog_id>/completions (SSE)
- GET /api/v1/chatbots/<dialog_id>/info
- POST /api/v1/agentbots/<agent_id>/completions (SSE)
- GET /api/v1/agentbots/<agent_id>/inputs
New surface
-----------
- internal/common/constants.go StatusDialogValid = "1" + tests
- internal/agent/dsl/extract.go FindBeginComponentID, ExtractPrologue, ExtractMode
- internal/handler/agent_attachment.go DownloadAttachment handler
- internal/handler/bot.go BotHandler (4 endpoints)
- internal/handler/bot_test.go 29 acceptance criteria, 26 tests
- internal/handler/auth.go BetaAuthMiddleware
- internal/handler/auth_test.go middleware stub tests
- internal/service/bot.go BotService + loadCanvas
- internal/service/bot_completion.go ChatbotCompletion + SSE envelope writers
- internal/service/bot_completion_history_test.go history round-trip tests
- internal/router/bot_routes.go RegisterChatbotRoutes + RegisterAgentbotRoutes
- internal/dao/api_token.go API4ConversationDAO.Update for turn persistence
Changes
-------
- internal/dao/chat_session.go uses common.StatusDialogValid
- internal/router/agent_routes.go /agents/attachments/:attachment_id/download
- internal/router/router.go chat/agentbot routes on apiNoAuth (no regular AuthMiddleware)
- internal/handler/agent.go AgentChatCompletions reuses WriteChatbotRunEvent (F2: unified envelope)
- internal/handler/agent_test.go envelope assertions updated
- internal/agent/dsl/extract_test.go 8 new helper tests
- cmd/server_main.go wires botService + botHandler
Behavioural parity with Python
------------------------------
- Bot routes mount on apiNoAuth (R0) — beta token OR regular JWT, NOT behind AuthMiddleware
- ChatbotCompletion seeds prologue + carries prior turns into the LLM call, persists new
turn via API4ConversationDAO.Update (F8: multi-turn parity)
- SSE envelope matches canvas_service.completion: {code, message, data:{answer,reference,...}}
- BotService.AgentbotCompletion has defence-in-depth canvas authorisation before RunAgent (H2)
- DownloadAttachment sanitises attachment_id (filepath.Base + CR/LF/quote) only, no UUID gate (F9)
- SSE error frames sanitised — internal errors never leak to client (M2)
- DSL helpers share navigateToComponent addressing rule (F3, F5)
Verified: go vet ./... + go build ./... + go test ./internal/{handler,service,agent/dsl,common,dao}/ = 1199 passed in 5 packages.
Co-Authored-By: Claude <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (4)
🚧 Files skipped from review as they are similar to previous changes (4)
📝 WalkthroughWalkthroughThe PR adds shared dialog-status constants, Begin-component DSL extraction, bot service and SSE completion logic, new chatbot/agentbot HTTP routes with beta auth, and an attachment download endpoint. ChangesBot API feature
Sequence Diagram(s)sequenceDiagram
participant Client
participant Router
participant AuthHandler
participant BotHandler
participant BotService
participant API4ConversationDAO
participant LLMService
Client->>Router: POST /api/v1/chatbots/{dialog_id}/completions
Router->>AuthHandler: BetaAuthMiddleware()
AuthHandler->>BotHandler: set user in context
BotHandler->>BotService: ChatbotCompletion(...)
BotService->>API4ConversationDAO: load and save conversation
BotService->>LLMService: ChatWithMessages(...)
BotService-->>BotHandler: ChatbotSSEFrame stream
BotHandler-->>Client: data: ... / [DONE]
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
The /run endpoint was emitting the legacy per-run envelope
{event, message_id, created_at, task_id, session_id, data} via
writeRunEventSSE + sseEnvelope. Migrate it to
service.WriteChatbotRunEvent so the entire SSE surface uses one
shape, matching /api/v1/agents/chat/completions and
/api/v1/agentbots/<id>/completions.
Deletes writeRunEventSSE and sseEnvelope — no remaining callers.
The code base now has exactly one SSE writer (service.WriteChatbotRunEvent)
and exactly one frame format (the python canvas_service.completion
envelope).
Co-Authored-By: Claude <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (1)
internal/handler/agent_attachment.go (1)
77-98: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winValidate unservable IDs before the storage call.
Line 81 sends
attachmentIDtoDownloadAgentFileeven when Lines 94-98 will later reject it for header safety. Move the same validation before the file-service I/O so control characters/quotes never cross the service boundary.Proposed refactor
ext := c.DefaultQuery("ext", "markdown") + + // Sanitize the attachment_id before using it in either downstream + // services or Content-Disposition. + safe := filepath.Base(attachmentID) + if safe == "" || safe == "." || safe == "/" || strings.ContainsAny(safe, "\r\n\"") { + jsonError(c, common.CodeArgumentError, "invalid attachment id.") + return + } // IDOR note: the Go User struct collapses user/tenant into one // identifier (same model as the python download_agent_file @@ - // Sanitize the attachment_id before echoing it in - // Content-Disposition (header-injection defence). The Go - // net/http layer rejects CR/LF in header values, but we sanitize - // at the source so we don't rely on the implicit defense. - safe := filepath.Base(attachmentID) - if safe == "" || safe == "." || safe == "/" || strings.ContainsAny(safe, "\r\n\"") { - jsonError(c, common.CodeArgumentError, "invalid attachment id.") - 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_attachment.go` around lines 77 - 98, Validate the attachment ID before calling h.fileService.DownloadAgentFile in agent attachment handling. The current flow in the agent attachment handler still sends attachmentID to storage and only later rejects unsafe values, so move the same filepath.Base plus control-character/quote checks ahead of the file-service call. Keep the existing jsonError responses and ensure the validation in the agent attachment path matches the header-safety checks currently used before building the Content-Disposition value.
🤖 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/agent_attachment.go`:
- Line 70: The response MIME type construction in the attachment handler is
using the raw ext query value, which can produce malformed types for blank or
dotted inputs. Update the logic around c.DefaultQuery and the MIME-building code
in the attachment response path to normalize ext by trimming whitespace,
removing any leading dot, and falling back to markdown when the value is empty.
Keep the existing markdown default behavior intact and ensure the normalized ext
is used consistently wherever the response type is built.
In `@internal/handler/auth_test.go`:
- Around line 51-57: The auth test currently only checks that jsonError returns
a non-empty body, so it does not actually verify the unauthorized response
contract. Update the assertion in auth_test.go to decode the response body from
the handler path that uses jsonError and compare the JSON envelope’s code field
against common.CodeUnauthorized, using the existing test setup around rec to
validate the actual payload instead of _ = common.CodeUnauthorized.
In `@internal/handler/bot.go`:
- Around line 162-184: The SSE handling in bot.go is treating the terminator
event like a normal message, which emits an extra empty answer frame and can
hide the actual done signal. Update the event loop in the bot handler so
message_end and done are handled as terminators rather than passed through to
WriteAgentbotFrame/WriteChatbotFrame, while regular message events still write
the assistant payload. Keep the termination path in the same switch around
ev.Type and ensure WriteDoneFrame is always sent once for the terminal event.
- Around line 147-148: The JSON bind check in the completion handlers is too
strict because it only runs when ContentLength is greater than zero, which skips
valid chunked requests with a nonpositive length. Update the request-body guard
in both completion handler paths in bot.go so JSON binding happens whenever the
request has a body length other than zero, and make sure the same fix is applied
in both handler functions that bind session_id/question payloads.
In `@internal/service/bot.go`:
- Around line 148-149: The Agentbot canvas invocation is dropping the bound
request inputs because Bot.Completion only forwards req.UserInput to
agentService.RunAgent. Update the call in Bot.Completion so it preserves the
request’s question and files data from AgentbotCompletionRequest, likely by
composing the agent input from those fields instead of using only req.UserInput.
Verify the RunAgent call path still receives the full payload needed by the
canvas.
---
Nitpick comments:
In `@internal/handler/agent_attachment.go`:
- Around line 77-98: Validate the attachment ID before calling
h.fileService.DownloadAgentFile in agent attachment handling. The current flow
in the agent attachment handler still sends attachmentID to storage and only
later rejects unsafe values, so move the same filepath.Base plus
control-character/quote checks ahead of the file-service call. Keep the existing
jsonError responses and ensure the validation in the agent attachment path
matches the header-safety checks currently used before building the
Content-Disposition value.
🪄 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: 83a228cc-9157-47a3-9c73-09d592bf9726
📒 Files selected for processing (20)
cmd/server_main.gointernal/agent/dsl/extract.gointernal/agent/dsl/extract_test.gointernal/common/constants.gointernal/common/constants_test.gointernal/dao/api_token.gointernal/dao/chat_session.gointernal/handler/agent.gointernal/handler/agent_attachment.gointernal/handler/agent_test.gointernal/handler/auth.gointernal/handler/auth_test.gointernal/handler/bot.gointernal/handler/bot_test.gointernal/router/agent_routes.gointernal/router/bot_routes.gointernal/router/router.gointernal/service/bot.gointernal/service/bot_completion.gointernal/service/bot_completion_history_test.go
Five CodeRabbit findings addressed:
1. agent_attachment.go: sanitize attachment_id BEFORE the file-service
call so unsafe ids never cross the service boundary. Also normalise
the `ext` query (trim, lowercase, strip leading dot, fallback to
markdown on empty) — ?ext= / ?ext=.pdf would otherwise produce
`application/` or `application/.pdf`.
2. auth_test.go: decode the JSON envelope and assert the code field
matches common.CodeUnauthorized, instead of only checking for a
non-empty body. Uses common.ErrorCode for the struct field type.
3. bot.go (both AgentbotCompletion and ChatbotCompletion): change the
request-body guard from `ContentLength > 0` to `ContentLength != 0`
so chunked requests with ContentLength == -1 still bind their JSON
body. The old `> 0` guard silently dropped those payloads.
4. bot.go AgentbotCompletion: treat `message_end` and `done` as
terminators rather than passing them through as a normal message
frame. The previous code emitted an extra empty `answer` frame on
`message_end` and dropped `done` events entirely. New behaviour:
forward non-empty `Data` on terminator events as a final answer
frame, then emit exactly one WriteDoneFrame and return.
5. service/bot.go AgentbotCompletion: compose the canvas user input
from `req.UserInput` (the `inputs` dict) plus top-level `question`
and `files`. The previous code dropped question/files, so a body
like `{"question":"hi"}` reached the canvas with empty inputs.
Co-Authored-By: Claude <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16405 +/- ##
==========================================
- Coverage 94.56% 93.16% -1.40%
==========================================
Files 10 10
Lines 717 717
Branches 118 118
==========================================
- Hits 678 668 -10
- Misses 25 29 +4
- Partials 14 20 +6 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…on/info endpoints from Python (#16405) ## Summary Ports five Python agent APIs to Go under the v1 Gin router: - `GET /api/v1/agents/attachments/<attachment_id>/download` - `POST /api/v1/chatbots/<dialog_id>/completions` (SSE) - `GET /api/v1/chatbots/<dialog_id>/info` - `POST /api/v1/agentbots/<agent_id>/completions` (SSE) - `GET /api/v1/agentbots/<agent_id>/inputs` Mirrors the existing Python wire shape (`{code, message, data:{answer,reference,...}}` per Python `canvas_service.completion`) so the iframe SDK and existing JS widgets keep working. ## Behavioural parity with Python | # | Concern | How it's met | |---|---------|--------------| | R0 | Bot routes must not require regular user session | Routes mount on `apiNoAuth` (router.go:198-202), with `BetaAuthMiddleware` only | | R3 | Two SSE formats in Go drift | F2: `AgentChatCompletions` and `AgentbotCompletion` share `service.WriteChatbotRunEvent` | | R7 | `GetBySessionID` returns `(nil, nil)` on miss | Defensive nil-check before `session.UserID != tenantID` | | R8 | Begin component name vs ID | `FindBeginComponentID` resolves name → ID first, then `ExtractComponentInputForm(dsl, beginID)` | | R9 | Defensive PromptConfig parsing | `stringFromMap` helper used for `prologue` and `tavily_api_key` | | R10 | `BetaAuthMiddleware` Bearer-prefix pre-filter | Removed — `GetUserByToken` is called unconditionally, falls back to `GetUserByBetaAPIToken` | | F8 | Multi-turn chatbot history | `ChatbotCompletion` reads prior turns from `session.Message`, appends user turn, calls LLM, persists new pair via new `API4ConversationDAO.Update` | | F9 | UUID gate stricter than plan | Removed — only `filepath.Base` + CR/LF/quote header sanitization remains | | H2 | Defence-in-depth IDOR | `AgentbotCompletion` calls `loadCanvas` before delegating to `RunAgent` | | M2 | SSE error leakage | `WriteChatbotFrame` emits generic `"an internal error occurred"`; real error logged via `common.Error` | ## Verification ```bash $ go vet ./... # clean (only pre-existing issues) $ go build ./... # success $ go test ./internal/handler/ ./internal/service/ ./internal/agent/dsl/ ./internal/common/ ./internal/dao/ ok ragflow/internal/handler 0.617s ok ragflow/internal/service 1.729s ok ragflow/internal/agent/dsl 0.008s ok ragflow/internal/common 0.087s ok ragflow/internal/dao 0.083s ``` 1199 tests pass across 5 packages. ## Known follow-ups (out of scope for this PR) - **F1**: token-level streaming in `ChatbotCompletion` (currently emits one frame per turn) - **F3**: per-route `auth_types` attribute in Go (currently applied via route group middleware) --------- Co-authored-by: Claude <[email protected]>
…sion/user + input/output to Langfuse for agent runs Rebuilt on current upstream/main after force-push; cherry-pick of the 7 PR-original commits collapsed into a single net diff to avoid conflicts with intervening commits pulled in by repeated merges of upstream/main. Original PR work (commits dropped during rebuild because their content already lives on upstream/main or was a merge of upstream/main): c7339ae Enhance LLMService with token usage reporting 0266cf0 Implement token usage tracking and Langfuse integration ab2b267 Include session_id in run_kwargs 8bf937c Implement token usage tracking in chat model c955988 Enhance token tracking with context variables and functions 3e88ed5 fix(agent): address CodeRabbit review on token usage tracking 74b8c8c fix(agent): address CodeRabbit follow-up review Forced-upstream duplicates dropped (already merged to main): 70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405), 730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410), c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436), ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609), 2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985), bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426), 4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145) Plus 18 'Merge branch main into main' commits dropped (polluted topology).
…sion/user + input/output to Langfuse for agent runs Rebuilt on current upstream/main after force-push; cherry-pick of the 7 PR-original commits collapsed into a single net diff to avoid conflicts with intervening commits pulled in by repeated merges of upstream/main. Original PR work (commits dropped during rebuild because their content already lives on upstream/main or was a merge of upstream/main): c7339ae Enhance LLMService with token usage reporting 0266cf0 Implement token usage tracking and Langfuse integration ab2b267 Include session_id in run_kwargs 8bf937c Implement token usage tracking in chat model c955988 Enhance token tracking with context variables and functions 3e88ed5 fix(agent): address CodeRabbit review on token usage tracking 74b8c8c fix(agent): address CodeRabbit follow-up review Forced-upstream duplicates dropped (already merged to main): 70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405), 730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410), c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436), ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609), 2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985), bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426), 4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145) Plus 18 'Merge branch main into main' commits dropped (polluted topology). Co-authored-by: yzc <[email protected]>
Summary
Ports five Python agent APIs to Go under the v1 Gin router:
GET /api/v1/agents/attachments/<attachment_id>/downloadPOST /api/v1/chatbots/<dialog_id>/completions(SSE)GET /api/v1/chatbots/<dialog_id>/infoPOST /api/v1/agentbots/<agent_id>/completions(SSE)GET /api/v1/agentbots/<agent_id>/inputsMirrors the existing Python wire shape (
{code, message, data:{answer,reference,...}}per Pythoncanvas_service.completion) so the iframe SDK and existing JS widgets keep working.Behavioural parity with Python
apiNoAuth(router.go:198-202), withBetaAuthMiddlewareonlyAgentChatCompletionsandAgentbotCompletionshareservice.WriteChatbotRunEventGetBySessionIDreturns(nil, nil)on misssession.UserID != tenantIDFindBeginComponentIDresolves name → ID first, thenExtractComponentInputForm(dsl, beginID)stringFromMaphelper used forprologueandtavily_api_keyBetaAuthMiddlewareBearer-prefix pre-filterGetUserByTokenis called unconditionally, falls back toGetUserByBetaAPITokenChatbotCompletionreads prior turns fromsession.Message, appends user turn, calls LLM, persists new pair via newAPI4ConversationDAO.Updatefilepath.Base+ CR/LF/quote header sanitization remainsAgentbotCompletioncallsloadCanvasbefore delegating toRunAgentWriteChatbotFrameemits generic"an internal error occurred"; real error logged viacommon.ErrorVerification
1199 tests pass across 5 packages.
Known follow-ups (out of scope for this PR)
ChatbotCompletion(currently emits one frame per turn)auth_typesattribute in Go (currently applied via route group middleware)