diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue index 3cead90b..4eb51095 100644 --- a/frontend/src/components/IMChannelPanel.vue +++ b/frontend/src/components/IMChannelPanel.vue @@ -32,9 +32,11 @@ + {{ $t('agentEditor.im.addChannel') }} @@ -429,8 +431,10 @@ import { } from '@/api/agent'; import { listKnowledgeBases } from '@/api/knowledge-base'; import type { IMChannel } from '@/api/agent'; +import { useAuthStore } from '@/stores/auth'; const { t } = useI18n(); +const authStore = useAuthStore(); const props = defineProps<{ agentId: string; diff --git a/frontend/src/components/IMChannelsOverviewPanel.vue b/frontend/src/components/IMChannelsOverviewPanel.vue index ef18376f..30fcd10a 100644 --- a/frontend/src/components/IMChannelsOverviewPanel.vue +++ b/frontend/src/components/IMChannelsOverviewPanel.vue @@ -84,6 +84,7 @@ :value="ch.enabled" size="small" :loading="togglingId === ch.id" + :disabled="!authStore.hasRole('admin')" @change="handleToggle(ch)" /> @@ -98,6 +99,7 @@ import { ref, watch } from 'vue'; import { useRouter } from 'vue-router'; import { useI18n } from 'vue-i18n'; import { MessagePlugin } from 'tdesign-vue-next'; +import { useAuthStore } from '@/stores/auth'; import { listAllIMChannels, listAgents, @@ -138,6 +140,7 @@ const emit = defineEmits<{ const { t } = useI18n(); const router = useRouter(); +const authStore = useAuthStore(); const channels = ref([]); const agentMap = ref>(new Map()); diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue index e0a022e6..c8e1cf2a 100644 --- a/frontend/src/components/UserMenu.vue +++ b/frontend/src/components/UserMenu.vue @@ -71,6 +71,23 @@ {{ $t('general.allSettings') }} + + + + + +
+
+ {{ $t('tenant.switcher.menuLabel') }} +
+
+
+
+ {{ tenantInitial(m) }} +
+
+ {{ tenantDisplayName(m) }} + {{ formatRole(m.role) }} +
+ {{ $t('tenant.switcher.currentBadge') }} +
+
+ {{ $t('tenant.switcher.empty') }} +
+
+
+
@@ -165,11 +223,15 @@ const authStore = useAuthStore() const menuRef = ref() const imMenuItemRef = ref() +const tenantMenuItemRef = ref() const menuVisible = ref(false) const imSubmenuOpen = ref(false) const imSubmenuStyle = ref>({}) +const tenantSubmenuOpen = ref(false) +const tenantSubmenuStyle = ref>({}) const hasActiveIMChannels = ref(false) let imSubmenuHideTimer: ReturnType | null = null +let tenantSubmenuHideTimer: ReturnType | null = null // 用户信息 const userInfo = ref({ @@ -236,9 +298,129 @@ const scheduleHideIMSubmenu = () => { const closeAll = () => { imSubmenuOpen.value = false + tenantSubmenuOpen.value = false menuVisible.value = false } +// ---------- Tenant switcher submenu ---------- +// +// Same hover-driven submenu pattern as the IM panel above; data comes from +// authStore.memberships (populated by /auth/login). PR 4 of #1303 relaxed +// the X-Tenant-ID gate in middleware/auth.go to accept active membership +// rows, so flipping authStore.selectedTenantId here is enough — the next +// page reload re-issues every request with the new header and the server +// resolves the role server-side. +type Membership = { + tenant_id: number + tenant_name?: string + role: string +} + +// switchableMemberships is the curated list shown in the dropdown. We keep +// the active tenant in there (with a "Current" badge) so the user has a +// single place to glance at "where am I right now"; clicking the current +// row is a no-op (handled in switchToTenant). +const switchableMemberships = computed(() => { + return authStore.memberships ?? [] +}) + +// Rendered only when there's something to switch *to*. Multi-tenant members +// (memberships.length > 1) need it for tenant switching; superusers keep +// using the sidebar TenantSelector for the "any tenant in the system" case, +// so we don't double-show the entry there. +const showTenantSwitcher = computed(() => { + return switchableMemberships.value.length > 1 +}) + +const isCurrentTenant = (id: number) => { + const active = authStore.effectiveTenantId + return active != null && Number(active) === Number(id) +} + +const tenantDisplayName = (m: Membership) => + m.tenant_name && m.tenant_name.trim() !== '' ? m.tenant_name : `#${m.tenant_id}` + +const tenantInitial = (m: Membership) => { + const name = tenantDisplayName(m).trim() + 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() + return + } + // 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) { + authStore.setSelectedTenant(null, null) + } else { + authStore.setSelectedTenant(m.tenant_id, tenantDisplayName(m)) + } + closeAll() + MessagePlugin.success(t('tenant.switchSuccess')) + // Hard reload so every cached store / open SSE stream / in-flight + // request gets re-keyed under the new tenant. Same approach as + // TenantSelector.vue. + setTimeout(() => { + window.location.reload() + }, 400) +} + +const showTenantSubmenu = () => { + if (tenantSubmenuHideTimer) { + clearTimeout(tenantSubmenuHideTimer) + tenantSubmenuHideTimer = null + } + positionTenantSubmenu() + tenantSubmenuOpen.value = true +} + +const scheduleHideTenantSubmenu = () => { + if (tenantSubmenuHideTimer) clearTimeout(tenantSubmenuHideTimer) + tenantSubmenuHideTimer = setTimeout(() => { + tenantSubmenuOpen.value = false + tenantSubmenuHideTimer = null + }, 180) +} + +const positionTenantSubmenu = () => { + const el = tenantMenuItemRef.value + if (!el) return + const rect = el.getBoundingClientRect() + const PANEL_WIDTH = 280 + const PANEL_MAX_HEIGHT = 360 + const GAP = 8 + const MARGIN = 8 + + let left = rect.right + GAP + if (left + PANEL_WIDTH + MARGIN > window.innerWidth) { + left = Math.max(MARGIN, rect.left - PANEL_WIDTH - GAP) + } + + let top = rect.top - 4 + const maxTop = window.innerHeight - Math.min(PANEL_MAX_HEIGHT, window.innerHeight - MARGIN * 2) - MARGIN + if (top > maxTop) top = maxTop + if (top < MARGIN) top = MARGIN + + tenantSubmenuStyle.value = { + left: `${left}px`, + top: `${top}px`, + } +} + // Silent prefetch so the "live" indicator on the IM menu item reflects reality // as soon as the user sees the avatar area. Errors are swallowed — the // indicator just stays off if the request fails, which is the conservative @@ -374,12 +556,16 @@ const loadUserInfo = async () => { const handleClickOutside = (e: MouseEvent) => { const target = e.target as Node if (menuRef.value && menuRef.value.contains(target)) return - // The submenu is teleported to body, so it's not inside menuRef — check it - // separately to avoid closing the dropdown when the user clicks the submenu. - const floating = document.querySelector('.im-submenu-floating') - if (floating && floating.contains(target)) return + // The IM and tenant submenus are teleported to body, so they're not inside + // menuRef — check them separately to avoid closing the dropdown when the + // user clicks one of the floating panels. + const imFloating = document.querySelector('.im-submenu-floating') + if (imFloating && imFloating.contains(target)) return + const tenantFloating = document.querySelector('.tenant-submenu-floating') + if (tenantFloating && tenantFloating.contains(target)) return menuVisible.value = false imSubmenuOpen.value = false + tenantSubmenuOpen.value = false } onMounted(() => { @@ -725,5 +911,120 @@ onUnmounted(() => { // panel so hovering across the gap doesn't fire mouseleave-hide. padding-left: 2px; } + +// Tenant switcher submenu — same teleport rationale as .im-submenu-floating. +// All styling for the panel itself lives here (not in a child component) so +// the markup in UserMenu.vue stays self-contained. +.tenant-submenu-floating { + position: fixed; + z-index: 1100; + width: 280px; + max-height: 360px; + display: flex; + flex-direction: column; + background: var(--td-bg-color-container); + border: 0.5px solid var(--td-component-stroke); + border-radius: 10px; + box-shadow: 0 6px 24px rgba(0, 0, 0, 0.12); + // Pointer bridge so the user can slide off the menu item onto the panel + // without hitting the gap and triggering mouseleave-hide. + padding-left: 2px; + overflow: hidden; + + .tenant-submenu-header { + padding: 10px 14px 8px; + font-size: 12px; + font-weight: 600; + color: var(--td-text-color-secondary); + border-bottom: 0.5px solid var(--td-component-stroke); + } + + .tenant-submenu-list { + overflow-y: auto; + padding: 6px; + } + + .tenant-submenu-item { + display: flex; + align-items: center; + gap: 10px; + padding: 8px 10px; + border-radius: 6px; + cursor: pointer; + transition: background 0.15s; + + &:hover { + background: var(--td-bg-color-secondarycontainer); + } + + &.is-current { + background: rgba(7, 192, 95, 0.08); + cursor: default; + + .tenant-submenu-item-name { + color: var(--td-brand-color); + font-weight: 500; + } + } + } + + .tenant-submenu-item-avatar { + width: 32px; + height: 32px; + border-radius: 6px; + background: var(--td-bg-color-secondarycontainer); + display: flex; + align-items: center; + justify-content: center; + font-size: 13px; + font-weight: 600; + color: var(--td-text-color-secondary); + flex-shrink: 0; + + &.is-current { + background: linear-gradient(135deg, var(--td-brand-color) 0%, var(--td-brand-color-active) 100%); + color: var(--td-text-color-anti); + } + } + + .tenant-submenu-item-info { + flex: 1; + min-width: 0; + display: flex; + flex-direction: column; + gap: 1px; + } + + .tenant-submenu-item-name { + font-size: 13px; + color: var(--td-text-color-primary); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .tenant-submenu-item-role { + font-size: 11px; + color: var(--td-text-color-placeholder); + } + + .tenant-submenu-item-badge { + flex-shrink: 0; + font-size: 10px; + font-weight: 600; + line-height: 1.2; + padding: 2px 6px; + border-radius: 4px; + background: var(--td-brand-color-light); + color: var(--td-brand-color); + } + + .tenant-submenu-empty { + padding: 16px 12px; + text-align: center; + font-size: 12px; + color: var(--td-text-color-placeholder); + } +} diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts index d60719ae..93c47545 100755 --- a/frontend/src/i18n/locales/en-US.ts +++ b/frontend/src/i18n/locales/en-US.ts @@ -2268,6 +2268,11 @@ export default { title: 'Tenant Information', currentTenant: 'Current Tenant', switchTenant: 'Switch Tenant', + switcher: { + menuLabel: 'Switch Tenant', + currentBadge: 'Current', + empty: 'You only belong to one tenant', + }, sectionDescription: 'View detailed configuration for the tenant', apiDocument: 'API Document', name: 'Tenant Name', diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts index ba7eccf5..aad90ab3 100755 --- a/frontend/src/i18n/locales/ko-KR.ts +++ b/frontend/src/i18n/locales/ko-KR.ts @@ -1526,6 +1526,11 @@ export default { title: "테넌트 정보", currentTenant: "현재 테넌트", switchTenant: "테넌트 전환", + switcher: { + menuLabel: "테넌트 전환", + currentBadge: "현재", + empty: "현재 하나의 테넌트에만 속해 있습니다", + }, sectionDescription: "테넌트의 상세 설정 정보 보기", apiDocument: "API 문서", name: "테넌트 이름", diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts index 6eac3604..1e3a2071 100755 --- a/frontend/src/i18n/locales/ru-RU.ts +++ b/frontend/src/i18n/locales/ru-RU.ts @@ -1344,6 +1344,11 @@ export default { title: 'Информация об арендаторе', currentTenant: 'Текущий арендатор', switchTenant: 'Сменить арендатора', + switcher: { + menuLabel: 'Сменить арендатора', + currentBadge: 'Текущий', + empty: 'Вы состоите только в одном арендаторе', + }, sectionDescription: 'Просмотр детальной конфигурации арендатора', apiDocument: 'Документация API', name: 'Имя арендатора', diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts index 5edd9cfc..cd75acd5 100755 --- a/frontend/src/i18n/locales/zh-CN.ts +++ b/frontend/src/i18n/locales/zh-CN.ts @@ -1507,6 +1507,11 @@ export default { title: "租户信息", currentTenant: "当前租户", switchTenant: "切换租户", + switcher: { + menuLabel: "切换租户", + currentBadge: "当前", + empty: "你目前只属于这一个租户", + }, sectionDescription: "查看租户的详细配置信息", apiDocument: "API文档", name: "租户名称", diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts index 22899cac..8d9608d7 100644 --- a/frontend/src/stores/auth.ts +++ b/frontend/src/stores/auth.ts @@ -73,6 +73,25 @@ export const useAuthStore = defineStore('auth', () => { return match?.role || '' }) + // hasRole answers "is the current tenant role at least ?", used by + // role-aware UI gating across KB / Agent / settings views. The numeric + // ordering (viewer < contributor < admin < owner) mirrors the server-side + // matrix in middleware/rbac.go so a v-if here lines up with the 403 the + // backend would return. + // + // SECURITY: shares the same caveat as currentTenantRole — derived from + // localStorage, MUST be treated as UI-rendering-only. Never rely on + // hasRole() for security decisions; the server is the source of truth. + const ROLE_LEVEL: Record = { + viewer: 10, + contributor: 20, + admin: 30, + owner: 40, + } + const hasRole = (min: 'viewer' | 'contributor' | 'admin' | 'owner'): boolean => { + return (ROLE_LEVEL[currentTenantRole.value] ?? 0) >= ROLE_LEVEL[min] + } + const effectiveTenantId = computed(() => { // 如果选择了其他租户,使用选择的租户ID,否则使用用户默认租户ID return selectedTenantId.value || (tenant.value?.id ? Number(tenant.value.id) : null) @@ -294,6 +313,7 @@ export const useAuthStore = defineStore('auth', () => { currentUserId, canAccessAllTenants, currentTenantRole, + hasRole, effectiveTenantId, isLiteMode, diff --git a/frontend/src/views/agent/AgentList.vue b/frontend/src/views/agent/AgentList.vue index 8381ab9b..98f1f4a4 100644 --- a/frontend/src/views/agent/AgentList.vue +++ b/frontend/src/views/agent/AgentList.vue @@ -14,7 +14,7 @@

{{ $t('agent.title') }}

- + {{ $t('agent.empty.title') }} {{ $t('agent.empty.description') }} - +