Files
Enterprise-Knowledge-Base/frontend/src/views/settings/RetrievalSettings.vue
T
wizardchen 466182c8d6 feat(frontend): tenant switcher in user menu + role-aware UI gates
PR 4 of #1303 wired the backend X-Tenant-ID gate to accept active
tenant_members rows (not just superusers), but the frontend never
exposed a switcher to ordinary multi-tenant members. The only
existing component, the sidebar TenantSelector, is gated to
canAccessAllTenants and queries /tenants/search — both wrong for a
Contributor that an Owner just invited to a second tenant.

This PR closes both gaps:

1. Switcher entry inside the user-avatar dropdown
   - New "Switch Tenant" submenu in UserMenu.vue, hover-triggered, with
     a teleported floating panel (same pattern as the existing IM
     overview submenu so the layout/animation read consistently).
   - Data source is authStore.memberships, populated by /auth/login.
     No new API call: the JWT-issued claim already enumerates every
     tenant the user is an active member of plus their role.
   - Visibility: only shown when memberships.length > 1. Cluster
     superusers keep using the sidebar TenantSelector for "any tenant
     in the system" — the avatar entry is the curated "tenants I'm a
     member of" list.
   - Click writes via authStore.setSelectedTenant(...), then
     window.location.reload() so every cached store / open SSE
     stream / in-flight request is re-keyed under the new tenant.
     Same approach as the existing TenantSelector.

2. Role-aware UI gates on high-friction surfaces
   - authStore exposes a new hasRole(min: 'viewer'|'contributor'|
     'admin'|'owner') helper (numeric ordering matches
     middleware/rbac.go) so v-if gates line up with the server-side
     matrix instead of duplicating ['admin','owner'].includes(...).
   - Gates applied per the PR 4 audit:
     * KB list "Create" button — Contributor+
     * Agent list "Create" button — Contributor+
     * Model / VectorStore / WebSearch / MCP — Add+Edit+Delete+Test
       are Admin+ (and the per-card action menus return [] for
       non-Admins so the dropdowns disappear, not just disable).
     * Parser / Storage engine drawers — Save button Admin+
     * Retrieval settings — slider/selector inputs disabled for
       non-Admins (the form auto-saves on change, no dedicated Save).
     * API key reset — Owner+ (Reset is the highest-impact tenant op).
     * IM channel toggle/edit/delete + Add — Admin+. Same in the
       avatar-menu IM submenu (toggle disabled for non-Admins).
   - KB / agent per-card edit/delete already key off kb.isMine /
     agent.isMine + (for builtins) is_builtin; that path is left as-is.

3. i18n
   - Three new keys under tenant.switcher.* in en-US/zh-CN/ko-KR/ru-RU.
   - Role labels reuse the existing tenantMember.role.* bundle from
     PR 3, with a "show raw role" fallback if a locale lacks the key.

The server is the source of truth for every gated action — these
changes only hide buttons that would 403, never grant new authority.
authStore.hasRole and currentTenantRole both carry a SECURITY note
saying they read from localStorage and are UI-rendering-only.

vue-tsc --build error count unchanged from baseline (90, all
pre-existing issues unrelated to this PR).
2026-05-18 17:28:58 +08:00

288 lines
7.7 KiB
Vue

