Repository navigation
feat: implement POST /api/v1/agents/<agent_id>/upload API - #15633
Conversation
- 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]>
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis 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. ChangesAgent File Upload Feature
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ 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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (6)
cmd/server_main.gointernal/handler/agent.gointernal/handler/agent_upload_test.gointernal/router/router.gointernal/service/agent.gointernal/service/agent_test.go
| 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"]) | ||
| } |
There was a problem hiding this comment.
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.
Codecov Report✅ All modified and coverable lines are covered by tests. 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. 🚀 New features to boost your workflow:
|
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]>
There was a problem hiding this comment.
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 winFix the test double:
lastTenantIDis asserted but never defined/captured.Line 228 reads
svc.lastTenantID, butfakeUploadFileService(Lines 59-66) has no such field and does not persisttenantID. 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
📒 Files selected for processing (4)
internal/handler/agent.gointernal/handler/agent_upload_test.gointernal/service/agent.gointernal/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
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
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/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
📒 Files selected for processing (4)
internal/handler/agent.gointernal/router/router.gointernal/service/agent.goweb/vite.config.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- internal/service/agent.go
- internal/handler/agent.go
…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
Summary
Implement the
POST /api/v1/agents/<agent_id>/uploadendpoint in Go, allowing file uploads associated with agent canvases.Changes
internal/service/agent.go— AddedCheckCanvasAccessmethod (owner + team-level permission semantics)internal/handler/agent.go— AddedUploadAgentFilehandler with auth check, multipart file parsing, and delegation toFileService. AddedfileUploaderinterface for testability.internal/router/router.go— RegisteredPOST /:agent_id/uploadroutecmd/server_main.go— WiredfileServiceintoAgentHandlerinternal/service/agent_test.go— 4 service-level tests forCheckCanvasAccess(owner, team member, private denial, not found)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):
Co-Authored-By: Claude Opus 4.8 [email protected]