diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts index 48490000..e0e027ed 100644 --- a/frontend/src/stores/auth.ts +++ b/frontend/src/stores/auth.ts @@ -6,6 +6,7 @@ import i18n from '@/i18n' import { reloadFontFromStorage } from '@/composables/useFont' import { reloadThemeFromStorage } from '@/composables/useTheme' import { resetMigrationLatch } from '@/composables/preferenceStorage' +import { BUILTIN_QUICK_ANSWER_ID } from '@/api/agent' // Per-user UI preferences are namespaced by user id in localStorage. // Reload them whenever the active user changes. @@ -175,7 +176,43 @@ export const useAuthStore = defineStore('auth', () => { } } + // Wipe chat / KB selections that were saved under the previous tenant. + // These keys are NOT tenant-scoped in storage; after a tenant switch they + // would otherwise be reloaded verbatim and the chat input would post under + // the new tenant with an Agent / model id that only existed in the old + // tenant — backend 403s or "model not found". Called from setSelectedTenant + // only on an actual tenant change, so logout / init paths are not touched. + const clearTenantScopedClientState = () => { + try { + localStorage.removeItem('weknora_last_chat_model_id') + localStorage.removeItem('weknora_current_kb') + const raw = localStorage.getItem('WeKnora_settings') + if (raw) { + const parsed = JSON.parse(raw) + if (parsed && typeof parsed === 'object') { + parsed.selectedAgentId = BUILTIN_QUICK_ANSWER_ID + parsed.selectedAgentSourceTenantId = null + if (parsed.conversationModels && typeof parsed.conversationModels === 'object') { + parsed.conversationModels.summaryModelId = '' + parsed.conversationModels.rerankModelId = '' + parsed.conversationModels.selectedChatModelId = '' + } + parsed.selectedKnowledgeBases = [] + parsed.selectedFiles = [] + parsed.selectedFileKbMap = {} + parsed.knowledgeBaseId = '' + localStorage.setItem('WeKnora_settings', JSON.stringify(parsed)) + } + } + } catch (e) { + // localStorage may be disabled or contain malformed JSON — best effort. + console.warn('[auth] failed to clear tenant-scoped client state', e) + } + } + const setSelectedTenant = (tenantId: number | null, tenantName: string | null = null) => { + const previousTenantId = selectedTenantId.value + const tenantChanged = previousTenantId !== tenantId selectedTenantId.value = tenantId selectedTenantName.value = tenantName if (tenantId !== null) { @@ -187,6 +224,9 @@ export const useAuthStore = defineStore('auth', () => { localStorage.removeItem('weknora_selected_tenant_id') localStorage.removeItem('weknora_selected_tenant_name') } + if (tenantChanged) { + clearTenantScopedClientState() + } } const setAllTenants = (tenants: TenantInfoFromAPI[]) => { diff --git a/frontend/src/views/knowledge/KnowledgeBase.vue b/frontend/src/views/knowledge/KnowledgeBase.vue index 8cd4a223..e0ca50bd 100644 --- a/frontend/src/views/knowledge/KnowledgeBase.vue +++ b/frontend/src/views/knowledge/KnowledgeBase.vue @@ -212,20 +212,45 @@ const isOwner = computed(() => { return creatorId === userId; }); -// Can edit: KB creator (any role), or tenant Admin+, or org-share-grant. -// The hasRole('contributor') branch is intentionally NOT here — being a -// Contributor in a tenant does not by itself grant edit on someone -// else's KB. Org shares (orgStore.canEditKB) carry their own grant. +// Current KB's shared record (when accessed via organization share) +const currentSharedKb = computed(() => + orgStore.sharedKnowledgeBases.find((s) => s.knowledge_base?.id === kbId.value) ?? null, +); + +// Accessed via organization share: when the KB shows up in our +// sharedKnowledgeBases list it means we reached it through a shared space, +// not because we own/manage it in our tenant. In that case the user's local +// tenant role does NOT grant edit/manage — only the share grant does. +// Without this guard a local tenant Admin would see edit/upload entries on +// a read-only shared KB and get 403'd by the backend on click. +// +// Note: tenant_id comparison alone is unreliable — a user can be a member of +// both the source and receiving tenants, and currentTenantId reflects the +// active switcher rather than "how this KB became visible to me". Presence +// in the share list is the authoritative signal. +const isViaShare = computed(() => !!currentSharedKb.value); + +// Can edit: when accessed via an organization share, ONLY the share grant +// counts — even if the current user happens to be the original creator of +// the KB. The backend's RBAC middleware authorizes based on the active +// tenant, not on creator_id, so a creator viewing their own KB from a +// different tenant context will be 403'd on write. Otherwise: KB creator +// (any role) or tenant Admin+ in the home tenant. +// +// hasRole('contributor') is intentionally NOT here — being a Contributor +// in a tenant does not by itself grant edit on someone else's KB. const canEdit = computed(() => { + if (isViaShare.value) return orgStore.canEditKB(kbId.value, false); if (isOwner.value) return true; if (authStore.hasRole('admin')) return true; return orgStore.canEditKB(kbId.value, false); }); -// Can manage (delete, settings, etc.): KB creator or tenant Admin+. -// Org shares are intentionally excluded here — sharing a KB grants -// read/edit, never delete or settings access. +// Can manage (delete, settings, etc.): same isViaShare-first rule. For +// shared KBs only an 'admin' share grant qualifies — editor/viewer (and +// even being the creator viewed via share) never grant delete/settings. const canManage = computed(() => { + if (isViaShare.value) return orgStore.canManageKB(kbId.value, false); if (isOwner.value) return true; if (authStore.hasRole('admin')) return true; return orgStore.canManageKB(kbId.value, false); @@ -235,33 +260,33 @@ const canManage = computed(() => { // two endpoints is g.Contributor(), so the caller MUST be Contributor+ // in their tenant on top of having KB edit permission. Without the extra // role check, an org-share-editor whose tenant role is Viewer would see -// the "Move" / "Batch manage" entries and 403 on click. +// the "Move" / "Batch manage" entries and 403 on click. For shared KBs +// the local tenant role is irrelevant — canEdit already encodes the share +// grant, so trust it. const canMutateKnowledge = computed(() => { if (!canEdit.value) return false; + if (isViaShare.value) return true; if (isOwner.value) return true; if (authStore.hasRole('admin')) return true; return authStore.hasRole('contributor'); }); -// Current KB's shared record (when accessed via organization share) -const currentSharedKb = computed(() => - orgStore.sharedKnowledgeBases.find((s) => s.knowledge_base?.id === kbId.value) ?? null, -); - // Effective permission: from direct org share list or from GET /knowledge-bases/:id (e.g. agent-visible KB) const effectiveKBPermission = computed(() => orgStore.getKBPermission(kbId.value) || kbInfo.value?.my_permission || ''); -// Display role label: owner or org role (admin/editor/viewer) +// Display role label: when accessed via share, surface the share role even +// if the user happens to be the original creator — the active context is +// "viewing through a shared space", and write actions will 403 regardless. const accessRoleLabel = computed(() => { - if (isOwner.value) return t('knowledgeBase.accessInfo.roleOwner'); + if (!isViaShare.value && isOwner.value) return t('knowledgeBase.accessInfo.roleOwner'); const perm = effectiveKBPermission.value; if (perm) return t(`organization.role.${perm}`); return '--'; }); -// Permission summary text for current role +// Permission summary text for current role (mirrors accessRoleLabel rule). const accessPermissionSummary = computed(() => { - if (isOwner.value) return t('knowledgeBase.accessInfo.permissionOwner'); + if (!isViaShare.value && isOwner.value) return t('knowledgeBase.accessInfo.permissionOwner'); const perm = effectiveKBPermission.value; if (perm === 'admin') return t('knowledgeBase.accessInfo.permissionAdmin'); if (perm === 'editor') return t('knowledgeBase.accessInfo.permissionEditor'); @@ -755,7 +780,7 @@ const loadKnowledgeList = async () => { name: item.name, type: item.type || 'document', })); - + // Also include shared knowledge bases from orgStore const sharedKbs = (orgStore.sharedKnowledgeBases || []) .filter(s => s.knowledge_base != null) @@ -764,11 +789,11 @@ const loadKnowledgeList = async () => { name: s.knowledge_base.name, type: s.knowledge_base.type || 'document', })); - + // Merge and deduplicate by id (my KBs take precedence) const myKbIds = new Set(myKbs.map(kb => kb.id)); const uniqueSharedKbs = sharedKbs.filter(kb => !myKbIds.has(kb.id)); - + knowledgeList.value = [...myKbs, ...uniqueSharedKbs]; } catch (error) { console.error('Failed to load knowledge list:', error); @@ -956,7 +981,7 @@ watch(() => cardList.value, (newValue) => { // Filter items that need polling: parsing in progress OR summary generation in progress analyzeList = newValue.filter(item => { const isParsing = item.parse_status == 'pending' || item.parse_status == 'processing'; - const isSummaryPending = item.parse_status == 'completed' && + const isSummaryPending = item.parse_status == 'completed' && (item.summary_status == 'pending' || item.summary_status == 'processing'); return isParsing || isSummaryPending; }) @@ -967,7 +992,7 @@ watch(() => cardList.value, (newValue) => { if (analyzeList.length) { updateStatus(analyzeList) } - + }, { deep: true }) type KnowledgeCard = { id: string; @@ -1005,11 +1030,11 @@ const updateStatus = (analyzeList: KnowledgeCard[]) => { (result.data as KnowledgeCard[]).forEach((item: KnowledgeCard) => { const index = cardList.value.findIndex(card => card.id == item.id); if (index == -1) return; - + if (cardList.value[index].parse_status !== item.parse_status || - cardList.value[index].summary_status !== item.summary_status || - cardList.value[index].description !== item.description) { - + cardList.value[index].summary_status !== item.summary_status || + cardList.value[index].description !== item.description) { + // Always update the card data cardList.value[index].parse_status = item.parse_status; cardList.value[index].summary_status = item.summary_status; @@ -1023,7 +1048,7 @@ const updateStatus = (analyzeList: KnowledgeCard[]) => { // The watch will clear this timeout if it triggers. const stillPending = cardList.value.filter(item => { const isParsing = item.parse_status == 'pending' || item.parse_status == 'processing'; - const isSummaryPending = item.parse_status == 'completed' && + const isSummaryPending = item.parse_status == 'completed' && (item.summary_status == 'pending' || item.summary_status == 'processing'); return isParsing || isSummaryPending; }); @@ -1034,7 +1059,7 @@ const updateStatus = (analyzeList: KnowledgeCard[]) => { // 错误处理 const stillPending = cardList.value.filter(item => { const isParsing = item.parse_status == 'pending' || item.parse_status == 'processing'; - const isSummaryPending = item.parse_status == 'completed' && + const isSummaryPending = item.parse_status == 'completed' && (item.summary_status == 'pending' || item.summary_status == 'processing'); return isParsing || isSummaryPending; }); @@ -1290,7 +1315,7 @@ const handleDocumentUpload = async (event: Event) => { const input = event.target as HTMLInputElement; const files = input?.files; if (!files || files.length === 0) return; - + if (!kbId.value) { MessagePlugin.error(t('error.missingKbId')); resetUploadInput(); @@ -1447,14 +1472,14 @@ const handleFolderUpload = async (event: Event) => { for (let i = 0; i < files.length; i++) { const file = files[i]; const relativePath = (file as any).webkitRelativePath || file.name; - + const pathParts = relativePath.split('/'); const hasHiddenComponent = pathParts.some((part: string) => part.startsWith('.')); if (hasHiddenComponent) { hiddenFileCount++; continue; } - + const fileExt = file.name.substring(file.name.lastIndexOf('.') + 1).toLowerCase(); const imageTypes = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp']; const videoTypes = ['mp4', 'mov', 'avi', 'mkv', 'webm', 'wmv', 'flv']; @@ -1476,7 +1501,7 @@ const handleFolderUpload = async (event: Event) => { audioFilteredCount++; continue; } - + if (!kbFileTypeVerification(file, true, dynamicTypes)) { validFiles.push(file); } @@ -1572,7 +1597,7 @@ const handleURLImportConfirm = async () => { MessagePlugin.warning(t('knowledgeBase.urlRequired')); return; } - + // 简单的URL格式验证 try { new URL(url); @@ -1888,11 +1913,11 @@ const handleKBEditorSuccess = (kbIdValue: string) => { const getTitle = (session_id: string, value: string) => { const now = new Date().toISOString(); - let obj = { - title: t('knowledgeBase.newSession'), - path: `chat/${session_id}`, - id: session_id, - isMore: false, + let obj = { + title: t('knowledgeBase.newSession'), + path: `chat/${session_id}`, + id: session_id, + isMore: false, isNoTitle: true, created_at: now, updated_at: now @@ -1929,19 +1954,10 @@ async function createNewSession(value: string): Promise { {{ $t('menu.knowledgeBase') }} - - -