refactor(frontend): enhance chat resources store for knowledge bases and agents

- Introduced caching mechanisms for knowledge bases and agents to prevent redundant API calls during concurrent requests.
- Updated logic to handle creator-specific filtering for knowledge bases and agents, ensuring that non-'all' requests bypass caching.
- Improved session state handling in the settings store to ensure proper state restoration without overwriting user selections.
- Utilized `nextTick` to manage asynchronous state updates effectively, enhancing the reliability of the application state management.
This commit is contained in:
wizardchen
2026-06-09 12:24:26 +08:00
committed by lyingbug
parent 815c72c964
commit e78a9482d4
2 changed files with 71 additions and 31 deletions
+63 -30
View File
@@ -30,6 +30,10 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
const loadedAt = ref<Partial<Record<ResourceKey, number>>>({}) const loadedAt = ref<Partial<Record<ResourceKey, number>>>({})
const inflight = new Map<ResourceKey, Promise<void>>() const inflight = new Map<ResourceKey, Promise<void>>()
// creator==='all' 的列表请求单独去重:首屏 platform 预取与对话页 onMounted
// 可能并发触发,缓存尚未写入时不去重会重复打 listKnowledgeBases / listAgents。
let kbAllInflight: Promise<any[]> | null = null
let agentsAllInflight: Promise<{ data: CustomAgent[]; disabled_own_agent_ids: string[] }> | null = null
const agentKbCache = new Map<string, { at: number; data: any[] }>() const agentKbCache = new Map<string, { at: number; data: any[] }>()
const agentKbInflight = new Map<string, Promise<any[]>>() const agentKbInflight = new Map<string, Promise<any[]>>()
@@ -63,23 +67,31 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
force = false, force = false,
): Promise<any[]> { ): Promise<any[]> {
const creator = params?.creator ?? 'all' const creator = params?.creator ?? 'all'
if (!force && creator === 'all' && isFresh('knowledgeBases')) { // 带 creator 过滤的列表是列表页专用、不进缓存,直接透传请求。
if (creator !== 'all') {
const res: any = await listKnowledgeBases({ creator })
return res?.data && Array.isArray(res.data) ? res.data : []
}
if (!force && isFresh('knowledgeBases')) {
return rawKnowledgeBases.value return rawKnowledgeBases.value
} }
if (!force && kbAllInflight) return kbAllInflight
const res: any = await listKnowledgeBases( kbAllInflight = (async () => {
creator === 'all' ? undefined : { creator }, try {
) const res: any = await listKnowledgeBases()
const data = res?.data && Array.isArray(res.data) ? res.data : [] const data = res?.data && Array.isArray(res.data) ? res.data : []
rawKnowledgeBases.value = data
if (creator === 'all') { loadedAt.value.knowledgeBases = Date.now()
rawKnowledgeBases.value = data const orgStore = useOrganizationStore()
loadedAt.value.knowledgeBases = Date.now() await orgStore.fetchSharedKnowledgeBases({ force })
const orgStore = useOrganizationStore() return data
await orgStore.fetchSharedKnowledgeBases({ force }) } finally {
} kbAllInflight = null
}
return data })()
return kbAllInflight
} }
async function ensureKnowledgeBases(force = false): Promise<void> { async function ensureKnowledgeBases(force = false): Promise<void> {
@@ -94,25 +106,40 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
force = false, force = false,
): Promise<{ data: CustomAgent[]; disabled_own_agent_ids: string[] }> { ): Promise<{ data: CustomAgent[]; disabled_own_agent_ids: string[] }> {
const creator = params?.creator ?? 'all' const creator = params?.creator ?? 'all'
if (!force && creator === 'all' && isFresh('agents')) { const orgStore = useOrganizationStore()
// 带 creator 过滤的列表不进缓存,但仍需刷新共享智能体(与全量路径保持一致)。
if (creator !== 'all') {
const [agentsRes] = await Promise.all([
listAgents({ creator }),
orgStore.fetchSharedAgents({ force }),
])
const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
return { data: res.data || [], disabled_own_agent_ids: res.disabled_own_agent_ids || [] }
}
if (!force && isFresh('agents')) {
return { data: agents.value, disabled_own_agent_ids: disabledOwnAgentIds.value } return { data: agents.value, disabled_own_agent_ids: disabledOwnAgentIds.value }
} }
if (!force && agentsAllInflight) return agentsAllInflight
const orgStore = useOrganizationStore() agentsAllInflight = (async () => {
const [agentsRes] = await Promise.all([ try {
listAgents(creator === 'all' ? undefined : { creator }), const [agentsRes] = await Promise.all([
orgStore.fetchSharedAgents({ force }), listAgents(),
]) orgStore.fetchSharedAgents({ force }),
const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] } ])
const data = res.data || [] const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
const data = res.data || []
if (creator === 'all') { agents.value = data
agents.value = data disabledOwnAgentIds.value = res.disabled_own_agent_ids || []
disabledOwnAgentIds.value = res.disabled_own_agent_ids || [] loadedAt.value.agents = Date.now()
loadedAt.value.agents = Date.now() return { data, disabled_own_agent_ids: res.disabled_own_agent_ids || [] }
} } finally {
agentsAllInflight = null
return { data, disabled_own_agent_ids: res.disabled_own_agent_ids || [] } }
})()
return agentsAllInflight
} }
async function ensureAgents(force = false): Promise<void> { async function ensureAgents(force = false): Promise<void> {
@@ -222,6 +249,8 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
allModels.value = [] allModels.value = []
webSearchProviders.value = [] webSearchProviders.value = []
agentKbCache.clear() agentKbCache.clear()
kbAllInflight = null
agentsAllInflight = null
invalidateKnowledgeBaseDetail() invalidateKnowledgeBaseDetail()
return return
} }
@@ -230,8 +259,12 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
}) })
if (keys.includes('knowledgeBases')) { if (keys.includes('knowledgeBases')) {
agentKbCache.clear() agentKbCache.clear()
kbAllInflight = null
invalidateKnowledgeBaseDetail() invalidateKnowledgeBaseDetail()
} }
if (keys.includes('agents')) {
agentsAllInflight = null
}
} }
return { return {
+8 -1
View File
@@ -1,4 +1,5 @@
import { defineStore } from "pinia"; import { defineStore } from "pinia";
import { nextTick } from "vue";
import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent"; import { BUILTIN_QUICK_ANSWER_ID, BUILTIN_SMART_REASONING_ID } from "@/api/agent";
import { getApiBaseUrl } from "@/utils/api-base"; import { getApiBaseUrl } from "@/utils/api-base";
import { updateMyPreferences, type UserPreferences } from "@/api/auth"; import { updateMyPreferences, type UserPreferences } from "@/api/auth";
@@ -479,7 +480,13 @@ export const useSettingsStore = defineStore("settings", {
this.settings.webSearchEnabled = state.web_search_enabled; this.settings.webSearchEnabled = state.web_search_enabled;
} }
} finally { } finally {
this._isApplyingSessionState = false; // 复位必须延后到下一次 flush 之后:监听 selectedAgentId 的 watcher 默认
// flush:'pre',是异步执行的;若在此处同步复位,watcher 真正运行时标志早已
// 为 false,守卫形同虚设、恢复出来的 KB 仍会被 agent 配置覆盖。放到 nextTick
// 可保证本次状态变更触发的 watcher 在标志仍为 true 时执行。
nextTick(() => {
this._isApplyingSessionState = false;
});
} }
// 注意:故意不写 localStorage —— 旧会话的状态不应污染"用户默认"。 // 注意:故意不写 localStorage —— 旧会话的状态不应污染"用户默认"。
// 离开会话时 restoreDefaultsIfSnapshotted 会把 localStorage 里那份完整 // 离开会话时 restoreDefaultsIfSnapshotted 会把 localStorage 里那份完整