Skip to content

RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.

refa: derive service identity from context (#21904)

buua436ff985091fb0b
diff --git a/internal/handler/agent.go b/internal/handler/agent.go
index 3da9e2eefd..04fc5ccba0 100644
--- a/internal/handler/agent.go
+++ b/internal/handler/agent.go
@@ -69,7 +69,7 @@ type agentFileService interface {
// NewAgentHandler assigns the concrete *service.AgentService — which
// satisfies this interface because its RunAgent signature matches.
type chatAgentService interface {
- RunAgent(ctx context.Context, userID, canvasID, sessionID, version string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error)
+ RunAgent(ctx context.Context, canvasID, sessionID, version string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error)
}
// AgentHandler agent handler
@@ -166,17 +166,12 @@ func (h *AgentHandler) WithNewExecutor(f func(taskCtx *task.TaskContext, canvasI
// @Success 200 {object} service.ListAgentsResponse
// @Router /api/v1/agents [get]
func (h *AgentHandler) ListAgents(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
// Filter-aggregation mode: the agents page filter bar fetches
// GET /api/v1/agents?type=filter and expects
// {filter: {owner, canvas_category}, total} instead of a canvas list.
if c.Query("type") == "filter" {
- filters, code, err := h.agentService.ListAgentFilters(c.Request.Context(), user.ID, strings.TrimSpace(c.Query("canvas_category")))
+ filters, code, err := h.agentService.ListAgentFilters(c.Request.Context(), strings.TrimSpace(c.Query("canvas_category")))
if err != nil {
common.RespondError(c, code, err.Error())
return
@@ -233,7 +228,6 @@ func (h *AgentHandler) ListAgents(c *gin.Context) {
result, code, err := h.agentService.ListAgents(
ctx,
- user.ID,
keywords,
page,
pageSize,
@@ -306,7 +300,7 @@ func (h *AgentHandler) CreateAgent(c *gin.Context) {
common.RespondError(c, common.CodeArgumentError, "Invalid request: "+err.Error())
return
}
- row, code, err := h.agentService.CreateAgent(c.Request.Context(), user.ID, &req)
+ row, code, err := h.agentService.CreateAgent(c.Request.Context(), &req)
if err != nil {
common.RespondError(c, code, err.Error())
return
@@ -322,13 +316,8 @@ func (h *AgentHandler) CreateAgent(c *gin.Context) {
// @Success 200 {object} agentDetailResponse
// @Router /api/v1/agents/{canvas_id} [get]
func (h *AgentHandler) GetAgent(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
- row, err := h.agentService.GetAgent(c.Request.Context(), user.ID, canvasID)
+ row, err := h.agentService.GetAgent(c.Request.Context(), canvasID)
if err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
@@ -383,11 +372,6 @@ func decodeJSONWithNumber(body io.Reader, target any) error {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/agents/{canvas_id} [put]
func (h *AgentHandler) UpdateAgent(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
var req map[string]interface{}
if err := decodeJSONWithNumber(c.Request.Body, &req); err != nil && !errors.Is(err, io.EOF) {
@@ -397,12 +381,12 @@ func (h *AgentHandler) UpdateAgent(c *gin.Context) {
if req == nil {
req = map[string]interface{}{}
}
- if err := h.agentService.UpdateAgent(c.Request.Context(), user.ID, canvasID, req); err != nil {
+ if err := h.agentService.UpdateAgent(c.Request.Context(), canvasID, req); err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
return
}
- canvasInstance, err := h.agentService.GetAgent(c.Request.Context(), user.ID, canvasID)
+ canvasInstance, err := h.agentService.GetAgent(c.Request.Context(), canvasID)
if err != nil || canvasInstance == nil {
common.RespondSuccess(c, map[string]interface{}{}, "success")
return
@@ -420,13 +404,8 @@ func (h *AgentHandler) UpdateAgent(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/agents/{canvas_id} [delete]
func (h *AgentHandler) DeleteAgent(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
- if err := h.agentService.DeleteAgent(c.Request.Context(), user.ID, canvasID); err != nil {
+ if err := h.agentService.DeleteAgent(c.Request.Context(), canvasID); err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
return
@@ -443,10 +422,6 @@ func (h *AgentHandler) DeleteAgent(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/agents/templates [get]
func (h *AgentHandler) ListTemplates(c *gin.Context) {
- if _, errorCode, errorMessage := GetUser(c); errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
ctx := c.Request.Context()
templates, err := h.agentService.ListTemplates(ctx)
if err != nil {
@@ -472,11 +447,6 @@ func (h *AgentHandler) ListTemplates(c *gin.Context) {
// @Success 200 {string} string "SSE: data: {...}\\n\\n"
// @Router /api/v1/agents/{canvas_id}/run [post]
func (h *AgentHandler) RunAgent(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
version := c.Query("version")
sessionID := c.Query("session_id")
@@ -494,7 +464,7 @@ func (h *AgentHandler) RunAgent(c *gin.Context) {
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
- events, err := h.chatRunner.RunAgent(ctx, user.ID, canvasID, sessionID, version, userInput, nil)
+ events, err := h.chatRunner.RunAgent(ctx, canvasID, sessionID, version, userInput, nil)
if err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
@@ -674,16 +644,11 @@ func (h *AgentHandler) extractChatDebugFile(ctx context.Context, files []map[str
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/tasks/{session_id}/cancel [post]
func (h *AgentHandler) CancelSessionRun(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
if h.agentService == nil {
common.RespondError(c, common.CodeServerError, "agent service unavailable")
return
}
- if err := h.agentService.CancelSessionRun(c.Request.Context(), user.ID, c.Param("session_id")); err != nil {
+ if err := h.agentService.CancelSessionRun(c.Request.Context(), c.Param("session_id")); err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
return
@@ -709,18 +674,13 @@ type publishAgentRequest struct {
// @Success 200 {object} entity.UserCanvasVersion
// @Router /api/v1/agents/{canvas_id}/publish [post]
func (h *AgentHandler) PublishAgent(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
var req publishAgentRequest
if err := decodeJSONWithNumber(c.Request.Body, &req); err != nil && !errors.Is(err, io.EOF) {
common.RespondError(c, common.CodeArgumentError, "Invalid request: "+err.Error())
return
}
- row, err := h.agentService.PublishAgent(c.Request.Context(), user.ID, canvasID, &service.PublishAgentRequest{
+ row, err := h.agentService.PublishAgent(c.Request.Context(), canvasID, &service.PublishAgentRequest{
Title: req.Title,
Description: req.Description,
Alias: req.Alias,
@@ -745,13 +705,12 @@ func (h *AgentHandler) PublishAgent(c *gin.Context) {
// @Success 200 {array} entity.UserCanvasVersion
// @Router /api/v1/agents/{canvas_id}/versions [get]
func (h *AgentHandler) ListVersions(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
+ if _, code, msg := GetUser(c); code != common.CodeSuccess {
common.RespondError(c, code, msg)
return
}
canvasID := c.Param("canvas_id")
- rows, err := h.agentService.ListVersions(c.Request.Context(), user.ID, canvasID)
+ rows, err := h.agentService.ListVersions(c.Request.Context(), canvasID)
if err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
@@ -778,14 +737,13 @@ func (h *AgentHandler) ListVersions(c *gin.Context) {
// @Success 200 {object} entity.UserCanvasVersion
// @Router /api/v1/agents/{canvas_id}/versions/{version_id} [get]
func (h *AgentHandler) GetVersion(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
+ if _, code, msg := GetUser(c); code != common.CodeSuccess {
common.RespondError(c, code, msg)
return
}
canvasID := c.Param("canvas_id")
versionID := c.Param("version_id")
- row, err := h.agentService.GetVersion(c.Request.Context(), user.ID, canvasID, versionID)
+ row, err := h.agentService.GetVersion(c.Request.Context(), canvasID, versionID)
if err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
@@ -806,14 +764,13 @@ func (h *AgentHandler) GetVersion(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/agents/{canvas_id}/versions/{version_id} [delete]
func (h *AgentHandler) DeleteVersion(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
+ if _, code, msg := GetUser(c); code != common.CodeSuccess {
common.RespondError(c, code, msg)
return
}
canvasID := c.Param("canvas_id")
versionID := c.Param("version_id")
- if err := h.agentService.DeleteVersion(c.Request.Context(), user.ID, canvasID, versionID); err != nil {
+ if err := h.agentService.DeleteVersion(c.Request.Context(), canvasID, versionID); err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
return
@@ -834,8 +791,7 @@ func (h *AgentHandler) DeleteVersion(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/agents/{canvas_id}/versions/{version_id} [patch]
func (h *AgentHandler) PatchVersion(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
+ if _, code, msg := GetUser(c); code != common.CodeSuccess {
common.RespondError(c, code, msg)
return
}
@@ -851,7 +807,7 @@ func (h *AgentHandler) PatchVersion(c *gin.Context) {
return
}
patch := dao.UserCanvasVersionPatch{Alias: req.Alias, Title: req.Title, Description: req.Description}
- if err := h.agentService.UpdateVersion(c.Request.Context(), user.ID, canvasID, versionID, patch); err != nil {
+ if err := h.agentService.UpdateVersion(c.Request.Context(), canvasID, versionID, patch); err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
return
@@ -868,14 +824,13 @@ func (h *AgentHandler) PatchVersion(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/agents/{canvas_id}/versions/{version_id}/apply [post]
func (h *AgentHandler) ApplyVersion(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
+ if _, code, msg := GetUser(c); code != common.CodeSuccess {
common.RespondError(c, code, msg)
return
}
canvasID := c.Param("canvas_id")
versionID := c.Param("version_id")
- if err := h.agentService.ApplyVersion(c.Request.Context(), user.ID, canvasID, versionID); err != nil {
+ if err := h.agentService.ApplyVersion(c.Request.Context(), canvasID, versionID); err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
return
@@ -887,10 +842,6 @@ func (h *AgentHandler) ApplyVersion(c *gin.Context) {
// ListAgentTemplates GET /api/v1/agents/templates
func (h *AgentHandler) ListAgentTemplates(c *gin.Context) {
- if _, code, msg := GetUser(c); code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
ctx := c.Request.Context()
rows, err := h.agentService.ListTemplates(ctx)
if err != nil {
@@ -904,10 +855,6 @@ func (h *AgentHandler) ListAgentTemplates(c *gin.Context) {
// authoring guidelines the agent UI surfaces. The Python agent API
// returns these from a module-level constant; we keep the same shape.
func (h *AgentHandler) Prompts(c *gin.Context) {
- if _, code, msg := GetUser(c); code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
common.RespondSuccess(c, gin.H{
"task_analysis": "As an AI agent designer, your role is to engage users by understanding their objectives and creating effective agent designs. Begin by analyzing the user's request to determine the appropriate actions.",
"output_format": "For each agent you create, detail its components and explain how they collaborate to achieve the user's goal.",
@@ -918,13 +865,8 @@ func (h *AgentHandler) Prompts(c *gin.Context) {
// ListAgentTags list agent tags.
func (h *AgentHandler) ListAgentTags(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
ctx := c.Request.Context()
- rows, errCode, err := h.agentService.ListAgentTags(ctx, user.ID, strings.TrimSpace(c.Query("canvas_category")))
+ rows, errCode, err := h.agentService.ListAgentTags(ctx, strings.TrimSpace(c.Query("canvas_category")))
if err != nil {
common.RespondError(c, errCode, err.Error())
return
@@ -935,11 +877,6 @@ func (h *AgentHandler) ListAgentTags(c *gin.Context) {
// UpdateAgentTags PUT /api/v1/agents/:canvas_id/tags
func (h *AgentHandler) UpdateAgentTags(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
var body struct {
Tags interface{} `json:"tags"`
@@ -949,7 +886,7 @@ func (h *AgentHandler) UpdateAgentTags(c *gin.Context) {
return
}
ctx := c.Request.Context()
- ok, errCode, errMsg := h.agentService.UpdateAgentTags(ctx, user.ID, canvasID, body.Tags)
+ ok, errCode, errMsg := h.agentService.UpdateAgentTags(ctx, canvasID, body.Tags)
if !ok {
common.RespondError(c, errCode, errMsg.Error())
return
@@ -959,11 +896,6 @@ func (h *AgentHandler) UpdateAgentTags(c *gin.Context) {
// ListAgentSessions GET /api/v1/agents/:canvas_id/sessions
func (h *AgentHandler) ListAgentSessions(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "30"))
@@ -984,7 +916,7 @@ func (h *AgentHandler) ListAgentSessions(c *gin.Context) {
common.RespondError(c, common.CodeArgumentError, err.Error())
return
}
- resp, code, err := h.agentService.ListAgentSessions(ctx, user.ID, user.ID, canvasID, service.ListAgentSessionsRequest{
+ resp, code, err := h.agentService.ListAgentSessions(ctx, canvasID, service.ListAgentSessionsRequest{
Page: page,
PageSize: pageSize,
Keywords: keywords,
@@ -1044,11 +976,6 @@ func (h *AgentHandler) CreateAgentSession(c *gin.Context) {
// GetAgentSession GET /api/v1/agents/:canvas_id/sessions/:session_id
func (h *AgentHandler) GetAgentSession(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
sessionID := c.Param("session_id")
ctx := c.Request.Context()
@@ -1057,7 +984,7 @@ func (h *AgentHandler) GetAgentSession(c *gin.Context) {
common.RespondError(c, common.CodeArgumentError, err.Error())
return
}
- row, code, err := h.agentService.GetAgentSession(ctx, user.ID, canvasID, sessionID, options)
+ row, code, err := h.agentService.GetAgentSession(ctx, canvasID, sessionID, options)
if err != nil {
common.RespondError(c, code, err.Error())
return
@@ -1071,16 +998,11 @@ func (h *AgentHandler) GetAgentSession(c *gin.Context) {
// - /sessions/:session_id -> single item delete
// - /sessions -> JSON ids/delete_all, or query parameters without a body
func (h *AgentHandler) DeleteAgentSession(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
ctx := c.Request.Context()
canvasID := c.Param("canvas_id")
sessionID := c.Param("session_id")
if sessionID != "" {
- _, code, err := h.agentService.DeleteAgentSessionItem(ctx, user.ID, canvasID, sessionID)
+ _, code, err := h.agentService.DeleteAgentSessionItem(ctx, canvasID, sessionID)
if err != nil {
common.RespondError(c, code, err.Error())
return
@@ -1108,7 +1030,7 @@ func (h *AgentHandler) DeleteAgentSession(c *gin.Context) {
common.RespondError(c, common.CodeArgumentError, "Invalid request: "+err.Error())
return
}
- result, code, err := h.agentService.DeleteAgentSessions(ctx, user.ID, canvasID, ids, deleteAll)
+ result, code, err := h.agentService.DeleteAgentSessions(ctx, canvasID, ids, deleteAll)
if err != nil {
common.RespondError(c, code, err.Error())
return
@@ -1284,7 +1206,7 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {
)
if req.OpenAICompat {
- h.handleOpenAICompat(c, user, &req)
+ h.handleOpenAICompat(c, &req)
return
}
@@ -1299,7 +1221,7 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {
// kb_id is involved: the debug context always runs KB-less (see
// runCanvasPipelineDebug).
if h.loader != nil {
- if cv, lerr := h.loader.LoadCanvasByID(c.Request.Context(), user.ID, req.AgentID); lerr == nil && cv.CanvasCategory == "dataflow_canvas" {
+ if cv, lerr := h.loader.LoadCanvasByID(c.Request.Context(), req.AgentID); lerr == nil && cv.CanvasCategory == "dataflow_canvas" {
fileName, fileData := h.extractChatDebugFile(c.Request.Context(), req.Files, user)
if len(fileData) == 0 {
common.RespondError(c, common.CodeDataError, "dataflow debug requires an uploaded file")
@@ -1339,7 +1261,7 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {
// its `len(files) > 0` guard sees a file-less run.
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
- events, err := h.chatRunner.RunAgent(ctx, user.ID, req.AgentID, req.SessionID, "", userInput, req.Files)
+ events, err := h.chatRunner.RunAgent(ctx, req.AgentID, req.SessionID, "", userInput, req.Files)
if err != nil {
common.Warn("agent chat completions: RunAgent failed",
append([]zap.Field{
@@ -1539,18 +1461,13 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {
// TestDBConnection POST /api/v1/agents/test-db-connection
func (h *AgentHandler) TestDBConnection(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
var req service.TestDBConnectionRequest
if err := c.ShouldBindJSON(&req); err != nil && !errors.Is(err, io.EOF) {
common.RespondError(c, common.CodeArgumentError, "Invalid request: "+err.Error())
return
}
ctx := c.Request.Context()
- code, err := h.agentService.TestDBConnection(ctx, user.ID, &req)
+ code, err := h.agentService.TestDBConnection(ctx, &req)
if err != nil {
common.RespondError(c, code, err.Error())
return
@@ -1648,14 +1565,9 @@ func (h *AgentHandler) persistAgentToolInvocations(ctx context.Context, canvasID
// empty dict so the test contract `data is dict` and `code == 0` are both
// satisfied when nothing has been written yet.
func (h *AgentHandler) GetAgentLogs(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
messageID := c.Param("message_id")
- ok, errCode, errMsg := h.checkCanvasAccessForHandler(c, user.ID, canvasID)
+ ok, errCode, errMsg := h.checkCanvasAccessForHandler(c, canvasID)
if !ok {
common.RespondError(c, errCode, errMsg)
return
@@ -1680,14 +1592,9 @@ func (h *AgentHandler) GetAgentLogs(c *gin.Context) {
// protocol: establish since_ts, discover a run, then fetch events by
// webhook_id until a finished event arrives.
func (h *AgentHandler) GetAgentWebhookLogs(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
ctx := c.Request.Context()
- ok, err := h.agentService.CheckCanvasAccess(ctx, user.ID, canvasID)
+ ok, err := h.agentService.CheckCanvasAccess(ctx, canvasID)
if err != nil || !ok {
// CheckCanvasAccess now surfaces ErrUserCanvasNotFound when
// the canvas row is missing; the Python envelope is
@@ -1727,9 +1634,9 @@ func (h *AgentHandler) GetAgentWebhookLogs(c *gin.Context) {
// PR2 routes that need to call service.CheckCanvasAccess and surface
// the access-denied envelope with the same shape the existing
// loadCanvasForUser-based handlers use.
-func (h *AgentHandler) checkCanvasAccessForHandler(c *gin.Context, userID, canvasID string) (bool, common.ErrorCode, string) {
+func (h *AgentHandler) checkCanvasAccessForHandler(c *gin.Context, canvasID string) (bool, common.ErrorCode, string) {
ctx := c.Request.Context()
- ok, err := h.agentService.CheckCanvasAccess(ctx, userID, canvasID)
+ ok, err := h.agentService.CheckCanvasAccess(ctx, canvasID)
if err != nil {
// The Python agent API uses @_require_canvas_access_async on
// /sessions and /logs/:message_id, which folds "canvas does
@@ -1772,13 +1679,8 @@ func (h *AgentHandler) checkCanvasAccessForHandler(c *gin.Context, userID, canva
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/agents/{canvas_id}/reset [post]
func (h *AgentHandler) ResetAgent(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
canvasID := c.Param("canvas_id")
- dsl, err := h.agentService.ResetAgent(c.Request.Context(), user.ID, canvasID)
+ dsl, err := h.agentService.ResetAgent(c.Request.Context(), canvasID)
if err != nil {
ec, em := mapAgentError(err)
common.RespondError(c, ec, em)
diff --git a/internal/handler/agent_component.go b/internal/handler/agent_component.go
index 45d0c47af3..470755cb3e 100644
--- a/internal/handler/agent_component.go
+++ b/internal/handler/agent_component.go
@@ -61,7 +61,7 @@ func (h *AgentHandler) GetComponentInputForm(c *gin.Context) {
return
}
- cv, err := h.loader.LoadCanvasByID(c.Request.Context(), user.ID, canvasID)
+ cv, err := h.loader.LoadCanvasByID(c.Request.Context(), canvasID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
common.RespondError(c, common.CodeOperatingError, canvasNoAccessMessage)
@@ -153,7 +153,7 @@ func (h *AgentHandler) DebugComponent(c *gin.Context) {
return
}
- cv, err := h.loader.LoadCanvasByID(c.Request.Context(), user.ID, canvasID)
+ cv, err := h.loader.LoadCanvasByID(c.Request.Context(), canvasID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
common.RespondError(c, common.CodeOperatingError, canvasNoAccessMessage)
diff --git a/internal/handler/agent_openai.go b/internal/handler/agent_openai.go
index aad880cbae..0b07c911f9 100644
--- a/internal/handler/agent_openai.go
+++ b/internal/handler/agent_openai.go
@@ -27,7 +27,6 @@ import (
"ragflow/internal/agent/canvas"
"ragflow/internal/common"
- "ragflow/internal/entity"
"ragflow/internal/service"
"ragflow/internal/tokenizer"
)
@@ -104,7 +103,7 @@ type openAICompatCompletion struct {
// chat-completion wire format. It deliberately does not use the normal
// RAGFlow response helpers because those add the {code,data,message} REST
// envelope and are not accepted by OpenAI-compatible clients.
-func (h *AgentHandler) handleOpenAICompat(c *gin.Context, user *entity.User, req *agentChatCompletionsRequest) {
+func (h *AgentHandler) handleOpenAICompat(c *gin.Context, req *agentChatCompletionsRequest) {
question := extractLastUserContent(req.Messages)
if req.SessionID == "" {
req.SessionID = common.GenerateToken()
@@ -114,7 +113,7 @@ func (h *AgentHandler) handleOpenAICompat(c *gin.Context, user *entity.User, req
runContext, cancel := context.WithCancel(service.WithOpenAICompatMessages(c.Request.Context(), req.Messages))
defer cancel()
events, err := h.chatRunner.RunAgent(
- runContext, user.ID, req.AgentID, req.SessionID, "", question, req.Files,
+ runContext, req.AgentID, req.SessionID, "", question, req.Files,
)
if err != nil {
writeOpenAICompatError(c, err)
diff --git a/internal/handler/agent_test.go b/internal/handler/agent_test.go
index 70c89731ea..03fc8b4f11 100644
--- a/internal/handler/agent_test.go
+++ b/internal/handler/agent_test.go
@@ -608,7 +608,7 @@ func (f *fullFakeAgentService) UpdateAgent(context.Context, string, string, map[
func (f *fullFakeAgentService) DeleteAgent(context.Context, string, string) error {
return nil
}
-func (f *fullFakeAgentService) RunAgent(context.Context, string, string, string, string, any) (<-chan canvas.RunEvent, error) {
+func (f *fullFakeAgentService) RunAgent(context.Context, string, string, string, any, []map[string]interface{}) (<-chan canvas.RunEvent, error) {
ch := make(chan canvas.RunEvent)
close(ch)
return ch, nil
@@ -616,16 +616,16 @@ func (f *fullFakeAgentService) RunAgent(context.Context, string, string, string,
func (f *fullFakeAgentService) PublishAgent(context.Context, string, string, *service.PublishAgentRequest) (*entity.UserCanvasVersion, error) {
return f.version, nil
}
-func (f *fullFakeAgentService) ListVersions(context.Context, string, string) ([]*entity.UserCanvasVersion, error) {
+func (f *fullFakeAgentService) ListVersions(context.Context, string) ([]*entity.UserCanvasVersion, error) {
return f.versions, nil
}
-func (f *fullFakeAgentService) GetVersion(context.Context, string, string, string) (*entity.UserCanvasVersion, error) {
+func (f *fullFakeAgentService) GetVersion(context.Context, string, string) (*entity.UserCanvasVersion, error) {
if f.getErr != nil {
return nil, f.getErr
}
return f.version, nil
}
-func (f *fullFakeAgentService) DeleteVersion(context.Context, string, string, string) error {
+func (f *fullFakeAgentService) DeleteVersion(context.Context, string, string) error {
return f.getErr
}
@@ -876,7 +876,7 @@ type stubChatRunner struct {
userInput any
}
-func (s *stubChatRunner) RunAgent(ctx context.Context, _, _, sessionID, _ string, userInput any, _ []map[string]interface{}) (<-chan canvas.RunEvent, error) {
+func (s *stubChatRunner) RunAgent(ctx context.Context, _, sessionID, _ string, userInput any, _ []map[string]interface{}) (<-chan canvas.RunEvent, error) {
s.sessionID = sessionID
s.trustedSessionID = service.AgentSessionIDFromContext(ctx)
s.userInput = userInput
@@ -1133,7 +1133,7 @@ type emptySessionCaptureRunner struct {
trustedSessionID string
}
-func (r *emptySessionCaptureRunner) RunAgent(ctx context.Context, _, _, sessionID, _ string, _ any, _ []map[string]interface{}) (<-chan canvas.RunEvent, error) {
+func (r *emptySessionCaptureRunner) RunAgent(ctx context.Context, _, sessionID, _ string, _ any, _ []map[string]interface{}) (<-chan canvas.RunEvent, error) {
r.sessionID = sessionID
r.trustedSessionID = service.AgentSessionIDFromContext(ctx)
ch := make(chan canvas.RunEvent)
@@ -1296,7 +1296,7 @@ type captureChatRunner struct {
capturedFiles *[]map[string]interface{}
}
-func (c *captureChatRunner) RunAgent(_ context.Context, _, _, _, _ string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error) {
+func (c *captureChatRunner) RunAgent(_ context.Context, _, _, _ string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error) {
*c.captured = userInput
if c.capturedFiles != nil {
*c.capturedFiles = files
diff --git a/internal/handler/agent_upload.go b/internal/handler/agent_upload.go
index 0364855fa3..0125a3e0dc 100644
--- a/internal/handler/agent_upload.go
+++ b/internal/handler/agent_upload.go
@@ -73,7 +73,7 @@ func (h *AgentHandler) UploadAgentFile(c *gin.Context) {
// IDOR mitigation; the user-visible envelope uses OPERATING_ERROR
// (103) with the python permission message so existing clients can
// still pattern-match the text.
- if _, err := h.loader.LoadCanvasByID(c.Request.Context(), user.ID, canvasID); err != nil {
+ if _, err := h.loader.LoadCanvasByID(c.Request.Context(), canvasID); err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
common.RespondError(c, common.CodeOperatingError, canvasNoAccessMessage)
return
diff --git a/internal/handler/agent_upload_test.go b/internal/handler/agent_upload_test.go
index 30847bcdda..759c246f48 100644
--- a/internal/handler/agent_upload_test.go
+++ b/internal/handler/agent_upload_test.go
@@ -31,6 +31,7 @@ import (
"ragflow/internal/dao"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
)
// uploadFakes is a paired pair of fakes used by the upload-handler
@@ -73,6 +74,7 @@ func makeUploadCtx(t *testing.T, n int) (*gin.Context, *httptest.ResponseRecorde
c.Request = req
c.Params = gin.Params{{Key: "canvas_id", Value: "c1"}}
c.Set("user", &entity.User{ID: "u-1"})
+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "u-1", "u-1"))
return c, w
}
@@ -94,6 +96,7 @@ func makeUploadCtxNoFile(t *testing.T) (*gin.Context, *httptest.ResponseRecorder
c.Request = req
c.Params = gin.Params{{Key: "canvas_id", Value: "c1"}}
c.Set("user", &entity.User{ID: "u-1"})
+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "u-1", "u-1"))
return c, w
}
diff --git a/internal/handler/agent_version_test.go b/internal/handler/agent_version_test.go
index 9bdac7ec63..a44591a9cd 100644
--- a/internal/handler/agent_version_test.go
+++ b/internal/handler/agent_version_test.go
@@ -83,6 +83,9 @@ func TestAgentVersionActions(t *testing.T) {
wantCode = common.CodeOperatingError
case "unauthenticated":
delete(c.Keys, "user")
+ delete(c.Keys, "user_id")
+ delete(c.Keys, "tenant_id")
+ c.Request = c.Request.WithContext(t.Context())
wantCode = common.CodeUnauthorized
case "nil_dsl":
version.DSL = nil
diff --git a/internal/handler/agent_wait_for_user_test.go b/internal/handler/agent_wait_for_user_test.go
index 095ecdb38c..d150d6864c 100644
--- a/internal/handler/agent_wait_for_user_test.go
+++ b/internal/handler/agent_wait_for_user_test.go
@@ -37,6 +37,7 @@ import (
"ragflow/internal/agent/runtime"
"ragflow/internal/common"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
"ragflow/internal/service"
)
@@ -94,9 +95,8 @@ func (f *waitFakeAgentService) DeleteAgent(context.Context, string, string) erro
// RunAgent mimics service.AgentService.RunAgent for the test
// driver. It loads the canvas (a no-op in tests), builds a RunFunc
// from the supplied stub, and hands off to the orchestrator.
-func (f *waitFakeAgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID, version string, userInput any, _ []map[string]interface{}) (<-chan canvas.RunEvent, error) {
- _ = ctx
- _ = userID
+func (f *waitFakeAgentService) RunAgent(ctx context.Context, canvasID, sessionID, version string, userInput any, _ []map[string]interface{}) (<-chan canvas.RunEvent, error) {
+ userID := permission.UserIDFromContext(ctx)
_ = version
stub := f.stubRunFunc
run := func(ctx context.Context, root map[string]any) (*runtime.CanvasState, error) {
@@ -117,13 +117,13 @@ func (f *waitFakeAgentService) RunAgent(ctx context.Context, userID, canvasID, s
func (f *waitFakeAgentService) PublishAgent(context.Context, string, string, *service.PublishAgentRequest) (*entity.UserCanvasVersion, error) {
return &entity.UserCanvasVersion{}, nil
}
-func (f *waitFakeAgentService) ListVersions(context.Context, string, string) ([]*entity.UserCanvasVersion, error) {
+func (f *waitFakeAgentService) ListVersions(context.Context, string) ([]*entity.UserCanvasVersion, error) {
return nil, nil
}
-func (f *waitFakeAgentService) GetVersion(context.Context, string, string, string) (*entity.UserCanvasVersion, error) {
+func (f *waitFakeAgentService) GetVersion(context.Context, string, string) (*entity.UserCanvasVersion, error) {
return &entity.UserCanvasVersion{}, nil
}
-func (f *waitFakeAgentService) DeleteVersion(context.Context, string, string, string) error {
+func (f *waitFakeAgentService) DeleteVersion(context.Context, string, string) error {
return nil
}
@@ -140,6 +140,7 @@ func waitForUserRoutes(svc *waitFakeAgentService) *gin.Engine {
g := r.Group("/api/v1/agents")
g.Use(func(c *gin.Context) {
c.Set("user", &entity.User{ID: "user-wait"})
+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "user-wait", ""))
c.Next()
})
g.POST("/:canvas_id/run", func(c *gin.Context) {
@@ -150,7 +151,7 @@ func waitForUserRoutes(svc *waitFakeAgentService) *gin.Engine {
canvasID := c.Param("canvas_id")
sessionID := c.Query("session_id")
userInput := c.Query("user_input")
- events, err := svc.RunAgent(c.Request.Context(), "user-wait", canvasID, sessionID, "", userInput, nil)
+ events, err := svc.RunAgent(c.Request.Context(), canvasID, sessionID, "", userInput, nil)
if err != nil {
// We never expect a non-nil err from the fake,
// but be defensive.
diff --git a/internal/handler/agent_webhook.go b/internal/handler/agent_webhook.go
index 3c46fda6d4..0cba146ad7 100644
--- a/internal/handler/agent_webhook.go
+++ b/internal/handler/agent_webhook.go
@@ -95,14 +95,14 @@ import (
// ErrUserCanvasNotFound to 103 "Make sure you have permission..." which
// is the chat/run contract — wrong for the webhook path.
type canvasLoader interface {
- LoadCanvasByID(ctx context.Context, userID, canvasID string) (*entity.UserCanvas, error)
- RunAgentWithWebhook(ctx context.Context, userID, canvasID string, payload map[string]any) (<-chan canvas.RunEvent, error)
+ LoadCanvasByID(ctx context.Context, canvasID string) (*entity.UserCanvas, error)
+ RunAgentWithWebhook(ctx context.Context, canvasID string, payload map[string]any) (<-chan canvas.RunEvent, error)
}
type agentWebhookCredentialManager interface {
Issue(ctx context.Context, canvas *entity.UserCanvas) (string, error)
Resolve(ctx context.Context, canvasID, token string) (*entity.AgentWebhookCredential, error)
- Revoke(ctx context.Context, canvasID, userID string) error
+ Revoke(ctx context.Context, canvasID string) error
}
// Webhook handles the public credential-authenticated trigger and the
@@ -122,14 +122,7 @@ func (h *AgentHandler) Webhook(c *gin.Context) {
}
isTest := strings.HasSuffix(c.Request.URL.Path, "/webhook/test")
ctx := c.Request.Context()
- userID := ""
if isTest {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.Respond(c, http.StatusUnauthorized, code, nil, msg)
- return
- }
- userID = user.ID
} else {
// Production webhooks are mounted outside AuthMiddleware. External
// callers authenticate with a per-user capability in the URL; RAGFlow
@@ -143,7 +136,6 @@ func (h *AgentHandler) Webhook(c *gin.Context) {
}
return
}
- userID = credential.UserID
ctx = permission.WithIdentity(ctx, credential.UserID, credential.TenantID)
// The URL credential is transport authentication, not Agent input.
query := c.Request.URL.Query()
@@ -157,7 +149,7 @@ func (h *AgentHandler) Webhook(c *gin.Context) {
// api/apps/restful_apis/agent_api.py:1572 and the existing
// GetAgentWebhookLogs envelope), so we DO NOT route through
// handler.mapAgentError here.
- cv, err := h.loader.LoadCanvasByID(ctx, userID, canvasID)
+ cv, err := h.loader.LoadCanvasByID(ctx, canvasID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) || errors.Is(err, dao.ErrUserCanvasVersionNotFound) {
common.RespondError(c, common.CodeDataError, "Canvas not found.")
@@ -264,30 +256,25 @@ func (h *AgentHandler) Webhook(c *gin.Context) {
}
// Detached background run — does NOT inherit c.Request.Context()
// so a client disconnect does not cancel the canvas run.
- go h.runWebhookDetached(ctx, userID, cv, clean, isTest, startTs)
+ go h.runWebhookDetached(ctx, cv, clean, isTest, startTs)
c.Data(status, contentType, payload)
return
}
// Streaming / blocking mode.
- out := h.runWebhookSync(ctx, userID, cv, clean, isTest, startTs)
+ out := h.runWebhookSync(ctx, cv, clean, isTest, startTs)
c.JSON(out.status, out.body)
}
// CreateWebhookCredential issues or rotates the authenticated user's
// capability for this Agent and returns the URL once.
func (h *AgentHandler) CreateWebhookCredential(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
if h.loader == nil {
jsonInternalError(c, errors.New("agent webhook: loader not configured"))
return
}
canvasID := c.Param("canvas_id")
ctx := c.Request.Context()
- canvas, err := h.loader.LoadCanvasByID(ctx, user.ID, canvasID)
+ canvas, err := h.loader.LoadCanvasByID(ctx, canvasID)
if err != nil {
responseCode, responseMessage := mapAgentError(err)
common.RespondError(c, responseCode, responseMessage)
@@ -313,12 +300,7 @@ func (h *AgentHandler) CreateWebhookCredential(c *gin.Context) {
// RevokeWebhookCredential revokes only the authenticated user's capability
// for this Agent.
func (h *AgentHandler) RevokeWebhookCredential(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
- if err := h.webhookCredentialManager().Revoke(c.Request.Context(), c.Param("canvas_id"), user.ID); err != nil {
+ if err := h.webhookCredentialManager().Revoke(c.Request.Context(), c.Param("canvas_id")); err != nil {
jsonInternalError(c, err)
return
}
@@ -580,20 +562,20 @@ func renderImmediatelyResponse(cfg map[string]any) (int, string, []byte, error)
// Mirrors python: agent_api.py:2123-2175 (the asyncio.create_task body
// inside the Immediately branch).
func (h *AgentHandler) runWebhookDetached(
- parent context.Context, userID string, cv *entity.UserCanvas, payload map[string]any, isTest bool, startTs time.Time,
+ parent context.Context, cv *entity.UserCanvas, payload map[string]any, isTest bool, startTs time.Time,
) {
sessionID := common.GenerateToken()
parent = service.WithAgentSessionID(parent, sessionID)
ctx, cancel := context.WithTimeout(context.WithoutCancel(parent), 5*time.Minute)
defer cancel()
- h.runWebhookDetachedWithContext(ctx, userID, cv, payload, isTest, startTs, sessionID)
+ h.runWebhookDetachedWithContext(ctx, cv, payload, isTest, startTs, sessionID)
}
func (h *AgentHandler) runWebhookDetachedWithContext(
- ctx context.Context, userID string, cv *entity.UserCanvas, payload map[string]any,
+ ctx context.Context, cv *entity.UserCanvas, payload map[string]any,
isTest bool, startTs time.Time, sessionID string,
) {
- events, err := h.loader.RunAgentWithWebhook(ctx, userID, cv.ID, payload)
+ events, err := h.loader.RunAgentWithWebhook(ctx, cv.ID, payload)
if err != nil {
common.Warn("webhook detached run start failed",
zap.String("canvas", cv.ID),
@@ -654,13 +636,13 @@ type webhookSyncResult struct {
}
func (h *AgentHandler) runWebhookSync(
- ctx context.Context, userID string, cv *entity.UserCanvas, payload map[string]any,
+ ctx context.Context, cv *entity.UserCanvas, payload map[string]any,
isTest bool, startTs time.Time,
) webhookSyncResult {
status := 200
sessionID := common.GenerateToken()
ctx = service.WithAgentSessionID(ctx, sessionID)
- events, err := h.loader.RunAgentWithWebhook(ctx, userID, cv.ID, payload)
+ events, err := h.loader.RunAgentWithWebhook(ctx, cv.ID, payload)
if err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
event := webhookContextTerminalEvent(ctxErr, sessionID)
diff --git a/internal/handler/agent_webhook_test.go b/internal/handler/agent_webhook_test.go
index 74aea05a14..591dd9b84d 100644
--- a/internal/handler/agent_webhook_test.go
+++ b/internal/handler/agent_webhook_test.go
@@ -87,21 +87,22 @@ func (f *fakeAgentWebhookCredentialManager) Resolve(_ context.Context, canvasID,
return &credential, nil
}
-func (f *fakeAgentWebhookCredentialManager) Revoke(_ context.Context, canvasID, userID string) error {
+func (f *fakeAgentWebhookCredentialManager) Revoke(ctx context.Context, canvasID string) error {
f.revokedID = canvasID
- f.revokedUser = userID
+ f.revokedUser = permission.UserIDFromContext(ctx)
return nil
}
-func (f *fakeCanvasLoader) LoadCanvasByID(_ context.Context, userID, _ string) (*entity.UserCanvas, error) {
- f.loadUserID = userID
+func (f *fakeCanvasLoader) LoadCanvasByID(ctx context.Context, _ string) (*entity.UserCanvas, error) {
+ f.loadUserID = permission.UserIDFromContext(ctx)
if f.err != nil {
return nil, f.err
}
return f.canvas, nil
}
-func (f *fakeCanvasLoader) RunAgentWithWebhook(ctx context.Context, userID, canvasID string, payload map[string]any) (<-chan canvas.RunEvent, error) {
+func (f *fakeCanvasLoader) RunAgentWithWebhook(ctx context.Context, canvasID string, payload map[string]any) (<-chan canvas.RunEvent, error) {
+ userID := permission.UserIDFromContext(ctx)
f.runCalls.Add(1)
f.runUserID = userID
f.runCanvasID = canvasID
@@ -199,6 +200,7 @@ func webhookCtx(method, path, body, contentType string) (*gin.Context, *httptest
c.Request.Header.Set("Content-Type", contentType)
}
c.Set("user", &entity.User{ID: "u-1"})
+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "u-1", "u-1"))
return c, w
}
@@ -900,7 +902,7 @@ func TestRunWebhookDetachedAppendsFinishedTrace(t *testing.T) {
trace = append(trace, ev)
}
- h.runWebhookDetached(t.Context(), "u-1", cv, map[string]any{}, true, time.Now())
+ h.runWebhookDetached(t.Context(), cv, map[string]any{}, true, time.Now())
assertWebhookFinishedTrace(t, trace, tt.wantSuccess)
if tt.forbidden != "" {
@@ -941,7 +943,7 @@ func TestRunWebhookDetachedRecordsTimeoutTrace(t *testing.T) {
)
defer cancel()
<-ctx.Done()
- h.runWebhookDetachedWithContext(ctx, "u-1", cv, map[string]any{}, true, time.Now(), "session-1")
+ h.runWebhookDetachedWithContext(ctx, cv, map[string]any{}, true, time.Now(), "session-1")
if len(trace) < 2 || trace[0].Type != "error" || !strings.Contains(trace[0].Data, "timed out") {
t.Fatalf("timeout trace = %+v, want error followed by failed finished event", trace)
@@ -964,7 +966,7 @@ func TestRunWebhookSyncRecordsCancelledTrace(t *testing.T) {
ctx, cancel := context.WithCancel(t.Context())
cancel()
- result := h.runWebhookSync(ctx, "u-1", cv, map[string]any{}, true, time.Now())
+ result := h.runWebhookSync(ctx, cv, map[string]any{}, true, time.Now())
if result.status != http.StatusConflict {
t.Errorf("status = %d, want %d", result.status, http.StatusConflict)
@@ -983,13 +985,13 @@ func TestWebhookBufferedTerminalEventAfterCancellationUsesCleanupContext(t *test
{
name: "detached",
run: func(_ *testing.T, h *AgentHandler, ctx context.Context, cv *entity.UserCanvas) {
- h.runWebhookDetachedWithContext(ctx, "u-1", cv, map[string]any{}, true, time.Now(), "session-1")
+ h.runWebhookDetachedWithContext(ctx, cv, map[string]any{}, true, time.Now(), "session-1")
},
},
{
name: "sync",
run: func(t *testing.T, h *AgentHandler, ctx context.Context, cv *entity.UserCanvas) {
- result := h.runWebhookSync(ctx, "u-1", cv, map[string]any{}, true, time.Now())
+ result := h.runWebhookSync(ctx, cv, map[string]any{}, true, time.Now())
if result.status != http.StatusConflict {
t.Errorf("status = %d, want %d", result.status, http.StatusConflict)
}
diff --git a/internal/handler/agent_webhook_workflow_test.go b/internal/handler/agent_webhook_workflow_test.go
index 545ce991e7..84c8f9abde 100644
--- a/internal/handler/agent_webhook_workflow_test.go
+++ b/internal/handler/agent_webhook_workflow_test.go
@@ -27,7 +27,7 @@ import (
type webhookWorkflowLoader struct{ *fakeCanvasLoader }
// RunAgentWithWebhook forwards the cleaned HTTP payload into a compiled Begin-to-Message workflow.
-func (f *webhookWorkflowLoader) RunAgentWithWebhook(ctx context.Context, _, _ string, payload map[string]any) (<-chan canvas.RunEvent, error) {
+func (f *webhookWorkflowLoader) RunAgentWithWebhook(ctx context.Context, _ string, payload map[string]any) (<-chan canvas.RunEvent, error) {
raw, err := json.Marshal(f.canvas.DSL)
if err != nil {
return nil, err
diff --git a/internal/handler/bot.go b/internal/handler/bot.go
index 23627b0c9a..d7f450ca2b 100644
--- a/internal/handler/bot.go
+++ b/internal/handler/bot.go
@@ -39,15 +39,15 @@ type BotHandler struct {
// botService is the subset of BotService used by these handlers. It
// is interface-typed so the test suite can inject a stub.
type botService interface {
- ChatbotInfo(ctx context.Context, userID, dialogID string) (
+ ChatbotInfo(ctx context.Context, dialogID string) (
title, avatar, prologue, llmID string, hasWebSearch bool, ec common.ErrorCode, err error)
- AgentbotInputs(ctx context.Context, userID, agentID string) (
+ AgentbotInputs(ctx context.Context, agentID string) (
title, avatar, prologue, mode string, inputs map[string]any,
ec common.ErrorCode, err error)
- AgentbotCompletion(ctx context.Context, userID, agentID string, req service.AgentbotCompletionRequest) (
+ AgentbotCompletion(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (
<-chan canvas.RunEvent, common.ErrorCode, error)
- AgentbotLogs(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error)
- ChatbotCompletion(ctx context.Context, userID, dialogID string, req service.ChatbotCompletionRequest) (
+ AgentbotLogs(ctx context.Context, agentID, messageID string) (map[string]any, common.ErrorCode, error)
+ ChatbotCompletion(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (
<-chan service.ChatbotSSEFrame, common.ErrorCode, error)
}
@@ -61,18 +61,13 @@ func NewBotHandler(svc *service.BotService) *BotHandler {
// Mirrors python bot_api.py:126-154. Returns the public metadata of
// a chatbot dialog (title, avatar, prologue, web search flag, llm_id).
func (h *BotHandler) ChatbotInfo(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
dialogID := c.Param("dialog_id")
if dialogID == "" {
common.RespondError(c, common.CodeArgumentError, "`dialog_id` is required.")
return
}
title, avatar, prologue, llmID, hasWebSearch, ec, err := h.botService.ChatbotInfo(
- c.Request.Context(), user.ID, dialogID)
+ c.Request.Context(), dialogID)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -95,18 +90,13 @@ func (h *BotHandler) ChatbotInfo(c *gin.Context) {
// Mirrors python bot_api.py:239-250. Returns the public metadata of
// an agentbot canvas (title, avatar, inputs, prologue, mode).
func (h *BotHandler) AgentbotInputs(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
agentID := c.Param("agent_id")
if agentID == "" {
common.RespondError(c, common.CodeArgumentError, "`agent_id` is required.")
return
}
title, avatar, prologue, mode, inputs, ec, err := h.botService.AgentbotInputs(
- c.Request.Context(), user.ID, agentID)
+ c.Request.Context(), agentID)
if err != nil {
common.RespondError(c, ec, err.Error())
return
@@ -136,11 +126,6 @@ func (h *BotHandler) AgentbotInputs(c *gin.Context) {
// canvas event, including node_* telemetry used by the "Thinking"
// log panel).
func (h *BotHandler) AgentbotCompletion(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
agentID := c.Param("agent_id")
if agentID == "" {
common.RespondError(c, common.CodeArgumentError, "`agent_id` is required.")
@@ -170,7 +155,7 @@ func (h *BotHandler) AgentbotCompletion(c *gin.Context) {
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
events, ec, err := h.botService.AgentbotCompletion(
- ctx, user.ID, agentID, body)
+ ctx, agentID, body)
if err != nil {
common.RespondError(c, ec, err.Error())
return
@@ -198,11 +183,6 @@ func (h *BotHandler) AgentbotCompletion(c *gin.Context) {
// SSE frames in the Python envelope shape. The streaming helper
// lives in service/bot_completion.go.
func (h *BotHandler) ChatbotCompletion(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
dialogID := c.Param("dialog_id")
if dialogID == "" {
common.RespondError(c, common.CodeArgumentError, "`dialog_id` is required.")
@@ -222,7 +202,7 @@ func (h *BotHandler) ChatbotCompletion(c *gin.Context) {
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
frames, ec, err := h.botService.ChatbotCompletion(
- ctx, user.ID, dialogID, body)
+ ctx, dialogID, body)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -252,11 +232,6 @@ func (h *BotHandler) ChatbotCompletion(c *gin.Context) {
// "Thinking" button hits this endpoint because the share flow authenticates
// with a beta APIToken (no session JWT). Mirrors python bot_api.py:agent_bot_logs.
func (h *BotHandler) GetAgentbotLogs(c *gin.Context) {
- user, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
agentIDStr := c.Param("agent_id")
if agentIDStr == "" {
common.RespondError(c, common.CodeArgumentError, "agent_id is required")
@@ -277,7 +252,7 @@ func (h *BotHandler) GetAgentbotLogs(c *gin.Context) {
return
}
}
- data, ec, err := h.botService.AgentbotLogs(c.Request.Context(), user.ID, agentIDStr, messageID)
+ data, ec, err := h.botService.AgentbotLogs(c.Request.Context(), agentIDStr, messageID)
if err != nil {
common.RespondError(c, ec, err.Error())
return
diff --git a/internal/handler/bot_test.go b/internal/handler/bot_test.go
index 47e9f6be3b..c5839beb73 100644
--- a/internal/handler/bot_test.go
+++ b/internal/handler/bot_test.go
@@ -40,44 +40,44 @@ import (
// BotHandler. Each test case sets only the methods it needs; unset
// methods return safe defaults.
type stubBotService struct {
- chatbotInfoFn func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error)
- agentbotInputsFn func(ctx context.Context, userID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error)
- agentbotCompleteFn func(ctx context.Context, userID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error)
- agentbotLogsFn func(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error)
- chatbotCompleteFn func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error)
+ chatbotInfoFn func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error)
+ agentbotInputsFn func(ctx context.Context, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error)
+ agentbotCompleteFn func(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error)
+ agentbotLogsFn func(ctx context.Context, agentID, messageID string) (map[string]any, common.ErrorCode, error)
+ chatbotCompleteFn func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error)
}
-func (s *stubBotService) ChatbotInfo(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+func (s *stubBotService) ChatbotInfo(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
if s.chatbotInfoFn != nil {
- return s.chatbotInfoFn(ctx, tenantID, dialogID)
+ return s.chatbotInfoFn(ctx, dialogID)
}
return "", "", "", "", false, common.CodeDataError, errors.New("not stubbed")
}
-func (s *stubBotService) AgentbotInputs(ctx context.Context, userID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
+func (s *stubBotService) AgentbotInputs(ctx context.Context, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
if s.agentbotInputsFn != nil {
- return s.agentbotInputsFn(ctx, userID, agentID)
+ return s.agentbotInputsFn(ctx, agentID)
}
return "", "", "", "", nil, common.CodeDataError, errors.New("not stubbed")
}
-func (s *stubBotService) AgentbotCompletion(ctx context.Context, userID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+func (s *stubBotService) AgentbotCompletion(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
if s.agentbotCompleteFn != nil {
- return s.agentbotCompleteFn(ctx, userID, agentID, req)
+ return s.agentbotCompleteFn(ctx, agentID, req)
}
return nil, common.CodeDataError, errors.New("not stubbed")
}
-func (s *stubBotService) AgentbotLogs(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
+func (s *stubBotService) AgentbotLogs(ctx context.Context, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
if s.agentbotLogsFn != nil {
- return s.agentbotLogsFn(ctx, userID, agentID, messageID)
+ return s.agentbotLogsFn(ctx, agentID, messageID)
}
return nil, common.CodeDataError, errors.New("not stubbed")
}
-func (s *stubBotService) ChatbotCompletion(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+func (s *stubBotService) ChatbotCompletion(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
if s.chatbotCompleteFn != nil {
- return s.chatbotCompleteFn(ctx, tenantID, dialogID, req)
+ return s.chatbotCompleteFn(ctx, dialogID, req)
}
return nil, common.CodeDataError, errors.New("not stubbed")
}
@@ -138,7 +138,7 @@ func doJSON(r *gin.Engine, method, path, body string) *httptest.ResponseRecorder
// TestChatbotInfo_OK covers the happy path (criterion 13).
func TestChatbotInfo_OK(t *testing.T) {
stub := &stubBotService{
- chatbotInfoFn: func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+ chatbotInfoFn: func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
return "My Bot", "avatar.png", "Hello!", "gpt-4", false, common.CodeSuccess, nil
},
}
@@ -172,7 +172,7 @@ func TestChatbotInfo_OK(t *testing.T) {
// TestChatbotInfo_HasTavilyKey covers criterion 14.
func TestChatbotInfo_HasTavilyKey(t *testing.T) {
stub := &stubBotService{
- chatbotInfoFn: func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+ chatbotInfoFn: func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
return "Bot", "", "", "gpt-4", true, common.CodeSuccess, nil
},
}
@@ -193,7 +193,7 @@ func TestChatbotInfo_HasTavilyKey(t *testing.T) {
// TestChatbotInfo_ForeignTenant covers criterion 15.
func TestChatbotInfo_ForeignTenant(t *testing.T) {
stub := &stubBotService{
- chatbotInfoFn: func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+ chatbotInfoFn: func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
return "", "", "", "", false, common.CodeNotFound, permission.ErrPermissionDenied
},
}
@@ -220,7 +220,7 @@ func TestChatbotInfo_MissingPrologueField(t *testing.T) {
// Stub returns empty prologue (mimics the defensive stringFromMap
// fallback when the field is absent or non-string).
stub := &stubBotService{
- chatbotInfoFn: func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+ chatbotInfoFn: func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
return "Bot", "", "", "gpt-4", false, common.CodeSuccess, nil
},
}
@@ -240,7 +240,7 @@ func TestChatbotInfo_MissingPrologueField(t *testing.T) {
// TestChatbotCompletion_AuthoriseFail covers criterion 6.
func TestChatbotCompletion_AuthoriseFail(t *testing.T) {
stub := &stubBotService{
- chatbotCompleteFn: func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+ chatbotCompleteFn: func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
return nil, common.CodeNotFound, permission.ErrPermissionDenied
},
}
@@ -265,7 +265,7 @@ func TestChatbotCompletion_AuthoriseFail(t *testing.T) {
// TestChatbotCompletion_StreamsSSE covers criterion 11.
func TestChatbotCompletion_StreamsSSE(t *testing.T) {
stub := &stubBotService{
- chatbotCompleteFn: func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+ chatbotCompleteFn: func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
ch := make(chan service.ChatbotSSEFrame, 4)
go func() {
defer close(ch)
@@ -308,7 +308,7 @@ func TestChatbotCompletion_StreamsSSE(t *testing.T) {
// TestChatbotCompletion_LLMUnavailable covers criterion 12.
func TestChatbotCompletion_LLMUnavailable(t *testing.T) {
stub := &stubBotService{
- chatbotCompleteFn: func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+ chatbotCompleteFn: func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
return nil, common.CodeDataError, errors.New("LLM not available: timeout")
},
}
@@ -330,7 +330,7 @@ func TestChatbotCompletion_LLMUnavailable(t *testing.T) {
// TestChatbotCompletion_SessionNotFound covers criterion 10.
func TestChatbotCompletion_SessionNotFound(t *testing.T) {
stub := &stubBotService{
- chatbotCompleteFn: func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+ chatbotCompleteFn: func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
return nil, common.CodeDataError, errors.New("session not found")
},
}
@@ -353,7 +353,7 @@ func TestChatbotCompletion_SessionNotFound(t *testing.T) {
func TestChatbotCompletion_CreatesNewSession(t *testing.T) {
var capturedReq service.ChatbotCompletionRequest
stub := &stubBotService{
- chatbotCompleteFn: func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+ chatbotCompleteFn: func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
capturedReq = req
ch := make(chan service.ChatbotSSEFrame, 2)
close(ch)
@@ -377,7 +377,7 @@ func TestChatbotCompletion_CreatesNewSession(t *testing.T) {
func TestChatbotCompletion_ReusesSession(t *testing.T) {
var capturedReq service.ChatbotCompletionRequest
stub := &stubBotService{
- chatbotCompleteFn: func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+ chatbotCompleteFn: func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
capturedReq = req
ch := make(chan service.ChatbotSSEFrame, 2)
close(ch)
@@ -394,7 +394,7 @@ func TestChatbotCompletion_ReusesSession(t *testing.T) {
// TestChatbotCompletion_SessionTenantMismatch covers criterion 9.
func TestChatbotCompletion_SessionTenantMismatch(t *testing.T) {
stub := &stubBotService{
- chatbotCompleteFn: func(ctx context.Context, tenantID, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
+ chatbotCompleteFn: func(ctx context.Context, dialogID string, req service.ChatbotCompletionRequest) (<-chan service.ChatbotSSEFrame, common.ErrorCode, error) {
return nil, common.CodeDataError, errors.New("session not found")
},
}
@@ -420,7 +420,7 @@ func TestChatbotCompletion_SessionTenantMismatch(t *testing.T) {
// data:{answer}} envelope — terminated by [DONE].
func TestAgentbotCompletion_StreamsSSE(t *testing.T) {
stub := &stubBotService{
- agentbotCompleteFn: func(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+ agentbotCompleteFn: func(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
ch := make(chan canvas.RunEvent, 4)
go func() {
defer close(ch)
@@ -471,7 +471,7 @@ func TestAgentbotCompletion_StreamsSSE(t *testing.T) {
func TestAgentbotCompletion_URLBoundAgentID(t *testing.T) {
var capturedAgentID string
stub := &stubBotService{
- agentbotCompleteFn: func(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+ agentbotCompleteFn: func(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
capturedAgentID = agentID
ch := make(chan canvas.RunEvent, 2)
close(ch)
@@ -490,7 +490,7 @@ func TestAgentbotCompletion_URLBoundAgentID(t *testing.T) {
// TestAgentbotCompletion_NoAccess covers criterion 19.
func TestAgentbotCompletion_NoAccess(t *testing.T) {
stub := &stubBotService{
- agentbotCompleteFn: func(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+ agentbotCompleteFn: func(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
return nil, common.CodeDataError, errors.New("can't find agent by ID: a1")
},
}
@@ -513,7 +513,7 @@ func TestAgentbotCompletion_NoAccess(t *testing.T) {
func TestAgentbotCompletion_ResumesSession(t *testing.T) {
var capturedReq service.AgentbotCompletionRequest
stub := &stubBotService{
- agentbotCompleteFn: func(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+ agentbotCompleteFn: func(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
capturedReq = req
ch := make(chan canvas.RunEvent, 2)
close(ch)
@@ -530,7 +530,7 @@ func TestAgentbotCompletion_ResumesSession(t *testing.T) {
func TestAgentbotCompletion_BindsReleaseQuery(t *testing.T) {
var capturedReq service.AgentbotCompletionRequest
stub := &stubBotService{
- agentbotCompleteFn: func(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+ agentbotCompleteFn: func(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
capturedReq = req
ch := make(chan canvas.RunEvent)
close(ch)
@@ -547,7 +547,7 @@ func TestAgentbotCompletion_BindsReleaseQuery(t *testing.T) {
func TestAgentbotCompletion_BindsFileDescriptors(t *testing.T) {
var capturedReq service.AgentbotCompletionRequest
stub := &stubBotService{
- agentbotCompleteFn: func(ctx context.Context, tenantID, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
+ agentbotCompleteFn: func(ctx context.Context, agentID string, req service.AgentbotCompletionRequest) (<-chan canvas.RunEvent, common.ErrorCode, error) {
capturedReq = req
ch := make(chan canvas.RunEvent)
close(ch)
@@ -572,7 +572,7 @@ func TestAgentbotCompletion_BindsFileDescriptors(t *testing.T) {
// TestAgentbotInputs_OK covers criterion 21.
func TestAgentbotInputs_OK(t *testing.T) {
stub := &stubBotService{
- agentbotInputsFn: func(ctx context.Context, tenantID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
+ agentbotInputsFn: func(ctx context.Context, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
return "My Agent", "agent.png", "Welcome", "Agent", map[string]any{"query": map[string]any{"type": "string"}}, common.CodeSuccess, nil
},
}
@@ -609,7 +609,7 @@ func TestAgentbotInputs_MissingBeginComponent(t *testing.T) {
// service-layer fallback when FindBeginComponentID returns
// ErrComponentNotFound).
stub := &stubBotService{
- agentbotInputsFn: func(ctx context.Context, tenantID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
+ agentbotInputsFn: func(ctx context.Context, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
return "Agent", "", "", "", nil, common.CodeSuccess, nil
},
}
@@ -633,7 +633,7 @@ func TestAgentbotInputs_MissingBeginComponent(t *testing.T) {
// TestAgentbotInputs_NotFound covers criterion 23.
func TestAgentbotInputs_NotFound(t *testing.T) {
stub := &stubBotService{
- agentbotInputsFn: func(ctx context.Context, tenantID, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
+ agentbotInputsFn: func(ctx context.Context, agentID string) (string, string, string, string, map[string]any, common.ErrorCode, error) {
return "", "", "", "", nil, common.CodeDataError, errors.New("can't find agent by ID: a1")
},
}
@@ -783,29 +783,26 @@ func (f *fakeFileService) UploadFromURL(ctx context.Context, tenantID, rawURL st
// ----- Cross-cutting tests (criteria 24, 25, 26) -----
-// TestBotRoutes_RequireAuth covers criterion 24. Without a user
-// context (no `user` set by middleware), the handler should return
-// an error. We construct an engine that runs the routes WITHOUT the
-// fake-user middleware to assert GetUser() short-circuits with 401.
+// TestBotRoutes_RequireAuth covers criterion 24. The BetaAuthMiddleware
+// rejects requests without credentials before dispatching to the handlers.
func TestBotRoutes_RequireAuth(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
h := NewBotHandler(nil)
h.botService = &stubBotService{
- chatbotInfoFn: func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+ chatbotInfoFn: func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
t.Fatal("service should not be called when user is missing")
return "", "", "", "", false, common.CodeUnauthorized, nil
},
}
g := r.Group("/api/v1")
+ g.Use((&AuthHandler{}).BetaAuthMiddleware())
// Inline registration avoids the import cycle that
// RegisterChatbotRoutes would create (router -> handler).
chatbot := g.Group("/chatbots")
- chatbot.Use(func(c *gin.Context) { c.Next() })
chatbot.POST("/:dialog_id/completions", h.ChatbotCompletion)
chatbot.GET("/:dialog_id/info", h.ChatbotInfo)
agentbot := g.Group("/agentbots")
- agentbot.Use(func(c *gin.Context) { c.Next() })
agentbot.POST("/:agent_id/completions", h.AgentbotCompletion)
agentbot.GET("/:agent_id/inputs", h.AgentbotInputs)
cases := []struct {
@@ -823,10 +820,10 @@ func TestBotRoutes_RequireAuth(t *testing.T) {
Message string `json:"message"`
}
_ = json.Unmarshal(w.Body.Bytes(), &resp)
- if resp.Code != 401 {
- t.Errorf("%s %s: code = %d, want 401; body = %s", tc.method, tc.path, resp.Code, w.Body.String())
+ if resp.Code != int(common.CodeDataError) {
+ t.Errorf("%s %s: code = %d, want %d; body = %s", tc.method, tc.path, resp.Code, common.CodeDataError, w.Body.String())
}
- if !strings.Contains(resp.Message, "User not found") && !strings.Contains(resp.Message, "Authorization") {
+ if resp.Message != "Authorization is not valid!" {
t.Errorf("%s %s: message = %q, want auth error", tc.method, tc.path, resp.Message)
}
}
@@ -973,7 +970,7 @@ func TestBotRoutes_NoRegularAuthRequired(t *testing.T) {
ah := &AuthHandler{userService: stub}
h := NewBotHandler(nil)
h.botService = &stubBotService{
- chatbotInfoFn: func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+ chatbotInfoFn: func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
return "Bot", "", "", "gpt-4", false, common.CodeSuccess, nil
},
}
@@ -1157,7 +1154,7 @@ func parseBotSSEFrames(t *testing.T, body []byte) []string {
// TestChatbotInfo_DialogNotFound pins the DAO miss path.
func TestChatbotInfo_DialogNotFound(t *testing.T) {
stub := &stubBotService{
- chatbotInfoFn: func(ctx context.Context, tenantID, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
+ chatbotInfoFn: func(ctx context.Context, dialogID string) (string, string, string, string, bool, common.ErrorCode, error) {
return "", "", "", "", false, common.CodeDataError, errors.New("dialog not found")
},
}
@@ -1245,6 +1242,7 @@ func TestGetAgentbotLogs_AllowsUnboundTokenForAccessibleAgent(t *testing.T) {
c, _ := gin.CreateTestContext(w)
c.Request = httptest.NewRequest("GET",
"/api/v1/agentbots/agent-a/logs/msg-1", nil)
+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "u1", ""))
c.Set("user", &entity.User{ID: "u1"})
c.Params = gin.Params{
{Key: "agent_id", Value: "agent-a"},
@@ -1252,9 +1250,9 @@ func TestGetAgentbotLogs_AllowsUnboundTokenForAccessibleAgent(t *testing.T) {
}
h := NewBotHandler(nil)
- h.botService = &stubBotService{agentbotLogsFn: func(_ context.Context, tenantID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
- if tenantID != "u1" || agentID != "agent-a" || messageID != "msg-1" {
- t.Fatalf("logs arguments = (%q, %q, %q)", tenantID, agentID, messageID)
+ h.botService = &stubBotService{agentbotLogsFn: func(ctx context.Context, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
+ if permission.UserIDFromContext(ctx) != "u1" || agentID != "agent-a" || messageID != "msg-1" {
+ t.Fatalf("logs identity/arguments = (%q, %q, %q)", permission.UserIDFromContext(ctx), agentID, messageID)
}
return map[string]any{"events": []any{}}, common.CodeSuccess, nil
}}
@@ -1283,7 +1281,7 @@ func TestGetAgentbotLogs_AllowsMatchingBoundAgent(t *testing.T) {
}
h := NewBotHandler(nil)
- h.botService = &stubBotService{agentbotLogsFn: func(_ context.Context, tenantID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
+ h.botService = &stubBotService{agentbotLogsFn: func(_ context.Context, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
return map[string]any{"events": []any{}}, common.CodeSuccess, nil
}}
h.GetAgentbotLogs(c)
@@ -1310,7 +1308,7 @@ func TestGetAgentbotLogs_DeniesMismatchedBoundAgent(t *testing.T) {
}
h := NewBotHandler(nil)
- h.botService = &stubBotService{agentbotLogsFn: func(context.Context, string, string, string) (map[string]any, common.ErrorCode, error) {
+ h.botService = &stubBotService{agentbotLogsFn: func(context.Context, string, string) (map[string]any, common.ErrorCode, error) {
t.Fatal("AgentbotLogs should not be called for a mismatched bound agent")
return nil, common.CodeServerError, errors.New("unexpected call")
}}
@@ -1342,7 +1340,7 @@ func TestGetAgentbotLogs_DeniesInaccessibleAgent(t *testing.T) {
}
h := NewBotHandler(nil)
- h.botService = &stubBotService{agentbotLogsFn: func(context.Context, string, string, string) (map[string]any, common.ErrorCode, error) {
+ h.botService = &stubBotService{agentbotLogsFn: func(context.Context, string, string) (map[string]any, common.ErrorCode, error) {
return nil, common.CodeDataError, errors.New("can't find agent by ID: agent-b")
}}
h.GetAgentbotLogs(c)
diff --git a/internal/handler/chat.go b/internal/handler/chat.go
index efed077a8b..37685129af 100644
--- a/internal/handler/chat.go
+++ b/internal/handler/chat.go
@@ -71,13 +71,6 @@ type ChatMindMapRequest struct {
// @Success 200 {object} service.ListChatsResponse
// @Router /api/v1/chats [get]
func (h *ChatHandler) ListChats(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
- userID := user.ID
-
// Parse query parameters
keywords := c.Query("keywords")
// Exact id and name filters take precedence over the fuzzy keyword
@@ -125,7 +118,7 @@ func (h *ChatHandler) ListChats(c *gin.Context) {
ctx := c.Request.Context()
// List chats - default to valid status "1" (same as Python StatusEnum.VALID.value)
- result, err := h.chatService.ListChats(ctx, userID, "1", keywords, id, name, page, pageSize, terms, ownerIDs)
+ result, err := h.chatService.ListChats(ctx, "1", keywords, id, name, page, pageSize, terms, ownerIDs)
if err != nil {
if respondPermissionErrorIf(c, err, false) {
return
@@ -154,12 +147,6 @@ func (h *ChatHandler) Create(c *gin.Context) {
return
}
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
var req map[string]interface{}
decoder := json.NewDecoder(c.Request.Body)
decoder.UseNumber()
@@ -172,7 +159,7 @@ func (h *ChatHandler) Create(c *gin.Context) {
}
ctx := c.Request.Context()
- result, code, err := h.chatService.Create(ctx, user.ID, req)
+ result, code, err := h.chatService.Create(ctx, req)
if err != nil {
common.RespondError(c, code, err.Error())
return
@@ -189,11 +176,6 @@ func (h *ChatHandler) Create(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/chat/mindmap [post]
func (h *ChatHandler) MindMap(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
var req ChatMindMapRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -252,13 +234,6 @@ func (h *ChatHandler) MindMap(c *gin.Context) {
}
func (h *ChatHandler) DeleteChat(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
- userID := user.ID
-
chatID := c.Param("chat_id")
if chatID == "" {
common.Respond(c, http.StatusBadRequest, common.CodeBadRequest, nil, "chat_id is required")
@@ -266,7 +241,7 @@ func (h *ChatHandler) DeleteChat(c *gin.Context) {
}
ctx := c.Request.Context()
- if err := h.chatService.DeleteChat(ctx, userID, chatID); err != nil {
+ if err := h.chatService.DeleteChat(ctx, chatID); err != nil {
if respondPermissionErrorIf(c, err, true) {
return
}
@@ -279,12 +254,6 @@ func (h *ChatHandler) DeleteChat(c *gin.Context) {
// BulkDeleteChats soft deletes multiple chats owned by the current user.
func (h *ChatHandler) BulkDeleteChats(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
- userID := user.ID
if c.Request.Body == nil || c.Request.ContentLength == 0 {
common.RespondSuccess(c, map[string]interface{}{}, "success")
return
@@ -299,7 +268,7 @@ func (h *ChatHandler) BulkDeleteChats(c *gin.Context) {
ctx := c.Request.Context()
if len(req.IDs) == 0 && !req.DeleteAll {
if req.ChatID != "" {
- if err := h.chatService.DeleteChat(ctx, userID, req.ChatID); err != nil {
+ if err := h.chatService.DeleteChat(ctx, req.ChatID); err != nil {
if respondPermissionErrorIf(c, err, true) {
return
}
@@ -315,7 +284,7 @@ func (h *ChatHandler) BulkDeleteChats(c *gin.Context) {
return
}
- result, err := h.chatService.BulkDeleteChats(ctx, userID, &req)
+ result, err := h.chatService.BulkDeleteChats(ctx, &req)
if err != nil {
common.RespondError(c, common.CodeDataError, err.Error())
return
@@ -342,14 +311,6 @@ func (h *ChatHandler) BulkDeleteChats(c *gin.Context) {
// Python implementation details:
// - Route: @manager.route("/chats/<chat_id>", methods=["GET"])
func (h *ChatHandler) GetChat(c *gin.Context) {
- // Get current user from context (same as Python current_user)
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
- userID := user.ID
-
// Get chat_id from path parameter (same as Python <chat_id>)
chatID := c.Param("chat_id")
if chatID == "" {
@@ -359,7 +320,7 @@ func (h *ChatHandler) GetChat(c *gin.Context) {
// Get chat detail with permission check
ctx := c.Request.Context()
- chat, err := h.chatService.GetChat(ctx, userID, chatID)
+ chat, err := h.chatService.GetChat(ctx, chatID)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -411,17 +372,12 @@ func (h *ChatHandler) GetChat(c *gin.Context) {
// GetAgenticRAGConfig returns defaults and effective Agentic RAG settings.
func (h *ChatHandler) GetAgenticRAGConfig(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
chatID := c.Param("chat_id")
if chatID == "" {
common.Respond(c, http.StatusBadRequest, common.CodeBadRequest, nil, "chat_id is required")
return
}
- settings, err := h.chatService.GetAgenticRAGConfig(c.Request.Context(), user.ID, chatID)
+ settings, err := h.chatService.GetAgenticRAGConfig(c.Request.Context(), chatID)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -443,12 +399,6 @@ func (h *ChatHandler) PatchChat(c *gin.Context) {
}
func (h *ChatHandler) updateChatByMethod(c *gin.Context, patch bool) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
chatID := c.Param("chat_id")
if chatID == "" {
common.RespondError(c, common.CodeBadRequest, "chat_id is required")
@@ -465,9 +415,9 @@ func (h *ChatHandler) updateChatByMethod(c *gin.Context, patch bool) {
var err error
ctx := c.Request.Context()
if patch {
- result, err = h.chatService.PatchChat(ctx, user.ID, chatID, req)
+ result, err = h.chatService.PatchChat(ctx, chatID, req)
} else {
- result, err = h.chatService.UpdateChat(ctx, user.ID, chatID, req)
+ result, err = h.chatService.UpdateChat(ctx, chatID, req)
}
if err != nil {
if respondPermissionErrorIf(c, err, false) {
diff --git a/internal/handler/chat_channel.go b/internal/handler/chat_channel.go
index fd45d15939..0eed41658a 100644
--- a/internal/handler/chat_channel.go
+++ b/internal/handler/chat_channel.go
@@ -26,12 +26,12 @@ import (
)
type ChatChannelService interface {
- CreateChatChannel(ctx context.Context, userID, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error)
- List(ctx context.Context, userID string) ([]*entity.ChatChannelListResponse, error)
- GetChatChannel(ctx context.Context, userID, channelID string) (*entity.ChatChannel, common.ErrorCode, error)
- UpdateChatChannel(ctx context.Context, userID, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error)
- GetChatChannelRuntime(ctx context.Context, userID, channelID string) (map[string]any, common.ErrorCode, error)
- DeleteChatChannel(ctx context.Context, userID, channelID string) (bool, common.ErrorCode, error)
+ CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error)
+ List(ctx context.Context) ([]*entity.ChatChannelListResponse, error)
+ GetChatChannel(ctx context.Context, channelID string) (*entity.ChatChannel, common.ErrorCode, error)
+ UpdateChatChannel(ctx context.Context, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error)
+ GetChatChannelRuntime(ctx context.Context, channelID string) (map[string]any, common.ErrorCode, error)
+ DeleteChatChannel(ctx context.Context, channelID string) (bool, common.ErrorCode, error)
}
type ChatChannelHandler struct {
@@ -56,12 +56,6 @@ type CreateChatChannelRequest struct {
// CreateChatChannel handles POST /chat-channels.
func (h *ChatChannelHandler) CreateChatChannel(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
var req CreateChatChannelRequest
if err := c.ShouldBindJSON(&req); err != nil {
common.RespondError(c, common.CodeDataError, "Invalid request: "+err.Error())
@@ -75,7 +69,6 @@ func (h *ChatChannelHandler) CreateChatChannel(c *gin.Context) {
row, err := h.chatChannelService.CreateChatChannel(
ctx,
- user.ID,
req.Name,
req.Channel,
req.Config,
@@ -93,14 +86,8 @@ func (h *ChatChannelHandler) CreateChatChannel(c *gin.Context) {
// ListChatChannel handles GET /chat-channels.
func (h *ChatChannelHandler) ListChatChannel(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
ctx := c.Request.Context()
- rows, err := h.chatChannelService.List(ctx, user.ID)
+ rows, err := h.chatChannelService.List(ctx)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -113,18 +100,6 @@ func (h *ChatChannelHandler) ListChatChannel(c *gin.Context) {
// GetChatChannel handles GET /chat-channels/:channel_id.
func (h *ChatChannelHandler) GetChatChannel(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := strings.TrimSpace(user.ID)
- if userID == "" {
- common.RespondError(c, common.CodeArgumentError, "user_id is required")
- return
- }
-
channelID := strings.TrimSpace(c.Param("channel_id"))
if channelID == "" {
common.RespondError(c, common.CodeArgumentError, "channel_id is required")
@@ -132,7 +107,7 @@ func (h *ChatChannelHandler) GetChatChannel(c *gin.Context) {
}
ctx := c.Request.Context()
- channel, code, err := h.chatChannelService.GetChatChannel(ctx, userID, channelID)
+ channel, code, err := h.chatChannelService.GetChatChannel(ctx, channelID)
if code != common.CodeSuccess || err != nil {
writeChatChannelError(c, code, chatChannelErrMsg(code, err))
return
@@ -143,18 +118,6 @@ func (h *ChatChannelHandler) GetChatChannel(c *gin.Context) {
// UpdateChatChannel handles PATCH /chat-channels/:channel_id.
func (h *ChatChannelHandler) UpdateChatChannel(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := strings.TrimSpace(user.ID)
- if userID == "" {
- common.RespondError(c, common.CodeArgumentError, "user_id is required")
- return
- }
-
channelID := strings.TrimSpace(c.Param("channel_id"))
if channelID == "" {
common.RespondError(c, common.CodeArgumentError, "channel_id is required")
@@ -168,7 +131,7 @@ func (h *ChatChannelHandler) UpdateChatChannel(c *gin.Context) {
}
ctx := c.Request.Context()
- result, code, err := h.chatChannelService.UpdateChatChannel(ctx, userID, channelID, unwrapChatChannelPayload(request))
+ result, code, err := h.chatChannelService.UpdateChatChannel(ctx, channelID, unwrapChatChannelPayload(request))
if code != common.CodeSuccess || err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -182,18 +145,6 @@ func (h *ChatChannelHandler) UpdateChatChannel(c *gin.Context) {
// GetChatChannelRuntime returns live runtime metadata for a running chat channel.
func (h *ChatChannelHandler) GetChatChannelRuntime(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := strings.TrimSpace(user.ID)
- if userID == "" {
- common.RespondError(c, common.CodeArgumentError, "user_id is required")
- return
- }
-
channelID := strings.TrimSpace(c.Param("channel_id"))
if channelID == "" {
common.RespondError(c, common.CodeArgumentError, "channel_id is required")
@@ -201,7 +152,7 @@ func (h *ChatChannelHandler) GetChatChannelRuntime(c *gin.Context) {
}
ctx := c.Request.Context()
- result, code, err := h.chatChannelService.GetChatChannelRuntime(ctx, userID, channelID)
+ result, code, err := h.chatChannelService.GetChatChannelRuntime(ctx, channelID)
if code != common.CodeSuccess || err != nil {
writeChatChannelError(c, code, chatChannelErrMsg(code, err))
return
@@ -211,18 +162,6 @@ func (h *ChatChannelHandler) GetChatChannelRuntime(c *gin.Context) {
// DeleteChatChannel handles DELETE /chat-channels/:channel_id.
func (h *ChatChannelHandler) DeleteChatChannel(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := strings.TrimSpace(user.ID)
- if userID == "" {
- common.RespondError(c, common.CodeArgumentError, "user_id is required")
- return
- }
-
channelID := strings.TrimSpace(c.Param("channel_id"))
if channelID == "" {
common.RespondError(c, common.CodeArgumentError, "channel_id is required")
@@ -230,7 +169,7 @@ func (h *ChatChannelHandler) DeleteChatChannel(c *gin.Context) {
}
ctx := c.Request.Context()
- _, code, err := h.chatChannelService.DeleteChatChannel(ctx, userID, channelID)
+ _, code, err := h.chatChannelService.DeleteChatChannel(ctx, channelID)
if code != common.CodeSuccess || err != nil {
writeChatChannelError(c, code, chatChannelErrMsg(code, err))
return
diff --git a/internal/handler/chat_channel_test.go b/internal/handler/chat_channel_test.go
index 8014980ebe..8ee12a3008 100644
--- a/internal/handler/chat_channel_test.go
+++ b/internal/handler/chat_channel_test.go
@@ -13,57 +13,62 @@ import (
"ragflow/internal/common"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
)
type fakeChatChannelService struct {
- createFn func(tenantID, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error)
- listFn func(tenantID string) ([]*entity.ChatChannelListResponse, error)
- getFn func(userID, channelID string) (*entity.ChatChannel, common.ErrorCode, error)
- updateFn func(userID, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error)
- runtimeFn func(userID, channelID string) (map[string]any, common.ErrorCode, error)
- deleteFn func(userID, channelID string) (bool, common.ErrorCode, error)
+ createFn func(context.Context, string, string, entity.JSONMap, *string) (*entity.ChatChannel, error)
+ listFn func(context.Context) ([]*entity.ChatChannelListResponse, error)
+ getFn func(context.Context, string) (*entity.ChatChannel, common.ErrorCode, error)
+ updateFn func(context.Context, string, map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error)
+ runtimeFn func(context.Context, string) (map[string]any, common.ErrorCode, error)
+ deleteFn func(context.Context, string) (bool, common.ErrorCode, error)
}
-func (f fakeChatChannelService) CreateChatChannel(ctx context.Context, tenantID, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
+func (f fakeChatChannelService) CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
if f.createFn == nil {
return nil, errors.New("unexpected CreateChatChannel call")
}
- return f.createFn(tenantID, name, channelType, config, chatID)
+ return f.createFn(ctx, name, channelType, config, chatID)
}
-func (f fakeChatChannelService) List(ctx context.Context, tenantID string) ([]*entity.ChatChannelListResponse, error) {
+func (f fakeChatChannelService) List(ctx context.Context) ([]*entity.ChatChannelListResponse, error) {
if f.listFn == nil {
return nil, errors.New("unexpected List call")
}
- return f.listFn(tenantID)
+ return f.listFn(ctx)
}
-func (f fakeChatChannelService) GetChatChannel(ctx context.Context, userID, channelID string) (*entity.ChatChannel, common.ErrorCode, error) {
+func (f fakeChatChannelService) GetChatChannel(ctx context.Context, channelID string) (*entity.ChatChannel, common.ErrorCode, error) {
if f.getFn == nil {
return nil, common.CodeServerError, errors.New("unexpected GetChatChannel call")
}
- return f.getFn(userID, channelID)
+ return f.getFn(ctx, channelID)
}
-func (f fakeChatChannelService) UpdateChatChannel(ctx context.Context, userID, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error) {
+func (f fakeChatChannelService) UpdateChatChannel(ctx context.Context, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error) {
if f.updateFn == nil {
return nil, common.CodeServerError, errors.New("unexpected UpdateChatChannel call")
}
- return f.updateFn(userID, channelID, req)
+ return f.updateFn(ctx, channelID, req)
}
-func (f fakeChatChannelService) GetChatChannelRuntime(ctx context.Context, userID, channelID string) (map[string]any, common.ErrorCode, error) {
+func (f fakeChatChannelService) GetChatChannelRuntime(ctx context.Context, channelID string) (map[string]any, common.ErrorCode, error) {
if f.runtimeFn == nil {
return nil, common.CodeServerError, errors.New("unexpected GetChatChannelRuntime call")
}
- return f.runtimeFn(userID, channelID)
+ return f.runtimeFn(ctx, channelID)
}
-func (f fakeChatChannelService) DeleteChatChannel(ctx context.Context, userID, channelID string) (bool, common.ErrorCode, error) {
+func (f fakeChatChannelService) DeleteChatChannel(ctx context.Context, channelID string) (bool, common.ErrorCode, error) {
if f.deleteFn == nil {
return false, common.CodeServerError, errors.New("unexpected DeleteChatChannel call")
}
- return f.deleteFn(userID, channelID)
+ return f.deleteFn(ctx, channelID)
+}
+
+func setChatChannelHandlerIdentity(c *gin.Context) {
+ c.Request = c.Request.WithContext(permission.WithIdentity(c.Request.Context(), "tenant-1", "tenant-1"))
}
func TestChatChannelHandlerCreateSuccess(t *testing.T) {
@@ -75,15 +80,15 @@ func TestChatChannelHandlerCreateSuccess(t *testing.T) {
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- createFn: func(tenantID, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
- gotTenantID = tenantID
+ createFn: func(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
+ gotTenantID = permission.TenantIDFromContext(ctx)
gotName = name
gotChannel = channelType
gotConfig = config
gotChatID = chatID
return &entity.ChatChannel{
ID: "cc-1",
- TenantID: tenantID,
+ TenantID: permission.TenantIDFromContext(ctx),
Name: name,
Channel: channelType,
Config: config,
@@ -96,7 +101,7 @@ func TestChatChannelHandlerCreateSuccess(t *testing.T) {
router := gin.New()
router.POST("/api/v1/chat-channels", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.CreateChatChannel(c)
})
@@ -135,7 +140,7 @@ func TestChatChannelHandlerCreateInvalidRequestStopsEarly(t *testing.T) {
called := false
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- createFn: func(tenantID, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
+ createFn: func(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
called = true
return nil, nil
},
@@ -144,7 +149,7 @@ func TestChatChannelHandlerCreateInvalidRequestStopsEarly(t *testing.T) {
router := gin.New()
router.POST("/api/v1/chat-channels", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.CreateChatChannel(c)
})
@@ -172,8 +177,8 @@ func TestChatChannelHandlerListSuccess(t *testing.T) {
gotTenantID := ""
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- listFn: func(tenantID string) ([]*entity.ChatChannelListResponse, error) {
- gotTenantID = tenantID
+ listFn: func(ctx context.Context) ([]*entity.ChatChannelListResponse, error) {
+ gotTenantID = permission.TenantIDFromContext(ctx)
return []*entity.ChatChannelListResponse{
{ID: "cc-1", Name: "bot-a", Channel: "dingtalk", Status: 1},
}, nil
@@ -183,7 +188,7 @@ func TestChatChannelHandlerListSuccess(t *testing.T) {
router := gin.New()
router.GET("/api/v1/chat-channels", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.ListChatChannel(c)
})
@@ -209,7 +214,7 @@ func TestChatChannelHandlerListServiceError(t *testing.T) {
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- listFn: func(tenantID string) ([]*entity.ChatChannelListResponse, error) {
+ listFn: func(ctx context.Context) ([]*entity.ChatChannelListResponse, error) {
return nil, errors.New("db failed")
},
},
@@ -217,7 +222,7 @@ func TestChatChannelHandlerListServiceError(t *testing.T) {
router := gin.New()
router.GET("/api/v1/chat-channels", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.ListChatChannel(c)
})
@@ -239,7 +244,7 @@ func TestChatChannelHandlerGetChatChannelHidesPermissionDenial(t *testing.T) {
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- getFn: func(userID, channelID string) (*entity.ChatChannel, common.ErrorCode, error) {
+ getFn: func(ctx context.Context, channelID string) (*entity.ChatChannel, common.ErrorCode, error) {
return nil, common.CodeNotFound, errors.New("Resource not found")
},
},
@@ -247,7 +252,7 @@ func TestChatChannelHandlerGetChatChannelHidesPermissionDenial(t *testing.T) {
router := gin.New()
router.GET("/api/v1/chat-channels/:channel_id", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.GetChatChannel(c)
})
@@ -273,16 +278,16 @@ func TestChatChannelHandlerUpdateChatChannelUnwrapsData(t *testing.T) {
var gotReq map[string]interface{}
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- updateFn: func(userID, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error) {
+ updateFn: func(ctx context.Context, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error) {
gotReq = req
- return &entity.ChatChannel{ID: channelID, TenantID: userID, Name: "new-name"}, common.CodeSuccess, nil
+ return &entity.ChatChannel{ID: channelID, TenantID: permission.TenantIDFromContext(ctx), Name: "new-name"}, common.CodeSuccess, nil
},
},
}
router := gin.New()
router.PATCH("/api/v1/chat-channels/:channel_id", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.UpdateChatChannel(c)
})
@@ -302,8 +307,8 @@ func TestChatChannelHandlerDeleteChatChannelSuccess(t *testing.T) {
var gotUserID, gotChannelID string
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- deleteFn: func(userID, channelID string) (bool, common.ErrorCode, error) {
- gotUserID = userID
+ deleteFn: func(ctx context.Context, channelID string) (bool, common.ErrorCode, error) {
+ gotUserID = permission.UserIDFromContext(ctx)
gotChannelID = channelID
return true, common.CodeSuccess, nil
},
@@ -312,7 +317,7 @@ func TestChatChannelHandlerDeleteChatChannelSuccess(t *testing.T) {
router := gin.New()
router.DELETE("/api/v1/chat-channels/:channel_id", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.DeleteChatChannel(c)
})
@@ -342,8 +347,8 @@ func TestChatChannelHandlerGetRuntimeSuccess(t *testing.T) {
var gotUserID, gotChannelID string
h := &ChatChannelHandler{
chatChannelService: fakeChatChannelService{
- runtimeFn: func(userID, channelID string) (map[string]any, common.ErrorCode, error) {
- gotUserID = userID
+ runtimeFn: func(ctx context.Context, channelID string) (map[string]any, common.ErrorCode, error) {
+ gotUserID = permission.UserIDFromContext(ctx)
gotChannelID = channelID
return map[string]any{"status": "waiting"}, common.CodeSuccess, nil
},
@@ -352,7 +357,7 @@ func TestChatChannelHandlerGetRuntimeSuccess(t *testing.T) {
router := gin.New()
router.GET("/api/v1/chat-channels/:channel_id/runtime", func(c *gin.Context) {
- c.Set("user", &entity.User{ID: "tenant-1"})
+ setChatChannelHandlerIdentity(c)
h.GetChatChannelRuntime(c)
})
diff --git a/internal/handler/chat_recommendation.go b/internal/handler/chat_recommendation.go
index aa21b11bdf..b37d00080e 100644
--- a/internal/handler/chat_recommendation.go
+++ b/internal/handler/chat_recommendation.go
@@ -43,11 +43,6 @@ type ChatRecommendationRequest struct {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/chat/recommendation [post]
func (h *ChatHandler) Recommendation(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
var req ChatRecommendationRequest
if err := c.ShouldBindJSON(&req); err != nil {
diff --git a/internal/handler/chat_session.go b/internal/handler/chat_session.go
index f8cc33e79c..cd92cb9fd0 100644
--- a/internal/handler/chat_session.go
+++ b/internal/handler/chat_session.go
@@ -72,13 +72,6 @@ func sessionHistoryQuery(c *gin.Context) (dao.ConversationHistoryOptions, error)
// @Success 200 {object} service.ListChatSessionsResponse
// @Router /api/v1/chats/<chat_id>/sessions [get]
func (h *ChatSessionHandler) ListChatSessions(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
- userID := user.ID
-
// Get chat_id from query parameter
chatID := c.Param("chat_id")
if chatID == "" {
@@ -133,7 +126,7 @@ func (h *ChatSessionHandler) ListChatSessions(c *gin.Context) {
return
}
options.NoHistory = includeHistory == "false" || includeHistory == "False"
- result, err := h.chatSessionService.ListChatSessions(ctx, userID, chatID, c.Query("id"), c.Query("name"), c.Query("user_id"), terms, page, pageSize, options)
+ result, err := h.chatSessionService.ListChatSessions(ctx, chatID, c.Query("id"), c.Query("name"), c.Query("user_id"), terms, page, pageSize, options)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -179,13 +172,6 @@ type ChatCompletionsRequest struct {
// @Success 200 {string} text/event-stream "Streaming SSE response"
// @Router /api/v1/chat/completions [post]
func (h *ChatSessionHandler) ChatCompletions(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
- userID := user.ID
-
var rawBody map[string]interface{}
if err := c.ShouldBindJSON(&rawBody); err != nil {
common.RespondError(c, common.CodeBadRequest, err.Error())
@@ -281,7 +267,7 @@ func (h *ChatSessionHandler) ChatCompletions(c *gin.Context) {
go func() {
defer close(streamChan)
_, _ = h.chatSessionService.ChatCompletions(
- ctx, userID,
+ ctx,
req.ChatID, sessionID,
req.Messages, req.Question, req.Files,
req.LLMID, genConfig, kwargs,
@@ -312,7 +298,7 @@ func (h *ChatSessionHandler) ChatCompletions(c *gin.Context) {
clearResponseWriteDeadline(c)
var result map[string]interface{}
result, err = h.chatSessionService.ChatCompletions(
- c.Request.Context(), userID,
+ c.Request.Context(),
req.ChatID, sessionID,
req.Messages, req.Question, req.Files,
req.LLMID, genConfig, kwargs,
@@ -333,13 +319,6 @@ func (h *ChatSessionHandler) ChatCompletions(c *gin.Context) {
}
func (h *ChatSessionHandler) GetSession(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := user.ID
chatID, sessionID := c.Param("chat_id"), c.Param("session_id")
ctx := c.Request.Context()
@@ -348,7 +327,7 @@ func (h *ChatSessionHandler) GetSession(c *gin.Context) {
common.RespondError(c, common.CodeArgumentError, err.Error())
return
}
- result, code, err := h.chatSessionService.GetSession(ctx, userID, chatID, sessionID, options)
+ result, code, err := h.chatSessionService.GetSession(ctx, chatID, sessionID, options)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -361,18 +340,6 @@ func (h *ChatSessionHandler) GetSession(c *gin.Context) {
// CreateSession create a session in a dialog
func (h *ChatSessionHandler) CreateSession(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := strings.TrimSpace(user.ID)
- if userID == "" {
- common.RespondError(c, common.CodeBadRequest, "user_id is required")
- return
- }
-
chatID := strings.TrimSpace(c.Param("chat_id"))
if chatID == "" {
common.RespondError(c, common.CodeBadRequest, "chat_id is required")
@@ -394,7 +361,7 @@ func (h *ChatSessionHandler) CreateSession(c *gin.Context) {
}
ctx := c.Request.Context()
- result, code, err := h.chatSessionService.CreateSession(ctx, userID, chatID, req)
+ result, code, err := h.chatSessionService.CreateSession(ctx, chatID, req)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -408,24 +375,12 @@ func (h *ChatSessionHandler) CreateSession(c *gin.Context) {
// DeleteSessions delete a session in a dialog
func (h *ChatSessionHandler) DeleteSessions(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
chatID := strings.TrimSpace(c.Param("chat_id"))
if chatID == "" {
common.RespondError(c, common.CodeBadRequest, "chat_id is required")
return
}
- userID := strings.TrimSpace(user.ID)
- if userID == "" {
- common.RespondError(c, common.CodeBadRequest, "user_id is required")
- return
- }
-
req := map[string]interface{}{}
if err := json.NewDecoder(c.Request.Body).Decode(&req); err != nil {
if errors.Is(err, io.EOF) {
@@ -441,7 +396,7 @@ func (h *ChatSessionHandler) DeleteSessions(c *gin.Context) {
}
ctx := c.Request.Context()
- result, message, code, err := h.chatSessionService.DeleteSessions(ctx, userID, chatID, req)
+ result, message, code, err := h.chatSessionService.DeleteSessions(ctx, chatID, req)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -454,13 +409,6 @@ func (h *ChatSessionHandler) DeleteSessions(c *gin.Context) {
}
func (h *ChatSessionHandler) UpdateSession(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := user.ID
chatID, sessionID := c.Param("chat_id"), c.Param("session_id")
// An empty payload is a valid no-op (mirrors Python's update_session).
@@ -471,7 +419,7 @@ func (h *ChatSessionHandler) UpdateSession(c *gin.Context) {
}
ctx := c.Request.Context()
- result, code, err := h.chatSessionService.UpdateSession(ctx, userID, chatID, sessionID, req)
+ result, code, err := h.chatSessionService.UpdateSession(ctx, chatID, sessionID, req)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -483,16 +431,10 @@ func (h *ChatSessionHandler) UpdateSession(c *gin.Context) {
}
func (h *ChatSessionHandler) DeleteSessionMessage(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
- userID := user.ID
chatID, sessionID, msgID := c.Param("chat_id"), c.Param("session_id"), c.Param("msg_id")
ctx := c.Request.Context()
- result, code, err := h.chatSessionService.DeleteSessionMessage(ctx, userID, chatID, sessionID, msgID)
+ result, code, err := h.chatSessionService.DeleteSessionMessage(ctx, chatID, sessionID, msgID)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
@@ -504,13 +446,6 @@ func (h *ChatSessionHandler) DeleteSessionMessage(c *gin.Context) {
}
func (h *ChatSessionHandler) UpdateMessageFeedback(c *gin.Context) {
- user, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
- userID := user.ID
chatID, sessionID, msgID := c.Param("chat_id"), c.Param("session_id"), c.Param("msg_id")
req := map[string]interface{}{}
@@ -527,7 +462,7 @@ func (h *ChatSessionHandler) UpdateMessageFeedback(c *gin.Context) {
return
}
- result, code, err := h.chatSessionService.UpdateMessageFeedback(c.Request.Context(), userID, chatID, sessionID, msgID, req)
+ result, code, err := h.chatSessionService.UpdateMessageFeedback(c.Request.Context(), chatID, sessionID, msgID, req)
if err != nil {
if respondPermissionErrorIf(c, err, true) {
return
diff --git a/internal/handler/chat_session_test.go b/internal/handler/chat_session_test.go
index 94e7dd7995..75b8432116 100644
--- a/internal/handler/chat_session_test.go
+++ b/internal/handler/chat_session_test.go
@@ -9,6 +9,7 @@ import (
"ragflow/internal/common"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
"ragflow/internal/service"
"github.com/gin-gonic/gin"
@@ -127,6 +128,7 @@ func TestChatSessionHandlerChatCompletionsRejectsNonStringUserContent(t *testing
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/v1/chat/completions", strings.NewReader(`{"stream":false,"store_history_messages":false,"messages":[{"role":"user","content":{"type":"text","text":"probe"}}]}`))
ctx.Request.Header.Set("Content-Type", "application/json")
ctx.Set("user", &entity.User{ID: "user-1"})
+ ctx.Request = ctx.Request.WithContext(permission.WithIdentity(ctx.Request.Context(), "user-1", ""))
handler := NewChatSessionHandler(service.NewChatSessionService(), nil)
handler.ChatCompletions(ctx)
diff --git a/internal/handler/compilation_template.go b/internal/handler/compilation_template.go
index e599a47ac1..21919f5673 100644
--- a/internal/handler/compilation_template.go
+++ b/internal/handler/compilation_template.go
@@ -43,11 +43,6 @@ func NewCompilationTemplateHandler(svc *service.CompilationTemplateService) *Com
// @Success 200 {object} map[string]interface{}
// @Router /v1/compilation-templates/builtins [get]
func (h *CompilationTemplateHandler) ListBuiltins(c *gin.Context) {
- _, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
templates, err := h.compilationTemplateService.ListBuiltins(c.Request.Context())
if err != nil {
common.RespondError(c, common.CodeExceptionError, err.Error())
@@ -64,11 +59,6 @@ func (h *CompilationTemplateHandler) ListBuiltins(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /v1/compilation-templates/wiki-presets [get]
func (h *CompilationTemplateHandler) ListWikiPresets(c *gin.Context) {
- _, code, msg := GetUser(c)
- if code != common.CodeSuccess {
- common.RespondError(c, code, msg)
- return
- }
presets, err := h.compilationTemplateService.LoadWikiPresets()
if err != nil {
common.RespondError(c, common.CodeExceptionError, err.Error())
diff --git a/internal/handler/dataset.go b/internal/handler/dataset.go
index c25bf862a2..fb59e72ca3 100644
--- a/internal/handler/dataset.go
+++ b/internal/handler/dataset.go
@@ -1113,11 +1113,6 @@ func (h *DatasetsHandler) GetCompilationStatus(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/datasets/metadata/flattened [get]
func (h *DatasetsHandler) ListMetadataFlattened(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
datasetIDsStr := c.Query("dataset_ids")
if datasetIDsStr == "" {
diff --git a/internal/handler/document.go b/internal/handler/document.go
index 3e670733e3..67ebea2330 100644
--- a/internal/handler/document.go
+++ b/internal/handler/document.go
@@ -121,11 +121,6 @@ func NewDocumentHandler(documentService documentServiceIface, datasetService *da
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/documents/{id} [get]
func (h *DocumentHandler) GetDocumentByID(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
id := c.Param("id")
if id == "" {
@@ -224,11 +219,6 @@ func (h *DocumentHandler) GetDocumentImageForDocument(c *gin.Context) {
}
func (h *DocumentHandler) GetDocumentThumbnail(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
data, err := h.documentService.GetDocumentThumbnail(c.Request.Context(), c.Param("id"))
if err != nil {
common.RespondError(c, common.CodeDataError, "Image not found.")
@@ -297,11 +287,6 @@ func (h *DocumentHandler) GetDocumentArtifact(c *gin.Context) {
}
func (h *DocumentHandler) GetDocumentPreview(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
docID := c.Param("id")
@@ -353,11 +338,6 @@ func (h *DocumentHandler) GetDocumentPreview(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/documents/{id} [put]
func (h *DocumentHandler) UpdateDocument(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
id := c.Param("id")
if id == "" {
@@ -386,7 +366,7 @@ func (h *DocumentHandler) UpdateDocument(c *gin.Context) {
return
}
- if errorCode, err = h.documentService.UpdateDocument(ctx, id, &req); err != nil {
+ if errorCode, err := h.documentService.UpdateDocument(ctx, id, &req); err != nil {
if errorCode == common.CodeServerError {
common.Respond(c, http.StatusInternalServerError, errorCode, nil, err.Error())
} else {
@@ -408,11 +388,6 @@ func (h *DocumentHandler) UpdateDocument(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/documents/{id} [delete]
func (h *DocumentHandler) DeleteDocument(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
id := c.Param("id")
if id == "" {
@@ -1640,11 +1615,6 @@ func (h *DocumentHandler) StopParseDocuments(c *gin.Context) {
}
func (h *DocumentHandler) MetadataSummaryByDataset(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
datasetID := c.Param("dataset_id")
if datasetID == "" {
@@ -1848,11 +1818,6 @@ func (h *DocumentHandler) UpdateDocumentMetadatas(c *gin.Context) {
}
func (h *DocumentHandler) handleBatchUpdateDocumentMetadatas(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
datasetID := strings.TrimSpace(c.Param("dataset_id"))
if datasetID == "" {
diff --git a/internal/handler/file_commit.go b/internal/handler/file_commit.go
index bf199da92d..21a4e55da1 100644
--- a/internal/handler/file_commit.go
+++ b/internal/handler/file_commit.go
@@ -88,12 +88,6 @@ func CommitFolderResolver(h *FileCommitHandler, entityType, urlParam string) gin
return
}
ctx := c.Request.Context()
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- c.Abort()
- return
- }
// Authorize, not just existence: the commit surface exposes artifact
// contents and history, so it needs the same access check the dataset
// routes apply.
@@ -672,11 +666,6 @@ func (h *FileCommitHandler) GetCommitFileContent(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/workspace-files/{file_id}/versions [get]
func (h *FileCommitHandler) GetFileVersionHistory(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
fileID := c.Param("file_id")
if fileID == "" {
diff --git a/internal/handler/mcp_server.go b/internal/handler/mcp_server.go
index cfcfdf54a4..28f837eace 100644
--- a/internal/handler/mcp_server.go
+++ b/internal/handler/mcp_server.go
@@ -26,6 +26,7 @@ import (
"ragflow/internal/common"
"ragflow/internal/dao"
"ragflow/internal/mcp"
+ "ragflow/internal/permission"
"ragflow/internal/server/config"
"ragflow/internal/service"
dataset "ragflow/internal/service/dataset"
@@ -127,7 +128,13 @@ func mcpListDatasets(ctx context.Context, ds *dataset.DatasetService, userID str
// mcpListChats wraps ChatService.ListChats for the MCP tool handler,
// converting the typed response into a generic []map[string]interface{}.
func mcpListChats(ctx context.Context, chatService *service.ChatService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {
- resp, err := chatService.ListChats(ctx, userID, "1", "", "", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}}, nil)
+ contextUserID := permission.UserIDFromContext(ctx)
+ if contextUserID == "" {
+ ctx = permission.WithIdentity(ctx, userID, permission.TenantIDFromContext(ctx))
+ } else if contextUserID != userID {
+ return nil, 0, permission.ErrIdentityMismatch
+ }
+ resp, err := chatService.ListChats(ctx, "1", "", "", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}}, nil)
if err != nil {
return nil, 0, err
}
diff --git a/internal/handler/plugin.go b/internal/handler/plugin.go
index f3bce3d97b..7788e0dc08 100644
--- a/internal/handler/plugin.go
+++ b/internal/handler/plugin.go
@@ -46,10 +46,6 @@ func NewPluginHandler(pluginService *service.PluginService) *PluginHandler {
// @Success 200 {object} map[string]interface{}
// @Router /v1/plugin/tools [get]
func (h *PluginHandler) ListLLMTools(c *gin.Context) {
- if _, errorCode, errorMessage := GetUser(c); errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
common.RespondSuccessList(c, h.pluginService.ListLLMTools(), "success")
}
diff --git a/internal/handler/plugin_test.go b/internal/handler/plugin_test.go
index f29064bd87..2df8bdebfb 100644
--- a/internal/handler/plugin_test.go
+++ b/internal/handler/plugin_test.go
@@ -33,12 +33,16 @@ func newPluginRouter(authenticate bool) (*gin.Engine, *PluginHandler) {
gin.SetMode(gin.TestMode)
h := NewPluginHandler(service.NewPluginService())
r := gin.New()
- r.GET("/api/v1/plugin/tools", func(c *gin.Context) {
- if authenticate {
+ api := r.Group("/api/v1")
+ if authenticate {
+ api.Use(func(c *gin.Context) {
c.Set("user", &entity.User{ID: "tenant-1"})
- }
- h.ListLLMTools(c)
- })
+ c.Next()
+ })
+ } else {
+ api.Use((&AuthHandler{}).AuthMiddleware())
+ }
+ api.GET("/plugin/tools", h.ListLLMTools)
return r, h
}
diff --git a/internal/handler/search.go b/internal/handler/search.go
index aee46669f8..b6d5c992a4 100644
--- a/internal/handler/search.go
+++ b/internal/handler/search.go
@@ -85,11 +85,6 @@ func getOwnerIDs(c *gin.Context) []string {
// @Success 200 {object} service.ListSearchAppsResponse
// @Router /api/v1/searches [get]
func (h *SearchHandler) ListSearches(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
// Parse query parameters
keywords := c.Query("keywords")
@@ -168,13 +163,6 @@ func (h *SearchHandler) CreateSearch(c *gin.Context) {
return
}
- // Get current user from context (same as Python current_user)
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
// Parse request body (same as Python get_request_json())
var req CreateSearchRequest
if err = c.ShouldBindJSON(&req); err != nil {
@@ -209,13 +197,6 @@ func (h *SearchHandler) CreateSearch(c *gin.Context) {
// @Success 200 {object} entity.Search
// @Router /api/v1/searches/{search_id} [get]
func (h *SearchHandler) GetSearch(c *gin.Context) {
- // Get current user from context (same as Python current_user)
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
// Get search_id from path parameter (same as Python <search_id>)
searchID := c.Param("search_id")
if searchID == "" {
@@ -265,13 +246,6 @@ func (h *SearchHandler) GetSearch(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/searches/{search_id} [delete]
func (h *SearchHandler) DeleteSearch(c *gin.Context) {
- // Get current user from context (same as Python current_user)
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
// Get search_id from path parameter (same as Python <search_id>)
searchID := c.Param("search_id")
if searchID == "" {
@@ -305,13 +279,6 @@ func (h *SearchHandler) DeleteSearch(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/searches/{search_id} [put]
func (h *SearchHandler) UpdateSearch(c *gin.Context) {
- // Get current user from context (same as Python current_user)
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
-
// Get search_id from path parameter (same as Python <search_id>)
searchID := c.Param("search_id")
if searchID == "" {
@@ -376,11 +343,6 @@ func (h *SearchHandler) UpdateSearch(c *gin.Context) {
}
func (h *SearchHandler) Completion(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
var req service.SearchCompletionsRequest
if err := c.ShouldBindJSON(&req); err != nil {
diff --git a/internal/handler/searchbot.go b/internal/handler/searchbot.go
index 8b0b8d979b..03896dee99 100644
--- a/internal/handler/searchbot.go
+++ b/internal/handler/searchbot.go
@@ -131,11 +131,6 @@ func (h *SearchBotHandler) SetAskService(svc *service.AskService) { h.askSvc = s
// @Router /api/v1/searchbots/related-questions [post]
func (h *SearchBotHandler) Handle(c *gin.Context) {
ctx := c.Request.Context()
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
var req SearchBotRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -169,11 +164,6 @@ func (h *SearchBotHandler) Handle(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/searchbots/retrieval [post]
func (h *SearchBotHandler) RetrievalTest(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.Respond(c, http.StatusUnauthorized, errorCode, nil, errorMessage)
- return
- }
var req SearchBotRetrievalTestRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -234,11 +224,6 @@ func (h *SearchBotHandler) RetrievalTest(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/searchbots/ask [post]
func (h *SearchBotHandler) Ask(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
var req SearchBotAskRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -360,11 +345,6 @@ func (h *SearchBotHandler) Ask(c *gin.Context) {
// @Success 200 {object} map[string]interface{}
// @Router /api/v1/searchbots/mindmap [post]
func (h *SearchBotHandler) MindMap(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
var req SearchBotMindMapRequest
if err := c.ShouldBindJSON(&req); err != nil {
diff --git a/internal/handler/searchbot_test.go b/internal/handler/searchbot_test.go
index 320b6b0aca..5a873394d3 100644
--- a/internal/handler/searchbot_test.go
+++ b/internal/handler/searchbot_test.go
@@ -145,18 +145,27 @@ func TestSearchBotsRetrieval_MissingQuestion(t *testing.T) {
}
}
-func TestSearchBotsRetrieval_NoAuth(t *testing.T) {
+func TestSearchBotsRetrieval_Unauthenticated(t *testing.T) {
h := NewSearchBotHandler(nil, nil, nil, &mockChunkService{})
gin.SetMode(gin.TestMode)
r := gin.New()
- r.POST("/api/v1/searchbots/retrieval", h.RetrievalTest)
+ api := r.Group("/api/v1")
+ api.Use((&AuthHandler{}).BetaAuthMiddleware())
+ api.POST("/searchbots/retrieval", h.RetrievalTest)
w := httptest.NewRecorder()
body := `{"kb_ids": ["kb1"], "question": "test"}`
req, _ := http.NewRequest("POST", "/api/v1/searchbots/retrieval", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
r.ServeHTTP(w, req)
- if w.Code != http.StatusUnauthorized {
- t.Errorf("expected 401, got %d", w.Code)
+ if w.Code != http.StatusOK {
+ t.Fatalf("expected BetaAuthMiddleware response status 200, got %d", w.Code)
+ }
+ var resp map[string]interface{}
+ if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("failed to unmarshal response: %v", err)
+ }
+ if resp["code"] != float64(common.CodeDataError) {
+ t.Errorf("expected BetaAuthMiddleware auth error code %d, got %v", common.CodeDataError, resp["code"])
}
}
diff --git a/internal/handler/system.go b/internal/handler/system.go
index 3bdc2d3bc8..f385ff69c9 100644
--- a/internal/handler/system.go
+++ b/internal/handler/system.go
@@ -86,11 +86,6 @@ func (h *SystemHandler) GetConfig(c *gin.Context) {
// GetStatus get RAGFlow status
func (h *SystemHandler) GetStatus(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
ctx := c.Request.Context()
status, err := h.systemService.GetStatus(ctx)
diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go
index e8d49ae91c..fe40a2bbdd 100644
--- a/internal/handler/tenant.go
+++ b/internal/handler/tenant.go
@@ -263,11 +263,6 @@ type CreateChunkTableRequest struct {
// @Success 200 {object} map[string]interface{}
// @Router /v1/tenant/chunk-store [post]
func (h *TenantHandler) CreateChunkStore(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
var req CreateChunkTableRequest
if err := c.ShouldBindJSON(&req); err != nil {
@@ -311,11 +306,6 @@ type DeleteChunkTableRequest struct {
// @Success 200 {object} map[string]interface{}
// @Router /v1/tenant/chunk-store [delete]
func (h *TenantHandler) DeleteChunkStore(c *gin.Context) {
- _, errorCode, errorMessage := GetUser(c)
- if errorCode != common.CodeSuccess {
- common.RespondError(c, errorCode, errorMessage)
- return
- }
ctx := c.Request.Context()
var req DeleteChunkTableRequest
diff --git a/internal/router/agent_routes_test.go b/internal/router/agent_routes_test.go
index acbeec1c67..2b8e995bc0 100644
--- a/internal/router/agent_routes_test.go
+++ b/internal/router/agent_routes_test.go
@@ -39,6 +39,9 @@ import (
func TestAgentRoutesRegistered(t *testing.T) {
eng := gin.New()
g := eng.Group("/api/v1/agents")
+ g.Use(func(c *gin.Context) {
+ c.AbortWithStatus(http.StatusUnauthorized)
+ })
RegisterAgentRoutes(g, &handler.AgentHandler{})
cases := []struct {
@@ -67,10 +70,10 @@ func TestAgentRoutesRegistered(t *testing.T) {
w := httptest.NewRecorder()
req := httptest.NewRequest(c.method, c.path, nil)
eng.ServeHTTP(w, req)
- // The handler dereferences a nil AgentService so a non-404 here
- // would panic; what we care about is "not NoRoute 404".
- if w.Code == http.StatusNotFound {
- t.Errorf("route %s %s returned 404 — RegisterAgentRoutes did not wire it", c.method, c.path)
+ // The auth middleware stops the request before handler dependencies
+ // are reached. Registered routes return 401; unmatched routes return 404.
+ if w.Code != http.StatusUnauthorized {
+ t.Errorf("route %s %s returned %d, want %d", c.method, c.path, w.Code, http.StatusUnauthorized)
}
}
}
diff --git a/internal/service/agent.go b/internal/service/agent.go
index 4461de6597..794defd059 100644
--- a/internal/service/agent.go
+++ b/internal/service/agent.go
@@ -71,10 +71,8 @@ type webhookPayloadKey struct{}
// Mirrors python: api/apps/restful_apis/agent_api.py:1570
// (`UserCanvasService.get_by_id(agent_id)`), with the same IDOR guard
// the chat handler uses.
-func (s *AgentService) LoadCanvasByID(
- ctx context.Context, userID, canvasID string,
-) (*entity.UserCanvas, error) {
- return s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead)
+func (s *AgentService) LoadCanvasByID(ctx context.Context, canvasID string) (*entity.UserCanvas, error) {
+ return s.loadCanvasForUser(ctx, canvasID, permission.OperationRead)
}
// RunAgentWithWebhook is a thin wrapper over RunAgent that attaches the
@@ -88,12 +86,12 @@ func (s *AgentService) LoadCanvasByID(
// Mirrors python: api/apps/restful_apis/agent_api.py:2125
// (`canvas.run(..., webhook_payload=clean_request)`).
func (s *AgentService) RunAgentWithWebhook(
- ctx context.Context, userID, canvasID string, payload map[string]any,
+ ctx context.Context, canvasID string, payload map[string]any,
) (<-chan canvas.RunEvent, error) {
if payload != nil {
ctx = context.WithValue(ctx, webhookPayloadKey{}, payload)
}
- return s.RunAgent(ctx, userID, canvasID, AgentSessionIDFromContext(ctx), "", "", nil)
+ return s.RunAgent(ctx, canvasID, AgentSessionIDFromContext(ctx), "", "", nil)
}
type agentSessionIDContextKey struct{}
@@ -503,9 +501,10 @@ type AgentFiltersResponse struct {
// agent_api.list_agents. A non-empty canvasCategory scopes the owner counts
// to one tab: canvas categories aggregate only that category's canvases,
// while CompilationTemplateGroupCategory reports the tenant's groups.
-func (s *AgentService) ListAgentFilters(ctx context.Context, userID, canvasCategory string) (*AgentFiltersResponse, common.ErrorCode, error) {
+func (s *AgentService) ListAgentFilters(ctx context.Context, canvasCategory string) (*AgentFiltersResponse, common.ErrorCode, error) {
+ userID := permission.UserIDFromContext(ctx)
if canvasCategory == CompilationTemplateGroupCategory {
- return s.listCompilationGroupFilters(ctx, userID)
+ return s.listCompilationGroupFilters(ctx)
}
canvasScope, err := permission.NewDatabaseChecker(dao.DB).Scope(ctx, permission.ScopeQuery{
@@ -586,7 +585,8 @@ func (s *AgentService) ListAgentFilters(ctx context.Context, userID, canvasCateg
// listCompilationGroupFilters reports the tenant's compilation template groups
// as the only owner/category option: groups are tenant-owned and carry neither
// canvas categories nor per-canvas owners.
-func (s *AgentService) listCompilationGroupFilters(ctx context.Context, userID string) (*AgentFiltersResponse, common.ErrorCode, error) {
+func (s *AgentService) listCompilationGroupFilters(ctx context.Context) (*AgentFiltersResponse, common.ErrorCode, error) {
+ userID := permission.UserIDFromContext(ctx)
groupCount, err := s.compilationTemplateGroupDAO.CountSavedByTenant(ctx, dao.DB, userID)
if err != nil {
return nil, common.CodeServerError, fmt.Errorf("failed to count compilation template groups: %w", err)
@@ -638,10 +638,11 @@ func toAgentItem(c *dao.UserCanvasListItem) *AgentItem {
}
}
-// ListAgents returns agent canvases visible to userID.
+// ListAgents returns agent canvases visible to the authenticated caller.
// Mirrors Python agent_api.list_agents — validates owner_ids against joined tenants,
// then delegates to the DAO.
-func (s *AgentService) ListAgents(ctx context.Context, userID string, keywords string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string, canvasCategory, canvasType string, tags []string) (*ListAgentsResponse, common.ErrorCode, error) {
+func (s *AgentService) ListAgents(ctx context.Context, keywords string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string, canvasCategory, canvasType string, tags []string) (*ListAgentsResponse, common.ErrorCode, error) {
+ userID := permission.UserIDFromContext(ctx)
checker := permission.NewDatabaseChecker(dao.DB)
canvasScope, err := checker.Scope(ctx, permission.ScopeQuery{
Kind: permission.ResourceKindCanvas,
@@ -985,8 +986,8 @@ type CreateAgentRequest struct {
// can map validation/duplicate errors to codes 101/102 without
// introducing a separate error type. Missing DSL or title and a
// duplicate title under the authenticated owner surface as specific codes.
-func (s *AgentService) CreateAgent(ctx context.Context, userID string, req *CreateAgentRequest) (*entity.UserCanvas, common.ErrorCode, error) {
- userID = strings.TrimSpace(userID)
+func (s *AgentService) CreateAgent(ctx context.Context, req *CreateAgentRequest) (*entity.UserCanvas, common.ErrorCode, error) {
+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))
if userID == "" {
code, permissionErr := permissionresponse.Normalize(permission.ErrUnauthenticated)
return nil, code, permissionErr
@@ -1109,11 +1110,9 @@ func updatedAgentCanvasCategory(canvasInstance *entity.UserCanvas, updates map[s
// raw errors here would have left a DAO-string leak in the very first
// hop — the earlier af2ac2eda + 804854a5e commits only sanitized the
// version-read path, missing the canvas-access path.
-func (s *AgentService) loadCanvasForUser(ctx context.Context, userID, canvasID string, operation permission.Operation) (*entity.UserCanvas, error) {
- if canvasID == "" {
- return nil, dao.ErrUserCanvasNotFound
- }
- if userID == "" {
+func (s *AgentService) loadCanvasForUser(ctx context.Context, canvasID string, operation permission.Operation) (*entity.UserCanvas, error) {
+ userID := permission.UserIDFromContext(ctx)
+ if canvasID == "" || userID == "" {
return nil, dao.ErrUserCanvasNotFound
}
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: canvasID}, operation); err != nil {
@@ -1135,8 +1134,8 @@ func (s *AgentService) loadCanvasForUser(ctx context.Context, userID, canvasID s
// GetAgent returns a single canvas visible to the requesting user.
// Returns dao.ErrUserCanvasNotFound (not 403) when the canvas is missing
// or belongs to another user.
-func (s *AgentService) GetAgent(ctx context.Context, userID, canvasID string) (*entity.UserCanvas, error) {
- canvasInstance, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead)
+func (s *AgentService) GetAgent(ctx context.Context, canvasID string) (*entity.UserCanvas, error) {
+ canvasInstance, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationRead)
if err != nil {
return nil, err
}
@@ -1170,8 +1169,9 @@ func (s *AgentService) GetLastPublishTime(ctx context.Context, canvasID string)
//
// Shared users may edit canvas content, but only the owner may change its
// visibility.
-func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string, patch map[string]interface{}) error {
- canvasInstance, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate)
+func (s *AgentService) UpdateAgent(ctx context.Context, canvasID string, patch map[string]interface{}) error {
+ userID := permission.UserIDFromContext(ctx)
+ canvasInstance, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationUpdate)
if err != nil {
return err
}
@@ -1367,8 +1367,8 @@ func (s *AgentService) UpdateAgent(ctx context.Context, userID, canvasID string,
// canvas that the user has no access to, surfaces as
// dao.ErrUserCanvasNotFound so mapAgentError emits the same 404 the
// Python handler does for "canvas not found."
-func (s *AgentService) ResetAgent(ctx context.Context, userID, canvasID string) (entity.JSONMap, error) {
- row, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate)
+func (s *AgentService) ResetAgent(ctx context.Context, canvasID string) (entity.JSONMap, error) {
+ row, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationUpdate)
if err != nil {
return nil, err
}
@@ -1389,7 +1389,7 @@ func (s *AgentService) ResetAgent(ctx context.Context, userID, canvasID string)
// rows in a single transaction so a mid-flight failure cannot leave
// orphan version rows. Canvas delete access is decided by the permission
// policy, including its sharing rules.
-func (s *AgentService) DeleteAgent(ctx context.Context, userID, canvasID string) error {
+func (s *AgentService) DeleteAgent(ctx context.Context, canvasID string) error {
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: canvasID}, permission.OperationDelete); err != nil {
if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
return ErrAgentNotOwner
@@ -1415,8 +1415,9 @@ type PublishAgentRequest struct {
DSL entity.JSONMap `json:"dsl,omitempty"`
}
-func (s *AgentService) PublishAgent(ctx context.Context, userID, canvasID string, req *PublishAgentRequest) (*entity.UserCanvasVersion, error) {
- canvasInstance, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate)
+func (s *AgentService) PublishAgent(ctx context.Context, canvasID string, req *PublishAgentRequest) (*entity.UserCanvasVersion, error) {
+ userID := permission.UserIDFromContext(ctx)
+ canvasInstance, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationUpdate)
if err != nil {
return nil, err
}
@@ -1506,8 +1507,8 @@ func buildVersionTitle(agentTitle string, ts time.Time) string {
// newest first. The parent-canvas access check is enforced before the
// version list is loaded so unauthorized users cannot enumerate version
// ids of canvases they cannot read.
-func (s *AgentService) ListVersions(ctx context.Context, userID, canvasID string) ([]*entity.UserCanvasVersion, error) {
- if _, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead); err != nil {
+func (s *AgentService) ListVersions(ctx context.Context, canvasID string) ([]*entity.UserCanvasVersion, error) {
+ if _, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationRead); err != nil {
return nil, err
}
return s.versionDAO.ListByCanvasID(ctx, dao.DB, canvasID)
@@ -1518,11 +1519,11 @@ func (s *AgentService) ListVersions(ctx context.Context, userID, canvasID string
// exist or belongs to a different canvas, and
// dao.ErrUserCanvasNotFound when the parent canvas is not visible to
// the requesting user.
-func (s *AgentService) GetVersion(ctx context.Context, userID, canvasID, versionID string) (*entity.UserCanvasVersion, error) {
+func (s *AgentService) GetVersion(ctx context.Context, canvasID, versionID string) (*entity.UserCanvasVersion, error) {
if versionID == "" {
return nil, dao.ErrUserCanvasVersionNotFound
}
- if _, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRead); err != nil {
+ if _, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationRead); err != nil {
return nil, err
}
row, err := s.versionDAO.GetByID(ctx, dao.DB, versionID)
@@ -1539,11 +1540,11 @@ func (s *AgentService) GetVersion(ctx context.Context, userID, canvasID, version
// Returns dao.ErrUserCanvasVersionNotFound when the row does not exist
// (or belongs to a different canvas) and dao.ErrUserCanvasNotFound when
// the parent canvas is not visible to the requesting user.
-func (s *AgentService) DeleteVersion(ctx context.Context, userID, canvasID, versionID string) error {
+func (s *AgentService) DeleteVersion(ctx context.Context, canvasID, versionID string) error {
if versionID == "" {
return dao.ErrUserCanvasVersionNotFound
}
- canvas, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate)
+ canvas, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationUpdate)
if err != nil {
return err
}
@@ -1578,11 +1579,11 @@ func (s *AgentService) DeleteVersion(ctx context.Context, userID, canvasID, vers
// dao.ErrUserCanvasVersionNotFound when the row does not exist or belongs to a
// different canvas, and dao.ErrUserCanvasNotFound when the parent canvas is not
// updatable by the requesting user.
-func (s *AgentService) UpdateVersion(ctx context.Context, userID, canvasID, versionID string, patch dao.UserCanvasVersionPatch) error {
+func (s *AgentService) UpdateVersion(ctx context.Context, canvasID, versionID string, patch dao.UserCanvasVersionPatch) error {
if versionID == "" {
return dao.ErrUserCanvasVersionNotFound
}
- if _, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationUpdate); err != nil {
+ if _, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationUpdate); err != nil {
return err
}
row, err := s.versionDAO.GetByID(ctx, dao.DB, versionID)
@@ -1602,8 +1603,8 @@ func (s *AgentService) UpdateVersion(ctx context.Context, userID, canvasID, vers
// user_canvas_version: the restored DSL already exists as a historical row,
// so a new one would be a pure duplicate counting against the per-canvas
// version cap.
-func (s *AgentService) ApplyVersion(ctx context.Context, userID, canvasID, versionID string) error {
- version, err := s.GetVersion(ctx, userID, canvasID, versionID)
+func (s *AgentService) ApplyVersion(ctx context.Context, canvasID, versionID string) error {
+ version, err := s.GetVersion(ctx, canvasID, versionID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) || errors.Is(err, dao.ErrUserCanvasVersionNotFound) {
return err
@@ -1615,7 +1616,7 @@ func (s *AgentService) ApplyVersion(ctx context.Context, userID, canvasID, versi
}
// The "apply" flag tells UpdateAgent to skip the version write and refresh
// only the live draft.
- return s.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": version.DSL, "apply": true})
+ return s.UpdateAgent(ctx, canvasID, map[string]interface{}{"dsl": version.DSL, "apply": true})
}
// RunAgent starts a run for the given canvas and returns a channel of
@@ -1635,9 +1636,10 @@ func (s *AgentService) ApplyVersion(ctx context.Context, userID, canvasID, versi
// The per-run RunFunc is built by buildRunFunc — see its doc comment
// for the full production chain (real Compile/Invoke, resume path,
// error-layering contract).
-func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID, version string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error) {
+func (s *AgentService) RunAgent(ctx context.Context, canvasID, sessionID, version string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error) {
+ userID := permission.UserIDFromContext(ctx)
receivedAt := float64(time.Now().UnixNano()) / 1e9
- canvasRow, err := s.loadCanvasForUser(ctx, userID, canvasID, permission.OperationRun)
+ canvasRow, err := s.loadCanvasForUser(ctx, canvasID, permission.OperationRun)
if err != nil {
return nil, err
}
@@ -2022,12 +2024,12 @@ func (s *AgentService) RunAgent(ctx context.Context, userID, canvasID, sessionID
// runReleasedAgent runs the most recently published version of a canvas.
// Public agent runs keep using RunAgent's editable/latest-version behavior;
// this path is reserved for the agentbot release=true contract.
-func (s *AgentService) runReleasedAgent(ctx context.Context, userID, canvasID, sessionID string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error) {
+func (s *AgentService) runReleasedAgent(ctx context.Context, canvasID, sessionID string, userInput any, files []map[string]interface{}) (<-chan canvas.RunEvent, error) {
version, err := s.versionDAO.GetLatestReleased(ctx, dao.DB, canvasID)
if err != nil {
return nil, fmt.Errorf("load latest released version for canvas %q: %w", canvasID, err)
}
- return s.RunAgent(ctx, userID, canvasID, sessionID, version.ID, userInput, files)
+ return s.RunAgent(ctx, canvasID, sessionID, version.ID, userInput, files)
}
// validateAgentChatModels rejects stale Agent model references before execution.
@@ -3161,7 +3163,8 @@ func normalisedDSLForRun(v *entity.UserCanvasVersion) map[string]any {
// the local run context when present and publishes a session-scoped Redis
// marker for an owning instance. Unknown and finished sessions are idempotent
// successes.
-func (s *AgentService) CancelSessionRun(ctx context.Context, userID, sessionID string) error {
+func (s *AgentService) CancelSessionRun(ctx context.Context, sessionID string) error {
+ userID := permission.UserIDFromContext(ctx)
s.runMu.Lock()
active := s.activeSessions[sessionID]
s.runMu.Unlock()
diff --git a/internal/service/agent_cancel_test.go b/internal/service/agent_cancel_test.go
index abfc294c5c..08f8372096 100644
--- a/internal/service/agent_cancel_test.go
+++ b/internal/service/agent_cancel_test.go
@@ -17,6 +17,7 @@ import (
"ragflow/internal/agent/canvas"
"ragflow/internal/dao"
"ragflow/internal/entity"
+ "ragflow/internal/permission"
)
func newAgentCancelTracker(t *testing.T) (*canvas.RunTracker, *miniredis.Miniredis) {
@@ -40,13 +41,13 @@ func TestCancelSessionRunLocalPermissionAndIdempotency(t *testing.T) {
}
svc.activeSessions[active.sessionID] = active
- if err := svc.CancelSessionRun(t.Context(), "user-b", "session-1"); !errors.Is(err, ErrAgentNotOwner) {
+ if err := svc.CancelSessionRun(permission.WithIdentity(t.Context(), "user-b", ""), "session-1"); !errors.Is(err, ErrAgentNotOwner) {
t.Fatalf("other user cancel error = %v, want ErrAgentNotOwner", err)
}
if calls.Load() != 0 {
t.Fatal("unauthorized cancel invoked the active cancel func")
}
- if err := svc.CancelSessionRun(t.Context(), "user-a", "session-1"); err != nil {
+ if err := svc.CancelSessionRun(permission.WithIdentity(t.Context(), "user-a", ""), "session-1"); err != nil {
t.Fatalf("owner CancelSessionRun: %v", err)
}
if calls.Load() != 1 || !active.cancelRequested.Load() {
@@ -54,10 +55,10 @@ func TestCancelSessionRunLocalPermissionAndIdempotency(t *testing.T) {
}
delete(svc.activeSessions, "session-1")
- if err := svc.CancelSessionRun(t.Context(), "user-a", "session-1"); err != nil {
+ if err := svc.CancelSessionRun(permission.WithIdentity(t.Context(), "user-a", ""), "session-1"); err != nil {
t.Fatalf("finished session cancel must be idempotent: %v", err)
}
- if err := svc.CancelSessionRun(t.Context(), "user-a", "unknown"); err != nil {
+ if err := svc.CancelSessionRun(permission.WithIdentity(t.Context(), "user-a", ""), "unknown"); err != nil {
t.Fatalf("unknown session cancel must be idempotent: %v", err)
}
}
@@ -71,7 +72,7 @@ func TestCancelSessionRunDoesNotAffectAnotherSession(t *testing.T) {
svc.activeSessions["session-b"] = &activeAgentRun{
userID: "user-a", sessionID: "session-b", cancelRun: func() { callsB.Add(1) },
}
- if err := svc.CancelSessionRun(t.Context(), "user-a", "session-a"); err != nil {
+ if err := svc.CancelSessionRun(permission.WithIdentity(t.Context(), "user-a", ""), "session-a"); err != nil {
t.Fatalf("CancelSessionRun: %v", err)
}
if callsA.Load() != 1 || callsB.Load() != 0 {
@@ -125,13 +126,13 @@ func TestCancelSessionRunFinishedSessionDoesNotCreateCancelMarker(t *testing.T)
}
svc := NewAgentServiceWithOptions(nil, nil, tracker)
- if err := svc.CancelSessionRun(t.Context(), "user-a", "session-persisted"); err != nil {
+ if err := svc.CancelSessionRun(permission.WithIdentity(t.Context(), "user-a", ""), "session-persisted"); err != nil {
t.Fatalf("late owner cancel error = %v", err)
}
if mr.Exists(sessionID + "-cancel") {
t.Fatal("late cancel recreated a marker after the run finished")
}
- if err := svc.CancelSessionRun(t.Context(), "user-a", "missing-session"); err != nil {
+ if err := svc.CancelSessionRun(permission.WithIdentity(t.Context(), "user-a", ""), "missing-session"); err != nil {
t.Fatalf("missing session cancel must be idempotent: %v", err)
}
if mr.Exists("missing-session-cancel") {
@@ -152,7 +153,7 @@ func TestRunAgentInitializationFailureReleasesActiveSession(t *testing.T) {
svc := NewAgentServiceWithOptions(nil, nil, tracker)
const sessionID = "session-initialization-failure"
- if _, err := svc.RunAgent(t.Context(), "user-a", "agent-1", sessionID, "missing-version", "", nil); err == nil {
+ if _, err := svc.RunAgent(permission.WithIdentity(t.Context(), "user-a", ""), "agent-1", sessionID, "missing-version", "", nil); err == nil {
t.Fatal("RunAgent with missing version returned nil error")
}
active, err := tracker.GetActiveSession(t.Context(), sessionID)
diff --git a/internal/service/agent_dbcheck.go b/internal/service/agent_dbcheck.go
index 4d8ff8c321..ef7d35e5a4 100644
--- a/internal/service/agent_dbcheck.go
+++ b/internal/service/agent_dbcheck.go
@@ -34,6 +34,7 @@ import (
"go.uber.org/zap"
"ragflow/internal/common"
+ "ragflow/internal/permission"
)
// TestDBConnectionRequest is the request body for AgentService.TestDBConnection.
@@ -226,7 +227,8 @@ func dbConnectionPort(port interface{}) string {
// short timeout to keep the API responsive when targets are unreachable.
// The "required argument are missing" message has a trailing semicolon
// and space to stay byte-identical with the Python implementation.
-func (s *AgentService) TestDBConnection(ctx context.Context, userID string, req *TestDBConnectionRequest) (common.ErrorCode, error) {
+func (s *AgentService) TestDBConnection(ctx context.Context, req *TestDBConnectionRequest) (common.ErrorCode, error) {
+ userID := permission.UserIDFromContext(ctx)
if missing := missingDBConnectionFields(req); len(missing) > 0 {
return common.CodeArgumentError, fmt.Errorf("required argument are missing: %s; ", strings.Join(missing, ","))
}
diff --git a/internal/service/agent_deferred_failure_test.go b/internal/service/agent_deferred_failure_test.go
index 231a96ddf1..6b7ef02291 100644
--- a/internal/service/agent_deferred_failure_test.go
+++ b/internal/service/agent_deferred_failure_test.go
@@ -115,7 +115,6 @@ func TestRunAgent_DeferredAgentModelFailureStaysInChatStream(t *testing.T) {
svc := NewAgentServiceWithOptions(nil, nil, tracker)
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-deferred-fail"),
- "user-1",
"canvas-deferred-fail",
"session-deferred-fail",
"",
diff --git a/internal/service/agent_input_test.go b/internal/service/agent_input_test.go
index fba533b922..e8ce6fd5a6 100644
--- a/internal/service/agent_input_test.go
+++ b/internal/service/agent_input_test.go
@@ -67,7 +67,7 @@ func TestAgentbotCompletionPreservesBooleanBeginInput(t *testing.T) {
if err := json.Unmarshal([]byte(body), &req); err != nil {
t.Fatal(err)
}
- events, code, err := svc.AgentbotCompletion(serviceTestContext(t, "user-1", "tenant-1"), "user-1", "canvas-bool", req)
+ events, code, err := svc.AgentbotCompletion(serviceTestContext(t, "user-1", "tenant-1"), "canvas-bool", req)
if err != nil || code != common.CodeSuccess {
t.Fatalf("AgentbotCompletion = (%d, %v)", code, err)
}
diff --git a/internal/service/agent_message_draft_test.go b/internal/service/agent_message_draft_test.go
index e7755982a2..44669b1c71 100644
--- a/internal/service/agent_message_draft_test.go
+++ b/internal/service/agent_message_draft_test.go
@@ -43,15 +43,15 @@ func TestMessageDraftRoundTripAndExecution(t *testing.T) {
t.Run(tt.name, func(t *testing.T) {
title := "Message " + tt.name
ctx := serviceTestContext(t, "user-1", "user-1")
- row, code, err := svc.CreateAgent(ctx, "user-1", &CreateAgentRequest{Title: &title, DSL: messageDraftDSL(tt.params)})
+ row, code, err := svc.CreateAgent(ctx, &CreateAgentRequest{Title: &title, DSL: messageDraftDSL(tt.params)})
if err != nil || code != common.CodeSuccess {
t.Fatalf("create: code=%v err=%v", code, err)
}
for range 2 {
- if err := svc.UpdateAgent(ctx, "user-1", row.ID, map[string]any{"dsl": messageDraftDSL(tt.params)}); err != nil {
+ if err := svc.UpdateAgent(ctx, row.ID, map[string]any{"dsl": messageDraftDSL(tt.params)}); err != nil {
t.Fatalf("save: %v", err)
}
- saved, err := svc.GetAgent(ctx, "user-1", row.ID)
+ saved, err := svc.GetAgent(ctx, row.ID)
if err != nil {
t.Fatal(err)
}
@@ -85,11 +85,11 @@ func TestMessageDraftRoundTripAndExecution(t *testing.T) {
if err == nil || !strings.Contains(err.Error(), "content does not support empty") {
t.Fatalf("compile error=%v", err)
}
- if err := svc.UpdateAgent(t.Context(), "user-1", row.ID, map[string]any{"dsl": messageDraftDSL(tt.params), "release": true}); err == nil {
- t.Fatal("release accepted incomplete Message")
+ if err := svc.UpdateAgent(ctx, row.ID, map[string]any{"dsl": messageDraftDSL(tt.params), "release": true}); err == nil || !strings.Contains(err.Error(), "content does not support empty") {
+ t.Fatalf("release validation error = %v, want incomplete Message error", err)
}
- if _, err := svc.PublishAgent(t.Context(), "user-1", row.ID, &PublishAgentRequest{DSL: messageDraftDSL(tt.params)}); err == nil {
- t.Fatal("publish accepted incomplete Message")
+ if _, err := svc.PublishAgent(ctx, row.ID, &PublishAgentRequest{DSL: messageDraftDSL(tt.params)}); err == nil || !strings.Contains(err.Error(), "content does not support empty") {
+ t.Fatalf("publish validation error = %v, want incomplete Message error", err)
}
return
}
diff --git a/internal/service/agent_persistence_test.go b/internal/service/agent_persistence_test.go
index ef67a93dd8..97716f020a 100644
--- a/internal/service/agent_persistence_test.go
+++ b/internal/service/agent_persistence_test.go
@@ -183,7 +183,7 @@ func TestPersistAgentRunSessionPreservesThinking(t *testing.T) {
results := make(chan error, 2)
for _, question := range []string{"concurrent question 1", "concurrent question 2"} {
go func(question string) {
- events, err := svc.RunAgent(ctx, "user-1", "canvas-think", "session-think", "", question, nil)
+ events, err := svc.RunAgent(ctx, "canvas-think", "session-think", "", question, nil)
if err == nil {
for event := range events {
if event.Type == "error" {
diff --git a/internal/service/agent_run_e2e_test.go b/internal/service/agent_run_e2e_test.go
index 37427b7be6..ab0892cfdc 100644
--- a/internal/service/agent_run_e2e_test.go
+++ b/internal/service/agent_run_e2e_test.go
@@ -207,7 +207,6 @@ func TestRunAgent_RealCanvas_BeginMessage(t *testing.T) {
svc := NewAgentServiceWithOptions(cp, nil, tracker)
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-hello"),
- "user-1",
"canvas-hello",
"session-hello",
"", // draft DSL
@@ -298,7 +297,7 @@ func TestRunAgent_SessionHistoryFeedsSysHistoryAndPersists(t *testing.T) {
svc := NewAgentService()
run := func(input string) canvas.MessageEvent {
t.Helper()
- events, err := svc.RunAgent(serviceTestContext(t, "user-1", "tenant-1"), "user-1", "canvas-history", "session-history", "", input, nil)
+ events, err := svc.RunAgent(serviceTestContext(t, "user-1", "tenant-1"), "canvas-history", "session-history", "", input, nil)
if err != nil {
t.Fatalf("RunAgent(%q): %v", input, err)
}
@@ -394,7 +393,7 @@ func TestRunAgent_NewSessionPersistsHistoryForNextTurn(t *testing.T) {
makeCanvasWithDSL(t, "canvas-new-session", "user-1", "tenant-1", "v-new-session", dsl)
svc := NewAgentService()
- events, err := svc.RunAgent(serviceTestContext(t, "user-1", "tenant-1"), "user-1", "canvas-new-session", "", "", "1", nil)
+ events, err := svc.RunAgent(serviceTestContext(t, "user-1", "tenant-1"), "canvas-new-session", "", "", "1", nil)
if err != nil {
t.Fatalf("first RunAgent: %v", err)
}
@@ -425,7 +424,7 @@ func TestRunAgent_NewSessionPersistsHistoryForNextTurn(t *testing.T) {
t.Fatalf("new session lost reusable env state: %#v", globals["env.topic"])
}
- events, err = svc.RunAgent(serviceTestContext(t, "user-1", "tenant-1"), "user-1", "canvas-new-session", session.ID, "", "1", nil)
+ events, err = svc.RunAgent(serviceTestContext(t, "user-1", "tenant-1"), "canvas-new-session", session.ID, "", "1", nil)
if err != nil {
t.Fatalf("second RunAgent: %v", err)
}
@@ -482,7 +481,6 @@ func TestRunAgent_RejectsSessionOwnedByAnotherUser(t *testing.T) {
events, err := NewAgentService().RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-session-owner",
"session-foreign",
"",
@@ -605,7 +603,6 @@ func TestRunAgent_RealCanvas_WaitForUserResume(t *testing.T) {
// Run 1: should emit a waiting_for_user event.
events1, err := svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-fillup",
"session-fillup",
"",
@@ -639,7 +636,6 @@ func TestRunAgent_RealCanvas_WaitForUserResume(t *testing.T) {
// production environment's checkpoint store.
events2, err := svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-fillup",
"session-fillup", // SAME sessionID as run 1
"",
@@ -716,7 +712,6 @@ func TestRunAgent_InterruptPersistsPartialAssistantHistory(t *testing.T) {
events, err := NewAgentService().RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-partial",
"session-partial",
"",
@@ -803,7 +798,6 @@ func TestRunAgent_RealCanvas_WaitForUserResume_EventSemantics(t *testing.T) {
events1, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-fillup-events"),
- "user-1",
"canvas-fillup-events",
"session-fillup-events",
"",
@@ -826,7 +820,6 @@ func TestRunAgent_RealCanvas_WaitForUserResume_EventSemantics(t *testing.T) {
events2, err := svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-fillup-events",
"session-fillup-events",
"",
@@ -944,7 +937,6 @@ func TestRunAgent_RealCanvas_GroupedParallelOuterFollower(t *testing.T) {
svc := NewAgentService()
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-parallel"),
- "user-1",
"canvas-parallel",
"session-parallel",
"",
@@ -1021,7 +1013,6 @@ func TestRunAgent_AllFixture_LoopInterruptResume(t *testing.T) {
events1, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-all-loop"),
- "user-1",
"canvas-all",
"session-all-loop",
"",
@@ -1061,7 +1052,6 @@ func TestRunAgent_AllFixture_LoopInterruptResume(t *testing.T) {
events2, err := svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-all",
"session-all-loop",
"",
@@ -1087,7 +1077,7 @@ func TestRunAgent_AllFixture_LoopInterruptResume(t *testing.T) {
}
events3, err := svc.RunAgent(
- serviceTestContext(t, "user-1", "tenant-1"), "user-1", "canvas-all", "session-all-loop", "", "1", nil,
+ serviceTestContext(t, "user-1", "tenant-1"), "canvas-all", "session-all-loop", "", "1", nil,
)
if err != nil {
t.Fatalf("RunAgent run 3: %v", err)
@@ -1148,7 +1138,6 @@ func TestRunAgent_AllFixture_LoopInterruptResume_MultiTurn(t *testing.T) {
}
events, err := svc.RunAgent(
runCtx,
- "user-1",
"canvas-all-multi",
sessionID,
"",
@@ -1241,7 +1230,6 @@ func TestRunAgent_AllFixture_IterationFormatsItems(t *testing.T) {
events1, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), sessionID),
- "user-1",
"canvas-all-iteration",
sessionID,
"",
@@ -1270,7 +1258,6 @@ func TestRunAgent_AllFixture_IterationFormatsItems(t *testing.T) {
events2, err := svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-all-iteration",
sessionID,
"",
@@ -1296,7 +1283,7 @@ func TestRunAgent_AllFixture_IterationFormatsItems(t *testing.T) {
}
events3, err := svc.RunAgent(
- serviceTestContext(t, "user-1", "tenant-1"), "user-1", "canvas-all-iteration", sessionID, "", "a,b,c,d,e", nil,
+ serviceTestContext(t, "user-1", "tenant-1"), "canvas-all-iteration", sessionID, "", "a,b,c,d,e", nil,
)
if err != nil {
t.Fatalf("RunAgent run 3: %v", err)
@@ -1351,7 +1338,6 @@ func TestRunAgent_AllFixture_VarAssigner(t *testing.T) {
svc := NewAgentServiceWithOptions(cp, nil, tracker)
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-all-var-assigner"),
- "user-1",
"canvas-all-var-assigner",
"session-all-var-assigner",
"",
@@ -1374,7 +1360,6 @@ func TestRunAgent_AllFixture_VarAssigner(t *testing.T) {
}
events, err = svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-all-var-assigner",
"session-all-var-assigner",
"",
@@ -1435,7 +1420,6 @@ func TestRunAgent_AllFixture_DataOps(t *testing.T) {
svc := NewAgentServiceWithOptions(cp, nil, tracker)
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-all-data-ops"),
- "user-1",
"canvas-all-data-ops",
"session-all-data-ops",
"",
@@ -1458,7 +1442,6 @@ func TestRunAgent_AllFixture_DataOps(t *testing.T) {
}
events, err = svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-all-data-ops",
"session-all-data-ops",
"",
@@ -1537,7 +1520,6 @@ func TestRunAgent_RealCanvas_CompileFails(t *testing.T) {
svc := NewAgentService()
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-bogus"),
- "user-1",
"canvas-bogus",
"session-bogus",
"",
@@ -1578,7 +1560,7 @@ func TestRunAgent_ExeSQLConfigErrorIsUserFacing(t *testing.T) {
}}
makeCanvasWithDSL(t, "canvas-exesql-config", "user-1", "tenant-1", "v-exesql-config", dsl)
- events, err := NewAgentService().RunAgent(WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-exesql-config"), "user-1", "canvas-exesql-config", "session-exesql-config", "", "hello", nil)
+ events, err := NewAgentService().RunAgent(WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-exesql-config"), "canvas-exesql-config", "session-exesql-config", "", "hello", nil)
if err != nil {
t.Fatalf("RunAgent returned sync error: %v", err)
}
@@ -1641,7 +1623,6 @@ func TestRunAgent_AllFixture_CategorizeResume(t *testing.T) {
svc := NewAgentServiceWithOptions(cp, nil, tracker)
events1, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-all-categorize"),
- "user-1",
"canvas-all-categorize",
"session-all-categorize",
"",
@@ -1669,7 +1650,6 @@ func TestRunAgent_AllFixture_CategorizeResume(t *testing.T) {
events2, err := svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-all-categorize",
"session-all-categorize",
"",
@@ -1703,7 +1683,6 @@ func TestRunAgent_AllFixture_CategorizeResume(t *testing.T) {
events3, err := svc.RunAgent(
serviceTestContext(t, "user-1", "tenant-1"),
- "user-1",
"canvas-all-categorize",
"session-all-categorize",
"",
@@ -1799,7 +1778,6 @@ func TestRunAgent_RealCanvas_InvokeFails(t *testing.T) {
svc := NewAgentService()
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-invoke-fail"),
- "user-1",
"canvas-invoke-fail",
"session-invoke-fail",
"",
@@ -1906,7 +1884,6 @@ func TestRunAgent_RunTracker_AttachCheckpoint_CallSequence(t *testing.T) {
svc := NewAgentServiceWithOptions(cp, canvas.CanvasStateSerializer{}, tracker)
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-cp"),
- "user-1",
"canvas-cp",
"session-cp",
"", // draft DSL
@@ -2081,7 +2058,6 @@ func TestRunAgent_FilesPopulateIteration(t *testing.T) {
svc := NewAgentService()
events, err := svc.RunAgent(
WithAgentSessionID(ctx, sessionID),
- "user-1",
canvasID,
sessionID,
"",
@@ -2148,7 +2124,6 @@ func TestRunAgent_MissingUploadEmitsError(t *testing.T) {
events, err := NewAgentService().RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), "session-missing-upload"),
- "user-1",
"canvas-missing-upload",
"session-missing-upload",
"",
@@ -2226,7 +2201,6 @@ func TestRunAgent_NoFilesRunsNormally(t *testing.T) {
svc := NewAgentService()
events, err := svc.RunAgent(
WithAgentSessionID(serviceTestContext(t, "user-1", "tenant-1"), sessionID),
- "user-1",
canvasID,
sessionID,
"",
diff --git a/internal/service/agent_sessions.go b/internal/service/agent_sessions.go
index acbeb22c9f..10a2161680 100644
--- a/internal/service/agent_sessions.go
+++ b/internal/service/agent_sessions.go
@@ -76,7 +76,7 @@ type DeleteAgentSessionsResponse struct {
// CheckCanvasAccess returns true when the user is the canvas owner or
// holds team-level permission for the owner's tenant.
-func (s *AgentService) CheckCanvasAccess(ctx context.Context, userID, canvasID string) (bool, error) {
+func (s *AgentService) CheckCanvasAccess(ctx context.Context, canvasID string) (bool, error) {
err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: canvasID}, permission.OperationRead)
if errors.Is(err, permission.ErrResourceNotFound) {
return false, dao.ErrUserCanvasNotFound
@@ -246,12 +246,12 @@ func checkDuplicateSessionIDs(ids []string) ([]string, []string) {
}
// ListAgentSessions returns paginated agent sessions visible to the caller.
-func (s *AgentService) ListAgentSessions(ctx context.Context, userID, _ string, agentID string, req ListAgentSessionsRequest) (*ListAgentSessionsResponse, common.ErrorCode, error) {
+func (s *AgentService) ListAgentSessions(ctx context.Context, agentID string, req ListAgentSessionsRequest) (*ListAgentSessionsResponse, common.ErrorCode, error) {
if agentID == "" {
return nil, common.CodeArgumentError, errors.New("agent_id is required")
}
- ok, err := s.CheckCanvasAccess(ctx, userID, agentID)
+ ok, err := s.CheckCanvasAccess(ctx, agentID)
if err != nil {
// The Python agent API folds "canvas does not exist" into
// the same 103 access envelope as a permission mismatch
@@ -317,11 +317,11 @@ func (s *AgentService) ListAgentSessions(ctx context.Context, userID, _ string,
}
// GetAgentSession fetches a single conversation belonging to agentID.
-func (s *AgentService) GetAgentSession(ctx context.Context, userID, agentID, sessionID string, options ...dao.ConversationHistoryOptions) (*entity.API4Conversation, common.ErrorCode, error) {
+func (s *AgentService) GetAgentSession(ctx context.Context, agentID, sessionID string, options ...dao.ConversationHistoryOptions) (*entity.API4Conversation, common.ErrorCode, error) {
if sessionID == "" {
return nil, common.CodeArgumentError, fmt.Errorf("session_id is required")
}
- ok, err := s.CheckCanvasAccess(ctx, userID, agentID)
+ ok, err := s.CheckCanvasAccess(ctx, agentID)
if err != nil {
if errors.Is(err, dao.ErrUserCanvasNotFound) {
return nil, common.CodeOperatingError, errors.New("agent not found or no permission")
@@ -347,7 +347,7 @@ func (s *AgentService) GetAgentSession(ctx context.Context, userID, agentID, ses
}
// DeleteAgentSessionItem removes one conversation if it belongs to agentID.
-func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agentID, sessionID string) (bool, common.ErrorCode, error) {
+func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, agentID, sessionID string) (bool, common.ErrorCode, error) {
if sessionID == "" {
return false, common.CodeArgumentError, errors.New("session_id is required")
}
@@ -378,7 +378,7 @@ func (s *AgentService) DeleteAgentSessionItem(ctx context.Context, userID, agent
// DeleteAgentSessions removes selected conversations belonging to agentID.
// When ids is empty and deleteAll is true, every session under agentID is
// removed.
-func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID string, ids []string, deleteAll bool) (*DeleteAgentSessionsResult, common.ErrorCode, error) {
+func (s *AgentService) DeleteAgentSessions(ctx context.Context, agentID string, ids []string, deleteAll bool) (*DeleteAgentSessionsResult, common.ErrorCode, error) {
if agentID == "" {
return nil, common.CodeArgumentError, errors.New("agent_id is required")
}
@@ -458,7 +458,7 @@ func (s *AgentService) DeleteAgentSessions(ctx context.Context, userID, agentID
}
// ListAgentTags list agent tags
-func (s *AgentService) ListAgentTags(ctx context.Context, userID, canvasCategory string) ([]AgentTagCount, common.ErrorCode, error) {
+func (s *AgentService) ListAgentTags(ctx context.Context, canvasCategory string) ([]AgentTagCount, common.ErrorCode, error) {
canvasScope, err := permission.NewDatabaseChecker(dao.DB).Scope(ctx, permission.ScopeQuery{
Kind: permission.ResourceKindCanvas,
Operation: permission.OperationRead,
@@ -556,7 +556,7 @@ func normalizeAgentTags(rawTags interface{}) (string, error) {
}
// UpdateAgentTags normalises tags and persists them on a single canvas.
-func (s *AgentService) UpdateAgentTags(ctx context.Context, userID, canvasID string, tags interface{}) (bool, common.ErrorCode, error) {
+func (s *AgentService) UpdateAgentTags(ctx context.Context, canvasID string, tags interface{}) (bool, common.ErrorCode, error) {
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: canvasID}, permission.OperationUpdate); err != nil {
if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
return false, common.CodeOperatingError, errors.New("agent not found or no permission")
diff --git a/internal/service/agent_test.go b/internal/service/agent_test.go
index 8502f642af..e793f433e7 100644
--- a/internal/service/agent_test.go
+++ b/internal/service/agent_test.go
@@ -311,7 +311,7 @@ func TestListVersions_Success(t *testing.T) {
ctx := serviceTestContext(t, "user-1", "user-1")
svc := NewAgentService()
- versions, err := svc.ListVersions(ctx, "user-1", "canvas-1")
+ versions, err := svc.ListVersions(ctx, "canvas-1")
if err != nil {
t.Fatalf("ListVersions failed: %v", err)
}
@@ -356,7 +356,7 @@ func TestListVersions_Empty(t *testing.T) {
ctx := serviceTestContext(t, "user-1", "user-1")
svc := NewAgentService()
- versions, err := svc.ListVersions(ctx, "user-1", "canvas-empty")
+ versions, err := svc.ListVersions(ctx, "canvas-empty")
if err != nil {
t.Fatalf("ListVersions failed: %v", err)
}
@@ -469,7 +469,7 @@ func TestGetVersion_Success(t *testing.T) {
ctx := serviceTestContext(t, "user-1", "user-1")
svc := NewAgentService()
- v, err := svc.GetVersion(ctx, "user-1", "canvas-1", "v1")
+ v, err := svc.GetVersion(ctx, "canvas-1", "v1")
if err != nil {
t.Fatalf("GetVersion failed: %v", err)
}
@@ -503,7 +503,7 @@ func TestGetVersion_WrongCanvas(t *testing.T) {
ctx := serviceTestContext(t, "user-other", "user-other")
svc := NewAgentService()
- _, err := svc.GetVersion(ctx, "user-other", "canvas-other", "v1")
+ _, err := svc.GetVersion(ctx, "canvas-other", "v1")
if err == nil {
t.Error("expected error for version belonging to another canvas")
}
@@ -528,7 +528,7 @@ func TestGetVersion_NotFound(t *testing.T) {
ctx := serviceTestContext(t, "user-1", "user-1")
svc := NewAgentService()
- _, err := svc.GetVersion(ctx, "user-1", "canvas-1", "non-existent")
+ _, err := svc.GetVersion(ctx, "canvas-1", "non-existent")
if err == nil {
t.Error("expected error for non-existent version")
}
@@ -585,7 +585,6 @@ func TestRunAgent_VersionBelongsToOtherCanvas(t *testing.T) {
svc := NewAgentService()
_, err := svc.RunAgent(
ctx,
- "user-1",
"canvas-1", // we're running canvas-1…
"", // session ID auto-generated
"v-on-canvas-2", // …with a version that belongs to canvas-2
@@ -632,7 +631,6 @@ func TestRunAgent_VersionNotFound(t *testing.T) {
svc := NewAgentService()
_, err := svc.RunAgent(
ctx,
- "user-1",
"canvas-1",
"",
"does-not-exist",
@@ -690,7 +688,6 @@ func TestRunAgent_NoVersionPublishedPlaceholder(t *testing.T) {
svc := NewAgentService()
events, err := svc.RunAgent(
WithAgentSessionID(ctx, "test-session"),
- "user-1",
"canvas-empty",
"test-session",
"", // no explicit version → draft DSL, which is empty here
@@ -766,7 +763,7 @@ func TestRunAgentRejectsUntrustedSessionContinuation(t *testing.T) {
{name: "valid resume", sessionID: "session-valid", userID: "user-1"},
} {
t.Run(tc.name, func(t *testing.T) {
- events, err := svc.RunAgent(serviceTestContext(t, tc.userID, "user-1"), tc.userID, "canvas-1", tc.sessionID, "", "hello", nil)
+ events, err := svc.RunAgent(serviceTestContext(t, tc.userID, "user-1"), "canvas-1", tc.sessionID, "", "hello", nil)
if tc.wantErr {
if !errors.Is(err, dao.ErrUserCanvasNotFound) {
t.Fatalf("RunAgent error = %v, want ErrUserCanvasNotFound", err)
@@ -837,7 +834,6 @@ func TestRunAgent_StorageErrorFromCanvasAccess(t *testing.T) {
svc := NewAgentService()
_, err := svc.RunAgent(
ctx,
- "user-1",
"canvas-1",
"",
"",
@@ -890,7 +886,7 @@ func TestLoadCanvasForUser_StorageErrorWrap(t *testing.T) {
ctx := permission.WithIdentity(t.Context(), "user-1", "user-1")
svc := NewAgentService()
- _, err := svc.loadCanvasForUser(ctx, "user-1", "canvas-1", permission.OperationRead)
+ _, err := svc.loadCanvasForUser(ctx, "canvas-1", permission.OperationRead)
if err == nil {
t.Fatal("expected storage error from closed DB")
}
@@ -1006,7 +1002,7 @@ func TestListAgentSessionsServiceSuccess(t *testing.T) {
createAgentSessionTestConversation(t, "session-other-agent", "canvas-other", "user-1", 9999)
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := NewAgentService().ListAgentSessions(ctx, "user-1", "user-1", "canvas-1", ListAgentSessionsRequest{
+ resp, code, err := NewAgentService().ListAgentSessions(ctx, "canvas-1", ListAgentSessionsRequest{
Page: 1,
PageSize: 10,
OrderBy: "update_time",
@@ -1050,7 +1046,7 @@ func TestListAgentSessionsServiceSuccess(t *testing.T) {
}
}
for _, page := range []struct{ number, size, count int }{{1, 30, 30}, {4, 10, 10}, {5, 10, 1}, {6, 10, 0}} {
- resp, code, err := NewAgentService().ListAgentSessions(ctx, "user-1", "user-1", "canvas-1", ListAgentSessionsRequest{
+ resp, code, err := NewAgentService().ListAgentSessions(ctx, "canvas-1", ListAgentSessionsRequest{
Page: page.number, PageSize: page.size, ExpUserID: "exp-user",
})
if err != nil || code != common.CodeSuccess {
@@ -1074,7 +1070,7 @@ func TestListAgentSessionsServiceDenied(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-2")
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := NewAgentService().ListAgentSessions(ctx, "user-1", "user-1", "canvas-1", ListAgentSessionsRequest{})
+ resp, code, err := NewAgentService().ListAgentSessions(ctx, "canvas-1", ListAgentSessionsRequest{})
if err == nil {
t.Fatal("expected permission error")
}
@@ -1101,7 +1097,7 @@ func TestGetAgentSessionServiceSuccess(t *testing.T) {
}); err != nil {
t.Fatal(err)
}
- session, code, err := NewAgentService().GetAgentSession(ctx, "user-1", "canvas-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true})
+ session, code, err := NewAgentService().GetAgentSession(ctx, "canvas-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true})
if err != nil {
t.Fatalf("GetAgentSession failed: %v", err)
}
@@ -1203,7 +1199,7 @@ func TestCreateAgentSessionLeavesVersionTitleNilWithVersions(t *testing.T) {
}
// The list surface used by the agent log page must expose nil too.
- resp, code, err := svc.ListAgentSessions(ctx, "user-1", "user-1", "canvas-1", ListAgentSessionsRequest{Page: 1, PageSize: 10})
+ resp, code, err := svc.ListAgentSessions(ctx, "canvas-1", ListAgentSessionsRequest{Page: 1, PageSize: 10})
if err != nil {
t.Fatalf("ListAgentSessions failed: %v", err)
}
@@ -1316,7 +1312,7 @@ func TestAgentModelValidationUsesCanvasTenant(t *testing.T) {
if _, code, err := svc.CreateAgentSession(ctx, &CreateAgentSessionRequest{UserID: tenantOwnerID, AgentID: canvasRow.ID}); err != nil || code != common.CodeSuccess {
t.Fatalf("CreateAgentSession with tenant model = (%d, %v), want success", code, err)
}
- if err := svc.UpdateAgent(ctx, tenantOwnerID, canvasRow.ID, map[string]any{"dsl": dsl}); err != nil {
+ if err := svc.UpdateAgent(ctx, canvasRow.ID, map[string]any{"dsl": dsl}); err != nil {
t.Fatalf("UpdateAgent with tenant model: %v", err)
}
}
@@ -1328,7 +1324,7 @@ func TestGetAgentSessionServiceNotFoundWhenSessionBelongsToAnotherAgent(t *testi
createAgentSessionTestConversation(t, "session-other", "canvas-other", "user-1", 1000)
ctx := serviceTestContext(t, "user-1", "user-1")
- session, code, err := NewAgentService().GetAgentSession(ctx, "user-1", "canvas-1", "session-other")
+ session, code, err := NewAgentService().GetAgentSession(ctx, "canvas-1", "session-other")
if err == nil {
t.Fatal("expected not found error")
}
@@ -1348,7 +1344,7 @@ func TestDeleteAgentSessionItemServiceDeletesMatchingSession(t *testing.T) {
createAgentSessionTestConversation(t, "session-other", "canvas-other", "user-1", 2000)
ctx := serviceTestContext(t, "user-1", "user-1")
- deleted, code, err := NewAgentService().DeleteAgentSessionItem(ctx, "user-1", "canvas-1", "session-1")
+ deleted, code, err := NewAgentService().DeleteAgentSessionItem(ctx, "canvas-1", "session-1")
if err != nil {
t.Fatalf("DeleteAgentSessionItem failed: %v", err)
}
@@ -1382,7 +1378,7 @@ func TestDeleteAgentSessionItemServiceNoopForSessionFromAnotherAgent(t *testing.
createAgentSessionTestConversation(t, "session-other", "canvas-other", "user-1", 1000)
ctx := serviceTestContext(t, "user-1", "user-1")
- deleted, code, err := NewAgentService().DeleteAgentSessionItem(ctx, "user-1", "canvas-1", "session-other")
+ deleted, code, err := NewAgentService().DeleteAgentSessionItem(ctx, "canvas-1", "session-other")
if err != nil {
t.Fatalf("DeleteAgentSessionItem failed: %v", err)
}
@@ -1411,7 +1407,7 @@ func TestDeleteAgentSessionsServiceDeleteAll(t *testing.T) {
createAgentSessionTestConversation(t, "session-other", "canvas-other", "user-1", 3000)
ctx := serviceTestContext(t, "user-1", "user-1")
- result, code, err := NewAgentService().DeleteAgentSessions(ctx, "user-1", "canvas-1", nil, true)
+ result, code, err := NewAgentService().DeleteAgentSessions(ctx, "canvas-1", nil, true)
if err != nil {
t.Fatalf("DeleteAgentSessions failed: %v", err)
}
@@ -1449,7 +1445,7 @@ func TestDeleteAgentSessionsServiceDuplicateIDsPartial(t *testing.T) {
createAgentSessionTestConversation(t, "session-1", "canvas-1", "user-1", 1000)
ctx := serviceTestContext(t, "user-1", "user-1")
- result, code, err := NewAgentService().DeleteAgentSessions(ctx, "user-1", "canvas-1", []string{"session-1", "session-1"}, false)
+ result, code, err := NewAgentService().DeleteAgentSessions(ctx, "canvas-1", []string{"session-1", "session-1"}, false)
if err != nil {
t.Fatalf("DeleteAgentSessions failed: %v", err)
}
@@ -1481,7 +1477,7 @@ func TestDeleteAgentSessionsServiceMissingSessionError(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-1")
ctx := serviceTestContext(t, "user-1", "user-1")
- result, code, err := NewAgentService().DeleteAgentSessions(ctx, "user-1", "canvas-1", []string{"missing-session"}, false)
+ result, code, err := NewAgentService().DeleteAgentSessions(ctx, "canvas-1", []string{"missing-session"}, false)
if err == nil {
t.Fatal("expected missing session error")
}
@@ -1503,7 +1499,7 @@ func TestDeleteAgentSessionsServiceRequiresOwner(t *testing.T) {
createAgentSessionTestConversation(t, "session-1", "canvas-1", "user-1", 1000)
ctx := serviceTestContext(t, "user-1", "user-1")
- result, code, err := NewAgentService().DeleteAgentSessions(ctx, "user-1", "canvas-1", []string{"session-1"}, false)
+ result, code, err := NewAgentService().DeleteAgentSessions(ctx, "canvas-1", []string{"session-1"}, false)
if err == nil {
t.Fatal("expected owner error")
}
@@ -1529,7 +1525,7 @@ func TestUpdateAgentTagsServiceSuccess(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-1")
ctx := serviceTestContext(t, "user-1", "user-1")
- ok, code, err := NewAgentService().UpdateAgentTags(ctx, "user-1", "canvas-1", []interface{}{"alpha", "beta", "alpha", "with,comma"})
+ ok, code, err := NewAgentService().UpdateAgentTags(ctx, "canvas-1", []interface{}{"alpha", "beta", "alpha", "with,comma"})
if err != nil {
t.Fatalf("UpdateAgentTags failed: %v", err)
}
@@ -1555,7 +1551,7 @@ func TestUpdateAgentTagsServiceInvalidPayload(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-1")
ctx := serviceTestContext(t, "user-1", "user-1")
- ok, code, err := NewAgentService().UpdateAgentTags(ctx, "user-1", "canvas-1", map[string]string{"tag": "alpha"})
+ ok, code, err := NewAgentService().UpdateAgentTags(ctx, "canvas-1", map[string]string{"tag": "alpha"})
if err == nil {
t.Fatal("expected invalid tags error")
}
@@ -1581,7 +1577,7 @@ func TestUpdateAgentTagsServiceNoPermission(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-2")
ctx := serviceTestContext(t, "user-1", "user-1")
- ok, code, err := NewAgentService().UpdateAgentTags(ctx, "user-1", "canvas-1", []string{"alpha"})
+ ok, code, err := NewAgentService().UpdateAgentTags(ctx, "canvas-1", []string{"alpha"})
if err == nil {
t.Fatal("expected permission error")
}
@@ -1672,7 +1668,7 @@ func TestAssertHostIsSafeAllowsPrivateHostWhenConfigured(t *testing.T) {
func TestTestDBConnectionMissingFields(t *testing.T) {
ctx := t.Context()
- code, err := NewAgentService().TestDBConnection(ctx, "user-1", &TestDBConnectionRequest{DBType: "mysql"})
+ code, err := NewAgentService().TestDBConnection(ctx, &TestDBConnectionRequest{DBType: "mysql"})
if err == nil {
t.Fatal("expected missing field error")
}
@@ -1687,7 +1683,7 @@ func TestTestDBConnectionMissingFields(t *testing.T) {
func TestTestDBConnectionUnsupportedDatabaseType(t *testing.T) {
ctx := t.Context()
- code, err := NewAgentService().TestDBConnection(ctx, "user-1", &TestDBConnectionRequest{
+ code, err := NewAgentService().TestDBConnection(ctx, &TestDBConnectionRequest{
DBType: "unsupported",
Database: "rag_flow",
Username: "root",
@@ -1767,7 +1763,7 @@ func TestResetAgentServiceClearsPerRunState(t *testing.T) {
t.Fatalf("failed to seed agent: %v", err)
}
- got, err := NewAgentService().ResetAgent(ctx, "user-1", "canvas-1")
+ got, err := NewAgentService().ResetAgent(ctx, "canvas-1")
if err != nil {
t.Fatalf("ResetAgent failed: %v", err)
}
@@ -1833,7 +1829,7 @@ func TestResetAgentServiceNotFound(t *testing.T) {
setupAgentSessionServiceTest(t)
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := NewAgentService().ResetAgent(ctx, "user-1", "missing")
+ _, err := NewAgentService().ResetAgent(ctx, "missing")
if err == nil {
t.Fatal("expected error for missing canvas")
}
@@ -1868,7 +1864,7 @@ func TestUpdateAgentSettingsPreservesDSL(t *testing.T) {
t.Fatalf("failed to seed agent: %v", err)
}
- err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-settings", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "canvas-settings", map[string]interface{}{
"description": "new description",
})
if err != nil {
@@ -1905,7 +1901,7 @@ func TestUpdateAgentAllowsExistingTitleForSameCanvas(t *testing.T) {
t.Fatalf("failed to seed agent: %v", err)
}
- err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-same-title", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "canvas-same-title", map[string]interface{}{
"title": "Same Title",
"description": "new description",
})
@@ -1954,14 +1950,14 @@ func TestUpdateAgentTeamMemberCanUpdateButCannotChangePermission(t *testing.T) {
memberCtx := serviceTestContext(t, "member-1", "owner-1", "owner-1")
samePermission := " TEAM "
- if err := NewAgentService().UpdateAgent(memberCtx, "member-1", "canvas-team-edit", map[string]interface{}{
+ if err := NewAgentService().UpdateAgent(memberCtx, "canvas-team-edit", map[string]interface{}{
"description": "member edit",
"permission": samePermission,
}); err != nil {
t.Fatalf("UpdateAgent with same permission failed: %v", err)
}
- if err := NewAgentService().UpdateAgent(memberCtx, "member-1", "canvas-team-edit", map[string]interface{}{
+ if err := NewAgentService().UpdateAgent(memberCtx, "canvas-team-edit", map[string]interface{}{
"title": "Owner Duplicate",
}); err == nil || err.Error() != "Owner Duplicate already exists." {
t.Fatalf("UpdateAgent duplicate title error = %v, want Owner Duplicate already exists.", err)
@@ -1969,7 +1965,7 @@ func TestUpdateAgentTeamMemberCanUpdateButCannotChangePermission(t *testing.T) {
ownerCtx := serviceTestContext(t, "owner-1", "owner-1", "member-1")
nextPermission := "me"
- if err := NewAgentService().UpdateAgent(memberCtx, "member-1", "canvas-team-edit", map[string]interface{}{
+ if err := NewAgentService().UpdateAgent(memberCtx, "canvas-team-edit", map[string]interface{}{
"permission": nextPermission,
}); err == nil {
t.Fatal("UpdateAgent allowed shared member to change canvas permission")
@@ -1981,7 +1977,7 @@ func TestUpdateAgentTeamMemberCanUpdateButCannotChangePermission(t *testing.T) {
if canvas.Permission != string(entity.TenantPermissionTeam) {
t.Fatalf("canvas permission = %q, want unchanged %q", canvas.Permission, entity.TenantPermissionTeam)
}
- if err := NewAgentService().UpdateAgent(ownerCtx, "owner-1", "canvas-team-edit", map[string]interface{}{
+ if err := NewAgentService().UpdateAgent(ownerCtx, "canvas-team-edit", map[string]interface{}{
"permission": nextPermission,
}); err != nil {
t.Fatalf("canvas owner could not change permission: %v", err)
@@ -2011,7 +2007,7 @@ func TestUpdateAgentRejectsDuplicateTitleInDestinationCategory(t *testing.T) {
t.Fatalf("failed to seed duplicate agent: %v", err)
}
- err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-source-category", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "canvas-source-category", map[string]interface{}{
"title": "Duplicate Title",
"canvas_category": "dataflow_canvas",
})
@@ -2043,7 +2039,7 @@ func TestUpdateAgentRejectsCategoryOnlyDuplicateTitleInDestinationCategory(t *te
}
ctx := serviceTestContext(t, "user-1", "user-1")
- err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-category-only-source", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "canvas-category-only-source", map[string]interface{}{
"canvas_category": "dataflow_canvas",
})
if err == nil || err.Error() != "Shared Title already exists." {
@@ -2065,7 +2061,7 @@ func TestUpdateAgentAllowsCaseOnlyTitleChange(t *testing.T) {
t.Fatalf("failed to seed agent: %v", err)
}
- if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-case-only-title", map[string]interface{}{
+ if err := NewAgentService().UpdateAgent(ctx, "canvas-case-only-title", map[string]interface{}{
"title": "case title",
}); err != nil {
t.Fatalf("UpdateAgent failed for case-only title change: %v", err)
@@ -2094,7 +2090,7 @@ func TestCreateAgentDedupesDuplicateTitle(t *testing.T) {
t.Fatalf("failed to seed agent: %v", err)
}
- row, code, err := NewAgentService().CreateAgent(ctx, "user-1", &CreateAgentRequest{
+ row, code, err := NewAgentService().CreateAgent(ctx, &CreateAgentRequest{
Title: sptr("Dup Title"),
DSL: entity.JSONMap{},
})
@@ -2149,7 +2145,7 @@ func seedAgentServiceCreateContext(t *testing.T) context.Context {
}
func TestCreateAgentRequiresAuthenticatedUserID(t *testing.T) {
- row, code, err := NewAgentService().CreateAgent(t.Context(), " ", &CreateAgentRequest{
+ row, code, err := NewAgentService().CreateAgent(t.Context(), &CreateAgentRequest{
Title: sptr("Agent"),
DSL: entity.JSONMap{},
})
@@ -2172,7 +2168,7 @@ func TestUpdateAgentPersistsDSLAsJSONMap(t *testing.T) {
t.Fatalf("failed to seed agent: %v", err)
}
- err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-dsl-update", map[string]interface{}{
+ err := NewAgentService().UpdateAgent(ctx, "canvas-dsl-update", map[string]interface{}{
"dsl": map[string]interface{}{
"graph": map[string]interface{}{
"nodes": []interface{}{map[string]interface{}{"id": "begin"}},
@@ -2232,14 +2228,14 @@ func TestUpdateAgentDSLCreatesAndReplacesDraftVersion(t *testing.T) {
},
},
}
- if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-version-draft", patch); err != nil {
+ if err := NewAgentService().UpdateAgent(ctx, "canvas-version-draft", patch); err != nil {
t.Fatalf("first UpdateAgent failed: %v", err)
}
secondPatch := map[string]interface{}{
"title": "Renamed Agent",
"dsl": patch["dsl"],
}
- if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-version-draft", secondPatch); err != nil {
+ if err := NewAgentService().UpdateAgent(ctx, "canvas-version-draft", secondPatch); err != nil {
t.Fatalf("second UpdateAgent failed: %v", err)
}
@@ -2293,7 +2289,7 @@ func TestUpdateAgentReleaseTrueMarksCanvasAndVersionReleased(t *testing.T) {
ctx := serviceTestContext(t, "user-1", "user-1")
// The front-end publish flow sends release as the string "true".
- if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-update-release", map[string]interface{}{
+ if err := NewAgentService().UpdateAgent(ctx, "canvas-update-release", map[string]interface{}{
"title": "Release Agent",
"release": "true",
"dsl": map[string]interface{}{
@@ -2359,7 +2355,7 @@ func TestUpdateAgentWithoutReleaseKeepsCanvasUnreleased(t *testing.T) {
// Python parity: update_agent coerces a missing release to False and
// always writes it back to the canvas row.
ctx := serviceTestContext(t, "user-1", "user-1")
- if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-update-draft", map[string]interface{}{
+ if err := NewAgentService().UpdateAgent(ctx, "canvas-update-draft", map[string]interface{}{
"title": "Draft Agent",
"dsl": map[string]interface{}{
"graph": map[string]interface{}{
@@ -2410,7 +2406,7 @@ func TestListAgentsIncludesReleaseTime(t *testing.T) {
t.Fatalf("failed to seed released version: %v", err)
}
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "", "", nil)
+ resp, code, err := NewAgentService().ListAgents(ctx, "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents failed: code=%v err=%v", code, err)
}
@@ -2460,7 +2456,7 @@ func TestListAgents_MultiCategoryFilter(t *testing.T) {
}
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "dataflow_canvas,agent_canvas", "", nil)
+ resp, code, err := NewAgentService().ListAgents(ctx, "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "dataflow_canvas,agent_canvas", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents failed: code=%v err=%v", code, err)
}
@@ -2468,7 +2464,7 @@ func TestListAgents_MultiCategoryFilter(t *testing.T) {
t.Fatalf("multi-category filter returned total=%d rows=%d, want 3/3", resp.Total, len(resp.Canvas))
}
- single, code, err := NewAgentService().ListAgents(ctx, "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "agent_canvas", "", nil)
+ single, code, err := NewAgentService().ListAgents(ctx, "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "agent_canvas", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents (single category) failed: code=%v err=%v", code, err)
}
@@ -2509,7 +2505,7 @@ func TestListAgents_MergesCompilationTemplateGroups(t *testing.T) {
t.Fatalf("failed to seed builtin group: %v", err)
}
- resp, code, err := NewAgentService().ListAgents(serviceTestContext(t, "user-1", "user-1"), "user-1", "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "", "", nil)
+ resp, code, err := NewAgentService().ListAgents(serviceTestContext(t, "user-1", "user-1"), "", 1, 30, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil, "", "", nil)
if err != nil || code != common.CodeSuccess {
t.Fatalf("ListAgents failed: code=%v err=%v", code, err)
}
@@ -2658,7 +2654,7 @@ func TestPublishAgentUpdatesCanvasAndReleasedVersion(t *testing.T) {
},
},
}
- row, err := NewAgentService().PublishAgent(ctx, "user-1", "canvas-publish", &PublishAgentRequest{
+ row, err := NewAgentService().PublishAgent(ctx, "canvas-publish", &PublishAgentRequest{
Title: &publishTitle,
Description: &description,
DSL: publishDSL,
@@ -2754,7 +2750,7 @@ func TestUpdateAgentDSLDoesNotOverwriteLatestReleasedVersion(t *testing.T) {
t.Fatalf("failed to seed released version: %v", err)
}
- if err := NewAgentService().UpdateAgent(ctx, "user-1", "canvas-released-latest", map[string]interface{}{"dsl": map[string]interface{}(dsl)}); err != nil {
+ if err := NewAgentService().UpdateAgent(ctx, "canvas-released-latest", map[string]interface{}{"dsl": map[string]interface{}(dsl)}); err != nil {
t.Fatalf("UpdateAgent failed: %v", err)
}
@@ -2792,7 +2788,7 @@ func TestResetAgentServiceOtherTenant(t *testing.T) {
createAgentSessionTestCanvas(t, "canvas-1", "user-2")
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := NewAgentService().ResetAgent(ctx, "user-1", "canvas-1")
+ _, err := NewAgentService().ResetAgent(ctx, "canvas-1")
if !errors.Is(err, dao.ErrUserCanvasNotFound) {
t.Errorf("expected ErrUserCanvasNotFound for cross-tenant access, got %v", err)
}
@@ -2819,7 +2815,7 @@ func TestGetAgentSession_RejectsIDOR(t *testing.T) {
createAgentSessionTestConversation(t, "session-1", "agent-1", "user-1", 1000)
ctx := serviceTestContext(t, "user-1", "user-1")
- data, code, err := NewAgentService().GetAgentSession(ctx, "user-1", "agent-2", "session-1")
+ data, code, err := NewAgentService().GetAgentSession(ctx, "agent-2", "session-1")
if err == nil {
t.Fatal("expected non-nil error for cross-agent session access")
}
@@ -2842,7 +2838,7 @@ func TestGetAgentSession_SuccessWhenAgentMatches(t *testing.T) {
createAgentSessionTestConversation(t, "session-1", "agent-1", "user-1", 1000)
ctx := serviceTestContext(t, "user-1", "user-1")
- data, code, err := NewAgentService().GetAgentSession(ctx, "user-1", "agent-1", "session-1")
+ data, code, err := NewAgentService().GetAgentSession(ctx, "agent-1", "session-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -2872,7 +2868,7 @@ func TestDeleteAgentSessionItem_RejectsIDOR(t *testing.T) {
createAgentSessionTestConversation(t, "session-1", "agent-1", "user-1", 1000)
ctx := serviceTestContext(t, "user-1", "user-1")
- deleted, code, err := NewAgentService().DeleteAgentSessionItem(ctx, "user-1", "agent-2", "session-1")
+ deleted, code, err := NewAgentService().DeleteAgentSessionItem(ctx, "agent-2", "session-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -2884,7 +2880,7 @@ func TestDeleteAgentSessionItem_RejectsIDOR(t *testing.T) {
}
// The session must still exist — the cross-agent delete was a no-op.
- verify, _, err := NewAgentService().GetAgentSession(ctx, "user-1", "agent-1", "session-1")
+ verify, _, err := NewAgentService().GetAgentSession(ctx, "agent-1", "session-1")
if err != nil {
t.Fatalf("session should still exist for the legitimate owner: %v", err)
}
@@ -2965,7 +2961,7 @@ func TestDeleteAgent_SharedCanvasMemberCannotDeleteAgent(t *testing.T) {
setupAgentSessionServiceTest(t)
createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "owner-1")
- err := NewAgentService().DeleteAgent(serviceTestContext(t, "user-1", "owner-1", "owner-1", "user-1"), "user-1", "canvas-1")
+ err := NewAgentService().DeleteAgent(serviceTestContext(t, "user-1", "owner-1", "owner-1", "user-1"), "canvas-1")
if !errors.Is(err, ErrAgentNotOwner) {
t.Fatalf("DeleteAgent error = %v, want ErrAgentNotOwner", err)
}
@@ -2982,7 +2978,7 @@ func TestDeleteAgentSessionItem_SharedCanvasGrantsDeleteAccess(t *testing.T) {
setupAgentSessionServiceTest(t)
createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "owner-1")
- deleted, code, err := NewAgentService().DeleteAgentSessionItem(serviceTestContext(t, "user-1", "owner-1", "owner-1", "user-1"), "user-1", "canvas-1", "session-1")
+ deleted, code, err := NewAgentService().DeleteAgentSessionItem(serviceTestContext(t, "user-1", "owner-1", "owner-1", "user-1"), "canvas-1", "session-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -3006,7 +3002,7 @@ func TestDeleteAgentSessionItem_SessionCreatorCanDeleteOwnSession(t *testing.T)
setupAgentSessionServiceTest(t)
createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "user-1")
- deleted, code, err := NewAgentService().DeleteAgentSessionItem(serviceTestContext(t, "user-1", "owner-1", "owner-1", "user-1"), "user-1", "canvas-1", "session-1")
+ deleted, code, err := NewAgentService().DeleteAgentSessionItem(serviceTestContext(t, "user-1", "owner-1", "owner-1", "user-1"), "canvas-1", "session-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -3022,7 +3018,7 @@ func TestDeleteAgentSessionItem_CanvasOwnerCanDeleteAnySession(t *testing.T) {
setupAgentSessionServiceTest(t)
createTeamSharedAgentTestFixtures(t, "owner-1", "user-1", "session-1", "user-1")
- deleted, code, err := NewAgentService().DeleteAgentSessionItem(serviceTestContext(t, "owner-1", "owner-1", "owner-1", "user-1"), "owner-1", "canvas-1", "session-1")
+ deleted, code, err := NewAgentService().DeleteAgentSessionItem(serviceTestContext(t, "owner-1", "owner-1", "owner-1", "user-1"), "canvas-1", "session-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
diff --git a/internal/service/agent_tool_history_test.go b/internal/service/agent_tool_history_test.go
index 26aae65d98..cc374aea23 100644
--- a/internal/service/agent_tool_history_test.go
+++ b/internal/service/agent_tool_history_test.go
@@ -254,7 +254,7 @@ func TestRunAgent_ToolHistoryPersists(t *testing.T) {
}
tracker, _ := newAgentCancelTracker(t)
svc := NewAgentServiceWithOptions(nil, nil, tracker)
- events, err := svc.RunAgent(WithAgentSessionID(ctx, sessionID), "user-1", canvasID, sessionID, "", "Find the manual", nil)
+ events, err := svc.RunAgent(WithAgentSessionID(ctx, sessionID), canvasID, sessionID, "", "Find the manual", nil)
if err != nil {
t.Fatal(err)
}
@@ -349,7 +349,7 @@ func TestRunAgent_ToolHistoryPersists(t *testing.T) {
t.Errorf("persisted memory missing summary: %s", raw)
}
// A fresh direct-answer turn reuses persisted DSL but must not re-summarize old calls.
- events, err = svc.RunAgent(WithAgentSessionID(ctx, sessionID), "user-1", canvasID, sessionID, "", "direct on next turn", nil)
+ events, err = svc.RunAgent(WithAgentSessionID(ctx, sessionID), canvasID, sessionID, "", "direct on next turn", nil)
if err != nil {
t.Fatal(err)
}
diff --git a/internal/service/agent_version_test.go b/internal/service/agent_version_test.go
index 835163afe8..b6c31a08fb 100644
--- a/internal/service/agent_version_test.go
+++ b/internal/service/agent_version_test.go
@@ -63,13 +63,13 @@ func TestApplyVersionDraftSave(t *testing.T) {
wantErr = context.Canceled
}
svc := NewAgentService()
- err := svc.ApplyVersion(ctx, "user-1", current.ID, version.ID)
+ err := svc.ApplyVersion(ctx, current.ID, version.ID)
if !errors.Is(err, wantErr) {
t.Fatalf("ApplyVersion error = %v, want %v", err, wantErr)
}
wantDSL, wantRelease := current.DSL, true
if wantErr == nil {
- if err := svc.ApplyVersion(ctx, "user-1", current.ID, version.ID); err != nil {
+ if err := svc.ApplyVersion(ctx, current.ID, version.ID); err != nil {
t.Fatalf("repeated ApplyVersion failed: %v", err)
}
wantDSL, wantRelease = version.DSL, false
diff --git a/internal/service/agent_webhook_credential.go b/internal/service/agent_webhook_credential.go
index a6d2ab6f77..627a0c9505 100644
--- a/internal/service/agent_webhook_credential.go
+++ b/internal/service/agent_webhook_credential.go
@@ -149,13 +149,17 @@ func (s *AgentWebhookCredentialService) Resolve(ctx context.Context, canvasID, t
// Revoke removes the authenticated user's ability to trigger this canvas with
// their webhook credential. The operation is idempotent.
-func (s *AgentWebhookCredentialService) Revoke(ctx context.Context, canvasID, userID string) error {
+func (s *AgentWebhookCredentialService) Revoke(ctx context.Context, canvasID string) error {
if s == nil || s.db == nil {
return gorm.ErrInvalidDB
}
- if strings.TrimSpace(canvasID) == "" || strings.TrimSpace(userID) == "" {
+ if strings.TrimSpace(canvasID) == "" {
return permission.ErrInvalidPermission
}
+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))
+ if userID == "" {
+ return permission.ErrUnauthenticated
+ }
return dao.RevokeAgentWebhookCredential(ctx, s.db, canvasID, userID)
}
diff --git a/internal/service/agent_webhook_credential_test.go b/internal/service/agent_webhook_credential_test.go
index 60f92a7b40..c16bbee025 100644
--- a/internal/service/agent_webhook_credential_test.go
+++ b/internal/service/agent_webhook_credential_test.go
@@ -103,10 +103,13 @@ func TestAgentWebhookCredentialUsesBoundPrincipalAndCanBeRotated(t *testing.T) {
if _, err := svc.Resolve(ctx, canvas.ID, secondToken); !errors.Is(err, ErrInvalidAgentWebhookCredential) {
t.Fatalf("removed member token resolution error = %v, want invalid credential", err)
}
- if err := svc.Revoke(ctx, canvas.ID, "caller-1"); err != nil {
+ if err := svc.Revoke(permission.WithIdentity(t.Context(), "", ""), canvas.ID); !errors.Is(err, permission.ErrUnauthenticated) {
+ t.Fatalf("revoke without authenticated user error = %v, want unauthenticated", err)
+ }
+ if err := svc.Revoke(ctx, canvas.ID); err != nil {
t.Fatalf("revoke credential: %v", err)
}
- if err := svc.Revoke(ctx, canvas.ID, "caller-1"); err != nil {
+ if err := svc.Revoke(ctx, canvas.ID); err != nil {
t.Fatalf("repeat revoke: %v", err)
}
if _, err := svc.Resolve(ctx, canvas.ID, secondToken); !errors.Is(err, ErrInvalidAgentWebhookCredential) {
diff --git a/internal/service/bot.go b/internal/service/bot.go
index b6561b366c..a2ee14510a 100644
--- a/internal/service/bot.go
+++ b/internal/service/bot.go
@@ -65,7 +65,7 @@ func NewBotService(agentSvc *AgentService) *BotService {
}
// ChatbotInfo returns the public metadata of a chatbot dialog.
-func (s *BotService) ChatbotInfo(ctx context.Context, userID, dialogID string) (
+func (s *BotService) ChatbotInfo(ctx context.Context, dialogID string) (
title, avatar, prologue, llmID string, hasWebSearch bool, ec common.ErrorCode, err error,
) {
if err = permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: dialogID}, permission.OperationRead); err != nil {
@@ -102,11 +102,11 @@ func (s *BotService) ChatbotInfo(ctx context.Context, userID, dialogID string) (
// Mirrors the python `bot_api.py::agentbot_inputs` handler. The
// authorisation check is the same IDOR guard the production
// AgentService uses (canvas must be visible to the requesting user).
-func (s *BotService) AgentbotInputs(ctx context.Context, userID, agentID string) (
+func (s *BotService) AgentbotInputs(ctx context.Context, agentID string) (
title, avatar, prologue, mode string, inputs map[string]any,
ec common.ErrorCode, err error,
) {
- cv, err := s.loadCanvas(ctx, userID, agentID, permission.OperationRead)
+ cv, err := s.loadCanvas(ctx, agentID, permission.OperationRead)
if err != nil {
return "", "", "", "", nil, common.CodeDataError, err
}
@@ -141,7 +141,7 @@ func (s *BotService) AgentbotInputs(ctx context.Context, userID, agentID string)
// is the cheap fast-fail that costs a single DAO roundtrip
// instead of a full canvas compile.
func (s *BotService) AgentbotCompletion(
- ctx context.Context, userID, agentID string, req AgentbotCompletionRequest,
+ ctx context.Context, agentID string, req AgentbotCompletionRequest,
) (<-chan canvas.RunEvent, common.ErrorCode, error) {
question, err := ResolveCompletionQuestion(req.Question, req.Query, req.Messages)
if err != nil {
@@ -151,16 +151,16 @@ func (s *BotService) AgentbotCompletion(
if s.agentService == nil {
return nil, common.CodeServerError, fmt.Errorf("bot: agent service not wired")
}
- if _, err := s.loadCanvas(ctx, userID, agentID, permission.OperationRun); err != nil {
+ if _, err := s.loadCanvas(ctx, agentID, permission.OperationRun); err != nil {
return nil, common.CodeDataError, err
}
userInput := NormalizeAgentInput(question, req.UserInput)
var ch <-chan canvas.RunEvent
if req.Release != nil && *req.Release {
- ch, err = s.agentService.runReleasedAgent(ctx, userID, agentID,
+ ch, err = s.agentService.runReleasedAgent(ctx, agentID,
req.SessionID, userInput, req.Files)
} else {
- ch, err = s.agentService.RunAgent(ctx, userID, agentID,
+ ch, err = s.agentService.RunAgent(ctx, agentID,
req.SessionID, "", userInput, req.Files)
}
if err != nil {
@@ -172,8 +172,8 @@ func (s *BotService) AgentbotCompletion(
// AgentbotLogs returns the stored execution timeline for an agentbot run.
// Access is scoped to the caller's accessible tenants, matching the Python
// agent_bot_logs endpoint.
-func (s *BotService) AgentbotLogs(ctx context.Context, userID, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
- if _, err := s.loadCanvas(ctx, userID, agentID, permission.OperationRead); err != nil {
+func (s *BotService) AgentbotLogs(ctx context.Context, agentID, messageID string) (map[string]any, common.ErrorCode, error) {
+ if _, err := s.loadCanvas(ctx, agentID, permission.OperationRead); err != nil {
return nil, common.CodeDataError, err
}
payload, err := kvrocks.Get().Get(ctx, fmt.Sprintf("%s-%s-logs", agentID, messageID))
@@ -241,15 +241,12 @@ type ChatbotCompletionRequest struct {
// loadCanvas authorizes a bot operation before loading its canvas. Keeping this
// guard here prevents public bot endpoints from depending on AgentService.
-func (s *BotService) loadCanvas(ctx context.Context, userID, agentID string, operation permission.Operation) (*entity.UserCanvas, error) {
+func (s *BotService) loadCanvas(ctx context.Context, agentID string, operation permission.Operation) (*entity.UserCanvas, error) {
if agentID == "" {
return nil, dao.ErrUserCanvasNotFound
}
- if userID == "" {
- return nil, dao.ErrUserCanvasNotFound
- }
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: agentID}, operation); err != nil {
- if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) {
+ if errors.Is(err, permission.ErrResourceNotFound) || errors.Is(err, permission.ErrPermissionDenied) || errors.Is(err, permission.ErrUnauthenticated) {
return nil, dao.ErrUserCanvasNotFound
}
return nil, fmt.Errorf("bot: check canvas %s permission: %w", agentID, err)
diff --git a/internal/service/bot_completion.go b/internal/service/bot_completion.go
index 484f2f3275..0b90d77df5 100644
--- a/internal/service/bot_completion.go
+++ b/internal/service/bot_completion.go
@@ -289,7 +289,7 @@ func writeSSEJSON(w http.ResponseWriter, payload map[string]any) error {
// Authorization is checked against the Chat resource before the
// completion pipeline or session state is touched.
func (s *BotService) ChatbotCompletion(
- ctx context.Context, userID, dialogID string, req ChatbotCompletionRequest,
+ ctx context.Context, dialogID string, req ChatbotCompletionRequest,
) (<-chan ChatbotSSEFrame, common.ErrorCode, error) {
receivedAt := float64(time.Now().UnixNano()) / 1e9
question, err := ResolveCompletionQuestion(req.Question, req.Query, req.Messages)
@@ -302,6 +302,7 @@ func (s *BotService) ChatbotCompletion(
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, code, normalizedErr
}
+ userID := permission.UserIDFromContext(ctx)
dialog, err := s.chatDAO.GetDialogByID(ctx, dao.DB, dialogID)
if err != nil {
if dao.IsNotFoundErr(err) {
diff --git a/internal/service/bot_completion_history_test.go b/internal/service/bot_completion_history_test.go
index 5890a270d8..3e173cbbfe 100644
--- a/internal/service/bot_completion_history_test.go
+++ b/internal/service/bot_completion_history_test.go
@@ -182,7 +182,7 @@ func TestBotService_AgentbotInputs_CrossTenantDenied(t *testing.T) {
// Attacker (tenant-B) asks for victim (tenant-A's canvas).
title, _, _, _, _, code, err := svc.AgentbotInputs(serviceTestContext(t, "tenant-B", "tenant-B"),
- "tenant-B", "agent-victim")
+ "agent-victim")
if !errors.Is(err, dao.ErrUserCanvasNotFound) {
t.Errorf("cross-tenant: want ErrUserCanvasNotFound, got %v", err)
}
@@ -246,7 +246,7 @@ func TestBotService_AgentbotInputsReadsBeginParams(t *testing.T) {
svc := NewBotService(nil)
gotTitle, gotAvatar, prologue, mode, inputs, code, err := svc.AgentbotInputs(
- serviceTestContext(t, "owner-1", "tenant-1"), "owner-1", "agent-1")
+ serviceTestContext(t, "owner-1", "tenant-1"), "agent-1")
if err != nil {
t.Fatalf("AgentbotInputs: %v", err)
}
@@ -417,7 +417,7 @@ func TestBotService_ChatbotCompletion_NewSessionSkipsLLM(t *testing.T) {
// fail loudly, so a successful run proves the LLM was skipped.
svc := NewBotService(nil)
frames, code, err := svc.ChatbotCompletion(serviceTestContext(t, "tenant-1", "tenant-1"),
- "tenant-1", "dlg-1", ChatbotCompletionRequest{Question: ""})
+ "dlg-1", ChatbotCompletionRequest{Question: ""})
if err != nil {
t.Fatalf("ChatbotCompletion: %v", err)
}
diff --git a/internal/service/bot_permission_test.go b/internal/service/bot_permission_test.go
index 9c91d1bfb7..250d73e150 100644
--- a/internal/service/bot_permission_test.go
+++ b/internal/service/bot_permission_test.go
@@ -49,18 +49,18 @@ func TestBotServiceChatbotEndpointsUseChatPermissions(t *testing.T) {
svc := NewBotService(nil)
ownerCtx := serviceTestContext(t, "owner-1", "owner-1", "outsider")
- _, _, _, _, _, code, err := svc.ChatbotInfo(ownerCtx, "owner-1", "chat-1")
+ _, _, _, _, _, code, err := svc.ChatbotInfo(ownerCtx, "chat-1")
if err != nil || code != common.CodeSuccess {
t.Fatalf("ChatbotInfo(owner) = (%d, %v), want success", code, err)
}
outsiderCtx := serviceTestContext(t, "outsider", "owner-1", "owner-1")
- _, _, _, _, _, code, err = svc.ChatbotInfo(outsiderCtx, "outsider", "chat-1")
+ _, _, _, _, _, code, err = svc.ChatbotInfo(outsiderCtx, "chat-1")
if !errors.Is(err, permission.ErrPermissionDenied) || code != common.CodeNotFound {
t.Fatalf("ChatbotInfo(outsider) = (%d, %v), want hidden permission denial", code, err)
}
- _, code, err = svc.ChatbotCompletion(outsiderCtx, "outsider", "chat-1", ChatbotCompletionRequest{Question: "hello"})
+ _, code, err = svc.ChatbotCompletion(outsiderCtx, "chat-1", ChatbotCompletionRequest{Question: "hello"})
if !errors.Is(err, permission.ErrPermissionDenied) || code != common.CodeNotFound {
t.Fatalf("ChatbotCompletion(outsider) = (%d, %v), want hidden permission denial", code, err)
}
diff --git a/internal/service/chat.go b/internal/service/chat.go
index 2b54c9381c..27c263c4f6 100644
--- a/internal/service/chat.go
+++ b/internal/service/chat.go
@@ -107,7 +107,7 @@ type ListChatsResponse struct {
}
// ListChats list chats for a user
-func (s *ChatService) ListChats(ctx context.Context, userID, status, keywords, id, name string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string) (*ListChatsResponse, error) {
+func (s *ChatService) ListChats(ctx context.Context, status, keywords, id, name string, page, pageSize int, terms []dao.OrderTerm, ownerIDs []string) (*ListChatsResponse, error) {
chatScope, err := s.permissionChecker.Scope(ctx, permission.ScopeQuery{
Kind: permission.ResourceKindChat,
Operation: permission.OperationRead,
@@ -196,7 +196,8 @@ type CreateChatRequest struct {
TenantID *string `json:"tenant_id"`
}
-func (s *ChatService) Create(ctx context.Context, userID string, req map[string]interface{}) (map[string]interface{}, common.ErrorCode, error) {
+func (s *ChatService) Create(ctx context.Context, req map[string]interface{}) (map[string]interface{}, common.ErrorCode, error) {
+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))
tenantID, err := requireCurrentTenantID(ctx, userID)
if err != nil {
code, normalized := permissionresponse.Normalize(err)
@@ -241,7 +242,7 @@ func (s *ChatService) Create(ctx context.Context, userID string, req map[string]
datasetIDsValue, hasDatasetIDs = req["kb_ids"]
}
if hasDatasetIDs {
- kbIDs, err := s.validateCreateDatasetIDs(ctx, datasetIDsValue, userID)
+ kbIDs, err := s.validateCreateDatasetIDs(ctx, datasetIDsValue)
if err != nil {
return nil, common.CodeDataError, err
}
@@ -395,7 +396,7 @@ func validateCreateChatName(value interface{}) (string, error) {
return name, nil
}
-func (s *ChatService) validateCreateDatasetIDs(ctx context.Context, value interface{}, userID string) ([]string, error) {
+func (s *ChatService) validateCreateDatasetIDs(ctx context.Context, value interface{}) ([]string, error) {
if value == nil {
return []string{}, nil
}
@@ -820,7 +821,7 @@ const (
pyDefaultEmptyResponse = "Sorry! No relevant content was found in the knowledge base!"
)
-func (s *ChatService) getChatForOperation(ctx context.Context, userID, chatID string, operation permission.Operation) (*entity.Chat, error) {
+func (s *ChatService) getChatForOperation(ctx context.Context, chatID string, operation permission.Operation) (*entity.Chat, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, operation); err != nil {
return nil, err
}
@@ -870,20 +871,24 @@ var defaultRerankModels = map[string]struct{}{
}
// UpdateChat mirrors PUT /api/v1/chats/<chat_id> in the Python REST API.
-func (s *ChatService) UpdateChat(ctx context.Context, userID, chatID string, req map[string]interface{}) (map[string]interface{}, error) {
- return s.updateChatREST(ctx, userID, chatID, req, false)
+func (s *ChatService) UpdateChat(ctx context.Context, chatID string, req map[string]interface{}) (map[string]interface{}, error) {
+ return s.updateChatREST(ctx, chatID, req, false)
}
// PatchChat mirrors PATCH /api/v1/chats/<chat_id> in the Python REST API.
-func (s *ChatService) PatchChat(ctx context.Context, userID, chatID string, req map[string]interface{}) (map[string]interface{}, error) {
- return s.updateChatREST(ctx, userID, chatID, req, true)
+func (s *ChatService) PatchChat(ctx context.Context, chatID string, req map[string]interface{}) (map[string]interface{}, error) {
+ return s.updateChatREST(ctx, chatID, req, true)
}
-func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string, req map[string]interface{}, patch bool) (map[string]interface{}, error) {
- currentChat, err := s.getChatForOperation(ctx, userID, chatID, permission.OperationUpdate)
+func (s *ChatService) updateChatREST(ctx context.Context, chatID string, req map[string]interface{}, patch bool) (map[string]interface{}, error) {
+ currentChat, err := s.getChatForOperation(ctx, chatID, permission.OperationUpdate)
if err != nil {
return nil, err
}
+ modelTenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))
+ if modelTenantID == "" {
+ modelTenantID = currentChat.TenantID
+ }
if !patch && isTruthy(req["tenant_id"]) {
return nil, errors.New("`tenant_id` must not be provided")
@@ -909,7 +914,7 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
value, hasDatasetIDs = req["kb_ids"]
}
if hasDatasetIDs {
- kbIDs, err := s.validateRESTDatasetIDs(ctx, value, userID)
+ kbIDs, err := s.validateRESTDatasetIDs(ctx, value)
if err != nil {
return nil, err
}
@@ -933,7 +938,7 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
if value, ok := req["llm_id"]; ok {
llmID := fmt.Sprint(value)
- tenantLLMID, err := s.resolveRESTLLMID(ctx, llmID, userID, llmSetting)
+ tenantLLMID, err := s.resolveRESTLLMID(ctx, llmID, modelTenantID, llmSetting)
if err != nil {
return nil, err
}
@@ -950,7 +955,7 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
req["tenant_decision_id"] = nil
} else {
modelFactory := NewModelFactory()
- target, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: userID}, entity.ModelTypeDecision, decisionID)
+ target, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: modelTenantID}, entity.ModelTypeDecision, decisionID)
if err != nil {
return nil, fmt.Errorf("`decision_id` %s doesn't exist", decisionID)
}
@@ -960,7 +965,7 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
if value, ok := req["rerank_id"]; ok {
rerankID := fmt.Sprint(value)
- tenantRerankID, err := s.resolveRESTRerankID(ctx, rerankID, userID)
+ tenantRerankID, err := s.resolveRESTRerankID(ctx, rerankID, modelTenantID)
if err != nil {
return nil, err
}
@@ -1014,7 +1019,7 @@ func (s *ChatService) updateChatREST(ctx context.Context, userID, chatID string,
currentName = *currentChat.Name
}
available, err := common.NameAvailable(currentName, name, func(candidate string) (bool, error) {
- return s.chatDAO.ExistsByNameTenantStatus(ctx, dao.DB, candidate, userID, string(entity.StatusValid))
+ return s.chatDAO.ExistsByNameTenantStatus(ctx, dao.DB, candidate, currentChat.TenantID, string(entity.StatusValid))
})
if err != nil {
return nil, err
@@ -1139,7 +1144,7 @@ func validateRESTChatName(value interface{}, required bool) (string, bool, error
return name, true, nil
}
-func (s *ChatService) validateRESTDatasetIDs(ctx context.Context, value interface{}, userID string) (entity.JSONSlice, error) {
+func (s *ChatService) validateRESTDatasetIDs(ctx context.Context, value interface{}) (entity.JSONSlice, error) {
if value == nil {
return entity.JSONSlice{}, nil
}
@@ -1294,8 +1299,8 @@ func (s *ChatService) buildRESTChatResponse(ctx context.Context, chat *entity.Ch
}
// DeleteChat soft deletes a single chat owned by the current user.
-func (s *ChatService) DeleteChat(ctx context.Context, userID, chatID string) error {
- if _, err := s.getChatForOperation(ctx, userID, chatID, permission.OperationDelete); err != nil {
+func (s *ChatService) DeleteChat(ctx context.Context, chatID string) error {
+ if _, err := s.getChatForOperation(ctx, chatID, permission.OperationDelete); err != nil {
return err
}
if err := s.chatDAO.UpdateByID(ctx, dao.DB, chatID, map[string]interface{}{
@@ -1339,7 +1344,7 @@ func checkDuplicateChatIDs(ids []string) ([]string, []string) {
}
// BulkDeleteChats soft deletes chats owned by the current user with partial success semantics.
-func (s *ChatService) BulkDeleteChats(ctx context.Context, userID string, req *BulkDeleteChatsRequest) (map[string]interface{}, error) {
+func (s *ChatService) BulkDeleteChats(ctx context.Context, req *BulkDeleteChatsRequest) (map[string]interface{}, error) {
ids := req.IDs
if len(ids) == 0 && req.DeleteAll {
chatScope, err := s.permissionChecker.Scope(ctx, permission.ScopeQuery{
@@ -1365,7 +1370,7 @@ func (s *ChatService) BulkDeleteChats(ctx context.Context, userID string, req *B
successCount := 0
for _, chatID := range uniqueIDs {
- if _, err := s.getChatForOperation(ctx, userID, chatID, permission.OperationDelete); err != nil {
+ if _, err := s.getChatForOperation(ctx, chatID, permission.OperationDelete); err != nil {
errorsList = append(errorsList, fmt.Sprintf("Chat(%s) not found.", chatID))
continue
}
@@ -1410,7 +1415,7 @@ type GetChatResponse struct {
}
// GetChat gets chat detail by ID with permission check
-func (s *ChatService) GetChat(ctx context.Context, userID string, chatID string) (*GetChatResponse, error) {
+func (s *ChatService) GetChat(ctx context.Context, chatID string) (*GetChatResponse, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationRead); err != nil {
return nil, err
}
diff --git a/internal/service/chat_agentic_config.go b/internal/service/chat_agentic_config.go
index 2bb0c3b119..0e8dc92a6d 100644
--- a/internal/service/chat_agentic_config.go
+++ b/internal/service/chat_agentic_config.go
@@ -8,8 +8,8 @@ import (
)
// GetAgenticRAGConfig resolves the chat's saved override against current defaults.
-func (s *ChatService) GetAgenticRAGConfig(ctx context.Context, userID, chatID string) (*agentic_rag.Settings, error) {
- chat, err := s.getChatForOperation(ctx, userID, chatID, permission.OperationRead)
+func (s *ChatService) GetAgenticRAGConfig(ctx context.Context, chatID string) (*agentic_rag.Settings, error) {
+ chat, err := s.getChatForOperation(ctx, chatID, permission.OperationRead)
if err != nil {
return nil, err
}
diff --git a/internal/service/chat_agentic_config_test.go b/internal/service/chat_agentic_config_test.go
index 4f773477f3..9866806c27 100644
--- a/internal/service/chat_agentic_config_test.go
+++ b/internal/service/chat_agentic_config_test.go
@@ -27,7 +27,7 @@ func TestChatAgenticConfigPersistsAndResets(t *testing.T) {
map[string]any{"tools": []any{"grep_chunks", "list_chunks"}},
nil,
} {
- _, err := svc.PatchChat(ctx, "user-1", "chat-1", map[string]any{
+ _, err := svc.PatchChat(ctx, "chat-1", map[string]any{
"prompt_config": map[string]any{"agentic_rag": override},
})
if err != nil {
@@ -45,7 +45,7 @@ func TestChatAgenticConfigPersistsAndResets(t *testing.T) {
if chat.PromptConfig["system"] != "old system" || chat.PromptConfig["quote"] != true {
t.Fatalf("unrelated settings changed: %#v", chat.PromptConfig)
}
- settings, err := reloaded.GetAgenticRAGConfig(ctx, "user-1", "chat-1")
+ settings, err := reloaded.GetAgenticRAGConfig(ctx, "chat-1")
if err != nil || settings == nil {
t.Fatalf("GetAgenticRAGConfig() = (%#v, %v)", settings, err)
}
@@ -74,7 +74,7 @@ func TestChatAgenticConfigCreateAndPut(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
override := map[string]any{"content": "Created instruction", "tools": []any{"grep_chunks", "list_chunks"}}
- result, code, err := svc.Create(ctx, "user-1", map[string]any{
+ result, code, err := svc.Create(ctx, map[string]any{
"name": "Agentic configuration",
"prompt_config": map[string]any{"agentic_rag": override},
})
@@ -89,7 +89,7 @@ func TestChatAgenticConfigCreateAndPut(t *testing.T) {
if !reflect.DeepEqual(chat.PromptConfig["agentic_rag"], override) {
t.Fatalf("create did not persist override: %#v", chat.PromptConfig)
}
- _, err = svc.UpdateChat(ctx, "user-1", chatID, map[string]any{
+ _, err = svc.UpdateChat(ctx, chatID, map[string]any{
"prompt_config": map[string]any{"agentic_rag": nil, "system": "replacement"},
})
if err != nil {
@@ -125,20 +125,21 @@ func TestChatAgenticConfigRejectsInvalidWrites(t *testing.T) {
db := setupChatRESTUpdateServiceTestDB(t)
createChatRESTUpdateServiceTestChat(t, db, "chat-1", "user-1")
svc := NewChatService()
+ ctx := serviceTestContext(t, "user-1", "user-1")
for _, method := range []string{"create", "put", "patch"} {
payload := map[string]any{"prompt_config": map[string]any{"agentic_rag": override}}
var err error
switch method {
case "create":
payload["name"] = "Invalid configuration"
- _, _, err = svc.Create(t.Context(), "user-1", payload)
+ _, _, err = svc.Create(ctx, payload)
case "put":
- _, err = svc.UpdateChat(t.Context(), "user-1", "chat-1", payload)
+ _, err = svc.UpdateChat(ctx, "chat-1", payload)
case "patch":
- _, err = svc.PatchChat(t.Context(), "user-1", "chat-1", payload)
+ _, err = svc.PatchChat(ctx, "chat-1", payload)
}
- if err == nil {
- t.Fatalf("%s accepted invalid override %#v", method, override)
+ if err == nil || !strings.Contains(err.Error(), "agentic_rag") {
+ t.Fatalf("%s validation error = %v for invalid override %#v", method, err, override)
}
}
chat, err := svc.chatDAO.GetByID(t.Context(), dao.DB, "chat-1")
@@ -161,10 +162,10 @@ func TestChatAgenticConfigEnforcesPermissions(t *testing.T) {
createChatRESTUpdateServiceTestChat(t, db, "other-chat", "other-tenant")
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- if _, err := svc.GetAgenticRAGConfig(ctx, "user-1", "other-chat"); !errors.Is(err, permission.ErrResourceNotFound) && !errors.Is(err, permission.ErrPermissionDenied) {
+ if _, err := svc.GetAgenticRAGConfig(ctx, "other-chat"); !errors.Is(err, permission.ErrResourceNotFound) && !errors.Is(err, permission.ErrPermissionDenied) {
t.Fatalf("cross-tenant read error = %v", err)
}
- _, err := svc.PatchChat(ctx, "user-1", "other-chat", map[string]any{
+ _, err := svc.PatchChat(ctx, "other-chat", map[string]any{
"prompt_config": map[string]any{"agentic_rag": map[string]any{"content": "Forbidden"}},
})
if !errors.Is(err, permission.ErrResourceNotFound) && !errors.Is(err, permission.ErrPermissionDenied) {
diff --git a/internal/service/chat_channel.go b/internal/service/chat_channel.go
index dff05c4c15..1de83ca21a 100644
--- a/internal/service/chat_channel.go
+++ b/internal/service/chat_channel.go
@@ -77,7 +77,7 @@ func getChatChannelRuntimeProvider() ChatChannelRuntimeProvider {
return chatChannelRuntimeProvider
}
-func (s *ChatChannelService) List(ctx context.Context, userID string) ([]*entity.ChatChannelListResponse, error) {
+func (s *ChatChannelService) List(ctx context.Context) ([]*entity.ChatChannelListResponse, error) {
channelScope, err := permission.NewDatabaseChecker(dao.DB).Scope(ctx, permission.ScopeQuery{
Kind: permission.ResourceKindChatChannel,
Operation: permission.OperationRead,
@@ -92,10 +92,8 @@ func (s *ChatChannelService) List(ctx context.Context, userID string) ([]*entity
return s.chatChannelDAO.ListByIDs(ctx, dao.DB, channelIDs)
}
-func (s *ChatChannelService) CreateChatChannel(ctx context.Context, userID, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
- if strings.TrimSpace(userID) == "" {
- return nil, permission.ErrUnauthenticated
- }
+func (s *ChatChannelService) CreateChatChannel(ctx context.Context, name, channelType string, config entity.JSONMap, chatID *string) (*entity.ChatChannel, error) {
+ userID := permission.UserIDFromContext(ctx)
tenantID, err := requireCurrentTenantID(ctx, userID)
if err != nil {
return nil, err
@@ -135,7 +133,7 @@ func (s *ChatChannelService) CreateChatChannel(ctx context.Context, userID, name
return created, nil
}
-func (s *ChatChannelService) GetChatChannel(ctx context.Context, userID, channelID string) (*entity.ChatChannel, common.ErrorCode, error) {
+func (s *ChatChannelService) GetChatChannel(ctx context.Context, channelID string) (*entity.ChatChannel, common.ErrorCode, error) {
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChatChannel, ID: channelID}, permission.OperationRead); err != nil {
code, permissionErr := permissionresponse.NormalizeHidden(err)
return nil, code, permissionErr
@@ -152,7 +150,7 @@ func (s *ChatChannelService) GetChatChannel(ctx context.Context, userID, channel
return channel, common.CodeSuccess, nil
}
-func (s *ChatChannelService) UpdateChatChannel(ctx context.Context, userID, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error) {
+func (s *ChatChannelService) UpdateChatChannel(ctx context.Context, channelID string, req map[string]interface{}) (*entity.ChatChannel, common.ErrorCode, error) {
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChatChannel, ID: channelID}, permission.OperationUpdate); err != nil {
code, permissionErr := permissionresponse.NormalizeHidden(err)
return nil, code, permissionErr
@@ -201,7 +199,7 @@ func (s *ChatChannelService) UpdateChatChannel(ctx context.Context, userID, chan
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, code, normalizedErr
}
- if channel.TenantID != userID {
+ if channel.TenantID != strings.TrimSpace(permission.UserIDFromContext(ctx)) {
ownerCtx := permission.WithIdentity(ctx, channel.TenantID, channel.TenantID)
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ownerCtx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationUse); err != nil {
code, normalizedErr := permissionresponse.NormalizeHidden(err)
@@ -231,7 +229,7 @@ func (s *ChatChannelService) UpdateChatChannel(ctx context.Context, userID, chan
}
// GetChatChannelRuntime returns the live runtime metadata for a WhatsApp chat channel.
-func (s *ChatChannelService) GetChatChannelRuntime(ctx context.Context, userID, channelID string) (map[string]any, common.ErrorCode, error) {
+func (s *ChatChannelService) GetChatChannelRuntime(ctx context.Context, channelID string) (map[string]any, common.ErrorCode, error) {
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChatChannel, ID: channelID}, permission.OperationUse); err != nil {
code, permissionErr := permissionresponse.NormalizeHidden(err)
return nil, code, permissionErr
@@ -287,9 +285,9 @@ func (s *ChatChannelService) HandleIncomingMessage(ctx context.Context, msg Chat
return "", err
}
+ completionCtx := permission.WithIdentity(ctx, dialog.TenantID, dialog.TenantID)
result, err := s.chatSessionSvc.ChatCompletions(
- ctx,
- dialog.TenantID,
+ completionCtx,
dialog.ID,
session.ID,
[]map[string]interface{}{{"role": "user", "content": msg.Text}},
@@ -313,7 +311,7 @@ func (s *ChatChannelService) HandleIncomingMessage(ctx context.Context, msg Chat
return answer, nil
}
-func (s *ChatChannelService) DeleteChatChannel(ctx context.Context, userID, channelID string) (bool, common.ErrorCode, error) {
+func (s *ChatChannelService) DeleteChatChannel(ctx context.Context, channelID string) (bool, common.ErrorCode, error) {
if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChatChannel, ID: channelID}, permission.OperationDelete); err != nil {
code, permissionErr := permissionresponse.NormalizeHidden(err)
return false, code, permissionErr
diff --git a/internal/service/chat_channel_test.go b/internal/service/chat_channel_test.go
index 01ae032c4d..b9f4d81213 100644
--- a/internal/service/chat_channel_test.go
+++ b/internal/service/chat_channel_test.go
@@ -95,7 +95,6 @@ func TestChatChannelServiceCreateAndList(t *testing.T) {
ctx := serviceTestContext(t, "tenant-1", "tenant-1")
channel, err := svc.CreateChatChannel(
ctx,
- "tenant-1",
"bot-a",
"dingtalk",
entity.JSONMap{"token": "abc"},
@@ -111,7 +110,7 @@ func TestChatChannelServiceCreateAndList(t *testing.T) {
t.Fatalf("unexpected created channel: %+v", channel)
}
- list, err := svc.List(ctx, "tenant-1")
+ list, err := svc.List(ctx)
if err != nil {
t.Fatalf("List failed: %v", err)
}
@@ -137,7 +136,7 @@ func TestChatChannelServiceGetChatChannelAllowsJoinedTenant(t *testing.T) {
ctx := serviceTestContext(t, "user-2", "tenant-1")
grantServiceTestResource(t, "tenant-1", "dialog", "cc-1", "user-2", testResourcePermissionRead)
- channel, code, err := NewChatChannelService().GetChatChannel(ctx, "user-2", "cc-1")
+ channel, code, err := NewChatChannelService().GetChatChannel(ctx, "cc-1")
if err != nil {
t.Fatalf("GetChatChannel failed: %v", err)
}
@@ -161,7 +160,7 @@ func TestChatChannelServiceListUsesPermissionScope(t *testing.T) {
ctx := serviceTestContext(t, "user-2", "tenant-1")
grantServiceTestResource(t, "tenant-1", "dialog", "channel-team", "user-2", testResourcePermissionRead)
- channels, err := NewChatChannelService().List(ctx, "user-2")
+ channels, err := NewChatChannelService().List(ctx)
if err != nil {
t.Fatalf("List() failed: %v", err)
}
@@ -186,7 +185,7 @@ func TestChatChannelServiceUpdateChatChannelSuccess(t *testing.T) {
})
ctx := serviceTestContext(t, "tenant-1", "tenant-1")
- updated, code, err := NewChatChannelService().UpdateChatChannel(ctx, "tenant-1", "cc-1", map[string]interface{}{
+ updated, code, err := NewChatChannelService().UpdateChatChannel(ctx, "cc-1", map[string]interface{}{
"name": "bot-b",
"config": map[string]interface{}{"token": "new"},
"chat_id": "dialog-2",
@@ -221,7 +220,7 @@ func TestChatChannelServiceUpdateChatChannelRejectsCrossTenantDialog(t *testing.
})
ctx := serviceTestContext(t, "tenant-1", "tenant-1")
- _, code, err := NewChatChannelService().UpdateChatChannel(ctx, "tenant-1", "cc-1", map[string]interface{}{
+ _, code, err := NewChatChannelService().UpdateChatChannel(ctx, "cc-1", map[string]interface{}{
"chat_id": "dialog-2",
})
if code != common.CodeNotFound {
@@ -246,7 +245,7 @@ func TestChatChannelServiceUpdateChatChannelRequiresChannelOwnerAccess(t *testin
createServiceTestMembership(t, db, "user-1", "tenant-1")
createServiceTestMembership(t, db, "user-1", "tenant-2")
- _, code, err := NewChatChannelService().UpdateChatChannel(serviceTestContext(t, "user-1", "tenant-1", "tenant-1"), "user-1", "cc-1", map[string]interface{}{
+ _, code, err := NewChatChannelService().UpdateChatChannel(serviceTestContext(t, "user-1", "tenant-1", "tenant-1"), "cc-1", map[string]interface{}{
"chat_id": "dialog-2",
})
if code != common.CodeNotFound || !errors.Is(err, permission.ErrPermissionDenied) {
@@ -272,7 +271,7 @@ func TestChatChannelServiceDeleteChatChannel(t *testing.T) {
svc := NewChatChannelService()
ctx := permission.WithIdentity(t.Context(), "user-2", "tenant-2")
- deleted, code, err := svc.DeleteChatChannel(ctx, "user-2", "cc-1")
+ deleted, code, err := svc.DeleteChatChannel(ctx, "cc-1")
if code != common.CodeNotFound || err == nil {
t.Fatalf("expected hidden resource-not-found response, got code=%v err=%v", code, err)
}
@@ -283,7 +282,7 @@ func TestChatChannelServiceDeleteChatChannel(t *testing.T) {
t.Fatal("expected delete to be rejected")
}
- deleted, code, err = svc.DeleteChatChannel(serviceTestContext(t, "tenant-1", "tenant-1"), "tenant-1", "cc-1")
+ deleted, code, err = svc.DeleteChatChannel(serviceTestContext(t, "tenant-1", "tenant-1"), "cc-1")
if err != nil {
t.Fatalf("DeleteChatChannel failed: %v", err)
}
diff --git a/internal/service/chat_delete_test.go b/internal/service/chat_delete_test.go
index e2cb73b872..18ac9304f0 100644
--- a/internal/service/chat_delete_test.go
+++ b/internal/service/chat_delete_test.go
@@ -63,7 +63,7 @@ func TestChatServiceDeleteChatRejectsNonOwner(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "tenant-1")
- err := svc.DeleteChat(ctx, "user-1", "chat-1")
+ err := svc.DeleteChat(ctx, "chat-1")
if !errors.Is(err, permission.ErrPermissionDenied) {
t.Fatalf("expected permission denied, got %v", err)
}
@@ -85,7 +85,7 @@ func TestChatServiceBulkDeleteChatsDeleteAllOnlyDeletesOwnedChats(t *testing.T)
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- result, err := svc.BulkDeleteChats(ctx, "user-1", &BulkDeleteChatsRequest{DeleteAll: true})
+ result, err := svc.BulkDeleteChats(ctx, &BulkDeleteChatsRequest{DeleteAll: true})
if err != nil {
t.Fatalf("BulkDeleteChats failed: %v", err)
}
@@ -126,7 +126,7 @@ func TestChatServiceBulkDeleteChatsReturnsPartialSuccessErrors(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- result, err := svc.BulkDeleteChats(ctx, "user-1", &BulkDeleteChatsRequest{
+ result, err := svc.BulkDeleteChats(ctx, &BulkDeleteChatsRequest{
IDs: []string{"chat-1", "chat-2", "chat-1"},
})
if err != nil {
diff --git a/internal/service/chat_list_test.go b/internal/service/chat_list_test.go
index de9f6424c4..abb557f7be 100644
--- a/internal/service/chat_list_test.go
+++ b/internal/service/chat_list_test.go
@@ -88,7 +88,7 @@ func TestChatServiceListChatsDefaultReturnsAllWithCorrectTotal(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- result, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ result, err := svc.ListChats(ctx, "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -130,7 +130,7 @@ func TestChatServiceListChatsDoesNotExposeAnotherTenantsChats(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- result, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"tenant-2"})
+ result, err := svc.ListChats(ctx, "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"tenant-2"})
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -148,7 +148,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- exactResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword_1", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ exactResult, err := svc.ListChats(ctx, "1", "list_keyword_1", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats keyword exact failed: %v", err)
}
@@ -159,7 +159,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
t.Fatalf("expected chat name 'list_keyword_1', got %+v", exactResult.Chats[0].Name)
}
- unknownResult, err := svc.ListChats(ctx, "user-1", "1", "unknown_keyword", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ unknownResult, err := svc.ListChats(ctx, "1", "unknown_keyword", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats unknown keyword failed: %v", err)
}
@@ -167,7 +167,7 @@ func TestChatServiceListChatsKeywordFiltersCorrectly(t *testing.T) {
t.Fatalf("expected 0 chats for unknown keyword, got %d", len(unknownResult.Chats))
}
- partialResult, err := svc.ListChats(ctx, "user-1", "1", "list_keyword", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ partialResult, err := svc.ListChats(ctx, "1", "list_keyword", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats partial keyword failed: %v", err)
}
@@ -185,7 +185,7 @@ func TestChatServiceListChatsPagination(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- page1, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 1, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ page1, err := svc.ListChats(ctx, "1", "", "", "", 1, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats page 1 failed: %v", err)
}
@@ -196,7 +196,7 @@ func TestChatServiceListChatsPagination(t *testing.T) {
t.Fatalf("expected total=5, got %d", page1.Total)
}
- page3, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 3, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ page3, err := svc.ListChats(ctx, "1", "", "", "", 3, 2, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats page 3 failed: %v", err)
}
@@ -215,7 +215,7 @@ func TestChatServiceListChatsExcludesDeletedChats(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- result, err := svc.ListChats(ctx, "user-1", "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
+ result, err := svc.ListChats(ctx, "1", "", "", "", 0, 0, []dao.OrderTerm{{Column: "create_time", Desc: true}}, nil)
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
@@ -236,7 +236,7 @@ func TestChatServiceListChatsExactFilters(t *testing.T) {
ctx := serviceTestContext(t, "user-1", "user-1")
terms := []dao.OrderTerm{{Column: "create_time", Desc: true}}
- byID, err := svc.ListChats(ctx, "user-1", "1", "", "chat-2", "", 0, 0, terms, nil)
+ byID, err := svc.ListChats(ctx, "1", "", "chat-2", "", 0, 0, terms, nil)
if err != nil {
t.Fatalf("ListChats by id failed: %v", err)
}
@@ -244,7 +244,7 @@ func TestChatServiceListChatsExactFilters(t *testing.T) {
t.Fatalf("expected only chat-2 for id filter, got total=%d chats=%+v", byID.Total, byID.Chats)
}
- byName, err := svc.ListChats(ctx, "user-1", "1", "", "", "exact_alpha", 0, 0, terms, nil)
+ byName, err := svc.ListChats(ctx, "1", "", "", "exact_alpha", 0, 0, terms, nil)
if err != nil {
t.Fatalf("ListChats by name failed: %v", err)
}
@@ -252,7 +252,7 @@ func TestChatServiceListChatsExactFilters(t *testing.T) {
t.Fatalf("expected only chat-1 for name filter, got total=%d chats=%+v", byName.Total, byName.Chats)
}
- withOwners, err := svc.ListChats(ctx, "user-1", "1", "", "chat-2", "", 0, 0, terms, []string{"user-1"})
+ withOwners, err := svc.ListChats(ctx, "1", "", "chat-2", "", 0, 0, terms, []string{"user-1"})
if err != nil {
t.Fatalf("ListChats by id with owner_ids failed: %v", err)
}
@@ -299,7 +299,7 @@ func TestChatServiceListChatsPaginatesOwnerBranch(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- result, err := NewChatService().ListChats(serviceTestContext(t, "user-1", "user-1"), "user-1", "1", "", "", "", tt.page, tt.pageSize, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"user-1"})
+ result, err := NewChatService().ListChats(serviceTestContext(t, "user-1", "user-1"), "1", "", "", "", tt.page, tt.pageSize, []dao.OrderTerm{{Column: "create_time", Desc: true}}, []string{"user-1"})
if err != nil {
t.Fatalf("ListChats failed: %v", err)
}
diff --git a/internal/service/chat_rest_update_test.go b/internal/service/chat_rest_update_test.go
index fa7dfbf98a..2bcdff506f 100644
--- a/internal/service/chat_rest_update_test.go
+++ b/internal/service/chat_rest_update_test.go
@@ -132,7 +132,7 @@ func TestChatServiceCreateRejectsForeignKBIDs(t *testing.T) {
db := setupChatRESTUpdateServiceTestDB(t)
insertForeignPrivateDatasetForChatTest(t, db)
- _, _, err := NewChatService().Create(serviceTestContext(t, "user-1", "user-1"), "user-1", map[string]interface{}{
+ _, _, err := NewChatService().Create(serviceTestContext(t, "user-1", "user-1"), map[string]interface{}{
"name": "chat with foreign dataset",
"kb_ids": []interface{}{"kb-private"},
})
@@ -146,7 +146,7 @@ func TestChatServicePatchRejectsForeignKBIDs(t *testing.T) {
insertForeignPrivateDatasetForChatTest(t, db)
createChatRESTUpdateServiceTestChat(t, db, "chat-1", "user-1")
- _, err := NewChatService().PatchChat(serviceTestContext(t, "user-1", "user-1"), "user-1", "chat-1", map[string]interface{}{
+ _, err := NewChatService().PatchChat(serviceTestContext(t, "user-1", "user-1"), "chat-1", map[string]interface{}{
"kb_ids": []interface{}{"kb-private"},
})
if !isAccessDeniedOrHidden(err) {
@@ -183,7 +183,7 @@ func TestChatServiceCreateDefaultsMetaDataFilter(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ resp, code, err := svc.Create(ctx, map[string]interface{}{
"name": "created chat",
})
if err != nil {
@@ -213,7 +213,7 @@ func TestChatServiceCreateAcceptsNilMetaDataFilter(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ resp, code, err := svc.Create(ctx, map[string]interface{}{
"name": "created chat",
"meta_data_filter": nil,
})
@@ -231,7 +231,7 @@ func TestChatServiceCreateRejectsInvalidMetaDataFilter(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ _, code, err := svc.Create(ctx, map[string]interface{}{
"name": "created chat",
"meta_data_filter": []interface{}{"invalid"},
})
@@ -249,7 +249,7 @@ func TestChatServicePatchChatMergesPromptConfigAndLLMSetting(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, err := svc.PatchChat(ctx, "user-1", "chat-1", map[string]interface{}{
+ resp, err := svc.PatchChat(ctx, "chat-1", map[string]interface{}{
"prompt_config": map[string]interface{}{"quote": false},
"llm_setting": map[string]interface{}{"temperature": float64(0.2)},
})
@@ -287,7 +287,7 @@ func TestChatServiceUpdateChatRejectsTenantID(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.UpdateChat(ctx, "user-1", "chat-1", map[string]interface{}{
+ _, err := svc.UpdateChat(ctx, "chat-1", map[string]interface{}{
"tenant_id": "tenant-2",
})
if err == nil || err.Error() != "`tenant_id` must not be provided" {
@@ -301,7 +301,7 @@ func TestChatServiceUpdateChatRejectsInvalidLLMSetting(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.UpdateChat(ctx, "user-1", "chat-1", map[string]interface{}{
+ _, err := svc.UpdateChat(ctx, "chat-1", map[string]interface{}{
"llm_setting": "invalid",
})
if err == nil || err.Error() != "`llm_setting` should be an object" {
@@ -323,7 +323,7 @@ func TestChatServiceUpdateChatAcceptsMetaDataFilterObject(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.UpdateChat(ctx, "user-1", "chat-1", map[string]interface{}{
+ _, err := svc.UpdateChat(ctx, "chat-1", map[string]interface{}{
"name": "chat-chat-1",
"meta_data_filter": map[string]interface{}{
"method": "disabled",
@@ -349,7 +349,7 @@ func TestChatServiceUpdateChatNormalizesKeywordsSimilarityWeight(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, err := svc.UpdateChat(ctx, "user-1", "chat-1", map[string]interface{}{
+ resp, err := svc.UpdateChat(ctx, "chat-1", map[string]interface{}{
"name": "chat-chat-1",
"keywords_similarity_weight": 0.7,
})
@@ -399,7 +399,7 @@ func TestChatServiceUpdateChatRejectsMismatchedSimilarityWeights(t *testing.T) {
db := setupChatRESTUpdateServiceTestDB(t)
createChatRESTUpdateServiceTestChat(t, db, "chat-1", "user-1")
- _, err := NewChatService().UpdateChat(serviceTestContext(t, "user-1", "user-1"), "user-1", "chat-1", map[string]interface{}{
+ _, err := NewChatService().UpdateChat(serviceTestContext(t, "user-1", "user-1"), "chat-1", map[string]interface{}{
"name": "chat-chat-1",
"keywords_similarity_weight": 0.7,
"vector_similarity_weight": 0.4,
@@ -415,7 +415,7 @@ func TestChatServiceUpdateChatBackfillsNilMetaDataFilter(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, err := svc.UpdateChat(ctx, "user-1", "chat-1", map[string]interface{}{
+ resp, err := svc.UpdateChat(ctx, "chat-1", map[string]interface{}{
"name": "chat-chat-1",
})
if err != nil {
@@ -439,7 +439,7 @@ func TestChatServicePatchChatIgnoresTenantIDAndUpdatesName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.PatchChat(ctx, "user-1", "chat-1", map[string]interface{}{
+ _, err := svc.PatchChat(ctx, "chat-1", map[string]interface{}{
"tenant_id": "tenant-2",
"name": " renamed chat ",
})
@@ -464,7 +464,7 @@ func TestChatServiceCreateValidatesName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, code, err := svc.Create(ctx, "user-1", map[string]interface{}{"name": " "})
+ _, code, err := svc.Create(ctx, map[string]interface{}{"name": " "})
if err == nil {
t.Fatal("expected name validation error")
}
@@ -482,7 +482,7 @@ func TestChatServiceCreateDedupesDuplicateName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, code, err := svc.Create(ctx, "user-1", map[string]interface{}{"name": "chat-chat-1"})
+ _, code, err := svc.Create(ctx, map[string]interface{}{"name": "chat-chat-1"})
if err != nil {
t.Fatalf("expected deduped create to succeed, got %v", err)
}
@@ -501,7 +501,7 @@ func TestChatServiceUpdateValidatesName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.UpdateChat(ctx, "user-1", "chat-1", map[string]interface{}{"name": " "})
+ _, err := svc.UpdateChat(ctx, "chat-1", map[string]interface{}{"name": " "})
if err == nil {
t.Fatal("expected name validation error")
}
@@ -517,7 +517,7 @@ func TestChatServiceUpdateRejectsDuplicateName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.UpdateChat(ctx, "user-1", "chat-1", map[string]interface{}{"name": "chat-chat-2"})
+ _, err := svc.UpdateChat(ctx, "chat-1", map[string]interface{}{"name": "chat-chat-2"})
if err == nil {
t.Fatal("expected duplicate name error")
}
@@ -532,7 +532,7 @@ func TestChatServicePatchChatRejectsEmptyName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.PatchChat(ctx, "user-1", "chat-1", map[string]interface{}{"name": ""})
+ _, err := svc.PatchChat(ctx, "chat-1", map[string]interface{}{"name": ""})
if err == nil || err.Error() != "`name` cannot be empty" {
t.Fatalf("expected empty name error, got %v", err)
}
@@ -544,7 +544,7 @@ func TestChatServicePatchChatRejectsNonStringName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.PatchChat(ctx, "user-1", "chat-1", map[string]interface{}{"name": 123})
+ _, err := svc.PatchChat(ctx, "chat-1", map[string]interface{}{"name": 123})
if err == nil || err.Error() != "chat name must be a string" {
t.Fatalf("expected non-string name error, got %v", err)
}
@@ -557,7 +557,7 @@ func TestChatServicePatchChatRejectsTooLongName(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
longName := strings.Repeat("a", 256)
- _, err := svc.PatchChat(ctx, "user-1", "chat-1", map[string]interface{}{"name": longName})
+ _, err := svc.PatchChat(ctx, "chat-1", map[string]interface{}{"name": longName})
if err == nil {
t.Fatal("expected too long name error")
}
@@ -573,7 +573,7 @@ func TestChatServiceUpdateRejectsDuplicateNameCaseInsensitive(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, err := svc.PatchChat(ctx, "user-1", "chat-1", map[string]interface{}{"name": "CHAT-CHAT-2"})
+ _, err := svc.PatchChat(ctx, "chat-1", map[string]interface{}{"name": "CHAT-CHAT-2"})
if err == nil || err.Error() != "duplicated chat name" {
t.Fatalf("expected case-insensitive duplicate name error, got %v", err)
}
@@ -584,7 +584,7 @@ func TestChatServiceCreateRejectsTenantID(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ _, code, err := svc.Create(ctx, map[string]interface{}{
"name": "valid chat",
"tenant_id": "other-tenant",
})
@@ -601,7 +601,7 @@ func TestChatServiceCreateRejectsInvalidPromptConfig(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- _, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ _, code, err := svc.Create(ctx, map[string]interface{}{
"name": "valid chat",
"prompt_config": "invalid",
})
@@ -618,7 +618,7 @@ func TestChatServiceUpdateRejectsDuplicatePromptParameterKeys(t *testing.T) {
createChatRESTUpdateServiceTestChat(t, db, "chat-1", "user-1")
svc := NewChatService()
- _, err := svc.UpdateChat(serviceTestContext(t, "user-1", "user-1"), "user-1", "chat-1", map[string]interface{}{
+ _, err := svc.UpdateChat(serviceTestContext(t, "user-1", "user-1"), "chat-1", map[string]interface{}{
"prompt_config": map[string]interface{}{
"parameters": []interface{}{
map[string]interface{}{"key": "knowledge"},
@@ -636,7 +636,7 @@ func TestChatServiceCreatePromptDefaultsContract(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ resp, code, err := svc.Create(ctx, map[string]interface{}{
"name": "prompt defaults chat",
})
if err != nil {
@@ -684,7 +684,7 @@ func TestChatServiceCreateWithDatasetSeedsDatasetSystemPrompt(t *testing.T) {
svc := NewChatService()
ctx := serviceTestContext(t, "user-1", "user-1")
- resp, code, err := svc.Create(ctx, "user-1", map[string]interface{}{
+ resp, code, err := svc.Create(ctx, map[string]interface{}{
"name": "prompt defaults chat with dataset",
"kb_ids": []interface{}{"kb-1"},
})
diff --git a/internal/service/chat_sdk_contract_test.go b/internal/service/chat_sdk_contract_test.go
index d24342f8c2..19c381ea1d 100644
--- a/internal/service/chat_sdk_contract_test.go
+++ b/internal/service/chat_sdk_contract_test.go
@@ -44,10 +44,10 @@ func TestChatConfigurationRejectsInvalidTypes(t *testing.T) {
var err error
if operation == "create" {
payload["name"] = "validation"
- _, _, err = svc.Create(ctx, "user-1", payload)
+ _, _, err = svc.Create(ctx, payload)
} else {
createChatRESTUpdateServiceTestChat(t, db, "chat", "user-1")
- _, err = svc.PatchChat(ctx, "user-1", "chat", payload)
+ _, err = svc.PatchChat(ctx, "chat", payload)
}
if err == nil {
t.Fatalf("accepted invalid configuration: %#v", payload)
diff --git a/internal/service/chat_session.go b/internal/service/chat_session.go
index bcbdd126c2..c40f111fd8 100644
--- a/internal/service/chat_session.go
+++ b/internal/service/chat_session.go
@@ -132,7 +132,7 @@ type ChatSessionPayload struct {
}
// ListChatSessions lists chat sessions for a dialog
-func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatID, sessionID, name, sessionUserID string, terms []dao.OrderTerm, page, pageSize int, options ...dao.ConversationHistoryOptions) (*ListChatSessionsResponse, error) {
+func (s *ChatSessionService) ListChatSessions(ctx context.Context, chatID, sessionID, name, sessionUserID string, terms []dao.OrderTerm, page, pageSize int, options ...dao.ConversationHistoryOptions) (*ListChatSessionsResponse, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationRead); err != nil {
_, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, normalizedErr
@@ -175,7 +175,7 @@ func (s *ChatSessionService) ListChatSessions(ctx context.Context, userID, chatI
}
// GetSession returns one chat session after ownership validation.
-func (s *ChatSessionService) GetSession(ctx context.Context, userID, chatID, sessionID string, options ...dao.ConversationHistoryOptions) (*ChatSessionPayload, common.ErrorCode, error) {
+func (s *ChatSessionService) GetSession(ctx context.Context, chatID, sessionID string, options ...dao.ConversationHistoryOptions) (*ChatSessionPayload, common.ErrorCode, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationRead); err != nil {
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, code, normalizedErr
@@ -205,7 +205,11 @@ func (s *ChatSessionService) GetSession(ctx context.Context, userID, chatID, ses
}
// CreateSession create a session in a dialog
-func (s *ChatSessionService) CreateSession(ctx context.Context, userID, chatID string, req map[string]interface{}) (*ChatSessionPayload, common.ErrorCode, error) {
+func (s *ChatSessionService) CreateSession(ctx context.Context, chatID string, req map[string]interface{}) (*ChatSessionPayload, common.ErrorCode, error) {
+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))
+ if userID == "" {
+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated
+ }
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationCreate); err != nil {
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, code, normalizedErr
@@ -266,7 +270,7 @@ func (s *ChatSessionService) CreateSession(ctx context.Context, userID, chatID s
}
// DeleteSessions delete a session in a dialog
-func (s *ChatSessionService) DeleteSessions(ctx context.Context, userID, chatID string, req map[string]interface{}) (interface{}, string, common.ErrorCode, error) {
+func (s *ChatSessionService) DeleteSessions(ctx context.Context, chatID string, req map[string]interface{}) (interface{}, string, common.ErrorCode, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationRead); err != nil {
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, "", code, normalizedErr
@@ -333,7 +337,7 @@ func (s *ChatSessionService) DeleteSessions(ctx context.Context, userID, chatID
continue
}
- s.removeSessionUploadFiles(ctx, userID, session)
+ s.removeSessionUploadFiles(ctx, session)
if err = s.chatSessionDAO.DeleteByID(ctx, dao.DB, sid); err != nil {
return nil, "", common.CodeServerError, err
@@ -386,9 +390,9 @@ func stringSliceFromValue(value interface{}) ([]string, bool) {
return ids, true
}
-func (s *ChatSessionService) removeSessionUploadFiles(ctx context.Context, userID string, session *entity.ChatSession) {
+func (s *ChatSessionService) removeSessionUploadFiles(ctx context.Context, session *entity.ChatSession) {
messages := parseMessages(session.Message)
- bucket := fmt.Sprintf("%s-downloads", userID)
+ bucket := fmt.Sprintf("%s-downloads", strings.TrimSpace(permission.UserIDFromContext(ctx)))
storageImpl := storage.GetStorageFactory().GetStorage()
if storageImpl == nil {
common.Warn("storage is not initialized; skip chat upload cleanup", zap.String("bucket", bucket))
@@ -447,7 +451,7 @@ func checkDuplicateChatSessionIDs(ids []string) ([]string, []string) {
}
// UpdateSession updates one chat session after Python-style field validation.
-func (s *ChatSessionService) UpdateSession(ctx context.Context, userID, chatID, sessionID string, req map[string]interface{}) (*ChatSessionPayload, common.ErrorCode, error) {
+func (s *ChatSessionService) UpdateSession(ctx context.Context, chatID, sessionID string, req map[string]interface{}) (*ChatSessionPayload, common.ErrorCode, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationRead); err != nil {
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, code, normalizedErr
@@ -519,7 +523,7 @@ func (s *ChatSessionService) UpdateSession(ctx context.Context, userID, chatID,
return s.buildSessionPayload(session, nil, false), common.CodeSuccess, nil
}
-func (s *ChatSessionService) DeleteSessionMessage(ctx context.Context, userID, chatID, sessionID, msgID string) (*ChatSessionPayload, common.ErrorCode, error) {
+func (s *ChatSessionService) DeleteSessionMessage(ctx context.Context, chatID, sessionID, msgID string) (*ChatSessionPayload, common.ErrorCode, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationRead); err != nil {
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, code, normalizedErr
@@ -579,7 +583,7 @@ func (s *ChatSessionService) DeleteSessionMessage(ctx context.Context, userID, c
return s.buildSessionPayload(session, nil, false), common.CodeSuccess, nil
}
-func (s *ChatSessionService) UpdateMessageFeedback(ctx context.Context, userID, chatID, sessionID, msgID string, req map[string]interface{}) (*ChatSessionPayload, common.ErrorCode, error) {
+func (s *ChatSessionService) UpdateMessageFeedback(ctx context.Context, chatID, sessionID, msgID string, req map[string]interface{}) (*ChatSessionPayload, common.ErrorCode, error) {
if err := s.permissionChecker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindChat, ID: chatID}, permission.OperationRead); err != nil {
code, normalizedErr := permissionresponse.NormalizeHidden(err)
return nil, code, normalizedErr
@@ -1116,7 +1120,6 @@ func isChatSessionNotFound(err error) bool {
// When stream=false, returns the structured answer map.
func (s *ChatSessionService) ChatCompletions(
ctx context.Context,
- userID string,
chatID string, sessionID string,
messages []map[string]interface{}, question string, files []interface{},
llmID string, genConfig map[string]interface{}, kwargs map[string]interface{},
@@ -1131,6 +1134,10 @@ func (s *ChatSessionService) ChatCompletions(
}
return nil, err
}
+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))
+ if userID == "" {
+ return fail(common.NewCodedError(common.CodeUnauthorized, permission.ErrUnauthenticated.Error()))
+ }
sendOrCancel := func(data string) bool {
if ctx.Err() != nil {
@@ -1190,7 +1197,7 @@ func (s *ChatSessionService) ChatCompletions(
return fail(common.NewCodedError(code, normalizedErr.Error()))
}
} else if storeHistoryMessages {
- session, err = s.createSessionForCompletion(ctx, chatID, dialog, userID)
+ session, err = s.createSessionForCompletion(ctx, chatID, dialog)
if err != nil {
return fail(err)
}
@@ -1618,7 +1625,11 @@ func (s *ChatSessionService) buildDefaultCompletionDialog(tenantID string) *enti
}
}
-func (s *ChatSessionService) createSessionForCompletion(ctx context.Context, chatID string, dialog *entity.Chat, userID string) (*entity.ChatSession, error) {
+func (s *ChatSessionService) createSessionForCompletion(ctx context.Context, chatID string, dialog *entity.Chat) (*entity.ChatSession, error) {
+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))
+ if userID == "" {
+ return nil, permission.ErrUnauthenticated
+ }
name := "New session"
prologue := "Hi! I'm your assistant. What can I do for you?"
diff --git a/internal/service/chat_session_contract_test.go b/internal/service/chat_session_contract_test.go
index 054d663a9f..ac0a199317 100644
--- a/internal/service/chat_session_contract_test.go
+++ b/internal/service/chat_session_contract_test.go
@@ -59,8 +59,8 @@ func TestCreateSession_Success(t *testing.T) {
pipeline: &fakePipeline{},
}
- ctx := t.Context()
- resp, code, err := svc.CreateSession(ctx, "user-1", "chat-1", map[string]interface{}{"name": "valid"})
+ ctx := permission.WithIdentity(t.Context(), "user-1", "user-1")
+ resp, code, err := svc.CreateSession(ctx, "chat-1", map[string]interface{}{"name": "valid"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -89,9 +89,9 @@ func TestCreateSession_RejectsEmptyOrNonStringName(t *testing.T) {
pipeline: &fakePipeline{},
}
- ctx := t.Context()
+ ctx := permission.WithIdentity(t.Context(), "user-1", "user-1")
for _, name := range []interface{}{"", " ", 1} {
- _, code, err := svc.CreateSession(ctx, "user-1", "chat-1", map[string]interface{}{"name": name})
+ _, code, err := svc.CreateSession(ctx, "chat-1", map[string]interface{}{"name": name})
if err == nil || err.Error() != "`name` can not be empty" {
t.Fatalf("name=%#v err=%v", name, err)
}
@@ -112,9 +112,9 @@ func TestCreateSession_TruncatesLongName(t *testing.T) {
pipeline: &fakePipeline{},
}
- ctx := t.Context()
+ ctx := permission.WithIdentity(t.Context(), "user-1", "user-1")
longName := strings.Repeat("a", 300)
- resp, code, err := svc.CreateSession(ctx, "user-1", "chat-1", map[string]interface{}{"name": longName})
+ resp, code, err := svc.CreateSession(ctx, "chat-1", map[string]interface{}{"name": longName})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -134,8 +134,8 @@ func TestCreateSession_NotOwner(t *testing.T) {
pipeline: &fakePipeline{},
}
- ctx := t.Context()
- _, code, err := svc.CreateSession(ctx, "user-1", "chat-1", map[string]interface{}{"name": "x"})
+ ctx := permission.WithIdentity(t.Context(), "user-1", "user-1")
+ _, code, err := svc.CreateSession(ctx, "chat-1", map[string]interface{}{"name": "x"})
if err == nil || err.Error() != "Resource not found" {
t.Fatalf("err=%v", err)
}
@@ -150,7 +150,7 @@ func TestListChatSessionsChecksChatPermissionWhenThereAreNoSessions(t *testing.T
permissionChecker: emptyChatSessionScopeChecker{checkErr: permission.ErrPermissionDenied},
}
- result, err := svc.ListChatSessions(t.Context(), "outsider", "chat-1", "", "", "", nil, 1, 20)
+ result, err := svc.ListChatSessions(t.Context(), "chat-1", "", "", "", nil, 1, 20)
if result != nil {
t.Fatalf("expected no response for unauthorized chat, got %+v", result)
}
@@ -177,7 +177,7 @@ func TestDeleteSessions_SuccessByIDs(t *testing.T) {
}
ctx := permission.WithIdentity(t.Context(), "user-1", "user-1")
- result, message, code, err := svc.DeleteSessions(ctx, "user-1", "chat-1", map[string]interface{}{"ids": []interface{}{"s1"}})
+ result, message, code, err := svc.DeleteSessions(ctx, "chat-1", map[string]interface{}{"ids": []interface{}{"s1"}})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -207,13 +207,13 @@ func TestDeleteSessions_DeleteAllAndInvalidID(t *testing.T) {
// Empty payload -> success with empty result map.
ctx := permission.WithIdentity(t.Context(), "user-1", "user-1")
- if _, _, code, err := svc.DeleteSessions(ctx, "user-1", "chat-1", map[string]interface{}{}); err != nil || code != common.CodeSuccess {
+ if _, _, code, err := svc.DeleteSessions(ctx, "chat-1", map[string]interface{}{}); err != nil || code != common.CodeSuccess {
t.Fatalf("empty payload: code=%v err=%v", code, err)
}
// delete_all removes every session for the chat.
store.sessions["s1"] = &entity.ChatSession{ID: "s1", DialogID: "chat-1"}
- if _, _, code, err := svc.DeleteSessions(ctx, "user-1", "chat-1", map[string]interface{}{"delete_all": true}); err != nil || code != common.CodeSuccess {
+ if _, _, code, err := svc.DeleteSessions(ctx, "chat-1", map[string]interface{}{"delete_all": true}); err != nil || code != common.CodeSuccess {
t.Fatalf("delete_all: code=%v err=%v", code, err)
}
if len(store.sessions) != 0 {
@@ -222,7 +222,7 @@ func TestDeleteSessions_DeleteAllAndInvalidID(t *testing.T) {
// Unknown id -> DataError reporting the unowned session.
store.sessions["s1"] = &entity.ChatSession{ID: "s1", DialogID: "chat-1"}
- _, _, code, err := svc.DeleteSessions(ctx, "user-1", "chat-1", map[string]interface{}{"ids": []interface{}{"missing"}})
+ _, _, code, err := svc.DeleteSessions(ctx, "chat-1", map[string]interface{}{"ids": []interface{}{"missing"}})
if err == nil || !strings.Contains(err.Error(), "The chat doesn't own the session missing") {
t.Fatalf("invalid id: err=%v", err)
}
@@ -240,7 +240,7 @@ func TestDeleteSessions_NotOwner(t *testing.T) {
}
ctx := t.Context()
- _, _, code, err := svc.DeleteSessions(ctx, "user-1", "chat-1", map[string]interface{}{"ids": []interface{}{"s1"}})
+ _, _, code, err := svc.DeleteSessions(ctx, "chat-1", map[string]interface{}{"ids": []interface{}{"s1"}})
if err == nil || err.Error() != "Resource not found" {
t.Fatalf("err=%v", err)
}
diff --git a/internal/service/chat_session_test.go b/internal/service/chat_session_test.go
index 8a0fdae924..58e7099fc1 100644
--- a/internal/service/chat_session_test.go
+++ b/internal/service/chat_session_test.go
@@ -368,7 +368,7 @@ func TestChatCompletionsPersistsAnswerDetailsForHistory(t *testing.T) {
)}
svc := &ChatSessionService{chatSessionDAO: store, permissionChecker: store, pipeline: pipeline}
streamChan := make(chan string, 8)
- if _, err := svc.ChatCompletions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "chat-1", "session-1", nil, "new question", nil, "", nil, nil, mode.legacy, mode.stream, streamChan); err != nil {
+ if _, err := svc.ChatCompletions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "chat-1", "session-1", nil, "new question", nil, "", nil, nil, mode.legacy, mode.stream, streamChan); err != nil {
t.Fatal(err)
}
if len(pipeline.messages) != 3 || pipeline.messages[1]["content"] != "old answer" {
@@ -381,7 +381,7 @@ func TestChatCompletionsPersistsAnswerDetailsForHistory(t *testing.T) {
}
}
}
- payload, code, err := svc.GetSession(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "chat-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true, IncludePrompt: true})
+ payload, code, err := svc.GetSession(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "chat-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true, IncludePrompt: true})
if err != nil || code != common.CodeSuccess {
t.Fatalf("GetSession: code=%v err=%v", code, err)
}
@@ -589,7 +589,7 @@ func TestListChatSessions_Success(t *testing.T) {
ctx := t.Context()
terms := []dao.OrderTerm{{Column: "create_time", Desc: true}}
- resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})
+ resp, err := svc.ListChatSessions(ctx, "chat-1", "", "", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -602,7 +602,7 @@ func TestListChatSessions_Success(t *testing.T) {
}
}
for page, wantCount := range map[int]int{4: 10, 5: 1, 6: 0} {
- resp, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", terms, page, 10, dao.ConversationHistoryOptions{NoHistory: true})
+ resp, err := svc.ListChatSessions(ctx, "chat-1", "", "", "", terms, page, 10, dao.ConversationHistoryOptions{NoHistory: true})
if err != nil {
t.Fatalf("page %d: %v", page, err)
}
@@ -610,11 +610,11 @@ func TestListChatSessions_Success(t *testing.T) {
t.Fatalf("page %d: got total=%d and %d sessions, want total=41 and %d sessions", page, resp.Total, len(resp.Sessions), wantCount)
}
}
- resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", terms, 1, 0, dao.ConversationHistoryOptions{NoHistory: true})
+ resp, err = svc.ListChatSessions(ctx, "chat-1", "", "", "", terms, 1, 0, dao.ConversationHistoryOptions{NoHistory: true})
if err != nil || resp.Total != 41 || len(resp.Sessions) != 0 {
t.Fatalf("zero page size: got response=%+v err=%v, want total=41 and no sessions", resp, err)
}
- resp, err = svc.ListChatSessions(ctx, "user-1", "chat-1", "session-01", "", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})
+ resp, err = svc.ListChatSessions(ctx, "chat-1", "session-01", "", "", terms, 1, 30, dao.ConversationHistoryOptions{NoHistory: true})
if err != nil || resp.Total != 1 || len(resp.Sessions) != 1 {
t.Fatalf("ID filter: got response=%+v err=%v, want total=1 and one session", resp, err)
}
@@ -630,7 +630,7 @@ func TestListChatSessions_NotOwner(t *testing.T) {
}
ctx := t.Context()
- _, err := svc.ListChatSessions(ctx, "user-1", "chat-1", "", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 1, 30)
+ _, err := svc.ListChatSessions(ctx, "chat-1", "", "", "", []dao.OrderTerm{{Column: "create_time", Desc: true}}, 1, 30)
if err == nil || err.Error() != "Resource not found" {
t.Fatalf("got %v", err)
}
@@ -660,7 +660,7 @@ func TestGetSession_Success(t *testing.T) {
}
ctx := t.Context()
- resp, code, err := svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true, IncludePrompt: true})
+ resp, code, err := svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true, IncludePrompt: true})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -698,7 +698,7 @@ func TestGetSession_NotOwner(t *testing.T) {
}
ctx := t.Context()
- _, code, err := svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "session-1")
+ _, code, err := svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "session-1")
if err == nil || err.Error() != "Resource not found" {
t.Fatalf("err=%v", err)
}
@@ -719,7 +719,7 @@ func TestGetSession_WrongChat(t *testing.T) {
}
ctx := t.Context()
- _, code, err := svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "session-1")
+ _, code, err := svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "session-1")
if err == nil || err.Error() != "session does not belong to this chat" {
t.Fatalf("err=%v", err)
}
@@ -746,7 +746,7 @@ func TestUpdateSession_Success(t *testing.T) {
longName := " " + strings.Repeat("x", 260) + " "
ctx := t.Context()
- resp, code, err := svc.UpdateSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "session-1", map[string]interface{}{
+ resp, code, err := svc.UpdateSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "session-1", map[string]interface{}{
"name": longName,
"user_id": "spoof",
"chat_id": "spoof-chat",
@@ -801,7 +801,7 @@ func TestUpdateSession_ValidationErrors(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctx := t.Context()
- _, code, err := svc.UpdateSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "session-1", tc.req)
+ _, code, err := svc.UpdateSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "session-1", tc.req)
if err == nil || err.Error() != tc.message {
t.Fatalf("err=%v", err)
}
@@ -823,7 +823,7 @@ func TestUpdateSession_NotFound(t *testing.T) {
}
ctx := t.Context()
- _, code, err := svc.UpdateSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "missing", map[string]interface{}{"name": "renamed"})
+ _, code, err := svc.UpdateSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "missing", map[string]interface{}{"name": "renamed"})
if err == nil || err.Error() != "Session not found!" {
t.Fatalf("err=%v", err)
}
@@ -854,7 +854,7 @@ func TestDeleteSessionMessage_RemovesMessagePairAndReference(t *testing.T) {
}
ctx := t.Context()
- resp, code, err := svc.DeleteSessionMessage(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "session-1", "msg-1")
+ resp, code, err := svc.DeleteSessionMessage(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "session-1", "msg-1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -870,7 +870,7 @@ func TestDeleteSessionMessage_RemovesMessagePairAndReference(t *testing.T) {
if _, ok := resp.Messages[2]["reference"]; ok {
t.Fatalf("delete response contains reference: %#v", resp.Messages[2])
}
- resp, code, err = svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "chat-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true})
+ resp, code, err = svc.GetSession(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "chat-1", "session-1", dao.ConversationHistoryOptions{IncludeReference: true})
if err != nil || code != common.CodeSuccess {
t.Fatalf("GetSession: code=%v err=%v", code, err)
}
@@ -906,7 +906,7 @@ func TestUpdateMessageFeedback_AppliesChunkFeedbackWithResolvedTenantAndContext(
}
ctx := context.WithValue(permission.WithIdentity(t.Context(), "user-1", "tenant-owner"), feedbackContextKey{}, "request-context")
- resp, code, err := svc.UpdateMessageFeedback(ctx, "user-1", "chat-1", "session-1", "msg-1", map[string]interface{}{
+ resp, code, err := svc.UpdateMessageFeedback(ctx, "chat-1", "session-1", "msg-1", map[string]interface{}{
"thumbup": true,
})
if err != nil {
@@ -958,7 +958,7 @@ func TestUpdateMessageFeedback_ToggleUsesResolvedTenantForUndoAndApply(t *testin
docEngine: docEngine,
}
- resp, code, err := svc.UpdateMessageFeedback(permission.WithIdentity(t.Context(), "user-1", "tenant-owner"), "user-1", "chat-1", "session-1", "msg-1", map[string]interface{}{
+ resp, code, err := svc.UpdateMessageFeedback(permission.WithIdentity(t.Context(), "user-1", "tenant-owner"), "chat-1", "session-1", "msg-1", map[string]interface{}{
"thumbup": false,
"feedback": "not useful",
})
@@ -1142,7 +1142,7 @@ func TestChatCompletions_AppendOnly(t *testing.T) {
}
ctx := t.Context()
- result, err := svc.ChatCompletions(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "user-1", "dialog-1", "session-1", []map[string]interface{}{
+ result, err := svc.ChatCompletions(permission.WithIdentity(ctx, "user-1", permission.TenantIDFromContext(ctx)), "dialog-1", "session-1", []map[string]interface{}{
{"role": "user", "content": "ignored client history"},
{"id": "msg-1", "role": "user", "content": "hi"},
}, "", nil, "", nil, nil, false, false, nil)
@@ -1204,7 +1204,7 @@ func TestChatCompletions_AppendOnly(t *testing.T) {
)}
svc := &ChatSessionService{chatSessionDAO: store, permissionChecker: store, pipeline: pipeline}
streamChan := make(chan string, 8)
- result, err := svc.ChatCompletions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "dialog-1", sessionID, payload, "must not replace payload", nil, "", nil, map[string]interface{}{"store_history_messages": false}, legacy, stream, streamChan)
+ result, err := svc.ChatCompletions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "dialog-1", sessionID, payload, "must not replace payload", nil, "", nil, map[string]interface{}{"store_history_messages": false}, legacy, stream, streamChan)
if err != nil {
t.Errorf("completion failed: %v", err)
return
@@ -1233,7 +1233,7 @@ func TestChatCompletions_AppendOnly(t *testing.T) {
if len(store.updateCalled) != 2 || len(store.createCalled) != 0 || string(stored.Message) != storedMessages {
t.Fatal("model tests changed stored history or created a session")
}
- if _, err := svc.ChatCompletions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "dialog-1", "", nil, "question without messages", nil, "", nil, map[string]interface{}{"store_history_messages": false}, false, false, nil); err == nil {
+ if _, err := svc.ChatCompletions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "dialog-1", "", nil, "question without messages", nil, "", nil, map[string]interface{}{"store_history_messages": false}, false, false, nil); err == nil {
t.Fatal("non-storing completion must require messages")
}
})
@@ -1271,7 +1271,7 @@ func TestChatCompletionsPassesRequestUserIDToPipeline(t *testing.T) {
}
_, err := svc.ChatCompletions(permission.WithIdentity(t.Context(),
- "user-1", permission.TenantIDFromContext(t.Context())), "user-1",
+ "user-1", permission.TenantIDFromContext(t.Context())),
"dialog-1",
"session-1",
[]map[string]interface{}{{"role": "user", "content": "hi"}},
@@ -1352,7 +1352,7 @@ func TestChatCompletionsStreamFinalCarriesDecoratedReference(t *testing.T) {
streamChan := make(chan string, 8)
_, err := svc.ChatCompletions(permission.WithIdentity(t.Context(),
- "user-1", permission.TenantIDFromContext(t.Context())), "user-1",
+ "user-1", permission.TenantIDFromContext(t.Context())),
"dialog-1",
"session-1",
[]map[string]interface{}{{"role": "user", "content": "what is marigold"}},
@@ -1450,7 +1450,7 @@ func TestChatCompletionsModelIDOverrideUsesModelResolver(t *testing.T) {
}
_, err := svc.ChatCompletions(permission.WithIdentity(t.Context(),
- "user-1", permission.TenantIDFromContext(t.Context())), "user-1",
+ "user-1", permission.TenantIDFromContext(t.Context())),
"dialog-1",
"session-1",
[]map[string]interface{}{{"role": "user", "content": "hi"}},
@@ -1847,7 +1847,7 @@ func newSharedChatReadonlyService() (*ChatSessionService, *fakeSessionStore) {
func TestUpdateSession_SharedSessionReadonlyForTeammate(t *testing.T) {
svc, store := newSharedChatReadonlyService()
- _, code, err := svc.UpdateSession(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "chat-1", "session-1", map[string]interface{}{"name": "renamed"})
+ _, code, err := svc.UpdateSession(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "chat-1", "session-1", map[string]interface{}{"name": "renamed"})
if err == nil || err.Error() != "Resource not found" {
t.Fatalf("err=%v", err)
}
@@ -1865,7 +1865,7 @@ func TestUpdateSession_SessionCreatorCanRenameInSharedChat(t *testing.T) {
// rename sessions they created themselves on the shared chat.
store.sessions["session-1"].UserID = strPtr("user-1")
- resp, code, err := svc.UpdateSession(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "chat-1", "session-1", map[string]interface{}{"name": "renamed"})
+ resp, code, err := svc.UpdateSession(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "chat-1", "session-1", map[string]interface{}{"name": "renamed"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -1882,7 +1882,7 @@ func TestUpdateSession_ChatOwnerCanRenameAnySession(t *testing.T) {
// The dialog tenant itself may manage every session of its chat.
store.dialogExists["tenant-owner|chat-1"] = true
- _, code, err := svc.UpdateSession(permission.WithIdentity(t.Context(), "tenant-owner", permission.TenantIDFromContext(t.Context())), "tenant-owner", "chat-1", "session-1", map[string]interface{}{"name": "renamed"})
+ _, code, err := svc.UpdateSession(permission.WithIdentity(t.Context(), "tenant-owner", permission.TenantIDFromContext(t.Context())), "chat-1", "session-1", map[string]interface{}{"name": "renamed"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
@@ -1894,7 +1894,7 @@ func TestUpdateSession_ChatOwnerCanRenameAnySession(t *testing.T) {
func TestDeleteSessions_SharedSessionReadonlyForTeammate(t *testing.T) {
svc, store := newSharedChatReadonlyService()
- resp, msg, code, err := svc.DeleteSessions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "chat-1", map[string]interface{}{"ids": []interface{}{"session-1"}})
+ resp, msg, code, err := svc.DeleteSessions(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "chat-1", map[string]interface{}{"ids": []interface{}{"session-1"}})
if err == nil || !strings.Contains(err.Error(), "Resource not found") {
t.Fatalf("err=%v", err)
}
@@ -1914,7 +1914,7 @@ func TestDeleteSessions_SharedSessionReadonlyForTeammate(t *testing.T) {
func TestDeleteSessionMessage_SharedSessionReadonlyForTeammate(t *testing.T) {
svc, _ := newSharedChatReadonlyService()
- _, code, err := svc.DeleteSessionMessage(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "user-1", "chat-1", "session-1", "msg-1")
+ _, code, err := svc.DeleteSessionMessage(permission.WithIdentity(t.Context(), "user-1", permission.TenantIDFromContext(t.Context())), "chat-1", "session-1", "msg-1")
if err == nil || err.Error() != "Resource not found" {
t.Fatalf("err=%v", err)
}
@@ -1926,7 +1926,8 @@ func TestDeleteSessionMessage_SharedSessionReadonlyForTeammate(t *testing.T) {
func TestUpdateMessageFeedback_SharedSessionReadonlyForTeammate(t *testing.T) {
svc, _ := newSharedChatReadonlyService()
- _, code, err := svc.UpdateMessageFeedback(t.Context(), "user-1", "chat-1", "session-1", "msg-1", map[string]interface{}{"thumbup": true})
+ ctx := permission.WithIdentity(t.Context(), "user-1", "")
+ _, code, err := svc.UpdateMessageFeedback(ctx, "chat-1", "session-1", "msg-1", map[string]interface{}{"thumbup": true})
if err == nil || err.Error() != "Resource not found" {
t.Fatalf("err=%v", err)
}
@@ -1949,7 +1950,7 @@ func TestChatCompletions_SharedSessionReadonlyForTeammate(t *testing.T) {
svc.pipeline = pipeline
_, err := svc.ChatCompletions(permission.WithIdentity(t.Context(),
- "user-1", permission.TenantIDFromContext(t.Context())), "user-1",
+ "user-1", permission.TenantIDFromContext(t.Context())),
"chat-1",
"session-1",
[]map[string]interface{}{{"role": "user", "content": "hi"}},
@@ -2000,7 +2001,7 @@ func TestChatCompletions_CancelledNonStreamDoesNotPersistBlankTurn(t *testing.T)
}
_, _ = svc.ChatCompletions(permission.WithIdentity(ctx,
- "user-1", permission.TenantIDFromContext(ctx)), "user-1",
+ "user-1", permission.TenantIDFromContext(ctx)),
"chat-1",
"session-1",
nil,
diff --git a/internal/service/delete_version_test.go b/internal/service/delete_version_test.go
index 28ab6e9415..d41a2ed0bb 100644
--- a/internal/service/delete_version_test.go
+++ b/internal/service/delete_version_test.go
@@ -81,7 +81,7 @@ func TestDeleteVersion_ReferencedVersionStillDeleted(t *testing.T) {
ctx := serviceTestContext(t, userID, userID)
svc := NewAgentService()
- if err := svc.DeleteVersion(ctx, userID, canvasID, versionID); err != nil {
+ if err := svc.DeleteVersion(ctx, canvasID, versionID); err != nil {
t.Fatalf("DeleteVersion referenced version: %v", err)
}
@@ -129,7 +129,7 @@ func TestDeleteVersion_UnreferencedVersionDeleted(t *testing.T) {
ctx := serviceTestContext(t, userID, userID)
svc := NewAgentService()
- if err := svc.DeleteVersion(ctx, userID, canvasID, versionID); err != nil {
+ if err := svc.DeleteVersion(ctx, canvasID, versionID); err != nil {
t.Fatalf("DeleteVersion unreferenced version: %v", err)
}
if _, err := dao.NewUserCanvasVersionDAO().GetByID(ctx, dao.DB, versionID); !errors.Is(err, dao.ErrUserCanvasVersionNotFound) {
diff --git a/internal/service/openai_chat.go b/internal/service/openai_chat.go
index 32d044f991..970f98a24a 100644
--- a/internal/service/openai_chat.go
+++ b/internal/service/openai_chat.go
@@ -237,7 +237,7 @@ func (s *OpenAIChatService) OpenAIChatCompletions(c *gin.Context, userID, chatID
ctx, cancel := context.WithCancel(c.Request.Context())
defer cancel()
- dialogResp, err := s.chatSvc.GetChat(ctx, userID, chatID)
+ dialogResp, err := s.chatSvc.GetChat(ctx, chatID)
if err != nil {
if permissionresponse.IsPermissionError(err) {
code, permissionErr := permissionresponse.NormalizeHidden(err)
diff --git a/internal/service/update_agent_save_semantics_test.go b/internal/service/update_agent_save_semantics_test.go
index 2a83cf1b63..faca230bd7 100644
--- a/internal/service/update_agent_save_semantics_test.go
+++ b/internal/service/update_agent_save_semantics_test.go
@@ -61,7 +61,7 @@ func TestUpdateAgent_AutosaveUpdatesDraftOnly(t *testing.T) {
svc := NewAgentService()
ctx := serviceTestContext(t, userID, userID)
- if err := svc.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": sampleDSL()}); err != nil {
+ if err := svc.UpdateAgent(ctx, canvasID, map[string]interface{}{"dsl": sampleDSL()}); err != nil {
t.Fatalf("manual save: %v", err)
}
before, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(ctx, dao.DB, canvasID)
@@ -74,7 +74,7 @@ func TestUpdateAgent_AutosaveUpdatesDraftOnly(t *testing.T) {
autoDSL := sampleDSL()
autoDSL["autosave_marker"] = "yes"
- if err := svc.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": autoDSL, "autosave": true}); err != nil {
+ if err := svc.UpdateAgent(ctx, canvasID, map[string]interface{}{"dsl": autoDSL, "autosave": true}); err != nil {
t.Fatalf("autosave: %v", err)
}
after, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(ctx, dao.DB, canvasID)
@@ -104,10 +104,10 @@ func TestUpdateAgent_ManualSaveInsertsNewVersion(t *testing.T) {
svc := NewAgentService()
ctx := serviceTestContext(t, userID, userID)
- if err := svc.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": sampleDSL()}); err != nil {
+ if err := svc.UpdateAgent(ctx, canvasID, map[string]interface{}{"dsl": sampleDSL()}); err != nil {
t.Fatalf("first save: %v", err)
}
- if err := svc.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": sampleDSL()}); err != nil {
+ if err := svc.UpdateAgent(ctx, canvasID, map[string]interface{}{"dsl": sampleDSL()}); err != nil {
t.Fatalf("second save: %v", err)
}
versions, err := dao.NewUserCanvasVersionDAO().ListByCanvasID(ctx, dao.DB, canvasID)
@@ -131,7 +131,7 @@ func TestUpdateAgent_ManualSaveCarriesAlias(t *testing.T) {
ctx := serviceTestContext(t, userID, userID)
alias := "carried-alias"
- if err := svc.UpdateAgent(ctx, userID, canvasID, map[string]interface{}{"dsl": sampleDSL(), "alias": alias}); err != nil {
+ if err := svc.UpdateAgent(ctx, canvasID, map[string]interface{}{"dsl": sampleDSL(), "alias": alias}); err != nil {
t.Fatalf("save with alias: %v", err)
}
latest, err := dao.NewUserCanvasVersionDAO().GetLatest(ctx, dao.DB, canvasID)
diff --git a/internal/service/update_version_test.go b/internal/service/update_version_test.go
index 9570808605..dc10a64f24 100644
--- a/internal/service/update_version_test.go
+++ b/internal/service/update_version_test.go
@@ -38,7 +38,7 @@ func TestUpdateVersion_PatchesAliasWithoutNewVersion(t *testing.T) {
ctx := serviceTestContext(t, userID, userID)
svc := NewAgentService()
patch := dao.UserCanvasVersionPatch{Alias: &alias}
- if err := svc.UpdateVersion(ctx, userID, canvasID, versionID, patch); err != nil {
+ if err := svc.UpdateVersion(ctx, canvasID, versionID, patch); err != nil {
t.Fatalf("UpdateVersion alias: %v", err)
}
@@ -85,7 +85,7 @@ func TestUpdateVersion_CrossCanvasRejected(t *testing.T) {
ctx := serviceTestContext(t, userID, userID)
svc := NewAgentService()
patch := dao.UserCanvasVersionPatch{Alias: &alias}
- err := svc.UpdateVersion(ctx, userID, otherCanvasID, versionID, patch)
+ err := svc.UpdateVersion(ctx, otherCanvasID, versionID, patch)
if !errors.Is(err, dao.ErrUserCanvasVersionNotFound) {
t.Fatalf("expected ErrUserCanvasVersionNotFound, got %v", err)
}