Repository navigation
feat[Go]: port agent webhook trigger, agent file upload/download, component input-form + debug endpoints from Python - #16403
Conversation
…ponent input-form + debug endpoints from Python
|
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 (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughThe PR adds agent upload, download, component inspection/debug, and webhook endpoints; wires webhook payload state through the agent runtime; adds DSL extraction, webhook security/schema helpers, and a strict Redis token-bucket evaluator; and updates route registration and compatibility notes. ChangesAgent API and webhook stack
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (5)
go.mod (1)
120-120: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winMark
github.com/golang-jwt/jwt/v5as a direct dependency
internal/handler/agent_webhook_security.goimports this package, sogo.mod:120should drop// indirect.Proposed fix
- github.com/golang-jwt/jwt/v5 v5.3.0 // indirect + github.com/golang-jwt/jwt/v5 v5.3.0🤖 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 `@go.mod` at line 120, Mark github.com/golang-jwt/jwt/v5 as a direct dependency in go.mod by removing the // indirect annotation, since internal/handler/agent_webhook_security.go imports it directly. Update the dependency entry for jwt/v5 so it is recorded as an explicit requirement rather than an indirect one.internal/handler/agent_webhook_schema_test.go (1)
227-241: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert the returned defaults here.
This test currently only checks that
defaultForTypedoes not panic, so a broken default table would still pass. Please verify the concrete outputs for each case.🤖 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_schema_test.go` around lines 227 - 241, The TestDefaultForType coverage is too weak because it only checks that defaultForType does not panic, so incorrect defaults can slip through. Update TestDefaultForType to assert the concrete value returned for each case in the cases table, using defaultForType as the target and verifying each expected zero value explicitly.internal/handler/agent_webhook.go (1)
367-385: 🔒 Security & Privacy | 🔵 Trivial | ⚡ Quick winPropagate body-read errors out of
parseWebhookRequest.
io.ReadAll/ParseFormfailures are discarded here, so an oversized request can still fall through with an empty or partial body instead of failing the configuredmax_body_sizecheck.Proposed fix
switch ctype { case "application/json": - raw, _ := io.ReadAll(c.Request.Body) + raw, err := io.ReadAll(c.Request.Body) + if err != nil { + return nil, err + } if len(raw) > 0 { _ = json.Unmarshal(raw, &body) } case "application/x-www-form-urlencoded": - if err := c.Request.ParseForm(); err == nil { - for k, vals := range c.Request.PostForm { - if len(vals) == 1 { - body[k] = vals[0] - } else { - body[k] = vals - } + if err := c.Request.ParseForm(); err != nil { + return nil, err + } + for k, vals := range c.Request.PostForm { + if len(vals) == 1 { + body[k] = vals[0] + } else { + body[k] = vals } } default: - raw, _ := io.ReadAll(c.Request.Body) + raw, err := io.ReadAll(c.Request.Body) + if err != nil { + return nil, err + } if len(raw) > 0 { _ = json.Unmarshal(raw, &body) } }🤖 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 367 - 385, Propagate body parsing failures from parseWebhookRequest instead of ignoring them: the io.ReadAll and c.Request.ParseForm calls in the webhook body parsing branch should return errors to the caller so oversized or unreadable requests fail fast rather than continuing with empty/partial body data. Update parseWebhookRequest to capture and return these errors, and ensure the existing max_body_size handling in agent_webhook.go can rely on those failures.internal/handler/agent_webhook_test.go (1)
45-59: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winPopulate
canvas_idin the Gin context and assert it reaches the loader.These tests invoke the handler directly, so
c.Param("canvas_id")stays empty unlessc.Paramsis set. Because the fake loader also ignores its inputs, this suite will not catch a broken route-param contract.Proposed fix
type fakeCanvasLoader struct { canvas *entity.UserCanvas err error events []canvas.RunEvent + gotUserID string + gotCanvasID string } -func (f *fakeCanvasLoader) LoadCanvasByID(_ context.Context, _, _ string) (*entity.UserCanvas, error) { +func (f *fakeCanvasLoader) LoadCanvasByID(_ context.Context, userID, canvasID string) (*entity.UserCanvas, error) { + f.gotUserID = userID + f.gotCanvasID = canvasID if f.err != nil { return nil, f.err } return f.canvas, nil } -func webhookCtx(method, path, body, contentType string) (*gin.Context, *httptest.ResponseRecorder) { +func webhookCtx(method, path, canvasID, body, contentType string) (*gin.Context, *httptest.ResponseRecorder) { gin.SetMode(gin.TestMode) w := httptest.NewRecorder() c, _ := gin.CreateTestContext(w) @@ c.Request = httptest.NewRequest(method, path, reader) + c.Params = gin.Params{{Key: "canvas_id", Value: canvasID}} if contentType != "" { c.Request.Header.Set("Content-Type", contentType) } c.Set("user", &entity.User{ID: "u-1"}) return c, w }Also applies to: 90-105
🤖 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_test.go` around lines 45 - 59, The webhook handler tests are not exercising the route parameter contract because the Gin context never gets a canvas_id, and fakeCanvasLoader ignores the received values. Update the tests around fakeCanvasLoader and the handler invocation to populate c.Params with canvas_id before calling the handler, then make the fake loader capture its inputs so you can assert LoadCanvasByID and RunAgentWithWebhook receive the expected canvas_id. This will ensure the direct handler tests fail if the route param is missing or not forwarded correctly.internal/handler/agent_component_test.go (1)
213-291: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a malformed nested-param regression.
The suite checks missing top-level
params, but not{"params":{"query":{}}}ornull. That is the branch the flattening loop currently mishandles, so it needs a dedicated test.🤖 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_test.go` around lines 213 - 291, Add a regression test in TestDebugComponent for malformed nested params, especially when DebugComponent receives {"params":{"query":{}}} or a null nested value, since the flattening path currently misses this case. Extend the existing test block around componentCtx and AgentHandler.DebugComponent to assert the proper argument-error response and message for these nested-param shapes.
🤖 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/agent/dsl/extract.go`:
- Around line 47-54: In extract.go, treat any present-but-wrongly-typed DSL
fields as malformed rather than missing or empty: in extract() and the related
params handling at the referenced block, validate the concrete types for
comp["obj"], obj["input_form"], and the params map separately, and return
ErrMalformedDSL for type mismatches while reserving ErrMissingInputForm only for
true absence. Update the extraction logic so DebugComponent cannot proceed with
corrupt DSL data and the sentinel errors in internal/agent/dsl/errors.go stay
consistent.
In `@internal/handler/agent_component.go`:
- Around line 132-138: The params-to-inputs mapping in agent_component.go
currently allows entries like body.Params[k] without a value to slip through as
nil, which then still calls the component. Update the input-building logic in
the handler path that iterates over body.Params so it validates each entry has a
non-nil value field before populating inputs; if a param omits value, fail fast
with an error instead of continuing. Use the existing body.Params loop and
inputs map construction in the handler to locate the fix.
In `@internal/handler/agent_webhook_security.go`:
- Around line 275-280: Empty configured auth secrets are currently accepted in
the token/basic auth checks, which can let unauthenticated requests through;
update the auth validation in the webhook security flow to reject missing or
blank configured credentials before comparing request headers. In the token path
around the token header/value handling and in the basic auth path around the
basic credential check, add explicit checks that the configured secret values
are non-empty and return an auth error if they are not, so a request cannot
authenticate against an empty expected secret.
- Around line 132-149: The max_body_size parsing in validateMaxBodySize can
overflow before the 10MB cap check, so validate the parsed numeric value against
the maximum allowed size before doing any kb/mb multiplication. Update the
sizeStr switch in internal/handler/agent_webhook_security.go so the limit is
bounded using the raw parsed number first, then multiply only after confirming
it cannot exceed webhookBodyMaxBytes, keeping the existing invalid format
handling intact.
---
Nitpick comments:
In `@go.mod`:
- Line 120: Mark github.com/golang-jwt/jwt/v5 as a direct dependency in go.mod
by removing the // indirect annotation, since
internal/handler/agent_webhook_security.go imports it directly. Update the
dependency entry for jwt/v5 so it is recorded as an explicit requirement rather
than an indirect one.
In `@internal/handler/agent_component_test.go`:
- Around line 213-291: Add a regression test in TestDebugComponent for malformed
nested params, especially when DebugComponent receives {"params":{"query":{}}}
or a null nested value, since the flattening path currently misses this case.
Extend the existing test block around componentCtx and
AgentHandler.DebugComponent to assert the proper argument-error response and
message for these nested-param shapes.
In `@internal/handler/agent_webhook_schema_test.go`:
- Around line 227-241: The TestDefaultForType coverage is too weak because it
only checks that defaultForType does not panic, so incorrect defaults can slip
through. Update TestDefaultForType to assert the concrete value returned for
each case in the cases table, using defaultForType as the target and verifying
each expected zero value explicitly.
In `@internal/handler/agent_webhook_test.go`:
- Around line 45-59: The webhook handler tests are not exercising the route
parameter contract because the Gin context never gets a canvas_id, and
fakeCanvasLoader ignores the received values. Update the tests around
fakeCanvasLoader and the handler invocation to populate c.Params with canvas_id
before calling the handler, then make the fake loader capture its inputs so you
can assert LoadCanvasByID and RunAgentWithWebhook receive the expected
canvas_id. This will ensure the direct handler tests fail if the route param is
missing or not forwarded correctly.
In `@internal/handler/agent_webhook.go`:
- Around line 367-385: Propagate body parsing failures from parseWebhookRequest
instead of ignoring them: the io.ReadAll and c.Request.ParseForm calls in the
webhook body parsing branch should return errors to the caller so oversized or
unreadable requests fail fast rather than continuing with empty/partial body
data. Update parseWebhookRequest to capture and return these errors, and ensure
the existing max_body_size handling in agent_webhook.go can rely on those
failures.
🪄 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: e7160cfa-9d09-4884-99ae-8815f950aede
⛔ Files ignored due to path filters (1)
go.sumis excluded by!**/*.sum
📒 Files selected for processing (25)
api/apps/backward_compat.pyapi/apps/restful_apis/agent_api.pygo.modinternal/agent/component/begin.gointernal/agent/component/begin_test.gointernal/agent/dsl/errors.gointernal/agent/dsl/extract.gointernal/agent/dsl/extract_test.gointernal/engine/redis/redis.gointernal/engine/redis/redis_test.gointernal/handler/agent.gointernal/handler/agent_component.gointernal/handler/agent_component_test.gointernal/handler/agent_download.gointernal/handler/agent_download_test.gointernal/handler/agent_upload.gointernal/handler/agent_upload_test.gointernal/handler/agent_webhook.gointernal/handler/agent_webhook_schema.gointernal/handler/agent_webhook_schema_test.gointernal/handler/agent_webhook_security.gointernal/handler/agent_webhook_security_test.gointernal/handler/agent_webhook_test.gointernal/router/agent_routes.gointernal/service/agent.go
CodeRabbit review comments (infiniflow#16403): 1. [Major] extract.go: treat wrong field types as malformed DSL. Presence + wrong type (e.g. input_form is a list) used to collapse into ErrMissingInputForm. Now ErrMalformedDSL is returned for type mismatches, ErrMissingInputForm only for true absence. Same for params. 2. [Minor] DebugComponent: params.*.value must be present. A param entry like {"q":{}} used to slip through as nil and still invoke the component. Now fails fast with 101. 3. [Major] webhook security: cap-check before multiplication. A huge configured n (e.g. 999999999mb) would overflow n*bytesPerMB and wrap to a small positive number, bypassing the 10MB cap. Now bounded against the cap before multiplying. 4. [Major] webhook security: reject empty configured auth secrets. Empty token_value used to mean "accept any request without that header". Empty basic username/password likewise. Both now rejected as misconfigured. User instruction: change kb/mb units from 1024-base (Python parity) to 1000-base (SI decimal). - bytesPerKB = 1 000, bytesPerMB = 1 000 000 - webhookBodyMaxBytes = 10 * bytesPerMB = 10 000 000 bytes - This DIVERGES from python agent_api.py:1643 (uses 1 KB = 1 024 B). Documented in code comments + TestParseMaxBodySize_ DecimalUnits. Tests: +5 new (input_form wrong-type, params wrong-type, missing value, overflow guard, decimal units, empty token value). 1444 tests passing (was 1439), vet clean on touched code. See PR: infiniflow#16403
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@internal/handler/agent_webhook_security_test.go`:
- Around line 320-330: The TestValidateMaxBodySize_OverflowGuard test in
agent_webhook_security_test.go is not hitting the pre-multiplication overflow
path because the current max_body_size value still fits in int64. Update this
test to use a value large enough to overflow n*bytesPerMB before the cap check
in validateMaxBodySize, so it truly verifies the overflow guard and fails if the
implementation only checks the 10 MB limit after multiplication.
🪄 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: 863a1923-e6ed-438b-bff7-a96a269f2f44
📒 Files selected for processing (6)
internal/agent/dsl/extract.gointernal/agent/dsl/extract_test.gointernal/handler/agent_component.gointernal/handler/agent_component_test.gointernal/handler/agent_webhook_security.gointernal/handler/agent_webhook_security_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
- internal/agent/dsl/extract.go
- internal/handler/agent_component_test.go
- internal/agent/dsl/extract_test.go
- internal/handler/agent_component.go
- internal/handler/agent_webhook_security.go
…wGuard CodeRabbit PR review infiniflow#5: 999999999mb (= ~1e15 bytes) still fits in int64, so the old value did not actually exercise the pre- multiplication overflow guard. Replaced with 9223372036855mb which when multiplied by bytesPerMB (1 000 000) would overflow int64 max — the test now actually verifies the guard.
…ponent input-form + debug endpoints from Python (#16403) port agent webhook trigger, agent file upload/download, component input-form + debug endpoints from Python - [x] New Feature (non-breaking change which adds functionality)
…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]>
port agent webhook trigger, agent file upload/download, component input-form + debug endpoints from Python