Skip to content

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

TypeScript
68.1 KB
Raw Blame
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type {
  AccessCatalog,
  PendingWorkflowApproval,
  WorkflowApprovalDecisionResult,
  WorkflowRecipeListResult,
  WorkflowRecipeResource,
  WorkflowRunsResult,
} from '../../../src/types'
import { AGENT_WORKSPACE_ROUTES, DESKTOP_ROUTES } from '../constants/navigation'
import { pickLatestAgent } from '../lib/agents'
import { toPrettyJson } from '../lib/format'
import {
  type HostAuthorityHoldKind,
  type HostAuthorityStore,
  createHostAuthorityStore,
} from '../lib/hostAuthorityStore'
import { selectUnauthenticatedView } from '../lib/unauthenticatedView'
import { summarizeWorkflowResource } from '../lib/workflows'
import type {
  AgentApprovalNotificationTarget,
  AgentConversationNotificationTarget,
  AgentWorkspaceRoute,
  AppNotification,
  NavItem,
  Tone,
  WorkflowCompletionNotificationTarget,
} from '../uiTypes'
import {
  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'
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'
import { useMcpServerController } from './domain/useMcpServerController'
import { useMcpServersDataController } from './domain/useMcpServersDataController'
import { useNavigationController } from './domain/useNavigationController'
import { useNotificationSettingsController } from './domain/useNotificationSettingsController'
import { useNotificationsController } from './domain/useNotificationsController'
import { useOnboardingController } from './domain/useOnboardingController'
import { useTeamsDataController } from './domain/useTeamsDataController'
import { useToastController } from './domain/useToastController'
import {
  EMPTY_WORKFLOW_SELECTION,
  type WorkflowSelectionState,
  createResetWorkflowSelection,
} from './domain/useWorkflowController.types'
import { scheduleAfterFirstPaint } from './scheduleAfterFirstPaint'
import { useChatStore } from './useChatStore'

// 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',
  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(
  target: Pick<WorkflowCompletionNotificationTarget, 'namespace' | 'name'>
): Promise<WorkflowRunsResult> {
  const raw = (await window.clerum.workflows.runs(
    target.namespace,
    target.name,
    20
  )) as WorkflowRunsResult
  const rows = Array.isArray(raw?.items) ? raw.items : []
  const items = await Promise.all(
    rows.map(async run => {
      if (!run.executionRef) return run
      try {
        const artifacts = await window.clerum.workflows.listRunArtifacts(
          target.namespace,
          target.name,
          run.id
        )
        return { ...run, artifacts: artifacts.artifacts ?? [] }
      } catch {
        return { ...run, artifacts: [] }
      }
    })
  )
  return {
    ...raw,
    items,
    count: typeof raw?.count === 'number' ? raw.count : items.length,
  }
}

export async function loadWorkflowRunsWithArtifactsForApprovalRefresh(
  approval: Pick<PendingWorkflowApproval, 'recipeNamespace' | 'recipeName'>
): Promise<WorkflowRunsResult> {
  return loadWorkflowRunsWithArtifactsForWorkflowTarget({
    namespace: approval.recipeNamespace,
    name: approval.recipeName,
  })
}

interface SessionIdentityRef {
  current: string | null
}

export function scheduleAfterFirstPaintForSession(
  sessionIdentityRef: SessionIdentityRef,
  expectedIdentity: string,
  task: () => Promise<unknown>
): void {
  scheduleAfterFirstPaint(async () => {
    if (sessionIdentityRef.current !== expectedIdentity) return
    await task()
  })
}

export function useAppController() {
  const queryClient = useQueryClient()

  // ─── Toast ───
  const toastCtrl = useToastController()
  const { toasts, pushToast } = toastCtrl

  // ─── Global status state (owned by coordinator, not auth) ───
  const [statusText, setStatusText] = useState('Ready.')
  const [statusTone, setStatusTone] = useState<Tone>('info')
  const [postPaintDataReady, setPostPaintDataReady] = useState(false)

  // Build fullSetStatus using refs to avoid circular dependencies
  const setStatusTextRef = useRef(setStatusText)
  setStatusTextRef.current = setStatusText
  const setStatusToneRef = useRef(setStatusTone)
  setStatusToneRef.current = setStatusTone
  const pushToastRef = useRef(pushToast)
  pushToastRef.current = pushToast

  const fullSetStatus = useCallback(
    (
      message: string,
      tone: Tone = 'info',
      payload?: unknown,
      options: { global?: boolean; toast?: boolean; toastDurationMs?: number } = {}
    ) => {
      const { global: updateGlobal = true, toast = true } = options
      if (updateGlobal) {
        setStatusTextRef.current(payload ? `${message}\n${toPrettyJson(payload)}` : message)
        setStatusToneRef.current(tone)
      }
      if (toast) pushToastRef.current(message, tone, { durationMs: options.toastDurationMs })
    },
    []
  )

  // ─── Navigation ───
  const nav = useNavigationController()

  // Use a ref so the stable onSessionNeedsLoad callback can call the real loadSession
  // without creating a circular dependency (loadSession is defined after auth+session).
  const loadSessionRef = useRef(async (_options?: { preserveNav?: boolean }) => {})
  const activeAuthenticatedSessionIdentityRef = useRef<string | null>(null)
  const authenticatedSessionIdentityRef = useRef<string | null>(null)
  const catalogRefreshPromiseRef = useRef<Promise<AccessCatalog> | null>(null)

  const onSessionNeedsLoad = useCallback(async (options?: { preserveNav?: boolean }) => {
    return loadSessionRef.current(options)
  }, [])
  const logoutForEnvironmentMismatchRef = useRef<() => Promise<number | null>>(async () => null)
  const logoutForEnvironmentMismatch = useCallback(
    () => logoutForEnvironmentMismatchRef.current(),
    []
  )

  // ─── Auth ───
  const auth = useAuthController({
    setStatus: fullSetStatus,
    onSessionNeedsLoad,
    logoutForEnvironmentMismatch,
  })

  // ─── First-run onboarding ───
  const onboarding = useOnboardingController()
  // Onboarding owns the unauthenticated screen only while the app has no
  // environment at all. Saving one — or selecting Localhost —
  // flips `configured`, which retires the wizard; deleting the last one brings
  // it back rather than leaving a sign-in form with nothing to sign in to.
  const unauthenticatedView = selectUnauthenticatedView({
    hasDependencyOutage: auth.hasDependencyOutage,
    runtimeConfigMissing: auth.runtimeConfigMissing,
    isAuthenticated: auth.isAuthenticated,
  })
  // The controller is app-level, so wizard state outlives the wizard itself.
  // Once an environment exists the run is finished: rewind to Q1, so deleting
  // that environment later reopens onboarding at the first question instead of
  // the step of a path the user already left.
  const resetOnboarding = onboarding.reset
  useEffect(() => {
    if (!auth.runtimeConfigMissing) resetOnboarding()
  }, [auth.runtimeConfigMissing, resetOnboarding])

  // ─── First-screen data contexts ───
  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()
  // The authenticated principal's own team: the ONE place `me.teamId` is read.
  // The chat-list cache scope (`currentTeamId`) may fall back to the display
  // directory when it is empty; the delete fence (`chatAuthorityTeamId`) never
  // does, because a directory team was never proven to be the session's.
  const principalTeamId = auth.me?.teamId ?? ''
  const currentTeamId = principalTeamId || teamsData.currentTeamId || ''
  const availableTeamIds = useMemo(() => teamsData.teams.map(team => team.id), [teamsData.teams])
  const authenticatedPrincipalIdentity =
    auth.isAuthenticated && auth.me
      ? `${auth.me.id}:${String(auth.me.email || '')
          .trim()
          .toLowerCase()}`
      : null
  const currentTeamName =
    teamsData.teams.find(team => team.id === currentTeamId)?.name || auth.me?.teamName || ''
  const currentTeamIdRef = useRef(currentTeamId)
  currentTeamIdRef.current = currentTeamId
  const notificationTeamContextQueueRef = useRef<Promise<void>>(Promise.resolve())
  const openAgentConversationFromNotificationRef = useRef<
    (target: AgentConversationNotificationTarget) => Promise<void>
  >(async () => {})
  const decideApprovalFromNotificationRef = useRef<
    (target: AgentApprovalNotificationTarget) => Promise<void>
  >(async () => {})
  // §4.7.4: the central approval-decision function is built AFTER the chat
  // controller (it needs its FSM store), but the in-app bell handlers live in
  // `useNotificationsController` (created earlier). This ref bridges the order so
  // all four surfaces funnel through the same `decideApproval`.
  const decideApprovalRef = useRef<(target: ApprovalDecisionTarget) => Promise<void>>(
    async () => {}
  )
  const decideApproval = useCallback(
    (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),
    []
  )
  const decideApprovalFromNotification = useCallback(
    (target: AgentApprovalNotificationTarget) => decideApprovalFromNotificationRef.current(target),
    []
  )

  const refreshWorkflowRunsAfterApprovalDecision = useCallback(
    async ({
      approval,
      result,
    }: {
      approval: PendingWorkflowApproval
      result: WorkflowApprovalDecisionResult
    }) => {
      if (!result.run) return
      const key = desktopQueryKeys.workflowRuns(approval.recipeNamespace, approval.recipeName, 20)
      try {
        const enriched = await loadWorkflowRunsWithArtifactsForApprovalRefresh(approval)
        queryClient.setQueryData<WorkflowRunsResult>(key, enriched)
      } catch {
        void queryClient.invalidateQueries({ queryKey: key })
      }
    },
    [queryClient]
  )

  // ─── Notifications ───
  const notificationSettings = useNotificationSettingsController()
  const channelNotificationPreferences = useChannelNotificationPreferencesController({
    isAuthenticated: auth.isAuthenticated,
    pushToast,
  })
  const notif = useNotificationsController({
    isAuthenticated: auth.isAuthenticated,
    notificationSoundVolume: notificationSettings.settings.soundVolume,
    canDeliverChatResponseNotification: notificationSettings.canDeliverChatResponseNotification,
    showDesktopNotification: notificationSettings.showDesktopNotification,
    onWorkflowApprovalDecision: refreshWorkflowRunsAfterApprovalDecision,
    decideApproval,
    pushToast,
    setStatus: fullSetStatus,
  })

  // ─── Agent Chat ───
  // Human-visible agent name (spec.host display name) for chat notification
  // titles. Total over catalog agents at the producer; the identifier is the
  // sanctioned fallback (Decision #6).
  const agentDisplayName = useCallback(
    (agentName: string) => agentsData.agentDisplayByName[agentName] ?? agentName,
    [agentsData.agentDisplayByName]
  )
  const authorityScope = `${auth.runtimeConfigState?.envKey ?? ''}:${auth.isAuthenticated}:${authenticatedPrincipalIdentity ?? ''}:${currentTeamId}`
  const authorityScopeRef = useRef(authorityScope)
  authorityScopeRef.current = authorityScope
  const navigationIntentEpochRef = useRef(0)
  // Lazy-init: the factory must run once per mount, like the FSM store.
  const hostAuthorityRef = useRef<HostAuthorityStore | null>(null)
  if (!hostAuthorityRef.current) hostAuthorityRef.current = createHostAuthorityStore()
  const hostAuthority = hostAuthorityRef.current
  const [hostAuthorityRevision, setHostAuthorityRevision] = useState(0)
  const selectedAgentRef = useRef(nav.selectedAgent)
  selectedAgentRef.current = nav.selectedAgent
  const isHostAccessBlocked = useCallback(
    (agentRef: string) => hostAuthority.isBlocked(agentRef),
    [hostAuthority]
  )
  const getHostAuthorityEpoch = useCallback(
    (agentRef: string) => hostAuthority.getEpoch(agentRef),
    [hostAuthority]
  )
  useEffect(() => {
    hostAuthority.reset()
    setHostAuthorityRevision(revision => revision + 1)
  }, [authorityScope, hostAuthority])
  const { invalidateSessionCatalog } = useChatStore()
  const blockHostAccess = useCallback(
    (agentRef: string, kind: HostAuthorityHoldKind) => {
      // F4: a catalog request issued before the hold must not be shared with a
      // reader that starts after `verifyHostAccess` releases it.
      invalidateSessionCatalog(agentRef)
      if (!hostAuthority.hold(agentRef, kind)) return
      setHostAuthorityRevision(revision => revision + 1)
      if (selectedAgentRef.current === agentRef) nav.setSelectedAgent(null)
      void agentsData.refresh()
    },
    [agentsData.refresh, hostAuthority, invalidateSessionCatalog, nav.setSelectedAgent]
  )
  const onHostAccessRevoked = useCallback(
    (agentRef: string) => blockHostAccess(agentRef, 'revoked'),
    [blockHostAccess]
  )
  const onHostAuthorityUncertain = useCallback(
    (agentRef: string) => blockHostAccess(agentRef, 'uncertain'),
    [blockHostAccess]
  )
  const verifyHostAccess = useCallback(
    async (agentRef: string): Promise<boolean> => {
      const heldAtEpoch = hostAuthority.heldAtEpoch(agentRef)
      if (heldAtEpoch === undefined) return true
      const scope = authorityScopeRef.current
      try {
        await window.clerum.rpc.listSessions(agentRef, undefined, { agent: agentRef, limit: 1 })
      } catch {
        return false
      }
      if (authorityScopeRef.current !== scope || !hostAuthority.release(agentRef, heldAtEpoch))
        return false
      setHostAuthorityRevision(revision => revision + 1)
      return true
    },
    [hostAuthority]
  )
  const chat = useAgentChatController({
    selectedAgent: nav.selectedAgent,
    agentNames: agentsData.agentNames,
    currentUserId: auth.me?.id,
    currentTeamId,
    currentEnvironmentKey: auth.runtimeConfigState?.envKey ?? '',
    currentTeamName,
    isAuthenticated: auth.isAuthenticated,
    loadMenuData: postPaintDataReady,
    navItem: nav.navItem,
    pushToast,
    pushNotification: notif.pushNotification,
    agentDisplayName,
    canDeliverChatResponseNotification: notificationSettings.canDeliverChatResponseNotification,
    showDesktopNotification: notificationSettings.showDesktopNotification,
    openAgentConversationFromNotification,
    decideApprovalFromNotification,
    onHostAccessRevoked,
    onHostAuthorityUncertain,
    isHostAccessBlocked,
    getHostAuthorityEpoch,
    hostAuthorityRevision,
    chatAuthorityTeamId: principalTeamId,
  })

  // §4.7.4: the ONE central approval-decision function, bound to the chat
  // controller's FSM store. All four surfaces (desktop notification, in-app bell,
  // in-chat gate, in-flight placeholder) funnel through it so the badge converges
  // the same way from every entry point (closes V8/GAP-N1). Reconcile routes
  // through the single-flight `chat.reconcileChat` gate (§4.3, wired below).
  const decideApprovalImpl = useCallback(
    (target: ApprovalDecisionTarget) =>
      decideApprovalCore(
        {
          fsm: chat.sessionFsmStore,
          approve: t =>
            window.clerum.rpc.approveToolCall(t.agentRef, t.taskId, t.requestId, [t.agentRef], {
              teamId: t.teamId ?? undefined,
            }),
          deny: t =>
            window.clerum.rpc.denyToolCall(
              t.agentRef,
              t.taskId,
              t.requestId,
              DENY_REASON_BY_SOURCE[t.source],
              [t.agentRef],
              { teamId: t.teamId ?? undefined }
            ),
          reconcile: (chatKey, reason, taskId) => {
            // §4.3: every approval-decision convergence path goes through the
            // single-flight reconcileChat gate — including a decision made from the
            // in-app bell on a NON-active chat (which previously did nothing until
            // the chat was reopened). `taskId` drives the idle durable fallback
            // (GAP-H1). Single-flight + backoff live in the gate.
            void chat.reconcileChat(chatKey, { reason, taskIdHint: taskId })
          },
          resolveApprovalNotification: notif.resolveApprovalNotification,
          pushToast,
        },
        target
      ),
    [chat.sessionFsmStore, chat.reconcileChat, notif.resolveApprovalNotification, pushToast]
  )
  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).
  //
  // 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).
  //
  // 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 }) => {
      // 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: () => store.getSnapshot(),
          decide: target => void decideApprovalRef.current(target),
          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)
      }
    })

    const unsubStore = store.subscribe(() => {
      if (buffer.size() === 0) return
      fire(
        buffer.drain(Date.now(), server => resolveConnectResumeTargets(store.getSnapshot(), server))
      )
    })

    return () => {
      unsub?.()
      unsubStore()
    }
  }, [chat.sessionFsmStore, connectorsData.refresh])

  // ─── MCP Server ───
  const mcpServer = useMcpServerController({
    selectedAgent: nav.selectedAgent,
    navItem: nav.navItem,
    isAuthenticated: auth.isAuthenticated,
    agentProviderByName: agentsData.agentProviderByName,
  })

  // ─── Host pre-warm (authenticated catalog only — see the hook's anti-flapping doc) ───
  useHostPrewarmController({
    agentNames: agentsData.agentNames,
    isAuthenticated: auth.isAuthenticated && postPaintDataReady,
  })

  // ─── Desktop ───
  const desktop = useDesktopController({
    selectedAgent: nav.selectedAgent,
    pushToast,
  })

  // ─── Activity ───
  const activity = useActivityController({
    selectedAgent: nav.selectedAgent,
    isAuthenticated: auth.isAuthenticated,
    loadMenuData: postPaintDataReady,
    chatList: chat.chatList,
    progressByAgentMessage: chat.progressByAgentMessage,
    agentNames: agentsData.agentNames,
  })

  const getCatalogRefreshPromise = useCallback(() => {
    if (!catalogRefreshPromiseRef.current) {
      catalogRefreshPromiseRef.current = window.clerum.access.refreshCatalog().finally(() => {
        catalogRefreshPromiseRef.current = null
      })
    }
    return catalogRefreshPromiseRef.current
  }, [])

  const refreshAgentsData = useCallback(async () => {
    return agentsData.refreshWithCatalog(getCatalogRefreshPromise())
  }, [agentsData.refreshWithCatalog, getCatalogRefreshPromise])

  const refreshContextsData = useCallback(async () => {
    await contextsData.refreshWithCatalog(getCatalogRefreshPromise())
  }, [contextsData.refreshWithCatalog, getCatalogRefreshPromise])

  const refreshMcpServersData = useCallback(async () => {
    await mcpServersData.refreshWithCatalog(getCatalogRefreshPromise())
  }, [getCatalogRefreshPromise, mcpServersData.refreshWithCatalog])

  const refreshWorkflowsData = useCallback(async () => {
    try {
      await queryClient.fetchQuery({
        queryKey: desktopQueryKeys.workflows,
        queryFn: () => window.clerum.workflows.list() as Promise<WorkflowRecipeListResult>,
        staleTime: 0,
      })
    } catch {
      // Query state already records the error for consumers.
    }
  }, [queryClient])

  const resetWorkflowsData = useCallback(() => {
    queryClient.setQueryData<WorkflowSelectionState>(
      desktopQueryKeys.workflowSelection,
      createResetWorkflowSelection
    )
    queryClient.removeQueries({ queryKey: desktopQueryKeys.workflows })
    queryClient.removeQueries({ queryKey: ['desktop-app', 'workflow-detail'] })
    queryClient.removeQueries({ queryKey: ['desktop-app', 'workflow-runs'] })
  }, [queryClient])

  const refreshAuthenticatedData = useCallback(
    async (options: { initialLoad?: boolean; sessionIdentity?: string } = {}) => {
      const refreshTeams = options.initialLoad
        ? teamsData.refreshInitialDirectory
        : teamsData.refresh
      if (options.initialLoad) {
        const scheduledIdentity = options.sessionIdentity
        if (!scheduledIdentity) return false
        let agentsLoaded = false
        try {
          agentsLoaded = await refreshAgentsData()
        } catch (error) {
          console.warn('[startup] failed to load the initial agent catalog', error)
        } finally {
          scheduleAfterFirstPaintForSession(
            activeAuthenticatedSessionIdentityRef,
            scheduledIdentity,
            async () => {
              setPostPaintDataReady(true)
              await Promise.all([
                refreshContextsData(),
                refreshMcpServersData(),
                refreshTeams(),
                refreshWorkflowsData(),
                connectorsData.refresh(),
                notif.handleRefreshPendingApprovals({ silent: true }),
              ])
            }
          )
        }
        return agentsLoaded
      }
      return Promise.all([
        refreshAgentsData(),
        refreshContextsData(),
        refreshMcpServersData(),
        refreshTeams(),
        refreshWorkflowsData(),
        connectorsData.refresh(),
        notif.handleRefreshPendingApprovals({ silent: true }),
      ])
    },
    [
      connectorsData.refresh,
      notif.handleRefreshPendingApprovals,
      refreshAgentsData,
      refreshContextsData,
      refreshMcpServersData,
      refreshWorkflowsData,
      setPostPaintDataReady,
      teamsData.refresh,
      teamsData.refreshInitialDirectory,
    ]
  )

  const refreshWorkspaceDataForRoute = useCallback(
    async (route: NavItem) => {
      // Route refreshes deliberately update only the visible section. Hidden
      // route data remains deferred until that route becomes visible; shared
      // menu/composer data is loaded by the post-paint bootstrap instead.
      const refreshers = [
        {
          route: DESKTOP_ROUTES.agents,
          refresh: () => agentsData.refreshWithCatalog(getCatalogRefreshPromise()),
        },
        {
          route: DESKTOP_ROUTES.connectors,
          refresh: () => mcpServersData.refreshWithCatalog(getCatalogRefreshPromise()),
        },
        { route: DESKTOP_ROUTES.plugins, refresh: refreshWorkflowsData },
      ] as const

      const current = refreshers.find(entry => entry.route === route)

      if (current) await current.refresh()
    },
    [
      agentsData.refreshWithCatalog,
      getCatalogRefreshPromise,
      mcpServersData.refreshWithCatalog,
      refreshWorkflowsData,
    ]
  )

  useEffect(() => {
    if (!auth.isAuthenticated) return
    if (agentsData.accessCatalog && nav.selectedAgent) {
      if (
        !agentsData.agentNames.includes(nav.selectedAgent) ||
        isHostAccessBlocked(nav.selectedAgent)
      ) {
        nav.setSelectedAgent(null)
      }
    }
  }, [
    agentsData.accessCatalog,
    agentsData.agentNames,
    auth.isAuthenticated,
    nav.selectedAgent,
    nav.setSelectedAgent,
    isHostAccessBlocked,
  ])

  const switchTeamForWorkspace = useCallback(
    async (teamId: string, options: { announce?: boolean } = {}) => {
      const { announce = true } = options
      auth.setBusy(true)
      try {
        if (!teamId) throw new Error('Select a team')
        const sessionState = await window.clerum.team.switch(teamId)
        if (!sessionState.authenticated || !sessionState.me) {
          throw new Error('Team switch ended without an authenticated session')
        }
        // GAP-N4: the renderer half of a team switch. `clearActiveChat`
        // only deselects — the previous team's tracker entries and FSM projection
        // survive, so a late terminal from an old-team task could run side effects
        // and stale badges leak across teams. Tear down the renderer chat state
        // (tracker.releaseAll + fsm.reset via resetChat) exactly like logout, once
        // the switch is CONFIRMED (before `refreshAuthenticatedData` repopulates) —
        // doing it before the RPC would wipe the view on a failed switch. The old
        // 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 || '')
        currentTeamIdRef.current = sessionState.me.teamId || teamId
        const switchedIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`
        activeAuthenticatedSessionIdentityRef.current = switchedIdentity
        authenticatedSessionIdentityRef.current = switchedIdentity
        // Team switching owns a complete foreground refresh. If it invalidated
        // the login-time post-paint callback, re-enable deferred menu data here.
        setPostPaintDataReady(true)
        await refreshAuthenticatedData()
        if (announce) {
          const teamName =
            teamsData.teams.find(team => team.id === teamId)?.name ||
            sessionState.me.teamName ||
            teamId
          fullSetStatus(`Switched team to ${teamName}.`, 'success')
        }
      } finally {
        auth.setBusy(false)
      }
    },
    [
      auth.setBusy,
      auth.setEmail,
      auth.setIsAuthenticated,
      auth.setMe,
      chat.resetChat,
      connectorsData.reset,
      fullSetStatus,
      refreshAuthenticatedData,
      setPostPaintDataReady,
      teamsData.teams,
    ]
  )

  const ensureTeamContext = useCallback(
    async (target: { teamId?: string; announce?: boolean }): Promise<boolean> => {
      const targetTeamId = String(target.teamId || '').trim()
      if (!targetTeamId) return false

      const queuedSwitch = notificationTeamContextQueueRef.current.then(async () => {
        const activeTeamId = currentTeamIdRef.current
        if (targetTeamId === activeTeamId) return false

        await switchTeamForWorkspace(targetTeamId, { announce: target.announce ?? false })
        return true
      })
      notificationTeamContextQueueRef.current = queuedSwitch.then(
        () => undefined,
        () => undefined
      )
      return queuedSwitch
    },
    [switchTeamForWorkspace]
  )
  const getCurrentTeamId = useCallback(() => currentTeamIdRef.current, [])

  const decideApprovalNotificationTarget = useCallback(
    async (target: AgentApprovalNotificationTarget) => {
      const targetAgent = String(target.agentName || '').trim()
      const chatId = String(target.chatId || '').trim()
      const taskId = String(target.taskId || '').trim()
      const requestId = String(target.requestId || '').trim()
      if (!targetAgent || !taskId || !requestId) return
      // Surface (a): the desktop-notification Approve/Deny action funnels through
      // the central decider (§4.7.4). Navigation/focus stay in
      // openAgentConversationTarget; this only decides.
      await decideApproval({
        agentRef: targetAgent,
        chatId,
        teamId: target.teamId,
        taskId,
        requestId,
        decision: target.decision,
        source: 'desktop_notification',
      })
    },
    [decideApproval]
  )

  decideApprovalFromNotificationRef.current = decideApprovalNotificationTarget

  // ─── Cross-domain: loadSession ───
  const loadSession = useCallback(
    async (options: { preserveNav?: boolean } = {}) => {
      const { preserveNav = false } = options
      try {
        void window.clerum.auth
          .getDependenciesHealth()
          .then(auth.setDependencyHealth)
          .catch(error => {
            console.warn('[Desktop] Could not refresh dependency health:', error)
            auth.setDependencyHealth(null)
          })
        const sessionState = await window.clerum.auth.getSessionState()
        const authenticated = Boolean(sessionState.authenticated && sessionState.me)
        auth.setIsAuthenticated(authenticated)
        auth.setMe(sessionState.me)

        if (!authenticated || !sessionState.me) {
          setPostPaintDataReady(false)
          auth.setDesktopReleaseStatus(null)
          await chat.stopAllActivityStreams()
          agentsData.reset()
          contextsData.reset()
          mcpServersData.reset()
          connectorsData.reset()
          teamsData.reset()
          resetWorkflowsData()
          queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
          chat.resetChat()
          notif.resetNotifications()
          activeAuthenticatedSessionIdentityRef.current = null
          authenticatedSessionIdentityRef.current = null
          if (!preserveNav) nav.handleNavSelect(DESKTOP_ROUTES.chat)
          return
        }

        auth.setPassword('')
        auth.setEmail(sessionState.me.email || '')
        void auth.refreshDesktopReleaseStatus()
        const sessionIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`
        activeAuthenticatedSessionIdentityRef.current = sessionIdentity
        if (authenticatedSessionIdentityRef.current !== sessionIdentity) {
          setPostPaintDataReady(false)
          const loaded = await refreshAuthenticatedData({
            initialLoad: true,
            sessionIdentity,
          })
          if (loaded && activeAuthenticatedSessionIdentityRef.current === sessionIdentity) {
            authenticatedSessionIdentityRef.current = sessionIdentity
          }
        } else {
          // A prior post-paint callback may have been invalidated by an identity
          // transition. An already-initialized matching session is ready now.
          setPostPaintDataReady(true)
        }
        if (!preserveNav) {
          nav.handleNavSelect(DESKTOP_ROUTES.chat)
        }
      } finally {
        auth.refreshRuntimeConfigState().catch(() => undefined)
        auth.setBooting(false)
      }
    },
    [
      agentsData.reset,
      auth.refreshRuntimeConfigState,
      connectorsData.reset,
      auth.setBooting,
      auth.setDependencyHealth,
      auth.setDesktopReleaseStatus,
      auth.setEmail,
      auth.setIsAuthenticated,
      auth.setMe,
      auth.setPassword,
      auth.refreshDesktopReleaseStatus,
      chat.resetChat,
      chat.stopAllActivityStreams,
      contextsData.reset,
      mcpServersData.reset,
      nav.handleNavSelect,
      notif.resetNotifications,
      queryClient,
      refreshAuthenticatedData,
      resetWorkflowsData,
      setPostPaintDataReady,
      teamsData.reset,
    ]
  )

  // Wire loadSession into the ref so auth's boot effect calls the real one
  loadSessionRef.current = loadSession

  // ─── Cross-domain: handleLogout ───
  const logoutAndGetSessionGeneration = useCallback(async (): Promise<number | null> => {
    let logoutGeneration: number | null = null
    const reflectSignedOutState = () => {
      auth.setIsAuthenticated(false)
      auth.setMe(null)
      auth.setPassword('')
    }
    try {
      auth.setBusy(true)
      await chat.stopAllActivityStreams()
      catalogRefreshPromiseRef.current = null
      agentsData.reset()
      contextsData.reset()
      mcpServersData.reset()
      connectorsData.reset()
      teamsData.reset()
      resetWorkflowsData()
      queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })
      // Drop ALL cached queries on logout: the singleton
      // desktopQueryClient uses staleTime:Infinity, so any env-scoped data left
      // in cache would otherwise bleed into the next login (possibly a different
      // environment, since the env is chosen pre-login).
      queryClient.clear()
      activeAuthenticatedSessionIdentityRef.current = null
      authenticatedSessionIdentityRef.current = null
      const logoutResult = await window.clerum.auth.logout()
      logoutGeneration = logoutResult.sessionGeneration
      reflectSignedOutState()
      chat.resetChat()
      notif.resetNotifications()
      fullSetStatus('Logged out.', 'success')
      try {
        await loadSession()
      } catch (error) {
        reflectSignedOutState()
        fullSetStatus(
          `Signed out, but could not refresh the desktop session: ${error instanceof Error ? error.message : String(error)}`,
          'warn'
        )
      }
      return logoutGeneration
    } catch (error) {
      if (logoutGeneration !== null) {
        reflectSignedOutState()
        fullSetStatus(
          `Signed out, but could not refresh the desktop session: ${error instanceof Error ? error.message : String(error)}`,
          'warn'
        )
        return logoutGeneration
      }
      fullSetStatus(
        `Logout failed: ${error instanceof Error ? error.message : String(error)}`,
        'error'
      )
      return null
    } finally {
      auth.setBusy(false)
    }
  }, [
    agentsData.reset,
    auth.setBusy,
    auth.setIsAuthenticated,
    auth.setMe,
    auth.setPassword,
    chat.resetChat,
    chat.stopAllActivityStreams,
    connectorsData.reset,
    contextsData.reset,
    fullSetStatus,
    loadSession,
    mcpServersData.reset,
    notif.resetNotifications,
    queryClient,
    resetWorkflowsData,
    teamsData.reset,
  ])
  const handleLogout = useCallback(async (): Promise<void> => {
    await logoutAndGetSessionGeneration()
  }, [logoutAndGetSessionGeneration])
  logoutForEnvironmentMismatchRef.current = logoutAndGetSessionGeneration

  // ─── Cross-domain: handleOpenAgentWorkspace ───
  const openAgentWorkspace = useCallback(
    (agentName: string, route: AgentWorkspaceRoute = AGENT_WORKSPACE_ROUTES.connectors) => {
      if (!agentName) return
      chat.setPendingChatSelection(agentName, null)
      chat.clearActiveChat()
      // Open/focus the agents tab (single writer). It clears selectedAgent/route,
      // which the two setters below immediately override in the same batch.
      nav.handleNavSelect(DESKTOP_ROUTES.agents)
      nav.setSelectedAgentRoute(route)
      nav.setSelectedAgent(agentName)
    },
    [
      chat.clearActiveChat,
      chat.setPendingChatSelection,
      nav.handleNavSelect,
      nav.setSelectedAgent,
      nav.setSelectedAgentRoute,
    ]
  )
  const handleOpenAgentWorkspace = useCallback(
    (agentName: string, route: AgentWorkspaceRoute = AGENT_WORKSPACE_ROUTES.connectors) => {
      if (!agentName) return
      const navigationIntentEpoch = ++navigationIntentEpochRef.current
      if (!isHostAccessBlocked(agentName)) {
        openAgentWorkspace(agentName, route)
        return
      }
      const scope = authorityScopeRef.current
      void verifyHostAccess(agentName).then(verified => {
        if (
          verified &&
          authorityScopeRef.current === scope &&
          navigationIntentEpochRef.current === navigationIntentEpoch
        ) {
          openAgentWorkspace(agentName, route)
        }
      })
    },
    [isHostAccessBlocked, openAgentWorkspace, verifyHostAccess]
  )

  // ─── Cross-domain: handleSelectChatAgent (Chat page agent picker) ───
  const selectChatAgent = useCallback(
    (
      agentName: string,
      options: {
        selectLatest?: boolean
        chatId?: string
        isRemote?: boolean
        title?: string
        // When true, drive the chat controller (pending selection + selectedAgent)
        // WITHOUT flipping `navItem` to the chat route. The chat-drawer coexists
        // with the live app on the `apps` route and needs to swap the shared
        // <ChatPage>'s conversation in place, so it must not navigate away.
        keepNavItem?: boolean
      } = {}
    ) => {
      if (!agentName) return
      const targetChatId = String(options.chatId || '').trim()
      // Fast path — ONLY when we are already on the chat route. `switchToChat`
      // sets the active chat imperatively and leaves no pending selection behind,
      // which is safe exactly while the agent-selection effect
      // (useAgentChatController, deps [currentTeamId, navItem, selectedAgent])
      // is NOT about to re-run. Coming from any other route the `setNavItem`
      // below flips `navItem`, that effect re-runs, finds no pending selection
      // and takes its reset branch (activeChatId -> null) — which would blank the
      // just-opened session into the "new chat" empty state for a frame and then
      // auto-select the most recent chat instead of the requested one. So from
      // another route (Apps embed, agent workspace, settings…) we fall through to
      // the pending-selection path below, which is designed to survive a route
      // change: it sets the active chat synchronously AND records the selection
      // the effect replays.
      // `keepNavItem` always takes the pending-selection path below: it is used
      // when the route is changing to (or staying on) a non-chat route (the app
      // drawer). The pending selection is what survives a route change — but it is
      // only replayed when the agent-selection effect re-runs (deps include
      // `navItem`/`selectedAgent`). When `keepNavItem` selects a chat of the
      // ALREADY-selected agent WITHOUT a route change (drawer reopen / switcher),
      // neither dep changes, the effect never replays, and the pending selection
      // is left stuck loading. That case gets an imperative `switchToChat` below.
      if (
        targetChatId &&
        nav.selectedAgent === agentName &&
        nav.navItem === DESKTOP_ROUTES.chat &&
        !options.keepNavItem
      ) {
        // D.4: switchToChat is now a single unified path (no isRemote) — the
        // server is the source of truth and hydrates server-only chats itself.
        void chat
          .switchToChat(agentName, targetChatId, {
            onCurrentError: error => {
              fullSetStatus(
                `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,
                'error'
              )
            },
          })
          .catch(() => undefined)
        nav.setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
        // Activate the chat tab (dedupes/focuses by chatId). We are already on
        // the chat route, so `navItem` stays `chat` — same-commit derivation, no
        // blank frame.
        nav.activateChatTab(agentName, targetChatId, options.title)
        return
      }
      const shouldSelectLatest = targetChatId ? false : options.selectLatest !== false
      const pendingSelectionOptions: {
        selectLatest: boolean
        suppressAutoSelect: boolean
        deferSwitch: boolean
        title?: string
        isRemote?: boolean
      } = {
        selectLatest: shouldSelectLatest,
        suppressAutoSelect: !shouldSelectLatest && !targetChatId,
        deferSwitch: options.keepNavItem === true,
      }
      if (options.title) pendingSelectionOptions.title = options.title
      if (options.isRemote !== undefined) pendingSelectionOptions.isRemote = options.isRemote
      chat.setPendingChatSelection(agentName, targetChatId || null, pendingSelectionOptions)
      if (!targetChatId) {
        chat.clearActiveChat()
      }
      nav.setSelectedAgentRoute(AGENT_WORKSPACE_ROUTES.connectors)
      nav.setSelectedAgent(agentName)
      // Non-drawer: activate the chat tab so `navItem` derives to `chat` in the
      // SAME commit as `setSelectedAgent` — the agent-selection effect replays
      // into its pending branch. `keepNavItem` (drawer) never touches the active
      // tab, so the app tab stays active and the route stays on `apps`.
      if (!options.keepNavItem) {
        nav.activateChatTab(agentName, targetChatId || null, options.title)
      }
      // Drawer same-agent selection: `setSelectedAgent` above is a no-op (same
      // value) and `navItem` is not flipped, so the agent-selection effect will
      // not replay to consume the pending selection — load the chat imperatively.
      // The pending selection is still set above so that when the caller DID
      // change the route in the same batch (launch-from-chat: chat→apps), the
      // effect replays into its `specific` branch instead of the reset branch;
      // both switches target the same chat and `switchToChat` coalesces them.
      if (options.keepNavItem && targetChatId && nav.selectedAgent === agentName) {
        void chat
          .switchToChat(agentName, targetChatId, {
            onCurrentError: error => {
              fullSetStatus(
                `Could not open conversation: ${error instanceof Error ? error.message : String(error)}`,
                'error'
              )
            },
          })
          .catch(() => undefined)
      }
    },
    [
      chat.clearActiveChat,
      chat.setPendingChatSelection,
      chat.switchToChat,
      fullSetStatus,
      nav.activateChatTab,
      nav.navItem,
      nav.selectedAgent,
      nav.setSelectedAgent,
      nav.setSelectedAgentRoute,
    ]
  )
  const handleSelectChatAgent = useCallback(
    (agentName: string, options: Parameters<typeof selectChatAgent>[1] = {}) => {
      if (!agentName) return
      const navigationIntentEpoch = ++navigationIntentEpochRef.current
      if (!isHostAccessBlocked(agentName)) {
        selectChatAgent(agentName, options)
        return
      }
      const scope = authorityScopeRef.current
      void verifyHostAccess(agentName).then(verified => {
        if (
          verified &&
          authorityScopeRef.current === scope &&
          navigationIntentEpochRef.current === navigationIntentEpoch
        ) {
          selectChatAgent(agentName, options)
        }
      })
    },
    [isHostAccessBlocked, selectChatAgent, verifyHostAccess]
  )

  // ─── Cross-domain: handleNavSelect (extended) ───
  const handleNavSelect = useCallback(
    (item: NavItem) => {
      const focusedChat = nav.handleNavSelect(item)
      if (item === DESKTOP_ROUTES.chat) {
        // `nav.handleNavSelect` owns the "which chat did this focus" precedence
        // (active chat → last chat tab → blank) and RETURNS it. Load exactly that:
        // an existing conversation is re-activated in place (dedupes by chatId —
        // no new tab), so clicking "chats" resumes the open conversation instead of
        // appending a fresh blank chat on every click. Only when the nav focused a
        // blank/absent chat (`null`) do we pre-select the latest agent. No second
        // copy of the precedence lives here — that seam duplication (D4) would let
        // the loaded chat drift from the focused one if the rule ever changed.
        if (focusedChat) {
          handleSelectChatAgent(focusedChat.agentRef, {
            chatId: focusedChat.chatId,
            selectLatest: false,
          })
          return
        }
        const latestAgent = pickLatestAgent(agentsData.agentNames, activity.agentLastActiveByAgent)
        if (latestAgent) {
          handleSelectChatAgent(latestAgent, { selectLatest: false })
        }
      }
    },
    [
      activity.agentLastActiveByAgent,
      agentsData.agentNames,
      handleSelectChatAgent,
      nav.handleNavSelect,
    ]
  )

  const openAgentConversationTarget = useCallback(
    async (
      target: AgentConversationNotificationTarget,
      options: { keepNavItem?: boolean } = {}
    ) => {
      const targetAgent = String(target.agentName || '').trim()
      if (!targetAgent) return
      const targetChatId = String(target.chatId || '').trim()
      const targetTeamId = String(target.teamId || '').trim()
      const activeTeamId = currentTeamIdRef.current
      const requiresTeamSwitch = Boolean(targetTeamId && targetTeamId !== activeTeamId)
      // minispec 04 approach C: when the app embed is live (App requests
      // `keepNavItem`) and no team switch is needed, surface the conversation IN
      // the drawer instead of ejecting to the full-screen chat route. A team
      // switch tears the embed down, so that case keeps the full-screen path.
      const stayInDrawer = Boolean(options.keepNavItem) && !requiresTeamSwitch

      try {
        if (requiresTeamSwitch) {
          await ensureTeamContext({ teamId: targetTeamId })
        }
        if (isHostAccessBlocked(targetAgent) && !(await verifyHostAccess(targetAgent))) return

        if (stayInDrawer) {
          // handleSelectChatAgent(keepNavItem) sets the active chat without
          // flipping `navItem` (and imperatively switches for the same-agent
          // case); the drawer reconciler (approach A) syncs the switcher tab.
          handleSelectChatAgent(targetAgent, {
            selectLatest: false,
            keepNavItem: true,
            ...(targetChatId ? { chatId: targetChatId } : {}),
          })
          return
        }

        // Same imperative-fast-path guard as handleSelectChatAgent: `switchToChat`
        // leaves no pending selection, so it only survives while the route (and
        // hence the agent-selection effect's deps) does not change. Opening a
        // notification from the Apps embed / a workspace / settings flips
        // `navItem` below, re-running that effect into its reset branch — the
        // conversation would blank to the "new chat" empty state and then land on
        // the most recent chat instead of the notification's. From another route
        // we fall through to the pending-selection path, which replays the
        // requested chat across the re-run.
        if (
          targetChatId &&
          !requiresTeamSwitch &&
          nav.selectedAgent === targetAgent &&
          nav.navItem === DESKTOP_ROUTES.chat
        ) {
          try {
            await chat.switchToChat(targetAgent, targetChatId, {
              onCurrentError: error => {
                fullSetStatus(
                  `Could not open notification: ${error instanceof Error ? error.message : String(error)}`,
                  'error'
                )
              },
            })
          } catch {
            // The request owns current feedback and still rejects to awaiters.
            // This UI event observes that rejection without reporting it again.
            return
          }
          nav.activateChatTab(targetAgent, targetChatId)
          return
        }

        chat.setPendingChatSelection(targetAgent, targetChatId || null)
        nav.setSelectedAgent(targetAgent)
        nav.activateChatTab(targetAgent, targetChatId || null)
      } catch (error) {
        fullSetStatus(
          `Could not open notification: ${error instanceof Error ? error.message : String(error)}`,
          'error'
        )
      }
    },
    [
      chat.setPendingChatSelection,
      chat.switchToChat,
      ensureTeamContext,
      fullSetStatus,
      handleSelectChatAgent,
      isHostAccessBlocked,
      verifyHostAccess,
      nav.activateChatTab,
      nav.navItem,
      nav.selectedAgent,
      nav.setSelectedAgent,
    ]
  )

  openAgentConversationFromNotificationRef.current = openAgentConversationTarget

  const openWorkflowCompletionTarget = useCallback(
    async (notification: AppNotification) => {
      const target = notification.workflow
      if (!target) return
      try {
        await ensureTeamContext({ teamId: notification.teamId })
        nav.handleNavSelect(DESKTOP_ROUTES.plugins)

        const fallbackWorkflow = {
          namespace: target.namespace,
          name: target.name,
          triggerableByUser: false,
        }
        queryClient.setQueryData<WorkflowSelectionState>(
          desktopQueryKeys.workflowSelection,
          current => ({
            ...(current ?? EMPTY_WORKFLOW_SELECTION),
            selectedWorkflow: fallbackWorkflow,
            workflowInputValues: EMPTY_WORKFLOW_SELECTION.workflowInputValues,
            workflowTriggerLoading: false,
            selectionVersion:
              (current?.selectionVersion ?? EMPTY_WORKFLOW_SELECTION.selectionVersion) + 1,
          })
        )

        const detail = (await window.clerum.workflows.read(
          target.namespace,
          target.name
        )) as WorkflowRecipeResource
        const selectedWorkflow = summarizeWorkflowResource(detail)
        queryClient.setQueryData(
          desktopQueryKeys.workflowDetail(target.namespace, target.name),
          detail
        )
        queryClient.setQueryData<WorkflowSelectionState>(
          desktopQueryKeys.workflowSelection,
          current => ({
            ...(current ?? EMPTY_WORKFLOW_SELECTION),
            selectedWorkflow,
            workflowInputValues: EMPTY_WORKFLOW_SELECTION.workflowInputValues,
            workflowTriggerLoading: false,
          })
        )

        const runs = await loadWorkflowRunsWithArtifactsForWorkflowTarget(target)
        queryClient.setQueryData<WorkflowRunsResult>(
          desktopQueryKeys.workflowRuns(target.namespace, target.name, 20),
          runs
        )
        fullSetStatus('Workflow ' + target.name + ' results refreshed.', 'success', undefined, {
          global: false,
          toast: true,
        })
      } catch (error) {
        void queryClient.invalidateQueries({
          queryKey: desktopQueryKeys.workflowDetail(target.namespace, target.name),
        })
        void queryClient.invalidateQueries({
          queryKey: desktopQueryKeys.workflowRuns(target.namespace, target.name, 20),
        })
        fullSetStatus(
          'Could not refresh workflow results: ' +
            (error instanceof Error ? error.message : String(error)),
          'error'
        )
      }
    },
    [ensureTeamContext, fullSetStatus, nav.handleNavSelect, queryClient]
  )

  const openSdkNotificationTarget = useCallback(
    async (notification: AppNotification) => {
      const target = notification.sdk
      if (!target) return
      try {
        // SDK notifications are user-addressed and do not carry one canonical
        // team. Recipe reads use the current user session and its effective
        // direct access instead of inventing a team switch.
        nav.handleNavSelect(DESKTOP_ROUTES.plugins)

        const fallbackWorkflow = {
          namespace: target.recipeNamespace,
          name: target.recipeName,
          triggerableByUser: false,
        }
        queryClient.setQueryData<WorkflowSelectionState>(
          desktopQueryKeys.workflowSelection,
          current => ({
            ...(current ?? EMPTY_WORKFLOW_SELECTION),
            selectedWorkflow: fallbackWorkflow,
            workflowInputValues: EMPTY_WORKFLOW_SELECTION.workflowInputValues,
            workflowTriggerLoading: false,
            selectionVersion:
              (current?.selectionVersion ?? EMPTY_WORKFLOW_SELECTION.selectionVersion) + 1,
          })
        )

        const detail = (await window.clerum.workflows.read(
          target.recipeNamespace,
          target.recipeName
        )) as WorkflowRecipeResource
        const selectedWorkflow = summarizeWorkflowResource(detail)
        queryClient.setQueryData(
          desktopQueryKeys.workflowDetail(target.recipeNamespace, target.recipeName),
          detail
        )
        queryClient.setQueryData<WorkflowSelectionState>(
          desktopQueryKeys.workflowSelection,
          current => ({
            ...(current ?? EMPTY_WORKFLOW_SELECTION),
            selectedWorkflow,
            workflowInputValues: EMPTY_WORKFLOW_SELECTION.workflowInputValues,
            workflowTriggerLoading: false,
            selectionVersion:
              (current?.selectionVersion ?? EMPTY_WORKFLOW_SELECTION.selectionVersion) + 1,
          })
        )
      } catch (error) {
        void queryClient.invalidateQueries({
          queryKey: desktopQueryKeys.workflowDetail(target.recipeNamespace, target.recipeName),
        })
        fullSetStatus(
          'Could not open SDK notification: ' +
            (error instanceof Error ? error.message : String(error)),
          'error'
        )
      }
    },
    [fullSetStatus, nav.handleNavSelect, queryClient]
  )

  // ─── Cross-domain: handleOpenNotification ───
  const handleOpenNotification = useCallback(
    async (notification: AppNotification, options: { keepNavItem?: boolean } = {}) => {
      notif.markNotificationRead(notification.id)
      if (notification.kind === 'workflow_completed') {
        await openWorkflowCompletionTarget(notification)
        return
      }
      if (notification.kind === 'sdk_notification') {
        await openSdkNotificationTarget(notification)
        return
      }
      // `keepNavItem` (App passes it when the app embed is live) only reaches the
      // agent-conversation surface — workflow/SDK targets navigate elsewhere.
      await openAgentConversationTarget(notification, options)
    },
    [
      notif.markNotificationRead,
      openAgentConversationTarget,
      openSdkNotificationTarget,
      openWorkflowCompletionTarget,
    ]
  )

  // ─── Cross-domain: handleRefreshMcpHealth ───
  const handleRefreshMcpHealth = useCallback(async () => {
    mcpServer.setMcpHealthRefreshing(true)
    try {
      await refreshMcpServersData()
      mcpServer.bumpReconnectNonce()
    } finally {
      mcpServer.setMcpHealthRefreshing(false)
    }
  }, [mcpServer.bumpReconnectNonce, mcpServer.setMcpHealthRefreshing, refreshMcpServersData])

  // Guard effects for nav item guards (team-details/context-details without selection)
  // These were in useWorkspaceController — in the new world we handle them in the coordinator
  // by extending handleNavSelect, but we also need the reactive guard.
  // We add them here:
  // Note: useEffect cannot be used here conditionally. We use the hooks pattern inline.
  // These guards are handled by useNavigationController's state + the coordinator logic.
  // We replicate the original behavior by watching nav state changes.

  return {
    // Auth
    booting: auth.booting,
    initialExperienceLoading:
      auth.isAuthenticated &&
      !auth.hasDependencyOutage &&
      agentsData.loading &&
      !agentsData.accessCatalog,
    busy: auth.busy,
    statusText,
    statusTone,
    isAuthenticated: auth.isAuthenticated,
    me: auth.me,
    currentTeamId,
    availableTeamIds,
    teamDirectoryHydrated: teamsData.teamDirectoryHydrated,
    authenticatedPrincipalIdentity,
    email: auth.email,
    password: auth.password,
    desktopSetupAuthorizationToken: auth.desktopSetupAuthorizationToken,
    desktopSetupStarted: auth.desktopSetupStarted,
    runtimeConfigSetupName: auth.runtimeConfigSetupName,
    runtimeConfigSetupExternalRestApiBaseUrl: auth.runtimeConfigSetupExternalRestApiBaseUrl,
    runtimeConfigSetupRpcProxyBaseUrl: auth.runtimeConfigSetupRpcProxyBaseUrl,
    authTransitioning: auth.authTransitioning,
    runtimeConfigState: auth.runtimeConfigState,
    runtimeConfigMissing: auth.runtimeConfigMissing,
    onboarding,
    unauthenticatedView,
    desktopReleaseStatus: auth.desktopReleaseStatus,
    desktopEnvironmentSetupComplete: auth.desktopEnvironmentSetupComplete,
    pendingDesktopEnvironmentSetup: auth.pendingDesktopEnvironmentSetup,
    pendingDesktopEnvironmentSwitchConfirmation: auth.pendingDesktopEnvironmentSwitchConfirmation,
    backendSwitchHint: auth.backendSwitchHint,
    showRuntimeConfigSelector: auth.showRuntimeConfigSelector,
    dependencyHealth: auth.dependencyHealth,
    hasDependencyOutage: auth.hasDependencyOutage,
    setBooting: auth.setBooting,
    setEmail: auth.setEmail,
    setPassword: auth.setPassword,
    setDesktopSetupAuthorizationToken: auth.setDesktopSetupAuthorizationToken,
    setRuntimeConfigSetupName: auth.setRuntimeConfigSetupName,
    setRuntimeConfigSetupExternalRestApiBaseUrl: auth.setRuntimeConfigSetupExternalRestApiBaseUrl,
    setRuntimeConfigSetupRpcProxyBaseUrl: auth.setRuntimeConfigSetupRpcProxyBaseUrl,
    setPendingDesktopEnvironmentSetup: auth.setPendingDesktopEnvironmentSetup,
    setStatus: fullSetStatus,
    loadSession,
    handlePasswordLogin: auth.handlePasswordLogin,
    handleSwitchLoginBackend: auth.handleSwitchLoginBackend,
    handleStartDesktopSetup: auth.handleStartDesktopSetup,
    handleCompleteDesktopSetup: auth.handleCompleteDesktopSetup,
    handleSaveRuntimeConfig: auth.handleSaveRuntimeConfig,
    handleDeleteRuntimeConfig: auth.handleDeleteRuntimeConfig,
    handleSelectRuntimeConfig: auth.handleSelectRuntimeConfig,
    handleClearRuntimeConfigSelection: auth.handleClearRuntimeConfigSelection,
    handleCancelDesktopEnvironmentSetup: auth.handleCancelDesktopEnvironmentSetup,
    handleConfirmDesktopEnvironmentSetup: auth.handleConfirmDesktopEnvironmentSetup,
    handleCancelDesktopEnvironmentSwitchConfirmation:
      auth.handleCancelDesktopEnvironmentSwitchConfirmation,
    handleConfirmDesktopEnvironmentSwitchConfirmation:
      auth.handleConfirmDesktopEnvironmentSwitchConfirmation,
    handleOpenDesktopRelease: auth.handleOpenDesktopRelease,
    setDesktopEnvironmentSetupComplete: auth.setDesktopEnvironmentSetupComplete,
    handleLogout,

    // Navigation
    navItem: nav.navItem,
    selectedAgent: nav.selectedAgent,
    isHostAccessBlocked,
    hostAuthorityRevision,
    selectedAgentRoute: nav.selectedAgentRoute,
    setSelectedAgent: nav.setSelectedAgent,
    handleNavSelect,
    // Universal tab store (single writer; App composes the strip/reveal/reconcile
    // over these — `navItem` above is its read-only projection).
    workspaceTabs: nav.workspaceTabs,
    setWorkspaceTabs: nav.setWorkspaceTabs,
    activeWorkspaceTab: nav.activeTab,
    nextWorkspaceTabId: nav.nextWorkspaceTabId,
    appsPickerActive: nav.appsPickerActive,
    showAppsPicker: nav.showAppsPicker,
    clearAppsPicker: nav.clearAppsPicker,
    activateWorkspaceChatTab: nav.activateChatTab,
    lastActiveChatTabId: nav.lastActiveChatTabId,
    openFilesSection: nav.openFilesSection,
    openPreviewSection: nav.openPreviewSection,
    handleOpenAgentWorkspace,
    handleSelectChatAgent,
    handleEnsureTeamContext: ensureTeamContext,
    getCurrentTeamId,
    handleBackToAgents: nav.handleBackToAgents,
    handleRefreshWorkspaceData: refreshWorkspaceDataForRoute,

    // Notifications
    notifications: notif.notifications,
    notificationActionById: notif.notificationActionById,
    pendingApprovals: notif.pendingApprovals,
    pendingApprovalsLoading: notif.pendingApprovalsLoading,
    pendingApprovalActionId: notif.pendingApprovalActionId,
    unreadNotificationCount: notif.unreadNotificationCount,
    toasts,
    pushToast,
    dismissToast: toastCtrl.dismissToast,
    markNotificationsRead: notif.markNotificationsRead,
    clearNotifications: notif.clearNotifications,
    removeNotification: notif.removeNotification,
    resolveApprovalNotification: notif.resolveApprovalNotification,
    decideApproval,
    handleOpenNotification,
    handleApproveNotification: notif.handleApproveNotification,
    handleDenyNotification: notif.handleDenyNotification,
    handleRefreshPendingApprovals: notif.handleRefreshPendingApprovals,
    handleDecidePendingApproval: notif.handleDecidePendingApproval,
    notificationSettings: notificationSettings.settings,
    desktopNotificationPermission: notificationSettings.desktopNotificationPermission,
    saveNotificationSettings: notificationSettings.saveNotificationSettings,
    setNotificationSoundVolume: notificationSettings.setNotificationSoundVolume,
    playNotificationSoundPreview: notif.playNotificationSound,
    channelNotificationPreferences: channelNotificationPreferences.channelNotificationPreferences,
    channelNotificationPreferencesLoading:
      channelNotificationPreferences.channelNotificationPreferencesLoading,
    channelNotificationPreferencesSaving:
      channelNotificationPreferences.channelNotificationPreferencesSaving,
    saveChannelNotificationPreferences:
      channelNotificationPreferences.saveChannelNotificationPreferences,

    // Chat
    activeChatId: chat.activeChatId,
    chatList: chat.chatList,
    sessionStateByChatId: chat.sessionStateByChatId,
    sessionStateByChatKey: chat.sessionStateByChatKey,
    chatListLoading: chat.chatListLoading,
    chatListMoreLoading: chat.chatListMoreLoading,
    chatListHasMoreRemoteSessions: chat.chatListHasMoreRemoteSessions,
    latestChatSessions: chat.latestChatSessions,
    latestChatSessionsLoading: chat.latestChatSessionsLoading,
    chatMessages: chat.chatMessages,
    chatMessagesLoading: chat.chatMessagesLoading,
    hasOlderMessages: chat.hasOlderMessages,
    olderMessagesLoading: chat.olderMessagesLoading,
    composerImageAttachments: chat.composerImageAttachments,
    composerFileAttachments: chat.composerFileAttachments,
    composerFileRefusals: chat.composerFileRefusals,
    composerReferenceAttachments: chat.composerReferenceAttachments,
    agentSending: chat.agentSending,
    agentError: chat.agentError,
    failedAgentSend: chat.failedAgentSend,
    chatEndRef: chat.chatEndRef,
    scrollChatToBottom: chat.scrollChatToBottom,
    activeMessages: chat.chatMessages,
    activityByMessageId: chat.activityByMessageId,
    progressByMessageId: chat.progressByMessageId,
    groupedMessages: chat.groupedMessages,
    handleCreateChat: chat.handleCreateChat,
    handleRenameChat: chat.handleRenameChat,
    handleRenameChatForAgent: chat.handleRenameChatForAgent,
    captureChatDeleteFence: chat.captureChatDeleteFence,
    handleDeleteChat: chat.handleDeleteChat,
    handleDeleteChatForAgent: chat.handleDeleteChatForAgent,
    handleSelectChat: chat.handleSelectChat,
    handleLoadOlderMessages: chat.handleLoadOlderMessages,
    loadMoreChatSessions: chat.loadMoreChatSessions,
    handleSendAgentMessage: chat.handleSendAgentMessage,
    handleRetryFailedAgentSend: chat.handleRetryFailedAgentSend,
    handleRecoverFailedAgentSend: chat.handleRecoverFailedAgentSend,
    handleDiscardFailedAgentSend: chat.handleDiscardFailedAgentSend,
    clearComposerSendError: chat.clearComposerSendError,
    handleAddComposerImageAttachments: chat.handleAddComposerImageAttachments,
    handleUpdateComposerImageAttachment: chat.handleUpdateComposerImageAttachment,
    handleRemoveComposerImageAttachment: chat.handleRemoveComposerImageAttachment,
    handleAddComposerFiles: chat.handleAddComposerFiles,
    handleRemoveComposerFileAttachment: chat.handleRemoveComposerFileAttachment,
    handleAddComposerReferenceAttachments: chat.handleAddComposerReferenceAttachments,
    handleRemoveComposerReferenceAttachment: chat.handleRemoveComposerReferenceAttachment,
    handleClearComposerAttachments: chat.handleClearComposerAttachments,
    cancelTask: chat.cancelTask,

    // MCP Server
    hostRuntimeStatus: mcpServer.hostRuntimeStatus,
    hostRuntimeLoading: mcpServer.hostRuntimeLoading,
    hostRuntimeError: mcpServer.hostRuntimeError,
    hostRuntimeLastUpdatedAt: mcpServer.hostRuntimeLastUpdatedAt,
    hostRuntimeIsStale: mcpServer.hostRuntimeIsStale,
    activeLlmModel: mcpServer.activeLlmModel,
    activeLlmProvider: mcpServer.activeLlmProvider,
    mcpHealthRefreshing: mcpServer.mcpHealthRefreshing,
    handleRefreshMcpHealth,

    // Desktop
    desktopStatus: desktop.desktopStatus,
    desktopError: desktop.desktopError,
    desktopAvailable: desktop.desktopAvailable,
    handleOpenDesktop: desktop.handleOpenDesktop,

    // Activity
    agentLastActiveByAgent: activity.agentLastActiveByAgent,
    selectedAgentActivitySummary: activity.selectedAgentActivitySummary,
  }
}