Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.
Go agentagenticaichatbotdsh-pluginembeddingsevaluationgenerative-aigolangknowledge-basellmmulti-tenantollamaopenaiquestion-answeringragrerankingsemantic-searchvector-searchwiki
fix(invitation): harden auto-accept follow-ups from code review
wizardchenafd1ef8cf30c
diff --git a/client/auth.go b/client/auth.goindex 64f2e5d7a..c22f6178a 100644--- a/client/auth.go+++ b/client/auth.go@@ -82,12 +82,21 @@ type AuthTenant struct {Name string `json:"name"`}+// AuthCapabilities mirrors GET /auth/me capabilities for SPA feature gates.+type AuthCapabilities struct {+ CanCreateTenant bool `json:"can_create_tenant"`+ AutoAcceptInvitation bool `json:"auto_accept_invitation"`+}+// CurrentUserResponse is the body of GET /api/v1/auth/me.type CurrentUserResponse struct {Success bool `json:"success"`Data struct {- User *AuthUser `json:"user,omitempty"`- Tenant *AuthTenant `json:"tenant,omitempty"`+ User *AuthUser `json:"user,omitempty"`+ Tenant *AuthTenant `json:"tenant,omitempty"`+ Memberships []AuthMembership `json:"memberships,omitempty"`+ TenantRequired bool `json:"tenant_required,omitempty"`+ Capabilities *AuthCapabilities `json:"capabilities,omitempty"`} `json:"data"`}diff --git a/docs/api/auth.md b/docs/api/auth.mdindex 194698f81..d65f607f6 100644--- a/docs/api/auth.md+++ b/docs/api/auth.md@@ -275,20 +275,45 @@ curl --location 'http://localhost:8080/api/v1/auth/me' \```json{"success": true,- "user": {- "id": "usr-...",- "username": "alice",- "email": "[email protected]",- "avatar": "",- "tenant_id": 1,- "is_active": true,- "can_access_all_tenants": false,- "created_at": "2026-05-11T10:00:00+08:00",- "updated_at": "2026-05-11T10:00:00+08:00"+ "data": {+ "user": {+ "id": "usr-...",+ "username": "alice",+ "email": "[email protected]",+ "avatar": "",+ "tenant_id": 1,+ "is_active": true,+ "can_access_all_tenants": false,+ "created_at": "2026-05-11T10:00:00+08:00",+ "updated_at": "2026-05-11T10:00:00+08:00"+ },+ "tenant": {+ "id": 1,+ "name": "My Workspace"+ },+ "memberships": [+ {+ "tenant_id": 1,+ "tenant_name": "My Workspace",+ "role": "owner"+ }+ ],+ "tenant_required": false,+ "capabilities": {+ "can_create_tenant": false,+ "auto_accept_invitation": false+ }}}```+`capabilities` 供 SPA 读取部署级开关,无需调用超管设置 API:++| 字段 | 说明 |+| ---- | ---- |+| `can_create_tenant` | 当前用户是否可自助创建空间 |+| `auto_accept_invitation` | 全局 `tenant.auto_accept_invitation`:邮箱邀请已注册用户时是否直接加入(无需收件箱确认) |+---## POST `/auth/change-password` - 修改密码diff --git a/docs/api/tenant.md b/docs/api/tenant.mdindex 06864e1d8..e8bad6655 100644--- a/docs/api/tenant.md+++ b/docs/api/tenant.md@@ -636,3 +636,14 @@ curl --location --request PUT 'http://localhost:8080/api/v1/tenants/kv/agent-con- `retrieval-config`: `embedding_top_k` / `rerank_top_k` ∈ `[0, 200]`;阈值范围同上。- `storage-engine-config`: `default_provider` 必须在 `STORAGE_ALLOW_LIST` 允许的列表内。- `chat-history-config`: 启用且设置了 `embedding_model_id` 而尚未关联知识库时,会自动创建一个隐藏知识库并将其 ID 写入配置。++## 空间邀请(邮箱邀请已注册用户)++`POST /tenants/:id/invitations` 通过邮箱邀请**已注册**用户。全局开关 `tenant.auto_accept_invitation`(环境变量 `WEKNORA_TENANT_AUTO_ACCEPT_INVITATION`,默认 `false`)控制行为:++| 开关 | 行为 | 成功响应 `data` 形状 |+| ---- | ---- | -------------------- |+| `false` | 创建 pending 邀请,受邀人须在 `/me/invitations` 接受 | `TenantInvitation`(含 `id`、`status: pending`) |+| `true` | 直接写入 `tenant_members`,并 reconcile 已有 pending 行 | `TenantMember`(含 `user_id`、`status: active`) |++开启 auto-accept 时,无默认空间的受邀人会将该空间设为 home tenant(与手动接受邀请一致)。SPA 通过 `GET /auth/me` 的 `capabilities.auto_accept_invitation` 感知开关,无需读取系统设置 API。diff --git a/docs/docs.go b/docs/docs.goindex 5dcac39cf..f69ff5723 100644--- a/docs/docs.go+++ b/docs/docs.go@@ -8895,6 +8895,52 @@ const docTemplate = `{}}},+ "/me/invitations/accept-by-token": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "已登录用户用共享邀请链接 token 加入空间,不创建新账号;对已是成员的用户幂等。",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "我的邀请"+ ],+ "summary": "通过共享链接加入空间",+ "parameters": [+ {+ "description": "邀请 token",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/internal_handler.acceptInvitationByTokenRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "410": {+ "description": "链接无效或已撤销",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ }+ }+ }+ },"/me/invitations/pending-count": {"get": {"security": [@@ -13609,7 +13655,7 @@ const docTemplate = `{"Bearer": []}],- "description": "Owner 通过邮箱邀请已注册用户加入当前空间;被邀请人需要在 /me/invitations 接受后才会成为成员。",+ "description": "Owner 通过邮箱邀请已注册用户加入空间。开启 tenant.auto_accept_invitation 后被邀请人立即自动加入(响应为成员结构),否则需在 /me/invitations 接受后成为成员。","consumes": ["application/json"],@@ -20009,7 +20055,8 @@ const docTemplate = `{"baidu","searxng","keenable",- "zhipu"+ "zhipu",+ "metaso"],"x-enum-varnames": ["WebSearchProviderTypeBing",@@ -20020,7 +20067,8 @@ const docTemplate = `{"WebSearchProviderTypeBaidu","WebSearchProviderTypeSearxng","WebSearchProviderTypeKeenable",- "WebSearchProviderTypeZhipu"+ "WebSearchProviderTypeZhipu",+ "WebSearchProviderTypeMetaso"]},"github_com_Tencent_WeKnora_internal_types.WikiConfig": {@@ -22082,6 +22130,17 @@ const docTemplate = `{}}},+ "internal_handler.acceptInvitationByTokenRequest": {+ "type": "object",+ "required": [+ "token"+ ],+ "properties": {+ "token": {+ "type": "string"+ }+ }+ },"internal_handler.addMemberRequest": {"type": "object","required": [diff --git a/docs/swagger.json b/docs/swagger.jsonindex 35c94d568..5c09304e1 100644--- a/docs/swagger.json+++ b/docs/swagger.json@@ -8888,6 +8888,52 @@}}},+ "/me/invitations/accept-by-token": {+ "post": {+ "security": [+ {+ "Bearer": []+ }+ ],+ "description": "已登录用户用共享邀请链接 token 加入空间,不创建新账号;对已是成员的用户幂等。",+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "我的邀请"+ ],+ "summary": "通过共享链接加入空间",+ "parameters": [+ {+ "description": "邀请 token",+ "name": "request",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/internal_handler.acceptInvitationByTokenRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "type": "object",+ "additionalProperties": true+ }+ },+ "410": {+ "description": "链接无效或已撤销",+ "schema": {+ "$ref": "#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError"+ }+ }+ }+ }+ },"/me/invitations/pending-count": {"get": {"security": [@@ -13602,7 +13648,7 @@"Bearer": []}],- "description": "Owner 通过邮箱邀请已注册用户加入当前空间;被邀请人需要在 /me/invitations 接受后才会成为成员。",+ "description": "Owner 通过邮箱邀请已注册用户加入空间。开启 tenant.auto_accept_invitation 后被邀请人立即自动加入(响应为成员结构),否则需在 /me/invitations 接受后成为成员。","consumes": ["application/json"],@@ -20002,7 +20048,8 @@"baidu","searxng","keenable",- "zhipu"+ "zhipu",+ "metaso"],"x-enum-varnames": ["WebSearchProviderTypeBing",@@ -20013,7 +20060,8 @@"WebSearchProviderTypeBaidu","WebSearchProviderTypeSearxng","WebSearchProviderTypeKeenable",- "WebSearchProviderTypeZhipu"+ "WebSearchProviderTypeZhipu",+ "WebSearchProviderTypeMetaso"]},"github_com_Tencent_WeKnora_internal_types.WikiConfig": {@@ -22075,6 +22123,17 @@}}},+ "internal_handler.acceptInvitationByTokenRequest": {+ "type": "object",+ "required": [+ "token"+ ],+ "properties": {+ "token": {+ "type": "string"+ }+ }+ },"internal_handler.addMemberRequest": {"type": "object","required": [diff --git a/docs/swagger.yaml b/docs/swagger.yamlindex 6f77ff9d6..e67f0cf1f 100644--- a/docs/swagger.yaml+++ b/docs/swagger.yaml@@ -3974,6 +3974,7 @@ definitions:- searxng- keenable- zhipu+ - metasotype: stringx-enum-varnames:- WebSearchProviderTypeBing@@ -3985,6 +3986,7 @@ definitions:- WebSearchProviderTypeSearxng- WebSearchProviderTypeKeenable- WebSearchProviderTypeZhipu+ - WebSearchProviderTypeMetasogithub_com_Tencent_WeKnora_internal_types.WikiConfig:properties:content_instructions:@@ -5473,6 +5475,13 @@ definitions:etc. by the JSON unmarshaller). Service.encodeForType normalisesthese against the registry's declared type and rejects mismatches.type: object+ internal_handler.acceptInvitationByTokenRequest:+ properties:+ token:+ type: string+ required:+ - token+ type: objectinternal_handler.addMemberRequest:properties:email:@@ -11583,6 +11592,35 @@ paths:summary: 拒绝邀请tags:- 我的邀请+ /me/invitations/accept-by-token:+ post:+ consumes:+ - application/json+ description: 已登录用户用共享邀请链接 token 加入空间,不创建新账号;对已是成员的用户幂等。+ parameters:+ - description: 邀请 token+ in: body+ name: request+ required: true+ schema:+ $ref: '#/definitions/internal_handler.acceptInvitationByTokenRequest'+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ additionalProperties: true+ type: object+ "410":+ description: 链接无效或已撤销+ schema:+ $ref: '#/definitions/github_com_Tencent_WeKnora_internal_errors.AppError'+ security:+ - Bearer: []+ summary: 通过共享链接加入空间+ tags:+ - 我的邀请/me/invitations/pending-count:get:description: 轻量级 endpoint,返回当前登录用户的 pending 邀请数,用于头像旁的角标轮询。@@ -14414,7 +14452,8 @@ paths:post:consumes:- application/json- description: Owner 通过邮箱邀请已注册用户加入当前空间;被邀请人需要在 /me/invitations 接受后才会成为成员。+ description: Owner 通过邮箱邀请已注册用户加入空间。开启 tenant.auto_accept_invitation 后被邀请人立即自动加入(响应为成员结构),否则需在+ /me/invitations 接受后成为成员。parameters:- description: 空间 IDin: pathdiff --git a/frontend/src/main.ts b/frontend/src/main.tsindex 5da03f654..10d9ae73a 100644--- a/frontend/src/main.ts+++ b/frontend/src/main.ts@@ -18,6 +18,7 @@ import { initTheme } from "@/composables/useTheme";import { initFont } from "@/composables/useFont";import { installTDesignIconOfflineGuard } from "@/utils/tdesign-icon-offline";import { installAutofillGuard } from "@/utils/disable-autofill";+import { useAuthStore } from "@/stores/auth";// 必须在 Vue 组件挂载之前执行,避免 tdesign-icons 运行时请求 tdesign.gtimg.cominstallTDesignIconOfflineGuard();@@ -25,20 +26,36 @@ installTDesignIconOfflineGuard();initTheme();initFont();-const app = createApp(App);+async function bootstrap() {+ const app = createApp(App);-// 全局错误处理:捕获未处理的组件错误,防止白屏-app.config.errorHandler = (err, instance, info) => {- console.error("[WeKnora] Unhandled Vue error:", err, "\nComponent:", instance, "\nInfo:", info);-};+ // 全局错误处理:捕获未处理的组件错误,防止白屏+ app.config.errorHandler = (err, instance, info) => {+ console.error("[WeKnora] Unhandled Vue error:", err, "\nComponent:", instance, "\nInfo:", info);+ };-app.use(TDesign);-app.use(createPinia());-app.use(router);-app.use(i18n);+ app.use(TDesign);+ const pinia = createPinia();+ app.use(pinia);-// 等首屏路由(含导航守卫、Lite 自动登录)完成后再挂载,避免先闪默认页再跳转-router.isReady().finally(() => {+ // Capabilities (can_create_tenant, auto_accept_invitation) are not cached+ // in localStorage — reconcile once before first paint when a session exists.+ const authStore = useAuthStore();+ if (localStorage.getItem("weknora_token")) {+ try {+ await authStore.refreshFromAuthMe();+ } catch {+ // best-effort; capabilities stay at defaults until the next refresh+ }+ }++ app.use(router);+ app.use(i18n);++ // 等首屏路由(含导航守卫、Lite 自动登录)完成后再挂载,避免先闪默认页再跳转+ await router.isReady();app.mount("#app");installAutofillGuard();-});+}++bootstrap();diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.tsindex 8e46dd80d..3996734c4 100644--- a/frontend/src/router/index.ts+++ b/frontend/src/router/index.ts@@ -281,6 +281,10 @@ async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStoreauthStore.setCanCreateTenant(canCreateTenant)}+ authStore.setAutoAcceptInvitation(+ response.data?.capabilities?.auto_accept_invitation === true,+ )+return true} catch {return falsediff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.tsindex 4e293beb9..464cea534 100644--- a/frontend/src/stores/auth.ts+++ b/frontend/src/stores/auth.ts@@ -308,6 +308,10 @@ export const useAuthStore = defineStore('auth', () => {canCreateTenant.value = allowed}+ const setAutoAcceptInvitation = (enabled: boolean) => {+ autoAcceptInvitation.value = enabled+ }+// fetchPendingInvitationCount hits the dedicated /me/invitations/// pending-count endpoint and updates the store. Errors are// swallowed — the badge degrades to its last-known value instead@@ -370,7 +374,7 @@ export const useAuthStore = defineStore('auth', () => {setCanCreateTenant(createCapability)}- autoAcceptInvitation.value = response.data?.capabilities?.auto_accept_invitation === true+ setAutoAcceptInvitation(response.data?.capabilities?.auto_accept_invitation === true)return true} catch {@@ -532,13 +536,6 @@ export const useAuthStore = defineStore('auth', () => {}isLiteMode.value = localStorage.getItem('weknora_lite_mode') === 'true'-- // localStorage only caches user/tenant/memberships — never capabilities.- // Reconcile with /auth/me so deployment switches (can_create_tenant,- // auto_accept_invitation) track the live server, not last-login state.- if (storedToken) {- refreshFromAuthMe()- }}// 初始化时从localStorage恢复状态@@ -585,6 +582,7 @@ export const useAuthStore = defineStore('auth', () => {setMemberships,setPendingInvitationCount,setCanCreateTenant,+ setAutoAcceptInvitation,fetchPendingInvitationCount,refreshFromAuthMe,acceptInvitationByTokenAndRefresh,diff --git a/internal/application/service/tenant_invitation.go b/internal/application/service/tenant_invitation.goindex cc3c11e8b..d25bd5cfe 100644--- a/internal/application/service/tenant_invitation.go+++ b/internal/application/service/tenant_invitation.go@@ -268,6 +268,25 @@ func (s *tenantInvitationService) Accept(return member, nil}+// MarkPendingAcceptedIfExists reconciles a stale per-user pending row when+// tenant.auto_accept_invitation joins the invitee directly. member_added+// audit from AddMember is the authoritative trail; we only flip status here.+func (s *tenantInvitationService) MarkPendingAcceptedIfExists(+ ctx context.Context,+ tenantID uint64,+ inviteeUserID string,+) error {+ s.sweep(ctx)+ inv, err := s.repo.GetPendingByPair(ctx, tenantID, inviteeUserID)+ if err != nil {+ return err+ }+ if inv == nil {+ return nil+ }+ return s.repo.MarkStatusIfPending(ctx, inv.ID, types.TenantInvitationStatusAccepted, s.now())+}+// emitInvitationAccepted writes the rbac.invitation_accepted audit row.// Actor is the invitee (acting on their own inbox); target is the same// user since the action is self-directed.diff --git a/internal/application/service/tenant_invitation_test.go b/internal/application/service/tenant_invitation_test.goindex 1a0b3c2aa..97fcc1446 100644--- a/internal/application/service/tenant_invitation_test.go+++ b/internal/application/service/tenant_invitation_test.go@@ -584,3 +584,33 @@ func TestInvitationService_AcceptByToken_RequiresUserID(t *testing.T) {t.Fatalf("empty user id must be rejected")}}++func TestInvitationService_MarkPendingAcceptedIfExists_NoPending(t *testing.T) {+ svc, _, _ := newInvitationSvc()+ ctx := context.Background()+ if err := svc.MarkPendingAcceptedIfExists(ctx, 1, "u-alice"); err != nil {+ t.Fatalf("MarkPendingAcceptedIfExists: %v", err)+ }+}++func TestInvitationService_MarkPendingAcceptedIfExists_FlipsPendingRow(t *testing.T) {+ svc, invRepo, _ := newInvitationSvc()+ ctx := context.Background()+ inv, err := svc.Create(ctx, 1, "u-alice", types.TenantRoleViewer, nil, "")+ if err != nil {+ t.Fatalf("Create: %v", err)+ }+ if inv.Status != types.TenantInvitationStatusPending {+ t.Fatalf("want pending, got %s", inv.Status)+ }+ if err := svc.MarkPendingAcceptedIfExists(ctx, 1, "u-alice"); err != nil {+ t.Fatalf("MarkPendingAcceptedIfExists: %v", err)+ }+ got, err := invRepo.GetByID(ctx, inv.ID)+ if err != nil {+ t.Fatalf("GetByID: %v", err)+ }+ if got.Status != types.TenantInvitationStatusAccepted {+ t.Fatalf("want accepted, got %s", got.Status)+ }+}diff --git a/internal/handler/tenant_invitation.go b/internal/handler/tenant_invitation.goindex 32b99df51..6b705526f 100644--- a/internal/handler/tenant_invitation.go+++ b/internal/handler/tenant_invitation.go@@ -1,6 +1,7 @@package handlerimport (+ "context""errors""net/http""strconv"@@ -306,8 +307,7 @@ func (h *TenantInvitationHandler) CreateInvitation(c *gin.Context) {c.Error(apperrors.NewInternalServerError("failed to add member"))return}- // Writes the 201 member response / mapped error; auto-accept is done.- addMemberAndRespond(c, ctx, h.memberService, user, tenantID, req.Role, invitedBy)+ h.autoAcceptInvitationAndRespond(c, ctx, user, tenantID, req.Role, invitedBy)return}@@ -345,6 +345,44 @@ func (h *TenantInvitationHandler) CreateInvitation(c *gin.Context) {})}+// autoAcceptInvitationAndRespond adds the invitee as an active member,+// reconciles any stale pending invitation row, and adopts the invited+// tenant as the invitee's home tenant when they are tenantless (same as+// AcceptMyInvitation).+func (h *TenantInvitationHandler) autoAcceptInvitationAndRespond(+ c *gin.Context,+ ctx context.Context,+ user *types.User,+ tenantID uint64,+ role types.TenantRole,+ invitedBy *string,+) {+ member, err := h.memberService.AddMember(ctx, user.ID, tenantID, role, invitedBy)+ if err != nil {+ writeAddMemberError(c, ctx, user, tenantID, err)+ return+ }+ if h.invitationService != nil {+ if markErr := h.invitationService.MarkPendingAcceptedIfExists(ctx, tenantID, user.ID); markErr != nil {+ logger.Warnf(ctx,+ "auto_accept: failed to reconcile pending invitation for user=%s tenant=%d: %v",+ user.ID, tenantID, markErr)+ }+ }+ if user.TenantID == 0 {+ user.TenantID = tenantID+ if updateErr := h.userService.UpdateUser(ctx, user); updateErr != nil {+ logger.Errorf(ctx,+ "auto_accept: member added but default tenant update failed: user=%s tenant=%d err=%v",+ user.ID, tenantID, updateErr)+ c.Error(apperrors.NewInternalServerError(+ "member added but default workspace update failed").WithDetails(updateErr.Error()))+ return+ }+ }+ writeAddMemberSuccess(c, user, member)+}+// RevokeInvitation godoc// @Summary 撤销待接受邀请// @Description Owner 取消一条还在 pending 的邀请;已 accepted/declined/revoked/expired 的行不可再撤销。@@ -553,7 +591,7 @@ type acceptInvitationByTokenRequest struct {// @Produce json// @Param request body acceptInvitationByTokenRequest true "邀请 token"// @Success 200 {object} map[string]interface{}-// @Failure 410 {object} errors.AppError "链接无效或已撤销"+// @Failure 410 {object} apperrors.AppError "链接无效或已撤销"// @Security Bearer// @Router /me/invitations/accept-by-token [post]func (h *TenantInvitationHandler) AcceptMyInvitationByToken(c *gin.Context) {diff --git a/internal/handler/tenant_invitation_auto_accept_test.go b/internal/handler/tenant_invitation_auto_accept_test.goindex 00939cee6..e950bb001 100644--- a/internal/handler/tenant_invitation_auto_accept_test.go+++ b/internal/handler/tenant_invitation_auto_accept_test.go@@ -53,8 +53,10 @@ func (s *autoAcceptMemberSvc) AddMember(_ context.Context, userID string, _ uint// autoAcceptUserSvc resolves GetUserByEmail for the 404 / happy paths.type autoAcceptUserSvc struct {interfaces.UserService- user *types.User- uerr error+ user *types.User+ uerr error+ updatedTenant uint64+ updateCalled bool}func (s *autoAcceptUserSvc) GetUserByEmail(_ context.Context, _ string) (*types.User, error) {@@ -65,11 +67,18 @@ func (s *autoAcceptUserSvc) GetUserByID(_ context.Context, _ string) (*types.Usereturn nil, nil}+func (s *autoAcceptUserSvc) UpdateUser(_ context.Context, user *types.User) error {+ s.updateCalled = true+ s.updatedTenant = user.TenantID+ return nil+}+// autoAcceptInvitationSvc records whether the classic pending-invitation// flow was reached (it must NOT run when auto-accept is on).type autoAcceptInvitationSvc struct {interfaces.TenantInvitationService- created bool+ created bool+ reconcilePending bool}func (s *autoAcceptInvitationSvc) Create(_ context.Context, tenantID uint64, userID string, role types.TenantRole, _ *string, _ string) (*types.TenantInvitation, error) {@@ -83,6 +92,11 @@ func (s *autoAcceptInvitationSvc) Create(_ context.Context, tenantID uint64, use}, nil}+func (s *autoAcceptInvitationSvc) MarkPendingAcceptedIfExists(_ context.Context, _ uint64, _ string) error {+ s.reconcilePending = true+ return nil+}+func newAutoAcceptTestRouter(h *TenantInvitationHandler) *gin.Engine {gin.SetMode(gin.TestMode)r := gin.New()@@ -124,6 +138,9 @@ func TestCreateInvitation_AutoAcceptEnabled_AddsMemberDirectly(t *testing.T) {if invites.created {t.Fatal("auto-accept must not create a pending invitation row")}+ if !invites.reconcilePending {+ t.Fatal("auto-accept should reconcile any stale pending invitation")+ }var resp struct {Success bool `json:"success"`Data struct {@@ -252,3 +269,27 @@ func TestCreateInvitation_AutoAcceptEnabled_NilMemberServiceReturns500(t *testint.Fatal("memberService nil must not silently fall back to invitation flow")}}++func TestCreateInvitation_AutoAccept_AdoptsTenantlessInviteeHomeTenant(t *testing.T) {+ users := &autoAcceptUserSvc{+ user: &types.User{ID: "u-bob", Email: "[email protected]", Username: "bob", TenantID: 0},+ }+ members := &autoAcceptMemberSvc{}+ invites := &autoAcceptInvitationSvc{}+ h := &TenantInvitationHandler{+ invitationService: invites,+ userService: users,+ memberService: members,+ systemSettingSvc: &autoAcceptSettingSvc{enabled: true},+ }+ r := newAutoAcceptTestRouter(h)++ w := postAutoAcceptInvitation(t, r, `{"email":"[email protected]","role":"contributor"}`)+ if w.Code != http.StatusCreated {+ t.Fatalf("status=%d body=%s", w.Code, w.Body.String())+ }+ if !users.updateCalled || users.updatedTenant != 7 {+ t.Fatalf("tenantless invitee should adopt tenant 7, updateCalled=%v updatedTenant=%d",+ users.updateCalled, users.updatedTenant)+ }+}diff --git a/internal/handler/tenant_member.go b/internal/handler/tenant_member.goindex 4badbae99..cfcf66037 100644--- a/internal/handler/tenant_member.go+++ b/internal/handler/tenant_member.go@@ -240,39 +240,30 @@ func (h *TenantMemberHandler) AddMember(c *gin.Context) {addMemberAndRespond(c, ctx, h.memberService, user, tenantID, req.Role, invitedBy)}-// addMemberAndRespond calls TenantMemberService.AddMember and writes the-// HTTP response: 201 with a TenantMemberResponse on success, or the service-// sentinel mapped to its HTTP status (400 / 403 / 409 / 500) on error. It-// always writes exactly one response, so the caller MUST return right after.-// Shared by TenantMemberHandler.AddMember and the auto-accept branch of-// TenantInvitationHandler.CreateInvitation so the mapping never drifts.-func addMemberAndRespond(+func writeAddMemberError(c *gin.Context,ctx context.Context,- memberService interfaces.TenantMemberService,user *types.User,tenantID uint64,- role types.TenantRole,- invitedBy *string,+ err error,) {- member, err := memberService.AddMember(ctx, user.ID, tenantID, role, invitedBy)- if err != nil {- switch {- case errors.Is(err, service.ErrInvalidTenantRole):- c.Error(apperrors.NewValidationError(err.Error()))- case errors.Is(err, service.ErrAPIKeyCannotAssignOwner):- c.Error(apperrors.NewForbiddenError(err.Error()))- case errors.Is(err, service.ErrMembershipAlreadyExists):- // 409 reads better than 400 here: the request was syntactically- // fine, the conflict is semantic ("already a member").- c.Error(apperrors.NewConflictError(err.Error()))- default:- logger.Errorf(ctx, "AddMember failed: user=%s tenant=%d err=%v",- user.ID, tenantID, err)- c.Error(apperrors.NewInternalServerError("failed to add member").WithDetails(err.Error()))- }- return+ switch {+ case errors.Is(err, service.ErrInvalidTenantRole):+ c.Error(apperrors.NewValidationError(err.Error()))+ case errors.Is(err, service.ErrAPIKeyCannotAssignOwner):+ c.Error(apperrors.NewForbiddenError(err.Error()))+ case errors.Is(err, service.ErrMembershipAlreadyExists):+ // 409 reads better than 400 here: the request was syntactically+ // fine, the conflict is semantic ("already a member").+ c.Error(apperrors.NewConflictError(err.Error()))+ default:+ logger.Errorf(ctx, "AddMember failed: user=%s tenant=%d err=%v",+ user.ID, tenantID, err)+ c.Error(apperrors.NewInternalServerError("failed to add member").WithDetails(err.Error()))}+}++func writeAddMemberSuccess(c *gin.Context, user *types.User, member *types.TenantMember) {// Project the freshly added row through the same response shape the// list endpoint uses, so the UI can swap "Add Member" UX into the// table without an extra round-trip.@@ -291,6 +282,29 @@ func addMemberAndRespond(})}+// addMemberAndRespond calls TenantMemberService.AddMember and writes the+// HTTP response: 201 with a TenantMemberResponse on success, or the service+// sentinel mapped to its HTTP status (400 / 403 / 409 / 500) on error. It+// always writes exactly one response, so the caller MUST return right after.+// Shared by TenantMemberHandler.AddMember and the auto-accept branch of+// TenantInvitationHandler.CreateInvitation so the mapping never drifts.+func addMemberAndRespond(+ c *gin.Context,+ ctx context.Context,+ memberService interfaces.TenantMemberService,+ user *types.User,+ tenantID uint64,+ role types.TenantRole,+ invitedBy *string,+) {+ member, err := memberService.AddMember(ctx, user.ID, tenantID, role, invitedBy)+ if err != nil {+ writeAddMemberError(c, ctx, user, tenantID, err)+ return+ }+ writeAddMemberSuccess(c, user, member)+}+// UpdateMemberRole godoc// @Summary 修改空间成员角色// @Description Owner 修改某位成员在当前空间内的角色;不能将最后一位 Owner 降级diff --git a/internal/types/interfaces/tenant_invitation_service.go b/internal/types/interfaces/tenant_invitation_service.goindex 865c3b0b6..5f6b12e26 100644--- a/internal/types/interfaces/tenant_invitation_service.go+++ b/internal/types/interfaces/tenant_invitation_service.go@@ -94,4 +94,9 @@ type TenantInvitationService interface {// same link. Idempotent: if the user already has membership, the// existing row is returned.AcceptByToken(ctx context.Context, plainToken string, newUserID string) (*types.TenantMember, error)++ // MarkPendingAcceptedIfExists transitions a per-user pending invitation+ // into accepted when auto-accept joins the invitee without inbox+ // confirmation. No-op when no pending row exists.+ MarkPendingAcceptedIfExists(ctx context.Context, tenantID uint64, inviteeUserID string) error}