refactor(frontend): streamline knowledge base and agent handling with chat resources store

- Updated components to utilize the new `useChatResourcesStore` for managing knowledge bases and agents, improving data fetching and caching mechanisms.
- Refactored `AgentSelector`, `IMChannelPanel`, `Input-field`, and `menu` components to replace direct API calls with store methods, enhancing maintainability and performance.
- Adjusted knowledge base loading logic to ensure consistency across components and reduce redundant API requests.
- Improved session state handling in `settings` store to prevent overwriting user selections during state restoration.
This commit is contained in:
wizardchen
2026-06-08 20:55:54 +08:00
committed by lyingbug
parent dc8d4f686a
commit 815c72c964
22 changed files with 994 additions and 501 deletions
+2 -2
View File
@@ -370,10 +370,10 @@ const getMcpCapability = (agent: CustomAgent): string => {
return '';
}
if (config.mcp_selection_mode === 'all') {
return t('agent.detail.shareScope.mcpAll');
return t('agent.shareScope.mcpAll');
}
if (config.mcp_services?.length) {
return t('agent.detail.shareScope.mcpSelected', { count: config.mcp_services.length });
return t('agent.shareScope.mcpSelected', { count: config.mcp_services.length });
}
return t('agent.capabilities.mcpEnabled');
};
@@ -1,8 +1,8 @@
import { ref, watch, onMounted, computed } from 'vue'
import { listKnowledgeBases, knowledgeSemanticSearch } from '@/api/knowledge-base'
import { knowledgeSemanticSearch } from '@/api/knowledge-base'
import { searchMessages, type MessageSearchGroupItem } from '@/api/chat-history'
import { listAgents } from '@/api/agent'
import { useOrganizationStore } from '@/stores/organization'
import { useChatResourcesStore } from '@/stores/chatResources'
import { useMenuStore } from '@/stores/menu'
export interface CmdkKb {
@@ -103,17 +103,15 @@ export function useCmdkSearch(options: {
if (kbsLoadingPromise) return kbsLoadingPromise
kbsLoadingPromise = (async () => {
try {
const [kbRes, shared] = await Promise.all([
listKnowledgeBases(),
orgStore.fetchSharedKnowledgeBases(),
])
const own: CmdkKb[] = ((kbRes as any)?.data || []).map((kb: any) => ({
const chatResources = useChatResourcesStore()
await chatResources.ensureKnowledgeBases()
const own: CmdkKb[] = chatResources.rawKnowledgeBases.map((kb: any) => ({
id: String(kb.id),
name: kb.name || '',
type: kb.type,
}))
const ownIds = new Set(own.map(k => k.id))
const sharedList: CmdkKb[] = (shared || [])
const sharedList: CmdkKb[] = (orgStore.sharedKnowledgeBases || [])
.filter((s: any) => s?.knowledge_base != null)
.map((s: any) => ({
id: String(s.knowledge_base.id),
@@ -124,7 +122,6 @@ export function useCmdkSearch(options: {
knowledgeBases.value = [...own, ...sharedList]
kbsLoaded.value = true
} catch (e) {
// Best-effort; silent failure keeps the palette usable.
console.error('[cmdk] failed to load knowledge bases', e)
} finally {
kbsLoadingPromise = null
@@ -156,11 +153,9 @@ export function useCmdkSearch(options: {
if (agentsLoadingPromise) return agentsLoadingPromise
agentsLoadingPromise = (async () => {
try {
const [ownRes, shared] = await Promise.all([
listAgents(),
orgStore.fetchSharedAgents(),
])
const own: CmdkAgent[] = ((ownRes as any)?.data || []).map((a: any) => ({
const chatResources = useChatResourcesStore()
await chatResources.ensureAgents()
const own: CmdkAgent[] = chatResources.agents.map((a: any) => ({
id: String(a.id),
name: a.name || '',
description: a.description,
@@ -169,7 +164,7 @@ export function useCmdkSearch(options: {
source: 'own',
}))
const ownIds = new Set(own.map(a => a.id))
const sharedList: CmdkAgent[] = (shared || [])
const sharedList: CmdkAgent[] = (orgStore.sharedAgents || [])
.filter((s: any) => s?.agent != null)
.map((s: any) => ({
id: String(s.agent.id),
+5 -4
View File
@@ -429,7 +429,7 @@ import {
listIMChannels, createIMChannel, updateIMChannel, deleteIMChannel, toggleIMChannel,
getWeChatQRCode, pollWeChatQRCodeStatus,
} from '@/api/agent';
import { listKnowledgeBases } from '@/api/knowledge-base';
import { useChatResourcesStore } from '@/stores/chatResources';
import type { IMChannel } from '@/api/agent';
import { useAuthStore } from '@/stores/auth';
@@ -591,12 +591,13 @@ function stopWeChatPolling() {
async function loadChannels() {
loading.value = true;
try {
const [channelRes, kbRes] = await Promise.all([
const chatResources = useChatResourcesStore();
const [channelRes] = await Promise.all([
listIMChannels(props.agentId),
listKnowledgeBases(),
chatResources.ensureKnowledgeBases(),
]);
channels.value = channelRes.data || [];
knowledgeBases.value = (kbRes.data || []).map((kb: any) => ({ id: kb.id, name: kb.name }));
knowledgeBases.value = chatResources.rawKnowledgeBases.map((kb: any) => ({ id: kb.id, name: kb.name }));
} catch {
channels.value = [];
} finally {
+67 -83
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch, nextTick, h } from "vue";
import { storeToRefs } from 'pinia';
import { useRoute, useRouter } from 'vue-router';
import { onBeforeRouteUpdate } from 'vue-router';
import { MessagePlugin } from "tdesign-vue-next";
@@ -14,9 +15,9 @@ import MentionSelector from './MentionSelector.vue';
import AgentSelector from './AgentSelector.vue';
import { getCaretCoordinates } from '@/utils/caret';
import { getRootZoom, rectToCssPx, cssViewportSize } from '@/utils/zoom';
import { listModels, type ModelConfig } from '@/api/model';
import { listAgents, type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider';
import { type ModelConfig } from '@/api/model';
import { type CustomAgent, BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from '@/api/agent';
import { useChatResourcesStore } from '@/stores/chatResources';
import { useI18n } from 'vue-i18n';
import AttachmentUpload, { type AttachmentFile } from './AttachmentUpload.vue';
import {
@@ -32,6 +33,13 @@ const settingsStore = useSettingsStore();
const uiStore = useUIStore();
const orgStore = useOrganizationStore();
const menuStore = useMenuStore();
const chatResources = useChatResourcesStore();
const {
agents,
disabledOwnAgentIds,
chatModels: availableModels,
webSearchProviders,
} = storeToRefs(chatResources);
const { t } = useI18n();
let query = ref("");
@@ -122,10 +130,6 @@ const showAgentModeSelector = ref(false);
const agentModeButtonRef = ref<HTMLElement>();
const agentModeDropdownStyle = ref<Record<string, string>>({});
// 智能体相关状态(完整列表供选中态解析;对话下拉用 enabledAgents)
const agents = ref<CustomAgent[]>([]);
/** 当前租户在对话下拉中停用的「我的」智能体 ID(仅影响本租户) */
const disabledOwnAgentIds = ref<string[]>([]);
const selectedAgentId = computed({
get: () => settingsStore.selectedAgentId || BUILTIN_QUICK_ANSWER_ID,
set: (val: string) => settingsStore.selectAgent(val)
@@ -202,6 +206,7 @@ const sharedAgentKbList = ref<Array<{ id: string; name: string; type?: string; k
// 当智能体改变时,模型、网络搜索、可@知识库列表均跟随新智能体配置
// 知识库:用新智能体配置的列表替换当前选中,使已选与可@列表一致(含共享智能体)
watch([selectedAgentId, agentKnowledgeBases, agentKBSelectionMode], ([newAgentId, newAgentKbs, newKbMode], [oldAgentId]) => {
if (settingsStore._isApplyingSessionState) return;
if (newAgentId !== oldAgentId && oldAgentId !== undefined) {
if (newKbMode === 'none') {
settingsStore.selectKnowledgeBases([]);
@@ -224,8 +229,7 @@ watch([selectedAgentId, agentKnowledgeBases, agentKBSelectionMode], ([newAgentId
watch([selectedAgentId, () => settingsStore.selectedAgentSourceTenantId], async ([agentId, sourceTenantId]) => {
if (sourceTenantId && agentId) {
try {
const res: any = await listKnowledgeBases({ agent_id: agentId });
const list = res?.data && Array.isArray(res.data) ? res.data : [];
const list = await chatResources.ensureAgentKnowledgeBases(agentId);
sharedAgentKbList.value = list.map((kb: any) => ({
id: kb.id,
name: kb.name,
@@ -405,8 +409,8 @@ const isWebSearchEnabled = computed(() => settingsStore.isWebSearchEnabled);
const selectedKbIds = computed(() => settingsStore.settings.selectedKnowledgeBases || []);
const selectedFileIds = computed(() => settingsStore.settings.selectedFiles || []);
// 获取已选择的知识库信息
const knowledgeBases = ref<Array<{ id: string; name: string; type?: 'document' | 'faq'; knowledge_count?: number; chunk_count?: number }>>([]);
// 已就绪的知识库(来自租户级缓存)
const knowledgeBases = computed(() => chatResources.validKnowledgeBases);
const fileList = ref<Array<{ id: string; name: string }>>([]);
// 选中的知识库:包含自己的 + 组织共享的 + 共享智能体下的(用于展示已选列表与 org 角标)
@@ -501,8 +505,6 @@ const removeSelectedItem = (item: { id: string; type: 'kb' | 'file'; isAgentConf
}
};
// 模型相关状态
const availableModels = ref<ModelConfig[]>([]);
// 使用 computed 从 store 读取,并通过 setter 同步回 store
const selectedModelId = computed({
get: () => settingsStore.conversationModels.selectedChatModelId || '',
@@ -547,47 +549,33 @@ const inputPlaceholder = computed(() => {
});
// 加载知识库列表(自己的 + 共享的,用于 @ 提及等)
const loadKnowledgeBases = async () => {
const loadKnowledgeBases = async (force = false) => {
try {
const response: any = await listKnowledgeBases();
if (response.data && Array.isArray(response.data)) {
const validKbs = response.data.filter((kb: any) => {
if (!kb.summary_model_id || kb.summary_model_id === '') return false
const strategy = kb.indexing_strategy
const needsEmbedding = !strategy || strategy.vector_enabled || strategy.keyword_enabled
if (needsEmbedding && (!kb.embedding_model_id || kb.embedding_model_id === '')) return false
return true
});
knowledgeBases.value = validKbs;
await chatResources.ensureKnowledgeBases(force);
const validKbs = knowledgeBases.value;
// 拉取共享知识库(供 @ 提及与清理选中项时识别)
await orgStore.fetchSharedKnowledgeBases().catch(() => { });
// 清理无效的知识库ID:只移除既不在自己列表、也不在组织共享、也不在共享智能体知识库中的 ID(刷新后保留共享智能体下已选知识库)
const validKbIds = new Set(validKbs.map((kb: any) => kb.id));
const sharedKbIds = new Set(
(orgStore.sharedKnowledgeBases || []).map((s: any) => s.knowledge_base?.id).filter(Boolean)
);
let sharedAgentKbIdSet = new Set<string>();
const sourceTenantId = settingsStore.selectedAgentSourceTenantId;
const agentId = settingsStore.selectedAgentId;
if (sourceTenantId && agentId) {
try {
const res: any = await listKnowledgeBases({ agent_id: agentId });
const list = res?.data && Array.isArray(res.data) ? res.data : [];
list.forEach((kb: any) => kb?.id && sharedAgentKbIdSet.add(kb.id));
} catch {
sharedAgentKbIdSet = new Set();
}
const validKbIds = new Set(validKbs.map((kb: any) => kb.id));
const sharedKbIds = new Set(
(orgStore.sharedKnowledgeBases || []).map((s: any) => s.knowledge_base?.id).filter(Boolean)
);
let sharedAgentKbIdSet = new Set<string>();
const sourceTenantId = settingsStore.selectedAgentSourceTenantId;
const agentId = settingsStore.selectedAgentId;
if (sourceTenantId && agentId) {
try {
const list = await chatResources.ensureAgentKnowledgeBases(agentId, force);
list.forEach((kb: any) => kb?.id && sharedAgentKbIdSet.add(kb.id));
} catch {
sharedAgentKbIdSet = new Set();
}
const currentSelectedIds = settingsStore.settings.selectedKnowledgeBases || [];
const validSelectedIds = currentSelectedIds.filter(
(id: string) => validKbIds.has(id) || sharedKbIds.has(id) || sharedAgentKbIdSet.has(id)
);
}
const currentSelectedIds = settingsStore.settings.selectedKnowledgeBases || [];
const validSelectedIds = currentSelectedIds.filter(
(id: string) => validKbIds.has(id) || sharedKbIds.has(id) || sharedAgentKbIdSet.has(id)
);
if (validSelectedIds.length !== currentSelectedIds.length) {
settingsStore.selectKnowledgeBases(validSelectedIds);
}
if (validSelectedIds.length !== currentSelectedIds.length) {
settingsStore.selectKnowledgeBases(validSelectedIds);
}
} catch (error) {
console.error('Failed to load knowledge bases:', error);
@@ -644,8 +632,6 @@ watch(selectedFileIds, () => {
loadFiles();
}, { immediate: true });
const webSearchProviders = ref<WebSearchProviderEntity[]>([]);
const isWebSearchConfigured = computed(() => {
const agentProviderId = agentWebSearchProviderId.value;
if (agentProviderId) {
@@ -655,18 +641,16 @@ const isWebSearchConfigured = computed(() => {
return webSearchProviders.value.some(p => p.is_default);
});
const loadWebSearchConfig = async () => {
const loadWebSearchConfig = async (force = false) => {
try {
const response = await listWebSearchProviders();
const providers = (response as any)?.data;
webSearchProviders.value = Array.isArray(providers) ? providers : [];
await chatResources.ensureWebSearchProviders(force);
if (!isWebSearchConfigured.value && settingsStore.isWebSearchEnabled) {
settingsStore.toggleWebSearch(false);
}
} catch (error) {
console.error('Failed to load web search config:', error);
webSearchProviders.value = [];
chatResources.invalidate('webSearchProviders');
if (settingsStore.isWebSearchEnabled) {
settingsStore.toggleWebSearch(false);
}
@@ -674,20 +658,14 @@ const loadWebSearchConfig = async () => {
};
// 加载智能体列表(我的 + 共享,供选中态与就绪检查用)
const loadAgents = async () => {
const loadAgents = async (force = false) => {
try {
const [agentsRes] = await Promise.all([
listAgents(),
orgStore.fetchSharedAgents(),
]);
const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
agents.value = res.data || []
disabledOwnAgentIds.value = res.disabled_own_agent_ids || []
ensureSelectedAgentNotDisabled()
await chatResources.ensureAgents(force);
ensureSelectedAgentNotDisabled();
} catch (error) {
console.error('Failed to load agents:', error)
console.error('Failed to load agents:', error);
}
}
};
// 默认选中的 builtin(builtin-quick-answer)也可能被当前租户管理员停用。
// 列表加载完后做一次纠偏:若当前选中的是本租户停用的 agent(仅限「我的/builtin」,
@@ -775,16 +753,15 @@ const initChatModelSelection = () => {
ensureModelSelection();
};
const loadChatModels = async () => {
const loadChatModels = async (force = false) => {
if (modelsLoading.value) return;
modelsLoading.value = true;
try {
const models = await listModels('KnowledgeQA');
availableModels.value = Array.isArray(models) ? models : [];
await chatResources.ensureChatModels(force);
ensureModelSelection();
} catch (error) {
console.error('Failed to load chat models:', error);
availableModels.value = [];
chatResources.invalidate('models');
} finally {
modelsLoading.value = false;
}
@@ -1021,8 +998,7 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
if (sourceTenantId && agentId) {
// 共享智能体:按 agent_id 拉取该智能体配置的知识库范围(后端从共享关系解析租户)
try {
const res: any = await listKnowledgeBases({ agent_id: agentId });
const list = res?.data && Array.isArray(res.data) ? res.data : [];
const list = await chatResources.ensureAgentKnowledgeBases(agentId);
const orgLabel = sharedAgentOrgName.value || '';
// 保留 capabilities / indexing_strategy,后面过滤时要用
availableKbs = list.map((kb: any) => ({
@@ -1123,7 +1099,10 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
const toolsAllowFiles = !hasAgentConfig.value || toolsConsumeFiles(agentAllowedTools.value);
const shouldLoadFiles = kbModeAllowsFiles && toolsAllowFiles;
if (shouldLoadFiles) {
// 后端 /knowledge/search 要求非空 keyword;打开 @ 面板时仅展示本地 KB 列表,
// 用户输入搜索词后再拉取文件结果。
const fileSearchKeyword = q.trim();
if (shouldLoadFiles && fileSearchKeyword) {
mentionLoading.value = true;
try {
const fileTypesParam = agentSupportedFileTypes.value.length > 0 ? agentSupportedFileTypes.value : undefined;
@@ -1131,7 +1110,7 @@ const loadMentionItems = async (q: string, resetIndex = true, append = false) =>
const agentId = selectedAgentId.value;
const searchOptions = sourceTenantId && agentId ? { agent_id: agentId } : undefined;
const res: any = await searchKnowledge(
q || '',
fileSearchKeyword,
mentionOffset.value,
MENTION_PAGE_SIZE,
fileTypesParam,
@@ -1504,11 +1483,14 @@ let resizeHandler: (() => void) | null = null;
let scrollHandler: (() => void) | null = null;
onMounted(() => {
loadKnowledgeBases();
loadWebSearchConfig();
// 并行拉取;若 platform 已预取且缓存未过期则直接复用
initChatModelSelection();
loadChatModels();
loadAgents();
void Promise.all([
loadKnowledgeBases(),
loadWebSearchConfig(),
loadChatModels(),
loadAgents(),
]);
window.addEventListener(CHAT_FILE_DROP_EVENT, handleChatFileDrop as EventListener);
// 从持久化恢复 fileId -> kbId,刷新后共享知识库文件可带 kb_id 拉取(仅保留当前仍选中的文件)
@@ -1586,7 +1568,8 @@ watch(() => route.params.kbId, (newKbId) => {
watch(() => uiStore.showSettingsModal, (visible, prevVisible) => {
if (prevVisible && !visible) {
loadWebSearchConfig();
loadWebSearchConfig(true);
loadChatModels(true);
}
});
@@ -1747,8 +1730,9 @@ const toggleAgentModeSelector = () => {
showAgentModeSelector.value = !showAgentModeSelector.value;
if (showAgentModeSelector.value) {
// 重新加载智能体列表
loadAgents();
if (!chatResources.isFresh('agents')) {
void loadAgents(true);
}
// 多次更新位置确保准确
nextTick(() => {
updateAgentModeDropdownPosition();
+20 -29
View File
@@ -157,7 +157,7 @@ import { storeToRefs } from 'pinia';
import { onMounted, watch, computed, ref, h } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getSessionsList, delSession, batchDelSessions, deleteAllSessions, clearSessionMessages, pinSession, unpinSession } from "@/api/chat/index";
import { getKnowledgeBaseById } from '@/api/knowledge-base';
import { useChatResourcesStore } from '@/stores/chatResources';
import { logout as logoutApi } from '@/api/auth';
import { useMenuStore } from '@/stores/menu';
import { useAuthStore } from '@/stores/auth';
@@ -169,6 +169,8 @@ import UserMenu from '@/components/UserMenu.vue';
import TenantSelector from '@/components/TenantSelector.vue';
import { useI18n } from 'vue-i18n';
import { getSystemInfo } from '@/api/system';
const chatResources = useChatResourcesStore();
// Platform logos reused from IMChannelsOverviewPanel — keeps the session list
// visually consistent with the channels admin view.
import wecomLogo from '@/assets/img/im/wecom.svg';
@@ -660,6 +662,21 @@ const getMessageList = async (isLoadMore = false) => {
})
}
async function loadCurrentKbInfo(kbId: string) {
if (!kbId || !isInKnowledgeBase.value) {
currentKbName.value = ''
currentKbInfo.value = null
return
}
const data = await chatResources.fetchKnowledgeBaseById(kbId)
if (data) {
currentKbName.value = data.name || ''
currentKbInfo.value = data
} else {
currentKbInfo.value = null
}
}
onMounted(async () => {
const routeName = typeof route.name === 'string' ? route.name : (route.name ? String(route.name) : '')
currentpath.value = routeName;
@@ -675,20 +692,7 @@ onMounted(async () => {
}
}).catch(() => { })
// 初始化知识库信息
const kbId = (route.params as any)?.kbId as string
if (kbId && isInKnowledgeBase.value) {
try {
const kbRes: any = await getKnowledgeBaseById(kbId)
if (kbRes?.data) {
currentKbName.value = kbRes.data.name || ''
currentKbInfo.value = kbRes.data
}
} catch { }
} else {
currentKbName.value = ''
currentKbInfo.value = null
}
await loadCurrentKbInfo((route.params as any)?.kbId as string)
// 加载对话列表
getMessageList();
@@ -728,20 +732,7 @@ watch([() => route.name, () => route.params], (newvalue, oldvalue) => {
// 如果切换了知识库,更新知识库名称但不重新加载对话列表
if (newvalue[1].kbId !== oldvalue?.[1]?.kbId) {
const kbId = (newvalue[1] as any)?.kbId as string;
if (kbId && isInKnowledgeBase.value) {
getKnowledgeBaseById(kbId).then((kbRes: any) => {
if (kbRes?.data) {
currentKbName.value = kbRes.data.name || '';
currentKbInfo.value = kbRes.data;
}
}).catch(() => {
currentKbInfo.value = null;
});
} else {
currentKbName.value = '';
currentKbInfo.value = null;
}
loadCurrentKbInfo((newvalue[1] as any)?.kbId as string);
}
});
let knowledgeIcon = ref('zhishiku-green.svg');
@@ -1,20 +1,23 @@
import { computed, onMounted, ref, watch } from 'vue'
import { useUIStore } from '@/stores/ui'
import { useChatResourcesStore } from '@/stores/chatResources'
import {
fetchTenantModelReadiness,
evaluateTenantModelReadiness,
type TenantModelReadiness,
} from '@/utils/tenantModelReadiness'
export function useTenantModelReadiness() {
const uiStore = useUIStore()
const chatResources = useChatResourcesStore()
const readiness = ref<TenantModelReadiness | null>(null)
const loaded = ref(false)
const loading = ref(false)
const refresh = async () => {
const refresh = async (force = false) => {
loading.value = true
try {
readiness.value = await fetchTenantModelReadiness()
await chatResources.ensureModels(force)
readiness.value = evaluateTenantModelReadiness(chatResources.allModels)
} finally {
loading.value = false
loaded.value = true
@@ -29,7 +32,7 @@ export function useTenantModelReadiness() {
() => uiStore.showSettingsModal,
(open, wasOpen) => {
if (wasOpen && !open) {
refresh()
refresh(true)
}
},
)
+259
View File
@@ -0,0 +1,259 @@
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { listKnowledgeBases, getKnowledgeBaseById } from '@/api/knowledge-base'
import { listAgents, type CustomAgent } from '@/api/agent'
import { listModels, type ModelConfig } from '@/api/model'
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider'
import { useOrganizationStore } from '@/stores/organization'
/** 租户级资源缓存 TTL */
const CACHE_TTL_MS = 60_000
type ResourceKey = 'knowledgeBases' | 'agents' | 'models' | 'webSearchProviders'
export type ListCreatorFilter = 'all' | 'mine' | 'others'
function isKbModelReady(kb: any): boolean {
if (!kb.summary_model_id || kb.summary_model_id === '') return false
const strategy = kb.indexing_strategy
const needsEmbedding = !strategy || strategy.vector_enabled || strategy.keyword_enabled
if (needsEmbedding && (!kb.embedding_model_id || kb.embedding_model_id === '')) return false
return true
}
export const useChatResourcesStore = defineStore('chatResources', () => {
const rawKnowledgeBases = ref<any[]>([])
const agents = ref<CustomAgent[]>([])
const disabledOwnAgentIds = ref<string[]>([])
const allModels = ref<ModelConfig[]>([])
const webSearchProviders = ref<WebSearchProviderEntity[]>([])
const loadedAt = ref<Partial<Record<ResourceKey, number>>>({})
const inflight = new Map<ResourceKey, Promise<void>>()
const agentKbCache = new Map<string, { at: number; data: any[] }>()
const agentKbInflight = new Map<string, Promise<any[]>>()
const kbDetailCache = new Map<string, { at: number; data: any }>()
const kbDetailInflight = new Map<string, Promise<any | null>>()
const validKnowledgeBases = computed(() => rawKnowledgeBases.value.filter(isKbModelReady))
const chatModels = computed(() => allModels.value.filter((m) => m.type === 'KnowledgeQA'))
function isFresh(key: ResourceKey): boolean {
const at = loadedAt.value[key]
return !!at && Date.now() - at < CACHE_TTL_MS
}
async function runOnce(key: ResourceKey, force: boolean, loader: () => Promise<void>): Promise<void> {
if (!force && isFresh(key)) return
const existing = inflight.get(key)
if (existing) return existing
const p = loader().finally(() => {
inflight.delete(key)
})
inflight.set(key, p)
return p
}
/**
* 知识库列表(支持 creator 筛选)。creator=all 时写入缓存供对话页复用。
*/
async function fetchKnowledgeBasesForList(
params?: { creator?: ListCreatorFilter },
force = false,
): Promise<any[]> {
const creator = params?.creator ?? 'all'
if (!force && creator === 'all' && isFresh('knowledgeBases')) {
return rawKnowledgeBases.value
}
const res: any = await listKnowledgeBases(
creator === 'all' ? undefined : { creator },
)
const data = res?.data && Array.isArray(res.data) ? res.data : []
if (creator === 'all') {
rawKnowledgeBases.value = data
loadedAt.value.knowledgeBases = Date.now()
const orgStore = useOrganizationStore()
await orgStore.fetchSharedKnowledgeBases({ force })
}
return data
}
async function ensureKnowledgeBases(force = false): Promise<void> {
await fetchKnowledgeBasesForList({ creator: 'all' }, force)
}
/**
* 智能体列表(支持 creator 筛选)。creator=all 时写入缓存。
*/
async function fetchAgentsForList(
params?: { creator?: ListCreatorFilter },
force = false,
): Promise<{ data: CustomAgent[]; disabled_own_agent_ids: string[] }> {
const creator = params?.creator ?? 'all'
if (!force && creator === 'all' && isFresh('agents')) {
return { data: agents.value, disabled_own_agent_ids: disabledOwnAgentIds.value }
}
const orgStore = useOrganizationStore()
const [agentsRes] = await Promise.all([
listAgents(creator === 'all' ? undefined : { creator }),
orgStore.fetchSharedAgents({ force }),
])
const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
const data = res.data || []
if (creator === 'all') {
agents.value = data
disabledOwnAgentIds.value = res.disabled_own_agent_ids || []
loadedAt.value.agents = Date.now()
}
return { data, disabled_own_agent_ids: res.disabled_own_agent_ids || [] }
}
async function ensureAgents(force = false): Promise<void> {
await fetchAgentsForList({ creator: 'all' }, force)
}
async function ensureModels(force = false): Promise<void> {
return runOnce('models', force, async () => {
const models = await listModels()
allModels.value = Array.isArray(models) ? models : []
loadedAt.value.models = Date.now()
})
}
/** @deprecated 使用 ensureModels;保留别名供对话输入栏调用 */
async function ensureChatModels(force = false): Promise<void> {
return ensureModels(force)
}
async function ensureWebSearchProviders(force = false): Promise<void> {
return runOnce('webSearchProviders', force, async () => {
const response = await listWebSearchProviders()
const providers = (response as any)?.data
webSearchProviders.value = Array.isArray(providers) ? providers : []
loadedAt.value.webSearchProviders = Date.now()
})
}
/** 并行预取对话输入栏及列表页常用的租户级资源 */
async function prefetchChatInput(force = false): Promise<void> {
const orgStore = useOrganizationStore()
await Promise.all([
ensureKnowledgeBases(force),
ensureAgents(force),
ensureModels(force),
ensureWebSearchProviders(force),
orgStore.fetchOrganizations({ force }),
])
}
async function ensureAgentKnowledgeBases(agentId: string, force = false): Promise<any[]> {
const cached = agentKbCache.get(agentId)
if (!force && cached && Date.now() - cached.at < CACHE_TTL_MS) {
return cached.data
}
const existing = agentKbInflight.get(agentId)
if (existing) return existing
const p = (async () => {
try {
const res: any = await listKnowledgeBases({ agent_id: agentId })
const list = res?.data && Array.isArray(res.data) ? res.data : []
agentKbCache.set(agentId, { at: Date.now(), data: list })
return list
} finally {
agentKbInflight.delete(agentId)
}
})()
agentKbInflight.set(agentId, p)
return p
}
/** 单个知识库详情(侧栏 + 详情页共用,去重并发请求) */
async function fetchKnowledgeBaseById(kbId: string, force = false): Promise<any | null> {
if (!kbId) return null
const cached = kbDetailCache.get(kbId)
if (!force && cached && Date.now() - cached.at < CACHE_TTL_MS) {
return cached.data
}
const existing = kbDetailInflight.get(kbId)
if (existing) return existing
const p = (async () => {
try {
const res: any = await getKnowledgeBaseById(kbId)
const data = res?.data ?? null
if (data) {
kbDetailCache.set(kbId, { at: Date.now(), data })
}
return data
} catch {
return null
} finally {
kbDetailInflight.delete(kbId)
}
})()
kbDetailInflight.set(kbId, p)
return p
}
function invalidateKnowledgeBaseDetail(kbId?: string) {
if (kbId) {
kbDetailCache.delete(kbId)
kbDetailInflight.delete(kbId)
} else {
kbDetailCache.clear()
kbDetailInflight.clear()
}
}
function invalidate(...keys: ResourceKey[]) {
if (keys.length === 0) {
loadedAt.value = {}
rawKnowledgeBases.value = []
agents.value = []
disabledOwnAgentIds.value = []
allModels.value = []
webSearchProviders.value = []
agentKbCache.clear()
invalidateKnowledgeBaseDetail()
return
}
keys.forEach((k) => {
delete loadedAt.value[k]
})
if (keys.includes('knowledgeBases')) {
agentKbCache.clear()
invalidateKnowledgeBaseDetail()
}
}
return {
rawKnowledgeBases,
validKnowledgeBases,
agents,
disabledOwnAgentIds,
allModels,
chatModels,
webSearchProviders,
isFresh,
fetchKnowledgeBasesForList,
fetchAgentsForList,
ensureKnowledgeBases,
ensureAgents,
ensureModels,
ensureChatModels,
ensureWebSearchProviders,
ensureAgentKnowledgeBases,
prefetchChatInput,
fetchKnowledgeBaseById,
invalidateKnowledgeBaseDetail,
invalidate,
}
})
+203
View File
@@ -0,0 +1,203 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
getStorageEngineConfig,
getStorageEngineStatus,
getPromptTemplates,
getParserEngines,
getSystemInfo,
type PromptTemplatesConfig,
type StorageEngineStatusItem,
type ParserEngineInfo,
type SystemInfo,
} from '@/api/system'
import { listMCPServices, type MCPService } from '@/api/mcp-service'
import { listSkills, type SkillInfo } from '@/api/skill'
import { getAgentTypePresets, getPlaceholders, type AgentTypePreset, type PlaceholderDefinition } from '@/api/agent'
import { getTenantRetrievalConfig } from '@/api/retrieval'
const CACHE_TTL_MS = 60_000
type EditorResourceKey =
| 'storageEngine'
| 'mcpServices'
| 'skills'
| 'agentTypePresets'
| 'promptTemplates'
| 'placeholders'
| 'tenantRetrievalConfig'
| 'parserEngines'
| 'systemInfo'
export const useEditorResourcesStore = defineStore('editorResources', () => {
const storageConfig = ref<Awaited<ReturnType<typeof getStorageEngineConfig>>['data'] | null>(null)
const storageStatus = ref<StorageEngineStatusItem[]>([])
const storageAllowedProviders = ref<string[]>([])
const mcpServices = ref<MCPService[]>([])
const skills = ref<SkillInfo[]>([])
const skillsAvailable = ref(true)
const agentTypePresets = ref<AgentTypePreset[]>([])
const promptTemplates = ref<PromptTemplatesConfig | null>(null)
const placeholders = ref<PlaceholderDefinition[]>([])
const tenantRetrievalConfig = ref<Record<string, unknown> | null>(null)
const parserEngines = ref<ParserEngineInfo[]>([])
const systemInfo = ref<SystemInfo | null>(null)
const loadedAt = ref<Partial<Record<EditorResourceKey, number>>>({})
const inflight = new Map<EditorResourceKey, Promise<void>>()
function isFresh(key: EditorResourceKey): boolean {
const at = loadedAt.value[key]
return !!at && Date.now() - at < CACHE_TTL_MS
}
async function runOnce(key: EditorResourceKey, force: boolean, loader: () => Promise<void>): Promise<void> {
if (!force && isFresh(key)) return
const existing = inflight.get(key)
if (existing) return existing
const p = loader().finally(() => inflight.delete(key))
inflight.set(key, p)
return p
}
async function ensureStorageEngine(force = false): Promise<void> {
return runOnce('storageEngine', force, async () => {
const [configRes, statusRes] = await Promise.all([
getStorageEngineConfig(),
getStorageEngineStatus(),
])
storageConfig.value = configRes?.data ?? null
storageStatus.value = statusRes?.data?.engines ?? []
storageAllowedProviders.value = statusRes?.data?.allowed_providers ?? []
loadedAt.value.storageEngine = Date.now()
})
}
async function ensureMcpServices(force = false): Promise<void> {
return runOnce('mcpServices', force, async () => {
const list = await listMCPServices()
mcpServices.value = Array.isArray(list) ? list : []
loadedAt.value.mcpServices = Date.now()
})
}
async function ensureSkills(force = false): Promise<void> {
return runOnce('skills', force, async () => {
try {
const skillsRes = await listSkills()
skillsAvailable.value = skillsRes.skills_available !== false
skills.value = skillsRes.data && skillsRes.data.length > 0 ? skillsRes.data : []
} catch {
skillsAvailable.value = false
skills.value = []
}
loadedAt.value.skills = Date.now()
})
}
async function ensureAgentTypePresets(force = false): Promise<void> {
return runOnce('agentTypePresets', force, async () => {
const presetsRes: any = await getAgentTypePresets()
agentTypePresets.value = presetsRes?.data && Array.isArray(presetsRes.data) ? presetsRes.data : []
loadedAt.value.agentTypePresets = Date.now()
})
}
async function ensurePromptTemplates(force = false): Promise<void> {
return runOnce('promptTemplates', force, async () => {
const tmplRes = await getPromptTemplates()
promptTemplates.value = tmplRes?.data ?? null
loadedAt.value.promptTemplates = Date.now()
})
}
async function ensurePlaceholders(force = false): Promise<void> {
return runOnce('placeholders', force, async () => {
const placeholdersRes = await getPlaceholders()
placeholders.value = placeholdersRes?.data ?? []
loadedAt.value.placeholders = Date.now()
})
}
async function ensureTenantRetrievalConfig(force = false): Promise<void> {
return runOnce('tenantRetrievalConfig', force, async () => {
const retrievalRes: any = await getTenantRetrievalConfig()
tenantRetrievalConfig.value = retrievalRes?.data ?? null
loadedAt.value.tenantRetrievalConfig = Date.now()
})
}
async function ensureParserEngines(force = false): Promise<void> {
return runOnce('parserEngines', force, async () => {
const resp = await getParserEngines()
parserEngines.value = resp?.data && Array.isArray(resp.data) ? resp.data : []
loadedAt.value.parserEngines = Date.now()
})
}
async function ensureSystemInfo(force = false): Promise<void> {
return runOnce('systemInfo', force, async () => {
const response = await getSystemInfo()
systemInfo.value = response?.data ?? null
loadedAt.value.systemInfo = Date.now()
})
}
/** 智能体编辑器打开时预取的依赖(不含 IM channels / 单 KB shares) */
async function prefetchAgentEditorDeps(force = false): Promise<void> {
await Promise.all([
ensureMcpServices(force),
ensureSkills(force),
ensureAgentTypePresets(force),
ensurePromptTemplates(force),
ensureStorageEngine(force),
ensurePlaceholders(force),
ensureTenantRetrievalConfig(force),
])
}
function invalidate(...keys: EditorResourceKey[]) {
if (keys.length === 0) {
loadedAt.value = {}
storageConfig.value = null
storageStatus.value = []
storageAllowedProviders.value = []
mcpServices.value = []
skills.value = []
agentTypePresets.value = []
promptTemplates.value = null
placeholders.value = []
tenantRetrievalConfig.value = null
parserEngines.value = []
systemInfo.value = null
return
}
keys.forEach((k) => delete loadedAt.value[k])
}
return {
storageConfig,
storageStatus,
storageAllowedProviders,
mcpServices,
skills,
skillsAvailable,
agentTypePresets,
promptTemplates,
placeholders,
tenantRetrievalConfig,
parserEngines,
systemInfo,
ensureStorageEngine,
ensureMcpServices,
ensureSkills,
ensureAgentTypePresets,
ensurePromptTemplates,
ensurePlaceholders,
ensureTenantRetrievalConfig,
ensureParserEngines,
ensureSystemInfo,
prefetchAgentEditorDeps,
invalidate,
}
})
+81 -28
View File
@@ -38,6 +38,13 @@ export const useOrganizationStore = defineStore('organization', () => {
const resourceCounts = ref<ResourceCountsByOrg | null>(null)
/** 用于去重:同一时刻只允许一次 GET /organizations 请求 */
let fetchOrganizationsPromise: Promise<void> | null = null
let organizationsLoadedAt = 0
/** 共享资源缓存 TTL,与 chatResources 对齐 */
const SHARED_RESOURCE_TTL_MS = 60_000
let sharedKbLoadedAt = 0
let sharedAgentsLoadedAt = 0
let fetchSharedKbPromise: Promise<SharedKnowledgeBase[]> | null = null
let fetchSharedAgentsPromise: Promise<SharedAgentInfo[]> | null = null
// Computed
const myOrganizations = computed(() => organizations.value)
@@ -59,9 +66,17 @@ export const useOrganizationStore = defineStore('organization', () => {
/**
* Fetch all organizations the user belongs to.
* 去重:并发调用只发一次请求,共用同一 Promise。
* 去重 + 短期缓存,列表页与侧栏等多处共用。
*/
async function fetchOrganizations() {
async function fetchOrganizations(options?: { force?: boolean }) {
const force = options?.force ?? false
if (
!force &&
organizationsLoadedAt > 0 &&
Date.now() - organizationsLoadedAt < SHARED_RESOURCE_TTL_MS
) {
return
}
if (fetchOrganizationsPromise) return fetchOrganizationsPromise
loading.value = true
error.value = null
@@ -71,6 +86,7 @@ export const useOrganizationStore = defineStore('organization', () => {
if (response.success && response.data) {
organizations.value = response.data.organizations
resourceCounts.value = response.data.resource_counts ?? null
organizationsLoadedAt = Date.now()
} else {
resourceCounts.value = null
error.value = response.message || 'Failed to fetch organizations'
@@ -343,43 +359,74 @@ export const useOrganizationStore = defineStore('organization', () => {
}
/**
* Fetch shared knowledge bases
* Fetch shared knowledge bases.
* 去重 + 短期缓存,避免对话页等多处并发重复请求。
*/
async function fetchSharedKnowledgeBases() {
async function fetchSharedKnowledgeBases(options?: { force?: boolean }) {
const force = options?.force ?? false
if (
!force &&
sharedKbLoadedAt > 0 &&
Date.now() - sharedKbLoadedAt < SHARED_RESOURCE_TTL_MS
) {
return sharedKnowledgeBases.value
}
if (fetchSharedKbPromise) return fetchSharedKbPromise
loading.value = true
error.value = null
try {
const response = await listSharedKnowledgeBases()
if (response.success && response.data) {
// Filter out shares whose knowledge_base was deleted (null)
sharedKnowledgeBases.value = response.data.filter(s => s.knowledge_base != null)
return sharedKnowledgeBases.value
} else {
fetchSharedKbPromise = (async () => {
try {
const response = await listSharedKnowledgeBases()
if (response.success && response.data) {
sharedKnowledgeBases.value = response.data.filter(s => s.knowledge_base != null)
sharedKbLoadedAt = Date.now()
return sharedKnowledgeBases.value
}
error.value = response.message || 'Failed to fetch shared knowledge bases'
return []
} catch (e: any) {
error.value = e.message || 'Failed to fetch shared knowledge bases'
return []
} finally {
loading.value = false
fetchSharedKbPromise = null
}
} catch (e: any) {
error.value = e.message || 'Failed to fetch shared knowledge bases'
return []
} finally {
loading.value = false
}
})()
return fetchSharedKbPromise
}
/**
* Fetch shared agents (shared to me through organizations)
* Fetch shared agents (shared to me through organizations).
* 去重 + 短期缓存。
*/
async function fetchSharedAgents() {
try {
const response = await listSharedAgents()
if (response.success && response.data) {
sharedAgents.value = response.data.filter(s => s.agent != null)
return sharedAgents.value
}
return []
} catch (e: any) {
return []
async function fetchSharedAgents(options?: { force?: boolean }) {
const force = options?.force ?? false
if (
!force &&
sharedAgentsLoadedAt > 0 &&
Date.now() - sharedAgentsLoadedAt < SHARED_RESOURCE_TTL_MS
) {
return sharedAgents.value
}
if (fetchSharedAgentsPromise) return fetchSharedAgentsPromise
fetchSharedAgentsPromise = (async () => {
try {
const response = await listSharedAgents()
if (response.success && response.data) {
sharedAgents.value = response.data.filter(s => s.agent != null)
sharedAgentsLoadedAt = Date.now()
return sharedAgents.value
}
return []
} catch {
return []
} finally {
fetchSharedAgentsPromise = null
}
})()
return fetchSharedAgentsPromise
}
/**
@@ -430,6 +477,12 @@ export const useOrganizationStore = defineStore('organization', () => {
resourceCounts.value = null
previewData.value = null
error.value = null
sharedKbLoadedAt = 0
sharedAgentsLoadedAt = 0
fetchSharedKbPromise = null
fetchSharedAgentsPromise = null
organizationsLoadedAt = 0
fetchOrganizationsPromise = null
}
return {
+30 -23
View File
@@ -108,6 +108,8 @@ export const useSettingsStore = defineStore("settings", {
// 进入会话时拍下"全局默认"的快照;离开会话时还原。非持久化字段:
// 刷新页面相当于重新走"进入会话"流程,自然会重新拍快照。
_defaultsSnapshot: null as Settings | null,
/** 正在从 session.last_request_state 恢复输入栏,避免 agent 切换 watch 覆盖 KB 选择 */
_isApplyingSessionState: false,
}),
getters: {
@@ -450,29 +452,34 @@ export const useSettingsStore = defineStore("settings", {
// 任何字段缺失则保留 store 现值,做"尽力恢复"。
applyLastRequestState(state: SessionLastRequestStatePayload | null | undefined) {
if (!state) return;
if (typeof state.agent_enabled === "boolean") {
this.settings.isAgentEnabled = state.agent_enabled;
}
if (typeof state.agent_id === "string" && state.agent_id) {
this.settings.selectedAgentId = state.agent_id;
// 上次记录是自有 agent 还是共享 agent,目前服务端不区分回传 sourceTenantId。
// 与 selectAgent() 不同,这里**不**重置 KB/文件选择 —— 因为我们紧接着
// 就要用 state 里的 KB/文件覆盖,不需要先清空再写。
}
if (state.model_id !== undefined) {
const current = this.settings.conversationModels || defaultSettings.conversationModels;
this.settings.conversationModels = { ...current, selectedChatModelId: state.model_id || "" };
}
if (Array.isArray(state.knowledge_base_ids)) {
this.settings.selectedKnowledgeBases = [...state.knowledge_base_ids];
}
if (Array.isArray(state.knowledge_ids)) {
this.settings.selectedFiles = [...state.knowledge_ids];
// selectedFileKbMap 此时无法重建(state 里没存 KB 归属),交给前端按
// 需要 lazy 拉取。保留 store 现值,避免误删用户刚加进来的文件映射。
}
if (typeof state.web_search_enabled === "boolean") {
this.settings.webSearchEnabled = state.web_search_enabled;
this._isApplyingSessionState = true;
try {
if (typeof state.agent_enabled === "boolean") {
this.settings.isAgentEnabled = state.agent_enabled;
}
if (typeof state.agent_id === "string" && state.agent_id) {
this.settings.selectedAgentId = state.agent_id;
// 上次记录是自有 agent 还是共享 agent,目前服务端不区分回传 sourceTenantId。
// 与 selectAgent() 不同,这里**不**重置 KB/文件选择 —— 因为我们紧接着
// 就要用 state 里的 KB/文件覆盖,不需要先清空再写。
}
if (state.model_id !== undefined) {
const current = this.settings.conversationModels || defaultSettings.conversationModels;
this.settings.conversationModels = { ...current, selectedChatModelId: state.model_id || "" };
}
if (Array.isArray(state.knowledge_base_ids)) {
this.settings.selectedKnowledgeBases = [...state.knowledge_base_ids];
}
if (Array.isArray(state.knowledge_ids)) {
this.settings.selectedFiles = [...state.knowledge_ids];
// selectedFileKbMap 此时无法重建(state 里没存 KB 归属),交给前端按
// 需要 lazy 拉取。保留 store 现值,避免误删用户刚加进来的文件映射。
}
if (typeof state.web_search_enabled === "boolean") {
this.settings.webSearchEnabled = state.web_search_enabled;
}
} finally {
this._isApplyingSessionState = false;
}
// 注意:故意不写 localStorage —— 旧会话的状态不应污染"用户默认"。
// 离开会话时 restoreDefaultsIfSnapshotted 会把 localStorage 里那份完整
+94 -183
View File
@@ -1290,7 +1290,7 @@
</div>
<!-- IM集成(仅编辑模式) -->
<div v-if="props.mode === 'edit' && props.agent?.id" v-show="currentSection === 'im'" class="section">
<div v-if="props.mode === 'edit' && props.agent?.id && currentSection === 'im'" class="section">
<div class="section-header">
<h2>{{ $t('agentEditor.im.title') }}</h2>
<p class="section-description">
@@ -1340,8 +1340,6 @@ import { MessagePlugin } from 'tdesign-vue-next';
import {
createAgent,
updateAgent,
getPlaceholders,
getAgentTypePresets,
type CustomAgent,
type PlaceholderDefinition,
type AgentTypePreset,
@@ -1349,16 +1347,16 @@ import {
type AgentTypeKBFilter,
type KBCapabilities,
} from '@/api/agent';
import { listModels, type ModelConfig } from '@/api/model';
import { listKnowledgeBases } from '@/api/knowledge-base';
import { listMCPServices, type MCPService } from '@/api/mcp-service';
import { listSkills, type SkillInfo } from '@/api/skill';
import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-search-provider';
import { getStorageEngineStatus, getPromptTemplates, type StorageEngineStatusItem, type PromptTemplate } from '@/api/system';
import { getTenantRetrievalConfig } from '@/api/retrieval';
import { type ModelConfig } from '@/api/model';
import { type MCPService } from '@/api/mcp-service';
import { type SkillInfo } from '@/api/skill';
import { type WebSearchProviderEntity } from '@/api/web-search-provider';
import { type StorageEngineStatusItem, type PromptTemplate, type PromptTemplatesConfig } from '@/api/system';
import { useUIStore } from '@/stores/ui';
import { useAuthStore } from '@/stores/auth';
import { useOrganizationStore } from '@/stores/organization';
import { useChatResourcesStore } from '@/stores/chatResources';
import { useEditorResourcesStore } from '@/stores/editorResources';
import AgentAvatar from '@/components/AgentAvatar.vue';
import PromptTemplateSelector from '@/components/PromptTemplateSelector.vue';
import ModelSelector from '@/components/ModelSelector.vue';
@@ -1375,6 +1373,8 @@ import {
const uiStore = useUIStore();
const authStore = useAuthStore();
const orgStore = useOrganizationStore();
const chatResources = useChatResourcesStore();
const editorResources = useEditorResourcesStore();
const { t, locale: i18nLocale } = useI18n();
@@ -2624,18 +2624,17 @@ watch(isAgentMode, (isAgent) => {
// 监听设置弹窗关闭,刷新模型列表
watch(() => uiStore.showSettingsModal, async (visible, prevVisible) => {
// 从设置页面返回时(弹窗关闭),刷新模型列表
if (prevVisible && !visible && props.visible) {
try {
const [models, statusRes] = await Promise.all([
listModels(),
getStorageEngineStatus(),
await Promise.all([
chatResources.ensureModels(true),
editorResources.ensureStorageEngine(true),
]);
if (models && models.length > 0) {
allModels.value = models;
if (chatResources.allModels.length > 0) {
allModels.value = chatResources.allModels;
}
if (statusRes?.data?.engines) {
storageEngineStatus.value = statusRes.data.engines;
if (editorResources.storageStatus.length > 0) {
storageEngineStatus.value = editorResources.storageStatus;
}
} catch (e) {
console.warn('Failed to refresh data after settings closed', e);
@@ -2643,183 +2642,95 @@ watch(() => uiStore.showSettingsModal, async (visible, prevVisible) => {
}
});
// 加载依赖数据
const mapKbToOption = (kb: any, shared: boolean, orgName?: string) => {
const strategy = kb.indexing_strategy;
const caps: KBCapabilities | undefined = kb.capabilities;
return {
label: kb.name,
value: kb.id,
type: kb.type || 'document',
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0),
shared,
orgName,
ragEnabled: caps ? (caps.vector || caps.keyword) : (!strategy || strategy.vector_enabled || strategy.keyword_enabled),
wikiEnabled: caps ? caps.wiki : (strategy?.wiki_enabled || false),
capabilities: caps,
};
};
const applyPromptTemplateDefaults = (cfg: PromptTemplatesConfig | null) => {
if (!cfg) return;
if (cfg.agent_system_prompt && Array.isArray(cfg.agent_system_prompt)) {
agentSystemPromptTemplates.value = cfg.agent_system_prompt;
const ragDefault =
cfg.agent_system_prompt.find(t => t.mode === 'rag' && t.default) ||
cfg.agent_system_prompt.find(t => t.mode === 'rag');
if (ragDefault?.content) {
defaultAgentSystemPrompt.value = ragDefault.content;
}
}
const pickDefault = (arr?: PromptTemplate[]): PromptTemplate | undefined =>
Array.isArray(arr) ? arr.find(t => t.default) : undefined;
const sysPrompt = pickDefault(cfg.system_prompt);
if (sysPrompt?.content) defaultNormalSystemPrompt.value = sysPrompt.content;
const ctxTmpl = pickDefault(cfg.context_template);
if (ctxTmpl?.content) defaultContextTemplate.value = ctxTmpl.content;
const rewriteTmpl = pickDefault(cfg.rewrite);
if (rewriteTmpl?.content) defaultRewritePromptSystem.value = rewriteTmpl.content;
if (rewriteTmpl?.user) defaultRewritePromptUser.value = rewriteTmpl.user;
const fallbackList = Array.isArray(cfg.fallback) ? cfg.fallback : [];
const fixedFallback = fallbackList.find(t => t.default && t.mode !== 'model');
if (fixedFallback?.content) defaultFallbackResponse.value = fixedFallback.content;
const modelFallback = fallbackList.find(t => t.mode === 'model' && t.default) || fallbackList.find(t => t.mode === 'model');
if (modelFallback?.content) defaultFallbackPrompt.value = modelFallback.content;
if (Array.isArray(cfg.intent_prompts)) {
intentPromptTemplates.value = cfg.intent_prompts;
}
};
// 加载依赖数据(复用租户级缓存,避免重复请求)
const loadDependencies = async () => {
try {
// 加载所有模型列表(ModelSelector 组件会自动按类型过滤)
const models = await listModels();
if (models && models.length > 0) {
allModels.value = models;
}
// 加载知识库列表(我的 + 共享的)
const kbRes: any = await listKnowledgeBases();
const myKbs: typeof kbOptions.value = [];
if (kbRes.data) {
kbRes.data.forEach((kb: any) => {
const strategy = kb.indexing_strategy;
const caps: KBCapabilities | undefined = kb.capabilities;
myKbs.push({
label: kb.name,
value: kb.id,
type: kb.type || 'document',
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0),
shared: false,
ragEnabled: caps ? (caps.vector || caps.keyword) : (!strategy || strategy.vector_enabled || strategy.keyword_enabled),
wikiEnabled: caps ? caps.wiki : (strategy?.wiki_enabled || false),
capabilities: caps,
});
});
}
// 加载共享给我的知识库
const sharedKbs: typeof kbOptions.value = [];
try {
const sharedList = await orgStore.fetchSharedKnowledgeBases();
if (sharedList && sharedList.length > 0) {
const myKbIds = new Set(myKbs.map(kb => kb.value));
sharedList.forEach((shared: any) => {
const kb = shared.knowledge_base;
if (!kb || myKbIds.has(kb.id)) return;
const caps: KBCapabilities | undefined = kb.capabilities;
sharedKbs.push({
label: kb.name,
value: kb.id,
type: kb.type || 'document',
count: kb.type === 'faq' ? (kb.chunk_count || 0) : (kb.knowledge_count || 0),
shared: true,
orgName: shared.org_name,
ragEnabled: caps ? (caps.vector || caps.keyword) : (!kb.indexing_strategy || kb.indexing_strategy.vector_enabled || kb.indexing_strategy.keyword_enabled),
wikiEnabled: caps ? caps.wiki : (kb.indexing_strategy?.wiki_enabled || false),
capabilities: caps,
});
});
}
} catch (e) {
console.warn('Failed to load shared knowledge bases', e);
await Promise.all([
chatResources.ensureModels(),
chatResources.ensureKnowledgeBases(),
chatResources.ensureWebSearchProviders(),
editorResources.prefetchAgentEditorDeps(),
]);
if (chatResources.allModels.length > 0) {
allModels.value = chatResources.allModels;
}
const myKbs = chatResources.rawKnowledgeBases.map((kb: any) => mapKbToOption(kb, false));
const myKbIds = new Set(myKbs.map(kb => kb.value));
const sharedKbs = (orgStore.sharedKnowledgeBases || [])
.filter((shared: any) => shared.knowledge_base && !myKbIds.has(shared.knowledge_base.id))
.map((shared: any) => mapKbToOption(shared.knowledge_base, true, shared.org_name));
kbOptions.value = [...myKbs, ...sharedKbs];
// 加载 MCP 服务列表(只加载启用的)
try {
const mcpList = await listMCPServices();
if (mcpList && mcpList.length > 0) {
mcpOptions.value = mcpList
.filter((mcp: MCPService) => mcp.enabled)
.map((mcp: MCPService) => ({ label: mcp.name, value: mcp.id }));
}
} catch (e) {
console.warn('Failed to load MCP services', e);
}
mcpOptions.value = editorResources.mcpServices
.filter((mcp: MCPService) => mcp.enabled)
.map((mcp: MCPService) => ({ label: mcp.name, value: mcp.id }));
// 加载预装 Skills 列表及沙箱可用性(skills_available=false 时前端不展示 Skills 配置)
try {
const skillsRes = await listSkills();
skillsAvailable.value = skillsRes.skills_available !== false;
if (skillsRes.data && skillsRes.data.length > 0) {
skillOptions.value = skillsRes.data;
}
} catch (e) {
console.warn('Failed to load skills', e);
skillsAvailable.value = false;
}
skillsAvailable.value = editorResources.skillsAvailable;
skillOptions.value = editorResources.skills;
// 加载智能体类型预设(smart-reasoning 模式下的"类型"下拉)
try {
const presetsRes: any = await getAgentTypePresets();
if (presetsRes?.data && Array.isArray(presetsRes.data)) {
agentTypePresets.value = presetsRes.data as AgentTypePreset[];
}
} catch (e) {
console.warn('Failed to load agent type presets', e);
}
agentTypePresets.value = editorResources.agentTypePresets as AgentTypePreset[];
applyPromptTemplateDefaults(editorResources.promptTemplates);
// 加载 prompt-templates 用于:
// 1. agent_system_prompt 列表(applyAgentTypePreset 通过 system_prompt_id 回填正文)
// 2. 普通模式(builtin-quick-answer)创建时的默认 system_prompt / context_template /
// rewrite / fallback —— 取每个分类里 default: true 的那条
try {
const tmplRes = await getPromptTemplates();
const cfg = tmplRes?.data;
if (cfg?.agent_system_prompt && Array.isArray(cfg.agent_system_prompt)) {
agentSystemPromptTemplates.value = cfg.agent_system_prompt;
// Smart-reasoning (Progressive RAG) 默认提示词:取 mode='rag' &&
// default 的那条;找不到就退化到第一条 mode==='rag'。这块取代了
// 之前的 getAgentConfig() —— 后端实现就是从同一份模板里挑这条。
const ragDefault =
cfg.agent_system_prompt.find(t => t.mode === 'rag' && t.default) ||
cfg.agent_system_prompt.find(t => t.mode === 'rag');
if (ragDefault?.content) {
defaultAgentSystemPrompt.value = ragDefault.content;
}
}
const pickDefault = (arr?: PromptTemplate[]): PromptTemplate | undefined =>
Array.isArray(arr) ? arr.find(t => t.default) : undefined;
const sysPrompt = pickDefault(cfg?.system_prompt);
if (sysPrompt?.content) defaultNormalSystemPrompt.value = sysPrompt.content;
const ctxTmpl = pickDefault(cfg?.context_template);
if (ctxTmpl?.content) defaultContextTemplate.value = ctxTmpl.content;
const rewriteTmpl = pickDefault(cfg?.rewrite);
if (rewriteTmpl?.content) defaultRewritePromptSystem.value = rewriteTmpl.content;
if (rewriteTmpl?.user) defaultRewritePromptUser.value = rewriteTmpl.user;
// fallback templates split into fixed-response (default) and model-mode (mode === 'model').
const fallbackList = Array.isArray(cfg?.fallback) ? cfg.fallback : [];
const fixedFallback = fallbackList.find(t => t.default && t.mode !== 'model');
if (fixedFallback?.content) defaultFallbackResponse.value = fixedFallback.content;
const modelFallback = fallbackList.find(t => t.mode === 'model' && t.default) || fallbackList.find(t => t.mode === 'model');
if (modelFallback?.content) defaultFallbackPrompt.value = modelFallback.content;
if (Array.isArray(cfg?.intent_prompts)) {
intentPromptTemplates.value = cfg.intent_prompts;
}
} catch (e) {
console.warn('Failed to load prompt templates', e);
}
storageEngineStatus.value = editorResources.storageStatus;
// 加载存储引擎可用状态(用于图片存储 provider 选择)
try {
const statusRes = await getStorageEngineStatus();
if (statusRes?.data?.engines) {
storageEngineStatus.value = statusRes.data.engines;
}
} catch (e) {
console.warn('Failed to load storage engine status', e);
}
webSearchProviderList.value = chatResources.webSearchProviders as WebSearchProviderEntity[];
// 加载网络搜索引擎配置列表
try {
const wsRes: any = await listWebSearchProviders();
if (wsRes?.data && Array.isArray(wsRes.data)) {
webSearchProviderList.value = wsRes.data;
}
} catch (e) {
console.warn('Failed to load web search providers', e);
}
placeholderData.value = editorResources.placeholders as PlaceholderDefinition[];
// 加载占位符定义(从统一 API)
try {
const placeholdersRes = await getPlaceholders();
if (placeholdersRes?.data) {
placeholderData.value = placeholdersRes.data;
}
} catch (e) {
console.warn('Failed to load placeholders', e);
}
// 加载租户检索默认参数(embedding_top_k / 阈值 / rerank top_k 等)。
// temperature 与 max_completion_tokens 不在 RetrievalConfig 中,保持组件内
// 硬编码默认值(0.7 / 2048);用户在 agent 表单里可逐项调整。
try {
const retrievalRes: any = await getTenantRetrievalConfig();
const rc = retrievalRes?.data;
if (rc?.embedding_top_k) defaultEmbeddingTopK.value = rc.embedding_top_k;
if (rc?.keyword_threshold !== undefined) defaultKeywordThreshold.value = rc.keyword_threshold;
if (rc?.vector_threshold !== undefined) defaultVectorThreshold.value = rc.vector_threshold;
if (rc?.rerank_top_k) defaultRerankTopK.value = rc.rerank_top_k;
if (rc?.rerank_threshold !== undefined) defaultRerankThreshold.value = rc.rerank_threshold;
} catch (e) {
console.warn('Failed to load retrieval config', e);
}
const rc = editorResources.tenantRetrievalConfig as Record<string, number> | null;
if (rc?.embedding_top_k) defaultEmbeddingTopK.value = rc.embedding_top_k;
if (rc?.keyword_threshold !== undefined) defaultKeywordThreshold.value = rc.keyword_threshold;
if (rc?.vector_threshold !== undefined) defaultVectorThreshold.value = rc.vector_threshold;
if (rc?.rerank_top_k) defaultRerankTopK.value = rc.rerank_top_k;
if (rc?.rerank_threshold !== undefined) defaultRerankThreshold.value = rc.rerank_threshold;
} catch (e) {
console.error('Failed to load dependencies', e);
}
+23 -21
View File
@@ -819,7 +819,8 @@
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { listAgents, deleteAgent, copyAgent, type CustomAgent } from '@/api/agent'
import { deleteAgent, copyAgent, type CustomAgent } from '@/api/agent'
import { useChatResourcesStore } from '@/stores/chatResources'
import { formatStringDate } from '@/utils/index'
import { useI18n } from 'vue-i18n'
import { createSessions } from '@/api/chat/index'
@@ -847,6 +848,7 @@ const router = useRouter()
const authStore = useAuthStore()
const uiStore = useUIStore()
const orgStore = useOrganizationStore()
const chatResources = useChatResourcesStore()
const { loaded: modelsReadyLoaded, isReadyForAgent } = useTenantModelReadiness()
interface AgentWithUI extends CustomAgent {
@@ -1100,21 +1102,21 @@ const showAgentListContextualGuide = computed(
() => showAgentListEmpty.value && isReadyForAgent.value && !editorVisible.value,
)
const fetchList = () => {
const applyAgentListData = (res: { data: CustomAgent[]; disabled_own_agent_ids: string[] }) => {
const disabledOwnIds = res.disabled_own_agent_ids || []
agents.value = (res.data || []).map((agent: CustomAgent) => ({
...agent,
showMore: false,
disabled_by_me: disabledOwnIds.includes(agent.id)
}))
checkAndOpenEditModal()
}
const fetchList = (force = false) => {
loading.value = true
return Promise.all([
listAgents({ creator: creatorFilter.value }).then((res: any) => {
const data = res.data || []
const disabledOwnIds = res.disabled_own_agent_ids || []
agents.value = data.map((agent: CustomAgent) => ({
...agent,
showMore: false,
disabled_by_me: disabledOwnIds.includes(agent.id)
}))
checkAndOpenEditModal()
}),
orgStore.fetchSharedAgents(),
orgStore.fetchOrganizations()
chatResources.fetchAgentsForList({ creator: creatorFilter.value }, force).then(applyAgentListData),
orgStore.fetchOrganizations({ force }),
]).finally(() => { loading.value = false }).then(() => {
// 各空间智能体数量已由 GET /organizations 的 resource_counts 带回,存于 orgStore.resourceCounts
const counts = orgStore.resourceCounts?.agents?.by_organization
@@ -1184,7 +1186,7 @@ watch(spaceSelection, (val) => {
// predicate uniformly (also keeps built-in agents always present, see
// the matching block in custom_agent.go).
watch(creatorFilter, () => {
fetchList()
fetchList(true)
})
onMounted(() => {
@@ -1425,7 +1427,7 @@ const handleCopy = (agent: AgentWithUI) => {
copyAgent(agent.id).then((res: any) => {
if (res.data) {
MessagePlugin.success(t('agent.messages.copied'))
fetchList()
fetchList(true)
} else {
MessagePlugin.error(res.message || t('agent.messages.copyFailed'))
}
@@ -1441,7 +1443,7 @@ const handleToggleDisabled = (agent: AgentWithUI) => {
setSharedAgentDisabledByMe(agent.id, nextDisabled).then((res: any) => {
if (res.success) {
MessagePlugin.success(nextDisabled ? t('agent.messages.disabled') : t('agent.messages.enabled'))
fetchList()
fetchList(true)
} else {
MessagePlugin.error(res.message || t('agent.messages.saveFailed'))
}
@@ -1458,7 +1460,7 @@ const handleToggleSharedDisabled = (agent: DisplayAgent) => {
setSharedAgentDisabledByMe(agent.id, nextDisabled).then((res: any) => {
if (res.success) {
MessagePlugin.success(nextDisabled ? t('agent.messages.disabled') : t('agent.messages.enabled'))
orgStore.fetchSharedAgents()
orgStore.fetchSharedAgents({ force: true })
} else {
MessagePlugin.error(res.message || t('agent.messages.saveFailed'))
}
@@ -1474,7 +1476,7 @@ const handleToggleSharedDisabledFromShared = (shared: SharedAgentInfo) => {
setSharedAgentDisabledByMe(shared.agent.id, nextDisabled).then((res: any) => {
if (res.success) {
MessagePlugin.success(nextDisabled ? t('agent.messages.disabled') : t('agent.messages.enabled'))
orgStore.fetchSharedAgents()
orgStore.fetchSharedAgents({ force: true })
} else {
MessagePlugin.error(res.message || t('agent.messages.saveFailed'))
}
@@ -1491,7 +1493,7 @@ const confirmDelete = () => {
MessagePlugin.success(t('agent.messages.deleted'))
deleteVisible.value = false
deletingAgent.value = null
fetchList()
fetchList(true)
} else {
MessagePlugin.error(res.message || t('agent.messages.deleteFailed'))
}
@@ -1503,7 +1505,7 @@ const confirmDelete = () => {
const handleEditorSuccess = () => {
editorVisible.value = false
editingAgent.value = null
fetchList()
fetchList(true)
}
const formatDate = (dateStr: string) => {
+75 -20
View File
@@ -24,7 +24,7 @@
<div class="suggested-questions-title"><t-skeleton animation="gradient" :row-col="[{ width: '120px', height: '18px' }]" /></div>
<div class="suggested-questions-grid">
<div v-for="n in 6" :key="'sq-skel-'+n" class="suggested-question-card sq-card-skeleton">
<t-skeleton animation="gradient" :row-col="[{ width: '90%', height: '14px' }, { width: '60%', height: '14px' }]" />
<t-skeleton animation="gradient" :row-col="[{ width: '100%', height: '14px', type: 'rect' }]" />
</div>
</div>
</div>
@@ -106,7 +106,7 @@
</template>
<script setup>
import { storeToRefs } from 'pinia';
import { ref, onMounted, onUnmounted, nextTick, watch, reactive, markRaw, onBeforeUnmount, defineProps } from 'vue';
import { ref, onMounted, onBeforeMount, onUnmounted, nextTick, watch, reactive, markRaw, onBeforeUnmount, defineProps } from 'vue';
import { useRoute, useRouter, onBeforeRouteLeave, onBeforeRouteUpdate } from 'vue-router';
import InputField from '../../components/Input-field.vue';
import botmsg from './components/botmsg.vue';
@@ -249,7 +249,31 @@ const suggestedQuestionsLoading = ref(false);
let suggestedQuestionsFetchId = 0; // 用于取消过时的请求
let suggestedDebounceTimer = null;
const cancelSuggestedQuestionsFetch = () => {
suggestedQuestionsFetchId++;
suggestedQuestionsLoading.value = false;
suggestedQuestions.value = [];
if (suggestedDebounceTimer) {
clearTimeout(suggestedDebounceTimer);
suggestedDebounceTimer = null;
}
};
const fetchSuggestedQuestionsIfNeeded = async () => {
// 初始历史尚未拉完时不能判断是否有消息,避免有历史的会话误请求推荐问法
if (historyLoading.value || messagesList.length > 0) {
if (messagesList.length > 0) {
cancelSuggestedQuestionsFetch();
}
return;
}
await fetchSuggestedQuestions();
};
const fetchSuggestedQuestions = async () => {
if (historyLoading.value || messagesList.length > 0) {
return;
}
const fetchId = ++suggestedQuestionsFetchId;
suggestedQuestionsLoading.value = true;
// 加载期间保留旧数据,不清空,避免布局抖动
@@ -288,8 +312,9 @@ const handleSuggestedQuestionClick = (question) => {
// 防抖包装,切换知识库/文件时300ms内不重复请求
const debouncedFetchSuggestions = () => {
if (historyLoading.value || messagesList.length > 0) return;
if (suggestedDebounceTimer) clearTimeout(suggestedDebounceTimer);
suggestedDebounceTimer = setTimeout(() => { fetchSuggestedQuestions(); }, 300);
suggestedDebounceTimer = setTimeout(() => { fetchSuggestedQuestionsIfNeeded(); }, 300);
};
// 监听 Agent / 知识库 / 文件切换,重新获取推荐问题
@@ -337,7 +362,7 @@ const findLastMessage = (predicate) => {
}
return undefined;
};
watch([() => route.params], (newvalue) => {
watch([() => route.params], async (newvalue) => {
isFirstEnter.value = true;
if (newvalue[0].chatid) {
if (!firstQuery.value) {
@@ -361,7 +386,7 @@ watch([() => route.params], (newvalue) => {
useSettingsStoreInstance.restoreDefaultsIfSnapshotted();
checkmenuTitle(session_id.value)
loadSessionAndHydrate(session_id.value);
await loadSessionAndHydrate(session_id.value);
let data = {
session_id: session_id.value,
created_at: '',
@@ -414,7 +439,7 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {
if (historyLoadingMore.value || !hasMoreHistory.value) return;
historyLoadingMore.value = true;
}
getMessageList(data).then(res => {
getMessageList(data).then(async (res) => {
const batch = res?.data;
if (!batch?.length) {
if (isScrollType) {
@@ -422,6 +447,9 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {
}
return;
}
if (!isScrollType) {
cancelSuggestedQuestionsFetch();
}
const nextCursor = batch[0].created_at;
if (isScrollType && created_at.value && nextCursor === created_at.value) {
hasMoreHistory.value = false;
@@ -431,7 +459,7 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {
hasMoreHistory.value = false;
}
created_at.value = nextCursor;
handleMsgList(batch, isScrollType, scrollHeight);
await handleMsgList(batch, isScrollType, scrollHeight);
}).catch((err) => {
console.error('Failed to load messages:', err);
if (isScrollType) {
@@ -440,6 +468,9 @@ const getmsgList = (data, isScrollType = false, scrollHeight) => {
}).finally(() => {
historyLoading.value = false;
historyLoadingMore.value = false;
if (!isScrollType && messagesList.length === 0) {
fetchSuggestedQuestionsIfNeeded();
}
})
}
@@ -1481,13 +1512,11 @@ const handleSessionCleared = (e) => {
created_at.value = '';
hasMoreHistory.value = true;
historyLoadingMore.value = false;
fetchSuggestedQuestionsIfNeeded();
}
};
onMounted(async () => {
window.addEventListener('session-messages-cleared', handleSessionCleared);
messagesList.splice(0);
onBeforeMount(async () => {
// 若从智能体列表点击共享智能体进入,URL 带 agent_id 与 source_tenant_id,同步到 store
const agentIdFromQuery = props.embeddedAgentId || (route.query.agent_id && String(route.query.agent_id));
const sourceTenantIdFromQuery = route.query.source_tenant_id && String(route.query.source_tenant_id);
@@ -1496,17 +1525,22 @@ onMounted(async () => {
} else if (agentIdFromQuery) {
useSettingsStoreInstance.selectAgent(agentIdFromQuery, null);
}
if (props.embeddedKbIds && props.embeddedKbIds.length > 0) {
useSettingsStoreInstance.selectKnowledgeBases(props.embeddedKbIds);
}
// 必须在 Input-field onMounted 之前完成:按 session.last_request_state 恢复输入栏
await loadSessionAndHydrate(session_id.value);
});
onMounted(async () => {
window.addEventListener('session-messages-cleared', handleSessionCleared);
messagesList.splice(0);
// 初始化状态:加载历史消息时不应显示loading
loading.value = false;
isReplying.value = false;
// 拉会话详情;若服务端记录了 last_request_state,则按其恢复输入栏状态。
await loadSessionAndHydrate(session_id.value);
checkmenuTitle(session_id.value)
if (firstQuery.value) {
@@ -1532,9 +1566,6 @@ onMounted(async () => {
}
getmsgList(data)
}
// 初始加载推荐问题
fetchSuggestedQuestions();
})
const clearData = () => {
stopStream();
@@ -1857,7 +1888,31 @@ onBeforeRouteUpdate((to, from, next) => {
transition: all 0.2s ease;
max-width: 100%;
&:hover {
&.sq-card-skeleton {
pointer-events: none;
flex-shrink: 0;
border-color: transparent;
background: var(--td-bg-color-secondarycontainer);
:deep(.t-skeleton) {
width: 100%;
}
:deep(.t-skeleton__row) {
margin: 0;
}
:deep(.t-skeleton__col) {
border-radius: 4px;
}
&:nth-child(1) { width: 132px; }
&:nth-child(2) { width: 168px; }
&:nth-child(3) { width: 116px; }
&:nth-child(4) { width: 152px; }
&:nth-child(5) { width: 124px; }
&:nth-child(6) { width: 144px; }
}
&:not(.sq-card-skeleton):hover {
border-color: var(--td-brand-color);
background: var(--td-brand-color-light);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
+23 -2
View File
@@ -11,7 +11,7 @@
<div class="suggested-questions-title"><t-skeleton animation="gradient" :row-col="[{ width: '120px', height: '18px' }]" /></div>
<div class="suggested-questions-grid">
<div v-for="n in 6" :key="'sq-skel-'+n" class="suggested-question-card sq-card-skeleton">
<t-skeleton animation="gradient" :row-col="[{ width: '90%', height: '14px' }, { width: '60%', height: '14px' }]" />
<t-skeleton animation="gradient" :row-col="[{ width: '100%', height: '14px', type: 'rect' }]" />
</div>
</div>
</div>
@@ -367,6 +367,27 @@ const handleKBEditorSuccess = (kbId: string) => {
opacity: 1;
transform: none;
cursor: default;
pointer-events: none;
flex-shrink: 0;
border-color: transparent;
background: var(--td-bg-color-secondarycontainer);
:deep(.t-skeleton) {
width: 100%;
}
:deep(.t-skeleton__row) {
margin: 0;
}
:deep(.t-skeleton__col) {
border-radius: 4px;
}
&:nth-child(1) { width: 132px; }
&:nth-child(2) { width: 168px; }
&:nth-child(3) { width: 116px; }
&:nth-child(4) { width: 152px; }
&:nth-child(5) { width: 124px; }
&:nth-child(6) { width: 144px; }
}
&.sq-card-visible {
@@ -374,7 +395,7 @@ const handleKBEditorSuccess = (kbId: string) => {
transform: translateY(0) scale(1);
}
&:hover {
&:not(.sq-card-skeleton):hover {
border-color: var(--td-brand-color);
background: var(--td-brand-color-light);
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
+27 -20
View File
@@ -14,15 +14,18 @@ import { useMenuStore } from '@/stores/menu';
import { useUIStore } from '@/stores/ui';
import { useOrganizationStore } from '@/stores/organization';
import { useAuthStore } from '@/stores/auth';
import { useChatResourcesStore } from '@/stores/chatResources';
import { useEditorResourcesStore } from '@/stores/editorResources';
import KnowledgeBaseEditorModal from './KnowledgeBaseEditorModal.vue';
const usemenuStore = useMenuStore();
const uiStore = useUIStore();
const orgStore = useOrganizationStore();
const authStore = useAuthStore();
const chatResources = useChatResourcesStore();
const editorResources = useEditorResourcesStore();
const router = useRouter();
import {
batchQueryKnowledge,
getKnowledgeBaseById,
listKnowledgeTags,
updateKnowledgeTagBatch,
createKnowledgeBaseTag,
@@ -30,7 +33,6 @@ import {
deleteKnowledgeBaseTag,
uploadKnowledgeFile,
createKnowledgeFromURL,
listKnowledgeBases,
reparseKnowledge,
cancelKnowledgeParse,
batchDeleteKnowledge,
@@ -51,7 +53,7 @@ import { listMoveTargets, moveKnowledge, getKnowledgeMoveProgress } from '@/api/
import { useI18n } from 'vue-i18n';
import { formatStringDate, kbFileTypeVerification } from '@/utils';
import { formatFileSize } from '@/utils/files';
import { getParserEngines, type ParserEngineInfo } from '@/api/system';
import type { ParserEngineInfo } from '@/api/system';
const route = useRoute();
const { t } = useI18n();
const kbId = computed(() => (route.params as any).kbId as string || '');
@@ -153,7 +155,7 @@ const missingStorageEngine = computed(() => {
const spc = kbInfo.value.storage_provider_config
return !spc || !spc.provider
})
const parserEngines = ref<ParserEngineInfo[]>([]);
const parserEngines = computed<ParserEngineInfo[]>(() => editorResources.parserEngines);
const supportedFileTypes = computed<Set<string>>(() => {
const engines = parserEngines.value
@@ -811,7 +813,7 @@ const handleKnowledgeTagChange = async (knowledgeId: string, tagValue: string) =
}
};
const loadKnowledgeBaseInfo = async (targetKbId: string) => {
const loadKnowledgeBaseInfo = async (targetKbId: string, force = false) => {
if (!targetKbId) {
kbInfo.value = null;
cardList.value = [];
@@ -820,10 +822,10 @@ const loadKnowledgeBaseInfo = async (targetKbId: string) => {
}
kbLoading.value = true;
try {
const res: any = await getKnowledgeBaseById(targetKbId);
const data = await chatResources.fetchKnowledgeBaseById(targetKbId, force);
if (!isCurrentKb(targetKbId)) return;
kbInfo.value = res?.data || null;
kbInfo.value = data;
selectedTagId.value = '';
// 重置store中的标签选择状态,避免上传文档时自动带上之前选择的标签
uiStore.setSelectedTagId('');
@@ -851,8 +853,8 @@ const loadKnowledgeBaseInfo = async (targetKbId: string) => {
const loadKnowledgeList = async () => {
try {
const res: any = await listKnowledgeBases();
const myKbs = (res?.data || []).map((item: any) => ({
await chatResources.ensureKnowledgeBases();
const myKbs = chatResources.rawKnowledgeBases.map((item: any) => ({
id: String(item.id),
name: item.name,
type: item.type || 'document',
@@ -890,7 +892,15 @@ watch(activeKbTab, (tab) => {
})
watch(() => kbId.value, (newKbId, oldKbId) => {
if (newKbId && newKbId !== oldKbId) {
if (!newKbId) {
kbInfo.value = null;
cardList.value = [];
total.value = 0;
return;
}
if (newKbId === oldKbId && kbInfo.value) return;
if (newKbId !== oldKbId) {
clearTraceAvailabilityCache();
cardList.value = [];
total.value = 0;
@@ -898,11 +908,10 @@ watch(() => kbId.value, (newKbId, oldKbId) => {
resetPage();
tagSearchQuery.value = '';
tagPage.value = 1;
// 重置标签选择状态,避免在不同知识库间保持标签选择
uiStore.setSelectedTagId('');
loadKnowledgeBaseInfo(newKbId);
}
}, { immediate: false });
loadKnowledgeBaseInfo(newKbId);
}, { immediate: true });
watch(selectedTagId, (newVal, oldVal) => {
if (oldVal === undefined) return
@@ -1027,13 +1036,8 @@ const handleOpenKnowledgeEvent = (e: Event) => {
};
onMounted(() => {
loadKnowledgeBaseInfo(kbId.value);
loadKnowledgeList();
orgStore.fetchSharedKnowledgeBases();
getParserEngines()
.then(res => { parserEngines.value = res?.data || [] })
.catch(() => { parserEngines.value = [] })
editorResources.ensureParserEngines();
window.addEventListener('knowledgeFileUploaded', handleFileUploaded as EventListener);
window.addEventListener('openURLImportDialog', handleOpenURLImportDialog as EventListener);
@@ -2022,8 +2026,11 @@ watch(cardList, () => {
// 处理知识库编辑成功后的回调
const handleKBEditorSuccess = (kbIdValue: string) => {
chatResources.invalidateKnowledgeBaseDetail(kbIdValue);
chatResources.invalidate('knowledgeBases');
loadKnowledgeList();
if (kbIdValue === kbId.value) {
loadKnowledgeBaseInfo(kbIdValue);
loadKnowledgeBaseInfo(kbIdValue, true);
}
};
@@ -219,7 +219,7 @@
</div>
<!-- 解析引擎 -->
<div v-if="!isFAQ && formData" v-show="currentSection === 'parser'" class="section">
<div v-if="!isFAQ && formData && currentSection === 'parser'" class="section">
<KBParserSettings
:parser-engine-rules="formData.chunkingConfig.parserEngineRules"
@update:parser-engine-rules="handleParserEngineRulesUpdate"
@@ -227,7 +227,7 @@
</div>
<!-- 存储引擎 -->
<div v-if="!isFAQ && formData" v-show="currentSection === 'storage'" class="section">
<div v-if="!isFAQ && formData && currentSection === 'storage'" class="section">
<KBStorageSettings
:storage-provider="formData.storageProvider"
:has-files="mode === 'edit' && hasFiles"
@@ -335,7 +335,7 @@
</div>
<!-- 知识图谱 -->
<div v-if="!isFAQ" v-show="currentSection === 'graph'" class="section">
<div v-if="!isFAQ && currentSection === 'graph'" class="section">
<GraphSettings
v-if="formData"
:graph-extract="formData.nodeExtractConfig"
@@ -358,12 +358,12 @@
</div>
<!-- 数据源管理(仅编辑模式) -->
<div v-if="mode === 'edit' && kbId" v-show="currentSection === 'datasource'" class="section">
<div v-if="mode === 'edit' && kbId && currentSection === 'datasource'" class="section">
<DataSourceSettings :kb-id="kbId" @count="dsCount = $event" />
</div>
<!-- 共享设置(仅编辑模式) -->
<div v-if="mode === 'edit' && kbId" v-show="currentSection === 'share'" class="section">
<div v-if="mode === 'edit' && kbId && currentSection === 'share'" class="section">
<KBShareSettings :kb-id="kbId" :can-share="canShareKB" />
</div>
</div>
@@ -395,8 +395,9 @@ import { KB_EDITOR_FOCUS_SECTION_EVENT, markContextualGuideDone } from '@/config
import { MessagePlugin, DialogPlugin } from 'tdesign-vue-next'
import { createKnowledgeBase, getKnowledgeBaseById, listKnowledgeFiles, updateKnowledgeBase, rebuildKBIndex } from '@/api/knowledge-base'
import { updateKBConfig, type KBModelConfigRequest } from '@/api/initialization'
import { listModels, type ModelConfig } from '@/api/model'
import { getStorageEngineConfig } from '@/api/system'
import { type ModelConfig } from '@/api/model'
import { useChatResourcesStore } from '@/stores/chatResources'
import { useEditorResourcesStore } from '@/stores/editorResources'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import KBModelConfig from './settings/KBModelConfig.vue'
@@ -413,6 +414,8 @@ import { useI18n } from 'vue-i18n'
const uiStore = useUIStore()
const authStore = useAuthStore()
const chatResources = useChatResourcesStore()
const editorResources = useEditorResourcesStore()
const { t } = useI18n()
// Props
@@ -676,10 +679,10 @@ const initFormData = (type: 'document' | 'faq' = 'document') => {
}
// 加载所有模型
const loadAllModels = async () => {
const loadAllModels = async (force = false) => {
try {
const models = await listModels()
allModels.value = models || []
await chatResources.ensureModels(force)
allModels.value = chatResources.allModels || []
} catch (error) {
console.error('Failed to load model list:', error)
MessagePlugin.error(t('knowledgeEditor.messages.loadModelsFailed'))
@@ -693,9 +696,8 @@ const loadKBData = async () => {
loading.value = true
try {
const [kbInfo, models, filesResult] = await Promise.all([
const [kbInfo, filesResult] = await Promise.all([
getKnowledgeBaseById(props.kbId),
loadAllModels(),
listKnowledgeFiles(props.kbId, { page: 1, page_size: 1 })
])
@@ -923,10 +925,10 @@ const handleStorageProviderUpdate = (value: string) => {
}
}
async function loadTenantDefaultStorageProvider() {
async function loadTenantDefaultStorageProvider(force = false) {
try {
const res = await getStorageEngineConfig()
tenantDefaultStorageProvider.value = res?.data?.default_provider || 'local'
await editorResources.ensureStorageEngine(force)
tenantDefaultStorageProvider.value = editorResources.storageConfig?.default_provider || 'local'
} catch {
tenantDefaultStorageProvider.value = 'local'
}
@@ -1379,7 +1381,7 @@ watch(
() => uiStore.showSettingsModal,
async (visible, previous) => {
if (!visible && previous && props.visible) {
await loadAllModels()
await loadAllModels(true)
}
}
)
@@ -772,7 +772,8 @@
import { onMounted, onUnmounted, ref, computed, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { MessagePlugin, Icon as TIcon } from 'tdesign-vue-next'
import { listKnowledgeBases, deleteKnowledgeBase, togglePinKnowledgeBase } from '@/api/knowledge-base'
import { deleteKnowledgeBase, togglePinKnowledgeBase } from '@/api/knowledge-base'
import { useChatResourcesStore } from '@/stores/chatResources'
import { formatStringDate } from '@/utils/index'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
@@ -797,6 +798,7 @@ const uiStore = useUIStore()
const authStore = useAuthStore()
const { loaded: modelsReadyLoaded, isReadyForDocumentKb } = useTenantModelReadiness()
const orgStore = useOrganizationStore()
const chatResources = useChatResourcesStore()
const { t } = useI18n()
// 左侧空间选择:默认根据当前角色决定。
@@ -1202,27 +1204,26 @@ interface UploadSummary {
hasError: boolean
}
const fetchList = () => {
const applyKbListData = (data: any[]) => {
kbs.value = data.map((kb: any) => ({
...kb,
updated_at: kb.updated_at ? formatStringDate(new Date(kb.updated_at)) : '',
showMore: false,
isProcessing: kb.is_processing || false,
processing_count: kb.processing_count || 0
}))
}
const fetchList = (force = false) => {
loading.value = true
// The creator filter only applies to the caller's own tenant KBs (the
// first call). Shared KBs are inherently "not mine" so we don't filter
// them server-side; the segmented control is also hidden whenever the
// user is browsing the shared / per-space scopes.
return Promise.all([
listKnowledgeBases({ creator: creatorFilter.value }).then((res: any) => {
const data = res.data || []
// 格式化时间,并初始化 showMore 状态
// is_processing 字段由后端返回
kbs.value = data.map((kb: any) => ({
...kb,
updated_at: kb.updated_at ? formatStringDate(new Date(kb.updated_at)) : '',
showMore: false,
isProcessing: kb.is_processing || false,
processing_count: kb.processing_count || 0
}))
}),
orgStore.fetchSharedKnowledgeBases(),
orgStore.fetchOrganizations()
chatResources.fetchKnowledgeBasesForList({ creator: creatorFilter.value }, force).then(applyKbListData),
orgStore.fetchSharedKnowledgeBases({ force }),
orgStore.fetchOrganizations({ force }),
]).finally(() => { loading.value = false }).then(() => {
// 各空间知识库数量已由 GET /organizations 的 resource_counts 带回,存于 orgStore.resourceCounts
const counts = orgStore.resourceCounts?.knowledge_bases?.by_organization
@@ -1261,7 +1262,7 @@ watch(spaceSelection, (val) => {
// than filtering in-memory so the server stays the single source of truth
// (and we don't need to worry about stale share_count or pagination later).
watch(creatorFilter, () => {
fetchList()
fetchList(true)
})
onMounted(() => {
@@ -1388,7 +1389,7 @@ const handleTogglePin = async (kb: KB) => {
MessagePlugin.success(
res.data.is_pinned ? t('knowledgeList.pin.pinSuccess') : t('knowledgeList.pin.unpinSuccess')
)
fetchList()
fetchList(true)
}
} catch {
MessagePlugin.error(t('knowledgeList.pin.failed'))
@@ -1402,7 +1403,7 @@ const handleTogglePinById = async (id: string) => {
MessagePlugin.success(
res.data.is_pinned ? t('knowledgeList.pin.pinSuccess') : t('knowledgeList.pin.unpinSuccess')
)
fetchList()
fetchList(true)
}
} catch {
MessagePlugin.error(t('knowledgeList.pin.failed'))
@@ -1419,7 +1420,7 @@ const handleShare = (kb: KB) => {
const handleShareSuccess = () => {
// 共享成功后可刷新列表
fetchList()
fetchList(true)
}
const handleSharedKbClick = (sharedKb: SharedKnowledgeBase) => {
@@ -1489,7 +1490,7 @@ const confirmDelete = () => {
MessagePlugin.success(t('knowledgeList.messages.deleted'))
deleteVisible.value = false
deletingKb.value = null
fetchList()
fetchList(true)
} else {
MessagePlugin.error(res.message || t('knowledgeList.messages.deleteFailed'))
}
@@ -1652,7 +1653,7 @@ const handleCreateKnowledgeBase = () => {
const handleKBEditorSuccess = (kbId: string) => {
console.log('[KnowledgeBaseList] knowledge operation success:', kbId)
const shouldOpenDetailForUploadGuide = !isContextualGuideDone('kbDetail')
fetchList().then(() => {
fetchList(true).then(() => {
if (shouldOpenDetailForUploadGuide && kbId) {
goDetail(kbId)
}
@@ -1726,7 +1727,7 @@ const handleUploadFinishedEvent = (event: Event) => {
clearTimeout(uploadRefreshTimer)
}
uploadRefreshTimer = setTimeout(() => {
fetchList()
fetchList(true)
uploadRefreshTimer = null
}, 800)
}
@@ -300,7 +300,7 @@ import { ref, watch, onMounted, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { extractTextRelations, fabriText, fabriTag, type Node, type Relation } from '@/api/initialization'
import { getSystemInfo } from '@/api/system'
import { useEditorResourcesStore } from '@/stores/editorResources'
import { useAuthStore } from '@/stores/auth'
const { t } = useI18n()
@@ -544,11 +544,13 @@ const clearExtractExample = () => {
MessagePlugin.success(t('graphSettings.exampleCleared'))
}
const editorResources = useEditorResourcesStore()
// 加载系统信息
const loadSystemInfo = async () => {
const loadSystemInfo = async (force = false) => {
try {
const response = await getSystemInfo()
systemInfo.value = response.data
await editorResources.ensureSystemInfo(force)
systemInfo.value = editorResources.systemInfo
} catch (error: any) {
console.error('Failed to load system info:', error)
}
@@ -86,11 +86,13 @@
<script setup lang="ts">
import { ref, watch, computed, onMounted, onUnmounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { getParserEngines, type ParserEngineInfo } from '@/api/system'
import { type ParserEngineInfo } from '@/api/system'
import { useEditorResourcesStore } from '@/stores/editorResources'
import { useUIStore } from '@/stores/ui'
import { storeToRefs } from 'pinia'
const { t } = useI18n()
const editorResources = useEditorResourcesStore()
function getEngineDisplayName(engineName: string): string {
const key = `kbSettings.parser.engines.${engineName}.name`
@@ -253,13 +255,11 @@ function goToParserSettings() {
uiStore.openSettings('parser')
}
async function loadEngines() {
async function loadEngines(force = false) {
loading.value = true
try {
const resp = await getParserEngines()
if (resp?.data && Array.isArray(resp.data)) {
parserEngines.value = resp.data
}
await editorResources.ensureParserEngines(force)
parserEngines.value = editorResources.parserEngines as ParserEngineInfo[]
} catch {
parserEngines.value = []
} finally {
@@ -282,7 +282,7 @@ onMounted(loadEngines)
const { showSettingsModal } = storeToRefs(uiStore)
watch(showSettingsModal, (open, wasOpen) => {
if (wasOpen && !open) {
loadEngines()
loadEngines(true)
}
})
@@ -163,7 +163,7 @@
</template>
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { ref, computed, watch } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { useOrganizationStore } from '@/stores/organization'
@@ -304,12 +304,6 @@ watch(() => props.kbId, async (newKbId) => {
await Promise.all([loadOrganizations(), loadShares()])
}
}, { immediate: true })
onMounted(async () => {
if (props.kbId) {
await Promise.all([loadOrganizations(), loadShares()])
}
})
</script>
<style scoped lang="less">
@@ -53,8 +53,9 @@
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
import { useI18n } from 'vue-i18n'
import { getStorageEngineConfig, getStorageEngineStatus, type StorageEngineStatusItem } from '@/api/system'
import { type StorageEngineStatusItem } from '@/api/system'
import { useUIStore } from '@/stores/ui'
import { useEditorResourcesStore } from '@/stores/editorResources'
const { t } = useI18n()
@@ -68,6 +69,7 @@ const emit = defineEmits<{
}>()
const uiStore = useUIStore()
const editorResources = useEditorResourcesStore()
// Keep empty until tenant default_provider is loaded — do not pre-fill 'local'.
const localProvider = ref(props.storageProvider)
const loading = ref(true)
@@ -176,18 +178,15 @@ function goToStorageSettings() {
uiStore.openSettings?.('storage')
}
async function load() {
async function load(force = false) {
loading.value = true
try {
const [configRes, statusRes] = await Promise.all([
getStorageEngineConfig(),
getStorageEngineStatus(),
])
const engines = statusRes?.data?.engines ?? []
await editorResources.ensureStorageEngine(force)
const engines = editorResources.storageStatus
engineStatus.value = engines
allowedProviders.value = statusRes?.data?.allowed_providers ?? []
defaultProvider.value = configRes?.data?.default_provider || 'local'
const d = configRes?.data
allowedProviders.value = editorResources.storageAllowedProviders
defaultProvider.value = editorResources.storageConfig?.default_provider || 'local'
const d = editorResources.storageConfig
hasAnyConfig.value = !!(d?.local?.path_prefix || d?.minio?.bucket_name || d?.cos?.bucket_name || d?.tos?.bucket_name || d?.s3?.bucket_name || d?.oss?.bucket_name || d?.ks3?.bucket_name || d?.obs?.bucket_name)
const parentUnset = !props.storageProvider
if (parentUnset) {
+3
View File
@@ -30,6 +30,7 @@ import GlobalCommandPalette from '@/components/GlobalCommandPalette.vue'
import GlobalInvitationBell from '@/components/GlobalInvitationBell.vue'
import NewUserGuide from '@/components/NewUserGuide.vue'
import { useCommandPaletteStore } from '@/stores/commandPalette'
import { useChatResourcesStore } from '@/stores/chatResources'
import { getKnowledgeBaseById } from '@/api/knowledge-base/index'
import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
@@ -202,6 +203,8 @@ onMounted(() => {
// 支持通过 URL 查询参数打开全局命令面板,例如旧路径
// /platform/knowledge-search?q=foo 重定向后携带 ?cmdk=foo
maybeOpenCmdkFromRoute()
// 后台预取对话输入栏资源,进入 creatChat / chat 时复用缓存
void useChatResourcesStore().prefetchChatInput()
});
// 监听路由变化,兼容 SPA 内部跳转时的 ?cmdk= 参数