<template>
<div class="retrieval-settings">
<div class="section-header">
<h2>{{ t('retrievalSettings.title') }}</h2>
<p class="section-description">{{ t('retrievalSettings.description') }}</p>
</div>
<div class="settings-group">
<!-- Rerank Model -->
<div class="setting-item">
<div class="setting-label">
<span>{{ t('retrievalSettings.rerankModelLabel') }} <span class="required-mark">*</span></span>
</div>
<p class="setting-desc">{{ t('retrievalSettings.rerankModelDescription') }}</p>
<p v-if="!localConfig.rerank_model_id" class="setting-desc warning-text">
{{ t('retrievalSettings.rerankModelRequired') }}
</p>
<div class="setting-control-full">
<ModelSelector
model-type="Rerank"
:selected-model-id="localConfig.rerank_model_id"
:disabled="!canEdit"
@update:selected-model-id="handleModelChange"
/>
</div>
</div>
<!-- Embedding Top K -->
<div class="setting-item">
<div class="setting-label-row">
<span>{{ t('retrievalSettings.embeddingTopKLabel') }}</span>
<span class="value-display">{{ localConfig.embedding_top_k }}</span>
</div>
<t-slider
v-model="localConfig.embedding_top_k"
:min="1"
:max="100"
:step="1"
:disabled="!canEdit"
@change="handleParamChange"
/>
</div>
<!-- Vector Threshold -->
<div class="setting-item">
<div class="setting-label-row">
<span>{{ t('retrievalSettings.vectorThresholdLabel') }}</span>
<span class="value-display">{{ localConfig.vector_threshold.toFixed(2) }}</span>
</div>
<t-slider
v-model="localConfig.vector_threshold"
:min="0"
:max="1"
:step="0.05"
:disabled="!canEdit"
@change="handleParamChange"
/>
</div>
<!-- Keyword Threshold -->
<div class="setting-item">
<div class="setting-label-row">
<span>{{ t('retrievalSettings.keywordThresholdLabel') }}</span>
<span class="value-display">{{ localConfig.keyword_threshold.toFixed(2) }}</span>
</div>
<t-slider
v-model="localConfig.keyword_threshold"
:min="0"
:max="1"
:step="0.05"
:disabled="!canEdit"
@change="handleParamChange"
/>
</div>
<!-- Rerank Top K -->
<div class="setting-item">
<div class="setting-label-row">
<span>{{ t('retrievalSettings.rerankTopKLabel') }}</span>
<span class="value-display">{{ localConfig.rerank_top_k }}</span>
</div>
<t-slider
v-model="localConfig.rerank_top_k"
:min="1"
:max="100"
:step="1"
:disabled="!canEdit"
@change="handleParamChange"
/>
</div>
<!-- Rerank Threshold -->
<div class="setting-item">
<div class="setting-label-row">
<span>{{ t('retrievalSettings.rerankThresholdLabel') }}</span>
<span class="value-display">{{ localConfig.rerank_threshold.toFixed(2) }}</span>
</div>
<t-slider
v-model="localConfig.rerank_threshold"
:min="-10"
:max="10"
:step="0.1"
:disabled="!canEdit"
@change="handleParamChange"
/>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { reactive, computed, onMounted, nextTick } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import ModelSelector from '@/components/ModelSelector.vue'
import {
getTenantRetrievalConfig,
updateTenantRetrievalConfig,
type RetrievalConfig,
} from '@/api/retrieval'
import { useAuthStore } from '@/stores/auth'
const { t } = useI18n()
const authStore = useAuthStore()
// PUT /tenants/kv/retrieval-config requires Admin+ on the server. Hide the
// banner + lock all controls for non-Admins so they can read the
// configuration without tripping a 403 mid-edit.
const canEdit = computed(() => authStore.hasRole('admin'))
const defaultConfig: RetrievalConfig = {
embedding_top_k: 50,
vector_threshold: 0.15,
keyword_threshold: 0.3,
rerank_top_k: 10,
rerank_threshold: 0.2,
rerank_model_id: '',
}
const localConfig = reactive<RetrievalConfig>({ ...defaultConfig })
let initialConfig: RetrievalConfig = { ...defaultConfig }
let isInitializing = true
const loadConfig = async () => {
try {
const response = await getTenantRetrievalConfig()
if (response.data) {
const cfg = response.data
Object.assign(localConfig, {
embedding_top_k: cfg.embedding_top_k || defaultConfig.embedding_top_k,
vector_threshold: cfg.vector_threshold || defaultConfig.vector_threshold,
keyword_threshold: cfg.keyword_threshold || defaultConfig.keyword_threshold,
rerank_top_k: cfg.rerank_top_k || defaultConfig.rerank_top_k,
rerank_threshold: cfg.rerank_threshold ?? defaultConfig.rerank_threshold,
rerank_model_id: cfg.rerank_model_id || '',
})
initialConfig = { ...localConfig }
}
} catch (error: any) {
console.error('Failed to load retrieval config:', error)
} finally {
await nextTick()
await nextTick()
setTimeout(() => { isInitializing = false }, 100)
}
}
const hasConfigChanged = (): boolean => {
return JSON.stringify(localConfig) !== JSON.stringify(initialConfig)
}
const saveConfig = async () => {
if (!hasConfigChanged()) return
try {
const response = await updateTenantRetrievalConfig({ ...localConfig })
if (response.data) {
initialConfig = { ...localConfig }
}
MessagePlugin.success(t('retrievalSettings.toasts.saveSuccess'))
} catch (error: any) {
console.error('Failed to save retrieval config:', error)
const errorMessage = error?.message || 'Unknown error'
MessagePlugin.error(t('retrievalSettings.toasts.saveFailed', { message: errorMessage }))
}
}
let saveTimer: number | null = null
const debouncedSave = () => {
if (isInitializing) return
if (saveTimer) clearTimeout(saveTimer)
saveTimer = window.setTimeout(() => {
saveConfig().catch(() => {})
}, 500)
}
const handleParamChange = () => debouncedSave()
const handleModelChange = (modelId: string) => {
localConfig.rerank_model_id = modelId
debouncedSave()
}
onMounted(async () => {
isInitializing = true
await loadConfig()
})
</script>
<style lang="less" scoped>
.retrieval-settings {
width: 100%;
}
.section-header {
margin-bottom: 24px;
h2 {
font-size: 20px;
font-weight: 600;
color: var(--td-text-color-primary);
margin: 0 0 6px 0;
}
.section-description {
font-size: 13px;
color: var(--td-text-color-secondary);
margin: 0;
line-height: 1.5;
}
}
.settings-group {
display: flex;
flex-direction: column;
gap: 0;
}
.setting-item {
padding: 16px 0;
border-bottom: 1px solid var(--td-component-stroke);
&:last-child {
border-bottom: none;
}
}
.setting-label {
font-size: 14px;
font-weight: 500;
color: var(--td-text-color-primary);
margin-bottom: 4px;
}
.setting-label-row {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 14px;
font-weight: 500;
color: var(--td-text-color-primary);
margin-bottom: 10px;
}
.setting-desc {
font-size: 12px;
color: var(--td-text-color-secondary);
margin: 0 0 8px 0;
line-height: 1.5;
}
.required-mark {
color: var(--td-error-color);
}
.warning-text {
color: var(--td-warning-color) !important;
}
.setting-control-full {
width: 100%;
}
.value-display {
font-size: 13px;
font-weight: 600;
color: var(--td-brand-color);
font-family: var(--app-font-family-mono);
}
</style>