Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(connectors): proactive connectors panel + connect/disconnect (U2/U3/U4)

Diego Zacarias555e6199ee14
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index a9c68ed1d..8cf4f3c6c 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -60,6 +60,7 @@ import {
PrewarmHostResult,
ProfileSettingsOpenOptions,
RpcAllowedServersResult,
+ RpcConnectorsResult,
RpcScope,
SessionLifecycleState,
SessionMe,
@@ -4500,13 +4501,22 @@ export class AppService {
async requestMcpOauthAuthorize(
mcpServerName: string,
hostRef: string,
- contextId?: string
+ contextId?: string,
+ // Proactive panel (spec 11 U3/D-4): when the connector is `oauth-context`
+ // ("shared by the team"), authorizing affects the WHOLE Context, so the
+ // panel asks main to show an explicit confirm dialog first. The reactive
+ // U5 path never sets this, so its behavior is byte-identical.
+ options?: { confirmShared?: boolean }
): Promise<void> {
const server = String(mcpServerName || '').trim()
const targetHostRef = String(hostRef || '').trim()
if (!server) throw new Error('mcpServerName is required')
if (!targetHostRef) throw new Error('hostRef is required')
const ctx = contextId ? String(contextId).trim() || undefined : undefined
+ if (options?.confirmShared) {
+ const confirmed = await this.confirmSharedConnectorAction('connect', server)
+ if (!confirmed) return
+ }
let rpc = await this.issueRpcTokenForHostRefs(MCP_SERVER_INVOKE_SCOPES, [targetHostRef])
let result: { authorizeUrl: string }
try {
@@ -4529,6 +4539,118 @@ export class AppService {
await shell.openExternal(result.authorizeUrl)
}
+ /**
+ * Proactive connectors read-model (spec 11 U2). Returns the user's agent fleet
+ * with each connector classified tri-state (`authorized`/`requires_setup`/
+ * `no_oauth`). Host refs come from the access catalog purely to mint the
+ * `mcp:servers:list` RPC token (rpc-proxy derives the userId from `auth.sub`
+ * and enumerates agents server-side). Retry-after-refresh mirrors
+ * {@link listAccessibleMcpServers}.
+ */
+ async getConnectors(): Promise<RpcConnectorsResult> {
+ const token = this.requireSessionToken()
+ const catalog = await this.getAccessCatalog()
+ const hostRefs = AppService.dedupe(
+ (catalog.agentNames || []).map(name => String(name || '').trim()).filter(Boolean)
+ )
+ if (!hostRefs.length) {
+ const me = this.me ?? (await this.authClient.getMe(token))
+ this.me = me
+ return { userId: me.id, agents: [] }
+ }
+ const rpc = await this.issueRpcTokenForHostRefs(MCP_SERVERS_LIST_SCOPES, hostRefs)
+ try {
+ return await this.rpcClient.getConnectors(rpc.token)
+ } catch (error) {
+ if (AppService.shouldRefreshRpcToken(error)) {
+ this.rpcTokenManager.clear()
+ const retried = await this.issueRpcTokenForHostRefs(MCP_SERVERS_LIST_SCOPES, hostRefs)
+ return this.rpcClient.getConnectors(retried.token)
+ }
+ throw error
+ }
+ }
+
+ /**
+ * Disconnect (revoke) an mcp-server's OAuth grant from the proactive panel
+ * (spec 11 U4). Host-bound to the agent whose row triggered it (RPC tokens
+ * require ≥1 hostRef; `mcp:server:invoke`, same as connect). Disconnect is
+ * destructive, so it ALWAYS asks for explicit confirmation via a native
+ * dialog (D-4); for an `oauth-context` connector the copy names the team-wide
+ * blast radius. `userId` is derived by rpc-proxy from `auth.sub`, never sent.
+ * Resolves `{ confirmed:false }` when the user cancels (nothing was revoked).
+ */
+ async disconnectMcpServer(
+ mcpServerName: string,
+ hostRef: string,
+ contextId?: string,
+ options?: { shared?: boolean }
+ ): Promise<{ confirmed: boolean }> {
+ const server = String(mcpServerName || '').trim()
+ const targetHostRef = String(hostRef || '').trim()
+ if (!server) throw new Error('mcpServerName is required')
+ if (!targetHostRef) throw new Error('hostRef is required')
+ const ctx = contextId ? String(contextId).trim() || undefined : undefined
+ const confirmed = await this.confirmSharedConnectorAction(
+ 'disconnect',
+ server,
+ Boolean(options?.shared)
+ )
+ if (!confirmed) return { confirmed: false }
+ let rpc = await this.issueRpcTokenForHostRefs(MCP_SERVER_INVOKE_SCOPES, [targetHostRef])
+ try {
+ await this.rpcClient.deleteMcpOauthGrant(rpc.token, server, ctx)
+ } catch (error) {
+ // The DELETE is idempotent and rpc-proxy emits every 401/403-missing-scope
+ // from its auth middleware BEFORE the upstream call, so a retried error is
+ // always a pre-effect rejection — safe to re-mint (same hostRef) and retry.
+ if (AppService.shouldRefreshRpcToken(error)) {
+ this.rpcTokenManager.clear()
+ rpc = await this.issueRpcTokenForHostRefs(MCP_SERVER_INVOKE_SCOPES, [targetHostRef])
+ await this.rpcClient.deleteMcpOauthGrant(rpc.token, server, ctx)
+ } else {
+ throw error
+ }
+ }
+ return { confirmed: true }
+ }
+
+ /**
+ * Native confirmation dialog for a connector action whose effect is either
+ * destructive (any disconnect) or team-wide (`oauth-context`). Mirrors the
+ * background-consent dialog of {@link requestSandboxUiOauthAuthorize}. The
+ * `shared` copy names the Context blast radius; every disconnect carries the
+ * revocation-latency note (D-5 — no immediate push; eviction is by idle
+ * timeout). Returns true iff the user confirmed.
+ */
+ private async confirmSharedConnectorAction(
+ action: 'connect' | 'disconnect',
+ server: string,
+ shared = true
+ ): Promise<boolean> {
+ const { dialog, BrowserWindow } = await import('electron')
+ const win = BrowserWindow.getFocusedWindow() ?? undefined
+ const verb = action === 'connect' ? 'Connect' : 'Disconnect'
+ const latencyNote =
+ action === 'disconnect' ? ' It can take a few minutes to cut active sessions.' : ''
+ const message = shared ? `${verb} "${server}" for the whole team?` : `${verb} "${server}"?`
+ const detail = shared
+ ? action === 'connect'
+ ? `This connector is shared by the team. Authorizing it connects every agent in this context on your behalf.${latencyNote}`
+ : `This connector is shared by the team. Disconnecting removes access for every agent in this context.${latencyNote}`
+ : `This removes your authorization for this connector.${latencyNote}`
+ const opts = {
+ type: (action === 'disconnect' ? 'warning' : 'question') as 'warning' | 'question',
+ buttons: ['Cancel', verb],
+ defaultId: 1,
+ cancelId: 0,
+ message,
+ detail,
+ }
+ const result = win ? await dialog.showMessageBox(win, opts) : await dialog.showMessageBox(opts)
+ return result.response === 1
+ }
+
/**
* Open the sandbox-ui WebContentsView. Mints a session cookie, installs it
* into the per-recipe Electron partition, and mounts a single embedded
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 0496f4505..8c31e2260 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -1123,14 +1123,42 @@ export function registerIpcHandlers(service: AppService): void {
// conversation's hostRef) and opens it in the OS browser. The deep-link return
// (`clerum://oauth-completed?…&source=mcp`) is routed by main.ts back to the
// renderer to resume the suspended task.
- ipcMain.handle('rpc:connectMcpServer', async (event, { mcpServerName, hostRef, contextId }) => {
+ ipcMain.handle(
+ 'rpc:connectMcpServer',
+ async (event, { mcpServerName, hostRef, contextId, options }) => {
+ assertTrustedSender(event)
+ const server = sanitizeString(mcpServerName)
+ const targetHostRef = sanitizeString(hostRef)
+ const ctx = sanitizeString(contextId) || undefined
+ // `confirmShared` is a UX-only flag (the server-side authz per flavor is
+ // authoritative). The panel sets it for `oauth-context` connectors so main
+ // shows a team-wide confirm dialog; the reactive U5 path omits it.
+ const confirmShared = options && typeof options === 'object' && options.confirmShared === true
+ return service.requestMcpOauthAuthorize(server, targetHostRef, ctx, { confirmShared })
+ }
+ )
+
+ // Proactive connectors panel (spec 11 U2): the classified per-agent fleet.
+ ipcMain.handle('rpc:listConnectors', async event => {
assertTrustedSender(event)
- const server = sanitizeString(mcpServerName)
- const targetHostRef = sanitizeString(hostRef)
- const ctx = sanitizeString(contextId) || undefined
- return service.requestMcpOauthAuthorize(server, targetHostRef, ctx)
+ return service.getConnectors()
})
+ // Proactive disconnect (spec 11 U4): revoke an mcp-server's OAuth grant. Main
+ // shows an explicit confirm dialog before the DELETE (destructive; team-wide
+ // for `oauth-context`). `shared` drives only the confirm copy.
+ ipcMain.handle(
+ 'rpc:disconnectMcpServer',
+ async (event, { mcpServerName, hostRef, contextId, options }) => {
+ assertTrustedSender(event)
+ const server = sanitizeString(mcpServerName)
+ const targetHostRef = sanitizeString(hostRef)
+ const ctx = sanitizeString(contextId) || undefined
+ const shared = options && typeof options === 'object' && options.shared === true
+ return service.disconnectMcpServer(server, targetHostRef, ctx, { shared })
+ }
+ )
+
ipcMain.handle('rpc:listServers', async (event, { hostRefs }) => {
assertTrustedSender(event)
return service.listAccessibleMcpServers(hostRefs)
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 9264c086f..353632dc0 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -457,8 +457,23 @@ const clerum = Object.freeze({
// U5 (mcp-oauth reactive consent): "Connect <server>" — open the provider
// authorize-URL for a task that suspended with `connect_required`. Host-bound
// to the suspended conversation's hostRef (RPC tokens require a hostRef).
- connectMcpServer: (mcpServerName: string, hostRef: string, contextId?: string) =>
- ipcRenderer.invoke('rpc:connectMcpServer', { mcpServerName, hostRef, contextId }),
+ connectMcpServer: (
+ mcpServerName: string,
+ hostRef: string,
+ contextId?: string,
+ options?: { confirmShared?: boolean }
+ ) => ipcRenderer.invoke('rpc:connectMcpServer', { mcpServerName, hostRef, contextId, options }),
+ // Proactive connectors panel (spec 11 U2): the classified per-agent fleet.
+ listConnectors: () => ipcRenderer.invoke('rpc:listConnectors'),
+ // Proactive disconnect (spec 11 U4): revoke an mcp-server's OAuth grant.
+ // `options.shared` only drives the native confirm-dialog copy.
+ disconnectMcpServer: (
+ mcpServerName: string,
+ hostRef: string,
+ contextId?: string,
+ options?: { shared?: boolean }
+ ) =>
+ ipcRenderer.invoke('rpc:disconnectMcpServer', { mcpServerName, hostRef, contextId, options }),
// Fired when the OAuth deep-link returns with `source=mcp`. The renderer
// correlates `mcpServerName` to its suspended entries and resumes the task.
onMcpOauthCompleted: (
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index e9f316640..115e082f4 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -32,6 +32,7 @@ import {
ProfileSettingsOpenOptions,
ReplaceChatMessagesOptions,
RpcAllowedServersResult,
+ RpcConnectorsResult,
SandboxUiApp,
SandboxUiDeepLinkEnvelope,
SessionLifecycleState,
@@ -568,8 +569,20 @@ declare global {
connectMcpServer: (
mcpServerName: string,
hostRef: string,
- contextId?: string
+ contextId?: string,
+ options?: { confirmShared?: boolean }
) => Promise<void>
+ // Proactive connectors panel (spec 11 U2): the classified per-agent fleet.
+ listConnectors: () => Promise<RpcConnectorsResult>
+ // Proactive disconnect (spec 11 U4): revoke an mcp-server's OAuth grant.
+ // Main shows a native confirm dialog first; resolves `{ confirmed:false }`
+ // when the user cancels. `options.shared` drives only the confirm copy.
+ disconnectMcpServer: (
+ mcpServerName: string,
+ hostRef: string,
+ contextId?: string,
+ options?: { shared?: boolean }
+ ) => Promise<{ confirmed: boolean }>
// Push fired when the OAuth deep-link returns with `source=mcp`; the
// renderer correlates `mcpServerName` and resumes the suspended task.
onMcpOauthCompleted: (
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index 4caf9ef95..004a4ecdc 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -13,6 +13,7 @@ import {
MessageToolStep,
PendingApprovalLite,
RpcAllowedServersResult,
+ RpcConnectorsResult,
SandboxUiApp,
SessionLifecycleState,
SessionMessagesQuery,
@@ -424,6 +425,45 @@ export class RpcProxyClient {
})
}
+ /**
+ * Proactive connectors read-model (spec 11 U2/U1) — the per-agent classified
+ * fleet (`authorized`/`requires_setup`/`no_oauth`). Reuses the `mcp:servers:list`
+ * scope (catalog read), like {@link listServers}; rpc-proxy derives the
+ * `userId` from `auth.sub` and enumerates the agents server-side, so the token
+ * only needs a valid host binding for the scope gate. Throws `ApiError` so
+ * `AppService.shouldRefreshRpcToken` can drive the retry-after-refresh.
+ */
+ async getConnectors(rpcAccessToken: string): Promise<RpcConnectorsResult> {
+ return requestJson<RpcConnectorsResult>('GET', url('/api/v1/rpc/connectors'), {
+ token: rpcAccessToken,
+ })
+ }
+
+ /**
+ * Disconnect (revoke) an mcp-server's OAuth grant (spec 11 U4). Mirrors the
+ * authorize-URL mint route but as a `DELETE`; the `userId` is derived by
+ * rpc-proxy from `auth.sub` and is NEVER sent in the body (invariant 3). The
+ * optional `contextId` is only a hint for the `oauth-context` flavor — control
+ * -api resolves the authoritative Context server-side. Idempotent: a missing
+ * grant answers 204. Throws `ApiError` (401/403-missing-scope → refresh retry).
+ */
+ async deleteMcpOauthGrant(
+ rpcAccessToken: string,
+ mcpServerName: string,
+ contextId?: string
+ ): Promise<void> {
+ await requestJson<unknown>(
+ 'DELETE',
+ url(`/api/v1/mcp-oauth/${encodeURIComponent(mcpServerName)}/grant`),
+ {
+ token: rpcAccessToken,
+ // Body is optional; only send `contextId` when present. `userId` is NEVER
+ // sent — rpc-proxy derives it from the JWT sub.
+ body: contextId ? { contextId } : {},
+ }
+ )
+ }
+
async invokeHostMessage(
rpcAccessToken: string,
hostRef: string,
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 3f803d203..f8a9bf2ae 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -484,6 +484,32 @@ export type RpcAllowedServersResult = {
servers: RpcMcpServer[]
}
+/**
+ * Proactive connectors read-model (spec 11 U2), projected verbatim from
+ * rpc-proxy's `GET /api/v1/rpc/connectors` (U1). NON-SECRET policy only —
+ * `authKind`/`provider`/`grantScope` — never `auth`/`secretRef`/tokens.
+ * The tri-state `status` is derived server-side from the authoritative grant
+ * store (`oauthGrantExists`, D4); the desktop never recomputes "connected".
+ */
+export type RpcConnector = {
+ name: string
+ provider?: string
+ authKind?: 'static' | 'oauth-user' | 'oauth-context'
+ grantScope?: 'user' | 'context'
+ status: 'authorized' | 'requires_setup' | 'no_oauth'
+}
+
+export type RpcAgentConnectors = {
+ name: string
+ contextRef: string | null
+ connectors: RpcConnector[]
+}
+
+export type RpcConnectorsResult = {
+ userId: string
+ agents: RpcAgentConnectors[]
+}
+
export type RpcTokenResult = {
token: string
accessScope: RpcAccessScope
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
index ff8667aa0..ffa195688 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx
@@ -184,6 +184,11 @@ export function extendMockClerumForAppController(
prewarmHost: vi.fn(async () => ({ status: 'ok' })),
approveToolCall: vi.fn(async () => undefined),
denyToolCall: vi.fn(async () => undefined),
+ // The coordinator now owns the connectors panel's initial load (post-auth
+ // bootstrap) — give the app-level `useConnectorsController` a producer.
+ listConnectors: vi.fn(async () => ({ userId: HARNESS_ME.id, agents: [] })),
+ connectMcpServer: vi.fn(async () => undefined),
+ disconnectMcpServer: vi.fn(async () => ({ confirmed: true })),
})
Object.assign(bridge, {
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/handleMcpOauthCompletion.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/handleMcpOauthCompletion.test.ts
new file mode 100644
index 000000000..f5218c619
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/handleMcpOauthCompletion.test.ts
@@ -0,0 +1,100 @@
+import { describe, expect, it, vi } from 'vitest'
+import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'
+import type { PendingApprovalLite } from '../../../../../src/types'
+import { handleMcpOauthCompletion } from '../approvalDecision'
+import { createSessionFsmStore } from '../sessionFsm'
+
+/**
+ * U3 invariants (spec 11), driven off the REAL `sessionFsmReducer` snapshot (T1)
+ * — a `connect_required` suspension is fed through the exact `STREAM_SUSPENDED`
+ * transition the live tracker fires, never hand-built.
+ */
+function suspend(
+ store: ReturnType<typeof createSessionFsmStore>,
+ agentRef: string,
+ chatId: string,
+ taskId: string,
+ approval: PendingApprovalLite
+): void {
+ store.dispatch(makeTaskKey(agentRef, chatId), { type: 'STREAM_SUSPENDED', taskId, approval })
+}
+
+const connectApproval = (requestId: string, mcpServerName: string): PendingApprovalLite => ({
+ requestId,
+ displayName: `${mcpServerName} tool`,
+ reason: 'connect_required',
+ mcpServerName,
+})
+
+describe('handleMcpOauthCompletion — U3 proactive + coexistence', () => {
+ it('T5#1 · no suspended turn → refreshes the connectors panel, resumes nothing (proactive branch)', () => {
+ const store = createSessionFsmStore()
+ // The panel "Authorize" flow: no turn is waiting on this server.
+ const decide = vi.fn()
+ const refreshConnectors = vi.fn()
+
+ const result = handleMcpOauthCompletion(
+ {
+ getSnapshot: () => store.getSnapshot(),
+ decide,
+ refreshConnectors,
+ },
+ 'monday'
+ )
+
+ expect(decide).not.toHaveBeenCalled()
+ expect(refreshConnectors).toHaveBeenCalledTimes(1)
+ expect(result).toEqual({ resumedCount: 0, wasProactive: true })
+ })
+
+ it('T5#2 · a turn is suspended on the server → resumes the turn AND refreshes the panel (coexistence)', () => {
+ const store = createSessionFsmStore()
+ suspend(store, 'agentA', 'chatA1', 'taskA', connectApproval('reqA', 'monday'))
+ const decide = vi.fn()
+ const refreshConnectors = vi.fn()
+
+ const result = handleMcpOauthCompletion(
+ {
+ getSnapshot: () => store.getSnapshot(),
+ decide,
+ refreshConnectors,
+ },
+ 'monday'
+ )
+
+ // The reactive resume is NOT broken…
+ expect(decide).toHaveBeenCalledTimes(1)
+ expect(decide).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentRef: 'agentA',
+ chatId: 'chatA1',
+ taskId: 'taskA',
+ requestId: 'reqA',
+ decision: 'approve',
+ source: 'connect_completed',
+ })
+ )
+ // …AND the panel is refreshed in the same completion.
+ expect(refreshConnectors).toHaveBeenCalledTimes(1)
+ expect(result).toEqual({ resumedCount: 1, wasProactive: false })
+ })
+
+ it('resumes every conversation suspended on the same server, refreshing once', () => {
+ const store = createSessionFsmStore()
+ suspend(store, 'agentA', 'chat1', 'task1', connectApproval('req1', 'monday'))
+ suspend(store, 'agentA', 'chat2', 'task2', connectApproval('req2', 'monday'))
+ const decide = vi.fn()
+ const refreshConnectors = vi.fn()
+
+ const result = handleMcpOauthCompletion(
+ { getSnapshot: () => store.getSnapshot(), decide, refreshConnectors },
+ 'monday'
+ )
+
+ expect(decide).toHaveBeenCalledTimes(2)
+ // A single refresh per completion — the queue's (server,provider) dedup keeps
+ // a cold-start replay from double-firing; a redundant invalidate is idempotent.
+ expect(refreshConnectors).toHaveBeenCalledTimes(1)
+ expect(result).toEqual({ resumedCount: 2, wasProactive: false })
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useConnectorsController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useConnectorsController.test.tsx
new file mode 100644
index 000000000..ec487e3a3
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useConnectorsController.test.tsx
@@ -0,0 +1,156 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, renderHook, waitFor } from '@testing-library/react'
+import type { RpcConnector, RpcConnectorsResult } from '../../../../../src/types'
+import { useConnectorsController } from '../useConnectorsController'
+
+/**
+ * Renderer-side invariants of the connectors panel actions (T5#click→IPC). The
+ * native confirm-dialog lives in main and is untestable in jsdom — this drives
+ * the hook logic with `window.clerum.rpc.{connectMcpServer,disconnectMcpServer}`
+ * stubbed and asserts the OBSERVABLE effects (T4): the exact IPC arguments, and
+ * the panel list the user sees after a disconnect.
+ *
+ * The disconnect result fixture is `{ confirmed: boolean }` — the exact contract
+ * `disconnectMcpServer` resolves (renderer.d.ts / appService.disconnectMcpServer),
+ * not a hand-invented shape.
+ */
+
+const SHARED: RpcConnector = {
+ name: 'shared-drive',
+ provider: 'google',
+ authKind: 'oauth-context',
+ grantScope: 'context',
+ status: 'requires_setup',
+}
+const USER: RpcConnector = {
+ name: 'monday',
+ provider: 'monday',
+ authKind: 'oauth-user',
+ grantScope: 'user',
+ status: 'authorized',
+}
+
+const AGENT = 'agent-alpha'
+const CTX = 'ctx-team'
+
+function payload(connectors: RpcConnector[]): RpcConnectorsResult {
+ return { userId: 'user-1', agents: [{ name: AGENT, contextRef: CTX, connectors }] }
+}
+
+function installClerum() {
+ const rpc = {
+ listConnectors: vi.fn(async () => payload([SHARED, USER])),
+ connectMcpServer: vi.fn(async () => undefined),
+ disconnectMcpServer: vi.fn(async () => ({ confirmed: true })),
+ }
+ Object.defineProperty(window, 'clerum', { configurable: true, value: { rpc } })
+ return rpc
+}
+
+function renderController() {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ return renderHook(() => useConnectorsController(), {
+ wrapper: ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ })
+}
+
+const connectorNames = (result: { current: ReturnType<typeof useConnectorsController> }) =>
+ result.current.agents[0]?.connectors.map(connector => connector.name) ?? []
+
+describe('useConnectorsController — click→IPC invariants (T5, T4)', () => {
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ it('authorize passes confirmShared+contextId ONLY for shared connectors', async () => {
+ const rpc = installClerum()
+ const { result } = renderController()
+
+ await act(async () => {
+ await result.current.authorize({ agentName: AGENT, contextRef: CTX, connector: SHARED })
+ })
+ // oauth-context → shared: carries confirmShared:true + the agent's contextRef.
+ expect(rpc.connectMcpServer).toHaveBeenLastCalledWith('shared-drive', AGENT, CTX, {
+ confirmShared: true,
+ })
+
+ await act(async () => {
+ await result.current.authorize({ agentName: AGENT, contextRef: CTX, connector: USER })
+ })
+ // oauth-user → NOT shared: confirmShared:false and NO contextId, even though a
+ // contextRef is available for the agent.
+ expect(rpc.connectMcpServer).toHaveBeenLastCalledWith('monday', AGENT, undefined, {
+ confirmShared: false,
+ })
+ })
+
+ it('disconnect passes shared+contextId ONLY for shared connectors', async () => {
+ const rpc = installClerum()
+ const { result } = renderController()
+
+ await act(async () => {
+ await result.current.disconnect({ agentName: AGENT, contextRef: CTX, connector: SHARED })
+ })
+ expect(rpc.disconnectMcpServer).toHaveBeenLastCalledWith('shared-drive', AGENT, CTX, {
+ shared: true,
+ })
+
+ await act(async () => {
+ await result.current.disconnect({ agentName: AGENT, contextRef: CTX, connector: USER })
+ })
+ expect(rpc.disconnectMcpServer).toHaveBeenLastCalledWith('monday', AGENT, undefined, {
+ shared: false,
+ })
+ })
+
+ it('disconnect refreshes the panel list when the revoke is confirmed', async () => {
+ const rpc = installClerum()
+ const { result } = renderController()
+
+ // App-owned initial load (the query is enabled:false); drive it here.
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(connectorNames(result)).toEqual(['shared-drive', 'monday']))
+
+ // A confirmed revoke changed the grant store; the refetch returns the new list.
+ rpc.disconnectMcpServer.mockResolvedValueOnce({ confirmed: true })
+ rpc.listConnectors.mockResolvedValueOnce(payload([USER]))
+ await act(async () => {
+ await result.current.disconnect({ agentName: AGENT, contextRef: CTX, connector: SHARED })
+ })
+
+ // Observable: the list the user sees dropped the revoked connector (T4).
+ await waitFor(() => expect(connectorNames(result)).toEqual(['monday']))
+ })
+
+ it('disconnect does NOT refresh the panel when the confirm dialog is cancelled', async () => {
+ const rpc = installClerum()
+ const { result } = renderController()
+
+ await act(async () => {
+ await result.current.refresh()
+ })
+ await waitFor(() => expect(connectorNames(result)).toEqual(['shared-drive', 'monday']))
+ const listCallsBefore = rpc.listConnectors.mock.calls.length
+
+ // Cancelled dialog: nothing was revoked. A queued (would-be) refetch payload is
+ // primed to prove it is NEVER consumed.
+ rpc.disconnectMcpServer.mockResolvedValueOnce({ confirmed: false })
+ rpc.listConnectors.mockResolvedValueOnce(payload([USER]))
+ await act(async () => {
+ await result.current.disconnect({ agentName: AGENT, contextRef: CTX, connector: SHARED })
+ })
+
+ // Observable: the list is unchanged, and no refetch was issued.
+ expect(connectorNames(result)).toEqual(['shared-drive', 'monday'])
+ expect(rpc.listConnectors.mock.calls.length).toBe(listCallsBefore)
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/approvalDecision.ts b/desktop-app/ui/src/hooks/domain/approvalDecision.ts
index 1e7ffdb99..34b53020e 100644
--- a/desktop-app/ui/src/hooks/domain/approvalDecision.ts
+++ b/desktop-app/ui/src/hooks/domain/approvalDecision.ts
@@ -104,6 +104,46 @@ export function resolveConnectResumeTargets(
return targets
}
+/**
+ * U3 (mcp-oauth proactive consent) — the OAuth deep-link return handler.
+ *
+ * A `clerum://oauth-completed?source=mcp&mcpServerName=<X>` arrives in TWO
+ * independent situations, and BOTH must be handled from the single completion:
+ * - REACTIVE: a turn suspended with `connect_required` is waiting on <X> →
+ * `resolveConnectResumeTargets` yields its resume target(s) and each is
+ * driven through the SAME central decider (approve → the tool re-executes).
+ * - PROACTIVE: the user clicked "Authorize" in the connectors panel with no
+ * turn in flight → `resolveConnectResumeTargets` yields `[]`.
+ *
+ * In EITHER case the grant store just changed, so the panel's tri-state is now
+ * stale — this ALWAYS refreshes it (the coexistence must-fix: when a suspended
+ * turn AND the panel are both live, resume the turn *and* refresh the panel).
+ * When there is no turn, the refresh is the only effect (the proactive branch).
+ * Pure orchestration over injected deps — no decision logic, no React — so it is
+ * unit-testable and re-reads truth solely from U1 (D4).
+ *
+ * `refreshConnectors` runs exactly once per completion, so the queue's existing
+ * `(server,provider)` dedup keeps a cold-start-replayed completion from firing a
+ * problematic double refresh (a redundant invalidate is idempotent regardless).
+ */
+export interface McpOauthCompletionDeps {
+ getSnapshot: () => Record<string, SessionFsmState>
+ decide: (target: ApprovalDecisionTarget) => void
+ refreshConnectors: () => void
+}
+
+export function handleMcpOauthCompletion(
+ deps: McpOauthCompletionDeps,
+ mcpServerName: string
+): { resumedCount: number; wasProactive: boolean } {
+ const resumeTargets = resolveConnectResumeTargets(deps.getSnapshot(), mcpServerName)
+ for (const target of resumeTargets) {
+ deps.decide(target)
+ }
+ deps.refreshConnectors()
+ return { resumedCount: resumeTargets.length, wasProactive: resumeTargets.length === 0 }
+}
+
export interface DecideApprovalDeps {
fsm: SessionFsmStore
approve: (target: ApprovalDecisionTarget) => Promise<ApprovalDecisionResult>
diff --git a/desktop-app/ui/src/hooks/domain/queryKeys.ts b/desktop-app/ui/src/hooks/domain/queryKeys.ts
index 80137d093..3872b10c5 100644
--- a/desktop-app/ui/src/hooks/domain/queryKeys.ts
+++ b/desktop-app/ui/src/hooks/domain/queryKeys.ts
@@ -26,6 +26,9 @@ export const desktopQueryKeys = {
['desktop-app', 'gfs', sessionScope, 'grants', drive, resourceId] as const,
gfsShares: (sessionScope: string, resourceId: string, drive: string) =>
['desktop-app', 'gfs', sessionScope, 'shares', drive, resourceId] as const,
+ // Proactive connectors panel (spec 11 U2). Invalidated on connect/disconnect
+ // completion (U3/U4) so the tri-state re-reads the authoritative grant store.
+ connectors: ['desktop-app', 'connectors'] as const,
pluginGrants: ['desktop-app', 'plugin-sdk', 'grants'] as const,
pluginActivity: (limit: number) =>
['desktop-app', 'plugin-sdk', 'activity', String(limit)] as const,
diff --git a/desktop-app/ui/src/hooks/domain/useConnectorsController.ts b/desktop-app/ui/src/hooks/domain/useConnectorsController.ts
new file mode 100644
index 000000000..68241587c
Binary files /dev/null and b/desktop-app/ui/src/hooks/domain/useConnectorsController.ts differ
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index 307b8903b..883516512 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -24,7 +24,7 @@ import type {
import {
type ApprovalDecisionTarget,
decideApproval as decideApprovalCore,
- resolveConnectResumeTargets,
+ handleMcpOauthCompletion,
} from './domain/approvalDecision'
import { desktopQueryKeys } from './domain/queryKeys'
import { useActivityController } from './domain/useActivityController'
@@ -32,6 +32,7 @@ import { useAgentChatController } from './domain/useAgentChatController'
import { useAgentsDataController } from './domain/useAgentsDataController'
import { useAuthController } from './domain/useAuthController'
import { useChannelNotificationPreferencesController } from './domain/useChannelNotificationPreferencesController'
+import { useConnectorsController } from './domain/useConnectorsController'
import { useContextsDataController } from './domain/useContextsDataController'
import { useDesktopController } from './domain/useDesktopController'
import { useHostPrewarmController } from './domain/useHostPrewarmController'
@@ -175,6 +176,10 @@ export function useAppController() {
const agentsData = useAgentsDataController()
const contextsData = useContextsDataController()
const mcpServersData = useMcpServersDataController()
+ // App-coordinated like the other data-controllers: the panel query is
+ // `enabled:false`, so the initial load and the identity teardown are owned
+ // here (see refreshAuthenticatedData / handleLogout / switchTeamForWorkspace).
+ const connectorsData = useConnectorsController()
const teamsData = useTeamsDataController()
const currentTeamId = auth.me?.teamId || teamsData.currentTeamId || ''
const availableTeamIds = useMemo(() => teamsData.teams.map(team => team.id), [teamsData.teams])
@@ -321,15 +326,29 @@ export function useAppController() {
// ephemeral client_id→server map. Each match resumes through the SAME central
// decider (`decideApproval` approve → the approval RPC re-executes the tool).
// Subscribed once; `chat.sessionFsmStore` and `decideApprovalRef` are read live.
+ // U3 (mcp-oauth PROACTIVE consent) adds the missing arm: when the completion
+ // matches no suspended turn (panel "Authorize" with no turn in flight),
+ // `handleMcpOauthCompletion` yields no resume targets and instead refreshes the
+ // connectors panel. When a turn IS suspended it does BOTH — resumes through the
+ // same decider AND refreshes the panel (coexistence must-fix). The panel's
+ // tri-state is always re-read from U1 (D4).
useEffect(() => {
const unsub = window.clerum.rpc.onMcpOauthCompleted?.(({ mcpServerName }) => {
- const targets = resolveConnectResumeTargets(chat.sessionFsmStore.getSnapshot(), mcpServerName)
- for (const target of targets) {
- void decideApprovalRef.current(target)
- }
+ handleMcpOauthCompletion(
+ {
+ getSnapshot: () => chat.sessionFsmStore.getSnapshot(),
+ decide: target => void decideApprovalRef.current(target),
+ // The panel query is `enabled:false`, so an invalidate would only mark
+ // it stale without refetching — drive the imperative refresh instead so
+ // both the PROACTIVE (no suspended turn) and coexistence (turn + panel)
+ // arms of U3 actually re-read the grant store.
+ refreshConnectors: () => void connectorsData.refresh(),
+ },
+ mcpServerName
+ )
})
return () => unsub?.()
- }, [chat.sessionFsmStore])
+ }, [chat.sessionFsmStore, connectorsData.refresh])
// ─── MCP Server ───
const mcpServer = useMcpServerController({
@@ -428,6 +447,7 @@ export function useAppController() {
refreshMcpServersData(),
refreshTeams(),
refreshWorkflowsData(),
+ connectorsData.refresh(),
notif.handleRefreshPendingApprovals({ silent: true }),
])
}
@@ -441,10 +461,12 @@ export function useAppController() {
refreshMcpServersData(),
refreshTeams(),
refreshWorkflowsData(),
+ connectorsData.refresh(),
notif.handleRefreshPendingApprovals({ silent: true }),
])
},
[
+ connectorsData.refresh,
notif.handleRefreshPendingApprovals,
refreshAgentsData,
refreshContextsData,
@@ -564,6 +586,11 @@ export function useAppController() {
// team's tasks stay alive server-side and converge on return via reconcile.
// Main-process stream teardown is Fase 4.
chat.resetChat()
+ // The connectors panel key is identity-unscoped, and its payload carries
+ // per-connector OAuth authorization state — drop it here (before the
+ // refresh below repopulates) so the previous team's grants cannot show,
+ // even for the frame between the confirmed switch and the refetch.
+ connectorsData.reset()
auth.setIsAuthenticated(true)
auth.setMe(sessionState.me)
auth.setEmail(sessionState.me.email || '')
@@ -592,6 +619,7 @@ export function useAppController() {
auth.setIsAuthenticated,
auth.setMe,
chat.resetChat,
+ connectorsData.reset,
fullSetStatus,
refreshAuthenticatedData,
setPostPaintDataReady,
@@ -670,6 +698,7 @@ export function useAppController() {
agentsData.reset()
contextsData.reset()
mcpServersData.reset()
+ connectorsData.reset()
teamsData.reset()
resetWorkflowsData()
queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
@@ -711,6 +740,7 @@ export function useAppController() {
[
agentsData.reset,
auth.refreshRuntimeConfigState,
+ connectorsData.reset,
auth.setBooting,
auth.setDependencyHealth,
auth.setDesktopReleaseStatus,
@@ -745,6 +775,7 @@ export function useAppController() {
agentsData.reset()
contextsData.reset()
mcpServersData.reset()
+ connectorsData.reset()
teamsData.reset()
resetWorkflowsData()
queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
@@ -773,6 +804,7 @@ export function useAppController() {
auth.setBusy,
chat.resetChat,
chat.stopAllActivityStreams,
+ connectorsData.reset,
contextsData.reset,
fullSetStatus,
loadSession,
diff --git a/desktop-app/ui/src/pages/McpServersPage.tsx b/desktop-app/ui/src/pages/McpServersPage.tsx
index 50822ec61..b9fe45ea6 100644
--- a/desktop-app/ui/src/pages/McpServersPage.tsx
+++ b/desktop-app/ui/src/pages/McpServersPage.tsx
@@ -1,173 +1,169 @@
-import { useMemo } from 'react'
-import { DataTable, EmptyState, ReferenceTag } from '@components/Common'
+import { Button, EmptyState, Pill, StatusBanner } from '@components/Common'
import { formatMcpServerDisplayName } from '@lib/format'
-import type { ScopedMcpServer } from '@/uiTypes'
-import { useNavigationContext } from '../contexts/NavigationContext'
-import { useMcpServersDataController } from '../hooks/domain/useMcpServersDataController'
+import type { RpcConnector } from '../../../src/types'
+import {
+ connectorActionKey,
+ isActionableConnector,
+ isSharedConnector,
+ useConnectorsController,
+} from '../hooks/domain/useConnectorsController'
-export function McpServersPage() {
- const {
- agentNames,
- agentDisplayByName,
- mcpServersByAgent,
- agentContextByName,
- globalMcpServers,
- mcpServerMappingUnavailableMessage,
- loading,
- error,
- } = useMcpServersDataController()
- const { handleOpenAgentWorkspace, handleOpenContextDetails } = useNavigationContext()
-
- const globalByName = useMemo(() => {
- const index = new Map<string, ScopedMcpServer>()
- for (const server of globalMcpServers) {
- index.set(server.name, server)
- }
- return index
- }, [globalMcpServers])
+const CONNECTORS_GRID_COLS =
+ 'minmax(10rem, 1.4fr) minmax(8rem, 0.6fr) minmax(12rem, 1.4fr) minmax(7rem, auto)'
- const serverRows = useMemo(() => {
- const rowsByServer = new Map<
- string,
- {
- agents: Set<string>
- contexts: Set<string>
- serverName: string
- url?: string
- }
- >()
+type StatusPresentation = {
+ label: string
+ tone: 'success' | 'warning' | 'neutral'
+}
- for (const agentName of agentNames) {
- const servers = Array.from(
- new Set(
- (mcpServersByAgent[agentName] || [])
- .map(name => String(name || '').trim())
- .filter(Boolean)
- )
- ).sort((a, b) => a.localeCompare(b))
- if (!servers.length) continue
+function statusPresentation(status: RpcConnector['status']): StatusPresentation {
+ switch (status) {
+ case 'authorized':
+ return { label: 'Authorized', tone: 'success' }
+ case 'requires_setup':
+ return { label: 'Requires setup', tone: 'warning' }
+ default:
+ return { label: 'No OAuth', tone: 'neutral' }
+ }
+}
- const contextRefRaw = agentContextByName[agentName]
- const contextId =
- typeof contextRefRaw === 'string' && contextRefRaw.trim().length > 0
- ? contextRefRaw.trim()
- : 'Unassigned context'
+/**
+ * The per-connector scope caption (spec §1.3 / D-1). A `oauth-user` grant is
+ * global to `(server, userId)`, so acting under one agent flips the SAME server
+ * across every agent that lists it; a `oauth-context` grant is shared by the
+ * whole Context. Surfaced verbatim so the user understands the blast radius
+ * before the derived state changes several rows at once.
+ */
+function scopeCaption(connector: RpcConnector): string | null {
+ if (connector.status === 'no_oauth') return null
+ if (isSharedConnector(connector)) {
+ return 'Shared by the team — affects everyone in this context.'
+ }
+ if (connector.authKind === 'oauth-user') {
+ return 'Affects all your agents that use this connector.'
+ }
+ return null
+}
- for (const serverName of servers) {
- const globalServer = globalByName.get(serverName)
- const existing = rowsByServer.get(serverName)
- if (existing) {
- existing.agents.add(agentName)
- existing.contexts.add(contextId)
- if (!existing.url && globalServer?.url) existing.url = globalServer.url
- continue
- }
- rowsByServer.set(serverName, {
- agents: new Set([agentName]),
- contexts: new Set([contextId]),
- serverName,
- ...(globalServer?.url ? { url: globalServer.url } : {}),
- })
- }
- }
+export function McpServersPage() {
+ const { loading, error, agents, pendingKey, authorize, disconnect } = useConnectorsController()
- return [...rowsByServer.values()]
- .map(row => ({
- agents: [...row.agents].sort((a, b) => a.localeCompare(b)),
- contexts: [...row.contexts].sort((a, b) => {
- if (a === 'Unassigned context') return 1
- if (b === 'Unassigned context') return -1
- return a.localeCompare(b)
- }),
- serverName: row.serverName,
- url: row.url,
- }))
- .sort((a, b) => a.serverName.localeCompare(b.serverName))
- }, [agentContextByName, agentNames, globalByName, mcpServersByAgent])
+ const hasAgents = agents.length > 0
return (
<section className="page">
<div className="page-header">
<h2>Connectors</h2>
- <p className="muted">Connectors mapped across available agents and contexts.</p>
+ <p className="muted">
+ Review the connectors available to each agent, authorize the ones that require setup, and
+ disconnect the ones you no longer want to grant.
+ </p>
</div>
<div className="page-layout">
- <section className="page-card mcp-servers-board-card">
- {loading && serverRows.length === 0 ? (
- <EmptyState title="Loading" body="Fetching connector inventory..." />
- ) : error && serverRows.length === 0 ? (
- <div className="composer-error" role="alert">
- <p className="error-text">{error}</p>
- </div>
- ) : serverRows.length === 0 ? (
- <EmptyState title="No connectors" body={mcpServerMappingUnavailableMessage} />
- ) : (
- <DataTable frameless fullBleed className="mcp-servers-data-table">
- <thead>
- <tr>
- <th className="da-table__col-header" scope="col">
- Server
- </th>
- <th className="da-table__col-header" scope="col">
- Contexts
- </th>
- <th className="da-table__col-header" scope="col">
- Agents
- </th>
- </tr>
- </thead>
- <tbody>
- {serverRows.map(row => (
- <tr key={row.serverName}>
- <td className="da-table__cell">
- <span className="mcp-servers-server-cell">
- {formatMcpServerDisplayName(row.serverName)}
- </span>
- {row.url ? <code className="mcp-servers-url-inline">{row.url}</code> : null}
- </td>
- <td className="da-table__cell">
- <span className="reference-tag-list">
- {row.contexts.map(contextId => (
- <ReferenceTag
- key={`${row.serverName}:${contextId}`}
- kind="context"
- title={contextId}
- aria-label={`Open context ${contextId}`}
- disabled={contextId === 'Unassigned context'}
- onClick={() => {
- if (contextId === 'Unassigned context') return
- handleOpenContextDetails(contextId)
- }}
- >
- {contextId}
- </ReferenceTag>
- ))}
- </span>
- </td>
- <td className="da-table__cell">
- <span className="reference-tag-list">
- {row.agents.map(agentName => (
- <ReferenceTag
- key={`${row.serverName}:${agentName}`}
- kind="agent"
- onClick={() => handleOpenAgentWorkspace(agentName)}
- title={agentName}
- aria-label={`Open agent ${agentName}`}
- >
- {/* Visible agent name (spec.host) read directly from
- the producer-total map — no fallback (Decision #6). */}
- {agentDisplayByName[agentName]}
- </ReferenceTag>
- ))}
+ {error ? <StatusBanner tone="error">{error}</StatusBanner> : null}
+
+ {loading && !hasAgents ? (
+ <section className="page-card">
+ <EmptyState title="Loading" body="Fetching your connectors…" />
+ </section>
+ ) : !hasAgents ? (
+ <section className="page-card">
+ <EmptyState
+ title="No connectors"
+ body="No agents with connectors are available for your account yet."
+ />
+ </section>
+ ) : (
+ agents.map(agent => {
+ const contextRef = agent.contextRef
+ return (
+ <section
+ className="page-card"
+ key={agent.name}
+ aria-labelledby={`agent-${agent.name}`}
+ >
+ <div className="page-card__header">
+ <div>
+ <h3 id={`agent-${agent.name}`}>{agent.name}</h3>
+ <p className="muted">
+ {contextRef ? `Context: ${contextRef}` : 'No context assigned'}
+ </p>
+ </div>
+ </div>
+
+ {agent.connectors.length === 0 ? (
+ <EmptyState
+ title="No connectors"
+ body="This agent's context lists no connectors."
+ />
+ ) : (
+ <div className="da-grid" style={{ '--da-grid-cols': CONNECTORS_GRID_COLS }}>
+ <div className="da-grid__head">
+ <span className="da-grid__col-header">Connector</span>
+ <span className="da-grid__col-header">Status</span>
+ <span className="da-grid__col-header">Scope</span>
+ <span className="da-grid__col-header da-grid__col-header--right">
+ Actions
</span>
- </td>
- </tr>
- ))}
- </tbody>
- </DataTable>
- )}
- </section>
+ </div>
+ <div className="da-grid__body">
+ {agent.connectors.map(connector => {
+ const presentation = statusPresentation(connector.status)
+ const caption = scopeCaption(connector)
+ const actionKey = connectorActionKey(agent.name, connector.name)
+ const busy = pendingKey === actionKey
+ const actionInput = { agentName: agent.name, contextRef, connector }
+ return (
+ <div className="da-grid__row" key={`${agent.name}:${connector.name}`}>
+ <span className="da-grid__cell">
+ {formatMcpServerDisplayName(connector.name)}
+ {connector.provider ? (
+ <span className="muted"> · {connector.provider}</span>
+ ) : null}
+ </span>
+ <span className="da-grid__cell">
+ <Pill tone={presentation.tone} size="sm">
+ {presentation.label}
+ </Pill>
+ </span>
+ <span className="da-grid__cell muted">{caption ?? '—'}</span>
+ <span className="da-grid__cell da-grid__cell--right">
+ {!isActionableConnector(connector) ? null : connector.status ===
+ 'authorized' ? (
+ <Button
+ color="danger"
+ disabled={busy}
+ loading={busy}
+ onClick={() => disconnect(actionInput).catch(() => undefined)}
+ size="sm"
+ variant="ghost"
+ >
+ Disconnect
+ </Button>
+ ) : (
+ <Button
+ color="primary"
+ disabled={busy}
+ loading={busy}
+ onClick={() => authorize(actionInput).catch(() => undefined)}
+ size="sm"
+ variant="soft"
+ >
+ Authorize
+ </Button>
+ )}
+ </span>
+ </div>
+ )
+ })}
+ </div>
+ </div>
+ )}
+ </section>
+ )
+ })
+ )}
</div>
</section>
)
diff --git a/desktop-app/ui/src/pages/__tests__/McpServersPage.test.tsx b/desktop-app/ui/src/pages/__tests__/McpServersPage.test.tsx
new file mode 100644
index 000000000..2fbd54982
--- /dev/null
+++ b/desktop-app/ui/src/pages/__tests__/McpServersPage.test.tsx
@@ -0,0 +1,127 @@
+// @vitest-environment jsdom
+import type { ReactNode } from 'react'
+import { afterEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
+import type { RpcConnectorsResult } from '../../../../src/types'
+import { desktopQueryKeys } from '../../hooks/domain/queryKeys'
+import { McpServersPage } from '../McpServersPage'
+
+/**
+ * T1: the fixture is typed as `RpcConnectorsResult` — the exact contract the IPC
+ * bridge resolves from rpc-proxy's `GET /api/v1/rpc/connectors` (U1). The
+ * compiler rejects any field the producer would not emit, and the U1 layer has
+ * its own real-producer (Postgres + upsertOAuthGrant) integration tests.
+ * T4: assertions are on the OBSERVABLE chip label + action the user sees.
+ */
+const CONNECTORS: RpcConnectorsResult = {
+ userId: 'user-1',
+ agents: [
+ {
+ name: 'agent-alpha',
+ contextRef: 'ctx-team',
+ connectors: [
+ {
+ name: 'monday',
+ provider: 'monday',
+ authKind: 'oauth-user',
+ grantScope: 'user',
+ status: 'authorized',
+ },
+ {
+ name: 'clickup',
+ provider: 'clickup',
+ authKind: 'oauth-user',
+ grantScope: 'user',
+ status: 'requires_setup',
+ },
+ { name: 'filesystem', authKind: 'static', status: 'no_oauth' },
+ {
+ name: 'shared-drive',
+ provider: 'google',
+ authKind: 'oauth-context',
+ grantScope: 'context',
+ status: 'requires_setup',
+ },
+ ],
+ },
+ ],
+}
+
+function installClerum(result: RpcConnectorsResult) {
+ const rpc = {
+ listConnectors: vi.fn(async () => result),
+ connectMcpServer: vi.fn(async () => undefined),
+ disconnectMcpServer: vi.fn(async () => ({ confirmed: true })),
+ }
+ Object.defineProperty(window, 'clerum', { configurable: true, value: { rpc } })
+ return rpc
+}
+
+function renderPage(result: RpcConnectorsResult) {
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ })
+ // The controller's query is `enabled:false` — the app coordinator owns the
+ // initial load, so a navigation to the panel only READS cache. Seed the cache
+ // the way the post-auth bootstrap would, then render.
+ client.setQueryData(desktopQueryKeys.connectors, result)
+ return render(
+ <QueryClientProvider client={client}>
+ <McpServersPage />
+ </QueryClientProvider>
+ )
+}
+
+describe('McpServersPage — tri-state chip + actionability (T5#3, T4)', () => {
+ afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+ delete (window as { clerum?: unknown }).clerum
+ })
+
+ it('distinguishes the 3 statuses and only authorized/requires_setup are actionable', async () => {
+ installClerum(CONNECTORS)
+ const { container } = renderPage(CONNECTORS)
+
+ // The agent group renders once the query resolves.
+ await waitFor(() => expect(screen.getByRole('heading', { name: 'agent-alpha' })).toBeTruthy())
+
+ const rows = Array.from(container.querySelectorAll<HTMLElement>('.da-grid__body .da-grid__row'))
+ // One row per connector in the fixture.
+ expect(rows).toHaveLength(4)
+
+ const rowByFirstCellText = (needle: string) => {
+ const row = rows.find(r => (r.textContent ?? '').includes(needle))
+ if (!row) throw new Error(`row not found for ${needle}`)
+ return row
+ }
+ const chipText = (row: HTMLElement) =>
+ row.querySelector('.ui-pill')?.textContent?.trim() ?? null
+ const buttonNames = (row: HTMLElement) =>
+ within(row)
+ .queryAllByRole('button')
+ .map(b => b.textContent?.trim())
+
+ // authorized → "Authorized" chip + Disconnect only.
+ const authorizedRow = rowByFirstCellText('monday')
+ expect(chipText(authorizedRow)).toBe('Authorized')
+ expect(buttonNames(authorizedRow)).toEqual(['Disconnect'])
+
+ // requires_setup (oauth-user) → "Requires setup" chip + Authorize only.
+ const requiresRow = rowByFirstCellText('clickup')
+ expect(chipText(requiresRow)).toBe('Requires setup')
+ expect(buttonNames(requiresRow)).toEqual(['Authorize'])
+
+ // no_oauth → "No OAuth" chip + NO action button (not actionable on this rail).
+ const noOauthRow = rowByFirstCellText('filesystem')
+ expect(chipText(noOauthRow)).toBe('No OAuth')
+ expect(buttonNames(noOauthRow)).toEqual([])
+
+ // oauth-context requires_setup → actionable AND flagged as shared/team-wide.
+ const sharedRow = rowByFirstCellText('shared-drive')
+ expect(chipText(sharedRow)).toBe('Requires setup')
+ expect(buttonNames(sharedRow)).toEqual(['Authorize'])
+ expect(within(sharedRow).getByText(/Shared by the team/i)).toBeTruthy()
+ })
+})