Skip to content

feat: implement POST /api/v1/agents/<agent_id>/upload API - #15633

Merged
yingfeng merged 8 commits into
infiniflow:mainfrom
xugangqiang:feat/go-agent-upload
Jun 4, 2026
Merged

yingfeng merged 8 commits into
infiniflow:mainfrom
xugangqiang:feat/go-agent-upload

Conversation

@xugangqiang

Copy link
Copy Markdown
Contributor

Summary

Implement the POST /api/v1/agents/<agent_id>/upload endpoint in Go, allowing file uploads associated with agent canvases.

Changes

  • Modified: internal/service/agent.go — Added CheckCanvasAccess method (owner + team-level permission semantics)
  • Modified: internal/handler/agent.go — Added UploadAgentFile handler with auth check, multipart file parsing, and delegation to FileService. Added fileUploader interface for testability.
  • Modified: internal/router/router.go — Registered POST /:agent_id/upload route
  • Modified: cmd/server_main.go — Wired fileService into AgentHandler
  • New: internal/service/agent_test.go — 4 service-level tests for CheckCanvasAccess (owner, team member, private denial, not found)
  • New: internal/handler/agent_upload_test.go — 3 handler-level tests (success with fake file service, cross-user denial, empty file rejection)

Testing

All 7 tests pass with zero mocking of the DB layer (in-memory SQLite):

=== RUN   TestCheckCanvasAccess_Owner               --- PASS
=== RUN   TestCheckCanvasAccess_NotOwner            --- PASS
=== RUN   TestCheckCanvasAccess_PrivateCanvas_Denied --- PASS
=== RUN   TestCheckCanvasAccess_NotFound            --- PASS
=== RUN   TestUploadAgentFileHandler_Success        --- PASS
=== RUN   TestUploadAgentFileHandler_NoPermission   --- PASS
=== RUN   TestUploadAgentFileHandler_NoFiles        --- PASS

Co-Authored-By: Claude Opus 4.8 [email protected]

- Add CheckCanvasAccess to AgentService with permission guard
- Add UploadAgentFile handler with auth check
- Register route
- Add service-layer tests (4 test cases)
- Add handler-layer tests (3 test cases, fake file service)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. 💞 feature Feature request, pull request that fullfill a new feature. labels Jun 4, 2026
@coderabbitai

coderabbitai Bot commented Jun 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR adds multipart file-upload support for agent canvases, including service contract updates to return canvas owner IDs, a new HTTP handler with authorization validation, handler tests covering success and error cases, and wiring/routing changes to integrate the feature.

Changes

Agent File Upload Feature

Layer / File(s) Summary
Canvas access control contract
internal/service/agent.go
CheckCanvasAccess signature updated to return canvas owner ID alongside authorization boolean, enabling downstream authorization via tenant context.
File upload handler with tests
internal/handler/agent.go, internal/handler/agent_upload_test.go
New fileUploader interface and UploadAgentFile handler implement multipart form parsing, canvas access validation, and delegation to FileService using the owner's tenant ID. Test suite covers authorization, file validation, and tenant-aware routing with stubs for DB, user/canvas setup, and fake FileService.
Routing, server wiring, and dev proxy
internal/router/router.go, cmd/server_main.go, web/vite.config.ts
Registers POST endpoint, injects FileService into AgentHandler at startup, and updates Vite proxy regex for upload path forwarding.

Sequence Diagram

sequenceDiagram
  participant Client
  participant Handler as UploadAgentFile
  participant GetUser
  participant CheckAccess as AgentService.CheckCanvasAccess
  participant FileUpload as FileService.UploadFile

  Client->>Handler: POST /api/v1/agents/:agent_id/upload (multipart)
  Handler->>GetUser: GetUser()
  alt user not found
    Handler-->>Client: error JSON
  end
  Handler->>Handler: validate agent_id param
  Handler->>CheckAccess: CheckCanvasAccess(userID, canvasID)
  CheckAccess-->>Handler: ownerID, authorized, error
  alt not authorized or error
    Handler-->>Client: operating error JSON
  end
  Handler->>Handler: parse MultipartForm()
  alt parse failed
    Handler-->>Client: argument error JSON
  end
  Handler->>Handler: validate file field exists
  alt no files
    Handler-->>Client: argument error JSON
  end
  Handler->>FileUpload: UploadFile(ownerID tenantID, "", files)
  FileUpload-->>Handler: result or error
  alt upload error
    Handler-->>Client: operating error JSON
  else success
    Handler-->>Client: success JSON + result
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • infiniflow/ragflow#15629: Modifies CheckCanvasAccess authorization signature and uses it in agent HTTP handlers registered under /api/v1/agents/:agent_id/... route group.

