RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
refa: remove remaining identity arguments (#22005)
buua436b9d814f24c8a
diff --git a/internal/agent/component/begin.go b/internal/agent/component/begin.goindex c52c39aa8b..7aabd0c20e 100644--- a/internal/agent/component/begin.go+++ b/internal/agent/component/begin.go@@ -16,7 +16,7 @@// Package component — Begin component (T3).//-// Begin is the DSL entry node. It injects the request's `inputs` into+// Begin is the DSL entry node. It injects the request's query into// the shared *CanvasState.Sys namespace and passes the input map// through to its downstream unchanged. File-input handling// (FileService.get_files) handles `query`, `user_id`, and file@@ -64,9 +64,10 @@ func NewBeginComponent(params map[string]any) (Component, error) {// the eino node-name injection in BuildWorkflow.func (b *BeginComponent) Name() string { return b.name }-// Invoke writes inputs["query"] and (when present) inputs["user_id"] into-// the shared *CanvasState.Sys namespace, then returns the input map as-// outputs, exposing structured webhook sections at top level.+// Invoke writes inputs["query"] into the shared *CanvasState.Sys namespace,+// then returns the input map as outputs, exposing structured webhook+// sections at top level. Other inputs, including user_id, remain ordinary+// Begin outputs and cannot override the authenticated runtime identity.// The input map is shallow-copied to avoid aliasing// surprises across concurrent goroutines that share an inputs map.func (b *BeginComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[string]any) (map[string]any, error) {@@ -82,13 +83,6 @@ func (b *BeginComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[strquery, _ := inputs["query"].(string)state.SetSys("query", query)- // Optional user_id — present in interactive chat flows, absent in- // background jobs. Always a string when set; cast failure silently- // drops the value (mirrors Python's getattr fallback).- if uid, ok := inputs["user_id"].(string); ok && uid != "" {- state.SetSys("user_id", uid)- }-// Webhook payload injection. The webhook HTTP handler sets// root["webhook_payload"] (see service/agent.go RunAgentWithWebhook)// which BuildWorkflow forwards into inputs. Surfacing it on@@ -213,7 +207,7 @@ func (b *BeginComponent) Stream(ctx context.Context, db *gorm.DB, inputs map[strfunc (b *BeginComponent) Inputs() map[string]string {return map[string]string{"query": "User query string (the chat input).",- "user_id": "Optional user/tenant identifier.",+ "user_id": "Optional user identifier passed through as a Begin input.","webhook_payload": "Optional structured webhook request (set by the webhook HTTP handler; absent on chat flows).","inputs": "Optional free-form inputs map; passthrough only.",}diff --git a/internal/agent/component/begin_test.go b/internal/agent/component/begin_test.goindex 73e45fbec4..d317c6d8b7 100644--- a/internal/agent/component/begin_test.go+++ b/internal/agent/component/begin_test.go@@ -188,14 +188,15 @@ func TestBegin_InitializesNilGlobalsAfterRestore(t *testing.T) {// arbitrary keys beyond query / user_id — is returned unchanged as// outputs. This is the contract downstream components rely on to access// DSL-level inputs the engine has not explicitly modeled.-func TestBegin_PassesThroughInputs(t *testing.T) {+func TestBegin_PassesThroughInputsWithoutOverridingIdentity(t *testing.T) {c, _ := NewBeginComponent(nil)state := canvas.NewCanvasState("run-2", "task-2")+ state.SeedIdentity("authenticated-user", "tenant-7")ctx := canvas.WithState(t.Context(), state)inputs := map[string]any{"query": "what is ragflow",- "user_id": "tenant-7",+ "user_id": "input-user","inputs": map[string]any{"k": "v"},"extra": 42,}@@ -206,8 +207,8 @@ func TestBegin_PassesThroughInputs(t *testing.T) {if !reflect.DeepEqual(out, inputs) {t.Errorf("output passthrough failed:\n got %v\n want %v", out, inputs)}- if got, _ := state.Sys["user_id"].(string); got != "tenant-7" {- t.Errorf("state.Sys[user_id]: got %q, want %q", got, "tenant-7")+ if got, _ := state.Sys["user_id"].(string); got != "authenticated-user" {+ t.Errorf("state.Sys[user_id]: got %q, want authenticated identity", got)}}diff --git a/internal/agent/component/message.go b/internal/agent/component/message.goindex 0ca8372d82..deb8697b91 100644--- a/internal/agent/component/message.go+++ b/internal/agent/component/message.go@@ -329,16 +329,16 @@ func (m *MessageComponent) Invoke(ctx context.Context, db *gorm.DB, inputs map[smemIDs = m.memoryIDs}if len(memIDs) > 0 {- userID := stringFromStateSys(state, "user_id")- if userID == "" {- userID = m.userID- }+ userID := m.userID// If userID is a canvas variable reference (e.g. "{cpn@user_id}"),// resolve it against the current state. Mirrors Python's// agent/component/message.py:569-571.if userID != "" && runtime.VarRefPattern.MatchString(userID) {userID = runtime.ResolveTemplateForDisplay(userID, state)}+ if userID == "" {+ userID = stringFromStateSys(state, "user_id")+ }saver := GetMemorySaver()saveErr := saver.Save(ctx, MemorySaveRequest{MemoryIDs: memIDs,diff --git a/internal/agent/component/message_phase8b_test.go b/internal/agent/component/message_phase8b_test.goindex 121b9d0bbb..c8421b4c32 100644--- a/internal/agent/component/message_phase8b_test.go+++ b/internal/agent/component/message_phase8b_test.go@@ -257,6 +257,7 @@ func TestMessage_MemorySave_Success(t *testing.T) {c, _ := NewMessageComponent(map[string]any{"text": "hi"})state := canvas.NewCanvasState("run-y", "session-y")state.Sys["query"] = "what?"+ state.Sys["user_id"] = "authenticated-user"state.Sys["canvas_id"] = "canvas-y"state.Sys["session_id"] = "session-y"state.Sys["agent_id"] = "agent-y"@@ -283,6 +284,9 @@ func TestMessage_MemorySave_Success(t *testing.T) {if saved.UserInput != "what?" {t.Errorf("UserInput: got %q, want what?", saved.UserInput)}+ if saved.UserID != "authenticated-user" {+ t.Errorf("UserID fallback: got %q, want authenticated-user", saved.UserID)+ }if saved.AgentResponse != "hi" {t.Errorf("AgentResponse: got %q, want hi", saved.AgentResponse)}@@ -376,6 +380,7 @@ func TestMessage_MemorySave_UserIDVariable(t *testing.T) {})state := canvas.NewCanvasState("run-uid", "task-uid")state.Sys["query"] = "hello?"+ state.Sys["user_id"] = "authenticated-user"state.SetVar("begin", "user_id", "resolved-user-123")ctx := withStateForTest(t.Context(), state)@@ -410,6 +415,7 @@ func TestMessage_MemorySave_UserIDLiteral(t *testing.T) {})state := canvas.NewCanvasState("run-uid2", "task-uid2")state.Sys["query"] = "hello?"+ state.Sys["user_id"] = "authenticated-user"ctx := withStateForTest(t.Context(), state)_, err := c.Invoke(ctx, nil, map[string]any{diff --git a/internal/handler/agent.go b/internal/handler/agent.goindex 9c1d225727..e38ca15666 100644--- a/internal/handler/agent.go+++ b/internal/handler/agent.go@@ -53,7 +53,7 @@ import (// the FileHandler (handler/file.go), not by any agent handler, so// the interface deliberately does NOT list it. (Code review CR1.)type agentFileService interface {- DownloadAgentFile(ctx context.Context, tenantID, location string) ([]byte, error)+ DownloadAgentFile(ctx context.Context, location string) ([]byte, error)// UploadInfos stores raw bytes in the per-user downloads bucket and// returns lightweight descriptors.UploadInfos(ctx context.Context, files []*multipart.FileHeader) ([]map[string]interface{}, error)@@ -610,7 +610,7 @@ func respondWithDebugResult(c *gin.Context, result *task.PipelineResult, err err// (id/name/created_by); the raw bytes are fetched from the per-user downloads// bucket via the file service. When no usable file is present it returns a// default name and a nil slice so the pipeline can still run file-less.-func (h *AgentHandler) extractChatDebugFile(ctx context.Context, files []map[string]interface{}, user *entity.User) (string, []byte) {+func (h *AgentHandler) extractChatDebugFile(ctx context.Context, files []map[string]interface{}) (string, []byte) {if len(files) == 0 {return "debug", nil}@@ -623,7 +623,7 @@ func (h *AgentHandler) extractChatDebugFile(ctx context.Context, files []map[str}return name, nil}- data, err := h.fileService.DownloadAgentFile(ctx, user.ID, id)+ data, err := h.fileService.DownloadAgentFile(ctx, id)if err != nil || len(data) == 0 {if name == "" {return "debug", nil@@ -941,11 +941,6 @@ func (h *AgentHandler) ListAgentSessions(c *gin.Context) {// CreateAgentSession POST /api/v1/agents/:canvas_id/sessionsfunc (h *AgentHandler) CreateAgentSession(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 {Name string `json:"name"`@@ -958,7 +953,6 @@ func (h *AgentHandler) CreateAgentSession(c *gin.Context) {}ctx := c.Request.Context()row, code, err := h.agentService.CreateAgentSession(ctx, &service.CreateAgentSessionRequest{- UserID: user.ID,AgentID: canvasID,Name: body.Name,Source: body.Source,@@ -1227,7 +1221,7 @@ func (h *AgentHandler) AgentChatCompletions(c *gin.Context) {// runCanvasPipelineDebug).if h.loader != nil {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)+ fileName, fileData := h.extractChatDebugFile(c.Request.Context(), req.Files)if len(fileData) == 0 {common.RespondError(c, common.CodeDataError, "dataflow debug requires an uploaded file")returndiff --git a/internal/handler/agent_attachment.go b/internal/handler/agent_attachment.goindex a5b6bc2d36..495a57cc17 100644--- a/internal/handler/agent_attachment.go+++ b/internal/handler/agent_attachment.go@@ -30,6 +30,7 @@ package handlerimport ("context"+ "errors""net/http""path/filepath""strings"@@ -37,13 +38,14 @@ import ("github.com/gin-gonic/gin""ragflow/internal/common"+ "ragflow/internal/permission""ragflow/internal/utility")// agentAttachmentFileService is the subset of FileService used by// the attachment-download handler.type agentAttachmentFileService interface {- DownloadAgentFile(ctx context.Context, tenantID, location string) ([]byte, error)+ DownloadAgentFile(ctx context.Context, location string) ([]byte, error)}// attachmentRequestMetadata holds the parsed query params used when@@ -76,15 +78,19 @@ func attachmentRequestMeta(c *gin.Context) attachmentRequestMetadata {// safe types, attachment for dangerous ones). When inline=false,// always uses attachment disposition. Mirrors Python// _stream_agent_attachment().-func (h *AgentHandler) streamAgentAttachment(c *gin.Context, tenantID, attachmentID string, inline bool) {+func (h *AgentHandler) streamAgentAttachment(c *gin.Context, attachmentID string, inline bool) {if h.fileService == nil {common.RespondError(c, common.CodeServerError, "file service not configured")return}ctx := c.Request.Context()- blob, err := h.fileService.DownloadAgentFile(ctx, tenantID, attachmentID)+ blob, err := h.fileService.DownloadAgentFile(ctx, attachmentID)if err != nil {+ if errors.Is(err, permission.ErrUnauthenticated) {+ common.RespondError(c, common.CodeUnauthorized, err.Error())+ return+ }common.RespondError(c, common.CodeDataError, "Attachment not found!")return}@@ -109,11 +115,6 @@ func (h *AgentHandler) streamAgentAttachment(c *gin.Context, tenantID, attachmen// Supports optional ?disposition=inline for browsers that prefer inline// rendering. Mirrors Python download_attachment() at agent_api.py:2507.func (h *AgentHandler) DownloadAttachment(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }attachmentID := c.Param("attachment_id")if attachmentID == "" {common.RespondError(c, common.CodeArgumentError, "`attachment_id` is required.")@@ -137,7 +138,7 @@ func (h *AgentHandler) DownloadAttachment(c *gin.Context) {// Support ?disposition=inline for optional inline viewing.inline := strings.ToLower(strings.TrimSpace(c.Query("disposition"))) == "inline"- h.streamAgentAttachment(c, user.ID, attachmentID, inline)+ h.streamAgentAttachment(c, attachmentID, inline)}// PreviewAttachment GET /api/v1/agents/attachments/<attachment_id>/preview@@ -148,11 +149,6 @@ func (h *AgentHandler) DownloadAttachment(c *gin.Context) {// preview_url generated by DocGenerator. Mirrors Python preview_attachment()// at agent_api.py:2496.func (h *AgentHandler) PreviewAttachment(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }attachmentID := c.Param("attachment_id")if attachmentID == "" {common.RespondError(c, common.CodeArgumentError, "`attachment_id` is required.")@@ -164,5 +160,5 @@ func (h *AgentHandler) PreviewAttachment(c *gin.Context) {return}- h.streamAgentAttachment(c, user.ID, attachmentID, true)+ h.streamAgentAttachment(c, attachmentID, true)}diff --git a/internal/handler/agent_component.go b/internal/handler/agent_component.goindex 470755cb3e..ab9b669405 100644--- a/internal/handler/agent_component.go+++ b/internal/handler/agent_component.go@@ -49,11 +49,6 @@ import (// GetComponentInputForm GET /api/v1/agents/:canvas_id/components/:component_id/input-formfunc (h *AgentHandler) GetComponentInputForm(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }canvasID := c.Param("canvas_id")componentID := c.Param("component_id")if canvasID == "" || componentID == "" {@@ -71,7 +66,7 @@ func (h *AgentHandler) GetComponentInputForm(c *gin.Context) {return}- form, err := h.componentInputForm(c.Request.Context(), cv.DSL, componentID, user.ID)+ form, err := h.componentInputForm(c.Request.Context(), cv.DSL, componentID)if err != nil {mapDSLError(c, componentID, err)return@@ -85,7 +80,7 @@ func (h *AgentHandler) GetComponentInputForm(c *gin.Context) {// it instantiates the runtime component and calls its GetInputForm method.// This mirrors Python's Canvas.get_component_input_form which invokes the// component's own get_input_form when the static field is absent.-func (h *AgentHandler) componentInputForm(ctx context.Context, dslMap map[string]any, componentID, userID string) (map[string]any, error) {+func (h *AgentHandler) componentInputForm(ctx context.Context, dslMap map[string]any, componentID string) (map[string]any, error) {form, err := dsl.ExtractComponentInputForm(dslMap, componentID)if err == nil {return form, nildiff --git a/internal/handler/agent_download.go b/internal/handler/agent_download.goindex 11ce295d20..ba4b6a1841 100644--- a/internal/handler/agent_download.go+++ b/internal/handler/agent_download.go@@ -17,18 +17,13 @@// Gap A — `GET /api/v1/agents/download` (Python// api/apps/restful_apis/agent_api.py:523-530).//-// Mirrors the python download_agent_file handler:-// - auth via @login_required → GetUser-// - tenant injection via @add_tenant_id_to_kwargs → user.TenantID (we use-// user.ID here because the user/tenant distinction is collapsed in-// the Go session model; FileService buckets by userID for download-// retrieval, same as the python tenantID). See service/file.go:1033.-// - reads `id` from query string and streams raw bytes back as-// application/octet-stream.+// Reads the authenticated caller's downloads bucket and streams the selected+// file as application/octet-stream.package handlerimport (+ "errors""fmt""net/http""net/url"@@ -38,15 +33,11 @@ import ("github.com/gin-gonic/gin""ragflow/internal/common"+ "ragflow/internal/permission")// DownloadAgentFile GET /api/v1/agents/download?id=<file_id>func (h *AgentHandler) DownloadAgentFile(c *gin.Context) {- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }fileID := c.Query("id")if fileID == "" {common.RespondError(c, common.CodeArgumentError, "`id` is required.")@@ -54,16 +45,12 @@ func (h *AgentHandler) DownloadAgentFile(c *gin.Context) {}ctx := c.Request.Context()- // IDOR note (security review H1): the Go User struct has no- // TenantID field — the project collapses user and tenant in a- // single-tenant session model. Python's @add_tenant_id_to_kwargs- // resolves tenant_id from the session, and the python download- // endpoint also reads `id` directly from the query string with no- // per-object ownership check, so this port preserves the python- // shape. A future per-object ownership check should be added in- // both the python and Go code paths.- blob, err := h.fileService.DownloadAgentFile(ctx, user.ID, fileID)+ blob, err := h.fileService.DownloadAgentFile(ctx, fileID)if err != nil {+ if errors.Is(err, permission.ErrUnauthenticated) {+ common.RespondError(c, common.CodeUnauthorized, err.Error())+ return+ }common.RespondError(c, common.CodeServerError, err.Error())return}diff --git a/internal/handler/agent_download_test.go b/internal/handler/agent_download_test.goindex 30774d5ae1..3c58eb5d05 100644--- a/internal/handler/agent_download_test.go+++ b/internal/handler/agent_download_test.go@@ -56,7 +56,7 @@ func (f *fakeAgentFileService) UploadFromURL(ctx context.Context, _ string) (map}return f.urlUpload, nil}-func (f *fakeAgentFileService) DownloadAgentFile(ctx context.Context, _ string, _ string) ([]byte, error) {+func (f *fakeAgentFileService) DownloadAgentFile(ctx context.Context, _ string) ([]byte, error) {if f.err != nil {return nil, f.err}diff --git a/internal/handler/api_token.go b/internal/handler/api_token.goindex 8e34118b84..7a50989381 100644--- a/internal/handler/api_token.go+++ b/internal/handler/api_token.go@@ -31,14 +31,14 @@ import (func (h *SystemHandler) ListAPIKeys(c *gin.Context) {ctx := c.Request.Context()- _, tenantID, code, err := currentAPIKeyOwner(c)+ code, err := currentAPIKeyOwner(c)if err != nil {respondAPIKeyContextError(c, code, err)return}// Get keys for the tenant- keys, err := h.systemService.ListAPIKeys(ctx, tenantID)+ keys, err := h.systemService.ListAPIKeys(ctx)if err != nil {common.Respond(c, http.StatusInternalServerError, 500, nil, "Failed to list keys")return@@ -49,7 +49,7 @@ func (h *SystemHandler) ListAPIKeys(c *gin.Context) {func (h *SystemHandler) CreateKey(c *gin.Context) {ctx := c.Request.Context()- user, tenantID, code, err := currentAPIKeyOwner(c)+ code, err := currentAPIKeyOwner(c)if err != nil {respondAPIKeyContextError(c, code, err)return@@ -64,7 +64,7 @@ func (h *SystemHandler) CreateKey(c *gin.Context) {}// Create key- key, err := h.systemService.CreateAPIKey(ctx, user.ID, tenantID, &req)+ key, err := h.systemService.CreateAPIKey(ctx, &req)if err != nil {common.Respond(c, http.StatusInternalServerError, 500, nil, "Failed to create key")return@@ -75,7 +75,7 @@ func (h *SystemHandler) CreateKey(c *gin.Context) {func (h *SystemHandler) DeleteKey(c *gin.Context) {ctx := c.Request.Context()- _, tenantID, code, err := currentAPIKeyOwner(c)+ code, err := currentAPIKeyOwner(c)if err != nil {respondAPIKeyContextError(c, code, err)return@@ -89,7 +89,7 @@ func (h *SystemHandler) DeleteKey(c *gin.Context) {}// Delete key- if err = h.systemService.DeleteAPIKey(ctx, tenantID, key); err != nil {+ if err = h.systemService.DeleteAPIKey(ctx, key); err != nil {common.Respond(c, http.StatusInternalServerError, 500, nil, "Failed to delete key")return}@@ -97,14 +97,14 @@ func (h *SystemHandler) DeleteKey(c *gin.Context) {common.RespondSuccess(c, nil, "success")}-func currentAPIKeyOwner(c *gin.Context) (*entity.User, string, common.ErrorCode, error) {+func currentAPIKeyOwner(c *gin.Context) (common.ErrorCode, error) {userValue, exists := c.Get("user")if !exists {- return nil, "", common.CodeUnauthorized, errors.New("Unauthorized")+ return common.CodeUnauthorized, errors.New("Unauthorized")}user, ok := userValue.(*entity.User)if !ok {- return nil, "", common.CodeServerError, errors.New("Invalid user data")+ return common.CodeServerError, errors.New("Invalid user data")}tenantID := c.GetString("tenant_id")@@ -114,9 +114,9 @@ func currentAPIKeyOwner(c *gin.Context) (*entity.User, string, common.ErrorCode,}membership, err := dao.NewUserTenantDAO().FilterByUserIDAndTenantID(c.Request.Context(), dao.DB, user.ID, tenantID)if err != nil || membership.Role != "owner" {- return nil, "", common.CodeForbidden, errors.New("Only the tenant owner can manage API keys")+ return common.CodeForbidden, errors.New("Only the tenant owner can manage API keys")}- return user, tenantID, common.CodeSuccess, nil+ return common.CodeSuccess, nil}func respondAPIKeyContextError(c *gin.Context, code common.ErrorCode, err error) {diff --git a/internal/handler/bot_test.go b/internal/handler/bot_test.goindex 44386a3cdd..7ca7943987 100644--- a/internal/handler/bot_test.go+++ b/internal/handler/bot_test.go@@ -769,7 +769,7 @@ type fakeFileService struct {err error}-func (f *fakeFileService) DownloadAgentFile(ctx context.Context, tenantID, location string) ([]byte, error) {+func (f *fakeFileService) DownloadAgentFile(ctx context.Context, location string) ([]byte, error) {return f.blob, f.err}diff --git a/internal/handler/chat_audio.go b/internal/handler/chat_audio.goindex 331fa0005d..063639077c 100644--- a/internal/handler/chat_audio.go+++ b/internal/handler/chat_audio.go@@ -31,7 +31,7 @@ import ("ragflow/internal/common"modelModule "ragflow/internal/entity/models"- "ragflow/internal/service"+ "ragflow/internal/permission")const (@@ -73,7 +73,7 @@ func (h *ChatHandler) ChatAudioSpeech(c *gin.Context) {return}- ttsModel, err := h.modelFactory.NewDefaultTTSModel(ctx, service.Identity{UserID: user.ID, TenantID: user.ID})+ ttsModel, err := h.modelFactory.NewDefaultTTSModel(permission.WithTenantID(ctx, user.ID))if err != nil {common.RespondError(c, common.CodeDataError, err.Error())return@@ -265,7 +265,7 @@ func (h *ChatHandler) ChatAudioTranscription(c *gin.Context) {return}- asrModel, err := h.modelFactory.NewDefaultASRModel(ctx, service.Identity{UserID: user.ID, TenantID: user.ID})+ asrModel, err := h.modelFactory.NewDefaultASRModel(permission.WithTenantID(ctx, user.ID))if err != nil {common.RespondError(c, common.CodeDataError, err.Error())returndiff --git a/internal/handler/dify_retrieval_handler.go b/internal/handler/dify_retrieval_handler.goindex 874c4b04e3..7dd0569228 100644--- a/internal/handler/dify_retrieval_handler.go+++ b/internal/handler/dify_retrieval_handler.go@@ -21,7 +21,9 @@ import ("errors""fmt""net/http"+"ragflow/internal/dao"+ "ragflow/internal/permission""strconv""strings"@@ -29,7 +31,6 @@ import ("ragflow/internal/engine""ragflow/internal/entity"modelModule "ragflow/internal/entity/models"- "ragflow/internal/permission""ragflow/internal/service""ragflow/internal/service/graph""ragflow/internal/service/nlp"@@ -49,8 +50,8 @@ type KBServiceIface interface {// ModelCreator supplies typed model instances to Dify retrieval.type ModelCreator interface {- NewEmbeddingModel(ctx context.Context, access service.Identity, modelRef string) (*modelModule.EmbeddingModel, error)- NewDefaultChatModel(ctx context.Context, access service.Identity) (*modelModule.ChatModel, error)+ NewEmbeddingModel(ctx context.Context, modelRef string) (*modelModule.EmbeddingModel, error)+ NewDefaultChatModel(ctx context.Context) (*modelModule.ChatModel, error)}// MetadataServiceIface abstracts MetadataService for the Dify handler.@@ -169,7 +170,7 @@ func NewDifyRetrievalHandler(// Retrieval handles POST/GET /api/v1/dify/retrieval.// Matches Python: api/apps/restful_apis/dify_retrieval_api.py::retrieval()func (h *DifyRetrievalHandler) Retrieval(c *gin.Context) {- user, errCode, errMsg := GetUser(c)+ _, errCode, errMsg := GetUser(c)if errCode != common.CodeSuccess {common.Respond(c, http.StatusUnauthorized, errCode, nil, errMsg)return@@ -245,8 +246,8 @@ func (h *DifyRetrievalHandler) Retrieval(c *gin.Context) {}// Get embedding model- access := service.Identity{UserID: user.ID, TenantID: kb.TenantID}- embModel, err := h.modelFactory.NewEmbeddingModel(ctx, access, kb.EmbdID)+ ctx = permission.WithTenantID(ctx, kb.TenantID)+ embModel, err := h.modelFactory.NewEmbeddingModel(ctx, kb.EmbdID)if err != nil {common.Respond(c, http.StatusInternalServerError, common.CodeServerError, nil, fmt.Sprintf("failed to get embedding model: %v", err))return@@ -310,7 +311,7 @@ func (h *DifyRetrievalHandler) Retrieval(c *gin.Context) {// KG retrieval (optional)if req.UseKG {- chatModel, kgErr := h.modelFactory.NewDefaultChatModel(ctx, access)+ chatModel, kgErr := h.modelFactory.NewDefaultChatModel(ctx)if kgErr != nil {common.Warn("KG retrieval: failed to get chat model", zap.String("kbID", req.KnowledgeID), zap.Error(kgErr))} else if chatModel != nil {diff --git a/internal/handler/dify_retrieval_handler_test.go b/internal/handler/dify_retrieval_handler_test.goindex 80a35a48b5..a2cf0b8a2b 100644--- a/internal/handler/dify_retrieval_handler_test.go+++ b/internal/handler/dify_retrieval_handler_test.go@@ -65,12 +65,12 @@ func (m *mockKBService) CheckResource(ctx context.Context, resource permission.Rtype mockModelFactory struct{}-func (mockModelFactory) NewEmbeddingModel(context.Context, service.Identity, string) (*modelModule.EmbeddingModel, error) {+func (mockModelFactory) NewEmbeddingModel(context.Context, string) (*modelModule.EmbeddingModel, error) {name := "test-model"return modelModule.NewEmbeddingModel(&modelModule.DummyModel{}, &name, &modelModule.APIConfig{}, 0), nil}-func (mockModelFactory) NewDefaultChatModel(context.Context, service.Identity) (*modelModule.ChatModel, error) {+func (mockModelFactory) NewDefaultChatModel(context.Context) (*modelModule.ChatModel, error) {name := "test-model"return modelModule.NewChatModel(&modelModule.DummyModel{}, &name, &modelModule.APIConfig{}), nil}diff --git a/internal/handler/document.go b/internal/handler/document.goindex 8cfb43bcc4..01ba0d7275 100644--- a/internal/handler/document.go+++ b/internal/handler/document.go@@ -71,9 +71,9 @@ type documentServiceIface interface {GetDocumentMetadataByID(ctx context.Context, docID string) (map[string]interface{}, error)GetDocumentArtifact(ctx context.Context, filename string) (*document.ArtifactResponse, error)GetDocumentPreview(ctx context.Context, docID string) (*document.DocumentPreview, error)- UploadLocalDocuments(ctx context.Context, kb *entity.Knowledgebase, tenantID string, files []*multipart.FileHeader, parentPath string, parserConfigOverride map[string]interface{}) ([]map[string]interface{}, []string)- UploadWebDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name, url string) (map[string]interface{}, common.ErrorCode, error)- UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name string) (map[string]interface{}, common.ErrorCode, error)+ UploadLocalDocuments(ctx context.Context, kb *entity.Knowledgebase, files []*multipart.FileHeader, parentPath string, parserConfigOverride map[string]interface{}) ([]map[string]interface{}, []string)+ UploadWebDocument(ctx context.Context, kb *entity.Knowledgebase, name, url string) (map[string]interface{}, common.ErrorCode, error)+ UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, name string) (map[string]interface{}, common.ErrorCode, error)DownloadDocument(ctx context.Context, datasetID, docID string) (*document.DownloadDocumentResp, error)UpdateDatasetDocument(ctx context.Context, datasetID, documentID string, req *document.UpdateDatasetDocumentRequest, present map[string]bool) (*document.UpdateDatasetDocumentResponse, common.ErrorCode, error)ApplyDatasetParserConfig(ctx context.Context, datasetID string) (*document.ApplyDatasetParserConfigResponse, common.ErrorCode, error)@@ -996,16 +996,15 @@ func invalidRunStatuses(statuses []string) []string {}func (h *DocumentHandler) UploadDocuments(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)+ ctx := c.Request.Context()+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ common.RespondError(c, common.CodeUnauthorized, permission.ErrUnauthenticated.Error())return}- tenantID := user.IDdatasetID := c.Param("dataset_id")uploadType := strings.ToLower(c.DefaultQuery("type", "local"))- ctx := c.Request.Context()kb, err := h.datasetService.GetKnowledgebaseByID(ctx, datasetID)if err != nil || kb == nil {common.RespondError(c, common.CodeDataError, fmt.Sprintf("Can't find the dataset with ID %s!", datasetID))@@ -1018,17 +1017,22 @@ func (h *DocumentHandler) UploadDocuments(c *gin.Context) {switch uploadType {case "web":- h.uploadWebDocument(c, kb, tenantID)+ h.uploadWebDocument(c, kb)case "empty":- h.uploadEmptyDocument(c, kb, tenantID)+ h.uploadEmptyDocument(c, kb)case "local":- h.uploadLocalDocuments(c, kb, tenantID)+ h.uploadLocalDocuments(c, kb)default:common.RespondError(c, common.CodeArgumentError, `"type" must be one of "local", "web", or "empty".`)}}-func (h *DocumentHandler) uploadLocalDocuments(c *gin.Context, kb *entity.Knowledgebase, tenantID string) {+func (h *DocumentHandler) uploadLocalDocuments(c *gin.Context, kb *entity.Knowledgebase) {+ userID := permission.UserIDFromContext(c.Request.Context())+ if userID == "" {+ common.RespondError(c, common.CodeUnauthorized, permission.ErrUnauthenticated.Error())+ return+ }form, err := c.MultipartForm()if err != nil || form == nil || len(form.File["file"]) == 0 {common.RespondError(c, common.CodeArgumentError, "No file part!")@@ -1041,7 +1045,7 @@ func (h *DocumentHandler) uploadLocalDocuments(c *gin.Context, kb *entity.KnowletotalSize += fh.Size}}- if !billingEnforceStorage(c, tenantID, totalSize) {+ if !billingEnforceStorage(c, userID, totalSize) {return}for _, fh := range files {@@ -1074,7 +1078,7 @@ func (h *DocumentHandler) uploadLocalDocuments(c *gin.Context, kb *entity.Knowle}}ctx := c.Request.Context()- data, errMsgs := h.documentService.UploadLocalDocuments(ctx, kb, tenantID, files, c.PostForm("parent_path"), override)+ data, errMsgs := h.documentService.UploadLocalDocuments(ctx, kb, files, c.PostForm("parent_path"), override)if len(errMsgs) > 0 {common.RespondError(c, common.CodeServerError, strings.Join(errMsgs, "\n"))return@@ -1095,7 +1099,7 @@ func (h *DocumentHandler) uploadLocalDocuments(c *gin.Context, kb *entity.Knowlecommon.RespondSuccessList(c, mapped, "success")}-func (h *DocumentHandler) uploadEmptyDocument(c *gin.Context, kb *entity.Knowledgebase, tenantID string) {+func (h *DocumentHandler) uploadEmptyDocument(c *gin.Context, kb *entity.Knowledgebase) {var req struct {Name string `json:"name"`}@@ -1116,7 +1120,7 @@ func (h *DocumentHandler) uploadEmptyDocument(c *gin.Context, kb *entity.Knowledreturn}ctx := c.Request.Context()- data, code, err := h.documentService.UploadEmptyDocument(ctx, kb, tenantID, name)+ data, code, err := h.documentService.UploadEmptyDocument(ctx, kb, name)if err != nil {common.RespondError(c, code, err.Error())return@@ -1124,7 +1128,7 @@ func (h *DocumentHandler) uploadEmptyDocument(c *gin.Context, kb *entity.Knowledcommon.RespondSuccess(c, mapDocKeysWithRunStatus(data), "success")}-func (h *DocumentHandler) uploadWebDocument(c *gin.Context, kb *entity.Knowledgebase, tenantID string) {+func (h *DocumentHandler) uploadWebDocument(c *gin.Context, kb *entity.Knowledgebase) {name := strings.TrimSpace(c.PostForm("name"))rawURL := c.PostForm("url")if name == "" {@@ -1144,7 +1148,7 @@ func (h *DocumentHandler) uploadWebDocument(c *gin.Context, kb *entity.Knowledgereturn}ctx := c.Request.Context()- data, code, err := h.documentService.UploadWebDocument(ctx, kb, tenantID, name, rawURL)+ data, code, err := h.documentService.UploadWebDocument(ctx, kb, name, rawURL)if err != nil {common.RespondError(c, code, err.Error())returndiff --git a/internal/handler/document_test.go b/internal/handler/document_test.goindex 38d0e350d1..74624cb1d3 100644--- a/internal/handler/document_test.go+++ b/internal/handler/document_test.go@@ -357,16 +357,16 @@ func (f *fakeDocumentService) HasActiveIngestionTasks(ctx context.Context, datasfunc (f *fakeDocumentService) GetDocumentMetadataByID(ctx context.Context, docID string) (map[string]interface{}, error) {return nil, nil}-func (f *fakeDocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.Knowledgebase, tenantID string, files []*multipart.FileHeader, parentPath string, parserConfigOverride map[string]interface{}) ([]map[string]interface{}, []string) {+func (f *fakeDocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.Knowledgebase, files []*multipart.FileHeader, parentPath string, parserConfigOverride map[string]interface{}) ([]map[string]interface{}, []string) {f.uploadLocalKB = kbf.uploadLocalPath = parentPathf.uploadOverride = parserConfigOverridereturn f.uploadLocalData, f.uploadLocalErrs}-func (f *fakeDocumentService) UploadWebDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name, url string) (map[string]interface{}, common.ErrorCode, error) {+func (f *fakeDocumentService) UploadWebDocument(ctx context.Context, kb *entity.Knowledgebase, name, url string) (map[string]interface{}, common.ErrorCode, error) {return nil, common.CodeServerError, fmt.Errorf("not implemented")}-func (f *fakeDocumentService) UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name string) (map[string]interface{}, common.ErrorCode, error) {+func (f *fakeDocumentService) UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, name string) (map[string]interface{}, common.ErrorCode, error) {return nil, common.CodeServerError, fmt.Errorf("not implemented")}diff --git a/internal/handler/file.go b/internal/handler/file.goindex d506701828..3be0c68186 100644--- a/internal/handler/file.go+++ b/internal/handler/file.go@@ -313,7 +313,7 @@ func (h *FileHandler) UploadFile(c *gin.Context) {operationLog.Resources[fileHeader.Filename] = fileHeader.Size}- result, err := h.fileService.UploadFile(ctx, userID, parentID, files, uploadLimit)+ result, err := h.fileService.UploadFile(ctx, parentID, files, uploadLimit)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -395,14 +395,7 @@ func (h *FileHandler) DeleteFiles(c *gin.Context) {common.Audit(operationLog)}()- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- operationLog.Code = int(errorCode)- operationLog.Error = errors.New(errorMessage)- return- }- operationLog.UserID = user.ID+ operationLog.UserID = permission.UserIDFromContext(c.Request.Context())var req DeleteFileRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -543,7 +536,7 @@ func (h *FileHandler) Download(c *gin.Context) {ctx := c.Request.Context()// Get file metadata and check permission- fileContent, err := h.fileService.GetFileContent(ctx, user.ID, fileID)+ fileContent, err := h.fileService.GetFileContent(ctx, fileID)if err != nil {if respondPermissionErrorIf(c, err, true) {operationLog.Code = int(common.CodePermissionError)diff --git a/internal/handler/file_commit.go b/internal/handler/file_commit.goindex bb3da38e8e..c704e97857 100644--- a/internal/handler/file_commit.go+++ b/internal/handler/file_commit.go@@ -130,12 +130,12 @@ func (h *FileCommitHandler) resolveDatasetFolderID(ctx context.Context, datasetIreturn "", common.ErrNotFound}-// folderAccessible reports whether userID may access the given workspace-// folder. Every folder is a File row owned by a tenant: the commit surface-// exposes artifact contents, history, and writes, so apply the same access-// check the other file routes use instead of trusting a caller-supplied-// folder id.-func (h *FileCommitHandler) folderAccessible(c *gin.Context, userID, folderID string) bool {+// folderAccessible reports whether the authenticated caller may access the+// given workspace folder. Every folder is a File row owned by a tenant. The+// commit surface exposes artifact contents, history, and writes, so use the+// same access check as the other file routes instead of trusting a+// caller-supplied folder ID.+func (h *FileCommitHandler) folderAccessible(c *gin.Context, folderID string) bool {ctx := c.Request.Context()folder, err := h.fileDAO.GetByID(ctx, dao.DB, folderID)if err != nil || folder == nil || folder.Type != "folder" {@@ -181,7 +181,7 @@ func (h *FileCommitHandler) CreateCommit(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}@@ -241,7 +241,7 @@ func (h *FileCommitHandler) CreateCommit(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/workspaces/{workspace_id}/commits [get]func (h *FileCommitHandler) ListCommits(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return@@ -253,7 +253,7 @@ func (h *FileCommitHandler) ListCommits(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}@@ -359,7 +359,7 @@ func (h *FileCommitHandler) ListCommits(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/workspaces/{workspace_id}/commits/{commit_id} [get]func (h *FileCommitHandler) GetCommit(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return@@ -372,7 +372,7 @@ func (h *FileCommitHandler) GetCommit(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}@@ -434,7 +434,7 @@ func (h *FileCommitHandler) GetCommit(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/workspaces/{workspace_id}/commits/{commit_id}/files [get]func (h *FileCommitHandler) ListCommitFiles(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return@@ -447,7 +447,7 @@ func (h *FileCommitHandler) ListCommitFiles(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}@@ -483,7 +483,7 @@ func (h *FileCommitHandler) ListCommitFiles(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/workspaces/{workspace_id}/commits/diff [get]func (h *FileCommitHandler) DiffCommits(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return@@ -497,7 +497,7 @@ func (h *FileCommitHandler) DiffCommits(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}@@ -536,7 +536,7 @@ func (h *FileCommitHandler) DiffCommits(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/workspaces/{workspace_id}/changes [get]func (h *FileCommitHandler) GetUncommittedChanges(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return@@ -548,7 +548,7 @@ func (h *FileCommitHandler) GetUncommittedChanges(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}@@ -573,7 +573,7 @@ func (h *FileCommitHandler) GetUncommittedChanges(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/workspaces/{workspace_id}/commits/{commit_id}/tree [get]func (h *FileCommitHandler) GetCommitTree(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return@@ -586,7 +586,7 @@ func (h *FileCommitHandler) GetCommitTree(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}@@ -622,7 +622,7 @@ func (h *FileCommitHandler) GetCommitTree(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/workspaces/{workspace_id}/commits/{commit_id}/files/{file_id}/content [get]func (h *FileCommitHandler) GetCommitFileContent(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)+ _, errorCode, errorMessage := GetUser(c)if errorCode != common.CodeSuccess {common.RespondError(c, errorCode, errorMessage)return@@ -637,7 +637,7 @@ func (h *FileCommitHandler) GetCommitFileContent(c *gin.Context) {return}- if !h.folderAccessible(c, user.ID, folderID) {+ if !h.folderAccessible(c, folderID) {common.RespondError(c, common.CodeNotFound, "Workspace not found")return}diff --git a/internal/handler/langfuse.go b/internal/handler/langfuse.goindex 2e1e6a26fe..636350b99a 100644--- a/internal/handler/langfuse.go+++ b/internal/handler/langfuse.go@@ -29,9 +29,9 @@ import (// LangfuseService is the behaviour the handler depends on (interface enables// mocking in tests).type LangfuseService interface {- SetAPIKey(ctx context.Context, tenantID, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error)- GetAPIKey(ctx context.Context, tenantID string) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error)- DeleteAPIKey(ctx context.Context, tenantID string) (bool, common.ErrorCode, string, error)+ SetAPIKey(ctx context.Context, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error)+ GetAPIKey(ctx context.Context) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error)+ DeleteAPIKey(ctx context.Context) (bool, common.ErrorCode, string, error)}// LangfuseHandler handles /langfuse/api-key HTTP requests.@@ -59,12 +59,6 @@ type SetLangfuseRequest struct {// SetAPIKey handles POST/PUT /langfuse/api-key.func (h *LangfuseHandler) SetAPIKey(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-var req SetLangfuseRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeDataError, "Invalid request: "+err.Error())@@ -72,7 +66,7 @@ func (h *LangfuseHandler) SetAPIKey(c *gin.Context) {}ctx := c.Request.Context()- row, code, err := h.langfuseService.SetAPIKey(ctx, user.ID, req.SecretKey, req.PublicKey, req.Host)+ row, code, err := h.langfuseService.SetAPIKey(ctx, req.SecretKey, req.PublicKey, req.Host)if err != nil {common.RespondError(c, code, err.Error())return@@ -89,14 +83,9 @@ func (h *LangfuseHandler) SetAPIKey(c *gin.Context) {// GetAPIKey handles GET /langfuse/api-key.func (h *LangfuseHandler) GetAPIKey(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- data, code, message, err := h.langfuseService.GetAPIKey(ctx, user.ID)+ data, code, message, err := h.langfuseService.GetAPIKey(ctx)if err != nil {common.RespondError(c, code, message)return@@ -106,14 +95,9 @@ func (h *LangfuseHandler) GetAPIKey(c *gin.Context) {// DeleteAPIKey handles DELETE /langfuse/api-key.func (h *LangfuseHandler) DeleteAPIKey(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- _, code, message, err := h.langfuseService.DeleteAPIKey(ctx, user.ID)+ _, code, message, err := h.langfuseService.DeleteAPIKey(ctx)if err != nil {common.RespondError(c, code, message)returndiff --git a/internal/handler/langfuse_test.go b/internal/handler/langfuse_test.goindex 021b567540..0f623be619 100644--- a/internal/handler/langfuse_test.go+++ b/internal/handler/langfuse_test.go@@ -32,37 +32,36 @@ import ()type fakeLangfuseService struct {- setFn func(ctx context.Context, tenantID, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error)- getFn func(ctx context.Context, tenantID string) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error)- deleteFn func(ctx context.Context, tenantID string) (bool, common.ErrorCode, string, error)+ setFn func(ctx context.Context, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error)+ getFn func(ctx context.Context) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error)+ deleteFn func(ctx context.Context) (bool, common.ErrorCode, string, error)}-func (f fakeLangfuseService) SetAPIKey(ctx context.Context, tenantID, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {+func (f fakeLangfuseService) SetAPIKey(ctx context.Context, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {if f.setFn == nil {return nil, common.CodeServerError, errors.New("unexpected SetAPIKey call")}- return f.setFn(ctx, tenantID, secretKey, publicKey, host)+ return f.setFn(ctx, secretKey, publicKey, host)}-func (f fakeLangfuseService) GetAPIKey(ctx context.Context, tenantID string) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {+func (f fakeLangfuseService) GetAPIKey(ctx context.Context) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {if f.getFn == nil {return nil, common.CodeServerError, "", errors.New("unexpected GetAPIKey call")}- return f.getFn(ctx, tenantID)+ return f.getFn(ctx)}-func (f fakeLangfuseService) DeleteAPIKey(ctx context.Context, tenantID string) (bool, common.ErrorCode, string, error) {+func (f fakeLangfuseService) DeleteAPIKey(ctx context.Context) (bool, common.ErrorCode, string, error) {if f.deleteFn == nil {return false, common.CodeServerError, "", errors.New("unexpected DeleteAPIKey call")}- return f.deleteFn(ctx, tenantID)+ return f.deleteFn(ctx)}func serveLangfuse(method, target, body string, h func(c *gin.Context)) *httptest.ResponseRecorder {gin.SetMode(gin.TestMode)router := gin.New()router.Handle(method, target, func(c *gin.Context) {- c.Set("user", &entity.User{ID: "tenant-1"})h(c)})@@ -88,19 +87,19 @@ func decode(t *testing.T, resp *httptest.ResponseRecorder) map[string]interface{}func TestLangfuseHandler_SetAPIKey_Success(t *testing.T) {- var gotTenant, gotSecret, gotPublic, gotHost string+ var gotSecret, gotPublic, gotHost stringh := &LangfuseHandler{langfuseService: fakeLangfuseService{- setFn: func(ctx context.Context, tenantID, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {- gotTenant, gotSecret, gotPublic, gotHost = tenantID, secretKey, publicKey, host- return &entity.TenantLangfuse{TenantID: tenantID, SecretKey: secretKey, PublicKey: publicKey, Host: host}, common.CodeSuccess, nil+ setFn: func(ctx context.Context, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {+ gotSecret, gotPublic, gotHost = secretKey, publicKey, host+ return &entity.TenantLangfuse{TenantID: "tenant-1", SecretKey: secretKey, PublicKey: publicKey, Host: host}, common.CodeSuccess, nil},}}body := `{"secret_key":"sk","public_key":"pk","host":"https://a.langfuse.com"}`resp := serveLangfuse(http.MethodPost, "/api/v1/langfuse/api-key", body, h.SetAPIKey)- if gotTenant != "tenant-1" || gotSecret != "sk" || gotPublic != "pk" || gotHost != "https://a.langfuse.com" {- t.Fatalf("service args: tenant=%q secret=%q public=%q host=%q", gotTenant, gotSecret, gotPublic, gotHost)+ if gotSecret != "sk" || gotPublic != "pk" || gotHost != "https://a.langfuse.com" {+ t.Fatalf("service args: secret=%q public=%q host=%q", gotSecret, gotPublic, gotHost)}payload := decode(t, resp)if payload["code"] != float64(common.CodeSuccess) {@@ -117,7 +116,7 @@ func TestLangfuseHandler_SetAPIKey_Success(t *testing.T) {func TestLangfuseHandler_SetAPIKey_ServiceError(t *testing.T) {h := &LangfuseHandler{langfuseService: fakeLangfuseService{- setFn: func(ctx context.Context, tenantID, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {+ setFn: func(ctx context.Context, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {return nil, common.CodeDataError, errors.New("Invalid Langfuse keys")},}}@@ -137,7 +136,7 @@ func TestLangfuseHandler_SetAPIKey_ServiceError(t *testing.T) {func TestLangfuseHandler_SetAPIKey_BindFailureStopsEarly(t *testing.T) {called := falseh := &LangfuseHandler{langfuseService: fakeLangfuseService{- setFn: func(ctx context.Context, tenantID, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {+ setFn: func(ctx context.Context, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {called = truereturn nil, common.CodeSuccess, nil},@@ -156,9 +155,9 @@ func TestLangfuseHandler_SetAPIKey_BindFailureStopsEarly(t *testing.T) {func TestLangfuseHandler_GetAPIKey_Success(t *testing.T) {h := &LangfuseHandler{langfuseService: fakeLangfuseService{- getFn: func(ctx context.Context, tenantID string) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {+ getFn: func(ctx context.Context) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {return &entity.LangfuseInfoResponse{- TenantID: tenantID, Host: "host", SecretKey: "sk", PublicKey: "pk",+ TenantID: "tenant-1", Host: "host", SecretKey: "sk", PublicKey: "pk",ProjectID: "proj-1", ProjectName: "My Project",}, common.CodeSuccess, "success", nil},@@ -181,7 +180,7 @@ func TestLangfuseHandler_GetAPIKey_Success(t *testing.T) {func TestLangfuseHandler_GetAPIKey_NoRecord(t *testing.T) {h := &LangfuseHandler{langfuseService: fakeLangfuseService{- getFn: func(ctx context.Context, tenantID string) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {+ getFn: func(ctx context.Context) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {return nil, common.CodeSuccess, "Have not record any Langfuse keys.", nil},}}@@ -202,7 +201,7 @@ func TestLangfuseHandler_GetAPIKey_NoRecord(t *testing.T) {func TestLangfuseHandler_GetAPIKey_Unauthorized(t *testing.T) {h := &LangfuseHandler{langfuseService: fakeLangfuseService{- getFn: func(ctx context.Context, tenantID string) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {+ getFn: func(ctx context.Context) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {return nil, common.CodeDataError, "Invalid Langfuse keys loaded", errors.New("unauthorized")},}}@@ -219,19 +218,14 @@ func TestLangfuseHandler_GetAPIKey_Unauthorized(t *testing.T) {}func TestLangfuseHandler_DeleteAPIKey_Success(t *testing.T) {- var gotTenant stringh := &LangfuseHandler{langfuseService: fakeLangfuseService{- deleteFn: func(ctx context.Context, tenantID string) (bool, common.ErrorCode, string, error) {- gotTenant = tenantID+ deleteFn: func(ctx context.Context) (bool, common.ErrorCode, string, error) {return true, common.CodeSuccess, "", nil},}}resp := serveLangfuse(http.MethodDelete, "/api/v1/langfuse/api-key", "", h.DeleteAPIKey)- if gotTenant != "tenant-1" {- t.Fatalf("tenant=%q", gotTenant)- }payload := decode(t, resp)if payload["code"] != float64(common.CodeSuccess) {t.Fatalf("payload=%v", payload)@@ -243,7 +237,7 @@ func TestLangfuseHandler_DeleteAPIKey_Success(t *testing.T) {func TestLangfuseHandler_DeleteAPIKey_NoRecord(t *testing.T) {h := &LangfuseHandler{langfuseService: fakeLangfuseService{- deleteFn: func(ctx context.Context, tenantID string) (bool, common.ErrorCode, string, error) {+ deleteFn: func(ctx context.Context) (bool, common.ErrorCode, string, error) {return false, common.CodeSuccess, "Have not record any Langfuse keys.", nil},}}diff --git a/internal/handler/mcp_retrieval.go b/internal/handler/mcp_retrieval.goindex 0c4018ed0c..29f476c82c 100644--- a/internal/handler/mcp_retrieval.go+++ b/internal/handler/mcp_retrieval.go@@ -48,12 +48,9 @@ type mcpDatasetService interface {// mcpRetrieval executes a retrieval request on behalf of the MCP tool handler.// It translates the mcp.RetrievalRequest into a service.SearchDatasetsRequest// and calls DatasetService.SearchDatasets. The result is serialized as JSON.-func mcpRetrieval(ctx context.Context, ds mcpDatasetService, userID string, req mcp.RetrievalRequest) (string, error) {- contextUserID := permission.UserIDFromContext(ctx)- if contextUserID == "" {- ctx = permission.WithIdentity(ctx, userID, permission.TenantIDFromContext(ctx))- } else if contextUserID != userID {- return "", permission.ErrIdentityMismatch+func mcpRetrieval(ctx context.Context, ds mcpDatasetService, req mcp.RetrievalRequest) (string, error) {+ if permission.UserIDFromContext(ctx) == "" {+ return "", permission.ErrUnauthenticated}if err := validateRetrievalWindow(req.Page, req.PageSize); err != nil {diff --git a/internal/handler/mcp_retrieval_test.go b/internal/handler/mcp_retrieval_test.goindex e19ef59a8d..592aa03d4c 100644--- a/internal/handler/mcp_retrieval_test.go+++ b/internal/handler/mcp_retrieval_test.go@@ -94,7 +94,7 @@ func TestMCPRetrievalUsesFixedWindowAndForwardsPagination(t *testing.T) {isolateKnowledgeCompilePublisher(t)probe := &recordingDatasetService{}- result, err := mcpRetrieval(t.Context(), probe, "user-1", mcp.RetrievalRequest{+ result, err := mcpRetrieval(permission.WithIdentity(t.Context(), "user-1", ""), probe, mcp.RetrievalRequest{DatasetIDs: []string{"ds-1"},DocumentIDs: []string{"doc-1"},Question: "alpha",@@ -174,7 +174,7 @@ func TestMCPRetrievalRejectsOutOfWindowBeforeAnyDownstreamCall(t *testing.T) {t.Run(tc.name, func(t *testing.T) {probe := &recordingDatasetService{}- result, err := mcpRetrieval(t.Context(), probe, "user-1", mcp.RetrievalRequest{+ result, err := mcpRetrieval(permission.WithIdentity(t.Context(), "user-1", ""), probe, mcp.RetrievalRequest{DatasetIDs: tc.datasetIDs,Question: "alpha",Page: tc.page,@@ -199,7 +199,7 @@ func TestMCPRetrievalPropagatesSearchError(t *testing.T) {sentinel := errors.New("search exploded")probe := &recordingDatasetService{searchErr: sentinel}- result, err := mcpRetrieval(t.Context(), probe, "user-1", mcp.RetrievalRequest{+ result, err := mcpRetrieval(permission.WithIdentity(t.Context(), "user-1", ""), probe, mcp.RetrievalRequest{DatasetIDs: []string{"ds-1"},Question: "alpha",Page: 1,diff --git a/internal/handler/mcp_server.go b/internal/handler/mcp_server.goindex e3d8f72c38..fd71fe7e42 100644--- a/internal/handler/mcp_server.go+++ b/internal/handler/mcp_server.go@@ -23,7 +23,6 @@ import ("github.com/gin-gonic/gin"- "ragflow/internal/common""ragflow/internal/dao""ragflow/internal/mcp""ragflow/internal/permission"@@ -35,29 +34,29 @@ import (// MCPServerHandler handles MCP protocol requests (JSON-RPC over HTTP).// It exposes RAGFlow capabilities as MCP tools to external AI clients.type MCPServerHandler struct {- listDatasetsFunc func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)- listChatsFunc func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)- retrievalFunc func(ctx context.Context, userID string, req mcp.RetrievalRequest) (string, error)+ listDatasetsFunc func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)+ listChatsFunc func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)+ retrievalFunc func(ctx context.Context, req mcp.RetrievalRequest) (string, error)}// NewMCPServerHandler shares the service callbacks between API and standalone transports.func NewMCPServerHandler(ds *dataset.DatasetService, chats *service.ChatService) *MCPServerHandler {return &MCPServerHandler{- listDatasetsFunc: func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {- return mcpListDatasets(ctx, ds, userID, page, pageSize, orderby, desc)+ listDatasetsFunc: func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {+ return mcpListDatasets(ctx, ds, page, pageSize, orderby, desc)},- listChatsFunc: func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {- return mcpListChats(ctx, chats, userID, page, pageSize, orderby, desc)+ listChatsFunc: func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {+ return mcpListChats(ctx, chats, page, pageSize, orderby, desc)},- retrievalFunc: func(ctx context.Context, userID string, req mcp.RetrievalRequest) (string, error) {- return mcpRetrieval(ctx, ds, userID, req)+ retrievalFunc: func(ctx context.Context, req mcp.RetrievalRequest) (string, error) {+ return mcpRetrieval(ctx, ds, req)},}}func (h *MCPServerHandler) newTransport(resolveUser func(context.Context, string) (string, error), opts mcp.Options) *mcp.Handler {- return mcp.NewHandler(resolveUser, func(userID string) mcp.Connector {- return mcp.NewServiceConnector(userID, h.listDatasetsFunc, h.listChatsFunc, h.retrievalFunc)+ return mcp.NewHandler(resolveUser, func() mcp.Connector {+ return mcp.NewServiceConnector(h.listDatasetsFunc, h.listChatsFunc, h.retrievalFunc)}, opts)}@@ -97,13 +96,13 @@ func (h *MCPServerHandler) NewStandalone(ctx context.Context, auth *AuthHandler,// @Produce json// @Router /api/v1/mcp [post]func (h *MCPServerHandler) HandleMCP(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-- hdl := h.newTransport(func(context.Context, string) (string, error) { return user.ID, nil }, mcp.Options{StreamableHTTP: true, JSONResponse: true})+ hdl := h.newTransport(func(ctx context.Context, _ string) (string, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return "", permission.ErrUnauthenticated+ }+ return userID, nil+ }, mcp.Options{StreamableHTTP: true, JSONResponse: true})defer hdl.Close()request := c.Request.Clone(c.Request.Context())request.URL.Path = "/mcp"@@ -117,12 +116,9 @@ func (h *MCPServerHandler) HandleMCP(c *gin.Context) {// mcpListDatasets wraps DatasetService.ListDatasets for the MCP tool handler,// filling in default values for parameters that the MCP tool does not expose.-func mcpListDatasets(ctx context.Context, ds *dataset.DatasetService, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {- contextUserID := permission.UserIDFromContext(ctx)- if contextUserID == "" {- ctx = permission.WithIdentity(ctx, userID, permission.TenantIDFromContext(ctx))- } else if contextUserID != userID {- return nil, 0, permission.ErrIdentityMismatch+func mcpListDatasets(ctx context.Context, ds *dataset.DatasetService, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {+ if permission.UserIDFromContext(ctx) == "" {+ return nil, 0, permission.ErrUnauthenticated}data, total, _, err := ds.ListDatasets(ctx,"", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}},@@ -133,12 +129,9 @@ 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) {- contextUserID := permission.UserIDFromContext(ctx)- if contextUserID == "" {- ctx = permission.WithIdentity(ctx, userID, permission.TenantIDFromContext(ctx))- } else if contextUserID != userID {- return nil, 0, permission.ErrIdentityMismatch+func mcpListChats(ctx context.Context, chatService *service.ChatService, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error) {+ if permission.UserIDFromContext(ctx) == "" {+ return nil, 0, permission.ErrUnauthenticated}resp, err := chatService.ListChats(ctx, "1", "", "", "", page, pageSize, []dao.OrderTerm{{Column: orderby, Desc: desc}}, nil)if err != nil {diff --git a/internal/handler/mindmap.go b/internal/handler/mindmap.goindex 9fdad99743..a629f35563 100644--- a/internal/handler/mindmap.go+++ b/internal/handler/mindmap.go@@ -20,9 +20,11 @@ import ("context""encoding/json""fmt"+"ragflow/internal/common""ragflow/internal/entity"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission""ragflow/internal/service""regexp""strings"@@ -47,13 +49,15 @@ func runMindMap(ctx context.Context, config mindMapRunConfig) (mindMapNode, erroif config.LLM == nil {return mindMapNode{}, fmt.Errorf("LLM not configured")}- identity, err := service.ResolveIdentity(ctx)- if err != nil {- return mindMapNode{}, err+ if permission.UserIDFromContext(ctx) == "" {+ return mindMapNode{}, permission.ErrUnauthenticated}modelTenantID := config.ModelTenantIDif modelTenantID == "" {- modelTenantID = identity.TenantID+ modelTenantID = permission.TenantIDFromContext(ctx)+ if modelTenantID == "" {+ modelTenantID = permission.UserIDFromContext(ctx)+ }}retrievalReq := mindMapRetrievalRequest(config.Question, config.KbIDs, config.SearchID, config.SearchConfig)ranks, err := config.ChunkSvc.RetrievalTest(ctx, retrievalReq)@@ -72,11 +76,10 @@ func runMindMap(ctx context.Context, config mindMapRunConfig) (mindMapNode, erro// A stale search_config chat_id should not prevent mind-map generation;// fall back to the tenant's configured default model.- identity.TenantID = modelTenantID- access := identity- chatModel, modelErr := config.LLM.NewChatModel(streamCtx, access, modelID)+ modelCtx := permission.WithTenantID(streamCtx, modelTenantID)+ chatModel, modelErr := config.LLM.NewChatModel(modelCtx, modelID)if modelErr != nil {- chatModel, modelErr = config.LLM.NewDefaultChatModel(streamCtx, access)+ chatModel, modelErr = config.LLM.NewDefaultChatModel(modelCtx)}if modelErr != nil {return mindMapNode{}, modelErrdiff --git a/internal/handler/openai_chat.go b/internal/handler/openai_chat.goindex ccf7f74b35..30103d6cb8 100644--- a/internal/handler/openai_chat.go+++ b/internal/handler/openai_chat.go@@ -50,12 +50,6 @@ func (h *OpenAIChatHandler) OpenAIChatCompletions(c *gin.Context) {return}- user, code, msg := GetUser(c)- if code != common.CodeSuccess {- common.RespondError(c, code, msg)- return- }-bodyBytes, err := io.ReadAll(c.Request.Body)if err != nil {common.RespondError(c, common.CodeArgumentError, err.Error())@@ -133,5 +127,5 @@ func (h *OpenAIChatHandler) OpenAIChatCompletions(c *gin.Context) {// Long agentic runs stream for minutes or compute before their single// write; clear http.Server.WriteTimeout so neither is cut off mid-response.clearResponseWriteDeadline(c)- h.svc.OpenAIChatCompletions(c, user.ID, chatID, bodyBytes)+ h.svc.OpenAIChatCompletions(c, chatID, bodyBytes)}diff --git a/internal/handler/providers.go b/internal/handler/providers.goindex bb8627a68a..89e925f08f 100644--- a/internal/handler/providers.go+++ b/internal/handler/providers.go@@ -99,11 +99,10 @@ func (h *ProviderHandler) ListProviders(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()// list tenant providers- providers, errorCode, err := h.modelProviderService.ListProvidersOfTenant(ctx, userID)+ providers, errorCode, err := h.modelProviderService.ListProvidersOfTenant(ctx)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -125,10 +124,9 @@ func (h *ProviderHandler) AddProvider(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- errorCode, err := h.modelProviderService.AddModelProvider(ctx, req.ProviderName, userID)+ errorCode, err := h.modelProviderService.AddModelProvider(ctx, req.ProviderName)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -144,10 +142,9 @@ func (h *ProviderHandler) DeleteProvider(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- errorCode, err := h.modelProviderService.DeleteModelProvider(ctx, userID, providerName)+ errorCode, err := h.modelProviderService.DeleteModelProvider(ctx, providerName)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -196,7 +193,7 @@ func (h *ProviderHandler) ListModels(c *gin.Context) {regionOverride = &value}apiKeyConfig := json.RawMessage(c.Query("api_key_config"))- instanceModels, err := h.fetchSavedProviderModels(c.Request.Context(), providerName, instanceName, c.GetString("user_id"), service.SavedProviderModelOptions{+ instanceModels, err := h.fetchSavedProviderModels(c.Request.Context(), providerName, instanceName, service.SavedProviderModelOptions{APIKeyConfig: apiKeyConfig,BaseURL: baseURLOverride,Region: regionOverride,@@ -211,7 +208,7 @@ func (h *ProviderHandler) ListModels(c *gin.Context) {_, baseURLProvided := c.GetQuery("base_url")_, regionProvided := c.GetQuery("region")if instanceName != "" && !apiKeyProvided && !baseURLProvided && !regionProvided {- instanceModels, err := h.fetchSavedProviderModels(c.Request.Context(), providerName, instanceName, c.GetString("user_id"), service.SavedProviderModelOptions{})+ instanceModels, err := h.fetchSavedProviderModels(c.Request.Context(), providerName, instanceName, service.SavedProviderModelOptions{})if err == nil {common.RespondSuccessList(c, instanceModels, "success")return@@ -235,8 +232,8 @@ func (h *ProviderHandler) ListModels(c *gin.Context) {common.RespondSuccessList(c, result, "success")}-func (h *ProviderHandler) fetchSavedProviderModels(ctx context.Context, providerName, instanceName, userID string, options service.SavedProviderModelOptions) ([]map[string]interface{}, error) {- config, err := h.modelProviderService.ResolveSavedProviderModelConfig(ctx, providerName, instanceName, userID, options)+func (h *ProviderHandler) fetchSavedProviderModels(ctx context.Context, providerName, instanceName string, options service.SavedProviderModelOptions) ([]map[string]interface{}, error) {+ config, err := h.modelProviderService.ResolveSavedProviderModelConfig(ctx, providerName, instanceName, options)if err != nil {return nil, err}@@ -515,14 +512,13 @@ func (h *ProviderHandler) CreateProviderInstance(c *gin.Context) {return}- userID := c.GetString("user_id")apiKey := service.NormalizeAPIKey(req.APIKey)// If the request body only contains "instance_name", create a name-only// instance without API key validation or model creation.// Mirrors Python's provider_api.py:349 — set(data.keys()) == {"instance_name"}.if apiKey == "" && req.BaseURL == "" && req.Region == "" && len(req.ModelInfo) == 0 {- code, err := h.modelProviderService.CreateNameOnlyProviderInstance(ctx, providerName, req.InstanceName, userID)+ code, err := h.modelProviderService.CreateNameOnlyProviderInstance(ctx, providerName, req.InstanceName)if err != nil {common.RespondError(c, code, err.Error())return@@ -531,7 +527,7 @@ func (h *ProviderHandler) CreateProviderInstance(c *gin.Context) {return}- code, err := h.modelProviderService.CreateProviderInstance(ctx, providerName, req.InstanceName, apiKey, req.BaseURL, req.Region, userID, req.ModelInfo)+ code, err := h.modelProviderService.CreateProviderInstance(ctx, providerName, req.InstanceName, apiKey, req.BaseURL, req.Region, req.ModelInfo)if err != nil {common.RespondError(c, code, err.Error())return@@ -547,10 +543,9 @@ func (h *ProviderHandler) ListProviderInstances(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- instances, errorCode, err := h.modelProviderService.ListProviderInstances(ctx, providerName, userID)+ instances, errorCode, err := h.modelProviderService.ListProviderInstances(ctx, providerName)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -572,10 +567,9 @@ func (h *ProviderHandler) ShowProviderInstance(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- instance, errorCode, err := h.modelProviderService.ShowProviderInstance(ctx, providerName, instanceIDOrName, userID)+ instance, errorCode, err := h.modelProviderService.ShowProviderInstance(ctx, providerName, instanceIDOrName)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -597,11 +591,9 @@ func (h *ProviderHandler) ShowInstanceBalance(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- // Get tenant ID from user- balance, errorCode, err := h.modelProviderService.ShowInstanceBalance(ctx, providerName, instanceName, userID)+ balance, errorCode, err := h.modelProviderService.ShowInstanceBalance(ctx, providerName, instanceName)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -624,8 +616,7 @@ func (h *ProviderHandler) CheckConnection(c *gin.Context) {return}- userID := c.GetString("user_id")- errCode, err := h.modelProviderService.CheckConnection(ctx, providerName, req, userID)+ errCode, err := h.modelProviderService.CheckConnection(ctx, providerName, req)if err != nil {common.RespondError(c, errCode, err.Error())return@@ -647,9 +638,7 @@ func (h *ProviderHandler) CheckInstanceConnection(c *gin.Context) {common.Respond(c, http.StatusBadRequest, 400, nil, "Instance name is required")return}- userID := c.GetString("user_id")-- instanceInfo, code, err := h.modelProviderService.ShowProviderInstance(ctx, providerName, instanceName, userID)+ instanceInfo, code, err := h.modelProviderService.ShowProviderInstance(ctx, providerName, instanceName)if err != nil {common.RespondError(c, code, err.Error())return@@ -660,7 +649,7 @@ func (h *ProviderHandler) CheckInstanceConnection(c *gin.Context) {errorCode, err := h.modelProviderService.CheckConnection(ctx, providerName, service.CheckConnectionRequest{UseSavedCredentials: true,InstanceID: instanceID,- }, userID)+ })if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -683,10 +672,7 @@ func (h *ProviderHandler) ListTasks(c *gin.Context) {return}- userID := c.GetString("user_id")-- // Get tenant ID from user- listTaskResponse, errorCode, err := h.modelProviderService.ListTasks(ctx, providerName, instanceName, userID)+ listTaskResponse, errorCode, err := h.modelProviderService.ListTasks(ctx, providerName, instanceName)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -715,10 +701,7 @@ func (h *ProviderHandler) ShowTask(c *gin.Context) {return}- userID := c.GetString("user_id")-- // Get tenant ID from user- taskResponse, errorCode, err := h.modelProviderService.ShowTask(ctx, providerName, instanceName, taskID, userID)+ taskResponse, errorCode, err := h.modelProviderService.ShowTask(ctx, providerName, instanceName, taskID)if err != nil {common.RespondError(c, errorCode, err.Error())return@@ -747,13 +730,7 @@ func (h *ProviderHandler) AlterProviderInstance(c *gin.Context) {return}- userID := c.GetString("user_id")- if userID == "" {- common.RespondError(c, common.CodeUnauthorized, "Unauthorized")- return- }-- code, err := h.modelProviderService.AlterProviderInstance(ctx, userID, providerName, instanceName, req.InstanceName, req.APIKey, req.ClearAPIKey, req.BaseURL, req.Region, *req.ModelInfo)+ code, err := h.modelProviderService.AlterProviderInstance(ctx, providerName, instanceName, req.InstanceName, req.APIKey, req.ClearAPIKey, req.BaseURL, req.Region, *req.ModelInfo)if err != nil {common.RespondError(c, code, err.Error())return@@ -774,10 +751,9 @@ func (h *ProviderHandler) DropProviderInstance(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- code, err := h.modelProviderService.DropProviderInstances(ctx, providerName, userID, req.Instances)+ code, err := h.modelProviderService.DropProviderInstances(ctx, providerName, req.Instances)if err != nil {common.RespondError(c, code, err.Error())return@@ -809,7 +785,7 @@ func (h *ProviderHandler) ListInstanceModels(c *gin.Context) {if keywords == "true" {// list supported models- modelList, err := h.fetchSavedProviderModels(ctx, providerName, instanceName, c.GetString("user_id"), service.SavedProviderModelOptions{})+ modelList, err := h.fetchSavedProviderModels(ctx, providerName, instanceName, service.SavedProviderModelOptions{})if err != nil {common.RespondError(c, common.CodeServerError, err.Error())return@@ -819,7 +795,7 @@ func (h *ProviderHandler) ListInstanceModels(c *gin.Context) {return}- modelInstances, err := h.modelProviderService.ListInstanceModels(ctx, providerName, instanceName, c.GetString("user_id"))+ modelInstances, err := h.modelProviderService.ListInstanceModels(ctx, providerName, instanceName)if err != nil {common.RespondError(c, common.CodeNotFound, err.Error())return@@ -846,7 +822,6 @@ func (h *ProviderHandler) AlterModel(c *gin.Context) {return}- userID := c.GetString("user_id")modelName := strings.TrimPrefix(c.Param("model_name"), "/")modelName = strings.TrimSpace(modelName)modelID := strings.TrimSpace(req.ModelID)@@ -882,7 +857,7 @@ func (h *ProviderHandler) AlterModel(c *gin.Context) {}ctx := c.Request.Context()- code, err := h.modelProviderService.AlterModel(ctx, providerName, instanceName, modelName, userID, modelID, updateDict)+ code, err := h.modelProviderService.AlterModel(ctx, providerName, instanceName, modelName, modelID, updateDict)if err != nil {common.RespondError(c, code, err.Error())return@@ -932,10 +907,9 @@ func (h *ProviderHandler) AddModel(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- code, err := h.modelProviderService.AddModel(ctx, &req, userID)+ code, err := h.modelProviderService.AddModel(ctx, &req)if err != nil {common.RespondError(c, code, err.Error())return@@ -966,10 +940,9 @@ func (h *ProviderHandler) DropInstanceModels(c *gin.Context) {return}- userID := c.GetString("user_id")ctx := c.Request.Context()- code, err := h.modelProviderService.DropInstanceModels(ctx, providerName, instanceName, userID, req.ModelNames)+ code, err := h.modelProviderService.DropInstanceModels(ctx, providerName, instanceName, req.ModelNames)if err != nil {common.RespondError(c, code, err.Error())return@@ -1645,17 +1618,11 @@ func (h *ProviderHandler) ParseFile(c *gin.Context) {// ListModelsForUserInTenant handles GET /api/v1/models for the authenticated// user and selected tenant context.func (h *ProviderHandler) ListModelsForUserInTenant(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-modelType := c.Query("type")tenantID := c.Query("tenant_id")ctx := c.Request.Context()- models, code, err := h.modelProviderService.ListModelsForUserInTenant(ctx, user.ID, tenantID, modelType)+ models, code, err := h.modelProviderService.ListModelsForUserInTenant(ctx, tenantID, modelType)if err != nil {common.RespondError(c, code, err.Error())returndiff --git a/internal/handler/search.go b/internal/handler/search.goindex b6d5c992a4..b3f557ea67 100644--- a/internal/handler/search.go+++ b/internal/handler/search.go@@ -19,7 +19,9 @@ package handlerimport ("context""net/http"+"ragflow/internal/common"+ "ragflow/internal/permission""strconv""strings"@@ -395,10 +397,10 @@ func (h *SearchHandler) Completion(c *gin.Context) {return}- adapter := &service.TenantStreamAdapter{Factory: h.modelFactory, Identity: plan.Identity, ModelID: plan.ModelID}-ctx, cancel := context.WithCancel(c.Request.Context())defer cancel()+ ctx = permission.WithTenantID(ctx, plan.TenantID)+ adapter := &service.TenantStreamAdapter{Factory: h.modelFactory, ModelID: plan.ModelID}c.Request = c.Request.WithContext(ctx)hadError := falsediff --git a/internal/handler/searchbot.go b/internal/handler/searchbot.goindex 03896dee99..9d2b91cecd 100644--- a/internal/handler/searchbot.go+++ b/internal/handler/searchbot.go@@ -28,6 +28,7 @@ import ("ragflow/internal/common""ragflow/internal/entity"+ "ragflow/internal/permission""ragflow/internal/service""go.uber.org/zap"@@ -254,12 +255,12 @@ func (h *SearchBotHandler) Ask(c *gin.Context) {// Resolve chat model ID.modelID := ""options := service.AskStreamOptions{}- askAccess, accessErr := service.ResolveIdentity(c.Request.Context())- if accessErr != nil {- if respondPermissionErrorIf(c, accessErr, true) {- return- }- jsonInternalError(c, accessErr)+ modelTenantID := strings.TrimSpace(permission.TenantIDFromContext(c.Request.Context()))+ if modelTenantID == "" {+ modelTenantID = permission.UserIDFromContext(c.Request.Context())+ }+ if modelTenantID == "" {+ jsonInternalError(c, permission.ErrUnauthenticated)return}if req.SearchID != "" {@@ -277,6 +278,9 @@ func (h *SearchBotHandler) Ask(c *gin.Context) {return}searchConfig := searchConfigFromDetail(detail)+ if tenantID, ok := detail["tenant_id"].(string); ok && strings.TrimSpace(tenantID) != "" {+ modelTenantID = strings.TrimSpace(tenantID)+ }options = service.BuildAskStreamOptions(req.SearchID, searchConfig)if chatID, ok := searchConfig["chat_id"].(string); ok && chatID != "" {modelID = chatID@@ -284,7 +288,7 @@ func (h *SearchBotHandler) Ask(c *gin.Context) {}if modelID == "" && h.modelFactory != nil {ctx := c.Request.Context()- if info, infoErr := h.modelFactory.ResolveDefaultInfo(ctx, askAccess, entity.ModelTypeChat); infoErr == nil {+ if info, infoErr := h.modelFactory.ResolveDefaultInfo(permission.WithTenantID(ctx, modelTenantID), entity.ModelTypeChat); infoErr == nil {modelID = service.ModelReference(info)}}@@ -308,9 +312,10 @@ func (h *SearchBotHandler) Ask(c *gin.Context) {}ctx, cancel := context.WithCancel(c.Request.Context())defer cancel()+ ctx = permission.WithTenantID(ctx, modelTenantID)c.Request = c.Request.WithContext(ctx)hadError := false- adapter := &service.TenantStreamAdapter{Factory: h.modelFactory, Identity: askAccess, ModelID: modelID}+ adapter := &service.TenantStreamAdapter{Factory: h.modelFactory, ModelID: modelID}for delta := range h.askSvc.StreamWithOptions(ctx, adapter, req.Question, filtered, options) {var ok boolswitch delta.Kind {@@ -372,6 +377,10 @@ func (h *SearchBotHandler) MindMap(c *gin.Context) {}searchConfig := map[string]interface{}{}+ modelTenantID := strings.TrimSpace(permission.TenantIDFromContext(c.Request.Context()))+ if modelTenantID == "" {+ modelTenantID = permission.UserIDFromContext(c.Request.Context())+ }if req.SearchID != "" {if h.searchSvc == nil {jsonInternalError(c, fmt.Errorf("search service not configured"))@@ -387,17 +396,21 @@ func (h *SearchBotHandler) MindMap(c *gin.Context) {return}searchConfig = searchConfigFromDetail(detail)+ if tenantID, ok := detail["tenant_id"].(string); ok && strings.TrimSpace(tenantID) != "" {+ modelTenantID = strings.TrimSpace(tenantID)+ }}ctx := c.Request.Context()mindMap, err := runMindMap(ctx, mindMapRunConfig{- Question: req.Question,- KbIDs: filtered,- SearchID: req.SearchID,- SearchConfig: searchConfig,- ChunkSvc: h.chunkSvc,- LLM: h.modelFactory,- TenantSvc: h.tenantSvc,+ Question: req.Question,+ KbIDs: filtered,+ SearchID: req.SearchID,+ SearchConfig: searchConfig,+ ModelTenantID: modelTenantID,+ ChunkSvc: h.chunkSvc,+ LLM: h.modelFactory,+ TenantSvc: h.tenantSvc,})if err != nil {if respondPermissionErrorIf(c, err, true) {diff --git a/internal/handler/skill_search.go b/internal/handler/skill_search.goindex 7a578a7ff6..230c6fb481 100644--- a/internal/handler/skill_search.go+++ b/internal/handler/skill_search.go@@ -57,17 +57,11 @@ func NewSkillSearchHandler(docEngine engine.DocEngine, spaceRemover file.DocRemo// @Success 200 {object} map[string]interface{}// @Router /v1/skills/config [get]func (h *SkillSearchHandler) GetConfig(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-embdID := c.Query("embd_id")spaceID := c.Query("space_id")ctx := c.Request.Context()- result, code, err := h.searchService.GetConfig(ctx, user.ID, spaceID, embdID)+ result, code, err := h.searchService.GetConfig(ctx, spaceID, embdID)if err != nil {common.RespondError(c, code, err.Error())return@@ -85,12 +79,6 @@ func (h *SkillSearchHandler) GetConfig(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/skills/config [post]func (h *SkillSearchHandler) UpdateConfig(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-var req service.UpdateConfigRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeDataError, err.Error())@@ -98,7 +86,7 @@ func (h *SkillSearchHandler) UpdateConfig(c *gin.Context) {}ctx := c.Request.Context()- result, code, err := h.searchService.UpdateConfig(ctx, user.ID, &req)+ result, code, err := h.searchService.UpdateConfig(ctx, &req)if err != nil {common.RespondError(c, code, err.Error())return@@ -116,19 +104,13 @@ func (h *SkillSearchHandler) UpdateConfig(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/skills/search [post]func (h *SkillSearchHandler) Search(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-var req service.SearchRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeDataError, err.Error())return}- result, code, err := h.searchService.Search(c.Request.Context(), user.ID, &req, h.docEngine)+ result, code, err := h.searchService.Search(c.Request.Context(), &req, h.docEngine)if err != nil {common.RespondError(c, code, err.Error())return@@ -153,12 +135,6 @@ type IndexSkillsRequest struct {// @Success 200 {object} map[string]interface{}// @Router /v1/skills/index [post]func (h *SkillSearchHandler) IndexSkills(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-var req IndexSkillsRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeDataError, err.Error())@@ -169,7 +145,7 @@ func (h *SkillSearchHandler) IndexSkills(c *gin.Context) {embdID := req.EmbdIDif embdID == "" {ctx := c.Request.Context()- config, code, err := h.searchService.GetConfig(ctx, user.ID, req.SpaceID, "")+ config, code, err := h.searchService.GetConfig(ctx, req.SpaceID, "")if err != nil {common.RespondError(c, code, "failed to get skill search config: "+err.Error())return@@ -184,13 +160,12 @@ func (h *SkillSearchHandler) IndexSkills(c *gin.Context) {// Ensure index exists before indexing (for both ES and Infinity)common.Info("Ensuring skill index exists before indexing",- zap.String("tenantID", user.ID),zap.String("spaceID", req.SpaceID),zap.String("engineType", h.docEngine.GetType()),zap.Int("skillCount", len(req.Skills)))if h.docEngine.GetType() == "elasticsearch" {- if err := h.indexerService.EnsureIndex(c.Request.Context(), user.ID, req.SpaceID, h.docEngine, embdID); err != nil {+ if err := h.indexerService.EnsureIndex(c.Request.Context(), req.SpaceID, h.docEngine, embdID); err != nil {if respondPermissionErrorIf(c, err, true) {return}@@ -199,17 +174,16 @@ func (h *SkillSearchHandler) IndexSkills(c *gin.Context) {}}- if err := h.indexerService.BatchIndexSkills(c.Request.Context(), user.ID, req.SpaceID, req.Skills, h.docEngine, embdID); err != nil {+ if err := h.indexerService.BatchIndexSkills(c.Request.Context(), req.SpaceID, req.Skills, h.docEngine, embdID); err != nil {if respondPermissionErrorIf(c, err, true) {return}- common.Error(fmt.Sprintf("Failed to batch index skills: tenantID=%s, spaceID=%s, error=%v", user.ID, req.SpaceID, err), err)+ common.Error(fmt.Sprintf("Failed to batch index skills: spaceID=%s, error=%v", req.SpaceID, err), err)common.RespondError(c, common.CodeOperatingError, err.Error())return}common.Info("Successfully indexed skills",- zap.String("tenantID", user.ID),zap.String("spaceID", req.SpaceID),zap.Int("indexedCount", len(req.Skills)))@@ -233,12 +207,6 @@ type ReindexRequest struct {// @Success 200 {object} map[string]interface{}// @Router /v1/skills/reindex [post]func (h *SkillSearchHandler) Reindex(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-var req ReindexRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeDataError, err.Error())@@ -249,7 +217,7 @@ func (h *SkillSearchHandler) Reindex(c *gin.Context) {embdID := req.EmbdIDif embdID == "" {ctx := c.Request.Context()- config, code, err := h.searchService.GetConfig(ctx, user.ID, req.SpaceID, "")+ config, code, err := h.searchService.GetConfig(ctx, req.SpaceID, "")if err != nil {common.RespondError(c, code, "failed to get skill search config: "+err.Error())return@@ -262,7 +230,7 @@ func (h *SkillSearchHandler) Reindex(c *gin.Context) {embdID = val}- result, err := h.indexerService.ReindexAll(c.Request.Context(), user.ID, req.SpaceID, h.docEngine, embdID)+ result, err := h.indexerService.ReindexAll(c.Request.Context(), req.SpaceID, h.docEngine, embdID)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -286,12 +254,6 @@ func (h *SkillSearchHandler) Reindex(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/skills/index [delete]func (h *SkillSearchHandler) DeleteSkillIndex(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-skillID := c.Query("skill_id")spaceID := c.Query("space_id")if skillID == "" {@@ -299,7 +261,7 @@ func (h *SkillSearchHandler) DeleteSkillIndex(c *gin.Context) {return}- err := h.indexerService.DeleteSkillIndex(c.Request.Context(), user.ID, spaceID, skillID, h.docEngine)+ err := h.indexerService.DeleteSkillIndex(c.Request.Context(), spaceID, skillID, h.docEngine)if err != nil {if respondPermissionErrorIf(c, err, true) {return@@ -323,12 +285,6 @@ func (h *SkillSearchHandler) DeleteSkillIndex(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/skill/search/init [post]func (h *SkillSearchHandler) InitializeIndex(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-embdID := c.Query("embd_id")spaceID := c.Query("space_id")if embdID == "" {@@ -336,7 +292,7 @@ func (h *SkillSearchHandler) InitializeIndex(c *gin.Context) {return}- if err := h.indexerService.InitializeIndex(c.Request.Context(), user.ID, spaceID, h.docEngine, embdID); err != nil {+ if err := h.indexerService.InitializeIndex(c.Request.Context(), spaceID, h.docEngine, embdID); err != nil {if respondPermissionErrorIf(c, err, true) {return}@@ -357,14 +313,8 @@ func (h *SkillSearchHandler) InitializeIndex(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/skills/spaces [get]func (h *SkillSearchHandler) ListSpaces(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-ctx := c.Request.Context()- result, code, err := h.spaceService.ListSpaces(ctx, user.ID)+ result, code, err := h.spaceService.ListSpaces(ctx)if err != nil {common.RespondError(c, code, err.Error())return@@ -392,12 +342,6 @@ type CreateSpaceRequest struct {// @Success 200 {object} map[string]interface{}// @Router /api/v1/skills/spaces [post]func (h *SkillSearchHandler) CreateSpace(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-var req CreateSpaceRequestif err := c.ShouldBindJSON(&req); err != nil {common.RespondError(c, common.CodeDataError, err.Error())@@ -405,7 +349,7 @@ func (h *SkillSearchHandler) CreateSpace(c *gin.Context) {}ctx := c.Request.Context()- result, code, err := h.spaceService.CreateSpace(ctx, user.ID, &service.CreateSpaceRequest{+ result, code, err := h.spaceService.CreateSpace(ctx, &service.CreateSpaceRequest{Name: req.Name,Description: req.Description,EmbdID: req.EmbdID,@@ -428,12 +372,6 @@ func (h *SkillSearchHandler) CreateSpace(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/skills/spaces/{space_id} [get]func (h *SkillSearchHandler) GetSpace(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-spaceID := c.Param("space_id")if spaceID == "" {common.RespondError(c, common.CodeDataError, "space_id is required")@@ -441,7 +379,7 @@ func (h *SkillSearchHandler) GetSpace(c *gin.Context) {}ctx := c.Request.Context()- result, code, err := h.spaceService.GetSpace(ctx, user.ID, spaceID)+ result, code, err := h.spaceService.GetSpace(ctx, spaceID)if err != nil {common.RespondError(c, code, err.Error())return@@ -471,12 +409,6 @@ type UpdateSpaceRequest struct {// @Success 200 {object} map[string]interface{}// @Router /api/v1/skills/spaces/{space_id} [put]func (h *SkillSearchHandler) UpdateSpace(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-spaceID := c.Param("space_id")if spaceID == "" {common.RespondError(c, common.CodeDataError, "space_id is required")@@ -490,7 +422,7 @@ func (h *SkillSearchHandler) UpdateSpace(c *gin.Context) {}ctx := c.Request.Context()- result, code, err := h.spaceService.UpdateSpace(ctx, user.ID, spaceID, &service.UpdateSpaceRequest{+ result, code, err := h.spaceService.UpdateSpace(ctx, spaceID, &service.UpdateSpaceRequest{Name: req.Name,Description: req.Description,EmbdID: req.EmbdID,@@ -516,19 +448,13 @@ func (h *SkillSearchHandler) UpdateSpace(c *gin.Context) {// @Success 202 {object} map[string]interface{}// @Router /api/v1/skills/spaces/{space_id} [delete]func (h *SkillSearchHandler) DeleteSpace(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-spaceID := c.Param("space_id")if spaceID == "" {common.RespondError(c, common.CodeDataError, "space_id is required")return}- code, err := h.spaceService.DeleteSpace(c.Request.Context(), user.ID, spaceID, h.docEngine)+ code, err := h.spaceService.DeleteSpace(c.Request.Context(), spaceID, h.docEngine)if err != nil {common.RespondError(c, code, err.Error())return@@ -553,12 +479,6 @@ func (h *SkillSearchHandler) DeleteSpace(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/skills/space/by-folder [get]func (h *SkillSearchHandler) GetSpaceByFolder(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-folderID := c.Query("folder_id")if folderID == "" {common.RespondError(c, common.CodeDataError, "folder_id is required")@@ -566,7 +486,7 @@ func (h *SkillSearchHandler) GetSpaceByFolder(c *gin.Context) {}ctx := c.Request.Context()- result, code, err := h.spaceService.GetSpaceByFolderID(ctx, user.ID, folderID)+ result, code, err := h.spaceService.GetSpaceByFolderID(ctx, folderID)if err != nil {common.RespondError(c, code, err.Error())returndiff --git a/internal/handler/stats.go b/internal/handler/stats.goindex ff62ce19c0..a84c7a3725 100644--- a/internal/handler/stats.go+++ b/internal/handler/stats.go@@ -39,12 +39,6 @@ func NewStatsHandler(statsService *service.StatsService) *StatsHandler {// GetChatStats returns API conversation statistics for the current user's tenant.func (h *StatsHandler) GetChatStats(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-now := time.Now()fromDate := c.DefaultQuery("from_date", now.AddDate(0, 0, -7).Format("2006-01-02 00:00:00"))toDate := c.DefaultQuery("to_date", now.Format("2006-01-02 15:04:05"))@@ -60,7 +54,7 @@ func (h *StatsHandler) GetChatStats(c *gin.Context) {ctx := c.Request.Context()// Get stats- stats, err := h.statsService.GetChatStats(ctx, user.ID, fromDate, toDate, source)+ stats, err := h.statsService.GetChatStats(ctx, fromDate, toDate, source)if err != nil {code := common.CodeExceptionErrorif errors.Is(err, service.ErrTenantNotFound) {diff --git a/internal/handler/tenant.go b/internal/handler/tenant.goindex fe40a2bbdd..9db16c20eb 100644--- a/internal/handler/tenant.go+++ b/internal/handler/tenant.go@@ -23,6 +23,8 @@ import ("net/http""net/mail""net/smtp"++ "ragflow/internal/permission""ragflow/internal/server""strings""time"@@ -30,7 +32,6 @@ import ("github.com/gin-gonic/gin""ragflow/internal/common"- "ragflow/internal/permission""ragflow/internal/service"dataset "ragflow/internal/service/dataset"@@ -71,12 +72,6 @@ type SetModelRequest struct {}func (h *TenantHandler) setDefaultModels(c *gin.Context, wrapModels bool) {- 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 SetModelRequestif err := c.ShouldBindJSON(&req); err != nil {@@ -85,7 +80,7 @@ func (h *TenantHandler) setDefaultModels(c *gin.Context, wrapModels bool) {}ctx := c.Request.Context()- code, err := h.userTenantService.SetModelSettings(ctx, user.ID, &service.SetModelSettingsRequest{+ code, err := h.userTenantService.SetModelSettings(ctx, &service.SetModelSettingsRequest{DefaultModel: &service.DefaultModelSelection{ModelProvider: req.ModelProvider,ModelInstance: req.ModelInstance,@@ -113,14 +108,9 @@ func (h *TenantHandler) setDefaultModels(c *gin.Context, wrapModels bool) {// models_api.py:84). The frontend hook `useFetchDefaultModels`// (web/src/hooks/use-llm-request.tsx:423) reads `data.data.models`.func (h *TenantHandler) GetDefaultModels(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- defaultModels, err := h.userTenantService.ListDefaultModels(ctx, user.ID)+ defaultModels, err := h.userTenantService.ListDefaultModels(ctx)if err != nil {common.RespondError(c, common.CodeExceptionError, err.Error())return@@ -144,14 +134,9 @@ func (h *TenantHandler) GetDefaultModels(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /v1/user/tenant_info [get]func (h *TenantHandler) TenantInfo(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- tenantInfo, err := h.userTenantService.GetCurrentTenantInfo(ctx, user.ID)+ tenantInfo, err := h.userTenantService.GetCurrentTenantInfo(ctx)if err != nil {common.RespondError(c, common.CodeExceptionError, err.Error())return@@ -173,14 +158,9 @@ func (h *TenantHandler) TenantInfo(c *gin.Context) {// @Success 200 {object} map[string]interface{}// @Router /api/v1/tenants [get]func (h *TenantHandler) TenantList(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }ctx := c.Request.Context()- tenantList, err := h.tenantService.GetTenantList(ctx, user.ID)+ tenantList, err := h.tenantService.GetTenantList(ctx)if err != nil {common.RespondError(c, common.CodeExceptionError, err.Error())return@@ -335,12 +315,6 @@ func (h *TenantHandler) DeleteChunkStore(c *gin.Context) {// @Param tenant_id path string true "Tenant ID"// @Router /api/v1/tenants/{tenant_id}/users [get]func (h *TenantHandler) ListTenantMembers(c *gin.Context) {- user, errorCode, errorMessage := GetUser(c)- if errorCode != common.CodeSuccess {- common.RespondError(c, errorCode, errorMessage)- return- }-tenantID := c.Param("tenant_id")if tenantID == "" {common.Respond(c, http.StatusBadRequest, common.CodeBadRequest, nil, "tenant_id is required")@@ -352,7 +326,7 @@ func (h *TenantHandler) ListTenantMembers(c *gin.Context) {}ctx := c.Request.Context()- members, code, err := h.tenantService.ListMembers(ctx, user.ID, tenantID)+ members, code, err := h.tenantService.ListMembers(ctx, tenantID)if err != nil {common.RespondError(c, code, err.Error())return@@ -541,7 +515,7 @@ func (h *TenantHandler) AddTenantMember(c *gin.Context) {}ctx := c.Request.Context()- resp, code, err := h.tenantService.AddMember(ctx, user.ID, tenantID, &req)+ resp, code, err := h.tenantService.AddMember(ctx, tenantID, &req)if err != nil {common.RespondError(c, code, err.Error())operationLog.Code = int(code)@@ -621,7 +595,7 @@ func (h *TenantHandler) RemoveTenantMember(c *gin.Context) {}ctx := c.Request.Context()- code, err := h.tenantService.RemoveMember(ctx, user.ID, tenantID, body.UserID)+ code, err := h.tenantService.RemoveMember(ctx, tenantID, body.UserID)if err != nil {common.RespondError(c, code, err.Error())operationLog.Code = int(code)@@ -668,7 +642,7 @@ func (h *TenantHandler) AcceptTenantInvite(c *gin.Context) {return}ctx := c.Request.Context()- code, err := h.tenantService.AcceptInvite(ctx, user.ID, tenantID)+ code, err := h.tenantService.AcceptInvite(ctx, tenantID)if err != nil {common.RespondError(c, code, err.Error())operationLog.Code = int(code)diff --git a/internal/handler/user.go b/internal/handler/user.goindex 59cdd8ca4d..d7af18c984 100644--- a/internal/handler/user.go+++ b/internal/handler/user.go@@ -535,7 +535,7 @@ func (h *UserHandler) SetTenantInfo(c *gin.Context) {req.TTSID = &value}- code, err := h.userTenantService.SetModelSettings(ctx, user.ID, &req)+ code, err := h.userTenantService.SetModelSettings(ctx, &req)if err != nil {common.RespondError(c, code, err.Error())operationLog.Code = int(code)diff --git a/internal/ingestion/task/embedder.go b/internal/ingestion/task/embedder.goindex 5f86a3ed7b..061c903357 100644--- a/internal/ingestion/task/embedder.go+++ b/internal/ingestion/task/embedder.go@@ -38,6 +38,7 @@ import ("ragflow/internal/dao""ragflow/internal/entity/models"componentpkg "ragflow/internal/ingestion/component"+ "ragflow/internal/permission""ragflow/internal/service""ragflow/internal/tokenizer"@@ -707,7 +708,7 @@ func init() {return kb.EmbdID, nil},func(ctx context.Context, tenantID, embdID string) (*models.EmbeddingModel, error) {- embeddingModel, err := modelFactory.NewEmbeddingModel(ctx, service.Identity{TenantID: tenantID}, embdID)+ embeddingModel, err := modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), embdID)if err != nil {return nil, err}diff --git a/internal/ingestion/task/knowledge_compiler_wiring.go b/internal/ingestion/task/knowledge_compiler_wiring.goindex df69504b0b..1daeccde2f 100644--- a/internal/ingestion/task/knowledge_compiler_wiring.go+++ b/internal/ingestion/task/knowledge_compiler_wiring.go@@ -32,6 +32,7 @@ import (knowledgecompiler "ragflow/internal/ingestion/component/knowledge_compiler"kc "ragflow/internal/ingestion/component/knowledge_compiler/common""ragflow/internal/ingestion/knowledge_compile"+ "ragflow/internal/permission""ragflow/internal/service"appcommon "ragflow/internal/common"@@ -565,7 +566,7 @@ func newKnowledgeCompilerDepsResolver() kc.DepsResolver {// actually run instead of failing / falling back to a no-op. Use the// tenant model ID so later model resolution can use the same persisted// tenant model directly.- defaultInfo, derr := modelFactory.ResolveDefaultInfo(modelCtx, service.Identity{TenantID: tenantID}, entity.ModelTypeChat)+ defaultInfo, derr := modelFactory.ResolveDefaultInfo(permission.WithTenantID(modelCtx, tenantID), entity.ModelTypeChat)if derr != nil || defaultInfo == nil || strings.TrimSpace(defaultInfo.ID) == "" {return kc.Deps{}, fmt.Errorf("knowledge_compiler: llm_id is empty and no tenant default chat model available: %w", derr)}@@ -579,7 +580,7 @@ func newKnowledgeCompilerDepsResolver() kc.DepsResolver {// generation cap and must not be used as the input budget.llmMax := kc.DefaultLLMContextLength// Bound the model-config lookup and inherit cancellation from the task.- modelInfo, contextLengthErr := modelFactory.ResolveInfo(modelCtx, service.Identity{TenantID: tenantID}, entity.ModelTypeChat, llmID)+ modelInfo, contextLengthErr := modelFactory.ResolveInfo(permission.WithTenantID(modelCtx, tenantID), entity.ModelTypeChat, llmID)if contextLengthErr == nil && modelInfo != nil && modelInfo.ContextLength > 0 {llmMax = modelInfo.ContextLength}@@ -625,7 +626,7 @@ func (c *kcChatInvoker) Chat(ctx context.Context, req kc.ChatRequest) (*kc.ChatRif req.LLMID != "" {llmID = req.LLMID}- chatModel, err := c.factory.NewChatModel(ctx, service.Identity{TenantID: c.tenantID}, llmID)+ chatModel, err := c.factory.NewChatModel(permission.WithTenantID(ctx, c.tenantID), llmID)if err != nil {return nil, err}@@ -805,7 +806,7 @@ func (e *kcEmbedder) Encode(ctx context.Context, texts []string) ([][]float32, e// loudly instead of silently producing empty vectors.func (e *kcEmbedder) resolveModel(ctx context.Context) (*models.EmbeddingModel, error) {if embdID := strings.TrimSpace(e.embdID); embdID != "" {- embeddingModel, err := e.factory.NewEmbeddingModel(ctx, service.Identity{TenantID: e.tenantID}, embdID)+ embeddingModel, err := e.factory.NewEmbeddingModel(permission.WithTenantID(ctx, e.tenantID), embdID)if err != nil {return nil, fmt.Errorf("knowledge_compiler: resolve embedding model: %w", err)}@@ -814,7 +815,7 @@ func (e *kcEmbedder) resolveModel(ctx context.Context) (*models.EmbeddingModel,}return embeddingModel, nil}- embeddingModel, err := e.factory.NewDefaultEmbeddingModel(ctx, service.Identity{TenantID: e.tenantID})+ embeddingModel, err := e.factory.NewDefaultEmbeddingModel(permission.WithTenantID(ctx, e.tenantID))if err != nil {return nil, fmt.Errorf("knowledge_compiler: embedding_model is required and no tenant default embedding model is set: %w", err)}diff --git a/internal/mcp/connector.go b/internal/mcp/connector.goindex 141d824bc6..1b1951b5f4 100644--- a/internal/mcp/connector.go+++ b/internal/mcp/connector.go@@ -25,23 +25,20 @@ import (// ServiceConnector implements the Connector interface using in-process// service layer calls, avoiding HTTP round-trips to self.type ServiceConnector struct {- userID string- listDatasets func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)- listChats func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)- retrieval func(ctx context.Context, userID string, req RetrievalRequest) (string, error)+ listDatasets func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)+ listChats func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error)+ retrieval func(ctx context.Context, req RetrievalRequest) (string, error)}// NewServiceConnector creates a ServiceConnector.// The function arguments abstract the service dependencies so this package// does not import the service layer directly.func NewServiceConnector(- userID string,- listDatasetsFunc func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error),- listChatsFunc func(ctx context.Context, userID string, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error),- retrievalFunc func(ctx context.Context, userID string, req RetrievalRequest) (string, error),+ listDatasetsFunc func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error),+ listChatsFunc func(ctx context.Context, page, pageSize int, orderby string, desc bool) ([]map[string]interface{}, int64, error),+ retrievalFunc func(ctx context.Context, req RetrievalRequest) (string, error),) *ServiceConnector {return &ServiceConnector{- userID: userID,listDatasets: listDatasetsFunc,listChats: listChatsFunc,retrieval: retrievalFunc,@@ -53,7 +50,7 @@ func (c *ServiceConnector) ListDatasets(ctx context.Context, page, pageSize int,var data []map[string]anyif pageSize == -1 {for page = 1; ; page++ {- items, total, err := c.listDatasets(ctx, c.userID, page, 100, orderby, desc)+ items, total, err := c.listDatasets(ctx, page, 100, orderby, desc)if err != nil {return "", err}@@ -67,7 +64,7 @@ func (c *ServiceConnector) ListDatasets(ctx context.Context, page, pageSize int,}} else {var err error- data, _, err = c.listDatasets(ctx, c.userID, page, min(pageSize, 100), orderby, desc)+ data, _, err = c.listDatasets(ctx, page, min(pageSize, 100), orderby, desc)if err != nil {return "", err}@@ -76,7 +73,7 @@ func (c *ServiceConnector) ListDatasets(ctx context.Context, page, pageSize int,}func (c *ServiceConnector) ListChats(ctx context.Context, page, pageSize int, orderby string, desc bool) (string, error) {- data, _, err := c.listChats(ctx, c.userID, page, pageSize, orderby, desc)+ data, _, err := c.listChats(ctx, page, pageSize, orderby, desc)if err != nil {return "", err}@@ -101,5 +98,5 @@ func listText(data []map[string]any, chats bool) (string, error) {}func (c *ServiceConnector) Retrieval(ctx context.Context, req RetrievalRequest) (string, error) {- return c.retrieval(ctx, c.userID, req)+ return c.retrieval(ctx, req)}diff --git a/internal/mcp/http.go b/internal/mcp/http.goindex 4f87c4872b..f55e222fb6 100644--- a/internal/mcp/http.go+++ b/internal/mcp/http.go@@ -11,6 +11,8 @@ import ("sync"sdk "github.com/modelcontextprotocol/go-sdk/mcp"++ "ragflow/internal/permission")// Options selects the Python-equivalent transport and response modes.@@ -49,13 +51,12 @@ func Credential(headers http.Header) string {// NewHandler authenticates every request and binds legacy SSE sessions to their// owner. Wire framing, initialization and dispatch remain SDK responsibilities.-func NewHandler(resolve func(context.Context, string) (string, error), connector func(string) Connector, opts Options) *Handler {+func NewHandler(resolve func(context.Context, string) (string, error), connector func() Connector, opts Options) *Handler {lifetime, cancel := context.WithCancel(context.Background())var mu sync.Mutexsessions := make(map[string]sseSession)- type identityKey struct{}streamable := sdk.NewStreamableHTTPHandler(func(r *http.Request) *sdk.Server {- return newServer(r.Context(), connector(r.Context().Value(identityKey{}).(string)))+ return newServer(r.Context(), connector())}, &sdk.StreamableHTTPOptions{Stateless: true, JSONResponse: opts.JSONResponse, MaxRequestBodyBytes: 1 << 20, PropagateRequestCancellation: true})mux := http.NewServeMux()if opts.StreamableHTTP {@@ -66,13 +67,13 @@ func NewHandler(resolve func(context.Context, string) (string, error), connectormux.HandleFunc("GET /sse", func(w http.ResponseWriter, r *http.Request) {id := rand.Text()transport := &sdk.SSEServerTransport{Endpoint: "/messages/?session_id=" + url.QueryEscape(id), Response: w, MaxRequestBodyBytes: 1 << 20}- owner := r.Context().Value(identityKey{}).(string)+ owner := permission.UserIDFromContext(r.Context())w.Header().Set("Content-Type", "text/event-stream")w.Header().Set("Cache-Control", "no-cache")// Hold the registry lock through Connect: it publishes the endpoint before// returning, so a fast client's first POST must wait until it is ready.mu.Lock()- session, err := newServer(r.Context(), connector(owner)).Connect(r.Context(), transport, nil)+ session, err := newServer(r.Context(), connector()).Connect(r.Context(), transport, nil)if err == nil {sessions[id] = sseSession{owner, transport}}@@ -98,7 +99,7 @@ func NewHandler(resolve func(context.Context, string) (string, error), connectormu.Lock()session, ok := sessions[id]mu.Unlock()- if !ok || session.owner != r.Context().Value(identityKey{}).(string) {+ if !ok || session.owner != permission.UserIDFromContext(r.Context()) {http.Error(w, "session not found", http.StatusNotFound)return}@@ -132,7 +133,8 @@ func NewHandler(resolve func(context.Context, string) (string, error), connectorhttp.Error(w, "invalid authorization", http.StatusUnauthorized)return}- mux.ServeHTTP(w, r.WithContext(context.WithValue(ctx, identityKey{}, userID)))+ ctx = permission.WithIdentity(ctx, userID, permission.TenantIDFromContext(ctx))+ mux.ServeHTTP(w, r.WithContext(ctx))})return &Handler{handler: protected, cancel: cancel}}diff --git a/internal/mcp/http_test.go b/internal/mcp/http_test.goindex e1158d2ad6..80509e1caa 100644--- a/internal/mcp/http_test.go+++ b/internal/mcp/http_test.go@@ -15,6 +15,8 @@ import ("time"sdk "github.com/modelcontextprotocol/go-sdk/mcp"++ "ragflow/internal/permission")type headerTransport struct {@@ -50,17 +52,18 @@ func TestSDKTransportsAndTools(t *testing.T) {for _, mode := range []string{"json", "stream", "sse"} {t.Run(mode, func(t *testing.T) {var retrieval RetrievalRequest- factory := func(user string) Connector {- return NewServiceConnector(user,- func(ctx context.Context, user string, page, size int, _ string, _ bool) ([]map[string]any, int64, error) {+ factory := func() Connector {+ return NewServiceConnector(+ func(ctx context.Context, page, size int, _ string, _ bool) ([]map[string]any, int64, error) {+ user := permission.UserIDFromContext(ctx)if user == "empty" {return nil, 0, nil}return []map[string]any{{"id": user, "name": "Dataset", "description": nil}}, 1, nil- }, func(context.Context, string, int, int, string, bool) ([]map[string]any, int64, error) {+ }, func(context.Context, int, int, string, bool) ([]map[string]any, int64, error) {return nil, 0, nil},- func(ctx context.Context, user string, req RetrievalRequest) (string, error) {+ func(ctx context.Context, req RetrievalRequest) (string, error) {retrieval = reqreturn `{"chunks":[],"query_info":{"question":"hello"}}`, nil})@@ -158,7 +161,7 @@ func TestCredential(t *testing.T) {}func TestConnectorPaginationAndNulls(t *testing.T) {var pages, sizes []int- c := NewServiceConnector("tenant", func(_ context.Context, user string, page, size int, _ string, _ bool) ([]map[string]any, int64, error) {+ c := NewServiceConnector(func(_ context.Context, page, size int, _ string, _ bool) ([]map[string]any, int64, error) {pages = append(pages, page)sizes = append(sizes, size)return []map[string]any{{"id": fmt.Sprint(page)}}, 2, nil@@ -179,10 +182,11 @@ func TestConcurrentTenantsAndSSEOwnership(t *testing.T) {return "", fmt.Errorf("denied")}return key, nil- }, func(user string) Connector {- return NewServiceConnector(user, func(_ context.Context, user string, _, _ int, _ string, _ bool) ([]map[string]any, int64, error) {+ }, func() Connector {+ return NewServiceConnector(func(ctx context.Context, _, _ int, _ string, _ bool) ([]map[string]any, int64, error) {+ user := permission.UserIDFromContext(ctx)return []map[string]any{{"id": user}}, 1, nil- }, func(context.Context, string, int, int, string, bool) ([]map[string]any, int64, error) {+ }, func(context.Context, int, int, string, bool) ([]map[string]any, int64, error) {return nil, 0, nil}, nil)}, Options{true, true, true})@@ -264,12 +268,12 @@ func TestConcurrentTenantsAndSSEOwnership(t *testing.T) {func TestProtocolErrorsAndCancellation(t *testing.T) {started := make(chan context.Context, 1)- h := NewHandler(func(_ context.Context, key string) (string, error) { return key, nil }, func(user string) Connector {- return NewServiceConnector(user, func(context.Context, string, int, int, string, bool) ([]map[string]any, int64, error) {+ h := NewHandler(func(_ context.Context, key string) (string, error) { return key, nil }, func() Connector {+ return NewServiceConnector(func(context.Context, int, int, string, bool) ([]map[string]any, int64, error) {return nil, 0, nil- }, func(context.Context, string, int, int, string, bool) ([]map[string]any, int64, error) {+ }, func(context.Context, int, int, string, bool) ([]map[string]any, int64, error) {return nil, 0, nil- }, func(ctx context.Context, _ string, _ RetrievalRequest) (string, error) {+ }, func(ctx context.Context, _ RetrievalRequest) (string, error) {started <- ctx<-ctx.Done()return "", ctx.Err()diff --git a/internal/permission/types.go b/internal/permission/types.goindex 328ece197d..0fdf8273c5 100644--- a/internal/permission/types.go+++ b/internal/permission/types.go@@ -41,6 +41,15 @@ func WithIdentity(ctx context.Context, userID, tenantID string) context.Contextreturn context.WithValue(ctx, tenantIDContextKey{}, tenantID)}+// WithTenantID sets the operation Tenant when ctx has no active Tenant. It+// preserves an authenticated Tenant so resource scope cannot switch tenants.+func WithTenantID(ctx context.Context, tenantID string) context.Context {+ if TenantIDFromContext(ctx) != "" {+ return ctx+ }+ return context.WithValue(ctx, tenantIDContextKey{}, tenantID)+}+// UserIDFromContext returns the authenticated user ID attached to ctx.func UserIDFromContext(ctx context.Context) string {if ctx == nil {@@ -50,7 +59,7 @@ func UserIDFromContext(ctx context.Context) string {return userID}-// TenantIDFromContext returns the active Tenant ID attached to ctx.+// TenantIDFromContext returns the active Tenant or operation scope attached to ctx.func TenantIDFromContext(ctx context.Context) string {if ctx == nil {return ""diff --git a/internal/server/api/server.go b/internal/server/api/server.goindex c28e619eaa..70356ebf10 100644--- a/internal/server/api/server.go+++ b/internal/server/api/server.go@@ -23,6 +23,7 @@ import ("net""net/http"_ "net/http/pprof"+"ragflow/internal/agent/audio""ragflow/internal/agent/canvas""ragflow/internal/agent/retrievalbridge"@@ -32,6 +33,7 @@ import ("ragflow/internal/channels"modelModule "ragflow/internal/entity/models""ragflow/internal/handler"+ "ragflow/internal/permission""ragflow/internal/router""ragflow/internal/server/local""ragflow/internal/service"@@ -154,21 +156,19 @@ func startServer(ctx context.Context, serverName string, arguments *bootstrap.SedocumentDAO,agenttool.RetrievalModelConstructors{Embedding: func(ctx context.Context, tenantID, modelRef string) (*modelModule.EmbeddingModel, error) {- access := service.Identity{TenantID: tenantID}if strings.TrimSpace(modelRef) == "" {- return modelFactory.NewDefaultEmbeddingModel(ctx, access)+ return modelFactory.NewDefaultEmbeddingModel(permission.WithTenantID(ctx, tenantID))}- return modelFactory.NewEmbeddingModel(ctx, access, modelRef)+ return modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), modelRef)},Chat: func(ctx context.Context, tenantID, modelRef string) (*modelModule.ChatModel, error) {- access := service.Identity{TenantID: tenantID}if strings.TrimSpace(modelRef) == "" {- return modelFactory.NewDefaultChatModel(ctx, access)+ return modelFactory.NewDefaultChatModel(permission.WithTenantID(ctx, tenantID))}- return modelFactory.NewChatModel(ctx, access, modelRef)+ return modelFactory.NewChatModel(permission.WithTenantID(ctx, tenantID), modelRef)},Rerank: func(ctx context.Context, tenantID, modelRef string) (*modelModule.RerankModel, error) {- return modelFactory.NewRerankModel(ctx, service.Identity{TenantID: tenantID}, modelRef)+ return modelFactory.NewRerankModel(permission.WithTenantID(ctx, tenantID), modelRef)},},retrievalEnhancer,diff --git a/internal/service/agent.go b/internal/service/agent.goindex 728d88f9c8..2a5527f58c 100644--- a/internal/service/agent.go+++ b/internal/service/agent.go@@ -23,6 +23,8 @@ import ("errors""fmt""maps"++ "ragflow/internal/permission""ragflow/internal/service/file""reflect""slices"@@ -44,7 +46,6 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"- "ragflow/internal/permission"permissionresponse "ragflow/internal/permission/response""ragflow/internal/tokenizer"@@ -688,7 +689,7 @@ func (s *AgentService) ListAgents(ctx context.Context, keywords string, page, paif len(ownerIDs) > 0 && !sliceContains(effectiveOwnerIDs, userID) {return &ListAgentsResponse{Canvas: []json.RawMessage{}, Total: 0}, common.CodeSuccess, nil}- return s.listAgentsGroupsOnly(ctx, userID, keywords, terms, page, pageSize)+ return s.listAgentsGroupsOnly(ctx, keywords, terms, page, pageSize)}// Fetch agents. In merge/mixed modes we disable SQL pagination (page=0) and@@ -733,7 +734,7 @@ func (s *AgentService) ListAgents(ctx context.Context, keywords string, page, pa// (Python include_template_groups).includeGroups := len(ownerIDs) == 0 || sliceContains(effectiveOwnerIDs, userID)if includeGroups && (mergeMode || wantsGroups) {- return s.mergeAgentsAndGroups(ctx, userID, agentItems, keywords, terms, page, pageSize)+ return s.mergeAgentsAndGroups(ctx, agentItems, keywords, terms, page, pageSize)}raw := make([]json.RawMessage, len(agentItems))@@ -746,7 +747,8 @@ func (s *AgentService) ListAgents(ctx context.Context, keywords string, page, pa// listAgentsGroupsOnly returns only the caller's compilation template groups// (Python canvas_category == ["compilation_template_group"] branch).-func (s *AgentService) listAgentsGroupsOnly(ctx context.Context, userID, keywords string, terms []dao.OrderTerm, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {+func (s *AgentService) listAgentsGroupsOnly(ctx context.Context, keywords string, terms []dao.OrderTerm, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)groups, err := s.compilationTemplateGroupDAO.ListSaved(ctx, dao.DB, userID, keywords, "", terms)if err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to list compilation template groups: %w", err)@@ -755,7 +757,7 @@ func (s *AgentService) listAgentsGroupsOnly(ctx context.Context, userID, keywordgroups = slicePage(groups, page, pageSize)raw := make([]json.RawMessage, 0, len(groups))for _, g := range groups {- item, err := s.marshalMergeGroupItem(ctx, userID, g)+ item, err := s.marshalMergeGroupItem(ctx, g)if err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to build group item: %w", err)}@@ -768,7 +770,8 @@ func (s *AgentService) listAgentsGroupsOnly(ctx context.Context, userID, keyword// groups into a single list ordered by the requested timestamp, then pages in Go.// A stable sort retains the original// agent-before-group order when timestamps are equal.-func (s *AgentService) mergeAgentsAndGroups(ctx context.Context, userID string, agentItems []*AgentItem, keywords string, terms []dao.OrderTerm, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {+func (s *AgentService) mergeAgentsAndGroups(ctx context.Context, agentItems []*AgentItem, keywords string, terms []dao.OrderTerm, page, pageSize int) (*ListAgentsResponse, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)groups, err := s.compilationTemplateGroupDAO.ListSaved(ctx, dao.DB, userID, keywords, "", terms)if err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to list compilation template groups: %w", err)@@ -787,7 +790,7 @@ func (s *AgentService) mergeAgentsAndGroups(ctx context.Context, userID string,})}for _, g := range groups {- raw, err := s.marshalMergeGroupItem(ctx, userID, g)+ raw, err := s.marshalMergeGroupItem(ctx, g)if err != nil {return nil, common.CodeServerError, fmt.Errorf("failed to build group item: %w", err)}@@ -823,7 +826,7 @@ func (s *AgentService) mergeAgentsAndGroups(ctx context.Context, userID string,// marshalMergeGroupItem renders a compilation template group as a merged /agents// canvas item: the group shape (ICompilationTemplateGroup) plus the "type" and// "title" discriminators the frontend union expects (Python _group_to_dict).-func (s *AgentService) marshalMergeGroupItem(ctx context.Context, userID string, g *entity.CompilationTemplateGroup) (json.RawMessage, error) {+func (s *AgentService) marshalMergeGroupItem(ctx context.Context, g *entity.CompilationTemplateGroup) (json.RawMessage, error) {children, err := s.compilationTemplateDAO.ListByGroup(ctx, dao.DB, g.ID)if err != nil {return nil, err@@ -992,7 +995,7 @@ func (s *AgentService) CreateAgent(ctx context.Context, req *CreateAgentRequest)code, permissionErr := permissionresponse.Normalize(permission.ErrUnauthenticated)return nil, code, permissionErr}- tenantID, err := prepareAgentCreation(ctx, userID)+ tenantID, err := prepareAgentCreation(ctx)if err != nil {code, normalized := permissionresponse.Normalize(err)return nil, code, normalized@@ -1292,7 +1295,7 @@ func (s *AgentService) UpdateAgent(ctx context.Context, canvasID string, patch mif err := validateEntries(dslMap); err != nil {return fmt.Errorf("update agent %s: %w", canvasID, err)}- if err := validateAgentChatModelReferences(ctx, userID, canvasInstance.EffectiveTenantID(), dslMap, !release); err != nil {+ if err := validateAgentChatModelReferences(ctx, canvasInstance.EffectiveTenantID(), dslMap, !release); err != nil {return err}updates["dsl"] = entity.JSONMap(dslpkg.NormalizeForCanvas(dslMap))@@ -1416,7 +1419,6 @@ type PublishAgentRequest struct {}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@@ -1444,7 +1446,7 @@ func (s *AgentService) PublishAgent(ctx context.Context, canvasID string, req *P}}- if err := validateAgentChatModels(ctx, userID, canvasInstance.EffectiveTenantID(), dsl); err != nil {+ if err := validateAgentChatModels(ctx, canvasInstance.EffectiveTenantID(), dsl); err != nil {return nil, err}if err := component.ValidateDynamicEntries(dsl); err != nil {@@ -1658,7 +1660,7 @@ func (s *AgentService) RunAgent(ctx context.Context, canvasID, sessionID, versioif !trustedFirstTouch {return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, dao.ErrUserCanvasNotFound)}- } else if err := checkAgentSessionRunPermission(ctx, userID, sessionID); err != nil {+ } else if err := checkAgentSessionRunPermission(ctx, sessionID); err != nil {return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, err)}}@@ -1675,10 +1677,10 @@ func (s *AgentService) RunAgent(ctx context.Context, canvasID, sessionID, versioif session == nil {return nil}- if err := checkAgentSessionRunPermission(ctx, userID, sessionID); err != nil {+ if err := checkAgentSessionRunPermission(ctx, sessionID); err != nil {return fmt.Errorf("RunAgent: session %q not found: %w", sessionID, err)}- if err := s.persistAgentRunQuestion(ctx, canvasID, userID, sessionID, messageID, userInput, receivedAt); err != nil {+ if err := s.persistAgentRunQuestion(ctx, canvasID, sessionID, messageID, userInput, receivedAt); err != nil {return fmt.Errorf("RunAgent: persist question: %w: %w", err, ErrAgentStorageError)}questionSaved = true@@ -1867,7 +1869,7 @@ func (s *AgentService) RunAgent(ctx context.Context, canvasID, sessionID, versioreturn nil, fmt.Errorf("RunAgent: load session %q: %w: %w", sessionID, err, ErrAgentStorageError)}if existingSession != nil {- if err := checkAgentSessionRunPermission(ctx, userID, sessionID); err != nil {+ if err := checkAgentSessionRunPermission(ctx, sessionID); err != nil {return nil, fmt.Errorf("RunAgent: session %q not found: %w", sessionID, err)}}@@ -1876,7 +1878,7 @@ func (s *AgentService) RunAgent(ctx context.Context, canvasID, sessionID, versiodsl = dslpkg.NormalizeForRun(existingSession.DSL)}}- if err := validateAgentChatModels(ctx, userID, agentTenantID, dsl); err != nil {+ if err := validateAgentChatModels(ctx, agentTenantID, dsl); err != nil {return nil, err}if err := component.ValidateDynamicEntries(dsl); err != nil {@@ -1889,7 +1891,7 @@ func (s *AgentService) RunAgent(ctx context.Context, canvasID, sessionID, versio// conversation. A new session may reuse its graph, memory, and env state,// but must never inherit conversation history or an execution path.dsl = dslpkg.ResetForNewSession(dsl)- if err = s.createAgentRunSession(ctx, sessionID, userID, canvasID, dsl, versionRow, userInput); err != nil {+ if err = s.createAgentRunSession(ctx, sessionID, canvasID, dsl, versionRow, userInput); err != nil {return nil, fmt.Errorf("RunAgent: create session %q: %w: %w", sessionID, err, ErrAgentStorageError)}}@@ -2037,11 +2039,11 @@ func (s *AgentService) runReleasedAgent(ctx context.Context, canvasID, sessionID// It resolves models in the canvas tenant and checks access for the actual// caller. Agent components always invoke a chat model; model-free// canvases contain no Agent component and pass through.-func validateAgentChatModels(ctx context.Context, userID, tenantID string, dsl map[string]any) error {- return validateAgentChatModelReferences(ctx, userID, tenantID, dsl, false)+func validateAgentChatModels(ctx context.Context, tenantID string, dsl map[string]any) error {+ return validateAgentChatModelReferences(ctx, tenantID, dsl, false)}-func validateAgentChatModelReferences(ctx context.Context, userID, tenantID string, dsl map[string]any, draft bool) error {+func validateAgentChatModelReferences(ctx context.Context, tenantID string, dsl map[string]any, draft bool) error {c, err := canvas.DecodeFromDSL(dsl)if err != nil {return nil@@ -2062,7 +2064,7 @@ func validateAgentChatModelReferences(ctx context.Context, userID, tenantID striif !ok {modelRef, _ = node.Obj.Params["llm_id"].(string)}- if _, err := modelFactory.ResolveInfo(ctx, Identity{UserID: userID, TenantID: tenantID}, entity.ModelTypeChat, modelRef); err != nil {+ if _, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeChat, modelRef); err != nil {if draft && (errors.Is(err, errModelConfigUnavailable) || errors.Is(err, gorm.ErrRecordNotFound)) && !errors.Is(err, permission.ErrPermissionDenied) && !errors.Is(err, permission.ErrResourceNotFound) {continue}@@ -2075,7 +2077,7 @@ func validateAgentChatModelReferences(ctx context.Context, userID, tenantID strireturn nil}-func checkAgentSessionRunPermission(ctx context.Context, userID, sessionID string) error {+func checkAgentSessionRunPermission(ctx context.Context, sessionID string) error {err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx,permission.ResourceRef{Kind: permission.ResourceKindAgentSession, ID: sessionID},@@ -2218,7 +2220,7 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanvif versionRow == nil && len(dsl) == 0 {answer := fmt.Sprintf("No published version found for canvas %q — publish a version before running.", canvasID)state.RecordOutput("answer", "answer", answer)- if err := s.persistAgentRunSession(ctx, canvasID, userID, sessionID, messageID, userInput, answer, "", nil, dsl, state, true); err != nil {+ if err := s.persistAgentRunSession(ctx, canvasID, sessionID, messageID, userInput, answer, "", nil, dsl, state, true); err != nil {return nil, canvas.NewInternalRunError(fmt.Errorf("persist agent session: %w: %w", err, ErrAgentStorageError))}// Emit a message event so the SSE surface matches the@@ -2240,7 +2242,7 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv// DSL → *Canvas.c, err := decodeCanvasFromDSL(dsl)if err != nil {- s.markAgentSessionFailed(ctx, canvasID, userID, sessionID, "decode: "+err.Error())+ s.markAgentSessionFailed(ctx, canvasID, sessionID, "decode: "+err.Error())s.markRunFailed(ctx, runID, "decode: "+err.Error())return nil, err}@@ -2317,9 +2319,9 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv// Only used for ParseAgentUploads (read-only); nil DocRemover means// this FileService MUST NOT be used for DeleteFiles.fileSvc := file.NewFileService(nil)- files, ferr := fileSvc.ParseAgentUploads(ctx, userID, rawFiles, beginLayoutRecognize(c))+ files, ferr := fileSvc.ParseAgentUploads(ctx, rawFiles, beginLayoutRecognize(c))if ferr != nil {- s.markAgentSessionFailed(ctx2, canvasID, userID, sessionID, "parse files: "+ferr.Error())+ s.markAgentSessionFailed(ctx2, canvasID, sessionID, "parse files: "+ferr.Error())s.markRunFailed(ctx2, runID, "parse files: "+ferr.Error())return nil, fmt.Errorf("parse agent files: %w", ferr)}@@ -2377,7 +2379,7 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanvzap.String("run", runID),zap.String("type", fmt.Sprintf("%T", err)),zap.Error(err))- s.markAgentSessionFailed(ctx2, canvasID, userID, sessionID, "compile: "+err.Error())+ s.markAgentSessionFailed(ctx2, canvasID, sessionID, "compile: "+err.Error())s.markRunFailed(ctx2, runID, "compile: "+err.Error())if _, ok := errors.AsType[*runtime.UserFacingError](err); ok {return nil, err@@ -2475,7 +2477,7 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanvif answer != "" {appendAssistantHistory(state, partialAssistantOutput(answer, downloads, attachment))}- if persistErr := s.persistAgentRunSession(ctx, canvasID, userID, sessionID, messageID, userInput, answer, thinking, referencePayload, dsl, state, answer != ""); persistErr != nil {+ if persistErr := s.persistAgentRunSession(ctx, canvasID, sessionID, messageID, userInput, answer, thinking, referencePayload, dsl, state, answer != ""); persistErr != nil {return nil, canvas.NewInternalRunError(fmt.Errorf("persist interrupted agent session: %w: %w", persistErr, ErrAgentStorageError),)@@ -2499,8 +2501,8 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanvemitAgentMessageEvents(emit, failureText, thinking, referencePayload)visibleAnswer = failureText}- if persistErr := s.persistAgentRunSession(ctx, canvasID, userID, sessionID, messageID, userInput, visibleAnswer, thinking, referencePayload, dsl, state, visibleAnswer != ""); persistErr != nil {- s.markAgentSessionFailed(ctx2, canvasID, userID, sessionID, "persist session: "+persistErr.Error())+ if persistErr := s.persistAgentRunSession(ctx, canvasID, sessionID, messageID, userInput, visibleAnswer, thinking, referencePayload, dsl, state, visibleAnswer != ""); persistErr != nil {+ s.markAgentSessionFailed(ctx2, canvasID, sessionID, "persist session: "+persistErr.Error())s.markRunFailed(ctx2, runID, "persist session: "+persistErr.Error())return nil, canvas.NewInternalRunError(fmt.Errorf("persist agent session: %w: %w", persistErr, ErrAgentStorageError),@@ -2513,11 +2515,11 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv})emit("message_end", string(meData))}- s.markAgentSessionFailed(ctx2, canvasID, userID, sessionID, "invoke: "+err.Error())+ s.markAgentSessionFailed(ctx2, canvasID, sessionID, "invoke: "+err.Error())s.markRunFailed(ctx2, runID, "invoke: "+err.Error())return state, nil}- s.markAgentSessionFailed(ctx2, canvasID, userID, sessionID, "invoke: "+err.Error())+ s.markAgentSessionFailed(ctx2, canvasID, sessionID, "invoke: "+err.Error())s.markRunFailed(ctx2, runID, "invoke: "+err.Error())return nil, canvasInvokeError(err)}@@ -2527,8 +2529,8 @@ func (s *AgentService) buildRunFunc(canvasID string, versionRow *entity.UserCanv// template literals; retaining it in the prompt history makes the model// reproduce and amplify those literals on later turns.appendAssistantHistory(state, partialAssistantOutput(answer, downloads, attachment))- if persistErr := s.persistAgentRunSession(ctx, canvasID, userID, sessionID, messageID, userInput, answer, thinking, referencePayload, dsl, state, true); persistErr != nil {- s.markAgentSessionFailed(ctx2, canvasID, userID, sessionID, "persist session: "+persistErr.Error())+ if persistErr := s.persistAgentRunSession(ctx, canvasID, sessionID, messageID, userInput, answer, thinking, referencePayload, dsl, state, true); persistErr != nil {+ s.markAgentSessionFailed(ctx2, canvasID, sessionID, "persist session: "+persistErr.Error())s.markRunFailed(ctx2, runID, "persist session: "+persistErr.Error())return nil, canvas.NewInternalRunError(fmt.Errorf("persist agent session: %w: %w", persistErr, ErrAgentStorageError),@@ -2581,7 +2583,7 @@ func beginLayoutRecognize(c *canvas.Canvas) string {func (s *AgentService) createAgentRunSession(ctx context.Context,- sessionID, userID, agentID string,+ sessionID, agentID string,runDSL map[string]any,versionRow *entity.UserCanvasVersion,userInput any,@@ -2589,6 +2591,10 @@ func (s *AgentService) createAgentRunSession(if s == nil || s.api4ConversationDAO == nil {return errors.New("agent session storage is not configured")}+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return permission.ErrUnauthenticated+ }source := "agent"name := deriveAgentSessionName(userInput)session := &entity.API4Conversation{@@ -2698,10 +2704,11 @@ func emptyDownloadValue(value any) bool {}}-func (s *AgentService) persistAgentRunQuestion(ctx context.Context, agentID, userID, sessionID, messageID string, userInput any, receivedAt float64) error {+func (s *AgentService) persistAgentRunQuestion(ctx context.Context, agentID, sessionID, messageID string, userInput any, receivedAt float64) error {if sessionID == "" || s == nil || s.api4ConversationDAO == nil || dao.DB == nil {return nil}+ userID := permission.UserIDFromContext(ctx)text := stringifyAgentUserInput(agentRunQuery(userInput))if text == "" {return nil@@ -2712,7 +2719,7 @@ func (s *AgentService) persistAgentRunQuestion(ctx context.Context, agentID, usefunc (s *AgentService) persistAgentRunSession(ctx context.Context,- agentID, userID, sessionID, messageID string,+ agentID, sessionID, messageID string,userInput any,answer string,thinking string,@@ -2725,6 +2732,7 @@ func (s *AgentService) persistAgentRunSession(if sessionID == "" || s == nil || s.api4ConversationDAO == nil || dao.DB == nil {return nil}+ userID := permission.UserIDFromContext(ctx)history := dao.ConversationHistoryUpdate{}if stringifyAgentUserInput(agentRunQuery(userInput)) != "" {history.QuestionID = messageID@@ -3138,10 +3146,11 @@ func (s *AgentService) markRunFailed(ctx context.Context, runID, reason string)// markAgentSessionFailed keeps the persisted agent log state aligned with the// run tracker. A streamed failure may still return a user-facing message, but// it must remain a failed execution in the session history.-func (s *AgentService) markAgentSessionFailed(ctx context.Context, canvasID, userID, sessionID, reason string) {+func (s *AgentService) markAgentSessionFailed(ctx context.Context, canvasID, sessionID, reason string) {if s == nil || s.api4ConversationDAO == nil || dao.DB == nil || sessionID == "" {return}+ userID := permission.UserIDFromContext(ctx)if err := s.api4ConversationDAO.UpdateHistory(ctx, dao.DB, sessionID, canvasID, userID,map[string]interface{}{"errors": reason}, dao.ConversationHistoryUpdate{}); err != nil {common.Warn("agent run: persist failed session status failed",diff --git a/internal/service/agent_persistence_test.go b/internal/service/agent_persistence_test.goindex 97716f020a..813d8a3580 100644--- a/internal/service/agent_persistence_test.go+++ b/internal/service/agent_persistence_test.go@@ -27,6 +27,7 @@ import ("ragflow/internal/agent/canvas""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission")func TestAgentRunSessionUpdateFailurePreventsSuccessEvents(t *testing.T) {@@ -70,7 +71,8 @@ func TestAgentRunSessionUpdateFailurePreventsSuccessEvents(t *testing.T) {"path": []any{"begin_0", "message_0"},}events := make(chan canvas.RunEvent, 32)- _, err := NewAgentService().buildRunFunc("canvas-update-failure", nil, dsl)(context.Background(), map[string]any{+ ctx := permission.WithIdentity(context.Background(), "user-1", "")+ _, err := NewAgentService().buildRunFunc("canvas-update-failure", nil, dsl)(ctx, map[string]any{"__events__": events,"__message_id__": "message-1","__session_id__": "session-update-failure",@@ -136,10 +138,11 @@ func TestPersistAgentRunSessionPreservesThinking(t *testing.T) {}svc := NewAgentService()- if err := svc.persistAgentRunQuestion(t.Context(), "canvas-think", "user-1", "session-think", "msg-think-1", "question", 1); err != nil {+ ctx := permission.WithIdentity(t.Context(), "user-1", "")+ if err := svc.persistAgentRunQuestion(ctx, "canvas-think", "session-think", "msg-think-1", "question", 1); err != nil {t.Fatalf("persist question: %v", err)}- if err := svc.persistAgentRunSession(context.Background(), "canvas-think", "user-1", "session-think", "msg-think-1", "question", "final answer", "reasoning trace", map[string]interface{}{}, nil, nil, true); err != nil {+ if err := svc.persistAgentRunSession(permission.WithIdentity(context.Background(), "user-1", ""), "canvas-think", "session-think", "msg-think-1", "question", "final answer", "reasoning trace", map[string]interface{}{}, nil, nil, true); err != nil {t.Fatalf("persist: %v", err)}diff --git a/internal/service/agent_sessions.go b/internal/service/agent_sessions.goindex b686872fd5..f2f7ad768d 100644--- a/internal/service/agent_sessions.go+++ b/internal/service/agent_sessions.go@@ -583,7 +583,6 @@ func (s *AgentService) UpdateAgentTags(ctx context.Context, canvasID string, tag// CreateAgentSessionRequest is the wire shape for POST// /api/v1/agents/:agent_id/sessions.type CreateAgentSessionRequest struct {- UserID stringAgentID stringName stringSource string@@ -620,8 +619,9 @@ func (s *AgentService) CreateAgentSession(ctx context.Context, req *CreateAgentSif req.AgentID == "" {return nil, common.CodeArgumentError, errors.New("create agent session: agent_id is required")}- if req.UserID == "" {- return nil, common.CodeArgumentError, errors.New("create agent session: user_id is required")+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated}if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindCanvas, ID: req.AgentID}, permission.OperationRun); err != nil {@@ -649,7 +649,7 @@ func (s *AgentService) CreateAgentSession(ctx context.Context, req *CreateAgentSif len(dsl) == 0 {dsl = canvas.DSL}- if err := validateAgentChatModels(ctx, req.UserID, canvas.EffectiveTenantID(), dsl); err != nil {+ if err := validateAgentChatModels(ctx, canvas.EffectiveTenantID(), dsl); err != nil {if errors.Is(err, ErrAgentStorageError) {return nil, common.CodeServerError, errors.New("Internal storage error while accessing the agent.")}@@ -681,8 +681,8 @@ func (s *AgentService) CreateAgentSession(ctx context.Context, req *CreateAgentSID: id,Name: namePtr,DialogID: req.AgentID,- UserID: req.UserID,- ExpUserID: &req.UserID,+ UserID: userID,+ ExpUserID: &userID,Message: messages,Source: sourcePtr,DSL: dsl,diff --git a/internal/service/agent_test.go b/internal/service/agent_test.goindex c773099a99..8f05fb8324 100644--- a/internal/service/agent_test.go+++ b/internal/service/agent_test.go@@ -958,7 +958,7 @@ func TestMergedAgentsRespectRequestedTimestamp(t *testing.T) {{"default", nil, "new"},} {t.Run(tc.name, func(t *testing.T) {- resp, code, err := NewAgentService().mergeAgentsAndGroups(t.Context(), "user-1", items, "", tc.terms, 1, 1)+ resp, code, err := NewAgentService().mergeAgentsAndGroups(permission.WithIdentity(t.Context(), "user-1", ""), items, "", tc.terms, 1, 1)if err != nil || code != common.CodeSuccess || resp.Total != 2 || len(resp.Canvas) != 1 {t.Fatalf("merge: response=%+v code=%v err=%v", resp, code, err)}@@ -1173,7 +1173,6 @@ func TestCreateAgentSessionLeavesVersionTitleNilWithVersions(t *testing.T) {ctx := serviceTestContext(t, "user-1", "user-1")svc := NewAgentService()session, code, err := svc.CreateAgentSession(ctx, &CreateAgentSessionRequest{- UserID: "user-1",AgentID: "canvas-1",Name: "hello",})@@ -1221,7 +1220,6 @@ func TestCreateAgentSessionNoVersionLeavesTitleNil(t *testing.T) {ctx := serviceTestContext(t, "user-1", "user-1")session, code, err := NewAgentService().CreateAgentSession(ctx, &CreateAgentSessionRequest{- UserID: "user-1",AgentID: "canvas-1",})if err != nil {@@ -1309,7 +1307,7 @@ func TestAgentModelValidationUsesCanvasTenant(t *testing.T) {ctx := permission.WithIdentity(t.Context(), tenantOwnerID, tenantID)svc := NewAgentService()- if _, code, err := svc.CreateAgentSession(ctx, &CreateAgentSessionRequest{UserID: tenantOwnerID, AgentID: canvasRow.ID}); err != nil || code != common.CodeSuccess {+ if _, code, err := svc.CreateAgentSession(ctx, &CreateAgentSessionRequest{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, canvasRow.ID, map[string]any{"dsl": dsl}); err != nil {diff --git a/internal/service/agentic_pipeline.go b/internal/service/agentic_pipeline.goindex a7b91a4ba2..fb0eb139cd 100644--- a/internal/service/agentic_pipeline.go+++ b/internal/service/agentic_pipeline.go@@ -30,6 +30,7 @@ import ("ragflow/internal/common""ragflow/internal/entity"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission""ragflow/internal/tokenizer")@@ -74,13 +75,13 @@ const defaultAgenticTokenBudget = 500_000func (s *ChatPipelineService) agenticRag(ctx context.Context,- userID string,chat *entity.Chat,messages []map[string]interface{},stream bool,kwargs map[string]interface{},quote bool,) (<-chan AsyncChatResult, error) {+ userID := permission.UserIDFromContext(ctx)tmpl, err := resolveChatAgenticTemplate(chat, kwargs)if err != nil {return nil, err@@ -192,7 +193,7 @@ func (s *ChatPipelineService) agenticRag(return sendResult(result)}- chain, chainErr := s.agenticModelChain(runCtx, userID, chat)+ chain, chainErr := s.agenticModelChain(runCtx, chat)if chainErr != nil {common.ErrorCtx(runCtx, "agentic_rag: resolve chat model", chainErr)emitResult(AsyncChatResult{Answer: fmt.Sprintf("**ERROR**: %s", chainErr.Error()), Final: true})@@ -203,7 +204,7 @@ func (s *ChatPipelineService) agenticRag(if info := chain[0].Info(); info != nil && entity.ModelTypeFromStrings(info.ModelTypes).Has(entity.ModelTypeImage2Text) {modelType = "image2text"}- agentMessages := s.convertMessagesToEino(runCtx, userID, modelType, messages)+ agentMessages := s.convertMessagesToEino(runCtx, modelType, messages)// Image-bearing turns cannot fail over to a text-only model.for _, msg := range agentMessages {if len(msg.UserInputMultiContent) > 0 {@@ -443,9 +444,9 @@ func agenticUsageFields(ctx context.Context, usage *tokenizer.RunUsage) []zap.Fi// the dialog configures. Agentic RAG must not silently broaden the dialog's// model choice to every chat model owned by the tenant: a failover chain is// exactly the list the dialog's author chose, and nothing else.-func (s *ChatPipelineService) agenticModelChain(ctx context.Context, userID string, chat *entity.Chat) ([]*modelModule.ChatModel, error) {- access := Identity{UserID: userID, TenantID: chat.TenantID}- primary, err := s.agenticPrimaryModel(ctx, access, chat)+func (s *ChatPipelineService) agenticModelChain(ctx context.Context, chat *entity.Chat) ([]*modelModule.ChatModel, error) {+ ctx = permission.WithTenantID(ctx, chat.TenantID)+ primary, err := s.agenticPrimaryModel(ctx, chat)if err != nil {return nil, err}@@ -459,7 +460,7 @@ func (s *ChatPipelineService) agenticModelChain(ctx context.Context, userID striif llmID == "" || llmID == chat.LLMID {continue}- model, resolveErr := s.ModelFactory.NewChatModel(ctx, access, llmID)+ model, resolveErr := s.ModelFactory.NewChatModel(ctx, llmID)if resolveErr != nil || model == nil {common.WarnCtx(ctx, "agentic_rag: skipping unresolvable failover model",zap.String("llm_id", llmID), zap.Error(resolveErr))@@ -474,15 +475,15 @@ func (s *ChatPipelineService) agenticModelChain(ctx context.Context, userID stri// agenticPrimaryModel resolves the dialog's own model, or the tenant default// when it selected none.-func (s *ChatPipelineService) agenticPrimaryModel(ctx context.Context, access Identity, chat *entity.Chat) (*modelModule.ChatModel, error) {+func (s *ChatPipelineService) agenticPrimaryModel(ctx context.Context, chat *entity.Chat) (*modelModule.ChatModel, error) {var (model *modelModule.ChatModelerr error)if chat.LLMID == "" {- model, err = s.ModelFactory.NewDefaultChatModel(ctx, access)+ model, err = s.ModelFactory.NewDefaultChatModel(ctx)} else {- model, err = s.ModelFactory.NewChatModel(ctx, access, chat.LLMID)+ model, err = s.ModelFactory.NewChatModel(ctx, chat.LLMID)}if err != nil {return nil, fmt.Errorf("resolve chat model: %w", err)@@ -523,14 +524,14 @@ func agenticFailoverModelIDs(chat *entity.Chat) []string {// convertMessagesToEino converts pre-filtered user/assistant messages into// eino schema messages, resolving uploaded attachments throughout the history.-func (s *ChatPipelineService) convertMessagesToEino(ctx context.Context, userID, modelType string, messages []map[string]interface{}) []*schema.Message {+func (s *ChatPipelineService) convertMessagesToEino(ctx context.Context, modelType string, messages []map[string]interface{}) []*schema.Message {out := make([]*schema.Message, 0, len(messages))for _, m := range messages {role, _ := m["role"].(string)content, _ := m["content"].(string)switch role {case "user":- text, images := s.splitChatAttachments(ctx, userID, m["files"])+ text, images := s.splitChatAttachments(ctx, m["files"])if text != "" {content += "\n\n" + text}diff --git a/internal/service/api_token.go b/internal/service/api_token.goindex 3b39579ad6..5e97019dd1 100644--- a/internal/service/api_token.go+++ b/internal/service/api_token.go@@ -18,10 +18,11 @@ package serviceimport ("context"- "fmt"+"ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission""ragflow/internal/service/billing""time")@@ -41,7 +42,11 @@ type APIKeyResponse struct {}// ListAPIKeys list all API keys for a tenant-func (s *SystemService) ListAPIKeys(ctx context.Context, tenantID string) ([]*APIKeyResponse, error) {+func (s *SystemService) ListAPIKeys(ctx context.Context) ([]*APIKeyResponse, error) {+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {+ return nil, err+ }APITokenDAO := dao.NewAPITokenDAO()keys, err := APITokenDAO.GetByTenantID(ctx, dao.DB, tenantID)if err != nil {@@ -87,9 +92,11 @@ type CreateAPIKeyRequest struct {}// CreateAPIKey creates a new API key for a tenant-func (s *SystemService) CreateAPIKey(ctx context.Context, userID, tenantID string, req *CreateAPIKeyRequest) (*APIKeyResponse, error) {- if userID == "" || tenantID == "" {- return nil, fmt.Errorf("user and tenant context are required")+func (s *SystemService) CreateAPIKey(ctx context.Context, req *CreateAPIKeyRequest) (*APIKeyResponse, error) {+ userID := permission.UserIDFromContext(ctx)+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {+ return nil, err}APITokenDAO := dao.NewAPITokenDAO()@@ -134,9 +141,13 @@ func apiTokenUserID(value *string) string {return *value}-func (s *SystemService) DeleteAPIKey(ctx context.Context, tenantID, key string) error {+func (s *SystemService) DeleteAPIKey(ctx context.Context, key string) error {+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {+ return err+ }APITokenDAO := dao.NewAPITokenDAO()- _, err := APITokenDAO.DeleteByTenantIDAndToken(ctx, dao.DB, tenantID, key)+ _, err = APITokenDAO.DeleteByTenantIDAndToken(ctx, dao.DB, tenantID, key)if err == nil {if billingService := billing.Get(); billingService != nil && billingService.Enabled() {billingService.DeleteRateLimitKeys(ctx, key)diff --git a/internal/service/api_token_test.go b/internal/service/api_token_test.goindex e5aea72e97..8e2baecdf7 100644--- a/internal/service/api_token_test.go+++ b/internal/service/api_token_test.go@@ -21,17 +21,22 @@ import ("ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission")func TestCreateAPIKeyStoresUserAndTenantContext(t *testing.T) {- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "tenant-1")db := setupServiceTestDB(t)- if err := db.AutoMigrate(&entity.APIToken{}); err != nil {- t.Fatalf("failed to migrate api_token: %v", err)+ if err := db.AutoMigrate(&entity.APIToken{}, &entity.UserTenant{}); err != nil {+ t.Fatalf("failed to migrate api_token and user_tenant: %v", err)+ }+ status := entity.TenantMembershipStatusJoined+ if err := db.Create(&entity.UserTenant{ID: "membership-1", UserID: "user-1", TenantID: "tenant-1", Role: "owner", Status: &status}).Error; err != nil {+ t.Fatalf("failed to create Tenant membership: %v", err)}pushServiceDB(t, db)- key, err := (&SystemService{}).CreateAPIKey(ctx, "user-1", "tenant-1", &CreateAPIKeyRequest{})+ key, err := (&SystemService{}).CreateAPIKey(ctx, &CreateAPIKeyRequest{})if err != nil {t.Fatalf("CreateAPIKey() error = %v", err)}diff --git a/internal/service/bot_completion.go b/internal/service/bot_completion.goindex cca9c06a72..9d67d6f166 100644--- a/internal/service/bot_completion.go+++ b/internal/service/bot_completion.go@@ -428,7 +428,7 @@ func (s *BotService) ChatbotCompletion(if err := s.persistChatbotQuestion(ctx, session, req.Question, messageID, receivedAt); err != nil {return nil, common.CodeServerError, err}- results, err := s.pipeline.AsyncChat(ctx, userID, dialog, messages, true, kwargs)+ results, err := s.pipeline.AsyncChat(ctx, dialog, messages, true, kwargs)if err != nil {return nil, common.CodeServerError, err}diff --git a/internal/service/chat.go b/internal/service/chat.goindex 27c263c4f6..b89160f019 100644--- a/internal/service/chat.go+++ b/internal/service/chat.go@@ -22,6 +22,7 @@ import ("errors""fmt""math"+"ragflow/internal/agentic_rag""ragflow/internal/common""ragflow/internal/entity"@@ -198,7 +199,7 @@ type CreateChatRequest struct {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)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {code, normalized := permissionresponse.Normalize(err)return nil, code, normalized@@ -436,7 +437,7 @@ func (s *ChatService) validateCreateDatasetIDs(ctx context.Context, value interfreturn normalizedIDs, nil}-func validateChatDatasetAccess(ctx context.Context, userID string, kbIDs entity.JSONSlice) error {+func validateChatDatasetAccess(ctx context.Context, kbIDs entity.JSONSlice) error {for _, rawID := range kbIDs {datasetID, ok := rawID.(string)if !ok || strings.TrimSpace(datasetID) == "" {@@ -476,7 +477,7 @@ func resolveCreateLLMID(ctx context.Context, llmID, tenantID string, llmSetting}}modelFactory := NewModelFactory()- target, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: tenantID}, modelType, llmID)+ target, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, tenantID), modelType, llmID)if err != nil {return "", fmt.Errorf("`llm_id` %s doesn't exist", llmID)}@@ -492,7 +493,7 @@ func resolveCreateRerankID(ctx context.Context, rerankID, tenantID string) (strireturn "", nil}modelFactory := NewModelFactory()- target, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: tenantID}, entity.ModelTypeRerank, rerankID)+ target, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeRerank, rerankID)if err != nil {return "", fmt.Errorf("`rerank_id` %s doesn't exist", rerankID)}@@ -955,7 +956,7 @@ func (s *ChatService) updateChatREST(ctx context.Context, chatID string, req mapreq["tenant_decision_id"] = nil} else {modelFactory := NewModelFactory()- target, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: modelTenantID}, entity.ModelTypeDecision, decisionID)+ target, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, modelTenantID), entity.ModelTypeDecision, decisionID)if err != nil {return nil, fmt.Errorf("`decision_id` %s doesn't exist", decisionID)}@@ -1209,7 +1210,7 @@ func (s *ChatService) resolveRESTLLMID(ctx context.Context, llmID, tenantID stri}}modelFactory := NewModelFactory()- target, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: tenantID}, modelType, llmID)+ target, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, tenantID), modelType, llmID)if err != nil {return "", fmt.Errorf("`llm_id` %s doesn't exist", llmID)}@@ -1225,7 +1226,7 @@ func (s *ChatService) resolveRESTRerankID(ctx context.Context, rerankID, tenantIreturn "", nil}modelFactory := NewModelFactory()- target, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: tenantID}, entity.ModelTypeRerank, rerankID)+ target, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeRerank, rerankID)if err != nil {return "", fmt.Errorf("`rerank_id` %s doesn't exist", rerankID)}diff --git a/internal/service/chat_channel.go b/internal/service/chat_channel.goindex 1de83ca21a..27e51c30c8 100644--- a/internal/service/chat_channel.go+++ b/internal/service/chat_channel.go@@ -94,7 +94,7 @@ func (s *ChatChannelService) List(ctx context.Context) ([]*entity.ChatChannelLisfunc (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)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return nil, err}diff --git a/internal/service/chat_pipeline.go b/internal/service/chat_pipeline.goindex 98f9a1d6be..14969c4f50 100644--- a/internal/service/chat_pipeline.go+++ b/internal/service/chat_pipeline.go@@ -22,11 +22,13 @@ import ("encoding/json""fmt""net/http"+"ragflow/internal/agentic_rag""ragflow/internal/common""ragflow/internal/engine""ragflow/internal/entity"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission"ragprompts "ragflow/internal/rag/prompts""ragflow/internal/service/file""ragflow/internal/service/graph"@@ -221,7 +223,6 @@ type ThinkEvent struct {// - kwargs: extra parameters (doc_ids, knowledge, quote, etc.).func (s *ChatPipelineService) AsyncChat(ctx context.Context,- userID string,chat *entity.Chat,messages []map[string]interface{},stream bool,@@ -243,7 +244,7 @@ func (s *ChatPipelineService) AsyncChat(if role, _ := lastMsg["role"].(string); role != "user" {return nil, fmt.Errorf("the last content of this conversation is not from user")}- if err := validateChatDatasetAccess(ctx, userID, chat.KBIDs); err != nil {+ if err := validateChatDatasetAccess(ctx, chat.KBIDs); err != nil {return nil, err}@@ -292,12 +293,12 @@ func (s *ChatPipelineService) AsyncChat(if useWebSearch {ctx = agentic_rag.WithWebSearch(ctx, s.webSearchFunc(chat.PromptConfig))}- return s.agenticRag(ctx, userID, chat, messages, stream, kwargs, quoteEnabled(kwargs, chat.PromptConfig))+ return s.agenticRag(ctx, chat, messages, stream, kwargs, quoteEnabled(kwargs, chat.PromptConfig))}// No KBs & no web search → fast-path to LLM-only chat.if !hasKBs && !useWebSearch {- return s.AsyncChatSolo(ctx, userID, chat, messages, stream, kwargs)+ return s.AsyncChatSolo(ctx, chat, messages, stream, kwargs)}if kwargs == nil {kwargs = make(map[string]interface{})@@ -461,7 +462,7 @@ func (s *ChatPipelineService) AsyncChat(}}var images []string- textAttachmentsList, images = splitFileAttachments(ctx, userID, files, modelType == "image2text")+ textAttachmentsList, images = splitFileAttachments(ctx, files, modelType == "image2text")imageFiles, hasImageAttachments = gateImageAttachments(chat.LLMID, modelType, images)attachments = strings.Join(textAttachmentsList, "\n\n")// Log counts only: attachment payloads are base64 images or@@ -475,7 +476,7 @@ func (s *ChatPipelineService) AsyncChat(var historyImageFiles []stringfor _, previous := range messages[:len(messages)-1] {if previous["role"] == "user" && previous["files"] != nil {- _, images := s.splitChatAttachments(ctx, userID, previous["files"])+ _, images := s.splitChatAttachments(ctx, previous["files"])modelType, _ := llmModelConfig["model_type"].(string)images, _ = gateImageAttachments(chat.LLMID, modelType, images)historyImageFiles = append(historyImageFiles, images...)@@ -1013,7 +1014,7 @@ func (s *ChatPipelineService) AsyncChat(// Fit messages within token budget.usedTokenCount, llmMessages := s.messageFitIn(llmMessages, int(float64(modelMaxTokens)*0.95))for i := range llmMessages[:len(llmMessages)-1] {- llmMessages[i] = s.chatHistoryMessage(ctx, userID, llmMessages[i], modelType, factoryName)+ llmMessages[i] = s.chatHistoryMessage(ctx, llmMessages[i], modelType, factoryName)}common.Debug("Messages fitted in token budget",zap.Int("model max_tokens", modelMaxTokens),@@ -1475,7 +1476,6 @@ func (s *ChatPipelineService) deepResearchProgressCallback(ctx context.Context,// Equivalent to Python's async_chat_solo() in dialog_service.py:289-337.func (s *ChatPipelineService) AsyncChatSolo(ctx context.Context,- userID string,chat *entity.Chat,messages []map[string]interface{},stream bool,@@ -1537,7 +1537,7 @@ func (s *ChatPipelineService) AsyncChatSolo(if len(messages) > 0 {if files, hasFiles := messages[len(messages)-1]["files"]; hasFiles {var images []string- attachmentsStr, images = s.splitChatAttachments(ctx, userID, files)+ attachmentsStr, images = s.splitChatAttachments(ctx, files)imageFiles, _ = gateImageAttachments(chat.LLMID, modelType, images)common.Info("AsyncChatSolo: file attachments resolved",zap.Bool("vision_model", isImage2Text),@@ -1554,7 +1554,7 @@ func (s *ChatPipelineService) AsyncChatSolo(continue}if i < len(messages)-1 {- m = s.chatHistoryMessage(ctx, userID, m, modelType, factoryName)+ m = s.chatHistoryMessage(ctx, m, modelType, factoryName)}llmMessage := normalizeLLMMessage(m)content := llmMessage["content"]@@ -1572,12 +1572,12 @@ func (s *ChatPipelineService) AsyncChatSolo(}// 4. Construct the selected chat model through the factory.- access := Identity{UserID: userID, TenantID: chat.TenantID}+ modelCtx := permission.WithTenantID(ctx, chat.TenantID)var chatModel *modelModule.ChatModelif strings.TrimSpace(chat.LLMID) == "" {- chatModel, err = s.ModelFactory.NewDefaultChatModel(ctx, access)+ chatModel, err = s.ModelFactory.NewDefaultChatModel(modelCtx)} else {- chatModel, err = s.ModelFactory.NewChatModel(ctx, access, chat.LLMID)+ chatModel, err = s.ModelFactory.NewChatModel(modelCtx, chat.LLMID)}if err != nil {sendResult(AsyncChatResult{@@ -1591,7 +1591,7 @@ func (s *ChatPipelineService) AsyncChatSolo(var ttsModel *modelModule.TTSModelif promptConfig != nil {if useTTS, _ := promptConfig["tts"].(bool); useTTS {- ttsModel, err = s.ModelFactory.NewDefaultTTSModel(ctx, access)+ ttsModel, err = s.ModelFactory.NewDefaultTTSModel(modelCtx)if err != nil || ttsModel == nil {common.Warn("AsyncChatSolo: TTS lookup failed; proceeding without TTS",zap.String("tenant_id", chat.TenantID),@@ -1829,13 +1829,13 @@ func (s *ChatPipelineService) AsyncChatSolo(//// Downstream ConvertLastUserMsgToMultimodal → parseDataURIOrB64 accepts the// returned data URIs directly.-func (s *ChatPipelineService) splitChatAttachments(ctx context.Context, userID string, files interface{}) (string, []string) {+func (s *ChatPipelineService) splitChatAttachments(ctx context.Context, files interface{}) (string, []string) {// ── File-dict mode ──if fileDicts, ok := parseFileDicts(files); ok {// Only used for GetFileContents (read-only); nil DocRemover means// this FileService MUST NOT be used for DeleteFiles.fileSvc := file.NewFileService(nil)- texts, images, err := fileSvc.GetFileContents(ctx, userID, fileDicts)+ texts, images, err := fileSvc.GetFileContents(ctx, fileDicts)if err != nil {common.Warn("GetFileContents failed in splitChatAttachments",zap.Error(err))@@ -2071,13 +2071,13 @@ func tokenizeText(text string) string {// models reject them at the provider (e.g. Zhipu GLM error 1210:// messages.content.type only allows 'text').func (s *ChatPipelineService) getLLMModelConfig(ctx context.Context, chat *entity.Chat) (map[string]interface{}, string, string, string, error) {- access := Identity{TenantID: chat.TenantID}+ ctx = permission.WithTenantID(ctx, chat.TenantID)var info *modelModule.ModelInfovar err errorif strings.TrimSpace(chat.LLMID) == "" {- info, err = s.ModelFactory.ResolveDefaultInfo(ctx, access, entity.ModelTypeChat)+ info, err = s.ModelFactory.ResolveDefaultInfo(ctx, entity.ModelTypeChat)} else {- info, err = s.ModelFactory.ResolveInfo(ctx, access, entity.ModelTypeChat, chat.LLMID)+ info, err = s.ModelFactory.ResolveInfo(ctx, entity.ModelTypeChat, chat.LLMID)}if err != nil {return nil, "", "", "", err@@ -2153,7 +2153,7 @@ func (s *ChatPipelineService) getModels(ctx context.Context, chat *entity.Chat)}if kbs[0].EmbdID != "" {embdTenantID := kbs[0].TenantID- model, err := s.ModelFactory.NewEmbeddingModel(ctx, Identity{TenantID: embdTenantID}, kbs[0].EmbdID)+ model, err := s.ModelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, embdTenantID), kbs[0].EmbdID)if err != nil {common.Warn("Failed to get embedding model for chat retrieval",zap.String("embdID", kbs[0].EmbdID),@@ -2166,25 +2166,25 @@ func (s *ChatPipelineService) getModels(ctx context.Context, chat *entity.Chat)}// Chat model.- access := Identity{TenantID: chat.TenantID}+ modelCtx := permission.WithTenantID(ctx, chat.TenantID)var chatModel *modelModule.ChatModelif strings.TrimSpace(chat.LLMID) == "" {- chatModel, _ = s.ModelFactory.NewDefaultChatModel(ctx, access)+ chatModel, _ = s.ModelFactory.NewDefaultChatModel(modelCtx)} else {- chatModel, _ = s.ModelFactory.NewChatModel(ctx, access, chat.LLMID)+ chatModel, _ = s.ModelFactory.NewChatModel(modelCtx, chat.LLMID)}// Rerank model.var rerankModel *modelModule.RerankModelif chat.RerankID != "" {- rerankModel, _ = s.ModelFactory.NewRerankModel(ctx, access, chat.RerankID)+ rerankModel, _ = s.ModelFactory.NewRerankModel(modelCtx, chat.RerankID)}// TTS model.var ttsModel *modelModule.TTSModelif chat.PromptConfig != nil {if useTTS, _ := chat.PromptConfig["tts"].(bool); useTTS {- ttsModel, _ = s.ModelFactory.NewDefaultTTSModel(ctx, access)+ ttsModel, _ = s.ModelFactory.NewDefaultTTSModel(modelCtx)}}@@ -2276,13 +2276,13 @@ func emptyResponseApplies(knowledgeCount int, attachments string, imageAttachmen// URIs → image files.// - raw=true: all items go to textAttachments (Python's FileService.get_files// with raw=True pre-separates images, so non-image content arrives here).-func splitFileAttachments(ctx context.Context, userID string, files interface{}, raw bool) (textAttachments []string, imageAttachments []string) {+func splitFileAttachments(ctx context.Context, files interface{}, raw bool) (textAttachments []string, imageAttachments []string) {// ── Mode 1: file dicts (Python-compatible) ──if fileDicts, ok := parseFileDicts(files); ok {// Only used for GetFileContents (read-only); nil DocRemover means// this FileService MUST NOT be used for DeleteFiles.fileSvc := file.NewFileService(nil)- texts, images, err := fileSvc.GetFileContents(ctx, userID, fileDicts)+ texts, images, err := fileSvc.GetFileContents(ctx, fileDicts)if err != nil {common.Warn("GetFileContents failed, falling back to string splitting",zap.Error(err))@@ -2744,11 +2744,11 @@ func (s *ChatPipelineService) buildChatMessages(systemContent string, messages [return result}-func (s *ChatPipelineService) chatHistoryMessage(ctx context.Context, userID string, message map[string]interface{}, modelType, factory string) map[string]interface{} {+func (s *ChatPipelineService) chatHistoryMessage(ctx context.Context, message map[string]interface{}, modelType, factory string) map[string]interface{} {if message["role"] != "user" || message["files"] == nil {return message}- _, images := s.splitChatAttachments(ctx, userID, message["files"])+ _, images := s.splitChatAttachments(ctx, message["files"])images, _ = gateImageAttachments("", modelType, images)msg := normalizeLLMMessage(message)converted, err := common.ConvertLastUserMsgToMultimodal(msg, images, factory)@@ -2790,15 +2790,15 @@ func (s *ChatPipelineService) buildChatDriver(ctx context.Context, chat *entity.if chatModel != nil {return chatModel}- access := Identity{TenantID: chat.TenantID}+ modelCtx := permission.WithTenantID(ctx, chat.TenantID)if strings.TrimSpace(chat.LLMID) == "" {- model, err := s.ModelFactory.NewDefaultChatModel(ctx, access)+ model, err := s.ModelFactory.NewDefaultChatModel(modelCtx)if err != nil {return nil}return model}- model, err := s.ModelFactory.NewChatModel(ctx, access, chat.LLMID)+ model, err := s.ModelFactory.NewChatModel(modelCtx, chat.LLMID)if err != nil {return nil}diff --git a/internal/service/chat_pipeline_image_test.go b/internal/service/chat_pipeline_image_test.goindex 5038d2a2f5..06768597ee 100644--- a/internal/service/chat_pipeline_image_test.go+++ b/internal/service/chat_pipeline_image_test.go@@ -23,6 +23,7 @@ import ("testing""ragflow/internal/common"+ "ragflow/internal/permission""ragflow/internal/storage")@@ -55,7 +56,7 @@ func TestSplitChatAttachments_FileDictModeReturnsDataURIs(t *testing.T) {seedChatImageStorage(t)svc := NewChatPipelineService()- texts, images := svc.splitChatAttachments(t.Context(), "user-1", []interface{}{chatImageFileDict})+ texts, images := svc.splitChatAttachments(permission.WithIdentity(t.Context(), "user-1", ""), []interface{}{chatImageFileDict})if len(images) != 1 {t.Fatalf("expected 1 image, got %v", images)}@@ -72,7 +73,7 @@ func TestSplitChatAttachments_FileDictModeReturnsDataURIs(t *testing.T) {// other non-empty entry stays in the text attachments.func TestSplitChatAttachments_StringModeKeepsDataURIsOnly(t *testing.T) {svc := NewChatPipelineService()- texts, images := svc.splitChatAttachments(t.Context(), "user-1", []interface{}{+ texts, images := svc.splitChatAttachments(permission.WithIdentity(t.Context(), "user-1", ""), []interface{}{"data:image/png;base64,AAA", "https://example.com/a.png", "plain text", " ",})if len(images) != 1 || images[0] != "data:image/png;base64,AAA" {@@ -112,7 +113,7 @@ func TestSplitChatAttachments_FetchesStorageOnce(t *testing.T) {t.Cleanup(func() { factory.SetStorage(original) })svc := NewChatPipelineService()- texts, images := svc.splitChatAttachments(t.Context(), "user-1", []interface{}{+ texts, images := svc.splitChatAttachments(permission.WithIdentity(t.Context(), "user-1", ""), []interface{}{chatImageFileDict,map[string]interface{}{"id": "img-2", "name": "photo2.jpeg", "mime_type": "image/jpeg", "created_by": "user-1"},})@@ -134,7 +135,7 @@ func TestSplitChatAttachments_FetchesStorageOnce(t *testing.T) {func TestSplitFileAttachmentsRawImagesFeedMultimodalConversion(t *testing.T) {seedChatImageStorage(t)- _, images := splitFileAttachments(t.Context(), "user-1", []interface{}{chatImageFileDict}, true)+ _, images := splitFileAttachments(permission.WithIdentity(t.Context(), "user-1", ""), []interface{}{chatImageFileDict}, true)if len(images) != 1 {t.Fatalf("expected 1 image from splitFileAttachments, got %v", images)}@@ -178,7 +179,7 @@ func TestSplitFileAttachmentsRawImagesFeedMultimodalConversion(t *testing.T) {func TestGateImageAttachmentsDropsImagesForTextOnlyChatModel(t *testing.T) {seedChatImageStorage(t)- texts, images := splitFileAttachments(t.Context(), "user-1", []interface{}{chatImageFileDict}, false)+ texts, images := splitFileAttachments(permission.WithIdentity(t.Context(), "user-1", ""), []interface{}{chatImageFileDict}, false)if len(images) != 1 {t.Fatalf("split still resolves file-dict images with raw=false, got %v", images)}@@ -201,7 +202,7 @@ func TestGateImageAttachmentsKeepsImagesForVisionModel(t *testing.T) {seedChatImageStorage(t)for _, raw := range []bool{false, true} {- texts, images := splitFileAttachments(t.Context(), "user-1", []interface{}{chatImageFileDict}, raw)+ texts, images := splitFileAttachments(permission.WithIdentity(t.Context(), "user-1", ""), []interface{}{chatImageFileDict}, raw)kept, attached := gateImageAttachments("qwen3-vl-plus@Tongyi-Qianwen", "image2text", images)if !attached || len(kept) != 1 {t.Fatalf("raw=%v: vision model must keep the image (kept=%v attached=%v)", raw, kept, attached)diff --git a/internal/service/chat_pipeline_test.go b/internal/service/chat_pipeline_test.goindex c38e4b4340..bda6a93ace 100644--- a/internal/service/chat_pipeline_test.go+++ b/internal/service/chat_pipeline_test.go@@ -34,6 +34,7 @@ import ("ragflow/internal/engine""ragflow/internal/entity"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission")// dialForTest builds a minimal *entity.Chat suitable for the@@ -88,7 +89,7 @@ func TestAsyncChat_RejectsNonUserLastMessage(t *testing.T) {{"role": "user", "content": "first"},{"role": "assistant", "content": "last message must not be assistant"},}- _, err := s.AsyncChat(t.Context(), "user-1", dialForTest(""), messages, false, nil)+ _, err := s.AsyncChat(t.Context(), dialForTest(""), messages, false, nil)if err == nil {t.Fatal("expected error for non-user last message, got nil")}@@ -101,7 +102,7 @@ func TestAsyncChat_RejectsNonUserLastMessage(t *testing.T) {// service should return an error before spawning the goroutine.func TestAsyncChat_EmptyMessages(t *testing.T) {s := &ChatPipelineService{}- _, err := s.AsyncChat(t.Context(), "user-1", dialForTest(""), nil, false, nil)+ _, err := s.AsyncChat(t.Context(), dialForTest(""), nil, false, nil)if err == nil {t.Fatal("expected error for empty messages, got nil")}@@ -110,7 +111,7 @@ func TestAsyncChat_EmptyMessages(t *testing.T) {func TestAsyncChatRejectsNonStringUserContent(t *testing.T) {s := &ChatPipelineService{}messages := []map[string]interface{}{{"role": "user", "content": map[string]interface{}{"text": "question"}}}- _, err := s.AsyncChat(t.Context(), "user-1", dialForTest(""), messages, false, nil)+ _, err := s.AsyncChat(t.Context(), dialForTest(""), messages, false, nil)if err == nil || !strings.Contains(err.Error(), "messages[0].content is invalid") {t.Fatalf("AsyncChat error = %v, want indexed invalid user content error", err)}@@ -143,7 +144,6 @@ func TestAsyncChatRejectsUnauthorizedDatasetsBeforeStartingPipeline(t *testing.Tchat.KBIDs = []interface{}{"kb-private"}results, err := (&ChatPipelineService{}).AsyncChat(serviceTestContext(t, "user-1", "user-1"),- "user-1",chat,[]map[string]interface{}{{"role": "user", "content": "show me the private dataset"}},false,@@ -1748,7 +1748,7 @@ func TestAsyncChatEmptyResponseQuoteDisabled(t *testing.T) {chat.PromptConfig["system"] = "Answer using {knowledge}"chat.PromptConfig["empty_response"] = "Nothing found."ctx := serviceTestContext(t, "user-1", "tenant-1")- results, err := NewChatPipelineService().AsyncChat(ctx, "user-1", chat,+ results, err := NewChatPipelineService().AsyncChat(ctx, chat,[]map[string]interface{}{{"role": "user", "content": "Question"}}, true,map[string]interface{}{"quote": false})if err != nil {@@ -1941,7 +1941,7 @@ func TestResolveModelConfigRejectsImage2TextOnlyModel(t *testing.T) {svc := NewChatPipelineService()_, err := svc.ModelFactory.resolveConfig(- t.Context(), Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, "model-image2text-tools",+ permission.WithTenantID(t.Context(), "tenant-1"), entity.ModelTypeChat, "model-image2text-tools",)if err == nil {t.Fatal("ResolveModelConfig accepted an image2text-only model as chat")@@ -2261,7 +2261,7 @@ func TestAsyncChat_ContextCancellationTerminatesGoroutine(t *testing.T) {cancel() // pre-cancel context to simulate client disconnectchat := dialForTest("glm-4-flash@ZHIPU-AI")- results, err := NewChatPipelineService().AsyncChat(ctx, "user-1", chat,+ results, err := NewChatPipelineService().AsyncChat(ctx, chat,[]map[string]interface{}{{"role": "user", "content": "Question"}}, true, nil)if err != nil {t.Fatal(err)diff --git a/internal/service/chat_session.go b/internal/service/chat_session.goindex c40f111fd8..ab90a3c0c3 100644--- a/internal/service/chat_session.go+++ b/internal/service/chat_session.go@@ -23,8 +23,10 @@ import ("errors""fmt""math"+"ragflow/internal/common""ragflow/internal/engine"+ "ragflow/internal/permission""ragflow/internal/storage""regexp""strconv"@@ -37,7 +39,6 @@ import ("ragflow/internal/dao""ragflow/internal/entity"modelModule "ragflow/internal/entity/models"- "ragflow/internal/permission"permissionresponse "ragflow/internal/permission/response""ragflow/internal/utility")@@ -60,13 +61,13 @@ type chatSessionPermissionChecker interface {}type chatPipelineRunner interface {- AsyncChat(ctx context.Context, userID string, chat *entity.Chat, messages []map[string]interface{}, stream bool, kwargs map[string]interface{}) (<-chan AsyncChatResult, error)+ AsyncChat(ctx context.Context, chat *entity.Chat, messages []map[string]interface{}, stream bool, kwargs map[string]interface{}) (<-chan AsyncChatResult, error)}type chatModelInfoResolver interface {- ResolveInfo(ctx context.Context, access Identity, modelType entity.ModelType, modelRef string) (*modelModule.ModelInfo, error)- ResolveDefaultInfo(ctx context.Context, access Identity, modelType entity.ModelType) (*modelModule.ModelInfo, error)- ResolveModelType(ctx context.Context, access Identity, modelRef string) ([]entity.ModelType, error)+ ResolveInfo(ctx context.Context, modelType entity.ModelType, modelRef string) (*modelModule.ModelInfo, error)+ ResolveDefaultInfo(ctx context.Context, modelType entity.ModelType) (*modelModule.ModelInfo, error)+ ResolveModelType(ctx context.Context, modelRef string) ([]entity.ModelType, error)}// chunkFeedbackApplier is the dispatch seam for chunk-level feedback@@ -1244,7 +1245,7 @@ func (s *ChatSessionService) ChatCompletions(dialog.LLMID = llmIDdialog.LLMSetting = genConfig} else if dialog.LLMID == "" {- modelInfo, err := NewModelFactory().ResolveDefaultInfo(ctx, Identity{UserID: userID, TenantID: dialog.TenantID}, entity.ModelTypeChat)+ modelInfo, err := NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, dialog.TenantID), entity.ModelTypeChat)if err != nil {return fail(errors.New("no default chat model for tenant"))}@@ -1280,7 +1281,7 @@ func (s *ChatSessionService) ChatCompletions(return fail(err)}}- resultChan, err := s.pipeline.AsyncChat(ctx, userID, dialog, requestMsg, stream, kwargs)+ resultChan, err := s.pipeline.AsyncChat(ctx, dialog, requestMsg, stream, kwargs)if err != nil {return fail(err)}@@ -1846,13 +1847,13 @@ func (s *ChatSessionService) checkTenantLLMAPIKey(ctx context.Context, tenantID,if modelFactory == nil {modelFactory = NewModelFactory()}+ ctx = permission.WithTenantID(ctx, tenantID)var err error- access := Identity{TenantID: tenantID}if modelName == "" {- _, err = modelFactory.ResolveDefaultInfo(ctx, access, entity.ModelTypeChat)+ _, err = modelFactory.ResolveDefaultInfo(ctx, entity.ModelTypeChat)} else {modelType := entity.ModelTypeChat- if modelTypes, typeErr := modelFactory.ResolveModelType(ctx, access, modelName); typeErr == nil {+ if modelTypes, typeErr := modelFactory.ResolveModelType(ctx, modelName); typeErr == nil {for _, resolvedType := range modelTypes {if resolvedType.Has(entity.ModelTypeImage2Text) {modelType = entity.ModelTypeImage2Text@@ -1860,7 +1861,7 @@ func (s *ChatSessionService) checkTenantLLMAPIKey(ctx context.Context, tenantID,}}}- _, err = modelFactory.ResolveInfo(ctx, access, modelType, modelName)+ _, err = modelFactory.ResolveInfo(ctx, modelType, modelName)}if err != nil {return false, errdiff --git a/internal/service/chat_session_test.go b/internal/service/chat_session_test.goindex 58e7099fc1..fbc75e63cb 100644--- a/internal/service/chat_session_test.go+++ b/internal/service/chat_session_test.go@@ -315,8 +315,8 @@ type fakePipeline struct {messages []map[string]interface{}}-func (f *fakePipeline) AsyncChat(ctx context.Context, userID string, chat *entity.Chat, messages []map[string]interface{}, stream bool, kwargs map[string]interface{}) (<-chan AsyncChatResult, error) {- f.userID = userID+func (f *fakePipeline) AsyncChat(ctx context.Context, chat *entity.Chat, messages []map[string]interface{}, stream bool, kwargs map[string]interface{}) (<-chan AsyncChatResult, error) {+ f.userID = permission.UserIDFromContext(ctx)f.messages = messagesreturn f.resultChan, f.err}@@ -455,8 +455,8 @@ type fakeChatModelConfigResolver struct {err error}-func (f *fakeChatModelConfigResolver) ResolveInfo(_ context.Context, access Identity, _ entity.ModelType, modelRef string) (*modelModule.ModelInfo, error) {- f.tenantID = access.TenantID+func (f *fakeChatModelConfigResolver) ResolveInfo(ctx context.Context, _ entity.ModelType, modelRef string) (*modelModule.ModelInfo, error) {+ f.tenantID = permission.TenantIDFromContext(ctx)f.llmID = modelRefif f.err != nil {return nil, f.err@@ -464,15 +464,15 @@ func (f *fakeChatModelConfigResolver) ResolveInfo(_ context.Context, access Idenreturn &modelModule.ModelInfo{ID: "resolved-model-id", Name: "resolved-model"}, nil}-func (f *fakeChatModelConfigResolver) ResolveDefaultInfo(_ context.Context, access Identity, _ entity.ModelType) (*modelModule.ModelInfo, error) {- f.tenantID = access.TenantID+func (f *fakeChatModelConfigResolver) ResolveDefaultInfo(ctx context.Context, _ entity.ModelType) (*modelModule.ModelInfo, error) {+ f.tenantID = permission.TenantIDFromContext(ctx)if f.err != nil {return nil, f.err}return &modelModule.ModelInfo{ID: "resolved-model-id", Name: "resolved-model"}, nil}-func (f *fakeChatModelConfigResolver) ResolveModelType(ctx context.Context, access Identity, modelRef string) ([]entity.ModelType, error) {+func (f *fakeChatModelConfigResolver) ResolveModelType(_ context.Context, modelRef string) ([]entity.ModelType, error) {return []entity.ModelType{entity.ModelTypeChat}, nil}diff --git a/internal/service/chunk/chunk.go b/internal/service/chunk/chunk.goindex 66cdffb63a..861fe2ab99 100644--- a/internal/service/chunk/chunk.go+++ b/internal/service/chunk/chunk.go@@ -27,6 +27,7 @@ import ("image/draw""image/jpeg""math"+"ragflow/internal/common""ragflow/internal/entity""ragflow/internal/entity/models"@@ -260,9 +261,9 @@ func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.Retrievalif filter != nil {method, _ := filter["method"].(string)if method == "auto" || method == "semi_auto" {- access := service.Identity{TenantID: tenantIDs[0]}+ modelCtx := permission.WithTenantID(ctx, tenantIDs[0])if chatID != "" {- chatModelForFilter, getErr = modelFactory.NewChatModel(ctx, access, chatID)+ chatModelForFilter, getErr = modelFactory.NewChatModel(modelCtx, chatID)if getErr != nil {common.Warn("Failed to get chat model from search_config chat_id, using tenant default", zap.String("chatID", chatID), zap.Error(getErr))} else {@@ -273,7 +274,7 @@ func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.Retrieval}if chatModelForFilter == nil {- chatModelForFilter, getErr = modelFactory.NewDefaultChatModel(ctx, access)+ chatModelForFilter, getErr = modelFactory.NewDefaultChatModel(modelCtx)if getErr != nil {common.Warn("Failed to get tenant default chat model for meta_data_filter", zap.Error(getErr))}@@ -309,7 +310,7 @@ func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.Retrievalvar llmModelName stringif len(req.CrossLanguages) > 0 || (req.Keyword != nil && *req.Keyword) {var err error- chatModel, err = modelFactory.NewDefaultChatModel(ctx, service.Identity{TenantID: tenantIDs[0]})+ chatModel, err = modelFactory.NewDefaultChatModel(permission.WithTenantID(ctx, tenantIDs[0]))if err != nil {common.Warn("Failed to get default chat model name for LLM transformations", zap.Error(err))} else {@@ -356,22 +357,22 @@ func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.Retrievallabels := metadataSvc.LabelQuestion(ctx, modifiedQuestion, kbRecords)// Determine embedding model.- access := service.Identity{TenantID: tenantIDs[0]}+ modelCtx := permission.WithTenantID(ctx, tenantIDs[0])var embeddingModel *models.EmbeddingModelvar embdID stringif kbRecords[0].TenantEmbdID != nil && *kbRecords[0].TenantEmbdID != "" {- embeddingModel, getErr = modelFactory.NewEmbeddingModel(ctx, access, *kbRecords[0].TenantEmbdID)+ embeddingModel, getErr = modelFactory.NewEmbeddingModel(modelCtx, *kbRecords[0].TenantEmbdID)if getErr != nil {return nil, fmt.Errorf("failed to get embedding model by tenant_embd_id: %w", getErr)}} else if kbRecords[0].EmbdID != "" {embdID = kbRecords[0].EmbdID- embeddingModel, getErr = modelFactory.NewEmbeddingModel(ctx, access, embdID)+ embeddingModel, getErr = modelFactory.NewEmbeddingModel(modelCtx, embdID)if getErr != nil {return nil, fmt.Errorf("failed to get embedding model by embd_id: %w", getErr)}} else {- embeddingModel, getErr = modelFactory.NewDefaultEmbeddingModel(ctx, access)+ embeddingModel, getErr = modelFactory.NewDefaultEmbeddingModel(modelCtx)if getErr != nil {return nil, fmt.Errorf("failed to get tenant default embedding model: %w", getErr)}@@ -391,12 +392,12 @@ func (s *ChunkService) RetrievalTest(ctx context.Context, req *service.Retrieval// Get rerank model if RerankID is specifiedvar rerankModel *models.RerankModelif tenantRerankID != nil && *tenantRerankID != "" {- rerankModel, getErr = modelFactory.NewRerankModel(ctx, access, *tenantRerankID)+ rerankModel, getErr = modelFactory.NewRerankModel(modelCtx, *tenantRerankID)if getErr != nil {return nil, fmt.Errorf("failed to get rerank model by tenant_rerank_id: %w", getErr)}} else if rerankID != nil && *rerankID != "" {- rerankModel, getErr = modelFactory.NewRerankModel(ctx, access, *rerankID)+ rerankModel, getErr = modelFactory.NewRerankModel(modelCtx, *rerankID)if getErr != nil {return nil, fmt.Errorf("failed to get rerank model by rerank_id: %w", getErr)}@@ -1741,7 +1742,7 @@ func (s *ChunkService) getEmbeddingModel(ctx context.Context, tenantID, embdID sif s.getEmbeddingModelFunc != nil {return s.getEmbeddingModelFunc(tenantID, embdID)}- embeddingModel, err := service.NewModelFactory().NewEmbeddingModel(ctx, service.Identity{TenantID: tenantID}, embdID)+ embeddingModel, err := service.NewModelFactory().NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), embdID)if err != nil {return nil, err}diff --git a/internal/service/compilation_template_group_service.go b/internal/service/compilation_template_group_service.goindex 235271da5f..1e71e02361 100644--- a/internal/service/compilation_template_group_service.go+++ b/internal/service/compilation_template_group_service.go@@ -311,7 +311,7 @@ func (s *CompilationTemplateGroupService) buildGroupItem(ctx context.Context, teName: c.Name,Description: derefString(c.Description),Kind: c.Kind,- Config: fillConfigDefaultLLM(ctx, c.Config, identityForTemplateTenant(ctx, tenantID)),+ Config: fillConfigDefaultLLM(ctx, c.Config, tenantID),CreateTime: timeStr(c.CreateTime),UpdateTime: timeStr(c.UpdateTime),})@@ -434,14 +434,18 @@ func (s *CompilationTemplateGroupService) insertChildren(ctx context.Context, db}}desc := child.Description- config := fillConfigDefaultLLM(ctx, child.Config, identityForTemplateTenant(ctx, tenantID))+ config := fillConfigDefaultLLM(ctx, child.Config, tenantID)if config == nil {config = entity.JSONMap{}}valid := string(entity.StatusValid)+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ userID = tenantID+ }tmpl := &entity.CompilationTemplate{ID: common.GenerateUUID(),- UserID: identityForTemplateTenant(ctx, tenantID).UserID,+ UserID: userID,TenantID: &tenantID,GroupID: &groupID,Name: name,@@ -539,7 +543,7 @@ func (s *CompilationTemplateGroupService) reconcileChildren(ctx context.Context,// Pass 3: apply updates and inserts.for _, item := range resolved {- config := fillConfigDefaultLLM(ctx, item.child.Config, identityForTemplateTenant(ctx, tenantID))+ config := fillConfigDefaultLLM(ctx, item.child.Config, tenantID)if config == nil {config = entity.JSONMap{}}@@ -564,9 +568,13 @@ func (s *CompilationTemplateGroupService) reconcileChildren(ctx context.Context,}newID := common.GenerateUUID()valid := string(entity.StatusValid)+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {+ userID = tenantID+ }tmpl := &entity.CompilationTemplate{ID: newID,- UserID: identityForTemplateTenant(ctx, tenantID).UserID,+ UserID: userID,TenantID: &tenantID,GroupID: &groupID,Name: newName,@@ -593,14 +601,6 @@ func (s *CompilationTemplateGroupService) reconcileChildren(ctx context.Context,return s.assertUniqueChildNames(ctx, db, groupID, oldNames)}-func identityForTemplateTenant(ctx context.Context, tenantID string) Identity {- access := Identity{UserID: tenantID, TenantID: tenantID}- if userID := strings.TrimSpace(permission.UserIDFromContext(ctx)); userID != "" {- access.UserID = userID- }- return access-}-// assertUniqueChildNames rejects a group whose valid children collide on a// case-insensitive name, matching the DAO's duplicate guard which ignores// built-in templates. oldNames maps each child id to its name before thediff --git a/internal/service/compilation_template_service.go b/internal/service/compilation_template_service.goindex fefc86468d..45b0dfce66 100644--- a/internal/service/compilation_template_service.go+++ b/internal/service/compilation_template_service.go@@ -29,6 +29,7 @@ import ("ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission""ragflow/internal/utility""gopkg.in/yaml.v3"@@ -38,14 +39,14 @@ import (// fill_config_default_llm: when the config has no explicit llm_id it lazily// fills the current member's default chat model id (read-side only; the DB row is left// untouched).-func fillConfigDefaultLLM(ctx context.Context, config entity.JSONMap, access Identity) entity.JSONMap {- if len(config) == 0 || access.TenantID == "" {+func fillConfigDefaultLLM(ctx context.Context, config entity.JSONMap, tenantID string) entity.JSONMap {+ if len(config) == 0 || tenantID == "" {return config}if _, ok := config["llm_id"]; ok {return config}- info, err := NewModelFactory().ResolveDefaultInfo(ctx, access, entity.ModelTypeChat)+ info, err := NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeChat)if err != nil {return config}@@ -119,7 +120,7 @@ func NewCompilationTemplateService() *CompilationTemplateService {// ListBuiltins returns the read-only template palette loaded from the YAML// definitions. Built-in templates are never persisted in the database.func (s *CompilationTemplateService) ListBuiltins(ctx context.Context) ([]*BuiltinTemplate, error) {- access, err := ResolveIdentity(ctx)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return nil, err}@@ -128,7 +129,7 @@ func (s *CompilationTemplateService) ListBuiltins(ctx context.Context) ([]*Builtreturn nil, err}for _, template := range templates {- template.Config = fillConfigDefaultLLM(ctx, template.Config, access)+ template.Config = fillConfigDefaultLLM(ctx, template.Config, tenantID)}return s.sortBuiltins(templates), nil}diff --git a/internal/service/connector.go b/internal/service/connector.goindex 1799b454dd..15ed71ecc4 100644--- a/internal/service/connector.go+++ b/internal/service/connector.go@@ -282,7 +282,7 @@ func (s *ConnectorService) CreateConnector(ctx context.Context, req *CreateConneif userID == "" {return nil, permission.ErrUnauthenticated}- tenantID, err := requireCurrentTenantID(ctx, userID)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return nil, err}@@ -367,7 +367,7 @@ func (s *ConnectorService) ListConnectors(ctx context.Context, requestedTenantIDtenantID := strings.TrimSpace(requestedTenantID)if tenantID == "" {var err error- tenantID, err = requireCurrentTenantID(ctx, userID)+ tenantID, err = requireCurrentTenantID(ctx)if errors.Is(err, permission.ErrMembershipNotFound) {return &ListConnectorsResponse{Connectors: []*dao.ConnectorListItem{}}, nil}diff --git a/internal/service/dataset/crud.go b/internal/service/dataset/crud.goindex eafdf23d3b..08f25b920d 100644--- a/internal/service/dataset/crud.go+++ b/internal/service/dataset/crud.go@@ -233,10 +233,10 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateDvar parserConfigMap map[string]interface{} = parserConfigmodelFactory := service.NewModelFactory()- identity := service.Identity{UserID: userID, TenantID: tenantID}+ modelCtx := permission.WithTenantID(ctx, tenantID)embdID, tenantEmbdID := "", ""if embeddingModel == "" {- embeddingInfo, embeddingErr := modelFactory.ResolveDefaultInfo(ctx, identity, entity.ModelTypeEmbedding)+ embeddingInfo, embeddingErr := modelFactory.ResolveDefaultInfo(modelCtx, entity.ModelTypeEmbedding)if embeddingErr == nil {embdID = service.ModelReference(embeddingInfo)tenantEmbdID = embeddingInfo.ID@@ -245,7 +245,7 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateD}}if embeddingModel != "" {- ok, message := d.verifyEmbeddingAvailability(ctx, embeddingModel, identity)+ ok, message := d.verifyEmbeddingAvailability(ctx, embeddingModel, tenantID)if !ok {return nil, common.CodeDataError, errors.New(message)}@@ -253,7 +253,7 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateDtenantEmbdID = ""}if embdID != "" && tenantEmbdID == "" {- target, err := modelFactory.ResolveInfo(ctx, identity, entity.ModelTypeEmbedding, embdID)+ target, err := modelFactory.ResolveInfo(modelCtx, entity.ModelTypeEmbedding, embdID)if err == nil {tenantEmbdID = target.ID} else {@@ -271,7 +271,7 @@ func (d *DatasetService) CreateDataset(ctx context.Context, req *service.CreateDname = dedupedNamellmID := ""- chatInfo, chatErr := modelFactory.ResolveDefaultInfo(ctx, identity, entity.ModelTypeChat)+ chatInfo, chatErr := modelFactory.ResolveDefaultInfo(modelCtx, entity.ModelTypeChat)if chatErr == nil {llmID = service.ModelReference(chatInfo)} else if !errors.Is(chatErr, service.ErrNoDefaultModel) {diff --git a/internal/service/dataset/embedding.go b/internal/service/dataset/embedding.goindex ca75c0c163..01a868de1c 100644--- a/internal/service/dataset/embedding.go+++ b/internal/service/dataset/embedding.go@@ -62,7 +62,7 @@ func (d *DatasetService) CheckEmbedding(ctx context.Context, datasetID string, rreturn nil, common.CodeServerError, errors.New("doc engine not initialized")}- embeddingModel, err := service.NewModelFactory().NewEmbeddingModel(ctx, service.Identity{TenantID: kb.TenantID}, embeddingID)+ embeddingModel, err := service.NewModelFactory().NewEmbeddingModel(permission.WithTenantID(ctx, kb.TenantID), embeddingID)if err != nil {return nil, common.CodeDataError, err}@@ -281,8 +281,8 @@ func (d *DatasetService) sampleRandomChunksWithVectors(ctx context.Context, tenareturn samples, nil}-func (d *DatasetService) verifyEmbeddingAvailability(ctx context.Context, embdID string, access service.Identity) (bool, string) {- _, err := service.NewModelFactory().ResolveInfo(ctx, access, entity.ModelTypeEmbedding, embdID)+func (d *DatasetService) verifyEmbeddingAvailability(ctx context.Context, embdID, tenantID string) (bool, string) {+ _, err := service.NewModelFactory().ResolveInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeEmbedding, embdID)if err != nil {return false, err.Error()}diff --git a/internal/service/dataset/metadata.go b/internal/service/dataset/metadata.goindex 6f10ba9bf8..33e5e98ace 100644--- a/internal/service/dataset/metadata.go+++ b/internal/service/dataset/metadata.go@@ -16,7 +16,6 @@ import (// UpdateDocumentMetadataConfig updates the metadata config for a document in a dataset.func (d *DatasetService) UpdateDocumentMetadataConfig(ctx context.Context, datasetID, documentID string, req map[string]interface{}) (*entity.Document, common.ErrorCode, error) {- userID := strings.TrimSpace(permission.UserIDFromContext(ctx))datasetID = strings.TrimSpace(datasetID)if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindDataset, ID: datasetID}, permission.OperationUpdate); err != nil {code, permissionErr := permissionresponse.Normalize(err)@@ -52,7 +51,7 @@ func (d *DatasetService) UpdateDocumentMetadataConfig(ctx context.Context, datasreturn nil, common.CodeServerError, errors.New("database operation failed")}llmID := ""- if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(ctx, service.Identity{UserID: userID, TenantID: kb.TenantID}, entity.ModelTypeChat); modelErr == nil {+ if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, kb.TenantID), entity.ModelTypeChat); modelErr == nil {llmID = service.ModelReference(modelInfo)}parserConfig = service.ApplyComponentScopedParserConfig(parserConfig, llmID)@@ -101,7 +100,6 @@ func (d *DatasetService) GetMetadataConfig(ctx context.Context, datasetID string// UpdateMetadataConfig updates the auto-metadata configuration for a dataset.func (d *DatasetService) UpdateMetadataConfig(ctx context.Context, datasetID string, req *service.MetadataConfigRequest) (map[string]interface{}, common.ErrorCode, error) {datasetID = strings.TrimSpace(datasetID)- userID := strings.TrimSpace(permission.UserIDFromContext(ctx))if err := permission.NewDatabaseChecker(dao.DB).CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindDataset, ID: datasetID}, permission.OperationUpdate); err != nil {code, permissionErr := permissionresponse.Normalize(err)@@ -162,7 +160,7 @@ func (d *DatasetService) UpdateMetadataConfig(ctx context.Context, datasetID strdelete(parserConfig, "enable_metadata")delete(parserConfig, "built_in_metadata")llmID := ""- if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(ctx, service.Identity{UserID: userID, TenantID: kb.TenantID}, entity.ModelTypeChat); modelErr == nil {+ if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, kb.TenantID), entity.ModelTypeChat); modelErr == nil {llmID = service.ModelReference(modelInfo)}parserConfig = service.ApplyComponentScopedParserConfig(parserConfig, llmID)diff --git a/internal/service/dataset/search.go b/internal/service/dataset/search.goindex 2ca35f9237..8f023b2e2a 100644--- a/internal/service/dataset/search.go+++ b/internal/service/dataset/search.go@@ -3,7 +3,9 @@ package datasetimport ("context""fmt"+"ragflow/internal/dao"+ "ragflow/internal/permission""slices""go.uber.org/zap"@@ -11,7 +13,6 @@ import ("ragflow/internal/common""ragflow/internal/entity"modelModule "ragflow/internal/entity/models"- "ragflow/internal/permission"permissionresponse "ragflow/internal/permission/response""ragflow/internal/service""ragflow/internal/service/nlp"@@ -216,16 +217,16 @@ func (d *DatasetService) SearchDatasets(ctx context.Context, req *service.Searchif metadataFilter != nil {method, _ := metadataFilter["method"].(string)if method == "auto" || method == "semi_auto" {- access := service.Identity{TenantID: tenantIDs[0]}+ modelCtx := permission.WithTenantID(ctx, tenantIDs[0])if chatID != "" {- chatModelForFilter, err = modelFactory.NewChatModel(ctx, access, chatID)+ chatModelForFilter, err = modelFactory.NewChatModel(modelCtx, chatID)if err != nil {common.Warn("Failed to get chat model config from search_config chat_id, using tenant default", zap.String("chatID", chatID), zap.Error(err))}}if chatModelForFilter == nil {- chatModelForFilter, err = modelFactory.NewDefaultChatModel(ctx, access)+ chatModelForFilter, err = modelFactory.NewDefaultChatModel(modelCtx)if err != nil {common.Warn("Failed to get tenant default chat model for meta_data_filter", zap.Error(err))}@@ -261,7 +262,7 @@ func (d *DatasetService) SearchDatasets(ctx context.Context, req *service.Search}}if keyword {- chatModel, err := modelFactory.NewDefaultChatModel(ctx, service.Identity{TenantID: tenantIDs[0]})+ chatModel, err := modelFactory.NewDefaultChatModel(permission.WithTenantID(ctx, tenantIDs[0]))if err != nil {common.Warn("Failed to get default chat model for LLM transformations", zap.Error(err))} else {@@ -281,7 +282,7 @@ func (d *DatasetService) SearchDatasets(ctx context.Context, req *service.Search// Determine embedding modelvar embeddingModel *modelModule.EmbeddingModelif kbRecords[0].EmbdID != "" {- embeddingModel, err = modelFactory.NewEmbeddingModel(ctx, service.Identity{TenantID: tenantIDs[0]}, kbRecords[0].EmbdID)+ embeddingModel, err = modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantIDs[0]), kbRecords[0].EmbdID)if err != nil {return nil, fmt.Errorf("failed to get embedding model by embd_id: %w", err)}@@ -290,7 +291,7 @@ func (d *DatasetService) SearchDatasets(ctx context.Context, req *service.Search// Get rerank model if rerankID is specifiedvar rerankModel *modelModule.RerankModelif rerankID != "" {- rerankModel, err = modelFactory.NewRerankModel(ctx, service.Identity{TenantID: tenantIDs[0]}, rerankID)+ rerankModel, err = modelFactory.NewRerankModel(permission.WithTenantID(ctx, tenantIDs[0]), rerankID)if err != nil {return nil, fmt.Errorf("failed to get rerank model by rerank_id: %w", err)}diff --git a/internal/service/dataset/search_integration_test.go b/internal/service/dataset/search_integration_test.goindex 96dbf6a68c..0ee9dc1af8 100644--- a/internal/service/dataset/search_integration_test.go+++ b/internal/service/dataset/search_integration_test.go@@ -201,7 +201,7 @@ func newSearchIntegrationFixture(t *testing.T) *searchIntegrationFixture {}grantDatasetTestResource(t, owner, "kb", kb, owner, "owner")}- model, err := service.NewModelFactory().NewEmbeddingModel(ctx, service.Identity{TenantID: owner}, info.ModelID+"@Builtin")+ model, err := service.NewModelFactory().NewEmbeddingModel(permission.WithTenantID(ctx, owner), info.ModelID+"@Builtin")if err != nil {t.Fatal(err)}diff --git a/internal/service/dataset/update.go b/internal/service/dataset/update.goindex 9bbb2e0b0d..13285b5766 100644--- a/internal/service/dataset/update.go+++ b/internal/service/dataset/update.go@@ -269,14 +269,14 @@ func (d *DatasetService) UpdateDataset(ctx context.Context, datasetID string, re} else {tenantEmbdID = ""}- identity := service.Identity{UserID: userID, TenantID: lockedKB.TenantID}- ok, message := d.verifyEmbeddingAvailability(ctx, effectiveEmbdID, identity)+ modelCtx := permission.WithTenantID(ctx, lockedKB.TenantID)+ ok, message := d.verifyEmbeddingAvailability(modelCtx, effectiveEmbdID, lockedKB.TenantID)if !ok {txCode = common.CodeDataErrorreturn errors.New(message)}if effectiveEmbdID != "" && tenantEmbdID == "" {- target, err := service.NewModelFactory().ResolveInfo(ctx, identity, entity.ModelTypeEmbedding, effectiveEmbdID)+ target, err := service.NewModelFactory().ResolveInfo(modelCtx, entity.ModelTypeEmbedding, effectiveEmbdID)if err == nil {tenantEmbdID = target.ID}diff --git a/internal/service/document/document_dataset_update.go b/internal/service/document/document_dataset_update.goindex 2c7e15b5df..bcf3cf3389 100644--- a/internal/service/document/document_dataset_update.go+++ b/internal/service/document/document_dataset_update.go@@ -7,6 +7,8 @@ import ("maps""math""path/filepath"++ "ragflow/internal/permission""ragflow/internal/service""strconv""strings"@@ -17,7 +19,6 @@ import ("ragflow/internal/entity"componentpkg "ragflow/internal/ingestion/component"pipelinepkg "ragflow/internal/ingestion/pipeline"- "ragflow/internal/permission"permissionresponse "ragflow/internal/permission/response""ragflow/internal/tokenizer""ragflow/internal/utility"@@ -292,7 +293,7 @@ func (s *DocumentService) UpdateDatasetDocument(ctx context.Context, datasetID,}pipelinepkg.ApplyParentChildChunkerConfig(cleaned, parentChildOverrides)llmID := ""- if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(ctx, service.Identity{TenantID: kb.TenantID}, entity.ModelTypeChat); modelErr == nil {+ if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, kb.TenantID), entity.ModelTypeChat); modelErr == nil {llmID = service.ModelReference(modelInfo)}cleaned = service.ApplyComponentScopedParserConfig(cleaned, llmID)@@ -323,7 +324,7 @@ func (s *DocumentService) UpdateDatasetDocument(ctx context.Context, datasetID,zap.String("parserID", effParserID), zap.Error(cpErr))} else {llmID := ""- if modelInfo, llmErr := service.NewModelFactory().ResolveDefaultInfo(ctx, service.Identity{TenantID: kb.TenantID}, entity.ModelTypeChat); llmErr == nil {+ if modelInfo, llmErr := service.NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, kb.TenantID), entity.ModelTypeChat); llmErr == nil {llmID = service.ModelReference(modelInfo)} else if !errors.Is(llmErr, service.ErrNoDefaultModel) {common.Warn("document pipeline/version switch: failed to resolve default chat model, falling back to no llm binding",diff --git a/internal/service/document/document_ingest.go b/internal/service/document/document_ingest.goindex 5c6d58a18c..b3ff134122 100644--- a/internal/service/document/document_ingest.go+++ b/internal/service/document/document_ingest.go@@ -14,15 +14,11 @@ import ()func (s *DocumentService) ListIngestionTasks(ctx context.Context, datasetID *string, page, pageSize int) ([]*entity.IngestionTask, error) {- return s.ingestionTaskSvc.ListByUser(ctx, permission.UserIDFromContext(ctx), datasetID, page, pageSize)+ return s.ingestionTaskSvc.List(ctx, datasetID, page, pageSize)}func (s *DocumentService) IngestDocuments(ctx context.Context, datasetID string, docIDs []string) ([]*service.ParseDocumentResponse, error) {- userID := permission.UserIDFromContext(ctx)- if userID == "" {- return nil, permission.ErrUnauthenticated- }- responses, err := s.ingestionTaskSvc.CreateForDocuments(ctx, datasetID, userID, docIDs)+ responses, err := s.ingestionTaskSvc.CreateForDocuments(ctx, datasetID, docIDs)if err != nil {return nil, err}diff --git a/internal/service/document/document_parser_selection.go b/internal/service/document/document_parser_selection.goindex d75f7f0295..8b8176dc58 100644--- a/internal/service/document/document_parser_selection.go+++ b/internal/service/document/document_parser_selection.go@@ -9,6 +9,7 @@ import (componentpkg "ragflow/internal/ingestion/component""ragflow/internal/ingestion/component/schema"pipelinepkg "ragflow/internal/ingestion/pipeline"+ "ragflow/internal/permission""ragflow/internal/service""ragflow/internal/utility"@@ -202,7 +203,7 @@ func rebuildParserConfig(ctx context.Context, kb *entity.Knowledgebase, target,}pipelinepkg.ApplyParentChildChunkerConfig(cleaned, raw)llmID := ""- if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(ctx, service.Identity{TenantID: kb.TenantID}, entity.ModelTypeChat); modelErr == nil {+ if modelInfo, modelErr := service.NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, kb.TenantID), entity.ModelTypeChat); modelErr == nil {llmID = service.ModelReference(modelInfo)}cleaned = service.ApplyComponentScopedParserConfig(cleaned, llmID)diff --git a/internal/service/document/document_parser_selection_test.go b/internal/service/document/document_parser_selection_test.goindex b7be44a647..e89a0c6a06 100644--- a/internal/service/document/document_parser_selection_test.go+++ b/internal/service/document/document_parser_selection_test.go@@ -8,6 +8,7 @@ import ("ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission""ragflow/internal/service""ragflow/internal/storage"syncerconnector "ragflow/internal/syncer/connector"@@ -486,7 +487,7 @@ func TestUploadLocalDocuments_RoutesFileTypesToDedicatedParsers(t *testing.T) {t.Fatalf("insert kb: %v", err)}- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")svc := testDocumentService(t)files := []*multipart.FileHeader{makeTestFileHeader(t, "file", "photo.jpg", []byte("jpeg-bytes")),@@ -495,7 +496,7 @@ func TestUploadLocalDocuments_RoutesFileTypesToDedicatedParsers(t *testing.T) {makeTestFileHeader(t, "file", "talk.mp3", []byte("mp3-bytes")),makeTestFileHeader(t, "file", "notes.txt", []byte("plain text")),}- got, errs := svc.UploadLocalDocuments(ctx, kb, "user-1", files, "", nil)+ got, errs := svc.UploadLocalDocuments(ctx, kb, files, "", nil)if len(errs) != 0 {t.Fatalf("unexpected errs: %v", errs)}@@ -569,7 +570,7 @@ func TestUploadLocalDocuments_FallsBackWhenSelectionLacksFamily(t *testing.T) {seedDocumentParserTenant(t, "tenant-1", "user-1")- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")svc := testDocumentService(t)presentationKB := &entity.Knowledgebase{@@ -583,7 +584,7 @@ func TestUploadLocalDocuments_FallsBackWhenSelectionLacksFamily(t *testing.T) {if err := dao.DB.Create(presentationKB).Error; err != nil {t.Fatalf("insert presentation kb: %v", err)}- got, errs := svc.UploadLocalDocuments(ctx, presentationKB, "user-1", []*multipart.FileHeader{+ got, errs := svc.UploadLocalDocuments(ctx, presentationKB, []*multipart.FileHeader{makeTestFileHeader(t, "file", "laws.txt", []byte("plain text")),makeTestFileHeader(t, "file", "deck.pptx", []byte("pptx-bytes")),}, "", nil)@@ -612,7 +613,7 @@ func TestUploadLocalDocuments_FallsBackWhenSelectionLacksFamily(t *testing.T) {if err := dao.DB.Create(canvasKB).Error; err != nil {t.Fatalf("insert canvas kb: %v", err)}- got, errs = svc.UploadLocalDocuments(ctx, canvasKB, "user-1", []*multipart.FileHeader{+ got, errs = svc.UploadLocalDocuments(ctx, canvasKB, []*multipart.FileHeader{makeTestFileHeader(t, "file", "report.pdf", []byte("%PDF-1.4")),makeTestFileHeader(t, "file", "laws.txt", []byte("plain text")),}, "", nil)@@ -667,9 +668,9 @@ func TestUploadLocalDocuments_SwitchesVideoToPicture(t *testing.T) {t.Fatalf("insert kb: %v", err)}- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")svc := testDocumentService(t)- got, errs := svc.UploadLocalDocuments(ctx, kb, "user-1", []*multipart.FileHeader{+ got, errs := svc.UploadLocalDocuments(ctx, kb, []*multipart.FileHeader{makeTestFileHeader(t, "file", "clip.mov", []byte("mov-bytes")),makeTestFileHeader(t, "file", "movie.mp4", []byte("mp4-bytes")),makeTestFileHeader(t, "file", "legacy.rmvb", []byte("rmvb-bytes")),diff --git a/internal/service/document/document_test.go b/internal/service/document/document_test.goindex 2600c29929..cc8c968164 100644--- a/internal/service/document/document_test.go+++ b/internal/service/document/document_test.go@@ -1401,10 +1401,10 @@ func TestUploadLocalDocuments_MirrorsPythonCoreFields(t *testing.T) {t.Fatalf("insert existing doc: %v", err)}- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")svc := testDocumentService(t)fh := makeTestFileHeader(t, "file", "deck.pptx", []byte("abc"))- got, errs := svc.UploadLocalDocuments(ctx, kb, "user-1", []*multipart.FileHeader{fh}, "nested/path", map[string]interface{}{+ got, errs := svc.UploadLocalDocuments(ctx, kb, []*multipart.FileHeader{fh}, "nested/path", map[string]interface{}{"table_column_mode": "assist",})if len(errs) != 0 {@@ -1464,9 +1464,9 @@ func TestUploadEmptyDocument_CreatesVirtualDocumentAndFileLink(t *testing.T) {t.Fatalf("insert kb: %v", err)}- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")svc := testDocumentService(t)- got, code, err := svc.UploadEmptyDocument(ctx, kb, "user-1", "draft.md")+ got, code, err := svc.UploadEmptyDocument(ctx, kb, "draft.md")if err != nil {t.Fatalf("UploadEmptyDocument error: %v", err)}diff --git a/internal/service/document/document_upload.go b/internal/service/document/document_upload.goindex 9c96ec74e5..2ac63d4950 100644--- a/internal/service/document/document_upload.go+++ b/internal/service/document/document_upload.go@@ -10,6 +10,7 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission""ragflow/internal/service""ragflow/internal/storage""ragflow/internal/utility"@@ -27,7 +28,11 @@ import (//// Gaps vs Python (documented, not yet ported): thumbnail generation and// read_potential_broken_pdf repair.-func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.Knowledgebase, tenantID string, files []*multipart.FileHeader, parentPath string, parserConfigOverride map[string]interface{}) ([]map[string]interface{}, []string) {+func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.Knowledgebase, files []*multipart.FileHeader, parentPath string, parserConfigOverride map[string]interface{}) ([]map[string]interface{}, []string) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, []string{permission.ErrUnauthenticated.Error()}+ }storageImpl := storage.GetStorageFactory().GetStorage()if storageImpl == nil {return nil, []string{"storage not initialized"}@@ -36,7 +41,7 @@ func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.K// Resolve (and create if needed) the dataset's file-manager folder up front.// Without the File / file2document linkage the document list (which inner-joins// file2document + file) would never surface the uploaded files.- kbFolder, err := s.ensureKBFolder(ctx, kb, tenantID)+ kbFolder, err := s.ensureKBFolder(ctx, kb, userID)if err != nil {return nil, []string{err.Error()}}@@ -90,7 +95,7 @@ func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.K}selection, parserConfig := resolveDocumentParser(ctx, kb, filename, filetype, merged)- doc := s.newDatasetDocument(kb, tenantID, filename, location, string(filetype), selection, parserConfig, "local", int64(len(blob)), blob)+ doc := s.newDatasetDocument(kb, userID, filename, location, string(filetype), selection, parserConfig, "local", int64(len(blob)), blob)if err = s.InsertDocument(ctx, doc); err != nil {// Roll back the orphaned blob so a failed insert doesn't leak storage.rmErr := removeObjectBestEffort(ctx, storageImpl, kb.ID, location)@@ -118,7 +123,11 @@ func (s *DocumentService) UploadLocalDocuments(ctx context.Context, kb *entity.K}// UploadEmptyDocument inserts a zero-byte "virtual" document into the dataset.-func (s *DocumentService) UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name string) (map[string]interface{}, common.ErrorCode, error) {+func (s *DocumentService) UploadEmptyDocument(ctx context.Context, kb *entity.Knowledgebase, name string) (map[string]interface{}, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated+ }// Fall back to a numbered name when the requested one is already taken.name, err := common.UniqueFileName(name, 255, func(candidate string) (bool, error) {return s.documentDAO.NameExistsInKB(ctx, dao.DB, kb.ID, candidate)@@ -127,14 +136,14 @@ func (s *DocumentService) UploadEmptyDocument(ctx context.Context, kb *entity.Knreturn nil, common.CodeServerError, err}- kbFolder, err := s.ensureKBFolder(ctx, kb, tenantID)+ kbFolder, err := s.ensureKBFolder(ctx, kb, userID)if err != nil {return nil, common.CodeServerError, err}// Virtual documents have no file type to route on, so they keep the// dataset parser (mirrors Python's _upload_empty_document).- doc := s.newDatasetDocument(kb, tenantID, name, "", "virtual", service.CurrentSelection(kb.ParserID, kb.PipelineID), kb.ParserConfig, "local", 0, nil)+ doc := s.newDatasetDocument(kb, userID, name, "", "virtual", service.CurrentSelection(kb.ParserID, kb.PipelineID), kb.ParserConfig, "local", 0, nil)if err = s.InsertDocument(ctx, doc); err != nil {return nil, common.CodeServerError, err}@@ -233,13 +242,17 @@ func (s *DocumentService) addFileFromKB(ctx context.Context, doc *entity.Documenreturn nil}-func (s *DocumentService) UploadWebDocument(ctx context.Context, kb *entity.Knowledgebase, tenantID, name, url string) (map[string]interface{}, common.ErrorCode, error) {+func (s *DocumentService) UploadWebDocument(ctx context.Context, kb *entity.Knowledgebase, name, url string) (map[string]interface{}, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, common.CodeUnauthorized, permission.ErrUnauthenticated+ }storageImpl := storage.GetStorageFactory().GetStorage()if storageImpl == nil {return nil, common.CodeServerError, fmt.Errorf("storage not initialized")}- kbFolder, err := s.ensureKBFolder(ctx, kb, tenantID)+ kbFolder, err := s.ensureKBFolder(ctx, kb, userID)if err != nil {return nil, common.CodeServerError, err}@@ -275,7 +288,7 @@ func (s *DocumentService) UploadWebDocument(ctx context.Context, kb *entity.Know}selection, parserConfig := resolveDocumentParser(ctx, kb, filename, filetype, kb.ParserConfig)- doc := s.newDatasetDocument(kb, tenantID, filename, location, string(filetype), selection, parserConfig, "web", int64(len(blob)), blob)+ doc := s.newDatasetDocument(kb, userID, filename, location, string(filetype), selection, parserConfig, "web", int64(len(blob)), blob)if err = s.InsertDocument(ctx, doc); err != nil {rmErr := removeObjectBestEffort(ctx, storageImpl, kb.ID, location)if rmErr != nil {diff --git a/internal/service/file/access.go b/internal/service/file/access.goindex ef24733381..92aa5bc322 100644--- a/internal/service/file/access.go+++ b/internal/service/file/access.go@@ -22,21 +22,6 @@ func checkFileAccess(ctx context.Context, file *entity.File, operation permissio}, operation)}-func fileRequestIdentity(ctx context.Context, identity string) (string, string, error) {- userID := permission.UserIDFromContext(ctx)- tenantID := permission.TenantIDFromContext(ctx)- if userID == "" && tenantID == "" {- return identity, identity, nil- }- if userID == "" || userID != identity {- return "", "", permission.ErrIdentityMismatch- }- if tenantID == "" {- tenantID = identity- }- return userID, tenantID, nil-}-func (s *FileService) checkFileTreeAccess(ctx context.Context, file *entity.File, operation permission.Operation) error {if file == nil {return permission.ErrResourceNotFounddiff --git a/internal/service/file/file_browse_permission_test.go b/internal/service/file/file_browse_permission_test.goindex ccb4d57e6a..7cc26f35a0 100644--- a/internal/service/file/file_browse_permission_test.go+++ b/internal/service/file/file_browse_permission_test.go@@ -64,7 +64,7 @@ func TestTenantMemberSeesOnlyReadableFilesAndPaths(t *testing.T) {if _, err := svc.GetAllParentFoldersForTenant(ctx, "owner", "private"); !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("resolve private file path error = %v, want permission denied", err)}- if _, err := svc.GetFileContent(ctx, "reader", "private"); !errors.Is(err, permission.ErrPermissionDenied) {+ if _, err := svc.GetFileContent(ctx, "private"); !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("read private file error = %v, want permission denied", err)}if err := svc.MoveFiles(ctx, []string{"private"}, "", "new-private.txt"); !errors.Is(err, permission.ErrPermissionDenied) {diff --git a/internal/service/file/file_content.go b/internal/service/file/file_content.goindex 3da60e9d2b..ca9a150a8c 100644--- a/internal/service/file/file_content.go+++ b/internal/service/file/file_content.go@@ -18,7 +18,7 @@ import (// GetFileContent gets file metadata and checks permission for download// Matches Python's file_api_service.get_file_content function-func (s *FileService) GetFileContent(ctx context.Context, uid, fileID string) (*entity.File, error) {+func (s *FileService) GetFileContent(ctx context.Context, fileID string) (*entity.File, error) {file, err := s.fileDAO.GetByID(ctx, dao.DB, fileID)if err != nil || file == nil {return nil, fmt.Errorf("document not found")@@ -80,13 +80,17 @@ func (s *FileService) GetStorageAddress(ctx context.Context, fileID string) (*St}// DownloadAgentFile downloads an agent-generated file directly from MinIO without querying the database.-func (s *FileService) DownloadAgentFile(ctx context.Context, tenantID, location string) ([]byte, error) {+func (s *FileService) DownloadAgentFile(ctx context.Context, location string) ([]byte, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }storageImpl := storage.GetStorageFactory().GetStorage()if storageImpl == nil {return nil, fmt.Errorf("storage not initialized")}- bucketName := fmt.Sprintf("%s-downloads", tenantID)+ bucketName := fmt.Sprintf("%s-downloads", userID)blob, err := storageImpl.Get(ctx, bucketName, location)if err != nil {@@ -112,7 +116,11 @@ func (s *FileService) DownloadAgentFile(ctx context.Context, tenantID, location// Blobs are stored directly in "{created_by}-downloads/{id}" in object// storage WITHOUT a corresponding File entity row in the database.// Mirrors Python's FileService.get_files → get_blob(user_id, file_id).-func (s *FileService) GetFileContents(ctx context.Context, uid string, fileDicts []map[string]interface{}) (texts []string, images []string, err error) {+func (s *FileService) GetFileContents(ctx context.Context, fileDicts []map[string]interface{}) (texts []string, images []string, err error) {+ uid := permission.UserIDFromContext(ctx)+ if uid == "" {+ return nil, nil, permission.ErrUnauthenticated+ }storageImpl := storage.GetStorageFactory().GetStorage()if storageImpl == nil {return nil, nil, fmt.Errorf("storage not initialized")@@ -164,7 +172,11 @@ func (s *FileService) GetFileContents(ctx context.Context, uid string, fileDicts// ParseAgentUploads resolves descriptors returned by upload_info from the// caller's downloads bucket and converts them to sys.files values.-func (s *FileService) ParseAgentUploads(ctx context.Context, userID string, fileDicts []map[string]interface{}, layoutRecognize string) ([]string, error) {+func (s *FileService) ParseAgentUploads(ctx context.Context, fileDicts []map[string]interface{}, layoutRecognize string) ([]string, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }storageImpl := storage.GetStorageFactory().GetStorage()if storageImpl == nil {return nil, fmt.Errorf("storage not initialized")diff --git a/internal/service/file/file_folder_test.go b/internal/service/file/file_folder_test.goindex 602e343693..bd056f369a 100644--- a/internal/service/file/file_folder_test.go+++ b/internal/service/file/file_folder_test.go@@ -333,7 +333,7 @@ func TestFileService_GetFileContentRejectsInaccessibleFile(t *testing.T) {setupFolderTestDB(t)insertFolderTestFile(t, "file-1", "folder-1", "private.pdf")- _, err := testFileService().GetFileContent(fileTestContext(t, "user-2", "tenant-1", "tenant-1"), "user-2", "file-1")+ _, err := testFileService().GetFileContent(fileTestContext(t, "user-2", "tenant-1", "tenant-1"), "file-1")if !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("GetFileContent error = %v, want permission denied", err)}@@ -420,7 +420,7 @@ func TestFileService_UploadRejectsInaccessibleParent(t *testing.T) {t.Fatalf("seed foreign folder: %v", err)}- _, err := testFileService().UploadFile(fileTestContext(t, "user-1", "user-1"), "user-1", foreignFolder.ID, nil, 1024)+ _, err := testFileService().UploadFile(fileTestContext(t, "user-1", "user-1"), foreignFolder.ID, nil, 1024)if !errors.Is(err, permission.ErrResourceNotFound) {t.Fatalf("UploadFile error = %v, want resource not found", err)}diff --git a/internal/service/file/file_test.go b/internal/service/file/file_test.goindex 22fa4af784..17015a615f 100644--- a/internal/service/file/file_test.go+++ b/internal/service/file/file_test.go@@ -158,7 +158,7 @@ func TestFileService_GetFileContents_NotAccessible(t *testing.T) {t.Cleanup(func() { factory.SetStorage(originalStorage) })svc := testFileService()- texts, images, err := svc.GetFileContents(t.Context(), "user-1", []map[string]interface{}{{+ texts, images, err := svc.GetFileContents(permission.WithIdentity(t.Context(), "user-1", ""), []map[string]interface{}{{"id": "loc-1","name": "secret.txt","mime_type": "text/plain",@@ -187,7 +187,7 @@ func TestFileService_GetFileContents_Accessible(t *testing.T) {t.Cleanup(func() { factory.SetStorage(originalStorage) })svc := testFileService()- texts, images, err := svc.GetFileContents(t.Context(), "user-1", []map[string]interface{}{{+ texts, images, err := svc.GetFileContents(permission.WithIdentity(t.Context(), "user-1", ""), []map[string]interface{}{{"id": "loc-1","name": "doc.txt","mime_type": "text/plain",@@ -220,7 +220,7 @@ func TestFileService_GetFileContents_ImageAttachmentAsDataURI(t *testing.T) {t.Cleanup(func() { factory.SetStorage(originalStorage) })svc := testFileService()- texts, images, err := svc.GetFileContents(t.Context(), "user-1", []map[string]interface{}{{+ texts, images, err := svc.GetFileContents(permission.WithIdentity(t.Context(), "user-1", ""), []map[string]interface{}{{"id": "img-1","name": "25336bcdd3126d32a522db5e9c9fcaf3.jpeg","mime_type": "image/jpeg",@@ -260,7 +260,8 @@ func TestFileService_GetFileContents_VideoAttachmentReportsNotice(t *testing.T)t.Cleanup(func() { factory.SetStorage(originalStorage) })svc := testFileService()- texts, images, err := svc.GetFileContents(ctx, "user-1", []map[string]interface{}{+ ctx = permission.WithIdentity(ctx, "user-1", "")+ texts, images, err := svc.GetFileContents(ctx, []map[string]interface{}{{"id": "vid-1", "name": "clip.mp4", "mime_type": "video/mp4", "created_by": "user-1"},{"id": "img-1", "name": "photo.jpeg", "mime_type": "image/jpeg", "created_by": "user-1"},})@@ -276,7 +277,7 @@ func TestFileService_GetFileContents_VideoAttachmentReportsNotice(t *testing.T)}func TestFileService_ParseAgentUploads_TextAndImageInRequestOrder(t *testing.T) {- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")memory := storage.NewMemoryStorage()if err := memory.Put(ctx, "user-1-downloads", "text-id", []byte("uploaded text")); err != nil {t.Fatalf("put text: %v", err)@@ -289,7 +290,7 @@ func TestFileService_ParseAgentUploads_TextAndImageInRequestOrder(t *testing.T)factory.SetStorage(memory)t.Cleanup(func() { factory.SetStorage(originalStorage) })- contents, err := testFileService().ParseAgentUploads(ctx, "user-1", []map[string]interface{}{+ contents, err := testFileService().ParseAgentUploads(ctx, []map[string]interface{}{{"id": "text-id", "name": "notes.txt", "mime_type": "text/plain", "created_by": "user-1"},{"id": "image-id", "name": "photo.bin", "mime_type": "image/png", "created_by": "user-1"},}, "Plain Text")@@ -308,7 +309,7 @@ func TestFileService_ParseAgentUploads_TextAndImageInRequestOrder(t *testing.T)}func TestFileService_ParseAgentUploads_RejectsVideoWithImageMime(t *testing.T) {- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")memory := storage.NewMemoryStorage()if err := memory.Put(ctx, "user-1-downloads", "video-id", []byte("mp4-bytes")); err != nil {t.Fatalf("put video: %v", err)@@ -318,7 +319,7 @@ func TestFileService_ParseAgentUploads_RejectsVideoWithImageMime(t *testing.T) {factory.SetStorage(memory)t.Cleanup(func() { factory.SetStorage(originalStorage) })- _, err := testFileService().ParseAgentUploads(ctx, "user-1", []map[string]interface{}{+ _, err := testFileService().ParseAgentUploads(ctx, []map[string]interface{}{{"id": "video-id", "name": "clip.mp4", "mime_type": "image/png", "created_by": "user-1"},}, "")if err == nil || !strings.Contains(err.Error(), "video content is not supported") {@@ -327,14 +328,14 @@ func TestFileService_ParseAgentUploads_RejectsVideoWithImageMime(t *testing.T) {}func TestFileService_ParseAgentUploads_RejectsForeignOwner(t *testing.T) {- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")memory := storage.NewMemoryStorage()factory := storage.GetStorageFactory()originalStorage := factory.GetStorage()factory.SetStorage(memory)t.Cleanup(func() { factory.SetStorage(originalStorage) })- _, err := testFileService().ParseAgentUploads(ctx, "user-1", []map[string]interface{}{+ _, err := testFileService().ParseAgentUploads(ctx, []map[string]interface{}{{"id": "file-id", "name": "secret.txt", "mime_type": "text/plain", "created_by": "user-2"},}, "")if err == nil || !strings.Contains(err.Error(), "created_by does not match") {@@ -343,14 +344,14 @@ func TestFileService_ParseAgentUploads_RejectsForeignOwner(t *testing.T) {}func TestFileService_ParseAgentUploads_MissingObjectFails(t *testing.T) {- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "user-1", "")memory := storage.NewMemoryStorage()factory := storage.GetStorageFactory()originalStorage := factory.GetStorage()factory.SetStorage(memory)t.Cleanup(func() { factory.SetStorage(originalStorage) })- _, err := testFileService().ParseAgentUploads(ctx, "user-1", []map[string]interface{}{+ _, err := testFileService().ParseAgentUploads(ctx, []map[string]interface{}{{"id": "missing", "name": "missing.txt", "mime_type": "text/plain", "created_by": "user-1"},}, "")if err == nil || !strings.Contains(err.Error(), "read upload") {@@ -374,11 +375,11 @@ func TestFileService_DownloadAgentFile_Success(t *testing.T) {})svc := testFileService()- tenantID := "tenant123"+ userID := "tenant123"location := "file-abc.txt"- ctx := t.Context()- blob, err := svc.DownloadAgentFile(ctx, tenantID, location)+ ctx := permission.WithIdentity(t.Context(), userID, "")+ blob, err := svc.DownloadAgentFile(ctx, location)if err != nil {t.Fatalf("expected no error, got %v", err)}@@ -410,11 +411,11 @@ func TestFileService_DownloadAgentFile_Error(t *testing.T) {})svc := testFileService()- tenantID := "tenant123"+ userID := "tenant123"location := "file-abc.txt"- ctx := t.Context()- blob, err := svc.DownloadAgentFile(ctx, tenantID, location)+ ctx := permission.WithIdentity(t.Context(), userID, "")+ blob, err := svc.DownloadAgentFile(ctx, location)if err == nil {t.Fatalf("expected error, got nil")}diff --git a/internal/service/file/file_upload.go b/internal/service/file/file_upload.goindex 2bdf016d5b..3a9c090bc9 100644--- a/internal/service/file/file_upload.go+++ b/internal/service/file/file_upload.go@@ -25,12 +25,15 @@ func DeploymentUploadMaxBytes() int64 {}// UploadFile uploads files to a folder-func (s *FileService) UploadFile(ctx context.Context, tenantID, parentID string, files []*multipart.FileHeader, maxBytes int64) ([]map[string]interface{}, error) {- userID, currentTenantID, err := fileRequestIdentity(ctx, tenantID)- if err != nil {- return nil, err+func (s *FileService) UploadFile(ctx context.Context, parentID string, files []*multipart.FileHeader, maxBytes int64) ([]map[string]interface{}, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }+ tenantID := permission.TenantIDFromContext(ctx)+ if tenantID == "" {+ tenantID = userID}- tenantID = currentTenantIDif err := permission.NewDatabaseChecker(dao.DB).CheckFeature(ctx, "file", permission.ActionWrite); err != nil {return nil, err}diff --git a/internal/service/generator.go b/internal/service/generator.goindex 6fd9d5847b..b1b47a6a5b 100644--- a/internal/service/generator.go+++ b/internal/service/generator.go@@ -27,6 +27,7 @@ import ("ragflow/internal/common"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission""ragflow/internal/rag/prompts""go.uber.org/zap"@@ -126,14 +127,13 @@ func CrossLanguages(ctx context.Context, tenantID string, llmID string, query stvar chatModel *modelModule.ChatModelvar err error- access := Identity{TenantID: tenantID}if llmID != "" {- chatModel, err = modelFactory.NewChatModel(ctx, access, llmID)+ chatModel, err = modelFactory.NewChatModel(permission.WithTenantID(ctx, tenantID), llmID)if err != nil {return query, fmt.Errorf("failed to get chat model: %w", err)}} else {- chatModel, err = modelFactory.NewDefaultChatModel(ctx, access)+ chatModel, err = modelFactory.NewDefaultChatModel(permission.WithTenantID(ctx, tenantID))if err != nil {return query, fmt.Errorf("failed to get default chat model: %w", err)}diff --git a/internal/service/identity.go b/internal/service/identity.godeleted file mode 100644index ee14466d7a..0000000000--- a/internal/service/identity.go+++ /dev/null@@ -1,47 +0,0 @@-//-// Copyright 2026 The InfiniFlow Authors. All Rights Reserved.-//-// Licensed under the Apache License, Version 2.0 (the "License");-// you may not use this file except in compliance with the License.-// You may obtain a copy of the License at-//-// http://www.apache.org/licenses/LICENSE-2.0-//-// Unless required by applicable law or agreed to in writing, software-// distributed under the License is distributed on an "AS IS" BASIS,-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.-// See the License for the specific language governing permissions and-// limitations under the License.--package service--import (- "context"- "strings"-- "ragflow/internal/permission"-)--// Identity identifies a user in a tenant. TenantID may be empty when an-// edition derives the effective tenant from the resource or user.-type Identity struct {- UserID string- TenantID string-}--// ResolveIdentity returns the authenticated user and their active tenant.-// Explicit Identity values remain available to background work without a-// request context.-func ResolveIdentity(ctx context.Context) (Identity, error) {- userID := strings.TrimSpace(permission.UserIDFromContext(ctx))- if userID == "" {- return Identity{}, permission.ErrUnauthenticated- }-- tenantID, err := requireCurrentTenantID(ctx, userID)- if err != nil {- return Identity{}, err- }-- return Identity{UserID: userID, TenantID: tenantID}, nil-}diff --git a/internal/service/ingestion_task_service.go b/internal/service/ingestion_task_service.goindex 0b5f10e2b6..40f8502c17 100644--- a/internal/service/ingestion_task_service.go+++ b/internal/service/ingestion_task_service.go@@ -14,6 +14,7 @@ import ("ragflow/internal/entity"ingestionpipeline "ragflow/internal/ingestion/pipeline""ragflow/internal/observability"+ "ragflow/internal/permission""go.uber.org/zap""gorm.io/gorm"@@ -188,14 +189,22 @@ func (s *IngestionTaskService) emitLifecycleEvent(ctx context.Context, task *ents.eventEmitter.EmitIngestLog(ctx, observability.BuildIngestLog(task, doc, run, typ, status, errorInfo, "", ""))}-func (s *IngestionTaskService) ListByUser(ctx context.Context, userID string, datasetID *string, page, pageSize int) ([]*entity.IngestionTask, error) {+func (s *IngestionTaskService) List(ctx context.Context, datasetID *string, page, pageSize int) ([]*entity.IngestionTask, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }if datasetID == nil {return s.ingestionTaskDAO.ListByUserID(ctx, dao.DB, userID, page, pageSize)}return s.ingestionTaskDAO.ListByUserIDAndDatasetID(ctx, dao.DB, userID, *datasetID, page, pageSize)}-func (s *IngestionTaskService) CreateForDocuments(ctx context.Context, datasetID, userID string, docIDs []string) ([]*ParseDocumentResponse, error) {+func (s *IngestionTaskService) CreateForDocuments(ctx context.Context, datasetID string, docIDs []string) ([]*ParseDocumentResponse, error) {+ userID := permission.UserIDFromContext(ctx)+ if userID == "" {+ return nil, permission.ErrUnauthenticated+ }uniqueDocIDs := common.Deduplicate(docIDs)if len(uniqueDocIDs) == 0 {return nil, fmt.Errorf("no documents to parse")diff --git a/internal/service/ingestion_task_service_test.go b/internal/service/ingestion_task_service_test.goindex 9cc5b0ce8f..dd5f4fa66a 100644--- a/internal/service/ingestion_task_service_test.go+++ b/internal/service/ingestion_task_service_test.go@@ -15,6 +15,7 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission")type recordingTaskPublisher struct {@@ -82,7 +83,7 @@ func TestIngestionTaskServiceCreateForDocumentsPublishesTaskMessages(t *testing.svc.taskPublisher = publisherctx := t.Context()- resp, err := svc.CreateForDocuments(ctx, "kb-1", "user-1", []string{"doc-1"})+ resp, err := svc.CreateForDocuments(permission.WithIdentity(ctx, "user-1", ""), "kb-1", []string{"doc-1"})if err != nil {t.Fatalf("CreateForDocuments failed: %v", err)}@@ -138,7 +139,7 @@ func TestIngestionTaskServiceCreateForDocumentsRejectsDatasetMismatch(t *testingsvc := NewIngestionTaskService()svc.taskPublisher = publisher- responses, err := svc.CreateForDocuments(ctx, "kb-1", "user-1", []string{"doc-1"})+ responses, err := svc.CreateForDocuments(permission.WithIdentity(ctx, "user-1", ""), "kb-1", []string{"doc-1"})if err != nil {t.Fatalf("expected per-document failure: %v", err)}@@ -174,7 +175,7 @@ func TestIngestionTaskServiceCreateForDocumentsRejectsMissingRunMetadata(t *testsvc := NewIngestionTaskService()svc.taskPublisher = publisher- responses, err := svc.CreateForDocuments(t.Context(), "missing-kb", "user-1", []string{"doc-1"})+ responses, err := svc.CreateForDocuments(permission.WithIdentity(t.Context(), "user-1", ""), "missing-kb", []string{"doc-1"})if err != nil {t.Fatalf("CreateForDocuments returns per-document failures: %v", err)}@@ -215,7 +216,7 @@ func TestIngestionTaskServiceMarksTaskScheduledOnlyAfterPublish(t *testing.T) {svc := NewIngestionTaskService()svc.taskPublisher = publisher- responses, err := svc.CreateForDocuments(t.Context(), "kb-1", "user-1", []string{"doc-1"})+ responses, err := svc.CreateForDocuments(permission.WithIdentity(t.Context(), "user-1", ""), "kb-1", []string{"doc-1"})if err != nil {t.Fatalf("CreateForDocuments failed: %v", err)}@@ -252,7 +253,7 @@ func TestIngestionTaskServiceAcceptsConsumerWinningPublishRace(t *testing.T) {svc := NewIngestionTaskService()svc.taskPublisher = publisher- responses, err := svc.CreateForDocuments(t.Context(), "kb-1", "user-1", []string{"doc-1"})+ responses, err := svc.CreateForDocuments(permission.WithIdentity(t.Context(), "user-1", ""), "kb-1", []string{"doc-1"})if err != nil {t.Fatalf("CreateForDocuments failed: %v", err)}@@ -336,7 +337,7 @@ func TestIngestionTaskServiceListByUserFiltersDataset(t *testing.T) {svc := NewIngestionTaskService()datasetID := "kb-1"ctx := t.Context()- tasks, err := svc.ListByUser(ctx, "user-1", &datasetID, 0, 0)+ tasks, err := svc.List(permission.WithIdentity(ctx, "user-1", ""), &datasetID, 0, 0)if err != nil {t.Fatalf("ListByUser failed: %v", err)}@@ -1935,7 +1936,7 @@ func TestIngestionTaskServiceCreateForDocumentsOpensPreTerminalPipelineLog(t *tesvc := NewIngestionTaskService()svc.taskPublisher = &recordingTaskPublisher{}ctx := t.Context()- if _, err := svc.CreateForDocuments(ctx, "kb-1", "user-1", []string{"doc-1"}); err != nil {+ if _, err := svc.CreateForDocuments(permission.WithIdentity(ctx, "user-1", ""), "kb-1", []string{"doc-1"}); err != nil {t.Fatalf("CreateForDocuments failed: %v", err)}@@ -2002,7 +2003,7 @@ func TestIngestionTaskServiceStartRunningAdvancesPreTerminalPipelineLog(t *testisvc := NewIngestionTaskService()svc.taskPublisher = &recordingTaskPublisher{}ctx := t.Context()- resp, err := svc.CreateForDocuments(ctx, "kb-1", "user-1", []string{"doc-1"})+ resp, err := svc.CreateForDocuments(permission.WithIdentity(ctx, "user-1", ""), "kb-1", []string{"doc-1"})if err != nil {t.Fatalf("CreateForDocuments failed: %v", err)}@@ -2043,7 +2044,7 @@ func TestIngestionTaskServiceRequestStopBeforeRunClosesPreTerminalPipelineLog(tsvc := NewIngestionTaskService()svc.taskPublisher = &recordingTaskPublisher{}ctx := t.Context()- if _, err := svc.CreateForDocuments(ctx, "kb-1", "user-1", []string{"doc-1"}); err != nil {+ if _, err := svc.CreateForDocuments(permission.WithIdentity(ctx, "user-1", ""), "kb-1", []string{"doc-1"}); err != nil {t.Fatalf("CreateForDocuments failed: %v", err)}loadOpenPipelineLog(t, ctx, db, "doc-1")@@ -2277,7 +2278,7 @@ func TestIngestionTaskServiceOpensPreTerminalLogBeforePublish(t *testing.T) {svc := NewIngestionTaskService()svc.taskPublisher = publisher- if _, err := svc.CreateForDocuments(t.Context(), "kb-1", "user-1", []string{"doc-1"}); err != nil {+ if _, err := svc.CreateForDocuments(permission.WithIdentity(t.Context(), "user-1", ""), "kb-1", []string{"doc-1"}); err != nil {t.Fatalf("CreateForDocuments failed: %v", err)}if logIDAtPublish == "" {diff --git a/internal/service/langfuse.go b/internal/service/langfuse.goindex 7be5cc5beb..bc37488e01 100644--- a/internal/service/langfuse.go+++ b/internal/service/langfuse.go@@ -42,7 +42,7 @@ var langfuseCtxKey = langfuseCtxKeyType{}// LangfuseClientFromTenant returns a tracing client for the given tenant,// or nil if Langfuse is not configured. Failures to look up credentials// are non-fatal; Langfuse is observability, not a chat path requirement.-func LangfuseClientFromTenant(ctx context.Context, tenantID, userID, chatID, modelName string) *LangfuseClient {+func LangfuseClientFromTenant(ctx context.Context, tenantID, chatID, modelName string) *LangfuseClient {if tenantID == "" {return nil}diff --git a/internal/service/langfuse_service.go b/internal/service/langfuse_service.goindex 194fcc22f3..365328234e 100644--- a/internal/service/langfuse_service.go+++ b/internal/service/langfuse_service.go@@ -24,6 +24,7 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ permissionresponse "ragflow/internal/permission/response""gorm.io/gorm")@@ -68,8 +69,13 @@ func NewLangfuseService() *LangfuseService {}// SetAPIKey validates and stores (insert or update) the Langfuse credentials-// for a tenant.-func (s *LangfuseService) SetAPIKey(ctx context.Context, tenantID, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {+// for the current tenant.+func (s *LangfuseService) SetAPIKey(ctx context.Context, secretKey, publicKey, host string) (*entity.TenantLangfuse, common.ErrorCode, error) {+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {+ code, normalized := permissionresponse.NormalizeHidden(err)+ return nil, code, normalized+ }if secretKey == "" || publicKey == "" || host == "" {return nil, common.CodeDataError, errors.New("missing required fields")}@@ -96,9 +102,14 @@ func (s *LangfuseService) SetAPIKey(ctx context.Context, tenantID, secretKey, pureturn row, common.CodeSuccess, nil}-// GetAPIKey returns the stored credentials enriched with the Langfuse project-// id/name.-func (s *LangfuseService) GetAPIKey(ctx context.Context, tenantID string) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {+// GetAPIKey returns the current tenant credentials enriched with the Langfuse+// project id/name.+func (s *LangfuseService) GetAPIKey(ctx context.Context) (*entity.LangfuseInfoResponse, common.ErrorCode, string, error) {+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {+ code, normalized := permissionresponse.NormalizeHidden(err)+ return nil, code, "", normalized+ }row, err := s.langfuseDAO.GetByTenantID(ctx, dao.DB, tenantID)if err != nil {return nil, common.CodeServerError, "", err@@ -129,8 +140,13 @@ func (s *LangfuseService) GetAPIKey(ctx context.Context, tenantID string) (*entireturn info, common.CodeSuccess, "success", nil}-// DeleteAPIKey removes the stored credentials for a tenant.-func (s *LangfuseService) DeleteAPIKey(ctx context.Context, tenantID string) (bool, common.ErrorCode, string, error) {+// DeleteAPIKey removes the stored credentials for the current tenant.+func (s *LangfuseService) DeleteAPIKey(ctx context.Context) (bool, common.ErrorCode, string, error) {+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {+ code, normalized := permissionresponse.NormalizeHidden(err)+ return false, code, "", normalized+ }if err := s.langfuseDAO.DeleteExistingByTenantID(ctx, dao.DB, tenantID); err != nil {if errors.Is(err, gorm.ErrRecordNotFound) {return false, common.CodeSuccess, "Have not record any Langfuse keys.", nildiff --git a/internal/service/langfuse_service_test.go b/internal/service/langfuse_service_test.goindex 27762cac79..e8261210b8 100644--- a/internal/service/langfuse_service_test.go+++ b/internal/service/langfuse_service_test.go@@ -27,6 +27,7 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission")func setupLangfuseServiceTestDB(t *testing.T) *gorm.DB {@@ -38,9 +39,15 @@ func setupLangfuseServiceTestDB(t *testing.T) *gorm.DB {if err != nil {t.Fatalf("failed to open sqlite: %v", err)}- if err := db.AutoMigrate(&entity.TenantLangfuse{}); err != nil {+ if err := db.AutoMigrate(&entity.TenantLangfuse{}, &entity.UserTenant{}); err != nil {t.Fatalf("failed to migrate test schema: %v", err)}+ active := string(entity.StatusValid)+ if err := db.Create(&entity.UserTenant{+ ID: "langfuse-membership", UserID: "tenant-1", TenantID: "tenant-1", Role: "owner", Status: &active,+ }).Error; err != nil {+ t.Fatalf("create tenant membership: %v", err)+ }origDB := dao.DBdao.DB = db@@ -72,9 +79,9 @@ func newLangfuseServiceForTest(v langfuseVerifier) *LangfuseService {func TestLangfuseService_SetAPIKey_MissingFields(t *testing.T) {setupLangfuseServiceTestDB(t)svc := newLangfuseServiceForTest(stubLangfuseVerifier{authOK: true})- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")- _, code, err := svc.SetAPIKey(ctx, "tenant-1", "", "pk", "host")+ _, code, err := svc.SetAPIKey(ctx, "", "pk", "host")if code != common.CodeDataError || err == nil || err.Error() != "missing required fields" {t.Fatalf("expected Missing required fields/CodeDataError, got code=%d err=%v", code, err)}@@ -83,9 +90,9 @@ func TestLangfuseService_SetAPIKey_MissingFields(t *testing.T) {func TestLangfuseService_SetAPIKey_InvalidKeys(t *testing.T) {setupLangfuseServiceTestDB(t)svc := newLangfuseServiceForTest(stubLangfuseVerifier{authOK: false})- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")- _, code, err := svc.SetAPIKey(ctx, "tenant-1", "sk", "pk", "host")+ _, code, err := svc.SetAPIKey(ctx, "sk", "pk", "host")if code != common.CodeDataError || err == nil || err.Error() != "invalid Langfuse keys" {t.Fatalf("expected Invalid Langfuse keys/CodeDataError, got code=%d err=%v", code, err)}@@ -94,9 +101,9 @@ func TestLangfuseService_SetAPIKey_InvalidKeys(t *testing.T) {func TestLangfuseService_SetAPIKey_VerifierError(t *testing.T) {setupLangfuseServiceTestDB(t)svc := newLangfuseServiceForTest(stubLangfuseVerifier{authErr: errors.New("network down")})- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")- _, code, err := svc.SetAPIKey(ctx, "tenant-1", "sk", "pk", "host")+ _, code, err := svc.SetAPIKey(ctx, "sk", "pk", "host")if code != common.CodeServerError || err == nil || err.Error() != "network down" {t.Fatalf("expected verifier error/CodeServerError, got code=%d err=%v", code, err)}@@ -105,10 +112,10 @@ func TestLangfuseService_SetAPIKey_VerifierError(t *testing.T) {func TestLangfuseService_SetAPIKey_CreateThenUpdate(t *testing.T) {db := setupLangfuseServiceTestDB(t)svc := newLangfuseServiceForTest(stubLangfuseVerifier{authOK: true})- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")// Create- row, code, err := svc.SetAPIKey(ctx, "tenant-1", "sk-1", "pk-1", "https://a.langfuse.com")+ row, code, err := svc.SetAPIKey(ctx, "sk-1", "pk-1", "https://a.langfuse.com")if err != nil || code != common.CodeSuccess {t.Fatalf("create failed: code=%d err=%v", code, err)}@@ -123,7 +130,7 @@ func TestLangfuseService_SetAPIKey_CreateThenUpdate(t *testing.T) {}// Update (same tenant) should not create a second row- _, code, err = svc.SetAPIKey(ctx, "tenant-1", "sk-2", "pk-2", "https://b.langfuse.com")+ _, code, err = svc.SetAPIKey(ctx, "sk-2", "pk-2", "https://b.langfuse.com")if err != nil || code != common.CodeSuccess {t.Fatalf("update failed: code=%d err=%v", code, err)}@@ -140,9 +147,9 @@ func TestLangfuseService_SetAPIKey_CreateThenUpdate(t *testing.T) {func TestLangfuseService_GetAPIKey_NoRecord(t *testing.T) {setupLangfuseServiceTestDB(t)svc := newLangfuseServiceForTest(stubLangfuseVerifier{})- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")- data, code, message, err := svc.GetAPIKey(ctx, "tenant-1")+ data, code, message, err := svc.GetAPIKey(ctx)if err != nil || code != common.CodeSuccess || data != nil {t.Fatalf("unexpected: code=%d data=%v err=%v", code, data, err)}@@ -153,13 +160,13 @@ func TestLangfuseService_GetAPIKey_NoRecord(t *testing.T) {func TestLangfuseService_GetAPIKey_Unauthorized(t *testing.T) {db := setupLangfuseServiceTestDB(t)- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")if err := dao.NewLangfuse().Create(ctx, db, &entity.TenantLangfuse{TenantID: "tenant-1", SecretKey: "sk", PublicKey: "pk", Host: "host"}); err != nil {t.Fatalf("seed failed: %v", err)}svc := newLangfuseServiceForTest(stubLangfuseVerifier{projErr: ErrLangfuseUnauthorized})- data, code, message, err := svc.GetAPIKey(ctx, "tenant-1")+ data, code, message, err := svc.GetAPIKey(ctx)if data != nil || code != common.CodeDataError || err == nil {t.Fatalf("unexpected: code=%d data=%v err=%v", code, data, err)}@@ -170,13 +177,13 @@ func TestLangfuseService_GetAPIKey_Unauthorized(t *testing.T) {func TestLangfuseService_GetAPIKey_ApiError(t *testing.T) {db := setupLangfuseServiceTestDB(t)- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")if err := dao.NewLangfuse().Create(ctx, db, &entity.TenantLangfuse{TenantID: "tenant-1", SecretKey: "sk", PublicKey: "pk", Host: "host"}); err != nil {t.Fatalf("seed failed: %v", err)}svc := newLangfuseServiceForTest(stubLangfuseVerifier{projErr: &LangfuseAPIError{StatusCode: 500, Body: "boom"}})- data, code, message, err := svc.GetAPIKey(ctx, "tenant-1")+ data, code, message, err := svc.GetAPIKey(ctx)if data != nil || code != common.CodeSuccess || err != nil {t.Fatalf("unexpected: code=%d data=%v err=%v", code, data, err)}@@ -187,13 +194,13 @@ func TestLangfuseService_GetAPIKey_ApiError(t *testing.T) {func TestLangfuseService_GetAPIKey_NonAPIError(t *testing.T) {db := setupLangfuseServiceTestDB(t)- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")if err := dao.NewLangfuse().Create(ctx, db, &entity.TenantLangfuse{TenantID: "tenant-1", SecretKey: "sk", PublicKey: "pk", Host: "host"}); err != nil {t.Fatalf("seed failed: %v", err)}svc := newLangfuseServiceForTest(stubLangfuseVerifier{projErr: errors.New("json parse failed")})- data, code, message, err := svc.GetAPIKey(ctx, "tenant-1")+ data, code, message, err := svc.GetAPIKey(ctx)if data != nil || code != common.CodeServerError || message != "" || err == nil {t.Fatalf("unexpected: code=%d message=%q data=%v err=%v", code, message, data, err)}@@ -201,13 +208,13 @@ func TestLangfuseService_GetAPIKey_NonAPIError(t *testing.T) {func TestLangfuseService_GetAPIKey_Success(t *testing.T) {db := setupLangfuseServiceTestDB(t)- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")if err := dao.NewLangfuse().Create(ctx, db, &entity.TenantLangfuse{TenantID: "tenant-1", SecretKey: "sk", PublicKey: "pk", Host: "https://a.langfuse.com"}); err != nil {t.Fatalf("seed failed: %v", err)}svc := newLangfuseServiceForTest(stubLangfuseVerifier{projID: "proj-1", projName: "My Project"})- data, code, message, err := svc.GetAPIKey(ctx, "tenant-1")+ data, code, message, err := svc.GetAPIKey(ctx)if err != nil || code != common.CodeSuccess || message != "success" {t.Fatalf("unexpected: code=%d message=%q err=%v", code, message, err)}@@ -224,9 +231,9 @@ func TestLangfuseService_GetAPIKey_Success(t *testing.T) {func TestLangfuseService_DeleteAPIKey_NoRecord(t *testing.T) {setupLangfuseServiceTestDB(t)svc := newLangfuseServiceForTest(stubLangfuseVerifier{})- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")- ok, code, message, err := svc.DeleteAPIKey(ctx, "tenant-1")+ ok, code, message, err := svc.DeleteAPIKey(ctx)if ok || code != common.CodeSuccess || err != nil {t.Fatalf("unexpected: ok=%v code=%d err=%v", ok, code, err)}@@ -237,13 +244,13 @@ func TestLangfuseService_DeleteAPIKey_NoRecord(t *testing.T) {func TestLangfuseService_DeleteAPIKey_Success(t *testing.T) {db := setupLangfuseServiceTestDB(t)- ctx := t.Context()+ ctx := permission.WithIdentity(t.Context(), "tenant-1", "tenant-1")if err := dao.NewLangfuse().Create(ctx, db, &entity.TenantLangfuse{TenantID: "tenant-1", SecretKey: "sk", PublicKey: "pk", Host: "host"}); err != nil {t.Fatalf("seed failed: %v", err)}svc := newLangfuseServiceForTest(stubLangfuseVerifier{})- ok, code, message, err := svc.DeleteAPIKey(ctx, "tenant-1")+ ok, code, message, err := svc.DeleteAPIKey(ctx)if !ok || code != common.CodeSuccess || message != "" || err != nil {t.Fatalf("unexpected: ok=%v code=%d message=%q err=%v", ok, code, message, err)}diff --git a/internal/service/mcp.go b/internal/service/mcp.goindex 64e487f34b..8a9f5e5972 100644--- a/internal/service/mcp.go+++ b/internal/service/mcp.go@@ -128,7 +128,7 @@ func (s *MCPService) CreateMCPServer(ctx context.Context, req CreateMCPServerReqreturn nil, common.CodeDataError, errors.New("invalid url")}- tenantID, err := requireCurrentTenantID(ctx, userID)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {code, normalized := permissionresponse.Normalize(err)return nil, code, normalized@@ -548,11 +548,10 @@ func headerOrVariablesChanged(req UpdateMCPServerRequest) bool {// ListMCPServers lists MCP servers belonging to a tenant the caller can use.func (s *MCPService) ListMCPServers(ctx context.Context, requestedTenantID string, ids []string, keywords string, page, pageSize int, orderby string, desc bool) (*ListMCPServersResponse, common.ErrorCode, error) {- userID := permission.UserIDFromContext(ctx)tenantID := strings.TrimSpace(requestedTenantID)if tenantID == "" {var err error- tenantID, err = requireCurrentTenantID(ctx, userID)+ tenantID, err = requireCurrentTenantID(ctx)if errors.Is(err, permission.ErrMembershipNotFound) {return &ListMCPServersResponse{MCPServers: []*MCPServerListItem{}}, common.CodeSuccess, nil}@@ -738,7 +737,7 @@ func (s *MCPService) ImportServers(ctx context.Context, servers map[string]map[sif userID == "" {return nil, permission.ErrUnauthenticated}- tenantID, err := requireCurrentTenantID(ctx, userID)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {_, normalized := permissionresponse.Normalize(err)return nil, normalizeddiff --git a/internal/service/memory.go b/internal/service/memory.goindex 4d10fe7ee2..c90af1d0c4 100644--- a/internal/service/memory.go+++ b/internal/service/memory.go@@ -22,9 +22,11 @@ import ("errors""fmt""math"+"ragflow/internal/common""ragflow/internal/entity""ragflow/internal/entity/models"+ "ragflow/internal/permission""slices""sort"@@ -39,7 +41,6 @@ import ("ragflow/internal/engine""ragflow/internal/engine/kvrocks"enginetypes "ragflow/internal/engine/types"- "ragflow/internal/permission""ragflow/internal/service/nlp")@@ -502,7 +503,7 @@ func (s *MemoryService) CreateMemory(ctx context.Context, req *CreateMemoryRequeif userID == "" {return nil, permission.ErrUnauthenticated}- tenantID, err := requireCurrentTenantID(ctx, userID)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return nil, err}@@ -514,7 +515,7 @@ func (s *MemoryService) CreateMemory(ctx context.Context, req *CreateMemoryReque// tenant_model row) — we leave the tenant_*_id fields nil and proceed.modelFactory := NewModelFactory()if req.LLMID != "" && req.TenantLLMID == nil {- info, err := modelFactory.ResolveInfo(ctx, Identity{UserID: userID, TenantID: tenantID}, entity.ModelTypeChat, req.LLMID)+ info, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeChat, req.LLMID)if err != nil {common.Warn("CreateMemory: failed to resolve tenant LLM id",zap.String("tenant_id", tenantID), zap.String("llm_id", req.LLMID), zap.Error(err))@@ -524,7 +525,7 @@ func (s *MemoryService) CreateMemory(ctx context.Context, req *CreateMemoryReque}}if req.EmbdID != "" && req.TenantEmbdID == nil {- info, err := modelFactory.ResolveInfo(ctx, Identity{UserID: userID, TenantID: tenantID}, entity.ModelTypeEmbedding, req.EmbdID)+ info, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeEmbedding, req.EmbdID)if err != nil {common.Warn("CreateMemory: failed to resolve tenant embedding id",zap.String("tenant_id", tenantID), zap.String("embd_id", req.EmbdID), zap.Error(err))@@ -684,7 +685,7 @@ func (s *MemoryService) UpdateMemory(ctx context.Context, memoryID string, req *if req.LLMID != nil {updateDict["llm_id"] = *req.LLMIDif req.TenantLLMID == nil && *req.LLMID != "" {- info, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: ownerTenantID}, entity.ModelTypeChat, *req.LLMID)+ info, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, ownerTenantID), entity.ModelTypeChat, *req.LLMID)if err != nil {common.Warn("UpdateMemory: failed to resolve tenant LLM id",zap.String("tenant_id", ownerTenantID), zap.String("llm_id", *req.LLMID), zap.Error(err))@@ -697,7 +698,7 @@ func (s *MemoryService) UpdateMemory(ctx context.Context, memoryID string, req *if req.EmbdID != nil {updateDict["embd_id"] = *req.EmbdIDif req.TenantEmbdID == nil && *req.EmbdID != "" {- info, err := modelFactory.ResolveInfo(ctx, Identity{TenantID: ownerTenantID}, entity.ModelTypeEmbedding, *req.EmbdID)+ info, err := modelFactory.ResolveInfo(permission.WithTenantID(ctx, ownerTenantID), entity.ModelTypeEmbedding, *req.EmbdID)if err != nil {common.Warn("UpdateMemory: failed to resolve tenant embedding id",zap.String("tenant_id", ownerTenantID), zap.String("embd_id", *req.EmbdID), zap.Error(err))@@ -1553,7 +1554,7 @@ func memoryFusionWeights(keywordsSimilarityWeight float64) string {}func (s *MemoryService) memoryMessageDenseExpr(ctx context.Context, question string, memory *entity.Memory, topN int, similarityThreshold float64) (*enginetypes.MatchDenseExpr, error) {- embeddingModel, err := NewModelFactory().NewEmbeddingModel(ctx, Identity{TenantID: memory.TenantID}, memory.EmbdID)+ embeddingModel, err := NewModelFactory().NewEmbeddingModel(permission.WithTenantID(ctx, memory.TenantID), memory.EmbdID)if err != nil {return nil, err}diff --git a/internal/service/memory_extractor.go b/internal/service/memory_extractor.goindex 7b98d689d6..e00a1403b6 100644--- a/internal/service/memory_extractor.go+++ b/internal/service/memory_extractor.go@@ -48,6 +48,7 @@ import ("ragflow/internal/engine/kvrocks""ragflow/internal/entity""ragflow/internal/entity/models"+ "ragflow/internal/permission""go.uber.org/zap""gorm.io/gorm"@@ -496,7 +497,7 @@ func (s *MemoryMessageService) extractByLLM(ctx context.Context, mem *CreateMemoif mem.TenantLLMID != nil && *mem.TenantLLMID != "" {llmRef = *mem.TenantLLMID}- chatModel, err := NewModelFactory().NewChatModel(ctx, Identity{TenantID: mem.TenantID}, llmRef)+ chatModel, err := NewModelFactory().NewChatModel(permission.WithTenantID(ctx, mem.TenantID), llmRef)if err != nil {return nil, fmt.Errorf("resolve chat model: %w", classifyMemoryTaskDependencyError(err))}diff --git a/internal/service/memory_message_service.go b/internal/service/memory_message_service.goindex 990501abc5..df46c5508b 100644--- a/internal/service/memory_message_service.go+++ b/internal/service/memory_message_service.go@@ -65,6 +65,7 @@ import ("ragflow/internal/engine/kvrocks""ragflow/internal/entity""ragflow/internal/entity/models"+ "ragflow/internal/permission""gorm.io/gorm")@@ -355,7 +356,7 @@ func (s *MemoryMessageService) embedAndSaveMessages(ctx context.Context, mem *Crfor i, message := range messages {contents[i], _ = message["content"].(string)}- embeddingModel, err := NewModelFactory().NewEmbeddingModel(ctx, Identity{TenantID: mem.TenantID}, mem.EmbdID)+ embeddingModel, err := NewModelFactory().NewEmbeddingModel(permission.WithTenantID(ctx, mem.TenantID), mem.EmbdID)if err != nil {return err}diff --git a/internal/service/model_call.go b/internal/service/model_call.goindex 65de88f17d..4d7a357601 100644--- a/internal/service/model_call.go+++ b/internal/service/model_call.go@@ -24,6 +24,7 @@ import ("ragflow/internal/common"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission")// ModelCallService provides the model-call API described in Model方法.pdf.@@ -41,11 +42,11 @@ func NewModelCallService() *ModelCallService {// ChatToModelWithMessages sends messages to the model selected by modelRef.func (s *ModelCallService) ChatToModelWithMessages(ctx context.Context, modelRef string, messages []modelModule.Message, config *modelModule.ChatConfig, usage *common.ModelUsage) (*modelModule.ChatResponse, common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return nil, code, err}- chatModel, err := s.modelFactory.NewChatModel(ctx, identity, modelRef)+ chatModel, err := s.modelFactory.NewChatModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return nil, common.CodeNotFound, err}@@ -53,7 +54,7 @@ func (s *ModelCallService) ChatToModelWithMessages(ctx context.Context, modelRefconfig = &modelModule.ChatConfig{}}info := chatModel.Info()- populateModelUsage(usage, info, chatModel.APIConfig, identity.TenantID, identity.UserID)+ populateModelUsage(ctx, usage, info, chatModel.APIConfig, tenantID)response, err := chatModel.ChatWithMessages(ctx, messages, config, usage)if err != nil {@@ -65,18 +66,18 @@ func (s *ModelCallService) ChatToModelWithMessages(ctx context.Context, modelRefreturn response, common.CodeSuccess, nil}func (s *ModelCallService) ChatToModelStreamWithSender(ctx context.Context, modelRef string, messages []modelModule.Message, config *modelModule.ChatConfig, usage *common.ModelUsage, sender func(*string, *string) error) (common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return code, err}- chatModel, err := s.modelFactory.NewChatModel(ctx, identity, modelRef)+ chatModel, err := s.modelFactory.NewChatModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return common.CodeNotFound, err}if config == nil {config = &modelModule.ChatConfig{}}- populateModelUsage(usage, chatModel.Info(), chatModel.APIConfig, identity.TenantID, identity.UserID)+ populateModelUsage(ctx, usage, chatModel.Info(), chatModel.APIConfig, tenantID)if err := chatModel.ChatStreamlyWithSender(ctx, messages, config, usage, sender); err != nil {return common.CodeServerError, err@@ -84,11 +85,11 @@ func (s *ModelCallService) ChatToModelStreamWithSender(ctx context.Context, modereturn common.CodeSuccess, nil}func (s *ModelCallService) EmbedText(ctx context.Context, modelRef string, texts []string, config *modelModule.EmbeddingConfig) ([]modelModule.EmbeddingData, common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return nil, code, err}- embeddingModel, err := s.modelFactory.NewEmbeddingModel(ctx, identity, modelRef)+ embeddingModel, err := s.modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return nil, common.CodeNotFound, err}@@ -113,11 +114,11 @@ func (s *ModelCallService) EmbedText(ctx context.Context, modelRef string, textsreturn embeddings, common.CodeSuccess, nil}func (s *ModelCallService) RerankDocument(ctx context.Context, modelRef, query string, documents []string, config *modelModule.RerankConfig) (*modelModule.RerankResponse, common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return nil, code, err}- rerankModel, err := s.modelFactory.NewRerankModel(ctx, identity, modelRef)+ rerankModel, err := s.modelFactory.NewRerankModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return nil, common.CodeNotFound, err}@@ -135,11 +136,11 @@ func (s *ModelCallService) RerankDocument(ctx context.Context, modelRef, query sreturn response, common.CodeSuccess, nil}func (s *ModelCallService) TranscribeAudio(ctx context.Context, modelRef string, audioFile *string, config *modelModule.ASRConfig) (*modelModule.ASRResponse, common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return nil, code, err}- asrModel, err := s.modelFactory.NewASRModel(ctx, identity, modelRef)+ asrModel, err := s.modelFactory.NewASRModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return nil, common.CodeNotFound, err}@@ -157,11 +158,11 @@ func (s *ModelCallService) TranscribeAudio(ctx context.Context, modelRef string,return response, common.CodeSuccess, nil}func (s *ModelCallService) TranscribeAudioStream(ctx context.Context, modelRef string, audioFile *string, config *modelModule.ASRConfig, sender func(*string, *string) error) (common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return code, err}- asrModel, err := s.modelFactory.NewASRModel(ctx, identity, modelRef)+ asrModel, err := s.modelFactory.NewASRModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return common.CodeNotFound, err}@@ -174,7 +175,7 @@ func (s *ModelCallService) TranscribeAudioStream(ctx context.Context, modelRef sreturn common.CodeSuccess, nil}func (s *ModelCallService) AudioSpeech(ctx context.Context, modelRef string, audioContent *string, config *modelModule.TTSConfig) (*modelModule.TTSResponse, common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return nil, code, err}@@ -182,9 +183,9 @@ func (s *ModelCallService) AudioSpeech(ctx context.Context, modelRef string, audttsModel *modelModule.TTSModel)if strings.TrimSpace(modelRef) == "" {- ttsModel, err = s.modelFactory.NewDefaultTTSModel(ctx, identity)+ ttsModel, err = s.modelFactory.NewDefaultTTSModel(permission.WithTenantID(ctx, tenantID))} else {- ttsModel, err = s.modelFactory.NewTTSModel(ctx, identity, modelRef)+ ttsModel, err = s.modelFactory.NewTTSModel(permission.WithTenantID(ctx, tenantID), modelRef)}if err != nil {return nil, common.CodeNotFound, err@@ -206,15 +207,15 @@ func (s *ModelCallService) AudioSpeechForTenant(ctx context.Context, modelRef, tif s == nil || s.modelFactory == nil {return nil, common.CodeServerError, errors.New("model call service is not initialized")}- access := Identity{TenantID: tenantID}+ modelCtx := permission.WithTenantID(ctx, tenantID)var (ttsModel *modelModule.TTSModelerr error)if strings.TrimSpace(modelRef) == "" {- ttsModel, err = s.modelFactory.NewDefaultTTSModel(ctx, access)+ ttsModel, err = s.modelFactory.NewDefaultTTSModel(modelCtx)} else {- ttsModel, err = s.modelFactory.NewTTSModel(ctx, access, modelRef)+ ttsModel, err = s.modelFactory.NewTTSModel(modelCtx, modelRef)}if err != nil {return nil, common.CodeNotFound, err@@ -233,11 +234,11 @@ func (s *ModelCallService) AudioSpeechForTenant(ctx context.Context, modelRef, treturn response, common.CodeSuccess, nil}func (s *ModelCallService) AudioSpeechStream(ctx context.Context, modelRef string, audioContent *string, config *modelModule.TTSConfig, sender func(*string, *string) error) (common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return code, err}- ttsModel, err := s.modelFactory.NewTTSModel(ctx, identity, modelRef)+ ttsModel, err := s.modelFactory.NewTTSModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return common.CodeNotFound, err}@@ -250,11 +251,11 @@ func (s *ModelCallService) AudioSpeechStream(ctx context.Context, modelRef strinreturn common.CodeSuccess, nil}func (s *ModelCallService) OCRFile(ctx context.Context, modelRef string, content []byte, url *string, config *modelModule.OCRConfig) (*modelModule.OCRFileResponse, common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return nil, code, err}- ocrModel, err := s.modelFactory.NewOCRModel(ctx, identity, modelRef)+ ocrModel, err := s.modelFactory.NewOCRModel(permission.WithTenantID(ctx, tenantID), modelRef)if err != nil {return nil, common.CodeNotFound, err}@@ -275,11 +276,11 @@ func (s *ModelCallService) OCRFile(ctx context.Context, modelRef string, content// ParseFile parses content or url with the document parser selected by// modelRef. A zero model type resolves catalog-only capabilities such as doc_parse.func (s *ModelCallService) ParseFile(ctx context.Context, modelRef string, content []byte, url *string, config *modelModule.ParseFileConfig) (*modelModule.ParseFileResponse, common.ErrorCode, error) {- identity, code, err := s.identityForRequest(ctx)+ tenantID, code, err := s.tenantIDForRequest(ctx)if err != nil {return nil, code, err}- target, err := s.modelFactory.resolveConfig(ctx, identity, 0, modelRef)+ target, err := s.modelFactory.resolveConfig(permission.WithTenantID(ctx, tenantID), 0, modelRef)if err != nil {return nil, common.CodeNotFound, err}@@ -300,22 +301,22 @@ func (s *ModelCallService) ParseFile(ctx context.Context, modelRef string, contereturn response, common.CodeSuccess, nil}-func (s *ModelCallService) identityForRequest(ctx context.Context) (Identity, common.ErrorCode, error) {+func (s *ModelCallService) tenantIDForRequest(ctx context.Context) (string, common.ErrorCode, error) {if s == nil || s.modelFactory == nil {- return Identity{}, common.CodeServerError, errors.New("model call service is not initialized")+ return "", common.CodeServerError, errors.New("model call service is not initialized")}- identity, err := ResolveIdentity(ctx)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {- return Identity{}, common.CodeNotFound, err+ return "", common.CodeNotFound, err}- return identity, common.CodeSuccess, nil+ return tenantID, common.CodeSuccess, nil}-func populateModelUsage(usage *common.ModelUsage, info *modelModule.ModelInfo, apiConfig *modelModule.APIConfig, tenantID, userID string) {+func populateModelUsage(ctx context.Context, usage *common.ModelUsage, info *modelModule.ModelInfo, apiConfig *modelModule.APIConfig, tenantID string) {if usage == nil || info == nil {return}- usage.UserID = userID+ usage.UserID = permission.UserIDFromContext(ctx)usage.TenantID = tenantIDusage.ProviderName = info.ProviderNameusage.InstanceID = info.InstanceIDdiff --git a/internal/service/model_chat.go b/internal/service/model_chat.goindex 1f351153fc..cfb16a9f55 100644--- a/internal/service/model_chat.go+++ b/internal/service/model_chat.go@@ -68,16 +68,15 @@ func chatStreamWithContext(ctx context.Context, chatModel *modelModule.ChatModel// TenantStreamAdapter adapts a factory-created chat model to AskService's// channel-based streaming interface.type TenantStreamAdapter struct {- Factory *ModelFactory- Identity Identity- ModelID string+ Factory *ModelFactory+ ModelID string}func (a *TenantStreamAdapter) ChatStream(ctx context.Context, messages []modelModule.Message, config *modelModule.ChatConfig) (<-chan string, <-chan error, error) {if a.Factory == nil {return nil, nil, fmt.Errorf("model factory not configured")}- chatModel, err := a.Factory.NewChatModel(ctx, a.Identity, a.ModelID)+ chatModel, err := a.Factory.NewChatModel(ctx, a.ModelID)if err != nil {return nil, nil, err}diff --git a/internal/service/model_factory.go b/internal/service/model_factory.goindex 5d4f79a00c..e3995661ff 100644--- a/internal/service/model_factory.go+++ b/internal/service/model_factory.go@@ -96,9 +96,9 @@ func NewModelFactory() *ModelFactory {}}-// NewChatModel resolves and constructs a chat model for the given access scope.-func (f *ModelFactory) NewChatModel(ctx context.Context, access Identity, modelRef string) (*modelModule.ChatModel, error) {- target, err := f.resolveConfig(ctx, access, entity.ModelTypeChat, modelRef)+// NewChatModel resolves a chat model in the Tenant scope carried by ctx.+func (f *ModelFactory) NewChatModel(ctx context.Context, modelRef string) (*modelModule.ChatModel, error) {+ target, err := f.resolveConfig(ctx, entity.ModelTypeChat, modelRef)if err != nil {return nil, err}@@ -106,8 +106,8 @@ func (f *ModelFactory) NewChatModel(ctx context.Context, access Identity, modelR}// NewDefaultChatModel constructs the tenant's configured default chat model.-func (f *ModelFactory) NewDefaultChatModel(ctx context.Context, access Identity) (*modelModule.ChatModel, error) {- target, err := f.resolveDefaultConfig(ctx, access, entity.ModelTypeChat)+func (f *ModelFactory) NewDefaultChatModel(ctx context.Context) (*modelModule.ChatModel, error) {+ target, err := f.resolveDefaultConfig(ctx, entity.ModelTypeChat)if err != nil {return nil, err}@@ -115,8 +115,8 @@ func (f *ModelFactory) NewDefaultChatModel(ctx context.Context, access Identity)}// NewEmbeddingModel resolves and constructs an embedding model.-func (f *ModelFactory) NewEmbeddingModel(ctx context.Context, access Identity, modelRef string) (*modelModule.EmbeddingModel, error) {- target, err := f.resolveConfig(ctx, access, entity.ModelTypeEmbedding, modelRef)+func (f *ModelFactory) NewEmbeddingModel(ctx context.Context, modelRef string) (*modelModule.EmbeddingModel, error) {+ target, err := f.resolveConfig(ctx, entity.ModelTypeEmbedding, modelRef)if err != nil {return nil, err}@@ -124,8 +124,8 @@ func (f *ModelFactory) NewEmbeddingModel(ctx context.Context, access Identity, m}// NewDefaultEmbeddingModel constructs the tenant's configured default embedding model.-func (f *ModelFactory) NewDefaultEmbeddingModel(ctx context.Context, access Identity) (*modelModule.EmbeddingModel, error) {- target, err := f.resolveDefaultConfig(ctx, access, entity.ModelTypeEmbedding)+func (f *ModelFactory) NewDefaultEmbeddingModel(ctx context.Context) (*modelModule.EmbeddingModel, error) {+ target, err := f.resolveDefaultConfig(ctx, entity.ModelTypeEmbedding)if err != nil {return nil, err}@@ -133,8 +133,8 @@ func (f *ModelFactory) NewDefaultEmbeddingModel(ctx context.Context, access Iden}// NewRerankModel resolves and constructs a rerank model.-func (f *ModelFactory) NewRerankModel(ctx context.Context, access Identity, modelRef string) (*modelModule.RerankModel, error) {- target, err := f.resolveConfig(ctx, access, entity.ModelTypeRerank, modelRef)+func (f *ModelFactory) NewRerankModel(ctx context.Context, modelRef string) (*modelModule.RerankModel, error) {+ target, err := f.resolveConfig(ctx, entity.ModelTypeRerank, modelRef)if err != nil {return nil, err}@@ -142,8 +142,8 @@ func (f *ModelFactory) NewRerankModel(ctx context.Context, access Identity, mode}// NewDefaultRerankModel constructs the tenant's configured default rerank model.-func (f *ModelFactory) NewDefaultRerankModel(ctx context.Context, access Identity) (*modelModule.RerankModel, error) {- target, err := f.resolveDefaultConfig(ctx, access, entity.ModelTypeRerank)+func (f *ModelFactory) NewDefaultRerankModel(ctx context.Context) (*modelModule.RerankModel, error) {+ target, err := f.resolveDefaultConfig(ctx, entity.ModelTypeRerank)if err != nil {return nil, err}@@ -151,8 +151,8 @@ func (f *ModelFactory) NewDefaultRerankModel(ctx context.Context, access Identit}// NewOCRModel resolves and constructs an OCR model.-func (f *ModelFactory) NewOCRModel(ctx context.Context, access Identity, modelRef string) (*modelModule.OCRModel, error) {- target, err := f.resolveConfig(ctx, access, entity.ModelTypeOCR, modelRef)+func (f *ModelFactory) NewOCRModel(ctx context.Context, modelRef string) (*modelModule.OCRModel, error) {+ target, err := f.resolveConfig(ctx, entity.ModelTypeOCR, modelRef)if err != nil {return nil, err}@@ -160,8 +160,8 @@ func (f *ModelFactory) NewOCRModel(ctx context.Context, access Identity, modelRe}// NewASRModel resolves and constructs a speech-to-text model.-func (f *ModelFactory) NewASRModel(ctx context.Context, access Identity, modelRef string) (*modelModule.ASRModel, error) {- target, err := f.resolveConfig(ctx, access, entity.ModelTypeSpeech2Text, modelRef)+func (f *ModelFactory) NewASRModel(ctx context.Context, modelRef string) (*modelModule.ASRModel, error) {+ target, err := f.resolveConfig(ctx, entity.ModelTypeSpeech2Text, modelRef)if err != nil {return nil, err}@@ -169,8 +169,8 @@ func (f *ModelFactory) NewASRModel(ctx context.Context, access Identity, modelRe}// NewDefaultASRModel constructs the tenant's configured default speech-to-text model.-func (f *ModelFactory) NewDefaultASRModel(ctx context.Context, access Identity) (*modelModule.ASRModel, error) {- target, err := f.resolveDefaultConfig(ctx, access, entity.ModelTypeSpeech2Text)+func (f *ModelFactory) NewDefaultASRModel(ctx context.Context) (*modelModule.ASRModel, error) {+ target, err := f.resolveDefaultConfig(ctx, entity.ModelTypeSpeech2Text)if err != nil {return nil, err}@@ -178,8 +178,8 @@ func (f *ModelFactory) NewDefaultASRModel(ctx context.Context, access Identity)}// NewTTSModel resolves and constructs a text-to-speech model.-func (f *ModelFactory) NewTTSModel(ctx context.Context, access Identity, modelRef string) (*modelModule.TTSModel, error) {- target, err := f.resolveConfig(ctx, access, entity.ModelTypeTTS, modelRef)+func (f *ModelFactory) NewTTSModel(ctx context.Context, modelRef string) (*modelModule.TTSModel, error) {+ target, err := f.resolveConfig(ctx, entity.ModelTypeTTS, modelRef)if err != nil {return nil, err}@@ -187,8 +187,8 @@ func (f *ModelFactory) NewTTSModel(ctx context.Context, access Identity, modelRe}// NewDefaultTTSModel constructs the tenant's configured default text-to-speech model.-func (f *ModelFactory) NewDefaultTTSModel(ctx context.Context, access Identity) (*modelModule.TTSModel, error) {- target, err := f.resolveDefaultConfig(ctx, access, entity.ModelTypeTTS)+func (f *ModelFactory) NewDefaultTTSModel(ctx context.Context) (*modelModule.TTSModel, error) {+ target, err := f.resolveDefaultConfig(ctx, entity.ModelTypeTTS)if err != nil {return nil, err}@@ -196,12 +196,11 @@ func (f *ModelFactory) NewDefaultTTSModel(ctx context.Context, access Identity)}// ResolveInfo returns model metadata without exposing API credentials or a driver.-func (f *ModelFactory) ResolveInfo(ctx context.Context, access Identity, modelType entity.ModelType, modelRef string) (*modelModule.ModelInfo, error) {- access = identityFromContext(ctx, access)+func (f *ModelFactory) ResolveInfo(ctx context.Context, modelType entity.ModelType, modelRef string) (*modelModule.ModelInfo, error) {if modelType == entity.ModelTypeOCR {modelName, instanceName, providerName := splitRightAnchoredModelName(modelRef)if modelName == "deepdoc" && instanceName == "default" && providerName == "infiniflow" {- if err := f.authorize(ctx, access); err != nil {+ if err := f.authorize(ctx); err != nil {return nil, err}return &modelModule.ModelInfo{@@ -212,7 +211,7 @@ func (f *ModelFactory) ResolveInfo(ctx context.Context, access Identity, modelTy}, nil}}- if err := f.authorize(ctx, access); err != nil {+ if err := f.authorize(ctx); err != nil {return nil, err}modelRef = strings.TrimSpace(modelRef)@@ -220,7 +219,7 @@ func (f *ModelFactory) ResolveInfo(ctx context.Context, access Identity, modelTyinfo, _ := dao.GetModelProviderManager().GetModelByName("Builtin", name)return modelInfoFromTarget(&modelTarget{ModelName: name, ModelType: modelType, ProviderName: "Builtin", ModelInfo: info}), nil}- identity, err := f.resolveModelIdentity(ctx, access, modelType, modelRef)+ identity, err := f.resolveModelIdentity(ctx, modelType, modelRef)if err != nil {return nil, err}@@ -232,18 +231,17 @@ func (f *ModelFactory) ResolveInfo(ctx context.Context, access Identity, modelTyreturn modelInfoFromTarget(target), nil}-// ResolveDefaultInfo returns metadata for the tenant's default model without-// exposing its provider driver or API credentials.-func (f *ModelFactory) ResolveDefaultInfo(ctx context.Context, access Identity, modelType entity.ModelType) (*modelModule.ModelInfo, error) {- access = identityFromContext(ctx, access)- if err := f.authorize(ctx, access); err != nil {+// ResolveDefaultInfo returns metadata for the operation tenant's default model+// without exposing its provider driver or API credentials.+func (f *ModelFactory) ResolveDefaultInfo(ctx context.Context, modelType entity.ModelType) (*modelModule.ModelInfo, error) {+ if err := f.authorize(ctx); err != nil {return nil, err}- ref, err := f.defaultModelReference(ctx, access, modelType)+ ref, err := f.defaultModelReference(ctx, modelType)if err != nil {return nil, err}- return f.ResolveInfo(ctx, access, modelType, ref)+ return f.ResolveInfo(ctx, modelType, ref)}func modelInfoFromTarget(target *modelTarget) *modelModule.ModelInfo {@@ -464,64 +462,40 @@ func maxOutputFromModelInfo(modelInfo *modelModule.Model) int {return *modelInfo.MaxOutput}-func (f *ModelFactory) resolveConfig(ctx context.Context, access Identity, modelType entity.ModelType, modelRef string) (*modelTarget, error) {- access = identityFromContext(ctx, access)- if err := f.authorize(ctx, access); err != nil {+func (f *ModelFactory) resolveConfig(ctx context.Context, modelType entity.ModelType, modelRef string) (*modelTarget, error) {+ if err := f.authorize(ctx); err != nil {return nil, err}- return f.resolveConfigAuthorized(ctx, access, modelType, modelRef)+ return f.resolveConfigAuthorized(ctx, modelType, modelRef)}-func (f *ModelFactory) resolveConfigAuthorized(ctx context.Context, access Identity, modelType entity.ModelType, modelRef string) (*modelTarget, error) {+func (f *ModelFactory) resolveConfigAuthorized(ctx context.Context, modelType entity.ModelType, modelRef string) (*modelTarget, error) {modelRef = strings.TrimSpace(modelRef)if modelRef == "" {return nil, fmt.Errorf("%w: model ref is required", errModelConfigUnavailable)}// A zero type skips category filtering for catalog-only capabilities such// as doc_parse that are not represented by entity.ModelType.- return f.resolveModel(ctx, access, modelType, modelRef)+ return f.resolveModel(ctx, modelType, modelRef)}-func normalizeIdentity(identity Identity) Identity {- identity.TenantID = strings.TrimSpace(identity.TenantID)- identity.UserID = strings.TrimSpace(identity.UserID)- return identity-}--func identityFromContext(ctx context.Context, identity Identity) Identity {- identity = normalizeIdentity(identity)- if identity.UserID == "" {- userID := strings.TrimSpace(permission.UserIDFromContext(ctx))- contextTenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))- if userID != "" && (contextTenantID == "" || contextTenantID == identity.TenantID) {- identity.UserID = userID- }- }- return identity-}--func (f *ModelFactory) authorize(ctx context.Context, access Identity) error {+func (f *ModelFactory) authorize(ctx context.Context) error {if f == nil {return fmt.Errorf("%w: model factory is not initialized", errModelConfigUnavailable)}- if access.TenantID == "" {+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ if tenantID == "" {return fmt.Errorf("%w: tenant id is required", errModelConfigUnavailable)}+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))// A user's personal tenant uses the user ID as its tenant ID. The owner// does not need a user_tenant membership row for that tenant; modelIdentity// still checks whether the requested provider belongs to a reachable tenant.- if access.UserID == "" || access.UserID == access.TenantID {+ if userID == "" || userID == tenantID {return nil}- contextUserID := permission.UserIDFromContext(ctx)- if contextUserID != "" && access.UserID != "" && contextUserID != access.UserID {- return fmt.Errorf("%w: user %s has no access to tenant %s: %w", errModelConfigUnavailable, access.UserID, access.TenantID, permission.ErrIdentityMismatch)- }- if contextUserID == "" && access.UserID != "" {- ctx = permission.WithIdentity(ctx, access.UserID, permission.TenantIDFromContext(ctx))- }- if err := permission.NewDatabaseChecker(dao.DB).CheckTenant(ctx, access.TenantID, permission.TenantMember); err != nil {- return fmt.Errorf("%w: user %s has no access to tenant %s: %w", errModelConfigUnavailable, access.UserID, access.TenantID, err)+ if err := permission.NewDatabaseChecker(dao.DB).CheckTenant(ctx, tenantID, permission.TenantMember); err != nil {+ return fmt.Errorf("%w: user %s has no access to tenant %s: %w", errModelConfigUnavailable, userID, tenantID, err)}return nil}@@ -537,34 +511,35 @@ func (f *ModelFactory) tenantOwnerMembership(ctx context.Context, tenantID strinreturn membership, nil}-func (f *ModelFactory) resolveDefaultConfig(ctx context.Context, access Identity, modelType entity.ModelType) (*modelTarget, error) {- access = identityFromContext(ctx, access)- if err := f.authorize(ctx, access); err != nil {+func (f *ModelFactory) resolveDefaultConfig(ctx context.Context, modelType entity.ModelType) (*modelTarget, error) {+ if err := f.authorize(ctx); err != nil {return nil, err}- ref, err := f.defaultModelReference(ctx, access, modelType)+ ref, err := f.defaultModelReference(ctx, modelType)if err != nil {return nil, err}- return f.resolveConfigAuthorized(ctx, access, modelType, ref)+ return f.resolveConfigAuthorized(ctx, modelType, ref)}-func (f *ModelFactory) defaultModelReference(ctx context.Context, access Identity, modelType entity.ModelType) (string, error) {+func (f *ModelFactory) defaultModelReference(ctx context.Context, modelType entity.ModelType) (string, error) {if modelType == 0 {return "", fmt.Errorf("%w: model type is required", errModelConfigUnavailable)}+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))var membership *entity.UserTenantvar err error- if access.UserID == "" {- membership, err = f.tenantOwnerMembership(ctx, access.TenantID)+ if userID == "" {+ membership, err = f.tenantOwnerMembership(ctx, tenantID)} else {- membership, err = f.userTenantDAO.FilterByUserIDAndTenantID(ctx, dao.DB, access.UserID, access.TenantID)- if errors.Is(err, gorm.ErrRecordNotFound) && access.UserID == access.TenantID {- membership, err = f.tenantOwnerMembership(ctx, access.TenantID)+ membership, err = f.userTenantDAO.FilterByUserIDAndTenantID(ctx, dao.DB, userID, tenantID)+ if errors.Is(err, gorm.ErrRecordNotFound) && userID == tenantID {+ membership, err = f.tenantOwnerMembership(ctx, tenantID)}}if err != nil {- return "", fmt.Errorf("failed to get user tenant model settings: %s type %s: %w", access.TenantID, modelType, err)+ return "", fmt.Errorf("failed to get user tenant model settings: %s type %s: %w", tenantID, modelType, err)}modelName, modelID := defaultModelRefs(membership, modelType)if modelID != "" {@@ -604,16 +579,15 @@ func defaultModelRefs(membership *entity.UserTenant, modelType entity.ModelType)// ResolveModelType returns every model category supported by modelRef. A// model may expose multiple categories, such as chat and vision.-func (s *ModelFactory) ResolveModelType(ctx context.Context, access Identity, modelRef string) ([]entity.ModelType, error) {- access = identityFromContext(ctx, access)- if err := s.authorize(ctx, access); err != nil {+func (s *ModelFactory) ResolveModelType(ctx context.Context, modelRef string) ([]entity.ModelType, error) {+ if err := s.authorize(ctx); err != nil {return nil, err}modelRef = strings.TrimSpace(modelRef)if _, ok := builtinEmbeddingName(modelRef); ok {return []entity.ModelType{entity.ModelTypeEmbedding}, nil}- identity, err := s.resolveModelIdentity(ctx, access, 0, modelRef)+ identity, err := s.resolveModelIdentity(ctx, 0, modelRef)if err != nil {return nil, err}@@ -674,18 +648,23 @@ func catalogToolSupport(providerName, modelName string) bool {// resolveModelIdentity resolves saved IDs and composite names before applying the// same ownership, relationship, status and resource permission checks.-func (s *ModelFactory) resolveModelIdentity(ctx context.Context, access Identity, requestedType entity.ModelType, modelRef string) (*modelIdentity, error) {+func (s *ModelFactory) resolveModelIdentity(ctx context.Context, requestedType entity.ModelType, modelRef string) (*modelIdentity, error) {if s == nil || s.modelDAO == nil || s.modelProviderDAO == nil || s.modelInstanceDAO == nil {return nil, fmt.Errorf("%w: model factory is not initialized", errModelConfigUnavailable)}if modelRef == "" {return nil, fmt.Errorf("%w: model ref is required", errModelConfigUnavailable)}+ tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx))+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if tenantID == "" {+ return nil, fmt.Errorf("%w: tenant id is required", errModelConfigUnavailable)+ }model, err := s.modelDAO.GetByID(ctx, dao.DB, modelRef)if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {return nil, err}- owner, err := s.tenantOwnerMembership(ctx, access.TenantID)+ owner, err := s.tenantOwnerMembership(ctx, tenantID)if err != nil {return nil, err}@@ -708,7 +687,7 @@ func (s *ModelFactory) resolveModelIdentity(ctx context.Context, access Identityreturn nil, fmt.Errorf("%w: model %q has no saved model row or valid composite name: %v", errModelConfigUnavailable, modelRef, parseErr)}identity.modelName = name- identity.providerEntity, err = s.modelProviderDAO.GetByTenantIDAndUserIDAndProviderName(ctx, dao.DB, access.TenantID, owner.UserID, providerName)+ identity.providerEntity, err = s.modelProviderDAO.GetByTenantIDAndUserIDAndProviderName(ctx, dao.DB, tenantID, owner.UserID, providerName)if err != nil {return nil, fmt.Errorf("%w: provider %q lookup failed: %w", errModelConfigUnavailable, providerName, err)}@@ -743,8 +722,8 @@ func (s *ModelFactory) resolveModelIdentity(ctx context.Context, access Identity}}provider, instance := identity.providerEntity, identity.instanceEntity- if provider.TenantID != access.TenantID || provider.UserID != owner.UserID {- return nil, fmt.Errorf("%w: tenant %s can use only its owner's model configuration", errModelConfigUnavailable, access.TenantID)+ if provider.TenantID != tenantID || provider.UserID != owner.UserID {+ return nil, fmt.Errorf("%w: tenant %s can use only its owner's model configuration", errModelConfigUnavailable, tenantID)}if instance.ProviderID != provider.ID {return nil, fmt.Errorf("%w: instance id=%s does not belong to provider id=%s", errModelConfigUnavailable, instance.ID, provider.ID)@@ -755,25 +734,13 @@ func (s *ModelFactory) resolveModelIdentity(ctx context.Context, access Identityif identity.modelEntity != nil && !strings.EqualFold(identity.modelEntity.Status, "active") {return nil, fmt.Errorf("%w: tenant model %q is disabled", errModelConfigUnavailable, modelRef)}- if access.UserID != "" {- contextUserID := permission.UserIDFromContext(ctx)- contextTenantID := permission.TenantIDFromContext(ctx)- if (contextUserID != "" && contextUserID != access.UserID) ||- (contextTenantID != "" && contextTenantID != access.TenantID) {- return nil, fmt.Errorf("%w: model access identity does not match authenticated identity", permission.ErrIdentityMismatch)- }- if contextUserID == "" || contextTenantID == "" {- if contextTenantID == "" {- contextTenantID = access.TenantID- }- ctx = permission.WithIdentity(ctx, access.UserID, contextTenantID)- }+ if userID != "" {checker := permission.NewDatabaseChecker(dao.DB)if err := checker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindModelProvider, ID: provider.ID}, permission.OperationRead); err != nil {- return nil, fmt.Errorf("%w: user %s cannot read model provider %q: %w", errModelConfigUnavailable, access.UserID, provider.ProviderName, err)+ return nil, fmt.Errorf("%w: user %s cannot read model provider %q: %w", errModelConfigUnavailable, userID, provider.ProviderName, err)}if err := checker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindModelInstance, ID: instance.ID}, permission.OperationUse); err != nil {- return nil, fmt.Errorf("%w: user %s cannot use model instance %q: %w", errModelConfigUnavailable, access.UserID, instance.InstanceName, err)+ return nil, fmt.Errorf("%w: user %s cannot use model instance %q: %w", errModelConfigUnavailable, userID, instance.InstanceName, err)}checkedModels := candidatesif requestedType != 0 || model != nil {@@ -787,7 +754,7 @@ func (s *ModelFactory) resolveModelIdentity(ctx context.Context, access Identitycontinue}if err := checker.CheckResource(ctx, permission.ResourceRef{Kind: permission.ResourceKindModel, ID: candidate.ID}, permission.OperationUse); err != nil {- return nil, fmt.Errorf("%w: user %s cannot use model %q: %w", errModelConfigUnavailable, access.UserID, modelRef, err)+ return nil, fmt.Errorf("%w: user %s cannot use model %q: %w", errModelConfigUnavailable, userID, modelRef, err)}}}@@ -797,7 +764,7 @@ func (s *ModelFactory) resolveModelIdentity(ctx context.Context, access Identityreturn identity, nil}-func (s *ModelFactory) resolveModel(ctx context.Context, access Identity, modelType entity.ModelType, modelRef string) (*modelTarget, error) {+func (s *ModelFactory) resolveModel(ctx context.Context, modelType entity.ModelType, modelRef string) (*modelTarget, error) {if name, ok := builtinEmbeddingName(modelRef); ok && modelType == entity.ModelTypeEmbedding {driver := modelModule.GetBuiltinEmbeddingModel(name)if driver == nil {@@ -811,7 +778,7 @@ func (s *ModelFactory) resolveModel(ctx context.Context, access Identity, modelT}return builtinModelTarget(modelType, name, driver, config, info), nil}- identity, err := s.resolveModelIdentity(ctx, access, modelType, modelRef)+ identity, err := s.resolveModelIdentity(ctx, modelType, modelRef)if err != nil {return nil, err}diff --git a/internal/service/model_factory_identity_test.go b/internal/service/model_factory_identity_test.goindex 70af103a15..eafc578a72 100644--- a/internal/service/model_factory_identity_test.go+++ b/internal/service/model_factory_identity_test.go@@ -48,11 +48,10 @@ func TestModelFactoryIDAndNameShareValidation(t *testing.T) {}ctx := serviceTestContext(t, "user-1", "user-1")factory := NewModelFactory()- access := Identity{UserID: "user-1", TenantID: "user-1"}for _, ref := range []string{"model-1", "gpt-test@default@OpenAI"} {- info, infoErr := factory.ResolveInfo(ctx, access, entity.ModelTypeChat, ref)- types, typeErr := factory.ResolveModelType(ctx, access, ref)- _, runErr := factory.resolveConfig(ctx, access, entity.ModelTypeChat, ref)+ info, infoErr := factory.ResolveInfo(ctx, entity.ModelTypeChat, ref)+ types, typeErr := factory.ResolveModelType(ctx, ref)+ _, runErr := factory.resolveConfig(ctx, entity.ModelTypeChat, ref)for _, err := range []error{infoErr, typeErr, runErr} {if test.table != "" {if !errors.Is(err, errModelConfigUnavailable) {@@ -86,20 +85,19 @@ func TestModelFactoryMetadataDoesNotBuildExecutionConfig(t *testing.T) {t.Fatal(err)}factory := NewModelFactory()- access := Identity{UserID: "user-1", TenantID: "user-1"}ctx := serviceTestContext(t, "user-1", "user-1")for _, ref := range []string{"model-1", "gpt-test@default@OpenAI"} {- if _, err := factory.ResolveInfo(ctx, access, entity.ModelTypeChat, ref); err != nil {+ if _, err := factory.ResolveInfo(ctx, entity.ModelTypeChat, ref); err != nil {t.Fatalf("metadata %s: %v", ref, err)}- if _, err := factory.ResolveModelType(ctx, access, ref); err != nil {+ if _, err := factory.ResolveModelType(ctx, ref); err != nil {t.Fatalf("types %s: %v", ref, err)}- if _, err := factory.resolveConfig(ctx, access, entity.ModelTypeChat, ref); err == nil {+ if _, err := factory.resolveConfig(ctx, entity.ModelTypeChat, ref); err == nil {t.Fatalf("execution %s accepted malformed configuration", ref)}}- if _, err := factory.ResolveDefaultInfo(ctx, access, entity.ModelTypeChat); err != nil {+ if _, err := factory.ResolveDefaultInfo(ctx, entity.ModelTypeChat); err != nil {t.Fatal(err)}}@@ -114,17 +112,16 @@ func TestModelFactoryCompositeSelectsRequestedType(t *testing.T) {t.Fatal(err)}factory := NewModelFactory()- access := Identity{UserID: "user-1", TenantID: "user-1"}ctx := serviceTestContext(t, "user-1", "user-1")ref := "gpt-test@default@OpenAI"- types, err := factory.ResolveModelType(ctx, access, ref)+ types, err := factory.ResolveModelType(ctx, ref)if err != nil {t.Fatal(err)}if !reflect.DeepEqual(types, []entity.ModelType{entity.ModelTypeChat, entity.ModelTypeEmbedding}) {t.Fatalf("types = %v", types)}- info, err := factory.ResolveInfo(ctx, access, entity.ModelTypeEmbedding, ref)+ info, err := factory.ResolveInfo(ctx, entity.ModelTypeEmbedding, ref)if err != nil {t.Fatal(err)}@@ -135,7 +132,7 @@ func TestModelFactoryCompositeSelectsRequestedType(t *testing.T) {t.Fatal(err)}for _, modelRef := range []string{"model-embedding", ref} {- if _, err := factory.ResolveInfo(ctx, access, entity.ModelTypeEmbedding, modelRef); !errors.Is(err, errModelConfigUnavailable) {+ if _, err := factory.ResolveInfo(ctx, entity.ModelTypeEmbedding, modelRef); !errors.Is(err, errModelConfigUnavailable) {t.Fatalf("%s: disabled model error = %v", modelRef, err)}}diff --git a/internal/service/model_service.go b/internal/service/model_service.goindex 6a015d5ba4..03863240f3 100644--- a/internal/service/model_service.go+++ b/internal/service/model_service.go@@ -24,6 +24,7 @@ import ("errors""fmt""os"+"ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"@@ -110,13 +111,14 @@ type CheckConnectionRequest struct {ModelInfo []CheckConnectionModelInfo `json:"model_info"`}-func (m *ModelProviderService) AddModelProvider(ctx context.Context, providerName, userID string) (common.ErrorCode, error) {+func (m *ModelProviderService) AddModelProvider(ctx context.Context, providerName string) (common.ErrorCode, error) {providerName = strings.TrimSpace(providerName)+ userID := permission.UserIDFromContext(ctx)if err := permission.NewDatabaseChecker(dao.DB).CheckFeature(ctx, "model_provider", permission.ActionEnable); err != nil {code, normalizedErr := permissionresponse.NormalizeHidden(err)return code, normalizedErr}- tenantID, err := requireCurrentTenantID(ctx, userID)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {code, normalizedErr := permissionresponse.NormalizeHidden(err)return code, normalizedErr@@ -145,8 +147,9 @@ func (m *ModelProviderService) AddModelProvider(ctx context.Context, providerNamreturn common.CodeSuccess, nil}-func (m *ModelProviderService) ListProvidersOfTenant(ctx context.Context, userID string) ([]map[string]interface{}, common.ErrorCode, error) {- ownedTenantID, err := requireCurrentTenantID(ctx, userID)+func (m *ModelProviderService) ListProvidersOfTenant(ctx context.Context) ([]map[string]interface{}, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)+ ownedTenantID, err := requireCurrentTenantID(ctx)if err != nil {if errors.Is(err, permission.ErrMembershipNotFound) {return []map[string]interface{}{}, common.CodeSuccess, nil@@ -248,8 +251,8 @@ func isExcludedTenantProvider(name string) bool {return false}-func (m *ModelProviderService) DeleteModelProvider(ctx context.Context, userID, providerName string) (common.ErrorCode, error) {- provider, err := m.resolveProviderInTenant(ctx, userID, providerName, permission.OperationDelete)+func (m *ModelProviderService) DeleteModelProvider(ctx context.Context, providerName string) (common.ErrorCode, error) {+ provider, err := m.resolveProviderInTenant(ctx, providerName, permission.OperationDelete)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -329,10 +332,10 @@ type SavedProviderModelConfig struct {// ResolveSavedProviderModelConfig validates access to a saved provider// instance and returns the credentials and endpoint for model discovery.-func (m *ModelProviderService) ResolveSavedProviderModelConfig(ctx context.Context, providerName, instanceName, userID string, options SavedProviderModelOptions) (SavedProviderModelConfig, error) {+func (m *ModelProviderService) ResolveSavedProviderModelConfig(ctx context.Context, providerName, instanceName string, options SavedProviderModelOptions) (SavedProviderModelConfig, error) {providerName = strings.TrimSpace(providerName)- provider, err := m.resolveProviderInTenant(ctx, userID, providerName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, providerName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {_, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -708,7 +711,12 @@ func mergeSavedProviderAPIKeyConfig(existing string, submitted json.RawMessage)return string(encoded), nil}-func (m *ModelProviderService) findProviderByIDOrNameInTenant(ctx context.Context, tenantID, userID, providerIDOrName string, includeTenantOwner bool) (*entity.TenantModelProvider, error) {+func (m *ModelProviderService) findProviderByIDOrNameInCurrentTenant(ctx context.Context, providerIDOrName string, includeTenantOwner bool) (*entity.TenantModelProvider, error) {+ userID := permission.UserIDFromContext(ctx)+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {+ return nil, err+ }providerIDOrName = strings.TrimSpace(providerIDOrName)if providerIDOrName == "" {return nil, gorm.ErrRecordNotFound@@ -755,12 +763,8 @@ func (m *ModelProviderService) findProviderByIDOrNameInTenant(ctx context.Contex// Provider names are only unique per tenant (idx_tenant_provider_user_unique),// so a lookup across every tenant a user belongs to can select a same-named// provider owned by another tenant.-func (m *ModelProviderService) resolveProviderInTenant(ctx context.Context, userID, providerIDOrName string, operation permission.Operation) (*entity.TenantModelProvider, error) {- tenantID, err := requireCurrentTenantID(ctx, userID)- if err != nil {- return nil, err- }- provider, err := m.findProviderByIDOrNameInTenant(ctx, tenantID, userID, providerIDOrName, operation == permission.OperationRead)+func (m *ModelProviderService) resolveProviderInTenant(ctx context.Context, providerIDOrName string, operation permission.Operation) (*entity.TenantModelProvider, error) {+ provider, err := m.findProviderByIDOrNameInCurrentTenant(ctx, providerIDOrName, operation == permission.OperationRead)if err != nil {return nil, err}@@ -823,13 +827,13 @@ func instanceLookupError(provider *entity.TenantModelProvider, instanceIDOrNamereturn fmt.Errorf("no instance found for provider '%s' and instance '%s'", provider.ProviderName, instanceIDOrName)}-func (m *ModelProviderService) CreateProviderInstance(ctx context.Context, providerIDOrName, instanceName, apiKey, baseURL, region, userID string, modelInfo []CreateInstanceModelInfo) (common.ErrorCode, error) {+func (m *ModelProviderService) CreateProviderInstance(ctx context.Context, providerIDOrName, instanceName, apiKey, baseURL, region string, modelInfo []CreateInstanceModelInfo) (common.ErrorCode, error) {providerIDOrName = strings.TrimSpace(providerIDOrName)apiKey = strings.TrimSpace(apiKey)baseURL = strings.TrimSpace(baseURL)region = strings.TrimSpace(region)- provider, err := m.resolveProviderInTenant(ctx, userID, providerIDOrName, permission.OperationCreate)+ provider, err := m.resolveProviderInTenant(ctx, providerIDOrName, permission.OperationCreate)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -918,14 +922,14 @@ func (m *ModelProviderService) addModelsToNewInstance(ctx context.Context, db *g// CreateNameOnlyProviderInstance creates a provider instance with only a name,// skipping API key validation and model creation.-func (m *ModelProviderService) CreateNameOnlyProviderInstance(ctx context.Context, providerIDOrName, instanceName, userID string) (common.ErrorCode, error) {+func (m *ModelProviderService) CreateNameOnlyProviderInstance(ctx context.Context, providerIDOrName, instanceName string) (common.ErrorCode, error) {providerIDOrName = strings.TrimSpace(providerIDOrName)if instanceName == "default" {return common.CodeBadRequest, errors.New("instance name cannot be 'default'")}- provider, err := m.resolveProviderInTenant(ctx, userID, providerIDOrName, permission.OperationCreate)+ provider, err := m.resolveProviderInTenant(ctx, providerIDOrName, permission.OperationCreate)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -1009,10 +1013,10 @@ func (m *ModelProviderService) createModelRecord(ctx context.Context, db *gorm.Dreturn m.modelDAO.Create(ctx, db, model)}-func (m *ModelProviderService) ListProviderInstances(ctx context.Context, providerIDOrName, userID string) ([]map[string]interface{}, common.ErrorCode, error) {+func (m *ModelProviderService) ListProviderInstances(ctx context.Context, providerIDOrName string) ([]map[string]interface{}, common.ErrorCode, error) {providerIDOrName = strings.TrimSpace(providerIDOrName)- provider, err := m.resolveProviderInTenant(ctx, userID, providerIDOrName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, providerIDOrName, permission.OperationRead)if err != nil {if errors.Is(err, permission.ErrMembershipNotFound) {return []map[string]interface{}{}, common.CodeSuccess, nil@@ -1080,10 +1084,10 @@ func (m *ModelProviderService) ListProviderInstances(ctx context.Context, providreturn result, common.CodeSuccess, nil}-func (m *ModelProviderService) ShowProviderInstance(ctx context.Context, providerName, instanceIDOrName, userID string) (map[string]interface{}, common.ErrorCode, error) {+func (m *ModelProviderService) ShowProviderInstance(ctx context.Context, providerName, instanceIDOrName string) (map[string]interface{}, common.ErrorCode, error) {providerName = strings.TrimSpace(providerName)- provider, err := m.resolveProviderInTenant(ctx, userID, providerName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, providerName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -1148,8 +1152,8 @@ func (m *ModelProviderService) ShowProviderInstance(ctx context.Context, provide}// resolveAuthorizedInstance checks the provider route and the requested instance operation.-func (m *ModelProviderService) resolveAuthorizedInstance(ctx context.Context, userID, providerName, instanceName string, operation permission.Operation) (*entity.TenantModelProvider, *entity.TenantModelInstance, common.ErrorCode, error) {- provider, err := m.resolveProviderInTenant(ctx, userID, providerName, permission.OperationRead)+func (m *ModelProviderService) resolveAuthorizedInstance(ctx context.Context, providerName, instanceName string, operation permission.Operation) (*entity.TenantModelProvider, *entity.TenantModelInstance, common.ErrorCode, error) {+ provider, err := m.resolveProviderInTenant(ctx, providerName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -1179,8 +1183,8 @@ func (m *ModelProviderService) resolveAuthorizedInstance(ctx context.Context, usreturn provider, instance, common.CodeSuccess, nil}-func (m *ModelProviderService) ShowInstanceBalance(ctx context.Context, providerName, instanceName, userID string) (map[string]interface{}, common.ErrorCode, error) {- provider, instance, code, err := m.resolveAuthorizedInstance(ctx, userID, providerName, instanceName, permission.OperationUse)+func (m *ModelProviderService) ShowInstanceBalance(ctx context.Context, providerName, instanceName string) (map[string]interface{}, common.ErrorCode, error) {+ provider, instance, code, err := m.resolveAuthorizedInstance(ctx, providerName, instanceName, permission.OperationUse)if err != nil {return nil, code, err}@@ -1218,7 +1222,7 @@ func (m *ModelProviderService) ShowInstanceBalance(ctx context.Context, provider// CheckConnection verifies provider connectivity. When saved credentials are// selected, only the instance owner may override their endpoint or config.-func (m *ModelProviderService) CheckConnection(ctx context.Context, providerName string, req CheckConnectionRequest, userID string) (common.ErrorCode, error) {+func (m *ModelProviderService) CheckConnection(ctx context.Context, providerName string, req CheckConnectionRequest) (common.ErrorCode, error) {providerName = strings.TrimSpace(providerName)apiKey := strings.TrimSpace(NormalizeAPIKey(req.APIKey))region := strings.TrimSpace(req.Region)@@ -1346,7 +1350,7 @@ func (m *ModelProviderService) CheckConnection(ctx context.Context, providerNamemodelVerifyResult, verifyErr := verifyProviderModel(ctx, driver, providerInfo.Models, apiConfig, modelInfo)if instanceID != "" && len(modelVerifyResult) > 0 {- if dbErr := m.updateModelVerifyResults(ctx, userID, providerName, instanceID, modelVerifyResult); dbErr != nil {+ if dbErr := m.updateModelVerifyResults(ctx, providerName, instanceID, modelVerifyResult); dbErr != nil {if permissionresponse.IsPermissionError(dbErr) {code, normalizedErr := permissionresponse.NormalizeHidden(dbErr)return code, normalizedErr@@ -1366,7 +1370,7 @@ func (m *ModelProviderService) CheckConnection(ctx context.Context, providerName// tenant_model table. It mirrors the Python update_model() called from the// /api/v1/providers/<name>/connection/verify endpoint when instance_id is// present in the request body.-func (m *ModelProviderService) updateModelVerifyResults(ctx context.Context, userID, providerName, instanceID string, modelVerifyResult map[string]string) error {+func (m *ModelProviderService) updateModelVerifyResults(ctx context.Context, providerName, instanceID string, modelVerifyResult map[string]string) error {instance, err := m.modelInstanceDAO.GetByID(ctx, dao.DB, instanceID)if err != nil {return fmt.Errorf("instance %s not found: %w", instanceID, err)@@ -1803,8 +1807,8 @@ func taskDriverConfig(provider *entity.TenantModelProvider, instance *entity.Tenreturn driver, apiConfig, nil}-func (m *ModelProviderService) ListTasks(ctx context.Context, providerName, instanceName, userID string) ([]modelModule.ListTaskStatus, common.ErrorCode, error) {- provider, instance, code, err := m.resolveAuthorizedInstance(ctx, userID, providerName, instanceName, permission.OperationUse)+func (m *ModelProviderService) ListTasks(ctx context.Context, providerName, instanceName string) ([]modelModule.ListTaskStatus, common.ErrorCode, error) {+ provider, instance, code, err := m.resolveAuthorizedInstance(ctx, providerName, instanceName, permission.OperationUse)if err != nil {return nil, code, err}@@ -1820,8 +1824,8 @@ func (m *ModelProviderService) ListTasks(ctx context.Context, providerName, instreturn listTaskResponse, common.CodeSuccess, nil}-func (m *ModelProviderService) ShowTask(ctx context.Context, providerName, instanceName, taskID, userID string) (*modelModule.TaskResponse, common.ErrorCode, error) {- provider, instance, code, err := m.resolveAuthorizedInstance(ctx, userID, providerName, instanceName, permission.OperationUse)+func (m *ModelProviderService) ShowTask(ctx context.Context, providerName, instanceName, taskID string) (*modelModule.TaskResponse, common.ErrorCode, error) {+ provider, instance, code, err := m.resolveAuthorizedInstance(ctx, providerName, instanceName, permission.OperationUse)if err != nil {return nil, code, err}@@ -1837,11 +1841,11 @@ func (m *ModelProviderService) ShowTask(ctx context.Context, providerName, instareturn taskResponse, common.CodeSuccess, nil}-// ListModelsForUserInTenant returns models available to userID in the requested+// ListModelsForUserInTenant returns models available to the current user in the requested// tenant context, filtered by the user's resource permissions. Provider and// instance configuration comes from the tenant owner.-func (m *ModelProviderService) ListModelsForUserInTenant(ctx context.Context, userID, requestedTenantID, modelTypeFilter string) ([]map[string]interface{}, common.ErrorCode, error) {- tenant, code, err := m.resolveModelListTenant(ctx, userID, requestedTenantID)+func (m *ModelProviderService) ListModelsForUserInTenant(ctx context.Context, requestedTenantID, modelTypeFilter string) ([]map[string]interface{}, common.ErrorCode, error) {+ tenant, code, err := m.resolveModelListTenant(ctx, requestedTenantID)if err != nil {return nil, code, err}@@ -1860,11 +1864,11 @@ func (m *ModelProviderService) ListModelsForUserInTenant(ctx context.Context, us// Mirror Python's ensure_*_from_env calls.if permission.NewDatabaseChecker(dao.DB).CheckTenant(ctx, tenantID, permission.TenantOwner) == nil {- _ = m.ensureMineruFromEnv(ctx, userID, tenantID)- _ = m.ensureMonkeyOCRv2FromEnv(ctx, userID, tenantID)- _ = m.ensureMonkeyOCRFromEnv(ctx, userID, tenantID)- _ = m.ensurePaddleOCREnabledFromEnv(ctx, userID, tenantID)- _ = m.ensureOpenDataLoaderFromEnv(ctx, userID, tenantID)+ _ = m.ensureMineruFromEnv(ctx, tenantID)+ _ = m.ensureMonkeyOCRv2FromEnv(ctx, tenantID)+ _ = m.ensureMonkeyOCRFromEnv(ctx, tenantID)+ _ = m.ensurePaddleOCREnabledFromEnv(ctx, tenantID)+ _ = m.ensureOpenDataLoaderFromEnv(ctx, tenantID)}var modelTypeFilterBin entity.ModelType@@ -2074,11 +2078,11 @@ func (m *ModelProviderService) ListModelsForUserInTenant(ctx context.Context, usreturn added, common.CodeSuccess, nil}-func (m *ModelProviderService) resolveModelListTenant(ctx context.Context, userID, requestedTenantID string) (*entity.Tenant, common.ErrorCode, error) {+func (m *ModelProviderService) resolveModelListTenant(ctx context.Context, requestedTenantID string) (*entity.Tenant, common.ErrorCode, error) {tenantID := requestedTenantIDif tenantID == "" {var err error- tenantID, err = requireCurrentTenantID(ctx, userID)+ tenantID, err = requireCurrentTenantID(ctx)if err != nil {if errors.Is(err, permission.ErrMembershipNotFound) {return nil, common.CodeSuccess, nil@@ -2105,31 +2109,31 @@ func (m *ModelProviderService) resolveModelListTenant(ctx context.Context, userI// ensureMineruFromEnv mirrors Python's ensure_mineru_from_env.// It ensures a MinerU OCR provider instance exists when env vars are configured.-func (m *ModelProviderService) ensureMineruFromEnv(ctx context.Context, userID, tenantID string) error {+func (m *ModelProviderService) ensureMineruFromEnv(ctx context.Context, tenantID string) error {config := collectEnvConfig(mineruEnvKeys, mineruDefaultConfig)- return m.ensureOCRProviderFromEnv(ctx, userID, tenantID, "MinerU", "mineru-from-env", config)+ return m.ensureOCRProviderFromEnv(ctx, tenantID, "MinerU", "mineru-from-env", config)}// ensurePaddleOCREnabledFromEnv mirrors Python's ensure_paddleocr_from_env.-func (m *ModelProviderService) ensurePaddleOCREnabledFromEnv(ctx context.Context, userID, tenantID string) error {+func (m *ModelProviderService) ensurePaddleOCREnabledFromEnv(ctx context.Context, tenantID string) error {config := collectEnvConfig(paddleOCREnvKeys, paddleOCRDefaultConfig)- return m.ensureOCRProviderFromEnv(ctx, userID, tenantID, "PaddleOCR", "paddleocr-from-env", config)+ return m.ensureOCRProviderFromEnv(ctx, tenantID, "PaddleOCR", "paddleocr-from-env", config)}// ensureOpenDataLoaderFromEnv mirrors Python's ensure_opendataloader_from_env.-func (m *ModelProviderService) ensureOpenDataLoaderFromEnv(ctx context.Context, userID, tenantID string) error {+func (m *ModelProviderService) ensureOpenDataLoaderFromEnv(ctx context.Context, tenantID string) error {config := collectEnvConfig(openDataLoaderEnvKeys, openDataLoaderDefaultConfig)- return m.ensureOCRProviderFromEnv(ctx, userID, tenantID, "OpenDataLoader", "opendataloader-from-env", config)+ return m.ensureOCRProviderFromEnv(ctx, tenantID, "OpenDataLoader", "opendataloader-from-env", config)}// ensureMonkeyOCRv2FromEnv mirrors Python's ensure_monkeyocrv2_from_env.-func (m *ModelProviderService) ensureMonkeyOCRv2FromEnv(ctx context.Context, userID, tenantID string) error {+func (m *ModelProviderService) ensureMonkeyOCRv2FromEnv(ctx context.Context, tenantID string) error {config := collectEnvConfig(monkeyOCRv2EnvKeys, monkeyOCRv2DefaultConfig)- return m.ensureOCRProviderFromEnv(ctx, userID, tenantID, "MonkeyOCRv2", "monkeyocrv2-from-env", config)+ return m.ensureOCRProviderFromEnv(ctx, tenantID, "MonkeyOCRv2", "monkeyocrv2-from-env", config)}// ensureMonkeyOCRFromEnv mirrors Python's ensure_monkeyocr_from_env.-func (m *ModelProviderService) ensureMonkeyOCRFromEnv(ctx context.Context, userID, tenantID string) error {+func (m *ModelProviderService) ensureMonkeyOCRFromEnv(ctx context.Context, tenantID string) error {config := collectEnvConfig(monkeyOCREnvKeys, monkeyOCRDefaultConfig)if config == nil {return nil@@ -2138,7 +2142,7 @@ func (m *ModelProviderService) ensureMonkeyOCRFromEnv(ctx context.Context, userIif strings.TrimSpace(apiserver) == "" {return nil}- return m.ensureOCRProviderFromEnv(ctx, userID, tenantID, "MonkeyOCR", "monkeyocr-from-env", config)+ return m.ensureOCRProviderFromEnv(ctx, tenantID, "MonkeyOCR", "monkeyocr-from-env", config)}// Environment-key/default tables mirror the Python OCR provider settings.@@ -2223,10 +2227,11 @@ func collectEnvConfig(envKeys []string, defaultConfig map[string]interface{}) ma// ensureOCRProviderFromEnv mirrors Python's _ensure_ocr_provider_from_env.// It finds or creates a provider, instance, and model for the given OCR provider.-func (m *ModelProviderService) ensureOCRProviderFromEnv(ctx context.Context, userID, tenantID, providerName, modelName string, config map[string]interface{}) error {+func (m *ModelProviderService) ensureOCRProviderFromEnv(ctx context.Context, tenantID, providerName, modelName string, config map[string]interface{}) error {if config == nil {return nil}+ userID := permission.UserIDFromContext(ctx)// 1. Find or create the provider.provider, err := m.modelProviderDAO.GetByTenantIDAndUserIDAndProviderName(ctx, dao.DB, tenantID, userID, providerName)@@ -2307,12 +2312,12 @@ func (m *ModelProviderService) ensureOCRProviderFromEnv(ctx context.Context, usereturn nil}-func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, userID, providerIDOrName, instanceIDOrName, newInstanceName string, apiKey json.RawMessage, clearAPIKey bool, baseURL, region string, modelInfo []CreateInstanceModelInfo) (common.ErrorCode, error) {+func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, providerIDOrName, instanceIDOrName, newInstanceName string, apiKey json.RawMessage, clearAPIKey bool, baseURL, region string, modelInfo []CreateInstanceModelInfo) (common.ErrorCode, error) {baseURL = strings.TrimSpace(baseURL)region = strings.TrimSpace(region)providerIDOrName = strings.TrimSpace(providerIDOrName)- provider, err := m.resolveProviderInTenant(ctx, userID, providerIDOrName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, providerIDOrName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -2492,13 +2497,13 @@ func (m *ModelProviderService) AlterProviderInstance(ctx context.Context, userIDreturn common.CodeSuccess, nil}-func (m *ModelProviderService) DropProviderInstances(ctx context.Context, providerIDOrName, userID string, instanceIDOrNames []string) (common.ErrorCode, error) {+func (m *ModelProviderService) DropProviderInstances(ctx context.Context, providerIDOrName string, instanceIDOrNames []string) (common.ErrorCode, error) {if len(instanceIDOrNames) == 0 {return common.CodeBadRequest, errors.New("instances is required")}// Find provider by ID or name inside the request's active tenant.- provider, err := m.resolveProviderInTenant(ctx, userID, providerIDOrName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, providerIDOrName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -2577,9 +2582,9 @@ func (m *ModelProviderService) DropProviderInstances(ctx context.Context, providreturn common.CodeSuccess, nil}-func (m *ModelProviderService) DropInstanceModels(ctx context.Context, providerIDOrName, instanceIDOrName, userID string, modelNames []string) (common.ErrorCode, error) {+func (m *ModelProviderService) DropInstanceModels(ctx context.Context, providerIDOrName, instanceIDOrName string, modelNames []string) (common.ErrorCode, error) {// Resolve the provider and instance inside the request's active tenant.- provider, err := m.resolveProviderInTenant(ctx, userID, providerIDOrName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, providerIDOrName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -2652,8 +2657,8 @@ func (m *ModelProviderService) DropInstanceModels(ctx context.Context, providerIreturn common.CodeSuccess, nil}-func (m *ModelProviderService) ListInstanceModels(ctx context.Context, providerName, instanceName, userID string) ([]map[string]interface{}, error) {- provider, err := m.resolveProviderInTenant(ctx, userID, providerName, permission.OperationRead)+func (m *ModelProviderService) ListInstanceModels(ctx context.Context, providerName, instanceName string) ([]map[string]interface{}, error) {+ provider, err := m.resolveProviderInTenant(ctx, providerName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {_, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -2747,7 +2752,7 @@ func (m *ModelProviderService) ListInstanceModels(ctx context.Context, providerNreturn modelList, nil}-func (m *ModelProviderService) AlterModel(ctx context.Context, providerName, instanceName, modelName, userID, modelID string, updateDict map[string]interface{}) (common.ErrorCode, error) {+func (m *ModelProviderService) AlterModel(ctx context.Context, providerName, instanceName, modelName, modelID string, updateDict map[string]interface{}) (common.ErrorCode, error) {modelName = strings.TrimSpace(modelName)modelID = strings.TrimSpace(modelID)if modelName == "" && modelID == "" {@@ -2762,7 +2767,7 @@ func (m *ModelProviderService) AlterModel(ctx context.Context, providerName, ins}// Check if provider exists- provider, err := m.resolveProviderInTenant(ctx, userID, providerName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, providerName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)@@ -2986,7 +2991,7 @@ type ModelRequest struct {Thinking *bool `json:"thinking"`}-func (m *ModelProviderService) AddModel(ctx context.Context, request *AddModelRequest, userID string) (common.ErrorCode, error) {+func (m *ModelProviderService) AddModel(ctx context.Context, request *AddModelRequest) (common.ErrorCode, error) {if request == nil {return common.CodeBadRequest, errors.New("request is required")}@@ -2997,7 +3002,7 @@ func (m *ModelProviderService) AddModel(ctx context.Context, request *AddModelRe}// Resolve the provider and instance inside the request's active tenant.- provider, err := m.resolveProviderInTenant(ctx, userID, request.ProviderName, permission.OperationRead)+ provider, err := m.resolveProviderInTenant(ctx, request.ProviderName, permission.OperationRead)if err != nil {if permissionresponse.IsPermissionError(err) {code, normalizedErr := permissionresponse.NormalizeHidden(err)diff --git a/internal/service/model_service_test.go b/internal/service/model_service_test.goindex 4b90c378fb..df2d99c40e 100644--- a/internal/service/model_service_test.go+++ b/internal/service/model_service_test.go@@ -77,7 +77,7 @@ func TestEnsureMonkeyOCRFromEnvSkipsBlankAPIServer(t *testing.T) {t.Setenv(common.EnvMonkeyOCRAPIServer, "")svc := &ModelProviderService{}- if err := svc.ensureMonkeyOCRFromEnv(context.Background(), "user-id", "tenant-id"); err != nil {+ if err := svc.ensureMonkeyOCRFromEnv(context.Background(), "tenant-id"); err != nil {t.Fatalf("ensureMonkeyOCRFromEnv: %v", err)}}@@ -515,7 +515,6 @@ func TestBedrockAPIKeyInstancePersistsDiscoveredModelsWithoutRuntimeVerificationapiKey,"","default",- "user-1",[]CreateInstanceModelInfo{{ModelName: "amazon.nova-lite-v1:0",ModelTypes: []string{"chat", "vision"},@@ -541,7 +540,6 @@ func TestBedrockAPIKeyInstancePersistsDiscoveredModelsWithoutRuntimeVerification}code, err = NewModelProviderService().AlterProviderInstance(serviceTestContext(t, "user-1", "tenant-bedrock"),- "user-1","Bedrock","api-key-instance","api-key-instance",@@ -587,7 +585,6 @@ func TestCreateProviderInstanceRollsBackInstanceWhenModelCreationFails(t *testin"sk-rollback","","default",- "user-1",[]CreateInstanceModelInfo{duplicated, duplicated},)if code != common.CodeServerError || err == nil {@@ -610,7 +607,7 @@ func TestCreateProviderInstanceRollsBackInstanceWhenModelCreationFails(t *testint.Fatalf("models = %d, want 0 after rollback", modelCount)}code, err = NewModelProviderService().CreateProviderInstance(- serviceTestContext(t, "user-1", "user-1"), "OpenAI", "broken-instance", "sk-rollback", "", "default", "user-1",+ serviceTestContext(t, "user-1", "user-1"), "OpenAI", "broken-instance", "sk-rollback", "", "default",[]CreateInstanceModelInfo{duplicated, {ModelName: "gpt-second", ModelTypes: []string{"chat"}}},)if code != common.CodeSuccess || err != nil {@@ -635,7 +632,7 @@ func TestModelProviderServiceAlterModelStatusByID(t *testing.T) {seedModelProviderServiceScope(t, db)ctx := serviceTestContext(t, "user-1", "user-1")- code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "default", "", "user-1", "model-1", map[string]interface{}{"status": "inactive"})+ code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "default", "", "model-1", map[string]interface{}{"status": "inactive"})if err != nil {t.Fatalf("AlterModel() error = %v", err)}@@ -668,7 +665,7 @@ func TestListProvidersOfTenantExcludesOtherTenants(t *testing.T) {}}- providers, code, err := NewModelProviderService().ListProvidersOfTenant(serviceTestContext(t, "user-1", "user-1"), "user-1")+ providers, code, err := NewModelProviderService().ListProvidersOfTenant(serviceTestContext(t, "user-1", "user-1"))if err != nil || code != common.CodeSuccess {t.Fatalf("ListProvidersOfTenant() = (%v, %v), want success", code, err)}@@ -695,7 +692,7 @@ func TestListProviderInstancesUsesOwnedTenantProvider(t *testing.T) {}service := NewModelProviderService()- instances, code, err := service.ListProviderInstances(serviceTestContext(t, "user-1", "user-1"), "OpenAI", "user-1")+ instances, code, err := service.ListProviderInstances(serviceTestContext(t, "user-1", "user-1"), "OpenAI")if err != nil || code != common.CodeSuccess {t.Fatalf("ListProviderInstances() = (%v, %v), want success", code, err)}@@ -703,7 +700,7 @@ func TestListProviderInstancesUsesOwnedTenantProvider(t *testing.T) {t.Fatalf("ListProviderInstances() = %v, want only the instance from user-1's own tenant", instances)}- if instances, code, err = service.ListProviderInstances(serviceTestContext(t, "user-1", "user-1"), "provider-2", "user-1"); err == nil || len(instances) != 0 {+ if instances, code, err = service.ListProviderInstances(serviceTestContext(t, "user-1", "user-1"), "provider-2"); err == nil || len(instances) != 0 {t.Fatalf("ListProviderInstances() for another tenant's provider = (%v, %v, %v), want it hidden", instances, code, err)}}@@ -727,7 +724,7 @@ func TestProviderModelListingUsesOwnedTenant(t *testing.T) {}service := NewModelProviderService()- models, err := service.ListInstanceModels(serviceTestContext(t, "user-1", "user-1"), "OpenAI", "default", "user-1")+ models, err := service.ListInstanceModels(serviceTestContext(t, "user-1", "user-1"), "OpenAI", "default")if err != nil {t.Fatalf("ListInstanceModels() error = %v, want success", err)}@@ -735,10 +732,10 @@ func TestProviderModelListingUsesOwnedTenant(t *testing.T) {t.Fatalf("ListInstanceModels() = %v, want only user-1's own-tenant model", models)}- if _, err = service.ListInstanceModels(serviceTestContext(t, "user-1", "user-1"), "provider-2", "default", "user-1"); !errors.Is(err, gorm.ErrRecordNotFound) {+ if _, err = service.ListInstanceModels(serviceTestContext(t, "user-1", "user-1"), "provider-2", "default"); !errors.Is(err, gorm.ErrRecordNotFound) {t.Fatalf("ListInstanceModels() for another tenant's provider error = %v, want record not found", err)}- if _, err = service.ResolveSavedProviderModelConfig(serviceTestContext(t, "user-1", "user-1"), "provider-2", "default", "user-1", SavedProviderModelOptions{}); !errors.Is(err, gorm.ErrRecordNotFound) {+ if _, err = service.ResolveSavedProviderModelConfig(serviceTestContext(t, "user-1", "user-1"), "provider-2", "default", SavedProviderModelOptions{}); !errors.Is(err, gorm.ErrRecordNotFound) {t.Fatalf("ResolveSavedProviderModelConfig() for another tenant's provider error = %v, want record not found", err)}}@@ -762,7 +759,7 @@ func TestShowProviderInstanceUsesOwnedTenantProvider(t *testing.T) {service := NewModelProviderService()ctx := serviceTestContext(t, "user-1", "user-1")- instance, code, err := service.ShowProviderInstance(ctx, "OpenAI", "instance-1", "user-1")+ instance, code, err := service.ShowProviderInstance(ctx, "OpenAI", "instance-1")if err != nil || code != common.CodeSuccess {t.Fatalf("ShowProviderInstance() = (%v, %v), want success", code, err)}@@ -782,7 +779,7 @@ func TestShowProviderInstanceUsesOwnedTenantProvider(t *testing.T) {t.Fatalf("ShowProviderInstance() credential_status = %v, want api_key configured", instance["credential_status"])}- if _, code, err = service.ShowProviderInstance(ctx, "provider-2", "instance-2", "user-1"); err == nil || code != common.CodeNotFound {+ if _, code, err = service.ShowProviderInstance(ctx, "provider-2", "instance-2"); err == nil || code != common.CodeNotFound {t.Fatalf("ShowProviderInstance() for another tenant's provider = (%v, %v), want hidden provider", code, err)}}@@ -883,7 +880,7 @@ func TestResolveSavedProviderModelConfigUsePermissionCannotOverrideSavedEndpoint}service := NewModelProviderService()ctx := serviceTestContext(t, "member-1", "tenant-1")- config, err := service.ResolveSavedProviderModelConfig(ctx, "OpenAI", "default", "member-1", SavedProviderModelOptions{})+ config, err := service.ResolveSavedProviderModelConfig(ctx, "OpenAI", "default", SavedProviderModelOptions{})if err != nil {t.Fatalf("ResolveSavedProviderModelConfig(use saved credentials) error = %v, want success", err)}@@ -892,12 +889,12 @@ func TestResolveSavedProviderModelConfigUsePermissionCannotOverrideSavedEndpoint}attackerURL := "https://attacker.example"- _, err = service.ResolveSavedProviderModelConfig(ctx, "OpenAI", "default", "member-1", SavedProviderModelOptions{BaseURL: &attackerURL})+ _, err = service.ResolveSavedProviderModelConfig(ctx, "OpenAI", "default", SavedProviderModelOptions{BaseURL: &attackerURL})if err == nil || !errors.Is(err, permission.ErrPermissionDenied) {t.Fatalf("ResolveSavedProviderModelConfig(use permission with endpoint override) error = %v, want hidden denial", err)}- _, err = service.ResolveSavedProviderModelConfig(ctx, "OpenAI", "default", "member-1", SavedProviderModelOptions{+ _, err = service.ResolveSavedProviderModelConfig(ctx, "OpenAI", "default", SavedProviderModelOptions{APIKeyConfig: json.RawMessage(`{"paddleocr_api_url":"https://attacker.example"}`),})if err == nil || !errors.Is(err, permission.ErrPermissionDenied) {@@ -905,13 +902,13 @@ func TestResolveSavedProviderModelConfigUsePermissionCannotOverrideSavedEndpoint}ownerCtx := serviceTestContext(t, "user-1", "tenant-1")- ownerInstance, code, err := service.ShowProviderInstance(ownerCtx, "OpenAI", "default", "user-1")+ ownerInstance, code, err := service.ShowProviderInstance(ownerCtx, "OpenAI", "default")if err != nil || code != common.CodeSuccess || ownerInstance["is_owner"] != true {t.Fatalf("ShowProviderInstance(owner) = (%v, %v, %v), want owner metadata", ownerInstance, code, err)}ownerURL := "https://owner-override.example"ownerRegion := "eu-west-1"- ownerConfig, err := service.ResolveSavedProviderModelConfig(ownerCtx, "OpenAI", "default", "user-1", SavedProviderModelOptions{+ ownerConfig, err := service.ResolveSavedProviderModelConfig(ownerCtx, "OpenAI", "default", SavedProviderModelOptions{APIKeyConfig: json.RawMessage(`{"group_id":"owner-group"}`),BaseURL: &ownerURL,Region: &ownerRegion,@@ -953,7 +950,7 @@ func TestCheckConnectionDeniesBeforeCallingProvider(t *testing.T) {APIKey: json.RawMessage(`"sk-test"`),Region: "default",InstanceID: "instance-1",- }, "member-1")+ })if err == nil || code != common.CodeNotFound {t.Fatalf("CheckConnection() = (%v, %v), want hidden update denial", code, err)}@@ -992,7 +989,7 @@ func TestCheckConnectionUsesStoredCredentialsAndAllowsOwnerOverrides(t *testing.UseSavedCredentials: true,InstanceID: "instance-1",ModelInfo: modelInfo,- }, "user-1")+ })if err != nil || code != common.CodeSuccess {t.Fatalf("CheckConnection(saved) = (%v, %v), want success", code, err)}@@ -1007,7 +1004,7 @@ func TestCheckConnectionUsesStoredCredentialsAndAllowsOwnerOverrides(t *testing.BaseURL: "https://attacker.example",InstanceID: "instance-1",ModelInfo: modelInfo,- }, "user-1")+ })if err != nil || code != common.CodeSuccess {t.Fatalf("CheckConnection(custom endpoint) = (%v, %v), want provider probe success", code, err)}@@ -1025,7 +1022,7 @@ func TestCheckConnectionUsesStoredCredentialsAndAllowsOwnerOverrides(t *testing.APIKeyConfig: json.RawMessage(`{"group_id":"owner-group"}`),InstanceID: "instance-1",ModelInfo: modelInfo,- }, "user-1")+ })if err != nil || code != common.CodeSuccess {t.Fatalf("CheckConnection(owner saved credential overrides) = (%v, %v), want success", code, err)}@@ -1043,7 +1040,7 @@ func TestModelFactoryResolveModelConfigByID(t *testing.T) {seedModelProviderServiceScope(t, db)ctx := serviceTestContext(t, "user-1", "user-1")- target, err := NewModelFactory().resolveConfig(ctx, Identity{TenantID: "user-1", UserID: "user-1"}, entity.ModelTypeChat, "model-1")+ target, err := NewModelFactory().resolveConfig(permission.WithTenantID(ctx, "user-1"), entity.ModelTypeChat, "model-1")if err != nil {t.Fatalf("resolveConfig() error = %v", err)}@@ -1076,7 +1073,7 @@ func TestModelProviderServiceMissingProviderAndInstancePreserveLookupError(t *te} {t.Run(modelRef, func(t *testing.T) {_, err := NewModelFactory().resolveConfig(- serviceTestContext(t, "user-1", "tenant-1"), Identity{TenantID: "tenant-1"}, entity.ModelTypeEmbedding, modelRef,+ permission.WithTenantID(serviceTestContext(t, "user-1", "tenant-1"), "tenant-1"), entity.ModelTypeEmbedding, modelRef,)if !errors.Is(err, errModelConfigUnavailable) || !errors.Is(err, gorm.ErrRecordNotFound) {t.Fatalf("resolveConfig() error = %v, want unavailable record-not-found error", err)@@ -1103,13 +1100,13 @@ func TestModelProviderServiceDecodesCompatibleInstanceExtra(t *testing.T) {{name: "model ID",resolve: func() (*modelTarget, error) {- return solver.resolveConfig(serviceTestContext(t, "user-1", "user-1"), Identity{TenantID: "user-1", UserID: "user-1"}, entity.ModelTypeChat, "model-1")+ return solver.resolveConfig(permission.WithTenantID(serviceTestContext(t, "user-1", "user-1"), "user-1"), entity.ModelTypeChat, "model-1")},},{name: "provider instance",resolve: func() (*modelTarget, error) {- return solver.resolveConfig(serviceTestContext(t, "user-1", "user-1"), Identity{TenantID: "user-1"}, entity.ModelTypeChat, "gpt-test@default@OpenAI")+ return solver.resolveConfig(permission.WithTenantID(serviceTestContext(t, "user-1", "user-1"), "user-1"), entity.ModelTypeChat, "gpt-test@default@OpenAI")},},}@@ -1168,7 +1165,7 @@ func TestModelInfoSeparatesContextLengthAndMaxOutput(t *testing.T) {func TestModelProviderServiceAlterModelRejectsInvalidStatus(t *testing.T) {ctx := serviceTestContext(t, "user-1", "tenant-1")- code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "default", "", "user-1", "model-1", map[string]interface{}{"status": "disabled"})+ code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "default", "", "model-1", map[string]interface{}{"status": "disabled"})if err == nil {t.Fatalf("AlterModel() error = nil, want invalid status error")}@@ -1182,7 +1179,7 @@ func TestModelProviderServiceAlterModelRejectsInvalidStatus(t *testing.T) {func TestModelProviderServiceAlterModelRejectsMissingModelSelector(t *testing.T) {ctx := serviceTestContext(t, "user-1", "tenant-1")- code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "default", "", "user-1", "", map[string]interface{}{"status": "active"})+ code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "default", "", "", map[string]interface{}{"status": "active"})if err == nil {t.Fatalf("AlterModel() error = nil, want missing model selector error")}@@ -1203,7 +1200,7 @@ func TestModelProviderServiceAlterModelRejectsWrongScopedModelID(t *testing.T) {}ctx := serviceTestContext(t, "user-1", "user-1")- code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "other", "", "user-1", "model-1", map[string]interface{}{"status": "inactive"})+ code, err := NewModelProviderService().AlterModel(ctx, "OpenAI", "other", "", "model-1", map[string]interface{}{"status": "inactive"})if err == nil {t.Fatalf("AlterModel() error = nil, want not found error")}@@ -1384,7 +1381,7 @@ func TestModelFactoryResolveModelConfigReportsToolSupport(t *testing.T) {ctx := serviceTestContext(t, "user-1", "tenant-1")// A reference that passes validation still reads the persisted flag.- target, err := solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, "model-active")+ target, err := solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, "model-active")if err != nil || target == nil || !target.SupportsTools {t.Fatalf("active chat model = (%v, %v), want tool support", target, err)}@@ -1397,7 +1394,7 @@ func TestModelFactoryResolveModelConfigReportsToolSupport(t *testing.T) {{"not enrolled as chat", "model-embedding"},{"provider owned by another tenant", "model-foreign"},} {- target, err := solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, tc.modelID)+ target, err := solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, tc.modelID)if err == nil {t.Errorf("%s: err = nil, want a validation error", tc.name)}@@ -1458,7 +1455,7 @@ func TestModelFactoryResolveModelConfigPrefersTenantToolFlag(t *testing.T) {solver := NewModelFactory()ctx := serviceTestContext(t, "user-1", "tenant-1")- target, err := solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, toolsOn+"@default@OpenAI")+ target, err := solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, toolsOn+"@default@OpenAI")if err != nil {t.Fatalf("tool-capable model: err = %v", err)}@@ -1466,7 +1463,7 @@ func TestModelFactoryResolveModelConfigPrefersTenantToolFlag(t *testing.T) {t.Errorf("tool support = true, want false: the tenant_model flag must win over the catalog")}- target, err = solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, toolsOff+"@default@OpenAI")+ target, err = solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, toolsOff+"@default@OpenAI")if err != nil {t.Fatalf("tool-incapable model: err = %v", err)}@@ -1474,7 +1471,7 @@ func TestModelFactoryResolveModelConfigPrefersTenantToolFlag(t *testing.T) {t.Errorf("tool support = false, want true: the tenant_model flag must win over the catalog")}- target, err = solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, toolsOn+"-disabled@default@OpenAI")+ target, err = solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, toolsOn+"-disabled@default@OpenAI")if err == nil || (target != nil && target.SupportsTools) {t.Errorf("disabled model = (%v, %v), want (false, error)", target, err)}@@ -1500,7 +1497,7 @@ func TestModelFactoryResolveModelConfigPropagatesLookupFailure(t *testing.T) {solver := NewModelFactory()ctx := serviceTestContext(t, "user-1", "tenant-1")- if target, err := solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, "model-1"); err != nil || target == nil || !target.SupportsTools {+ if target, err := solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, "model-1"); err != nil || target == nil || !target.SupportsTools {t.Fatalf("baseline = (%v, %v), want tool support", target, err)}@@ -1511,11 +1508,11 @@ func TestModelFactoryResolveModelConfigPropagatesLookupFailure(t *testing.T) {t.Fatalf("failed to drop provider table: %v", err)}// Composite refs resolve the provider row directly.- if target, err := solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, "gpt-test@default@OpenAI"); err == nil {+ if target, err := solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, "gpt-test@default@OpenAI"); err == nil {t.Errorf("composite provider lookup failure = (%v, nil), want a propagated error", target)}// The UUID path too.- if target, err := solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, "model-1"); err == nil {+ if target, err := solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, "model-1"); err == nil {t.Errorf("uuid provider lookup failure = (%v, nil), want a propagated error", target)}@@ -1523,7 +1520,7 @@ func TestModelFactoryResolveModelConfigPropagatesLookupFailure(t *testing.T) {if err := db.Migrator().DropTable(&entity.TenantModel{}); err != nil {t.Fatalf("failed to drop model table: %v", err)}- if target, err := solver.resolveConfig(ctx, Identity{TenantID: "tenant-1"}, entity.ModelTypeChat, "model-1"); err == nil {+ if target, err := solver.resolveConfig(permission.WithTenantID(ctx, "tenant-1"), entity.ModelTypeChat, "model-1"); err == nil {t.Errorf("model lookup failure = (%v, nil), want a propagated error", target)}}@@ -1549,7 +1546,7 @@ func TestDropProviderInstancesRollsBackWhenInstanceDeleteFails(t *testing.T) {_ = db.Callback().Delete().Remove("test:fail_tenant_model_instance_delete")})- code, err := NewModelProviderService().DropProviderInstances(serviceTestContext(t, "user-1", "user-1"), "provider-1", "user-1", []string{"instance-1"})+ code, err := NewModelProviderService().DropProviderInstances(serviceTestContext(t, "user-1", "user-1"), "provider-1", []string{"instance-1"})if err == nil {t.Fatalf("DropProviderInstances() error = nil, want forced instance delete failure")}@@ -1616,7 +1613,6 @@ func TestAlterProviderInstanceUsesActiveTenantProvider(t *testing.T) {code, err := NewModelProviderService().AlterProviderInstance(serviceTestContext(t, "user-1", "tenant-2"),- "user-1","DeepSeek","instance-2","ds",@@ -1683,7 +1679,6 @@ func TestAlterProviderInstanceReportsInstanceProviderMismatch(t *testing.T) {code, err := NewModelProviderService().AlterProviderInstance(serviceTestContext(t, "user-1", "tenant-2"),- "user-1","OpenAI","instance-deepseek","ds",@@ -1726,14 +1721,14 @@ func TestAlterProviderInstanceScopesToActiveTenant(t *testing.T) {service := NewModelProviderService()if code, err := service.AlterProviderInstance(serviceTestContext(t, "user-1", "tenant-2"),- "user-1", "DeepSeek", "instance-2", "ds", json.RawMessage(`"sk-from-tenant-2"`), false, "", "",+ "DeepSeek", "instance-2", "ds", json.RawMessage(`"sk-from-tenant-2"`), false, "", "",[]CreateInstanceModelInfo{{ModelName: "model-2", ModelTypes: []string{"chat"}, MaxTokens: 8192}},); err != nil || code != common.CodeSuccess {t.Fatalf("AlterProviderInstance(tenant-2) = (%v, %v), want success", code, err)}if code, err := service.AlterProviderInstance(serviceTestContext(t, "user-1", "tenant-1"),- "user-1", "DeepSeek", "instance-1", "ds", json.RawMessage(`"sk-from-tenant-1"`), false, "", "",+ "DeepSeek", "instance-1", "ds", json.RawMessage(`"sk-from-tenant-1"`), false, "", "",[]CreateInstanceModelInfo{{ModelName: "model-1", ModelTypes: []string{"chat"}, MaxTokens: 8192}},); err != nil || code != common.CodeSuccess {t.Fatalf("AlterProviderInstance(tenant-1) = (%v, %v), want success", code, err)@@ -1772,7 +1767,6 @@ func TestAddModelUsesActiveTenantProvider(t *testing.T) {code, err := NewModelProviderService().AddModel(serviceTestContext(t, "user-1", "tenant-2"),&AddModelRequest{ProviderName: "DeepSeek", InstanceName: "instance-2", ModelName: "added-model", ModelTypes: []string{"chat"}, MaxTokens: 1024},- "user-1",)if err != nil {t.Fatalf("AddModel() error = %v", err)@@ -1799,7 +1793,7 @@ func TestCreateProviderInstanceUsesActiveTenantProvider(t *testing.T) {code, err := NewModelProviderService().CreateProviderInstance(serviceTestContext(t, "user-1", "tenant-2"),- "DeepSeek", "created-in-tenant-2", "sk-created", "", "default", "user-1",+ "DeepSeek", "created-in-tenant-2", "sk-created", "", "default",[]CreateInstanceModelInfo{{ModelName: "deepseek-v4-pro", ModelTypes: []string{"chat"}, MaxTokens: 8192}},)if err != nil {diff --git a/internal/service/model_service_tts_test.go b/internal/service/model_service_tts_test.goindex 98d4d4e069..a14e0a579b 100644--- a/internal/service/model_service_tts_test.go+++ b/internal/service/model_service_tts_test.go@@ -23,6 +23,7 @@ import ("ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"+ "ragflow/internal/permission")// insertTTSTestTenant inserts a tenant and owner membership; ttsID may be nil (no default@@ -82,7 +83,7 @@ func TestResolveDefaultModelConfig_NilTTSPointer(t *testing.T) {pushServiceDB(t, testDB)insertTTSTestTenant(t, "tenant-2", nil)- _, err := NewModelFactory().resolveDefaultConfig(t.Context(), Identity{TenantID: "tenant-2"}, entity.ModelTypeTTS)+ _, err := NewModelFactory().resolveDefaultConfig(permission.WithTenantID(t.Context(), "tenant-2"), entity.ModelTypeTTS)if err == nil {t.Fatal("expected error for nil tts_id, got nil")}diff --git a/internal/service/model_stored_provider_name_test.go b/internal/service/model_stored_provider_name_test.goindex 9f5c15a811..28997614e0 100644--- a/internal/service/model_stored_provider_name_test.go+++ b/internal/service/model_stored_provider_name_test.go@@ -23,6 +23,7 @@ import ("ragflow/internal/common""ragflow/internal/entity"+ "ragflow/internal/permission")// mistralOCRStoredKey is the api_key Python's "Mistral OCR" factory stored when@@ -58,7 +59,6 @@ func TestModelFactoryResolvesStoredMistralOCRProvider(t *testing.T) {useModelProviderServiceTestDB(t, db)seedStoredMistralOCRProvider(t, db)- access := Identity{TenantID: "user-1", UserID: "user-1"}for _, tc := range []struct {name stringmodelRef string@@ -69,7 +69,7 @@ func TestModelFactoryResolvesStoredMistralOCRProvider(t *testing.T) {{name: "catalog composite", modelRef: "mistral-ocr-2512@default@Mistral OCR", wantModel: "mistral-ocr-2512"},} {t.Run(tc.name, func(t *testing.T) {- target, err := NewModelFactory().resolveConfig(serviceTestContext(t, "user-1", "user-1"), access, entity.ModelTypeOCR, tc.modelRef)+ target, err := NewModelFactory().resolveConfig(serviceTestContext(t, "user-1", "user-1"), entity.ModelTypeOCR, tc.modelRef)if err != nil {t.Fatalf("resolveConfig(%q): %v", tc.modelRef, err)}@@ -96,7 +96,7 @@ func TestModelFactoryResolveModelTypeForStoredMistralOCRProvider(t *testing.T) {useModelProviderServiceTestDB(t, db)seedStoredMistralOCRProvider(t, db)- types, err := NewModelFactory().ResolveModelType(serviceTestContext(t, "user-1", "user-1"), Identity{TenantID: "user-1", UserID: "user-1"}, "mistral-ocr-2512@default@Mistral OCR")+ types, err := NewModelFactory().ResolveModelType(permission.WithTenantID(serviceTestContext(t, "user-1", "user-1"), "user-1"), "mistral-ocr-2512@default@Mistral OCR")if err != nil {t.Fatalf("ResolveModelType: %v", err)}@@ -124,7 +124,7 @@ func TestModelFactoryResolvesStoredMistralOCRCapability(t *testing.T) {factory := NewModelFactory()for _, modelRef := range []string{"model-mistral-ocr", "mistral-ocr-latest@default@Mistral OCR"} {t.Run(modelRef, func(t *testing.T) {- target, err := factory.resolveConfig(serviceTestContext(t, "user-1", "user-1"), Identity{TenantID: "user-1", UserID: "user-1"}, 0, modelRef)+ target, err := factory.resolveConfig(permission.WithTenantID(serviceTestContext(t, "user-1", "user-1"), "user-1"), 0, modelRef)if err != nil {t.Fatalf("resolve model %q: %v", modelRef, err)}@@ -151,7 +151,7 @@ func TestListProvidersOfTenantSkipsStoredMistralOCRProvider(t *testing.T) {t.Fatalf("create provider: %v", err)}- providers, code, err := NewModelProviderService().ListProvidersOfTenant(serviceTestContext(t, "user-1", "user-1"), "user-1")+ providers, code, err := NewModelProviderService().ListProvidersOfTenant(serviceTestContext(t, "user-1", "user-1"))if err != nil || code != common.CodeSuccess {t.Fatalf("ListProvidersOfTenant = (%v, %v)", code, err)}diff --git a/internal/service/nav_embedder.go b/internal/service/nav_embedder.goindex 0562794a43..49c77feca2 100644--- a/internal/service/nav_embedder.go+++ b/internal/service/nav_embedder.go@@ -19,7 +19,9 @@ package serviceimport ("context""fmt"+modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission""strings")@@ -59,12 +61,11 @@ func (e *NavEmbedder) encode(ctx context.Context, tenantID string, texts []strin}name := e.embdModelNamevar model *modelModule.EmbeddingModel- access := Identity{TenantID: tenantID}var err errorif name == "" {- model, err = e.modelFactory.NewDefaultEmbeddingModel(ctx, access)+ model, err = e.modelFactory.NewDefaultEmbeddingModel(permission.WithTenantID(ctx, tenantID))} else {- model, err = e.modelFactory.NewEmbeddingModel(ctx, access, name)+ model, err = e.modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), name)}if err != nil {return nil, fmt.Errorf("datasetnav: resolve embedding model for tenant %s: %w", tenantID, err)diff --git a/internal/service/nav_merge_llm.go b/internal/service/nav_merge_llm.goindex f490de365e..989dbad2f2 100644--- a/internal/service/nav_merge_llm.go+++ b/internal/service/nav_merge_llm.go@@ -24,6 +24,7 @@ import (modelModule "ragflow/internal/entity/models"kccommon "ragflow/internal/ingestion/component/knowledge_compiler/common"+ "ragflow/internal/permission")// navNamingTemperature is the decoding temperature Python pins for both cluster@@ -225,15 +226,14 @@ func navChatText(ctx context.Context, modelFactory *ModelFactory, tenantID, modeif modelFactory == nil {return "", fmt.Errorf("datasetnav: model factory not initialized")}- access := Identity{TenantID: tenantID}var (chatModel *modelModule.ChatModelerr error)if strings.TrimSpace(modelRef) == "" {- chatModel, err = modelFactory.NewDefaultChatModel(ctx, access)+ chatModel, err = modelFactory.NewDefaultChatModel(permission.WithTenantID(ctx, tenantID))} else {- chatModel, err = modelFactory.NewChatModel(ctx, access, modelRef)+ chatModel, err = modelFactory.NewChatModel(permission.WithTenantID(ctx, tenantID), modelRef)}if err != nil {return "", errdiff --git a/internal/service/openai_chat.go b/internal/service/openai_chat.goindex 970f98a24a..14b9ff4af9 100644--- a/internal/service/openai_chat.go+++ b/internal/service/openai_chat.go@@ -25,9 +25,9 @@ import ("strings""time"- "ragflow/internal/entity"-"ragflow/internal/common"+ "ragflow/internal/entity"+ "ragflow/internal/permission"permissionresponse "ragflow/internal/permission/response""ragflow/internal/tokenizer"@@ -139,7 +139,7 @@ type OpenAIChatRequest struct {MaxTokens *int `json:"max_tokens,omitempty"`}-func (s *OpenAIChatService) OpenAIChatCompletions(c *gin.Context, userID, chatID string, bodyBytes []byte) {+func (s *OpenAIChatService) OpenAIChatCompletions(c *gin.Context, chatID string, bodyBytes []byte) {var req OpenAIChatRequestif err := json.Unmarshal(bodyBytes, &req); err != nil {s.writeArgError(c, err.Error())@@ -248,7 +248,7 @@ func (s *OpenAIChatService) OpenAIChatCompletions(c *gin.Context, userID, chatIDreturn}dialog := dialogResp.Chat- if err := validateChatDatasetAccess(ctx, userID, dialog.KBIDs); err != nil {+ if err := validateChatDatasetAccess(ctx, dialog.KBIDs); err != nil {code, permissionErr := permissionresponse.NormalizeHidden(err)common.RespondError(c, code, permissionErr.Error())return@@ -261,7 +261,7 @@ func (s *OpenAIChatService) OpenAIChatCompletions(c *gin.Context, userID, chatID}}if req.Model != "model" {- if _, mErr := s.pipeline.ModelFactory.ResolveInfo(ctx, Identity{UserID: userID, TenantID: dialog.TenantID}, entity.ModelTypeChat, resolvedModel); mErr != nil {+ if _, mErr := s.pipeline.ModelFactory.ResolveInfo(permission.WithTenantID(ctx, dialog.TenantID), entity.ModelTypeChat, resolvedModel); mErr != nil {s.writeArgError(c, fmt.Sprintf("`llm_id` %s doesn't exist", req.Model))return}@@ -288,7 +288,7 @@ func (s *OpenAIChatService) OpenAIChatCompletions(c *gin.Context, userID, chatIDcompletionID := fmt.Sprintf("chatcmpl-%s", openaiReq.ChatID)- lfClient := LangfuseClientFromTenant(ctx, dialog.TenantID, userID, openaiReq.ChatID, openaiReq.Model)+ lfClient := LangfuseClientFromTenant(ctx, dialog.TenantID, openaiReq.ChatID, openaiReq.Model)if lfClient != nil {ctx = context.WithValue(ctx, langfuseCtxKey, lfClient)defer func() {@@ -335,7 +335,7 @@ func (s *OpenAIChatService) OpenAIChatCompletions(c *gin.Context, userID, chatID}chatKwargs := openAIChatKwargs(&req, needReference, docIDsStr)- asyncResults, asyncErr := s.pipeline.AsyncChat(ctx, userID, dialog, filteredMessages, openaiReq.Stream, chatKwargs)+ asyncResults, asyncErr := s.pipeline.AsyncChat(ctx, dialog, filteredMessages, openaiReq.Stream, chatKwargs)if asyncErr != nil {s.writeDataError(c, asyncErr.Error())returndiff --git a/internal/service/related_question.go b/internal/service/related_question.goindex 0f55c82c6a..6db4b187d4 100644--- a/internal/service/related_question.go+++ b/internal/service/related_question.go@@ -26,6 +26,7 @@ import ("ragflow/internal/entity"modelModule "ragflow/internal/entity/models"+ "ragflow/internal/permission""ragflow/internal/rag/prompts")@@ -34,14 +35,17 @@ func GenerateRelatedQuestions(ctx context.Context, question, searchID string, seif modelFactory == nil {return nil, fmt.Errorf("model factory not configured")}- searchConfig, err := relatedQuestionsSearchConfig(ctx, searchID, searchSvc)+ searchConfig, tenantID, err := relatedQuestionsSearchConfig(ctx, searchID, searchSvc)if err != nil {return nil, err}- access, err := ResolveIdentity(ctx)- if err != nil {- return nil, err+ if tenantID == "" {+ tenantID, err = requireCurrentTenantID(ctx)+ if err != nil {+ return nil, err+ }}+ modelCtx := permission.WithTenantID(ctx, tenantID)modelID, _ := searchConfig["chat_id"].(string)prompt, err := (prompts.EmbeddedPromptLoader{}).Load("related_question")if err != nil {@@ -53,12 +57,12 @@ func GenerateRelatedQuestions(ctx context.Context, question, searchID string, se}var chatModel *modelModule.ChatModelif modelID == "" {- chatModel, err = modelFactory.NewDefaultChatModel(ctx, access)+ chatModel, err = modelFactory.NewDefaultChatModel(modelCtx)if errors.Is(err, ErrNoDefaultModel) {return nil, fmt.Errorf("no chat model configured")}} else {- chatModel, err = modelFactory.NewChatModel(ctx, access, modelID)+ chatModel, err = modelFactory.NewChatModel(modelCtx, modelID)}if err != nil {return nil, err@@ -73,18 +77,19 @@ func GenerateRelatedQuestions(ctx context.Context, question, searchID string, sereturn []string{}, nil}-func relatedQuestionsSearchConfig(ctx context.Context, searchID string, searchSvc *SearchService) (map[string]interface{}, error) {+func relatedQuestionsSearchConfig(ctx context.Context, searchID string, searchSvc *SearchService) (map[string]interface{}, string, error) {if searchID == "" {- return map[string]interface{}{}, nil+ return map[string]interface{}{}, "", nil}if searchSvc == nil {- return nil, fmt.Errorf("search service not configured")+ return nil, "", fmt.Errorf("search service not configured")}detail, err := searchSvc.GetDetail(ctx, searchID)if err != nil {- return nil, err+ return nil, "", err}- return relatedQuestionsSearchConfigFromDetail(detail), nil+ tenantID, _ := detail["tenant_id"].(string)+ return relatedQuestionsSearchConfigFromDetail(detail), strings.TrimSpace(tenantID), nil}func relatedQuestionsSearchConfigFromDetail(detail map[string]interface{}) map[string]interface{} {diff --git a/internal/service/search.go b/internal/service/search.goindex af55c4791c..408150324e 100644--- a/internal/service/search.go+++ b/internal/service/search.go@@ -22,6 +22,7 @@ import ("strings""gorm.io/gorm"+"ragflow/internal/common""ragflow/internal/dao""ragflow/internal/entity"@@ -153,7 +154,8 @@ type CreateSearchResponse struct {// 6. Save to database within DB.atomic() transaction// 7. Return {search_id: id} on successfunc (s *SearchService) CreateSearch(ctx context.Context, name string, description *string) (*CreateSearchResponse, error) {- identity, err := ResolveIdentity(ctx)+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return nil, err}@@ -170,7 +172,7 @@ func (s *SearchService) CreateSearch(ctx context.Context, name string, descripti// Generate unique name (same as Python duplicate_name)// search.name is a 128-byte column; keep generated names within it.uniqueName, err := common.UniqueName(name, 128, func(candidate string) (bool, error) {- existing, err := s.searchDAO.GetByNameAndTenant(ctx, dao.DB, candidate, identity.TenantID)+ existing, err := s.searchDAO.GetByNameAndTenant(ctx, dao.DB, candidate, tenantID)if err != nil {return false, err}@@ -184,10 +186,10 @@ func (s *SearchService) CreateSearch(ctx context.Context, name string, descripti// Create search entitysearch := &entity.Search{ID: searchID,- UserID: identity.UserID,- TenantID: identity.TenantID,+ UserID: userID,+ TenantID: tenantID,Name: uniqueName,- CreatedBy: identity.UserID,+ CreatedBy: userID,SearchConfig: make(entity.JSONMap),}@@ -272,7 +274,7 @@ func (s *SearchService) DeleteSearch(ctx context.Context, searchID string) error}type SearchCompletionPlan struct {- Identity Identity+ TenantID stringSearchID stringQuestion stringDatasetIDs []string@@ -324,21 +326,21 @@ func (s *SearchService) PrepareCompletion(ctx context.Context, searchID string,return nil, code, permissionErr}}- identity, err := ResolveIdentity(ctx)- if err != nil {- code, normalizedErr := permissionresponse.Normalize(err)- return nil, code, normalizedErr+ tenantID, _ := searchDetail["tenant_id"].(string)+ tenantID = strings.TrimSpace(tenantID)+ if tenantID == "" {+ return nil, common.CodeDataError, fmt.Errorf("search %s has no tenant", searchID)}modelID, _ := stringFromSearchConfig(searchConfig["chat_id"])if modelID == "" {- if info, infoErr := NewModelFactory().ResolveDefaultInfo(ctx, identity, entity.ModelTypeChat); infoErr == nil {+ if info, infoErr := NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeChat); infoErr == nil {modelID = ModelReference(info)}}return &SearchCompletionPlan{- Identity: identity,+ TenantID: tenantID,SearchID: searchID,Question: question,DatasetIDs: datasetIDs,diff --git a/internal/service/search_active_tenant_test.go b/internal/service/search_active_tenant_test.goindex 92a8a14679..8237556ccb 100644--- a/internal/service/search_active_tenant_test.go+++ b/internal/service/search_active_tenant_test.go@@ -39,7 +39,7 @@ func TestPrepareCompletionKeepsActiveTenantIdentity(t *testing.T) {if code != common.CodeSuccess {t.Fatalf("PrepareCompletion() code = %v, want success", code)}- if plan.Identity != (Identity{UserID: "user-1", TenantID: "team-1"}) {- t.Fatalf("Identity = %+v, want user-1 in team-1", plan.Identity)+ if plan.TenantID != "team-1" {+ t.Fatalf("TenantID = %q, want team-1", plan.TenantID)}}diff --git a/internal/service/skill_indexer.go b/internal/service/skill_indexer.goindex a63b3b4f26..95e1d25401 100644--- a/internal/service/skill_indexer.go+++ b/internal/service/skill_indexer.go@@ -22,6 +22,7 @@ import ("errors""fmt""path/filepath"+"ragflow/internal/common""ragflow/internal/dao""ragflow/internal/engine"@@ -78,8 +79,8 @@ func isElasticsearch(docEngine engine.DocEngine) bool {// Uses skill_id as doc_id for direct mapping, with version control for incremental updates// For ES: xxx fields store original content, xxx_tks fields store RAG-tokenized content (space-separated)// For Infinity: only xxx fields with built-in rag-analyzer-func (s *SkillIndexerService) IndexSkill(ctx context.Context, userID, spaceID string, skill SkillInfo, docEngine engine.DocEngine, embdID string) error {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+func (s *SkillIndexerService) IndexSkill(ctx context.Context, spaceID string, skill SkillInfo, docEngine engine.DocEngine, embdID string) error {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {return err}@@ -209,8 +210,8 @@ func (s *SkillIndexerService) indexSkill(ctx context.Context, tenantID, spaceID// BatchIndexSkills indexes multiple skills in batch// Optimized to use batch embedding API for better performance-func (s *SkillIndexerService) BatchIndexSkills(ctx context.Context, userID, spaceID string, skills []SkillInfo, docEngine engine.DocEngine, embdID string) error {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+func (s *SkillIndexerService) BatchIndexSkills(ctx context.Context, spaceID string, skills []SkillInfo, docEngine engine.DocEngine, embdID string) error {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {return err}@@ -374,8 +375,8 @@ func (s *SkillIndexerService) batchIndexSkills(ctx context.Context, tenantID, sp// DeleteSkillIndex deletes a skill's index by skill ID// Returns nil if the document doesn't exist (idempotent delete)-func (s *SkillIndexerService) DeleteSkillIndex(ctx context.Context, userID, spaceID, skillID string, docEngine engine.DocEngine) error {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+func (s *SkillIndexerService) DeleteSkillIndex(ctx context.Context, spaceID, skillID string, docEngine engine.DocEngine) error {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {return err}@@ -409,8 +410,8 @@ func (s *SkillIndexerService) deleteSkillByName(ctx context.Context, tenantID, s// UpdateSkillVersion updates a skill's index when version changes// Deletes old version and indexes new version-func (s *SkillIndexerService) UpdateSkillVersion(ctx context.Context, userID, spaceID string, skill SkillInfo, docEngine engine.DocEngine, embdID string) error {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+func (s *SkillIndexerService) UpdateSkillVersion(ctx context.Context, spaceID string, skill SkillInfo, docEngine engine.DocEngine, embdID string) error {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {return err}@@ -432,8 +433,8 @@ func (s *SkillIndexerService) UpdateSkillVersion(ctx context.Context, userID, sp// 2. Traverse all skill folders under the space// 3. For each skill, get the latest version// 4. Reindex all skills-func (s *SkillIndexerService) ReindexAll(ctx context.Context, userID, spaceID string, docEngine engine.DocEngine, embdID string) (map[string]interface{}, error) {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+func (s *SkillIndexerService) ReindexAll(ctx context.Context, spaceID string, docEngine engine.DocEngine, embdID string) (map[string]interface{}, error) {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {return nil, err}@@ -865,8 +866,8 @@ func (s *SkillIndexerService) cleanupOldVersions(ctx context.Context, tenantID,}// InitializeIndex initializes the skill search index for a tenant-func (s *SkillIndexerService) InitializeIndex(ctx context.Context, userID, spaceID string, docEngine engine.DocEngine, embdID string) error {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+func (s *SkillIndexerService) InitializeIndex(ctx context.Context, spaceID string, docEngine engine.DocEngine, embdID string) error {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {return err}@@ -941,8 +942,8 @@ func (s *SkillIndexerService) createIndexWithDimension(ctx context.Context, tena}// EnsureIndex ensures the skill index exists for a tenant-func (s *SkillIndexerService) EnsureIndex(ctx context.Context, userID, spaceID string, docEngine engine.DocEngine, embdID string) error {- return s.InitializeIndex(ctx, userID, spaceID, docEngine, embdID)+func (s *SkillIndexerService) EnsureIndex(ctx context.Context, spaceID string, docEngine engine.DocEngine, embdID string) error {+ return s.InitializeIndex(ctx, spaceID, docEngine, embdID)}// generateEmbedding generates embedding for text using the specified model@@ -955,7 +956,7 @@ func (s *SkillIndexerService) generateEmbedding(ctx context.Context, text, embdIreturn nil, fmt.Errorf("embedding model ID not configured")}- embeddingModel, err := s.modelFactory.NewEmbeddingModel(ctx, Identity{TenantID: tenantID}, embdID)+ embeddingModel, err := s.modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), embdID)if err != nil {return nil, fmt.Errorf("failed to get embedding model: %w", err)}@@ -986,7 +987,7 @@ func (s *SkillIndexerService) generateEmbeddings(ctx context.Context, texts []st}common.Info(fmt.Sprintf("Getting embedding model for %s", embdID))- embeddingModel, err := s.modelFactory.NewEmbeddingModel(ctx, Identity{TenantID: tenantID}, embdID)+ embeddingModel, err := s.modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), embdID)if err != nil {common.Error(fmt.Sprintf("Failed to get embedding model: %v", err), err)return nil, fmt.Errorf("failed to get embedding model: %w", err)@@ -1021,7 +1022,7 @@ func (s *SkillIndexerService) getEmbeddingDimension(ctx context.Context, tenantIreturn 0, fmt.Errorf("embedding model ID not configured")}- embeddingModel, err := s.modelFactory.NewEmbeddingModel(ctx, Identity{TenantID: tenantID}, embdID)+ embeddingModel, err := s.modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), embdID)if err != nil {return 0, fmt.Errorf("failed to get embedding model: %w", err)}diff --git a/internal/service/skill_search.go b/internal/service/skill_search.goindex 5b924d8f98..13883c2991 100644--- a/internal/service/skill_search.go+++ b/internal/service/skill_search.go@@ -22,6 +22,7 @@ import ("encoding/hex""errors""fmt"+"ragflow/internal/common""ragflow/internal/dao""ragflow/internal/engine"@@ -56,9 +57,9 @@ type GetConfigRequest struct {}// GetConfig retrieves the search configuration for a tenant-func (s *SkillSearchService) GetConfig(ctx context.Context, userID, spaceID, embdID string) (map[string]interface{}, common.ErrorCode, error) {+func (s *SkillSearchService) GetConfig(ctx context.Context, spaceID, embdID string) (map[string]interface{}, common.ErrorCode, error) {spaceID = normalizeSpaceID(spaceID)- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationRead)+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationRead)if err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -89,7 +90,7 @@ func (s *SkillSearchService) GetConfig(ctx context.Context, userID, spaceID, emb} else {config, err = s.configDAO.GetByTenantAndEmbdID(ctx, dao.DB, tenantID, spaceID, embdID)if err != nil {- tenantID, err = resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+ tenantID, err = resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -118,9 +119,9 @@ type UpdateConfigRequest struct {}// UpdateConfig updates the search configuration for a tenant-func (s *SkillSearchService) UpdateConfig(ctx context.Context, userID string, req *UpdateConfigRequest) (map[string]interface{}, common.ErrorCode, error) {+func (s *SkillSearchService) UpdateConfig(ctx context.Context, req *UpdateConfigRequest) (map[string]interface{}, common.ErrorCode, error) {req.SpaceID = normalizeSpaceID(req.SpaceID)- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, req.SpaceID, permission.OperationUpdate)+ tenantID, err := resolveSkillSpaceTenantID(ctx, req.SpaceID, permission.OperationUpdate)if err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -223,9 +224,9 @@ type SearchResponse struct {}// Search performs skill search with the configured strategy-func (s *SkillSearchService) Search(ctx context.Context, userID string, req *SearchRequest, docEngine engine.DocEngine) (*SearchResponse, common.ErrorCode, error) {+func (s *SkillSearchService) Search(ctx context.Context, req *SearchRequest, docEngine engine.DocEngine) (*SearchResponse, common.ErrorCode, error) {req.SpaceID = normalizeSpaceID(req.SpaceID)- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, req.SpaceID, permission.OperationUse)+ tenantID, err := resolveSkillSpaceTenantID(ctx, req.SpaceID, permission.OperationUse)if err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -661,7 +662,7 @@ func (s *SkillSearchService) getEmbedding(ctx context.Context, text, embdID, tenreturn nil, fmt.Errorf("embedding model ID not configured")}- embeddingModel, err := s.modelFactory.NewEmbeddingModel(ctx, Identity{TenantID: tenantID}, embdID)+ embeddingModel, err := s.modelFactory.NewEmbeddingModel(permission.WithTenantID(ctx, tenantID), embdID)if err != nil {return nil, fmt.Errorf("failed to get embedding model: %w", err)}diff --git a/internal/service/skill_search_test.go b/internal/service/skill_search_test.goindex 86d137c7ae..23fe2efe0b 100644--- a/internal/service/skill_search_test.go+++ b/internal/service/skill_search_test.go@@ -29,6 +29,7 @@ import ("ragflow/internal/engine""ragflow/internal/engine/types""ragflow/internal/entity"+ "ragflow/internal/permission")// ---------------------------------------------------------------------------@@ -91,6 +92,11 @@ func setupSkillSearchTenant(t *testing.T) {}}+func skillSearchTestContext(t *testing.T) context.Context {+ t.Helper()+ return permission.WithIdentity(t.Context(), "owner", "")+}+// saveSkillSearchConfig inserts an active config row for owner/default.func saveSkillSearchConfig(t *testing.T, config *entity.SkillSearchConfig) {t.Helper()@@ -264,7 +270,7 @@ func TestSearchReturnsEmptyWhenIndexMissing(t *testing.T) {service := NewSkillSearchService()eng := &skillSearchEngine{indexExists: false}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "anything"}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "anything"}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -288,7 +294,7 @@ func TestSearchKeywordWhenNoEmbeddingConfigured(t *testing.T) {searchResults: []map[string]interface{}{esStyleChunk("kw-skill", 1.0)},}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "find"}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "find"}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -330,7 +336,7 @@ func TestSearchKeywordOnZeroVectorWeight(t *testing.T) {searchResults: []map[string]interface{}{esStyleChunk("zero-weight", 0.5)},}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "find"}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "find"}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -360,7 +366,7 @@ func TestSearchEmptyQueryListsAllWithoutThreshold(t *testing.T) {},}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: ""}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: ""}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -398,7 +404,7 @@ func TestSearchHybridFallsBackToKeywordWhenEmbeddingUnavailable(t *testing.T) {searchResults: []map[string]interface{}{esStyleChunk("fallback-skill", 0.7)},}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "find", SortBy: "name", SortOrder: "asc"}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "find", SortBy: "name", SortOrder: "asc"}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -437,7 +443,7 @@ func TestSearchHybridFallsBackToKeywordOnEngineError(t *testing.T) {// Embedding resolution fails first (no model rows); Search then retries// with keyword search, whose engine error must surface to the caller.- _, _, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "find"}, eng)+ _, _, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "find"}, eng)if err == nil || !strings.Contains(err.Error(), "engine down") {t.Fatalf("err = %v, want engine error propagated from keyword fallback", err)}@@ -459,7 +465,7 @@ func TestSearchVectorFallsBackToKeywordWhenEmbeddingUnavailable(t *testing.T) {searchResults: []map[string]interface{}{esStyleChunk("vector-fallback", 0.55)},}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "find"}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "find"}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -478,7 +484,7 @@ func TestSearchPropagatesKeywordSearchError(t *testing.T) {service := NewSkillSearchService()eng := &skillSearchEngine{indexExists: true, searchErr: errors.New("boom")}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "find"}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "find"}, eng)if err == nil || code == common.CodeSuccess {t.Fatalf("code=%d err=%v, want error propagated from keyword search", code, err)}@@ -498,7 +504,7 @@ func TestSearchPaginationWindow(t *testing.T) {}eng := &skillSearchEngine{indexExists: true, searchResults: results}- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "", Page: 2, PageSize: 10}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "", Page: 2, PageSize: 10}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -515,7 +521,7 @@ func TestSearchPaginationWindow(t *testing.T) {}// Page beyond the result set must return an empty slice, not panic.- resp, _, err = service.Search(t.Context(), "owner", &SearchRequest{Query: "", Page: 9, PageSize: 10}, eng)+ resp, _, err = service.Search(skillSearchTestContext(t), &SearchRequest{Query: "", Page: 9, PageSize: 10}, eng)if err != nil {t.Fatalf("out-of-range page: %v", err)}@@ -535,7 +541,7 @@ func TestSearchDefaultsPageAndPageSize(t *testing.T) {}// Page/page_size default to 1/10 when non-positive.- resp, code, err := service.Search(t.Context(), "owner", &SearchRequest{Query: "", Page: -1, PageSize: -1}, eng)+ resp, code, err := service.Search(skillSearchTestContext(t), &SearchRequest{Query: "", Page: -1, PageSize: -1}, eng)if err != nil || code != common.CodeSuccess {t.Fatalf("Search: code=%d err=%v", code, err)}@@ -575,7 +581,7 @@ func TestUpdateConfigRejectsInvalidParameters(t *testing.T) {t.Run(tc.name, func(t *testing.T) {req := base()tc.mut(req)- resp, code, err := service.UpdateConfig(t.Context(), "owner", req)+ resp, code, err := service.UpdateConfig(skillSearchTestContext(t), req)if err == nil || code != common.CodeDataError {t.Fatalf("code=%d err=%v, want CodeDataError", code, err)}@@ -592,7 +598,7 @@ func TestUpdateConfigCreatesThenUpdatesSingleActiveConfig(t *testing.T) {setupSkillSearchTenant(t)service := NewSkillSearchService()- created, code, err := service.UpdateConfig(t.Context(), "owner", &UpdateConfigRequest{+ created, code, err := service.UpdateConfig(skillSearchTestContext(t), &UpdateConfigRequest{SpaceID: "default", EmbdID: "embd-1",VectorSimilarityWeight: 0.5, SimilarityThreshold: 0.2, TopK: 10,FieldConfig: entity.DefaultFieldConfig(),@@ -604,7 +610,7 @@ func TestUpdateConfigCreatesThenUpdatesSingleActiveConfig(t *testing.T) {t.Fatalf("embd_id = %v, want embd-1", created["embd_id"])}- updated, code, err := service.UpdateConfig(t.Context(), "owner", &UpdateConfigRequest{+ updated, code, err := service.UpdateConfig(skillSearchTestContext(t), &UpdateConfigRequest{SpaceID: "default", EmbdID: "embd-2",VectorSimilarityWeight: 0.7, SimilarityThreshold: 0.3, TopK: 20,FieldConfig: entity.DefaultFieldConfig(),@@ -633,7 +639,7 @@ func TestGetConfigReturnsDefaultsWhenNoConfigExists(t *testing.T) {setupSkillSearchTenant(t)service := NewSkillSearchService()- config, code, err := service.GetConfig(t.Context(), "owner", "default", "")+ config, code, err := service.GetConfig(skillSearchTestContext(t), "default", "")if err != nil || code != common.CodeSuccess {t.Fatalf("GetConfig: code=%d err=%v", code, err)}@@ -654,7 +660,7 @@ func TestGetConfigWithEmbdIDCreatesMissingConfig(t *testing.T) {setupSkillSearchTenant(t)service := NewSkillSearchService()- config, code, err := service.GetConfig(t.Context(), "owner", "default", "embd-1")+ config, code, err := service.GetConfig(skillSearchTestContext(t), "default", "embd-1")if err != nil || code != common.CodeSuccess {t.Fatalf("GetConfig: code=%d err=%v", code, err)}diff --git a/internal/service/skill_space.go b/internal/service/skill_space.goindex 319ee01269..0a8dab9eef 100644--- a/internal/service/skill_space.go+++ b/internal/service/skill_space.go@@ -20,6 +20,7 @@ import ("context""errors""fmt"+"ragflow/internal/common""ragflow/internal/dao""ragflow/internal/engine"@@ -34,10 +35,10 @@ import (permissionresponse "ragflow/internal/permission/response")-func resolveSkillSpaceTenantID(ctx context.Context, userID, spaceID string, operation permission.Operation) (string, error) {+func resolveSkillSpaceTenantID(ctx context.Context, spaceID string, operation permission.Operation) (string, error) {spaceID = normalizeSpaceID(spaceID)if spaceID == defaultSkillSpaceID {- return requireCurrentTenantID(ctx, userID)+ return requireCurrentTenantID(ctx)}access, err := permission.NewDatabaseChecker(dao.DB).ResolveAccess(ctx, permission.ResourceRef{@@ -170,12 +171,13 @@ func (s *SkillSpaceService) getSkillsFolderID(ctx context.Context, tenantID stri}// CreateSpace creates a new skills space with associated folder-func (s *SkillSpaceService) CreateSpace(ctx context.Context, userID string, req *CreateSpaceRequest) (map[string]interface{}, common.ErrorCode, error) {+func (s *SkillSpaceService) CreateSpace(ctx context.Context, req *CreateSpaceRequest) (map[string]interface{}, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)// Validate nameif req.Name == "" {return nil, common.CodeDataError, fmt.Errorf("space name is required")}- tenantID, err := requireCurrentTenantID(ctx, userID)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -186,7 +188,7 @@ func (s *SkillSpaceService) CreateSpace(ctx context.Context, userID string, req}defaultEmbdID := req.EmbdIDif defaultEmbdID == "" {- info, modelErr := NewModelFactory().ResolveDefaultInfo(ctx, Identity{UserID: userID, TenantID: tenantID}, entity.ModelTypeEmbedding)+ info, modelErr := NewModelFactory().ResolveDefaultInfo(permission.WithTenantID(ctx, tenantID), entity.ModelTypeEmbedding)if modelErr == nil {defaultEmbdID = ModelReference(info)} else if !errors.Is(modelErr, ErrNoDefaultModel) {@@ -327,7 +329,7 @@ func (s *SkillSpaceService) CreateSpace(ctx context.Context, userID string, req}// ListSpaces lists skill spaces the caller can read.-func (s *SkillSpaceService) ListSpaces(ctx context.Context, userID string) (map[string]interface{}, common.ErrorCode, error) {+func (s *SkillSpaceService) ListSpaces(ctx context.Context) (map[string]interface{}, common.ErrorCode, error) {spaceScope, err := permission.NewDatabaseChecker(dao.DB).Scope(ctx, permission.ScopeQuery{Kind: permission.ResourceKindSkillSpace,Operation: permission.OperationRead,@@ -358,8 +360,8 @@ func (s *SkillSpaceService) ListSpaces(ctx context.Context, userID string) (map[}// GetSpace retrieves a skills space by ID (includes deleting status for visibility)-func (s *SkillSpaceService) GetSpace(ctx context.Context, userID, spaceID string) (map[string]interface{}, common.ErrorCode, error) {- if _, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationRead); err != nil {+func (s *SkillSpaceService) GetSpace(ctx context.Context, spaceID string) (map[string]interface{}, common.ErrorCode, error) {+ if _, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationRead); err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized}@@ -379,8 +381,8 @@ func (s *SkillSpaceService) GetSpace(ctx context.Context, userID, spaceID string}// UpdateSpace updates a skills space-func (s *SkillSpaceService) UpdateSpace(ctx context.Context, userID, spaceID string, req *UpdateSpaceRequest) (map[string]interface{}, common.ErrorCode, error) {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationUpdate)+func (s *SkillSpaceService) UpdateSpace(ctx context.Context, spaceID string, req *UpdateSpaceRequest) (map[string]interface{}, common.ErrorCode, error) {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationUpdate)if err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized@@ -462,8 +464,8 @@ func (s *SkillSpaceService) UpdateSpace(ctx context.Context, userID, spaceID str// DeleteSpace starts asynchronous deletion of a skills space and returns immediately.// The space status is set to "deleting" and the actual cleanup runs in a background goroutine.-func (s *SkillSpaceService) DeleteSpace(ctx context.Context, userID, spaceID string, docEngine engine.DocEngine) (common.ErrorCode, error) {- tenantID, err := resolveSkillSpaceTenantID(ctx, userID, spaceID, permission.OperationDelete)+func (s *SkillSpaceService) DeleteSpace(ctx context.Context, spaceID string, docEngine engine.DocEngine) (common.ErrorCode, error) {+ tenantID, err := resolveSkillSpaceTenantID(ctx, spaceID, permission.OperationDelete)if err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return code, normalized@@ -671,13 +673,13 @@ func (s *SkillSpaceService) deleteFolderRecursive(ctx context.Context, folderID}// GetSpaceByFolderID retrieves a skills space by its folder ID-func (s *SkillSpaceService) GetSpaceByFolderID(ctx context.Context, userID, folderID string) (map[string]interface{}, common.ErrorCode, error) {+func (s *SkillSpaceService) GetSpaceByFolderID(ctx context.Context, folderID string) (map[string]interface{}, common.ErrorCode, error) {space, err := s.spaceDAO.GetByFolderID(ctx, dao.DB, folderID)if err != nil {code, normalized := permissionresponse.NormalizeHidden(permission.ErrResourceNotFound)return nil, code, normalized}- if _, err := resolveSkillSpaceTenantID(ctx, userID, space.ID, permission.OperationRead); err != nil {+ if _, err := resolveSkillSpaceTenantID(ctx, space.ID, permission.OperationRead); err != nil {code, normalized := permissionresponse.NormalizeHidden(err)return nil, code, normalized}diff --git a/internal/service/skill_space_test.go b/internal/service/skill_space_test.goindex fbe8ed21d1..1abf9c786d 100644--- a/internal/service/skill_space_test.go+++ b/internal/service/skill_space_test.go@@ -331,7 +331,7 @@ func TestDeleteSpaceRestartsCleanupLeftInTheDeletingState(t *testing.T) {}ctx := permission.WithIdentity(context.Background(), "owner-1", "tenant-1")- code, err := NewSkillSpaceService(nil).DeleteSpace(ctx, "owner-1", space.ID, nil)+ code, err := NewSkillSpaceService(nil).DeleteSpace(ctx, space.ID, nil)if err != nil || code != common.CodeSuccess {t.Fatalf("DeleteSpace = (%v, %v), want success", code, err)}diff --git a/internal/service/stats.go b/internal/service/stats.goindex 918c435cdb..3b67d93cde 100644--- a/internal/service/stats.go+++ b/internal/service/stats.go@@ -29,15 +29,11 @@ var ErrTenantNotFound = errors.New("Tenant not found!")// StatPoint matches the frontend [date, value] tuple shape.type StatPoint [2]interface{}-type StatsService struct {- userTenantDAO *dao.UserTenantDAO-}+type StatsService struct{}-// NewStatsService create stats service+// NewStatsService creates a stats service.func NewStatsService() *StatsService {- return &StatsService{- userTenantDAO: dao.NewUserTenantDAO(),- }+ return &StatsService{}}// ChatStatsResponse matches Python GET /api/v1/system/stats response data.@@ -50,14 +46,14 @@ type ChatStatsResponse struct {ThumbUp []StatPoint `json:"thumb_up"`}-// GetChatStats returns daily API conversation statistics for the first tenant of a user.-func (s *StatsService) GetChatStats(ctx context.Context, userID, fromDate, toDate string, source *string) (*ChatStatsResponse, error) {- tenants, err := s.userTenantDAO.GetByUserID(ctx, dao.DB, userID)- if err != nil || len(tenants) == 0 {+// GetChatStats returns daily API conversation statistics for the current tenant.+func (s *StatsService) GetChatStats(ctx context.Context, fromDate, toDate string, source *string) (*ChatStatsResponse, error) {+ tenantID, err := requireCurrentTenantID(ctx)+ if err != nil {return nil, ErrTenantNotFound}- rows, err := dao.NewAPI4ConversationDAO().Stats(ctx, dao.DB, tenants[0].TenantID, fromDate, toDate, source)+ rows, err := dao.NewAPI4ConversationDAO().Stats(ctx, dao.DB, tenantID, fromDate, toDate, source)if err != nil {return nil, err}diff --git a/internal/service/stub.go b/internal/service/stub.goindex ade604467f..cdc8817549 100644--- a/internal/service/stub.go+++ b/internal/service/stub.go@@ -23,6 +23,7 @@ import ("ragflow/internal/common""ragflow/internal/entity"+ "ragflow/internal/permission""gorm.io/gorm")@@ -40,16 +41,18 @@ func (h *AdminClient) UpdateClient(clientInfo any) error { return nil }// prepareAgentCreation grants no additional permissions before an agent is// created.-func prepareAgentCreation(_ context.Context, userID string) (string, error) { return userID, nil }+func prepareAgentCreation(ctx context.Context) (string, error) {+ return permission.UserIDFromContext(ctx), nil+}// tenantMemberPermissionEE leaves membership checks to the community policy.-func tenantMemberPermissionEE(ctx context.Context, db *gorm.DB, userID, tenantID string, required int32) (*entity.UserTenant, int32, bool, error) {+func tenantMemberPermissionEE(ctx context.Context, db *gorm.DB, tenantID string, required int32) (*entity.UserTenant, int32, bool, error) {return nil, 0, false, nil}// recordTenantPermissionChangeEE records nothing: the community edition has no// permission audit trail.-func recordTenantPermissionChangeEE(tx *gorm.DB, tenantID, actorUserID, eventType, targetType, targetID, resourceType, resourceID, actionType string, beforePermission, afterPermission int32, beforeData, afterData interface{}) error {+func recordTenantPermissionChangeEE(ctx context.Context, tx *gorm.DB, tenantID, eventType, targetType, targetID, resourceType, resourceID, actionType string, beforePermission, afterPermission int32, beforeData, afterData interface{}) error {return nil}@@ -70,7 +73,7 @@ func resolveCurrentUserTenantEE(context.Context, string) (*entity.UserTenant, bo}// resolveDefaultTenantIDEE leaves tenant resolution to the community path.-func resolveDefaultTenantIDEE(context.Context, string) (string, bool, error) {+func resolveDefaultTenantIDEE(context.Context) (string, bool, error) {return "", false, nil}diff --git a/internal/service/tenant.go b/internal/service/tenant.goindex 759dffcfee..82ced56309 100644--- a/internal/service/tenant.go+++ b/internal/service/tenant.go@@ -20,6 +20,7 @@ import ("context""errors""fmt"+"ragflow/internal/common""ragflow/internal/dao""ragflow/internal/engine"@@ -49,8 +50,9 @@ type tenantInviteRole struct {// tenantMemberPermission keeps community membership policy in shared code and// lets Enterprise apply its Tenant permission grants through the EE hook.-func tenantMemberPermission(ctx context.Context, db *gorm.DB, userID, tenantID string, required int32) (*entity.UserTenant, int32, error) {- membership, mask, handled, err := tenantMemberPermissionEE(ctx, db, userID, tenantID, required)+func tenantMemberPermission(ctx context.Context, db *gorm.DB, tenantID string, required int32) (*entity.UserTenant, int32, error) {+ userID := permission.UserIDFromContext(ctx)+ membership, mask, handled, err := tenantMemberPermissionEE(ctx, db, tenantID, required)if err != nil || handled {return membership, mask, err}@@ -81,8 +83,8 @@ func tenantRoleErrorCode(err error) common.ErrorCode {return code}-func recordTenantPermissionChange(tx *gorm.DB, tenantID, actorUserID, eventType, targetType, targetID, resourceType, resourceID, actionType string, beforePermission, afterPermission int32, beforeData, afterData interface{}) error {- return recordTenantPermissionChangeEE(tx, tenantID, actorUserID, eventType, targetType, targetID, resourceType, resourceID, actionType, beforePermission, afterPermission, beforeData, afterData)+func recordTenantPermissionChange(ctx context.Context, tx *gorm.DB, tenantID, eventType, targetType, targetID, resourceType, resourceID, actionType string, beforePermission, afterPermission int32, beforeData, afterData interface{}) error {+ return recordTenantPermissionChangeEE(ctx, tx, tenantID, eventType, targetType, targetID, resourceType, resourceID, actionType, beforePermission, afterPermission, beforeData, afterData)}func resolveTenantInviteRole(tx *gorm.DB, tenantID string) (tenantInviteRole, error) {@@ -124,7 +126,8 @@ type TenantListItem struct {}// GetTenantList get tenant list for a user-func (s *TenantService) GetTenantList(ctx context.Context, userID string) ([]*TenantListItem, error) {+func (s *TenantService) GetTenantList(ctx context.Context) ([]*TenantListItem, error) {+ userID := permission.UserIDFromContext(ctx)tenants, err := s.userTenantDAO.GetTenantsByUserID(ctx, dao.DB, userID)if err != nil {return nil, err@@ -282,8 +285,8 @@ type TenantMemberResponse struct {}// ListMembers returns all non-owner members of tenantID.-func (s *TenantService) ListMembers(ctx context.Context, userID, tenantID string) ([]*TenantMemberResponse, common.ErrorCode, error) {- if _, _, err := tenantMemberPermission(ctx, dao.DB.WithContext(ctx), userID, tenantID, entity.TenantPermissionManageMembers); err != nil {+func (s *TenantService) ListMembers(ctx context.Context, tenantID string) ([]*TenantMemberResponse, common.ErrorCode, error) {+ if _, _, err := tenantMemberPermission(ctx, dao.DB.WithContext(ctx), tenantID, entity.TenantPermissionManageMembers); err != nil {return nil, tenantRoleErrorCode(err), err}rows, err := s.userTenantDAO.GetMembersByTenantID(ctx, dao.DB, tenantID)@@ -326,8 +329,9 @@ type AddMemberResponse struct {}// AddMember invites a user (by email) to the tenant.-func (s *TenantService) AddMember(ctx context.Context, userID, tenantID string, req *AddMemberRequest) (*AddMemberResponse, common.ErrorCode, error) {- if _, _, err := tenantMemberPermission(ctx, dao.DB.WithContext(ctx), userID, tenantID, entity.TenantPermissionManageMembers); err != nil {+func (s *TenantService) AddMember(ctx context.Context, tenantID string, req *AddMemberRequest) (*AddMemberResponse, common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)+ if _, _, err := tenantMemberPermission(ctx, dao.DB.WithContext(ctx), tenantID, entity.TenantPermissionManageMembers); err != nil {return nil, tenantRoleErrorCode(err), err}if req == nil {@@ -371,7 +375,7 @@ func (s *TenantService) AddMember(ctx context.Context, userID, tenantID string,if err := tx.Create(&membership).Error; err != nil {return fmt.Errorf("failed to create invitation: %w", err)}- return recordTenantPermissionChange(tx, tenantID, userID, "tenant.member.invited", "user", invitee.ID, "tenant_membership", membership.ID, "invite", 0, 0, nil,+ return recordTenantPermissionChange(ctx, tx, tenantID, "tenant.member.invited", "user", invitee.ID, "tenant_membership", membership.ID, "invite", 0, 0, nil,map[string]interface{}{"user_id": invitee.ID, "email": invitee.Email, "role": membership.Role, "invited_by": userID, "status": status})}oldStatus := tenantMembershipStatus(existing.Status)@@ -394,7 +398,7 @@ func (s *TenantService) AddMember(ctx context.Context, userID, tenantID string,}existing.Role, existing.InvitedBy, existing.Status = "", userID, &statusmembership = existing- return recordTenantPermissionChange(tx, tenantID, userID, "tenant.member.invited", "user", invitee.ID, "tenant_membership", membership.ID, "invite", 0, 0, before,+ return recordTenantPermissionChange(ctx, tx, tenantID, "tenant.member.invited", "user", invitee.ID, "tenant_membership", membership.ID, "invite", 0, 0, before,map[string]interface{}{"user_id": invitee.ID, "email": invitee.Email, "role": membership.Role, "invited_by": userID, "status": status})})if err != nil {@@ -407,12 +411,13 @@ func (s *TenantService) AddMember(ctx context.Context, userID, tenantID string,// RemoveMember removes a user from the tenant. The owner may remove members,// and a member may remove themselves. An invitee may decline their own pending// invitation. The tenant owner cannot be removed.-func (s *TenantService) RemoveMember(ctx context.Context, userID, tenantID, targetUserID string) (common.ErrorCode, error) {+func (s *TenantService) RemoveMember(ctx context.Context, tenantID, targetUserID string) (common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)if s.userTenantDAO == nil {return common.CodeServerError, fmt.Errorf("userTenantDAO not initialized")}if userID != targetUserID {- if _, _, err := tenantMemberPermission(ctx, dao.DB.WithContext(ctx), userID, tenantID, entity.TenantPermissionManageMembers); err != nil {+ if _, _, err := tenantMemberPermission(ctx, dao.DB.WithContext(ctx), tenantID, entity.TenantPermissionManageMembers); err != nil {return tenantRoleErrorCode(err), err}}@@ -462,7 +467,7 @@ func (s *TenantService) RemoveMember(ctx context.Context, userID, tenantID, targ"user_id": membership.UserID, "role": "","invited_by": membership.InvitedBy, "status": newStatus,}- return recordTenantPermissionChange(tx, tenantID, userID, eventType, "user", targetUserID, "tenant_membership", membership.ID, actionType, 0, 0, before, after)+ return recordTenantPermissionChange(ctx, tx, tenantID, eventType, "user", targetUserID, "tenant_membership", membership.ID, actionType, 0, 0, before, after)})if err != nil {return tenantRoleErrorCode(err), err@@ -471,7 +476,8 @@ func (s *TenantService) RemoveMember(ctx context.Context, userID, tenantID, targ}// AcceptInvite assigns the Tenant default role when a pending invitation is accepted.-func (s *TenantService) AcceptInvite(ctx context.Context, userID, tenantID string) (common.ErrorCode, error) {+func (s *TenantService) AcceptInvite(ctx context.Context, tenantID string) (common.ErrorCode, error) {+ userID := permission.UserIDFromContext(ctx)// Seat quota is enforced again at acceptance time: several pending// invitations can each fit the remaining seat but not all of them.if billingService := billing.Get(); billingService != nil && billingService.Enabled() {@@ -518,7 +524,7 @@ func (s *TenantService) AcceptInvite(ctx context.Context, userID, tenantID strinif role.roleName != "" {after["role_name"] = role.roleName}- return recordTenantPermissionChange(tx, tenantID, userID, "tenant.member.joined", "user", userID, "tenant_membership", membership.ID, "join", 0, 0, before, after)+ return recordTenantPermissionChange(ctx, tx, tenantID, "tenant.member.joined", "user", userID, "tenant_membership", membership.ID, "join", 0, 0, before, after)})if err != nil {return tenantRoleErrorCode(err), errdiff --git a/internal/service/tenant_context.go b/internal/service/tenant_context.goindex a7d5e543fc..5233d03063 100644--- a/internal/service/tenant_context.go+++ b/internal/service/tenant_context.go@@ -23,24 +23,18 @@ import ("ragflow/internal/permission")-func requireCurrentTenantID(ctx context.Context, userID string) (string, error) {- if strings.TrimSpace(userID) == "" {+func requireCurrentTenantID(ctx context.Context) (string, error) {+ userID := strings.TrimSpace(permission.UserIDFromContext(ctx))+ if userID == "" {return "", permission.ErrUnauthenticated}- contextUserID := strings.TrimSpace(permission.UserIDFromContext(ctx))- if contextUserID != "" && contextUserID != userID {- return "", permission.ErrIdentityMismatch- }if tenantID := strings.TrimSpace(permission.TenantIDFromContext(ctx)); tenantID != "" {- if contextUserID == "" {- ctx = permission.WithIdentity(ctx, userID, tenantID)- }if err := permission.NewDatabaseChecker(dao.DB).CheckTenant(ctx, tenantID, permission.TenantMember); err != nil {return "", err}return tenantID, nil}- tenantID, handled, err := resolveDefaultTenantIDEE(ctx, userID)+ tenantID, handled, err := resolveDefaultTenantIDEE(ctx)if err != nil {return "", err}diff --git a/internal/service/tenant_test.go b/internal/service/tenant_test.goindex 0ec3d64dcd..fbad476ee8 100644--- a/internal/service/tenant_test.go+++ b/internal/service/tenant_test.go@@ -61,7 +61,7 @@ func TestListMembersAuthCheck(t *testing.T) {seedTenantMembership(t, db, "owner", "owner-user", "tenant-xyz", "owner")s := &TenantService{userTenantDAO: dao.NewUserTenantDAO()}ctx := permission.WithIdentity(t.Context(), "user-abc", "tenant-xyz")- _, code, err := s.ListMembers(ctx, "user-abc", "tenant-xyz")+ _, code, err := s.ListMembers(ctx, "tenant-xyz")if err == nil {t.Fatal("expected error for non-owner, got nil")}@@ -77,7 +77,7 @@ func TestAddMemberAuthCheck(t *testing.T) {seedTenantMembership(t, db, "owner", "owner-user", "tenant-xyz", "owner")s := &TenantService{userTenantDAO: dao.NewUserTenantDAO()}ctx := permission.WithIdentity(t.Context(), "user-abc", "tenant-xyz")- _, code, err := s.AddMember(ctx, "user-abc", "tenant-xyz", &AddMemberRequest{Email: "[email protected]"})+ _, code, err := s.AddMember(ctx, "tenant-xyz", &AddMemberRequest{Email: "[email protected]"})if err == nil {t.Fatal("expected error for non-owner, got nil")}@@ -92,7 +92,7 @@ func TestAddMemberEmailRequired(t *testing.T) {seedTenantMembership(t, db, "owner", "owner-user", "tenant-xyz", "owner")s := &TenantService{userTenantDAO: dao.NewUserTenantDAO()}ctx := permission.WithIdentity(t.Context(), "owner-user", "tenant-xyz")- _, code, err := s.AddMember(ctx, "owner-user", "tenant-xyz", &AddMemberRequest{Email: ""})+ _, code, err := s.AddMember(ctx, "tenant-xyz", &AddMemberRequest{Email: ""})if err == nil {t.Fatal("expected error for empty email, got nil")}@@ -107,7 +107,7 @@ func TestRemoveMemberAuthCheck(t *testing.T) {seedTenantMembership(t, db, "owner", "owner-user", "tenant-xyz", "owner")s := &TenantService{userTenantDAO: dao.NewUserTenantDAO()}ctx := permission.WithIdentity(t.Context(), "user-abc", "tenant-xyz")- code, err := s.RemoveMember(ctx, "user-abc", "tenant-xyz", "user-def")+ code, err := s.RemoveMember(ctx, "tenant-xyz", "user-def")if err == nil {t.Fatal("expected error, got nil")}@@ -122,7 +122,7 @@ func TestRemoveMemberSelfAllowed(t *testing.T) {seedTenantMembership(t, db, "member", "user-abc", "tenant-xyz", "normal")s := &TenantService{userTenantDAO: dao.NewUserTenantDAO()}ctx := permission.WithIdentity(t.Context(), "user-abc", "tenant-xyz")- code, err := s.RemoveMember(ctx, "user-abc", "tenant-xyz", "user-abc")+ code, err := s.RemoveMember(ctx, "tenant-xyz", "user-abc")if code != common.CodeSuccess {t.Errorf("expected CodeSuccess, got %v: %v", code, err)}@@ -146,7 +146,7 @@ func TestDeclineOwnTenantInviteAllowed(t *testing.T) {}s := &TenantService{userTenantDAO: dao.NewUserTenantDAO()}- code, err := s.RemoveMember(permission.WithIdentity(t.Context(), "invitee-user", "tenant-xyz"), "invitee-user", "tenant-xyz", "invitee-user")+ code, err := s.RemoveMember(permission.WithIdentity(t.Context(), "invitee-user", "tenant-xyz"), "tenant-xyz", "invitee-user")if err != nil || code != common.CodeSuccess {t.Fatalf("RemoveMember(invitation self-decline) = (%v, %v), want success", code, err)}@@ -164,7 +164,7 @@ func TestRemoveMemberCannotRemoveTenantOwner(t *testing.T) {seedTenantMembership(t, db, "owner", "owner-user", "tenant-xyz", "owner")s := &TenantService{userTenantDAO: dao.NewUserTenantDAO()}- code, err := s.RemoveMember(permission.WithIdentity(t.Context(), "owner-user", "tenant-xyz"), "owner-user", "tenant-xyz", "owner-user")+ code, err := s.RemoveMember(permission.WithIdentity(t.Context(), "owner-user", "tenant-xyz"), "tenant-xyz", "owner-user")if err == nil || code != common.CodeArgumentError {t.Fatalf("RemoveMember(owner) = (%v, %v), want argument error", code, err)}@@ -175,7 +175,7 @@ func TestAcceptInviteAuthCheck(t *testing.T) {s := &TenantService{}// nil userTenantDAO: nil guard returns CodeServerError.ctx := t.Context()- code, err := s.AcceptInvite(ctx, "user-abc", "tenant-xyz")+ code, err := s.AcceptInvite(ctx, "tenant-xyz")if err == nil {t.Fatal("expected error when userTenantDAO is nil, got nil")}@@ -293,7 +293,7 @@ func TestSetModelSettings_WithModelID(t *testing.T) {// 4. Run the unified Tenant model settings path.s := NewUserTenantService()ctx := serviceTestContext(t, userID, tenantID)- code, err := s.SetModelSettings(ctx, userID, &SetModelSettingsRequest{+ code, err := s.SetModelSettings(ctx, &SetModelSettingsRequest{DefaultModel: &DefaultModelSelection{ModelType: "chat", ModelID: modelID},})if err != nil || code != common.CodeSuccess {diff --git a/internal/service/user_set_tenant_info_test.go b/internal/service/user_set_tenant_info_test.goindex d1c5f32b17..e2bc6cdcb8 100644--- a/internal/service/user_set_tenant_info_test.go+++ b/internal/service/user_set_tenant_info_test.go@@ -36,7 +36,7 @@ func TestSetModelSettingsRejectsInvalidSettingTypesBeforeDatabaseLookup(t *testifor _, tt := range tests {t.Run(tt.name, func(t *testing.T) {- code, err := (&UserTenantService{}).SetModelSettings(context.Background(), "user-1", &SetModelSettingsRequest{Raw: tt.raw})+ code, err := (&UserTenantService{}).SetModelSettings(context.Background(), &SetModelSettingsRequest{Raw: tt.raw})if code != common.CodeArgumentError || err == nil {t.Fatalf("SetModelSettings() = (%v, %v), want argument error", code, err)}diff --git a/internal/service/user_tenant.go b/internal/service/user_tenant.goindex e218bce42e..881a67cf61 100644--- a/internal/service/user_tenant.go+++ b/internal/service/user_tenant.go@@ -78,8 +78,9 @@ type TenantInfoResponse struct {}// GetCurrentTenantInfo returns the active tenant with the user's membership settings.-func (s *UserTenantService) GetCurrentTenantInfo(ctx context.Context, userID string) (*TenantInfoResponse, error) {- tenantID, err := requireCurrentTenantID(ctx, userID)+func (s *UserTenantService) GetCurrentTenantInfo(ctx context.Context) (*TenantInfoResponse, error) {+ userID := permission.UserIDFromContext(ctx)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return nil, err}@@ -135,7 +136,7 @@ func (s *UserTenantService) GetUserTenantRelationByUserIDWithContext(ctx contextvar defaultModelTypeNames = [...]string{"chat", "embedding", "rerank", "asr", "vision", "tts", "ocr", "decision"}// SetModelSettings validates and updates default models on the user's active tenant membership.-func (s *UserTenantService) SetModelSettings(ctx context.Context, userID string, req *SetModelSettingsRequest) (common.ErrorCode, error) {+func (s *UserTenantService) SetModelSettings(ctx context.Context, req *SetModelSettingsRequest) (common.ErrorCode, error) {if req == nil || (req.Raw != nil && req.DefaultModel != nil) {return common.CodeArgumentError, fmt.Errorf("provide either model settings or one default model selection")}@@ -167,7 +168,8 @@ func (s *UserTenantService) SetModelSettings(ctx context.Context, userID string,if err != nil {return common.CodeArgumentError, err}- tenantID, err := requireCurrentTenantID(ctx, userID)+ userID := permission.UserIDFromContext(ctx)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return common.CodeForbidden, err}@@ -211,7 +213,7 @@ func (s *UserTenantService) SetModelSettings(ctx context.Context, userID string,continue}- info, err := factory.ResolveInfo(ctx, Identity{UserID: userID, TenantID: tenantID}, modelType, modelRef)+ info, err := factory.ResolveInfo(permission.WithTenantID(ctx, tenantID), modelType, modelRef)if err != nil {switch {case errors.Is(err, permission.ErrPermissionDenied), errors.Is(err, permission.ErrResourceNotFound), errors.Is(err, permission.ErrMembershipNotFound):@@ -330,8 +332,9 @@ func ptrStringValue(value *string) string {}// ListDefaultModels returns the models configured on the user's current tenant membership.-func (s *UserTenantService) ListDefaultModels(ctx context.Context, userID string) ([]ModelItem, error) {- tenantID, err := requireCurrentTenantID(ctx, userID)+func (s *UserTenantService) ListDefaultModels(ctx context.Context) ([]ModelItem, error) {+ userID := permission.UserIDFromContext(ctx)+ tenantID, err := requireCurrentTenantID(ctx)if err != nil {return nil, err}@@ -368,7 +371,7 @@ func (s *UserTenantService) ListDefaultModels(ctx context.Context, userID stringif err != nil {continue}- info, err := factory.ResolveInfo(ctx, Identity{UserID: userID, TenantID: tenantID}, modelType, modelRef)+ info, err := factory.ResolveInfo(permission.WithTenantID(ctx, tenantID), modelType, modelRef)if err != nil || info == nil {continue}