diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index 02578a20..0fdebff1 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -8,8 +8,36 @@ - {{ userName }} - {{ userEmail }} + + + {{ activeTenantName }} + + {{ userName }} + · + + {{ currentRoleLabel }} + + + + {{ userName }} + {{ userEmail }} + @@ -18,15 +46,59 @@ - + + + + + {{ activeTenantName || userName }} + + + + + + {{ currentRoleLabel }} + + + + + {{ $t('settings.modelManagement') }} - - + {{ $t('settings.webSearchConfig') }} - + {{ $t('settings.mcpService') }} - + {{ $t('settings.apiInfo') }} @@ -71,23 +143,8 @@ {{ $t('general.allSettings') }} - - - - {{ $t('tenant.switcher.menuLabel') }} - - + 🦞 @@ -185,15 +242,40 @@ > {{ tenantInitial(m) }} + + + + + {{ tenantDisplayName(m) }} - {{ formatRole(m.role) }} + + + + {{ formatRole(m.role) }} + + {{ $t('tenant.switcher.currentBadge') }} + - {{ $t('tenant.switcher.currentBadge') }} {{ $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 = { + 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() const imMenuItemRef = ref() @@ -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.ts new file mode 100644 index 00000000..01a3f2ab --- /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 = { + 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(() => { + 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(() => 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.ts index 53f4d638..41bdb143 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.ts index f39baec6..dbbe53bd 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.ts index f0c9af6d..15963594 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.ts index fec0a873..e231442d 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.vue index f29c8a49..40c7310d 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([]) const sharedAgents = computed(() => 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.vue index 981d8b6f..fac279f2 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.vue index ebe8bd7e..b6e5c220 100644 --- a/frontend/src/views/settings/ApiInfo.vue +++ b/frontend/src/views/settings/ApiInfo.vue @@ -172,73 +172,28 @@ - - - {{ $t('tenant.api.userSectionTitle') }} - - - - - {{ $t('tenant.api.userIdLabel') }} - {{ $t('tenant.api.userIdDescription') }} - - - {{ userInfo?.id || '-' }} - - - - - - - {{ $t('tenant.api.usernameLabel') }} - {{ $t('tenant.api.usernameDescription') }} - - - {{ userInfo?.username || '-' }} - - - - - - - {{ $t('tenant.api.emailLabel') }} - {{ $t('tenant.api.emailDescription') }} - - - {{ userInfo?.email || '-' }} - - - - - - - {{ $t('tenant.api.createdAtLabel') }} - {{ $t('tenant.api.createdAtDescription') }} - - - {{ formatDate(userInfo?.created_at) }} - - - + + +
{{ $t('tenant.api.userIdDescription') }}
{{ $t('tenant.api.usernameDescription') }}
{{ $t('tenant.api.emailDescription') }}
{{ $t('tenant.api.createdAtDescription') }}