Suggested labels

size:L

Suggested reviewers

  • JinHai-CN
  • Haruko386
  • Hz-186
  • yingfeng

Poem

🐰 A canvas now uploads with grace,
Where agents gather files in place,
With tenant checks and owner's care,
Permissions guard each upload share,
The tests stand ready, routes run true—
Here hops CodeRabbit, just for you! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically summarizes the main change: implementing a new file upload API endpoint for agent canvases, which is the core purpose of this PR.
Description check ✅ Passed The description follows the template structure with a clear summary, detailed change list, and testing information. However, it lacks the 'Type of change' section from the template.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


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

❤️ Share

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

@xugangqiang xugangqiang added the ci Continue Integration label Jun 4, 2026
@xugangqiang
xugangqiang marked this pull request as draft June 4, 2026 06:21
@xugangqiang
xugangqiang marked this pull request as ready for review June 4, 2026 06:21

@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

🤖 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_upload_test.go`:
- Around line 101-106: The test currently ignores json.Unmarshal errors and then
casts resp["code"] which can yield a zero default, masking failures; update the
test in agent_upload_test.go to check and fail on the json.Unmarshal error
(capture the error returned), assert that resp["code"] exists and is the
expected numeric type before casting, and only then compare it against
common.CodeSuccess (use a typed comparison or convert common.CodeSuccess to
float64 for comparison); also surface resp["message"] in the failure message
when the decode or missing-field check fails.

In `@internal/handler/agent.go`:
- Around line 157-190: CheckCanvasAccess currently only returns ok and is used
to gate uploads, but UploadFile is called with user.ID which causes files to be
stored under the caller's tenant instead of the canvas owner's tenant; modify
the handler so that after CheckCanvasAccess you obtain the canvas owner/tenant
ID (either by updating CheckCanvasAccess to return the tenant ID or by loading
the canvas/agent metadata via the agentService) and pass that tenant ID to
fileService.UploadFile instead of user.ID (i.e., call UploadFile(canvasTenantID,
"", files)); also add a unit/integration test for a team-member upload that
asserts fileService.UploadFile was invoked with the canvas owner tenant ID.

In `@internal/service/agent_test.go`:
- Around line 126-141: Migrate the missing entity before exercising the
not-found branch and assert the specific not-found sentinel: add
entity.UserCanvas to the testDB.AutoMigrate call (so both &entity.User{} and
&entity.UserCanvas{} are migrated), then call svc.CheckCanvasAccess("user-1",
"non-existent") and assert the returned error equals the expected not-found
error (compare against the service/dao sentinel used in your codebase, e.g.
service.ErrCanvasNotFound or dao.ErrNotFound) rather than only checking for
non-nil.
🪄 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: 4668ec52-8afe-42cc-910b-4342602a9994

📥 Commits

Reviewing files that changed from the base of the PR and between 5db1b29 and 96c7ccc.

📒 Files selected for processing (6)
  • cmd/server_main.go
  • internal/handler/agent.go
  • internal/handler/agent_upload_test.go
  • internal/router/router.go
  • internal/service/agent.go
  • internal/service/agent_test.go

Comment on lines +101 to +106
var resp map[string]interface{}
json.Unmarshal(w.Body.Bytes(), &resp)
code, _ := resp["code"].(float64)
if code != float64(common.CodeSuccess) {
t.Fatalf("expected code 0, got %v: %v", code, resp["message"])
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fail the success test when the response is not valid JSON.

Line 102 ignores the json.Unmarshal error. If decoding fails or "code" is missing, Line 103 falls back to 0, and because common.CodeSuccess is also 0, this test can still pass without a valid success response. Check the decode error and assert the field exists before comparing.

🤖 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_test.go` around lines 101 - 106, The test
currently ignores json.Unmarshal errors and then casts resp["code"] which can
yield a zero default, masking failures; update the test in agent_upload_test.go
to check and fail on the json.Unmarshal error (capture the error returned),
assert that resp["code"] exists and is the expected numeric type before casting,
and only then compare it against common.CodeSuccess (use a typed comparison or
convert common.CodeSuccess to float64 for comparison); also surface
resp["message"] in the failure message when the decode or missing-field check
fails.

Comment thread internal/handler/agent.go Resolved
Comment thread internal/service/agent_test.go Resolved
@codecov

codecov Bot commented Jun 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (c6eee09) to head (53ddc9c).
⚠️ Report is 2 commits behind head on main.

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #15633   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

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

