Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): buffer cold-start OAuth completions until sessions seed (R3-M1)
Diego Zacariasc17683664252
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsxindex ff8667aa0..3bee9ebfa 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/appControllerHarness.tsx@@ -119,6 +119,13 @@ export interface AppControllerClerumHandle {switchTeam: FnrefreshCatalog: FnlistPending: Fn+ /** The `rpc.onMcpOauthCompleted` mock (U5 deep-link push registration). */+ onMcpOauthCompleted: Fn+ /**+ * Fire an OAuth-completed deep link to whatever listener the coordinator+ * registered via `rpc.onMcpOauthCompleted`. No-op if none is registered yet.+ */+ emitMcpOauthCompleted: (args: { mcpServerName: string; provider?: string }) => void/** Settles a dependency-health probe held by `delayHealth`. */resolveHealth: () => void/** Settles whatever `delayAuthenticatedLoad` is holding open. */@@ -179,11 +186,24 @@ export function extendMockClerumForAppController()const listPending = vi.fn(async () => (held() ? approvalsDeferred.promise : []))+ // U5: the OAuth deep-link push. Capture the coordinator's listener so a test+ // can fire a completion through the real registration path.+ let mcpOauthListener: ((args: { mcpServerName: string; provider: string }) => void) | null = null+ const onMcpOauthCompleted = vi.fn(+ (callback: (args: { mcpServerName: string; provider: string }) => void) => {+ mcpOauthListener = callback+ return () => {+ if (mcpOauthListener === callback) mcpOauthListener = null+ }+ }+ )+Object.assign(bridge.rpc as object, {listServers: vi.fn(async () => ({ servers: [] })),prewarmHost: vi.fn(async () => ({ status: 'ok' })),approveToolCall: vi.fn(async () => undefined),denyToolCall: vi.fn(async () => undefined),+ onMcpOauthCompleted,})Object.assign(bridge, {@@ -278,6 +298,10 @@ export function extendMockClerumForAppController(switchTeam,refreshCatalog,listPending,+ onMcpOauthCompleted,+ emitMcpOauthCompleted(args) {+ mcpOauthListener?.({ mcpServerName: args.mcpServerName, provider: args.provider ?? 'mcp' })+ },resolveHealth() {healthDeferred.resolve(createHealth())},diff --git a/desktop-app/ui/src/hooks/domain/__tests__/mcpOauthResumeBuffer.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/mcpOauthResumeBuffer.test.tsnew file mode 100644index 000000000..ab3f12137--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/mcpOauthResumeBuffer.test.ts@@ -0,0 +1,197 @@+import { describe, expect, it } from 'vitest'+import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'+import type { PendingApprovalLite } from '../../../../../src/types'+import { type ApprovalDecisionTarget, resolveConnectResumeTargets } from '../approvalDecision'+import { createMcpOauthResumeBuffer } from '../mcpOauthResumeBuffer'+import { createSessionFsmStore } from '../sessionFsm'++/**+ * U5/R3-M1 cold-start buffer. The snapshots the buffer re-evaluates are DERIVED+ * from the real `sessionFsmReducer` (via `createSessionFsmStore` + the exact+ * `STREAM_SUSPENDED` transition the live tracker fires) and read through the real+ * `resolveConnectResumeTargets` — never hand-built (T1). The buffer itself is a+ * pure TTL map, so `now` is passed explicitly instead of using timers.+ */++const connectApproval = (requestId: string, mcpServerName: string): PendingApprovalLite => ({+ requestId,+ displayName: `${mcpServerName} tool`,+ reason: 'connect_required',+ mcpServerName,+})++function suspendConnect(+ store: ReturnType<typeof createSessionFsmStore>,+ agentRef: string,+ chatId: string,+ taskId: string,+ requestId: string,+ mcpServerName: string+): void {+ store.dispatch(makeTaskKey(agentRef, chatId), {+ type: 'STREAM_SUSPENDED',+ taskId,+ approval: connectApproval(requestId, mcpServerName),+ })+}++/**+ * Mimic the real consequence of a resume: the central decider dispatches+ * `APPROVAL_DECIDED`, which moves the chat out of `awaiting_approval`, so it stops+ * resolving as a connect-resume target. This is the guard the buffer leans on for+ * idempotency instead of tracking fired requestIds itself.+ */+function resumeConnect(+ store: ReturnType<typeof createSessionFsmStore>,+ agentRef: string,+ chatId: string,+ taskId: string,+ requestId: string+): void {+ store.dispatch(makeTaskKey(agentRef, chatId), {+ type: 'APPROVAL_DECIDED',+ taskId,+ requestId,+ decision: 'approve',+ })+}++describe('createMcpOauthResumeBuffer', () => {+ const resolverFor = (store: ReturnType<typeof createSessionFsmStore>) => (server: string) =>+ resolveConnectResumeTargets(store.getSnapshot(), server)++ it('cold start: an entry buffered while empty resumes once the snapshot seeds', () => {+ const store = createSessionFsmStore()+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ const resolve = resolverFor(store)++ // Completion arrives before any session exists.+ buffer.add('monday', 1_000)+ expect(buffer.drain(100, resolve)).toEqual([]) // nothing to resume yet…+ expect(buffer.size()).toBe(1) // …but the entry is kept for a later snapshot.++ // The suspended session lands (real producer transition).+ suspendConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1', 'monday')++ const fired = buffer.drain(200, resolve)+ expect(fired).toEqual([+ {+ agentRef: 'agent-x',+ chatId: 'chat-1',+ taskId: 'task-1',+ requestId: 'req-1',+ decision: 'approve',+ source: 'connect_completed',+ },+ ])+ // Kept until its deadline (NOT removed on match) so later siblings resume too.+ expect(buffer.size()).toBe(1)+ // The real decider transition drops the resumed chat out of awaiting_approval…+ resumeConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1')+ // …so a later drain within the window re-fires nothing.+ expect(buffer.drain(300, resolve)).toEqual([])+ })++ it('anti-double: a resumed conversation is not fired twice (idempotent via the real APPROVAL_DECIDED transition, not by removing the entry)', () => {+ const store = createSessionFsmStore()+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ const resolve = resolverFor(store)++ suspendConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1', 'monday')+ buffer.add('monday', 1_000)++ expect(buffer.drain(100, resolve)).toHaveLength(1)+ // The central decider dispatches APPROVAL_DECIDED, moving the chat out of+ // awaiting_approval — so it stops resolving as a connect-resume target.+ resumeConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1')+ // The entry is still buffered (kept until deadline), but resolve() no longer+ // returns it → no second fire. Idempotency comes from the FSM guard, not from+ // removing the entry on first match (that would drop later siblings).+ expect(buffer.drain(200, resolve)).toEqual([])+ expect(buffer.size()).toBe(1) // TTL is the only removal path+ })++ it('TTL: an entry past its deadline is discarded WITHOUT firing, even if it would match', () => {+ const store = createSessionFsmStore()+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ const resolve = resolverFor(store)++ // A perfectly matchable suspension exists…+ suspendConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1', 'monday')+ buffer.add('monday', 1_000)++ // …but the drain happens after the deadline → dropped, no resume.+ expect(buffer.drain(1_001, resolve)).toEqual([])+ expect(buffer.size()).toBe(0)+ })++ it('a buffered entry with no matching server is kept until it expires', () => {+ const store = createSessionFsmStore()+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ const resolve = resolverFor(store)++ // Suspension on a DIFFERENT server.+ suspendConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1', 'clickup')+ buffer.add('monday', 1_000)++ expect(buffer.drain(100, resolve)).toEqual([])+ expect(buffer.size()).toBe(1) // still waiting for a monday suspension+ expect(buffer.drain(2_000, resolve)).toEqual([]) // now expired+ expect(buffer.size()).toBe(0)+ })++ it('resumes EVERY conversation on the server, INCLUDING a sibling seeded in a LATER drain (the real per-dispatch seam; per-user grant is global)', () => {+ const store = createSessionFsmStore()+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ const resolve = resolverFor(store)++ // First sibling seeded (one dispatch); completion buffered.+ suspendConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1', 'monday')+ buffer.add('monday', 1_000)++ const firstDrain = buffer.drain(100, resolve)+ expect(firstDrain.map(t => t.requestId)).toEqual(['req-1'])+ resumeConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1') // real transition++ // The SECOND sibling on the SAME server surfaces in a LATER dispatch/drain —+ // exactly how seedSessionSnapshots emits (one session per notify). A helper+ // that removed the entry on the first match would have dropped it here and+ // this sibling would NEVER resume (this is the R3-M1 review Should-fix).+ suspendConnect(store, 'agent-x', 'chat-2', 'task-2', 'req-2', 'monday')+ const secondDrain = buffer.drain(200, resolve)+ expect(secondDrain.map(t => t.requestId)).toEqual(['req-2'])+ expect(secondDrain.every(t => t.decision === 'approve')).toBe(true)++ expect(buffer.size()).toBe(1) // still kept until its deadline+ })++ it('a blank / whitespace server name is never buffered (fail-closed)', () => {+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ buffer.add('', 1_000)+ buffer.add(' ', 1_000)+ expect(buffer.size()).toBe(0)+ })++ it('drain is a no-op when nothing is buffered (normal path never re-fires)', () => {+ const store = createSessionFsmStore()+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ // Normal path: the completion resolved immediately so nothing was buffered.+ suspendConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1', 'monday')+ expect(buffer.size()).toBe(0)+ expect(buffer.drain(100, resolverFor(store))).toEqual([])+ })++ it('re-buffering the same server refreshes the deadline (last write wins)', () => {+ const store = createSessionFsmStore()+ const buffer = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ const resolve = resolverFor(store)++ buffer.add('monday', 500)+ buffer.add('monday', 5_000) // a repeat completion pushes the deadline out+ expect(buffer.size()).toBe(1)++ suspendConnect(store, 'agent-x', 'chat-1', 'task-1', 'req-1', 'monday')+ // Past the FIRST deadline but within the refreshed one → still resumes.+ expect(buffer.drain(1_000, resolve)).toHaveLength(1)+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/mcpOauthResumeColdStart.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/mcpOauthResumeColdStart.test.tsxnew file mode 100644index 000000000..59dc645a9--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/mcpOauthResumeColdStart.test.tsx@@ -0,0 +1,205 @@+// @vitest-environment jsdom+/**+ * R3-M1 regression — mcp-oauth reactive consent, COLD START.+ *+ * The OAuth "Connect <server>" deep link can return BEFORE the per-chat FSM+ * snapshot is seeded (sessions load async/auth-gated after `rendererReady`). The+ * pre-fix reactive handler resolved the resume targets against the snapshot AS IT+ * WAS when the completion arrived; on a cold start that snapshot is empty, so the+ * completion was dropped and the suspended conversation never auto-resumed (only+ * a second manual click recovered it — the grant already existed).+ *+ * The fix buffers a completion that finds no targets and re-evaluates it when the+ * FSM snapshot next changes (bounded TTL). This test drives the REAL coordinator:+ * the suspended session is seeded through the real `listSessions` → chat-list+ * loader → `seedSessionSnapshots` producer path (T1 — not a hand-built snapshot),+ * and the observable is the real approval RPC the central decider fires (T4).+ *+ * Against the parent commit (no buffer) the completion is dropped, so seeding the+ * session later produces NO resume and `approveToolCall` is never called — the+ * `waitFor` on it fails.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, waitFor } from '@testing-library/react'+import type { SessionsListResult } from '../../../../../src/types'+import {+ extendMockClerumForAppController,+ renderAppController,+} from './__fixtures__/appControllerHarness'+import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++let clerum: MockClerum++beforeEach(() => {+ // jsdom has no real audio pipeline; the notifications controller calls+ // `HTMLAudioElement.play()` (which returns undefined in jsdom and then throws+ // on `.catch`). Stub it so an unrelated notification never crashes the mount.+ vi.spyOn(window.HTMLMediaElement.prototype, 'play').mockImplementation(async () => undefined)+ clerum = installMockClerum()+})++afterEach(() => {+ vi.restoreAllMocks()+ vi.useRealTimers()+ uninstallMockClerum()+})++/** Contention headroom: the default 1s can expire on a cold/loaded machine. */+const SLOW = { timeout: 5000 } as const++/**+ * Drains micro + macro tasks inside `act`, so a "did not happen yet" negative is+ * made after everything that could have run has run.+ */+async function settle() {+ await act(async () => {+ await Promise.resolve()+ await new Promise(resolve => setTimeout(resolve, 0))+ })+}++/** A single session suspended on `monday` awaiting the OAuth connect grant. */+const SUSPENDED_ON_MONDAY: SessionsListResult = {+ items: [+ {+ agent: 'agent-x',+ chatId: 'chat-connect',+ turnCount: 1,+ lastActivityAt: '2026-05-03T00:00:00Z',+ state: 'awaiting_approval',+ activeTaskId: 'task-connect',+ pendingApproval: {+ requestId: 'req-connect',+ displayName: 'monday tool',+ reason: 'connect_required',+ mcpServerName: 'monday',+ },+ },+ ],+}++const CONNECT_KEY = 'agent-x::chat-connect'+const resumeCalls = (approveToolCall: ReturnType<typeof vi.fn>) =>+ approveToolCall.mock.calls.filter(call => call[2] === 'req-connect')++describe('mcp-oauth reactive consent — cold start (R3-M1)', () => {+ let unmountApp: (() => void) | null = null++ afterEach(() => {+ unmountApp?.()+ unmountApp = null+ })++ it('resumes a suspended conversation when the completion arrives before the snapshot is seeded', async () => {+ // Cold start: the session catalog load is STILL IN FLIGHT — `listSessions`+ // is a pending promise the test releases by hand — so the FSM snapshot is+ // empty when the completion arrives, exactly as on a real cold boot.+ let releaseSessions!: (result: SessionsListResult) => void+ const sessionsInFlight = new Promise<SessionsListResult>(resolve => {+ releaseSessions = resolve+ })+ clerum.rpc.listSessions.mockReturnValue(sessionsInFlight)+ const handle = extendMockClerumForAppController(clerum, { agentNames: ['agent-x'] })+ // `approveToolCall` is added to the rpc bridge by `extendMockClerumForAppController`,+ // so it isn't on the base `RpcMock` type — reach it through a cast.+ const approveToolCall = (clerum.rpc as unknown as { approveToolCall: ReturnType<typeof vi.fn> })+ .approveToolCall++ const app = renderAppController()+ unmountApp = app.unmount++ await waitFor(() => expect(app.result.current.booting).toBe(false), SLOW)+ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true), SLOW)+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false), SLOW)+ // The reactive handler must be wired, and the session load must have started+ // (and be blocked), before the completion arrives.+ await waitFor(() => expect(handle.onMcpOauthCompleted).toHaveBeenCalled(), SLOW)+ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled(), SLOW)+ // Cold start: the snapshot really is empty when the completion arrives.+ expect(app.result.current.sessionStateByChatKey[CONNECT_KEY]).toBeUndefined()++ // The OAuth deep link returns while the FSM snapshot is still empty.+ act(() => {+ handle.emitMcpOauthCompleted({ mcpServerName: 'monday' })+ })+ await settle()++ // Pre-fix: dropped. Post-fix: buffered, not yet resumed (no session exists).+ expect(approveToolCall).not.toHaveBeenCalled()++ // The in-flight session load now settles with the suspended session — seeded+ // into the store through the real `seedSessionSnapshots` producer path.+ await act(async () => {+ releaseSessions(SUSPENDED_ON_MONDAY)+ await sessionsInFlight+ })++ // The buffered completion re-evaluates on the new snapshot and resumes through+ // the central decider → the approval RPC re-executes the tool. This is the+ // assertion that FAILS against the parent (the resume was lost on cold start).+ await waitFor(+ () =>+ expect(approveToolCall).toHaveBeenCalledWith(+ 'agent-x',+ 'task-connect',+ 'req-connect',+ ['agent-x'],+ { teamId: undefined }+ ),+ SLOW+ )+ // Fired exactly once for the single suspended conversation.+ expect(resumeCalls(approveToolCall)).toHaveLength(1)+ })++ it('does not enter the buffer on the normal path and never double-resumes', async () => {+ // Session is already seeded before the completion arrives (warm path).+ clerum.rpc.listSessions.mockResolvedValue(SUSPENDED_ON_MONDAY)+ const handle = extendMockClerumForAppController(clerum, { agentNames: ['agent-x'] })+ // `approveToolCall` is added to the rpc bridge by `extendMockClerumForAppController`,+ // so it isn't on the base `RpcMock` type — reach it through a cast.+ const approveToolCall = (clerum.rpc as unknown as { approveToolCall: ReturnType<typeof vi.fn> })+ .approveToolCall++ const app = renderAppController()+ unmountApp = app.unmount++ await waitFor(() => expect(app.result.current.booting).toBe(false), SLOW)+ await waitFor(() => expect(app.result.current.isAuthenticated).toBe(true), SLOW)+ await waitFor(() => expect(app.result.current.initialExperienceLoading).toBe(false), SLOW)+ await waitFor(() => expect(handle.onMcpOauthCompleted).toHaveBeenCalled(), SLOW)++ // Boot auto-selected agent-x and seeded the suspended session already.+ await waitFor(+ () =>+ expect(+ app.result.current.sessionStateByChatKey[CONNECT_KEY]?.pendingApproval?.requestId+ ).toBe('req-connect'),+ SLOW+ )++ // Completion arrives with the snapshot already seeded → immediate resume.+ act(() => {+ handle.emitMcpOauthCompleted({ mcpServerName: 'monday' })+ })+ await waitFor(+ () =>+ expect(approveToolCall).toHaveBeenCalledWith(+ 'agent-x',+ 'task-connect',+ 'req-connect',+ ['agent-x'],+ { teamId: undefined }+ ),+ SLOW+ )++ // The optimistic APPROVAL_DECIDED transition is itself a store change; the+ // subscribe fires again with an EMPTY buffer, so nothing re-resumes. Draining+ // everything confirms the warm path left no buffered entry behind.+ await settle()+ expect(resumeCalls(approveToolCall)).toHaveLength(1)+ })+})diff --git a/desktop-app/ui/src/hooks/domain/mcpOauthResumeBuffer.ts b/desktop-app/ui/src/hooks/domain/mcpOauthResumeBuffer.tsnew file mode 100644index 000000000..5551daeb5--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/mcpOauthResumeBuffer.ts@@ -0,0 +1,92 @@+/**+ * U5 (mcp-oauth reactive consent) — cold-start buffer for OAuth completions.+ *+ * The OAuth "Connect <server>" deep link (`clerum://oauth-completed?…&source=mcp+ * &mcpServerName=<X>`) can arrive BEFORE the per-chat FSM snapshot has been+ * seeded — sessions load async/auth-gated after `rendererReady`, so on a cold+ * start `resolveConnectResumeTargets(getSnapshot(), X)` returns `[]` even though+ * the grant now exists and a conversation is suspended on that server. Dropping+ * the completion there loses the auto-resume (recoverable only by a second user+ * click).+ *+ * This is a bounded buffer-and-retry, NOT a decision module: no precedence,+ * merge, ordering or conflict resolution. A completion that found no targets is+ * kept (keyed by `mcpServerName`, with a wall-clock deadline). It stays buffered+ * until its deadline — it is NOT removed on the first match — because the real+ * cold-start seam (`seedSessionSnapshots`) dispatches ONE session per snapshot+ * (one store notification each), so sibling conversations suspended on the SAME+ * server surface across SEPARATE drains. Removing the entry on the first match+ * would resume only the sessions already seeded at that instant and silently drop+ * the later siblings — breaking the titular guarantee that a per-user grant+ * resumes EVERY conversation waiting on that server. Instead, every drain within+ * the window re-evaluates `resolve(server)` and fires whatever it returns.+ *+ * Idempotency is delegated to the caller, not re-implemented here (which would+ * drift toward a decision module): a conversation that has been resumed leaves+ * `awaiting_approval` (its FSM entry moves to `processing`), so it stops being a+ * target on the next `resolve` — each sibling fires once as a natural+ * consequence. Even a redundant re-fire is a guarded no-op: `decideApproval`+ * step 1 short-circuits an already-decided request client-side, and mcp-host is+ * idempotent per `requestId` server-side. Stale entries are discarded on the+ * first drain past their deadline — no timer, no zombie resume, no unbounded+ * growth (bounded by the number of distinct servers).+ *+ * Pure and store-agnostic: the caller injects a `resolve(server) => targets`+ * closure at drain time (which reads the live snapshot), so this is exhaustively+ * unit-testable without React or a store.+ */+export interface McpOauthResumeBuffer<T> {+ /**+ * Buffer a completion whose resume had no targets yet. Re-buffering the same+ * server refreshes its deadline (last write wins — a repeat completion is not+ * a second pending resume). A blank server name is ignored (fail-closed).+ */+ add(mcpServerName: string, deadline: number): void+ /**+ * Re-evaluate every buffered completion against the current snapshot.+ * - An entry whose deadline has passed (`now > deadline`) is dropped (the ONLY+ * removal path, besides an `add` that refreshes the deadline).+ * - Every live entry fires whatever `resolve(server)` returns — nothing is+ * removed on a match, so siblings on the same server that appear in LATER+ * drains (the real per-dispatch seam) still resume within the window.+ * Returns the flattened targets to fire, in buffer-insertion order. A resumed+ * conversation drops out of `resolve` on its own, so each sibling fires once;+ * any redundant re-fire is a guarded no-op (see the module docstring).+ */+ drain(now: number, resolve: (mcpServerName: string) => T[]): T[]+ /** Number of completions still pending (0 ⇒ drain is a no-op). */+ size(): number+}++export function createMcpOauthResumeBuffer<T>(): McpOauthResumeBuffer<T> {+ // server name -> deadline (epoch ms). Map keeps insertion order for a stable+ // drain order across concurrent pending completions.+ const pending = new Map<string, number>()++ return {+ add(mcpServerName, deadline) {+ const server = String(mcpServerName || '').trim()+ if (!server) return+ pending.set(server, deadline)+ },+ drain(now, resolve) {+ if (pending.size === 0) return []+ const fired: T[] = []+ for (const [server, deadline] of pending) {+ if (now > deadline) {+ // TTL is the only removal path: a stale grant must not drive a resume+ // long after the window.+ pending.delete(server)+ continue+ }+ // Kept alive until the deadline — re-fire whatever resolves NOW so a+ // sibling seeded in a later dispatch is still resumed.+ fired.push(...resolve(server))+ }+ return fired+ },+ size() {+ return pending.size+ },+ }+}diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 307b8903b..effebb514 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -26,6 +26,7 @@ import {decideApproval as decideApprovalCore,resolveConnectResumeTargets,} from './domain/approvalDecision'+import { createMcpOauthResumeBuffer } from './domain/mcpOauthResumeBuffer'import { desktopQueryKeys } from './domain/queryKeys'import { useActivityController } from './domain/useActivityController'import { useAgentChatController } from './domain/useAgentChatController'@@ -49,6 +50,13 @@ import {} from './domain/useWorkflowController.types'import { scheduleAfterFirstPaint } from './scheduleAfterFirstPaint'+// U5 cold-start buffer: how long an OAuth completion whose sessions are not yet+// seeded is retried against later snapshots before it is discarded. Long enough+// to cover the async/auth-gated session load after `rendererReady`, short enough+// that a stale grant can never drive a much-later resume. RPC token TTL is 300s;+// this stays well under it.+const MCP_OAUTH_RESUME_BUFFER_TTL_MS = 45_000+const DENY_REASON_BY_SOURCE: Record<ApprovalDecisionTarget['source'], string> = {desktop_notification: 'Denied from desktop notification',inapp_bell: 'Denied from notifications panel',@@ -206,6 +214,15 @@ export function useAppController() {(target: ApprovalDecisionTarget) => decideApprovalRef.current(target),[])+ // U5/R3-M1: buffers OAuth completions that arrive before their sessions are+ // seeded (cold start), retried on later FSM snapshots. Lazy-init the ref (the+ // factory must not re-run every render — same pattern as the FSM store).+ const mcpOauthResumeBufferRef = useRef<ReturnType<+ typeof createMcpOauthResumeBuffer<ApprovalDecisionTarget>+ > | null>(null)+ if (!mcpOauthResumeBufferRef.current) {+ mcpOauthResumeBufferRef.current = createMcpOauthResumeBuffer<ApprovalDecisionTarget>()+ }const openAgentConversationFromNotification = useCallback((target: AgentConversationNotificationTarget) =>openAgentConversationFromNotificationRef.current(target),@@ -320,15 +337,52 @@ 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.+ //+ // 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.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 }) => {- const targets = resolveConnectResumeTargets(chat.sessionFsmStore.getSnapshot(), mcpServerName)- for (const target of targets) {- void decideApprovalRef.current(target)+ const targets = resolveConnectResumeTargets(store.getSnapshot(), mcpServerName)+ if (targets.length > 0) {+ fire(targets)+ return}+ // 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)})- return () => unsub?.()++ const unsubStore = store.subscribe(() => {+ if (buffer.size() === 0) return+ fire(+ buffer.drain(Date.now(), server => resolveConnectResumeTargets(store.getSnapshot(), server))+ )+ })++ return () => {+ unsub?.()+ unsubStore()+ }}, [chat.sessionFsmStore])// ─── MCP Server ───