Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

refactor(frontend): drop TTL resource caches and remove duplicate startup requests (#3562)

lyingbug745a22d066ca
diff --git a/frontend/src/components/AgentEmbedChannelPanel.vue b/frontend/src/components/AgentEmbedChannelPanel.vue
index a28337e53..041199aff 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<string>('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 b575a7715..a24bfd6fb 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 7fbc468a0..77e956f8f 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 560c2a3cc..7ad4751d2 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 9152d5b61..d41f7f037 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 ef55f06d5..82f2476b3 100644
--- a/frontend/src/components/KnowledgeBaseSelector.vue
+++ b/frontend/src/components/KnowledgeBaseSelector.vue
@@ -65,7 +65,7 @@
<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import { useSettingsStore } from '@/stores/settings'
-import { listKnowledgeBases } from '@/api/knowledge-base'
+import { useChatResourcesStore } from '@/stores/chatResources'
import { useI18n } from 'vue-i18n'
import { getRootZoom, rectToCssPx, cssViewportSize } from '@/utils/zoom'
@@ -95,6 +95,7 @@ const settingsStore = useSettingsStore()
// 本地状态
const searchQuery = ref('')
const highlightedIndex = ref(0)
+const chatResources = useChatResourcesStore()
const knowledgeBases = ref<KnowledgeBase[]>([])
const searchInput = ref<HTMLInputElement | null>(null)
const kbList = ref<HTMLElement | null>(null)
@@ -164,8 +165,8 @@ const close = () => {
const loadKnowledgeBases = async () => {
try {
- const res: any = await listKnowledgeBases()
- if (res?.data && Array.isArray(res.data)) knowledgeBases.value = res.data
+ await chatResources.ensureKnowledgeBases()
+ knowledgeBases.value = chatResources.rawKnowledgeBases as KnowledgeBase[]
} catch (e) {
console.error(t('knowledgeBase.loadingFailed'), e)
}
diff --git a/frontend/src/components/PromptTemplateSelector.vue b/frontend/src/components/PromptTemplateSelector.vue
index c1d08d044..64b26ccec 100644
--- a/frontend/src/components/PromptTemplateSelector.vue
+++ b/frontend/src/components/PromptTemplateSelector.vue
@@ -74,7 +74,8 @@
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
-import { getPromptTemplates, type PromptTemplate, type PromptTemplatesConfig } from '@/api/system';
+import type { PromptTemplate, PromptTemplatesConfig } from '@/api/system';
+import { useEditorResourcesStore } from '@/stores/editorResources';
const { t } = useI18n();
@@ -100,7 +101,9 @@ const emit = defineEmits<{
const popupVisible = ref(false);
const loading = ref(false);
const resettingDefault = ref(false);
-const templatesConfig = ref<PromptTemplatesConfig | null>(null);
+// 模板配置走 editorResources 共享快照:智能体编辑器打开时已预取,这里直接复用。
+const editorResources = useEditorResourcesStore();
+const templatesConfig = computed<PromptTemplatesConfig | null>(() => editorResources.promptTemplates);
const handleVisibleChange = async (visible: boolean) => {
popupVisible.value = visible;
@@ -114,8 +117,7 @@ const loadTemplates = async () => {
if (loading.value) return;
loading.value = true;
try {
- const response = await getPromptTemplates();
- templatesConfig.value = response.data;
+ await editorResources.ensurePromptTemplates();
} catch (error) {
console.error('Failed to load prompt templates:', error);
} finally {
@@ -185,8 +187,7 @@ const handleResetToDefault = async () => {
if (!templatesConfig.value) {
resettingDefault.value = true;
try {
- const response = await getPromptTemplates();
- templatesConfig.value = response.data;
+ await editorResources.ensurePromptTemplates();
} catch (error) {
console.error('Failed to load prompt templates:', error);
return;
diff --git a/frontend/src/components/UserMenu.vue b/frontend/src/components/UserMenu.vue
index e377569e3..ffc03e556 100644
--- a/frontend/src/components/UserMenu.vue
+++ b/frontend/src/components/UserMenu.vue
@@ -202,7 +202,7 @@ import { useRouter } from 'vue-router'
import { useUIStore } from '@/stores/ui'
import { useAuthStore } from '@/stores/auth'
import { MessagePlugin } from 'tdesign-vue-next'
-import { getCurrentUser, logout as logoutApi, userInfoFromApi } from '@/api/auth'
+import { logout as logoutApi } from '@/api/auth'
import { useI18n } from 'vue-i18n'
import CreateTenantDialog from '@/components/CreateTenantDialog.vue'
import {
@@ -263,12 +263,13 @@ const tenantSubmenuOpen = ref(false)
const tenantSubmenuStyle = ref<Record<string, string>>({})
let tenantSubmenuHideTimer: ReturnType<typeof setTimeout> | null = null
-// 用户信息
-const userInfo = ref({
- username: t('common.defaultUser'),
- email: '[email protected]',
- avatar: ''
-})
+// 用户信息直接读 auth store:启动时 main.ts 已用 /auth/me 校准过,
+// 这里不再各自拉一份,避免首屏两次 /auth/me。
+const userInfo = computed(() => ({
+ username: authStore.user?.username || t('common.defaultUser'),
+ email: authStore.user?.email || '[email protected]',
+ avatar: authStore.user?.avatar || '',
+}))
const userName = computed(() => userInfo.value.username)
const userEmail = computed(() => userInfo.value.email)
@@ -524,47 +525,13 @@ const handleLogout = async () => {
router.push('/login')
}
-// 加载用户信息
+// 校准用户信息:本次会话已经用 /auth/me 校准过(main.ts 启动、登录流程)
+// 就直接复用 store;只有自动初始化等没走过 /auth/me 的路径才会真的发请求。
+// 落库逻辑(user / tenant / memberships / capabilities)统一在 auth store 里,
+// 这里不再手写一份字段拷贝。
const loadUserInfo = async () => {
try {
- const response = await getCurrentUser()
- if (response.success && response.data && response.data.user) {
- const user = response.data.user
- userInfo.value = {
- username: user.username || t('common.info'),
- email: user.email || '[email protected]',
- avatar: user.avatar || ''
- }
- // 同时更新 authStore 中的用户信息,确保包含 can_access_all_tenants /
- // is_system_admin 等所有字段。MUST 走 userInfoFromApi 工厂——历史
- // 上这里手写字段白名单,每加一个 user 字段都要在 5 个 setUser 调用
- // 点同步,is_system_admin 就因为漏了这一处导致进入 platform 后
- // user.value 的字段被 mount 时的 loadUserInfo 静默覆盖回 undefined
- // (同时污染 localStorage),系统管理入口在 hover 工作空间触发
- // refreshFromAuthMe 后才出现。新增字段请只改 userInfoFromApi。
- authStore.setUser(userInfoFromApi(user))
- // 如果返回了空间信息,也更新空间信息;tenantless 用户(/auth/me
- // 无 tenant)必须显式清空,否则会残留上一账号/上一会话的空间快照。
- if (response.data.tenant) {
- authStore.setTenant({
- id: String(response.data.tenant.id),
- name: response.data.tenant.name,
- owner_id: user.id,
- created_at: response.data.tenant.created_at,
- updated_at: response.data.tenant.updated_at
- })
- } else {
- authStore.setTenant(null)
- }
- const membershipsSync = response.data.memberships
- if (Array.isArray(membershipsSync)) {
- authStore.setMemberships(membershipsSync)
- }
- const canCreateTenant = response.data.capabilities?.can_create_tenant
- if (typeof canCreateTenant === 'boolean') {
- authStore.setCanCreateTenant(canCreateTenant)
- }
- }
+ await authStore.ensureAuthMe()
} catch (error) {
console.error('Failed to load user info:', error)
}
diff --git a/frontend/src/components/manual-knowledge-editor.vue b/frontend/src/components/manual-knowledge-editor.vue
index 432f0a091..5ff7a3664 100644
--- a/frontend/src/components/manual-knowledge-editor.vue
+++ b/frontend/src/components/manual-knowledge-editor.vue
@@ -5,7 +5,6 @@ import { marked } from 'marked'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useUIStore } from '@/stores/ui'
import {
- listKnowledgeBases,
getKnowledgeDetails,
getKnowledgeBaseById,
createManualKnowledge,
@@ -13,6 +12,7 @@ import {
} from '@/api/knowledge-base'
import { useUploadConfirmStore } from '@/stores/uploadConfirm'
import { useOrganizationStore } from '@/stores/organization'
+import { useChatResourcesStore } from '@/stores/chatResources'
import type { KnowledgeProcessOverrides } from '@/types/knowledgeProcess'
import { sanitizeHTML, safeMarkdownToHTML, hydrateProtectedFileImages } from '@/utils/security'
import { continueListOnEnter, countContent, indentOnTab } from '@/utils/markdownEditing'
@@ -57,6 +57,7 @@ const resolveManualKnowledgeStatus = (
const uiStore = useUIStore()
const uploadConfirmStore = useUploadConfirmStore()
const organizationStore = useOrganizationStore()
+const chatResources = useChatResourcesStore()
const { t } = useI18n()
const visible = computed({
@@ -598,14 +599,13 @@ const lastUpdatedText = computed(() =>
const loadKnowledgeBases = async () => {
kbLoading.value = true
try {
- const [ownRes, sharedKbs] = await Promise.all([
- listKnowledgeBases() as Promise<any>,
- organizationStore.fetchSharedKnowledgeBases().catch(() => []),
- ])
+ // ensureKnowledgeBases 同时刷新自己的与共享的知识库快照。
+ await chatResources.ensureKnowledgeBases()
+ const sharedKbs = organizationStore.sharedKnowledgeBases
const isDocumentKb = (type?: string) => !type || type === 'document'
- const ownKbs = Array.isArray(ownRes?.data) ? ownRes.data : []
+ const ownKbs = chatResources.rawKnowledgeBases
const list: KnowledgeBaseOption[] = ownKbs
.filter((item: any) => isDocumentKb(item.type))
.map((item: any) => ({ label: item.name, value: item.id }))
diff --git a/frontend/src/components/menu.vue b/frontend/src/components/menu.vue
index a64b0ebad..81458e944 100644
--- a/frontend/src/components/menu.vue
+++ b/frontend/src/components/menu.vue
@@ -277,9 +277,10 @@ import { MessagePlugin, DialogPlugin, Icon as TIcon } from "tdesign-vue-next";
import UserMenu from '@/components/UserMenu.vue';
import TenantSelector from '@/components/TenantSelector.vue';
import { useI18n } from 'vue-i18n';
-import { getSystemInfo } from '@/api/system';
+import { useEditorResourcesStore } from '@/stores/editorResources';
const chatResources = useChatResourcesStore();
+const editorResources = useEditorResourcesStore();
// Platform logos reused from IMChannelsOverviewPanel — keeps the session list
// visually consistent with the channels admin view.
import wecomLogo from '@/assets/img/im/wecom.svg';
@@ -1059,8 +1060,8 @@ onMounted(async () => {
window.addEventListener(SESSION_MUTATION_EVENT, handleSessionMutation);
isLiteEdition.value = authStore.isLiteMode
- getSystemInfo().then(res => {
- if (res.data?.edition === 'lite') {
+ editorResources.ensureSystemInfo().then(() => {
+ if (editorResources.systemInfo?.edition === 'lite') {
isLiteEdition.value = true
authStore.setLiteMode(true)
}
diff --git a/frontend/src/composables/useTenantModelReadiness.ts b/frontend/src/composables/useTenantModelReadiness.ts
index ecd5e4a4c..ae5101743 100644
--- a/frontend/src/composables/useTenantModelReadiness.ts
+++ b/frontend/src/composables/useTenantModelReadiness.ts
@@ -1,23 +1,24 @@
-import { computed, onMounted, ref, watch } from 'vue'
-import { useUIStore } from '@/stores/ui'
+import { computed, onMounted, ref } from 'vue'
import { useChatResourcesStore } from '@/stores/chatResources'
-import {
- evaluateTenantModelReadiness,
- type TenantModelReadiness,
-} from '@/utils/tenantModelReadiness'
-
+import { evaluateTenantModelReadiness } from '@/utils/tenantModelReadiness'
+
+/**
+ * 当前空间是否已配置好创建知识库 / 智能体所需的模型。
+ *
+ * 直接从 chatResources 的模型快照推导:设置页增删模型后会 `replaceModels`,
+ * 这里的 computed 随之更新,不需要再监听「设置弹窗关闭」之类的间接信号去重拉。
+ */
export function useTenantModelReadiness() {
- const uiStore = useUIStore()
const chatResources = useChatResourcesStore()
- const readiness = ref<TenantModelReadiness | null>(null)
const loaded = ref(false)
const loading = ref(false)
+ const readiness = computed(() => evaluateTenantModelReadiness(chatResources.allModels))
+
const refresh = async (force = false) => {
loading.value = true
try {
await chatResources.ensureModels(force)
- readiness.value = evaluateTenantModelReadiness(chatResources.allModels)
} finally {
loading.value = false
loaded.value = true
@@ -28,22 +29,11 @@ export function useTenantModelReadiness() {
refresh()
})
- watch(
- () => uiStore.showSettingsModal,
- (open, wasOpen) => {
- if (wasOpen && !open) {
- refresh(true)
- }
- },
- )
-
- const isReadyForDocumentKb = computed(
- () => readiness.value?.isReadyForDocumentKb ?? false,
- )
+ const isReadyForDocumentKb = computed(() => readiness.value.isReadyForDocumentKb)
- const isReadyForAgent = computed(() => readiness.value?.isReadyForAgent ?? false)
+ const isReadyForAgent = computed(() => readiness.value.isReadyForAgent)
- const hasChat = computed(() => readiness.value?.hasChat ?? false)
+ const hasChat = computed(() => readiness.value.hasChat)
return {
readiness,
diff --git a/frontend/src/router/index.ts b/frontend/src/router/index.ts
index 87bc78fdf..dd6d065b9 100644
--- a/frontend/src/router/index.ts
+++ b/frontend/src/router/index.ts
@@ -3,7 +3,7 @@ import { defineComponent } from 'vue'
import type { RouteLocationNormalized } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useDeploymentCapabilitiesStore } from '@/stores/deploymentCapabilities'
-import { autoSetup, getCurrentUser, userInfoFromApi } from '@/api/auth'
+import { autoSetup, userInfoFromApi } from '@/api/auth'
import type { DeploymentCapabilityKey } from '@/config/deploymentCapabilities'
import { MessagePlugin } from 'tdesign-vue-next'
import i18n from '@/i18n'
@@ -269,56 +269,9 @@ async function hydrateSessionFromToken(authStore: ReturnType<typeof useAuthStore
authStore.setRefreshToken(storedRefreshToken)
}
- try {
- const response = await getCurrentUser()
- const user = response.data?.user
- if (!response.success || !user) {
- return false
- }
-
- authStore.setUser(userInfoFromApi(user, response.data?.tenant?.id))
-
- const tenant = response.data?.tenant
- if (tenant) {
- authStore.setTenant({
- id: String(tenant.id) || '',
- name: tenant.name || '',
- owner_id: tenant.owner_id || user.id || '',
- description: tenant.description,
- status: tenant.status,
- business: tenant.business,
- storage_quota: tenant.storage_quota,
- storage_used: tenant.storage_used,
- created_at: tenant.created_at || new Date().toISOString(),
- updated_at: tenant.updated_at || new Date().toISOString(),
- })
- } else {
- authStore.setTenant(null)
- }
-
- // Refresh memberships on every page load — same reason as
- // App.vue's syncOIDCUserContext: without this the auth store
- // would only ever see the snapshot from the original /auth/login
- // call, so role changes (and tenant-switch role lookups) would
- // be silently stale until the user logged out and back in.
- const memberships = response.data?.memberships
- if (Array.isArray(memberships)) {
- authStore.setMemberships(memberships)
- }
-
- const canCreateTenant = response.data?.capabilities?.can_create_tenant
- if (typeof canCreateTenant === 'boolean') {
- authStore.setCanCreateTenant(canCreateTenant)
- }
-
- authStore.setAutoAcceptInvitation(
- response.data?.capabilities?.auto_accept_invitation === true,
- )
-
- return true
- } catch {
- return false
- }
+ // /auth/me 的落库逻辑只在 auth store 里维护一份(user / tenant / memberships /
+ // capabilities),这里只负责先把 token 放进 store。请求本身与启动、侧栏共用去重。
+ return authStore.refreshFromAuthMe()
}
let autoSetupAttempted = false
diff --git a/frontend/src/stores/auth.ts b/frontend/src/stores/auth.ts
index 464cea534..488bd45d3 100644
--- a/frontend/src/stores/auth.ts
+++ b/frontend/src/stores/auth.ts
@@ -11,6 +11,7 @@ import { BUILTIN_QUICK_ANSWER_ID } from '@/api/agent'
import { useChatResourcesStore } from '@/stores/chatResources'
import { useEditorResourcesStore } from '@/stores/editorResources'
import { useOrganizationStore } from '@/stores/organization'
+import { createSequencedRefresh } from '@/stores/sequencedRefresh'
/** 登出时丢弃 Pinia 内的空间级资源缓存,避免 SPA 重登复用上一账号数据。 */
function clearSessionResourceCaches() {
@@ -337,49 +338,73 @@ export const useAuthStore = defineStore('auth', () => {
// Login only populated memberships once; SPA navigations skip
// hydrateSessionFromToken when isLoggedIn is already true — so inviting
// flows or revokes would leave the sidebar switcher stale until reload.
- const refreshFromAuthMe = async (): Promise<boolean> => {
+ //
+ // 请求排序:refreshFromAuthMe 是「刷新」,结果必须来自本次调用之后发出的请求
+ // (接受邀请 / 建空间 / 改空间信息之后调用,不能吃到侧栏悬停早先发出的那次响应);
+ // ensureAuthMe 是「首屏共用」,有请求在飞行就直接复用。登出会作废飞行中的请求,
+ // 迟到的响应不再把会话写回来。
+ // 本次会话是否已经用 /auth/me 校准过。登录响应 / 自动初始化只写入登录时的快照,
+ // 之后第一次进入平台布局仍需校准一次;此后由写操作显式 refresh。
+ let authMeSynced = false
+
+ const authMeRequest = createSequencedRefresh<boolean>(async (isCurrent) => {
try {
const { getCurrentUser } = await import('@/api/auth')
const response = await getCurrentUser()
- const u = response.data?.user
- if (!response.success || !u) return false
-
- setUser(userInfoFromApi(u, response.data?.tenant?.id))
-
- const tenantSnapshot = response.data?.tenant
- if (tenantSnapshot) {
- setTenant({
- id: String(tenantSnapshot.id) || '',
- name: tenantSnapshot.name || '',
- owner_id: tenantSnapshot.owner_id || u.id || '',
- description: tenantSnapshot.description,
- status: tenantSnapshot.status,
- business: tenantSnapshot.business,
- storage_quota: tenantSnapshot.storage_quota,
- storage_used: tenantSnapshot.storage_used,
- created_at: tenantSnapshot.created_at || new Date().toISOString(),
- updated_at: tenantSnapshot.updated_at || new Date().toISOString(),
- })
- } else {
- setTenant(null)
- }
+ if (!isCurrent()) return false
+ return applyAuthMeResponse(response)
+ } catch {
+ return false
+ }
+ })
- const list = response.data?.memberships
- if (Array.isArray(list)) {
- setMemberships(list)
- }
+ const refreshFromAuthMe = (): Promise<boolean> => authMeRequest.refresh()
- const createCapability = response.data?.capabilities?.can_create_tenant
- if (typeof createCapability === 'boolean') {
- setCanCreateTenant(createCapability)
- }
+ /** 会话内已校准过就直接返回,否则复用飞行中的 /auth/me,没有就拉一次。 */
+ const ensureAuthMe = (): Promise<boolean> => {
+ if (authMeSynced) return Promise.resolve(true)
+ return authMeRequest.share()
+ }
- setAutoAcceptInvitation(response.data?.capabilities?.auto_accept_invitation === true)
+ type AuthMeResponse = Awaited<ReturnType<typeof import('@/api/auth')['getCurrentUser']>>
+ const applyAuthMeResponse = (response: AuthMeResponse): boolean => {
+ const u = response.data?.user
+ if (!response.success || !u) return false
+
+ setUser(userInfoFromApi(u, response.data?.tenant?.id))
+
+ const tenantSnapshot = response.data?.tenant
+ if (tenantSnapshot) {
+ setTenant({
+ id: String(tenantSnapshot.id) || '',
+ name: tenantSnapshot.name || '',
+ owner_id: tenantSnapshot.owner_id || u.id || '',
+ description: tenantSnapshot.description,
+ status: tenantSnapshot.status,
+ business: tenantSnapshot.business,
+ storage_quota: tenantSnapshot.storage_quota,
+ storage_used: tenantSnapshot.storage_used,
+ created_at: tenantSnapshot.created_at || new Date().toISOString(),
+ updated_at: tenantSnapshot.updated_at || new Date().toISOString(),
+ })
+ } else {
+ setTenant(null)
+ }
- return true
- } catch {
- return false
+ const list = response.data?.memberships
+ if (Array.isArray(list)) {
+ setMemberships(list)
}
+
+ const createCapability = response.data?.capabilities?.can_create_tenant
+ if (typeof createCapability === 'boolean') {
+ setCanCreateTenant(createCapability)
+ }
+
+ setAutoAcceptInvitation(response.data?.capabilities?.auto_accept_invitation === true)
+
+ authMeSynced = true
+ return true
}
// 用 token 加入空间并刷新成员关系、切到新空间。token 无效时返回 ok:false(不抛异常),
@@ -432,6 +457,9 @@ export const useAuthStore = defineStore('auth', () => {
pendingInvitationCount.value = 0
canCreateTenant.value = false
autoAcceptInvitation.value = false
+ authMeSynced = false
+ // 飞行中的 /auth/me 作废:登出之后才返回的响应不能再 setUser / setTenant。
+ authMeRequest.invalidate()
clearSessionResourceCaches()
// 清空localStorage
@@ -585,6 +613,7 @@ export const useAuthStore = defineStore('auth', () => {
setAutoAcceptInvitation,
fetchPendingInvitationCount,
refreshFromAuthMe,
+ ensureAuthMe,
acceptInvitationByTokenAndRefresh,
getSelectedTenant,
setLiteMode,
diff --git a/frontend/src/stores/chatResources.ts b/frontend/src/stores/chatResources.ts
index a61e949bc..a5488d1d9 100644
--- a/frontend/src/stores/chatResources.ts
+++ b/frontend/src/stores/chatResources.ts
@@ -7,14 +7,8 @@ import { listWebSearchProviders, type WebSearchProviderEntity } from '@/api/web-
import { isNamedSandboxBackend, listSandboxConfigs, type SandboxConfigRecord } from '@/api/system'
import { useOrganizationStore } from '@/stores/organization'
import { getCurrentLanguage } from '@/utils/request'
-import {
- isLocalizedCacheFresh,
- shouldCommitLocalizedGeneration,
- shouldReuseLocalizedInflight,
-} from './localizedResourceCache'
-
-/** 空间级资源缓存 TTL */
-const CACHE_TTL_MS = 60_000
+import { isLocalizedSnapshotUsable, shouldForceLocalizedRefetch } from './localizedResourceCache'
+import { createCachedResource, createKeyedSnapshotCache } from './resourceCache'
type ResourceKey = 'knowledgeBases' | 'agents' | 'models' | 'webSearchProviders' | 'sandboxConfigs'
@@ -28,6 +22,13 @@ function isKbModelReady(kb: any): boolean {
return true
}
+/**
+ * 空间级资源(知识库 / 智能体 / 模型 / 联网搜索 / 沙箱后端)的共享快照。
+ *
+ * 没有 TTL:每次 `ensureX()` 都会发请求(同一时刻只有一个在飞行,挂载突发共用它),
+ * 写操作之后由调用方 `ensureX(true)`、`replaceModels()` 或 `invalidate()` 显式刷新。
+ * 页面直接读这里的 ref 渲染,旧快照在新数据到达前先撑着。
+ */
export const useChatResourcesStore = defineStore('chatResources', () => {
const rawKnowledgeBases = ref<any[]>([])
const agents = ref<CustomAgent[]>([])
@@ -36,112 +37,156 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
const webSearchProviders = ref<WebSearchProviderEntity[]>([])
const sandboxConfigs = ref<SandboxConfigRecord[]>([])
- const loadedAt = ref<Partial<Record<ResourceKey, number>>>({})
- 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
- // 代际计数:force 与非 force 并发时句柄会被后来者覆盖,旧请求结束时凭此判断
- // 自己是否仍是最新的那次,避免误清正在飞行的句柄。
- let kbAllGen = 0
- let agentsAllGen = 0
- // 模型列表同样用代际挡住过期的 inflight:设置页保存后会 replaceModels,
- // 不能让保存前发出的 ensureModels 把旧列表写回来。
- let modelsGen = 0
-
- 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'))
- // 内置智能体名称/描述由后端按 Accept-Language 本地化返回;切换 UI 语言后
- // 旧缓存必须立即失效,否则要等 TTL 过期或强刷才能看到正确语言。
- // agentsLoadedLocale 必须是「请求发起时」的语言,不能在 await 之后再读当前语言。
- let agentsLoadedLocale = ''
- let agentsAllInflightLocale = ''
-
- function isFresh(key: ResourceKey): boolean {
- const at = loadedAt.value[key] ?? 0
- if (key === 'agents') {
- return isLocalizedCacheFresh(at, agentsLoadedLocale, getCurrentLanguage(), CACHE_TTL_MS)
- }
- return at > 0 && Date.now() - at < CACHE_TTL_MS
- }
+ const knowledgeBasesResource = createCachedResource(
+ async () => {
+ const res: any = await listKnowledgeBases()
+ return res?.data && Array.isArray(res.data) ? (res.data as any[]) : []
+ },
+ (data) => {
+ rawKnowledgeBases.value = data
+ },
+ )
- function bumpAgentsGeneration() {
- agentsAllGen++
- agentsAllInflight = null
- agentsAllInflightLocale = ''
- }
+ // 内置智能体名称/描述由后端按 Accept-Language 本地化返回;快照只对拉取时的
+ // UI 语言有效。agentsLoadedLocale 必须是「请求发起时」的语言,不能在 await 之后再读。
+ let agentsLoadedLocale = ''
+ let agentsInflightLocale = ''
+ const agentsResource = createCachedResource(
+ async () => {
+ const locale = getCurrentLanguage()
+ agentsInflightLocale = locale
+ const res = (await listAgents()) as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
+ return { data: res.data || [], disabled: res.disabled_own_agent_ids || [], locale }
+ },
+ ({ data, disabled, locale }) => {
+ agents.value = data
+ disabledOwnAgentIds.value = disabled
+ agentsLoadedLocale = locale
+ },
+ )
watch(
() => getCurrentLanguage(),
(locale) => {
if (agentsLoadedLocale && agentsLoadedLocale !== locale) {
- delete loadedAt.value.agents
+ agentsResource.invalidate()
agentsLoadedLocale = ''
- bumpAgentsGeneration()
}
},
)
- 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)
+ const modelsResource = createCachedResource(
+ async () => {
+ const models = await listModels()
+ return Array.isArray(models) ? models : []
+ },
+ (models) => {
+ allModels.value = models
+ },
+ )
+
+ const webSearchProvidersResource = createCachedResource(
+ async () => {
+ const response = await listWebSearchProviders()
+ const providers = (response as any)?.data
+ return Array.isArray(providers) ? (providers as WebSearchProviderEntity[]) : []
+ },
+ (providers) => {
+ webSearchProviders.value = providers
+ },
+ )
+
+ // 失败只吞掉不抛:这是可选资源——拿不到就只剩「不启用沙箱」一项,
+ // 智能体照样能编辑保存。调用方通常把它和一堆必需资源放在同一个
+ // Promise.all 里,若在这里抛出,整个编辑器的依赖加载都会连坐
+ // (技能可用性拿不到 ⇒ 技能配置分组直接消失)。
+ const sandboxConfigsResource = createCachedResource(
+ async () => {
+ try {
+ const res = await listSandboxConfigs()
+ const rows = Array.isArray(res?.data) ? res.data : []
+ return rows.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type))
+ } catch {
+ return [] as SandboxConfigRecord[]
+ }
+ },
+ (rows) => {
+ sandboxConfigs.value = rows
+ },
+ )
+
+ const resources: Record<ResourceKey, ReturnType<typeof createCachedResource>> = {
+ knowledgeBases: knowledgeBasesResource,
+ agents: agentsResource,
+ models: modelsResource,
+ webSearchProviders: webSearchProvidersResource,
+ sandboxConfigs: sandboxConfigsResource,
+ }
+
+ // 智能体可见知识库、单个知识库详情:拿到过就一直用,直到显式失效。
+ // @ 提及列表会逐条补 count,这类按 key 的读取不能每次都打接口。
+ const agentKbCache = createKeyedSnapshotCache(async (cacheKey: string) => {
+ const [agentId, sourceTenantId] = cacheKey.split(':')
+ const res: any = await listKnowledgeBases({
+ agent_id: agentId,
+ agent_source_tenant_id: sourceTenantId === 'current' ? undefined : sourceTenantId,
})
- inflight.set(key, p)
- return p
+ return res?.data && Array.isArray(res.data) ? (res.data as any[]) : []
+ })
+ const kbDetailCache = createKeyedSnapshotCache(async (kbId: string) => {
+ try {
+ const res: any = await getKnowledgeBaseById(kbId)
+ return res?.data ?? null
+ } catch {
+ return null
+ }
+ })
+
+ /** 是否已有快照(区别于「是否新鲜」:本 store 不再有新鲜度窗口)。 */
+ function isLoaded(key: ResourceKey): boolean {
+ if (key === 'agents') {
+ return isLocalizedSnapshotUsable(agentsResource.isLoaded(), agentsLoadedLocale, getCurrentLanguage())
+ }
+ return resources[key].isLoaded()
}
/**
- * 知识库列表(支持 creator 筛选)。creator=all 时写入缓存供对话页复用。
+ * 知识库列表(支持 creator 筛选)。creator=all 走共享快照供对话页复用。
*/
async function fetchKnowledgeBasesForList(
params?: { creator?: ListCreatorFilter },
force = false,
): Promise<any[]> {
const creator = params?.creator ?? 'all'
- // 带 creator 过滤的列表是列表页专用、不进缓存,直接透传请求。
+ // 带 creator 过滤的列表是列表页专用、不进快照,直接透传请求。
+ // 写操作后的强刷同时把全量快照刷一遍,否则对话输入栏会看到已删除的知识库。
if (creator !== 'all') {
+ if (force) void ensureKnowledgeBases(true).catch(() => {})
const res: any = await listKnowledgeBases({ creator })
return res?.data && Array.isArray(res.data) ? res.data : []
}
-
- if (!force && isFresh('knowledgeBases')) {
- return rawKnowledgeBases.value
- }
- if (!force && kbAllInflight) return kbAllInflight
-
- const gen = ++kbAllGen
- kbAllInflight = (async () => {
- try {
- const res: any = await listKnowledgeBases()
- const data = res?.data && Array.isArray(res.data) ? res.data : []
- rawKnowledgeBases.value = data
- loadedAt.value.knowledgeBases = Date.now()
- const orgStore = useOrganizationStore()
- await orgStore.fetchSharedKnowledgeBases({ force })
- return data
- } finally {
- if (kbAllGen === gen) kbAllInflight = null
- }
- })()
- return kbAllInflight
+ await ensureKnowledgeBases(force)
+ return rawKnowledgeBases.value
}
+ // 共享资源是附带刷新:它的接口挂了不能连坐自己的列表,否则调用方的 catch
+ // 会把已经拿到的自己的知识库 / 智能体一起清掉(手动文档编辑器、API 集成页)。
+ // 共享列表失败时保留上一次快照,由页面自己决定要不要单独强刷。
+ const swallow = (p: Promise<unknown>) => p.catch(() => undefined)
+
async function ensureKnowledgeBases(force = false): Promise<void> {
- await fetchKnowledgeBasesForList({ creator: 'all' }, force)
+ const orgStore = useOrganizationStore()
+ await Promise.all([
+ knowledgeBasesResource.ensure(force),
+ swallow(orgStore.fetchSharedKnowledgeBases({ force })),
+ ])
}
/**
- * 智能体列表(支持 creator 筛选)。creator=all 时写入缓存。
+ * 智能体列表(支持 creator 筛选)。creator=all 走共享快照。
*/
async function fetchAgentsForList(
params?: { creator?: ListCreatorFilter },
@@ -150,8 +195,9 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
const creator = params?.creator ?? 'all'
const orgStore = useOrganizationStore()
- // 带 creator 过滤的列表不进缓存,但仍需刷新共享智能体(与全量路径保持一致)。
+ // 带 creator 过滤的列表不进快照,但仍需刷新共享智能体(与全量路径保持一致)。
if (creator !== 'all') {
+ if (force) void ensureAgents(true).catch(() => {})
const [agentsRes] = await Promise.all([
listAgents({ creator }),
orgStore.fetchSharedAgents({ force }),
@@ -160,66 +206,31 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
return { data: res.data || [], disabled_own_agent_ids: res.disabled_own_agent_ids || [] }
}
- const locale = getCurrentLanguage()
- if (!force && isFresh('agents')) {
- return { data: agents.value, disabled_own_agent_ids: disabledOwnAgentIds.value }
- }
- if (
- !force &&
- shouldReuseLocalizedInflight(!!agentsAllInflight, agentsAllInflightLocale, locale)
- ) {
- return agentsAllInflight as Promise<{ data: CustomAgent[]; disabled_own_agent_ids: string[] }>
- }
-
- const gen = ++agentsAllGen
- const requestLocale = locale
- agentsAllInflightLocale = requestLocale
- agentsAllInflight = (async () => {
- try {
- const [agentsRes] = await Promise.all([
- listAgents(),
- orgStore.fetchSharedAgents({ force }),
- ])
- const res = agentsRes as { data?: CustomAgent[]; disabled_own_agent_ids?: string[] }
- const data = res.data || []
- const disabled = res.disabled_own_agent_ids || []
- if (shouldCommitLocalizedGeneration(gen, agentsAllGen)) {
- agents.value = data
- disabledOwnAgentIds.value = disabled
- loadedAt.value.agents = Date.now()
- agentsLoadedLocale = requestLocale
- }
- return { data, disabled_own_agent_ids: disabled }
- } finally {
- if (shouldCommitLocalizedGeneration(gen, agentsAllGen)) {
- agentsAllInflight = null
- agentsAllInflightLocale = ''
- }
- }
- })()
- return agentsAllInflight
+ await ensureAgents(force)
+ return { data: agents.value, disabled_own_agent_ids: disabledOwnAgentIds.value }
}
async function ensureAgents(force = false): Promise<void> {
- await fetchAgentsForList({ creator: 'all' }, force)
+ const orgStore = useOrganizationStore()
+ const locale = getCurrentLanguage()
+ // 飞行中的请求是用另一种语言发起的:不能复用它,排在它后面再发一次。
+ const mustForce =
+ force ||
+ shouldForceLocalizedRefetch(agentsResource.hasInFlightRequest(), agentsInflightLocale, locale)
+ await Promise.all([
+ agentsResource.ensure(mustForce),
+ swallow(orgStore.fetchSharedAgents({ force })),
+ ])
}
async function ensureModels(force = false): Promise<void> {
- return runOnce('models', force, async () => {
- const gen = ++modelsGen
- const models = await listModels()
- if (gen !== modelsGen) return
- allModels.value = Array.isArray(models) ? models : []
- loadedAt.value.models = Date.now()
- })
+ return modelsResource.ensure(force)
}
- /** 用刚拉到的列表覆盖缓存(模型增删改之后调用,避免 60s TTL 把旧窗口大小继续展示)。 */
+ /** 用刚拉到的列表覆盖快照(设置页增删改模型之后调用),并作废飞行中的旧请求。 */
function replaceModels(models: ModelConfig[]) {
- modelsGen++
- inflight.delete('models')
allModels.value = Array.isArray(models) ? models : []
- loadedAt.value.models = Date.now()
+ modelsResource.markLoaded()
}
/** @deprecated 使用 ensureModels;保留别名供对话输入栏调用 */
@@ -228,36 +239,15 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
}
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()
- })
+ return webSearchProvidersResource.ensure(force)
}
/**
* 沙箱后端配置,供智能体编辑器的后端选择器使用。
- *
- * 不进 prefetchChatInput:只有编辑智能体时才需要,而对话输入栏用不到,
- * 没必要让每次首屏都多打一次请求。
- *
- * 失败只吞掉不抛:这是可选资源——拿不到就只剩「不启用沙箱」一项,
- * 智能体照样能编辑保存。调用方通常把它和一堆必需资源放在同一个
- * Promise.all 里,若在这里抛出,整个编辑器的依赖加载都会连坐
- * (技能可用性拿不到 ⇒ 技能配置分组直接消失)。
+ * 不进 prefetchChatInput:只有编辑智能体时才需要,对话输入栏用不到。
*/
async function ensureSandboxConfigs(force = false): Promise<void> {
- return runOnce('sandboxConfigs', force, async () => {
- try {
- const res = await listSandboxConfigs()
- const rows = Array.isArray(res?.data) ? res.data : []
- sandboxConfigs.value = rows.filter((cfg) => isNamedSandboxBackend(cfg.sandbox_type))
- } catch {
- sandboxConfigs.value = []
- }
- loadedAt.value.sandboxConfigs = Date.now()
- })
+ return sandboxConfigsResource.ensure(force)
}
/** 并行预取对话输入栏及列表页常用的空间级资源 */
@@ -273,105 +263,41 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
}
async function ensureAgentKnowledgeBases(agentId: string, sourceTenantId?: string, force = false): Promise<any[]> {
- const cacheKey = `${agentId}:${sourceTenantId || 'current'}`
- const cached = agentKbCache.get(cacheKey)
- if (!force && cached && Date.now() - cached.at < CACHE_TTL_MS) {
- return cached.data
- }
- const existing = agentKbInflight.get(cacheKey)
- if (existing) return existing
-
- const p = (async () => {
- try {
- const res: any = await listKnowledgeBases({
- agent_id: agentId,
- agent_source_tenant_id: sourceTenantId,
- })
- const list = res?.data && Array.isArray(res.data) ? res.data : []
- agentKbCache.set(cacheKey, { at: Date.now(), data: list })
- return list
- } finally {
- agentKbInflight.delete(cacheKey)
- }
- })()
- agentKbInflight.set(cacheKey, p)
- return p
+ return agentKbCache.ensure(`${agentId}:${sourceTenantId || 'current'}`, force)
}
/** 单个知识库详情(侧栏 + 详情页共用,去重并发请求) */
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
+ return kbDetailCache.ensure(kbId, force)
}
function invalidateKnowledgeBaseDetail(kbId?: string) {
- if (kbId) {
- kbDetailCache.delete(kbId)
- kbDetailInflight.delete(kbId)
- } else {
- kbDetailCache.clear()
- kbDetailInflight.clear()
- }
+ kbDetailCache.invalidate(kbId)
}
function invalidate(...keys: ResourceKey[]) {
if (keys.length === 0) {
- loadedAt.value = {}
+ ;(Object.keys(resources) as ResourceKey[]).forEach((k) => resources[k].invalidate())
rawKnowledgeBases.value = []
agents.value = []
disabledOwnAgentIds.value = []
allModels.value = []
webSearchProviders.value = []
sandboxConfigs.value = []
- agentKbCache.clear()
- // 同时丢弃所有 inflight 句柄,否则失效后仍在飞行的请求会把旧数据写回缓存。
- inflight.clear()
- agentKbInflight.clear()
- kbAllInflight = null
agentsLoadedLocale = ''
- bumpAgentsGeneration()
- modelsGen++
+ agentsInflightLocale = ''
+ agentKbCache.invalidate()
invalidateKnowledgeBaseDetail()
return
}
- keys.forEach((k) => {
- delete loadedAt.value[k]
- inflight.delete(k)
- })
+ keys.forEach((k) => resources[k].invalidate())
if (keys.includes('knowledgeBases')) {
- agentKbCache.clear()
- agentKbInflight.clear()
- kbAllInflight = null
+ agentKbCache.invalidate()
invalidateKnowledgeBaseDetail()
}
if (keys.includes('agents')) {
agentsLoadedLocale = ''
- bumpAgentsGeneration()
- }
- if (keys.includes('models')) {
- modelsGen++
}
}
@@ -384,7 +310,7 @@ export const useChatResourcesStore = defineStore('chatResources', () => {
chatModels,
webSearchProviders,
sandboxConfigs,
- isFresh,
+ isLoaded,
fetchKnowledgeBasesForList,
fetchAgentsForList,
ensureKnowledgeBases,
diff --git a/frontend/src/stores/editorResources.ts b/frontend/src/stores/editorResources.ts
index 225ab93cd..ff9069169 100644
--- a/frontend/src/stores/editorResources.ts
+++ b/frontend/src/stores/editorResources.ts
@@ -22,8 +22,7 @@ import {
import { getAgentTypePresets, getPlaceholders, type AgentTypePreset, type PlaceholdersResponse } from '@/api/agent'
import { getTenantRetrievalConfig } from '@/api/retrieval'
import { isStorageConfigDenied } from './storageEngineAccess'
-
-const CACHE_TTL_MS = 60_000
+import { createCachedResource } from './resourceCache'
export function pickUsableStorageProvider(
candidate: string | undefined,
@@ -58,6 +57,11 @@ type EditorResourceKey =
| 'parserEngines'
| 'systemInfo'
+/**
+ * 智能体编辑器 / 知识库页面共用的配置类资源快照。
+ * 与 chatResources 同一套约定:无 TTL,每次 ensure 发一次请求(并发共用),
+ * 写操作后显式 `ensureX(true)` 或 `invalidate()`。
+ */
export const useEditorResourcesStore = defineStore('editorResources', () => {
const storageConfig = ref<Awaited<ReturnType<typeof getStorageEngineConfig>>['data'] | null>(null)
const storageStatus = ref<StorageEngineStatusItem[]>([])
@@ -75,25 +79,8 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
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 storageEngineResource = createCachedResource(
+ async () => {
const [configRes, statusRes] = await Promise.all([
// The config endpoint is admin-only (it carries integration secrets),
// while every creator — Contributors included — needs the status list
@@ -106,11 +93,151 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
}),
getStorageEngineStatus(),
])
+ return { configRes, statusRes }
+ },
+ ({ configRes, statusRes }) => {
storageConfig.value = configRes?.data ?? null
storageStatus.value = statusRes?.data?.engines ?? []
storageAllowedProviders.value = statusRes?.data?.allowed_providers ?? []
- loadedAt.value.storageEngine = Date.now()
- })
+ },
+ )
+
+ // A shared agent's skills and MCP services live in its owner's workspace and
+ // are an entirely different set from this workspace's. The cache key has to
+ // carry the agent, or switching agents would leave another workspace's
+ // entries in the @ picker.
+ function scopeKey(configId: string, agent?: AgentScope): string {
+ if (!agent?.agentId || !agent?.sourceTenantId) return configId
+ return `${configId}@${agent.sourceTenantId}:${agent.agentId}`
+ }
+
+ let mcpServicesRequestScope: { key: string; agent?: AgentScope } = { key: '' }
+ const mcpServicesResource = createCachedResource(
+ async () => {
+ const scope = mcpServicesRequestScope
+ const list = await listMCPServices(scope.agent)
+ return { key: scope.key, list: Array.isArray(list) ? list : [] }
+ },
+ ({ key, list }) => {
+ mcpServicesScope.value = key
+ mcpServices.value = list
+ },
+ )
+
+ let skillsRequestScope: { key: string; configId: string; agent?: AgentScope } = { key: '', configId: '' }
+ const skillsResource = createCachedResource(
+ async () => {
+ const scope = skillsRequestScope
+ // No sandbox config means no skills, for a shared agent too: its config
+ // id is part of the agent config this caller already holds. The backend
+ // re-reads it from the agent, so what is sent here only has to be
+ // non-empty when the agent actually has one.
+ if (!scope.configId) {
+ return { key: scope.key, available: false, list: [] as SkillInfo[] }
+ }
+ try {
+ const skillsRes = await listSkills(scope.configId, scope.agent)
+ return {
+ key: scope.key,
+ available: skillsRes.skills_available !== false,
+ list: skillsRes.data && skillsRes.data.length > 0 ? skillsRes.data : [],
+ }
+ } catch {
+ return { key: scope.key, available: false, list: [] as SkillInfo[] }
+ }
+ },
+ ({ key, available, list }) => {
+ skillsConfigId.value = key
+ skillsAvailable.value = available
+ skills.value = list
+ },
+ )
+
+ const skillCatalogResource = createCachedResource(
+ async () => {
+ const res = await listSkillCatalog()
+ return Array.isArray(res?.data) ? res.data : []
+ },
+ (rows) => {
+ skillCatalog.value = rows
+ },
+ )
+
+ const agentTypePresetsResource = createCachedResource(
+ async () => {
+ const presetsRes: any = await getAgentTypePresets()
+ return presetsRes?.data && Array.isArray(presetsRes.data) ? (presetsRes.data as AgentTypePreset[]) : []
+ },
+ (rows) => {
+ agentTypePresets.value = rows
+ },
+ )
+
+ const promptTemplatesResource = createCachedResource(
+ async () => {
+ const tmplRes = await getPromptTemplates()
+ return tmplRes?.data ?? null
+ },
+ (config) => {
+ promptTemplates.value = config
+ },
+ )
+
+ const placeholdersResource = createCachedResource(
+ async () => {
+ const placeholdersRes = await getPlaceholders()
+ return placeholdersRes?.data ?? null
+ },
+ (data) => {
+ placeholders.value = data
+ },
+ )
+
+ const tenantRetrievalConfigResource = createCachedResource(
+ async () => {
+ const retrievalRes: any = await getTenantRetrievalConfig()
+ return (retrievalRes?.data ?? null) as Record<string, unknown> | null
+ },
+ (config) => {
+ tenantRetrievalConfig.value = config
+ },
+ )
+
+ const parserEnginesResource = createCachedResource(
+ async () => {
+ const resp = await getParserEngines()
+ return resp?.data && Array.isArray(resp.data) ? resp.data : []
+ },
+ (rows) => {
+ parserEngines.value = rows
+ },
+ )
+
+ const systemInfoResource = createCachedResource(
+ async () => {
+ const response = await getSystemInfo()
+ return response?.data ?? null
+ },
+ (info) => {
+ systemInfo.value = info
+ },
+ )
+
+ const resources: Record<EditorResourceKey, ReturnType<typeof createCachedResource>> = {
+ storageEngine: storageEngineResource,
+ mcpServices: mcpServicesResource,
+ skills: skillsResource,
+ skillCatalog: skillCatalogResource,
+ agentTypePresets: agentTypePresetsResource,
+ promptTemplates: promptTemplatesResource,
+ placeholders: placeholdersResource,
+ tenantRetrievalConfig: tenantRetrievalConfigResource,
+ parserEngines: parserEnginesResource,
+ systemInfo: systemInfoResource,
+ }
+
+ async function ensureStorageEngine(force = false): Promise<void> {
+ return storageEngineResource.ensure(force)
}
function resolveUsableStorageProvider(candidate?: string): string {
@@ -123,24 +250,13 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
async function ensureMcpServices(agent?: AgentScope, force = false): Promise<void> {
const key = scopeKey('', agent)
- if (key !== mcpServicesScope.value) {
+ // 换了作用域:作废飞行中的旧请求,且必须排在它后面重新发。
+ if (key !== mcpServicesRequestScope.key) {
+ mcpServicesResource.invalidate()
force = true
}
- return runOnce('mcpServices', force, async () => {
- mcpServicesScope.value = key
- const list = await listMCPServices(agent)
- mcpServices.value = Array.isArray(list) ? list : []
- loadedAt.value.mcpServices = Date.now()
- })
- }
-
- // A shared agent's skills and MCP services live in its owner's workspace and
- // are an entirely different set from this workspace's. The cache key has to
- // carry the agent, or switching agents would leave another workspace's
- // entries in the @ picker.
- function scopeKey(configId: string, agent?: AgentScope): string {
- if (!agent?.agentId || !agent?.sourceTenantId) return configId
- return `${configId}@${agent.sourceTenantId}:${agent.agentId}`
+ mcpServicesRequestScope = { key, agent }
+ return mcpServicesResource.ensure(force)
}
async function ensureSkills(
@@ -150,87 +266,40 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
): Promise<void> {
const configId = sandboxConfigId?.trim() || ''
const key = scopeKey(configId, agent)
- if (key !== skillsConfigId.value) {
+ if (key !== skillsRequestScope.key) {
+ skillsResource.invalidate()
force = true
}
- return runOnce('skills', force, async () => {
- skillsConfigId.value = key
- // No sandbox config means no skills, for a shared agent too: its config
- // id is part of the agent config this caller already holds. The backend
- // re-reads it from the agent, so what is sent here only has to be
- // non-empty when the agent actually has one.
- if (!configId) {
- skillsAvailable.value = false
- skills.value = []
- loadedAt.value.skills = Date.now()
- return
- }
- try {
- const skillsRes = await listSkills(configId, agent)
- 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()
- })
+ skillsRequestScope = { key, configId, agent }
+ return skillsResource.ensure(force)
}
async function ensureSkillCatalog(force = false): Promise<void> {
- return runOnce('skillCatalog', force, async () => {
- const res = await listSkillCatalog()
- skillCatalog.value = Array.isArray(res?.data) ? res.data : []
- loadedAt.value.skillCatalog = Date.now()
- })
+ return skillCatalogResource.ensure(force)
}
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()
- })
+ return agentTypePresetsResource.ensure(force)
}
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()
- })
+ return promptTemplatesResource.ensure(force)
}
async function ensurePlaceholders(force = false): Promise<void> {
- return runOnce('placeholders', force, async () => {
- const placeholdersRes = await getPlaceholders()
- placeholders.value = placeholdersRes?.data ?? null
- loadedAt.value.placeholders = Date.now()
- })
+ return placeholdersResource.ensure(force)
}
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()
- })
+ return tenantRetrievalConfigResource.ensure(force)
}
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()
- })
+ return parserEnginesResource.ensure(force)
}
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()
- })
+ return systemInfoResource.ensure(force)
}
/** 智能体编辑器打开时预取的依赖(不含 IM channels / 单 KB shares) */
@@ -249,15 +318,17 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
function invalidate(...keys: EditorResourceKey[]) {
if (keys.length === 0) {
- loadedAt.value = {}
+ ;(Object.keys(resources) as EditorResourceKey[]).forEach((k) => resources[k].invalidate())
storageConfig.value = null
storageStatus.value = []
storageAllowedProviders.value = []
mcpServices.value = []
mcpServicesScope.value = ''
+ mcpServicesRequestScope = { key: '' }
skills.value = []
skillsAvailable.value = false
skillsConfigId.value = ''
+ skillsRequestScope = { key: '', configId: '' }
skillCatalog.value = []
agentTypePresets.value = []
promptTemplates.value = null
@@ -265,13 +336,9 @@ export const useEditorResourcesStore = defineStore('editorResources', () => {
tenantRetrievalConfig.value = null
parserEngines.value = []
systemInfo.value = null
- inflight.clear()
return
}
- keys.forEach((k) => {
- delete loadedAt.value[k]
- inflight.delete(k)
- })
+ keys.forEach((k) => resources[k].invalidate())
}
return {
diff --git a/frontend/src/stores/localizedResourceCache.test.ts b/frontend/src/stores/localizedResourceCache.test.ts
index 341bd5a19..38d61b8aa 100644
--- a/frontend/src/stores/localizedResourceCache.test.ts
+++ b/frontend/src/stores/localizedResourceCache.test.ts
@@ -1,20 +1,16 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
- isLocalizedCacheFresh,
- shouldCommitLocalizedGeneration,
+ isLocalizedSnapshotUsable,
shouldForceLocalizedRefetch,
shouldReuseLocalizedInflight,
} from './localizedResourceCache.ts'
-const TTL_MS = 60_000
-
-test('localized cache is fresh only when TTL and request locale both match', () => {
- const loadedAt = 1_000
- assert.equal(isLocalizedCacheFresh(loadedAt, 'zh-CN', 'zh-CN', TTL_MS, 2_000), true)
- assert.equal(isLocalizedCacheFresh(loadedAt, 'zh-CN', 'en-US', TTL_MS, 2_000), false)
- assert.equal(isLocalizedCacheFresh(loadedAt, 'zh-CN', 'zh-CN', TTL_MS, loadedAt + TTL_MS), false)
- assert.equal(isLocalizedCacheFresh(0, 'zh-CN', 'zh-CN', TTL_MS, 2_000), false)
+test('localized snapshot is usable only for the locale it was fetched in', () => {
+ assert.equal(isLocalizedSnapshotUsable(true, 'zh-CN', 'zh-CN'), true)
+ assert.equal(isLocalizedSnapshotUsable(true, 'zh-CN', 'en-US'), false)
+ assert.equal(isLocalizedSnapshotUsable(false, 'zh-CN', 'zh-CN'), false)
+ assert.equal(isLocalizedSnapshotUsable(true, '', 'zh-CN'), false)
})
test('landing prefetch must not be reused after the UI language changes', () => {
@@ -28,16 +24,10 @@ test('landing prefetch must not be reused after the UI language changes', () =>
assert.equal(shouldReuseLocalizedInflight(true, '', 'en-US'), false)
})
-test('stamping the request locale keeps a late zh-CN payload from looking fresh for en-US', () => {
+test('stamping the request locale keeps a late zh-CN payload from looking usable for en-US', () => {
const requestLocale = 'zh-CN'
- const loadedAt = Date.now()
// Wrong (old bug): stamp getCurrentLanguage() after await → 'en-US'.
- assert.equal(isLocalizedCacheFresh(loadedAt, 'en-US', 'en-US', TTL_MS), true)
+ assert.equal(isLocalizedSnapshotUsable(true, 'en-US', 'en-US'), true)
// Correct: stamp the locale the HTTP call was started with.
- assert.equal(isLocalizedCacheFresh(loadedAt, requestLocale, 'en-US', TTL_MS), false)
-})
-
-test('a superseded generation must not write the cache', () => {
- assert.equal(shouldCommitLocalizedGeneration(1, 1), true)
- assert.equal(shouldCommitLocalizedGeneration(1, 2), false)
+ assert.equal(isLocalizedSnapshotUsable(true, requestLocale, 'en-US'), false)
})
diff --git a/frontend/src/stores/localizedResourceCache.ts b/frontend/src/stores/localizedResourceCache.ts
index bd16b7178..0e6b83922 100644
--- a/frontend/src/stores/localizedResourceCache.ts
+++ b/frontend/src/stores/localizedResourceCache.ts
@@ -1,20 +1,19 @@
/**
- * Helpers for short-TTL caches of API payloads that vary by Accept-Language
+ * Helpers for cached API payloads that vary by Accept-Language
* (built-in agent names/descriptions, shared-agent lists, …).
*
* The request must stamp the locale it was *started* with. Stamping
- * getCurrentLanguage() after await lets a zh-CN response be marked fresh for
- * en-US when the user switches language while the call is in flight.
+ * getCurrentLanguage() after await lets a zh-CN response be marked as the
+ * en-US snapshot when the user switches language while the call is in flight.
*/
-export function isLocalizedCacheFresh(
- loadedAt: number,
+/** A localized snapshot is only usable for the UI language it was fetched in. */
+export function isLocalizedSnapshotUsable(
+ loaded: boolean,
loadedLocale: string,
currentLocale: string,
- ttlMs: number,
- now = Date.now(),
): boolean {
- return loadedAt > 0 && now - loadedAt < ttlMs && loadedLocale === currentLocale
+ return loaded && loadedLocale !== '' && loadedLocale === currentLocale
}
/** Reuse an in-flight list request only when it was started for this UI language. */
@@ -38,11 +37,3 @@ export function shouldForceLocalizedRefetch(
): boolean {
return hasInflight && inflightLocale !== '' && inflightLocale !== currentLocale
}
-
-/** Drop a completed payload when a newer generation (or language switch) superseded it. */
-export function shouldCommitLocalizedGeneration(
- requestGen: number,
- currentGen: number,
-): boolean {
- return requestGen === currentGen
-}
diff --git a/frontend/src/stores/organization.ts b/frontend/src/stores/organization.ts
index ff88602bf..dfca6409e 100644
--- a/frontend/src/stores/organization.ts
+++ b/frontend/src/stores/organization.ts
@@ -45,10 +45,7 @@ import {
} from '@/api/organization'
import { getCurrentLanguage } from '@/utils/request'
import { createVersionedRequestCoordinator } from './versionedRequest'
-import {
- isLocalizedCacheFresh,
- shouldForceLocalizedRefetch,
-} from './localizedResourceCache'
+import { shouldForceLocalizedRefetch } from './localizedResourceCache'
import {
applyOrganizationResourceDelta,
upsertById,
@@ -69,14 +66,11 @@ export const useOrganizationStore = defineStore('organization', () => {
const error = ref<string | null>(null)
/** 各空间内知识库/智能体数量(由 GET /organizations 的 resource_counts 填充,供列表侧栏使用) */
const resourceCounts = ref<ResourceCountsByOrg | null>(null)
- /** 用于去重:同一时刻只允许一次 GET /organizations 请求 */
- let organizationsLoadedAt = 0
- /** 共享资源缓存 TTL,与 chatResources 对齐 */
- const SHARED_RESOURCE_TTL_MS = 60_000
+ // 组织 / 共享资源列表不设 TTL:每次 fetch 都发请求(并发共用同一个),
+ // 写操作后 `fetch({ force: true })` 排在飞行中的请求之后再拉一次。
+ // 输入联想的搜索结果例外,按查询串短期记忆,写操作时整体清空。
const SEARCHABLE_ORGANIZATION_TTL_MS = 5 * 60_000
- let sharedKbLoadedAt = 0
- let sharedAgentsLoadedAt = 0
- /** 共享智能体含按请求语言本地化的内置名称;切换 UI 语言后缓存随之失效 */
+ /** 共享智能体含按请求语言本地化的内置名称;切换 UI 语言后快照随之失效 */
let sharedAgentsLoadedLocale = ''
let sharedAgentsInflightLocale = ''
let searchableOrganizationsQuery = ''
@@ -105,7 +99,7 @@ export const useOrganizationStore = defineStore('organization', () => {
/**
* Fetch all organizations the user belongs to.
- * 去重 + 短期缓存,列表页与侧栏等多处共用。
+ * 并发去重,列表页与侧栏等多处共用。
*/
const organizationsRequest = createVersionedRequestCoordinator(
async () => {
@@ -121,7 +115,6 @@ 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'
@@ -130,20 +123,11 @@ export const useOrganizationStore = defineStore('organization', () => {
)
async function fetchOrganizations(options?: { force?: boolean }) {
- const force = options?.force ?? false
- if (
- !force &&
- organizationsLoadedAt > 0 &&
- Date.now() - organizationsLoadedAt < SHARED_RESOURCE_TTL_MS
- ) {
- return
- }
- return organizationsRequest.fetch(force)
+ return organizationsRequest.fetch(options?.force ?? false)
}
function patchOrganization(id: string, patch: Partial<Organization>) {
organizationsRequest.invalidate()
- organizationsLoadedAt = 0
organizations.value = organizations.value.map(org =>
org.id === id ? { ...org, ...patch } : org
)
@@ -154,7 +138,6 @@ export const useOrganizationStore = defineStore('organization', () => {
function upsertOrganization(organization: Organization) {
organizationsRequest.invalidate()
- organizationsLoadedAt = 0
organizations.value = upsertById(organizations.value, organization)
if (currentOrganization.value?.id === organization.id) {
currentOrganization.value = organization
@@ -167,7 +150,6 @@ export const useOrganizationStore = defineStore('organization', () => {
*/
function mergeOrganizationDetail(organization: Organization) {
organizationsRequest.invalidate()
- organizationsLoadedAt = 0
const next = mergeById(organizations.value, organization)
organizations.value = next
currentOrganization.value =
@@ -180,7 +162,6 @@ export const useOrganizationStore = defineStore('organization', () => {
delta: number
) {
organizationsRequest.invalidate()
- organizationsLoadedAt = 0
const result = applyOrganizationResourceDelta(
organizations.value,
resourceCounts.value,
@@ -206,9 +187,7 @@ export const useOrganizationStore = defineStore('organization', () => {
const response = await createOrganization({ name, description, avatar })
if (response.success && response.data) {
upsertOrganization(response.data)
- // 创建成功后重置缓存时间戳,确保后续 fetchOrganizations() 不会被 TTL 缓存跳过,
- // 从而刷新 resource_counts 等创建接口不返回的聚合字段。
- organizationsLoadedAt = 0
+ // 创建接口不返回 resource_counts 等聚合字段,强刷一次列表补齐。
void fetchOrganizations({ force: true })
return response.data
} else {
@@ -261,7 +240,6 @@ export const useOrganizationStore = defineStore('organization', () => {
const response = await deleteOrganization(id)
if (response.success) {
organizationsRequest.invalidate()
- organizationsLoadedAt = 0
organizations.value = organizations.value.filter(o => o.id !== id)
if (currentOrganization.value?.id === id) {
currentOrganization.value = null
@@ -338,7 +316,6 @@ export const useOrganizationStore = defineStore('organization', () => {
const response = await leaveOrganization(id)
if (response.success) {
organizationsRequest.invalidate()
- organizationsLoadedAt = 0
organizations.value = organizations.value.filter(o => o.id !== id)
if (currentOrganization.value?.id === id) {
currentOrganization.value = null
@@ -459,7 +436,7 @@ export const useOrganizationStore = defineStore('organization', () => {
/**
* Fetch shared knowledge bases.
- * 去重 + 短期缓存,避免对话页等多处并发重复请求。
+ * 并发去重,避免对话页等多处同时重复请求。
*/
const sharedKnowledgeBasesRequest = createVersionedRequestCoordinator(
async () => {
@@ -474,7 +451,6 @@ export const useOrganizationStore = defineStore('organization', () => {
(response) => {
if (response.success && response.data) {
sharedKnowledgeBases.value = response.data.filter(s => s.knowledge_base != null)
- sharedKbLoadedAt = Date.now()
} else {
error.value = response.message || 'Failed to fetch shared knowledge bases'
}
@@ -482,21 +458,13 @@ export const useOrganizationStore = defineStore('organization', () => {
)
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
- }
- await sharedKnowledgeBasesRequest.fetch(force)
+ await sharedKnowledgeBasesRequest.fetch(options?.force ?? false)
return sharedKnowledgeBases.value
}
/**
* Fetch shared agents (shared to me through organizations).
- * 去重 + 短期缓存。
+ * 并发去重;快照只对拉取时的 UI 语言有效。
*/
const sharedAgentsRequest = createVersionedRequestCoordinator(
async () => {
@@ -508,7 +476,6 @@ export const useOrganizationStore = defineStore('organization', () => {
({ response, locale }) => {
if (response.success && response.data) {
sharedAgents.value = response.data.filter(s => s.agent != null)
- sharedAgentsLoadedAt = Date.now()
sharedAgentsLoadedLocale = locale
}
}
@@ -519,7 +486,6 @@ export const useOrganizationStore = defineStore('organization', () => {
(locale) => {
if (sharedAgentsLoadedLocale && sharedAgentsLoadedLocale !== locale) {
sharedAgentsRequest.invalidate()
- sharedAgentsLoadedAt = 0
sharedAgentsLoadedLocale = ''
sharedAgentsInflightLocale = ''
}
@@ -529,17 +495,7 @@ export const useOrganizationStore = defineStore('organization', () => {
async function fetchSharedAgents(options?: { force?: boolean }) {
const locale = getCurrentLanguage()
const force = options?.force ?? false
- if (
- !force &&
- isLocalizedCacheFresh(
- sharedAgentsLoadedAt,
- sharedAgentsLoadedLocale,
- locale,
- SHARED_RESOURCE_TTL_MS,
- )
- ) {
- return sharedAgents.value
- }
+ // 飞行中的请求是用另一种语言发起的:不能复用它,排在它后面再发一次。
const mustForce =
force ||
shouldForceLocalizedRefetch(
@@ -571,15 +527,12 @@ export const useOrganizationStore = defineStore('organization', () => {
function invalidateOrganizationData(options: InvalidateOrganizationDataOptions) {
if (options.organizations) {
organizationsRequest.invalidate()
- organizationsLoadedAt = 0
}
if (options.sharedKnowledgeBases) {
sharedKnowledgeBasesRequest.invalidate()
- sharedKbLoadedAt = 0
}
if (options.sharedAgents) {
sharedAgentsRequest.invalidate()
- sharedAgentsLoadedAt = 0
sharedAgentsLoadedLocale = ''
sharedAgentsInflightLocale = ''
}
@@ -834,11 +787,8 @@ export const useOrganizationStore = defineStore('organization', () => {
resourceCounts.value = null
previewData.value = null
error.value = null
- sharedKbLoadedAt = 0
- sharedAgentsLoadedAt = 0
sharedAgentsLoadedLocale = ''
sharedAgentsInflightLocale = ''
- organizationsLoadedAt = 0
searchableOrganizationsQuery = ''
searchableOrganizationCache.clear()
organizationsRequest.invalidate()
diff --git a/frontend/src/stores/resourceCache.test.ts b/frontend/src/stores/resourceCache.test.ts
new file mode 100644
index 000000000..27a0edaf3
--- /dev/null
+++ b/frontend/src/stores/resourceCache.test.ts
@@ -0,0 +1,156 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { createCachedResource, createKeyedSnapshotCache } from './resourceCache.ts'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
+test('concurrent ensure calls share one request; a later ensure issues a new one', async () => {
+ const calls: Array<ReturnType<typeof deferred<number>>> = []
+ const applied: number[] = []
+ const resource = createCachedResource(
+ () => {
+ const d = deferred<number>()
+ calls.push(d)
+ return d.promise
+ },
+ (v) => applied.push(v),
+ )
+
+ const a = resource.ensure()
+ const b = resource.ensure()
+ assert.equal(calls.length, 1, 'mount burst is deduplicated')
+ calls[0].resolve(1)
+ await Promise.all([a, b])
+ assert.deepEqual(applied, [1])
+ assert.equal(resource.isLoaded(), true)
+
+ // No TTL: the next ensure after the first one settled fetches again.
+ const c = resource.ensure()
+ assert.equal(calls.length, 2)
+ calls[1].resolve(2)
+ await c
+ assert.deepEqual(applied, [1, 2])
+})
+
+test('invalidate discards the in-flight response and the next ensure waits for a fresh one', async () => {
+ const calls: Array<ReturnType<typeof deferred<number>>> = []
+ const applied: number[] = []
+ const resource = createCachedResource(
+ () => {
+ const d = deferred<number>()
+ calls.push(d)
+ return d.promise
+ },
+ (v) => applied.push(v),
+ )
+
+ const stale = resource.ensure()
+ resource.invalidate()
+ const fresh = resource.ensure()
+ assert.equal(calls.length, 1, 'fresh request is queued behind the in-flight one')
+ calls[0].resolve(1)
+ await stale
+ assert.deepEqual(applied, [], 'stale response is not applied')
+ assert.equal(calls.length, 2)
+ calls[1].resolve(2)
+ await fresh
+ assert.deepEqual(applied, [2])
+ assert.equal(resource.isLoaded(), true)
+})
+
+test('markLoaded keeps an older in-flight response from overwriting the replaced snapshot', async () => {
+ const calls: Array<ReturnType<typeof deferred<number>>> = []
+ const applied: number[] = []
+ const resource = createCachedResource(
+ () => {
+ const d = deferred<number>()
+ calls.push(d)
+ return d.promise
+ },
+ (v) => applied.push(v),
+ )
+
+ const inflight = resource.ensure()
+ resource.markLoaded()
+ calls[0].resolve(1)
+ await inflight
+ assert.deepEqual(applied, [])
+ assert.equal(resource.isLoaded(), true)
+})
+
+test('keyed snapshot cache loads each key once until invalidated', async () => {
+ let loads = 0
+ const cache = createKeyedSnapshotCache(async (key: string) => {
+ loads += 1
+ return `${key}:${loads}`
+ })
+
+ const [a, b] = await Promise.all([cache.ensure('kb1'), cache.ensure('kb1')])
+ assert.equal(a, 'kb1:1')
+ assert.equal(b, 'kb1:1')
+ assert.equal(await cache.ensure('kb1'), 'kb1:1', 'snapshot reused without a request')
+ assert.equal(loads, 1)
+
+ cache.invalidate('kb1')
+ assert.equal(await cache.ensure('kb1'), 'kb1:2')
+ assert.equal(await cache.ensure('kb1', true), 'kb1:3', 'force bypasses the snapshot')
+})
+
+test('keyed snapshot: a response that lands after invalidate is not written back', async () => {
+ const pending = new Map<string, ReturnType<typeof deferred<string>>>()
+ let seq = 0
+ const cache = createKeyedSnapshotCache((key: string) => {
+ const d = deferred<string>()
+ pending.set(`${key}#${++seq}`, d)
+ return d.promise
+ })
+
+ // Sidebar read in flight; the editor saves, invalidates and forces a fresh read.
+ const stale = cache.ensure('kb1')
+ cache.invalidate('kb1')
+ const fresh = cache.ensure('kb1', true)
+ assert.equal(pending.size, 2)
+
+ pending.get('kb1#2')!.resolve('saved')
+ assert.equal(await fresh, 'saved')
+ pending.get('kb1#1')!.resolve('before-save')
+ assert.equal(await stale, 'before-save', 'caller of the stale read still gets its value')
+
+ // The snapshot must be the post-save detail, so a later non-force read is correct.
+ assert.equal(await cache.ensure('kb1'), 'saved')
+ assert.equal(pending.size, 2, 'served from snapshot')
+})
+
+test('keyed snapshot: a force read overlapping an in-flight read wins regardless of order', async () => {
+ const pending: Array<ReturnType<typeof deferred<string>>> = []
+ const cache = createKeyedSnapshotCache((_key: string) => {
+ const d = deferred<string>()
+ pending.push(d)
+ return d.promise
+ })
+
+ const first = cache.ensure('kb1')
+ const forced = cache.ensure('kb1', true)
+ pending[1].resolve('fresh')
+ pending[0].resolve('old')
+ await Promise.all([first, forced])
+ assert.equal(await cache.ensure('kb1'), 'fresh')
+
+ // invalidate() without a key must also fence every in-flight read.
+ const late = cache.ensure('kb2')
+ cache.invalidate()
+ pending[2].resolve('kb2-stale')
+ await late
+ const reloaded = cache.ensure('kb2')
+ assert.equal(pending.length, 4, 'kb2 is reloaded rather than served from the stale write')
+ pending[3].resolve('kb2-fresh')
+ assert.equal(await reloaded, 'kb2-fresh')
+})
diff --git a/frontend/src/stores/resourceCache.ts b/frontend/src/stores/resourceCache.ts
new file mode 100644
index 000000000..beffc0d55
--- /dev/null
+++ b/frontend/src/stores/resourceCache.ts
@@ -0,0 +1,111 @@
+import { createVersionedRequestCoordinator } from './versionedRequest'
+
+/**
+ * 空间级资源的读取原语。不设 TTL:
+ *
+ * - `ensure()`:同一资源同一时刻只有一个请求在飞行,并发调用共用它;没有在飞行的
+ * 就发一个新请求。返回的 Promise 在最新数据写入 store 后才 resolve,所以
+ * `await ensure()` 之后读到的一定是本次请求的结果,而不是旧快照。
+ * - `ensure(true)`:写操作之后调用。若此刻有请求在飞行,会在其结束后再发一次,
+ * 保证拿到的是写操作之后的数据。
+ * - `invalidate()`:丢弃快照并让飞行中的旧响应作废;下一次 `ensure()` 必然发新请求。
+ * - `markLoaded()`:调用方已经用别的接口拿到了最新列表并写回 store(如设置页
+ * `replaceModels`),把飞行中的旧请求作废,避免它把旧数据写回来。
+ *
+ * 旧快照仍然留在 store 的 ref 里供页面立即渲染;数据的新鲜度只由「是否刚发过请求」
+ * 和显式失效决定,不再有 60s 内一律读缓存的窗口。
+ */
+export interface CachedResource {
+ ensure: (force?: boolean) => Promise<void>
+ invalidate: () => void
+ markLoaded: () => void
+ isLoaded: () => boolean
+ hasInFlightRequest: () => boolean
+}
+
+export function createCachedResource<T>(
+ request: () => Promise<T>,
+ apply: (value: T) => void,
+): CachedResource {
+ let loaded = false
+ // invalidate 之后若仍有旧请求在飞行,下一次 ensure 必须排在它之后重新发,
+ // 否则调用方会 await 到一个结果已被作废的 Promise。
+ let needsFreshRequest = false
+
+ const coordinator = createVersionedRequestCoordinator(request, (value) => {
+ apply(value)
+ loaded = true
+ })
+
+ return {
+ ensure(force = false) {
+ const mustForce = force || needsFreshRequest
+ needsFreshRequest = false
+ return coordinator.fetch(mustForce)
+ },
+ invalidate() {
+ loaded = false
+ coordinator.invalidate()
+ needsFreshRequest = coordinator.hasInFlightRequest()
+ },
+ markLoaded() {
+ coordinator.invalidate()
+ needsFreshRequest = false
+ loaded = true
+ },
+ isLoaded: () => loaded,
+ hasInFlightRequest: () => coordinator.hasInFlightRequest(),
+ }
+}
+
+/**
+ * 按 key 缓存的单条资源(知识库详情、智能体可见知识库等)。
+ * 这类数据不随每次 ensure 重新拉取:拿到过就一直用,直到显式失效。
+ * 调用方在循环里逐条 ensure(如 @ 提及列表补 count),不能每次都打接口。
+ */
+export function createKeyedSnapshotCache<T>(load: (key: string) => Promise<T>) {
+ const snapshots = new Map<string, T>()
+ const inflight = new Map<string, { promise: Promise<T>; revision: number }>()
+ // 每个 key 一个代际;invalidate / force 都会推进它。请求返回时代际已变,
+ // 说明中途发生过失效或有更新的请求,这次响应只交给调用方,不落快照。
+ const revisions = new Map<string, number>()
+
+ const bump = (key: string) => {
+ const next = (revisions.get(key) ?? 0) + 1
+ revisions.set(key, next)
+ return next
+ }
+
+ return {
+ async ensure(key: string, force = false): Promise<T> {
+ if (!force && snapshots.has(key)) return snapshots.get(key) as T
+ const existing = inflight.get(key)
+ if (existing && !force) return existing.promise
+ const revision = force ? bump(key) : (revisions.get(key) ?? 0)
+ const promise = (async () => {
+ try {
+ const value = await load(key)
+ const stillCurrent = (revisions.get(key) ?? 0) === revision
+ // 加载失败以 null 表示时不落快照,下次读取会重试。
+ if (stillCurrent && value != null) snapshots.set(key, value)
+ return value
+ } finally {
+ if (inflight.get(key)?.revision === revision) inflight.delete(key)
+ }
+ })()
+ inflight.set(key, { promise, revision })
+ return promise
+ },
+ invalidate(key?: string) {
+ if (key === undefined) {
+ for (const k of new Set([...snapshots.keys(), ...inflight.keys()])) bump(k)
+ snapshots.clear()
+ inflight.clear()
+ return
+ }
+ bump(key)
+ snapshots.delete(key)
+ inflight.delete(key)
+ },
+ }
+}
diff --git a/frontend/src/stores/sequencedRefresh.test.ts b/frontend/src/stores/sequencedRefresh.test.ts
new file mode 100644
index 000000000..79d055c74
--- /dev/null
+++ b/frontend/src/stores/sequencedRefresh.test.ts
@@ -0,0 +1,81 @@
+import assert from 'node:assert/strict'
+import test from 'node:test'
+import { createSequencedRefresh } from './sequencedRefresh.ts'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason?: unknown) => void
+ const promise = new Promise<T>((res, rej) => {
+ resolve = res
+ reject = rej
+ })
+ return { promise, resolve, reject }
+}
+
+function setup() {
+ const calls: Array<{ d: ReturnType<typeof deferred<string>>; isCurrent: () => boolean }> = []
+ const applied: string[] = []
+ const sequencer = createSequencedRefresh<boolean>(async (isCurrent) => {
+ const d = deferred<string>()
+ calls.push({ d, isCurrent })
+ const value = await d.promise
+ if (!isCurrent()) return false
+ applied.push(value)
+ return true
+ })
+ return { calls, applied, sequencer }
+}
+
+test('share reuses the in-flight request; refresh waits for a request issued after the call', async () => {
+ const { calls, applied, sequencer } = setup()
+
+ const first = sequencer.share()
+ const shared = sequencer.share()
+ assert.equal(calls.length, 1)
+
+ // A write happened while the first request was in flight: its response is
+ // pre-change, so refresh must not settle on it.
+ const refreshed = sequencer.refresh()
+ const refreshedAgain = sequencer.refresh()
+ assert.equal(calls.length, 1, 'the fresh request is queued behind the in-flight one')
+
+ calls[0].d.resolve('before-write')
+ assert.deepEqual([await first, await shared], [true, true])
+ assert.deepEqual(applied, ['before-write'])
+ assert.equal(calls.length, 2, 'queued refresh started after the first settled')
+
+ calls[1].d.resolve('after-write')
+ assert.deepEqual([await refreshed, await refreshedAgain], [true, true])
+ assert.deepEqual(applied, ['before-write', 'after-write'])
+ assert.equal(sequencer.hasInFlightRequest(), false)
+})
+
+test('a response that arrives after invalidate (logout) is not applied', async () => {
+ const { calls, applied, sequencer } = setup()
+
+ const late = sequencer.share()
+ sequencer.invalidate()
+ calls[0].d.resolve('stale-session')
+ assert.equal(await late, false)
+ assert.deepEqual(applied, [])
+
+ // The next read is a fresh request under the new revision.
+ const next = sequencer.share()
+ assert.equal(calls.length, 2)
+ calls[1].d.resolve('new-session')
+ assert.equal(await next, true)
+ assert.deepEqual(applied, ['new-session'])
+})
+
+test('a queued refresh still runs when the in-flight request rejects', async () => {
+ const { calls, applied, sequencer } = setup()
+
+ const failing = sequencer.share()
+ const refreshed = sequencer.refresh()
+ calls[0].d.reject(new Error('network'))
+ await assert.rejects(failing)
+ assert.equal(calls.length, 2)
+ calls[1].d.resolve('recovered')
+ assert.equal(await refreshed, true)
+ assert.deepEqual(applied, ['recovered'])
+})
diff --git a/frontend/src/stores/sequencedRefresh.ts b/frontend/src/stores/sequencedRefresh.ts
new file mode 100644
index 000000000..42938ff1d
--- /dev/null
+++ b/frontend/src/stores/sequencedRefresh.ts
@@ -0,0 +1,60 @@
+/**
+ * 「刷新」语义的请求排序器(/auth/me 这类单例读取用)。
+ *
+ * - `refresh()`:结果必须来自本次调用之后发出的请求。已有请求在飞行时,
+ * 排一个新请求在它之后,多次并发的 refresh 共用同一个排队请求。
+ * - `share()`:只要有请求在飞行就直接复用,否则发一个新的。首屏多个消费者
+ * 同时要同一份数据时用它。
+ * - `invalidate()`:让飞行中的请求作废。`run` 拿到的 `isCurrent()` 在 await 之后
+ * 返回 false,调用方据此跳过落库;登出时用,避免迟到的响应把会话写回来。
+ */
+export interface SequencedRefresh<T> {
+ refresh: () => Promise<T>
+ share: () => Promise<T>
+ invalidate: () => void
+ hasInFlightRequest: () => boolean
+}
+
+export function createSequencedRefresh<T>(
+ run: (isCurrent: () => boolean) => Promise<T>,
+): SequencedRefresh<T> {
+ let revision = 0
+ let inflight: Promise<T> | null = null
+ let queued: Promise<T> | null = null
+
+ const start = (): Promise<T> => {
+ const requestRevision = revision
+ const current = run(() => requestRevision === revision).finally(() => {
+ if (inflight === current) inflight = null
+ })
+ inflight = current
+ return current
+ }
+
+ const refresh = (): Promise<T> => {
+ if (!inflight) return start()
+ if (!queued) {
+ const waitingFor = inflight
+ queued = waitingFor.then(
+ () => {
+ queued = null
+ return start()
+ },
+ () => {
+ queued = null
+ return start()
+ },
+ )
+ }
+ return queued
+ }
+
+ return {
+ refresh,
+ share: () => inflight ?? start(),
+ invalidate: () => {
+ revision += 1
+ },
+ hasInFlightRequest: () => inflight !== null,
+ }
+}
diff --git a/frontend/src/utils/tenantModelReadiness.ts b/frontend/src/utils/tenantModelReadiness.ts
index 4f94116ee..dc1ed0ba6 100644
--- a/frontend/src/utils/tenantModelReadiness.ts
+++ b/frontend/src/utils/tenantModelReadiness.ts
@@ -1,4 +1,4 @@
-import { listModels, type ModelConfig } from '@/api/model'
+import type { ModelConfig } from '@/api/model'
export interface TenantModelReadiness {
chatCount: number
@@ -25,12 +25,3 @@ export function evaluateTenantModelReadiness(models: ModelConfig[]): TenantModel
isReadyForAgent: hasChat,
}
}
-
-export async function fetchTenantModelReadiness(): Promise<TenantModelReadiness> {
- try {
- const models = await listModels()
- return evaluateTenantModelReadiness(models || [])
- } catch {
- return evaluateTenantModelReadiness([])
- }
-}
diff --git a/frontend/src/views/integrations/ApiIntegrationSettings.vue b/frontend/src/views/integrations/ApiIntegrationSettings.vue
index eefb9c01e..be86209b9 100644
--- a/frontend/src/views/integrations/ApiIntegrationSettings.vue
+++ b/frontend/src/views/integrations/ApiIntegrationSettings.vue
@@ -675,8 +675,9 @@ import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import { DialogPlugin, MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { copyWithToast } from '@/utils/clipboard'
-import { getCurrentUser } from '@/api/auth'
-import { listAgents, BUILTIN_SMART_REASONING_ID, type CustomAgent } from '@/api/agent'
+import { BUILTIN_SMART_REASONING_ID, type CustomAgent } from '@/api/agent'
+import { useAuthStore } from '@/stores/auth'
+import { useChatResourcesStore } from '@/stores/chatResources'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
import {
createTenantAPIKey,
@@ -691,7 +692,6 @@ import {
type TenantAPIKey,
type TenantAPIKeyCapability,
} from '@/api/tenant'
-import { listKnowledgeBases } from '@/api/knowledge-base'
import { getApiBaseUrl } from '@/utils/api-base'
import {
DEFAULT_TENANT_API_KEY_CAPABILITIES,
@@ -712,6 +712,8 @@ const DEFAULT_TOKEN_HEADER_NAME = 'X-External-User-Token'
const loading = ref(true)
const saving = ref(false)
const error = ref('')
+const authStore = useAuthStore()
+const chatResources = useChatResourcesStore()
const tenantId = ref(0)
const apiKey = ref('')
const config = ref<APIPrincipalConfig | null>(null)
@@ -1130,15 +1132,14 @@ async function load() {
loading.value = true
error.value = ''
try {
- const [userResp] = await Promise.all([
- getCurrentUser(),
- loadAgents(),
- ])
- const tenant = (userResp as any)?.data?.tenant
- if (!tenant?.id) {
+ // 当前生效空间就是每个请求 X-Tenant-ID 指向的空间,auth store 里已有,
+ // 不必再为拿一个 id 打一次 /auth/me。
+ await loadAgents()
+ const activeTenantId = authStore.effectiveTenantId
+ if (!activeTenantId) {
throw new Error(t('integrations.api.loadFailed'))
}
- tenantId.value = Number(tenant.id)
+ tenantId.value = Number(activeTenantId)
await Promise.all([
loadAPIKeys(),
loadKnowledgeBaseOptions(),
@@ -1187,9 +1188,8 @@ async function loadAPIKeys() {
async function loadKnowledgeBaseOptions() {
knowledgeBasesLoading.value = true
try {
- const resp: any = await listKnowledgeBases({ creator: 'all' })
- const rows = Array.isArray(resp?.data) ? resp.data : []
- knowledgeBases.value = rows.map((item: any) => ({
+ await chatResources.ensureKnowledgeBases()
+ knowledgeBases.value = chatResources.rawKnowledgeBases.map((item: any) => ({
id: String(item.id),
name: item.name || item.id,
}))
@@ -1204,8 +1204,8 @@ async function loadAgents() {
agentsLoading.value = true
agentsError.value = ''
try {
- const resp = await listAgents({ creator: 'all' }) as any
- agents.value = Array.isArray(resp?.data) ? resp.data : []
+ await chatResources.ensureAgents()
+ agents.value = chatResources.agents as CustomAgent[]
ensurePlaygroundAgent()
} catch (err: any) {
agentsError.value = err?.message || t('integrations.api.playgroundAgentsLoadFailed')
diff --git a/frontend/src/views/integrations/McpServerIntegrationSettings.vue b/frontend/src/views/integrations/McpServerIntegrationSettings.vue
index 0cd607a47..8bcc16ef6 100644
--- a/frontend/src/views/integrations/McpServerIntegrationSettings.vue
+++ b/frontend/src/views/integrations/McpServerIntegrationSettings.vue
@@ -260,8 +260,8 @@ import { useAuthStore } from '@/stores/auth'
import { copyWithToast } from '@/utils/clipboard'
import { useApiBaseUrlDisplay } from '@/composables/useApiBaseUrlDisplay'
import SettingDrawer from '@/components/settings/SettingDrawer.vue'
-import { listAgents, type CustomAgent } from '@/api/agent'
-import { listKnowledgeBases } from '@/api/knowledge-base'
+import type { CustomAgent } from '@/api/agent'
+import { useChatResourcesStore } from '@/stores/chatResources'
import {
createMcpEndpoint,
deleteMcpEndpoint,
@@ -283,6 +283,7 @@ import {
const { t } = useI18n()
const authStore = useAuthStore()
+const chatResources = useChatResourcesStore()
const { apiBaseUrlDisplay } = useApiBaseUrlDisplay()
const isAdmin = computed(() => authStore.hasRole('admin'))
@@ -398,13 +399,16 @@ async function loadOptions() {
kbLoading.value = true
agentsLoading.value = true
try {
- const [kbRes, agentRes] = await Promise.all([
- listKnowledgeBases({ creator: 'all' }).catch(() => null),
- listAgents().catch(() => null),
+ // 刷新失败时给空列表,而不是把上一次的共享快照当成本次结果展示。
+ const [kbResult, agentResult] = await Promise.allSettled([
+ chatResources.ensureKnowledgeBases(),
+ chatResources.ensureAgents(),
])
- const kbRows = ((kbRes as any)?.data ?? []) as Array<{ id: string | number; name?: string }>
+ const kbRows = kbResult.status === 'fulfilled'
+ ? (chatResources.rawKnowledgeBases as Array<{ id: string | number; name?: string }>)
+ : []
knowledgeBases.value = kbRows.map((kb) => ({ id: String(kb.id), name: kb.name || String(kb.id) }))
- agents.value = ((agentRes as any)?.data ?? []) as CustomAgent[]
+ agents.value = agentResult.status === 'fulfilled' ? (chatResources.agents as CustomAgent[]) : []
} finally {
kbLoading.value = false
agentsLoading.value = false
diff --git a/frontend/src/views/knowledge/components/FAQEntryManager.vue b/frontend/src/views/knowledge/components/FAQEntryManager.vue
index b322a8e03..77144fb1d 100644
--- a/frontend/src/views/knowledge/components/FAQEntryManager.vue
+++ b/frontend/src/views/knowledge/components/FAQEntryManager.vue
@@ -766,6 +766,7 @@ import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { useOrganizationStore } from '@/stores/organization'
+import { useChatResourcesStore } from '@/stores/chatResources'
import {
listFAQEntries,
upsertFAQEntries,
@@ -778,7 +779,6 @@ import {
listKnowledgeTags,
updateFAQEntryTagBatch,
getKnowledgeBaseById,
- listKnowledgeBases,
getFAQImportProgress,
updateFAQImportResultDisplayStatus,
} from '@/api/knowledge-base'
@@ -835,6 +835,7 @@ const router = useRouter()
const uiStore = useUIStore()
const authStore = useAuthStore()
const orgStore = useOrganizationStore()
+const chatResources = useChatResourcesStore()
// Permission control: check if current user owns this KB or has edit/manage permission.
//
@@ -1009,8 +1010,8 @@ const loadKnowledgeInfo = async (kbId: string) => {
const loadKnowledgeList = async () => {
try {
- const res: any = await listKnowledgeBases()
- const myKbs: typeof knowledgeList.value = (res?.data || []).map((item: any) => ({
+ await chatResources.ensureKnowledgeBases()
+ const myKbs: typeof knowledgeList.value = chatResources.rawKnowledgeBases.map((item: any) => ({
id: String(item.id),
name: item.name,
type: item.type,
diff --git a/frontend/src/views/settings/SystemInfo.vue b/frontend/src/views/settings/SystemInfo.vue
index 8e6c93c31..78188eca8 100644
--- a/frontend/src/views/settings/SystemInfo.vue
+++ b/frontend/src/views/settings/SystemInfo.vue
@@ -196,13 +196,15 @@
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
-import { getSystemInfo, type SystemInfo } from '@/api/system'
+import type { SystemInfo } from '@/api/system'
+import { useEditorResourcesStore } from '@/stores/editorResources'
import { useI18n } from 'vue-i18n'
import { docsUrl } from '@/utils/docsUrl'
const { t, locale } = useI18n()
// Reactive state
+const editorResources = useEditorResourcesStore()
const systemInfo = ref<SystemInfo | null>(null)
const loading = ref(true)
const error = ref('')
@@ -283,10 +285,11 @@ const loadInfo = async () => {
loading.value = true
error.value = ''
- const systemResponse = await getSystemInfo()
-
- if (systemResponse.data) {
- systemInfo.value = systemResponse.data
+ // 设置面板每次打开都要最新值;侧栏启动时拉过的快照走同一个 store。
+ await editorResources.ensureSystemInfo(true)
+
+ if (editorResources.systemInfo) {
+ systemInfo.value = editorResources.systemInfo
} else {
error.value = t('system.messages.fetchFailed')
}
diff --git a/frontend/src/views/settings/WebSearchSettings.vue b/frontend/src/views/settings/WebSearchSettings.vue
index 12e16f61b..5010602bf 100644
--- a/frontend/src/views/settings/WebSearchSettings.vue
+++ b/frontend/src/views/settings/WebSearchSettings.vue
@@ -312,7 +312,6 @@ import { MessagePlugin } from 'tdesign-vue-next'
import { useI18n } from 'vue-i18n'
import { AddIcon } from 'tdesign-icons-vue-next'
import {
- listWebSearchProviders,
listWebSearchProviderTypes,
createWebSearchProvider,
updateWebSearchProvider,
@@ -331,10 +330,12 @@ import CredentialResource, {
} from '@/components/credentials/CredentialResource.vue'
import { useConfirmDelete } from '@/components/settings/useConfirmDelete'
import { useAuthStore } from '@/stores/auth'
+import { useChatResourcesStore } from '@/stores/chatResources'
import { providerLogo } from './providerLogos'
const { t } = useI18n()
const authStore = useAuthStore()
+const chatResources = useChatResourcesStore()
const confirmDelete = useConfirmDelete()
// ===== State =====
@@ -506,12 +507,12 @@ const onProviderTypeChange = () => {
lastTestOk.value = null
}
+// 走 chatResources 的共享快照并强刷:增删改之后对话输入栏读到的就是最新列表,
+// 不需要它再监听设置弹窗关闭去重拉。
const loadProviderEntities = async () => {
try {
- const response = await listWebSearchProviders()
- if (response.data && Array.isArray(response.data)) {
- providerEntities.value = response.data
- }
+ await chatResources.ensureWebSearchProviders(true)
+ providerEntities.value = chatResources.webSearchProviders
} catch (error) {
console.error('Failed to load provider entities:', error)
}
diff --git a/frontend/src/views/system/ModelCatalog.vue b/frontend/src/views/system/ModelCatalog.vue
index cad8ca822..b64868db5 100644
--- a/frontend/src/views/system/ModelCatalog.vue
+++ b/frontend/src/views/system/ModelCatalog.vue
@@ -462,8 +462,9 @@ async function commit(overlay: CatalogOverlay, message = t('modelCatalog.publish
try {
state.value = await publishModelCatalog({ version: state.value.version, baseline: state.value.baseline, overlay })
providersStore.reset()
- // Model responses contain resolved catalog capabilities as well.
- chatResources.invalidate('models')
+ // Model responses contain resolved catalog capabilities as well. The
+ // chat input only loads models on mount, so refetch the snapshot now.
+ void chatResources.ensureModels(true).catch(() => {})
MessagePlugin.success(message)
return true
} catch (e: any) {