Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
Merge branch 'feat/mcp-connectors-disconnect' into feat/mcp-connectors-desktop
Diego Zacariasc1dbf9377d58
diff --cc desktop-app/src/appService.tsindex 291210973,5423bd995..6f7675637--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@@ -4553,122 -4573,9 +4583,121 @@@ export class AppServicethrow error}}- const { shell } = await import('electron')- await shell.openExternal(result.authorizeUrl)+ await openExternalDataUrl(result.authorizeUrl, { requireHttps: true })}+ /**+ * 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 embeddeddiff --cc desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsxindex ffa195688,3bee9ebfa..2c9d24a96--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx@@@ -184,11 -203,7 +203,12 @@@ export function extendMockClerumForAppCprewarmHost: 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 })),+ onMcpOauthCompleted,})Object.assign(bridge, {diff --cc desktop-app/ui/src/hooks/useAppController.tsindex 98fd1e56f,effebb514..5602e8aa9--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@@ -24,8 -24,9 +24,10 @@@ import typeimport {type ApprovalDecisionTarget,decideApproval as decideApprovalCore,+ handleMcpOauthCompletion,+ resolveConnectResumeTargets,} from './domain/approvalDecision'+ import { createMcpOauthResumeBuffer } from './domain/mcpOauthResumeBuffer'import { desktopQueryKeys } from './domain/queryKeys'import { useActivityController } from './domain/useActivityController'import { useAgentChatController } from './domain/useAgentChatController'@@@ -325,30 -337,53 +343,69 @@@ export function useAppController()// on that server, since a per-user grant is global to the user) and needs no// 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).+ //+ // R3-M1 (cold start): a completion can arrive BEFORE the FSM snapshot is seeded+ // (sessions load async/auth-gated after `rendererReady`), so `resolve…` returns+ // `[]` even though the grant exists and a conversation is suspended. Dropping it+ // there loses the auto-resume. Instead, an empty resolve buffers the completion+ // (bounded TTL) and the store `subscribe` re-evaluates it on EVERY snapshot+ // change until its deadline. The buffered entry is kept — not dropped on the+ // first match — because the real seam (`seedSessionSnapshots`) dispatches one+ // session per snapshot, so siblings on the SAME server surface across separate+ // notifications; keeping the entry alive lets every one of them resume within+ // the window (the per-user grant is global to the user). A resumed conversation+ // leaves `awaiting_approval`, so it stops resolving as a target — each sibling+ // fires once, and any redundant re-fire is a guarded no-op (decideApproval step- // 1 + mcp-host per-`requestId` idempotency). A completion that resolves targets- // on arrival (the normal path) fires immediately and never enters the buffer.- // Subscribed once; `chat.sessionFsmStore`, `decideApprovalRef` and the buffer- // ref are read live.++ // 1 + mcp-host per-`requestId` idempotency).++ //++ // U3 (mcp-oauth PROACTIVE consent) adds the connectors-panel arm: EVERY++ // completion refreshes the panel via `handleMcpOauthCompletion` (which resumes++ // any already-seeded suspended turn AND refreshes), so both the PROACTIVE (no++ // turn in flight) and coexistence (turn + panel) cases re-read the grant store++ // (U1 tri-state, D4). When the completion resolves no targets on arrival —++ // proactive OR cold-start — it is buffered: a genuinely proactive entry keeps++ // resolving `[]` and expires at TTL, a cold-start one resumes once the FSM is++ // seeded. Subscribed once; `chat.sessionFsmStore`, `decideApprovalRef`, the++ // buffer ref and `connectorsData.refresh` are read live.useEffect(() => {+ const store = chat.sessionFsmStore+ const buffer = mcpOauthResumeBufferRef.current!+ const fire = (targets: ApprovalDecisionTarget[]) => {+ for (const target of targets) void decideApprovalRef.current(target)+ }+const unsub = window.clerum.rpc.onMcpOauthCompleted?.(({ mcpServerName }) => {- handleMcpOauthCompletion(- const targets = resolveConnectResumeTargets(store.getSnapshot(), mcpServerName)- if (targets.length > 0) {- fire(targets)- return++ // Immediate arm: resume any already-seeded suspended turn(s) AND refresh++ // the connectors panel (U3). The panel query is `enabled:false`, so an++ // invalidate would only mark it stale — drive the imperative refresh.++ const { resumedCount } = handleMcpOauthCompletion(+ {- getSnapshot: () => chat.sessionFsmStore.getSnapshot(),++ getSnapshot: () => store.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+ )++ if (resumedCount === 0) {++ // Nothing resolved on arrival — proactive (no turn) OR cold-start (FSM++ // not seeded yet). Buffer for retry on a later snapshot; a proactive++ // entry keeps resolving `[]` and expires harmlessly at its TTL.++ buffer.add(mcpServerName, Date.now() + MCP_OAUTH_RESUME_BUFFER_TTL_MS)+ }- // Cold start: grant exists but sessions aren't seeded yet — retry on a- // later snapshot rather than dropping the resume.- buffer.add(mcpServerName, Date.now() + MCP_OAUTH_RESUME_BUFFER_TTL_MS)+ })++ const unsubStore = store.subscribe(() => {+ if (buffer.size() === 0) return+ fire(+ buffer.drain(Date.now(), server => resolveConnectResumeTargets(store.getSnapshot(), server))+ )})- return () => unsub?.()++ return () => {+ unsub?.()+ unsubStore()+ }- }, [chat.sessionFsmStore])+ }, [chat.sessionFsmStore, connectorsData.refresh])// ─── MCP Server ───const mcpServer = useMcpServerController({