Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
perf: keep authenticated UI shells mounted
Josué3f121a1748c8
diff --git a/control-ui/app/communication-channels/[name]/edit/page.tsx b/control-ui/app/communication-channels/[name]/edit/page.tsxindex 190b07260..eb2d08a84 100644--- a/control-ui/app/communication-channels/[name]/edit/page.tsx+++ b/control-ui/app/communication-channels/[name]/edit/page.tsx@@ -3,6 +3,7 @@import React, { useEffect, useMemo, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'import { ChannelCredentialsPanel } from '@components/ChannelCredentialsPanel'import { CommunicationChannelAccessSelector } from '@components/CommunicationChannelAccessSelector'import { CommunicationChannelConversationsTable } from '@components/CommunicationChannelConversations'@@ -232,7 +233,11 @@ export default function EditCommunicationChannelPage() {}>{loading ? (- <div className="cu-create-content">Loading communication channel...</div>+ <FormSectionsSkeleton+ label="Communication channel"+ primaryActionLabel="Save channel"+ sections={3}+ />) : loadError ? (<div className="cu-create-content"><div className="cu-banner cu-banner--error" role="alert">diff --git a/control-ui/app/contexts/[name]/page.tsx b/control-ui/app/contexts/[name]/page.tsxindex 0ea79a8ca..ed60c1555 100644--- a/control-ui/app/contexts/[name]/page.tsx+++ b/control-ui/app/contexts/[name]/page.tsx@@ -1,6 +1,7 @@'use client'import React, { useEffect, useMemo, useRef, useState } from 'react'+import Link from 'next/link'import { useParams, useRouter } from 'next/navigation'import { useConfirmDialog } from '@components/ConfirmDialog'import { CreateFlowPanel } from '@components/CreateFlowPanel'@@ -895,7 +896,7 @@ export default function ContextDetailsPage() {{sharedFileSystemsDraft.map(ref => (<tr key={`${ref.name}@${ref.mountPath}`}><td>- <a+ <LinkclassName="cu-link"href={CONTROL_ROUTES.agentFiles.detail(ref.name)}style={{@@ -906,7 +907,7 @@ export default function ContextDetailsPage() {><IconFolder />{ref.name}- </a>+ </Link></td><td><code style={{ fontSize: '0.85rem' }}>{ref.mountPath}</code>diff --git a/control-ui/app/cost/llm-prices/[id]/edit/page.tsx b/control-ui/app/cost/llm-prices/[id]/edit/page.tsxindex 0cf315142..edacc9aa2 100644--- a/control-ui/app/cost/llm-prices/[id]/edit/page.tsx+++ b/control-ui/app/cost/llm-prices/[id]/edit/page.tsx@@ -3,6 +3,7 @@import React, { useEffect, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'@@ -97,9 +98,12 @@ export default function EditLlmPricePage() {}>{loading ? (- <div className="cu-px-form">- <div className="cu-create-content">Loading price...</div>- </div>+ <FormSectionsSkeleton+ className="cu-px-form"+ label="LLM price"+ primaryActionLabel="Save price"+ sections={2}+ />) : loadError ? (<div className="cu-px-form"><div className="cu-banner cu-banner--error" role="alert">diff --git a/control-ui/app/cost/llm-prices/new/page.tsx b/control-ui/app/cost/llm-prices/new/page.tsxindex 9bb424669..d9d9f0924 100644--- a/control-ui/app/cost/llm-prices/new/page.tsx+++ b/control-ui/app/cost/llm-prices/new/page.tsx@@ -3,6 +3,7 @@import React, { Suspense, useState } from 'react'import { useRouter, useSearchParams } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { BodyLoadingSkeleton } from '@components/BodyLoadingSkeleton'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'@@ -74,7 +75,18 @@ function CreateLlmPriceContent() {export default function CreateLlmPricePage() {return (- <Suspense fallback={null}>+ <Suspense+ fallback={+ <BodyLoadingSkeleton+ backLabel="Back to prices"+ icon={<IconPrice />}+ primaryActionLabel="Add price"+ sections={3}+ subtitle="Set per-1M-token prices for a provider/model so cost budgets can price usage."+ title="Add LLM price"+ />+ }+ ><CreateLlmPriceContent /></Suspense>)diff --git a/control-ui/app/cost/llm-prices/page.tsx b/control-ui/app/cost/llm-prices/page.tsxindex b506d14fb..9d3ea9dba 100644--- a/control-ui/app/cost/llm-prices/page.tsx+++ b/control-ui/app/cost/llm-prices/page.tsx@@ -3,7 +3,6 @@import React, { useEffect, useState } from 'react'import Link from 'next/link'import { useRouter } from 'next/navigation'-import { useAuth } from '@components/AuthContext'import { useConfirmDialog } from '@components/ConfirmDialog'import { LlmPriceTable } from '@components/LlmPriceTable'import { useToast } from '@components/Toast'@@ -21,14 +20,13 @@ import {import { getProviderDisplayLabel } from '@lib/llm'export default function LlmPricesPage() {- const { authState } = useAuth()const router = useRouter()const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()const [prices, setPrices] = useState<LlmModelPrice[]>([])const [unpriced, setUnpriced] = useState<UnpricedModel[]>([])- const [loading, setLoading] = useState(false)+ const [loading, setLoading] = useState(true)const [error, setError] = useState('')// Cost budgets still pinning a price whose delete was rejected with 409.const [deleteBlockedBudgets, setDeleteBlockedBudgets] = useState<BudgetRef[] | null>(null)@@ -95,10 +93,8 @@ export default function LlmPricesPage() {}useEffect(() => {- if (authState.isLoggedIn && !authState.isLoading) {- void loadAll()- }- }, [authState.isLoggedIn, authState.isLoading])+ void loadAll()+ }, [])return (<>diff --git a/control-ui/app/cost/token-budgets/[id]/edit/page.tsx b/control-ui/app/cost/token-budgets/[id]/edit/page.tsxindex a022a9411..467afb153 100644--- a/control-ui/app/cost/token-budgets/[id]/edit/page.tsx+++ b/control-ui/app/cost/token-budgets/[id]/edit/page.tsx@@ -3,6 +3,7 @@import React, { useEffect, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'@@ -97,9 +98,12 @@ export default function EditTokenBudgetPage() {}>{loading ? (- <div className="cu-tb-form">- <div className="cu-create-content">Loading budget...</div>- </div>+ <FormSectionsSkeleton+ className="cu-tb-form"+ label="Token budget"+ primaryActionLabel="Save budget"+ sections={3}+ />) : loadError ? (<div className="cu-tb-form"><div className="cu-banner cu-banner--error" role="alert">diff --git a/control-ui/app/cost/token-budgets/page.tsx b/control-ui/app/cost/token-budgets/page.tsxindex 6e418fda7..af81f8786 100644--- a/control-ui/app/cost/token-budgets/page.tsx+++ b/control-ui/app/cost/token-budgets/page.tsx@@ -2,7 +2,6 @@import React, { useEffect, useState } from 'react'import { useRouter } from 'next/navigation'-import { useAuth } from '@components/AuthContext'import { useConfirmDialog } from '@components/ConfirmDialog'import { useToast } from '@components/Toast'import { TokenBudgetTable } from '@components/TokenBudgetTable'@@ -19,14 +18,13 @@ import {import type { BudgetScopeLookups } from '@lib/budgets'export default function TokenBudgetsPage() {- const { authState } = useAuth()const router = useRouter()const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()const [budgets, setBudgets] = useState<TokenBudget[]>([])const [lookups, setLookups] = useState<BudgetScopeLookups>({})- const [loading, setLoading] = useState(false)+ const [loading, setLoading] = useState(true)const [error, setError] = useState('')const [deletingId, setDeletingId] = useState<string | null>(null)const [togglingId, setTogglingId] = useState<string | null>(null)@@ -105,10 +103,8 @@ export default function TokenBudgetsPage() {}useEffect(() => {- if (authState.isLoggedIn && !authState.isLoading) {- void loadAll()- }- }, [authState.isLoggedIn, authState.isLoading])+ void loadAll()+ }, [])return (<>diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex 90c379468..4cffce381 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -4464,6 +4464,45 @@ textarea.cu-input {gap: var(--cu-space-3);}+.cu-body-loading-skeleton {+ display: grid;+ gap: var(--cu-space-5);+}++.cu-body-loading-skeleton__section {+ display: grid;+ gap: var(--cu-space-3);+}++.cu-body-loading-skeleton__heading {+ width: min(15rem, 45%);+ height: 1rem;+ border-radius: 4px;+}++.cu-body-loading-skeleton__line {+ width: min(34rem, 80%);+ height: 0.75rem;+ border-radius: 4px;+}++.cu-body-loading-skeleton__fields {+ display: grid;+ grid-template-columns: repeat(2, minmax(0, 1fr));+ gap: var(--cu-space-3);+}++.cu-body-loading-skeleton__field {+ height: 2.5rem;+ border-radius: var(--cu-radius-sm);+}++@media (max-width: 720px) {+ .cu-body-loading-skeleton__fields {+ grid-template-columns: 1fr;+ }+}+.cu-detail-content-stack > .cu-card:first-child {border-top: 0;border-top-left-radius: 0;@@ -8843,6 +8882,22 @@ textarea.cu-input {flex: 1;}+.cu-sidebar__item--loading {+ pointer-events: none;+}++.cu-sidebar__item--loading .cu-sidebar__icon {+ width: 1.1rem;+ height: 1.1rem;+ border-radius: 4px;+}++.cu-sidebar__item--loading .cu-sidebar__label {+ height: 0.75rem;+ max-width: 7.5rem;+ border-radius: 4px;+}+.cu-sidebar__footer {margin-top: auto;display: grid;diff --git a/control-ui/app/layout.tsx b/control-ui/app/layout.tsxindex fe6bacddd..680811df7 100644--- a/control-ui/app/layout.tsx+++ b/control-ui/app/layout.tsx@@ -4,6 +4,7 @@ import '@uiw/react-markdown-preview/markdown.css'import '@uiw/react-md-editor/markdown-editor.css'import { AdminBridgeAlerts } from '../components/AdminBridgeAlerts'import { AuthProvider } from '../components/AuthContext'+import { ControlAppFrame } from '../components/ControlAppFrame'import { ThemeProvider } from '../components/ThemeContext'import { ToastProvider } from '../components/Toast'import './globals.css'@@ -32,7 +33,7 @@ export default function RootLayout({ children }: { children: React.ReactNode })<ToastProvider><AuthProvider><AdminBridgeAlerts />- {children}+ <ControlAppFrame>{children}</ControlAppFrame></AuthProvider></ToastProvider></ThemeProvider>diff --git a/control-ui/app/llm-models/[id]/edit/page.tsx b/control-ui/app/llm-models/[id]/edit/page.tsxindex fdcc18a97..497d0d250 100644--- a/control-ui/app/llm-models/[id]/edit/page.tsx+++ b/control-ui/app/llm-models/[id]/edit/page.tsx@@ -3,6 +3,7 @@import React, { useEffect, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'@@ -94,9 +95,12 @@ export default function EditLlmModelPage() {}>{loading ? (- <div className="cu-px-form">- <div className="cu-create-content">Loading model...</div>- </div>+ <FormSectionsSkeleton+ className="cu-px-form"+ label="Allowed model"+ primaryActionLabel="Save model"+ sections={2}+ />) : loadError ? (<div className="cu-px-form"><div className="cu-banner cu-banner--error" role="alert">diff --git a/control-ui/app/llm-models/new/page.tsx b/control-ui/app/llm-models/new/page.tsxindex 99f40b348..2cc9b4502 100644--- a/control-ui/app/llm-models/new/page.tsx+++ b/control-ui/app/llm-models/new/page.tsx@@ -3,6 +3,7 @@import React, { Suspense, useState } from 'react'import { useRouter, useSearchParams } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { BodyLoadingSkeleton } from '@components/BodyLoadingSkeleton'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'@@ -83,7 +84,18 @@ function CreateLlmModelContent() {export default function CreateLlmModelPage() {return (- <Suspense fallback={null}>+ <Suspense+ fallback={+ <BodyLoadingSkeleton+ backLabel="Back to models"+ icon={<IconModels />}+ primaryActionLabel="Add model"+ sections={3}+ subtitle="Allow a provider/model so agents and runtime can select it."+ title="Add allowed model"+ />+ }+ ><CreateLlmModelContent /></Suspense>)diff --git a/control-ui/app/loading.tsx b/control-ui/app/loading.tsxdeleted file mode 100644index 81085949c..000000000--- a/control-ui/app/loading.tsx+++ /dev/null@@ -1,5 +0,0 @@-import { LoadingScreen } from '@components/LoadingScreen'--export default function Loading() {- return <LoadingScreen />-}diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsxindex 29330fefb..b7ba45e95 100644--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx@@ -3,6 +3,7 @@import React, { useCallback, useEffect, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'@@ -124,9 +125,12 @@ export default function EditMcpServerPage() {}>{loading ? (- <div className="cu-connector-edit-form">- <div className="cu-create-content">Loading connector...</div>- </div>+ <FormSectionsSkeleton+ className="cu-connector-edit-form"+ label="Connector"+ primaryActionLabel="Save egress"+ sections={3}+ />) : loadError ? (<div className="cu-connector-edit-form"><div className="cu-banner cu-banner--error" role="alert">diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsxindex 3ee79be3a..78daef225 100644--- a/control-ui/app/mcp-servers/page.tsx+++ b/control-ui/app/mcp-servers/page.tsx@@ -2,9 +2,7 @@import React, { useEffect, useState } from 'react'import { useRouter } from 'next/navigation'-import { LoadingScreen } from '@components/LoadingScreen'import { CONTROL_ROUTES } from '@constants/routes'-import { useAuth } from '../../components/AuthContext'import { useConfirmDialog } from '../../components/ConfirmDialog'import { DashboardLayout } from '../../components/DashboardLayout'import { McpServerTable } from '../../components/McpServerTable'@@ -23,7 +21,6 @@ import {isSilentApiError,} from '../../lib/api'import type { HostResource, McpServerResource } from '../../lib/api'-import { buildControlUiLoginPath, getCurrentControlUiPath } from '../../lib/authRedirect'function resourceName(resource: { metadata?: { name?: string } }): string {return resource.metadata?.name || 'unknown'@@ -102,10 +99,9 @@ async function loadContextAccess(}export default function McpServersPage() {- const { authState } = useAuth()const router = useRouter()const { showToast } = useToast()- const [loading, setLoading] = useState(false)+ const [loading, setLoading] = useState(true)const [error, setError] = useState('')const [mcpServers, setMcpServers] = useState<McpServerResource[]>([])const [accessByConnectorKey, setAccessByConnectorKey] = useState<ConnectorAccessSummaryMap>({})@@ -192,24 +188,8 @@ export default function McpServersPage() {}useEffect(() => {- if (authState.isLoggedIn && !authState.isLoading) {- void loadAll()- }- }, [authState.isLoggedIn, authState.isLoading])-- useEffect(() => {- if (!authState.isLoading && !authState.isLoggedIn) {- router.replace(buildControlUiLoginPath(getCurrentControlUiPath()))- }- }, [authState.isLoading, authState.isLoggedIn, router])-- if (authState.isLoading) {- return <LoadingScreen />- }-- if (!authState.isLoggedIn) {- return null- }+ void loadAll()+ }, [])return (<DashboardLayout>diff --git a/control-ui/app/plugin-workload-sdk/page.tsx b/control-ui/app/plugin-workload-sdk/page.tsxindex 7a556e24a..504dec436 100644--- a/control-ui/app/plugin-workload-sdk/page.tsx+++ b/control-ui/app/plugin-workload-sdk/page.tsx@@ -2,10 +2,8 @@import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useRouter } from 'next/navigation'-import { useAuth } from '@components/AuthContext'import { useConfirmDialog } from '@components/ConfirmDialog'import { DashboardLayout } from '@components/DashboardLayout'-import { LoadingScreen } from '@components/LoadingScreen'import { SectionSearchInput } from '@components/SectionSearchInput'import { SelectionDropdown } from '@components/SelectionDropdown'import { IconPluginSdk } from '@components/Sidebar/icons'@@ -29,7 +27,6 @@ import {searchPluginWorkloadSdkInvocations,upsertPluginWorkloadSdkGrant,} from '@lib/api'-import { buildControlUiLoginPath, getCurrentControlUiPath } from '@lib/authRedirect'import { useLlmAllowedModels } from '@lib/hooks/useLlmAllowedModels'import {LLM_PROVIDER_OPTIONS,@@ -123,14 +120,13 @@ async function fetchUsersByRefs(userRefs: string[]): Promise<AdminUser[]> {}export default function PluginWorkloadSdkPage() {- const { authState } = useAuth()const router = useRouter()const { confirm, confirmDialog } = useConfirmDialog()const { showToast } = useToast()const [view, setView] = useState<SdkView>('grants')const [grants, setGrants] = useState<PluginWorkloadSdkGrant[]>([])- const [grantsLoading, setGrantsLoading] = useState(false)+ const [grantsLoading, setGrantsLoading] = useState(true)const [grantsError, setGrantsError] = useState('')const [grantSearch, setGrantSearch] = useState('')const [deletingId, setDeletingId] = useState<string | null>(null)@@ -220,16 +216,9 @@ export default function PluginWorkloadSdkPage() {}, [filterRecipe, filterMethod, filterStatus])useEffect(() => {- if (!authState.isLoading && !authState.isLoggedIn) {- router.replace(buildControlUiLoginPath(getCurrentControlUiPath()))- }- }, [authState.isLoading, authState.isLoggedIn, router])-- useEffect(() => {- if (!authState.isLoggedIn || authState.isLoading) returnif (view === 'grants') void loadGrants()else void loadInvocations()- }, [authState.isLoggedIn, authState.isLoading, view, loadGrants, loadInvocations])+ }, [view, loadGrants, loadInvocations])async function handleDelete(grant: PluginWorkloadSdkGrant) {const shouldDelete = await confirm({@@ -260,11 +249,6 @@ export default function PluginWorkloadSdkPage() {await loadGrants()}- if (authState.isLoading) {- return <LoadingScreen />- }- if (!authState.isLoggedIn) return null-const normalizedGrantSearch = grantSearch.trim().toLowerCase()const filteredGrants = normalizedGrantSearch? grants.filter(g =>diff --git a/control-ui/app/registry/entries/[name]/[version]/edit/page.tsx b/control-ui/app/registry/entries/[name]/[version]/edit/page.tsxindex e81ac66bf..0dd7d9dca 100644--- a/control-ui/app/registry/entries/[name]/[version]/edit/page.tsx+++ b/control-ui/app/registry/entries/[name]/[version]/edit/page.tsx@@ -3,6 +3,7 @@import React, { useCallback, useEffect, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'@@ -142,9 +143,12 @@ export default function EditRegistryEntryPage() {}>{loading ? (- <div className="cu-create-content cu-registry-edit-form">- <div className="cu-muted">Loading entry…</div>- </div>+ <FormSectionsSkeleton+ className="cu-registry-edit-form"+ label="Marketplace entry"+ primaryActionLabel="Save changes"+ sections={3}+ />) : loadError ? (<div className="cu-create-content cu-registry-edit-form"><div className="cu-banner cu-banner--error">{loadError}</div>diff --git a/control-ui/app/registry/entries/[name]/[version]/loading.tsx b/control-ui/app/registry/entries/[name]/[version]/loading.tsxindex 934320b28..f37b5d8a9 100644--- a/control-ui/app/registry/entries/[name]/[version]/loading.tsx+++ b/control-ui/app/registry/entries/[name]/[version]/loading.tsx@@ -19,6 +19,16 @@ export default function RegistryEntryDetailLoading() {backLabel="Back to Marketplace"backDisabledonBack={() => undefined}+ titleActions={+ <>+ <button type="button" className="cu-btn cu-btn--primary cu-btn--sm" disabled>+ Install+ </button>+ <button type="button" className="cu-btn cu-btn--sm" disabled>+ Actions+ </button>+ </>+ }/>}>diff --git a/control-ui/app/registry/entries/[name]/[version]/page.tsx b/control-ui/app/registry/entries/[name]/[version]/page.tsxindex 8e7fc0fd3..0b10826ca 100644--- a/control-ui/app/registry/entries/[name]/[version]/page.tsx+++ b/control-ui/app/registry/entries/[name]/[version]/page.tsx@@ -7,7 +7,6 @@ import { useConfirmDialog } from '@components/ConfirmDialog'import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'-import { LoadingScreen } from '@components/LoadingScreen'import { RegistryEntryDetailSkeleton } from '@components/RegistryEntryDetailSkeleton'import { IconStore } from '@components/Sidebar/icons'import { useToast } from '@components/Toast'@@ -22,6 +21,7 @@ import {installRecipeFromRegistry,} from '@lib/api'import { trustBgColor, trustColor } from '@lib/trustLevel'+import RegistryEntryDetailLoading from './loading'export const dynamic = 'force-dynamic'@@ -112,7 +112,7 @@ function RegistryEntryActionsMenu({export default function RegistryEntryDetailPage() {return (- <Suspense fallback={<LoadingScreen />}>+ <Suspense fallback={<RegistryEntryDetailLoading />}><RegistryEntryDetailContent /></Suspense>)diff --git a/control-ui/app/registry/publish/page.tsx b/control-ui/app/registry/publish/page.tsxindex db088051d..b2c48b04e 100644--- a/control-ui/app/registry/publish/page.tsx+++ b/control-ui/app/registry/publish/page.tsx@@ -3,15 +3,17 @@import React, { Suspense } from 'react'import { useRouter, useSearchParams } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { CreateFlowLoadingScreen } from '@components/CreateFlowSkeleton'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'import { PublishToRegistryForm } from '@components/PublishToRegistryForm'import { IconStore } from '@components/Sidebar/icons'+import { CREATE_FLOW_LOADING } from '@constants/createFlowLoading'import { CONTROL_ROUTES } from '@constants/routes'export default function PublishRegistryPage() {return (- <Suspense fallback={null}>+ <Suspense fallback={<CreateFlowLoadingScreen {...CREATE_FLOW_LOADING.publishRegistryEntry} />}><PublishRegistryPageContent /></Suspense>)diff --git a/control-ui/app/secrets/recipe/[name]/edit/page.tsx b/control-ui/app/secrets/recipe/[name]/edit/page.tsxindex 6088f1509..55efa0531 100644--- a/control-ui/app/secrets/recipe/[name]/edit/page.tsx+++ b/control-ui/app/secrets/recipe/[name]/edit/page.tsx@@ -3,6 +3,7 @@import React, { Suspense, useEffect, useMemo, useState } from 'react'import { useParams, useRouter, useSearchParams } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { BodyLoadingSkeleton, FormSectionsSkeleton } from '@components/BodyLoadingSkeleton'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'import { IconKey } from '@components/Sidebar/icons'@@ -187,7 +188,11 @@ function EditRecipeSecretContent() {<div className="cu-create-panel"><div className="cu-create-content">{loading ? (- <div className="cu-banner cu-banner--info">Loading recipe secret…</div>+ <FormSectionsSkeleton+ label="Recipe secret"+ primaryActionLabel="Save secret"+ sections={2}+ />) : loadError ? (<div className="cu-banner cu-banner--error">{loadError}</div>) : notFound ? (@@ -362,7 +367,18 @@ function EditRecipeSecretContent() {export default function EditRecipeSecretPage() {return (- <Suspense fallback={<div>Loading…</div>}>+ <Suspense+ fallback={+ <BodyLoadingSkeleton+ backLabel="Back to secrets"+ icon={<IconKey />}+ primaryActionLabel="Save changes"+ sections={2}+ subtitle="Load the saved key metadata before editing stored values."+ title="Edit recipe secret"+ />+ }+ ><EditRecipeSecretContent /></Suspense>)diff --git a/control-ui/app/shared-filesystems/[name]/page.tsx b/control-ui/app/shared-filesystems/[name]/page.tsxindex 73e8cc4e9..525b694c7 100644--- a/control-ui/app/shared-filesystems/[name]/page.tsx+++ b/control-ui/app/shared-filesystems/[name]/page.tsx@@ -4,7 +4,6 @@ import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useParams, useRouter } from 'next/navigation'import { FileUploadModal } from '@components/FileUploadModal'import { CONTROL_ROUTES } from '@constants/routes'-import { useAuth } from '../../../components/AuthContext'import { useConfirmDialog } from '../../../components/ConfirmDialog'import { CreateFlowPanel } from '../../../components/CreateFlowPanel'import { CreatePageHeader } from '../../../components/CreatePageHeader'@@ -28,7 +27,6 @@ import {sfsOpenOrDownload,sfsUpload,} from '../../../lib/api'-import { buildControlUiLoginPath, getCurrentControlUiPath } from '../../../lib/authRedirect'const DELETE_ENTRY_REFRESH_DELAY_MS = 800const DELETE_ENTRY_REFRESH_ATTEMPTS = 4@@ -51,7 +49,6 @@ const FILE_COLUMNS: TableHeaderColumn[] = [export default function SharedFileSystemDetailsPage() {const params = useParams<{ name: string }>()const router = useRouter()- const { authState } = useAuth()const { showToast } = useToast()const sfsName = decodeURIComponent(params.name || '')@@ -133,22 +130,12 @@ export default function SharedFileSystemDetailsPage() {)useEffect(() => {- if (authState.isLoggedIn && !authState.isLoading) {- void loadMeta()- }- }, [authState.isLoggedIn, authState.isLoading, loadMeta])-- useEffect(() => {- if (!authState.isLoading && !authState.isLoggedIn) {- router.replace(buildControlUiLoginPath(getCurrentControlUiPath()))- }- }, [authState.isLoading, authState.isLoggedIn, router])+ void loadMeta()+ }, [loadMeta])useEffect(() => {- if (authState.isLoggedIn && !authState.isLoading) {- void loadEntries()- }- }, [authState.isLoggedIn, authState.isLoading, loadEntries])+ void loadEntries()+ }, [loadEntries])function joinPath(parent: string, child: string): string {if (!parent) return child@@ -329,7 +316,7 @@ export default function SharedFileSystemDetailsPage() {}}- if (authState.isLoading) {+ if (entriesLoading && !meta) {return (<DashboardLayout isDetailPage><CreateFlowPanel@@ -339,6 +326,7 @@ export default function SharedFileSystemDetailsPage() {icon={<IconFolder />}title={sfsName || 'Agent Files'}backLabel="Back to Agent Files"+ backDisabledonBack={() => router.push(CONTROL_ROUTES.agentFiles.root)}/>}@@ -356,6 +344,22 @@ export default function SharedFileSystemDetailsPage() {/>))}</div>+ <div className="cu-shared-files-detail__actions">+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--toolbar"+ aria-label="Refreshing files"+ disabled+ >+ <IconRefresh className="cu-spin" width={18} height={18} />+ </button>+ <button type="button" className="cu-btn cu-btn--ghost cu-btn--sm" disabled>+ New folder+ </button>+ <button type="button" className="cu-btn cu-btn--primary cu-btn--sm" disabled>+ Upload file+ </button>+ </div></div><div className="cu-table-wrap"><table className="cu-table">@@ -373,10 +377,6 @@ export default function SharedFileSystemDetailsPage() {)}- if (!authState.isLoggedIn) {- return null- }-const phase = meta?.status?.phaseconst capacityLabel = meta?.status?.capacity || meta?.spec?.size || '—'const storageClassLabel = meta?.status?.storageClassName || meta?.spec?.storageClassName || '—'diff --git a/control-ui/app/shared-filesystems/page.tsx b/control-ui/app/shared-filesystems/page.tsxindex 597e55b2a..11366a1bc 100644--- a/control-ui/app/shared-filesystems/page.tsx+++ b/control-ui/app/shared-filesystems/page.tsx@@ -2,7 +2,6 @@import React, { useCallback, useEffect, useRef, useState } from 'react'import { useRouter } from 'next/navigation'-import { useAuth } from '@components/AuthContext'import { DashboardLayout } from '@components/DashboardLayout'import { SectionSearchInput } from '@components/SectionSearchInput'import { IconSharedFiles } from '@components/Sidebar/icons'@@ -20,7 +19,6 @@ import {getSharedFileSystems,isSilentApiError,} from '@lib/api'-import { buildControlUiLoginPath, getCurrentControlUiPath } from '@lib/authRedirect'const SHARED_FILE_SYSTEM_COLUMNS: TableHeaderColumn[] = [{ key: 'name', label: 'Name' },@@ -44,10 +42,9 @@ const DELETE_REFRESH_ATTEMPTS = 6* NetworkPolicies in the background.*/export default function SharedFileSystemsPage() {- const { authState } = useAuth()const router = useRouter()const { showToast } = useToast()- const [loading, setLoading] = useState(false)+ const [loading, setLoading] = useState(true)const [error, setError] = useState('')const [items, setItems] = useState<SharedFileSystemResource[]>([])const [searchQuery, setSearchQuery] = useState('')@@ -118,16 +115,8 @@ export default function SharedFileSystemsPage() {}, [])useEffect(() => {- if (authState.isLoggedIn && !authState.isLoading) {- void load()- }- }, [authState.isLoggedIn, authState.isLoading, load])-- useEffect(() => {- if (!authState.isLoading && !authState.isLoggedIn) {- router.replace(buildControlUiLoginPath(getCurrentControlUiPath()))- }- }, [authState.isLoading, authState.isLoggedIn, router])+ void load()+ }, [load])async function handleDelete(name: string) {if (deletingNames.has(name)) return@@ -152,38 +141,6 @@ export default function SharedFileSystemsPage() {}}- if (authState.isLoading) {- return (- <DashboardLayout>- <div className="cu-card cu-card--viewport-fill">- <TablePanelHeader- title={- <>- <IconSharedFiles />- Agent Files- </>- }- subtitle="Workspace volumes that Contexts can mount read-only into agent pods."- />- <div className="cu-table-wrap">- <table className="cu-table cu-table--header-band">- <thead>- <TableHeaderRow columns={SHARED_FILE_SYSTEM_COLUMNS} />- </thead>- <tbody>- <SkeletonTableRows columns={SHARED_FILE_SYSTEM_COLUMNS.length} rows={5} />- </tbody>- </table>- </div>- </div>- </DashboardLayout>- )- }-- if (!authState.isLoggedIn) {- return null- }-const normalizedSearch = searchQuery.trim().toLowerCase()const filteredItems = normalizedSearch? items.filter(item => {@@ -261,67 +218,71 @@ export default function SharedFileSystemsPage() {<TableHeaderRow columns={SHARED_FILE_SYSTEM_COLUMNS} /></thead><tbody>- {filteredItems.map(item => {- const name = item.metadata?.name || ''- const isDeleting = deletingNames.has(name)- const status = item.status || {}- const mountedBy = status.mountedByContexts || []- const phase = status.phase || 'Unknown'- const phaseClass =- phase === 'Ready'- ? 'cu-badge cu-badge--ok'- : phase === 'Failed' || phase === 'Degraded'- ? 'cu-badge cu-badge--error'- : 'cu-badge'- return (- <tr- key={name}- className="cu-table__row cu-table__row--clickable"- onClick={() => {- if (!isDeleting) {- router.push(CONTROL_ROUTES.agentFiles.detail(name))- }- }}- onKeyDown={e => {- if (isDeleting) return- if (e.key === 'Enter' || e.key === ' ') {- e.preventDefault()- router.push(CONTROL_ROUTES.agentFiles.detail(name))- }- }}- tabIndex={0}- role="link"- aria-label={`Open shared filesystem ${name}`}- >- <td>- <span className="cu-link">{name}</span>- </td>- <td>- <span className={phaseClass}>{phase}</span>- </td>- <td>{status.capacity || item.spec?.size || '—'}</td>- <td>{status.storageClassName || item.spec?.storageClassName || '—'}</td>- <td>- {mountedBy.length === 0- ? '—'- : mountedBy.map(c => `${c.namespace}/${c.name}`).join(', ')}- </td>- <td style={{ textAlign: 'right' }} onClick={e => e.stopPropagation()}>- <button- type="button"- className="cu-btn cu-btn--icon cu-btn--danger-icon"- onClick={() => setDeleteTarget(name)}- disabled={isDeleting}- aria-label={- isDeleting ? `Deleting ${name}` : `Delete shared filesystem ${name}`+ {isInitialLoad ? (+ <SkeletonTableRows columns={SHARED_FILE_SYSTEM_COLUMNS.length} rows={5} />+ ) : (+ filteredItems.map(item => {+ const name = item.metadata?.name || ''+ const isDeleting = deletingNames.has(name)+ const status = item.status || {}+ const mountedBy = status.mountedByContexts || []+ const phase = status.phase || 'Unknown'+ const phaseClass =+ phase === 'Ready'+ ? 'cu-badge cu-badge--ok'+ : phase === 'Failed' || phase === 'Degraded'+ ? 'cu-badge cu-badge--error'+ : 'cu-badge'+ return (+ <tr+ key={name}+ className="cu-table__row cu-table__row--clickable"+ onClick={() => {+ if (!isDeleting) {+ router.push(CONTROL_ROUTES.agentFiles.detail(name))+ }+ }}+ onKeyDown={e => {+ if (isDeleting) return+ if (e.key === 'Enter' || e.key === ' ') {+ e.preventDefault()+ router.push(CONTROL_ROUTES.agentFiles.detail(name))}- >- <IconX width={16} height={16} />- </button>- </td>- </tr>- )- })}+ }}+ tabIndex={0}+ role="link"+ aria-label={`Open shared filesystem ${name}`}+ >+ <td>+ <span className="cu-link">{name}</span>+ </td>+ <td>+ <span className={phaseClass}>{phase}</span>+ </td>+ <td>{status.capacity || item.spec?.size || '—'}</td>+ <td>{status.storageClassName || item.spec?.storageClassName || '—'}</td>+ <td>+ {mountedBy.length === 0+ ? '—'+ : mountedBy.map(c => `${c.namespace}/${c.name}`).join(', ')}+ </td>+ <td style={{ textAlign: 'right' }} onClick={e => e.stopPropagation()}>+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--danger-icon"+ onClick={() => setDeleteTarget(name)}+ disabled={isDeleting}+ aria-label={+ isDeleting ? `Deleting ${name}` : `Delete shared filesystem ${name}`+ }+ >+ <IconX width={16} height={16} />+ </button>+ </td>+ </tr>+ )+ })+ )}</tbody></table></div>diff --git a/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx b/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsxindex 4140b19b1..a2357825a 100644--- a/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx+++ b/control-ui/app/workflow-recipes/[namespace]/[name]/page.tsx@@ -3,12 +3,12 @@import { Suspense, useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useParams, useRouter, useSearchParams } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { BodyLoadingSkeleton } from '@components/BodyLoadingSkeleton'import { useConfirmDialog } from '@components/ConfirmDialog'import { CreateFlowSkeleton } from '@components/CreateFlowSkeleton'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'import { DetailPageShell } from '@components/DetailPageShell'-import { LoadingScreen } from '@components/LoadingScreen'import { RecipeEditor } from '@components/RecipeEditor'import { RecipeIntegrationsPanel } from '@components/RecipeIntegrationsPanel'import { RecipeSecretsPanel } from '@components/RecipeSecretsPanel'@@ -298,7 +298,29 @@ export const dynamic = 'force-dynamic'export default function WorkflowRecipeDetailPage() {return (- <Suspense fallback={<LoadingScreen />}>+ <Suspense+ fallback={+ <BodyLoadingSkeleton+ backLabel="Back to plugins"+ icon={<IconWorkflow />}+ primaryActionLabel="Run"+ secondaryActionLabel="Actions"+ sections={3}+ subtitle="Plugin details and runtime status."+ title="Plugin"+ titleActions={+ <>+ <button type="button" className="cu-btn cu-btn--primary cu-btn--sm" disabled>+ Run+ </button>+ <button type="button" className="cu-btn cu-btn--sm" disabled>+ Actions+ </button>+ </>+ }+ />+ }+ ><WorkflowRecipeDetailContent /></Suspense>)diff --git a/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsx b/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsxindex 95c07baeb..cd8315c4a 100644--- a/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsx+++ b/control-ui/app/workflow-recipes/[namespace]/[name]/runs/[runId]/page.tsx@@ -4,9 +4,9 @@ import { Suspense } from 'react'import Link from 'next/link'import { useParams, useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'+import { BodyLoadingSkeleton } from '@components/BodyLoadingSkeleton'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'-import { LoadingScreen } from '@components/LoadingScreen'import { RecipeStatusContent } from '@components/RecipeStatusContent'import { IconWorkflow } from '@components/Sidebar/icons'import { CONTROL_ROUTES } from '@constants/routes'@@ -16,7 +16,18 @@ export const dynamic = 'force-dynamic'export default function WorkflowRunDetailPage() {return (- <Suspense fallback={<LoadingScreen />}>+ <Suspense+ fallback={+ <BodyLoadingSkeleton+ backLabel="Back to plugin"+ icon={<IconWorkflow />}+ primaryActionLabel="Open governed trace replay"+ sections={3}+ subtitle="Plugin run status, outputs, artifacts, and access."+ title="Plugin run"+ />+ }+ ><WorkflowRunDetailContent /></Suspense>)diff --git a/control-ui/app/workflow-recipes/page.tsx b/control-ui/app/workflow-recipes/page.tsxindex b9a94dd45..faf73db71 100644--- a/control-ui/app/workflow-recipes/page.tsx+++ b/control-ui/app/workflow-recipes/page.tsx@@ -2,32 +2,42 @@import { Suspense, useEffect, useRef, useState } from 'react'import { useRouter, useSearchParams } from 'next/navigation'-import { useAuth } from '@components/AuthContext'import { CreateFlowSkeleton } from '@components/CreateFlowSkeleton'import { CreatePageHeader } from '@components/CreatePageHeader'import { DashboardLayout } from '@components/DashboardLayout'-import { LoadingScreen } from '@components/LoadingScreen'import { RecipeEditor } from '@components/RecipeEditor'import { RecipesTab } from '@components/RecipesTab'import { IconWorkflow } from '@components/Sidebar/icons'import { CREATE_FLOW_LOADING } from '@constants/createFlowLoading'import { CONTROL_ROUTES } from '@constants/routes'import { isSilentApiError } from '@lib/api'-import { buildControlUiLoginPath, getCurrentControlUiPath } from '@lib/authRedirect'import { useRecipePolling } from '@lib/hooks/useRecipePolling'export const dynamic = 'force-dynamic'export default function WorkflowRecipesPage() {return (- <Suspense fallback={<LoadingScreen />}>+ <Suspense fallback={<WorkflowRecipesLoading />}><WorkflowRecipesPageContent /></Suspense>)}+function WorkflowRecipesLoading() {+ return (+ <DashboardLayout>+ <RecipesTab+ items={[]}+ loading+ error=""+ onInstall={() => undefined}+ onRefresh={() => undefined}+ />+ </DashboardLayout>+ )+}+function WorkflowRecipesPageContent() {- const { authState } = useAuth()const router = useRouter()const searchParams = useSearchParams()@@ -36,7 +46,7 @@ function WorkflowRecipesPageContent() {const [installerStarting, setInstallerStarting] = useState(false)const installerTimerRef = useRef<number | null>(null)const { recipes, loading, error, refresh } = useRecipePolling({- enabled: authState.isLoggedIn && !authState.isLoading,+ enabled: true,onError: fetchError => {if (!isSilentApiError(fetchError)) returnsetPageError('')@@ -47,7 +57,6 @@ function WorkflowRecipesPageContent() {// Legacy registry deep links now route through the registry install preview// so operators can review default-deny/public-web/exact-host egress first.useEffect(() => {- if (!authState.isLoggedIn) returnconst entry = searchParams.get('registry')const version = searchParams.get('version')if (!entry || !version) return@@ -55,13 +64,7 @@ function WorkflowRecipesPageContent() {params.set('entry', entry)params.set('version', version)router.replace(CONTROL_ROUTES.marketplace.install(Object.fromEntries(params)))- }, [authState.isLoggedIn, searchParams, router])-- useEffect(() => {- if (!authState.isLoading && !authState.isLoggedIn) {- router.replace(buildControlUiLoginPath(getCurrentControlUiPath()))- }- }, [authState.isLoading, authState.isLoggedIn, router])+ }, [searchParams, router])useEffect(() => {if (!installerStarting) return@@ -80,14 +83,6 @@ function WorkflowRecipesPageContent() {}}, [installerStarting])- if (authState.isLoading) {- return <LoadingScreen />- }-- if (!authState.isLoggedIn) {- return null- }-return (<DashboardLayout isDetailPage={installerOpen || installerStarting}>{installerStarting ? (diff --git a/control-ui/components/AuthContext.tsx b/control-ui/components/AuthContext.tsxindex d30f48015..b7dd6e27c 100644--- a/control-ui/components/AuthContext.tsx+++ b/control-ui/components/AuthContext.tsx@@ -1,6 +1,14 @@'use client'-import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'+import React, {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react'import { useRouter } from 'next/navigation'import { CONTROL_ROUTES } from '@constants/routes'import {@@ -12,6 +20,7 @@ import {setGlobalAuthErrorHandler,} from '../lib/api'import { buildControlUiLoginPath, getCurrentControlUiPath } from '../lib/authRedirect'+import { resetPublishScopeCache } from '../lib/hooks/usePublishScope'import { useToast } from './Toast'type AuthState = {@@ -47,6 +56,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {// this singleton registration tied to them if either provider is remounted.useEffect(() => {const handleAuthError = () => {+ resetPublishScopeCache()setAuthState({ id: '', isLoggedIn: false, isLoading: false, username: '', email: '' })router.replace(buildControlUiLoginPath(getCurrentControlUiPath()))if (sessionExpiredToastShownRef.current) return@@ -84,6 +94,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {const login = useCallback(async (username: string, password: string): Promise<AdminLoginResponse> => {const result = await loginControlUI(username, password)+ resetPublishScopeCache()sessionExpiredToastShownRef.current = falsesetAuthState({id: result.me.id,@@ -101,17 +112,19 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {try {await logoutControlUI()} finally {+ resetPublishScopeCache(authState.id)sessionExpiredToastShownRef.current = falsesetAuthState({ id: '', isLoggedIn: false, isLoading: false, username: '', email: '' })router.replace(CONTROL_ROUTES.login)}- }, [router])+ }, [authState.id, router])- return (- <AuthContext.Provider value={{ authState, login, logout, checkAuth }}>- {children}- </AuthContext.Provider>+ const value = useMemo(+ () => ({ authState, login, logout, checkAuth }),+ [authState, checkAuth, login, logout])++ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>}export function useAuth() {diff --git a/control-ui/components/AuthGate/index.tsx b/control-ui/components/AuthGate/index.tsxindex b8808a512..472d4d3f8 100644--- a/control-ui/components/AuthGate/index.tsx+++ b/control-ui/components/AuthGate/index.tsx@@ -1,13 +1,22 @@'use client'-import { useEffect } from 'react'+import { createContext, useContext, useEffect } from 'react'import { useRouter } from 'next/navigation'import { useAuth } from '@components/AuthContext'import { LoadingScreen } from '@components/LoadingScreen'import { buildControlUiLoginPath, getCurrentControlUiPath } from '@lib/authRedirect'import type { AuthGateProps } from './types'+const AuthGateContext = createContext(false)+export function AuthGate({ children }: AuthGateProps) {+ const isInsideAuthGate = useContext(AuthGateContext)+ if (isInsideAuthGate) return <>{children}</>++ return <AuthGateBoundary>{children}</AuthGateBoundary>+}++function AuthGateBoundary({ children }: AuthGateProps) {const { authState } = useAuth()const router = useRouter()@@ -25,5 +34,5 @@ export function AuthGate({ children }: AuthGateProps) {return null}- return <>{children}</>+ return <AuthGateContext.Provider value>{children}</AuthGateContext.Provider>}diff --git a/control-ui/components/BodyLoadingSkeleton/index.tsx b/control-ui/components/BodyLoadingSkeleton/index.tsxnew file mode 100644index 000000000..7d915a869--- /dev/null+++ b/control-ui/components/BodyLoadingSkeleton/index.tsx@@ -0,0 +1,103 @@+'use client'++import type { ReactNode } from 'react'+import { CreateFlowPanel } from '@components/CreateFlowPanel'+import { CreatePageHeader } from '@components/CreatePageHeader'+import { DashboardLayout } from '@components/DashboardLayout'+import { cn } from '@lib/cn'++type FormSectionsSkeletonProps = {+ className?: string+ label: string+ primaryActionLabel: string+ secondaryActionLabel?: string+ sections?: number+}++type BodyLoadingSkeletonProps = {+ backLabel: string+ icon: ReactNode+ primaryActionLabel: string+ secondaryActionLabel?: string+ sections?: number+ subtitle: string+ title: string+ titleActions?: ReactNode+}++export function FormSectionsSkeleton({+ className,+ label,+ primaryActionLabel,+ secondaryActionLabel = 'Cancel',+ sections = 2,+}: FormSectionsSkeletonProps) {+ return (+ <div+ className={cn('cu-create-content cu-body-loading-skeleton', className)}+ role="status"+ aria-label={`${label} loading`}+ aria-busy="true"+ >+ {Array.from({ length: sections }, (_, sectionIndex) => (+ <section className="cu-body-loading-skeleton__section" key={sectionIndex}>+ <span className="cu-skeleton cu-body-loading-skeleton__heading" />+ <span className="cu-skeleton cu-body-loading-skeleton__line" />+ <div className="cu-body-loading-skeleton__fields">+ <span className="cu-skeleton cu-body-loading-skeleton__field" />+ <span className="cu-skeleton cu-body-loading-skeleton__field" />+ </div>+ </section>+ ))}+ <div className="cu-create-actions">+ <button type="button" className="cu-btn cu-btn--ghost" disabled>+ {secondaryActionLabel}+ </button>+ <button type="button" className="cu-btn cu-btn--primary" disabled>+ {primaryActionLabel}+ </button>+ </div>+ </div>+ )+}++export function BodyLoadingSkeleton({+ backLabel,+ icon,+ primaryActionLabel,+ secondaryActionLabel = 'Cancel',+ sections = 2,+ subtitle,+ title,+ titleActions,+}: BodyLoadingSkeletonProps) {+ return (+ <DashboardLayout isDetailPage>+ <CreateFlowPanel+ className="cu-detail-flow-panel"+ header={+ <CreatePageHeader+ icon={icon}+ title={title}+ subtitle={subtitle}+ backLabel={backLabel}+ backDisabled+ onBack={() => undefined}+ titleActions={titleActions}+ />+ }+ >+ {null}+ </CreateFlowPanel>+ <div className="cu-card">+ <FormSectionsSkeleton+ className="cu-card__body"+ label={title}+ primaryActionLabel={primaryActionLabel}+ secondaryActionLabel={secondaryActionLabel}+ sections={sections}+ />+ </div>+ </DashboardLayout>+ )+}diff --git a/control-ui/components/ControlAppFrame.tsx b/control-ui/components/ControlAppFrame.tsxnew file mode 100644index 000000000..1980428b1--- /dev/null+++ b/control-ui/components/ControlAppFrame.tsx@@ -0,0 +1,26 @@+'use client'++import type { ReactNode } from 'react'+import { usePathname } from 'next/navigation'+import { isPublicControlUiPath } from '@lib/controlAppFrame'+import { PublishScopeProvider } from '@lib/hooks/usePublishScope'+import { useAuth } from './AuthContext'+import { AuthGate } from './AuthGate'+import { DashboardLayout } from './DashboardLayout'++export function ControlAppFrame({ children }: { children: ReactNode }) {+ const pathname = usePathname()+ const { authState } = useAuth()++ if (isPublicControlUiPath(pathname)) {+ return <>{children}</>+ }++ return (+ <AuthGate>+ <PublishScopeProvider cacheKey={authState.id}>+ <DashboardLayout>{children}</DashboardLayout>+ </PublishScopeProvider>+ </AuthGate>+ )+}diff --git a/control-ui/components/CreateFlowSkeleton/index.tsx b/control-ui/components/CreateFlowSkeleton/index.tsxindex fed26e3ad..4b86568e1 100644--- a/control-ui/components/CreateFlowSkeleton/index.tsx+++ b/control-ui/components/CreateFlowSkeleton/index.tsx@@ -13,6 +13,8 @@ export function CreateFlowSkeleton({className,iconKey,onBack = () => {},+ primaryActionLabel = 'Continue',+ secondaryActionLabel = 'Cancel',stepFlowClassName,steps,subtitle,@@ -36,6 +38,7 @@ export function CreateFlowSkeleton({className={cn('cu-agent-create-wizard cu-agent-create-skeleton', stepFlowClassName)}aria-label={`${title} loading`}aria-busy="true"+ role="status"><aside className="cu-agent-step-rail" aria-hidden="true">{steps.map((label, index) => (@@ -71,8 +74,12 @@ export function CreateFlowSkeleton({</div></div><div className="cu-agent-create-skeleton__actions">- <span className="cu-skeleton cu-agent-create-skeleton__button" />- <span className="cu-skeleton cu-agent-create-skeleton__button" />+ <button type="button" className="cu-btn cu-btn--ghost" disabled>+ {secondaryActionLabel}+ </button>+ <button type="button" className="cu-btn cu-btn--primary" disabled>+ {primaryActionLabel}+ </button></div></section></div>diff --git a/control-ui/components/CreateFlowSkeleton/types.ts b/control-ui/components/CreateFlowSkeleton/types.tsindex 910fd4446..277ae697e 100644--- a/control-ui/components/CreateFlowSkeleton/types.ts+++ b/control-ui/components/CreateFlowSkeleton/types.ts@@ -13,6 +13,8 @@ export type CreateFlowIconKey =export type CreateFlowLoadingConfig = {backLabel: stringiconKey: CreateFlowIconKey+ primaryActionLabel?: string+ secondaryActionLabel?: stringstepFlowClassName?: stringsteps: readonly string[]subtitle: stringdiff --git a/control-ui/components/DashboardLayout.tsx b/control-ui/components/DashboardLayout.tsxindex 0f37f63e9..206f30e63 100644--- a/control-ui/components/DashboardLayout.tsx+++ b/control-ui/components/DashboardLayout.tsx@@ -1,6 +1,13 @@'use client'-import React, { useMemo, useState } from 'react'+import React, {+ createContext,+ useCallback,+ useContext,+ useLayoutEffect,+ useMemo,+ useState,+} from 'react'import { usePathname } from 'next/navigation'import { CONTROL_ROUTES, isControlRouteSection } from '@constants/routes'import { useAuth } from './AuthContext'@@ -13,10 +20,50 @@ interface DashboardLayoutProps {isDetailPage?: boolean}+type DashboardFrameContextValue = {+ setDetailPage: (isDetailPage: boolean) => void+}++const DashboardFrameContext = createContext<DashboardFrameContextValue | null>(null)+export function DashboardLayout({ children, isDetailPage = false }: DashboardLayoutProps) {+ const frame = useContext(DashboardFrameContext)++ if (frame) {+ return (+ <NestedDashboardContent isDetailPage={isDetailPage} setDetailPage={frame.setDetailPage}>+ {children}+ </NestedDashboardContent>+ )+ }++ return <PersistentDashboardFrame>{children}</PersistentDashboardFrame>+}++function NestedDashboardContent({+ children,+ isDetailPage,+ setDetailPage,+}: DashboardLayoutProps & DashboardFrameContextValue) {+ useLayoutEffect(() => {+ setDetailPage(isDetailPage)+ return () => setDetailPage(false)+ }, [isDetailPage, setDetailPage])++ return <>{children}</>+}++function PersistentDashboardFrame({ children }: Pick<DashboardLayoutProps, 'children'>) {const pathname = usePathname()const { logout } = useAuth()const [menuOpen, setMenuOpen] = useState(false)+ const [isDetailPage, setIsDetailPage] = useState(false)++ const setDetailPage = useCallback((nextIsDetailPage: boolean) => {+ setIsDetailPage(nextIsDetailPage)+ }, [])++ const frameValue = useMemo(() => ({ setDetailPage }), [setDetailPage])const currentTab = useMemo<SidebarTab>(() => {if (isControlRouteSection(pathname, CONTROL_ROUTES.agents.root)) {@@ -87,7 +134,11 @@ export function DashboardLayout({ children, isDetailPage = false }: DashboardLayonNavigate={() => setMenuOpen(false)}onLogout={handleLogout}/>- <main className={isDetailPage ? 'cu-main cu-detail-layout' : 'cu-main'}>{children}</main>+ <main className={`cu-main${isDetailPage ? ' cu-detail-layout' : ''}`}>+ <DashboardFrameContext.Provider value={frameValue}>+ {children}+ </DashboardFrameContext.Provider>+ </main></div>)}diff --git a/control-ui/components/PublishToRegistryForm.tsx b/control-ui/components/PublishToRegistryForm.tsxindex 65f749194..c76c93a5c 100644--- a/control-ui/components/PublishToRegistryForm.tsx+++ b/control-ui/components/PublishToRegistryForm.tsx@@ -2,6 +2,7 @@import React, { useCallback, useEffect, useState } from 'react'import type { ReactNode } from 'react'+import Link from 'next/link'import { CONTROL_ROUTES } from '@constants/routes'import { getPublishScope, publishToRegistry } from '../lib/api'import type { PublishScope } from '../lib/api'@@ -587,7 +588,7 @@ export function PublishToRegistryForm({</p><p className="cu-field__hint">Need a key to publish from CI or a script?{' '}- <a href={CONTROL_ROUTES.marketplace.keys}>Manage API keys →</a>+ <Link href={CONTROL_ROUTES.marketplace.keys}>Manage API keys →</Link></p></div>))}diff --git a/control-ui/components/PublisherView/GrantedToMe.tsx b/control-ui/components/PublisherView/GrantedToMe.tsxindex 6c4817b7e..e6f6baa4e 100644--- a/control-ui/components/PublisherView/GrantedToMe.tsx+++ b/control-ui/components/PublisherView/GrantedToMe.tsx@@ -1,5 +1,6 @@'use client'+import Link from 'next/link'import { CONTROL_ROUTES } from '@constants/routes'import type { GrantedToMeItem } from '../../lib/api'import type { InboundGrantsStatus } from '../../lib/hooks/useInboundGrants'@@ -38,8 +39,8 @@ export function GrantedToMe({return (<p className="cu-banner cu-banner--warn">Plugins shared with your org appear in your{' '}- <a href={CONTROL_ROUTES.marketplace.root}>Marketplace catalog</a> and can be installed from- there.+ <Link href={CONTROL_ROUTES.marketplace.root}>Marketplace catalog</Link> and can be installed+ from there.</p>)}diff --git a/control-ui/components/RecipeEditor.tsx b/control-ui/components/RecipeEditor.tsxindex e479fa2ed..8264d6676 100644--- a/control-ui/components/RecipeEditor.tsx+++ b/control-ui/components/RecipeEditor.tsx@@ -2,6 +2,7 @@import React, { useCallback, useEffect, useMemo, useState } from 'react'import type { ReactNode } from 'react'+import Link from 'next/link'import { CONTROL_ROUTES } from '@constants/routes'import { useToast } from '@/components/Toast'import { Button } from '@/components/ui'@@ -2267,7 +2268,7 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)(ns: {secret.targetNamespaces.join(', ')})</span>{isEdit ? (- <a+ <Linkhref={CONTROL_ROUTES.secrets.editRecipe(secret.secretName)}style={{marginLeft: 12,@@ -2276,7 +2277,7 @@ export function RecipeEditor({ initial, onSaved, onCancel, pageHeader }: Props)}}>Edit stored values →- </a>+ </Link>) : (<spanstyle={{diff --git a/control-ui/components/RegistryApiKeysPanel.tsx b/control-ui/components/RegistryApiKeysPanel.tsxindex b6ebaf1ed..6136e748d 100644--- a/control-ui/components/RegistryApiKeysPanel.tsx+++ b/control-ui/components/RegistryApiKeysPanel.tsx@@ -1,6 +1,7 @@'use client'import { useCallback, useEffect, useState } from 'react'+import Link from 'next/link'import { CONTROL_ROUTES } from '@constants/routes'import {type CreateRegistryApiKeyInput,@@ -155,8 +156,7 @@ export default function RegistryApiKeysPanel() {) : null}{view.kind === 'no-org' ? (<p className="cu-banner cu-banner--warn">- This deployment is not bound to a registry org, so there are no org API keys to- manage.+ This deployment is not bound to a registry org, so there are no org API keys to manage.</p>) : null}{view.kind === 'auth-disabled' ? (@@ -170,7 +170,7 @@ export default function RegistryApiKeysPanel() {) : (<>API keys become available once this deployment is connected to the registry.{' '}- <a href={CONTROL_ROUTES.marketplace.connect}>Connect to Evenfire Registry</a>.+ <Link href={CONTROL_ROUTES.marketplace.connect}>Connect to Evenfire Registry</Link>.</>)}</p>diff --git a/control-ui/components/Sidebar/index.tsx b/control-ui/components/Sidebar/index.tsxindex 4782df5f6..d09593961 100644--- a/control-ui/components/Sidebar/index.tsx+++ b/control-ui/components/Sidebar/index.tsx@@ -14,7 +14,7 @@ import type { SidebarItem, SidebarProps, SidebarTab } from './types'export function Sidebar({ currentTab, isOpen = false, onNavigate, onLogout }: SidebarProps) {const pathname = usePathname()- const { scope } = usePublishScope()+ const { scope, loading: publishScopeLoading } = usePublishScope()const publisherEnabled = isPublisherEnabled(scope)const [expandedGroups, setExpandedGroups] = useState<Set<SidebarTab>>(() => new Set(SIDEBAR_TABS[currentTab].children?.length ? [currentTab] : [])@@ -22,7 +22,9 @@ export function Sidebar({ currentTab, isOpen = false, onNavigate, onLogout }: Siconst entries = (Object.entries(SIDEBAR_TABS) as Array<[SidebarTab, SidebarItem]>).filter(([tabKey, item]) =>- !item.hidden && tabKey !== 'settings' && (tabKey !== 'publisher' || publisherEnabled)+ !item.hidden &&+ tabKey !== 'settings' &&+ (tabKey !== 'publisher' || publisherEnabled || publishScopeLoading)).sort(([, first], [, second]) => first.label.localeCompare(second.label))const settings = SIDEBAR_TABS.settings@@ -60,6 +62,18 @@ export function Sidebar({ currentTab, isOpen = false, onNavigate, onLogout }: Si</div><nav className="cu-sidebar__nav" aria-label="Main sections">{entries.map(([tabKey, item]) => {+ if (tabKey === 'publisher' && publishScopeLoading) {+ return (+ <div+ key={tabKey}+ className="cu-sidebar__item cu-sidebar__item--loading"+ aria-hidden="true"+ >+ <span className="cu-sidebar__icon cu-skeleton" />+ <span className="cu-sidebar__label cu-skeleton" />+ </div>+ )+ }const active = currentTab === tabKeyconst expanded = expandedGroups.has(tabKey)if (item.children?.length) {diff --git a/control-ui/components/__tests__/BodyLoadingSkeleton.test.tsx b/control-ui/components/__tests__/BodyLoadingSkeleton.test.tsxnew file mode 100644index 000000000..8a5801199--- /dev/null+++ b/control-ui/components/__tests__/BodyLoadingSkeleton.test.tsx@@ -0,0 +1,44 @@+import type React from 'react'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { cleanup, render, screen } from '@testing-library/react'+import { BodyLoadingSkeleton, FormSectionsSkeleton } from '../BodyLoadingSkeleton'++vi.mock('../DashboardLayout', () => ({+ DashboardLayout: ({ children }: { children: React.ReactNode }) => <>{children}</>,+}))++afterEach(cleanup)++describe('BodyLoadingSkeleton', () => {+ it('keeps page chrome visible and disables actions while body sections load', () => {+ const view = render(+ <BodyLoadingSkeleton+ backLabel="Back to models"+ icon={<span>icon</span>}+ primaryActionLabel="Save model"+ sections={3}+ subtitle="Update the model configuration."+ title="Edit allowed model"+ />+ )++ expect(screen.getByRole('heading', { name: 'Edit allowed model' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'Back to models' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'Cancel' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'Save model' })).toBeDisabled()+ expect(screen.getByRole('status', { name: 'Edit allowed model loading' })).toHaveAttribute(+ 'aria-busy',+ 'true'+ )+ expect(view.container.querySelectorAll('.cu-body-loading-skeleton__section')).toHaveLength(3)+ })++ it('renders content-only form skeletons without replacing the page header', () => {+ const view = render(+ <FormSectionsSkeleton label="Connector" primaryActionLabel="Save egress" sections={2} />+ )++ expect(screen.getByRole('button', { name: 'Save egress' })).toBeDisabled()+ expect(view.container.querySelectorAll('.cu-body-loading-skeleton__section')).toHaveLength(2)+ })+})diff --git a/control-ui/components/__tests__/DashboardLayout.persistence.test.tsx b/control-ui/components/__tests__/DashboardLayout.persistence.test.tsxnew file mode 100644index 000000000..abbafcd79--- /dev/null+++ b/control-ui/components/__tests__/DashboardLayout.persistence.test.tsx@@ -0,0 +1,58 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import { cleanup, render, screen } from '@testing-library/react'+import { DashboardLayout } from '../DashboardLayout'++const navigationState = vi.hoisted(() => ({ pathname: '/agents' }))++vi.mock('next/navigation', () => ({+ usePathname: () => navigationState.pathname,+}))++vi.mock('../AuthContext', () => ({+ useAuth: () => ({ logout: vi.fn() }),+}))++vi.mock('../MobileHeader', () => ({+ MobileHeader: () => <header data-testid="mobile-header" />,+}))++vi.mock('../Sidebar', () => ({+ Sidebar: ({ currentTab }: { currentTab: string }) => (+ <aside data-testid="persistent-sidebar" data-current-tab={currentTab} />+ ),+}))++afterEach(() => {+ cleanup()+ navigationState.pathname = '/agents'+})++describe('DashboardLayout persistence', () => {+ it('keeps the application shell mounted across child route changes', () => {+ const view = render(+ <DashboardLayout>+ <DashboardLayout isDetailPage>+ <div>Agent detail</div>+ </DashboardLayout>+ </DashboardLayout>+ )+ const sidebar = screen.getByTestId('persistent-sidebar')+ const main = sidebar.parentElement?.querySelector('main')++ expect(sidebar).toHaveAttribute('data-current-tab', 'hosts')+ expect(main).toHaveClass('cu-detail-layout')++ navigationState.pathname = '/settings/ui'+ view.rerender(+ <DashboardLayout>+ <DashboardLayout>+ <div>Settings</div>+ </DashboardLayout>+ </DashboardLayout>+ )++ expect(screen.getByTestId('persistent-sidebar')).toBe(sidebar)+ expect(sidebar).toHaveAttribute('data-current-tab', 'settings')+ expect(main).not.toHaveClass('cu-detail-layout')+ })+})diff --git a/control-ui/components/__tests__/TokenBudgetErrorToasts.test.tsx b/control-ui/components/__tests__/TokenBudgetErrorToasts.test.tsxindex da9570cfa..fed1e6db5 100644--- a/control-ui/components/__tests__/TokenBudgetErrorToasts.test.tsx+++ b/control-ui/components/__tests__/TokenBudgetErrorToasts.test.tsx@@ -139,8 +139,8 @@ describe('structured budget/price errors surface an error toast', () => {render(<EditLlmPricePage />)// Wait for the loaded price form, then submit.- const saveButton = await screen.findByRole('button', { name: 'Save price' })- fireEvent.click(saveButton)+ await waitFor(() => expect(screen.getByRole('button', { name: 'Save price' })).toBeEnabled())+ fireEvent.click(screen.getByRole('button', { name: 'Save price' }))await waitFor(() => {expect(mockShowToast).toHaveBeenCalledWith(expect.stringContaining('used by 1 budget'), {diff --git a/control-ui/e2e/qa-recorder-navigation.spec.ts b/control-ui/e2e/qa-recorder-navigation.spec.tsindex f5ea1b626..20b95827a 100644--- a/control-ui/e2e/qa-recorder-navigation.spec.ts+++ b/control-ui/e2e/qa-recorder-navigation.spec.ts@@ -29,6 +29,18 @@ test.describe('optional QA recorder: Control UI navigation', () => {// The sidebar's primary nav region. 'Settings' lives in the footer outside// this region, so it is targeted with a global locator below.const mainNav = page.getByRole('navigation', { name: 'Main sections' })+ const sidebar = page.locator('.cu-sidebar')+ await expect(sidebar).toHaveCount(1)+ const sidebarElement = await sidebar.elementHandle()+ if (!sidebarElement) throw new Error('Control UI sidebar did not mount')++ async function expectPersistentSidebar() {+ expect(+ await sidebarElement.evaluate(+ element => element.isConnected && element === document.querySelector('.cu-sidebar')+ )+ ).toBe(true)+ }// 1) Agents — sidebar href is /agents, which next.config rewrites to the// /hosts page (the browser URL is not stable across rewrites), so assert@@ -37,6 +49,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {await expect(page.getByText('Manage available agents and their host mappings.', { exact: true })).toBeVisible({ timeout: 20_000 })+ await expectPersistentSidebar()await screenshotAndLog(page, testInfo, 'control-ui-navigation-agents')// 2) Contexts — /contexts is a real App Router segment; URL is stable.@@ -45,6 +58,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {await expect(page.getByText('Group connectors into reusable access scopes.', { exact: true })).toBeVisible({ timeout: 20_000 })+ await expectPersistentSidebar()await screenshotAndLog(page, testInfo, 'control-ui-navigation-contexts')// 3) Connectors — sidebar href is /connectors (rewritten from /mcp-servers);@@ -54,6 +68,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {await expect(page.getByText('Browse connector deployments and context bindings.', { exact: true })).toBeVisible({ timeout: 20_000 })+ await expectPersistentSidebar()await screenshotAndLog(page, testInfo, 'control-ui-navigation-connectors')// 4) External Channels — sidebar href is /external-channels (rewritten from@@ -63,6 +78,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {await expect(page.getByText('Route channel messages to the selected agent.', { exact: true })).toBeVisible({ timeout: 20_000 })+ await expectPersistentSidebar()await screenshotAndLog(page, testInfo, 'control-ui-navigation-external-channels')// 5) LLM Models — Catalog and Discovery Review share one tabbed operator@@ -73,6 +89,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {await expect(page.getByText('The authoritative allowlist of manual and discovered models')).toBeVisible({ timeout: 20_000 })+ await expectPersistentSidebar()await screenshotAndLog(page, testInfo, 'control-ui-navigation-llm-models')// 6) Users & Teams — sidebar href is /users-and-teams/users (rewritten from@@ -85,6 +102,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {{ exact: true })).toBeVisible({ timeout: 20_000 })+ await expectPersistentSidebar()await screenshotAndLog(page, testInfo, 'control-ui-navigation-users-teams')// 7) Settings — rendered in the sidebar FOOTER (outside 'Main sections').@@ -96,6 +114,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {await expect(page.getByText('Manage your Control UI admin account and theme.')).toBeVisible({timeout: 20_000,})+ await expectPersistentSidebar()await screenshotAndLog(page, testInfo, 'control-ui-navigation-settings')})})diff --git a/control-ui/lib/__tests__/controlAppFrame.test.ts b/control-ui/lib/__tests__/controlAppFrame.test.tsnew file mode 100644index 000000000..dfeab8644--- /dev/null+++ b/control-ui/lib/__tests__/controlAppFrame.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest'+import { isPublicControlUiPath } from '../controlAppFrame'++describe('isPublicControlUiPath', () => {+ it.each([+ '/',+ '/admin-email-confirmations/token',+ '/admin-invitations/token',+ '/admin-password-resets/token',+ ])('keeps %s outside the authenticated application frame', pathname => {+ expect(isPublicControlUiPath(pathname)).toBe(true)+ })++ it.each(['/agents', '/settings/ui', '/registry', '/profile-admin/users'])(+ 'keeps %s inside the authenticated application frame',+ pathname => {+ expect(isPublicControlUiPath(pathname)).toBe(false)+ }+ )+})diff --git a/control-ui/lib/controlAppFrame.ts b/control-ui/lib/controlAppFrame.tsnew file mode 100644index 000000000..420c2ab01--- /dev/null+++ b/control-ui/lib/controlAppFrame.ts@@ -0,0 +1,10 @@+const PUBLIC_CONTROL_UI_PREFIXES = [+ '/admin-email-confirmations/',+ '/admin-invitations/',+ '/admin-password-resets/',+] as const++export function isPublicControlUiPath(pathname: string): boolean {+ if (pathname === '/') return true+ return PUBLIC_CONTROL_UI_PREFIXES.some(prefix => pathname.startsWith(prefix))+}diff --git a/control-ui/lib/hooks/__tests__/usePublishScope.test.tsx b/control-ui/lib/hooks/__tests__/usePublishScope.test.tsxindex 5eccfb69f..18454ea45 100644--- a/control-ui/lib/hooks/__tests__/usePublishScope.test.tsx+++ b/control-ui/lib/hooks/__tests__/usePublishScope.test.tsx@@ -1,7 +1,12 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, render, screen, waitFor } from '@testing-library/react'import * as api from '../../api'-import { isPublisherEnabled, usePublishScope } from '../usePublishScope'+import {+ PublishScopeProvider,+ isPublisherEnabled,+ resetPublishScopeCache,+ usePublishScope,+} from '../usePublishScope'vi.mock('../../api', async orig => {const actual = await orig<typeof import('../../api')>()@@ -17,8 +22,15 @@ function Probe() {)}+function renderWithProvider(children: React.ReactNode = <Probe />) {+ return render(<PublishScopeProvider cacheKey="admin-1">{children}</PublishScopeProvider>)+}+afterEach(cleanup)-beforeEach(() => vi.clearAllMocks())+beforeEach(() => {+ vi.clearAllMocks()+ resetPublishScopeCache()+})describe('usePublishScope / isPublisherEnabled', () => {it('isPublisherEnabled: org-bound non-curator → true', () => {@@ -66,7 +78,7 @@ describe('usePublishScope / isPublisherEnabled', () => {curator: false,orgName: 'Acme',})- render(<Probe />)+ renderWithProvider()expect(await screen.findByText('enabled')).toBeInTheDocument()})@@ -74,7 +86,34 @@ describe('usePublishScope / isPublisherEnabled', () => {vi.mocked(api.getPublishScope).mockRejectedValue(Object.assign(new Error('boom'), { status: 500 }))- render(<Probe />)+ renderWithProvider()await waitFor(() => expect(screen.getByText('error')).toBeInTheDocument())})++ it('shares one request across consumers and child route changes', async () => {+ vi.mocked(api.getPublishScope).mockResolvedValue({+ scope: 'acme',+ curator: false,+ orgName: 'Acme',+ })++ const view = renderWithProvider(+ <>+ <Probe />+ <Probe />+ </>+ )+ expect(await screen.findAllByText('enabled')).toHaveLength(2)++ view.rerender(+ <PublishScopeProvider cacheKey="admin-1">+ <div data-testid="next-route">+ <Probe />+ </div>+ </PublishScopeProvider>+ )++ expect(await screen.findByTestId('next-route')).toBeInTheDocument()+ expect(api.getPublishScope).toHaveBeenCalledTimes(1)+ })})diff --git a/control-ui/lib/hooks/usePublishScope.ts b/control-ui/lib/hooks/usePublishScope.tsindex 203f088bb..119905dcc 100644--- a/control-ui/lib/hooks/usePublishScope.ts+++ b/control-ui/lib/hooks/usePublishScope.ts@@ -1,6 +1,7 @@'use client'-import { useEffect, useState } from 'react'+import type { ReactNode } from 'react'+import { createContext, createElement, useContext, useEffect, useMemo, useState } from 'react'import { type PublishScope, getPublishScope, isSilentApiError } from '../api'export type PublishScopeState = {@@ -9,35 +10,96 @@ export type PublishScopeState = {error: boolean}-/**- * Resolve the caller's registry publish scope once on mount. Used to gate the- * Publisher sidebar entry and view. Fails CLOSED: while loading, on a hard- * error, or on a curator / org-unbound scope, the Publisher surface stays- * hidden. A silent 401 (session expiry) is left to the global auth handler.- */-export function usePublishScope(): PublishScopeState {- const [state, setState] = useState<PublishScopeState>({- scope: null,- loading: true,- error: false,- })+const EMPTY_STATE: PublishScopeState = {+ scope: null,+ loading: true,+ error: false,+}++const PublishScopeContext = createContext<PublishScopeState | null>(null)+const resolvedScopes = new Map<string, PublishScope>()+const pendingScopes = new Map<string, Promise<PublishScope>>()++function requestPublishScope(cacheKey: string): Promise<PublishScope> {+ const resolved = resolvedScopes.get(cacheKey)+ if (resolved) return Promise.resolve(resolved)++ const pending = pendingScopes.get(cacheKey)+ if (pending) return pending++ const request = getPublishScope()+ .then(scope => {+ resolvedScopes.set(cacheKey, scope)+ return scope+ })+ .finally(() => {+ pendingScopes.delete(cacheKey)+ })+ pendingScopes.set(cacheKey, request)+ return request+}++export function resetPublishScopeCache(cacheKey?: string): void {+ if (cacheKey) {+ resolvedScopes.delete(cacheKey)+ pendingScopes.delete(cacheKey)+ return+ }+ resolvedScopes.clear()+ pendingScopes.clear()+}++export function PublishScopeProvider({+ cacheKey,+ children,+}: {+ cacheKey: string+ children: ReactNode+}) {+ const cachedScope = cacheKey ? resolvedScopes.get(cacheKey) : undefined+ const [state, setState] = useState<PublishScopeState>(() =>+ cachedScope ? { scope: cachedScope, loading: false, error: false } : EMPTY_STATE+ )useEffect(() => {let cancelled = false- getPublishScope()+ if (!cacheKey) {+ setState(EMPTY_STATE)+ return+ }++ const nextCachedScope = resolvedScopes.get(cacheKey)+ if (nextCachedScope) {+ setState({ scope: nextCachedScope, loading: false, error: false })+ return+ }++ setState(EMPTY_STATE)+ void requestPublishScope(cacheKey).then(scope => {if (!cancelled) setState({ scope, loading: false, error: false })})- .catch(err => {- if (cancelled || isSilentApiError(err)) return+ .catch(error => {+ if (cancelled || isSilentApiError(error)) returnsetState({ scope: null, loading: false, error: true })})+return () => {cancelled = true}- }, [])+ }, [cacheKey])- return state+ const value = useMemo(() => state, [state])+ return createElement(PublishScopeContext.Provider, { value }, children)+}++/**+ * Read the persistent caller scope shared by the sidebar and Publisher views.+ * It fails closed while loading or when the provider reports an error.+ */+export function usePublishScope(): PublishScopeState {+ const state = useContext(PublishScopeContext)+ return state ?? EMPTY_STATE}/**diff --git a/profile-ui/app/approval-channels/page.tsx b/profile-ui/app/approval-channels/page.tsxindex 5f45f6fc1..cad743dbc 100644--- a/profile-ui/app/approval-channels/page.tsx+++ b/profile-ui/app/approval-channels/page.tsx@@ -4,6 +4,8 @@ import { useEffect, useMemo, useState } from 'react'import { useRouter } from 'next/navigation'import { AuthGate } from '@components/AuthGate'import { Button } from '@components/Button'+import { useProfileAccess } from '@components/ProfileAccessContext'+import { ProfileBodySkeleton } from '@components/ProfileBodySkeleton'import { ProfileShell } from '@components/ProfileShell'import { SelectControl } from '@components/SelectControl'import { useToast } from '@components/Toast'@@ -17,27 +19,13 @@ import {} from '@lib/api'import {activeApprovalAccounts,- listApprovalChannelTargets,listWorkflowApprovalMediums,preferredAccountOptionLabel,} from '@lib/approvalChannels'-import type {- ApprovalChannelTarget,- WorkflowApprovalMediumAccount,-} from '@/app/types/approvalChannels'+import type { WorkflowApprovalMediumAccount } from '@/app/types/approvalChannels'import type { Me, NotificationPreferences } from '@/app/types/profile'-type LoadState = 'idle' | 'loading' | 'ready' | 'error'--function LoadingSkeleton() {- return (- <div className="profile-skeleton" role="status" aria-label="Loading">- <span className="profile-skeleton__line profile-skeleton__line--medium" />- <span className="profile-skeleton__line" />- <span className="profile-skeleton__line profile-skeleton__line--short" />- </div>- )-}+type LoadState = 'loading' | 'ready' | 'error'function settingsPathForMedium(medium: string): string {if (medium === 'slack') return PROFILE_ROUTES.settings.social('slack')@@ -48,11 +36,11 @@ function settingsPathForMedium(medium: string): string {function ApprovalChannelsContent() {const router = useRouter()const { showToast } = useToast()+ const { approvalTargets: targets, refreshApprovalTargets } = useProfileAccess()const [me, setMe] = useState<Me | null>(null)const [accounts, setAccounts] = useState<WorkflowApprovalMediumAccount[]>([])- const [targets, setTargets] = useState<ApprovalChannelTarget[]>([])const [preferences, setPreferences] = useState<NotificationPreferences | null>(null)- const [state, setState] = useState<LoadState>('idle')+ const [state, setState] = useState<LoadState>('loading')const [busy, setBusy] = useState(false)const [error, setError] = useState('')@@ -66,18 +54,17 @@ function ApprovalChannelsContent() {const selectedAccount = activeAccounts.find(account => account.id === selectedPreferredAccountId)const manageMedium = selectedAccount?.medium || activeAccounts[0]?.medium || 'telegram'- async function loadAll() {+ async function loadAll(forceAccess = false) {setState('loading')setError('')try {- const [current, nextTargets, nextAccounts, nextPreferences] = await Promise.all([+ const [current, , nextAccounts, nextPreferences] = await Promise.all([getMe() as Promise<Me>,- listApprovalChannelTargets(),+ refreshApprovalTargets({ force: forceAccess }),listWorkflowApprovalMediums(),getNotificationPreferences(),])setMe(current)- setTargets(nextTargets)setAccounts(nextAccounts)setPreferences(nextPreferences)setState('ready')@@ -138,7 +125,7 @@ function ApprovalChannelsContent() {<Buttonvariant="secondary"className="cu-btn--icon cu-btn--toolbar"- onClick={loadAll}+ onClick={() => void loadAll(true)}disabled={busy || state === 'loading'}aria-label={state === 'loading' ? 'Refreshing approval channels' : 'Refresh approval channels'@@ -149,7 +136,12 @@ function ApprovalChannelsContent() {</div></header>- {state === 'loading' ? <LoadingSkeleton /> : null}+ {state === 'loading' ? (+ <ProfileBodySkeleton+ label="Loading approval channels"+ sections={[{ title: 'Preferred approval channel', actions: ['Manage'], rows: 3 }]}+ />+ ) : null}{error ? <div className="message message--error">{error}</div> : null}{state !== 'loading' && preferences && targets.length > 0 ? (diff --git a/profile-ui/app/components/AuthContext/index.tsx b/profile-ui/app/components/AuthContext/index.tsxindex d43bca51b..a2a38ba88 100644--- a/profile-ui/app/components/AuthContext/index.tsx+++ b/profile-ui/app/components/AuthContext/index.tsx@@ -1,6 +1,14 @@'use client'-import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react'+import React, {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+} from 'react'import {clearToken,getMe,@@ -9,6 +17,7 @@ import {logoutProfileUI,setGlobalAuthErrorHandler,} from '@lib/api'+import { resetProfileAccessCache } from '@lib/profileAccess'import type { PasswordLoginResponse } from '@/app/types/api'import type { Me } from '@/app/types/profile'import type { AuthContextValue, AuthState } from './types'@@ -65,6 +74,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {setGlobalAuthErrorHandler(() => {if (sessionExpiredHandledRef.current) returnsessionExpiredHandledRef.current = true+ resetProfileAccessCache()setAuthState({ isLoggedIn: false, isLoading: false, me: null })})}, [])@@ -76,6 +86,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {const login = useCallback(async (email: string, password: string) => {try {const result = await loginWithPassword(email, password)+ resetProfileAccessCache()const current = await getMe().catch(error => {return meFromPasswordLoginResponse(result.me)})@@ -95,15 +106,17 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {const logout = useCallback(() => {sessionExpiredHandledRef.current = false+ resetProfileAccessCache(authState.me?.id)void logoutProfileUI()setAuthState({ isLoggedIn: false, isLoading: false, me: null })- }, [])+ }, [authState.me?.id])- return (- <AuthContext.Provider value={{ authState, login, logout, checkAuth }}>- {children}- </AuthContext.Provider>+ const value = useMemo(+ () => ({ authState, login, logout, checkAuth }),+ [authState, checkAuth, login, logout])++ return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>}export function useAuth() {diff --git a/profile-ui/app/components/AuthGate/index.tsx b/profile-ui/app/components/AuthGate/index.tsxindex bc77be944..0df2faa22 100644--- a/profile-ui/app/components/AuthGate/index.tsx+++ b/profile-ui/app/components/AuthGate/index.tsx@@ -1,10 +1,20 @@'use client'+import { createContext, useContext } from 'react'import { useAuth } from '@components/AuthContext'import { LoginPanel } from '@components/LoginPanel'import type { AuthGateProps } from './types'+const AuthGateContext = createContext(false)+export function AuthGate({ children }: AuthGateProps) {+ const isInsideAuthGate = useContext(AuthGateContext)+ if (isInsideAuthGate) return <>{children}</>++ return <AuthGateBoundary>{children}</AuthGateBoundary>+}++function AuthGateBoundary({ children }: AuthGateProps) {const { authState } = useAuth()if (authState.isLoading) {@@ -21,5 +31,5 @@ export function AuthGate({ children }: AuthGateProps) {return <LoginPanel />}- return <>{children}</>+ return <AuthGateContext.Provider value>{children}</AuthGateContext.Provider>}diff --git a/profile-ui/app/components/ProfileAccessContext/index.tsx b/profile-ui/app/components/ProfileAccessContext/index.tsxnew file mode 100644index 000000000..2c4d1bf0f--- /dev/null+++ b/profile-ui/app/components/ProfileAccessContext/index.tsx@@ -0,0 +1,127 @@+'use client'++import type { ReactNode } from 'react'+import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react'+import { useAuth } from '@components/AuthContext'+import { isSilentApiError } from '@lib/api'+import {+ readProfileAccessCache,+ requestApprovalTargets,+ requestManageableTeams,+} from '@lib/profileAccess'+import type { ApprovalChannelTarget } from '@/app/types/approvalChannels'+import type { ManageableTeam } from '@/app/types/profile'++type RefreshOptions = { force?: boolean }++type ProfileAccessContextValue = {+ approvalTargets: ApprovalChannelTarget[]+ approvalTargetsError: boolean+ approvalTargetsLoading: boolean+ canManageMembers: boolean+ manageableTeams: ManageableTeam[]+ manageableTeamsError: boolean+ manageableTeamsLoading: boolean+ refreshApprovalTargets: (options?: RefreshOptions) => Promise<ApprovalChannelTarget[]>+ refreshManageableTeams: (options?: RefreshOptions) => Promise<ManageableTeam[]>+}++const ProfileAccessContext = createContext<ProfileAccessContextValue | null>(null)++export function ProfileAccessProvider({ children }: { children: ReactNode }) {+ const { authState } = useAuth()+ const userId = authState.me?.id || ''+ const cached = readProfileAccessCache(userId)+ const [manageableTeams, setManageableTeams] = useState<ManageableTeam[]>(+ () => cached.manageableTeams ?? []+ )+ const [approvalTargets, setApprovalTargets] = useState<ApprovalChannelTarget[]>(+ () => cached.approvalTargets ?? []+ )+ const [manageableTeamsLoading, setManageableTeamsLoading] = useState(+ () => !cached.manageableTeams+ )+ const [approvalTargetsLoading, setApprovalTargetsLoading] = useState(+ () => !cached.approvalTargets+ )+ const [manageableTeamsError, setManageableTeamsError] = useState(false)+ const [approvalTargetsError, setApprovalTargetsError] = useState(false)++ const refreshManageableTeams = useCallback(+ async (options: RefreshOptions = {}) => {+ if (!userId) return []+ setManageableTeamsLoading(true)+ setManageableTeamsError(false)+ try {+ const teams = await requestManageableTeams(userId, options)+ setManageableTeams(teams)+ return teams+ } catch (error) {+ if (!isSilentApiError(error)) setManageableTeamsError(true)+ throw error+ } finally {+ setManageableTeamsLoading(false)+ }+ },+ [userId]+ )++ const refreshApprovalTargets = useCallback(+ async (options: RefreshOptions = {}) => {+ if (!userId) return []+ setApprovalTargetsLoading(true)+ setApprovalTargetsError(false)+ try {+ const targets = await requestApprovalTargets(userId, options)+ setApprovalTargets(targets)+ return targets+ } catch (error) {+ if (!isSilentApiError(error)) setApprovalTargetsError(true)+ throw error+ } finally {+ setApprovalTargetsLoading(false)+ }+ },+ [userId]+ )++ useEffect(() => {+ if (!userId) return+ void refreshManageableTeams().catch(() => undefined)+ void refreshApprovalTargets().catch(() => undefined)+ }, [refreshApprovalTargets, refreshManageableTeams, userId])++ const activeRoleCanManage = authState.me?.role === 'admin' || authState.me?.role === 'inviter'+ const value = useMemo<ProfileAccessContextValue>(+ () => ({+ approvalTargets,+ approvalTargetsError,+ approvalTargetsLoading,+ canManageMembers: activeRoleCanManage || manageableTeams.length > 0,+ manageableTeams,+ manageableTeamsError,+ manageableTeamsLoading,+ refreshApprovalTargets,+ refreshManageableTeams,+ }),+ [+ activeRoleCanManage,+ approvalTargets,+ approvalTargetsError,+ approvalTargetsLoading,+ manageableTeams,+ manageableTeamsError,+ manageableTeamsLoading,+ refreshApprovalTargets,+ refreshManageableTeams,+ ]+ )++ return <ProfileAccessContext.Provider value={value}>{children}</ProfileAccessContext.Provider>+}++export function useProfileAccess(): ProfileAccessContextValue {+ const value = useContext(ProfileAccessContext)+ if (!value) throw new Error('useProfileAccess must be used within a ProfileAccessProvider')+ return value+}diff --git a/profile-ui/app/components/ProfileAppFrame/index.tsx b/profile-ui/app/components/ProfileAppFrame/index.tsxnew file mode 100644index 000000000..3d9d14300--- /dev/null+++ b/profile-ui/app/components/ProfileAppFrame/index.tsx@@ -0,0 +1,24 @@+'use client'++import type { ReactNode } from 'react'+import { usePathname } from 'next/navigation'+import { AuthGate } from '@components/AuthGate'+import { ProfileAccessProvider } from '@components/ProfileAccessContext'+import { ProfileShell } from '@components/ProfileShell'+import { isPublicProfileUiPath } from '@lib/profileAppFrame'++export function ProfileAppFrame({ children }: { children: ReactNode }) {+ const pathname = usePathname()++ if (isPublicProfileUiPath(pathname)) {+ return <>{children}</>+ }++ return (+ <AuthGate>+ <ProfileAccessProvider>+ <ProfileShell>{children}</ProfileShell>+ </ProfileAccessProvider>+ </AuthGate>+ )+}diff --git a/profile-ui/app/components/ProfileBodySkeleton/index.tsx b/profile-ui/app/components/ProfileBodySkeleton/index.tsxnew file mode 100644index 000000000..6587c07e0--- /dev/null+++ b/profile-ui/app/components/ProfileBodySkeleton/index.tsx@@ -0,0 +1,43 @@+type ProfileBodySkeletonSection = {+ actions?: string[]+ rows?: number+ title: string+}++export function ProfileBodySkeleton({+ label,+ sections,+}: {+ label: string+ sections: ProfileBodySkeletonSection[]+}) {+ return (+ <div className="profile-body-skeleton" role="status" aria-label={label} aria-busy="true">+ {sections.map(section => (+ <section className="section" key={section.title}>+ <div className="settings-section-head">+ <h2 className="section-title">{section.title}</h2>+ {section.actions?.length ? (+ <div className="toolbar">+ {section.actions.map(action => (+ <button type="button" className="cu-btn" disabled key={action}>+ {action}+ </button>+ ))}+ </div>+ ) : null}+ </div>+ <div className="profile-skeleton">+ {Array.from({ length: section.rows ?? 3 }, (_, index) => (+ <div className="profile-skeleton__row" key={index}>+ <span className="profile-skeleton__line profile-skeleton__line--medium" />+ <span className="profile-skeleton__line" />+ <span className="profile-skeleton__line profile-skeleton__line--short" />+ </div>+ ))}+ </div>+ </section>+ ))}+ </div>+ )+}diff --git a/profile-ui/app/components/ProfileShell/index.tsx b/profile-ui/app/components/ProfileShell/index.tsxindex def1b48e3..dfc0e0b07 100644--- a/profile-ui/app/components/ProfileShell/index.tsx+++ b/profile-ui/app/components/ProfileShell/index.tsx@@ -1,17 +1,29 @@'use client'-import { useState } from 'react'-import { useRouter } from 'next/navigation'+import { createContext, useContext, useState } from 'react'+import { usePathname, useRouter } from 'next/navigation'import { useAuth } from '@components/AuthContext'import { MobileHeader } from '@components/MobileHeader'import { Sidebar } from '@components/Sidebar'import { PROFILE_ROUTES } from '@constants/routes'+import { profileRouteForPathname } from '@lib/profileAppFrame'import type { ProfileShellProps } from './types'-export function ProfileShell({ currentRoute, children }: ProfileShellProps) {+const ProfileShellContext = createContext(false)++export function ProfileShell({ children }: ProfileShellProps) {+ const isInsideProfileShell = useContext(ProfileShellContext)+ if (isInsideProfileShell) return <>{children}</>++ return <PersistentProfileShell>{children}</PersistentProfileShell>+}++function PersistentProfileShell({ children }: ProfileShellProps) {const router = useRouter()+ const pathname = usePathname()const { logout } = useAuth()const [menuOpen, setMenuOpen] = useState(false)+ const currentRoute = profileRouteForPathname(pathname)function handleLogout() {logout()@@ -31,7 +43,9 @@ export function ProfileShell({ currentRoute, children }: ProfileShellProps) {onNavigate={() => setMenuOpen(false)}onLogout={handleLogout}/>- <main className="cu-main">{children}</main>+ <main className="cu-main">+ <ProfileShellContext.Provider value>{children}</ProfileShellContext.Provider>+ </main></div>)}diff --git a/profile-ui/app/components/ProfileShell/types.ts b/profile-ui/app/components/ProfileShell/types.tsindex 5c11a1f46..baf13e8f6 100644--- a/profile-ui/app/components/ProfileShell/types.ts+++ b/profile-ui/app/components/ProfileShell/types.ts@@ -1,7 +1,7 @@import type { ReactNode } from 'react'-import type { ProfileRouteKey } from '@components/Sidebar/types'+import type { ProfileRouteKey } from '@lib/profileAppFrame'export type ProfileShellProps = {- currentRoute: ProfileRouteKey+ currentRoute?: ProfileRouteKeychildren: ReactNode}diff --git a/profile-ui/app/components/Sidebar/index.tsx b/profile-ui/app/components/Sidebar/index.tsxindex 0b751b27f..7458ca4ca 100644--- a/profile-ui/app/components/Sidebar/index.tsx+++ b/profile-ui/app/components/Sidebar/index.tsx@@ -1,157 +1,22 @@'use client'-import { useEffect, useState } from 'react'import Image from 'next/image'import Link from 'next/link'-import { useAuth } from '@components/AuthContext'-import { getManageableTeams, isSilentApiError } from '@lib/api'-import { listApprovalChannelTargets } from '@lib/approvalChannels'+import { useProfileAccess } from '@components/ProfileAccessContext'import packageJson from '../../../package.json'import { PROFILE_SIDEBAR_ITEMS } from './constants'import { IconLogout } from './icons'import type { ProfileRouteKey, ProfileSidebarItem, SidebarProps } from './types'-const MEMBER_ROUTE_ACCESS_CACHE_PREFIX = 'profile-ui.member-route-access.'-const APPROVAL_CHANNEL_ACCESS_CACHE_PREFIX = 'profile-ui.approval-channel-access.'--function memberRouteAccessCacheKey(userId: string): string {- return `${MEMBER_ROUTE_ACCESS_CACHE_PREFIX}${userId}`-}--function approvalChannelAccessCacheKey(userId: string): string {- return `${APPROVAL_CHANNEL_ACCESS_CACHE_PREFIX}${userId}`-}--function readCachedBoolean(key: string): boolean | null {- if (!key || typeof window === 'undefined') return null- try {- const value = window.sessionStorage.getItem(key)- if (value === 'true') return true- if (value === 'false') return false- } catch {- return null- }- return null-}--function readCachedMemberRouteAccess(userId: string): boolean | null {- if (!userId) return null- return readCachedBoolean(memberRouteAccessCacheKey(userId))-}--function readCachedApprovalChannelAccess(userId: string): boolean | null {- if (!userId) return null- return readCachedBoolean(approvalChannelAccessCacheKey(userId))-}--function writeCachedBoolean(key: string, allowed: boolean): void {- if (!key || typeof window === 'undefined') return- try {- window.sessionStorage.setItem(key, String(allowed))- } catch {- // Ignore private-mode or storage quota failures; the API result still drives this render.- }-}--function writeCachedMemberRouteAccess(userId: string, allowed: boolean): void {- if (!userId) return- writeCachedBoolean(memberRouteAccessCacheKey(userId), allowed)-}--function writeCachedApprovalChannelAccess(userId: string, allowed: boolean): void {- if (!userId) return- writeCachedBoolean(approvalChannelAccessCacheKey(userId), allowed)-}-export function Sidebar({ currentRoute, isOpen = false, onNavigate, onLogout }: SidebarProps) {- const { authState } = useAuth()- const userId = authState.me?.id || ''- const activeRoleCanManage = authState.me?.role === 'admin' || authState.me?.role === 'inviter'- const [hasManageableTeams, setHasManageableTeams] = useState(- () => readCachedMemberRouteAccess(userId) ?? false- )- const [hasExternalChannelAccess, setHasExternalChannelAccess] = useState(- () => readCachedApprovalChannelAccess(userId) ?? false- )- const canManageMembers = activeRoleCanManage || hasManageableTeams-- useEffect(() => {- let cancelled = false- if (!authState.isLoggedIn || !userId) {- setHasManageableTeams(false)- return- }-- const cachedAccess = readCachedMemberRouteAccess(userId)- if (cachedAccess !== null) {- setHasManageableTeams(cachedAccess)- } else {- setHasManageableTeams(false)- }-- if (activeRoleCanManage) {- writeCachedMemberRouteAccess(userId, true)- setHasManageableTeams(true)- return- }-- void getManageableTeams()- .then(response => {- if (cancelled) return- const allowed = Boolean(response.items?.length)- writeCachedMemberRouteAccess(userId, allowed)- setHasManageableTeams(allowed)- })- .catch(error => {- if (!cancelled && !isSilentApiError(error)) {- writeCachedMemberRouteAccess(userId, false)- setHasManageableTeams(false)- }- })- return () => {- cancelled = true- }- }, [activeRoleCanManage, authState.isLoggedIn, userId])-- useEffect(() => {- let cancelled = false- if (!authState.isLoggedIn || !userId) {- setHasExternalChannelAccess(false)- return- }- const cachedAccess = readCachedApprovalChannelAccess(userId)- if (cachedAccess !== null) {- setHasExternalChannelAccess(cachedAccess)- }- void listApprovalChannelTargets()- .then(items => {- if (!cancelled) {- const allowed = items.length > 0- writeCachedApprovalChannelAccess(userId, allowed)- setHasExternalChannelAccess(allowed)- }- })- .catch(error => {- if (!cancelled && !isSilentApiError(error)) {- if (cachedAccess === true) return- writeCachedApprovalChannelAccess(userId, false)- setHasExternalChannelAccess(false)- }- })- return () => {- cancelled = true- }- }, [authState.isLoggedIn, userId])+ const { approvalTargets, approvalTargetsLoading, canManageMembers, manageableTeamsLoading } =+ useProfileAccess()+ const hasExternalChannelAccess = approvalTargets.length > 0const navigationItems = (Object.entries(PROFILE_SIDEBAR_ITEMS) as Array<[ProfileRouteKey, ProfileSidebarItem]>)- .filter(- ([routeKey]) =>- routeKey !== 'settings' &&- (routeKey !== 'members' || canManageMembers) &&- (routeKey !== 'approvalChannels' || hasExternalChannelAccess)- )+ .filter(([routeKey]) => routeKey !== 'settings').sort(([, first], [, second]) => first.label.localeCompare(second.label))const settings = PROFILE_SIDEBAR_ITEMS.settings@@ -175,19 +40,42 @@ export function Sidebar({ currentRoute, isOpen = false, onNavigate, onLogout }:</div></div><nav className="cu-sidebar__nav" aria-label="Main sections">- {navigationItems.map(([routeKey, item]) => (- <Link- key={routeKey}- href={item.href}- className="cu-sidebar__item"- data-active={currentRoute === routeKey ? 'true' : 'false'}- aria-current={currentRoute === routeKey ? 'page' : undefined}- onClick={onNavigate}- >- <span className="cu-sidebar__icon">{item.icon}</span>- <span className="cu-sidebar__label">{item.label}</span>- </Link>- ))}+ {navigationItems.map(([routeKey, item]) => {+ const accessLoading =+ (routeKey === 'members' && manageableTeamsLoading && !canManageMembers) ||+ (routeKey === 'approvalChannels' && approvalTargetsLoading)+ const accessDenied =+ (routeKey === 'members' && !canManageMembers) ||+ (routeKey === 'approvalChannels' && !hasExternalChannelAccess)++ if (accessLoading) {+ return (+ <div+ key={routeKey}+ className="cu-sidebar__item cu-sidebar__item--loading"+ aria-hidden="true"+ >+ <span className="cu-sidebar__icon cu-skeleton" />+ <span className="cu-sidebar__label cu-skeleton" />+ </div>+ )+ }+ if (accessDenied) return null++ return (+ <Link+ key={routeKey}+ href={item.href}+ className="cu-sidebar__item"+ data-active={currentRoute === routeKey ? 'true' : 'false'}+ aria-current={currentRoute === routeKey ? 'page' : undefined}+ onClick={onNavigate}+ >+ <span className="cu-sidebar__icon">{item.icon}</span>+ <span className="cu-sidebar__label">{item.label}</span>+ </Link>+ )+ })}</nav><div className="cu-sidebar__footer"><Linkdiff --git a/profile-ui/app/components/Sidebar/types.ts b/profile-ui/app/components/Sidebar/types.tsindex a2bec3df3..392073017 100644--- a/profile-ui/app/components/Sidebar/types.ts+++ b/profile-ui/app/components/Sidebar/types.ts@@ -1,11 +1,7 @@import type { ReactNode } from 'react'+import type { ProfileRouteKey } from '@lib/profileAppFrame'-export type ProfileRouteKey =- | 'home'- | 'members'- | 'approvalChannels'- | 'connectedAccounts'- | 'settings'+export type { ProfileRouteKey } from '@lib/profileAppFrame'export type ProfileSidebarItem = {label: stringdiff --git a/profile-ui/app/connected-accounts/page.tsx b/profile-ui/app/connected-accounts/page.tsxindex cb6183faf..449be2120 100644--- a/profile-ui/app/connected-accounts/page.tsx+++ b/profile-ui/app/connected-accounts/page.tsx@@ -3,13 +3,14 @@import { useEffect, useState } from 'react'import { AuthGate } from '@components/AuthGate'import { Button } from '@components/Button'+import { ProfileBodySkeleton } from '@components/ProfileBodySkeleton'import { ProfileShell } from '@components/ProfileShell'import { useToast } from '@components/Toast'import { isSilentApiError } from '@lib/api'import {+ type ConnectedAccount,listConnectedAccounts,revokeConnectedAccount,- type ConnectedAccount,} from '@lib/connectedAccounts'type LoadState = 'loading' | 'ready' | 'error'@@ -60,7 +61,12 @@ function ConnectedAccountsContent() {</div></header>- {state === 'loading' && <div className="message message--plain">Loading...</div>}+ {state === 'loading' ? (+ <ProfileBodySkeleton+ label="Loading connected accounts"+ sections={[{ title: 'Connected accounts', rows: 3 }]}+ />+ ) : null}{state === 'error' && (<div className="message message--error">Could not load connected accounts.</div>)}diff --git a/profile-ui/app/globals.css b/profile-ui/app/globals.cssindex a70710327..93eb08826 100644--- a/profile-ui/app/globals.css+++ b/profile-ui/app/globals.css@@ -600,6 +600,22 @@ code {flex: 1;}+.cu-sidebar__item--loading {+ pointer-events: none;+}++.cu-sidebar__item--loading .cu-sidebar__icon {+ width: 1.1rem;+ height: 1.1rem;+ border-radius: 4px;+}++.cu-sidebar__item--loading .cu-sidebar__label {+ height: 0.75rem;+ max-width: 7.5rem;+ border-radius: 4px;+}+.cu-sidebar__footer {margin-top: auto;display: grid;@@ -1805,6 +1821,26 @@ code {background: rgba(var(--cu-panel-rgb), 0.42);}+.profile-body-skeleton {+ display: grid;+ gap: 1rem;+}++.profile-skeleton__row {+ display: grid;+ grid-template-columns: minmax(8rem, 1fr) minmax(10rem, 1.5fr) minmax(5rem, 0.65fr);+ gap: 0.75rem;+ align-items: center;+ min-height: 2.5rem;+ padding-bottom: 0.75rem;+ border-bottom: 1px solid var(--cu-border-subtle);+}++.profile-skeleton__row:last-child {+ padding-bottom: 0;+ border-bottom: 0;+}+.profile-skeleton__line {height: 0.85rem;border-radius: 999px;@@ -1836,6 +1872,12 @@ code {}}+@media (max-width: 720px) {+ .profile-skeleton__row {+ grid-template-columns: 1fr;+ }+}+.message--warning {color: var(--cu-warning);}diff --git a/profile-ui/app/layout.tsx b/profile-ui/app/layout.tsxindex 37fadfd1e..964705851 100644--- a/profile-ui/app/layout.tsx+++ b/profile-ui/app/layout.tsx@@ -1,6 +1,7 @@import type { ReactNode } from 'react'import type { Metadata } from 'next'import { AuthProvider } from '@components/AuthContext'+import { ProfileAppFrame } from '@components/ProfileAppFrame'import { ToastProvider } from '@components/Toast'import './globals.css'@@ -25,7 +26,9 @@ export default function RootLayout({ children }: { children: ReactNode }) {</head><body className="cu-body"><ToastProvider>- <AuthProvider>{children}</AuthProvider>+ <AuthProvider>+ <ProfileAppFrame>{children}</ProfileAppFrame>+ </AuthProvider></ToastProvider></body></html>diff --git a/profile-ui/app/members/[userId]/page.tsx b/profile-ui/app/members/[userId]/page.tsxindex 4756a6003..6933042c7 100644--- a/profile-ui/app/members/[userId]/page.tsx+++ b/profile-ui/app/members/[userId]/page.tsx@@ -7,6 +7,7 @@ import { AuthGate } from '@components/AuthGate'import { Button } from '@components/Button'import { useConfirmDialog } from '@components/ConfirmDialog'import { FormField } from '@components/FormField'+import { ProfileBodySkeleton } from '@components/ProfileBodySkeleton'import { ProfileShell } from '@components/ProfileShell'import { TextInput } from '@components/TextInput'import { useToast } from '@components/Toast'@@ -195,7 +196,12 @@ export default function MemberDetailsPage() {</div></header>- {state === 'loading' ? <div className="message message--plain">Loading...</div> : null}+ {state === 'loading' ? (+ <ProfileBodySkeleton+ label="Loading member details"+ sections={[{ title: 'Teams and permissions', rows: 4 }]}+ />+ ) : null}{error ? <div className="message message--error">{error}</div> : null}{!memberIsSelf && memberHasUncontrolledTeams ? (<div className="message message--warning message--plain">diff --git a/profile-ui/app/members/invite/page.tsx b/profile-ui/app/members/invite/page.tsxindex 774050e90..b85442996 100644--- a/profile-ui/app/members/invite/page.tsx+++ b/profile-ui/app/members/invite/page.tsx@@ -8,6 +8,7 @@ import { CreateFlowPanel } from '@components/CreateFlowPanel'import { CreatePageHeader } from '@components/CreatePageHeader'import { CreateStepFlow } from '@components/CreateStepFlow'import { FormField } from '@components/FormField'+import { useProfileAccess } from '@components/ProfileAccessContext'import { ProfileShell } from '@components/ProfileShell'import { SelectionDropdown } from '@components/SelectionDropdown'import { IconMembers } from '@components/Sidebar/icons'@@ -15,7 +16,7 @@ import { TextInput } from '@components/TextInput'import { useToast } from '@components/Toast'import { IconTrash } from '@components/icons'import { PROFILE_ROUTES } from '@constants/routes'-import { getManageableTeams, inviteManagedMember, isSilentApiError } from '@lib/api'+import { inviteManagedMember } from '@lib/api'import {formatTeamRole,permissionsForTeamRole,@@ -42,13 +43,16 @@ const STEP_DETAILS = [export default function InviteMemberPage() {const router = useRouter()const { showToast } = useToast()+ const {+ manageableTeams: teams,+ manageableTeamsError,+ manageableTeamsLoading: loadingTeams,+ } = useProfileAccess()const hasFocusedInitialFieldRef = useRef(false)const [step, setStep] = useState(0)const [name, setName] = useState('')const [email, setEmail] = useState('')- const [teams, setTeams] = useState<ManageableTeam[]>([])const [inviteRoles, setInviteRoles] = useState<Record<string, Role>>({})- const [loadingTeams, setLoadingTeams] = useState(true)const [saving, setSaving] = useState(false)const [error, setError] = useState('')const emailValid = EMAIL_PATTERN.test(email.trim())@@ -73,27 +77,6 @@ export default function InviteMemberPage() {const canSubmit = nameValid && emailValid && selectedTeams.length > 0 && !saving && !loadingTeamsconst canContinue = step === 0 ? nameValid && emailValid : !loadingTeams- useEffect(() => {- let cancelled = false- async function loadTeams() {- setLoadingTeams(true)- setError('')- try {- const response = await getManageableTeams()- if (!cancelled) setTeams(Array.isArray(response.items) ? response.items : [])- } catch (nextError) {- if (cancelled || isSilentApiError(nextError)) return- setError(nextError instanceof Error ? nextError.message : 'Failed to load teams')- } finally {- if (!cancelled) setLoadingTeams(false)- }- }- void loadTeams()- return () => {- cancelled = true- }- }, [])-useEffect(() => {if (loadingTeams || saving || hasFocusedInitialFieldRef.current) returnconst activeElement = document.activeElement@@ -244,6 +227,9 @@ export default function InviteMemberPage() {</div>) : null}+ {manageableTeamsError ? (+ <div className="message message--error">Failed to load teams</div>+ ) : null}{error ? <div className="message message--error">{error}</div> : null}<div className="cu-create-actions">diff --git a/profile-ui/app/members/page.tsx b/profile-ui/app/members/page.tsxindex a93a5ad22..cfb553208 100644--- a/profile-ui/app/members/page.tsx+++ b/profile-ui/app/members/page.tsx@@ -6,6 +6,8 @@ import { useAuth } from '@components/AuthContext'import { AuthGate } from '@components/AuthGate'import { Button } from '@components/Button'import { useConfirmDialog } from '@components/ConfirmDialog'+import { useProfileAccess } from '@components/ProfileAccessContext'+import { ProfileBodySkeleton } from '@components/ProfileBodySkeleton'import { ProfileShell } from '@components/ProfileShell'import { useToast } from '@components/Toast'import { IconAlertTriangle, IconRefresh, IconTrash } from '@components/icons'@@ -13,13 +15,12 @@ import { PROFILE_ROUTES } from '@constants/routes'import {cancelManagedInvitation,deleteManagedUser,- getManageableTeams,getManagedInvitations,getManagedMembers,isSilentApiError,resendManagedInvitation,} from '@lib/api'-import type { ManageableTeam, ManagedMember, ManagedPendingInvitation } from '@/app/types/profile'+import type { ManagedMember, ManagedPendingInvitation } from '@/app/types/profile'import { canDeleteMemberAccount, displayMemberName, memberDeleteTooltip } from './memberHelpers'type LoadState = 'loading' | 'ready' | 'error'@@ -28,25 +29,24 @@ export default function MembersPage() {const router = useRouter()const { authState } = useAuth()const { confirm, confirmDialog } = useConfirmDialog()+ const { manageableTeams, refreshManageableTeams } = useProfileAccess()const { showToast } = useToast()const [state, setState] = useState<LoadState>('loading')const [members, setMembers] = useState<ManagedMember[]>([])const [invitations, setInvitations] = useState<ManagedPendingInvitation[]>([])- const [manageableTeams, setManageableTeams] = useState<ManageableTeam[]>([])const [busy, setBusy] = useState(false)const [error, setError] = useState('')const currentUserId = authState.me?.id || ''- async function loadMembers() {+ async function loadMembers(forceAccess = false) {setState('loading')setError('')try {- const [teamsResponse, membersResponse, invitationsResponse] = await Promise.all([- getManageableTeams(),+ const [, membersResponse, invitationsResponse] = await Promise.all([+ refreshManageableTeams({ force: forceAccess }),getManagedMembers(),getManagedInvitations(),])- setManageableTeams(Array.isArray(teamsResponse.items) ? teamsResponse.items : [])setMembers(Array.isArray(membersResponse.items) ? membersResponse.items : [])setInvitations(Array.isArray(invitationsResponse.items) ? invitationsResponse.items : [])setState('ready')@@ -130,7 +130,7 @@ export default function MembersPage() {<Buttonvariant="secondary"className="cu-btn--icon cu-btn--toolbar"- onClick={loadMembers}+ onClick={() => void loadMembers(true)}disabled={busy || state === 'loading'}aria-label={state === 'loading' ? 'Refreshing members' : 'Refresh members'}>@@ -145,7 +145,15 @@ export default function MembersPage() {</div></header>- {state === 'loading' ? <div className="message message--plain">Loading...</div> : null}+ {state === 'loading' ? (+ <ProfileBodySkeleton+ label="Loading members"+ sections={[+ { title: 'Pending invitations', rows: 2 },+ { title: 'Members', rows: 4 },+ ]}+ />+ ) : null}{error ? <div className="message message--error">{error}</div> : null}{state !== 'loading' && manageableTeams.length === 0 ? (@@ -215,72 +223,74 @@ export default function MembersPage() {</section>) : null}- <section className="section members-section">- <div className="members-table-wrap">- <table className="members-table">- <thead>- <tr>- <th>Member</th>- <th>Email</th>- <th>Teams</th>- <th></th>- </tr>- </thead>- <tbody>- {members.map(member => {- const deleteAllowed = canDeleteMemberAccount(member, currentUserId)- return (- <tr key={member.id}>- <td>- <button- type="button"- className="table-link"- onClick={() => router.push(PROFILE_ROUTES.members.detail(member.id))}- >- {displayMemberName(member)}- </button>- </td>- <td>- <span className="member-email">- <span>{member.email}</span>- {member.passwordPendingFromAcceptedInvitation ? (- <span- className="member-email__alert"- title="Invitation accepted, but this member still needs to set a password."- aria-label="Invitation accepted, password setup pending"- >- <IconAlertTriangle width={14} height={14} />- </span>- ) : null}- </span>- </td>- <td>{member.teams.length}</td>- <td>- <div className="row-actions">+ {state !== 'loading' ? (+ <section className="section members-section">+ <div className="members-table-wrap">+ <table className="members-table">+ <thead>+ <tr>+ <th>Member</th>+ <th>Email</th>+ <th>Teams</th>+ <th></th>+ </tr>+ </thead>+ <tbody>+ {members.map(member => {+ const deleteAllowed = canDeleteMemberAccount(member, currentUserId)+ return (+ <tr key={member.id}>+ <td><buttontype="button"- className="icon-button icon-button--danger"- onClick={() => void deleteMemberAccount(member)}- disabled={busy || !deleteAllowed}- title={memberDeleteTooltip(member, currentUserId)}- aria-label={`Delete ${displayMemberName(member)}`}+ className="table-link"+ onClick={() => router.push(PROFILE_ROUTES.members.detail(member.id))}>- <IconTrash />+ {displayMemberName(member)}</button>- </div>- </td>+ </td>+ <td>+ <span className="member-email">+ <span>{member.email}</span>+ {member.passwordPendingFromAcceptedInvitation ? (+ <span+ className="member-email__alert"+ title="Invitation accepted, but this member still needs to set a password."+ aria-label="Invitation accepted, password setup pending"+ >+ <IconAlertTriangle width={14} height={14} />+ </span>+ ) : null}+ </span>+ </td>+ <td>{member.teams.length}</td>+ <td>+ <div className="row-actions">+ <button+ type="button"+ className="icon-button icon-button--danger"+ onClick={() => void deleteMemberAccount(member)}+ disabled={busy || !deleteAllowed}+ title={memberDeleteTooltip(member, currentUserId)}+ aria-label={`Delete ${displayMemberName(member)}`}+ >+ <IconTrash />+ </button>+ </div>+ </td>+ </tr>+ )+ })}+ {state === 'ready' && members.length === 0 ? (+ <tr>+ <td colSpan={4}>No members are visible for your teams.</td></tr>- )- })}- {state === 'ready' && members.length === 0 ? (- <tr>- <td colSpan={4}>No members are visible for your teams.</td>- </tr>- ) : null}- </tbody>- </table>- </div>- </section>+ ) : null}+ </tbody>+ </table>+ </div>+ </section>+ ) : null}{confirmDialog}</div>diff --git a/profile-ui/app/page.tsx b/profile-ui/app/page.tsxindex ef3ab2012..9468d4347 100644--- a/profile-ui/app/page.tsx+++ b/profile-ui/app/page.tsx@@ -55,19 +55,13 @@ function HomeContent() {export default function Page() {return (- <Suspense- fallback={- <main className="cu-app cu-app--auth">- <div className="cu-card cu-card--auth">- <div className="cu-card__body">Loading...</div>- </div>- </main>- }- >- <InvitationRedirect />+ <>+ <Suspense fallback={null}>+ <InvitationRedirect />+ </Suspense><AuthGate><HomeContent /></AuthGate>- </Suspense>+ </>)}diff --git a/profile-ui/app/settings/SettingsContent.tsx b/profile-ui/app/settings/SettingsContent.tsxindex 4680b215c..61e7a89f3 100644--- a/profile-ui/app/settings/SettingsContent.tsx+++ b/profile-ui/app/settings/SettingsContent.tsx@@ -8,6 +8,8 @@ import { useAuth } from '@components/AuthContext'import { Button } from '@components/Button'import { useConfirmDialog } from '@components/ConfirmDialog'import { FormField } from '@components/FormField'+import { useProfileAccess } from '@components/ProfileAccessContext'+import { ProfileBodySkeleton } from '@components/ProfileBodySkeleton'import { ProfileShell } from '@components/ProfileShell'import { TextInput } from '@components/TextInput'import { useToast } from '@components/Toast'@@ -23,7 +25,6 @@ import {} from '@lib/api'import {disconnectWorkflowApprovalMedium,- listApprovalChannelTargets,listWorkflowApprovalMediums,} from '@lib/approvalChannels'import {@@ -36,10 +37,7 @@ import {updateDraftRow,} from '@lib/profileSettings'import type { DesktopEnvironmentResponse } from '@/app/types/api'-import type {- ApprovalChannelTarget,- WorkflowApprovalMediumAccount,-} from '@/app/types/approvalChannels'+import type { WorkflowApprovalMediumAccount } from '@/app/types/approvalChannels'import type { Me } from '@/app/types/profile'import packageJson from '../../package.json'import { SettingsChannelSection } from './SettingsChannelSection'@@ -53,20 +51,10 @@ import type {SocialChannelTabKey,} from './types'-type LoadState = 'idle' | 'loading' | 'ready' | 'error'+type LoadState = 'loading' | 'ready' | 'error'type SettingsTab = 'profile' | 'social'type EditScope = 'profile' | null-function LoadingSkeleton() {- return (- <div className="profile-skeleton" role="status" aria-label="Loading">- <span className="profile-skeleton__line profile-skeleton__line--medium" />- <span className="profile-skeleton__line" />- <span className="profile-skeleton__line profile-skeleton__line--short" />- </div>- )-}-export function SettingsContent({activeSettingsTab,activeSocialTab,@@ -77,6 +65,7 @@ export function SettingsContent({const router = useRouter()const searchParams = useSearchParams()const { checkAuth, logout } = useAuth()+ const { approvalTargets: targets, refreshApprovalTargets } = useProfileAccess()const { showToast } = useToast()const { confirm, confirmDialog } = useConfirmDialog()const [me, setMe] = useState<Me | null>(null)@@ -84,9 +73,8 @@ export function SettingsContent({const [draft, setDraft] = useState<ProfileChannelDraft>(() =>channelsToDraft(EMPTY_PROFILE_CHANNELS))- const [targets, setTargets] = useState<ApprovalChannelTarget[]>([])const [accounts, setAccounts] = useState<WorkflowApprovalMediumAccount[]>([])- const [state, setState] = useState<LoadState>('idle')+ const [state, setState] = useState<LoadState>('loading')const [busy, setBusy] = useState(false)const [error, setError] = useState('')const [editScope, setEditScope] = useState<EditScope>(null)@@ -152,20 +140,19 @@ export function SettingsContent({}}, [searchParams])- async function loadAll() {+ async function loadAll(forceAccess = false) {setState('loading')setError('')try {- const [current, nextTargets, nextAccounts] = await Promise.all([+ const [current, , nextAccounts] = await Promise.all([getMe(),- listApprovalChannelTargets(),+ refreshApprovalTargets({ force: forceAccess }),listWorkflowApprovalMediums({ includeDisabled: true }),])const channels = normalizeProfileChannels(current.profile.channels)setMe({ ...current, profile: { ...current.profile, channels } })setDisplayName(current.profile.displayName || current.name || current.email)setDraft(channelsToDraft(channels))- setTargets(nextTargets)setAccounts(nextAccounts)setState('ready')} catch (err) {@@ -371,7 +358,7 @@ export function SettingsContent({<Buttonvariant="secondary"className="cu-btn--icon cu-btn--toolbar"- onClick={loadAll}+ onClick={() => void loadAll(true)}disabled={formDisabled}aria-label={state === 'loading' ? 'Refreshing settings' : 'Refresh settings'}>@@ -380,7 +367,6 @@ export function SettingsContent({</div></header>- {state === 'loading' && <LoadingSkeleton />}{error && <div className="message message--error">{error}</div>}<div className="tabs" role="tablist" aria-label="Settings sections">@@ -406,7 +392,16 @@ export function SettingsContent({) : null}</div>- {activeSettingsTab === 'profile' ? (+ {state === 'loading' ? (+ <ProfileBodySkeleton+ label="Loading settings"+ sections={[+ activeSettingsTab === 'profile'+ ? { title: 'Profile', actions: ['Update password', 'Edit'], rows: 3 }+ : { title: 'Social channels', actions: ['Connect'], rows: 4 },+ ]}+ />+ ) : activeSettingsTab === 'profile' ? (<section className="section settings-section"><div className="settings-section-head"><div>@@ -442,7 +437,7 @@ export function SettingsContent({</section>) : null}- {activeSettingsTab === 'social' && currentSocialTab ? (+ {state !== 'loading' && activeSettingsTab === 'social' && currentSocialTab ? (<section className="section settings-section"><div className="tabs" role="tablist" aria-label="Social networks">{visibleSocialTabs.map(tab => (diff --git a/profile-ui/lib/profileAccess.ts b/profile-ui/lib/profileAccess.tsnew file mode 100644index 000000000..7151c20ad--- /dev/null+++ b/profile-ui/lib/profileAccess.ts@@ -0,0 +1,81 @@+import type { ApprovalChannelTarget } from '../app/types/approvalChannels'+import type { ManageableTeam } from '../app/types/profile'+import { getManageableTeams } from './api'+import { listApprovalChannelTargets } from './approvalChannels'++type ProfileAccessCacheEntry = {+ approvalTargets?: ApprovalChannelTarget[]+ approvalTargetsRequest?: Promise<ApprovalChannelTarget[]>+ manageableTeams?: ManageableTeam[]+ manageableTeamsRequest?: Promise<ManageableTeam[]>+}++const accessCache = new Map<string, ProfileAccessCacheEntry>()++function entryFor(userId: string): ProfileAccessCacheEntry {+ const cached = accessCache.get(userId)+ if (cached) return cached+ const next: ProfileAccessCacheEntry = {}+ accessCache.set(userId, next)+ return next+}++export function readProfileAccessCache(userId: string): {+ approvalTargets?: ApprovalChannelTarget[]+ manageableTeams?: ManageableTeam[]+} {+ const cached = accessCache.get(userId)+ return {+ approvalTargets: cached?.approvalTargets,+ manageableTeams: cached?.manageableTeams,+ }+}++export function requestManageableTeams(+ userId: string,+ options: { force?: boolean } = {}+): Promise<ManageableTeam[]> {+ const cached = entryFor(userId)+ if (!options.force && cached.manageableTeams) return Promise.resolve(cached.manageableTeams)+ if (cached.manageableTeamsRequest) return cached.manageableTeamsRequest++ const request = getManageableTeams()+ .then(response => {+ const teams = Array.isArray(response.items) ? response.items : []+ cached.manageableTeams = teams+ return teams+ })+ .finally(() => {+ delete cached.manageableTeamsRequest+ })+ cached.manageableTeamsRequest = request+ return request+}++export function requestApprovalTargets(+ userId: string,+ options: { force?: boolean } = {}+): Promise<ApprovalChannelTarget[]> {+ const cached = entryFor(userId)+ if (!options.force && cached.approvalTargets) return Promise.resolve(cached.approvalTargets)+ if (cached.approvalTargetsRequest) return cached.approvalTargetsRequest++ const request = listApprovalChannelTargets()+ .then(targets => {+ cached.approvalTargets = targets+ return targets+ })+ .finally(() => {+ delete cached.approvalTargetsRequest+ })+ cached.approvalTargetsRequest = request+ return request+}++export function resetProfileAccessCache(userId?: string): void {+ if (userId) {+ accessCache.delete(userId)+ return+ }+ accessCache.clear()+}diff --git a/profile-ui/lib/profileAppFrame.ts b/profile-ui/lib/profileAppFrame.tsnew file mode 100644index 000000000..25f6ba73f--- /dev/null+++ b/profile-ui/lib/profileAppFrame.ts@@ -0,0 +1,26 @@+const PUBLIC_PROFILE_UI_PREFIXES = ['/desktop-setup', '/forgot-password', '/invitations'] as const++export function isPublicProfileUiPath(pathname: string): boolean {+ return PUBLIC_PROFILE_UI_PREFIXES.some(+ prefix => pathname === prefix || pathname.startsWith(`${prefix}/`)+ )+}++export type ProfileRouteKey =+ | 'home'+ | 'members'+ | 'approvalChannels'+ | 'connectedAccounts'+ | 'settings'++export function profileRouteForPathname(pathname: string): ProfileRouteKey {+ if (pathname === '/approval-channels' || pathname.startsWith('/approval-channels/')) {+ return 'approvalChannels'+ }+ if (pathname === '/connected-accounts' || pathname.startsWith('/connected-accounts/')) {+ return 'connectedAccounts'+ }+ if (pathname === '/members' || pathname.startsWith('/members/')) return 'members'+ if (pathname === '/settings' || pathname.startsWith('/settings/')) return 'settings'+ return 'home'+}diff --git a/profile-ui/test/invitations.test.ts b/profile-ui/test/invitations.test.tsindex 7a71db0c6..7eea49656 100644--- a/profile-ui/test/invitations.test.ts+++ b/profile-ui/test/invitations.test.ts@@ -2,6 +2,8 @@ import assert from 'node:assert/strict'import test from 'node:test'import { buildInvitationHeading, formatRemaining, resolveInvitationToken } from '../lib/invitations'import './approvalChannels.test'+import './profileAccess.test'+import './profileAppFrame.test'import './profileSettings.test'import './routes.test'diff --git a/profile-ui/test/profileAccess.test.ts b/profile-ui/test/profileAccess.test.tsnew file mode 100644index 000000000..ce0bccf74--- /dev/null+++ b/profile-ui/test/profileAccess.test.ts@@ -0,0 +1,51 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import {+ requestApprovalTargets,+ requestManageableTeams,+ resetProfileAccessCache,+} from '../lib/profileAccess'++test('profile access requests are cached and deduplicated per user', async () => {+ const originalFetch = globalThis.fetch+ const requests: string[] = []+ globalThis.fetch = (async input => {+ const url = String(input)+ requests.push(url)+ return new Response(JSON.stringify({ items: [] }), {+ headers: { 'Content-Type': 'application/json' },+ status: 200,+ })+ }) as typeof fetch++ try {+ resetProfileAccessCache()+ await Promise.all([+ requestManageableTeams('user-1'),+ requestManageableTeams('user-1'),+ requestApprovalTargets('user-1'),+ requestApprovalTargets('user-1'),+ ])++ assert.equal(requests.filter(url => url.includes('/manageable-teams')).length, 1)+ assert.equal(+ requests.filter(url => url.includes('/workflow-approval-mediums/targets')).length,+ 1+ )++ await requestManageableTeams('user-1')+ await requestApprovalTargets('user-1')+ assert.equal(requests.length, 2)++ await Promise.all([+ requestManageableTeams('user-1', { force: true }),+ requestManageableTeams('user-1', { force: true }),+ requestApprovalTargets('user-1', { force: true }),+ requestApprovalTargets('user-1', { force: true }),+ ])+ assert.equal(requests.length, 4)+ } finally {+ globalThis.fetch = originalFetch+ resetProfileAccessCache()+ }+})diff --git a/profile-ui/test/profileAppFrame.test.ts b/profile-ui/test/profileAppFrame.test.tsnew file mode 100644index 000000000..319e42e7d--- /dev/null+++ b/profile-ui/test/profileAppFrame.test.ts@@ -0,0 +1,23 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { isPublicProfileUiPath, profileRouteForPathname } from '../lib/profileAppFrame'++test('public profile routes stay outside the authenticated application frame', () => {+ for (const pathname of ['/desktop-setup', '/forgot-password', '/invitations/token']) {+ assert.equal(isPublicProfileUiPath(pathname), true, pathname)+ }+})++test('authenticated profile routes use the persistent application frame', () => {+ for (const pathname of ['/', '/members', '/approval-channels', '/connected-accounts']) {+ assert.equal(isPublicProfileUiPath(pathname), false, pathname)+ }+})++test('profileRouteForPathname derives the active persistent sidebar route', () => {+ assert.equal(profileRouteForPathname('/'), 'home')+ assert.equal(profileRouteForPathname('/members/member-1'), 'members')+ assert.equal(profileRouteForPathname('/approval-channels'), 'approvalChannels')+ assert.equal(profileRouteForPathname('/connected-accounts'), 'connectedAccounts')+ assert.equal(profileRouteForPathname('/settings'), 'settings')+})