From 745a22d066cab0dc555372a7510c017c5ddb9c6a Mon Sep 17 00:00:00 2001 From: lyingbug Date: Fri, 25 Sep 2026 22:22:48 +0800 Subject: [PATCH] refactor(frontend): drop TTL resource caches and remove duplicate startup requests (#3562) * refactor(frontend): drop TTL resource caches and remove duplicate startup requests Space-level resource stores (chatResources / editorResources / organization) cached lists for 60s. Pages that own the data bypassed the cache with force, while side consumers (chat input bar, selectors) read stale values and relied on a web of indirect refresh signals. Replace the TTL with in-flight deduplication plus explicit invalidation: - add stores/resourceCache.ts: createCachedResource (one request in flight per resource, force queues behind it, invalidate/markLoaded discard stale responses) and createKeyedSnapshotCache for per-id details - rebuild chatResources / editorResources on those primitives; organization store drops its loadedAt timestamps and uses the request coordinator only - isFresh -> isLoaded (only "has a snapshot" is meaningful now) Fix concrete duplicates found on the way: - /auth/me was fetched twice on every cold load (main.ts + UserMenu); auth store now dedupes in-flight calls and exposes ensureAuthMe, router hydrate reuses refreshFromAuthMe instead of a second copy of the persist logic - /system/info was fetched by menu.vue directly next to editorResources - /platform/settings rendered Settings.vue as the route component while the platform layout already mounts it, so two modals were visible and every settings panel request ran twice; the route now renders an empty view - components that called listKnowledgeBases / listAgents / getParserEngines / getPromptTemplates directly now go through the stores - Input-field no longer force-refreshes models and web-search providers on "settings closed" / "left settings route"; WebSearchSettings writes back to the shared snapshot and useTenantModelReadiness derives from the store Measured with a mock backend: cold load 19 -> 18 requests (/auth/me once), settings model panel 3 -> 2 (one modal), route changes now refetch lists (creatChat 3 -> 9, back to KB list 0 -> 4) instead of serving 60s-old data. * fix(frontend): fence stale responses in the resource caches and /auth/me refresh Review follow-ups on the TTL removal: - createKeyedSnapshotCache tracks a per-key revision; invalidate() and a force read both advance it, so a response that lands after invalidation or behind a newer request is handed to its caller but never written back into the snapshot. Previously a KB detail read still in flight during save could re-pin the pre-save detail until the next explicit invalidate. - ensureKnowledgeBases / ensureAgents no longer reject when the shared resource fetch fails; the own list is already applied and the previous shared snapshot is kept. Callers migrated onto the store (manual editor, KB selector, FAQ manager, API integration page) had independent failure handling before. McpServerIntegrationSettings shows empty lists on failure instead of the last snapshot. - /auth/me refresh is sequenced via a new createSequencedRefresh helper: refreshFromAuthMe() always resolves on a request issued after the call (queued behind an in-flight one), ensureAuthMe() shares in-flight, and logout() invalidates so a late response cannot re-apply the old session. Tests: keyed cache invalidate-during-flight and force-overlap; sequencer refresh ordering, invalidate after logout, and recovery after a failed in-flight request. * fix(frontend): refetch models after publishing a catalog change invalidate() no longer triggers a refetch and the chat input stopped reloading models when settings close, so the reasoning-level selector kept stale capabilities after a catalog publish. Force-refresh the snapshot. --- .../src/components/AgentEmbedChannelPanel.vue | 10 +- frontend/src/components/AttachmentUpload.vue | 7 +- frontend/src/components/IMChannelPanel.vue | 8 +- .../src/components/Input-field.focus.test.mjs | 2 +- frontend/src/components/Input-field.vue | 24 +- .../src/components/KnowledgeBaseSelector.vue | 7 +- .../src/components/PromptTemplateSelector.vue | 13 +- frontend/src/components/UserMenu.vue | 59 +-- .../components/manual-knowledge-editor.vue | 12 +- frontend/src/components/menu.vue | 7 +- .../composables/useTenantModelReadiness.ts | 36 +- frontend/src/router/index.ts | 55 +-- frontend/src/stores/auth.ts | 103 +++-- frontend/src/stores/chatResources.ts | 382 +++++++----------- frontend/src/stores/editorResources.ts | 273 ++++++++----- .../src/stores/localizedResourceCache.test.ts | 28 +- frontend/src/stores/localizedResourceCache.ts | 23 +- frontend/src/stores/organization.ts | 74 +--- frontend/src/stores/resourceCache.test.ts | 156 +++++++ frontend/src/stores/resourceCache.ts | 111 +++++ frontend/src/stores/sequencedRefresh.test.ts | 81 ++++ frontend/src/stores/sequencedRefresh.ts | 60 +++ frontend/src/utils/tenantModelReadiness.ts | 11 +- .../integrations/ApiIntegrationSettings.vue | 30 +- .../McpServerIntegrationSettings.vue | 18 +- .../knowledge/components/FAQEntryManager.vue | 7 +- frontend/src/views/settings/SystemInfo.vue | 13 +- .../src/views/settings/WebSearchSettings.vue | 11 +- frontend/src/views/system/ModelCatalog.vue | 5 +- 29 files changed, 949 insertions(+), 677 deletions(-) create mode 100644 frontend/src/stores/resourceCache.test.ts create mode 100644 frontend/src/stores/resourceCache.ts create mode 100644 frontend/src/stores/sequencedRefresh.test.ts create mode 100644 frontend/src/stores/sequencedRefresh.ts diff --git a/frontend/src/components/AgentEmbedChannelPanel.vue b/frontend/src/components/AgentEmbedChannelPanel.vue index a28337e5..041199af 100644 --- a/frontend/src/components/AgentEmbedChannelPanel.vue +++ b/frontend/src/components/AgentEmbedChannelPanel.vue @@ -427,13 +427,15 @@ import { validateAllowedOrigins, type AllowedOriginsValidationError, } from '@/utils/embedAllowedOrigins' -import { listAgents, type CustomAgent } from '@/api/agent' +import type { CustomAgent } from '@/api/agent' +import { useChatResourcesStore } from '@/stores/chatResources' import IntegrationsAgentFilter from '@/components/IntegrationsAgentFilter.vue' const filterAgentId = defineModel('filterAgentId', { default: '' }) const { t } = useI18n() const authStore = useAuthStore() +const chatResources = useChatResourcesStore() const isAdmin = computed(() => authStore.hasRole('admin')) const loading = ref(false) @@ -680,12 +682,12 @@ function mergeChannelDetail(detail: EmbedChannel) { const load = async () => { loading.value = true try { - const [res, agentRes] = await Promise.all([ + const [res] = await Promise.all([ listAllEmbedChannels(), - listAgents(), + chatResources.ensureAgents(), ]) allChannels.value = res?.data || [] - agents.value = agentRes?.data || [] + agents.value = chatResources.agents as CustomAgent[] await Promise.all(allChannels.value.map(async (ch) => { try { const statsRes = await getEmbedChannelStats(ch.id) diff --git a/frontend/src/components/AttachmentUpload.vue b/frontend/src/components/AttachmentUpload.vue index b575a771..a24bfd6f 100644 --- a/frontend/src/components/AttachmentUpload.vue +++ b/frontend/src/components/AttachmentUpload.vue @@ -3,7 +3,7 @@ import { ref, computed, onMounted, onUnmounted } from 'vue'; import { MessagePlugin } from 'tdesign-vue-next'; import { useI18n } from 'vue-i18n'; import { MAX_FILE_SIZE_MB } from '@/utils'; -import { getParserEngines } from '@/api/system'; +import { useEditorResourcesStore } from '@/stores/editorResources'; import { deleteTemporaryAttachment, getTemporaryAttachment, @@ -12,6 +12,7 @@ import { } from '@/api/chat/temporary-attachments'; const { t } = useI18n(); +const editorResources = useEditorResourcesStore(); export interface AttachmentFile { file: File; @@ -61,8 +62,8 @@ const supportedTypes = ref([ onMounted(async () => { try { - const response = await getParserEngines(); - const discovered = (response.data || []) + await editorResources.ensureParserEngines(); + const discovered = editorResources.parserEngines .filter(engine => engine.Available !== false) .flatMap(engine => engine.FileTypes || []) .filter(type => type && type.toLowerCase() !== 'url') diff --git a/frontend/src/components/IMChannelPanel.vue b/frontend/src/components/IMChannelPanel.vue index 7fbc468a..77e956f8 100644 --- a/frontend/src/components/IMChannelPanel.vue +++ b/frontend/src/components/IMChannelPanel.vue @@ -594,7 +594,7 @@ import { copyWithToast } from '@/utils/clipboard'; import { normalizeOptionalString } from '@/utils/optionalString'; import { listIMChannels, createIMChannel, updateIMChannel, deleteIMChannel, toggleIMChannel, - getWeChatQRCode, pollWeChatQRCodeStatus, listAllIMChannels, listAgents, + getWeChatQRCode, pollWeChatQRCodeStatus, listAllIMChannels, type IMChannelOverview, type CustomAgent, } from '@/api/agent'; import { useChatResourcesStore } from '@/stores/chatResources'; @@ -940,13 +940,13 @@ async function loadChannels() { loading.value = true; try { const chatResources = useChatResourcesStore(); - const [channelRes, agentRes] = await Promise.all([ + const [channelRes] = await Promise.all([ listAllIMChannels(), - listAgents(), + chatResources.ensureAgents(), chatResources.ensureKnowledgeBases(), ]); allChannels.value = channelRes.data || []; - agents.value = agentRes?.data || []; + agents.value = chatResources.agents as CustomAgent[]; knowledgeBases.value = chatResources.rawKnowledgeBases.map((kb: any) => ({ id: kb.id, name: kb.name })); } catch { allChannels.value = []; diff --git a/frontend/src/components/Input-field.focus.test.mjs b/frontend/src/components/Input-field.focus.test.mjs index 560c2a3c..7ad4751d 100644 --- a/frontend/src/components/Input-field.focus.test.mjs +++ b/frontend/src/components/Input-field.focus.test.mjs @@ -21,7 +21,7 @@ for (const mode of ['normal', 'embedded', 'after', 'inject']) { uploadedAttachments: { value: [] }, uploadedImages: { value: [] }, allSelectedItems: { value: [] }, selectedModelId: { value: 'model' }, selectedAgent: { value: { config: {} } }, - settingsStore: {}, chatResources: { isFresh: () => true }, + settingsStore: {}, chatResources: { isLoaded: () => true }, collectAgentNotReadyReasons: () => ({ keys: [], labels: [] }), attachmentUploadRef: { value: null }, emit: name => effects.push([name]), diff --git a/frontend/src/components/Input-field.vue b/frontend/src/components/Input-field.vue index 9152d5b6..d41f7f03 100644 --- a/frontend/src/components/Input-field.vue +++ b/frontend/src/components/Input-field.vue @@ -1980,18 +1980,12 @@ watch(() => route.params.kbId, (newKbId) => { } }); +// 模型 / 联网搜索列表由设置页在写操作后直接写回 chatResources +// (replaceModels / ensureWebSearchProviders(true)),这里读的是同一份快照, +// 不再靠「设置弹窗关闭」「离开设置路由」两个信号各强刷一次。 watch(() => uiStore.showSettingsModal, (visible, prevVisible) => { - if (prevVisible && !visible) { - loadWebSearchConfig(true); - loadChatModels(true); - if (!props.embeddedMode) void browserConnection.refresh(); - } -}); - -watch(() => route.path, (path, prev) => { - if (prev === '/platform/settings' && path !== '/platform/settings') { - loadWebSearchConfig(true); - loadChatModels(true); + if (prevVisible && !visible && !props.embeddedMode) { + void browserConnection.refresh(); } }); @@ -2099,7 +2093,7 @@ const createSession = async ( return; } - if (!chatResources.isFresh('models')) { + if (!chatResources.isLoaded('models')) { await loadChatModels() } @@ -2248,7 +2242,7 @@ const toggleAgentModeSelector = () => { showAgentModeSelector.value = !showAgentModeSelector.value; if (showAgentModeSelector.value) { - if (!chatResources.isFresh('agents')) { + if (!chatResources.isLoaded('agents')) { void loadAgents(true); } // 多次更新位置确保准确 @@ -2265,7 +2259,7 @@ const toggleAgentModeSelector = () => { } const selectAgentMode = async (mode: 'quick-answer' | 'smart-reasoning') => { - if (!chatResources.isFresh('models')) { + if (!chatResources.isLoaded('models')) { await loadChatModels() } @@ -2305,7 +2299,7 @@ const handleAgentNotReady = ( }; const handleSelectAgent = async (agent: CustomAgent, sourceTenantId?: string) => { - if (!chatResources.isFresh('models')) { + if (!chatResources.isLoaded('models')) { await loadChatModels() } diff --git a/frontend/src/components/KnowledgeBaseSelector.vue b/frontend/src/components/KnowledgeBaseSelector.vue index ef55f06d..82f2476b 100644 --- a/frontend/src/components/KnowledgeBaseSelector.vue +++ b/frontend/src/components/KnowledgeBaseSelector.vue @@ -65,7 +65,7 @@