Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): reframe connector flows around agent access (Phase 1 / Category B)
Miguelon Peluchon0daeedaf2692
diff --git a/control-ui/app/constants/connectorEdit.ts b/control-ui/app/constants/connectorEdit.tsindex bcecb49ee..6831b373b 100644--- a/control-ui/app/constants/connectorEdit.ts+++ b/control-ui/app/constants/connectorEdit.ts@@ -1,11 +1,11 @@export const CONNECTOR_EDIT_DEFAULT_TAB = 'credentials'-export const CONNECTOR_EDIT_TABS = ['credentials', 'egress', 'context'] as const+export const CONNECTOR_EDIT_TABS = ['credentials', 'egress', 'access'] as constexport type ConnectorEditTab = (typeof CONNECTOR_EDIT_TABS)[number]export const CONNECTOR_EDIT_TAB_LABELS: Record<ConnectorEditTab, string> = {egress: 'External Egress',credentials: 'Credentials',- context: 'Context',+ access: 'Access',}diff --git a/control-ui/app/constants/createFlowLoading.ts b/control-ui/app/constants/createFlowLoading.tsindex b9e4c9e6c..fceaa2d7b 100644--- a/control-ui/app/constants/createFlowLoading.ts+++ b/control-ui/app/constants/createFlowLoading.ts@@ -38,8 +38,8 @@ export const CREATE_FLOW_LOADING = {title: 'Create connector',subtitle: 'Register a new connector and optionally create its managed deployment metadata.',backLabel: 'Back to connectors',- steps: ['Connector', 'Runtime', 'Network', 'Secrets'],- stepFlowClassName: 'cu-create-step-flow--4',+ steps: ['Connector', 'Access', 'Secrets'],+ stepFlowClassName: 'cu-create-step-flow--3',},createMember: {iconKey: 'users',@@ -76,10 +76,10 @@ export const CREATE_FLOW_LOADING = {installRegistryEntry: {iconKey: 'store',title: 'Install from Marketplace',- subtitle: 'Install a Marketplace entry into your cluster and bind it to a context.',+ subtitle: 'Install a Marketplace entry into your cluster.',backLabel: 'Back to Marketplace',- steps: ['Package', 'Install'],- stepFlowClassName: 'cu-create-step-flow--2',+ steps: ['Package', 'Credentials', 'Install'],+ stepFlowClassName: 'cu-create-step-flow--3',},installPlugin: {iconKey: 'workflow',diff --git a/control-ui/app/globals.css b/control-ui/app/globals.cssindex c3ebfe0df..8ef4f1a47 100644--- a/control-ui/app/globals.css+++ b/control-ui/app/globals.css@@ -2143,15 +2143,15 @@ textarea.cu-input {grid-template-columns: repeat(auto-fit, minmax(10rem, 1fr));}-.cu-connector-context-access__list li {+.cu-connector-agent-access__list li {align-items: center;}-.cu-connector-context-access__name {+.cu-connector-agent-access__name {flex: 1 1 auto;}-.cu-connector-context-access__name > .cu-link {+.cu-connector-agent-access__name > .cu-link {display: block;max-width: 100%;overflow: hidden;@@ -2159,13 +2159,13 @@ textarea.cu-input {white-space: nowrap;}-.cu-connector-context-access__remove {+.cu-connector-agent-access__remove {width: var(--cu-space-5);height: var(--cu-space-5);flex: 0 0 auto;}-.cu-connector-context-access__add {+.cu-connector-agent-access__add {width: 100%;margin-top: auto;}@@ -2748,7 +2748,7 @@ textarea.cu-input {padding-left: var(--cu-space-5);}-.cu-registry-context-access {+.cu-entity-access {display: grid;grid-template-columns: repeat(auto-fit, minmax(11rem, 1fr));gap: var(--cu-space-2);@@ -2758,13 +2758,13 @@ textarea.cu-input {background: rgba(var(--cu-panel-rgb), 0.35);}-.cu-registry-context-access__intro {+.cu-entity-access__intro {display: grid;gap: calc(var(--cu-space-1) / 2);margin-top: var(--cu-space-1);}-.cu-registry-context-access__intro > span {+.cu-entity-access__intro > span {color: var(--cu-text-muted);font-size: 0.7rem;font-weight: 600;@@ -2772,14 +2772,14 @@ textarea.cu-input {text-transform: uppercase;}-.cu-registry-context-access__intro > p {+.cu-entity-access__intro > p {margin: 0;color: var(--cu-text-soft);font-size: 0.8125rem;line-height: 1.45;}-.cu-registry-context-access__group {+.cu-entity-access__group {position: relative;display: grid;align-content: start;@@ -2794,7 +2794,7 @@ textarea.cu-input {overflow: hidden;}-.cu-registry-context-access__group::before {+.cu-entity-access__group::before {position: absolute;top: 0;right: 0;@@ -2804,32 +2804,32 @@ textarea.cu-input {content: '';}-.cu-registry-context-access__group[data-kind='teams'] {+.cu-entity-access__group[data-kind='teams'] {background:linear-gradient(145deg, rgba(var(--cu-success-rgb), 0.1), transparent 52%), var(--cu-surface);}-.cu-registry-context-access__group[data-kind='teams']::before {+.cu-entity-access__group[data-kind='teams']::before {background: var(--cu-success);}-.cu-registry-context-access__group[data-kind='agents'] {+.cu-entity-access__group[data-kind='agents'] {background:linear-gradient(145deg, rgba(var(--cu-warning-rgb), 0.1), transparent 52%), var(--cu-surface);}-.cu-registry-context-access__group[data-kind='agents']::before {+.cu-entity-access__group[data-kind='agents']::before {background: var(--cu-warning);}-.cu-registry-context-access__heading {+.cu-entity-access__heading {display: flex;align-items: baseline;justify-content: space-between;gap: var(--cu-space-2);}-.cu-registry-context-access__heading h4 {+.cu-entity-access__heading h4 {margin: 0;color: var(--cu-text);font-size: 0.75rem;@@ -2838,7 +2838,7 @@ textarea.cu-input {text-transform: uppercase;}-.cu-registry-context-access__heading span {+.cu-entity-access__heading span {display: inline-grid;place-items: center;min-width: calc(var(--cu-space-3) * 2);@@ -2852,17 +2852,17 @@ textarea.cu-input {font-variant-numeric: tabular-nums;}-.cu-registry-context-access__group[data-kind='teams'] .cu-registry-context-access__heading span {+.cu-entity-access__group[data-kind='teams'] .cu-entity-access__heading span {border-color: rgba(var(--cu-success-rgb), 0.35);background: rgba(var(--cu-success-rgb), 0.12);}-.cu-registry-context-access__group[data-kind='agents'] .cu-registry-context-access__heading span {+.cu-entity-access__group[data-kind='agents'] .cu-entity-access__heading span {border-color: rgba(var(--cu-warning-rgb), 0.35);background: rgba(var(--cu-warning-rgb), 0.12);}-.cu-registry-context-access__list {+.cu-entity-access__list {display: grid;gap: var(--cu-space-1);max-height: 10rem;@@ -2874,14 +2874,14 @@ textarea.cu-input {list-style: none;}-.cu-registry-context-access__list li {+.cu-entity-access__list li {display: flex;align-items: center;gap: var(--cu-space-2);min-width: 0;}-.cu-registry-context-access__list li::before {+.cu-entity-access__list li::before {width: var(--cu-space-1);height: var(--cu-space-1);flex: 0 0 auto;@@ -2890,23 +2890,21 @@ textarea.cu-input {content: '';}-.cu-registry-context-access__group[data-kind='teams'] .cu-registry-context-access__list li::before {+.cu-entity-access__group[data-kind='teams'] .cu-entity-access__list li::before {background: rgba(var(--cu-success-rgb), 0.8);}-.cu-registry-context-access__group[data-kind='agents']- .cu-registry-context-access__list- li::before {+.cu-entity-access__group[data-kind='agents'] .cu-entity-access__list li::before {background: rgba(var(--cu-warning-rgb), 0.8);}-.cu-registry-context-access__list li > span {+.cu-entity-access__list li > span {overflow: hidden;text-overflow: ellipsis;white-space: nowrap;}-.cu-registry-context-access__group .cu-muted {+.cu-entity-access__group .cu-muted {margin: 0;font-size: 0.8125rem;}@@ -5645,15 +5643,6 @@ textarea.cu-input {margin-inline: var(--cu-space-3);}-.cu-connector-edit-context-name {- margin: 0 0 var(--cu-space-3);- color: var(--cu-text-muted);-}--.cu-connector-edit-context-name strong {- color: var(--cu-text);-}-.cu-connector-edit-form {flex: 1;min-height: 0;diff --git a/control-ui/app/mcp-servers/[name]/edit/page.tsx b/control-ui/app/mcp-servers/[name]/edit/page.tsxindex 507073b23..620247988 100644--- a/control-ui/app/mcp-servers/[name]/edit/page.tsx+++ b/control-ui/app/mcp-servers/[name]/edit/page.tsx@@ -175,7 +175,7 @@ export default function EditMcpServerPage() {} catch {if (!cancelled) {setContextNames([])- setContextListError('Context access data is unavailable. Try again later.')+ setContextListError('Agent access data is unavailable. Try again later.')}} finally {if (!cancelled) setLoadingContexts(false)@@ -305,7 +305,7 @@ export default function EditMcpServerPage() {<CreatePageHeadericon={<IconCable />}title={`Edit Connector: ${name}`}- subtitle="Review context access, rotate credentials, and update external egress for this connector."+ subtitle="Review agent access, rotate credentials, and update external egress for this connector."backLabel="Back to connectors"onBack={backToList}/>@@ -363,38 +363,35 @@ export default function EditMcpServerPage() {registryCredentialSource={registryCredentialSource}/></div>- ) : activeTab === 'context' ? (+ ) : activeTab === 'access' ? (<div className="cu-connector-edit-form cu-connector-edit-content">- <section className="cu-form-section" aria-labelledby="connector-context-title">+ <section className="cu-form-section" aria-labelledby="connector-access-title"><div className="cu-form-section__header">- <h2 id="connector-context-title" className="cu-form-section__title">- Context access+ <h2 id="connector-access-title" className="cu-form-section__title">+ Agent access</h2><p className="cu-form-section__description">- This connector is available in the contexts shown below. Context assignments- are derived from the current Context allowlists and cannot be changed here- yet.+ This connector is available to the agents, teams, and users shown below.+ Assignments are derived from the current access setup and cannot be changed+ here yet.</p></div>{loadingContexts ? (<p className="cu-muted" role="status">- Loading contexts…+ Loading agent access…</p>) : contextListError ? (<div className="cu-banner cu-banner--warn" role="alert">{contextListError}</div>- ) : (- <p className="cu-connector-edit-context-name" aria-label="Connector contexts">- Contexts:{' '}- <strong>{contextNames.length > 0 ? contextNames.join(', ') : 'None'}</strong>- </p>- )}+ ) : contextNames.length === 0 ? (+ <p className="cu-muted">No agents have access to this connector yet.</p>+ ) : null}{!loadingContexts && !contextListError && contextNames.length > 0 ? (loadingContextAccess ? (- <p className="cu-muted">Loading context access…</p>+ <p className="cu-muted">Loading agent access…</p>) : (<>{contextAccessError ? (@@ -402,19 +399,19 @@ export default function EditMcpServerPage() {{contextAccessError}</p>) : null}- <section className="cu-registry-context-access" aria-label="Context access">+ <section className="cu-entity-access" aria-label="Agent access">{CONTEXT_ACCESS_GROUPS.map(group => (<section- className="cu-registry-context-access__group"+ className="cu-entity-access__group"data-kind={group.key}key={group.key}>- <div className="cu-registry-context-access__heading">+ <div className="cu-entity-access__heading"><h4>{group.title}</h4><span>{contextAccess[group.key].length}</span></div>{contextAccess[group.key].length > 0 ? (- <ul className="cu-registry-context-access__list">+ <ul className="cu-entity-access__list">{contextAccess[group.key].map(principal => (<li key={principal.id}><span>{principal.label}</span>diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsxindex 83298079b..d48148633 100644--- a/control-ui/app/mcp-servers/page.tsx+++ b/control-ui/app/mcp-servers/page.tsx@@ -10,6 +10,8 @@ import type {ConnectorAccessPrincipal,ConnectorAccessSummary,ConnectorAccessSummaryMap,+ ConnectorAgentBinding,+ ConnectorAgentTarget,} from '../../components/McpServerTable.types'import { useToast } from '../../components/Toast'import {@@ -23,11 +25,7 @@ import {updateContext,} from '../../lib/api'import type { ContextResource, ContextSpec, HostResource, McpServerResource } from '../../lib/api'-import {- contextNamesForConnector,- mergeAccessSummaries,- sortAccessPrincipals,-} from '../../lib/connectorAccess'+import { mergeAccessSummaries, sortAccessPrincipals } from '../../lib/connectorAccess'import { buildContextUpdatePayload, contextMutationError } from '../../lib/contextMutation'function resourceName(resource: { metadata?: { name?: string } }): string {@@ -47,20 +45,72 @@ function getContextRef(resource: { spec?: Record<string, unknown> }): string {return typeof contextRef === 'string' ? contextRef.trim() : ''}-function agentsForContext(hosts: HostResource[], contextRef: string): ConnectorAccessPrincipal[] {- return sortAccessPrincipals(- hosts- .filter(host => getContextRef(host) === contextRef)- .map(host => {- const name = resourceName(host)- return { id: name, label: name }- })- )+function contextName(context: ContextResource): string {+ return String(context.metadata?.name || context.spec?.contextId || '').trim()+}++function contextSpec(context: ContextResource): ContextSpec {+ const name = contextName(context)+ return {+ contextId: context.spec?.contextId || name,+ description: context.spec?.description,+ mcpServers: Array.isArray(context.spec?.mcpServers) ? context.spec.mcpServers : [],+ sharedFileSystems: context.spec?.sharedFileSystems ?? [],+ }+}++// The agents an operator can grant connector access to. Each agent resolves to+// its private context (the write target); the context itself stays invisible.+function agentTargetsFromHosts(hosts: HostResource[]): ConnectorAgentTarget[] {+ return hosts+ .map(host => {+ const name = resourceName(host)+ const displayName =+ String((host.spec as { host?: string } | undefined)?.host || '').trim() || name+ return { name, label: displayName, contextRef: getContextRef(host) }+ })+ .filter(target => target.contextRef && target.name !== 'unknown')+ .sort((left, right) => left.label.localeCompare(right.label))}+// Per-connector write units: every context that carries the connector and is+// owned by at least one agent becomes one binding listing those agents.+// Contexts with no owning agent (per-install and workflow-recipe private+// scopes) are intentionally invisible — they are not user-managed.+function bindingsByConnectorFromContexts(+ contexts: ContextResource[],+ agentTargets: ConnectorAgentTarget[]+): Record<string, ConnectorAgentBinding[]> {+ const targetsByContextRef = new Map<string, ConnectorAccessPrincipal[]>()+ for (const target of agentTargets) {+ const principals = targetsByContextRef.get(target.contextRef) ?? []+ principals.push({ id: target.name, label: target.label })+ targetsByContextRef.set(target.contextRef, principals)+ }++ const bindings: Record<string, ConnectorAgentBinding[]> = {}+ for (const context of contexts) {+ const ref = contextName(context)+ const agents = targetsByContextRef.get(ref)+ if (!ref || !agents || agents.length === 0) continue+ for (const serverName of context.spec?.mcpServers ?? []) {+ const list = bindings[serverName] ?? []+ list.push({ contextRef: ref, agents: sortAccessPrincipals(agents) })+ bindings[serverName] = list+ }+ }+ for (const list of Object.values(bindings)) {+ list.sort((left, right) =>+ (left.agents[0]?.label ?? '').localeCompare(right.agents[0]?.label ?? '')+ )+ }+ return bindings+}++// User/team access summaries stay context-derived (read-only groups in the+// table); the agents group itself comes from the bindings above.async function loadContextAccess(- contextRef: string,- hosts: HostResource[]+ contextRef: string): Promise<readonly [ConnectorAccessSummary, boolean]> {const [usersResult, teamsResult] = await Promise.allSettled([getContextUsers(contextRef),@@ -94,7 +144,7 @@ async function loadContextAccess(return [{- agents: agentsForContext(hosts, contextRef),+ agents: [],users,teams,},@@ -102,6 +152,18 @@ async function loadContextAccess(] as const}+function connectorAccessMutationError(error: unknown, fallback: string): string {+ if ((error as { status?: unknown } | null)?.status === 409) {+ return 'This connector’s access changed since it was loaded. Reload the page and try again.'+ }+ return contextMutationError(error, fallback)+}++function agentListLabel(agents: ConnectorAccessPrincipal[]): string {+ if (agents.length === 1) return agents[0].label+ return `${agents.length} agents`+}+export default function McpServersPage() {const router = useRouter()const { showToast } = useToast()@@ -109,12 +171,14 @@ export default function McpServersPage() {const [error, setError] = useState('')const [mcpServers, setMcpServers] = useState<McpServerResource[]>([])const [contexts, setContexts] = useState<ContextResource[]>([])+ const [agentTargets, setAgentTargets] = useState<ConnectorAgentTarget[]>([])+ const [bindingsByConnectorName, setBindingsByConnectorName] = useState<+ Record<string, ConnectorAgentBinding[]>+ >({})const [accessByConnectorKey, setAccessByConnectorKey] = useState<ConnectorAccessSummaryMap>({})const [accessWarning, setAccessWarning] = useState('')const [deletingKey, setDeletingKey] = useState<string | null>(null)- const [updatingContextMembershipKey, setUpdatingContextMembershipKey] = useState<string | null>(- null- )+ const [updatingAgentAccessKey, setUpdatingAgentAccessKey] = useState<string | null>(null)const { confirm, confirmDialog } = useConfirmDialog()async function loadAll() {@@ -130,16 +194,22 @@ export default function McpServersPage() {const connectors = (serversResult.items || []) as McpServerResource[]const hosts = (hostsResult.items || []) as HostResource[]const nextContexts = (contextsResult.items || []) as ContextResource[]- const contextRefs = [+ const nextAgentTargets = agentTargetsFromHosts(hosts)+ const nextBindings = bindingsByConnectorFromContexts(nextContexts, nextAgentTargets)++ // Read-only user/team summaries are merged across the agent-owned+ // scopes that carry each connector (bindings), so the visible access+ // grid never depends on invisible orphan contexts.+ const managedContextRefs = [...new Set(- nextContexts- .map(context => String(context.metadata?.name || context.spec?.contextId || '').trim())- .filter(Boolean)+ Object.values(nextBindings)+ .flat()+ .map(binding => binding.contextRef)),]const accessResults = await Promise.all(- contextRefs.map(- async contextRef => [contextRef, await loadContextAccess(contextRef, hosts)] as const+ managedContextRefs.map(+ async contextRef => [contextRef, await loadContextAccess(contextRef)] as const))const accessByContext = new Map(@@ -154,10 +224,10 @@ export default function McpServersPage() {const nextAccessByConnectorKey = connectors.reduce<ConnectorAccessSummaryMap>((acc, connector) => {const connectorName = resourceName(connector)- const connectorContexts = contextNamesForConnector(nextContexts, connectorName)- if (connectorContexts.length > 0) {+ const bindingRefs = (nextBindings[connectorName] ?? []).map(binding => binding.contextRef)+ if (bindingRefs.length > 0) {acc[connectorKey(connector)] = mergeAccessSummaries(- connectorContexts.map(+ bindingRefs.map(contextRef =>accessByContext.get(contextRef) ?? { agents: [], users: [], teams: [] })@@ -169,6 +239,8 @@ export default function McpServersPage() {)setMcpServers(connectors)setContexts(nextContexts)+ setAgentTargets(nextAgentTargets)+ setBindingsByConnectorName(nextBindings)setAccessByConnectorKey(nextAccessByConnectorKey)} catch (e) {if (isSilentApiError(e)) return@@ -201,38 +273,19 @@ export default function McpServersPage() {}}- function handleOpenContext(contextName: string) {- const trimmed = contextName.trim()- if (!trimmed) return- router.push(CONTROL_ROUTES.contexts.connectors(trimmed))- }-- function contextName(context: ContextResource): string {- return String(context.metadata?.name || context.spec?.contextId || '').trim()- }-- function contextSpec(context: ContextResource): ContextSpec {- const name = contextName(context)- return {- contextId: context.spec?.contextId || name,- description: context.spec?.description,- mcpServers: Array.isArray(context.spec?.mcpServers) ? context.spec.mcpServers : [],- sharedFileSystems: context.spec?.sharedFileSystems ?? [],- }- }-- async function addConnectorToContexts(+ async function addConnectorToAgents(server: { name: string; namespace: string },- contextNames: string[]+ agents: Array<{ name: string; contextRef: string }>) {const key = `${server.namespace}/${server.name}`- const targets = contexts.filter(context => contextNames.includes(contextName(context)))- if (targets.length !== contextNames.length) {- setError('One or more selected contexts could not be loaded. Please refresh and try again.')+ const contextRefs = [...new Set(agents.map(agent => agent.contextRef))]+ const targets = contexts.filter(context => contextRefs.includes(contextName(context)))+ if (targets.length !== contextRefs.length) {+ setError('One or more selected agents could not be resolved. Please refresh and try again.')return}- setUpdatingContextMembershipKey(key)+ setUpdatingAgentAccessKey(key)setError('')try {await Promise.all(@@ -250,48 +303,61 @@ export default function McpServersPage() {)await loadAll()showToast(- contextNames.length === 1- ? `Connector ${server.name} added to context.`- : `Connector ${server.name} added to ${contextNames.length} contexts.`,+ agents.length === 1+ ? `Connector ${server.name} added to agent ${agents[0].name}.`+ : `Connector ${server.name} added to ${agents.length} agents.`,{ tone: 'success' })} catch (e) {if (isSilentApiError(e)) return- setError(contextMutationError(e, `Failed to add ${server.name} to contexts`))+ setError(connectorAccessMutationError(e, `Failed to give agents access to ${server.name}`))} finally {- setUpdatingContextMembershipKey(null)+ setUpdatingAgentAccessKey(null)}}- async function removeConnectorFromContext(+ async function removeConnectorFromAgents(server: { name: string; namespace: string },- targetContextName: string+ binding: ConnectorAgentBinding) {const key = `${server.namespace}/${server.name}`- const target = contexts.find(context => contextName(context) === targetContextName)+ const target = contexts.find(context => contextName(context) === binding.contextRef)if (!target) {- setError('Context could not be loaded. Please refresh and try again.')+ setError('This agent’s connector set could not be loaded. Please refresh and try again.')return}- setUpdatingContextMembershipKey(key)+ if (binding.agents.length > 1) {+ const sharedNames = binding.agents.map(agent => agent.label).join(', ')+ const shouldRemove = await confirm({+ title: 'Remove Connector Access',+ message: `Remove connector ${server.name} from ${binding.agents.length} agents (${sharedNames})? These agents share one connector set, so the change applies to all of them.`,+ confirmLabel: 'Remove',+ tone: 'danger',+ })+ if (!shouldRemove) return+ }++ setUpdatingAgentAccessKey(key)setError('')try {const spec = contextSpec(target)await updateContext(- targetContextName,+ binding.contextRef,buildContextUpdatePayload(target.metadata?.resourceVersion, {...spec,mcpServers: spec.mcpServers.filter(name => name !== server.name),}))await loadAll()- showToast(`Connector ${server.name} removed from ${targetContextName}.`, { tone: 'success' })+ showToast(`Connector ${server.name} removed from ${agentListLabel(binding.agents)}.`, {+ tone: 'success',+ })} catch (e) {if (isSilentApiError(e)) return- setError(contextMutationError(e, `Failed to remove ${server.name} from context`))+ setError(connectorAccessMutationError(e, `Failed to remove ${server.name} from agent access`))} finally {- setUpdatingContextMembershipKey(null)+ setUpdatingAgentAccessKey(null)}}@@ -310,17 +376,11 @@ export default function McpServersPage() {<McpServerTableitems={mcpServers as any}accessByConnectorKey={accessByConnectorKey}- contexts={contexts- .map(context => ({- name: contextName(context),- description: context.spec?.description,- mcpServers: context.spec?.mcpServers ?? [],- }))- .filter(context => context.name)}- onOpenContext={handleOpenContext}- onAddToContexts={addConnectorToContexts}- onRemoveFromContext={removeConnectorFromContext}- updatingContextMembershipKey={updatingContextMembershipKey}+ agentBindingsByConnectorName={bindingsByConnectorName}+ agentTargets={agentTargets}+ onAddToAgents={addConnectorToAgents}+ onRemoveFromAgents={removeConnectorFromAgents}+ updatingAgentAccessKey={updatingAgentAccessKey}onDelete={handleDelete}onEdit={server => router.push(CONTROL_ROUTES.connectors.edit(server.name))}deletingKey={deletingKey}diff --git a/control-ui/app/registry/install/page.tsx b/control-ui/app/registry/install/page.tsxindex e0a274406..01fc3e0b9 100644--- a/control-ui/app/registry/install/page.tsx+++ b/control-ui/app/registry/install/page.tsx@@ -624,8 +624,8 @@ function RegistryInstallPageContent() {const headerSubtitle = isPrivate? `Install ${entry?.name}, a private ${kindLabel} from your organization${orgScope ? ` ${orgScope}` : ''- }, into your cluster and bind it to a context.`- : 'Install a Marketplace entry into your cluster and bind it to a context.'+ }, into your cluster.`+ : 'Install a Marketplace entry into your cluster.'return (<AuthGate>diff --git a/control-ui/components/CreateMcpServerForm/index.tsx b/control-ui/components/CreateMcpServerForm/index.tsxindex 2694cbe58..5714c4136 100644--- a/control-ui/components/CreateMcpServerForm/index.tsx+++ b/control-ui/components/CreateMcpServerForm/index.tsx@@ -15,21 +15,20 @@ import {getContext,getContextTeams,getContextUsers,- getContexts,getHosts,listOrgImages,updateContext,} from '@/lib/api'-import type { EnvSecretKeyMapping, EnvVar, OrgImage } from '@/lib/api'-import type { EgressBinding } from '@/lib/api'+import type { EgressBinding, EnvSecretKeyMapping, EnvVar, HostResource, OrgImage } from '@/lib/api'import { buildContextUpdatePayload } from '@/lib/contextMutation'import type { EgressEditorStatus } from '@/lib/egressModel'+import { createPrivateContext } from '@/lib/privateContext'import { EgressEditor } from '../EgressEditor'import { DEFAULT_REGISTRY_HOST, buildImageCoordinate } from '../PublisherView/dockerCredential'import { MCP_SERVER_NAME_PATTERN, TRANSPORT_TYPES } from './constants'import type { CreateMcpServerFormProps, TransportType } from './types'-const STEPS = ['Connector', 'Context', 'Secrets'] as const+const STEPS = ['Connector', 'Access', 'Secrets'] as constconst STEP_DETAILS = [{@@ -39,8 +38,8 @@ const STEP_DETAILS = [},{description: 'Choose connector access',- title: 'Context',- subtitle: 'Choose where this connector will be available and review who can use it.',+ title: 'Access',+ subtitle: 'Optionally choose the agents that can use this connector right away.',},{description: 'Environment and credentials',@@ -49,20 +48,24 @@ const STEP_DETAILS = [},] as const-type ContextAccess = {- agents: Array<{ id: string; label: string }>+type AccessPreview = {teams: Array<{ id: string; label: string }>users: Array<{ id: string; label: string }>}-const EMPTY_CONTEXT_ACCESS: ContextAccess = { agents: [], teams: [], users: [] }+const EMPTY_ACCESS_PREVIEW: AccessPreview = { teams: [], users: [] }-const CONTEXT_ACCESS_GROUPS: Array<{ key: keyof ContextAccess; title: string }> = [+const ACCESS_PREVIEW_GROUPS: Array<{ key: keyof AccessPreview; title: string }> = [{ key: 'users', title: 'Users' },{ key: 'teams', title: 'Teams' },- { key: 'agents', title: 'Agents' },]+type AgentAccessTarget = {+ name: string+ label: string+ contextRef: string+}+type OrgImageOption = {value: stringlabel: string@@ -197,13 +200,13 @@ export function CreateMcpServerForm({const [transportType, setTransportType] = useState<TransportType>('streamableHttp')const [port, setPort] = useState(3000)const [description, setDescription] = useState('')- const [contextRef, setContextRef] = useState('')- const [contexts, setContexts] = useState<Array<{ name: string }>>([])- const [contextsLoading, setContextsLoading] = useState(true)- const [contextsError, setContextsError] = useState('')- const [contextAccess, setContextAccess] = useState<ContextAccess>(EMPTY_CONTEXT_ACCESS)- const [contextAccessError, setContextAccessError] = useState('')- const [loadingContextAccess, setLoadingContextAccess] = useState(false)+ const [selectedAgentNames, setSelectedAgentNames] = useState<string[]>([])+ const [agentTargets, setAgentTargets] = useState<AgentAccessTarget[]>([])+ const [agentsLoading, setAgentsLoading] = useState(true)+ const [agentsError, setAgentsError] = useState('')+ const [accessPreview, setAccessPreview] = useState<AccessPreview>(EMPTY_ACCESS_PREVIEW)+ const [accessPreviewError, setAccessPreviewError] = useState('')+ const [loadingAccessPreview, setLoadingAccessPreview] = useState(false)const [orgImages, setOrgImages] = useState<OrgImage[]>([])const [orgImageScope, setOrgImageScope] = useState('')const [managed, setManaged] = useState(true)@@ -236,18 +239,12 @@ export function CreateMcpServerForm({hasCompleteSecretMapping &&!hasIncompleteSecretMapping)const canSubmit =- Boolean(name && image && contextRef) &&- nameValid &&- egressValid &&- credentialsConfigured &&- !submitting+ Boolean(name && image) && nameValid && egressValid && credentialsConfigured && !submittingconst connectorComplete = Boolean(name && image && nameValid) && egressValid- const contextComplete = Boolean(contextRef)- const canContinue = step === 0 ? connectorComplete : step === 1 ? contextComplete : egressValid- const contextOptions = useMemo(- () => contexts.map(context => ({ value: context.name, label: context.name })),- [contexts]- )+ // The Access step is optional: a connector with no agents selected is valid+ // and simply is not reachable by any agent until one is granted from the+ // Installed Connectors list.+ const canContinue = step === 0 ? connectorComplete : trueconst orgImageOptions = useMemo<OrgImageOption[]>(() => {if (!orgImageScope) return []@@ -271,27 +268,32 @@ export function CreateMcpServerForm({useEffect(() => {let cancelled = false- setContextsLoading(true)- setContextsError('')+ setAgentsLoading(true)+ setAgentsError('')- getContexts()+ getHosts().then(result => {if (cancelled) return- const nextContexts = (result.items ?? [])- .map(context => ({- name: context.metadata?.name ?? context.spec?.contextId ?? '',- }))- .filter(context => context.name)- setContexts(nextContexts)- setContextRef(previous => previous || nextContexts[0]?.name || '')+ const targets = ((result.items ?? []) as HostResource[])+ .map(host => {+ const agentName = host.metadata?.name || ''+ const contextRef = String(host.spec?.contextRef ?? '').trim()+ const label = getAgentDisplayName(agentName) || agentName+ return { name: agentName, label, contextRef }+ })+ .filter(target => target.name && target.contextRef)+ .sort((left, right) => left.label.localeCompare(right.label))+ setAgentTargets(targets)}).catch(loadError => {if (cancelled) return- setContexts([])- setContextsError(loadError instanceof Error ? loadError.message : 'Failed to load contexts')+ setAgentTargets([])+ setAgentsError(+ loadError instanceof Error ? loadError.message : 'Failed to load available agents'+ )}).finally(() => {- if (!cancelled) setContextsLoading(false)+ if (!cancelled) setAgentsLoading(false)})return () => {@@ -299,65 +301,84 @@ export function CreateMcpServerForm({}}, [])+ // Preview: the users/teams that already have access to the selected agents.+ // Adding this connector makes it usable by exactly those people.+ const selectedContextRefs = useMemo(+ () =>+ Array.from(+ new Set(+ selectedAgentNames+ .map(agentName => agentTargets.find(target => target.name === agentName)?.contextRef)+ .filter((ref): ref is string => Boolean(ref))+ )+ ),+ [selectedAgentNames, agentTargets]+ )+useEffect(() => {- const selectedContext = contextRef.trim()- if (!selectedContext) {- setContextAccess(EMPTY_CONTEXT_ACCESS)- setContextAccessError('')- setLoadingContextAccess(false)+ if (selectedContextRefs.length === 0) {+ setAccessPreview(EMPTY_ACCESS_PREVIEW)+ setAccessPreviewError('')+ setLoadingAccessPreview(false)return}let cancelled = false- setLoadingContextAccess(true)- setContextAccessError('')+ setLoadingAccessPreview(true)+ setAccessPreviewError('')void (async () => {- const [usersResult, teamsResult, hostsResult] = await Promise.allSettled([- getContextUsers(selectedContext),- getContextTeams(selectedContext),- getHosts(),- ])+ const results = await Promise.all(+ selectedContextRefs.map(async contextRef => {+ const [usersResult, teamsResult] = await Promise.allSettled([+ getContextUsers(contextRef),+ getContextTeams(contextRef),+ ])+ return { usersResult, teamsResult }+ })+ )if (cancelled) return- const failed =- usersResult.status === 'rejected' ||- teamsResult.status === 'rejected' ||- hostsResult.status === 'rejected'- setContextAccess({- users:- usersResult.status === 'fulfilled'- ? (usersResult.value.items ?? []).map(user => ({- id: user.id,- label: user.displayName || user.name || user.email || user.id,- }))- : [],- teams:- teamsResult.status === 'fulfilled'- ? (teamsResult.value.items ?? []).map(team => ({ id: team.id, label: team.name }))- : [],- agents:- hostsResult.status === 'fulfilled'- ? (hostsResult.value.items ?? [])- .filter(host => String(host.spec?.contextRef ?? '').trim() === selectedContext)- .map(host => {- const agentName = host.metadata?.name || 'unknown'- return { id: agentName, label: getAgentDisplayName(agentName) || agentName }- })- : [],+ const failed = results.some(+ result =>+ result.usersResult.status === 'rejected' || result.teamsResult.status === 'rejected'+ )+ const users = results.flatMap(result =>+ result.usersResult.status === 'fulfilled'+ ? (result.usersResult.value.items ?? []).map(user => ({+ id: user.id,+ label: user.displayName || user.name || user.email || user.id,+ }))+ : []+ )+ const teams = results.flatMap(result =>+ result.teamsResult.status === 'fulfilled'+ ? (result.teamsResult.value.items ?? []).map(team => ({+ id: team.id,+ label: team.name || team.id,+ }))+ : []+ )+ const byLabel = (left: { label: string }, right: { label: string }) =>+ left.label.localeCompare(right.label)+ const dedupe = <T extends { id: string }>(items: T[]): T[] =>+ Array.from(new Map(items.map(item => [item.id, item])).values())+ setAccessPreview({+ users: dedupe(users).sort(byLabel),+ teams: dedupe(teams).sort(byLabel),})- setContextAccessError(+ setAccessPreviewError(failed? 'Some access information could not be loaded. The lists below may be incomplete.': '')- setLoadingContextAccess(false)+ setLoadingAccessPreview(false)})()return () => {cancelled = true}- }, [contextRef])+ }, [selectedContextRefs])useEffect(() => {let cancelled = false@@ -384,8 +405,7 @@ export function CreateMcpServerForm({function canSelectStep(targetStep: number) {if (targetStep <= step) return true- if (targetStep === 1) return connectorComplete- return connectorComplete && contextComplete+ return connectorComplete}const handleEgressChange = useCallback(@@ -475,9 +495,38 @@ export function CreateMcpServerForm({setSubmitting(true)setError('')+ // Resolve the write targets: the distinct private scopes of the selected+ // agents. With no selection the connector gets its own private scope (an+ // implementation detail, same as Marketplace installs) so the resource+ // contract stays satisfied without exposing any concept to the user.+ const selectedTargets = selectedAgentNames+ .map(agentName => agentTargets.find(target => target.name === agentName))+ .filter((target): target is AgentAccessTarget => Boolean(target))+ const selectedContextRefs = Array.from(+ new Set(selectedTargets.map(target => target.contextRef))+ )++ let primaryContextRef: string+ try {+ primaryContextRef =+ selectedContextRefs[0] ??+ (await createPrivateContext(+ {+ subject: name,+ description: `Connector access scope for ${name}`,+ mcpServers: [name],+ },+ 'We couldn’t finish creating this connector — please try again.'+ ))+ } catch (scopeError) {+ setError(formatCreateError(scopeError))+ setSubmitting(false)+ return+ }+const spec: Parameters<typeof createMcpServer>[0]['spec'] = {image,- contextRef,+ contextRef: primaryContextRef,description: description || undefined,enabled: true,managed,@@ -544,27 +593,40 @@ export function CreateMcpServerForm({spec,})- try {- const context = await getContext(contextRef)- const existingServers = context.spec?.mcpServers ?? []-- if (!existingServers.includes(name)) {- await updateContext(- contextRef,- buildContextUpdatePayload(context.metadata?.resourceVersion, {- contextId: context.spec?.contextId ?? contextRef,- description: context.spec?.description,- mcpServers: [...existingServers, name],- sharedFileSystems: context.spec?.sharedFileSystems ?? [],- })- )- }- } catch (contextError) {+ // Give the selected agents access. Each agent's private scope gets an+ // additive write with its own loaded resourceVersion; failures are+ // collected so the operator knows the connector itself was created.+ const failedAgents: string[] = []+ await Promise.all(+ selectedContextRefs.map(async contextRef => {+ try {+ const context = await getContext(contextRef)+ const existingServers = context.spec?.mcpServers ?? []++ if (!existingServers.includes(name)) {+ await updateContext(+ contextRef,+ buildContextUpdatePayload(context.metadata?.resourceVersion, {+ contextId: context.spec?.contextId ?? contextRef,+ description: context.spec?.description,+ mcpServers: [...existingServers, name],+ sharedFileSystems: context.spec?.sharedFileSystems ?? [],+ })+ )+ }+ } catch {+ const affected = selectedTargets+ .filter(target => target.contextRef === contextRef)+ .map(target => target.label)+ failedAgents.push(...affected)+ }+ })+ )++ if (failedAgents.length > 0) {setError(- `Connector created, but failed to add it to Context "${contextRef}" allowlist. ` +- `Please add "${name}" to the Context manually. (${- contextError instanceof Error ? contextError.message : String(contextError)- })`+ `Connector created, but we couldn't give access to ${failedAgents.join(', ')}. ` ++ `Grant "${name}" to those agents from the Installed Connectors list.`)setSubmitting(false)return@@ -774,73 +836,97 @@ export function CreateMcpServerForm({<div className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide"><section className="cu-form-section"><div className="cu-form-section__header">- <h3 className="cu-form-section__title">Context access</h3>+ <h3 className="cu-form-section__title">Agent access</h3><p className="cu-form-section__description">- Choose the context where this connector will be available. The access lists- update for the selected context.+ Optionally choose the agents that can use this connector right away. You can+ also grant access later from the Installed Connectors list.</p></div><Fielddescription={- contextsLoading- ? 'Loading available contexts...'- : contexts.length > 0- ? "The connector will be added to this context's allowlist."- : 'Create a context before creating a connector.'+ agentsLoading+ ? 'Loading available agents...'+ : selectedAgentNames.length > 0+ ? 'The connector will be usable by everyone who already has access to the selected agents.'+ : 'No agents selected: the connector is created but cannot be used by any agent until you grant access.'}- error={contextsError || undefined}- label="Context"- required+ error={agentsError || undefined}+ label="Agents"><SelectionDropdown- id="create-connector-context"- multiple={false}- onChange={next => setContextRef(next[0] ?? '')}- disabled={submitting || contextsLoading || contexts.length === 0}- value={contextRef ? [contextRef] : []}- options={contextOptions}- placeholder={contextsLoading ? 'Loading contexts...' : 'Select a context...'}- searchPlaceholder="Search contexts..."- emptyLabel="No contexts available."- selectionLabel="Context"- showSelectedChips={false}+ id="create-connector-agents"+ multiple+ onChange={setSelectedAgentNames}+ disabled={submitting || agentsLoading}+ value={selectedAgentNames}+ options={agentTargets.map(target => ({+ value: target.name,+ label: target.label,+ }))}+ placeholder={agentsLoading ? 'Loading agents...' : 'Select agents...'}+ searchPlaceholder="Search agents..."+ emptyLabel="No agents available."+ selectionLabel="Selected agents"/></Field>- {loadingContextAccess ? (- <p className="cu-muted">Loading context access…</p>- ) : contextRef ? (+ {loadingAccessPreview ? (+ <p className="cu-muted">Loading agent access…</p>+ ) : selectedAgentNames.length > 0 ? (<>- {contextAccessError ? (+ {accessPreviewError ? (<p className="cu-banner cu-banner--warn" role="status">- {contextAccessError}+ {accessPreviewError}</p>) : null}- <div className="cu-registry-context-access__intro">+ <div className="cu-entity-access__intro"><span>Access preview</span>- <p>These people and agents can use this connector in {contextRef}.</p>+ <p>+ These people already have access to the selected agents and will be able to+ use this connector.+ </p></div>- <section className="cu-registry-context-access" aria-label="Context access">- {CONTEXT_ACCESS_GROUPS.map(group => (+ <section className="cu-entity-access" aria-label="Agent access preview">+ <section className="cu-entity-access__group" data-kind="agents">+ <div className="cu-entity-access__heading">+ <h4>Agents</h4>+ <span>{selectedAgentNames.length}</span>+ </div>+ <ul className="cu-entity-access__list">+ {selectedAgentNames.map(agentName => {+ const target = agentTargets.find(+ candidate => candidate.name === agentName+ )+ return (+ <li key={agentName}>+ <span>{target?.label ?? agentName}</span>+ </li>+ )+ })}+ </ul>+ </section>+ {ACCESS_PREVIEW_GROUPS.map(group => (<section- className="cu-registry-context-access__group"+ className="cu-entity-access__group"data-kind={group.key}key={group.key}>- <div className="cu-registry-context-access__heading">+ <div className="cu-entity-access__heading"><h4>{group.title}</h4>- <span>{contextAccess[group.key].length}</span>+ <span>{accessPreview[group.key].length}</span></div>- {contextAccess[group.key].length > 0 ? (- <ul className="cu-registry-context-access__list">- {contextAccess[group.key].map(principal => (+ {accessPreview[group.key].length > 0 ? (+ <ul className="cu-entity-access__list">+ {accessPreview[group.key].map(principal => (<li key={principal.id}><span>{principal.label}</span></li>))}</ul>) : (- <p className="cu-muted">No {group.title.toLowerCase()} have access.</p>+ <p className="cu-muted">+ No {group.title.toLowerCase()} have access yet.+ </p>)}</section>))}diff --git a/control-ui/components/HostWizard/index.tsx b/control-ui/components/HostWizard/index.tsxindex 1f59c6c56..50d2823f4 100644--- a/control-ui/components/HostWizard/index.tsx+++ b/control-ui/components/HostWizard/index.tsx@@ -9,7 +9,6 @@ import { SelectionDropdown } from '@/components/SelectionDropdown'import { useToast } from '@/components/Toast'import { IconAlertTriangle, IconCheck, IconX } from '@/components/icons'import { Button, CheckboxField, Field, TextInput } from '@/components/ui'-import { createAgentContextName } from '@/lib/agentContext'import {apiSend,getAdminTeams,@@ -35,6 +34,7 @@ import {resolveDefaultModel,validateLlmSecretData,} from '@/lib/llm'+import { createPrivateContext } from '@/lib/privateContext'import { toKebabCase, toKebabInput } from '@/lib/string'import {HOST_NAMESPACE,@@ -136,39 +136,6 @@ async function createOrThrow(path: string, body: unknown, collisionMessage: stri}}-async function createPrivateContext(- agentName: string,- selectedMcpServers: string[],- collisionMessage: string-): Promise<string> {- // A generated context name is an implementation detail. Hide the rare- // collision from the operator by trying one fresh suffix before surfacing the- // existing friendly error. The successful name is returned to become the- // Host's contextRef.- for (let attempt = 0; attempt < 2; attempt += 1) {- const contextName = createAgentContextName(agentName)- try {- await createOrThrow(- '/api/v1/admin/contexts',- {- metadata: { name: contextName },- spec: {- contextId: contextName,- description: `Connector context for agent ${agentName}`,- mcpServers: selectedMcpServers,- },- },- collisionMessage- )- return contextName- } catch (error) {- if (!(error instanceof ResourceNameCollisionError) || attempt === 1) throw error- }- }-- throw new Error(collisionMessage)-}-function isStepValid(stepIndex: number, state: HostWizardValidationState): boolean {if (stepIndex === 0)return state.hostName.trim().length > 0 && getAgentNameError(state.hostName) === ''@@ -570,8 +537,11 @@ export function HostWizard({// intentionally generated here instead of being exposed as a wizard// field; the agent still needs a contextRef for its runtime contract.const generatedContextName = await createPrivateContext(- normalizedHostName,- Array.from(new Set(selectedMcp)),+ {+ subject: normalizedHostName,+ description: `Connector context for agent ${normalizedHostName}`,+ mcpServers: Array.from(new Set(selectedMcp)),+ },'We couldn’t finish setting up this agent’s connectors — please try again.')created.push({ kind: 'context', name: generatedContextName })diff --git a/control-ui/components/McpServerTable.tsx b/control-ui/components/McpServerTable.tsxindex 48da3eeb1..6eb487cc3 100644--- a/control-ui/components/McpServerTable.tsx+++ b/control-ui/components/McpServerTable.tsx@@ -4,7 +4,7 @@ import React, { Fragment, useMemo, useState } from 'react'import { copyTextToClipboard } from '../lib/clipboard'import type {ConnectorAccessSummary,- ConnectorContextBinding,+ ConnectorAgentBinding,McpServerStatus,McpServerTableProps,} from './McpServerTable.types'@@ -18,7 +18,7 @@ import type { TableHeaderColumn } from './TableHeaderRow/types'import { TablePanelHeader } from './TablePanelHeader'import { IconChevronRight, IconCopy, IconRefresh, IconX } from './icons'-const ENABLED_TOOLTIP = 'Enabled controls whether this server is available to contexts and agents.'+const ENABLED_TOOLTIP = 'Enabled controls whether this server is available to agents.'type ConnectorSortKey = 'name' | 'enabled' | 'status'type SortDirection = 'asc' | 'desc'@@ -95,9 +95,8 @@ function middleEllipsis(value: string, maxLength = 26): string {return `${value.slice(0, startLength)}...${value.slice(-(visibleLength - startLength))}`}-function AccessSummary({ summary }: { summary?: ConnectorAccessSummary }) {+function AccessReadGroups({ summary }: { summary?: ConnectorAccessSummary }) {const groups = [- { key: 'agents', label: 'Agents', items: summary?.agents ?? [] },{ key: 'teams', label: 'Teams', items: summary?.teams ?? [] },{ key: 'users', label: 'Users', items: summary?.users ?? [] },]@@ -105,17 +104,13 @@ function AccessSummary({ summary }: { summary?: ConnectorAccessSummary }) {return (<>{groups.map(group => (- <section- className="cu-registry-context-access__group"- data-kind={group.key}- key={group.key}- >- <div className="cu-registry-context-access__heading">+ <section className="cu-entity-access__group" data-kind={group.key} key={group.key}>+ <div className="cu-entity-access__heading"><h4>{group.label}</h4><span>{group.items.length}</span></div>{group.items.length > 0 ? (- <ul className="cu-registry-context-access__list">+ <ul className="cu-entity-access__list">{group.items.map(principal => (<li key={principal.id} title={principal.label}><span>{principal.label}</span>@@ -131,74 +126,68 @@ function AccessSummary({ summary }: { summary?: ConnectorAccessSummary }) {)}-function ConnectorContexts({+function ConnectorAgentsGroup({connectorName,namespace,- contexts,+ bindings,busy,- onOpenContext,onAdd,onRemove,}: {connectorName: stringnamespace: string- contexts: ConnectorContextBinding[]+ bindings: ConnectorAgentBinding[]busy: boolean- onOpenContext?: (contextName: string) => voidonAdd?: () => void- onRemove?: McpServerTableProps['onRemoveFromContext']+ onRemove?: McpServerTableProps['onRemoveFromAgents']}) {- const linkedContexts = contexts.map(context => ({ name: context.name, removable: true }))+ const agentCount = bindings.reduce((total, binding) => total + binding.agents.length, 0)return (- <section className="cu-registry-context-access__group" data-kind="contexts">- <div className="cu-registry-context-access__heading">- <h4>Contexts</h4>- <span>{linkedContexts.length}</span>+ <section className="cu-entity-access__group" data-kind="agents">+ <div className="cu-entity-access__heading">+ <h4>Agents</h4>+ <span>{agentCount}</span></div>- {linkedContexts.length > 0 ? (- <ul className="cu-registry-context-access__list cu-connector-context-access__list">- {linkedContexts.map(context => (- <li key={context.name}>- <span className="cu-connector-context-access__name" title={context.name}>- {onOpenContext ? (+ {agentCount > 0 ? (+ <ul className="cu-entity-access__list cu-connector-agent-access__list">+ {bindings.flatMap(binding =>+ binding.agents.map(agent => (+ <li key={`${binding.contextRef}/${agent.id}`}>+ <span className="cu-connector-agent-access__name" title={agent.label}>+ {agent.label}+ </span>+ {onRemove ? (<buttontype="button"- className="cu-link"- onClick={() => onOpenContext(context.name)}+ className="cu-btn cu-btn--icon cu-btn--danger-icon cu-connector-agent-access__remove"+ disabled={busy}+ aria-label={`Remove connector ${connectorName} from agent ${agent.label}`}+ title={+ binding.agents.length > 1+ ? `Remove from ${binding.agents.map(a => a.label).join(', ')}`+ : `Remove from ${agent.label}`+ }+ onClick={() => void onRemove({ namespace, name: connectorName }, binding)}>- {context.name}+ <IconX width={14} height={14} /></button>- ) : (- context.name- )}- </span>- {context.removable && onRemove ? (- <button- type="button"- className="cu-btn cu-btn--icon cu-btn--danger-icon cu-connector-context-access__remove"- disabled={busy}- aria-label={`Remove connector ${connectorName} from context ${context.name}`}- title={`Remove from ${context.name}`}- onClick={() => void onRemove({ namespace, name: connectorName }, context.name)}- >- <IconX width={14} height={14} />- </button>- ) : null}- </li>- ))}+ ) : null}+ </li>+ ))+ )}</ul>) : (- <p className="cu-muted">No contexts linked.</p>+ <p className="cu-muted">No agents have access yet.</p>)}{onAdd ? (<buttontype="button"- className="cu-btn cu-btn--secondary cu-btn--sm cu-connector-context-access__add"+ className="cu-btn cu-btn--secondary cu-btn--sm cu-connector-agent-access__add"disabled={busy}onClick={onAdd}>- Add contexts+ Add agents</button>) : null}</section>@@ -255,11 +244,11 @@ function CopyableValue({export function McpServerTable({items,accessByConnectorKey,- contexts = [],- onOpenContext,- onAddToContexts,- onRemoveFromContext,- updatingContextMembershipKey,+ agentBindingsByConnectorName = {},+ agentTargets = [],+ onAddToAgents,+ onRemoveFromAgents,+ updatingAgentAccessKey,onDelete,onEdit,deletingKey,@@ -274,8 +263,8 @@ export function McpServerTable({const [sortKey, setSortKey] = useState<ConnectorSortKey | null>(null)const [sortDirection, setSortDirection] = useState<SortDirection>('asc')const [expandedKeys, setExpandedKeys] = useState<Set<string>>(new Set())- const [serverKeyAddingContexts, setServerKeyAddingContexts] = useState<string | null>(null)- const [selectedContextNamesToAdd, setSelectedContextNamesToAdd] = useState<string[]>([])+ const [serverKeyAddingAgents, setServerKeyAddingAgents] = useState<string | null>(null)+ const [selectedAgentNamesToAdd, setSelectedAgentNamesToAdd] = useState<string[]>([])const [copiedValueKey, setCopiedValueKey] = useState<string | null>(null)const rows = useMemo(() =>@@ -382,19 +371,19 @@ export function McpServerTable({return column})- function contextsForConnector(name: string): ConnectorContextBinding[] {- return contexts.filter(context => context.mcpServers.includes(name))+ function bindingsForConnector(name: string): ConnectorAgentBinding[] {+ return agentBindingsByConnectorName[name] ?? []}- function openAddContexts(key: string) {- setSelectedContextNamesToAdd([])- setServerKeyAddingContexts(key)+ function openAddAgents(key: string) {+ setSelectedAgentNamesToAdd([])+ setServerKeyAddingAgents(key)}- function closeAddContexts() {- if (updatingContextMembershipKey) return- setSelectedContextNamesToAdd([])- setServerKeyAddingContexts(null)+ function closeAddAgents() {+ if (updatingAgentAccessKey) return+ setSelectedAgentNamesToAdd([])+ setServerKeyAddingAgents(null)}async function copyValue(copyKey: string, value: string) {@@ -428,7 +417,7 @@ export function McpServerTable({/>) : null}- subtitle="Browse connector deployments and context bindings."+ subtitle="Browse connector deployments and agent access."actionsClassName="cu-table-panel__actions--mcp"actions={<>@@ -493,8 +482,8 @@ export function McpServerTable({{filteredRows.map(({ key, namespace, name, item }) => {const spec = item.spec || {}const expanded = expandedKeys.has(key)- const assignedContexts = contextsForConnector(name)- const contextMembershipBusy = updatingContextMembershipKey === key+ const agentBindings = bindingsForConnector(name)+ const agentAccessBusy = updatingAgentAccessKey === keyreturn (<Fragment key={key}><tr@@ -611,19 +600,18 @@ export function McpServerTable({<div className="cu-expandable-field cu-expandable-field--wide cu-connector-access-field"><span className="cu-expandable-field__label">Access</span><section- className="cu-registry-context-access cu-connector-access-grid"+ className="cu-entity-access cu-connector-access-grid"aria-label="Connector access">- <ConnectorContexts+ <ConnectorAgentsGroupconnectorName={name}namespace={namespace}- contexts={assignedContexts}- busy={contextMembershipBusy}- onOpenContext={onOpenContext}- onAdd={onAddToContexts ? () => openAddContexts(key) : undefined}- onRemove={onRemoveFromContext}+ bindings={agentBindings}+ busy={agentAccessBusy}+ onAdd={onAddToAgents ? () => openAddAgents(key) : undefined}+ onRemove={onRemoveFromAgents}/>- <AccessSummary summary={accessByConnectorKey?.[key]} />+ <AccessReadGroups summary={accessByConnectorKey?.[key]} /></section></div></div>@@ -638,44 +626,45 @@ export function McpServerTable({</table></div>)}- {serverKeyAddingContexts+ {serverKeyAddingAgents? (() => {- const row = rows.find(candidate => candidate.key === serverKeyAddingContexts)- if (!row || !onAddToContexts) return null- const assignedNames = new Set(- contextsForConnector(row.name).map(context => context.name)+ const row = rows.find(candidate => candidate.key === serverKeyAddingAgents)+ if (!row || !onAddToAgents) return null+ const boundAgentNames = new Set(+ bindingsForConnector(row.name).flatMap(binding =>+ binding.agents.map(agent => agent.id)+ ))- const contextOptions = contexts- .filter(context => !assignedNames.has(context.name))- .map(context => ({- value: context.name,- label: context.name,- description: context.description || undefined,+ const agentOptions = agentTargets+ .filter(target => !boundAgentNames.has(target.name))+ .map(target => ({+ value: target.name,+ label: target.label,}))- const busy = updatingContextMembershipKey === row.key+ const busy = updatingAgentAccessKey === row.keyreturn (<divclassName="cu-modal-backdrop"role="presentation"onClick={event => {- if (event.target === event.currentTarget && !busy) closeAddContexts()+ if (event.target === event.currentTarget && !busy) closeAddAgents()}}><divclassName="cu-modal-panel cu-modal-panel--selection"role="dialog"aria-modal="true"- aria-labelledby="add-connector-context-title"+ aria-labelledby="add-connector-agents-title"onClick={event => event.stopPropagation()}><div className="cu-modal-panel__head">- <h3 id="add-connector-context-title" className="cu-modal-panel__title">- Add connector to contexts+ <h3 id="add-connector-agents-title" className="cu-modal-panel__title">+ Give agents access to this connector</h3><buttontype="button"className="cu-btn cu-btn--icon cu-btn--ghost"- onClick={closeAddContexts}+ onClick={closeAddAgents}disabled={busy}aria-label="Close">@@ -684,17 +673,17 @@ export function McpServerTable({</div><div className="cu-field">- <label htmlFor="connector-context-picker">Contexts</label>+ <label htmlFor="connector-agent-picker">Agents</label><SelectionDropdown- id="connector-context-picker"+ id="connector-agent-picker"inline- value={selectedContextNamesToAdd}- onChange={setSelectedContextNamesToAdd}- options={contextOptions}- placeholder="Select contexts"- searchPlaceholder="Search contexts..."- selectionLabel="Selected contexts"- emptyLabel="No available contexts."+ value={selectedAgentNamesToAdd}+ onChange={setSelectedAgentNamesToAdd}+ options={agentOptions}+ placeholder="Select agents"+ searchPlaceholder="Search agents..."+ selectionLabel="Selected agents"+ emptyLabel="No other agents available."disabled={busy}/></div>@@ -703,7 +692,7 @@ export function McpServerTable({<buttontype="button"className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={closeAddContexts}+ onClick={closeAddAgents}disabled={busy}>Cancel@@ -712,17 +701,23 @@ export function McpServerTable({type="button"className="cu-btn cu-btn--primary"onClick={async () => {- if (selectedContextNamesToAdd.length === 0) return- await onAddToContexts(+ if (selectedAgentNamesToAdd.length === 0) return+ const selected = agentTargets.filter(target =>+ selectedAgentNamesToAdd.includes(target.name)+ )+ await onAddToAgents({ namespace: row.namespace, name: row.name },- selectedContextNamesToAdd+ selected.map(target => ({+ name: target.name,+ contextRef: target.contextRef,+ })))- setSelectedContextNamesToAdd([])- setServerKeyAddingContexts(null)+ setSelectedAgentNamesToAdd([])+ setServerKeyAddingAgents(null)}}- disabled={busy || selectedContextNamesToAdd.length === 0}+ disabled={busy || selectedAgentNamesToAdd.length === 0}>- {selectedContextNamesToAdd.length > 1 ? 'Add to contexts' : 'Add to context'}+ {selectedAgentNamesToAdd.length > 1 ? 'Add to agents' : 'Add to agent'}</button></div></div>diff --git a/control-ui/components/McpServerTable.types.ts b/control-ui/components/McpServerTable.types.tsindex 4aa4383d0..02a016560 100644--- a/control-ui/components/McpServerTable.types.ts+++ b/control-ui/components/McpServerTable.types.ts@@ -50,20 +50,33 @@ export type McpServerItem = {export type ServerRef = { name: string; namespace: string }-export type ConnectorContextBinding = {+// One write-unit of connector access: the agents that share the underlying+// private context. The contextRef is internal plumbing for the owning page's+// PUT and is never rendered.+export type ConnectorAgentBinding = {+ contextRef: string+ agents: ConnectorAccessPrincipal[]+}++// An agent the operator can grant a connector to. Carries the agent's private+// contextRef so the page can resolve the write target without another lookup.+export type ConnectorAgentTarget = {name: string- description?: string- mcpServers: string[]+ label: string+ contextRef: string}export type McpServerTableProps = {items: McpServerItem[]accessByConnectorKey?: Record<string, ConnectorAccessSummary>- contexts?: ConnectorContextBinding[]- onOpenContext?: (contextName: string) => void- onAddToContexts?: (server: ServerRef, contextNames: string[]) => Promise<void>- onRemoveFromContext?: (server: ServerRef, contextName: string) => Promise<void>- updatingContextMembershipKey?: string | null+ agentBindingsByConnectorName?: Record<string, ConnectorAgentBinding[]>+ agentTargets?: ConnectorAgentTarget[]+ onAddToAgents?: (+ server: ServerRef,+ agents: Array<{ name: string; contextRef: string }>+ ) => Promise<void>+ onRemoveFromAgents?: (server: ServerRef, binding: ConnectorAgentBinding) => Promise<void>+ updatingAgentAccessKey?: string | nullonDelete?: (server: ServerRef) => Promise<void>onEdit?: (server: ServerRef) => voiddeletingKey?: string | nulldiff --git a/control-ui/components/RegistryInstallForm/index.tsx b/control-ui/components/RegistryInstallForm/index.tsxindex 90db02927..5fac2d99b 100644--- a/control-ui/components/RegistryInstallForm/index.tsx+++ b/control-ui/components/RegistryInstallForm/index.tsx@@ -3,27 +3,19 @@import React, { useEffect, useMemo, useRef, useState } from 'react'import { CreateStepFlow } from '@components/CreateStepFlow'import { EgressEditor } from '@components/EgressEditor'-import { SelectionDropdown } from '@components/SelectionDropdown'import { IconCheck } from '@components/icons'import { Button } from '@components/ui'-import { getAgentDisplayName } from '@lib/agentName'import type { CredentialSchema } from '@lib/api'-import {- getContextTeams,- getContextUsers,- getContexts,- getHosts,- getRegistryCredentialSchema,- installFromRegistry,-} from '@lib/api'+import { getRegistryCredentialSchema, installFromRegistry } from '@lib/api'import { registryEntryToEgressBindings } from '@lib/egressModel'import type { EgressBinding, EgressEditorStatus } from '@lib/egressModel'import { isValidK8sName, toK8sName } from '@lib/k8sValidation'import { buildPastedValue } from '@lib/pasteUtils'+import { createPrivateContext } from '@lib/privateContext'import { getEmbeddedCredentialSchema } from '../registryInstallHelpers'import type { RegistryInstallFormProps } from './types'-const STEPS = ['Package', 'Context', 'Credentials', 'Install'] as const+const STEPS = ['Package', 'Credentials', 'Install'] as constconst STEP_DETAILS = [{@@ -31,11 +23,6 @@ const STEP_DETAILS = [title: 'Marketplace package',subtitle: 'Review the package and optionally adjust its installation configuration.',},- {- description: 'Choose connector access',- title: 'Context',- subtitle: 'Choose where to install this connector and review who can use it.',- },{description: 'Add connector credentials',title: 'Credentials',@@ -48,20 +35,6 @@ const STEP_DETAILS = [},] as const-type ContextAccess = {- agents: Array<{ id: string; label: string }>- teams: Array<{ id: string; label: string }>- users: Array<{ id: string; label: string }>-}--const EMPTY_CONTEXT_ACCESS: ContextAccess = { agents: [], teams: [], users: [] }--const CONTEXT_ACCESS_GROUPS: Array<{ key: keyof ContextAccess; title: string }> = [- { key: 'users', title: 'Users' },- { key: 'teams', title: 'Teams' },- { key: 'agents', title: 'Agents' },-]-export function RegistryInstallForm({entry,onCancel,@@ -72,8 +45,6 @@ export function RegistryInstallForm({// Default to a K8s-valid name derived from the scoped registry name (e.g.// `@org/name` → `org-name`); `entry.name` itself is not a valid resource name.const [serverName, setServerName] = useState(toK8sName(entry.name))- const [contextRef, setContextRef] = useState('')- const [contexts, setContexts] = useState<Array<{ name: string }>>([])const [credSchema, setCredSchema] = useState<CredentialSchema | null>(null)const [credValues, setCredValues] = useState<Record<string, string>>({})const [loading, setLoading] = useState(true)@@ -81,9 +52,6 @@ export function RegistryInstallForm({const [error, setError] = useState('')const [egressBindings, setEgressBindings] = useState<EgressBinding[] | undefined>(undefined)const [egressStatus, setEgressStatus] = useState<EgressEditorStatus | null>(null)- const [contextAccess, setContextAccess] = useState<ContextAccess>(EMPTY_CONTEXT_ACCESS)- const [contextAccessError, setContextAccessError] = useState('')- const [loadingContextAccess, setLoadingContextAccess] = useState(false)const [installed, setInstalled] = useState(false)const installInFlightRef = useRef(false)const registryInitialEgressBindings = useMemo(() => registryEntryToEgressBindings(entry), [entry])@@ -96,28 +64,14 @@ export function RegistryInstallForm({setCredValues({})setEgressBindings(registryInitialEgressBindings)setEgressStatus(null)- setContextAccess(EMPTY_CONTEXT_ACCESS)- setContextAccessError('')setInstalled(false)setLoading(true);(async () => {try {- const [schema, ctxResult] = await Promise.all([- getRegistryCredentialSchema(entry.name, entry.version).catch(() =>- getEmbeddedCredentialSchema(entry)- ),- getContexts(),- ])+ const schema = await getRegistryCredentialSchema(entry.name, entry.version).catch(() =>+ getEmbeddedCredentialSchema(entry)+ )setCredSchema(schema)- const ctxItems = (ctxResult.items ?? [])- .map(c => ({- name: (c.metadata as Record<string, string>)?.name ?? '',- }))- .filter(c => c.name)- setContexts(ctxItems)- if (ctxItems.length > 0) {- setContextRef(prev => prev || ctxItems[0].name)- }} catch (loadError) {setError(loadError instanceof Error ? loadError.message : 'Failed to load configuration')} finally {@@ -126,66 +80,6 @@ export function RegistryInstallForm({})()}, [entry, registryInitialEgressBindings])- useEffect(() => {- const selectedContext = contextRef.trim()- if (!selectedContext) {- setContextAccess(EMPTY_CONTEXT_ACCESS)- setContextAccessError('')- setLoadingContextAccess(false)- return- }-- let cancelled = false- setLoadingContextAccess(true)- setContextAccessError('')-- void (async () => {- const [usersResult, teamsResult, hostsResult] = await Promise.allSettled([- getContextUsers(selectedContext),- getContextTeams(selectedContext),- getHosts(),- ])- if (cancelled) return-- const failed =- usersResult.status === 'rejected' ||- teamsResult.status === 'rejected' ||- hostsResult.status === 'rejected'- setContextAccess({- users:- usersResult.status === 'fulfilled'- ? (usersResult.value.items ?? []).map(user => ({- id: user.id,- label: user.displayName || user.name || user.email || user.id,- }))- : [],- teams:- teamsResult.status === 'fulfilled'- ? (teamsResult.value.items ?? []).map(team => ({ id: team.id, label: team.name }))- : [],- agents:- hostsResult.status === 'fulfilled'- ? (hostsResult.value.items ?? [])- .filter(host => String(host.spec?.contextRef ?? '').trim() === selectedContext)- .map(host => {- const name = host.metadata?.name || 'unknown'- return { id: name, label: getAgentDisplayName(name) || name }- })- : [],- })- setContextAccessError(- failed- ? 'Some access information could not be loaded. The lists below may be incomplete.'- : ''- )- setLoadingContextAccess(false)- })()-- return () => {- cancelled = true- }- }, [contextRef])-const nameValid = isValidK8sName(serverName)const credHasKeys = (credSchema?.keys?.length ?? 0) > 0const credRequired = !!credSchema?.required && credHasKeys@@ -203,18 +97,14 @@ export function RegistryInstallForm({egressStatus !== null &&egressStatus.errors.length === 0 &&!(remoteRequiresEgress && egressStatus.mode === 'none')- const canSubmit =- nameValid && contextRef.trim() !== '' && credComplete && egressValid && !installing+ const canSubmit = nameValid && credComplete && egressValid && !installingconst packageComplete = !loading && nameValid && egressValid- const contextComplete = contextRef.trim() !== ''- const canContinue =- step === 0 ? packageComplete : step === 1 ? contextComplete : step === 2 ? credComplete : true+ const canContinue = step === 0 ? packageComplete : step === 1 ? credComplete : truefunction canSelectStep(targetStep: number) {if (targetStep <= step) return trueif (targetStep === 1) return packageComplete- if (targetStep === 2) return packageComplete && contextComplete- return packageComplete && contextComplete && credComplete+ return packageComplete && credComplete}async function handleInstall() {@@ -239,6 +129,18 @@ export function RegistryInstallForm({? []: egressBindings+ // The install contract needs an access scope on the wire. It is an+ // implementation detail: a private scope is generated silently (same+ // pattern as agent creation) and the operator grants agents from the+ // Installed Connectors list afterwards.+ const contextRef = await createPrivateContext(+ {+ subject: serverName || entry.name,+ description: `Connector access scope for ${serverName || entry.name}`,+ },+ 'We couldn’t prepare this connector’s access — please try again.'+ )+await installFromRegistry({serverName: serverName || undefined,contextRef,@@ -272,7 +174,7 @@ export function RegistryInstallForm({<><CreateStepFlowariaLabel="Install connector steps"- className="cu-create-step-flow--4 cu-registry-install-flow"+ className="cu-create-step-flow--3 cu-registry-install-flow"currentStep={step}onStepChange={setStep}canSelectStep={canSelectStep}@@ -361,81 +263,6 @@ export function RegistryInstallForm({) : null}{step === 1 ? (- <div className="cu-agent-form-stack cu-agent-form-stack--wide">- <section className="cu-form-section">- <div className="cu-form-section__header">- <h3 className="cu-form-section__title">Context access</h3>- <p className="cu-form-section__description">- Choose the context where this connector will be available. The access lists- update for the selected context.- </p>- </div>- <div className="cu-field cu-field--compact">- <label>Context</label>- <SelectionDropdown- id="ri-context"- multiple={false}- value={contextRef ? [contextRef] : []}- onChange={next => setContextRef(next[0] ?? '')}- options={contexts.map(context => ({- value: context.name,- label: context.name,- }))}- placeholder="Select a context..."- searchPlaceholder="Search contexts..."- selectionLabel="Context"- showSelectedChips={false}- emptyLabel="No contexts available."- />- </div>-- {loadingContextAccess ? (- <p className="cu-muted">Loading context access…</p>- ) : contextRef ? (- <>- {contextAccessError ? (- <p className="cu-banner cu-banner--warn" role="status">- {contextAccessError}- </p>- ) : null}- <div className="cu-registry-context-access__intro">- <span>Access preview</span>- <p>These people and agents can use this connector in {contextRef}.</p>- </div>- <section className="cu-registry-context-access" aria-label="Context access">- {CONTEXT_ACCESS_GROUPS.map(group => (- <section- className="cu-registry-context-access__group"- data-kind={group.key}- key={group.key}- >- <div className="cu-registry-context-access__heading">- <h4>{group.title}</h4>- <span>{contextAccess[group.key].length}</span>- </div>- {contextAccess[group.key].length > 0 ? (- <ul className="cu-registry-context-access__list">- {contextAccess[group.key].map(principal => (- <li key={principal.id}>- <span>{principal.label}</span>- </li>- ))}- </ul>- ) : (- <p className="cu-muted">- No {group.title.toLowerCase()} have access.- </p>- )}- </section>- ))}- </section>- </>- ) : null}- </section>- </div>- ) : null}-- {step === 2 ? (<div className="cu-agent-form-stack cu-agent-form-stack--wide">{credHasKeys ? (<fieldset className="cu-form-section">@@ -483,17 +310,13 @@ export function RegistryInstallForm({</div>) : null}- {step === 3 ? (- <div className="cu-form-stack cu-agent-form-stack--wide">+ {step === 2 ? (+ <div className="cu-form-stack cu-agent-form-stack cu-agent-form-stack--wide"><section className="cu-summary-list" aria-label="Install summary"><div className="cu-summary-list__row"><span>Connector</span><strong>{serverName || '-'}</strong></div>- <div className="cu-summary-list__row">- <span>Context</span>- <strong>{contextRef || '-'}</strong>- </div><div className="cu-summary-list__row"><span>Marketplace package</span><strong>{entry.name}</strong>@@ -509,31 +332,10 @@ export function RegistryInstallForm({Connector access</h3><p className="cu-form-section__description">- Members, teams, and agents with access to <strong>{contextRef}</strong> will- be able to use this connector.+ After installing, choose which agents can use this connector from the+ Installed Connectors list.</p></div>- {loadingContextAccess ? (- <p className="cu-muted">Loading connector access…</p>- ) : (- <section- className="cu-registry-install-access-summary"- aria-label="Connector access principals"- >- {CONTEXT_ACCESS_GROUPS.map(group => (- <div className="cu-registry-install-access-summary__row" key={group.key}>- <span>{group.key === 'users' ? 'Members' : group.title}</span>- <strong>- {contextAccess[group.key].length > 0- ? contextAccess[group.key]- .map(principal => principal.label)- .join(', ')- : `No ${group.key === 'users' ? 'members' : group.title.toLowerCase()}`}- </strong>- </div>- ))}- </section>- )}</section></div>) : null}@@ -581,9 +383,9 @@ export function RegistryInstallForm({Congratulations — you're ready to go</h2><p id="registry-install-success-copy" className="cu-modal-copy">- <strong>{serverName}</strong> is available in <strong>{contextRef}</strong>. You can- now use it in the desktop app; visit Connectors to check its status or adjust its- settings.+ <strong>{serverName}</strong> is installed. Give agents access from the Installed+ Connectors list whenever you're ready; visit Connectors to check its status or+ adjust its settings.</p></div><div className="cu-modal-panel__foot cu-registry-install-success__actions">diff --git a/control-ui/components/RegistryInstallModal.tsx b/control-ui/components/RegistryInstallModal.tsxdeleted file mode 100644index 4374c460a..000000000--- a/control-ui/components/RegistryInstallModal.tsx+++ /dev/null@@ -1,461 +0,0 @@-'use client'--import React, { useEffect, useMemo, useRef, useState } from 'react'-import type { CredentialSchema, RegistryEntry } from '../lib/api'-import { getContexts, getRegistryCredentialSchema, installFromRegistry } from '../lib/api'-import { registryEntryToEgressBindings } from '../lib/egressModel'-import type { EgressBinding, EgressEditorStatus } from '../lib/egressModel'-import { isValidK8sName, toK8sName } from '../lib/k8sValidation'-import { buildPastedValue } from '../lib/pasteUtils'-import { trustBgColor, trustColor } from '../lib/trustLevel'-import { EgressEditor } from './EgressEditor'-import { useToast } from './Toast'-import { getEmbeddedCredentialSchema, getExternalEgressNotice } from './registryInstallHelpers'--interface Props {- entry: RegistryEntry- isOpen: boolean- onClose: () => void- onInstalled: () => void-}--export function RegistryInstallModal({ entry, isOpen, onClose, onInstalled }: Props) {- const { showToast } = useToast()- // Default to a K8s-valid name derived from the scoped registry name (e.g.- // `@org/name` → `org-name`); `entry.name` itself is not a valid resource name.- const [serverName, setServerName] = useState(toK8sName(entry.name))- const [contextRef, setContextRef] = useState('')- const [contexts, setContexts] = useState<Array<{ name: string }>>([])- const [credSchema, setCredSchema] = useState<CredentialSchema | null>(null)- const [credValues, setCredValues] = useState<Record<string, string>>({})- const [loading, setLoading] = useState(true)- const [installing, setInstalling] = useState(false)- const [error, setError] = useState('')- const [egressBindings, setEgressBindings] = useState<EgressBinding[] | undefined>(undefined)- const [egressStatus, setEgressStatus] = useState<EgressEditorStatus | null>(null)- const installInFlightRef = useRef(false)- const registryInitialEgressBindings = useMemo(() => registryEntryToEgressBindings(entry), [entry])-- // Load credential schema + contexts on open- useEffect(() => {- if (!isOpen) return- installInFlightRef.current = false- setServerName(toK8sName(entry.name))- setError('')- setCredValues({})- setEgressBindings(registryInitialEgressBindings)- setEgressStatus(null)- setLoading(true)- ;(async () => {- try {- const [schema, ctxResult] = await Promise.all([- getRegistryCredentialSchema(entry.name, entry.version).catch(() =>- getEmbeddedCredentialSchema(entry)- ),- getContexts(),- ])- setCredSchema(schema)- const ctxItems = (ctxResult.items ?? [])- .map(c => ({- name: (c.metadata as Record<string, string>)?.name ?? '',- }))- .filter(c => c.name)- setContexts(ctxItems)- if (ctxItems.length > 0) {- setContextRef(prev => prev || ctxItems[0].name)- }- } catch (err) {- setError(err instanceof Error ? err.message : 'Failed to load configuration')- } finally {- setLoading(false)- }- })()- }, [isOpen, entry.name, entry.version, registryInitialEgressBindings])-- if (!isOpen) return null-- const nameValid = isValidK8sName(serverName)- const credHasKeys = (credSchema?.keys?.length ?? 0) > 0- const credRequired = !!credSchema?.required && credHasKeys- const credStarted =- credRequired && credSchema!.keys.some(k => (credValues[k.name] ?? '').trim() !== '')- const missingCredentialKeys =- credRequired && credStarted- ? credSchema!.keys.filter(k => !(credValues[k.name] ?? '').trim()).map(k => k.label || k.name)- : []- const credComplete = !credStarted || missingCredentialKeys.length === 0- const externalEgressNotice = getExternalEgressNotice(entry)- const remoteRequiresEgress = entry.server_mode === 'remote'- const egressValid =- egressStatus !== null &&- egressStatus.errors.length === 0 &&- !(remoteRequiresEgress && egressStatus.mode === 'none')- const canSubmit =- nameValid && contextRef.trim() !== '' && credComplete && egressValid && !installing- const externalTargetsText = externalEgressNotice?.targets.length- ? externalEgressNotice.targets.join(', ')- : 'public internet'- const externalPortsText = externalEgressNotice?.ports.join(', ') ?? ''-- async function handleInstall() {- if (!canSubmit || installInFlightRef.current) return-- installInFlightRef.current = true- setInstalling(true)- setError('')-- try {- const filled = credHasKeys- ? Object.fromEntries(- credSchema!.keys- .map(k => [k.name, credValues[k.name] ?? ''])- .filter(([, v]) => (v as string).trim() !== '')- )- : {}- const credentials: Record<string, string> | undefined =- Object.keys(filled).length > 0 ? filled : undefined- const selectedEgressBindings =- egressStatus?.mode === 'none' && (registryInitialEgressBindings?.length ?? 0) > 0- ? []- : egressBindings-- await installFromRegistry({- serverName: serverName || undefined,- contextRef,- registryEntryName: entry.name,- registryEntryVersion: entry.version,- credentials,- egressBindings: selectedEgressBindings,- })-- showToast(`"${serverName}" was installed and added to context "${contextRef}".`, {- tone: 'success',- })- setCredValues({})- onInstalled()- } catch (err) {- setError(err instanceof Error ? err.message : 'Installation failed')- } finally {- installInFlightRef.current = false- setInstalling(false)- }- }-- function pasteCredentialValue(keyName: string, event: React.ClipboardEvent<HTMLInputElement>) {- const pasted = event.clipboardData.getData('text')- if (!pasted) return- event.preventDefault()-- const current = credValues[keyName] ?? ''- const nextValue = buildPastedValue(current, pasted, event.currentTarget)- setCredValues(previous => ({ ...previous, [keyName]: nextValue }))- }-- return (- <div- style={{- position: 'fixed',- inset: 0,- background: 'rgba(0,0,0,0.6)',- display: 'flex',- alignItems: 'center',- justifyContent: 'center',- zIndex: 1100,- padding: '1rem',- }}- role="presentation"- onClick={e => {- if (e.target === e.currentTarget) {- setCredValues({})- onClose()- }- }}- >- <div- className="cu-modal-panel"- style={{- width: 'min(36rem, 96vw)',- maxHeight: '90vh',- overflow: 'auto',- padding: '1.5rem',- }}- role="dialog"- aria-modal="true"- onClick={e => e.stopPropagation()}- >- <h3- style={{- margin: '0 0 1rem',- fontSize: '1.125rem',- fontWeight: 600,- color: 'var(--cu-text)',- }}- >- Install Connector from Marketplace- </h3>-- {externalEgressNotice && (- <div- role="alert"- style={{- background: '#3a3a1a',- border: '1px solid #996a3a',- borderRadius: 'var(--cu-radius-sm)',- padding: '0.75rem 1rem',- marginBottom: '0.75rem',- fontSize: '0.8rem',- color: '#fff8a0',- display: 'flex',- gap: '0.5rem',- alignItems: 'flex-start',- lineHeight: 1.4,- }}- >- <span aria-hidden="true" style={{ fontSize: '1rem', lineHeight: 1 }}>- ⚠️- </span>- <span>- {externalEgressNotice.isRemote- ? 'Remote connector.'- : externalEgressNotice.wideCidr- ? 'Public web egress required.'- : 'External API access required.'}{' '}- {externalEgressNotice.wideCidr- ? 'Installing this CRD explicitly authorizes public web egress via NetworkPolicy rules on TCP ports '- : 'Installing this CRD explicitly authorizes outbound egress via NetworkPolicy rules to '}- {!externalEgressNotice.wideCidr && <strong>{externalTargetsText}</strong>}- {!externalEgressNotice.wideCidr && ' on port'}- {!externalEgressNotice.wideCidr &&- (externalEgressNotice.ports.length > 1 ? 's ' : ' ')}- {externalEgressNotice.wideCidr && (- <>- <strong>{externalPortsText}</strong>. Private, metadata, cluster-internal,- link-local, multicast, and reserved ranges remain blocked.- {externalEgressNotice.targets.length > 0 && (- <>- {' '}- Listed domains ({externalTargetsText}) are examples and not the complete- enforcement boundary.- </>- )}- </>- )}- {!externalEgressNotice.wideCidr && <strong>{externalPortsText}</strong>}- {!externalEgressNotice.wideCidr && '.'} This expands to{' '}- <strong>{externalEgressNotice.bindingCount}</strong> egress binding- {externalEgressNotice.bindingCount === 1 ? '' : 's'}.- {externalEgressNotice.isRemote && (- <>- {' '}- Credentials will be securely stored in K8s and forwarded via the egress proxy. The- pod runs nginx in our cluster, NOT the vendor’s image.- </>- )}- {externalEgressNotice.blockingError && (- <span style={{ display: 'block', marginTop: 8, color: '#ff8ea7', fontWeight: 700 }}>- {externalEgressNotice.blockingError}- </span>- )}- </span>- </div>- )}-- {/* Entry details */}- <div- style={{- background: 'var(--cu-bg-elevated)',- borderRadius: 'var(--cu-radius-sm)',- padding: '0.75rem 1rem',- marginBottom: '1rem',- fontSize: '0.875rem',- }}- >- <div- style={{- display: 'flex',- gap: '0.5rem',- alignItems: 'baseline',- marginBottom: '0.25rem',- }}- >- <strong style={{ color: 'var(--cu-text)' }}>{entry.name}</strong>- <span style={{ color: 'var(--cu-text-muted)' }}>v{entry.version}</span>- <span- style={{- fontSize: '0.75rem',- padding: '1px 6px',- borderRadius: 4,- background: trustBgColor(entry.trust_level),- color: trustColor(entry.trust_level),- }}- >- {entry.trust_level}- </span>- </div>- {entry.description && (- <p style={{ margin: 0, color: 'var(--cu-text-muted)', lineHeight: 1.4 }}>- {entry.description}- </p>- )}- {entry.mcp_server_meta?.tools && entry.mcp_server_meta.tools.length > 0 && (- <div style={{ marginTop: '0.5rem', display: 'flex', gap: 4, flexWrap: 'wrap' }}>- {entry.mcp_server_meta.tools.slice(0, 8).map(t => (- <span- key={t}- style={{- fontSize: '0.7rem',- padding: '1px 5px',- borderRadius: 3,- background: 'var(--cu-bg-surface)',- color: 'var(--cu-text-muted)',- }}- >- {t}- </span>- ))}- {entry.mcp_server_meta.tools.length > 8 && (- <span style={{ fontSize: '0.7rem', color: 'var(--cu-text-muted)' }}>- +{entry.mcp_server_meta.tools.length - 8} more- </span>- )}- </div>- )}- </div>-- {loading ? (- <div style={{ textAlign: 'center', padding: '2rem', color: 'var(--cu-text-muted)' }}>- Loading configuration...- </div>- ) : (- <form- onSubmit={e => {- e.preventDefault()- handleInstall()- }}- >- {/* Server name */}- <div className="cu-field">- <label htmlFor="ri-name">Server Name</label>- <input- id="ri-name"- className="cu-input"- value={serverName}- onChange={e =>- setServerName(e.target.value.toLowerCase().replace(/[^a-z0-9-]/g, ''))- }- placeholder="my-mcp-server"- />- {serverName && !nameValid && (- <p- style={{ fontSize: '0.75rem', color: 'var(--cu-danger)', margin: '0.25rem 0 0' }}- >- Must be a valid K8s name (lowercase, alphanumeric, hyphens, max 63 chars)- </p>- )}- </div>-- {/* Context selector */}- <div className="cu-field">- <label htmlFor="ri-context">Context</label>- <select- id="ri-context"- className="cu-input"- value={contextRef}- onChange={e => setContextRef(e.target.value)}- >- <option value="">Select a context...</option>- {contexts.map(c => (- <option key={c.name} value={c.name}>- {c.name}- </option>- ))}- </select>- </div>-- {/* API key / token credential form */}- {credHasKeys && (- <fieldset- style={{- border: '1px solid var(--cu-border)',- borderRadius: 'var(--cu-radius-sm)',- padding: '0.75rem 1rem',- marginBottom: '1rem',- }}- >- <legend- style={{- fontSize: '0.85rem',- fontWeight: 600,- color: 'var(--cu-text-muted)',- padding: '0 0.25rem',- }}- >- Credentials ({credSchema!.authType}- {credRequired ? '' : ' — optional'})- </legend>- {credSchema!.keys.map(key => (- <div className="cu-field" key={key.name}>- <label htmlFor={`ri-cred-${key.name}`}>{key.label}</label>- <input- id={`ri-cred-${key.name}`}- className="cu-input"- type={key.kind === 'api-key' || key.kind === 'password' ? 'password' : 'text'}- value={credValues[key.name] ?? ''}- onChange={e =>- setCredValues(prev => ({ ...prev, [key.name]: e.target.value }))- }- onPaste={event => pasteCredentialValue(key.name, event)}- autoComplete="new-password"- placeholder={key.description}- />- </div>- ))}- {credRequired ? (- <div- className={`cu-banner ${credStarted && !credComplete ? 'cu-banner--error' : 'cu-banner--info'}`}- style={{ marginTop: '0.75rem' }}- >- {credStarted && !credComplete- ? `Complete all credential fields or clear them all to install pending. Missing: ${missingCredentialKeys.join(', ')}.`- : 'Leave all credential fields empty to install now and add this connector secret later from Secrets, or fill every field to create it during install.'}- </div>- ) : null}- </fieldset>- )}-- <EgressEditor- allowCidr- description="Review and adjust the egress contract that will be installed from this Marketplace entry. The final CRD is created from this selection, not from the Marketplace warning alone."- initialBindings={registryInitialEgressBindings}- key={`${entry.name}-${entry.version}-${JSON.stringify(registryInitialEgressBindings ?? [])}`}- onChange={(nextBindings, status) => {- setEgressBindings(nextBindings)- setEgressStatus(status)- }}- />- {remoteRequiresEgress && egressStatus?.mode === 'none' ? (- <div className="cu-banner cu-banner--error" role="alert">- Remote connectors must keep exact-host egress to the selected vendor endpoint.- </div>- ) : null}-- {error && (- <div className="cu-banner cu-banner--error" style={{ marginBottom: '1rem' }}>- {error}- </div>- )}-- <div style={{ display: 'flex', justifyContent: 'flex-end', gap: '0.5rem' }}>- <button type="button" className="cu-btn" onClick={onClose} disabled={installing}>- Cancel- </button>- <button type="submit" className="cu-btn cu-btn--primary" disabled={!canSubmit}>- {installing ? 'Installing...' : 'Install'}- </button>- </div>- </form>- )}- </div>- </div>- )-}diff --git a/control-ui/components/__tests__/ConnectorEditContext.test.tsx b/control-ui/components/__tests__/ConnectorEditContext.test.tsxindex 57e8d238d..b0367c192 100644--- a/control-ui/components/__tests__/ConnectorEditContext.test.tsx+++ b/control-ui/components/__tests__/ConnectorEditContext.test.tsx@@ -7,7 +7,7 @@ import { buildContextList, buildContextResource } from '../../test/fixtures/contconst replace = vi.fn()const push = vi.fn()-let activeTab = 'context'+let activeTab = 'access'vi.mock('next/navigation', () => ({useParams: () => ({ name: 'search', tab: activeTab }),@@ -50,10 +50,10 @@ vi.mock('../../lib/api', async importOriginal => {afterEach(() => {cleanup()vi.clearAllMocks()- activeTab = 'context'+ activeTab = 'access'})-describe('connector edit Context access', () => {+describe('connector edit agent access', () => {it('does not expose a stale legacy contextRef after allowlist membership is removed', async () => {vi.mocked(api.getMcpServer).mockResolvedValue({metadata: { name: 'search' },@@ -70,7 +70,10 @@ describe('connector edit Context access', () => {render(<EditMcpServerPage />)- expect(await screen.findByLabelText('Connector contexts')).toHaveTextContent('Contexts: None')+ expect(+ await screen.findByText('No agents have access to this connector yet.')+ ).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Agent access' })).toBeInTheDocument()expect(screen.queryByText('removed-context')).not.toBeInTheDocument()await waitFor(() => expect(api.getMcpServer).toHaveBeenCalledWith('search'))expect(api.getContextUsers).not.toHaveBeenCalled()@@ -78,7 +81,7 @@ describe('connector edit Context access', () => {expect(api.getHosts).not.toHaveBeenCalled()})- it('keeps credentials and egress usable when the Context list is unavailable', async () => {+ it('keeps credentials and egress usable when the agent access list is unavailable', async () => {vi.mocked(api.getMcpServer).mockResolvedValue({metadata: { name: 'search' },spec: { image: 'example/search:latest' },@@ -88,7 +91,7 @@ describe('connector edit Context access', () => {const { rerender } = render(<EditMcpServerPage />)expect(await screen.findByRole('alert')).toHaveTextContent(- 'Context access data is unavailable. Try again later.'+ 'Agent access data is unavailable. Try again later.')activeTab = 'credentials'diff --git a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx b/control-ui/components/__tests__/CreateMcpServerForm.test.tsxindex 1739dbf00..0146ad5ee 100644--- a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx+++ b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx@@ -7,23 +7,17 @@ import { ToastProvider } from '../Toast'// vi.mock is hoisted before imports; factory runs lazily so references to `api` are safe.vi.mock('../../lib/api', async () => {- const { buildContextList, buildContextResource } =- await import('../../test/fixtures/contextResource')+ const { buildContextResource } = await import('../../test/fixtures/contextResource')const context1 = buildContextResource({metadata: { name: 'context1', resourceVersion: 'rv-context1' },})return {+ apiSend: vi.fn().mockResolvedValue({}),createMcpServer: vi.fn().mockResolvedValue({ metadata: { name: 'test-server' } }),createMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),deleteMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),- getContexts: vi.fn().mockResolvedValue(- buildContextList([- context1,- buildContextResource({- metadata: { name: 'research', resourceVersion: 'rv-research' },- }),- ])- ),+ // The form no longer reads the context list; kept as a spy to lock that contract.+ getContexts: vi.fn(),getContext: vi.fn().mockResolvedValue(context1),getContextTeams: vi.fn().mockResolvedValue({ items: [] }),getContextUsers: vi.fn().mockResolvedValue({ items: [] }),@@ -43,7 +37,7 @@ function render(children: ReactNode) {}async function fillIdentity(name = 'brave-search') {- await waitFor(() => expect(api.getContexts).toHaveBeenCalledTimes(1))+ await waitFor(() => expect(api.getHosts).toHaveBeenCalledTimes(1))fireEvent.change(screen.getByPlaceholderText('my-mcp-server'), {target: { value: name },})@@ -53,6 +47,22 @@ async function fillIdentity(name = 'brave-search') {)}+function goToAccessStep() {+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+}++function continueToSecretsStep() {+ // Already on the Access step: a single Continue lands on Secrets.+ fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+}++async function selectAgents(...labels: string[]) {+ fireEvent.click(await screen.findByRole('button', { name: 'Select agents...' }))+ for (const label of labels) {+ fireEvent.click(screen.getByRole('option', { name: label }))+ }+}+function openAdvanced() {fireEvent.click(screen.getByText('Advanced options'))}@@ -89,19 +99,37 @@ describe('CreateMcpServerForm — render', () => {expect(continueButton).not.toBeDisabled()})- it('loads available contexts into the dedicated Context step', async () => {+ it('loads available agents into the dedicated Access step', async () => {+ vi.mocked(api.getHosts).mockResolvedValueOnce({+ items: [+ { metadata: { name: 'agents/product' }, spec: { contextRef: 'context1' } },+ { metadata: { name: 'research-agent' }, spec: { contextRef: 'research' } },+ // Hosts without a contextRef are not selectable agent targets.+ { metadata: { name: 'orphan-agent' } },+ ],+ })render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)await fillIdentity()- fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ goToAccessStep()+await waitFor(() =>- expect(screen.getByRole('heading', { name: 'Context access' })).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Agent access' })).toBeInTheDocument())- const contextSelector = screen.getByRole('button', { name: 'context1' })- fireEvent.click(contextSelector)+ expect(+ screen.getByText(+ /^Optionally choose the agents that can use this connector right away\. You can also grant access later/+ )+ ).toBeInTheDocument()++ fireEvent.click(await screen.findByRole('button', { name: 'Select agents...' }))- expect(screen.getByRole('option', { name: 'context1' })).toBeInTheDocument()- expect(screen.getByRole('option', { name: 'research' })).toBeInTheDocument()+ // Agent options are labeled with the derived display name.+ expect(screen.getByRole('option', { name: 'product' })).toBeInTheDocument()+ expect(screen.getByRole('option', { name: 'research-agent' })).toBeInTheDocument()+ expect(screen.queryByRole('option', { name: 'orphan-agent' })).not.toBeInTheDocument()+ // The context concept is gone from this flow.+ expect(api.getContexts).not.toHaveBeenCalled()})it('selects an organization image and fills its full registry coordinate', async () => {@@ -129,14 +157,18 @@ describe('CreateMcpServerForm — render', () => {).toBeInTheDocument()})- it('uses connector, context, and secrets steps', () => {+ it('uses connector, access, and secrets steps', () => {const { container } = render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)expect(container.querySelectorAll('.cu-agent-step-rail__item')).toHaveLength(3)+ const stepTitles = Array.from(container.querySelectorAll('.cu-agent-step-rail__title')).map(+ element => element.textContent+ )+ expect(stepTitles).toEqual(['Connector', 'Access', 'Secrets'])expect(screen.queryByText('Step 1 of 3')).not.toBeInTheDocument()expect(screen.queryByText('Step 1 of 4')).not.toBeInTheDocument()})- it('previews the selected context access before continuing to secrets', async () => {+ it('previews who can use the connector for selected agents', async () => {vi.mocked(api.getContextUsers).mockResolvedValueOnce({items: [{ id: 'user-1', displayName: 'Josue', email: '[email protected]', name: 'josue' }],})@@ -149,11 +181,17 @@ describe('CreateMcpServerForm — render', () => {render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)await fillIdentity()- fireEvent.click(screen.getByRole('button', { name: 'Continue' }))-- expect(await screen.findByText('Josue')).toBeInTheDocument()- expect(screen.getByText('Development Team')).toBeInTheDocument()- expect(screen.getByText('product')).toBeInTheDocument()+ goToAccessStep()+ await selectAgents('product')++ const preview = await screen.findByLabelText('Agent access preview')+ expect(screen.getByText('Access preview')).toBeInTheDocument()+ expect(preview).toHaveTextContent('product')+ expect(preview).toHaveTextContent('Josue')+ expect(preview).toHaveTextContent('Development Team')+ // Users/teams are resolved through the selected agent's scope.+ expect(api.getContextUsers).toHaveBeenCalledWith('context1')+ expect(api.getContextTeams).toHaveBeenCalledWith('context1')})it('hides the advanced options by default and reveals them on toggle', async () => {@@ -277,10 +315,21 @@ describe('CreateMcpServerForm — submit', () => {chooseNoCredentials()}- it('calls createMcpServer and adds the server to the Context allowlist on submit', async () => {+ it('creates the connector in the selected agents’ scope with one write per context', async () => {+ // Two agents sharing one contextRef must produce exactly one allowlist write.+ vi.mocked(api.getHosts).mockResolvedValueOnce({+ items: [+ { metadata: { name: 'agents/product' }, spec: { contextRef: 'context1' } },+ { metadata: { name: 'research-agent' }, spec: { contextRef: 'context1' } },+ ],+ })const onCreated = vi.fn()render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={onCreated} />)- await fillRequired()+ await fillIdentity()+ goToAccessStep()+ await selectAgents('product', 'research-agent')+ continueToSecretsStep()+ chooseNoCredentials()const submit = screen.getByRole('button', { name: 'Create connector' })await waitFor(() => expect(submit).not.toBeDisabled())@@ -289,7 +338,8 @@ describe('CreateMcpServerForm — submit', () => {await waitFor(() => {expect(api.createMcpServer).toHaveBeenCalledTimes(1)})- // Spec shape: streamableHttp default, managed: true default, in-cluster URL from the name+ // Spec shape: streamableHttp default, managed: true default, in-cluster URL from the name.+ // The connector is attached to the selected agents' contextRef.const createCall = (api.createMcpServer as ReturnType<typeof vi.fn>).mock.calls[0][0]expect(createCall).toMatchObject({metadata: { name: 'brave-search' },@@ -305,8 +355,10 @@ describe('CreateMcpServerForm — submit', () => {},},})+ // With agents selected no private scope is created.+ expect(api.apiSend).not.toHaveBeenCalled()- // Context allowlist update+ // Allowlist update: one read + one additive write for the shared contextRef.await waitFor(() => {expect(api.getContext).toHaveBeenCalledWith('context1')expect(api.updateContext).toHaveBeenCalledTimes(1)@@ -323,6 +375,80 @@ describe('CreateMcpServerForm — submit', () => {await waitFor(() => expect(onCreated).toHaveBeenCalledTimes(1), { timeout: 1500 })})+ it('creates a private access scope when no agents are selected', async () => {+ const onCreated = vi.fn()+ render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={onCreated} />)+ await fillIdentity()+ // Skip the optional Access step without selecting any agent.+ continueToSecrets()+ chooseNoCredentials()++ const submit = screen.getByRole('button', { name: 'Create connector' })+ await waitFor(() => expect(submit).not.toBeDisabled())+ fireEvent.click(submit)++ await waitFor(() => {+ expect(api.apiSend).toHaveBeenCalledWith('POST', '/api/v1/admin/contexts', expect.any(Object))+ })+ const scopeCall = vi+ .mocked(api.apiSend)+ .mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/contexts')+ expect(scopeCall).toBeDefined()+ const scopeBody = scopeCall![2] as {+ metadata: { name: string }+ spec: { contextId: string; description: string; mcpServers: string[] }+ }+ expect(scopeBody.metadata.name).toMatch(/^brave-search-[0-9]{5}$/)+ expect(scopeBody.spec.contextId).toBe(scopeBody.metadata.name)+ expect(scopeBody.spec.description).toBe('Connector access scope for brave-search')+ expect(scopeBody.spec.mcpServers).toEqual(['brave-search'])++ // The generated scope name becomes the created McpServer's contextRef.+ await waitFor(() => {+ expect(api.createMcpServer).toHaveBeenCalledTimes(1)+ })+ const createCall = (api.createMcpServer as ReturnType<typeof vi.fn>).mock.calls[0][0]+ expect(createCall.spec.contextRef).toBe(scopeBody.metadata.name)++ // No allowlist writes on this path.+ expect(api.getContext).not.toHaveBeenCalled()+ expect(api.updateContext).not.toHaveBeenCalled()+ expect(screen.getByText('Connector created successfully.')).toBeInTheDocument()+ await waitFor(() => expect(onCreated).toHaveBeenCalledTimes(1), { timeout: 1500 })+ })++ it('reports a partial failure when the access write rejects after creation', async () => {+ vi.mocked(api.getHosts).mockResolvedValueOnce({+ items: [{ metadata: { name: 'agents/product' }, spec: { contextRef: 'context1' } }],+ })+ ;(api.updateContext as ReturnType<typeof vi.fn>).mockRejectedValueOnce(+ new Error('context write failed')+ )+ const onCreated = vi.fn()+ render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={onCreated} />)+ await fillIdentity()+ goToAccessStep()+ await selectAgents('product')+ continueToSecretsStep()+ chooseNoCredentials()++ const submit = screen.getByRole('button', { name: 'Create connector' })+ await waitFor(() => expect(submit).not.toBeDisabled())+ fireEvent.click(submit)++ await waitFor(() => {+ expect(api.createMcpServer).toHaveBeenCalledTimes(1)+ expect(+ screen.getByText(+ `Connector created, but we couldn't give access to product. ` ++ `Grant "brave-search" to those agents from the Installed Connectors list.`+ )+ ).toBeInTheDocument()+ })+ expect(onCreated).not.toHaveBeenCalled()+ expect(screen.queryByText('Connector created successfully.')).not.toBeInTheDocument()+ })+it('submits exact-host egress bindings when configured', async () => {render(<CreateMcpServerForm onCancel={vi.fn()} onCreated={vi.fn()} />)await fillIdentity()diff --git a/control-ui/components/__tests__/McpServerTable.test.tsx b/control-ui/components/__tests__/McpServerTable.test.tsxindex 6cceb78e5..17dec6878 100644--- a/control-ui/components/__tests__/McpServerTable.test.tsx+++ b/control-ui/components/__tests__/McpServerTable.test.tsx@@ -1,7 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { buildContextResource } from '../../test/fixtures/contextResource'import { McpServerTable } from '../McpServerTable'+import type { ConnectorAgentBinding } from '../McpServerTable.types'afterEach(() => {cleanup()@@ -58,22 +58,6 @@ function makeItem(overrides: {return item}-function makeContextBinding(options: {- name: string- description?: string- mcpServers?: string[]-}) {- const context = buildContextResource({- metadata: { name: options.name },- spec: { description: options.description ?? '', mcpServers: options.mcpServers ?? [] },- })- return {- name: context.metadata.name,- description: context.spec.description,- mcpServers: context.spec.mcpServers,- }-}-// ─────────────────────────────────────────────────────────────────────────────// StatusBadge precedence// ─────────────────────────────────────────────────────────────────────────────@@ -254,18 +238,31 @@ describe('McpServerTable — connector access summaries', () => {items={items}accessByConnectorKey={{'mcp-server/airtable-server': {- agents: [- { id: 'agent-alpha', label: 'agent-alpha' },- { id: 'bravo', label: 'bravo' },- { id: 'charlie', label: 'charlie' },- { id: 'delta', label: 'delta' },- { id: 'echo', label: 'echo' },- { id: 'foxtrot', label: 'foxtrot' },- ],+ agents: [],users: [{ id: 'user-1', label: 'Ada Lovelace' }],teams: [{ id: 'team-1', label: 'Research' }],},}}+ agentBindingsByConnectorName={{+ 'airtable-server': [+ {+ contextRef: 'ctx-research',+ agents: [+ { id: 'agent-alpha', label: 'agent-alpha' },+ { id: 'bravo', label: 'bravo' },+ { id: 'charlie', label: 'charlie' },+ ],+ },+ {+ contextRef: 'ctx-sales',+ agents: [+ { id: 'delta', label: 'delta' },+ { id: 'echo', label: 'echo' },+ { id: 'foxtrot', label: 'foxtrot' },+ ],+ },+ ],+ }}/>)@@ -275,6 +272,11 @@ describe('McpServerTable — connector access summaries', () => {expect(access).toHaveTextContent('Agents')expect(access).toHaveTextContent('Teams')expect(access).toHaveTextContent('Users')+ expect(screen.queryByText('ctx-research')).not.toBeInTheDocument()+ expect(screen.queryByText('ctx-sales')).not.toBeInTheDocument()++ const agentsHeading = screen.getByRole('heading', { name: 'Agents' })+ expect(agentsHeading.parentElement).toHaveTextContent('6')for (const label of ['agent-alpha',@@ -295,7 +297,7 @@ describe('McpServerTable — connector access summaries', () => {render(<McpServerTable items={items} />)fireEvent.click(screen.getByText('unused-server').closest('tr')!)- expect(screen.getByText('No agents have access.')).toBeInTheDocument()+ expect(screen.getByText('No agents have access yet.')).toBeInTheDocument()expect(screen.getByText('No teams have access.')).toBeInTheDocument()expect(screen.getByText('No users have access.')).toBeInTheDocument()})@@ -309,7 +311,11 @@ describe('McpServerTable — connector access summaries', () => {configurable: true,value: { writeText },})- render(<McpServerTable items={[makeItem({ name: 'airtable-server', image })]} />)+ render(+ <McpServerTable+ items={[makeItem({ name: 'airtable-server', image, contextRef: 'ctx-private-plumbing' })]}+ />+ )fireEvent.click(screen.getByRole('button', { name: 'Expand connector airtable-server' }))@@ -319,7 +325,7 @@ describe('McpServerTable — connector access summaries', () => {label => label.textContent)expect(labels).toEqual(['URL', 'Image', 'Transport', 'Managed'])- expect(metadata).not.toHaveTextContent('Default context')+ expect(metadata).not.toHaveTextContent('ctx-private-plumbing')const compactUrl = screen.getByTitle(url)expect(compactUrl.textContent).toContain('...')@@ -376,15 +382,12 @@ describe('McpServerTable — connector access summaries', () => {})})-describe('McpServerTable — context membership', () => {- it('does not display a stale legacy contextRef without authoritative allowlist membership', () => {+describe('McpServerTable — agent membership', () => {+ it('does not display a stale legacy contextRef when no agent bindings exist', () => {render(<McpServerTableitems={[makeItem({ name: 'airtable-server', contextRef: 'removed-context' })]}- contexts={[- makeContextBinding({ name: 'removed-context' }),- makeContextBinding({ name: 'active-context', mcpServers: ['another-server'] }),- ]}+ agentBindingsByConnectorName={{}}accessByConnectorKey={{}}/>)@@ -392,80 +395,93 @@ describe('McpServerTable — context membership', () => {fireEvent.click(screen.getByRole('button', { name: 'Expand connector airtable-server' }))expect(screen.queryByText('removed-context')).not.toBeInTheDocument()- expect(screen.getByText('No contexts linked.')).toBeInTheDocument()- expect(screen.getByText('No agents have access.')).toBeInTheDocument()+ expect(screen.getByText('No agents have access yet.')).toBeInTheDocument()expect(screen.getByText('No teams have access.')).toBeInTheDocument()expect(screen.getByText('No users have access.')).toBeInTheDocument()})- it('shows attached contexts and lets an operator remove the connector from one', async () => {- const onRemoveFromContext = vi.fn().mockResolvedValue(undefined)- const items = [makeItem({ name: 'airtable-server' })]+ it('shows bound agents and lets an operator remove the connector from one', async () => {+ const onRemoveFromAgents = vi.fn().mockResolvedValue(undefined)+ const researchBinding: ConnectorAgentBinding = {+ contextRef: 'ctx-research',+ agents: [{ id: 'research-agent', label: 'research-agent' }],+ }render(<McpServerTable- items={items}- contexts={[- makeContextBinding({- name: 'research',- description: 'Research tools',- mcpServers: ['airtable-server'],- }),- makeContextBinding({ name: 'sales' }),- ]}- onAddToContexts={vi.fn().mockResolvedValue(undefined)}- onRemoveFromContext={onRemoveFromContext}+ items={[makeItem({ name: 'airtable-server' })]}+ agentBindingsByConnectorName={{ 'airtable-server': [researchBinding] }}+ onRemoveFromAgents={onRemoveFromAgents}/>)fireEvent.click(screen.getByRole('button', { name: 'Expand connector airtable-server' }))- expect(screen.getByRole('heading', { name: 'Contexts' })).toBeInTheDocument()- expect(screen.queryByText('Default', { exact: true })).not.toBeInTheDocument()- expect(screen.getByText('research')).toBeInTheDocument()+ expect(screen.getByRole('heading', { name: 'Agents' })).toBeInTheDocument()+ expect(screen.getByText('research-agent')).toBeInTheDocument()+ expect(screen.queryByText('ctx-research')).not.toBeInTheDocument()+fireEvent.click(screen.getByRole('button', {- name: 'Remove connector airtable-server from context research',+ name: 'Remove connector airtable-server from agent research-agent',}))- expect(onRemoveFromContext).toHaveBeenCalledWith(+ expect(onRemoveFromAgents).toHaveBeenCalledWith({ namespace: 'mcp-server', name: 'airtable-server' },- 'research'+ researchBinding)})- it('uses the Context detail selection modal to add the connector to more contexts', async () => {- const onAddToContexts = vi.fn().mockResolvedValue(undefined)+ it('uses the agent selection modal to give more agents access to the connector', async () => {+ const onAddToAgents = vi.fn().mockResolvedValue(undefined)const items = [makeItem({ name: 'airtable-server' })]render(<McpServerTableitems={items}- contexts={[- makeContextBinding({ name: 'research', mcpServers: ['airtable-server'] }),- makeContextBinding({ name: 'sales', description: 'Sales tools' }),+ agentBindingsByConnectorName={{+ 'airtable-server': [+ {+ contextRef: 'ctx-research',+ agents: [{ id: 'research-agent', label: 'research-agent' }],+ },+ ],+ }}+ agentTargets={[+ { name: 'research-agent', label: 'research-agent', contextRef: 'ctx-research' },+ { name: 'sales-agent', label: 'sales-agent', contextRef: 'ctx-sales' },+ { name: 'support-agent', label: 'support-agent', contextRef: 'ctx-support' },]}- onAddToContexts={onAddToContexts}- onRemoveFromContext={vi.fn().mockResolvedValue(undefined)}+ onAddToAgents={onAddToAgents}+ onRemoveFromAgents={vi.fn().mockResolvedValue(undefined)}/>)fireEvent.click(screen.getByRole('button', { name: 'Expand connector airtable-server' }))- fireEvent.click(screen.getByRole('button', { name: 'Add contexts' }))+ fireEvent.click(screen.getByRole('button', { name: 'Add agents' }))- const dialog = screen.getByRole('dialog', { name: 'Add connector to contexts' })+ const dialog = screen.getByRole('dialog', { name: 'Give agents access to this connector' })expect(dialog).toBeInTheDocument()expect(dialog).toHaveAttribute('aria-modal', 'true')expect(dialog.parentElement).toHaveClass('cu-modal-backdrop')- expect(screen.getByLabelText('Contexts')).toBeInTheDocument()- expect(screen.queryByText('No available contexts.')).not.toBeInTheDocument()+ expect(screen.getByLabelText('Agents')).toBeInTheDocument()+ expect(screen.queryByText('No other agents available.')).not.toBeInTheDocument()++ // Agents already bound to the connector are not offered again.+ expect(screen.queryByRole('option', { name: 'research-agent' })).not.toBeInTheDocument()++ fireEvent.click(screen.getByRole('option', { name: 'sales-agent' }))+ expect(screen.getByRole('button', { name: 'Add to agent' })).toBeInTheDocument()- fireEvent.click(screen.getByRole('option', { name: 'sales' }))- fireEvent.click(screen.getByRole('button', { name: 'Add to context' }))+ fireEvent.click(screen.getByRole('option', { name: 'support-agent' }))+ fireEvent.click(screen.getByRole('button', { name: 'Add to agents' }))await waitFor(() =>- expect(onAddToContexts).toHaveBeenCalledWith(+ expect(onAddToAgents).toHaveBeenCalledWith({ namespace: 'mcp-server', name: 'airtable-server' },- ['sales']+ [+ { name: 'sales-agent', contextRef: 'ctx-sales' },+ { name: 'support-agent', contextRef: 'ctx-support' },+ ]))})diff --git a/control-ui/components/__tests__/RegistryInstallForm.test.tsx b/control-ui/components/__tests__/RegistryInstallForm.test.tsxindex ac9e8411a..982f4e472 100644--- a/control-ui/components/__tests__/RegistryInstallForm.test.tsx+++ b/control-ui/components/__tests__/RegistryInstallForm.test.tsx@@ -5,32 +5,23 @@ import * as api from '../../lib/api'import { RegistryInstallForm } from '../RegistryInstallForm'import { ToastProvider } from '../Toast'-vi.mock('../../lib/api', async () => {- const { buildContextList, buildContextResource } =- await import('../../test/fixtures/contextResource')- const mod: Record<string, unknown> = {}- mod.getRegistryCredentialSchema = vi.fn().mockResolvedValue({+vi.mock('../../lib/api', () => ({+ apiSend: vi.fn().mockResolvedValue({}),+ getRegistryCredentialSchema: vi.fn().mockResolvedValue({required: false,authType: 'none',keys: [],- })- mod.getContexts = vi- .fn()- .mockResolvedValue(buildContextList([buildContextResource({ metadata: { name: 'context1' } })]))- mod.getContextUsers = vi.fn().mockResolvedValue({ items: [] })- mod.getContextTeams = vi.fn().mockResolvedValue({ items: [] })- mod.getHosts = vi.fn().mockResolvedValue({ items: [] })- mod.installFromRegistry = vi.fn().mockResolvedValue({+ }),+ installFromRegistry: vi.fn().mockResolvedValue({serverName: 'brave-search',namespace: 'mcp-server',- contextRef: 'context1',+ contextRef: 'brave-search-00000',contextUpdated: true,registryEntry: 'brave-search',registryVersion: '1.0.0',correlationId: 'test-corr-id',- })- return mod-})+ }),+}))const MOCK_ENTRY: api.RegistryEntry = {id: '1',@@ -99,7 +90,7 @@ describe('RegistryInstallForm -- pending connector credentials', () => {await waitForContinue()fireEvent.click(screen.getByText('Configuration'))expect(screen.queryByLabelText('API Key')).not.toBeInTheDocument()- fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ // Package → Credentials: a single Continue now that the Context step is gone.fireEvent.click(screen.getByRole('button', { name: 'Continue' }))expect(@@ -134,7 +125,7 @@ describe('RegistryInstallForm -- server name default', () => {expect(screen.queryByText(/Must be a valid K8s name/i)).toBeNull()})- it('keeps configuration collapsed and shows Package, Context, Credentials, and Install flow steps', async () => {+ it('keeps configuration collapsed and shows Package, Credentials, and Install flow steps', async () => {const { container } = render(<RegistryInstallForm entry={MOCK_ENTRY} onCancel={vi.fn()} onInstalled={vi.fn()} />)@@ -145,61 +136,74 @@ describe('RegistryInstallForm -- server name default', () => {expect(configuration).not.toBeNull()expect(configuration).not.toHaveAttribute('open')expect(screen.getByRole('button', { name: /Package/ })).toBeInTheDocument()- expect(screen.getByRole('button', { name: /Context/ })).toBeInTheDocument()expect(screen.getByRole('button', { name: /Credentials/ })).toBeInTheDocument()expect(screen.getByRole('button', { name: /Install/ })).toBeInTheDocument()+ // The Context step no longer exists in the flow.+ expect(screen.queryByRole('button', { name: /Context/ })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: /Configure/ })).not.toBeInTheDocument()expect(screen.queryByRole('button', { name: /Network/ })).not.toBeInTheDocument()expect(screen.queryByText('high')).not.toBeInTheDocument()})- it('shows the install details as a stacked summary', async () => {+ it('shows the install details as a stacked summary without a Context row', async () => {render(<RegistryInstallForm entry={MOCK_ENTRY} onCancel={vi.fn()} onInstalled={vi.fn()} />)await waitForContinue()fireEvent.click(screen.getByRole('button', { name: 'Continue' }))fireEvent.click(screen.getByRole('button', { name: 'Continue' }))- fireEvent.click(screen.getByRole('button', { name: 'Continue' }))const summary = screen.getByLabelText('Install summary')expect(summary).toHaveTextContent('Connector')expect(summary).toHaveTextContent('brave-search')- expect(summary).toHaveTextContent('Context')- expect(summary).toHaveTextContent('context1')expect(summary).toHaveTextContent('Marketplace package')expect(summary).toHaveTextContent('Version')- expect(screen.getByRole('region', { name: 'Connector access' })).toBeInTheDocument()- expect(screen.getByRole('region', { name: 'Connector access principals' })).toBeInTheDocument()- })+ expect(summary).not.toHaveTextContent('Context')- it('lists the users, teams, and agents that can access the selected context', async () => {- vi.mocked(api.getContextUsers).mockResolvedValueOnce({- items: [{ id: 'user-1', email: '[email protected]', name: 'Ada', displayName: 'Ada Lovelace' }],- })- vi.mocked(api.getContextTeams).mockResolvedValueOnce({- items: [{ id: 'team-1', name: 'Platform' }],- })- vi.mocked(api.getHosts).mockResolvedValueOnce({- items: [{ metadata: { name: 'research-agent' }, spec: { contextRef: 'context1' } }],- })+ const access = screen.getByRole('region', { name: 'Connector access' })+ expect(access).toHaveTextContent(+ /After installing, choose which agents can use this connector from the Installed Connectors list\./+ )+ expect(+ screen.queryByRole('region', { name: 'Connector access principals' })+ ).not.toBeInTheDocument()+ })+})+describe('RegistryInstallForm -- install', () => {+ it('installs into a generated private scope and passes it as the install contextRef', async () => {render(<RegistryInstallForm entry={MOCK_ENTRY} onCancel={vi.fn()} onInstalled={vi.fn()} />)await waitForContinue()- fireEvent.click(screen.getByRole('button', { name: 'Continue' }))-- const access = await screen.findByLabelText('Context access')- expect(access).toHaveTextContent('Ada Lovelace')- expect(access).toHaveTextContent('Platform')- expect(access).toHaveTextContent('research-agent')-fireEvent.click(screen.getByRole('button', { name: 'Continue' }))fireEvent.click(screen.getByRole('button', { name: 'Continue' }))+ fireEvent.click(screen.getByRole('button', { name: 'Install' }))- const reviewAccess = screen.getByRole('region', { name: 'Connector access' })- expect(reviewAccess).toHaveTextContent('Ada Lovelace')- expect(reviewAccess).toHaveTextContent('Platform')- expect(reviewAccess).toHaveTextContent('research-agent')+ // The private access scope is created before the install request.+ await waitFor(() => {+ expect(api.apiSend).toHaveBeenCalledWith('POST', '/api/v1/admin/contexts', expect.any(Object))+ })+ const scopeCall = vi+ .mocked(api.apiSend)+ .mock.calls.find(call => call[0] === 'POST' && call[1] === '/api/v1/admin/contexts')+ expect(scopeCall).toBeDefined()+ const scopeBody = scopeCall![2] as {+ metadata: { name: string }+ spec: { contextId: string; description: string; mcpServers: string[] }+ }+ expect(scopeBody.metadata.name).toMatch(/^brave-search-[0-9]{5}$/)+ expect(scopeBody.spec.contextId).toBe(scopeBody.metadata.name)+ expect(scopeBody.spec.description).toBe('Connector access scope for brave-search')+ expect(scopeBody.spec.mcpServers).toEqual([])++ await waitFor(() => {+ expect(api.installFromRegistry).toHaveBeenCalledTimes(1)+ })+ const installCall = vi.mocked(api.installFromRegistry).mock.calls[0][0]+ expect(installCall.serverName).toBe('brave-search')+ expect(installCall.contextRef).toBe(scopeBody.metadata.name)+ expect(installCall.contextRef).toMatch(/^brave-search-[0-9]{5}$/)+ expect(installCall.registryEntryName).toBe('brave-search')+ expect(installCall.registryEntryVersion).toBe('1.0.0')})it('shows a success card and lets the user open Connectors after installation', async () => {@@ -216,12 +220,14 @@ describe('RegistryInstallForm -- server name default', () => {await waitForContinue()fireEvent.click(screen.getByRole('button', { name: 'Continue' }))fireEvent.click(screen.getByRole('button', { name: 'Continue' }))- fireEvent.click(screen.getByRole('button', { name: 'Continue' }))fireEvent.click(screen.getByRole('button', { name: 'Install' }))expect(await screen.findByRole('heading', { name: "Congratulations — you're ready to go" })).toBeInTheDocument()+ expect(+ screen.getByText(/is installed\. Give agents access from the Installed Connectors list/)+ ).toBeInTheDocument()expect(screen.queryByText(/was installed and added to context/)).not.toBeInTheDocument()fireEvent.click(screen.getByRole('button', { name: 'Go to Connectors' }))expect(onViewConnectors).toHaveBeenCalledOnce()diff --git a/control-ui/components/__tests__/RegistryInstallModal.test.tsx b/control-ui/components/__tests__/RegistryInstallModal.test.tsxdeleted file mode 100644index 138282815..000000000--- a/control-ui/components/__tests__/RegistryInstallModal.test.tsx+++ /dev/null@@ -1,1031 +0,0 @@-import type { ReactNode } from 'react'-import { afterEach, describe, expect, it, vi } from 'vitest'-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'-import * as api from '../../lib/api'-import { RegistryInstallModal } from '../RegistryInstallModal'-import { ToastProvider } from '../Toast'--// vi.mock is hoisted before imports, factory runs lazily-vi.mock('../../lib/api', async () => {- const mod: Record<string, unknown> = {}- mod.getRegistryCredentialSchema = vi.fn().mockResolvedValue({- required: false,- authType: 'none',- keys: [],- })- mod.getContexts = vi.fn().mockResolvedValue({- items: [{ metadata: { name: 'context1' } }],- })- mod.installFromRegistry = vi.fn().mockResolvedValue({- serverName: 'brave-search',- namespace: 'sandbox-recipes',- contextRef: 'context1',- contextUpdated: true,- registryEntry: 'brave-search',- registryVersion: '1.0.0',- correlationId: 'test-corr-id',- })- mod.createMcpSecret = vi.fn().mockResolvedValue({ name: 'test-credentials' })- mod.createMcpServer = vi.fn().mockResolvedValue({ metadata: { name: 'test-server' } })- mod.getContext = vi.fn().mockResolvedValue({- spec: { contextId: 'context1', mcpServers: [] },- })- mod.updateContext = vi.fn().mockResolvedValue({})- mod.reportRegistryInstall = vi.fn().mockResolvedValue({ acknowledged: true, stored: true })- mod.installRecipeFromRegistry = vi.fn().mockResolvedValue({- recipeName: 'test-recipe',- registryEntry: 'test',- registryVersion: '1.0.0',- correlationId: 'c2',- })- // addServerToContextAllowlist calls the mocked getContext + updateContext- mod.addServerToContextAllowlist = vi.fn(async (serverName: string, contextRef: string) => {- const ctx = await (mod.getContext as Function)(contextRef)- const existing: string[] = ctx.spec?.mcpServers ?? []- if (existing.includes(serverName)) return false- await (mod.updateContext as Function)(contextRef, {- spec: {- contextId: ctx.spec?.contextId ?? contextRef,- description: ctx.spec?.description,- mcpServers: [...existing, serverName],- },- })- return true- })- return mod-})--const MOCK_ENTRY: api.RegistryEntry = {- id: '1',- name: 'brave-search',- version: '1.0.0',- entry_type: 'mcp-server' as const,- description: 'Brave web search',- author: 'test',- origin: 'human-authored',- category: 'search',- tags: ['search'],- trust_level: 'high' as const,- quality_tier: 'verified' as const,- status: 'published',- server_mode: 'local' as const,- transport: 'streamableHttp',- recipe_type: null,- mcp_server_meta: { imageRef: 'brave-search:1.0', port: 3000 },- recipe_meta: null,- artifact_refs: null,- downloads: 42,- installs: 10,- created_at: '2026-01-01T00:00:00Z',-}--const MOCK_LOCAL_EGRESS_ENTRY: api.RegistryEntry = {- ...MOCK_ENTRY,- name: 'airtable-mcp',- description: 'Airtable MCP with outbound API access',- mcp_server_meta: {- imageRef: 'airtable-mcp:1.0',- port: 3000,- egressSummary: {- domains: ['api.airtable.com'],- ports: [443],- wideCidr: false,- },- },-}--const MOCK_TOO_MANY_EGRESS_ENTRY: api.RegistryEntry = {- ...MOCK_ENTRY,- name: 'mcp-whois',- description: 'WHOIS MCP with too many exact-host targets',- mcp_server_meta: {- imageRef: 'mcp-whois:1.0',- port: 3000,- egressSummary: {- domains: [- 'whois.iana.org',- 'whois.verisign-grs.com',- 'whois.nic.io',- 'whois.nic.ai',- 'whois.nic.co',- 'whois.nic.xyz',- 'whois.publicinterestregistry.org',- ],- ports: [43, 80, 443],- wideCidr: false,- },- },-}--function render(children: ReactNode) {- return rtlRender(<ToastProvider>{children}</ToastProvider>)-}--function deferredPromise<T>() {- let resolve!: (value: T | PromiseLike<T>) => void- let reject!: (reason?: unknown) => void- const promise = new Promise<T>((res, rej) => {- resolve = res- reject = rej- })- return { promise, resolve, reject }-}--afterEach(() => {- cleanup()- vi.clearAllMocks()-})--describe('RegistryInstallModal -- render', () => {- it('renders entry details when open', async () => {- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.getByText('brave-search')).toBeInTheDocument()- expect(screen.getByText('v1.0.0')).toBeInTheDocument()- expect(screen.getByText('Brave web search')).toBeInTheDocument()- })-- it('pre-fills server name from entry', async () => {- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const nameInput = screen.getByLabelText('Server Name') as HTMLInputElement- expect(nameInput.value).toBe('brave-search')- })-- it('shows context selector with loaded contexts', async () => {- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const contextSelect = screen.getByLabelText('Context') as HTMLSelectElement- expect(contextSelect).toBeInTheDocument()-- const options = contextSelect.querySelectorAll('option')- const optionTexts = Array.from(options).map(o => o.textContent)- expect(optionTexts).toContain('context1')- })-- it('hides credential form when not required', async () => {- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.queryByRole('group')).not.toBeInTheDocument()- })-- it('shows credential form when required', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockResolvedValueOnce({- required: true,- authType: 'api-key',- keys: [- {- name: 'API_KEY',- label: 'API Key',- kind: 'api-key',- semanticType: 'api-key',- description: 'Your API key',- },- ],- } as api.CredentialSchema)-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.getByRole('group')).toBeInTheDocument()- expect(screen.getByText(/Credentials/)).toBeInTheDocument()- expect(screen.getByLabelText('API Key')).toBeInTheDocument()- })-- it('shows credential form when optional (required=false) but keys exist, and allows submit without filling it', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockResolvedValueOnce({- required: false,- authType: 'api-key',- keys: [- {- name: 'GLASSNODE_API_KEY',- label: 'Glassnode API Key',- kind: 'api-key',- semanticType: 'plain-string',- description: 'Optional for free tier',- },- ],- } as api.CredentialSchema)-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.getByRole('group')).toBeInTheDocument()- expect(screen.getByText(/optional/i)).toBeInTheDocument()- expect(screen.getByLabelText('Glassnode API Key')).toBeInTheDocument()-- const installButton = screen.getByRole('button', { name: 'Install' })- await waitFor(() => expect(installButton).not.toBeDisabled())-- fireEvent.click(installButton)- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- expect(payload.credentials).toBeUndefined()- })-})--describe('RegistryInstallModal -- validation', () => {- it('Install button disabled when context not selected', async () => {- vi.mocked(api.getContexts).mockResolvedValueOnce({ items: [] })-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).toBeDisabled()- })-})--describe('RegistryInstallModal -- install flow', () => {- it('full install flow calls APIs in order', async () => {- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- // Context should be auto-selected to "context1" (the first available)- const contextSelect = screen.getByLabelText('Context') as HTMLSelectElement- expect(contextSelect.value).toBe('context1')-- // Click Install- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).not.toBeDisabled()- fireEvent.click(installButton)-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })-- // Verify installFromRegistry payload- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- expect(payload.serverName).toBe('brave-search')- expect(payload.contextRef).toBe('context1')- expect(payload.registryEntryName).toBe('brave-search')- expect(payload.registryEntryVersion).toBe('1.0.0')- })-- it('shows success toast on completion', async () => {- const onInstalled = vi.fn()- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={onInstalled}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const installButton = screen.getByRole('button', { name: 'Install' })- fireEvent.click(installButton)-- await waitFor(() => {- expect(screen.getByText(/was installed and added to context/)).toBeInTheDocument()- })-- expect(onInstalled).toHaveBeenCalledTimes(1)- })-- it('shows error when installFromRegistry fails', async () => {- vi.mocked(api.installFromRegistry).mockRejectedValueOnce(- new Error('409 Conflict: server already exists')- )-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const installButton = screen.getByRole('button', { name: 'Install' })- fireEvent.click(installButton)-- await waitFor(() => {- expect(screen.getByText('409 Conflict: server already exists')).toBeInTheDocument()- })-- // Should NOT show success toast- expect(screen.queryByText('Connector Installed')).not.toBeInTheDocument()- expect(screen.queryByText(/was installed and added to context/)).not.toBeInTheDocument()- })-- it('ignores duplicate submits while an install is already in flight', async () => {- const installDeferred = deferredPromise<api.InstallFromRegistryResponse>()- vi.mocked(api.installFromRegistry).mockReturnValueOnce(installDeferred.promise)-- const onInstalled = vi.fn()- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={onInstalled}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const installButton = screen.getByRole('button', { name: 'Install' })- fireEvent.click(installButton)- fireEvent.click(installButton)-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })-- installDeferred.resolve({- installed: true,- serverName: 'brave-search',- namespace: 'sandbox-recipes',- contextRef: 'context1',- contextUpdated: true,- registryEntry: 'brave-search',- registryVersion: '1.0.0',- })-- await waitFor(() => {- expect(screen.getByText(/was installed and added to context/)).toBeInTheDocument()- })- expect(onInstalled).toHaveBeenCalledTimes(1)- })-})--describe('RegistryInstallModal -- visibility', () => {- it('does not render when isOpen is false', () => {- const { container } = render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={false}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- expect(container.querySelector('[role="dialog"]')).toBeNull()- expect(screen.queryByText('Install Connector from Marketplace')).not.toBeInTheDocument()- })-})--// ── Remote server_mode flow ──────────────────────────────────────────────────--const MOCK_REMOTE_ENTRY: api.RegistryEntry = {- id: '2',- name: 'sentry-mcp',- version: '1.0.0',- entry_type: 'mcp-server' as const,- description: 'Sentry MCP for remote monitoring',- author: 'test',- origin: 'human-authored',- category: 'monitoring',- tags: ['monitoring'],- trust_level: 'mid' as const,- quality_tier: 'verified' as const,- status: 'published',- server_mode: 'remote' as const,- transport: 'streamableHttp',- recipe_type: null,- mcp_server_meta: {- imageRef: 'clerum/nginx-egress-proxy:0.1.0',- port: 3000,- remoteEndpoints: [- { url: 'https://mcp.sentry.io/sse', region: 'us', description: 'US endpoint' },- ],- },- recipe_meta: null,- artifact_refs: null,- downloads: 20,- installs: 5,- created_at: '2026-01-01T00:00:00Z',-}--const MOCK_WIDE_CIDR_ENTRY: api.RegistryEntry = {- ...MOCK_ENTRY,- name: 'wide-egress-mcp',- description: 'connector requiring blanket outbound reachability',- mcp_server_meta: {- imageRef: 'wide-egress-mcp:1.0',- port: 3000,- egressSummary: {- domains: [],- ports: [443],- wideCidr: true,- },- },-}--describe('RegistryInstallModal -- remote server flow', () => {- it('test_registryInstallModal_remoteEntry_showsWarningBanner', async () => {- render(- <RegistryInstallModal- entry={MOCK_REMOTE_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const alert = screen.getByRole('alert')- expect(alert).toHaveTextContent(/Remote connector/)- expect(alert).toHaveTextContent(/explicitly authorizes outbound egress/i)- expect(alert).toHaveTextContent(/NetworkPolicy/i)- expect(alert).toHaveTextContent('mcp.sentry.io')- expect(alert).toHaveTextContent('443')- expect(alert).toHaveTextContent(/egress proxy/)- expect(alert).toHaveTextContent(/nginx/)- })-- it('test_registryInstallModal_remoteEntry_payloadIncludesRemoteAndEgress', async () => {- render(- <RegistryInstallModal- entry={MOCK_REMOTE_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).not.toBeDisabled()- fireEvent.click(installButton)-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })-- // Server-side endpoint handles spec building — verify correct entry info is sent- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- expect(payload.serverName).toBe('sentry-mcp')- expect(payload.registryEntryName).toBe('sentry-mcp')- expect(payload.registryEntryVersion).toBe('1.0.0')- expect(payload.contextRef).toBe('context1')- expect(payload.egressBindings).toEqual([{ dns: 'mcp.sentry.io', port: 443, protocol: 'TCP' }])- })-- it('blocks remote MCP install if the operator clears required vendor egress', async () => {- render(- <RegistryInstallModal- entry={MOCK_REMOTE_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- fireEvent.change(screen.getByDisplayValue('Exact-host egress'), {- target: { value: 'none' },- })-- expect(screen.getByText(/Remote connectors must keep exact-host egress/i)).toBeInTheDocument()- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).toBeDisabled()- })-- it('test_registryInstallModal_remoteEntry_sendsCorrectEntryInfo', async () => {- render(- <RegistryInstallModal- entry={MOCK_REMOTE_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const installButton = screen.getByRole('button', { name: 'Install' })- fireEvent.click(installButton)-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })-- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- // Verify registry entry details are passed to server-side endpoint- expect(payload.registryEntryName).toBe('sentry-mcp')- expect(payload.registryEntryVersion).toBe('1.0.0')- })-- it('test_registryInstallModal_localEntry_noWarningBanner', async () => {- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.queryByText(/external connector/)).not.toBeInTheDocument()- })-})--describe('RegistryInstallModal -- external egress notice', () => {- it('shows a stronger warning when the registry entry requests public-web egress', async () => {- render(- <RegistryInstallModal- entry={MOCK_WIDE_CIDR_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.getByText(/Public web egress required/i)).toBeInTheDocument()- expect(- screen.getAllByText((_, node) => node?.textContent?.includes('TCP ports 80, 443') ?? false)- .length- ).toBeGreaterThan(0)- expect(screen.getAllByText(/Private, metadata, cluster-internal/i).length).toBeGreaterThan(0)- expect(screen.queryByText(/wide CIDR/i)).not.toBeInTheDocument()- expect(screen.queryByText(/0\.0\.0\.0\/0/)).not.toBeInTheDocument()- })-})--describe('RegistryInstallModal -- external egress notice', () => {- it('shows explicit NetworkPolicy egress authorization for local entries with external APIs', async () => {- render(- <RegistryInstallModal- entry={MOCK_LOCAL_EGRESS_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const alert = screen.getByRole('alert')- expect(alert).toHaveTextContent(/External API access required/)- expect(alert).toHaveTextContent(/explicitly authorizes outbound egress/i)- expect(alert).toHaveTextContent(/NetworkPolicy/i)- expect(alert).toHaveTextContent('api.airtable.com')- expect(alert).toHaveTextContent('443')- })-- it('blocks install when exact-host metadata expands beyond the CRD maximum', async () => {- render(- <RegistryInstallModal- entry={MOCK_TOO_MANY_EGRESS_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.getAllByText(/expands to 21 egress bindings/i).length).toBeGreaterThan(0)- expect(screen.getByText(/7 domain\(s\) x 3 port\(s\) = 21 binding\(s\)/i)).toBeInTheDocument()- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).toBeDisabled()- })-- it('sends an explicit empty egress override when the operator clears registry egress', async () => {- render(- <RegistryInstallModal- entry={MOCK_LOCAL_EGRESS_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- fireEvent.change(screen.getByDisplayValue('Exact-host egress'), {- target: { value: 'none' },- })-- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).not.toBeDisabled()- fireEvent.click(installButton)-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })- expect(vi.mocked(api.installFromRegistry).mock.calls[0][0].egressBindings).toEqual([])- })-})--describe('RegistryInstallModal -- credential filling', () => {- it('test_registryInstallModal_credFilled_createsSecretBeforeServer', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockResolvedValueOnce({- required: true,- authType: 'api-key',- keys: [- {- name: 'API_KEY',- label: 'API Key',- kind: 'api-key',- semanticType: 'api-key',- description: 'Your API key',- },- ],- } as api.CredentialSchema)-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- // Fill in the credential- const apiKeyInput = screen.getByLabelText('API Key')- fireEvent.change(apiKeyInput, { target: { value: 'sk-test-123' } })-- // Install- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).not.toBeDisabled()- fireEvent.click(installButton)-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })-- // Credentials should be passed to server-side install endpoint- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- expect(payload.credentials).toBeDefined()- expect(payload.credentials!.API_KEY).toBe('sk-test-123')- })-- it('accepts pasted API keys in credential fields', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockResolvedValueOnce({- required: true,- authType: 'api-key',- keys: [- {- name: 'API_KEY',- label: 'API Key',- kind: 'api-key',- semanticType: 'api-key',- description: 'Your API key',- },- ],- } as api.CredentialSchema)-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const apiKeyInput = screen.getByLabelText('API Key') as HTMLInputElement- fireEvent.paste(apiKeyInput, {- clipboardData: {- getData: () => 'sk-pasted-123',- },- })-- expect(apiKeyInput).toHaveValue('sk-pasted-123')- fireEvent.click(screen.getByRole('button', { name: 'Install' }))-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- expect(payload.credentials!.API_KEY).toBe('sk-pasted-123')- })-- it('falls back to embedded credential schema when schema endpoint fails', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockRejectedValueOnce(- new Error('schema unavailable')- )-- render(- <RegistryInstallModal- entry={{- ...MOCK_ENTRY,- mcp_server_meta: {- ...MOCK_ENTRY.mcp_server_meta,- credentialSchema: {- required: true,- authType: 'api-key',- keys: [- {- name: 'API_KEY',- label: 'API Key',- kind: 'api-key',- semanticType: 'api-key',- description: 'Your API key',- },- ],- },- },- }}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(screen.getByLabelText('API Key')).toBeInTheDocument()- expect(- screen.getByText(/Leave all credential fields empty to install now/i)- ).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Install' })).not.toBeDisabled()- })-- it('keeps embedded credential keys when label/kind metadata is missing', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockRejectedValueOnce(- new Error('schema unavailable')- )-- render(- <RegistryInstallModal- entry={{- ...MOCK_ENTRY,- mcp_server_meta: {- ...MOCK_ENTRY.mcp_server_meta,- credentialSchema: {- required: true,- authType: 'api-key',- // This test deliberately omits label/kind to verify the- // component's graceful-fallback behavior. Cast bypasses the- // CredentialKey type requirement for exactly that reason.- // eslint-disable-next-line @typescript-eslint/no-explicit-any- keys: [{ name: 'API_KEY' } as any],- },- },- }}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const fallbackInput = screen.getByLabelText('API_KEY')- expect(fallbackInput).toHaveAttribute('type', 'password')-- fireEvent.change(fallbackInput, { target: { value: 'sk-test-embedded' } })- fireEvent.click(screen.getByRole('button', { name: 'Install' }))-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })-- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- expect(payload.credentials).toEqual({ API_KEY: 'sk-test-embedded' })- })-- it('allows required credentials to stay empty for pending connector secret setup', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockResolvedValueOnce({- required: true,- authType: 'api-key',- keys: [- {- name: 'API_KEY',- label: 'API Key',- kind: 'api-key',- semanticType: 'api-key',- description: 'Your API key',- },- ],- } as api.CredentialSchema)-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- expect(- screen.getByText(/Leave all credential fields empty to install now/i)- ).toBeInTheDocument()- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).not.toBeDisabled()- fireEvent.click(installButton)-- await waitFor(() => {- expect(api.installFromRegistry).toHaveBeenCalledTimes(1)- })- const payload = vi.mocked(api.installFromRegistry).mock.calls[0][0]- expect(payload.credentials).toBeUndefined()- })-- it('blocks partially filled required credentials with a clear message', async () => {- vi.mocked(api.getRegistryCredentialSchema).mockResolvedValueOnce({- required: true,- authType: 'api-key',- keys: [- {- name: 'API_KEY',- label: 'API Key',- kind: 'api-key',- semanticType: 'api-key',- description: 'Your API key',- },- {- name: 'CLIENT_SECRET',- label: 'Client Secret',- kind: 'password',- semanticType: 'api-key',- description: 'Your client secret',- },- ],- } as api.CredentialSchema)-- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- fireEvent.change(screen.getByLabelText('API Key'), { target: { value: 'sk-test-123' } })-- expect(- screen.getByText(- 'Complete all credential fields or clear them all to install pending. Missing: Client Secret.'- )- ).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Install' })).toBeDisabled()- expect(api.installFromRegistry).not.toHaveBeenCalled()- })-})--describe('RegistryInstallModal -- name validation', () => {- it('test_registryInstallModal_invalidName_showsValidationError', async () => {- render(- <RegistryInstallModal- entry={MOCK_ENTRY}- isOpen={true}- onClose={vi.fn()}- onInstalled={vi.fn()}- />- )-- await waitFor(() => {- expect(screen.queryByText('Loading configuration...')).not.toBeInTheDocument()- })-- const nameInput = screen.getByLabelText('Server Name') as HTMLInputElement- // setServerName lowercases the input, so we need to set it directly via onChange- fireEvent.change(nameInput, { target: { value: '-invalid-name-' } })-- // Should show the validation warning- expect(screen.getByText(/Must be a valid K8s name/)).toBeInTheDocument()-- // Install button should be disabled- const installButton = screen.getByRole('button', { name: 'Install' })- expect(installButton).toBeDisabled()- })-})diff --git a/control-ui/lib/privateContext.ts b/control-ui/lib/privateContext.tsnew file mode 100644index 000000000..e926ae7ad--- /dev/null+++ b/control-ui/lib/privateContext.ts@@ -0,0 +1,57 @@+import { createAgentContextName } from './agentContext'+import { apiSend } from './api'++export type PrivateContextDraft = {+ // Subject whose private context this is (agent name or connector server+ // name). Only feeds the generated RFC 1123 name.+ subject: string+ description: string+ mcpServers?: string[]+}++// A code-less 409 from a create-only POST is an unambiguous AlreadyExists name+// collision; a coded 409 (e.g. context_crd_outdated) must keep the server's+// own message. Mirrors the discrimination the agent wizard does at its create+// sites.+function isNameCollision(error: unknown): boolean {+ if (!(error instanceof Error)) return false+ if ((error as Error & { status?: number }).status !== 409) return false+ const body = (error as Error & { body?: { code?: unknown } }).body+ const hasCode = typeof body?.code === 'string' && body.code.length > 0+ return !hasCode+}++/**+ * Creates a private context for the given subject and returns its name.+ *+ * The context is an implementation detail of the subject (agent or Marketplace+ * install), so the name is generated, never chosen by the user, and a rare+ * collision is hidden by retrying once with a fresh suffix before surfacing+ * the friendly failure message.+ */+export async function createPrivateContext(+ draft: PrivateContextDraft,+ failureMessage: string+): Promise<string> {+ for (let attempt = 0; attempt < 2; attempt += 1) {+ const contextName = createAgentContextName(draft.subject)+ try {+ await apiSend('POST', '/api/v1/admin/contexts', {+ metadata: { name: contextName },+ spec: {+ contextId: contextName,+ description: draft.description,+ mcpServers: draft.mcpServers ?? [],+ },+ })+ return contextName+ } catch (error) {+ if (!isNameCollision(error)) throw error+ // Collision: retry once with a fresh suffix, then surface the friendly+ // message instead of the raw apiserver AlreadyExists text.+ if (attempt === 1) break+ }+ }++ throw new Error(failureMessage)+}diff --git a/control-ui/next.config.js b/control-ui/next.config.jsindex cd656fe70..029acc396 100644--- a/control-ui/next.config.js+++ b/control-ui/next.config.js@@ -133,6 +133,12 @@ const nextConfig = {destination: '/agents/:name/connectors',permanent: true,},+ // Connector edit "Context" tab renamed to "Access".+ {+ source: '/connectors/:name/edit/context',+ destination: '/connectors/:name/edit/access',+ permanent: true,+ },{ source: '/marketplace', destination: '/marketplace/connectors', permanent: true },{ source: '/cost-and-usage', destination: '/cost-and-usage/usage', permanent: true },{diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 9371562e4..c7cda9813 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.458",+ "version": "0.1.459","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.458",+ "version": "0.1.459","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-ui/package.json b/control-ui/package.jsonindex 6feb28a82..29e399255 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.458",+ "version": "0.1.459","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/docs/features/control-ui-context-removal.md b/docs/features/control-ui-context-removal.mdindex 0a61e4fc7..58946bf31 100644--- a/docs/features/control-ui-context-removal.md+++ b/docs/features/control-ui-context-removal.md@@ -192,6 +192,7 @@ Tests updated in the same commit: `HostTable.test.tsx` (hover card now asserts a| --- | --- | --- || 2026-08-26 | — | Document created; baseline verified at `a584c259a`; research inventories completed (surfaces + test impact) || 2026-08-26 | 0 | E1/E2/E3 implemented: hover card shows neutral "Connectors" heading (no slug), click opens the agent's own Connectors tab (`onOpenConnectors`), wizard failure copy reworded, error mapping verified interceptor-covered. CSS family renamed (`cu-agent-connectors-summary*`, `cu-host-connectors-*`; dead `cu-host-context-select` removed). Tests: `HostTable.test.tsx` (+slug-never-renders invariant, +click-navigation), `HostWizard.test.tsx` copy. `tsc --noEmit` + full vitest green (1743 passed). No backend changes. |+| 2026-08-26 | 1 | Category B implemented. **B1** connectors list: expanded row now has one write-capable **Agents** group (per-binding remove, shared-scope confirm when a context backs >1 agent, "Add agents" modal picking agents); Teams/Users stay read-only; orphan contexts (no owning agent) are invisible; `McpServerTable` props reworked (`agentBindingsByConnectorName`, `agentTargets`, `onAdd/RemoveFromAgents`, `updatingAgentAccessKey`). **B2** connector edit: tab `context`→`access` ("Access"), section "Agent access", redirect added for `/connectors/:name/edit/context`. **B3** create connector: steps `['Connector','Access','Secrets']`, optional agent multi-select with access preview; no-selection path creates a private scope (CRD requires `spec.contextRef`, so the connector gets its own invisible scope — same as installs); partial-failure copy names agents. **B4** install page form: steps `['Package','Credentials','Install']`, silent private scope per install via new `lib/privateContext.ts` (also adopted by HostWizard); success copy reworded. **B5** CSS renames (`cu-entity-access*`, `cu-connector-agent-access*`). Dead `RegistryInstallModal` + test deleted (zero production importers; documented dead in self-hosted-registry-ux-redesign.md). New shared helper `lib/privateContext.ts` (create-POST with one collision retry; wire shape identical to wizard's). Tests updated: McpServerTable, ConnectorEditContext, CreateMcpServerForm, RegistryInstallForm. Full vitest green (1718 passed), `tsc --noEmit` clean. **No backend changes** (verified: registry install API still receives `contextRef`; McpServer CRD still gets a valid `spec.contextRef`). |## 11. Open questions / follow-ups (non-blocking)