CheckCanvasAccess now returns the canvas owner's ID so that
when a team member uploads to a shared canvas, the file is
written into the canvas owner's file tree.

- Change CheckCanvasAccess signature: (userID, canvasID) → (ownerID, ok, error)
- Handler passes canvasOwnerID to UploadFile
- Add TeamMemberTenant test that asserts forwarded tenant ID

Co-Authored-By: Claude Opus 4.8 <[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/agent_upload_test.go (1)

59-66: ⚠️ Potential issue | 🔴 Critical | ⚡ Quick win

Fix the test double: lastTenantID is asserted but never defined/captured.

Line 228 reads svc.lastTenantID, but fakeUploadFileService (Lines 59-66) has no such field and does not persist tenantID. This is a compile break and prevents validating the tenant-owner routing behavior.

🔧 Proposed fix
 type fakeUploadFileService struct {
 	uploaded     []map[string]interface{}
 	err          error
+	lastTenantID string
 }
 
 func (f *fakeUploadFileService) UploadFile(tenantID, parentID string, files []*multipart.FileHeader) ([]map[string]interface{}, error) {
+	f.lastTenantID = tenantID
 	return f.uploaded, f.err
 }

Also applies to: 228-230

🤖 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_test.go` around lines 59 - 66, The test double
fakeUploadFileService is missing a field to capture the tenantID asserted later;
add a field lastTenantID string to the struct and assign it inside its
UploadFile method (set f.lastTenantID = tenantID) so svc.lastTenantID can be
inspected in the test; ensure the method still returns f.uploaded and f.err
after recording the tenantID.
🤖 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/agent_upload_test.go`:
- Around line 59-66: The test double fakeUploadFileService is missing a field to
capture the tenantID asserted later; add a field lastTenantID string to the
struct and assign it inside its UploadFile method (set f.lastTenantID =
tenantID) so svc.lastTenantID can be inspected in the test; ensure the method
still returns f.uploaded and f.err after recording the tenantID.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: ed5a2f82-525f-4a6b-8951-c3c66b5b15b5

📥 Commits

Reviewing files that changed from the base of the PR and between e2036e4 and 2086328.

📒 Files selected for processing (4)
  • internal/handler/agent.go
  • internal/handler/agent_upload_test.go
  • internal/service/agent.go
  • internal/service/agent_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/handler/agent.go
  • internal/service/agent_test.go

xugangqiang and others added 2 commits June 4, 2026 15:02
Previously only entity.User was migrated, so the test passed on
the wrong error (missing table) instead of the intended
record-not-found path. Adding entity.UserCanvas to AutoMigrate
ensures the query reaches the correct table and returns the
expected GORM record-not-found error.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Resolved conflicts:
- internal/handler/agent.go: kept both ListAgentVersions and UploadAgentFile handlers
- internal/service/agent.go: kept CheckCanvasAccess with (bool, error) signature
- internal/service/agent_test.go: kept upstream version (same tests)
- internal/router/router.go: kept both version list and upload routes
- web/vite.config.ts: combined agent paths in hybrid proxy regex
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 4, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 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/router/router.go`:
- Around line 370-372: Restore the missing versions endpoint by adding a route
under the existing agents group that maps GET /:agent_id/versions to the agent
handler (e.g. add agents.GET("/:agent_id/versions",
r.agentHandler.ListAgentVersions) next to agents.GET("",
r.agentHandler.ListAgents)); if ListAgentVersions handler does not exist, add or
alias an existing method on r.agentHandler that returns the agent versions so
the route matches the expected /api/v1/agents/:agent_id/versions path used by
clients and the dev proxy.
🪄 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: 065cb79b-4e24-4219-879e-6eb0b5179e14

📥 Commits

Reviewing files that changed from the base of the PR and between a7fe223 and 0fd36c8.

📒 Files selected for processing (4)
  • internal/handler/agent.go
  • internal/router/router.go
  • internal/service/agent.go
  • web/vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/service/agent.go
  • internal/handler/agent.go

Comment thread internal/router/router.go Resolved
…re, update tests

- Re-add ListAgentVersions handler lost during conflict resolution
- Change CheckCanvasAccess to return (bool, error) to match handler calls
- Add ListVersions method to AgentService
- Fix NewAgentHandler calls in tests (now requires 2 args)
- Remove duplicate sptr in agent_test.go
- Fix upload test to expect authenticated user instead of canvas owner
- Add tracking fields to fakeUploadFileService
@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:M This PR changes 30-99 lines, ignoring generated files. labels Jun 4, 2026
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels Jun 4, 2026
@yingfeng
yingfeng merged commit 23aae19 into infiniflow:main Jun 4, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants