From bdd41f92d64018e196aa48379dc4427570ab50ec Mon Sep 17 00:00:00 2001 From: zerob13 Date: Thu, 26 Nov 2026 22:15:44 +0800 Subject: [PATCH 1/2] fix(mcp): scope plugin switches to selected agent Refs #2550 --- .../mcp-config/components/McpServerCard.vue | 5 +- .../mcp-config/components/McpServers.vue | 3 ++ .../src/features/mcp/McpSettingsView.vue | 21 +++++--- .../src/pages/plugins/McpPluginsPage.vue | 5 ++ .../components/McpSettings.isolation.test.ts | 53 ++++++++++++++++++- 5 files changed, 76 insertions(+), 11 deletions(-) diff --git a/src/renderer/src/components/mcp-config/components/McpServerCard.vue b/src/renderer/src/components/mcp-config/components/McpServerCard.vue index 81d176c11c..07b6768ce5 100644 --- a/src/renderer/src/components/mcp-config/components/McpServerCard.vue +++ b/src/renderer/src/components/mcp-config/components/McpServerCard.vue @@ -41,6 +41,7 @@ interface Props { isManaged?: boolean isLoading?: boolean disabled?: boolean + toggleDisabled?: boolean toolsCount?: number promptsCount?: number resourcesCount?: number @@ -281,9 +282,9 @@ watch(watchDescription, () => { {{ t('settings.mcp.authenticate') }} diff --git a/src/renderer/src/components/mcp-config/components/McpServers.vue b/src/renderer/src/components/mcp-config/components/McpServers.vue index 4cab674ce6..6750a4611e 100644 --- a/src/renderer/src/components/mcp-config/components/McpServers.vue +++ b/src/renderer/src/components/mcp-config/components/McpServers.vue @@ -631,6 +631,9 @@ defineExpose({ mcpStore.serverLoadingStates[server.name] || props.serverLoadingOverrides[server.name] " :disabled="mcpStore.configLoading || (props.agentScopedToggle && props.agentScopedBusy)" + :toggle-disabled=" + props.agentScopedToggle && (server.enabled === false || server.disable) + " :tools-count="getServerToolsCount(server.name)" :prompts-count="getServerPromptsCount(server.name)" :resources-count="getServerResourcesCount(server.name)" diff --git a/src/renderer/src/features/mcp/McpSettingsView.vue b/src/renderer/src/features/mcp/McpSettingsView.vue index d3f87f909a..53a0504573 100644 --- a/src/renderer/src/features/mcp/McpSettingsView.vue +++ b/src/renderer/src/features/mcp/McpSettingsView.vue @@ -42,11 +42,20 @@ {{ t('routes.settings-mcp-market') }} + + {{ t('chat.input.mcp.openSettings') }} + @@ -279,6 +288,7 @@ const props = withDefaults( const emit = defineEmits<{ 'agent-policy-saved': [agentId: string] + 'open-global-settings': [] 'open-market': [] 'close-market': [] 'continue-onboarding': [state: GuidedOnboardingState | null] @@ -350,12 +360,9 @@ const isDeepChatTarget = computed(() => ) const globallyAvailableServerIds = computed(() => normalizeList( - mcpStore.serverList - .filter((server) => { - const config = mcpStore.config.mcpServers[server.name] - return config?.enabled !== false && !config?.disable - }) - .map((server) => server.name) + Object.entries(mcpStore.config.mcpServers) + .filter(([, config]) => config.enabled !== false && !config.disable) + .map(([name]) => name) ) ) const agentEnabledMcpServerIds = computed(() => targetAgentConfig.value.enabledMcpServerIds) diff --git a/src/renderer/src/pages/plugins/McpPluginsPage.vue b/src/renderer/src/pages/plugins/McpPluginsPage.vue index 26d5c9a267..63837a7a50 100644 --- a/src/renderer/src/pages/plugins/McpPluginsPage.vue +++ b/src/renderer/src/pages/plugins/McpPluginsPage.vue @@ -1,6 +1,9 @@ diff --git a/src/renderer/src/pages/plugins/UserPluginDetails.vue b/src/renderer/src/pages/plugins/UserPluginDetails.vue index df4405b0af..02876ae642 100644 --- a/src/renderer/src/pages/plugins/UserPluginDetails.vue +++ b/src/renderer/src/pages/plugins/UserPluginDetails.vue @@ -6,6 +6,7 @@ import { DcButton } from '@dc-ui/components/button' import { Input } from '@shadcn/components/ui/input' import { DcConfirmDialog } from '@dc-ui/components/confirm-dialog' import { createPluginClient } from '@api/PluginClient' +import { createSettingsClient } from '@api/SettingsClient' import { usePluginCatalogStore } from '@/stores/pluginCatalog' import type { PluginListItem, PluginActionResult } from '@shared/types/plugin' import UserPluginInstallDialog from './UserPluginInstallDialog.vue' @@ -14,6 +15,7 @@ const props = defineProps<{ plugin: PluginListItem }>() const { t } = useI18n() const router = useRouter() const client = createPluginClient() +const settingsClient = createSettingsClient() const catalog = usePluginCatalogStore() const details = computed(() => props.plugin.userPlugin!) const updateOpen = ref(false) @@ -204,9 +206,12 @@ async function retry(invocationId: string): Promise { > - {{ - t('settings.userPlugins.manageMcp') - }} + {{ t('settings.userPlugins.manageMcp') }} { ) }) - it('routes MCP imports through the chat window IPC', async () => { + it('opens MCP imports in global settings with the server configuration', async () => { const deeplinkService = await createDeeplinkService() - const chatWindow = { - id: 1, - isDestroyed: () => false, - isMinimized: () => false, - show: vi.fn(), - focus: vi.fn(), - webContents: { - isLoadingMainFrame: () => false, - once: vi.fn() - } - } const payload = { mcpServers: { demo: { @@ -194,14 +183,14 @@ describe('DeeplinkService', () => { } } const url = `deepchat://mcp/install?code=${Buffer.from(JSON.stringify(payload)).toString('base64')}` - presenterMock.windowPresenter.getAllWindows.mockReturnValue([chatWindow as any]) - browserWindowFromIdMock.mockReturnValue(chatWindow) await deeplinkService.handleDeepLink(url) - expect(presenterMock.windowPresenter.createSettingsWindow).not.toHaveBeenCalled() + expect(presenterMock.windowPresenter.createSettingsWindow).toHaveBeenCalledWith({ + routeName: 'settings-mcp' + }) expect(presenterMock.windowPresenter.sendToWindow).toHaveBeenCalledWith( - 1, + 9, DEEPLINK_EVENTS.MCP_INSTALL, { mcpConfig: JSON.stringify({ diff --git a/test/main/desktop/window.test.ts b/test/main/desktop/window.test.ts index 3040d73f49..80ba468c97 100644 --- a/test/main/desktop/window.test.ts +++ b/test/main/desktop/window.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { BrowserWindow } from 'electron' -import { SETTINGS_EVENTS } from '@/events' +import { DEEPLINK_EVENTS, SETTINGS_EVENTS } from '@/events' +import { DEEPCHAT_EVENT_CHANNEL } from '@shared/contracts/channels' const activateAppOnMacMock = vi.hoisted(() => vi.fn()) const originalBrowserWindowFromId = (BrowserWindow as any).fromId @@ -60,8 +61,10 @@ describe('WindowPresenter', () => { routeName: 'settings-about' }) ).toBe(true) + const payload = { mcpConfig: JSON.stringify({ mcpServers: { demo: { command: 'demo' } } }) } + expect(presenter.sendToWindow(9, DEEPLINK_EVENTS.MCP_INSTALL, payload)).toBe(true) expect(send).not.toHaveBeenCalled() - expect((presenter as any).pendingSettingsMessages).toHaveLength(2) + expect((presenter as any).pendingSettingsMessages).toHaveLength(3) presenter.notifySettingsReady(99) @@ -71,6 +74,10 @@ describe('WindowPresenter', () => { expect(send).toHaveBeenNthCalledWith(2, SETTINGS_EVENTS.NAVIGATE, { routeName: 'settings-about' }) + expect(send).toHaveBeenNthCalledWith(3, DEEPCHAT_EVENT_CHANNEL, { + name: 'appRuntime.mcpInstallRequested', + payload + }) expect((presenter as any).pendingSettingsMessages).toHaveLength(0) }) diff --git a/test/renderer/components/App.startup.test.ts b/test/renderer/components/App.startup.test.ts index e2208b98bf..8c898fcb6c 100644 --- a/test/renderer/components/App.startup.test.ts +++ b/test/renderer/components/App.startup.test.ts @@ -36,8 +36,6 @@ const mountApp = async (options?: { const onboardingStatus = options?.onboardingStatus ?? 'idle' const onboardingCurrentStepId = options?.onboardingCurrentStepId ?? null const trackRuntimeLifecycle = options?.trackRuntimeLifecycle ?? false - const setupMcpDeeplink = vi.fn() - const cleanupMcpDeeplink = vi.fn() const setupAppIpcRuntime = vi.fn() const cleanupAppIpcRuntime = vi.fn() const route = reactive({ @@ -408,11 +406,7 @@ const mountApp = async (options?: { useModelStore: () => modelStore })) vi.doMock('@/lib/storeInitializer', () => ({ - initAppStores: vi.fn().mockResolvedValue(undefined), - useMcpInstallDeeplinkHandler: () => ({ - setup: setupMcpDeeplink, - cleanup: cleanupMcpDeeplink - }) + initAppStores: vi.fn().mockResolvedValue(undefined) })) if (trackRuntimeLifecycle) { vi.doMock('@/composables/useAppIpcRuntime', () => ({ @@ -475,8 +469,6 @@ const mountApp = async (options?: { ipcOn, spotlightStore, wrapper, - setupMcpDeeplink, - cleanupMcpDeeplink, setupAppIpcRuntime, cleanupAppIpcRuntime } @@ -488,26 +480,18 @@ afterEach(() => { }) describe('App startup welcome flow', () => { - it('registers runtime and MCP deeplink listeners on mount and cleans them up on unmount', async () => { - const { - wrapper, - setupMcpDeeplink, - cleanupMcpDeeplink, - setupAppIpcRuntime, - cleanupAppIpcRuntime - } = await mountApp({ + it('registers runtime listeners on mount and cleans them up on unmount', async () => { + const { wrapper, setupAppIpcRuntime, cleanupAppIpcRuntime } = await mountApp({ initComplete: true, routeName: 'chat', trackRuntimeLifecycle: true }) - expect(setupMcpDeeplink).toHaveBeenCalledTimes(1) expect(setupAppIpcRuntime).toHaveBeenCalledTimes(1) wrapper.unmount() expect(cleanupAppIpcRuntime).toHaveBeenCalledTimes(1) - expect(cleanupMcpDeeplink).toHaveBeenCalledTimes(1) }, 30000) it('leaves the initial session request to the chat route host', async () => { diff --git a/test/renderer/components/McpSettings.isolation.test.ts b/test/renderer/components/McpSettings.isolation.test.ts index f15c99d2f8..b90647c5bd 100644 --- a/test/renderer/components/McpSettings.isolation.test.ts +++ b/test/renderer/components/McpSettings.isolation.test.ts @@ -8,6 +8,7 @@ import type { GuidedOnboardingState } from '@shared/contracts/routes' import { GUIDED_ONBOARDING_STEP_IDS, GUIDED_ONBOARDING_VERSION } from '@shared/guidedOnboarding' import { settingsRouteComponents } from '../../../src/renderer/settings/settingsRouteComponents' import { useAgentStore } from '@/stores/ui/agent' +import { useMcpStore } from '@/stores/mcp' vi.unmock('pinia') vi.unmock('vue-i18n') @@ -18,7 +19,6 @@ it.each(['settings', 'plugins'])( async (entry) => { const pinia = createPinia() const agentStore = entry === 'plugins' ? useAgentStore(pinia) : null - agentStore?.setSelectedAgent('agent-a') const selections = new Map() let demoEnabled = true const listeners = new Map>() @@ -142,27 +142,67 @@ it.each(['settings', 'plugins'])( await button!.trigger('click') await flushPromises() } - await vi.waitFor(() => - expect(wrapper.text()).toContain(i18n.global.t('mcp.market.builtinTitle')) - ) - await clickButton('common.back') - expect(router.currentRoute.value.query).toEqual({ foo: '1' }) + if (agentStore) { + expect(wrapper.text()).toContain(i18n.global.t('dialog.agentTransfer.selectTarget')) + expect(wrapper.find('[role="switch"]').exists()).toBe(false) + expect(invoke).not.toHaveBeenCalledWith('config.listAgents', expect.anything()) + expect(agentStore.selectedAgentId).toBeNull() + agentStore.setSelectedAgent('agent-a') + } else { + await vi.waitFor(() => + expect(wrapper.text()).toContain(i18n.global.t('mcp.market.builtinTitle')) + ) + await clickButton('common.back') + expect(router.currentRoute.value.query).toEqual({ foo: '1' }) + } await vi.waitFor(() => expect(wrapper.text()).toContain('demo')) const demoSwitch = () => wrapper.get('[role="switch"][aria-label="demo"]') if (agentStore) { expect( wrapper.get('[role="switch"][aria-label="offline"]').attributes('disabled') ).toBeDefined() - await clickButton('chat.input.mcp.openSettings') + for (const key of [ + 'common.add', + 'routes.settings-mcp-market', + 'settings.mcp.npmRegistry.title' + ]) { + expect(wrapper.text()).not.toContain(i18n.global.t(key)) + } + expect(wrapper.find('[aria-label$=": demo"]').exists()).toBe(false) + await wrapper + .findAll('h3') + .find((heading) => heading.text() === 'demo')! + .trigger('click') + expect(document.querySelector('[role="dialog"]')).toBeNull() + await clickButton('settings.userPlugins.manageMcp') expect(invoke).toHaveBeenCalledWith('system.openSettings', { routeName: 'settings-mcp' }) await demoSwitch().trigger('click') await flushPromises() expect(invoke).not.toHaveBeenCalledWith('mcp.setServerEnabled', expect.anything()) + expect(agentStore.selectedAgentId).toBe('agent-a') expect(selections.get('agent-a')).toEqual(['managed']) expect(demoSwitch().attributes('aria-checked')).toBe('false') + selections.set('agent-b', ['demo', 'managed']) agentStore.setSelectedAgent('agent-b') await flushPromises() expect(demoSwitch().attributes('aria-checked')).toBe('true') + const mcpStore = useMcpStore(pinia) + demoEnabled = false + await mcpStore.loadConfig({ force: true }) + await flushPromises() + expect(demoSwitch().attributes('disabled')).toBeDefined() + expect(demoSwitch().attributes('aria-checked')).toBe('false') + demoEnabled = true + await mcpStore.loadConfig({ force: true }) + await flushPromises() + expect(demoSwitch().attributes('aria-checked')).toBe('true') + expect(invoke).toHaveBeenCalledWith('config.updateDeepChatAgent', { + agentId: 'agent-a', + updates: { config: { enabledMcpServerIds: ['managed'] } } + }) + expect( + invoke.mock.calls.filter(([name]) => name === 'config.updateDeepChatAgent') + ).toHaveLength(1) agentStore.setSelectedAgent('agent-a') await flushPromises() expect(demoSwitch().attributes('aria-checked')).toBe('false') @@ -175,12 +215,12 @@ it.each(['settings', 'plugins'])( }) expect(demoSwitch().attributes('aria-checked')).toBe('false') expect(selections.size).toBe(0) + await clickButton('routes.settings-mcp-market') + expect(router.currentRoute.value.query).toEqual({ foo: '1', view: 'market' }) + await clickButton('common.back') + expect(router.currentRoute.value.name).toBe('settings-mcp') + await vi.waitFor(() => expect(wrapper.text()).toContain('demo')) } - await clickButton('routes.settings-mcp-market') - expect(router.currentRoute.value.query).toEqual({ foo: '1', view: 'market' }) - await clickButton('common.back') - expect(router.currentRoute.value.name).toBe(`${entry}-mcp`) - await vi.waitFor(() => expect(wrapper.text()).toContain('demo')) const assertIsolated = () => { expect(pinia.state.value).not.toHaveProperty('session') expect(pinia.state.value).not.toHaveProperty('message') diff --git a/test/renderer/components/McpSettings.test.ts b/test/renderer/components/McpSettings.test.ts index 0dd3cbf213..3d6113bb18 100644 --- a/test/renderer/components/McpSettings.test.ts +++ b/test/renderer/components/McpSettings.test.ts @@ -267,7 +267,8 @@ describe('McpSettingsView', () => { it('requires an explicit target for agent scope', async () => { const { wrapper, configClient } = await setup({ scope: 'agent' }) expect(configClient.listAgents).not.toHaveBeenCalled() - expect(wrapper.get('[role="alert"]').text()).toContain('agentScopeUnsupported') + expect(wrapper.get('[role="status"]').text()).toContain('dialog.agentTransfer.selectTarget') + expect(wrapper.find('[data-testid="servers-view"]').exists()).toBe(false) }) it('ignores a policy load that returns after switching targets', async () => {