From 3a578153bbd91073c507b9f848af67d03d4d993e Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Thu, 19 Nov 2026 22:33:21 +0800 Subject: [PATCH] =?UTF-8?q?feat(tenant):=20=E6=96=B0=E7=A9=BA=E9=97=B4?= =?UTF-8?q?=E5=BC=80=E7=AE=B1=E5=8D=B3=E7=94=A8:=E8=87=AA=E5=8A=A8?= =?UTF-8?q?=E5=88=9D=E5=A7=8B=E5=8C=96=E9=BB=98=E8=AE=A4=E6=A8=A1=E5=9E=8B?= =?UTF-8?q?=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增 TenantBootstrapService:建空间后自动创建「新手入门」知识库 (绑定内置默认对话/向量化模型)、预置欢迎文档(走标准上传管道)、 配置租户级检索重排模型;整体 fail-open 且幂等,不阻断主流程 - 挂钩 Register(普通注册与 OIDC 首登自动开户均覆盖)与手动创建 工作区接口,内置模型宿主租户(10000)跳过 - CreateKnowledgeBase / CreateAgent 空的必填模型字段自动落系统默认 (is_default 优先,否则该类型第一个 active),API 直调路径同样兜底 - 自动化编辑器模型选择预填系统默认对话模型 --- .../src/views/automation/AutomationEditor.vue | 13 + internal/application/service/custom_agent.go | 17 ++ internal/application/service/knowledgebase.go | 16 ++ .../application/service/tenant_bootstrap.go | 241 ++++++++++++++++++ internal/application/service/user.go | 27 +- internal/container/container.go | 1 + internal/handler/custom_agent_avatar_test.go | 2 +- internal/handler/custom_agent_patch_test.go | 2 +- internal/handler/system_user_status_test.go | 2 +- internal/handler/tenant.go | 16 +- .../interfaces/tenant_bootstrap_service.go | 20 ++ 11 files changed, 344 insertions(+), 13 deletions(-) create mode 100644 internal/application/service/tenant_bootstrap.go create mode 100644 internal/types/interfaces/tenant_bootstrap_service.go diff --git a/frontend/src/views/automation/AutomationEditor.vue b/frontend/src/views/automation/AutomationEditor.vue index 5a35529..736076e 100644 --- a/frontend/src/views/automation/AutomationEditor.vue +++ b/frontend/src/views/automation/AutomationEditor.vue @@ -313,6 +313,8 @@ import { type ScheduleKind, } from '@/utils/automationSchedule' import ModelSelector from '@/components/ModelSelector.vue' +import { selectInitialModelId } from '@/utils/modelDefaults' +import { useChatResourcesStore } from '@/stores/chatResources' import { useUIStore } from '@/stores/ui' const props = defineProps<{ @@ -323,6 +325,7 @@ const emit = defineEmits<{ 'update:visible': [value: boolean]; saved: [value: Au const { t, locale } = useI18n() const uiStore = useUIStore() +const chatResources = useChatResourcesStore() type Section = 'basic' | 'schedule' | 'execution' | 'notify' @@ -409,6 +412,16 @@ watch(() => props.visible, (open) => { Object.assign(schedule, defaultScheduleForm()) timezone.value = browserTimezone() maxMinutes.value = 30 + if (!a) { + // 开箱即用:create 模式预填系统默认对话模型(与知识库/智能体编辑器 + // 的 applyDefaultModelsIfEmpty 同模式)。模型列表异步加载,回来后仅当 + // 仍为空时落值,不覆盖用户已选;编辑已有自动化时不做预填。 + void chatResources.ensureModels().then(() => { + if (!props.automation && props.visible && !form.model_id) { + form.model_id = selectInitialModelId(chatResources.allModels || [], 'KnowledgeQA') || '' + } + }).catch(() => {}) + } if (a) { Object.assign(form, { name: a.name, diff --git a/internal/application/service/custom_agent.go b/internal/application/service/custom_agent.go index 1b6d7df..85d465c 100644 --- a/internal/application/service/custom_agent.go +++ b/internal/application/service/custom_agent.go @@ -44,6 +44,10 @@ type customAgentService struct { tagRepo interfaces.KnowledgeTagRepository knowledgeRepo interfaces.KnowledgeRepository agentShareRepo interfaces.AgentShareRepository + // modelService is optional (nil in some unit tests) and only used by + // the create-time fallback that fills an empty Config.ModelID with the + // tenant-visible default chat model (out-of-the-box experience). + modelService interfaces.ModelService } // NewCustomAgentService creates a new custom agent service @@ -56,6 +60,7 @@ func NewCustomAgentService( tagRepo interfaces.KnowledgeTagRepository, knowledgeRepo interfaces.KnowledgeRepository, agentShareRepo interfaces.AgentShareRepository, + modelService interfaces.ModelService, ) interfaces.CustomAgentService { return &customAgentService{ repo: repo, @@ -66,6 +71,7 @@ func NewCustomAgentService( tagRepo: tagRepo, knowledgeRepo: knowledgeRepo, agentShareRepo: agentShareRepo, + modelService: modelService, } } @@ -110,6 +116,17 @@ func (s *customAgentService) CreateAgent(ctx context.Context, agent *types.Custo return nil, err } + // 开箱即用兜底:主对话模型为空时自动落到系统默认(内置 is_default + // 优先,否则该类型第一个 active)。fail-open:解析不到保持为空, + // 运行时的 "chat model is not configured" 报错行为与现状一致。 + if strings.TrimSpace(agent.Config.ModelID) == "" && s.modelService != nil { + if models, err := s.modelService.ListModels(ctx); err == nil { + agent.Config.ModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA) + } else { + logger.Warnf(ctx, "agent create: default model fallback lookup failed: %v", err) + } + } + logger.Infof(ctx, "Creating custom agent, ID: %s, tenant ID: %d, name: %s, agent_mode: %s", agent.ID, agent.TenantID, agent.Name, agent.Config.AgentMode) diff --git a/internal/application/service/knowledgebase.go b/internal/application/service/knowledgebase.go index a1e420e..854b038 100644 --- a/internal/application/service/knowledgebase.go +++ b/internal/application/service/knowledgebase.go @@ -141,6 +141,22 @@ func (s *knowledgeBaseService) CreateKnowledgeBase(ctx context.Context, } kb.EnsureDefaults() applyTenantDefaultStorageProvider(ctx, kb) + // 开箱即用兜底:对话/向量化模型为空时自动落到系统默认(内置 + // is_default 优先,否则该类型第一个 active)。fail-open:解析不到 + // 保持为空,与用户显式不选的行为一致(空 embedding + 向量索引开启 + // 时的检索回退由查询侧既有逻辑处理)。 + if kb.SummaryModelID == "" || kb.EmbeddingModelID == "" { + if models, listErr := s.modelService.ListModels(ctx); listErr == nil { + if kb.SummaryModelID == "" { + kb.SummaryModelID = PickDefaultModelID(models, types.ModelTypeKnowledgeQA) + } + if kb.EmbeddingModelID == "" { + kb.EmbeddingModelID = PickDefaultModelID(models, types.ModelTypeEmbedding) + } + } else { + logger.Warnf(ctx, "[kb.create] default model fallback lookup failed: %v", listErr) + } + } if err := s.applyAndValidateStorageBackend(ctx, kb); err != nil { return nil, err } diff --git a/internal/application/service/tenant_bootstrap.go b/internal/application/service/tenant_bootstrap.go new file mode 100644 index 0000000..1b3abb8 --- /dev/null +++ b/internal/application/service/tenant_bootstrap.go @@ -0,0 +1,241 @@ +package service + +import ( + "bytes" + "context" + "errors" + "io" + "mime/multipart" + "strings" + + "academy/internal/logger" + "academy/internal/types" + "academy/internal/types/interfaces" +) + +// --------------------------------------------------------------------------- +// 新工作空间开箱即用初始化(tenant bootstrap) +// +// 目标:新用户注册/新建空间后,无需手动配置任何模型即可直接使用: +// 1. 解析系统默认模型(内置模型 is_builtin=true 全租户可见,is_default 优先); +// 2. 自动创建「新手入门」知识库,绑定默认对话/向量化模型; +// 3. 在该库中预置一份欢迎文档(走标准上传管道,自动切片/向量化); +// 4. 把租户级检索重排模型(retrieval_config.rerank_model_id)配成默认。 +// +// 整体 fail-open:任何一步失败只记日志,绝不阻断注册/建租户主流程; +// 且整体幂等——租户下已存在同名入门库时直接跳过。 +// --------------------------------------------------------------------------- + +const ( + // BootstrapKBName 开箱默认知识库名;幂等检查按此名匹配。 + BootstrapKBName = "新手入门" + + bootstrapWelcomeFileName = "欢迎使用指南.md" +) + +// bootstrapWelcomeDocContent 预置欢迎文档内容。走标准文档解析管道, +// 处理完成后用户即可在「新手入门」库上直接问答验证开箱效果。 +const bootstrapWelcomeDocContent = `# 欢迎使用 Academy + +这是一份由系统自动创建的入门知识库,已经为你配置好默认的对话与向量化模型—— +现在你可以直接开始提问了。 + +## 你现在就可以做什么 + +- **知识库问答**:进入任意知识库,右侧对话面板直接提问。本库已内置这份入门指南, + 可以试试问它:"这个平台能做什么?" +- **智能体对话**:打开对话页面即可与 Academy 助手聊天,助手默认使用系统配置好的对话模型。 + +## 接下来你可能想做的事 + +1. **创建自己的知识库**:左侧知识库 → 新建知识库。系统会自动为你预填默认模型, + 上传文档(支持 Markdown、Word、PDF、Excel 等)后即可对文档内容提问。 +2. **创建智能体**:智能体页面 → 新建。主模型同样自动预填;你还可以为智能体单独配置 + 重排、视觉(图片理解)、语音(ASR)等模型。 +3. **邀请团队成员**:右上角头像 → 设置 → 成员管理 → 邀请成员。支持单个邀请、 + 生成共享链接,以及按 Excel 模板批量导入成员。 +4. **管理模型**:设置 → 模型管理。系统内置的默认模型已开箱可用;如需接入 + 自己的模型(OpenAI 兼容 API、Ollama 本地模型、各云厂商),在「添加模型」中配置即可。 + +## 小提示 + +- 带锁图标的模型是系统内置模型,所有空间共享,可直接使用。 +- 新建知识库/智能体时,模型字段已自动填好默认值,不需要手动选择;当然你随时可以更换。 + +祝使用愉快! +` + +// NewTenantBootstrapService wires the bootstrap service. All dependencies are +// optional at the DI level but each seeding step degrades gracefully when its +// service misbehaves (fail-open, see SeedTenantDefaults). +func NewTenantBootstrapService( + modelService interfaces.ModelService, + kbService interfaces.KnowledgeBaseService, + kgService interfaces.KnowledgeService, + tenantService interfaces.TenantService, +) interfaces.TenantBootstrapService { + return &tenantBootstrapService{ + modelService: modelService, + kbService: kbService, + kgService: kgService, + tenantService: tenantService, + } +} + +type tenantBootstrapService struct { + modelService interfaces.ModelService + kbService interfaces.KnowledgeBaseService + kgService interfaces.KnowledgeService + tenantService interfaces.TenantService +} + +// SeedTenantDefaults implements interfaces.TenantBootstrapService. See the +// interface doc for the contract; every step logs and moves on. +func (s *tenantBootstrapService) SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string) { + // 整体兜底:seed 属于附加体验,任何 panic(如上游依赖 nil)都不能 + // 波及注册/建租户主流程。 + defer func() { + if r := recover(); r != nil { + logger.Errorf(ctx, "tenant bootstrap: recovered from panic: %v", r) + } + }() + + if tenant == nil || tenant.ID == 0 { + return + } + // 内置模型的宿主租户(tenant 10000)不是用户空间,永不 seed。 + if tenant.ID == types.DefaultBuiltinModelTenantID { + return + } + + // 构造服务级 ctx:显式指定执行租户与租户信息(CreateKnowledgeFromFile + // 依赖 TenantInfo),并归因创建人(synthetic API-key 用户跳过,同 KB + // 服务的 CreatorID 语义)。必须先于所有服务调用——挂钩处的调用方 ctx + // 还停留在调用者的"当前空间",不是刚创建的新空间。 + seedCtx := types.WithExecutionTenant(ctx, tenant.ID) + seedCtx = context.WithValue(seedCtx, types.TenantInfoContextKey, tenant) + if ownerUserID != "" && !types.IsSyntheticUserID(ownerUserID) { + seedCtx = context.WithValue(seedCtx, types.UserIDContextKey, ownerUserID) + } + + // 幂等:已有同名入门库的工作空间视为已初始化。 + kbs, err := s.kbService.ListKnowledgeBasesByTenantID(seedCtx, tenant.ID) + if err != nil { + logger.Warnf(ctx, "tenant bootstrap: list KBs failed, skip seeding: tenant=%d err=%v", tenant.ID, err) + return + } + for _, kb := range kbs { + if kb != nil && kb.Name == BootstrapKBName { + logger.Infof(ctx, "tenant bootstrap: workspace already seeded, skip: tenant=%d", tenant.ID) + return + } + } + + // 解析系统默认模型(内置 is_default 优先,否则该类型第一个 active)。 + models, err := s.modelService.ListModels(seedCtx) + if err != nil { + logger.Warnf(ctx, "tenant bootstrap: list models failed, skip seeding: tenant=%d err=%v", tenant.ID, err) + return + } + chatID := PickDefaultModelID(models, types.ModelTypeKnowledgeQA) + embedID := PickDefaultModelID(models, types.ModelTypeEmbedding) + rerankID := PickDefaultModelID(models, types.ModelTypeRerank) + + // 1) 默认知识库。模型解析不到就留空——行为与用户手动不选一致。 + kb := &types.KnowledgeBase{ + Name: BootstrapKBName, + Description: "系统自动创建的入门知识库,已绑定默认模型,可直接提问体验知识库问答。", + Type: types.KnowledgeBaseTypeDocument, + SummaryModelID: chatID, + EmbeddingModelID: embedID, + } + createdKB, err := s.kbService.CreateKnowledgeBase(seedCtx, kb) + if err != nil { + logger.Warnf(ctx, "tenant bootstrap: create starter KB failed: tenant=%d err=%v", tenant.ID, err) + return + } + logger.Infof(ctx, "tenant bootstrap: starter KB created: tenant=%d kb=%s", tenant.ID, createdKB.ID) + + // 2) 预置欢迎文档(标准上传管道,切片/向量化由后台任务异步完成)。 + if fh, fhErr := buildInMemoryFileHeader(bootstrapWelcomeFileName, bootstrapWelcomeDocContent); fhErr != nil { + logger.Warnf(ctx, "tenant bootstrap: build welcome file failed: tenant=%d err=%v", tenant.ID, fhErr) + } else if _, upErr := s.kgService.CreateKnowledgeFromFile(seedCtx, createdKB.ID, fh, nil, nil, "", nil, "", nil); upErr != nil { + logger.Warnf(ctx, "tenant bootstrap: upload welcome doc failed: tenant=%d kb=%s err=%v", + tenant.ID, createdKB.ID, upErr) + } else { + logger.Infof(ctx, "tenant bootstrap: welcome doc queued: tenant=%d kb=%s", tenant.ID, createdKB.ID) + } + + // 3) 租户级检索重排模型(RetrievalConfig 其余零值按 GetEffective* 回退默认)。 + if rerankID != "" { + if tenant.RetrievalConfig == nil { + tenant.RetrievalConfig = &types.RetrievalConfig{} + } + if tenant.RetrievalConfig.RerankModelID == "" { + tenant.RetrievalConfig.RerankModelID = rerankID + if _, err := s.tenantService.UpdateTenant(ctx, tenant); err != nil { + logger.Warnf(ctx, "tenant bootstrap: set tenant rerank model failed: tenant=%d err=%v", + tenant.ID, err) + } else { + logger.Infof(ctx, "tenant bootstrap: tenant rerank model set: tenant=%d model=%s", + tenant.ID, rerankID) + } + } + } +} + +// PickDefaultModelID returns the tenant-visible default model of the given +// type: the is_default row first, then the first active row. Empty string +// when the deployment has no usable model of that type. Shared by the +// create-time fallbacks (KB / agent) so every path resolves defaults the +// same way. +func PickDefaultModelID(models []*types.Model, modelType types.ModelType) string { + first := "" + for _, m := range models { + if m == nil || m.Type != modelType || strings.TrimSpace(m.ID) == "" { + continue + } + if m.Status != "" && m.Status != types.ModelStatusActive { + continue + } + if m.IsDefault { + return m.ID + } + if first == "" { + first = m.ID + } + } + return first +} + +// buildInMemoryFileHeader constructs a real *multipart.FileHeader for in-memory +// content so service paths that expect an uploaded file (CreateKnowledgeFromFile) +// can be reused without an HTTP round-trip. FileHeader's Open() reads unexported +// content captured by multipart form parsing, so the only reliable construction +// is a synthetic multipart round-trip in memory. +func buildInMemoryFileHeader(name, content string) (*multipart.FileHeader, error) { + if strings.TrimSpace(name) == "" { + return nil, errors.New("file name is required") + } + body := &bytes.Buffer{} + mw := multipart.NewWriter(body) + fw, err := mw.CreateFormFile("file", name) + if err != nil { + return nil, err + } + if _, err := io.Copy(fw, strings.NewReader(content)); err != nil { + return nil, err + } + if err := mw.Close(); err != nil { + return nil, err + } + form, err := multipart.NewReader(body, mw.Boundary()).ReadForm(int64(body.Len()) + 1<<20) + if err != nil { + return nil, err + } + fhs := form.File["file"] + if len(fhs) == 0 { + return nil, errors.New("multipart form contains no file part") + } + return fhs[0], nil +} diff --git a/internal/application/service/user.go b/internal/application/service/user.go index 38ce4fa..733a2ad 100644 --- a/internal/application/service/user.go +++ b/internal/application/service/user.go @@ -98,14 +98,18 @@ func getJwtSecret() string { // userService implements the UserService interface type userService struct { - userRepo interfaces.UserRepository - tokenRepo interfaces.AuthTokenRepository - tenantService interfaces.TenantService - memberService interfaces.TenantMemberService + userRepo interfaces.UserRepository + tokenRepo interfaces.AuthTokenRepository + tenantService interfaces.TenantService + memberService interfaces.TenantMemberService invitationService interfaces.TenantInvitationService - config *config.Config - systemSettingSvc interfaces.SystemSettingService - sandboxReleaser SandboxOwnerReleaser + config *config.Config + systemSettingSvc interfaces.SystemSettingService + sandboxReleaser SandboxOwnerReleaser + // bootstrap is optional (nil in unit tests): seeds out-of-the-box + // defaults (starter KB + tenant rerank) into freshly created personal + // workspaces. Fail-open by contract — see TenantBootstrapService. + bootstrap interfaces.TenantBootstrapService } // NewUserService creates a new user service instance @@ -117,6 +121,7 @@ func NewUserService( memberService interfaces.TenantMemberService, invitationService interfaces.TenantInvitationService, systemSettingSvc interfaces.SystemSettingService, + bootstrap interfaces.TenantBootstrapService, ) interfaces.UserService { return &userService{ userRepo: userRepo, @@ -126,6 +131,7 @@ func NewUserService( invitationService: invitationService, config: configInfo, systemSettingSvc: systemSettingSvc, + bootstrap: bootstrap, } } @@ -226,6 +232,13 @@ func (s *userService) Register(ctx context.Context, req *types.RegisterRequest) } logger.Info(ctx, "User registered successfully") + + // 开箱即用:为新个人空间 seed 默认模型配置(入门知识库 + 欢迎文档 + + // 租户级重排模型)。整体 fail-open,任何失败不影响注册结果。 + if createdTenant != nil && s.bootstrap != nil { + s.bootstrap.SeedTenantDefaults(ctx, createdTenant, user.ID) + } + return user, nil } diff --git a/internal/container/container.go b/internal/container/container.go index 3d4f90d..c94e356 100644 --- a/internal/container/container.go +++ b/internal/container/container.go @@ -260,6 +260,7 @@ func BuildContainer(container *dig.Container) *dig.Container { must(container.Provide(service.NewTenantService)) must(container.Provide(service.NewTenantAPIKeyService)) must(container.Provide(service.NewTenantMemberService)) + must(container.Provide(service.NewTenantBootstrapService)) must(container.Provide(service.NewTenantInvitationService)) must(container.Provide(service.NewAuditLogService)) must(container.Provide(service.NewAuditLogRetentionRunner)) diff --git a/internal/handler/custom_agent_avatar_test.go b/internal/handler/custom_agent_avatar_test.go index 2f4a8a1..a9ea929 100644 --- a/internal/handler/custom_agent_avatar_test.go +++ b/internal/handler/custom_agent_avatar_test.go @@ -68,7 +68,7 @@ func TestCustomAgentAvatarAndErrorResponses(t *testing.T) { agent: &types.CustomAgent{ID: "custom-1", Name: "old", Avatar: "🤖", TenantID: 1}, err: tc.repoErr, } - svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil) + svc := service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil, nil) h := &CustomAgentHandler{service: svc} router := gin.New() router.Use(middleware.ErrorHandler()) diff --git a/internal/handler/custom_agent_patch_test.go b/internal/handler/custom_agent_patch_test.go index 8de11ee..c4724a2 100644 --- a/internal/handler/custom_agent_patch_test.go +++ b/internal/handler/custom_agent_patch_test.go @@ -50,7 +50,7 @@ func servePatchWith( ) *httptest.ResponseRecorder { t.Helper() gin.SetMode(gin.TestMode) - h.service = service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil) + h.service = service.NewCustomAgentService(repo, nil, nil, nil, nil, nil, nil, nil, nil) router := gin.New() router.Use(middleware.ErrorHandler()) router.PATCH("/agents/:id", h.PatchAgent) diff --git a/internal/handler/system_user_status_test.go b/internal/handler/system_user_status_test.go index 94cfb7e..ddae592 100644 --- a/internal/handler/system_user_status_test.go +++ b/internal/handler/system_user_status_test.go @@ -90,7 +90,7 @@ func TestSetUserStatus_NotFound404(t *testing.T) { require.NoError(t, err) t.Cleanup(func() { require.NoError(t, sqlDB.Close()) }) require.NoError(t, db.AutoMigrate(&types.User{})) - svc := service.NewUserService(nil, repository.NewUserRepository(db), nil, nil, nil, nil, nil) + svc := service.NewUserService(nil, repository.NewUserRepository(db), nil, nil, nil, nil, nil, nil) h := &SystemHandler{userSvc: svc} r := statusRouter(h, "admin-1") body, _ := json.Marshal(map[string]any{"user_id": "ghost", "is_active": true}) diff --git a/internal/handler/tenant.go b/internal/handler/tenant.go index 4c96904..598220f 100644 --- a/internal/handler/tenant.go +++ b/internal/handler/tenant.go @@ -36,6 +36,10 @@ type TenantHandler struct { // in-code default, so a SystemAdmin's UI override applies on the // very next CreateTenant call. systemSettingSvc interfaces.SystemSettingService + // bootstrap seeds out-of-the-box defaults (starter KB bound to the + // built-in default models, welcome doc, tenant rerank) into freshly + // created workspaces. Optional; fail-open by contract. + bootstrap interfaces.TenantBootstrapService } // NewTenantHandler creates a new tenant handler instance with the provided service @@ -63,6 +67,7 @@ func NewTenantHandler( kbService interfaces.KnowledgeBaseService, config *config.Config, systemSettingSvc interfaces.SystemSettingService, + bootstrap interfaces.TenantBootstrapService, ) *TenantHandler { return &TenantHandler{ service: service, @@ -72,6 +77,7 @@ func NewTenantHandler( kbService: kbService, config: config, systemSettingSvc: systemSettingSvc, + bootstrap: bootstrap, } } @@ -445,12 +451,16 @@ func (h *TenantHandler) CreateTenant(c *gin.Context) { } } + // 开箱即用:为新建空间 seed 默认模型配置(入门知识库 + 欢迎文档 + + // 租户级重排模型)。整体 fail-open,任何失败不影响建租户结果。 + if h.bootstrap != nil { + h.bootstrap.SeedTenantDefaults(ctx, createdTenant, caller.ID) + } + logger.Infof( ctx, "Tenant created successfully, ID: %d, name: %s", - createdTenant.ID, - secutils.SanitizeForLog(createdTenant.Name), - ) + createdTenant.ID, secutils.SanitizeForLog(createdTenant.Name)) // data carries the created tenant. When the legacy auto-create-key // behaviour is enabled we embed the plaintext token as data.api_key so diff --git a/internal/types/interfaces/tenant_bootstrap_service.go b/internal/types/interfaces/tenant_bootstrap_service.go new file mode 100644 index 0000000..0387e47 --- /dev/null +++ b/internal/types/interfaces/tenant_bootstrap_service.go @@ -0,0 +1,20 @@ +package interfaces + +import ( + "context" + + "academy/internal/types" +) + +// TenantBootstrapService seeds "out-of-the-box" defaults into a freshly +// created workspace so a new user can use the platform without manually +// configuring models first: a starter knowledge base bound to the built-in +// default chat/embedding models, a welcome document inside it, and the +// tenant-level rerank model. All steps are best-effort (fail-open) — a +// bootstrap failure must never fail tenant creation or registration. +type TenantBootstrapService interface { + // SeedTenantDefaults is idempotent: workspaces that already contain the + // bootstrap knowledge base are skipped. ownerUserID (may be empty for + // platform-managed tenants) is recorded as the KB creator. + SeedTenantDefaults(ctx context.Context, tenant *types.Tenant, ownerUserID string) +}