π€― 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(connector): finish legacy MCP migrations before refreshing lists (#23550)
AmAzing-22bf75369503
diff --git a/src/features/Connectors/CustomConnectorModal/index.tsx b/src/features/Connectors/CustomConnectorModal/index.tsxindex 9483df109ab..38ace316d6d 100644--- a/src/features/Connectors/CustomConnectorModal/index.tsx+++ b/src/features/Connectors/CustomConnectorModal/index.tsx@@ -19,7 +19,6 @@ import { waitForConnectorOAuth } from '@/utils/connectorOAuth';import { executeOAuthCreate } from '@/utils/connectorOAuthCreate';import { saveConnectorEdit } from './connectorEdit';-import { executeLegacyMigrationSave } from './legacyPluginMigration';import { saveOAuthConnectorEdit } from './oauthEdit';import {countDroppedAccounts,@@ -93,6 +92,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(({ open, onClose, connectorId, legacyPlugin, onEditSuccess, visibility }) => {const { t } = useTranslation('tool');const createConnector = useToolStore((s) => s.createConnector);+ const migrateLegacyPlugin = useToolStore((s) => s.migrateLegacyPlugin);const deleteConnector = useToolStore((s) => s.deleteConnector);const getConnectorForEdit = useToolStore((s) => s.getConnectorForEdit);const startConnectorOAuth = useToolStore((s) => s.startConnectorOAuth);@@ -289,18 +289,7 @@ const CustomConnectorModal = memo<CustomConnectorModalProps>(// `value` is the full form state β DevModal seeded itself from// `legacyPlugin` via `editValue`, so anything the user edited (or left// alone) is already inside `value`. Hand it to the orchestrator.- const result = await executeLegacyMigrationSave(legacyPlugin, value, {- // The migration orchestrator predates the server-reported `isNew`- // and still keys its rollback on `hasExistingConnector` below.- createConnector: async (payload) => (await createConnector(payload)).id,- deleteConnector,- // Read fresh so the rollback only deletes a connector this migration- // created, never one the idempotent upsert merely updated.- hasExistingConnector: (id) =>- Boolean(connectorSelectors.connectorByIdentifier(id)(useToolStore.getState())),- syncConnectorTools,- uninstallCustomPlugin,- });+ const result = await migrateLegacyPlugin(legacyPlugin, value);if (!result.ok) {throw new Error(result.reason === 'no-mcp'diff --git a/src/features/Settings/skill/features/SkillDetail/index.tsx b/src/features/Settings/skill/features/SkillDetail/index.tsxindex 0ad5efea0db..d6cbeb0a758 100644--- a/src/features/Settings/skill/features/SkillDetail/index.tsx+++ b/src/features/Settings/skill/features/SkillDetail/index.tsx@@ -506,13 +506,9 @@ const SkillDetail = memo<SkillDetailProps>(({ identifier, type, onDelete, visibilegacyPlugin={legacyPlugin}open={migrateOpen}onClose={() => setMigrateOpen(false)}- onEditSuccess={async () => {+ onEditSuccess={() => {setMigrateOpen(false);setNoManifest(false);- // The migration created a `user_connectors` row keyed by the same- // identifier; refresh so this panel resolves it and swaps to the- // permission editor.- await fetchConnectors();}}/>)}diff --git a/src/store/tool/slices/connector/action.legacyMigration.test.ts b/src/store/tool/slices/connector/action.legacyMigration.test.tsnew file mode 100644index 00000000000..3c138d13854--- /dev/null+++ b/src/store/tool/slices/connector/action.legacyMigration.test.ts@@ -0,0 +1,121 @@+import type { LobeToolCustomPlugin } from '@lobechat/types';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { lambdaClient } from '@/libs/trpc/client';++import { useToolStore } from '../../store';+import { initialConnectorState } from './initialState';++vi.mock('@/libs/trpc/client', () => ({+ lambdaClient: {+ connector: {+ create: { mutate: vi.fn() },+ delete: { mutate: vi.fn() },+ list: { query: vi.fn() },+ listAgentBound: { query: vi.fn() },+ syncTools: { mutate: vi.fn() },+ syncToolsFromClientById: { mutate: vi.fn() },+ },+ market: {+ getMcpManifest: { query: vi.fn(async () => ({ tools: [{ name: 'search' }] })) },+ },+ plugin: {+ getPlugins: { query: vi.fn() },+ removePlugin: { mutate: vi.fn() },+ },+ },+}));++const legacy = {+ customParams: { mcp: { type: 'http', url: 'https://example.com/mcp' } },+ identifier: 'legacy',+ type: 'customPlugin',+} satisfies LobeToolCustomPlugin;++describe('legacy MCP migration with the connector and plugin stores', () => {+ const { connector, plugin } = lambdaClient;++ beforeEach(() => {+ useToolStore.setState({+ ...initialConnectorState,+ installedPlugins: [legacy],+ isAgentBoundInit: true,+ isConnectorsInit: true,+ isInstalledPluginsInit: true,+ });+ vi.mocked(connector.create.mutate).mockResolvedValue({ id: 'created', isNew: true });+ vi.mocked(connector.list.query).mockResolvedValue([]);+ vi.mocked(connector.listAgentBound.query).mockResolvedValue([]);+ vi.mocked(plugin.getPlugins.query).mockResolvedValue([]);+ });++ afterEach(() => {+ vi.resetAllMocks();+ vi.restoreAllMocks();+ });++ it('finishes the save and removes the legacy plugin while list reads are pending', async () => {+ const refresh = Promise.withResolvers<[]>();+ vi.mocked(connector.list.query).mockReturnValue(refresh.promise);+ vi.mocked(connector.listAgentBound.query).mockReturnValue(refresh.promise);+ vi.mocked(plugin.getPlugins.query).mockReturnValue(refresh.promise);+ const completed = vi.fn();+ const save = useToolStore.getState().migrateLegacyPlugin(legacy, legacy).then(completed);+ try {+ await vi.waitFor(() =>+ expect(completed).toHaveBeenCalledWith({ connectorId: 'created', ok: true }),+ );+ expect(plugin.removePlugin.mutate).toHaveBeenCalledWith({ id: 'legacy' });+ expect(useToolStore.getState().installedPlugins).toEqual([]);+ expect(connector.syncTools.mutate).toHaveBeenCalledWith({ id: 'created' });+ expect(connector.list.query).toHaveBeenCalledTimes(1);+ expect(connector.listAgentBound.query).toHaveBeenCalledTimes(1);+ expect(plugin.getPlugins.query).toHaveBeenCalledTimes(1);+ } finally {+ refresh.resolve([]);+ await save;+ }+ });++ it('keeps a synced connector when the list refresh fails', async () => {+ const readError = new Error('list read failed');+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});+ vi.mocked(connector.list.query).mockRejectedValue(readError);+ await expect(+ useToolStore.getState().migrateLegacyPlugin(legacy, legacy),+ ).resolves.toMatchObject({ ok: true });+ await vi.waitFor(() =>+ expect(log).toHaveBeenCalledWith('[connector-migration] refreshing lists failed', readError),+ );+ expect(connector.delete.mutate).not.toHaveBeenCalled();+ expect(plugin.removePlugin.mutate).toHaveBeenCalledWith({ id: 'legacy' });+ });++ it('syncs a cloud manifest from the saved transport before the connector is in the list', async () => {+ const cloud = {+ ...legacy,+ customParams: { mcp: { type: 'cloud', url: 'https://example.com/mcp' } },+ } satisfies LobeToolCustomPlugin;+ await useToolStore.getState().migrateLegacyPlugin(cloud, cloud);+ expect(connector.syncToolsFromClientById.mutate).toHaveBeenCalledWith({+ id: 'created',+ tools: [expect.objectContaining({ toolName: 'search' })],+ });+ expect(connector.syncTools.mutate).not.toHaveBeenCalled();+ expect(plugin.removePlugin.mutate).toHaveBeenCalledWith({ id: 'legacy' });+ });++ it.each([true, false])(+ 'uses the server upsert result on sync failure (isNew=%s)',+ async (isNew) => {+ vi.mocked(connector.create.mutate).mockResolvedValue({ id: 'target', isNew });+ vi.mocked(connector.syncTools.mutate).mockRejectedValue(new Error('endpoint unreachable'));+ await expect(useToolStore.getState().migrateLegacyPlugin(legacy, legacy)).rejects.toThrow(+ 'endpoint unreachable',+ );+ if (isNew) expect(connector.delete.mutate).toHaveBeenCalledWith({ id: 'target' });+ else expect(connector.delete.mutate).not.toHaveBeenCalled();+ expect(plugin.removePlugin.mutate).not.toHaveBeenCalled();+ },+ );+});diff --git a/src/store/tool/slices/connector/action.ts b/src/store/tool/slices/connector/action.tsindex 5135424b99b..317fca485f4 100644--- a/src/store/tool/slices/connector/action.ts+++ b/src/store/tool/slices/connector/action.ts@@ -1,4 +1,5 @@import { isDesktop } from '@lobechat/const';+import type { LobeToolCustomPlugin } from '@lobechat/types';import {connectorDeviceBinding,connectorMcpEndpoint,@@ -26,6 +27,7 @@ import type { StoreSetter } from '@/store/types';import { ConnectorOAuthError, waitForConnectorOAuth } from '@/utils/connectorOAuth';import type { ToolStore } from '../../store';+import { executeLegacyMigrationSave } from './legacyPluginMigration';import {agentBoundConnectorsEntity,agentBoundConnectorsResource,@@ -431,6 +433,17 @@ export class ConnectorActionImpl {}};+ migrateLegacyPlugin = (legacy: LobeToolCustomPlugin, value: LobeToolCustomPlugin) =>+ executeLegacyMigrationSave(legacy, value, {+ createConnector: (payload) => lambdaClient.connector.create.mutate(payload),+ deleteConnector: this.#deleteConnectorRecord,+ refreshLists: async () => {+ await Promise.all([this.#refreshConnectorLists(), this.#get().refreshPlugins()]);+ },+ syncConnectorTools: (id, payload) => this.#writeConnectorTools(id, {}, payload),+ uninstallCustomPlugin: (identifier) => this.#get().removeInstalledPluginRecord(identifier),+ });+/** Connect an additional account and refresh all connector lists after authorization. */connectConnectorAccount = (connectorId: string,@@ -559,9 +572,13 @@ export class ConnectorActionImpl {* removal is confirmed rather than optimistic.*/deleteConnector = async (id: string): Promise<void> => {+ await this.#deleteConnectorRecord(id);+ await this.#refreshConnectorLists();+ };++ #deleteConnectorRecord = async (id: string): Promise<void> => {await lambdaClient.connector.delete.mutate({ id });this.#connectorRows.remove(id);- await this.#refreshConnectorLists();};updateConnector = async (@@ -606,10 +623,11 @@ export class ConnectorActionImpl {'syncConnectorTools/start',);try {- const synced =- (await this.#syncCloudConnectorTools(id, options)) ||- (await this.#syncLocalConnectorTools(id, options));- if (!synced) await lambdaClient.connector.syncTools.mutate({ id, ...options });+ await this.#writeConnectorTools(+ id,+ options,+ connectorSelectors.connectorById(id)(this.#get()),+ );await this.#refreshConnectorLists();} finally {this.#set(@@ -620,26 +638,30 @@ export class ConnectorActionImpl {}};- /**- * A market-hosted (`cloud`) server has no endpoint to list tools from: the- * market serves them in the server's manifest. Returns false for any other- * connector.- */- #syncCloudConnectorTools = async (+ #writeConnectorTools = async (id: string,options: { pruneMissingAutoTools?: boolean },- ): Promise<boolean> => {- const connector = connectorSelectors.connectorById(id)(this.#get());- if (connector?.mcpConnectionType !== 'cloud') return false;+ connector: Pick<ConnectorWithTools, 'identifier' | 'mcpConnectionType'> | undefined,+ ): Promise<void> => {+ if (connector?.mcpConnectionType === 'cloud') {+ await this.#syncCloudConnectorTools(id, options, connector.identifier);+ } else if (!(await this.#syncLocalConnectorTools(id, options))) {+ await lambdaClient.connector.syncTools.mutate({ id, ...options });+ }+ };- const { identifier } = connector;+ /** A market-hosted connector lists its tools in the market manifest. */+ #syncCloudConnectorTools = async (+ id: string,+ options: { pruneMissingAutoTools?: boolean },+ identifier: string,+ ): Promise<void> => {const data = await discoverService.getMCPPluginManifest(identifier);await lambdaClient.connector.syncToolsFromClientById.mutate({id,...options,tools: cloudManifestTools(buildCloudMcpManifest({ data, plugin: { identifier } })),});- return true;};/**diff --git a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts b/src/store/tool/slices/connector/legacyPluginMigration.test.tssimilarity index 98%rename from src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.tsrename to src/store/tool/slices/connector/legacyPluginMigration.test.tsindex 329cecbd25b..44614f9901e 100644--- a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.test.ts+++ b/src/store/tool/slices/connector/legacyPluginMigration.test.ts@@ -392,7 +392,7 @@ describe('executeLegacyMigrationSave', () => {let createConnector: Mock<MigrationSaveDeps['createConnector']>;let deleteConnector: Mock<MigrationSaveDeps['deleteConnector']>;- let hasExistingConnector: Mock<MigrationSaveDeps['hasExistingConnector']>;+ const refreshLists = vi.fn<MigrationSaveDeps['refreshLists']>();let syncConnectorTools: Mock<MigrationSaveDeps['syncConnectorTools']>;let uninstallCustomPlugin: Mock<MigrationSaveDeps['uninstallCustomPlugin']>;let calls: string[];@@ -401,7 +401,7 @@ describe('executeLegacyMigrationSave', () => {const getMigrationDeps = (): MigrationSaveDeps => ({createConnector,deleteConnector,- hasExistingConnector,+ refreshLists,syncConnectorTools,uninstallCustomPlugin,});@@ -410,13 +410,12 @@ describe('executeLegacyMigrationSave', () => {calls = [];createConnector = vi.fn<MigrationSaveDeps['createConnector']>(async () => {calls.push('createConnector');- return 'new-conn-id';+ return { id: 'new-conn-id', isNew: true };});deleteConnector = vi.fn<MigrationSaveDeps['deleteConnector']>(async () => {calls.push('deleteConnector');});- // Default: no pre-existing connector (the common fresh-migration case).- hasExistingConnector = vi.fn<MigrationSaveDeps['hasExistingConnector']>(() => false);+ refreshLists.mockReset().mockResolvedValue(undefined);syncConnectorTools = vi.fn<MigrationSaveDeps['syncConnectorTools']>(async () => {calls.push('syncConnectorTools');});@@ -521,7 +520,7 @@ describe('executeLegacyMigrationSave', () => {// UPDATED, not created. A transient sync failure must not delete it β// that would destroy a working connector's synced tools/credentials (e.g. a// prior successful migration whose best-effort legacy uninstall had failed).- hasExistingConnector.mockReturnValue(true);+ createConnector.mockResolvedValueOnce({ id: 'existing', isNew: false });syncConnectorTools.mockRejectedValueOnce(new Error('mcp tools/list timeout'));await expect(executeLegacyMigrationSave(legacy(), legacy(), getMigrationDeps()),diff --git a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts b/src/store/tool/slices/connector/legacyPluginMigration.tssimilarity index 64%rename from src/features/Connectors/CustomConnectorModal/legacyPluginMigration.tsrename to src/store/tool/slices/connector/legacyPluginMigration.tsindex 1959520f67f..c1a29d6168c 100644--- a/src/features/Connectors/CustomConnectorModal/legacyPluginMigration.ts+++ b/src/store/tool/slices/connector/legacyPluginMigration.ts@@ -133,43 +133,12 @@ export const buildConnectorPayloadFromLegacy = (legacy: LobeToolCustomPlugin): M};};-/**- * Orchestrate the legacy β connector save flow. Sequence matters:- *- * 1. Build payload from legacy shape; reject early on broken data.- * 2. `createConnector` β server is idempotent on `(user_id, identifier)` so- * a half-baked marketplace connector from the old `syncPluginTools` path- * becomes an UPDATE, no client-side collision branch needed.- * 3. `syncConnectorTools` β fail-loud. On failure (the MCP endpoint is- * unreachable / 500s), ROLL BACK the connector β but only when step 2- * actually CREATED it (see `hasExistingConnector`), never when it merely- * updated a pre-existing row. Leaving a freshly-created one behind would- * strand the user: the tool-less- * connector now shadows the legacy row, so it renders as a duplicate in- * the connector list AND `connectorByIdentifier` starts resolving it,- * which removes the "Configure to migrate" entry point (that only shows- * when no connector exists). Rolling back returns us atomically to the- * pre-migration state β legacy row only β so the user can retry once the- * endpoint is healthy (create is rebuilt from the untouched legacy shape).- * 4. `uninstallCustomPlugin` β best-effort. A throw is logged but swallowed;- * the runtime's `connectorIdentifierSet` filter in- * `aiAgent/index.ts:1717` dedupes by identifier (connector wins), so a- * lingering legacy row is harmless and the next save retries cleanup.- *- * Returning the validation failure inline (vs throwing) lets the modal show a- * friendly toast distinct from a network error.- */export interface MigrationSaveDeps {- createConnector: (payload: MigrationCreatePayload) => Promise<string>;+ createConnector: (payload: MigrationCreatePayload) => Promise<{ id: string; isNew: boolean }>;deleteConnector: (id: string) => Promise<void>;- /**- * Whether a `user_connectors` row already exists for this identifier BEFORE- * the create call. `createConnector` is an idempotent upsert, so on the sync- * failure path we must NOT delete a row we merely updated β only one we created.- */- hasExistingConnector: (identifier: string) => boolean;- syncConnectorTools: (id: string) => Promise<void>;- uninstallCustomPlugin: (id: string) => Promise<void>;+ refreshLists: () => Promise<void>;+ syncConnectorTools: (id: string, payload: MigrationCreatePayload) => Promise<void>;+ uninstallCustomPlugin: (identifier: string) => Promise<void>;}export type MigrationSaveResult =@@ -196,39 +165,33 @@ export const executeLegacyMigrationSave = async (identifier: legacyPlugin.identifier,};- // Capture pre-existence BEFORE the upsert so the rollback below only ever- // deletes a connector THIS migration created (see MigrationSaveDeps).- const connectorAlreadyExisted = deps.hasExistingConnector(payload.identifier);-- const newConnectorId = await deps.createConnector(payload);+ const { id, isNew } = await deps.createConnector(payload);try {- await deps.syncConnectorTools(newConnectorId);- } catch (syncError) {- // Endpoint unreachable / manifest fetch failed. Roll the just-created- // connector back so we don't leave a tool-less duplicate alongside the- // surviving legacy plugin (see step 3 above), then rethrow so the modal- // surfaces the failure and the legacy row stays as the single source.- //- // Skip rollback when a connector already existed for this identifier: the- // upsert UPDATED that row (it did not create one), so deleting it would- // destroy a working connector's synced tools/credentials β e.g. a prior- // successful migration whose best-effort legacy uninstall had failed.- if (!connectorAlreadyExisted) {- try {- await deps.deleteConnector(newConnectorId);- } catch (rollbackError) {- console.error('[connector-migration] rollback after failed sync failed', rollbackError);+ try {+ await deps.syncConnectorTools(id, payload);+ } catch (error) {+ // The server owns the upsert decision. A cached list may omit a connector+ // that was already installed before this attempt.+ if (isNew) {+ await deps.deleteConnector(id).catch((rollbackError) => {+ console.error('[connector-migration] rollback after failed sync failed', rollbackError);+ });}+ throw error;}- throw syncError;- }- try {- await deps.uninstallCustomPlugin(legacyPlugin.identifier);- } catch (e) {- console.error('[connector-migration] uninstall legacy plugin failed', e);+ // Keep the synced connector if legacy cleanup fails (connector-first runtime).+ await deps.uninstallCustomPlugin(legacyPlugin.identifier).catch((error) => {+ console.error('[connector-migration] uninstall legacy plugin failed', error);+ });++ return { connectorId: id, ok: true };+ } finally {+ // Refresh only after the writes finish. A stalled list must neither hold+ // the save open nor turn a successful tool sync into a rollback.+ void deps.refreshLists().catch((error) => {+ console.error('[connector-migration] refreshing lists failed', error);+ });}-- return { connectorId: newConnectorId, ok: true };};diff --git a/src/store/tool/slices/plugin/action.ts b/src/store/tool/slices/plugin/action.tsindex 9cb1e66c177..457b1e23d36 100644--- a/src/store/tool/slices/plugin/action.ts+++ b/src/store/tool/slices/plugin/action.ts@@ -124,10 +124,13 @@ export class PluginActionImpl {* plugin again.*/uninstallPlugin = async (identifier: string): Promise<void> => {+ await this.removeInstalledPluginRecord(identifier);+ await this.#get().refreshPlugins();+ };++ removeInstalledPluginRecord = async (identifier: string): Promise<void> => {await pluginService.uninstallPlugin(identifier);this.#installedPlugins.removeEntity(identifier);-- await this.#get().refreshPlugins();};updateInstallLoadingState = (id: string, loading: boolean | undefined): void => {