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
feat(rbac-ui): rework tenant identity surfaces
wizardchene7f9a6580ae6
diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vueindex 02578a20e..0fdebff12 100644--- a/frontend/src/components/UserMenu.vue+++ b/frontend/src/components/UserMenu.vue@@ -8,8 +8,36 @@</div><template v-if="!uiStore.sidebarCollapsed"><div class="user-info">- <div class="user-name">{{ userName }}</div>- <div class="user-email">{{ userEmail }}</div>+ <!-- 多租户 / superuser 视角下,左下角入口的两行让位给租户身份信息:+ 第一行 = tenant 名(独占整行,避免被 icon / 徽标挤压成省略号)。+ 第二行 caption = username · [角色图标] 角色名。+ - username 仍露出,让用户切到非 home tenant 后能确认账号;+ - 角色图标与角色名连读,跟切租户子菜单 / dropdown 顶部+ 保持视觉一致(同一份 roleIcon mapping)。+ - 当 tenant 名 === username 时(自创 home tenant 的 fallback 情况)+ 只显示一次 username 避免重复;其它情况都拼出完整 caption。+ 单租户用户没有切租户语义,保留原本的 username + email 布局。 -->+ <template v-if="showTenantIdentityLine">+ <div class="user-tenant-name" :title="activeTenantName">{{ activeTenantName }}</div>+ <div class="user-tenant-meta">+ <span v-if="userName && userName !== activeTenantName" class="user-tenant-meta-name">{{ userName }}</span>+ <span+ v-if="(userName && userName !== activeTenantName) && currentRoleLabel"+ class="user-tenant-meta-sep"+ >·</span>+ <t-icon+ v-if="currentRoleIcon"+ :name="currentRoleIcon"+ size="11px"+ class="user-tenant-meta-icon"+ />+ <span v-if="currentRoleLabel" class="user-tenant-meta-role">{{ currentRoleLabel }}</span>+ </div>+ </template>+ <template v-else>+ <div class="user-name">{{ userName }}</div>+ <div class="user-email">{{ userEmail }}</div>+ </template></div><t-icon :name="menuVisible ? 'chevron-up' : 'chevron-down'" class="dropdown-icon" /></template>@@ -18,15 +46,59 @@<!-- 下拉菜单 --><Transition name="dropdown"><div v-if="menuVisible" class="user-dropdown" @click.stop>- <div class="menu-item" @click="handleQuickNav('models')">+ <!-- 顶部「切换租户」入口:单行高密度信息。+ 只展示当前 tenant 名 + 角色 caption,hover 出切租户子菜单。+ 之前堆了 home icon + username + 角色 + chevron 在一起,视觉+ 太密;trigger 按钮里已经有完整的 tenant + home + 角色信息,+ 这里 dropdown 只需要让用户「秒识别这是切租户入口」即可。+ home / 当前 徽标已经在切租户子菜单里 per-row 标注了,+ 顶部入口本身不需要再多一份指示。 -->+ <div+ v-if="userName"+ ref="tenantMenuItemRef"+ class="dropdown-identity"+ :class="{+ 'is-open': tenantSubmenuOpen,+ 'is-clickable': showTenantSwitcher,+ }"+ @mouseenter="showTenantSwitcher && showTenantSubmenu()"+ @mouseleave="showTenantSwitcher && scheduleHideTenantSubmenu()"+ >+ <div class="dropdown-identity-main">+ <span class="dropdown-identity-tenant" :title="activeTenantName || userName">+ {{ activeTenantName || userName }}+ </span>+ <t-icon+ v-if="showTenantSwitcher"+ name="swap"+ class="dropdown-identity-arrow"+ :title="$t('tenant.switcher.menuLabel')"+ />+ </div>+ <div v-if="currentRoleLabel" class="dropdown-identity-caption">+ <t-icon+ v-if="currentRoleIcon"+ :name="currentRoleIcon"+ size="12px"+ class="dropdown-identity-caption-icon"+ />+ <span>{{ currentRoleLabel }}</span>+ </div>+ </div>+ <div class="menu-divider"></div>+ <!-- QuickNav 入口与 Settings 的最低角色对齐:models/websearch/mcp/api+ 分别对应 viewer/admin/admin/owner(详情见 Settings.vue 的+ SECTION_MIN_ROLE)。低角色用户看到这些入口点进去也只能看到+ role-denied 兜底页,索性藏起来。 -->+ <div v-if="canSeeQuickNav('models')" class="menu-item" @click="handleQuickNav('models')"><t-icon name="control-platform" class="menu-icon" /><span>{{ $t('settings.modelManagement') }}</span></div>- <div class="menu-item" @click="handleQuickNav('websearch')">- <svg- width="16"- height="16"- viewBox="0 0 18 18"+ <div v-if="canSeeQuickNav('websearch')" class="menu-item" @click="handleQuickNav('websearch')">+ <svg+ width="16"+ height="16"+ viewBox="0 0 18 18"fill="none"xmlns="http://www.w3.org/2000/svg"class="menu-icon svg-icon"@@ -39,11 +111,11 @@</svg><span>{{ $t('settings.webSearchConfig') }}</span></div>- <div class="menu-item" @click="handleQuickNav('mcp')">+ <div v-if="canSeeQuickNav('mcp')" class="menu-item" @click="handleQuickNav('mcp')"><t-icon name="tools" class="menu-icon" /><span>{{ $t('settings.mcpService') }}</span></div>- <div class="menu-item" @click="handleQuickNav('api')">+ <div v-if="canSeeQuickNav('api')" class="menu-item" @click="handleQuickNav('api')"><t-icon name="secured" class="menu-icon" /><span>{{ $t('settings.apiInfo') }}</span></div>@@ -71,23 +143,8 @@<t-icon name="setting" class="menu-icon" /><span>{{ $t('general.allSettings') }}</span></div>- <!-- Tenant switcher submenu — only meaningful when the user belongs- to more than one tenant. Superusers (canAccessAllTenants) keep- using the sidebar TenantSelector for "any tenant in the system";- the entry here is the curated "tenants I'm a member of" list,- matching what the backend memberships claim covers. -->- <div- v-if="showTenantSwitcher"- ref="tenantMenuItemRef"- class="menu-item menu-item--submenu"- :class="{ 'is-open': tenantSubmenuOpen }"- @mouseenter="showTenantSubmenu"- @mouseleave="scheduleHideTenantSubmenu"- >- <t-icon name="swap" class="menu-icon" />- <span class="menu-item-label">{{ $t('tenant.switcher.menuLabel') }}</span>- <t-icon name="chevron-right" class="menu-chevron" />- </div>+ <!-- 切换租户入口已移到顶部身份卡(dropdown-identity-row--tenant),+ 这里不再单独列条目,避免和身份卡里的「当前租户 + 切换」重复。 --><div class="menu-divider"></div><div class="menu-item" @click="openClawhubSkill"><span class="menu-icon menu-icon--emoji" role="img" :aria-label="$t('common.clawhubSkill')">🦞</span>@@ -185,15 +242,40 @@><div class="tenant-submenu-item-avatar" :class="{ 'is-current': isCurrentTenant(m.tenant_id) }">{{ tenantInitial(m) }}+ <!-- Home 标识:home tenant 行的 avatar 右下角加一个小 home+ icon。比起在 meta 行单独立一个「我的」pill,这里更省地、+ 也保持各行徽标列对齐。 -->+ <span+ v-if="isHomeTenant(m.tenant_id)"+ class="tenant-submenu-item-home-dot"+ :title="$t('tenant.switcher.homeTooltip')"+ >+ <t-icon name="home" size="9px" />+ </span></div>+ <!-- 两行布局:第一行是 tenant 名(拿满剩余宽度,避免被徽标截断+ — 之前 home + 当前 两个徽标在同一行时,长 tenant 名直接+ 被压成省略号);第二行 role(带角色图标) + 「当前」徽标。+ home 徽标已挪到 tenant 名首字母 avatar 角落,不再在 meta+ 行额外占位,避免徽标列宽不齐。 --><div class="tenant-submenu-item-info"><span class="tenant-submenu-item-name">{{ tenantDisplayName(m) }}</span>- <span class="tenant-submenu-item-role">{{ formatRole(m.role) }}</span>+ <div class="tenant-submenu-item-meta">+ <span class="tenant-submenu-item-role">+ <t-icon+ v-if="roleIcon(m.role)"+ :name="roleIcon(m.role)"+ size="12px"+ class="tenant-submenu-item-role-icon"+ />+ {{ formatRole(m.role) }}+ </span>+ <span+ v-if="isCurrentTenant(m.tenant_id)"+ class="tenant-submenu-item-badge"+ >{{ $t('tenant.switcher.currentBadge') }}</span>+ </div></div>- <span- v-if="isCurrentTenant(m.tenant_id)"- class="tenant-submenu-item-badge"- >{{ $t('tenant.switcher.currentBadge') }}</span></div><div v-if="switchableMemberships.length === 0" class="tenant-submenu-empty">{{ $t('tenant.switcher.empty') }}@@ -215,12 +297,50 @@ import { useI18n } from 'vue-i18n'import IMChannelsOverviewPanel from '@/components/IMChannelsOverviewPanel.vue'import { listAllIMChannels, type IMChannelOverview } from '@/api/agent'import { navigateAfterTenantSwitch } from '@/utils/tenantSwitch'+import { useRoleLabel, useHomeTenant } from '@/composables/useRoleLabel'const { t } = useI18n()const router = useRouter()const uiStore = useUIStore()const authStore = useAuthStore()+const { formatRole, roleIcon } = useRoleLabel()+const { homeTenantId, isHomeTenantActive, isHomeTenant } = useHomeTenant()++// 顶部用户卡片展示的租户名 / 当前角色:跟着 tenant 切换器实时变。+// activeTenantName 优先用切换器选中的名字(含 fallback 到 home tenant 名字),+// 单租户用户也能正常显示自己的 home tenant 名。+const activeTenantName = computed(() => {+ return (+ authStore.selectedTenantName ||+ authStore.tenant?.name ||+ ''+ )+})+const currentRoleLabel = computed(() => formatRole(authStore.currentTenantRole))+const currentRoleIcon = computed(() => roleIcon(authStore.currentTenantRole))++// 单租户用户(memberships <= 1 且非 superuser)= 永远 home + owner,第三+// 行就是 user-email 信息的重复,没必要占视觉空间;只对多租户 / superuser+// 渲染。Lite 模式下没有 RBAC 概念,统一隐藏。+const showTenantIdentityLine = computed(() => {+ if (authStore.isLiteMode) return false+ if (authStore.canAccessAllTenants) return true+ return (authStore.memberships ?? []).length > 1+})++// 与 Settings.vue 的 SECTION_MIN_ROLE 同步;这里只挂 quickNav 直接跳转的+// 那 4 项。改这张表前请同步 Settings.vue 的对照注释。+const QUICKNAV_MIN_ROLE: Record<string, 'viewer' | 'contributor' | 'admin' | 'owner'> = {+ models: 'viewer',+ websearch: 'admin',+ mcp: 'admin',+ api: 'owner',+}+const canSeeQuickNav = (key: string): boolean => {+ if (authStore.canAccessAllTenants) return true+ return authStore.hasRole(QUICKNAV_MIN_ROLE[key] ?? 'viewer')+}const menuRef = ref<HTMLElement>()const imMenuItemRef = ref<HTMLElement>()@@ -346,16 +466,6 @@ const tenantInitial = (m: Membership) => {return (name.charAt(0) || '?').toUpperCase()}-const formatRole = (role: string) => {- // Roles match the backend enum: viewer/contributor/admin/owner. The- // i18n bundle already carries human labels under tenantMember.role.*- // (see PR 3); reuse those rather than inventing a new key namespace.- const key = `tenantMember.role.${role}`- const label = t(key)- // Fallback when the locale doesn't have the key: show the raw role.- return label === key ? role : label-}-const switchToTenant = (m: Membership) => {if (isCurrentTenant(m.tenant_id)) {closeAll()@@ -364,8 +474,8 @@ const switchToTenant = (m: Membership) => {// Treat switching back to the user's home tenant as "clear the// override" so request.ts stops attaching X-Tenant-ID. This mirrors// what TenantSelector.vue does in selectTenant().- const homeTenantId = authStore.tenant?.id ? Number(authStore.tenant.id) : null- if (homeTenantId !== null && homeTenantId === m.tenant_id) {+ const home = homeTenantId.value+ if (home !== null && home === m.tenant_id) {authStore.setSelectedTenant(null, null)} else {authStore.setSelectedTenant(m.tenant_id, tenantDisplayName(m))@@ -677,6 +787,52 @@ onUnmounted(() => {overflow: hidden;text-overflow: ellipsis;}++ // 多租户视角下取代 user-name + user-email 的两行:第一行 tenant 名+ // (独占整行,让长名字也不被截),第二行 home icon(home active 时)+ // + role。视觉权重对齐 user-name + user-email,整体布局高度不变。+ .user-tenant-name {+ font-size: 14px;+ font-weight: 500;+ color: var(--td-text-color-primary);+ line-height: 1.3;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ // 第二行 caption 行:username + 角色名(拼接 「user · ✏ 编辑」)。+ // 长 username 优先压缩 / 截断,保留尾部的 role icon + role 名 — 用户+ // 「我现在的角色」比 username 更高频要看清。+ .user-tenant-meta {+ display: flex;+ align-items: center;+ gap: 4px;+ margin-top: 1px;+ min-width: 0;+ font-size: 12px;+ line-height: 1.3;+ color: var(--td-text-color-secondary);++ .user-tenant-meta-name {+ flex: 0 1 auto;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ }+ .user-tenant-meta-sep {+ flex-shrink: 0;+ color: var(--td-text-color-placeholder);+ }+ .user-tenant-meta-icon {+ flex-shrink: 0;+ color: inherit;+ }+ .user-tenant-meta-role {+ flex-shrink: 0;+ }+ }}.dropdown-icon {@@ -700,6 +856,74 @@ onUnmounted(() => {z-index: 1000;}+// 顶部「切换租户」入口:单块、hover 即可切租户。极简两行 — 主行 tenant+// 名 + chevron,caption 只放角色。home icon 不在这里出现(trigger 按钮+// 已经画了一份;切租户子菜单里 per-row 也会标注 home),避免顶部入口+// 多一个图标显得拥挤。+.dropdown-identity {+ display: flex;+ flex-direction: column;+ gap: 2px;+ padding: 12px 16px;+ transition: background 0.15s ease;++ &.is-clickable {+ cursor: pointer;++ &:hover,+ &.is-open {+ background: var(--td-bg-color-container-hover);++ .dropdown-identity-arrow {+ color: var(--td-text-color-secondary);+ }+ }+ }++ .dropdown-identity-main {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ }++ .dropdown-identity-tenant {+ flex: 1;+ min-width: 0;+ font-size: 14px;+ font-weight: 500;+ color: var(--td-text-color-primary);+ line-height: 1.3;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }++ .dropdown-identity-arrow {+ flex-shrink: 0;+ font-size: 14px;+ color: var(--td-text-color-placeholder);+ transition: color 0.15s ease;+ }++ .dropdown-identity-caption {+ display: flex;+ align-items: center;+ gap: 4px;+ font-size: 12px;+ color: var(--td-text-color-secondary);+ line-height: 1.3;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;++ .dropdown-identity-caption-icon {+ flex-shrink: 0;+ color: inherit;+ }+ }+}+.menu-item {display: flex;align-items: center;@@ -995,7 +1219,7 @@ onUnmounted(() => {min-width: 0;display: flex;flex-direction: column;- gap: 1px;+ gap: 2px;}.tenant-submenu-item-name {@@ -1006,9 +1230,28 @@ onUnmounted(() => {text-overflow: ellipsis;}+ // 第二行:role + 徽标,以 inline 形式排在一起。徽标缩到次级位置,+ // 让第一行的 tenant 名拿满宽度(之前长名字会被徽标挤成省略号)。+ .tenant-submenu-item-meta {+ display: flex;+ align-items: center;+ gap: 6px;+ flex-wrap: wrap;+ min-width: 0;+ }+.tenant-submenu-item-role {+ display: inline-flex;+ align-items: center;+ gap: 4px;font-size: 11px;color: var(--td-text-color-placeholder);++ .tenant-submenu-item-role-icon {+ flex-shrink: 0;+ // 颜色继承 role 文字色,避免抢走视觉+ color: inherit;+ }}.tenant-submenu-item-badge {@@ -1022,6 +1265,29 @@ onUnmounted(() => {color: var(--td-brand-color);}+ // Home 标识改为叠在 avatar 右下角的小 dot,不在 meta 行额外占位,让+ // 各行徽标列宽对齐;用户切到非 home tenant 时这个小 icon 仍能一眼指+ // 出「我的主租户在哪一行」。+ .tenant-submenu-item-avatar {+ position: relative;+ }+ .tenant-submenu-item-home-dot {+ position: absolute;+ right: -3px;+ bottom: -3px;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: var(--td-bg-color-container);+ color: var(--td-brand-color);+ border: 1.5px solid var(--td-bg-color-container);+ display: flex;+ align-items: center;+ justify-content: center;+ pointer-events: none;+ box-shadow: 0 0 0 0.5px var(--td-success-color-light);+ }+.tenant-submenu-empty {padding: 16px 12px;text-align: center;diff --git a/frontend/src/composables/useRoleLabel.ts b/frontend/src/composables/useRoleLabel.tsnew file mode 100644index 000000000..01a3f2abe--- /dev/null+++ b/frontend/src/composables/useRoleLabel.ts@@ -0,0 +1,74 @@+import { computed } from 'vue'+import { useI18n } from 'vue-i18n'+import { useAuthStore } from '@/stores/auth'++/**+ * Format a tenant role enum value ('viewer' | 'contributor' | 'admin' | 'owner')+ * into the user-facing label declared under tenantMember.role.* in the i18n+ * bundle. Falls back to the raw role string when the locale does not carry+ * the key — same behaviour as the inline helper this used to live in+ * (UserMenu.vue), now extracted so role-aware UI gates across views can+ * share one implementation.+ *+ * `roleIcon(role)` returns a TDesign icon name suitable for prefixing the+ * role label (e.g. in tenant switcher rows). The mapping is intentionally+ * limited to icons already known to ship in this codebase to avoid a+ * runtime "icon not found" footgun on uncommon role names.+ */+export function useRoleLabel() {+ const { t } = useI18n()+ const formatRole = (role: string | null | undefined): string => {+ if (!role) return ''+ const key = `tenantMember.role.${role}`+ const label = t(key)+ return label === key ? role : label+ }+ const ROLE_ICONS: Record<string, string> = {+ owner: 'secured',+ admin: 'user-circle',+ contributor: 'edit',+ viewer: 'browse',+ }+ const roleIcon = (role: string | null | undefined): string =>+ (role && ROLE_ICONS[role]) || ''+ return { formatRole, roleIcon }+}++/**+ * Derive home-tenant identity helpers off the auth store. The home tenant+ * is the tenant the user was registered into — the row id stored on the+ * users table at signup time, exposed via `authStore.user.tenant_id` and+ * never mutated by /auth/switch-tenant.+ *+ * IMPORTANT: do NOT read `authStore.tenant?.id` here. That field is the+ * *active* tenant returned by /auth/me (see internal/handler/auth.go+ * GetCurrentUser — it deliberately reflects the X-Tenant-ID override).+ * After a tenant switch, `authStore.tenant.id` becomes the peer tenant+ * id; treating it as "home" makes the home badge follow the user across+ * switches and incorrectly mark whichever tenant they're currently in.+ *+ * `activeTenantId` is the currently selected tenant (= home id when no+ * override is in play), used by `isHomeTenantActive` to answer "am I+ * sitting in my home tenant right now?".+ */+export function useHomeTenant() {+ const authStore = useAuthStore()+ const homeTenantId = computed<number | null>(() => {+ const raw = authStore.user?.tenant_id+ if (raw === null || raw === undefined || raw === '') return null+ const n = Number(raw)+ return Number.isFinite(n) && n > 0 ? n : null+ })+ const activeTenantId = computed<number | null>(() => authStore.effectiveTenantId)+ const isHomeTenantActive = computed(() => {+ const home = homeTenantId.value+ const active = activeTenantId.value+ return home !== null && active !== null && home === active+ })+ const isHomeTenant = (id: number | string | null | undefined): boolean => {+ if (id === null || id === undefined || id === '') return false+ const home = homeTenantId.value+ return home !== null && Number(id) === home+ }+ return { homeTenantId, activeTenantId, isHomeTenantActive, isHomeTenant }+}diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.tsindex 53f4d6383..41bdb1439 100755--- a/frontend/src/i18n/locales/en-US.ts+++ b/frontend/src/i18n/locales/en-US.ts@@ -642,6 +642,10 @@ export default {workspace: 'Workspace & Access',system: 'System Info',},+ roleDenied: {+ title: 'Insufficient permissions',+ desc: "Your role can't access this settings page. Ask an admin of this tenant to grant the required role.",+ },weknoraCloud: {title: 'WeKnora Cloud',description: 'Configure WeKnora Cloud APPID and APPSECRET credentials. Credentials are used for model services and document parsing engine.',@@ -2278,8 +2282,13 @@ export default {switcher: {menuLabel: 'Switch Tenant',currentBadge: 'Current',+ homeBadge: 'Home',+ homeTooltip: 'Your home tenant',empty: 'You only belong to one tenant',},+ currentChip: {+ home: 'Home tenant',+ },sectionDescription: 'View detailed configuration for the tenant',apiDocument: 'API Document',name: 'Tenant Name',@@ -4315,6 +4324,10 @@ export default {confirmRemoveBody:'This permanently deletes the stored credential. Integrations using it will stop working until you configure a new value.',},+ userProfile: {+ title: 'User Profile',+ description: 'View your account info (user ID, username, email, registration time).',+ },tenantMember: {title: 'Members',sectionDescription: 'Invite teammates to the tenant and manage their roles. Only Owner can add or remove members.',diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.tsindex f39baec69..dbbe53bd8 100755--- a/frontend/src/i18n/locales/ko-KR.ts+++ b/frontend/src/i18n/locales/ko-KR.ts@@ -518,6 +518,10 @@ export default {workspace: "공간 및 권한",system: "시스템 정보",},+ roleDenied: {+ title: "권한 없음",+ desc: "현재 역할로는 이 설정 페이지에 접근할 수 없습니다. 이 테넌트의 관리자에게 필요한 역할을 요청하세요.",+ },weknoraCloud: {title: 'WeKnora Cloud',description: 'WeKnora Cloud APPID 및 APPSECRET 자격 증명을 설정합니다. 자격 증명은 모델 서비스와 문서 파싱 엔진에 사용됩니다.',@@ -1536,8 +1540,13 @@ export default {switcher: {menuLabel: "테넌트 전환",currentBadge: "현재",+ homeBadge: "Home",+ homeTooltip: "기본 테넌트",empty: "현재 하나의 테넌트에만 속해 있습니다",},+ currentChip: {+ home: "기본 테넌트",+ },sectionDescription: "테넌트의 상세 설정 정보 보기",apiDocument: "API 문서",name: "테넌트 이름",@@ -4375,6 +4384,10 @@ export default {confirmRemoveBody:"저장된 credential이 영구적으로 삭제되며, 이를 사용하는 통합은 새 값을 구성할 때까지 동작하지 않습니다.",},+ userProfile: {+ title: "사용자 정보",+ description: "계정 기본 정보(사용자 ID, 사용자 이름, 이메일, 가입 시각)를 확인합니다.",+ },tenantMember: {title: "멤버 관리",sectionDescription: "테넌트에 동료를 초대하고 역할을 관리합니다. 소유자만 멤버를 추가하거나 제거할 수 있습니다.",diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.tsindex f0c9af6df..159635946 100755--- a/frontend/src/i18n/locales/ru-RU.ts+++ b/frontend/src/i18n/locales/ru-RU.ts@@ -627,6 +627,10 @@ export default {workspace: 'Пространство и доступ',system: 'Сведения о системе',},+ roleDenied: {+ title: 'Недостаточно прав',+ desc: 'Ваша роль не позволяет открыть этот раздел настроек. Обратитесь к администратору арендатора, чтобы запросить нужную роль.',+ },weknoraCloud: {title: 'WeKnora Cloud',description: 'Настройте учётные данные APPID и APPSECRET для WeKnora Cloud. Данные используются для модельных сервисов и движка парсинга документов.',@@ -1354,8 +1358,13 @@ export default {switcher: {menuLabel: 'Сменить арендатора',currentBadge: 'Текущий',+ homeBadge: 'Home',+ homeTooltip: 'Ваш основной арендатор',empty: 'Вы состоите только в одном арендаторе',},+ currentChip: {+ home: 'Основной арендатор',+ },sectionDescription: 'Просмотр детальной конфигурации арендатора',apiDocument: 'Документация API',name: 'Имя арендатора',@@ -4275,6 +4284,10 @@ export default {confirmRemoveBody:'Сохранённые учётные данные будут безвозвратно удалены. Интеграции, использующие их, перестанут работать до настройки нового значения.',},+ userProfile: {+ title: 'Информация о пользователе',+ description: 'Просмотр базовых данных аккаунта (ID пользователя, имя, email, дата регистрации).',+ },tenantMember: {title: 'Участники',sectionDescription: 'Приглашайте коллег в тенант и управляйте их ролями. Добавлять и удалять участников может только Владелец.',diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.tsindex fec0a873b..e231442db 100755--- a/frontend/src/i18n/locales/zh-CN.ts+++ b/frontend/src/i18n/locales/zh-CN.ts@@ -515,7 +515,10 @@ export default {workspace: "空间与权限",system: "系统信息",},- weknoraCloud: {+ roleDenied: {+ title: "权限不足",+ desc: "你当前的角色无权访问此设置项。请联系本租户的管理员获取所需角色。",+ }, weknoraCloud: {title: "WeKnora Cloud",description: "配置 WeKnora Cloud 的 APPID 和 APPSECRET 凭证。凭证用于模型服务和文档解析引擎。",viewDocs: "查看文档",@@ -1517,8 +1520,13 @@ export default {switcher: {menuLabel: "切换租户",currentBadge: "当前",+ homeBadge: "我的",+ homeTooltip: "我的租户",empty: "你目前只属于这一个租户",},+ currentChip: {+ home: "我的租户",+ },sectionDescription: "查看租户的详细配置信息",apiDocument: "API文档",name: "租户名称",@@ -4308,6 +4316,10 @@ export default {confirmRemoveBody:"此操作将永久删除已保存的凭据,依赖它的集成将停止工作,直到您重新配置。",},+ userProfile: {+ title: "用户信息",+ description: "查看您的账户基础信息(用户 ID、用户名、邮箱、注册时间)",+ },tenantMember: {title: "成员管理",sectionDescription: "邀请伙伴加入当前租户并分配角色。只有 Owner 可以新增或移除成员。",@@ -4333,10 +4345,10 @@ export default {joinedAt: "加入时间",},role: {- owner: "拥有者",+ owner: "所有者",admin: "管理员",- contributor: "贡献者",- viewer: "查看者",+ contributor: "编辑",+ viewer: "访客",},add: {button: "邀请成员",diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vueindex f29c8a491..40c7310d9 100644--- a/frontend/src/views/agent/AgentList.vue+++ b/frontend/src/views/agent/AgentList.vue@@ -582,8 +582,12 @@ interface AgentWithUI extends CustomAgent {/** Merged agent for "all" tab: my agents (isMine: true) or shared (isMine: false, org_name, source_tenant_id, share_id, disabled_by_me?) */type DisplayAgent = (AgentWithUI & { isMine: true }) | (CustomAgent & { isMine: false; org_name: string; source_tenant_id: number; share_id: string; showMore?: boolean; disabled_by_me?: boolean })-// 左侧空间选择:我的 / 空间 ID(已去掉「全部」)-const spaceSelection = ref<'all' | 'mine' | string>('mine')+// 左侧空间选择:默认根据当前角色决定。+// 与 KnowledgeBaseList 同款逻辑:Viewer 在当前租户里通常没有自建智能体,+// 默认落到 "all" 才能看到内置 + 共享给我的;Contributor 以上仍默认 "mine"。+const initialSpaceSelection = (): 'all' | 'mine' =>+ authStore.hasRole('contributor') ? 'mine' : 'all'+const spaceSelection = ref<'all' | 'mine' | string>(initialSpaceSelection())const agents = ref<AgentWithUI[]>([])const sharedAgents = computed<SharedAgentInfo[]>(() => orgStore.sharedAgents || [])const allAgentsCount = computed(() => agents.value.length + sharedAgents.value.length)diff --git a/frontend/src/views/knowledge/KnowledgeBaseList.vue b/frontend/src/views/knowledge/KnowledgeBaseList.vueindex 981d8b6f5..fac279f2d 100644--- a/frontend/src/views/knowledge/KnowledgeBaseList.vue+++ b/frontend/src/views/knowledge/KnowledgeBaseList.vue@@ -669,8 +669,13 @@ const authStore = useAuthStore()const orgStore = useOrganizationStore()const { t } = useI18n()-// 左侧空间选择:我的 / 空间 ID(已去掉「全部」)-const spaceSelection = ref<'all' | 'mine' | 'shared' | string>('mine')+// 左侧空间选择:默认根据当前角色决定。+// Viewer 在该租户里通常 0 KB owned,"我的"会显示空状态、又把共享 KB 藏起来,+// 体验非常误导;所以 Viewer 默认落到 "all"(我的 + 共享给我都显示)。+// Contributor 及以上一进来主要管理自己创建的 KB,仍默认 "mine"。+const initialSpaceSelection = (): 'all' | 'mine' =>+ authStore.hasRole('contributor') ? 'mine' : 'all'+const spaceSelection = ref<'all' | 'mine' | 'shared' | string>(initialSpaceSelection())interface KB {id: string;diff --git a/frontend/src/views/settings/ApiInfo.vue b/frontend/src/views/settings/ApiInfo.vueindex ebe8bd7ea..b6e5c2205 100644--- a/frontend/src/views/settings/ApiInfo.vue+++ b/frontend/src/views/settings/ApiInfo.vue@@ -172,73 +172,28 @@</p></div></div>-- <!-- User info -->- <div class="info-section-title">{{ $t('tenant.api.userSectionTitle') }}</div>-- <!-- User ID -->- <div class="setting-row">- <div class="setting-info">- <label>{{ $t('tenant.api.userIdLabel') }}</label>- <p class="desc">{{ $t('tenant.api.userIdDescription') }}</p>- </div>- <div class="setting-control">- <span class="info-value">{{ userInfo?.id || '-' }}</span>- </div>- </div>-- <!-- Username -->- <div class="setting-row">- <div class="setting-info">- <label>{{ $t('tenant.api.usernameLabel') }}</label>- <p class="desc">{{ $t('tenant.api.usernameDescription') }}</p>- </div>- <div class="setting-control">- <span class="info-value">{{ userInfo?.username || '-' }}</span>- </div>- </div>-- <!-- Email -->- <div class="setting-row">- <div class="setting-info">- <label>{{ $t('tenant.api.emailLabel') }}</label>- <p class="desc">{{ $t('tenant.api.emailDescription') }}</p>- </div>- <div class="setting-control">- <span class="info-value">{{ userInfo?.email || '-' }}</span>- </div>- </div>-- <!-- Created at -->- <div class="setting-row">- <div class="setting-info">- <label>{{ $t('tenant.api.createdAtLabel') }}</label>- <p class="desc">{{ $t('tenant.api.createdAtDescription') }}</p>- </div>- <div class="setting-control">- <span class="info-value">{{ formatDate(userInfo?.created_at) }}</span>- </div>- </div>-+ <!-- 用户信息原本嵌在这一页底部,但 api 信息页是 owner-only(要看+ api key + reset),把用户基本信息(id / 用户名 / 邮箱 / 注册+ 时间)也卡在这里意味着 viewer / contributor 看不到自己的账户+ 信息。已拆到独立的 UserProfile.vue(settings 里 viewer 可见)。 --></div></div></template><script setup lang="ts">import { ref, computed, onMounted } from 'vue'-import { getCurrentUser, type TenantInfo, type UserInfo } from '@/api/auth'+import { getCurrentUser, type TenantInfo } from '@/api/auth'import { resetTenantApiKey } from '@/api/tenant'import { getApiBaseUrl } from '@/utils/api-base'import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'import { useI18n } from 'vue-i18n'import { useAuthStore } from '@/stores/auth'-const { t, locale } = useI18n()+const { t } = useI18n()const authStore = useAuthStore()// Reactive stateconst tenantInfo = ref<TenantInfo | null>(null)-const userInfo = ref<UserInfo | null>(null)const loading = ref(true)const error = ref('')const showApiKey = ref(false)@@ -430,9 +385,8 @@ const loadInfo = async () => {error.value = ''const userResponse = await getCurrentUser()-+if ((userResponse as any).success && userResponse.data) {- userInfo.value = userResponse.data.usertenantInfo.value = userResponse.data.tenant} else {error.value = userResponse.message || t('tenant.messages.fetchFailed')@@ -546,24 +500,6 @@ const copyApiUrl = async () => {}}-const formatDate = (dateStr: string | undefined) => {- if (!dateStr) return t('tenant.unknown')-- try {- const date = new Date(dateStr)- const formatter = new Intl.DateTimeFormat(locale.value || 'zh-CN', {- year: 'numeric',- month: '2-digit',- day: '2-digit',- hour: '2-digit',- minute: '2-digit'- })- return formatter.format(date)- } catch {- return t('tenant.formatError')- }-}-// LifecycleonMounted(async () => {await tryLoadWailsApiBaseURL()diff --git a/frontend/src/views/settings/Settings.vue b/frontend/src/views/settings/Settings.vueindex c4e7c42dd..76c19963f 100644--- a/frontend/src/views/settings/Settings.vue+++ b/frontend/src/views/settings/Settings.vue@@ -90,6 +90,17 @@<!-- 右侧内容区域 --><div class="settings-content"><div class="content-wrapper">+ <!-- 角色不允许访问当前 section(deep-link 进来 / 跨租户切换后角色降级)—— 优先于具体 section 渲染。+ 正常导航走 navItems filter 不会到这里,但 watch(navItems) 的 fallback 会在角色降级+ 的瞬间触发;这一段做兜底兼容旧 URL。 -->+ <div v-if="!canSeeSection(currentSection)" class="section role-denied">+ <div class="role-denied-icon">+ <t-icon name="lock-on" size="48px" />+ </div>+ <div class="role-denied-title">{{ $t('settings.roleDenied.title') }}</div>+ <div class="role-denied-desc">{{ $t('settings.roleDenied.desc') }}</div>+ </div>+ <template v-else><!-- 常规设置 --><div v-if="currentSection === 'general'" class="section"><GeneralSettings />@@ -140,6 +151,13 @@<SystemInfo /></div>+ <!-- 用户信息(账户基础信息:ID / 用户名 / 邮箱 / 注册时间)。+ 从 ApiInfo.vue 拆出来,原页面挂的是 owner-only 入口,+ 用户的基本信息不该跟 owner 权限绑定。 -->+ <div v-if="currentSection === 'userprofile'" class="section">+ <UserProfile />+ </div>+<!-- 租户信息 --><div v-if="currentSection === 'tenant'" class="section"><TenantInfo />@@ -159,6 +177,7 @@<div v-if="currentSection === 'mcp'" class="section"><McpSettings /></div>+ </template></div></div></div>@@ -177,6 +196,7 @@ import { useI18n } from 'vue-i18n'import SystemInfo from './SystemInfo.vue'import TenantInfo from './TenantInfo.vue'import ApiInfo from './ApiInfo.vue'+import UserProfile from './UserProfile.vue'import GeneralSettings from './GeneralSettings.vue'import ModelSettings from './ModelSettings.vue'import OllamaSettings from './OllamaSettings.vue'@@ -212,8 +232,52 @@ type NavGroup = {items: NavItem[]}+// 设置二级导航的最低可见角色:和 internal/router/router.go 的守卫矩阵对齐。+// 以「页面里至少有 1 个有意义的写操作所要求的最低角色」为基准,把基础设+// 施配置(models 写、ollama 下载、websearch 写、parser/storage/vector/mcp+// CRUD、chat-history 配置)统一收到 admin;只读类(general / system info /+// tenant-info / members 名册)保留 viewer 可见;最高敏感的 reset api+// key 是 owner-only。改这张表前请在 router.go 里复核对应路由组。+//+// 特别说明:+// - chathistory 页面唯一的「启用消息索引」开关 PUT /tenants/kv/chat-history-config+// 后端走 g.Admin()。给 viewer/contributor 看到入口、点开开关、保存时+// 403,体验很差,所以入口本身归 admin。+// - models 列表 viewer 可读,页面内的「+ 添加模型 / 编辑 / 删除」按钮在+// ModelSettings.vue 里另用 hasRole('admin') 自己 gate,所以入口保留+// viewer 是合理的(contributor 也能浏览模型列表)。+type RoleKey = 'viewer' | 'contributor' | 'admin' | 'owner'+const SECTION_MIN_ROLE: Record<string, RoleKey> = {+ general: 'viewer',+ ollama: 'admin',+ weknoracloud: 'admin',+ models: 'viewer',+ websearch: 'admin',+ chathistory: 'admin',+ vectorstore: 'admin',+ parser: 'admin',+ storage: 'admin',+ mcp: 'admin',+ system: 'viewer',+ userprofile: 'viewer',+ tenant: 'viewer',+ members: 'viewer',+ api: 'owner',+}++const canSeeSection = (key: string): boolean => {+ const min = SECTION_MIN_ROLE[key] ?? 'viewer'+ // canAccessAllTenants(superuser)和路由层一样必须 bypass,否则 cross-tenant+ // 管理员看不到自己有权操作的入口(参考 TenantMembers.vue 的 canManage)。+ if (authStore.canAccessAllTenants) return true+ return authStore.hasRole(min)+}+const navItems = computed(() => {- const items: NavItem[] = [+ // 一律走 SECTION_MIN_ROLE 表,避免 ad-hoc isAdmin/isOwner 散落在多处。+ // 服务端在每条路由上仍以 g.Viewer/Admin/Owner 为准,这里只决定 UI 是+ // 否露入口;改动入口规则请同步更新 SECTION_MIN_ROLE 注释里的对照路由。+ const all: NavItem[] = [{ key: 'general', icon: 'setting', label: t('general.title') },{ key: 'ollama', icon: 'server', label: 'Ollama' },{ key: 'weknoracloud', icon: '', label: 'WeKnora Cloud' },@@ -225,17 +289,18 @@ const navItems = computed(() => {{ key: 'storage', icon: 'cloud', label: t('settings.storageEngine') },{ key: 'mcp', icon: 'tools', label: t('settings.mcpService') },{ key: 'system', icon: 'info-circle', label: t('settings.systemSettings') },+ { key: 'userprofile', icon: 'user', label: t('userProfile.title') },{ key: 'tenant', icon: 'user-circle', label: t('settings.tenantInfo') },+ { key: 'members', icon: 'usergroup', label: t('tenantMember.title') },+ { key: 'api', icon: 'secured', label: t('settings.apiInfo') },]- // Member management is hidden until the auth middleware resolves a- // real tenant role for the user. Empty string means "membership not- // loaded yet" — better to suppress the tab than to flash it on cold- // navigation. Server still enforces every mutation.- if (authStore.currentTenantRole) {- items.push({ key: 'members', icon: 'usergroup', label: t('tenantMember.title') })+ // currentTenantRole 为空表示「membership 还没加载」—— 比起渲染整套+ // viewer 入口然后角色一返回又消失,先卡住不渲染更稳,跟原先 members+ // 入口的策略一致。+ if (!authStore.currentTenantRole && !authStore.canAccessAllTenants) {+ return [] as NavItem[]}- items.push({ key: 'api', icon: 'secured', label: t('settings.apiInfo') })- return items+ return all.filter((it) => canSeeSection(it.key))})const navGroups = computed<NavGroup[]>(() => {@@ -245,7 +310,7 @@ const navGroups = computed<NavGroup[]>(() => {{ key: 'basic', label: t('settings.navGroups.basic'), items: pickItems(['general']) },{ key: 'ai', label: t('settings.navGroups.ai'), items: pickItems(['models', 'ollama', 'weknoracloud', 'websearch', 'mcp']) },{ key: 'data', label: t('settings.navGroups.data'), items: pickItems(['vectorstore', 'parser', 'storage']) },- { key: 'workspace', label: t('settings.navGroups.workspace'), items: pickItems(['tenant', 'members']) },+ { key: 'workspace', label: t('settings.navGroups.workspace'), items: pickItems(['userprofile', 'tenant', 'members']) },{ key: 'system', label: t('settings.navGroups.system'), items: pickItems(['chathistory', 'system', 'api']) },].filter((group) => group.items.length > 0)})@@ -321,6 +386,15 @@ watch(() => uiStore.settingsInitialSection, (section) => {}}, { immediate: true })+// 切换租户后角色可能变化,原本可见的 admin-only 面板可能消失。+// 如果 currentSection 落到了不再显示的 key 上,就回退到第一个可见项。+watch(navItems, (items) => {+ if (!items.some((item) => item.key === currentSection.value)) {+ currentSection.value = items[0]?.key || 'general'+ currentSubSection.value = ''+ }+})+// ESC 键关闭const handleEscape = (e: KeyboardEvent) => {if (e.key === 'Escape' && visible.value) {@@ -634,5 +708,31 @@ onUnmounted(() => {.settings-content::-webkit-scrollbar-thumb:hover {background: var(--td-gray-color-6);}++.role-denied {+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ text-align: center;+ padding: 64px 24px;+ gap: 12px;+ min-height: 240px;++ .role-denied-icon {+ color: var(--td-text-color-placeholder);+ }+ .role-denied-title {+ font-size: 16px;+ font-weight: 600;+ color: var(--td-text-color-primary);+ }+ .role-denied-desc {+ font-size: 13px;+ color: var(--td-text-color-secondary);+ max-width: 360px;+ line-height: 1.6;+ }+}</style>diff --git a/frontend/src/views/settings/UserProfile.vue b/frontend/src/views/settings/UserProfile.vuenew file mode 100644index 000000000..63d569aaa--- /dev/null+++ b/frontend/src/views/settings/UserProfile.vue@@ -0,0 +1,210 @@+<template>+ <div class="user-profile">+ <div class="section-header">+ <h2>{{ $t('userProfile.title') }}</h2>+ <p class="section-description">{{ $t('userProfile.description') }}</p>+ </div>++ <!-- Loading -->+ <div v-if="loading" class="loading-inline">+ <t-loading size="small" />+ <span>{{ $t('tenant.loadingInfo') }}</span>+ </div>++ <!-- Error -->+ <div v-else-if="error" class="error-inline">+ <t-alert theme="error" :message="error">+ <template #operation>+ <t-button size="small" @click="loadInfo">{{ $t('tenant.retry') }}</t-button>+ </template>+ </t-alert>+ </div>++ <!-- Content -->+ <div v-else class="settings-group">+ <!-- 用户 ID -->+ <div class="setting-row">+ <div class="setting-info">+ <label>{{ $t('tenant.api.userIdLabel') }}</label>+ <p class="desc">{{ $t('tenant.api.userIdDescription') }}</p>+ </div>+ <div class="setting-control">+ <span class="info-value">{{ userInfo?.id || '-' }}</span>+ </div>+ </div>++ <!-- 用户名 -->+ <div class="setting-row">+ <div class="setting-info">+ <label>{{ $t('tenant.api.usernameLabel') }}</label>+ <p class="desc">{{ $t('tenant.api.usernameDescription') }}</p>+ </div>+ <div class="setting-control">+ <span class="info-value">{{ userInfo?.username || '-' }}</span>+ </div>+ </div>++ <!-- 邮箱 -->+ <div class="setting-row">+ <div class="setting-info">+ <label>{{ $t('tenant.api.emailLabel') }}</label>+ <p class="desc">{{ $t('tenant.api.emailDescription') }}</p>+ </div>+ <div class="setting-control">+ <span class="info-value">{{ userInfo?.email || '-' }}</span>+ </div>+ </div>++ <!-- 注册时间 -->+ <div class="setting-row">+ <div class="setting-info">+ <label>{{ $t('tenant.api.createdAtLabel') }}</label>+ <p class="desc">{{ $t('tenant.api.createdAtDescription') }}</p>+ </div>+ <div class="setting-control">+ <span class="info-value">{{ formatDate(userInfo?.created_at) }}</span>+ </div>+ </div>+ </div>+ </div>+</template>++<script setup lang="ts">+import { ref, onMounted } from 'vue'+import { getCurrentUser, type UserInfo } from '@/api/auth'+import { useI18n } from 'vue-i18n'++const { t, locale } = useI18n()++const userInfo = ref<UserInfo | null>(null)+const loading = ref(true)+const error = ref('')++const loadInfo = async () => {+ try {+ loading.value = true+ error.value = ''+ const resp = await getCurrentUser()+ if ((resp as any).success && resp.data) {+ userInfo.value = resp.data.user+ } else {+ error.value = resp.message || t('tenant.messages.fetchFailed')+ }+ } catch (err: any) {+ error.value = err?.message || t('tenant.messages.networkError')+ } finally {+ loading.value = false+ }+}++const formatDate = (dateStr: string | undefined) => {+ if (!dateStr) return t('tenant.unknown')+ try {+ const d = new Date(dateStr)+ const fmt = new Intl.DateTimeFormat(locale.value || 'zh-CN', {+ year: 'numeric',+ month: '2-digit',+ day: '2-digit',+ hour: '2-digit',+ minute: '2-digit',+ })+ return fmt.format(d)+ } catch {+ return t('tenant.formatError')+ }+}++onMounted(loadInfo)+</script>++<style lang="less" scoped>+.user-profile {+ width: 100%;+}++.section-header {+ margin-bottom: 32px;++ h2 {+ font-size: 20px;+ font-weight: 600;+ color: var(--td-text-color-primary);+ margin: 0 0 8px 0;+ }++ .section-description {+ font-size: 14px;+ color: var(--td-text-color-secondary);+ margin: 0;+ line-height: 1.5;+ }+}++.loading-inline {+ display: flex;+ align-items: center;+ gap: 12px;+ padding: 40px 0;+ justify-content: center;+ color: var(--td-text-color-secondary);+ font-size: 14px;+}++.error-inline {+ padding: 20px 0;+}++.settings-group {+ display: flex;+ flex-direction: column;+ gap: 0;+}++.setting-row {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ padding: 20px 0;+ border-bottom: 1px solid var(--td-component-stroke);++ &:last-child {+ border-bottom: none;+ }+}++.setting-info {+ flex: 1;+ max-width: 65%;+ padding-right: 24px;++ label {+ font-size: 15px;+ font-weight: 500;+ color: var(--td-text-color-primary);+ display: block;+ margin-bottom: 4px;+ }++ .desc {+ font-size: 13px;+ color: var(--td-text-color-secondary);+ margin: 0;+ line-height: 1.5;+ }+}++.setting-control {+ flex-shrink: 0;+ min-width: 280px;+ display: flex;+ justify-content: flex-end;+ align-items: flex-start;++ .info-value {+ font-size: 14px;+ color: var(--td-text-color-primary);+ text-align: right;+ word-break: break-word;+ }+}+</style>