🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
🐛 fix(agent-profile): keep bound tools until the tool catalogs load (#20797)
YuTengjing76cd52c0a382
diff --git a/src/features/ProfileEditor/AgentTool.tsx b/src/features/ProfileEditor/AgentTool.tsxindex 0e7ae1b1fc2..23a61399bb2 100644--- a/src/features/ProfileEditor/AgentTool.tsx+++ b/src/features/ProfileEditor/AgentTool.tsx@@ -44,7 +44,7 @@ import { connectorSelectors } from '@/store/tool/slices/connector';import PluginTag from './PluginTag';import PopoverContent from './PopoverContent';import { getVisibleProfileToolIds } from './profileToolVisibility';-import { resolveStalePluginCleanup } from './staleProfilePlugins';+import { resolveStalePluginCleanup, selectProfileToolCatalogsSynced } from './staleProfilePlugins';export interface AgentToolProps {/**@@ -202,6 +202,11 @@ const AgentTool = memo<AgentToolProps>([agentConnectors, excludeAgentConnectors],);const isConnectorsInit = useToolStore((s) => s.isConnectorsInit);+ const isToolStoreCatalogSynced = useToolStore(selectProfileToolCatalogsSynced);+ // Not `serverConfigInit`: it is also set by the error fallback, whose default+ // config hides the Composio and LobeHub Skill catalogs.+ const isServerConfigLoaded = useServerConfigStore((s) => s.serverConfigLoaded);+ const isToolCatalogSynced = isToolStoreCatalogSynced && isServerConfigLoaded;const fetchConnectors = useToolStore((s) => s.fetchConnectors);useEffect(() => {if (!isConnectorsInit) fetchConnectors();@@ -785,18 +790,19 @@ const AgentTool = memo<AgentToolProps>(// Track whether initial cleanup has been performedconst cleanupDoneRef = useRef(false);- // Auto-remove stale plugin IDs from the agent config- // Uses a short debounce to allow async data (SWR) to complete loading+ // Auto-remove stale plugin IDs from the agent config. The catalog gates+ // decide when the data is complete; the debounce only coalesces the burst+ // of catalog updates that arrive together.useEffect(() => {if (cleanupDoneRef.current) return;- // Defer cleanup to avoid race with async data loading (SWR, Composio, etc.)const timer = setTimeout(() => {const cleanedPlugins = resolveStalePluginCleanup({canEditContent: canEdit,canEditResource,isAccessResolved,isConnectorsInit,+ isToolCatalogSynced,plugins: config?.plugins,validIdentifiers,});@@ -817,7 +823,14 @@ const AgentTool = memo<AgentToolProps>(return () => clearTimeout(timer);// eslint-disable-next-line react-hooks/exhaustive-deps- }, [validIdentifiers, canEdit, canEditResource, isAccessResolved, isConnectorsInit]);+ }, [+ validIdentifiers,+ canEdit,+ canEditResource,+ isAccessResolved,+ isConnectorsInit,+ isToolCatalogSynced,+ ]);// Only display tools that this profile surface actually manages. Runtime-// managed entries remain untouched in config for compatibility with otherdiff --git a/src/features/ProfileEditor/staleProfilePlugins.test.ts b/src/features/ProfileEditor/staleProfilePlugins.test.tsindex 5a10a8d4990..4f0a1c6c9eb 100644--- a/src/features/ProfileEditor/staleProfilePlugins.test.ts+++ b/src/features/ProfileEditor/staleProfilePlugins.test.ts@@ -1,12 +1,23 @@import { describe, expect, it } from 'vitest';-import { resolveStalePluginCleanup, type StalePluginCleanupInput } from './staleProfilePlugins';+import { initialState, type ToolStoreState } from '@/store/tool/initialState';+import { AGENT_SKILL_LIST_KEY } from '@/store/tool/slices/agentSkills/projection';+import { UNINSTALLED_BUILTIN_TOOLS_KEY } from '@/store/tool/slices/builtin/projection';+import { CONNECTOR_LIST_KEY } from '@/store/tool/slices/connector/projection';+import { INSTALLED_PLUGINS_KEY } from '@/store/tool/slices/plugin/projection';++import {+ resolveStalePluginCleanup,+ selectProfileToolCatalogsSynced,+ type StalePluginCleanupInput,+} from './staleProfilePlugins';const baseInput = (overrides: Partial<StalePluginCleanupInput> = {}): StalePluginCleanupInput => ({canEditContent: true,canEditResource: true,isAccessResolved: true,isConnectorsInit: true,+ isToolCatalogSynced: true,plugins: ['web-search', 'ghost-tool'],validIdentifiers: new Set(['web-search']),...overrides,@@ -39,6 +50,21 @@ describe('resolveStalePluginCleanup', () => {expect(resolveStalePluginCleanup(baseInput({ isConnectorsInit: false }))).toBeNull();});+ // https://github.com/lobehub/lobehub/issues/18856 — on a cold start the+ // installed-plugin list is still empty when the connectors load, so a bound+ // custom tool looked stale and the profile saved `plugins: []`.+ it('returns null while the tool catalogs are still loading', () => {+ expect(+ resolveStalePluginCleanup(+ baseInput({+ isToolCatalogSynced: false,+ plugins: ['web-search', 'my-custom-tool'],+ validIdentifiers: new Set(['web-search']),+ }),+ ),+ ).toBeNull();+ });+it('returns null when no identifiers are known yet', () => {expect(resolveStalePluginCleanup(baseInput({ validIdentifiers: new Set() }))).toBeNull();});@@ -72,3 +98,91 @@ describe('resolveStalePluginCleanup', () => {});});});++describe('selectProfileToolCatalogsSynced', () => {+ type Source = 'local' | 'server' | 'storage';++ const entry = (source: Source) => ({ data: [], source }) as any;++ const stateWith = (sources: {+ agentSkills?: Source;+ connectors?: Source;+ installedPlugins?: Source;+ uninstalledBuiltinTools?: Source;+ }): ToolStoreState =>+ ({+ ...initialState,+ agentSkillListReplica: {+ ...initialState.agentSkillListReplica,+ entries: sources.agentSkills ? { [AGENT_SKILL_LIST_KEY]: entry(sources.agentSkills) } : {},+ },+ connectorsReplica: {+ ...initialState.connectorsReplica,+ entries: sources.connectors ? { [CONNECTOR_LIST_KEY]: entry(sources.connectors) } : {},+ },+ installedPluginsReplica: {+ ...initialState.installedPluginsReplica,+ entries: sources.installedPlugins+ ? { [INSTALLED_PLUGINS_KEY]: entry(sources.installedPlugins) }+ : {},+ },+ uninstalledBuiltinToolsReplica: {+ ...initialState.uninstalledBuiltinToolsReplica,+ entries: sources.uninstalledBuiltinTools+ ? { [UNINSTALLED_BUILTIN_TOOLS_KEY]: entry(sources.uninstalledBuiltinTools) }+ : {},+ },+ }) as ToolStoreState;++ it('is true once every catalog holds the server response', () => {+ expect(+ selectProfileToolCatalogsSynced(+ stateWith({+ agentSkills: 'server',+ connectors: 'server',+ installedPlugins: 'server',+ uninstalledBuiltinTools: 'server',+ }),+ ),+ ).toBe(true);+ });++ // `isConnectorsInit` is already true after the IndexedDB hydrate, so a+ // connector bound on another device would look stale until the server list lands.+ it('is false while the connector list only holds its persisted IndexedDB copy', () => {+ expect(+ selectProfileToolCatalogsSynced(+ stateWith({+ agentSkills: 'server',+ connectors: 'storage',+ installedPlugins: 'server',+ uninstalledBuiltinTools: 'server',+ }),+ ),+ ).toBe(false);+ });++ it('is false on a cold start before the installed plugins load', () => {+ expect(+ selectProfileToolCatalogsSynced(+ stateWith({ agentSkills: 'server', uninstalledBuiltinTools: 'server' }),+ ),+ ).toBe(false);+ });++ it('is false while a catalog only holds its persisted IndexedDB copy', () => {+ expect(+ selectProfileToolCatalogsSynced(+ stateWith({+ agentSkills: 'server',+ installedPlugins: 'storage',+ uninstalledBuiltinTools: 'server',+ }),+ ),+ ).toBe(false);+ });++ it('is false before the agent skills or builtin tool state loads', () => {+ expect(selectProfileToolCatalogsSynced(stateWith({ installedPlugins: 'server' }))).toBe(false);+ });+});diff --git a/src/features/ProfileEditor/staleProfilePlugins.ts b/src/features/ProfileEditor/staleProfilePlugins.tsindex 035ff929e34..6741d023077 100644--- a/src/features/ProfileEditor/staleProfilePlugins.ts+++ b/src/features/ProfileEditor/staleProfilePlugins.ts@@ -1,5 +1,27 @@import { type AgentPluginEntry, parsePluginEntry } from '@lobechat/types';+import type { ToolStoreState } from '@/store/tool/initialState';+import { AGENT_SKILL_LIST_KEY } from '@/store/tool/slices/agentSkills/projection';+import { UNINSTALLED_BUILTIN_TOOLS_KEY } from '@/store/tool/slices/builtin/projection';+import { CONNECTOR_LIST_KEY } from '@/store/tool/slices/connector/projection';+import { INSTALLED_PLUGINS_KEY } from '@/store/tool/slices/plugin/projection';++/**+ * Whether every asynchronously loaded catalog that feeds `validIdentifiers`+ * holds the server's answer. An unloaded catalog is empty, and a catalog+ * hydrated from IndexedDB can predate a tool installed on another device, so+ * pruning against either would delete valid tools and persist the loss. This+ * includes custom connectors: `isConnectorsInit` already turns true on the+ * IndexedDB hydrate, before the server list arrives.+ *+ * @see https://github.com/lobehub/lobehub/issues/18856+ */+export const selectProfileToolCatalogsSynced = (s: ToolStoreState): boolean =>+ s.installedPluginsReplica.entries[INSTALLED_PLUGINS_KEY]?.source === 'server' &&+ s.connectorsReplica.entries[CONNECTOR_LIST_KEY]?.source === 'server' &&+ s.uninstalledBuiltinToolsReplica.entries[UNINSTALLED_BUILTIN_TOOLS_KEY]?.source === 'server' &&+ s.agentSkillListReplica.entries[AGENT_SKILL_LIST_KEY]?.source === 'server';+export interface StalePluginCleanupInput {/*** Workspace role permits editing own content (`edit_own_content`). Personal@@ -22,6 +44,14 @@ export interface StalePluginCleanupInput {* connectors as stale.*/isConnectorsInit: boolean;+ /**+ * Installed plugins, custom connectors, installed builtin tools and agent+ * skills have all been loaded from the server+ * (`selectProfileToolCatalogsSynced`), and the server config that decides the+ * connector catalog has loaded successfully. Until then a+ * valid custom tool is missing from `validIdentifiers`.+ */+ isToolCatalogSynced: boolean;plugins: AgentPluginEntry[] | undefined;validIdentifiers: ReadonlySet<string>;}@@ -45,11 +75,12 @@ export const resolveStalePluginCleanup = ({canEditResource,isAccessResolved,isConnectorsInit,+ isToolCatalogSynced,plugins,validIdentifiers,}: StalePluginCleanupInput): AgentPluginEntry[] | null => {if (!canEditContent || !isAccessResolved || !canEditResource) return null;- if (!isConnectorsInit) return null;+ if (!isConnectorsInit || !isToolCatalogSynced) return null;if (validIdentifiers.size === 0) return null;const rawPlugins = plugins ?? [];diff --git a/src/store/serverConfig/action.test.ts b/src/store/serverConfig/action.test.tsindex da148cf6c18..9ea46958980 100644--- a/src/store/serverConfig/action.test.ts+++ b/src/store/serverConfig/action.test.ts@@ -79,6 +79,7 @@ describe('ServerConfigAction', () => {expect(state.serverConfig).toBeDefined();expect(state.featureFlags).toBeDefined();expect(state.canAccessDevDock).toBe(true);+ expect(state.serverConfigLoaded).toBe(true);});it('should mark server config as initialized when the fetch fails', () => {@@ -90,6 +91,9 @@ describe('ServerConfigAction', () => {store.getState().useInitServerConfig();expect(store.getState().serverConfigInit).toBe(true);+ // The fallback is not a loaded config: consumers that prune data+ // against server-gated catalogs must keep waiting.+ expect(store.getState().serverConfigLoaded).toBe(false);expect(store.getState().serverConfig).toEqual({ aiProvider: {}, telemetry: {} });expect(store.getState().canAccessDevDock).toBe(false);});diff --git a/src/store/serverConfig/action.ts b/src/store/serverConfig/action.tsindex b2c0c51adbe..17d8aed893b 100644--- a/src/store/serverConfig/action.ts+++ b/src/store/serverConfig/action.ts@@ -50,6 +50,7 @@ export class ServerConfigActionImpl {featureFlags: data.serverFeatureFlags,serverConfig: data.serverConfig,serverConfigInit: true,+ serverConfigLoaded: true,},false,'initServerConfig',diff --git a/src/store/serverConfig/store.ts b/src/store/serverConfig/store.tsindex 463f45a05ba..1124e4e32c7 100644--- a/src/store/serverConfig/store.ts+++ b/src/store/serverConfig/store.ts@@ -33,6 +33,12 @@ interface ServerConfigState {segmentVariants?: string;serverConfig: GlobalServerConfig;serverConfigInit: boolean;+ /**+ * The global config request succeeded. `serverConfigInit` also turns true on+ * the error fallback, where `serverConfig` keeps its defaults and every+ * server-gated feature reads as disabled.+ */+ serverConfigLoaded: boolean;}const initialState: ServerConfigState = {@@ -44,6 +50,7 @@ const initialState: ServerConfigState = {segmentVariants: '',serverConfig: { aiProvider: {}, telemetry: {} },serverConfigInit: false,+ serverConfigLoaded: false,};// =============== Aggregate createStoreFn ============ //