Skip to content

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

TypeScript

feat(desktop-app): u5 reactive oauth connect prompt + deep-link resume

Diego Zacariasbdc099c3f0cc
diff --git a/desktop-app/src/__tests__/clerumDeepLink.test.ts b/desktop-app/src/__tests__/clerumDeepLink.test.ts
new file mode 100644
index 000000000..2fa9e0c5f
--- /dev/null
+++ b/desktop-app/src/__tests__/clerumDeepLink.test.ts
@@ -0,0 +1,77 @@
+import { describe, expect, it } from 'vitest'
+import { routeClerumOauthCompleted } from '../clerumDeepLink.js'
+
+const PROTO = 'clerum'
+
+describe('routeClerumOauthCompleted — U5 source branching (T5 guardian)', () => {
+ it('source ABSENT routes to the sandbox-ui embed, byte-identical to pre-U5', () => {
+ const route = routeClerumOauthCompleted(
+ 'clerum://oauth-completed?clientId=abc123&provider=google',
+ PROTO
+ )
+ // The sandbox-ui / recipe path is unchanged: same clientId + provider envelope
+ // the embed dispatch has always consumed.
+ expect(route).toEqual({ kind: 'sandbox', oauthClientId: 'abc123', provider: 'google' })
+ })
+
+ it('source=mcp routes to the task resume (NOT the embed), carrying mcpServerName', () => {
+ const route = routeClerumOauthCompleted(
+ 'clerum://oauth-completed?clientId=abc123&provider=google&source=mcp&mcpServerName=monday',
+ PROTO
+ )
+ expect(route).toEqual({ kind: 'mcp', mcpServerName: 'monday', provider: 'google' })
+ // Guardian: an mcp completion must never be dispatched to the sandbox embed.
+ expect(route.kind).not.toBe('sandbox')
+ })
+
+ it('source=mcp wins even though the deep-link still carries clientId', () => {
+ // control-api builds clientId unconditionally; the branch is on `source`, so
+ // the presence of clientId must NOT drag an mcp completion into the embed path.
+ const route = routeClerumOauthCompleted(
+ 'clerum://oauth-completed?clientId=abc123&provider=microsoft-graph&source=mcp&mcpServerName=office365',
+ PROTO
+ )
+ expect(route.kind).toBe('mcp')
+ })
+
+ it('an unknown source (!== mcp) falls through to the sandbox path unchanged', () => {
+ const route = routeClerumOauthCompleted(
+ 'clerum://oauth-completed?clientId=abc123&provider=google&source=recipe',
+ PROTO
+ )
+ expect(route).toEqual({ kind: 'sandbox', oauthClientId: 'abc123', provider: 'google' })
+ })
+
+ it('missing clientId is ignored for BOTH paths (guard precedes the source branch)', () => {
+ expect(routeClerumOauthCompleted('clerum://oauth-completed?provider=google', PROTO).kind).toBe(
+ 'ignore'
+ )
+ expect(
+ routeClerumOauthCompleted(
+ 'clerum://oauth-completed?provider=google&source=mcp&mcpServerName=monday',
+ PROTO
+ ).kind
+ ).toBe('ignore')
+ })
+
+ it('ignores a non-clerum protocol, a wrong host, and an unparseable URL', () => {
+ expect(routeClerumOauthCompleted('https://oauth-completed?clientId=x', PROTO).kind).toBe(
+ 'ignore'
+ )
+ expect(routeClerumOauthCompleted('clerum://oauth?clientId=x&source=mcp', PROTO).kind).toBe(
+ 'ignore'
+ )
+ expect(routeClerumOauthCompleted('not a url', PROTO).kind).toBe('ignore')
+ })
+
+ it('mcpServerName defaults to empty string when absent on an mcp deep-link', () => {
+ // Forward-compatibility: if control-api has not yet appended &mcpServerName,
+ // the route is still mcp (never sandbox) with an empty key — the renderer then
+ // simply finds no correlation match rather than mis-dispatching to the embed.
+ const route = routeClerumOauthCompleted(
+ 'clerum://oauth-completed?clientId=abc123&provider=google&source=mcp',
+ PROTO
+ )
+ expect(route).toEqual({ kind: 'mcp', mcpServerName: '', provider: 'google' })
+ })
+})
diff --git a/desktop-app/src/__tests__/mcpOauthCompletionQueue.test.ts b/desktop-app/src/__tests__/mcpOauthCompletionQueue.test.ts
new file mode 100644
index 000000000..6bf8d73d7
--- /dev/null
+++ b/desktop-app/src/__tests__/mcpOauthCompletionQueue.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it, vi } from 'vitest'
+import { McpOauthCompletionQueue } from '../mcpOauthCompletionQueue.js'
+
+const A = { mcpServerName: 'monday', provider: 'google' }
+const B = { mcpServerName: 'clickup', provider: 'clickup' }
+
+describe('McpOauthCompletionQueue — U5 cold-start delivery (T5)', () => {
+ it('delivers immediately when the renderer is ready (queue stays empty)', () => {
+ const deliver = vi.fn().mockReturnValue(true)
+ const queue = new McpOauthCompletionQueue(deliver)
+
+ queue.submit(A)
+
+ expect(deliver).toHaveBeenCalledOnce()
+ expect(deliver).toHaveBeenCalledWith(A)
+ expect(queue.pendingCount()).toBe(0)
+ })
+
+ it('a completion arriving BEFORE renderer-ready is queued, then delivered on drain (not lost)', () => {
+ // deliver returns false while the renderer is not ready, true afterwards —
+ // exactly the cold-start sequence (deep link before the ready handshake).
+ let ready = false
+ const deliver = vi.fn((_c: typeof A) => ready)
+ const queue = new McpOauthCompletionQueue(deliver)
+
+ // Cold start: deep link arrives before the renderer installs its listener.
+ queue.submit(A)
+ expect(queue.pendingCount()).toBe(1) // held, NOT swallowed
+ expect(deliver).toHaveBeenCalledTimes(1) // one failed attempt
+
+ // Renderer-ready handshake fires → drain flushes the held completion.
+ ready = true
+ queue.drain()
+
+ expect(deliver).toHaveBeenLastCalledWith(A)
+ expect(queue.pendingCount()).toBe(0)
+ })
+
+ it('queues multiple distinct completions across concurrent cold-start suspensions', () => {
+ const deliver = vi.fn().mockReturnValue(false)
+ const queue = new McpOauthCompletionQueue(deliver)
+
+ queue.submit(A)
+ queue.submit(B)
+ expect(queue.pendingCount()).toBe(2)
+
+ const delivered: Array<typeof A> = []
+ const queue2Deliver = vi.fn((c: typeof A) => {
+ delivered.push(c)
+ return true
+ })
+ // Re-drain through a ready deliver by swapping behaviour: emulate readiness.
+ deliver.mockImplementation(c => {
+ queue2Deliver(c)
+ return true
+ })
+ queue.drain()
+
+ expect(delivered).toEqual([A, B])
+ expect(queue.pendingCount()).toBe(0)
+ })
+
+ it('dedups an identical retried completion while queued', () => {
+ const deliver = vi.fn().mockReturnValue(false)
+ const queue = new McpOauthCompletionQueue(deliver)
+
+ queue.submit(A)
+ queue.submit(A)
+
+ expect(queue.pendingCount()).toBe(1)
+ })
+
+ it('re-queues a completion the renderer still cannot accept mid-drain (never dropped)', () => {
+ const deliver = vi.fn().mockReturnValue(false)
+ const queue = new McpOauthCompletionQueue(deliver)
+
+ queue.submit(A)
+ queue.drain() // window died again → still not accepted
+
+ expect(queue.pendingCount()).toBe(1)
+ })
+})
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index f3c2539c6..3bdb8b8e4 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -148,6 +148,12 @@ const HOST_MODEL_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.model
const HOST_ARTIFACT_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.artifact
const HOST_APPROVAL_SCOPES: RpcScope[] = HOST_FINITE_OPERATION_SCOPES.approval
const MCP_SERVERS_LIST_SCOPES: RpcScope[] = ['mcp:servers:list']
+// U5 (mcp-oauth reactive consent): "Connect <server>" reuses the SAME capability
+// the desktop already holds to invoke mcp tools — connecting is a precondition of
+// invoking, so rpc-proxy gates the authorize-url route on this scope (no new
+// scope is minted). The token is host-bound to the suspended conversation's
+// hostRef, which the user demonstrably has access to.
+const MCP_SERVER_INVOKE_SCOPES: RpcScope[] = ['mcp:server:invoke']
const DESKTOP_VIEW_SCOPES: RpcScope[] = ['desktop:view']
const SANDBOX_UI_VIEW_SCOPES: RpcScope[] = ['sandbox:ui:view']
// hostRefs is required by control-api's RPC token issuance (see
@@ -3019,6 +3025,52 @@ export class AppService {
await shell.openExternal(result.authorizeUrl)
}
+ /**
+ * U5 (mcp-oauth reactive consent) — the renderer's "Connect <server>" button.
+ * A tool-call against an OAuth mcp-server suspended the task with
+ * `connect_required`; this fetches a fresh provider authorize URL via rpc-proxy
+ * and `shell.openExternal`s it. The rest of the flow runs in the OS browser;
+ * control-api's callback stores the grant and bounces back to
+ * `clerum://oauth-completed?…&source=mcp`, which `main.ts` routes to the
+ * renderer to resume the suspended task (NOT the sandbox-ui embed).
+ *
+ * Analogous to `requestSandboxUiOauthAuthorize`, but keyed by `mcpServerName`
+ * (never a recipe) and host-bound to the suspended conversation's `hostRef`
+ * (RPC tokens require ≥1 hostRef; the user has access to the host they are
+ * chatting in). `userId` is derived by rpc-proxy from `auth.sub`, never sent.
+ */
+ async requestMcpOauthAuthorize(
+ mcpServerName: string,
+ hostRef: string,
+ contextId?: string
+ ): 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
+ let rpc = await this.issueRpcTokenForHostRefs(MCP_SERVER_INVOKE_SCOPES, [targetHostRef])
+ let result: { authorizeUrl: string }
+ try {
+ result = await this.rpcClient.requestMcpOauthAuthorizeUrl(rpc.token, server, ctx)
+ } catch (error) {
+ // §4.5-7: a 401/expired-scope means the 300s RPC token lapsed; clear the
+ // cache, re-mint (same hostRef) and retry once. Every 401/403-missing-scope
+ // on this route is emitted by rpc-proxy's auth middleware BEFORE any grant
+ // mutation, so a retried error is always a pre-effect rejection — the
+ // authorize-url mint is idempotent regardless.
+ if (AppService.shouldRefreshRpcToken(error)) {
+ this.rpcTokenManager.clear()
+ rpc = await this.issueRpcTokenForHostRefs(MCP_SERVER_INVOKE_SCOPES, [targetHostRef])
+ result = await this.rpcClient.requestMcpOauthAuthorizeUrl(rpc.token, server, ctx)
+ } else {
+ throw error
+ }
+ }
+ const { shell } = await import('electron')
+ await shell.openExternal(result.authorizeUrl)
+ }
+
/**
* 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/clerumDeepLink.ts b/desktop-app/src/clerumDeepLink.ts
new file mode 100644
index 000000000..c5ac89664
--- /dev/null
+++ b/desktop-app/src/clerumDeepLink.ts
@@ -0,0 +1,52 @@
+/**
+ * Pure routing for the `clerum://oauth-completed?…` deep link the control-api
+ * OAuth callback bounces to. Extracted from `main.ts` (which has no testable
+ * exports) so the source-branching invariant is unit-testable — mirrors the
+ * `mainWindowCoordinator` extraction pattern.
+ *
+ * Two producers land on the SAME `oauth-completed` host:
+ * - sandbox-ui / recipe OAuth — FROZEN wire shape: `clientId` + `provider`, no
+ * `source`. Routed to the active sandbox-ui embed (`dispatchSandboxUiOauthCompleted`).
+ * - mcp-server OAuth (U5 reactive consent) — control-api appends `&source=mcp`
+ * (and, per the option-(b) deep-link, `&mcpServerName=<X>`). Routed to the
+ * renderer to resume the suspended conversation, correlated by `mcpServerName`.
+ *
+ * The `source`-absent / `source!=='mcp'` path is byte-identical to the pre-U5
+ * behaviour: same guard order, same `clientId`-required rejection, same sandbox
+ * envelope.
+ */
+export type ClerumOauthCompletedRoute =
+ | { kind: 'ignore' }
+ | { kind: 'sandbox'; oauthClientId: string; provider: string }
+ | { kind: 'mcp'; mcpServerName: string; provider: string }
+
+export function routeClerumOauthCompleted(
+ rawUrl: string,
+ clerumProtocol: string
+): ClerumOauthCompletedRoute {
+ let parsed: URL
+ try {
+ parsed = new URL(rawUrl)
+ } catch {
+ return { kind: 'ignore' }
+ }
+ if (parsed.protocol !== `${clerumProtocol}:`) return { kind: 'ignore' }
+ if (parsed.hostname.toLowerCase() !== 'oauth-completed') return { kind: 'ignore' }
+
+ const oauthClientId = parsed.searchParams.get('clientId') || ''
+ const provider = parsed.searchParams.get('provider') || ''
+ // clientId is required for BOTH producers (control-api builds it
+ // unconditionally, even for the mcp subject), so the guard precedes the
+ // source branch exactly as before — an mcp completion still carries clientId.
+ if (!oauthClientId) return { kind: 'ignore' }
+
+ if ((parsed.searchParams.get('source') || '') === 'mcp') {
+ return {
+ kind: 'mcp',
+ mcpServerName: parsed.searchParams.get('mcpServerName') || '',
+ provider,
+ }
+ }
+
+ return { kind: 'sandbox', oauthClientId, provider }
+}
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 573ffafe6..7400a645b 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -966,6 +966,19 @@ export function registerIpcHandlers(service: AppService): void {
}
)
+ // U5 (mcp-oauth reactive consent): the renderer's "Connect <server>" button.
+ // Fetches a fresh provider authorize-URL (host-bound to the suspended
+ // 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 }) => {
+ assertTrustedSender(event)
+ const server = sanitizeString(mcpServerName)
+ const targetHostRef = sanitizeString(hostRef)
+ const ctx = sanitizeString(contextId) || undefined
+ return service.requestMcpOauthAuthorize(server, targetHostRef, ctx)
+ })
+
ipcMain.handle('rpc:listServers', async (event, { hostRefs }) => {
assertTrustedSender(event)
return service.listAccessibleMcpServers(hostRefs)
diff --git a/desktop-app/src/main.ts b/desktop-app/src/main.ts
index d190f540e..ad8ef5cc7 100644
--- a/desktop-app/src/main.ts
+++ b/desktop-app/src/main.ts
@@ -1,10 +1,12 @@
import { BrowserWindow, app, ipcMain, nativeTheme, powerMonitor } from 'electron'
import path from 'node:path'
import { AppService } from './appService.js'
+import { routeClerumOauthCompleted } from './clerumDeepLink.js'
import { config } from './config.js'
import { assertTrustedSender, registerIpcHandlers } from './ipc.js'
import { createMainWindowCoordinator, createRetryableInitializer } from './mainWindowCoordinator.js'
import { wireMainWindowRendererReadiness } from './mainWindowReadiness.js'
+import { McpOauthCompletionQueue } from './mcpOauthCompletionQueue.js'
import { collectInitialProtocolUrls } from './protocolLaunchArgs.js'
import { SandboxUiDeepLinkQueue } from './sandboxUiDeepLinkQueue.js'
import {
@@ -32,6 +34,15 @@ const appService = new AppService()
const pendingEvenfireUrls: string[] = []
const MAX_PENDING_EVENFIRE_URLS = 20
const sandboxUiDeepLinkQueue = new SandboxUiDeepLinkQueue()
+// U5: deliver mcp-oauth completions to the renderer, or queue them when the
+// renderer is not yet ready (cold start), draining after `app:rendererReady`.
+const mcpOauthCompletionQueue = new McpOauthCompletionQueue(completion => {
+ if (mainWindow && !mainWindow.isDestroyed() && mainWindowRendererReady) {
+ mainWindow.webContents.send('rpc:mcpOauthCompleted', completion)
+ return true
+ }
+ return false
+})
let mainWindowLifecycleReady = false
let mainWindowRendererReady = false
let appWindowVisibilityWired = false
@@ -145,6 +156,11 @@ ipcMain.handle('app:rendererReady', event => {
if (!mainWindow || event.sender !== mainWindow.webContents) return
mainWindowRendererReady = true
drainPendingEvenfireUrls()
+ // U5: flush mcp-oauth completions that arrived before the renderer installed
+ // its listener (cold start). The onMcpOauthCompleted listener is registered by
+ // useAppController's effect, which runs before App's rendererReady effect, so
+ // it is guaranteed installed by the time this handshake fires.
+ mcpOauthCompletionQueue.drain()
})
ipcMain.handle('sandboxUi:listPendingDeepLinks', event => {
@@ -295,22 +311,33 @@ function drainPendingEvenfireUrls(): void {
* the OS-protocol-handler level.
*/
function handleClerumUrl(rawUrl: string): void {
- let parsed: URL
- try {
- parsed = new URL(rawUrl)
- } catch {
+ // U5 (mcp-oauth reactive consent): the routing decision — which producer this
+ // deep link came from — lives in the pure, unit-tested `routeClerumOauthCompleted`.
+ // The sandbox-ui path (source absent / !== 'mcp') is byte-identical to before.
+ const route = routeClerumOauthCompleted(rawUrl, CLERUM_PROTOCOL)
+ if (route.kind === 'ignore') return
+
+ if (route.kind === 'mcp') {
+ // An mcp-server OAuth completion resumes the suspended conversation: forward
+ // `mcpServerName` (the correlation key, self-describing on the deep-link) to
+ // the renderer, which matches it against its suspended entries and re-fires
+ // the approval/resume RPC. It does NOT dispatch to the sandbox-ui embed.
+ // Queued when the renderer is not yet ready (cold start) so it is never
+ // swallowed before `onMcpOauthCompleted` is installed.
+ mcpOauthCompletionQueue.submit({
+ mcpServerName: route.mcpServerName,
+ provider: route.provider,
+ })
+ focusMainWindow()
return
}
- if (parsed.protocol !== `${CLERUM_PROTOCOL}:`) return
- if (parsed.hostname.toLowerCase() !== 'oauth-completed') return
-
- const oauthClientId = parsed.searchParams.get('clientId') || ''
- const provider = parsed.searchParams.get('provider') || ''
- if (!oauthClientId) return
void (async () => {
const driver = await import('./sandboxUiDriver.js')
- driver.dispatchSandboxUiOauthCompleted({ oauthClientId, provider })
+ driver.dispatchSandboxUiOauthCompleted({
+ oauthClientId: route.oauthClientId,
+ provider: route.provider,
+ })
})()
focusMainWindow()
diff --git a/desktop-app/src/mcpOauthCompletionQueue.ts b/desktop-app/src/mcpOauthCompletionQueue.ts
new file mode 100644
index 000000000..4ce3a3ae2
--- /dev/null
+++ b/desktop-app/src/mcpOauthCompletionQueue.ts
@@ -0,0 +1,62 @@
+/**
+ * U5 (mcp-oauth reactive consent) — cold-start delivery guard for the OAuth
+ * `oauth-completed?source=mcp` deep link.
+ *
+ * On a cold start the deep link arrives (macOS `app.on('open-url')`, or the
+ * non-darwin startup-argv sweep) BEFORE the renderer has mounted and installed
+ * its `onMcpOauthCompleted` listener. A bare `webContents.send` at that moment is
+ * swallowed and the suspended task never resumes. This mirrors the
+ * `pendingEvenfireUrls` queue: deliver immediately when the renderer is ready,
+ * otherwise queue and drain after the `app:rendererReady` handshake.
+ *
+ * Extracted as an injectable class (like `SandboxUiDeepLinkQueue`) so the
+ * "never swallowed on cold start" invariant is unit-testable without booting the
+ * Electron main process.
+ */
+export interface McpOauthCompletion {
+ mcpServerName: string
+ provider: string
+}
+
+export class McpOauthCompletionQueue {
+ private readonly pending: McpOauthCompletion[] = []
+
+ /**
+ * @param deliver Sends the completion to the renderer, returning `true` iff it
+ * was accepted (window alive AND renderer past its ready handshake). A
+ * `false` return means "not ready" → the completion is queued.
+ */
+ constructor(
+ private readonly deliver: (completion: McpOauthCompletion) => boolean,
+ private readonly maxSize = 20
+ ) {}
+
+ /** Deliver now if the renderer accepts it; otherwise queue for `drain()`. */
+ submit(completion: McpOauthCompletion): void {
+ if (this.deliver(completion)) return
+ // Dedup identical completions (a retried deep link) while keeping distinct
+ // servers/providers — two conversations on different servers must both queue.
+ const duplicate = this.pending.some(
+ c => c.mcpServerName === completion.mcpServerName && c.provider === completion.provider
+ )
+ if (duplicate) return
+ this.pending.push(completion)
+ if (this.pending.length > this.maxSize) this.pending.shift()
+ }
+
+ /**
+ * Flush queued completions — called after the renderer-ready handshake. Any the
+ * renderer still cannot accept (window died mid-drain) are re-queued rather than
+ * dropped.
+ */
+ drain(): void {
+ const batch = this.pending.splice(0)
+ for (const completion of batch) {
+ if (!this.deliver(completion)) this.pending.push(completion)
+ }
+ }
+
+ pendingCount(): number {
+ return this.pending.length
+ }
+}
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 1239a88e2..d1bd9c8de 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -342,6 +342,23 @@ const clerum = Object.freeze({
setHostModel: (hostRef: string, chatId: string, model: string, hostRefs?: string[]) =>
ipcRenderer.invoke('rpc:setHostModel', { hostRef, chatId, model, hostRefs }),
getTokenMetadata: () => ipcRenderer.invoke('rpc:getTokenMetadata'),
+ // 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 }),
+ // Fired when the OAuth deep-link returns with `source=mcp`. The renderer
+ // correlates `mcpServerName` to its suspended entries and resumes the task.
+ onMcpOauthCompleted: (
+ callback: (args: { mcpServerName: string; provider: string }) => void
+ ) => {
+ const listener = (
+ _event: Electron.IpcRendererEvent,
+ args: { mcpServerName: string; provider: string }
+ ) => callback(args)
+ ipcRenderer.on('rpc:mcpOauthCompleted', listener)
+ return () => ipcRenderer.off('rpc:mcpOauthCompleted', listener)
+ },
},
workflows: {
list: () => ipcRenderer.invoke('workflows:list'),
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 6d54a7a29..71669a31f 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -438,6 +438,18 @@ declare global {
hostRefs?: string[]
) => Promise<SetHostModelResult>
getTokenMetadata: () => Promise<TokenMetadata>
+ // U5 (mcp-oauth reactive consent): "Connect <server>" for a task
+ // suspended with `connect_required`. Host-bound to that conversation.
+ connectMcpServer: (
+ mcpServerName: string,
+ hostRef: string,
+ contextId?: string
+ ) => Promise<void>
+ // Push fired when the OAuth deep-link returns with `source=mcp`; the
+ // renderer correlates `mcpServerName` and resumes the suspended task.
+ onMcpOauthCompleted: (
+ callback: (args: { mcpServerName: string; provider: string }) => void
+ ) => () => void
}
app: {
openUrl: (url: string) => Promise<void>
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index 73772ebcd..940d523c7 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -601,6 +601,55 @@ export class RpcProxyClient {
return { authorizeUrl: json.authorizeUrl }
}
+ /**
+ * U5 (mcp-oauth reactive consent) — fetch the provider authorize URL for a
+ * "Connect <server>" flow, initiated when a tool-call against an OAuth
+ * mcp-server suspended with `connect_required`. Mirrors
+ * `requestSandboxUiOauthAuthorizeUrl` but keyed by `mcpServerName` (never a
+ * recipe): rpc-proxy derives the `userId` from `auth.sub` and forwards to
+ * control-api's internal mint. The returned URL is opened via
+ * `shell.openExternal`.
+ *
+ * Throws `ApiError` (not a bare Error) so `AppService.shouldRefreshRpcToken`
+ * can see a 401/403-missing-scope status and drive the retry-after-refresh,
+ * exactly like `approveToolCall`. A legitimate 403 (`context_membership_denied`),
+ * 404 (`server_not_found`), 400 (`not_oauth_server`, …) or 502/503 propagates
+ * verbatim in the message for the renderer to surface.
+ */
+ async requestMcpOauthAuthorizeUrl(
+ rpcAccessToken: string,
+ mcpServerName: string,
+ contextId?: string
+ ): Promise<{ authorizeUrl: string }> {
+ const response = await fetch(
+ url(`/api/v1/mcp-oauth/${encodeURIComponent(mcpServerName)}/authorize-url`),
+ {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${rpcAccessToken}`,
+ 'content-type': 'application/json',
+ },
+ // Body is optional; only send `contextId` when present. The `userId` is
+ // NEVER sent — rpc-proxy derives it from the JWT sub (invariant 3).
+ body: JSON.stringify(contextId ? { contextId } : {}),
+ signal: withTimeout(),
+ }
+ )
+ if (!response.ok) {
+ const body = await response.text()
+ throw new ApiError(
+ `mcp-oauth authorize-url request failed (${response.status}): ${body || '<empty>'}`,
+ response.status,
+ body
+ )
+ }
+ const json = (await response.json()) as { authorizeUrl?: unknown }
+ if (typeof json?.authorizeUrl !== 'string' || !json.authorizeUrl) {
+ throw new Error('mcp-oauth authorize-url response missing authorizeUrl')
+ }
+ return { authorizeUrl: json.authorizeUrl }
+ }
+
private async openHostStream(
rpcAccessToken: string,
path: string,
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 7b3570468..b15dc3d32 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -767,6 +767,13 @@ export type TaskProgressStreamEvent =
requestId: string
displayName: string
reason: string
+ // U5 (mcp-oauth reactive consent): present ONLY when
+ // `reason === 'connect_required'` — the mcp-host emitter attaches these
+ // so the desktop renders a "Connect <server>" prompt (not the generic
+ // approval prompt) and correlates the later deep-link completion back to
+ // this suspension by `mcpServerName`. Absent for `approval_required`.
+ mcpServerName?: string
+ provider?: string
}
}
| { type: 'cancelled'; data: { taskId: string; reason: string } }
@@ -835,6 +842,14 @@ export type SessionLifecycleState = 'idle' | 'processing' | 'awaiting_approval'
export interface PendingApprovalLite {
requestId: string
displayName: string
+ // U5 (mcp-oauth reactive consent): additive. `reason === 'connect_required'`
+ // marks a suspension that needs an OAuth "Connect <server>" flow rather than a
+ // generic tool approval; `mcpServerName`/`provider` identify the server to
+ // connect and correlate the deep-link completion back to this suspension.
+ // Absent on ordinary `approval_required` suspensions (byte-identical there).
+ reason?: string
+ mcpServerName?: string
+ provider?: string
}
/**
diff --git a/desktop-app/ui/src/components/ProgressStepper.tsx b/desktop-app/ui/src/components/ProgressStepper.tsx
index 6a3c3d9e0..9b356acb7 100644
--- a/desktop-app/ui/src/components/ProgressStepper.tsx
+++ b/desktop-app/ui/src/components/ProgressStepper.tsx
@@ -12,6 +12,9 @@ interface ProgressStepperProps {
onApprove?: () => void
onDeny?: () => void
onCancel?: () => void
+ // U5 (mcp-oauth reactive consent): fired for a `connect_required` suspension —
+ // opens the provider "Connect <server>" OAuth flow instead of Approve/Deny.
+ onConnect?: () => void
}
function ThinkingIndicator({ label }: { label: string }) {
@@ -258,9 +261,11 @@ export function ProgressStepper({
onApprove,
onDeny,
onCancel,
+ onConnect,
}: ProgressStepperProps) {
const [expanded, setExpanded] = useState(false)
const [approvalPending, setApprovalPending] = useState(false)
+ const [connectPending, setConnectPending] = useState(false)
const [isCancelling, setIsCancelling] = useState(false)
const handleCancelClick = () => {
@@ -274,6 +279,15 @@ export function ProgressStepper({
return () => clearTimeout(timeout)
}, [isCancelling])
+ // U5: re-enable the Connect button after a short window so a user who dismissed
+ // the browser consent (task still suspended) can retry. Once the connect
+ // completes the task resumes and the suspended block unmounts entirely.
+ useEffect(() => {
+ if (!connectPending) return
+ const timeout = setTimeout(() => setConnectPending(false), 5000)
+ return () => clearTimeout(timeout)
+ }, [connectPending])
+
const status = progress?.status
const stopAgentAriaLabel = isCancelling ? 'Stopping agent' : 'Stop agent'
useEffect(() => {
@@ -396,17 +410,28 @@ export function ProgressStepper({
if (status === 'suspended') {
const info = progress.suspendedInfo
+ // U5: a `connect_required` suspension renders a "Connect <server>" prompt and
+ // a Connect button (opens the provider OAuth flow) instead of Approve/Deny.
+ // `canConnect` requires BOTH the marker and a usable `onConnect` (which the
+ // caller only wires when `mcpServerName` is present) — a connect_required
+ // without an actionable connect falls back to the generic Approve/Deny prompt
+ // rather than rendering a dead-end suspended block with no action.
+ const isConnect = info?.reason === 'connect_required'
+ const connectServer = info?.mcpServerName || 'the connector'
+ const canConnect = isConnect && !!onConnect
return (
<div data-testid="progress-stepper" className="progress-stepper status-suspended">
<div className="stepper-suspended-row">
<span className="stepper-suspended-icon">&#9888;</span>
<span className="stepper-suspended-label">
- {info
- ? `${formatToolApprovalLabel({
- displayName: info.displayName,
- toolName: info.toolName,
- })} requires approval`
- : 'Waiting for approval...'}
+ {canConnect
+ ? `Connect ${connectServer} to continue`
+ : info
+ ? `${formatToolApprovalLabel({
+ displayName: info.displayName,
+ toolName: info.toolName,
+ })} requires approval`
+ : 'Waiting for approval...'}
</span>
{onCancel && (
<IconButton
@@ -425,7 +450,25 @@ export function ProgressStepper({
</IconButton>
)}
</div>
- {info && (onApprove || onDeny) && (
+ {info && canConnect && (
+ <div className="stepper-approval-actions">
+ <Button
+ data-testid="connect-mcp-btn"
+ className="stepper-btn stepper-btn-approve"
+ color="success"
+ disabled={connectPending}
+ onClick={() => {
+ setConnectPending(true)
+ onConnect()
+ }}
+ size="sm"
+ variant="soft"
+ >
+ {connectPending ? 'Connecting...' : `Connect ${connectServer}`}
+ </Button>
+ </div>
+ )}
+ {info && !canConnect && (onApprove || onDeny) && (
<div className="stepper-approval-actions">
{onApprove && (
<Button
diff --git a/desktop-app/ui/src/components/__tests__/ProgressStepper.test.tsx b/desktop-app/ui/src/components/__tests__/ProgressStepper.test.tsx
index b1155d30c..580fbd80a 100644
--- a/desktop-app/ui/src/components/__tests__/ProgressStepper.test.tsx
+++ b/desktop-app/ui/src/components/__tests__/ProgressStepper.test.tsx
@@ -410,6 +410,95 @@ describe('ProgressStepper — suspended status (approval flow)', () => {
})
})
+describe('ProgressStepper — connect_required suspension (U5, T5 invariant c)', () => {
+ const connectProgress = () =>
+ makeProgress({
+ status: 'suspended',
+ suspendedInfo: {
+ requestId: 'req-1',
+ displayName: 'monday tool',
+ reason: 'connect_required',
+ mcpServerName: 'monday',
+ },
+ })
+
+ it('renders a "Connect <server>" prompt, NOT the generic approval prompt', () => {
+ render(<ProgressStepper progress={connectProgress()} onConnect={vi.fn()} />)
+ expect(screen.getByText('Connect monday to continue')).toBeDefined()
+ // The generic approval label / buttons must NOT appear for a connect suspension.
+ expect(screen.queryByText(/requires approval/)).toBeNull()
+ expect(screen.queryByTestId('approval-approve-btn')).toBeNull()
+ expect(screen.queryByTestId('approval-deny-btn')).toBeNull()
+ })
+
+ it('renders a Connect button that fires onConnect and shows "Connecting..." on click', () => {
+ const onConnect = vi.fn()
+ render(<ProgressStepper progress={connectProgress()} onConnect={onConnect} />)
+ const btn = screen.getByTestId('connect-mcp-btn')
+ expect(btn.textContent).toBe('Connect monday')
+ fireEvent.click(btn)
+ expect(onConnect).toHaveBeenCalledOnce()
+ expect(btn.textContent).toBe('Connecting...')
+ })
+
+ it('does NOT render Approve/Deny even when those callbacks are supplied (connect wins)', () => {
+ render(
+ <ProgressStepper
+ progress={connectProgress()}
+ onApprove={vi.fn()}
+ onDeny={vi.fn()}
+ onConnect={vi.fn()}
+ />
+ )
+ expect(screen.getByTestId('connect-mcp-btn')).toBeDefined()
+ expect(screen.queryByTestId('approval-approve-btn')).toBeNull()
+ expect(screen.queryByTestId('approval-deny-btn')).toBeNull()
+ })
+
+ it('a generic approval suspension still renders Approve/Deny (connect branch is scoped)', () => {
+ render(
+ <ProgressStepper
+ progress={makeProgress({
+ status: 'suspended',
+ suspendedInfo: { requestId: 'req-1', displayName: 'Tool X' },
+ })}
+ onApprove={vi.fn()}
+ onDeny={vi.fn()}
+ onConnect={vi.fn()}
+ />
+ )
+ expect(screen.getByTestId('approval-approve-btn')).toBeDefined()
+ expect(screen.queryByTestId('connect-mcp-btn')).toBeNull()
+ })
+
+ it('FIX2: connect_required WITHOUT an actionable onConnect falls back to Approve/Deny (no dead-end)', () => {
+ // Defensive: if mcpServerName were ever empty the caller leaves onConnect
+ // undefined — the block must still be actionable, never a suspended dead-end.
+ render(
+ <ProgressStepper
+ progress={makeProgress({
+ status: 'suspended',
+ suspendedInfo: {
+ requestId: 'req-1',
+ displayName: 'monday tool',
+ reason: 'connect_required',
+ mcpServerName: '',
+ },
+ })}
+ onApprove={vi.fn()}
+ onDeny={vi.fn()}
+ // onConnect intentionally omitted
+ />
+ )
+ // No Connect button (nothing to connect to), but Approve/Deny are present.
+ expect(screen.queryByTestId('connect-mcp-btn')).toBeNull()
+ expect(screen.getByTestId('approval-approve-btn')).toBeDefined()
+ expect(screen.getByTestId('approval-deny-btn')).toBeDefined()
+ // Falls back to the generic label, not a half-rendered connect prompt.
+ expect(screen.queryByText(/to continue$/)).toBeNull()
+ })
+})
+
describe('ProgressStepper — iteration dividers', () => {
it("shows 'Thinking further...' divider between different iterations after expanding", () => {
const steps = [
diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsx
index 53e8b595e..43bfd30ab 100644
--- a/desktop-app/ui/src/components/agents/ChatThread.tsx
+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx
@@ -462,6 +462,16 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {
: undefined
}
onCancel={canCancel ? () => onCancelTask!(taskId!) : undefined}
+ onConnect={
+ // U5: a connect_required suspension opens the provider OAuth flow,
+ // host-bound to this conversation's agent (hostRef ≡ selectedAgent).
+ // The deep-link completion resumes the task via the same approval RPC.
+ si?.reason === 'connect_required' && si.mcpServerName && selectedAgent
+ ? () => {
+ void window.clerum.rpc.connectMcpServer(si.mcpServerName!, selectedAgent)
+ }
+ : undefined
+ }
/>
)
},
diff --git a/desktop-app/ui/src/components/agents/InFlightAssistantPlaceholder.tsx b/desktop-app/ui/src/components/agents/InFlightAssistantPlaceholder.tsx
index 22b7f32e4..ad50939ca 100644
--- a/desktop-app/ui/src/components/agents/InFlightAssistantPlaceholder.tsx
+++ b/desktop-app/ui/src/components/agents/InFlightAssistantPlaceholder.tsx
@@ -20,7 +20,16 @@ interface Props {
* sticky `suspended` (V2) into the tracker. The tracker's own `pendingApproval`
* (live/replayed suspended) still wins when present.
*/
- pendingApproval?: { requestId: string; displayName: string }
+ pendingApproval?: {
+ requestId: string
+ displayName: string
+ // U5: carried through the FSM projection so the optimistic-paint fallback can
+ // also drive the "Connect <server>" prompt before the tracker's live
+ // suspended replays.
+ reason?: string
+ mcpServerName?: string
+ provider?: string
+ }
}
/**
@@ -100,6 +109,15 @@ export function InFlightAssistantPlaceholder({
: undefined
}
onCancel={onCancelTask ? () => onCancelTask(taskId) : undefined}
+ onConnect={
+ // U5: connect_required suspension → open the provider OAuth flow,
+ // host-bound to this conversation's agent (hostRef ≡ agentRef).
+ si?.reason === 'connect_required' && si.mcpServerName
+ ? () => {
+ void window.clerum.rpc.connectMcpServer(si.mcpServerName!, agentRef)
+ }
+ : undefined
+ }
/>
</div>
</section>
diff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts
index 466c69cb2..74b11e101 100644
--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts
+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/taskTracker.ts
@@ -589,6 +589,12 @@ export class TaskTracker implements AgentTaskTracker {
? {
requestId: sd.requestId,
displayName: sd.displayName || 'Unknown Tool',
+ // U5: preserved so downstream (stepper prompt, deep-link
+ // correlation) can distinguish a connect_required suspension and
+ // resume the right task. Undefined for ordinary approvals.
+ reason: sd.reason,
+ mcpServerName: sd.mcpServerName,
+ provider: sd.provider,
}
: undefined
})
diff --git a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts
index e8415b96f..aa0f97020 100644
--- a/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts
+++ b/desktop-app/ui/src/contexts/AgentTaskTrackerContext/types.ts
@@ -35,6 +35,13 @@ export interface TaskPendingApproval {
requestId: string
// P1-1: server-derived displayName only; the raw tool_name never crosses the wire.
displayName: string
+ // U5 (mcp-oauth reactive consent): `reason === 'connect_required'` marks an
+ // OAuth "Connect <server>" suspension (vs a generic tool approval);
+ // `mcpServerName`/`provider` identify the server and correlate the deep-link
+ // completion back to this task. Absent on ordinary approval suspensions.
+ reason?: string
+ mcpServerName?: string
+ provider?: string
}
/**
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/resolveConnectResumeTargets.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/resolveConnectResumeTargets.test.ts
new file mode 100644
index 000000000..39656b75e
--- /dev/null
+++ b/desktop-app/ui/src/hooks/domain/__tests__/resolveConnectResumeTargets.test.ts
@@ -0,0 +1,82 @@
+import { describe, expect, it } from 'vitest'
+import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'
+import type { PendingApprovalLite } from '../../../../../src/types'
+import { resolveConnectResumeTargets } from '../approvalDecision'
+import { createSessionFsmStore } from '../sessionFsm'
+
+/**
+ * T1: the FSM snapshot the correlation reads is DERIVED from the real
+ * `sessionFsmReducer` (via `createSessionFsmStore`), not hand-built — a
+ * `connect_required` suspension is fed through the exact `STREAM_SUSPENDED`
+ * transition the live tracker fires, so the entries have the real shape.
+ */
+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('resolveConnectResumeTargets — U5 deep-link correlation (T5, concurrency)', () => {
+ it('resumes ONLY the conversation whose mcpServerName matches, with 2 concurrent suspensions on different servers', () => {
+ const store = createSessionFsmStore()
+ suspend(store, 'agentA', 'chatA1', 'taskA', connectApproval('reqA', 'monday'))
+ suspend(store, 'agentB', 'chatB1', 'taskB', connectApproval('reqB', 'clickup'))
+
+ const targets = resolveConnectResumeTargets(store.getSnapshot(), 'monday')
+
+ expect(targets).toEqual([
+ {
+ agentRef: 'agentA',
+ chatId: 'chatA1',
+ taskId: 'taskA',
+ requestId: 'reqA',
+ decision: 'approve',
+ source: 'connect_completed',
+ },
+ ])
+ // The clickup suspension must be left untouched.
+ expect(targets.some(t => t.requestId === 'reqB')).toBe(false)
+ })
+
+ it('resumes EVERY conversation suspended on the same server (per-user grant is global)', () => {
+ const store = createSessionFsmStore()
+ suspend(store, 'agentA', 'chat1', 'task1', connectApproval('req1', 'monday'))
+ suspend(store, 'agentA', 'chat2', 'task2', connectApproval('req2', 'monday'))
+
+ const targets = resolveConnectResumeTargets(store.getSnapshot(), 'monday')
+
+ expect(targets).toHaveLength(2)
+ expect(new Set(targets.map(t => t.requestId))).toEqual(new Set(['req1', 'req2']))
+ expect(targets.every(t => t.decision === 'approve')).toBe(true)
+ })
+
+ it('never matches a generic (approval_required) suspension on the same chat model', () => {
+ const store = createSessionFsmStore()
+ // A plain tool approval — no reason / mcpServerName.
+ suspend(store, 'agentA', 'chatA1', 'taskA', {
+ requestId: 'reqA',
+ displayName: 'some tool',
+ })
+
+ expect(resolveConnectResumeTargets(store.getSnapshot(), 'monday')).toEqual([])
+ })
+
+ it('an empty / whitespace mcpServerName correlates to nothing (fail-closed)', () => {
+ const store = createSessionFsmStore()
+ suspend(store, 'agentA', 'chatA1', 'taskA', connectApproval('reqA', 'monday'))
+
+ expect(resolveConnectResumeTargets(store.getSnapshot(), '')).toEqual([])
+ expect(resolveConnectResumeTargets(store.getSnapshot(), ' ')).toEqual([])
+ })
+})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/sessionFsm.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/sessionFsm.test.ts
index 5bb1eff89..b931b9072 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/sessionFsm.test.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/sessionFsm.test.ts
@@ -200,6 +200,27 @@ describe('sessionFsmReducer — R3 approval notifications (GAP-N3 dedupe)', () =
})
expect(effects).toEqual([])
})
+
+ it('U5: a connect_required suspension flips the badge WITHOUT the generic approval notification', () => {
+ const { state, effects } = sessionFsmReducer(
+ stateWith({ phase: 'processing', activeTaskId: 't1' }),
+ {
+ type: 'STREAM_SUSPENDED',
+ taskId: 't1',
+ approval: {
+ requestId: 'req-1',
+ displayName: 'monday tool',
+ reason: 'connect_required',
+ mcpServerName: 'monday',
+ },
+ }
+ )
+ // Badge still moves to awaiting_approval (the connect completion resumes it via
+ // the same approval RPC) — but NO emit_approval_notification: a connect prompt
+ // is not a tool approval, and its decide-action would resume without a grant.
+ expect(state).toMatchObject({ phase: 'awaiting_approval' })
+ expect(effects).toEqual([])
+ })
})
describe('sessionFsmReducer — R3 decision optimism / revert / suppression', () => {
diff --git a/desktop-app/ui/src/hooks/domain/approvalDecision.ts b/desktop-app/ui/src/hooks/domain/approvalDecision.ts
index 9e0e841cf..1e7ffdb99 100644
--- a/desktop-app/ui/src/hooks/domain/approvalDecision.ts
+++ b/desktop-app/ui/src/hooks/domain/approvalDecision.ts
@@ -1,6 +1,6 @@
-import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'
+import { makeTaskKey, parseTaskKey } from '@contexts/AgentTaskTrackerContext'
import type { ApprovalDecisionResult } from '../../../../src/types'
-import type { SessionFsmStore } from './sessionFsm'
+import type { SessionFsmState, SessionFsmStore } from './sessionFsm'
/**
* Central approval-decision logic (spec-v2 §4.7.4). All four decision surfaces
@@ -50,7 +50,58 @@ export interface ApprovalDecisionTarget {
taskId: string
requestId: string
decision: 'approve' | 'deny'
- source: 'desktop_notification' | 'inapp_bell' | 'in_chat' | 'placeholder'
+ // `connect_completed` (U5): the OAuth deep-link returned for an mcp-server;
+ // the suspended task is resumed through the SAME approval RPC (mcp-host
+ // re-executes the tool with the freshly-minted grant). Always an approve.
+ source: 'desktop_notification' | 'inapp_bell' | 'in_chat' | 'placeholder' | 'connect_completed'
+}
+
+/**
+ * U5 (mcp-oauth reactive consent) — deep-link correlation.
+ *
+ * Given the FSM snapshot and the `mcpServerName` carried on the OAuth
+ * `oauth-completed?source=mcp` deep link, return the resume target for EVERY
+ * conversation currently suspended on that server. Correlating by `mcpServerName`
+ * (not client_id) is robust to 2+ concurrent suspensions:
+ * - suspensions on OTHER servers do not match and are left untouched;
+ * - a per-user grant is global to the user, so once the connect completes,
+ * every conversation waiting on that server can resume — this returns them all;
+ * - it reads only the FSM snapshot (the single source of truth already used by
+ * resume/reconcile), so no ephemeral client_id→conversation map is needed and
+ * it survives an app restart (the durable suspension re-seeds the snapshot).
+ *
+ * Pure and total: unit-testable without React. Always yields `decision:'approve'`
+ * — a connect completion only ever resumes.
+ */
+export function resolveConnectResumeTargets(
+ snapshot: Record<string, SessionFsmState>,
+ mcpServerName: string
+): ApprovalDecisionTarget[] {
+ const server = String(mcpServerName || '').trim()
+ if (!server) return []
+ const targets: ApprovalDecisionTarget[] = []
+ for (const [chatKey, entry] of Object.entries(snapshot)) {
+ const approval = entry.pendingApproval
+ if (
+ entry.phase !== 'awaiting_approval' ||
+ !approval ||
+ approval.reason !== 'connect_required' ||
+ approval.mcpServerName !== server ||
+ !entry.activeTaskId
+ ) {
+ continue
+ }
+ const { agentRef, chatId } = parseTaskKey(chatKey)
+ targets.push({
+ agentRef,
+ chatId,
+ taskId: entry.activeTaskId,
+ requestId: approval.requestId,
+ decision: 'approve',
+ source: 'connect_completed',
+ })
+ }
+ return targets
}
export interface DecideApprovalDeps {
diff --git a/desktop-app/ui/src/hooks/domain/sessionFsm.ts b/desktop-app/ui/src/hooks/domain/sessionFsm.ts
index 4f13030e5..2c1538612 100644
--- a/desktop-app/ui/src/hooks/domain/sessionFsm.ts
+++ b/desktop-app/ui/src/hooks/domain/sessionFsm.ts
@@ -221,7 +221,13 @@ export function sessionFsmReducer(
}
// GAP-N3: notify only on a genuine stream-driven transition, deduped by
// (taskId, requestId). A sticky re-emit or a repeat suspended is swallowed.
- if (!alreadyNotified) {
+ // U5: a `connect_required` suspension is NOT a tool approval — emitting the
+ // generic "approve" notification would let its decide-action resume the task
+ // WITHOUT a grant (401 → re-suspend loop). The in-chat "Connect <server>"
+ // prompt is its surface; the badge still flips to awaiting_approval below,
+ // and the connect completion resumes it via the same approval RPC.
+ const isConnectRequired = event.approval.reason === 'connect_required'
+ if (!alreadyNotified && !isConnectRequired) {
effects.push({
type: 'emit_approval_notification',
taskId: event.taskId,
diff --git a/desktop-app/ui/src/hooks/domain/trackerToProgress.ts b/desktop-app/ui/src/hooks/domain/trackerToProgress.ts
index 6a20fe2eb..6e19d50fd 100644
--- a/desktop-app/ui/src/hooks/domain/trackerToProgress.ts
+++ b/desktop-app/ui/src/hooks/domain/trackerToProgress.ts
@@ -36,6 +36,11 @@ export function trackerStateToTaskProgress(state: TaskState): TaskProgress {
? {
requestId: state.pendingApproval.requestId,
displayName: state.pendingApproval.displayName || 'Unknown Tool',
+ // U5: carried so the stepper renders "Connect <server>" for a
+ // connect_required suspension instead of the generic approval prompt.
+ reason: state.pendingApproval.reason,
+ mcpServerName: state.pendingApproval.mcpServerName,
+ provider: state.pendingApproval.provider,
}
: undefined,
cancelReason:
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index ba52de0b1..9e07a2386 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -24,6 +24,7 @@ import type {
import {
type ApprovalDecisionTarget,
decideApproval as decideApprovalCore,
+ resolveConnectResumeTargets,
} from './domain/approvalDecision'
import { desktopQueryKeys } from './domain/queryKeys'
import { useActivityController } from './domain/useActivityController'
@@ -53,6 +54,9 @@ const DENY_REASON_BY_SOURCE: Record<ApprovalDecisionTarget['source'], string> =
inapp_bell: 'Denied from notifications panel',
in_chat: 'User denied',
placeholder: 'User denied',
+ // U5: connect_completed is only ever an approve/resume — this deny reason is
+ // unreachable, present solely to satisfy the exhaustive source map.
+ connect_completed: 'User denied',
}
export async function loadWorkflowRunsWithArtifactsForWorkflowTarget(
@@ -307,6 +311,26 @@ export function useAppController() {
)
decideApprovalRef.current = decideApprovalImpl
+ // U5 (mcp-oauth reactive consent) — deep-link correlation + resume.
+ // When the OAuth "Connect <server>" flow completes, control-api bounces to
+ // `clerum://oauth-completed?…&source=mcp&mcpServerName=<X>`; main.ts forwards
+ // `{ mcpServerName }` here. Correlation is by `mcpServerName` against the FSM
+ // snapshot — the single source of truth already used by the resume/reconcile
+ // paths — so it is robust to concurrency (resumes EVERY conversation suspended
+ // 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.
+ useEffect(() => {
+ const unsub = window.clerum.rpc.onMcpOauthCompleted?.(({ mcpServerName }) => {
+ const targets = resolveConnectResumeTargets(chat.sessionFsmStore.getSnapshot(), mcpServerName)
+ for (const target of targets) {
+ void decideApprovalRef.current(target)
+ }
+ })
+ return () => unsub?.()
+ }, [chat.sessionFsmStore])
+
// ─── MCP Server ───
const mcpServer = useMcpServerController({
selectedAgent: nav.selectedAgent,
diff --git a/desktop-app/ui/src/uiTypes.ts b/desktop-app/ui/src/uiTypes.ts
index 0cc098064..ce23a9201 100644
--- a/desktop-app/ui/src/uiTypes.ts
+++ b/desktop-app/ui/src/uiTypes.ts
@@ -173,6 +173,12 @@ export interface SuspendedInfo {
/** Raw tool name (e.g. `clerum__plot_pnl`) — lets the approval label surface
* the function when the display name is generic. */
toolName?: string
+ /** U5 (mcp-oauth reactive consent): `'connect_required'` makes the stepper
+ * render a "Connect <server>" prompt instead of Approve/Deny. `mcpServerName`
+ * is the server to connect. Absent on ordinary approval suspensions. */
+ reason?: string
+ mcpServerName?: string
+ provider?: string
}
export interface TaskProgress {