diff --git a/src/main/deeplink/actions.ts b/src/main/deeplink/actions.ts index d18447f229..729ff5d6bf 100644 --- a/src/main/deeplink/actions.ts +++ b/src/main/deeplink/actions.ts @@ -82,9 +82,11 @@ class McpInstallActions implements DeeplinkMcpInstallPort { } async requestInstall(mcpConfig: string): Promise { - const targetWindow = await resolveChatWindow(this.windowPresenter) - return targetWindow - ? this.windowPresenter.sendToWindow(targetWindow.id, DEEPLINK_EVENTS.MCP_INSTALL, { + const settingsWindowId = await this.windowPresenter.createSettingsWindow({ + routeName: 'settings-mcp' + }) + return settingsWindowId != null + ? this.windowPresenter.sendToWindow(settingsWindowId, DEEPLINK_EVENTS.MCP_INSTALL, { mcpConfig }) : false diff --git a/src/main/deeplink/index.ts b/src/main/deeplink/index.ts index 277c4d56ad..af89e5f11c 100644 --- a/src/main/deeplink/index.ts +++ b/src/main/deeplink/index.ts @@ -345,7 +345,7 @@ export class DeeplinkService { const sent = await this.mcpInstall.requestInstall(JSON.stringify(completeMcpConfig)) if (!sent) { - console.error('Failed to resolve main window for MCP install deeplink') + console.error('Failed to open settings for MCP install deeplink') return } diff --git a/src/renderer/src/apps/chat-main/ChatMainApp.vue b/src/renderer/src/apps/chat-main/ChatMainApp.vue index 4144fb0a47..67ebe42d8c 100644 --- a/src/renderer/src/apps/chat-main/ChatMainApp.vue +++ b/src/renderer/src/apps/chat-main/ChatMainApp.vue @@ -28,7 +28,7 @@ import McpElicitationDialog from '@/components/mcp/McpElicitationDialog.vue' import McpAppConsentDialog from '@/components/mcp/McpAppConsentDialog.vue' import CliApprovalDialog from '@/components/cli/CliApprovalDialog.vue' import ChatGPTNoticeDialog from '@/components/chatgpt/ChatGPTNoticeDialog.vue' -import { initAppStores, useMcpInstallDeeplinkHandler } from '@/lib/storeInitializer' +import { initAppStores } from '@/lib/storeInitializer' import { ensureIconsLoaded } from '@/lib/iconLoader' import { useFontManager } from '@/composables/useFontManager' import { applyDocumentAppearance } from '@/foundation/appearance/documentAppearance' @@ -120,7 +120,6 @@ let cleanupSemanticNotifications: (() => void) | undefined const toasterTheme = computed(() => themeStore.themeMode === 'system' ? (themeStore.isDark ? 'dark' : 'light') : themeStore.themeMode ) -const { setup: setupMcpDeeplink, cleanup: cleanupMcpDeeplink } = useMcpInstallDeeplinkHandler() watch( [() => themeStore.themeMode, () => themeStore.isDark, () => uiSettingsStore.fontSizeClass], @@ -522,7 +521,6 @@ onMounted(() => { performanceReporter.setEnabled(uiSettingsStore.loggingEnabled) performanceReporter.recordStartup('app-stores-ready', { outcome: 'failed' }) }) - setupMcpDeeplink() setupAppIpcRuntime() watch( @@ -535,7 +533,6 @@ onMounted(() => { onBeforeUnmount(() => { cleanupAppIpcRuntime() - cleanupMcpDeeplink() cleanupSemanticNotifications?.() cleanupSemanticNotifications = undefined semanticNotificationController.dispose() diff --git a/src/renderer/src/components/mcp-config/components/McpServerCard.vue b/src/renderer/src/components/mcp-config/components/McpServerCard.vue index 81d176c11c..771cf3c83f 100644 --- a/src/renderer/src/components/mcp-config/components/McpServerCard.vue +++ b/src/renderer/src/components/mcp-config/components/McpServerCard.vue @@ -41,6 +41,8 @@ interface Props { isManaged?: boolean isLoading?: boolean disabled?: boolean + agentScoped?: boolean + toggleDisabled?: boolean toolsCount?: number promptsCount?: number resourcesCount?: number @@ -190,7 +192,7 @@ watch(watchDescription, () => { - + {
{ {{ t('settings.mcp.authenticate') }}
-
+
mcpStore.mcpInstallCache, (newCache) => { - if (newCache) { + if (newCache && !props.agentScopedToggle) { isAddServerDialogOpen.value = true } }, @@ -625,16 +625,20 @@ defineExpose({ ...server, enabled: getServerEnabled(server.name, Boolean(server.enabled)) }" + :agent-scoped="props.agentScopedToggle" :is-built-in="isBuiltInServer(server.name)" :is-managed="mcpStore.config.mcpServers[server.name]?.source === 'deepchat'" :is-loading=" 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)" - @click="openDetail(server.name)" + @click="!props.agentScopedToggle && openDetail(server.name)" @toggle="handleToggleServer(server.name)" @edit="openEditServerDialog(server.name)" @remove="handleRemoveServer(server.name)" @@ -678,8 +682,8 @@ defineExpose({
-
- +
+ diff --git a/src/renderer/src/features/mcp/McpSettingsView.vue b/src/renderer/src/features/mcp/McpSettingsView.vue index d3f87f909a..977560eb42 100644 --- a/src/renderer/src/features/mcp/McpSettingsView.vue +++ b/src/renderer/src/features/mcp/McpSettingsView.vue @@ -25,7 +25,7 @@

{{ t('settings.mcp.center.title') }}

-

+

{{ t('settings.mcp.enabledDescription') }}

@@ -34,19 +34,28 @@ class="flex shrink-0 items-center gap-3" @click="handleMcpGuideTargetInteract" > - + {{ t('common.add') }} - + {{ t('routes.settings-mcp-market') }} + + {{ t('settings.userPlugins.manageMcp') }} +
@@ -58,8 +67,15 @@
+

+ {{ t('dialog.agentTransfer.selectTarget') }} +

- {{ - 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 2ab4d8b9a8..b90647c5bd 100644 --- a/test/renderer/components/McpSettings.isolation.test.ts +++ b/test/renderer/components/McpSettings.isolation.test.ts @@ -7,6 +7,8 @@ import { createMemoryHistory, createRouter, RouterView } from 'vue-router' 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') @@ -16,6 +18,9 @@ it.each(['settings', 'plugins'])( 'keeps MCP, market and onboarding isolated in the %s host across reentry', async (entry) => { const pinia = createPinia() + const agentStore = entry === 'plugins' ? useAgentStore(pinia) : null + const selections = new Map() + let demoEnabled = true const listeners = new Map>() let onboardingState: GuidedOnboardingState = { version: GUIDED_ONBOARDING_VERSION, @@ -36,6 +41,13 @@ it.each(['settings', 'plugins'])( const originalInvoke = vi.mocked(window.deepchat.invoke).getMockImplementation()! const invoke = vi.spyOn(window.deepchat, 'invoke').mockImplementation(async (name, input) => { switch (name) { + case 'config.listAgents': + return { agents: input.ids.map((id: string) => ({ id, type: 'deepchat' })) } + case 'config.resolveDeepChatAgentConfig': + return { config: { enabledMcpServerIds: selections.get(input.agentId) } } + case 'config.updateDeepChatAgent': + selections.set(input.agentId, input.updates.config.enabledMcpServerIds) + return { agent: { id: input.agentId, type: 'deepchat', config: input.updates.config } } case 'onboarding.getState': return { state: onboardingState } case 'onboarding.setStepStatus': @@ -55,7 +67,16 @@ it.each(['settings', 'plugins'])( return { servers: [] } case 'mcp.getServers': - return { servers: { demo: { type: 'stdio', command: 'demo', enabled: true } } } + return { + servers: { + demo: { type: 'stdio', command: 'demo', enabled: demoEnabled }, + offline: { type: 'stdio', command: 'offline', enabled: false }, + managed: { type: 'stdio', source: 'plugin', enabled: true } + } + } + case 'mcp.setServerEnabled': + demoEnabled = input.enabled + return { enabled: demoEnabled } case 'mcp.getEnabled': return { enabled: true } case 'mcp.getClients': @@ -121,21 +142,89 @@ 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' }) - 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`) + 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() + 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') + } else { + await demoSwitch().trigger('click') + await flushPromises() + expect(invoke).toHaveBeenCalledWith('mcp.setServerEnabled', { + serverName: 'demo', + enabled: false + }) + 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')) + } const assertIsolated = () => { expect(pinia.state.value).not.toHaveProperty('session') expect(pinia.state.value).not.toHaveProperty('message') - expect(pinia.state.value).not.toHaveProperty('agent') + if (entry === 'settings') expect(pinia.state.value).not.toHaveProperty('agent') expect( on.mock.calls .map(([name]) => name) 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 () => {