diff --git a/src/vs/platform/agentHost/common/meta/mcpCustomizationMeta.ts b/src/vs/platform/agentHost/common/meta/mcpCustomizationMeta.ts index 13883ebf1b2e61..f99c62ece39277 100644 --- a/src/vs/platform/agentHost/common/meta/mcpCustomizationMeta.ts +++ b/src/vs/platform/agentHost/common/meta/mcpCustomizationMeta.ts @@ -4,5 +4,5 @@ *--------------------------------------------------------------------------------------------*/ export type { McpServerSource } from './vscode/mcpCustomizationMeta.js'; -export { readMcpRoutingServers, withMcpRoutingServers } from './vscode/mcpCustomizationMeta.js'; +export { copilotConnectorReconnectRequiredErrorType, readMcpRoutingServers, withMcpRoutingServers } from './vscode/mcpCustomizationMeta.js'; export { readMcpServerConnectorName, readMcpServerControllingSetting, readMcpServerDisplayName, readMcpServerSource, readMcpServerSourcePlugin, withMcpServerConnectorNameMeta, withMcpServerControllingSettingMeta, withMcpServerDisplayNameMeta, withMcpServerSourceMeta, withMcpServerSourcePluginMeta } from './vscode/mcpCustomizationMeta.js'; diff --git a/src/vs/platform/agentHost/common/meta/vscode/mcpCustomizationMeta.ts b/src/vs/platform/agentHost/common/meta/vscode/mcpCustomizationMeta.ts index e17cf22edb3397..dc25bc56060e75 100644 --- a/src/vs/platform/agentHost/common/meta/vscode/mcpCustomizationMeta.ts +++ b/src/vs/platform/agentHost/common/meta/vscode/mcpCustomizationMeta.ts @@ -13,6 +13,12 @@ const controllingSettingKey = 'vscode.mcpServerControllingSetting'; const connectorNameKey = 'vscode.mcpServerConnectorName'; const routingServersKey = 'vscode.mcpRoutingServers'; +/** + * `errorType` of a Copilot Connector server whose connection the Connector service reported as broken and + * not retryable. Only reconnecting the Connector, which refreshes its authorization, recovers it. + */ +export const copilotConnectorReconnectRequiredErrorType = 'copilot-connector-reconnect-required'; + /** Reads the servers with registered routing tools on this chat. */ export function readMcpRoutingServers(session: { readonly _meta?: Record } | undefined, chat: string): readonly string[] { const entries = session?._meta?.[routingServersKey]; diff --git a/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts b/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts index 4418d756ea688b..962d8fc467c89b 100644 --- a/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts +++ b/src/vs/platform/agentHost/node/copilot/copilotAgentSession.ts @@ -162,7 +162,7 @@ import type { IAgentHostScopedCredential } from '../../common/agentHostCredentia import type { ErrorInfo, ProtectedResourceMetadata } from '../../common/state/protocol/common/state.js'; import { CopilotSlashCommandProvider } from './copilotSlashCommandProvider.js'; import { CopilotMcpToolRoutingCache, getMcpRoutingCacheKey, getMcpRoutingProxyName, type ICopilotMcpRoutingServer, type ICopilotMcpRoutingTool } from './copilotMcpToolRoutingCache.js'; -import { readMcpRoutingServers, readMcpServerSource, withMcpRoutingServers } from '../../common/meta/mcpCustomizationMeta.js'; +import { copilotConnectorReconnectRequiredErrorType, readMcpRoutingServers, readMcpServerSource, withMcpRoutingServers } from '../../common/meta/mcpCustomizationMeta.js'; import { readRuntimePluginEnablement } from '../../common/meta/pluginEnablementMeta.js'; import { AgentHostStateManager, IAgentHostStateManager } from '../agentHostStateManager.js'; import { type CopilotPluginReloadReason, getCopilotCustomizationCommandHandler, installCopilotPlugin, type ICopilotMcpCommandServer, type ICopilotPluginCommandApi, removeCopilotPluginMarketplace } from './copilotCustomizationCommandDisplay.js'; @@ -1057,6 +1057,26 @@ function getEffectiveMcpServerEnablement(enabled: boolean | undefined, status: S return status !== undefined ? status !== 'disabled' && status !== 'not_configured' : enabled ?? true; } +function isRecord(value: unknown): value is Record { + return isObject(value); +} + +function isBrokenCopilotConnectorError(error: string): boolean { + const start = error.indexOf('{'); + const end = error.lastIndexOf('}'); + if (start === -1 || end < start || !error.includes('"com.github/copilot-connector-errors"')) { + return false; + } + try { + const parsed: unknown = JSON.parse(error.slice(start, end + 1)); + const details = isRecord(parsed) ? parsed['com.github/copilot-connector-errors'] : undefined; + return isRecord(details) + && details.reason === 'connection_broken' && details.action === 'reconnect' && details.retryable === false; + } catch { + return false; + } +} + class DirectUsageAccumulator { private readonly _tokenTotalsByModel = new Map>(); private _copilotNanoAiu: number | undefined; @@ -2323,6 +2343,8 @@ export class CopilotAgentSession extends Disposable { private readonly _lastMcpAuthRequirements = new Map(); /** Latest SDK status per server, used to notice a server leaving `connected`. */ private readonly _mcpSdkStatus = new Map(); + /** Structured failures observed before or after Connector ownership is published. */ + private readonly _mcpConnectorReconnectErrors = new Map(); /** Servers whose current connection has loaded tools, from lifecycle events or inventory `toolsLoaded`. */ private readonly _mcpToolsLoaded = new Set(); /** Invalidates inventory snapshots when lifecycle events or authentication challenges arrive. */ @@ -5095,7 +5117,10 @@ export class CopilotAgentSession extends Disposable { } const serverName = proxy.server.serverName; const enabled = this._mcpConfiguredEnablement.get(serverName) ?? this._mcpCustomizations.enabledForServer(serverName); - return enabled !== false + const status = this._mcpSdkStatus.get(serverName); + const reconnecting = this._isCopilotConnectorServer(serverName) && this._mcpConnectorReconnectErrors.has(serverName) + && (status === 'failed' || status === 'not_configured' || status === 'pending'); + return (enabled !== false || reconnecting) && this._getDesiredMcpServerEnablementByName([serverName]).get(serverName) !== false && !availableTools?.some(tool => tool.mcpServerName === serverName); } @@ -6805,11 +6830,25 @@ export class CopilotAgentSession extends Disposable { this._copilotConnectorAuthorizationRequired = connectorServers.authorizationRequired; // Republish servers that stopped being Connector-owned too, so their Connector metadata is removed. for (const serverName of new Set([...previous, ...connectorServers.servers.keys()])) { - const state = this._mcpCustomizations.stateForServer(serverName); + let state = this._mcpCustomizations.stateForServer(serverName); + const status = this._mcpSdkStatus.get(serverName); + const error = this._mcpConnectorReconnectErrors.get(serverName); + if (error && (status === 'failed' || status === 'not_configured') + && (!state || state.kind === McpServerStatus.Error || state.kind === McpServerStatus.Stopped) + && (state || this._isCopilotConnectorServer(serverName))) { + state = this._translateSdkMcpStatus(serverName, status, error, this._hasPendingMcpAuthentication(serverName)); + } else if (error && status === 'pending' && !state && this._isCopilotConnectorServer(serverName)) { + state = this._translateSdkMcpStatus(serverName, status, undefined, this._hasPendingMcpAuthentication(serverName)); + } if (state) { this._mcpCustomizations.applyOne({ name: serverName, displayName: this._copilotConnectorServers.get(serverName)?.displayName, state }); } } + for (const serverName of previous) { + if (!this._copilotConnectorServers.has(serverName)) { + this._mcpConnectorReconnectErrors.delete(serverName); + } + } if (this._mcpToolRoutingEnabled && this._clientToolConfiguration?.toolSearchActive) { await this._replaceClientTools(undefined, this._lifetimeCts.token, true); } @@ -9025,6 +9064,10 @@ export class CopilotAgentSession extends Disposable { throw new CancellationError(); } const state = this._mcpCustomizations.stateForServer(serverName); + const reconnectMessage = this._copilotConnectorReconnectMessage(serverName); + if (reconnectMessage && (!state || state.kind === McpServerStatus.Error || state.kind === McpServerStatus.Stopped)) { + throw new Error(reconnectMessage); + } if (state?.kind === McpServerStatus.AuthRequired) { this._mcpLifecycleVersion++; this._mcpCustomizations.applyOne({ name: serverName, state }, true); @@ -9296,6 +9339,7 @@ export class CopilotAgentSession extends Disposable { try { this._recordRuntimeMutation('mcpDisable'); await this._wrapper.session.rpc.mcp.disable(await this._mcpServerIdentity(serverName)); + this._mcpConnectorReconnectErrors.delete(serverName); this._hostMcpServerEnablement.set(serverName, false); } catch (error) { if (this._expectedMcpEnablementChanges.get(serverName) === false) { @@ -9316,6 +9360,7 @@ export class CopilotAgentSession extends Disposable { this._cancelPendingMcpAuthRequestsForServer(serverName); this._recordRuntimeMutation('userRequested'); await this._wrapper.session.rpc.mcp.stopServer(await this._mcpServerIdentity(serverName)); + this._mcpConnectorReconnectErrors.delete(serverName); this._mcpLifecycleVersion++; this._mcpCustomizations.applyOne({ name: serverName, state: { kind: McpServerStatus.Stopped } }); })); @@ -13692,7 +13737,7 @@ export class CopilotAgentSession extends Disposable { this._mcpAwaitingOAuthReconnect.delete(e.data.serverName); } this._observeMcpRestart(e.data.serverName, e.data.status); - this._noteMcpSdkStatus(e.data.serverName, e.data.status); + this._noteMcpSdkStatus(e.data.serverName, e.data.status, e.data.error, true); const requirement = this._lastMcpAuthRequirements.get(e.data.serverName); if (requirement && e.data.status !== 'pending') { this._lastMcpAuthRequirements.set(e.data.serverName, { ...requirement, acceptsTokenCompletion: false }); @@ -13797,7 +13842,7 @@ export class CopilotAgentSession extends Disposable { })), 'inventory'); for (const server of result.servers) { const status = server.live?.status ?? 'stopped'; - this._noteMcpSdkStatus(server.name, status); + this._noteMcpSdkStatus(server.name, status, server.live?.error); // The bundled SDK types predate inventory `toolsLoaded`; older runtimes use connected as ready. const toolsLoaded = (server.live as { readonly toolsLoaded?: boolean } | undefined)?.toolsLoaded; if (toolsLoaded === true || (toolsLoaded === undefined && status === 'connected')) { @@ -13988,11 +14033,20 @@ export class CopilotAgentSession extends Disposable { return { ...server, source, enabled, configuration, configurationError, sourceUri, tools }; } - private _noteMcpSdkStatus(serverName: string, status: SdkMcpServerStatus): void { + private _noteMcpSdkStatus(serverName: string, status: SdkMcpServerStatus, error?: string, statusEvent = false): void { if (this._mcpSdkStatus.get(serverName) === 'connected' && status !== 'connected') { this._mcpToolsLoaded.delete(serverName); this._mcpRoutingConnectionCalls.delete(serverName); } + if (status === 'failed' && (error !== undefined || statusEvent || this._mcpSdkStatus.get(serverName) !== 'failed')) { + if (error !== undefined && isBrokenCopilotConnectorError(error)) { + this._mcpConnectorReconnectErrors.set(serverName, error); + } else { + this._mcpConnectorReconnectErrors.delete(serverName); + } + } else if (status === 'connected' || status === 'disabled') { + this._mcpConnectorReconnectErrors.delete(serverName); + } this._mcpSdkStatus.set(serverName, status); } @@ -14030,6 +14084,16 @@ export class CopilotAgentSession extends Disposable { } this._mcpInventoryProvenance = new Map(servers.map(server => [server.name, { source: server.source, sourcePlugin: server.sourcePlugin, url: server.url }])); const sdkServers = servers.map(server => this._toSdkMcpServer(server)); + for (const [serverName, connector] of this._copilotConnectorServers) { + const status = this._mcpSdkStatus.get(serverName); + if (!serverNames.has(serverName) && this._mcpConnectorReconnectErrors.has(serverName) && (status === 'failed' || status === 'not_configured' || status === 'pending')) { + sdkServers.push({ + name: serverName, + displayName: connector.displayName, + state: this._translateSdkMcpStatus(serverName, status, undefined, this._hasPendingMcpAuthentication(serverName)), + }); + } + } this._mcpCustomizations.applyAll(sdkServers); for (const server of servers) { if (server.enabled === undefined) { @@ -14216,14 +14280,15 @@ export class CopilotAgentSession extends Disposable { const previous = this._mcpCustomizations.stateForServer(name); return { kind: McpServerStatus.Starting, blocking: previous?.kind === McpServerStatus.Starting ? previous.blocking ?? true : true }; } - case 'failed': + case 'failed': { + const reconnectMessage = this._copilotConnectorReconnectMessage(name); return { kind: McpServerStatus.Error, - error: { - errorType: 'mcp-server-failed', - message: error ?? 'MCP server failed to start', - }, + error: reconnectMessage + ? { errorType: copilotConnectorReconnectRequiredErrorType, message: reconnectMessage } + : { errorType: 'mcp-server-failed', message: error ?? 'MCP server failed to start' }, }; + } case 'pending': { const previous = this._mcpCustomizations.stateForServer(name); if (hasPendingAuthentication && previous?.kind === McpServerStatus.AuthRequired) { @@ -14239,8 +14304,14 @@ export class CopilotAgentSession extends Disposable { const auth = this._lastMcpAuthRequirements.get(name)?.auth ?? this._copilotConnectorAuthRequirement(name); return auth ? { kind: McpServerStatus.AuthRequired, ...auth } : { kind: McpServerStatus.Starting }; } + case 'not_configured': { + this._lastMcpAuthRequirements.delete(name); + const message = this._copilotConnectorReconnectMessage(name); + return message + ? { kind: McpServerStatus.Error, error: { errorType: copilotConnectorReconnectRequiredErrorType, message } } + : { kind: McpServerStatus.Stopped }; + } case 'disabled': - case 'not_configured': this._lastMcpAuthRequirements.delete(name); return { kind: McpServerStatus.Stopped }; default: @@ -14248,6 +14319,14 @@ export class CopilotAgentSession extends Disposable { } } + private _copilotConnectorReconnectMessage(serverName: string): string | undefined { + const connector = this._copilotConnectorServers.get(serverName); + const status = this._mcpSdkStatus.get(serverName); + return connector && this._mcpConnectorReconnectErrors.has(serverName) && (status === 'failed' || status === 'not_configured') + ? localize('copilot.connectorReconnect', "Disconnect and reconnect {0} using the Copilot account for this session to reauthorize it. In VS Code, manage connected connectors under Chat: Open Customizations > MCP Servers or browse Copilot Connectors.", connector.displayName) + : undefined; + } + /** * A runtime that classifies a Connector scope failure reports it on the Connector status instead of asking for * an MCP token, so describe the requirement for a Connector-owned server that needs authentication. diff --git a/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts b/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts index bd4b84c536d7c9..bfe43c3d0f59ba 100644 --- a/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts +++ b/src/vs/platform/agentHost/test/node/copilotAgentSession.test.ts @@ -33688,8 +33688,10 @@ Use the attached image as context. servers: new Map([['connector-workiq', { connectorName: 'workiqmcp', displayName: 'Work IQ' }]]), authorizationRequired: true, }; + const brokenConnectorError = 'failed to initialize MCP client: JSON-RPC error: 1001: Connector connection requires reauthorization({"com.github/copilot-connector-errors":{"reason":"connection_broken","action":"reconnect","retryable":false}})'; + const connectorReconnectMessage = 'Disconnect and reconnect Work IQ using the Copilot account for this session to reauthorize it. In VS Code, manage connected connectors under Chat: Open Customizations > MCP Servers or browse Copilot Connectors.'; - async function createConnectorRoutingSession(options: { routingEnabled?: boolean; serverEnabled?: boolean; reconcile?: Promise } = {}) { + async function createConnectorRoutingSession(options: { routingEnabled?: boolean; serverEnabled?: boolean; resolveServerEnabled?: () => boolean; reconcile?: Promise } = {}) { const activeClientToolSet = new ActiveClientToolSet(); activeClientToolSet.set('tool-search-client', globalMcpRoutingSnapshot.tools); const created = await createAgentSession(disposables, { @@ -33700,13 +33702,16 @@ Use the attached image as context. [AgentHostMcpToolRoutingEnabledConfigKey]: options.routingEnabled !== false, [AgentHostMcpConnectorsEnabledConfigKey]: true, }, - ...(options.serverEnabled === false ? { - resolveCustomizationEnablement: () => ({ - kind: 'resolved' as const, - enablement: [{ kind: CustomizationEnablementKind.Session, enabled: false }], - enabled: false, - workingDirectory: { kind: 'workspaceless' as const }, - }), + ...(options.serverEnabled === false || options.resolveServerEnabled ? { + resolveCustomizationEnablement: () => { + const enabled = options.resolveServerEnabled?.() ?? false; + return { + kind: 'resolved' as const, + enablement: [{ kind: CustomizationEnablementKind.Session, enabled }], + enabled, + workingDirectory: { kind: 'workspaceless' as const }, + }; + }, } : {}), configureMockSession: mock => { mock.connectorStatus = { @@ -33735,6 +33740,274 @@ Use the attached image as context. return created; } + test('MCP routing preserves broken Connector guidance across startup and missing inventory', async () => { + const reconcile = new DeferredPromise(); + const { session, mockSession, waitForSignal } = await createConnectorRoutingSession({ reconcile: reconcile.p }); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'failed', error: brokenConnectorError }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'not_configured' }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'not_configured' }); + + await reconcile.complete({ ...workIqConnectors, authorizationRequired: false }); + await session.refreshConnectors(); + const server = session.topLevelMcpCustomizations().find(candidate => candidate.name === 'connector-workiq'); + assert.ok(server); + const state = server.state; + mockSession.mcpStartServerError = new Error('no installed config to restart'); + await assert.rejects(session.startMcpServer(server.id), { message: connectorReconnectMessage }); + + const [search, proxy] = mockSession.setToolsCalls.at(-1)!; + session.resetTurnState('broken-connector-search'); + mockSession.fire('tool.execution_start', { toolCallId: 'find-broken-connector', toolName: search.name, arguments: { query: 'Work IQ' } }); + const searchPromise = invokeClientToolHandler(search, 'find-broken-connector', { query: 'Work IQ' }, [ + { name: proxy.name, description: proxy.description!, deferLoading: true }, + ]); + const searchReady = await waitForSignal(signal => isAction(signal, ActionType.ChatToolCallReady) + && signal.action.type === ActionType.ChatToolCallReady + && signal.action.toolCallId === 'find-broken-connector'); + assert.ok(isAction(searchReady, ActionType.ChatToolCallReady)); + session.handleClientToolCallComplete('find-broken-connector', { + success: true, pastTenseMessage: 'Searched tools', content: [{ type: ToolResultContentType.Text, text: JSON.stringify([proxy.name]) }], + }); + const searchResult = await searchPromise; + mockSession.mcpListResult = { servers: [] }; + session.resetTurnState('broken-connector-route'); + const result = await invokeClientToolHandler(proxy, 'broken-connector-route'); + assert.deepStrictEqual({ + state, + enabled: isCustomizationEnabled(server), + candidates: readToolCallMeta(searchReady.action as ChatToolCallReadyAction).toolSearchCandidates, + references: searchResult.toolReferences, + resultType: result.resultType, + error: result.error, + starts: mockSession.mcpStartServerCalls, + }, { + state: { kind: McpServerStatus.Error, error: { errorType: 'copilot-connector-reconnect-required', message: connectorReconnectMessage } }, + enabled: true, + candidates: [{ name: proxy.name, description: proxy.description }], + references: [proxy.name], + resultType: 'failure', + error: connectorReconnectMessage, + starts: [], + }); + }); + + test('publishes broken Connector guidance when inventory disappears before ownership resolves', async () => { + const reconcile = new DeferredPromise(); + const { session, mockSession, waitForSignal } = await createConnectorRoutingSession({ reconcile: reconcile.p }); + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + mockSession.mcpListResult = { servers: [] }; + mockSession.fire('session.mcp_servers_loaded', { servers: [] }); + await waitForSignal(signal => isAction(signal, ActionType.SessionCustomizationRemoved) + && signal.action.type === ActionType.SessionCustomizationRemoved + && signal.action.id.endsWith(':connector-workiq')); + const beforeOwnership = session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq'); + + await reconcile.complete(workIqConnectors); + await session.refreshConnectors(); + assert.deepStrictEqual({ + beforeOwnership, + afterOwnership: session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq')?.state, + }, { + beforeOwnership: undefined, + afterOwnership: { kind: McpServerStatus.Error, error: { errorType: 'copilot-connector-reconnect-required', message: connectorReconnectMessage } }, + }); + }); + + test('MCP routing waits for a reconnect in progress and clears broken Connector guidance when connected', async () => { + const { session, mockSession } = await createConnectorRoutingSession(); + const [, proxy] = mockSession.setToolsCalls.at(-1)!; + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'failed', error: brokenConnectorError }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + const failedState = session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq')?.state; + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'pending' }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'pending' }); + mockSession.mcpListResult = { servers: [] }; + + session.resetTurnState('reconnecting-connector-route'); + const activation = invokeClientToolHandler(proxy, 'reconnecting-connector-route'); + await timeout(0); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'connected', toolsLoaded: true }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'connected' }); + fireMcpToolsLoaded(mockSession, 'connector-workiq'); + const result = await activation; + assert.deepStrictEqual({ + failedState, + resultType: result.resultType, + starts: mockSession.mcpStartServerCalls, + discovered: mockSession.mcpListToolsCalls.some(call => call.serverName === 'connector-workiq'), + }, { + failedState: { kind: McpServerStatus.Error, error: { errorType: 'copilot-connector-reconnect-required', message: connectorReconnectMessage } }, + resultType: 'success', + starts: [], + discovered: true, + }); + }); + + test('MCP routing keeps a reconnecting broken Connector searchable after inventory disappears', async () => { + const { session, mockSession, waitForSignal } = await createConnectorRoutingSession(); + const [search, proxy] = mockSession.setToolsCalls.at(-1)!; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'not_configured' }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'not_configured' }); + mockSession.fire('session.mcp_servers_loaded', { servers: [] }); + await timeout(0); + + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'pending' }); + mockSession.mcpListResult = { servers: [] }; + mockSession.fire('session.mcp_servers_loaded', { servers: [] }); + await timeout(0); + const state = session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq')?.state; + + session.resetTurnState('reconnecting-connector-search'); + mockSession.fire('tool.execution_start', { toolCallId: 'find-reconnecting-connector', toolName: search.name, arguments: { query: 'Work IQ' } }); + const searchPromise = invokeClientToolHandler(search, 'find-reconnecting-connector', { query: 'Work IQ' }, [ + { name: proxy.name, description: proxy.description!, deferLoading: true }, + ]); + const searchReady = await waitForSignal(signal => isAction(signal, ActionType.ChatToolCallReady) + && signal.action.type === ActionType.ChatToolCallReady + && signal.action.toolCallId === 'find-reconnecting-connector'); + assert.ok(isAction(searchReady, ActionType.ChatToolCallReady)); + session.handleClientToolCallComplete('find-reconnecting-connector', { + success: true, pastTenseMessage: 'Searched tools', content: [{ type: ToolResultContentType.Text, text: JSON.stringify([proxy.name]) }], + }); + const result = await searchPromise; + assert.deepStrictEqual({ + state, + candidates: readToolCallMeta(searchReady.action as ChatToolCallReadyAction).toolSearchCandidates, + references: result.toolReferences, + }, { + state: { kind: McpServerStatus.Starting, blocking: true }, + candidates: [{ name: proxy.name, description: proxy.description }], + references: [proxy.name], + }); + }); + + test('replaces an inventory-only broken Connector failure with a later failure', async () => { + const { session, mockSession, waitForSignal } = await createConnectorRoutingSession(); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'failed', error: brokenConnectorError }] }; + mockSession.fire('session.mcp_servers_loaded', { servers: [] }); + await waitForSignal(signal => isAction(signal, ActionType.SessionCustomizationUpdated) + && signal.action.type === ActionType.SessionCustomizationUpdated + && signal.action.customization.type === CustomizationType.McpServer + && signal.action.customization.state.kind === McpServerStatus.Error + && signal.action.customization.state.error.message === connectorReconnectMessage); + const first = session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq')?.state; + + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'pending' }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'pending' }); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'failed' }] }; + mockSession.fire('session.mcp_servers_loaded', { servers: [] }); + await waitForSignal(signal => isAction(signal, ActionType.SessionCustomizationUpdated) + && signal.action.type === ActionType.SessionCustomizationUpdated + && signal.action.customization.type === CustomizationType.McpServer + && signal.action.customization.state.kind === McpServerStatus.Error + && signal.action.customization.state.error.message === 'MCP server failed to start'); + const replacement = session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq')?.state; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'not_configured' }); + const server = session.topLevelMcpCustomizations().find(candidate => candidate.name === 'connector-workiq'); + assert.ok(server); + mockSession.mcpStartServerError = new Error('ordinary start failure'); + await assert.rejects(session.startMcpServer(server.id), { message: 'ordinary start failure' }); + assert.deepStrictEqual({ first, replacement }, { + first: { kind: McpServerStatus.Error, error: { errorType: 'copilot-connector-reconnect-required', message: connectorReconnectMessage } }, + replacement: { kind: McpServerStatus.Error, error: { errorType: 'mcp-server-failed', message: 'MCP server failed to start' } }, + }); + }); + + test('stopping a broken Connector clears reconnect guidance', async () => { + const { session, mockSession } = await createConnectorRoutingSession(); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'failed', error: brokenConnectorError }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + const server = session.topLevelMcpCustomizations().find(candidate => candidate.name === 'connector-workiq'); + assert.ok(server); + const failedState = server.state; + await session.stopMcpServer(server.id); + mockSession.mcpStartServerError = new Error('ordinary start failure'); + await assert.rejects(session.startMcpServer(server.id), { message: 'ordinary start failure' }); + assert.deepStrictEqual({ + failedState, + stopCalls: mockSession.mcpStopServerCalls, + startCalls: mockSession.mcpStartServerCalls, + }, { + failedState: { kind: McpServerStatus.Error, error: { errorType: 'copilot-connector-reconnect-required', message: connectorReconnectMessage } }, + stopCalls: [{ serverName: 'connector-workiq' }], + startCalls: [{ serverName: 'connector-workiq' }], + }); + }); + + test('disabling a broken Connector clears reconnect guidance', async () => { + let enabled = true; + const { session, mockSession } = await createConnectorRoutingSession({ resolveServerEnabled: () => enabled }); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'failed', error: brokenConnectorError }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + enabled = false; + session.markConnectorConfigurationChanged(); + await session.refreshConnectors(); + const server = session.topLevelMcpCustomizations().find(candidate => candidate.name === 'connector-workiq'); + assert.ok(server); + const disabledState = server.state; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'not_configured' }); + mockSession.mcpStartServerError = new Error('ordinary start failure'); + await assert.rejects(session.startMcpServer(server.id), { message: 'ordinary start failure' }); + assert.deepStrictEqual({ disabledState, disableCalls: mockSession.mcpDisableCalls }, { + disabledState: { kind: McpServerStatus.Stopped }, + disableCalls: [{ serverName: 'connector-workiq' }], + }); + }); + + test('removing a broken Connector clears reconnect guidance before it is added again', async () => { + const { session, mockSession } = await createConnectorRoutingSession(); + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'failed', error: brokenConnectorError }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + mockSession.connectorStatus = { ...mockSession.connectorStatus, runtimeServers: [] }; + mockSession.mcpListResult = { servers: [] }; + session.markConnectorConfigurationChanged(); + await session.refreshConnectors(); + const removed = session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq'); + + mockSession.connectorStatus = { + ...mockSession.connectorStatus, + runtimeServers: [{ connectorName: 'workiqmcp', runtimeServerId: 'connector-workiq', status: 'not_configured' }], + }; + mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'not_configured' }] }; + session.markConnectorConfigurationChanged(); + await session.refreshConnectors(); + assert.deepStrictEqual({ + removed, + readded: session.topLevelMcpCustomizations().find(server => server.name === 'connector-workiq')?.state, + }, { + removed: undefined, + readded: { kind: McpServerStatus.Stopped }, + }); + }); + + test('MCP routing does not classify unrelated or non-Connector errors as broken connections', async () => { + const cases = [ + { connector: true, error: 'failed ({"com.github/copilot-connector-errors":{"reason":"connection_broken","action":"retry","retryable":true}})' }, + { connector: true, error: 'failed ({"com.github/copilot-connector-errors":invalid})' }, + { connector: false, error: brokenConnectorError }, + ]; + const states: McpServerCustomization['state'][] = []; + for (const testCase of cases) { + const { session, mockSession } = testCase.connector ? await createConnectorRoutingSession() : await createMcpRoutingSession(); + const name = testCase.connector ? 'connector-workiq' : 'docs'; + mockSession.mcpListResult = { servers: [{ name, status: 'failed', error: testCase.error }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: name, status: 'failed', error: testCase.error }); + const server = session.topLevelMcpCustomizations().find(candidate => candidate.name === name); + assert.ok(server); + const state = server.state; + mockSession.mcpListResult = { servers: [{ name, status: 'not_configured' }] }; + mockSession.fire('session.mcp_server_status_changed', { serverName: name, status: 'not_configured' }); + mockSession.mcpStartServerError = new Error('ordinary start failure'); + await assert.rejects(session.startMcpServer(server.id), { message: 'ordinary start failure' }); + states.push(state); + } + assert.deepStrictEqual(states, cases.map(testCase => ({ + kind: McpServerStatus.Error, error: { errorType: 'mcp-server-failed', message: testCase.error }, + }))); + }); + test('MCP routing registers searchable deferred Connector proxies after asynchronous launch discovery', async () => { const reconcile = new DeferredPromise(); const { session, mockSession, signals, waitForSignal } = await createConnectorRoutingSession({ reconcile: reconcile.p }); @@ -33780,7 +34053,7 @@ Use the attached image as context. }); }); - for (const timing of ['statusOnly', 'statusWhileStarting', 'sdkCallback'] as const) { + for (const timing of ['statusOnly', 'statusWhileStarting', 'sdkCallback', 'afterBrokenConnection'] as const) { test(`MCP routing requests Connector authorization only on selection (${timing})`, async () => { const { session, runtime, mockSession, signals, waitForSignal } = await createConnectorRoutingSession(); let authentication: ReturnType | undefined; @@ -33798,6 +34071,10 @@ Use the attached image as context. mockSession.mcpListResult = { servers: [{ name: 'connector-workiq', status: 'pending', source: 'managed' }] }; mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'pending' }); } + if (timing === 'afterBrokenConnection') { + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'failed', error: brokenConnectorError }); + mockSession.fire('session.mcp_server_status_changed', { serverName: 'connector-workiq', status: 'needs-auth' }); + } const [, proxy] = mockSession.setToolsCalls.at(-1)!; session.resetTurnState('connector-route'); mockSession.fire('tool.execution_start', { toolCallId: 'connect-workiq', toolName: proxy.name, arguments: {} }); diff --git a/src/vs/platform/notification/common/notificationTelemetry.ts b/src/vs/platform/notification/common/notificationTelemetry.ts index 18f9427c0567cc..a1a7f0a53053f4 100644 --- a/src/vs/platform/notification/common/notificationTelemetry.ts +++ b/src/vs/platform/notification/common/notificationTelemetry.ts @@ -42,6 +42,7 @@ export enum NotificationTelemetryId { PluginManagedRetryComplete = 'plugins.managed.retry.complete', PluginManagedRetryError = 'plugins.managed.retry.error', CustomizationMigration = 'customizations.migration', + CopilotConnectorReconnect = 'copilotConnectors.reconnect', DictationModelPrepare = 'dictation.model.prepare', DictationModelImport = 'dictation.model.import', FileSaveParticipants = 'files.saveParticipants', @@ -61,6 +62,7 @@ export enum NotificationActionTelemetryId { Decline = 'decline', Copy = 'copy', Configure = 'configure', + Reconnect = 'reconnect', } export enum ExtensionNotificationTelemetryId { diff --git a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts index d524a5b4c557de..5ab5b416dfdb7a 100644 --- a/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts +++ b/src/vs/workbench/contrib/chat/browser/agentSessions/agentHost/agentHostCustomizationService.ts @@ -14,7 +14,7 @@ import { cancelOnDispose, CancellationToken } from '../../../../../../base/commo import { Emitter, Event } from '../../../../../../base/common/event.js'; import { getErrorMessage, isCancellationError } from '../../../../../../base/common/errors.js'; import { StringSHA1 } from '../../../../../../base/common/hash.js'; -import { Disposable, DisposableResourceMap, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { Disposable, DisposableMap, DisposableResourceMap, DisposableStore, IDisposable, MutableDisposable, toDisposable } from '../../../../../../base/common/lifecycle.js'; import { ResourceSet } from '../../../../../../base/common/map.js'; import { AgentHostMcpServers, AgentHostMcpServersConfigKey, IPermissionsValue } from '../../../../../../platform/agentHost/common/agentHostSchema.js'; import { readMcpServerLogsChannelTemplate } from '../../../../../../platform/agentHost/common/otlp/mcpServerLogsChannel.js'; @@ -29,7 +29,7 @@ import { IAgentHostResourceUriMapper } from '../../../../../../platform/agentHos import { hasReadableCustomizationContent } from '../../../../../../platform/agentHost/common/agentHostCustomizationUri.js'; import { AMBIENT_AGENT_HOST_AUTHORITY, IAgentHostConnectionsService, IAgentHostSessionResolution } from '../../../../../../platform/agentHost/common/agentHostConnectionsService.js'; import { getEffectiveAgents } from '../../../../../../platform/agentHost/common/customAgents.js'; -import { readMcpServerConnectorName, readMcpServerControllingSetting, readMcpServerDisplayName, readMcpServerSource, readMcpServerSourcePlugin } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; +import { copilotConnectorReconnectRequiredErrorType, readMcpServerConnectorName, readMcpServerControllingSetting, readMcpServerDisplayName, readMcpServerSource, readMcpServerSourcePlugin } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; import { readAgentToolFullReferenceName } from '../../../../../../platform/agentHost/common/meta/agentToolDefinitionMeta.js'; import { getCustomizationDisabledReason, isCustomizationEnabled, withCustomizationEnablement } from '../../../../../../platform/agentHost/common/customizationEnablement.js'; import { type IAgentSubscription } from '../../../../../../platform/agentHost/common/state/agentSubscription.js'; @@ -43,6 +43,7 @@ import { IMcpServerConfiguration } from '../../../../../../platform/mcp/common/m import { IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { canLog, ILogger, ILoggerService, ILogService, log, LogLevel } from '../../../../../../platform/log/common/log.js'; import { INotificationService, Severity } from '../../../../../../platform/notification/common/notification.js'; +import { NotificationActionTelemetryId, NotificationTelemetryId } from '../../../../../../platform/notification/common/notificationTelemetry.js'; import { CopilotConnectorsError, ICopilotConnectorsService } from '../../aiCustomization/copilotConnectorsService.js'; import { AuthenticationSession } from '../../../../../services/authentication/common/authentication.js'; import { localize } from '../../../../../../nls.js'; @@ -261,6 +262,67 @@ interface IMcpAutoAuthenticationAttempt { rejected: boolean; } +const COPILOT_CONNECTOR_RECONNECT_VERIFICATION_TIMEOUT_MS = 60_000; +/** A Connector that breaks again within this time after an automatic reconnect is left to the user. */ +const COPILOT_CONNECTOR_RECONNECT_COOLDOWN_MS = 5 * 60_000; + +const enum CopilotConnectorReconnectPhase { + /** Repairing the connection without prompting. */ + Reconnecting, + /** Waiting for the Connector's servers to restart and become ready. */ + Verifying, + /** The user was asked to reconnect. */ + Failed, + Succeeded, +} + +class CopilotConnectorReconnectAttempt extends Disposable { + private _phase = CopilotConnectorReconnectPhase.Reconnecting; + private _phaseTime = Date.now(); + private readonly _verificationTimeout = this._register(new MutableDisposable()); + /** Whether a Connector server restarted while verifying. */ + restarted = false; + + constructor(readonly label: string, readonly sessions = new ResourceSet()) { + super(); + } + + get phase(): CopilotConnectorReconnectPhase { + return this._phase; + } + + get phaseTime(): number { + return this._phaseTime; + } + + get isInProgress(): boolean { + return this._phase === CopilotConnectorReconnectPhase.Reconnecting || this._phase === CopilotConnectorReconnectPhase.Verifying; + } + + verify(timeout: IDisposable): void { + this._setPhase(CopilotConnectorReconnectPhase.Verifying); + this._verificationTimeout.value = timeout; + } + + fail(): void { + this._setPhase(CopilotConnectorReconnectPhase.Failed); + } + + succeed(): void { + this._setPhase(CopilotConnectorReconnectPhase.Succeeded); + } + + private _setPhase(phase: CopilotConnectorReconnectPhase): void { + this._phase = phase; + this._phaseTime = Date.now(); + this._verificationTimeout.clear(); + } +} + +function isCopilotConnectorReconnectRequired(state: McpServerState): boolean { + return state.kind === McpServerStatus.Error && state.error.errorType === copilotConnectorReconnectRequiredErrorType; +} + export abstract class AbstractAgentHostCustomizationService extends Disposable implements IAgentHostCustomizationService { declare readonly _serviceBrand: undefined; @@ -273,6 +335,10 @@ export abstract class AbstractAgentHostCustomizationService extends Disposable i /** Sessions with advertised diagnostic logs or a revealed per-server Output channel. */ private readonly _mcpDiagnosticSessions = new ResourceSet(); private readonly _mcpAutoAuthentication = new Map(); + /** Automatic repairs of broken Copilot Connector connections, by Connector name, shared by all sessions. */ + private readonly _copilotConnectorReconnects = this._register(new DisposableMap()); + /** Bounds how long an automatic Connector reconnect waits for the Connector's servers to become ready. */ + protected _copilotConnectorReconnectVerificationTimeoutMs = COPILOT_CONNECTOR_RECONNECT_VERIFICATION_TIMEOUT_MS; private _copilotConnectorAuthorizationInstance: AgentHostCopilotConnectorAuthorization | undefined; private readonly _mcpAuthenticationVerifications = this._register(new DisposableStore()); /** Bounds how long Sign In waits for a server to leave the authentication-required state. */ @@ -374,7 +440,7 @@ export abstract class AbstractAgentHostCustomizationService extends Disposable i disabledReason: getCustomizationDisabledReason(server, plugin), ...(waitingForSessionStart ? { waitingForSessionStart: true } : {}), status: server.state.kind, - authenticating: this._isAutoAuthenticatingMcpServer(sessionResource, target, server), + authenticating: this._isAutoAuthenticatingMcpServer(sessionResource, target, server) || this._isReconnectingCopilotConnector(sessionResource, server), state: server.state, sourceUri: source.scheme === 'mcp-top-level' || !hasReadableCustomizationContent(source) ? undefined : target.resourceUris.fromAgentHost(source), sourceRange: source.scheme === 'mcp-top-level' || !hasReadableCustomizationContent(source) ? undefined : server.range, @@ -423,6 +489,124 @@ export abstract class AbstractAgentHostCustomizationService extends Disposable i return !entry.rejected && entry.tokenForwarded !== false; } + /** + * Repairs a Connector connection that the Connector service reported as broken, without prompting, the first + * time one of its servers reports it. Only when that does not bring the servers back does the user get a + * notification that offers an explicit reconnect, which may open the browser. + */ + private _isReconnectingCopilotConnector(sessionResource: URI, server: McpServerCustomization): boolean { + const connectorName = readMcpServerConnectorName(server); + if (connectorName === undefined) { + return false; + } + const state = server.state; + const reconnectRequired = isCopilotConnectorReconnectRequired(state); + let attempt = this._copilotConnectorReconnects.get(connectorName); + if (attempt) { + this._updateCopilotConnectorReconnect(connectorName, attempt, state); + attempt = this._copilotConnectorReconnects.get(connectorName); + } else if (reconnectRequired) { + const label = getMcpServerDisplayLabel({ name: server.name, displayName: readMcpServerDisplayName(server) }); + attempt = this._startCopilotConnectorReconnect(connectorName, label, new ResourceSet()); + } + attempt?.sessions.add(sessionResource); + return reconnectRequired && attempt !== undefined && attempt.isInProgress; + } + + /** + * Observes every state change of the sessions that saw a reconnect attempt, so that a transient restart is not + * missed when nobody reads the servers in between. + */ + private _reconcileCopilotConnectorReconnects(): void { + for (const [connectorName, attempt] of [...this._copilotConnectorReconnects]) { + for (const sessionResource of [...attempt.sessions]) { + const target = this._resolveTarget(sessionResource); + if (!target) { + attempt.sessions.delete(sessionResource); + continue; + } + for (const { server } of flattenMcpServerCustomizations(target.customizations)) { + if (this._copilotConnectorReconnects.get(connectorName) !== attempt) { + break; + } + if (readMcpServerConnectorName(server) === connectorName) { + this._updateCopilotConnectorReconnect(connectorName, attempt, server.state); + } + } + } + } + } + + private _updateCopilotConnectorReconnect(connectorName: string, attempt: CopilotConnectorReconnectAttempt, state: McpServerState): void { + switch (state.kind) { + case McpServerStatus.Ready: + if (attempt.phase !== CopilotConnectorReconnectPhase.Succeeded) { + this._logService.info(`[AgentHost] Copilot Connector '${connectorName}' is connected again`); + attempt.succeed(); + } + return; + case McpServerStatus.Starting: + if (attempt.phase === CopilotConnectorReconnectPhase.Verifying) { + attempt.restarted = true; + } + return; + default: + if (!isCopilotConnectorReconnectRequired(state)) { + return; + } + if (attempt.phase === CopilotConnectorReconnectPhase.Verifying && attempt.restarted) { + this._failCopilotConnectorReconnect(connectorName, attempt, 'the connection is still broken after the restart'); + } else if (attempt.phase === CopilotConnectorReconnectPhase.Succeeded) { + if (Date.now() - attempt.phaseTime < COPILOT_CONNECTOR_RECONNECT_COOLDOWN_MS) { + // The silent repair did not last, so repeating it would only loop. + this._failCopilotConnectorReconnect(connectorName, attempt, 'the connection broke again shortly after reconnecting'); + } else { + const { label, sessions } = attempt; + this._copilotConnectorReconnects.deleteAndDispose(connectorName); + this._startCopilotConnectorReconnect(connectorName, label, sessions); + } + } + } + } + + private _startCopilotConnectorReconnect(connectorName: string, label: string, sessions: ResourceSet): CopilotConnectorReconnectAttempt { + const attempt = new CopilotConnectorReconnectAttempt(label, sessions); + this._copilotConnectorReconnects.set(connectorName, attempt); + this._logService.info(`[AgentHost] Copilot Connector '${connectorName}' reported a broken connection; reconnecting`); + this._copilotConnectorAuthorization.reconnect(connectorName, false).then(reconnected => { + if (this._store.isDisposed || this._copilotConnectorReconnects.get(connectorName) !== attempt || attempt.phase !== CopilotConnectorReconnectPhase.Reconnecting) { + return; + } + if (reconnected) { + this._verifyCopilotConnectorReconnect(connectorName, attempt); + } else { + this._failCopilotConnectorReconnect(connectorName, attempt, 'it needs the user to reconnect'); + } + this._fireCustomizationsChanged(); + }); + return attempt; + } + + private _verifyCopilotConnectorReconnect(connectorName: string, attempt: CopilotConnectorReconnectAttempt): void { + attempt.verify(disposableTimeout(() => { + if (attempt.phase === CopilotConnectorReconnectPhase.Verifying) { + this._failCopilotConnectorReconnect(connectorName, attempt, 'its servers did not become ready in time'); + this._fireCustomizationsChanged(); + } + }, this._copilotConnectorReconnectVerificationTimeoutMs)); + } + + private _failCopilotConnectorReconnect(connectorName: string, attempt: CopilotConnectorReconnectAttempt, reason: string): void { + this._logService.info(`[AgentHost] Could not reconnect Copilot Connector '${connectorName}' automatically: ${reason}`); + attempt.fail(); + this._copilotConnectorAuthorization.notifyReconnectRequired(attempt.label, connectorName, () => { + if (this._copilotConnectorReconnects.get(connectorName) === attempt) { + attempt.restarted = false; + this._verifyCopilotConnectorReconnect(connectorName, attempt); + } + }); + } + private _reconcileMcpAutoAuthenticationAttempts(): void { for (const [key, entry] of this._mcpAutoAuthentication) { const target = this._resolveTarget(entry.sessionResource); @@ -842,6 +1026,7 @@ export abstract class AbstractAgentHostCustomizationService extends Disposable i protected _fireCustomizationsChanged(): void { this._reconcileMcpAutoAuthenticationAttempts(); + this._reconcileCopilotConnectorReconnects(); this._onDidChangeCustomizations.fire(); } @@ -942,6 +1127,46 @@ class AgentHostCopilotConnectorAuthorization { message: localize('agentHost.mcpConnectorStillUnauthorized', "{0} still cannot access Copilot connectors. Authorize Copilot connectors with the same GitHub account that you use for GitHub Copilot, then sign in again.", label), }); } + + /** Resolves whether the connection was re-established; failures are logged rather than thrown. */ + async reconnect(connectorName: string, interactive: boolean): Promise { + try { + return await this._copilotConnectorsService.reconnect(connectorName, interactive, CancellationToken.None); + } catch (error) { + if (isCancellationError(error)) { + this._logService.info(`[AgentHost] Reconnecting Copilot Connector '${connectorName}' was cancelled`); + } else { + this._logService.warn(`[AgentHost] Failed to reconnect Copilot Connector '${connectorName}'`, error); + if (interactive) { + this._notificationService.notify({ + severity: Severity.Error, + message: error instanceof CopilotConnectorsError + ? error.message + : localize('agentHost.mcpConnectorReconnectFailed', "Could not reconnect {0}: {1}", connectorName, getErrorMessage(error)), + }); + } + } + return false; + } + } + + /** Asks the user to reconnect a Connector whose connection could not be repaired automatically. */ + notifyReconnectRequired(label: string, connectorName: string, onDidReconnect: () => void): void { + this._notificationService.prompt( + Severity.Warning, + localize('agentHost.mcpConnectorReconnectRequired', "{0} lost its connection and could not reconnect automatically. Reconnect it to use its tools again.", label), + [{ + label: localize('agentHost.mcpConnectorReconnect', "Reconnect"), + telemetryId: NotificationActionTelemetryId.Reconnect, + run: async () => { + if (await this.reconnect(connectorName, true)) { + onDidReconnect(); + } + }, + }], + { telemetry: NotificationTelemetryId.CopilotConnectorReconnect }, + ); + } } async function listMcpServerTools(handleMcpRequest: NonNullable, channel: string): Promise { diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts index f3391c504da161..3aa42ce29f8753 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/aiCustomizationManagementEditor.ts @@ -24,7 +24,7 @@ import { DisposableStore, IDisposable, IReference, MutableDisposable, toDisposab import { Event } from '../../../../../base/common/event.js'; import { MarkdownString } from '../../../../../base/common/htmlContent.js'; import { ResourceMap, ResourceSet } from '../../../../../base/common/map.js'; -import { autorun } from '../../../../../base/common/observable.js'; +import { autorun, IObservable } from '../../../../../base/common/observable.js'; import { Orientation, Sizing, SplitView } from '../../../../../base/browser/ui/splitview/splitview.js'; import { Color } from '../../../../../base/common/color.js'; import { localize } from '../../../../../nls.js'; @@ -1378,8 +1378,8 @@ export class AICustomizationManagementEditor extends EditorPane { this.connectorDetailContainer = DOM.append(contentInner, $('.connector-detail-container')); this.createEmbeddedConnectorDetail(); - this.editorDisposables.add(this.mcpListWidget.onDidSelectConnector(connector => { - this.showEmbeddedConnectorDetail(connector); + this.editorDisposables.add(this.mcpListWidget.onDidSelectConnector(({ connector, error }) => { + this.showEmbeddedConnectorDetail(connector, error); })); this.editorDisposables.add(this.mcpListWidget.onDidRequestOpenMigrations(() => { @@ -6289,13 +6289,13 @@ export class AICustomizationManagementEditor extends EditorPane { this.editorDisposables.add(DOM.addDisposableListener(backButton, 'click', () => this.goBackFromConnectorDetail())); } - private showEmbeddedConnectorDetail(connector: ICopilotConnector): void { + private showEmbeddedConnectorDetail(connector: ICopilotConnector, error?: IObservable): void { if (!this.embeddedConnectorDetail) { return; } this.viewMode = 'connectorDetail'; this.updateContentVisibility(); - this.embeddedConnectorDetail.setInput(connector); + this.embeddedConnectorDetail.setInput(connector, error); if (this.dimension) { this.layout(this.dimension); } diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/copilotConnectorsService.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/copilotConnectorsService.ts index 0a6a459d2ebb86..e42733df89db28 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/copilotConnectorsService.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/copilotConnectorsService.ts @@ -48,6 +48,8 @@ const maxMcpServersPerConnector = 64; const refreshInterval = 60_000; const connectionPollInterval = 2_000; const connectionTimeout = 5 * 60_000; +/** A silent reconnect needs no consent, so it settles quickly or is left to the user. */ +const silentReconnectTimeout = 30_000; const maxConnectCatalogResets = 3; const requestTimeout = 30_000; /** Scopes of the Copilot credential forwarded to the Agent Host; Connectors are only available on GitHub.com. */ @@ -103,9 +105,12 @@ type CopilotConnectorsCatalogSnapshotClassification = { connectedMcpServerCount: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; isMeasurement: true; comment: 'Number of MCP servers advertised by connected connectors.' }; }; +type CopilotConnectorConnectionAction = 'connect' | 'disconnect' | 'reconnect'; +type CopilotConnectorConnectionActionOutcome = 'success' | 'error' | 'cancelled' | 'userActionRequired'; + type CopilotConnectorConnectionActionEvent = { - action: 'connect' | 'disconnect'; - outcome: 'success' | 'error' | 'cancelled'; + action: CopilotConnectorConnectionAction; + outcome: CopilotConnectorConnectionActionOutcome; connectionStatusBefore: CopilotConnectorConnectionStatus | 'not_loaded'; connectionStatusAfter: CopilotConnectorConnectionStatus | 'not_loaded'; durationMs: number; @@ -115,9 +120,9 @@ type CopilotConnectorConnectionActionEvent = { type CopilotConnectorConnectionActionClassification = { owner: 'pwang347'; - comment: 'Tracks explicit Copilot connector connection actions and outcomes for rollout and comparison with MCP server installation and usage.'; - action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the user attempted to connect or disconnect a connector.' }; - outcome: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the connection action succeeded, failed, or was cancelled.' }; + comment: 'Tracks Copilot connector connection actions and outcomes for rollout and comparison with MCP server installation and usage.'; + action: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Whether the user connected or disconnected a connector, or VS Code silently reconnected a broken connection.' }; + outcome: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; comment: 'Whether the connection action succeeded, failed, was cancelled, or needs the user to act.' }; connectionStatusBefore: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Last known connector connection status before the action.' }; connectionStatusAfter: { classification: 'SystemMetaData'; purpose: 'FeatureInsight'; comment: 'Last known connector connection status after the action.' }; durationMs: { classification: 'SystemMetaData'; purpose: 'PerformanceAndHealth'; isMeasurement: true; comment: 'Duration of the connection action in milliseconds, including authorization and polling.' }; @@ -217,6 +222,13 @@ export interface ICopilotConnectorsService { checkConnection(token: CancellationToken): Promise; connect(name: string, token: CancellationToken): Promise; disconnect(name: string, token: CancellationToken): Promise; + /** + * Re-establishes a connection that the Connector service reported as broken, then restarts the Connector's + * servers in live Agent Host sessions. Without `interactive`, it refreshes the connection with the existing + * Connector authorization, never prompts or opens a browser, and resolves `false` when the user must act. + * With `interactive`, it disconnects and connects again, which can prompt and open the consent page. + */ + reconnect(name: string, interactive: boolean, token: CancellationToken): Promise; } export class CopilotConnectorsService extends Disposable implements ICopilotConnectorsService { @@ -569,12 +581,48 @@ export class CopilotConnectorsService extends Disposable implements ICopilotConn }); } - private async trackConnectionAction(action: 'connect' | 'disconnect', name: string, operation: () => Promise): Promise { + async reconnect(name: string, interactive: boolean, token: CancellationToken): Promise { + if (interactive) { + const connectors = await this.refresh(token); + if (connectors.some(connector => connector.name === name && connector.connectionStatus === 'connected')) { + await this.disconnect(name, token); + } + await this.connect(name, token); + return true; + } + return this.trackConnectionAction('reconnect', name, async () => { + const operation = await this.createOperation(token); + try { + const authentication = await this.getAuthentication(operation.token, true); + if (!authentication?.sessions.some(session => hasConnectorScope(session, false))) { + return false; + } + const initialStatus = this._connectors.find(connector => connector.name === name)?.connectionStatus; + const document = await this.withClient( + authentication, + operation.token, + (client, cancellationToken, deadline) => client.connectors.connect(name, cancellationToken, { caller: 'copilotConnectors.reconnect', deadline }) + ); + if (parseHttpsUri(document.consent_link)) { + // Consent needs the user; only an explicit reconnect may open the browser. + return false; + } + await this.pollConnection(name, { initialStatus, deadline: Date.now() + silentReconnectTimeout, observedPending: false }, operation.token); + await this.refreshAgentHostConnectorSessions(name); + return true; + } finally { + operation.dispose(); + } + }, reconnected => reconnected ? 'success' : 'userActionRequired'); + } + + private async trackConnectionAction(action: CopilotConnectorConnectionAction, name: string, operation: () => Promise, getOutcome?: (result: T) => CopilotConnectorConnectionActionOutcome): Promise { const startTime = Date.now(); const connectionStatusBefore = this.getConnectionStatus(name); try { - await operation(); - this.reportConnectionAction(action, name, 'success', connectionStatusBefore, Date.now() - startTime); + const result = await operation(); + this.reportConnectionAction(action, name, getOutcome?.(result) ?? 'success', connectionStatusBefore, Date.now() - startTime); + return result; } catch (error) { this.reportConnectionAction(action, name, isCancellationError(error) ? 'cancelled' : 'error', connectionStatusBefore, Date.now() - startTime, error); throw error; @@ -582,9 +630,9 @@ export class CopilotConnectorsService extends Disposable implements ICopilotConn } private reportConnectionAction( - action: 'connect' | 'disconnect', + action: CopilotConnectorConnectionAction, name: string, - outcome: 'success' | 'error' | 'cancelled', + outcome: CopilotConnectorConnectionActionOutcome, connectionStatusBefore: CopilotConnectorConnectionStatus | 'not_loaded', durationMs: number, error?: unknown, diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/embeddedConnectorDetail.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/embeddedConnectorDetail.ts index 66ea335dca847d..fbc12b3b53c711 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/embeddedConnectorDetail.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/embeddedConnectorDetail.ts @@ -9,6 +9,7 @@ import { Button } from '../../../../../base/browser/ui/button/button.js'; import { CancellationToken, CancellationTokenSource } from '../../../../../base/common/cancellation.js'; import { getErrorMessage, isCancellationError } from '../../../../../base/common/errors.js'; import { Disposable, DisposableStore, MutableDisposable } from '../../../../../base/common/lifecycle.js'; +import { autorun, IObservable } from '../../../../../base/common/observable.js'; import { URI } from '../../../../../base/common/uri.js'; import { generateUuid } from '../../../../../base/common/uuid.js'; import { localize } from '../../../../../nls.js'; @@ -70,6 +71,8 @@ export class EmbeddedConnectorDetail extends Disposable { private readonly statusBadgeEl: HTMLElement; private readonly titleActionsEl: HTMLElement; private readonly descriptionEl: HTMLElement; + private readonly errorSection: HTMLElement; + private readonly errorMessageEl: HTMLElement; private readonly detailsEl: HTMLElement; private readonly factsEl: HTMLElement; private readonly containsEl: HTMLElement; @@ -78,6 +81,7 @@ export class EmbeddedConnectorDetail extends Disposable { private readonly otherInfoFactsEl: HTMLElement; private readonly emptyEl: HTMLElement; private readonly renderDisposables = this._register(new DisposableStore()); + private readonly errorDisposables = this._register(new DisposableStore()); private readonly factHoverGroupId = generateUuid(); private readonly narrowLayoutUpdate = this._register(new MutableDisposable()); private readonly actionCancellation = this._register(new MutableDisposable()); @@ -123,6 +127,16 @@ export class EmbeddedConnectorDetail extends Disposable { this.descriptionEl = DOM.append(this.root, $('.embedded-detail-description')); + this.errorSection = DOM.append(this.root, $('section.mcp-detail-diagnostic-section')); + const errorCard = DOM.append(this.errorSection, $('.mcp-detail-diagnostic-card.error')); + const errorHeader = DOM.append(errorCard, $('.mcp-detail-diagnostic-header')); + const errorIcon = DOM.append(errorHeader, $('.mcp-detail-diagnostic-icon.codicon.codicon-error')); + errorIcon.setAttribute('aria-hidden', 'true'); + DOM.append(errorHeader, $('.mcp-detail-diagnostic-summary')).textContent = localize('connectorDetailError', "This connector reported an error"); + const errorDetails = DOM.append(errorCard, $('.mcp-detail-diagnostic-details')); + this.errorMessageEl = DOM.append(errorDetails, $('p.mcp-detail-diagnostic-message')); + this.errorSection.style.display = 'none'; + this.detailsEl = DOM.append(this.root, $('.embedded-detail-section.connector-detail-facts')); DOM.append(this.detailsEl, $('h3.embedded-detail-section-title')).textContent = localize('connectorDetailsTitle', "Details"); this.factsEl = DOM.append(this.detailsEl, $('.embedded-detail-facts.plugin-detail-flat-list')); @@ -156,11 +170,12 @@ export class EmbeddedConnectorDetail extends Disposable { return this.primaryActionButton; } - setInput(connector: ICopilotConnector): void { + setInput(connector: ICopilotConnector, error?: IObservable): void { this.actionCancellation.value?.cancel(); this.actionCancellation.clear(); this.pendingAction = undefined; this.current = connector; + this.bindError(error); this.renderItem(); } @@ -169,9 +184,23 @@ export class EmbeddedConnectorDetail extends Disposable { this.actionCancellation.clear(); this.pendingAction = undefined; this.current = undefined; + this.bindError(undefined); this.renderItem(); } + private bindError(error: IObservable | undefined): void { + this.errorDisposables.clear(); + this.errorSection.style.display = 'none'; + this.errorMessageEl.textContent = ''; + if (error) { + this.errorDisposables.add(autorun(reader => { + const message = error.read(reader); + this.errorMessageEl.textContent = message ?? ''; + this.errorSection.style.display = message ? '' : 'none'; + })); + } + } + override dispose(): void { this.actionCancellation.value?.cancel(); this.pendingAction = undefined; diff --git a/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts b/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts index 430405fdabf9a2..41f1d467e83e9b 100644 --- a/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts +++ b/src/vs/workbench/contrib/chat/browser/aiCustomization/mcpListWidget.ts @@ -353,6 +353,7 @@ interface IMcpServerItemTemplateData { renderedRowKey?: string; /** What the actions currently show, so an unchanged status does not rebuild them. */ renderedStatusSignature?: string; + renderedConnectorError?: boolean; currentElement?: IMcpInstalledEntry; } @@ -530,6 +531,7 @@ export class McpServerItemRenderer extends Disposable implements IListRenderer()); readonly onDidRequestShowPlugin = this._onDidRequestShowPlugin.event; - private readonly _onDidSelectConnector = this._register(new Emitter()); + private readonly _onDidSelectConnector = this._register(new Emitter<{ connector: ICopilotConnector; error?: IObservable }>()); readonly onDidSelectConnector = this._onDidSelectConnector.event; private readonly _onDidRequestOpenMigrations = this._register(new Emitter()); @@ -2390,16 +2400,7 @@ export class McpListWidget extends Disposable { setRowLineHeight: false, horizontalScrolling: false, accessibilityProvider: { - getAriaLabel: entry => { - if (entry.type === 'group-header') { - return getCustomizationGroupAriaLabel(entry.label, entry.count, entry.description); - } - return entry.type === 'connector-item' - ? localize('connectorMcpServerAriaLabel', "{0}. Connector.", entry.label) - : entry.type === 'marketplace-item' - ? localize('marketplaceMcpServerRowAriaLabel', "{0}. Available to install from the MCP marketplace.", entry.server.label) - : this.getMcpEntryAriaLabel(entry); - }, + getAriaLabel: entry => this.getMcpTreeEntryAriaLabel(entry), getWidgetAriaLabel: () => localize('mcpServersListAriaLabel', "MCP Servers"), }, openOnSingleClick: true, @@ -2412,7 +2413,10 @@ export class McpListWidget extends Disposable { return; } if (entry.type !== 'marketplace-item' && isConnectorMcpEntry(entry)) { - this._onDidSelectConnector.fire(entry.connector.connector); + this._onDidSelectConnector.fire({ + connector: entry.connector.connector, + error: this.getConnectorDetailError(entry), + }); return; } this._onDidSelectServer.fire(entry.type === 'marketplace-item' @@ -2796,6 +2800,15 @@ export class McpListWidget extends Disposable { return undefined; } + private getConnectorDetailError(entry: IMcpConnectorItemEntry): IObservable { + const detailChanged = observableSignalFromEvent(this, this.onDidUpdateServerDetail); + const id = getMcpRowKey(entry); + return derived(this, reader => { + detailChanged.read(reader); + return this.getUpdatedServerDetail(id)?.error?.read(reader); + }); + } + private createInstalledMcpServerDetailInput(entry: IMcpInstalledEntry): IMcpServerDetailInput { const activeSessionServer = getActiveSessionServer(entry); if (activeSessionServer) { @@ -2845,10 +2858,21 @@ export class McpListWidget extends Disposable { return { provenance, definitionUnavailable }; } + private getMcpTreeEntryAriaLabel(entry: IMcpSectionEntry): string | IObservable { + if (entry.type === 'group-header') { + return getCustomizationGroupAriaLabel(entry.label, entry.count, entry.description); + } + if (entry.type === 'marketplace-item') { + return localize('marketplaceMcpServerRowAriaLabel', "{0}. Available to install from the MCP marketplace.", entry.server.label); + } + return this.getMcpEntryAriaLabel(entry); + } + private getMcpEntryAriaLabel(entry: IMcpInstalledEntry): IObservable { return derived(this, reader => { this.agentHostCustomizationsChanged.read(reader); - const label = getMcpEntryLabelWithSource(entry, this.labelService, this.agentPluginService, this.extensionsWorkbenchService); + const labelWithSource = getMcpEntryLabelWithSource(entry, this.labelService, this.agentPluginService, this.extensionsWorkbenchService); + const label = entry.type === 'connector-item' ? localize('connectorMcpServerAriaLabel', "{0}, Connector", labelWithSource) : labelWithSource; const compatibilityKind = this.getMcpServerCompatibilityKind(entry, reader); const compatibility = getMcpRowMessagePresentation(compatibilityKind, this.isMcpServerMigratable(entry, reader)); const activeSessionResource = this.customizationHarnessService.activeSessionResource.read(reader); diff --git a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts index 19165ecd41ad14..11b31586add5dc 100644 --- a/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/agentSessions/agentHostCustomizationService.test.ts @@ -25,10 +25,10 @@ import { IAgentConnection } from '../../../../../../platform/agentHost/common/ag import { type AgentProvider, type IAgentPluginInstallation } from '../../../../../../platform/agentHost/common/agent.js'; import { readRuntimePluginEnablement, withRuntimePluginEnablement } from '../../../../../../platform/agentHost/common/meta/pluginEnablementMeta.js'; import { IAgentHostMcpOAuthMetadataService } from '../../../../../../platform/agentHost/common/agentHostMcpOAuthMetadataService.js'; -import { withMcpServerConnectorNameMeta, withMcpServerControllingSettingMeta, withMcpServerDisplayNameMeta, withMcpServerSourceMeta, withMcpServerSourcePluginMeta } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; +import { copilotConnectorReconnectRequiredErrorType, withMcpServerConnectorNameMeta, withMcpServerControllingSettingMeta, withMcpServerDisplayNameMeta, withMcpServerSourceMeta, withMcpServerSourcePluginMeta } from '../../../../../../platform/agentHost/common/meta/mcpCustomizationMeta.js'; import { IAgentSubscription } from '../../../../../../platform/agentHost/common/state/agentSubscription.js'; import { ActionType, type ActionEnvelope } from '../../../../../../platform/agentHost/common/state/sessionActions.js'; -import { CustomizationEnablementKind, CustomizationLoadStatus, CustomizationType, McpAuthRequiredReason, McpServerCustomization, McpServerStatus, type Customization, type CustomizationEnablement, type PluginCustomization } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; +import { CustomizationEnablementKind, CustomizationLoadStatus, CustomizationType, McpAuthRequiredReason, McpServerCustomization, McpServerStatus, type Customization, type CustomizationEnablement, type McpServerState, type PluginCustomization } from '../../../../../../platform/agentHost/common/state/protocol/state.js'; import { createAgentHostResourceUriMapper, identityAgentHostResourceUriMapper, IAgentHostResourceUriMapper } from '../../../../../../platform/agentHost/common/agentHostUri.js'; import { createSessionState, RootState, SessionState, SessionStatus, StateComponents } from '../../../../../../platform/agentHost/common/state/sessionState.js'; import { IOutputService } from '../../../../../services/output/common/output.js'; @@ -37,7 +37,7 @@ import { AbstractMessageLogger, ILogService, ILoggerService, LogLevel, NullLogSe import { ILabelService } from '../../../../../../platform/label/common/label.js'; import { ConfigurationTarget, IConfigurationService } from '../../../../../../platform/configuration/common/configuration.js'; import { IDefaultAccountService } from '../../../../../../platform/defaultAccount/common/defaultAccount.js'; -import { INotification, INotificationHandle, INotificationService, Severity } from '../../../../../../platform/notification/common/notification.js'; +import { INotification, INotificationHandle, INotificationService, IPromptChoice, Severity } from '../../../../../../platform/notification/common/notification.js'; import { TestNotificationService } from '../../../../../../platform/notification/test/common/testNotificationService.js'; import { ICopilotConnectorsService } from '../../../browser/aiCustomization/copilotConnectorsService.js'; import { TestConfigurationService } from '../../../../../../platform/configuration/test/common/testConfigurationService.js'; @@ -163,6 +163,10 @@ class TestAgentHostCustomizationService extends AbstractAgentHostCustomizationSe this._mcpAuthenticationVerificationTimeoutMs = timeoutMs; } + setCopilotConnectorReconnectVerificationTimeout(timeoutMs: number): void { + this._copilotConnectorReconnectVerificationTimeoutMs = timeoutMs; + } + /** Replaces a target's customizations as the host would, notifying observers. */ updateTarget(target: FakeTarget, customizations: readonly Customization[]): void { target.customizations = customizations; @@ -1275,9 +1279,10 @@ suite('AbstractAgentHostCustomizationService', () => { id: 'connector-session', accessToken: 'connector-token', scopes: ['read:user', 'user:email', 'write:plugin_gateway_connections'], account: { id: 'test-account', label: 'Test Account' }, }; - function createConnectorSut(onRefresh: (sut: TestAgentHostCustomizationService) => Promise | void, options: { readonly authorizationError?: Error; readonly authenticationSessions?: AuthenticationSession[] } = {}) { + function createConnectorSut(onRefresh: (sut: TestAgentHostCustomizationService) => Promise | void, options: { readonly authorizationError?: Error; readonly authenticationSessions?: AuthenticationSession[]; readonly reconnect?: (interactive: boolean) => Promise } = {}) { const operations: string[] = []; const notifications: string[] = []; + const prompts: IPromptChoice[][] = []; const logs: string[] = []; const sut: TestAgentHostCustomizationService = createSut(undefined, { authenticationSessions: options.authenticationSessions ?? [fullScopeSession], @@ -1288,6 +1293,11 @@ suite('AbstractAgentHostCustomizationService', () => { notifications.push(`${notification.severity}:${notification.message}`); return new class extends mock() { }(); } + override prompt(severity: Severity, message: string, choices: IPromptChoice[]): INotificationHandle { + notifications.push(`${severity}:${message}`); + prompts.push(choices); + return new class extends mock() { }(); + } }()); instantiationService.stub(ICopilotConnectorsService, new class extends mock() { override async authorize(): Promise { @@ -1301,12 +1311,116 @@ suite('AbstractAgentHostCustomizationService', () => { operations.push(`refresh:${connectorName}`); await onRefresh(sut); } + override async reconnect(name: string, interactive: boolean): Promise { + operations.push(`reconnect:${name}:${interactive ? 'interactive' : 'silent'}`); + return options.reconnect ? options.reconnect(interactive) : true; + } }()); }, }); - return { sut, operations, notifications, logs }; + return { sut, operations, notifications, prompts, logs }; } + suite('automatic reconnect', () => { + const meta = withMcpServerConnectorNameMeta(withMcpServerDisplayNameMeta(undefined, 'Work IQ'), 'workiqmcp'); + const reconnectRequired: McpServerCustomization = { + ...mcpServer('workiq', 'connector-workiq'), + _meta: meta, + state: { kind: McpServerStatus.Error, error: { errorType: copilotConnectorReconnectRequiredErrorType, message: 'Reconnect Work IQ' } }, + }; + const withState = (state: McpServerState): McpServerCustomization => ({ ...reconnectRequired, state }); + const reconnectNotification = `${Severity.Warning}:Work IQ (Connector) lost its connection and could not reconnect automatically. Reconnect it to use its tools again.`; + + test('silently reconnects once and reports the server as authenticating until it is ready', async () => { + const session = URI.parse('vscode-agent-session:///session-1'); + const target = new FakeTarget([reconnectRequired]); + const reconnected = new DeferredPromise(); + const { sut, operations, notifications } = createConnectorSut(() => { }, { reconnect: () => reconnected.p }); + sut.setTarget(session, target); + + const reconnecting = sut.getMcpServers(session)[0].authenticating; + const repeated = sut.getMcpServers(session)[0].authenticating; + reconnected.complete(true); + await timeout(0); + const verifying = sut.getMcpServers(session)[0].authenticating; + sut.updateTarget(target, [withState({ kind: McpServerStatus.Starting })]); + sut.updateTarget(target, [withState({ kind: McpServerStatus.Ready })]); + const ready = sut.getMcpServers(session)[0].authenticating; + assert.deepStrictEqual({ reconnecting, repeated, verifying, ready, operations, notifications }, { + reconnecting: true, + repeated: true, + verifying: true, + ready: false, + operations: ['reconnect:workiqmcp:silent'], + notifications: [], + }); + }); + + test('asks the user to reconnect when a silent reconnect needs consent, and reconnects interactively on request', async () => { + const session = URI.parse('vscode-agent-session:///session-1'); + const target = new FakeTarget([reconnectRequired]); + const { sut, operations, notifications, prompts } = createConnectorSut(() => { }, { reconnect: async interactive => interactive }); + sut.setTarget(session, target); + + sut.getMcpServers(session); + await timeout(0); + const afterFailure = sut.getMcpServers(session)[0].authenticating; + await prompts[0][0].run(); + const afterUserReconnect = sut.getMcpServers(session)[0].authenticating; + assert.deepStrictEqual({ afterFailure, afterUserReconnect, choices: prompts.map(choices => choices.map(choice => choice.label)), operations, notifications }, { + afterFailure: false, + afterUserReconnect: true, + choices: [['Reconnect']], + operations: ['reconnect:workiqmcp:silent', 'reconnect:workiqmcp:interactive'], + notifications: [reconnectNotification], + }); + }); + + test('asks the user to reconnect when the connection is still broken after the restart', async () => { + const session = URI.parse('vscode-agent-session:///session-1'); + const target = new FakeTarget([reconnectRequired]); + const { sut, operations, notifications } = createConnectorSut(() => { }); + sut.setTarget(session, target); + + sut.getMcpServers(session); + await timeout(0); + sut.updateTarget(target, [withState({ kind: McpServerStatus.Starting })]); + sut.updateTarget(target, [reconnectRequired]); + const afterFailure = sut.getMcpServers(session)[0].authenticating; + sut.updateTarget(target, [reconnectRequired]); + assert.deepStrictEqual({ afterFailure, operations, notifications }, { + afterFailure: false, + operations: ['reconnect:workiqmcp:silent'], + notifications: [reconnectNotification], + }); + }); + + test('asks the user to reconnect when the servers do not become ready in time', async () => { + const session = URI.parse('vscode-agent-session:///session-1'); + const target = new FakeTarget([reconnectRequired]); + const { sut, notifications } = createConnectorSut(() => { }); + sut.setCopilotConnectorReconnectVerificationTimeout(0); + sut.setTarget(session, target); + + sut.getMcpServers(session); + await timeout(0); + await timeout(0); + assert.deepStrictEqual({ authenticating: sut.getMcpServers(session)[0].authenticating, notifications }, { + authenticating: false, + notifications: [reconnectNotification], + }); + }); + + test('does not reconnect servers that are not owned by a Connector', async () => { + const session = URI.parse('vscode-agent-session:///session-1'); + const target = new FakeTarget([{ ...reconnectRequired, _meta: undefined }]); + const { sut, operations } = createConnectorSut(() => { }); + sut.setTarget(session, target); + + assert.deepStrictEqual({ authenticating: sut.getMcpServers(session)[0].authenticating, operations }, { authenticating: false, operations: [] }); + }); + }); + test('signs in through Connector authorization by published Connector name and forwards no MCP token', async () => { const readStatus = captureStatus(); const meta = withMcpServerConnectorNameMeta(undefined, 'workiqmcp'); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/connectorPresentation.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/connectorPresentation.test.ts index efc1397e2ef093..5b502a5d3a0aca 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/connectorPresentation.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/connectorPresentation.test.ts @@ -10,6 +10,7 @@ import { CancellationToken } from '../../../../../../base/common/cancellation.js import { CancellationError } from '../../../../../../base/common/errors.js'; import { Emitter, Event } from '../../../../../../base/common/event.js'; import { toDisposable } from '../../../../../../base/common/lifecycle.js'; +import { observableValue } from '../../../../../../base/common/observable.js'; import { URI } from '../../../../../../base/common/uri.js'; import { mock } from '../../../../../../base/test/common/mock.js'; import { ensureNoDisposablesAreLeakedInTestSuite } from '../../../../../../base/test/common/utils.js'; @@ -95,6 +96,38 @@ suite('Connector presentation', () => { ]); }); + test('detail displays live Connector errors without replacing its action', () => { + const container = DOM.append(document.body, DOM.$('.connector-detail-test')); + disposables.add(toDisposable(() => container.remove())); + const service = new class extends mock() { + override readonly onDidChange = Event.None; + }(); + const detail = disposables.add(new EmbeddedConnectorDetail( + container, () => { }, service, new class extends mock() { }(), new class extends mock() { }(), NullHoverService, + )); + const error = observableValue('connectorError', undefined); + detail.setInput(connector('connected'), error); + const button = container.querySelector('.embedded-detail-title-actions .monaco-button'); + const read = () => ({ + message: container.querySelector('.mcp-detail-diagnostic-message')?.textContent, + display: container.querySelector('.mcp-detail-diagnostic-section')?.style.display, + sameButton: container.querySelector('.embedded-detail-title-actions .monaco-button') === button, + }); + const initial = read(); + error.set('Disconnect and reconnect Mail', undefined); + const failed = read(); + error.set(undefined, undefined); + const recovered = read(); + detail.clearInput(); + error.set('Stale error', undefined); + assert.deepStrictEqual({ initial, failed, recovered, cleared: read() }, { + initial: { message: '', display: 'none', sameButton: true }, + failed: { message: 'Disconnect and reconnect Mail', display: '', sameButton: true }, + recovered: { message: '', display: 'none', sameButton: true }, + cleared: { message: '', display: 'none', sameButton: false }, + }); + }); + test('detail links the connector homepage and Copilot Connectors source', async () => { const homepageUrl = 'https://amplitude.com/a%2Fb?query=x%26y'; const container = DOM.append(document.body, DOM.$('.connector-detail-test')); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/copilotConnectorsService.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/copilotConnectorsService.test.ts index b6fc39b3aacdd0..3bf7ae203042c3 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/copilotConnectorsService.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/copilotConnectorsService.test.ts @@ -1767,6 +1767,72 @@ suite('CopilotConnectorsService', () => { }); }); + test('silently reconnects a broken connection with the existing authorization and restarts its sessions', async () => { + const fixture = createFixture([ + { body: { status: 'Connected', provisioning_state: 'Succeeded' } }, + { body: catalogResponse('connected') }, + ]); + const reconnected = await fixture.service.reconnect('mail', false, CancellationToken.None); + assert.deepStrictEqual({ + reconnected, + methods: fixture.requests.map(request => request.type), + callers: fixture.apiRequests.map(request => request.options?.caller), + opened: fixture.opened, + consent: fixture.consentCalls.length, + reconciliations: fixture.reconciliationNames, + outcome: fixture.telemetryService.events.filter(event => event.name === 'copilotConnectors.connectionAction').map(event => [event.data.action, event.data.outcome]), + }, { + reconnected: true, + methods: ['PUT', 'GET'], + callers: ['copilotConnectors.reconnect', 'copilotConnectors.query'], + opened: [], + consent: 0, + reconciliations: [undefined, 'mail'], + outcome: [['reconnect', 'success']], + }); + }); + + test('a silent reconnect leaves consent to the user without opening the browser', async () => { + const fixture = createFixture([ + { body: { status: 'Unauthenticated', provisioning_state: 'Succeeded', consent_link: 'https://github.com/settings/copilot/connectors/mail' } }, + ]); + const reconnected = await fixture.service.reconnect('mail', false, CancellationToken.None); + assert.deepStrictEqual({ + reconnected, + methods: fixture.requests.map(request => request.type), + opened: fixture.opened, + consent: fixture.consentCalls.length, + outcome: fixture.telemetryService.events.filter(event => event.name === 'copilotConnectors.connectionAction').map(event => [event.data.action, event.data.outcome]), + }, { reconnected: false, methods: ['PUT'], opened: [], consent: 0, outcome: [['reconnect', 'userActionRequired']] }); + }); + + test('a silent reconnect without Connector authorization neither prompts nor requests', async () => { + const fixture = createFixture([]); + fixture.setSessions([{ ...fixture.initialSession, scopes: ['read:user'] }]); + const reconnected = await fixture.service.reconnect('mail', false, CancellationToken.None); + assert.deepStrictEqual({ reconnected, requests: fixture.requests.length, opened: fixture.opened, consent: fixture.consentCalls.length }, { + reconnected: false, requests: 0, opened: [], consent: 0, + }); + }); + + test('an interactive reconnect disconnects and connects again through consent', async () => { + const fixture = createFixture([ + { body: catalogResponse('connected') }, + { status: 204 }, + { body: catalogResponse('not_connected') }, + { body: catalogResponse('not_connected') }, + { body: { status: 'Unauthenticated', provisioning_state: 'Succeeded', consent_link: 'https://github.com/settings/copilot/connectors/mail' } }, + { body: catalogResponse('connected') }, + ]); + const reconnected = await fixture.service.reconnect('mail', true, CancellationToken.None); + assert.deepStrictEqual({ reconnected, methods: fixture.requests.map(request => request.type), opened: fixture.opened, status: fixture.service.connectors[0].connectionStatus }, { + reconnected: true, + methods: ['GET', 'DELETE', 'GET', 'GET', 'PUT', 'GET'], + opened: ['https://github.com/settings/copilot/connectors/mail'], + status: 'connected', + }); + }); + test('keeps authoritative connector state when live Agent Host refresh fails', async () => { const fixture = createFixture([{ body: catalogResponse('connected') }]); fixture.setReconciliationError(new Error('Agent Host unavailable')); diff --git a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts index e75ccd30b1f96a..55bbb4ea80a06b 100644 --- a/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts +++ b/src/vs/workbench/contrib/chat/test/browser/aiCustomization/mcpListWidget.test.ts @@ -2487,6 +2487,7 @@ suite('mcpListWidget', () => { function createRenderer(server: AgentHostMcpServer, isSessionsWindow = true, useRealManagementActions = false, authenticate = () => Promise.resolve(true), compatibilityKind: Parameters[0] = undefined, migratable = false) { const store = new DisposableStore(); const onDidChangeCustomizations = store.add(new Emitter()); + const onDidUpdateServerDetail = store.add(new Emitter()); const sessionResource = URI.parse('vscode-agent-session:///session-1'); const activeSessionResource = observableValue('activeSessionResource', sessionResource); let servers: AgentHostMcpServer[] = [server]; @@ -2613,7 +2614,9 @@ suite('mcpListWidget', () => { const widget = Object.create(McpListWidget.prototype) as { createInstalledMcpServerDetailInput(entry: Entry): ReturnType; getUpdatedServerDetail(id: string): ReturnType | undefined; + getConnectorDetailError(entry: Extract): IObservable; installedEntries: { entry: Entry }[]; + getMcpTreeEntryAriaLabel(entry: Entry): string | IObservable; getMcpEntryAriaLabel(entry: Entry): IObservable; isMcpServerMigratable(entry: Entry, reader?: IReader): boolean; getMcpServerActions(entry: Entry, store: DisposableStore): IAction[]; @@ -2630,6 +2633,7 @@ suite('mcpListWidget', () => { labelService, hoverService, agentHostCustomizationsChanged: observableSignalFromEvent('customizationsChanged', onDidChangeCustomizations.event), + onDidUpdateServerDetail: onDidUpdateServerDetail.event, mcpServerCompatibility: observableValue>(widget, new Map(compatibilityKind ? [['native', compatibilityKind]] : [])), getMcpServerCompatibilityKind: () => compatibilityKind, isMcpServerMigratable: () => migratable, @@ -2656,10 +2660,12 @@ suite('mcpListWidget', () => { menuActions: () => menuActions, activeSessionResource, detailInput: (entry: Entry) => widget.createInstalledMcpServerDetailInput(entry), + connectorDetailError: (entry: Extract) => widget.getConnectorDetailError(entry), updatedDetail: (entries: readonly Entry[], id: string) => { widget.installedEntries = entries.map(entry => ({ entry })); return widget.getUpdatedServerDetail(id); }, + notifyDetailUpdated: () => onDidUpdateServerDetail.fire(), setAriaProvider: (provider: (entry: Entry) => IObservable) => { widget.getMcpEntryAriaLabel = provider; }, setRuntimeServers: (next: readonly IMcpServer[]) => runtimeServers.set(next, undefined), menu: (entry: Entry, localServer?: IMcpServer) => { @@ -2695,8 +2701,8 @@ suite('mcpListWidget', () => { render: (entry: Entry = createBuiltinActiveSessionMcpEntries([server])[0]) => { renderer.renderElement(entry, 0, templateData); renderer.setFocusedRowKey(getMcpRowKey(entry)); - const label = widget.getMcpEntryAriaLabel(entry); - ariaSubscription.value = autorun(reader => { ariaLabel = label.read(reader); }); + const label = widget.getMcpTreeEntryAriaLabel(entry); + ariaSubscription.value = autorun(reader => { ariaLabel = typeof label === 'string' ? label : label.read(reader); }); }, read: () => ({ text: templateData.description.textContent, @@ -3730,6 +3736,94 @@ suite('mcpListWidget', () => { }); }); + for (const kind of ['connector-item', 'session-server-item'] as const) { + test(`${kind} shows Connector errors and restores its description after recovery`, () => { + const message = 'The Work IQ connector requires reauthorization. Disconnect and reconnect it.'; + const server = createAgentHostServer({ + name: 'connector-workiq', displayName: 'Work IQ', connectorName: 'workiqmcp', + status: McpServerStatus.Error, state: { kind: McpServerStatus.Error, error: { errorType: 'mcp-server-failed', message } }, + }); + const connector: ICopilotConnector = { + name: 'workiqmcp', displayName: 'Work IQ', description: 'Search work', tags: [], keywords: [], + capabilities: [], representativeQueries: [], connectionStatus: 'connected', scopes: [], + mcpServers: [{ name: 'connector-workiq', type: 'http' }], + }; + const entry: Entry = kind === 'connector-item' + ? { type: kind, id: 'connector-workiq', label: 'Work IQ', description: 'Connector', connector: { id: 'workiqmcp:connector-workiq', connector, serverName: 'connector-workiq' }, activeSessionServer: server } + : { type: kind, server }; + const ctx = createRenderer(server); + disposables.add(ctx.store); + ctx.render(entry); + const initial = ctx.read(); + const button = ctx.actionNode(); + const updatedMessage = 'Updated reconnect guidance'; + ctx.setServers([createAgentHostServer({ ...server, state: { kind: McpServerStatus.Error, error: { errorType: 'mcp-server-failed', message: updatedMessage } } })]); + ctx.notifyUnchanged(); + const updated = { ...ctx.read(), sameButton: ctx.actionNode() === button }; + ctx.setServers([createAgentHostServer({ ...server, status: McpServerStatus.Ready, state: { kind: McpServerStatus.Ready } })]); + ctx.notifyUnchanged(); + const recovered = ctx.read(); + const name = kind === 'connector-item' ? 'Work IQ, Connector' : 'Work IQ (Connector)'; + const description = kind === 'connector-item' ? 'Connector' : ''; + assert.deepStrictEqual({ initial, updated, recovered }, { + initial: { text: message, error: false, display: '', hover: message, ariaLabel: `${name}, Error, ${message}` }, + updated: { text: updatedMessage, error: false, display: '', hover: updatedMessage, ariaLabel: `${name}, Error, ${updatedMessage}`, sameButton: true }, + recovered: { text: description, error: false, display: description ? '' : 'none', hover: description, ariaLabel: `${name}, Running` }, + }); + }); + } + + test('open Connector detail follows an active server discovered later', () => { + const server = createAgentHostServer({ + name: 'connector-workiq', displayName: 'Work IQ', connectorName: 'workiqmcp', + status: McpServerStatus.Error, state: { kind: McpServerStatus.Error, error: { errorType: 'mcp-server-failed', message: 'Reconnect Work IQ' } }, + }); + const connector: ICopilotConnector = { + name: 'workiqmcp', displayName: 'Work IQ', description: 'Search work', tags: [], keywords: [], + capabilities: [], representativeQueries: [], connectionStatus: 'connected', scopes: [], + mcpServers: [{ name: 'connector-workiq', type: 'http' }], + }; + const entry: Extract = { + type: 'connector-item', id: 'workiqmcp:connector-workiq', label: 'Work IQ', description: 'Connector', + connector: { id: 'workiqmcp:connector-workiq', connector, serverName: 'connector-workiq' }, + }; + const ctx = createRenderer(server); + disposables.add(ctx.store); + const id = getMcpRowKey(entry); + ctx.updatedDetail([entry], id); + const observed: (string | undefined)[] = []; + const error = ctx.connectorDetailError(entry); + disposables.add(autorun(reader => { observed.push(error.read(reader)); })); + ctx.updatedDetail([{ ...entry, activeSessionServer: server }], id); + ctx.notifyDetailUpdated(); + ctx.setServers([{ ...server, status: McpServerStatus.Ready, state: { kind: McpServerStatus.Ready } }]); + ctx.notifyUnchanged(); + + assert.deepStrictEqual(observed, [undefined, 'Reconnect Work IQ', undefined]); + }); + + test('clears a Connector error when late ownership metadata disappears', () => { + const server = createAgentHostServer({ name: 'connector-workiq', displayName: 'Work IQ' }); + const entry: Entry = { type: 'session-server-item', server }; + const ctx = createRenderer(server); + disposables.add(ctx.store); + ctx.render(entry); + + const message = 'Disconnect and reconnect Work IQ'; + ctx.setServers([createAgentHostServer({ + ...server, connectorName: 'workiqmcp', status: McpServerStatus.Error, + state: { kind: McpServerStatus.Error, error: { errorType: 'mcp-server-failed', message } }, + })]); + ctx.notifyUnchanged(); + const error = ctx.read(); + ctx.setServers([server]); + ctx.notifyUnchanged(); + assert.deepStrictEqual({ error, recovered: ctx.read() }, { + error: { text: message, error: false, display: '', hover: message, ariaLabel: `Work IQ (Connector), Error, ${message}` }, + recovered: { text: '', error: false, display: 'none', hover: '', ariaLabel: 'Work IQ (Connector), Running' }, + }); + }); + test('native error updates retain management buttons without replacing descriptions', () => { const native = nativeServer(); const entry: Entry = { type: 'server-item', server: native.workbenchServer, localServer: native.server }; diff --git a/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts b/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts index d4ce2a097ab2fc..fa575a85f4ea4b 100644 --- a/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts +++ b/src/vs/workbench/test/browser/componentFixtures/sessions/aiCustomizationManagementEditor.fixture.ts @@ -784,6 +784,16 @@ const reconciledConnectorMcpServers: FixtureAgentHostMcpServer[] = [ { ...activeSessionMcpServers[1], id: 'session/github-copilot-connector-94d26095770df60673dd', name: 'github-copilot-connector-94d26095770df60673dd', displayName: 'Azure Data Explorer', source: 'managed', sourceUri: undefined }, ]; +const brokenConnectorMcpServer: FixtureAgentHostMcpServer = { + ...activeSessionMcpServers[0], + id: 'session/workiq-mail-mcp', + name: 'workiq-mail-mcp', + displayName: 'Work IQ Mail', + connectorName: 'workiq-mail', + status: McpServerStatus.Error, + state: { kind: McpServerStatus.Error, error: { errorType: 'mcp-server-failed', message: 'Disconnect and reconnect Work IQ Mail using the Copilot account for this session to reauthorize it. In VS Code, manage connected connectors under Chat: Open Customizations > MCP Servers or browse Copilot Connectors.' } }, +}; + // Organization managed-settings states for the agent-host harness. const organizationManagedMcpServers: FixtureAgentHostMcpServer[] = [ { ...activeSessionMcpServers[0], id: 'session/contoso-tickets', name: 'contoso-tickets', displayName: 'Contoso Tickets', source: 'managed', sourceUri: undefined }, @@ -5379,6 +5389,44 @@ export default defineThemedFixtureGroup({ path: 'chat/aiCustomizations/' }, { }), }), + BrokenConnectorRow: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['The Work IQ Mail Connector row shows an error icon and reconnect guidance beneath its name, alongside its actions.'], + render: async ctx => { + await renderEditor(ctx, { + sessionResource: localSessionResource, + isSessionsWindow: true, + selectedSection: AICustomizationManagementSection.McpServers, + copilotConnectorsEnabled: true, + activeSessionMcpServers: [brokenConnectorMcpServer], + mcpSearchQuery: 'workiq', + }); + const row = ctx.container.querySelector('.mcp-server-item'); + assert(row !== null && row.textContent?.includes('Disconnect and reconnect Work IQ Mail') === true, 'The Connector row must show the reconnect guidance.'); + const icon = row.querySelector('.mcp-server-icon img'); + assert(icon !== null, 'The Connector row must render its catalog icon.'); + await icon.decode(); + }, + }), + + BrokenConnectorDetail: defineComponentFixture({ + labels: { kind: 'screenshot' }, + expectedVisualDescriptions: ['The Work IQ Mail detail shows the full reconnect guidance and the Disconnect action together.'], + render: async ctx => { + await renderEditor(ctx, { + sessionResource: localSessionResource, + isSessionsWindow: true, + selectedSection: AICustomizationManagementSection.McpServers, + copilotConnectorsEnabled: true, + activeSessionMcpServers: [brokenConnectorMcpServer], + mcpSearchQuery: 'workiq', + openFirstItem: true, + openItemLabel: 'Work IQ Mail', + }); + assert(ctx.container.querySelector('.mcp-detail-diagnostic-message')?.textContent?.includes('Disconnect and reconnect Work IQ Mail') === true, 'The Connector detail must show the reconnect guidance.'); + }, + }), + ConnectorDetailNarrow: defineComponentFixture({ labels: { kind: 'screenshot' }, expectedVisualDescriptions: ['The connector name and connection action remain within the detail header at a narrow width, with the homepage link in the Details table.'],