Skip to content

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

TypeScript

fix(access): refresh grants and resolve context aliases

Miguelon Peluchon42bdbeeb354d
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index d55acd55d..5d430cb4d 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.523",
+ "version": "0.1.524",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.523",
+ "version": "0.1.524",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 738922c09..fa90332bd 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.523",
+ "version": "0.1.524",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/services/directory/accessReconciliation.ts b/control-api/src/services/directory/accessReconciliation.ts
index e019fbeb1..b0ed11d12 100644
--- a/control-api/src/services/directory/accessReconciliation.ts
+++ b/control-api/src/services/directory/accessReconciliation.ts
@@ -182,7 +182,7 @@ export async function listActiveContextIds(gateway: K8sGateway): Promise<string[
const contexts = Array.isArray(listed) ? (listed as ContextResource[]) : []
return normalizeUnique(
contexts
- .map(context => context?.metadata?.name)
+ .flatMap(context => [context?.metadata?.name, context?.spec?.contextId])
.filter((value): value is string => typeof value === 'string')
)
}
diff --git a/control-api/test/accessReconciliation.test.ts b/control-api/test/accessReconciliation.test.ts
index ea2783d0d..72ac09735 100644
--- a/control-api/test/accessReconciliation.test.ts
+++ b/control-api/test/accessReconciliation.test.ts
@@ -7,6 +7,7 @@ import {
buildAgentDirectoryEntry,
filterAccessValues,
listActiveAgentNames,
+ listActiveContextIds,
mergeActiveAgentUpdateWithDeletedHistory,
mergeActiveUpdateWithDeletedHistory,
normalizeUnique,
@@ -134,6 +135,21 @@ describe('access reconciliation helpers', () => {
expect(listResource).toHaveBeenCalledWith('hosts', 'mcp-host')
})
+ it('lists both Context resource-name and wire-id aliases as active', async () => {
+ const listResource = vi.fn().mockResolvedValue([
+ { metadata: { name: 'ctx-resource' }, spec: { contextId: 'ctx-wire' } },
+ { metadata: { name: 'ctx-same' }, spec: { contextId: 'ctx-same' } },
+ ])
+ const gateway = { listResource } as unknown as K8sGateway
+
+ await expect(listActiveContextIds(gateway)).resolves.toEqual([
+ 'ctx-resource',
+ 'ctx-wire',
+ 'ctx-same',
+ ])
+ expect(listResource).toHaveBeenCalledWith('contexts', expect.any(String))
+ })
+
it('preserves every deleted agent at the limit and rejects overflow without truncation', () => {
const atLimit = Array.from(
{ length: MAX_DELETED_ACCESS_HISTORY },
diff --git a/control-ui/app/mcp-servers/page.tsx b/control-ui/app/mcp-servers/page.tsx
index 1de79e6d5..1e6eab8a7 100644
--- a/control-ui/app/mcp-servers/page.tsx
+++ b/control-ui/app/mcp-servers/page.tsx
@@ -27,6 +27,7 @@ import {
import type { ContextResource, ContextSpec, HostResource, McpServerResource } from '../../lib/api'
import { mergeAccessSummaries, sortAccessPrincipals } from '../../lib/connectorAccess'
import { connectorContextAssignmentError } from '../../lib/connectorOAuthAccess'
+import { contextAliases, contextForAlias, contextResourceName } from '../../lib/contextIdentity'
import { buildContextUpdatePayload, contextMutationError } from '../../lib/contextMutation'
function resourceName(resource: { metadata?: { name?: string } }): string {
@@ -47,7 +48,7 @@ function getContextRef(resource: { spec?: Record<string, unknown> }): string {
}
function contextName(context: ContextResource): string {
- return String(context.metadata?.name || context.spec?.contextId || '').trim()
+ return contextResourceName(context)
}
function contextSpec(context: ContextResource): ContextSpec {
@@ -82,18 +83,14 @@ 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
+ const aliases = new Set(contextAliases(context))
+ const agents = agentTargets
+ .filter(target => aliases.has(target.contextRef))
+ .map(target => ({ id: target.name, label: target.label }))
+ if (!ref || agents.length === 0) continue
for (const serverName of context.spec?.mcpServers ?? []) {
const list = bindings[serverName] ?? []
list.push({ contextRef: ref, agents: sortAccessPrincipals(agents) })
@@ -309,11 +306,16 @@ export default function McpServersPage() {
setError(oauthScopeError)
return
}
- const targets = contexts.filter(context => contextRefs.includes(contextName(context)))
- if (targets.length !== contextRefs.length) {
+ const resolvedTargets = contextRefs.map(contextRef => contextForAlias(contexts, contextRef))
+ if (resolvedTargets.some(target => !target)) {
setError('One or more selected agents could not be resolved. Please refresh and try again.')
return
}
+ const targets = Array.from(
+ new Map(
+ resolvedTargets.map(target => [contextName(target as ContextResource), target] as const)
+ ).values()
+ ) as ContextResource[]
setUpdatingAgentAccessKey(key)
setError('')
@@ -351,7 +353,7 @@ export default function McpServersPage() {
binding: ConnectorAgentBinding
) {
const key = `${server.namespace}/${server.name}`
- const target = contexts.find(context => contextName(context) === binding.contextRef)
+ const target = contextForAlias(contexts, binding.contextRef)
if (!target) {
setError('This agent’s connector set could not be loaded. Please refresh and try again.')
return
@@ -373,7 +375,7 @@ export default function McpServersPage() {
try {
const spec = contextSpec(target)
await updateContext(
- binding.contextRef,
+ contextName(target),
buildContextUpdatePayload(target.metadata?.resourceVersion, {
...spec,
mcpServers: spec.mcpServers.filter(name => name !== server.name),
diff --git a/control-ui/app/profile-admin/teams/[teamId]/page.tsx b/control-ui/app/profile-admin/teams/[teamId]/page.tsx
index 8d44d6de3..41eda9ce2 100644
--- a/control-ui/app/profile-admin/teams/[teamId]/page.tsx
+++ b/control-ui/app/profile-admin/teams/[teamId]/page.tsx
@@ -11,10 +11,11 @@ import { useToast } from '@components/Toast'
import { CONTROL_ROUTES } from '@constants/routes'
import { partitionVisibleAccess } from '@lib/accessVisibility'
import {
+ agentNamesForContextAccess,
applyAgentAccessCompatibilityUpdate,
- planAgentAccessUpdate,
} from '@lib/agentAccessCompatibility'
import { getAgentDisplayName } from '@lib/agentName'
+import { contextResourceName, contextResourceNameForAlias } from '@lib/contextIdentity'
import { ConnectorCountCell } from '../../../../components/ConnectorCountCell'
import { InviteMemberDialog } from '../../../../components/InviteMemberDialog'
import { IconUsers } from '../../../../components/Sidebar/icons'
@@ -201,13 +202,6 @@ export default function TeamDetailsPage() {
[hosts]
)
- function contextIdFromResource(item: {
- metadata?: { name?: string }
- spec?: { contextId?: string }
- }) {
- return String(item.spec?.contextId || item.metadata?.name || '').trim()
- }
-
// Rows are context IDs on the wire, but the user sees what that access
// means: the owning agent(s) for private scopes, the stored display name
// for anything else, and the raw id as a last-resort muted fallback.
@@ -234,19 +228,16 @@ export default function TeamDetailsPage() {
// D8: granted set is agent-centric — direct team↔agent mapping unioned with
// agents resolved from legacy scope-only mappings.
const grantedAgentNames = useMemo(() => {
- const granted = new Set(assignedAgentNames)
- for (const contextId of assignedContextIds) {
- for (const [name, host] of hostsByName) {
- if (
- String((host.spec as { contextRef?: string } | undefined)?.contextRef || '').trim() ===
- contextId
- ) {
- granted.add(name)
- }
- }
- }
+ const granted = new Set([
+ ...assignedAgentNames,
+ ...agentNamesForContextAccess(
+ assignedContextIds,
+ [...hostsByName.values()],
+ contextResources
+ ),
+ ])
return [...granted].sort((a, b) => a.localeCompare(b))
- }, [assignedAgentNames, assignedContextIds, hostsByName])
+ }, [assignedAgentNames, assignedContextIds, contextResources, hostsByName])
const agentDisplay = (agentName: string): string => {
const host = hostsByName.get(agentName)
@@ -269,7 +260,8 @@ export default function TeamDetailsPage() {
async function loadTeamData(
resolvedTeamId: string,
visibleContextIds = availableContextIds,
- visibleAgentNames = hostNameOptions
+ visibleAgentNames = hostNameOptions,
+ visibleContexts = contextResources
) {
const [team, teamMembers, teamContexts, teamAgents, pendingInv] = await Promise.all([
getAdminTeam(resolvedTeamId),
@@ -291,7 +283,11 @@ export default function TeamDetailsPage() {
)
)
const contextPartition = partitionVisibleAccess(
- Array.isArray(teamContexts.contextIds) ? teamContexts.contextIds : [],
+ Array.isArray(teamContexts.contextIds)
+ ? teamContexts.contextIds.map(contextId =>
+ contextResourceNameForAlias(visibleContexts, contextId)
+ )
+ : [],
visibleContextIds,
Array.isArray(teamContexts.deletedContextIds) ? teamContexts.deletedContextIds : []
)
@@ -323,8 +319,9 @@ export default function TeamDetailsPage() {
setUsers(Array.isArray(usersData.items) ? usersData.items : [])
setHosts(Array.isArray(hostsData.items) ? hostsData.items : [])
setContextResources((contextsData.items || []) as ContextResource[])
- const ids = (contextsData.items || [])
- .map(item => contextIdFromResource(item as never))
+ const resources = (contextsData.items || []) as ContextResource[]
+ const ids = resources
+ .map(contextResourceName)
.filter(Boolean)
.sort((a, b) => a.localeCompare(b))
const hostNames = Array.from(
@@ -336,7 +333,7 @@ export default function TeamDetailsPage() {
).sort((a, b) => a.localeCompare(b))
setAvailableContextIds(ids)
if (!isNew) {
- await loadTeamData(teamId, ids, hostNames)
+ await loadTeamData(teamId, ids, hostNames, resources)
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load team data')
@@ -535,14 +532,17 @@ export default function TeamDetailsPage() {
setBusy(true)
setError('')
try {
- const updatePlan = planAgentAccessUpdate(assignedContextIds, nextGrantedAgents, [
- ...hostsByName.values(),
- ])
-
- const [updatedAgents, updatedContexts] = await applyAgentAccessCompatibilityUpdate(
- () => updateAdminTeamAgents(teamId, updatePlan.agentNames, observedAgentNames),
- () => updateAdminTeamContexts(teamId, updatePlan.contextIds)
- )
+ const [updatedAgents, updatedContexts] = await applyAgentAccessCompatibilityUpdate({
+ contexts: contextResources,
+ hosts: [...hostsByName.values()],
+ loadCurrentContextIds: async () => {
+ const current = await getAdminTeamContexts(teamId)
+ return [...(current.contextIds || []), ...(current.deletedContextIds || [])]
+ },
+ nextGrantedAgentNames: nextGrantedAgents,
+ updateAgents: agentNames => updateAdminTeamAgents(teamId, agentNames, observedAgentNames),
+ updateContexts: contextIds => updateAdminTeamContexts(teamId, contextIds),
+ })
const hostNames = [...hostsByName.keys()]
const agentPartition = partitionVisibleAccess(
@@ -551,7 +551,9 @@ export default function TeamDetailsPage() {
updatedAgents.deletedAgentNames || []
)
const contextPartition = partitionVisibleAccess(
- updatedContexts.contextIds || [],
+ (updatedContexts.contextIds || []).map(contextId =>
+ contextResourceNameForAlias(contextResources, contextId)
+ ),
availableContextIds,
updatedContexts.deletedContextIds || []
)
diff --git a/control-ui/app/profile-admin/users/[userId]/page.tsx b/control-ui/app/profile-admin/users/[userId]/page.tsx
index 929d77d66..8a454043d 100644
--- a/control-ui/app/profile-admin/users/[userId]/page.tsx
+++ b/control-ui/app/profile-admin/users/[userId]/page.tsx
@@ -13,10 +13,11 @@ import { CONTROL_ROUTES } from '@constants/routes'
import { accessScopeLabeler } from '@lib/accessScopeLabels'
import { partitionVisibleAccess } from '@lib/accessVisibility'
import {
+ agentNamesForContextAccess,
applyAgentAccessCompatibilityUpdate,
- planAgentAccessUpdate,
} from '@lib/agentAccessCompatibility'
import { getAgentDisplayName } from '@lib/agentName'
+import { contextResourceName, contextResourceNameForAlias } from '@lib/contextIdentity'
import type { DeleteCandidateTeam } from '@lib/profileAdminDelete'
import { formatTeamNames, getSoloMemberTeamsForUser } from '@lib/profileAdminDelete'
import { ConnectorCountCell } from '../../../../components/ConnectorCountCell'
@@ -166,19 +167,16 @@ export default function UserDetailsPage() {
// unioned with agents resolved from legacy scope-only mappings so nothing
// granted before this change disappears.
const grantedAgentNames = useMemo(() => {
- const granted = new Set(assignedAgentNames)
- for (const contextId of assignedContextIds) {
- for (const [name, host] of hostsByName) {
- if (
- String((host.spec as { contextRef?: string } | undefined)?.contextRef || '').trim() ===
- contextId
- ) {
- granted.add(name)
- }
- }
- }
+ const granted = new Set([
+ ...assignedAgentNames,
+ ...agentNamesForContextAccess(
+ assignedContextIds,
+ [...hostsByName.values()],
+ contextResources
+ ),
+ ])
return [...granted].sort((a, b) => a.localeCompare(b))
- }, [assignedAgentNames, assignedContextIds, hostsByName])
+ }, [assignedAgentNames, assignedContextIds, contextResources, hostsByName])
const agentDisplay = (agentName: string): string => {
const host = hostsByName.get(agentName)
@@ -265,13 +263,6 @@ export default function UserDetailsPage() {
return output
}
- function contextIdFromResource(item: {
- metadata?: { name?: string }
- spec?: { contextId?: string }
- }) {
- return String(item.spec?.contextId || item.metadata?.name || '').trim()
- }
-
async function loadData() {
setBusy(true)
setError('')
@@ -303,8 +294,9 @@ export default function UserDetailsPage() {
setContactEmailsDraft(uniqueTrimmed(context.channels.emails || [], true))
setSlackHandlesDraft(uniqueTrimmed(context.channels.slackUserNames || []))
setTelegramIdsDraft(uniqueTrimmed(context.channels.telegramIds || []))
- const ids = (contexts.items || [])
- .map(item => contextIdFromResource(item as never))
+ const resources = (contexts.items || []) as ContextResource[]
+ const ids = resources
+ .map(contextResourceName)
.filter(Boolean)
.sort((a, b) => a.localeCompare(b))
const hostNames = Array.from(
@@ -315,7 +307,11 @@ export default function UserDetailsPage() {
)
).sort((a, b) => a.localeCompare(b))
const contextPartition = partitionVisibleAccess(
- Array.isArray(contextAccess.contextIds) ? contextAccess.contextIds : [],
+ Array.isArray(contextAccess.contextIds)
+ ? contextAccess.contextIds.map(contextId =>
+ contextResourceNameForAlias(resources, contextId)
+ )
+ : [],
ids,
Array.isArray(contextAccess.deletedContextIds) ? contextAccess.deletedContextIds : []
)
@@ -337,7 +333,7 @@ export default function UserDetailsPage() {
])
setCommunicationChannels(communicationChannelsData.items || [])
setAvailableContextIds(ids)
- setContextResources((contexts.items || []) as ContextResource[])
+ setContextResources(resources)
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load member details')
} finally {
@@ -459,14 +455,17 @@ export default function UserDetailsPage() {
setBusy(true)
setError('')
try {
- const updatePlan = planAgentAccessUpdate(assignedContextIds, nextGrantedAgents, [
- ...hostsByName.values(),
- ])
-
- const [updatedAgents, updatedContexts] = await applyAgentAccessCompatibilityUpdate(
- () => updateAdminUserAgents(userId, updatePlan.agentNames, observedAgentNames),
- () => updateAdminUserContexts(userId, updatePlan.contextIds)
- )
+ const [updatedAgents, updatedContexts] = await applyAgentAccessCompatibilityUpdate({
+ contexts: contextResources,
+ hosts: [...hostsByName.values()],
+ loadCurrentContextIds: async () => {
+ const current = await getAdminUserContexts(userId)
+ return [...(current.contextIds || []), ...(current.deletedContextIds || [])]
+ },
+ nextGrantedAgentNames: nextGrantedAgents,
+ updateAgents: agentNames => updateAdminUserAgents(userId, agentNames, observedAgentNames),
+ updateContexts: contextIds => updateAdminUserContexts(userId, contextIds),
+ })
const hostNames = [...hostsByName.keys()]
const agentPartition = partitionVisibleAccess(
@@ -475,7 +474,11 @@ export default function UserDetailsPage() {
Array.isArray(updatedAgents.deletedAgentNames) ? updatedAgents.deletedAgentNames : []
)
const contextPartition = partitionVisibleAccess(
- Array.isArray(updatedContexts.contextIds) ? updatedContexts.contextIds : [],
+ Array.isArray(updatedContexts.contextIds)
+ ? updatedContexts.contextIds.map(contextId =>
+ contextResourceNameForAlias(contextResources, contextId)
+ )
+ : [],
availableContextIds,
Array.isArray(updatedContexts.deletedContextIds) ? updatedContexts.deletedContextIds : []
)
diff --git a/control-ui/components/__tests__/McpServersPage.aliases.test.tsx b/control-ui/components/__tests__/McpServersPage.aliases.test.tsx
new file mode 100644
index 000000000..beacf61d1
--- /dev/null
+++ b/control-ui/components/__tests__/McpServersPage.aliases.test.tsx
@@ -0,0 +1,152 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import McpServersPage from '../../app/mcp-servers/page'
+import * as api from '../../lib/api'
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn() }),
+}))
+
+vi.mock('../ConfirmDialog', () => ({
+ useConfirmDialog: () => ({ confirm: vi.fn().mockResolvedValue(true), confirmDialog: null }),
+}))
+
+vi.mock('../DashboardLayout', async () => {
+ const React = await import('react')
+ return {
+ DashboardLayout: ({ children }: { children: React.ReactNode }) =>
+ React.createElement('div', null, children),
+ }
+})
+
+vi.mock('../Toast', () => ({
+ useToast: () => ({ showToast: vi.fn() }),
+}))
+
+vi.mock('../McpServerTable', async () => {
+ const React = await import('react')
+ return {
+ McpServerTable: (props: {
+ agentBindingsByConnectorName: Record<
+ string,
+ Array<{
+ agents: Array<{ id: string; label: string }>
+ contextRef: string
+ }>
+ >
+ onAddToAgents: (
+ server: { name: string; namespace: string },
+ agents: Array<{ name: string; contextRef: string }>
+ ) => Promise<void>
+ onRemoveFromAgents: (
+ server: { name: string; namespace: string },
+ binding: {
+ agents: Array<{ id: string; label: string }>
+ contextRef: string
+ }
+ ) => Promise<void>
+ }) => {
+ const binding = props.agentBindingsByConnectorName.search?.[0]
+ return React.createElement(
+ 'div',
+ null,
+ React.createElement(
+ 'span',
+ null,
+ `owners:${binding?.agents.map(agent => agent.label).join(',') || 'none'}`
+ ),
+ React.createElement(
+ 'button',
+ {
+ onClick: () =>
+ props.onAddToAgents({ name: 'new-search', namespace: 'mcp-server' }, [
+ { name: 'agent-alpha', contextRef: 'ctx-wire' },
+ ]),
+ type: 'button',
+ },
+ 'add alias connector'
+ ),
+ binding
+ ? React.createElement(
+ 'button',
+ {
+ onClick: () =>
+ props.onRemoveFromAgents({ name: 'search', namespace: 'mcp-server' }, binding),
+ type: 'button',
+ },
+ 'remove alias connector'
+ )
+ : null
+ )
+ },
+ }
+})
+
+vi.mock('../../lib/api', () => ({
+ apiSend: vi.fn().mockResolvedValue({}),
+ getAgentTeams: vi.fn().mockResolvedValue({ items: [] }),
+ getAgentUsers: vi.fn().mockResolvedValue({ items: [] }),
+ getContexts: vi.fn(),
+ getHosts: vi.fn(),
+ getMcpServers: vi.fn(),
+ isSilentApiError: vi.fn().mockReturnValue(false),
+ updateContext: vi.fn().mockResolvedValue({}),
+}))
+
+describe('Installed Connectors Context aliases', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(api.getMcpServers).mockResolvedValue({
+ items: [
+ { metadata: { name: 'search', namespace: 'mcp-server' }, spec: {} },
+ { metadata: { name: 'new-search', namespace: 'mcp-server' }, spec: {} },
+ ],
+ })
+ vi.mocked(api.getContexts).mockResolvedValue({
+ items: [
+ {
+ metadata: { name: 'ctx-resource', resourceVersion: 'rv-1' },
+ spec: { contextId: 'ctx-wire', mcpServers: ['search'] },
+ },
+ ],
+ })
+ vi.mocked(api.getHosts).mockResolvedValue({
+ items: [
+ {
+ metadata: { name: 'agent-alpha' },
+ spec: { contextRef: 'ctx-wire', host: 'Agent Alpha' },
+ },
+ ],
+ })
+ })
+
+ it('shows the owner and uses the resource name for add and remove mutations', async () => {
+ render(<McpServersPage />)
+
+ expect(await screen.findByText('owners:Agent Alpha')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'add alias connector' }))
+ await waitFor(() => expect(api.updateContext).toHaveBeenCalledTimes(1))
+ expect(api.updateContext).toHaveBeenLastCalledWith(
+ 'ctx-resource',
+ expect.objectContaining({
+ metadata: { resourceVersion: 'rv-1' },
+ spec: expect.objectContaining({
+ contextId: 'ctx-wire',
+ mcpServers: ['search', 'new-search'],
+ }),
+ })
+ )
+
+ vi.mocked(api.updateContext).mockClear()
+ fireEvent.click(screen.getByRole('button', { name: 'remove alias connector' }))
+ await waitFor(() => expect(api.updateContext).toHaveBeenCalledTimes(1))
+ expect(api.updateContext).toHaveBeenLastCalledWith(
+ 'ctx-resource',
+ expect.objectContaining({
+ metadata: { resourceVersion: 'rv-1' },
+ spec: expect.objectContaining({ contextId: 'ctx-wire', mcpServers: [] }),
+ })
+ )
+ })
+})
diff --git a/control-ui/lib/__tests__/agentAccessCompatibility.test.ts b/control-ui/lib/__tests__/agentAccessCompatibility.test.ts
index cfa5139f1..aaef1813f 100644
--- a/control-ui/lib/__tests__/agentAccessCompatibility.test.ts
+++ b/control-ui/lib/__tests__/agentAccessCompatibility.test.ts
@@ -1,14 +1,23 @@
import { describe, expect, it, vi } from 'vitest'
import {
+ agentNamesForContextAccess,
applyAgentAccessCompatibilityUpdate,
planAgentAccessUpdate,
} from '../agentAccessCompatibility'
-import type { HostResource } from '../api'
+import type { ContextResource, HostResource } from '../api'
const hosts: HostResource[] = [
{ metadata: { name: 'agent-alpha' }, spec: { contextRef: 'ctx-alpha' } },
{ metadata: { name: 'agent-beta' }, spec: { contextRef: 'ctx-beta' } },
]
+const contexts: ContextResource[] = [
+ { metadata: { name: 'ctx-alpha' }, spec: { contextId: 'ctx-alpha', mcpServers: [] } },
+ { metadata: { name: 'ctx-beta' }, spec: { contextId: 'ctx-beta', mcpServers: [] } },
+ {
+ metadata: { name: 'member-private-scope' },
+ spec: { contextId: 'member-private-scope', mcpServers: [] },
+ },
+]
describe('planAgentAccessUpdate', () => {
it('keeps only the member’s already-assigned unowned scopes', () => {
@@ -49,6 +58,28 @@ describe('planAgentAccessUpdate', () => {
contextIds: ['ctx-shared'],
})
})
+
+ it.each(['member', 'team'])(
+ 'preserves existing %s access through mismatched Context aliases',
+ () => {
+ const aliasedContexts: ContextResource[] = [
+ {
+ metadata: { name: 'ctx-resource' },
+ spec: { contextId: 'ctx-wire', mcpServers: [] },
+ },
+ ]
+ const aliasedHosts: HostResource[] = [
+ { metadata: { name: 'agent-alpha' }, spec: { contextRef: 'ctx-wire' } },
+ ]
+
+ expect(
+ planAgentAccessUpdate(['ctx-resource'], ['agent-alpha'], aliasedHosts, aliasedContexts)
+ ).toEqual({ agentNames: ['agent-alpha'], contextIds: ['ctx-resource'] })
+ expect(agentNamesForContextAccess(['ctx-resource'], aliasedHosts, aliasedContexts)).toEqual([
+ 'agent-alpha',
+ ])
+ }
+ )
})
describe('applyAgentAccessCompatibilityUpdate', () => {
@@ -57,30 +88,82 @@ describe('applyAgentAccessCompatibilityUpdate', () => {
async () => {
const staleCas = Object.assign(new Error('Precondition failed'), { status: 412 })
const updateAgents = vi.fn().mockRejectedValue(staleCas)
+ const loadCurrentContextIds = vi.fn().mockResolvedValue(['member-private-scope'])
const updateContexts = vi.fn().mockResolvedValue({})
- await expect(applyAgentAccessCompatibilityUpdate(updateAgents, updateContexts)).rejects.toBe(
- staleCas
- )
+ await expect(
+ applyAgentAccessCompatibilityUpdate({
+ contexts,
+ hosts,
+ loadCurrentContextIds,
+ nextGrantedAgentNames: ['agent-alpha'],
+ updateAgents,
+ updateContexts,
+ })
+ ).rejects.toBe(staleCas)
expect(updateAgents).toHaveBeenCalledOnce()
+ expect(loadCurrentContextIds).not.toHaveBeenCalled()
expect(updateContexts).not.toHaveBeenCalled()
}
)
- it('writes Context compatibility state only after the Agent CAS succeeds', async () => {
+ it.each(['member', 'team'])(
+ 'does not restore an unowned Context revoked after the %s page loaded',
+ async () => {
+ const calls: string[] = []
+ const updateContexts = vi.fn(async (contextIds: string[]) => {
+ calls.push('contexts')
+ return { contextIds }
+ })
+
+ const result = await applyAgentAccessCompatibilityUpdate({
+ contexts,
+ hosts,
+ loadCurrentContextIds: async () => {
+ calls.push('refresh-contexts')
+ // The page originally saw ctx-sensitive, but another admin revoked
+ // it before this post-CAS refresh.
+ return []
+ },
+ nextGrantedAgentNames: ['agent-alpha'],
+ updateAgents: async agentNames => {
+ calls.push('agents')
+ return { agentNames }
+ },
+ updateContexts,
+ })
+
+ expect(calls).toEqual(['agents', 'refresh-contexts', 'contexts'])
+ expect(updateContexts).toHaveBeenCalledWith(['ctx-alpha'])
+ expect(updateContexts).not.toHaveBeenCalledWith(expect.arrayContaining(['ctx-sensitive']))
+ expect(result[1]).toEqual({ contextIds: ['ctx-alpha'] })
+ }
+ )
+
+ it('writes refreshed Context compatibility state only after the Agent CAS succeeds', async () => {
const calls: string[] = []
- const result = await applyAgentAccessCompatibilityUpdate(
- async () => {
+ const result = await applyAgentAccessCompatibilityUpdate({
+ contexts,
+ hosts,
+ loadCurrentContextIds: async () => {
+ calls.push('refresh-contexts')
+ return ['member-private-scope']
+ },
+ nextGrantedAgentNames: ['agent-alpha'],
+ updateAgents: async () => {
calls.push('agents')
return { agentNames: ['agent-alpha'] }
},
- async () => {
+ updateContexts: async contextIds => {
calls.push('contexts')
- return { contextIds: ['ctx-alpha'] }
- }
- )
+ return { contextIds }
+ },
+ })
- expect(calls).toEqual(['agents', 'contexts'])
- expect(result).toEqual([{ agentNames: ['agent-alpha'] }, { contextIds: ['ctx-alpha'] }])
+ expect(calls).toEqual(['agents', 'refresh-contexts', 'contexts'])
+ expect(result).toEqual([
+ { agentNames: ['agent-alpha'] },
+ { contextIds: ['ctx-alpha', 'member-private-scope'] },
+ ])
})
})
diff --git a/control-ui/lib/agentAccessCompatibility.ts b/control-ui/lib/agentAccessCompatibility.ts
index 8474cc2f5..f94624707 100644
--- a/control-ui/lib/agentAccessCompatibility.ts
+++ b/control-ui/lib/agentAccessCompatibility.ts
@@ -1,4 +1,5 @@
-import type { HostResource } from './api'
+import type { ContextResource, HostResource } from './api'
+import { contextAliases, contextForAlias, contextResourceName } from './contextIdentity'
export type AgentAccessUpdatePlan = {
agentNames: string[]
@@ -9,12 +10,32 @@ export type AgentAccessUpdatePlan = {
* Applies the authoritative Agent CAS before its legacy Context compatibility
* write. A stale Agent snapshot must fail before any Context grant can change.
*/
-export async function applyAgentAccessCompatibilityUpdate<AgentResult, ContextResult>(
- updateAgents: () => Promise<AgentResult>,
- updateContexts: () => Promise<ContextResult>
-): Promise<[AgentResult, ContextResult]> {
- const updatedAgents = await updateAgents()
- const updatedContexts = await updateContexts()
+export async function applyAgentAccessCompatibilityUpdate<AgentResult, ContextResult>(options: {
+ contexts: readonly ContextResource[]
+ hosts: readonly HostResource[]
+ loadCurrentContextIds: () => Promise<readonly string[]>
+ nextGrantedAgentNames: readonly string[]
+ updateAgents: (agentNames: string[]) => Promise<AgentResult>
+ updateContexts: (contextIds: string[]) => Promise<ContextResult>
+}): Promise<[AgentResult, ContextResult]> {
+ const agentPlan = planAgentAccessUpdate(
+ [],
+ options.nextGrantedAgentNames,
+ options.hosts,
+ options.contexts
+ )
+ const updatedAgents = await options.updateAgents(agentPlan.agentNames)
+ // Refresh after the Agent CAS. Hidden/unowned Context grants may have been
+ // revoked by another admin since this page loaded and must not be restored
+ // from the stale UI snapshot.
+ const currentContextIds = await options.loadCurrentContextIds()
+ const contextPlan = planAgentAccessUpdate(
+ currentContextIds,
+ agentPlan.agentNames,
+ options.hosts,
+ options.contexts
+ )
+ const updatedContexts = await options.updateContexts(contextPlan.contextIds)
return [updatedAgents, updatedContexts]
}
@@ -26,6 +47,30 @@ function hostContextRef(host: HostResource): string {
return String(host.spec?.contextRef ?? '').trim()
}
+export function agentNamesForContextAccess(
+ assignedContextIds: readonly string[],
+ hosts: readonly HostResource[],
+ contexts: readonly ContextResource[]
+): string[] {
+ const assignedResourceNames = new Set(
+ assignedContextIds.map(contextId => {
+ const context = contextForAlias(contexts, contextId)
+ return context ? contextResourceName(context) : contextId.trim()
+ })
+ )
+
+ return hosts
+ .filter(host => {
+ const contextRef = hostContextRef(host)
+ const context = contextForAlias(contexts, contextRef)
+ const resourceName = context ? contextResourceName(context) : contextRef
+ return assignedResourceNames.has(resourceName)
+ })
+ .map(hostName)
+ .filter(Boolean)
+ .sort((left, right) => left.localeCompare(right))
+}
+
/**
* Plans the compatibility payload for an Agent-centric access update.
*
@@ -37,12 +82,19 @@ function hostContextRef(host: HostResource): string {
export function planAgentAccessUpdate(
assignedContextIds: readonly string[],
nextGrantedAgentNames: readonly string[],
- hosts: readonly HostResource[]
+ hosts: readonly HostResource[],
+ contexts: readonly ContextResource[] = []
): AgentAccessUpdatePlan {
const normalizedAgents = Array.from(
new Set(nextGrantedAgentNames.map(value => value.trim()).filter(Boolean))
).sort((left, right) => left.localeCompare(right))
- const ownedContextIds = new Set(hosts.map(hostContextRef).filter(Boolean))
+ const ownedContextIds = new Set(
+ hosts.flatMap(host => {
+ const ref = hostContextRef(host)
+ const context = contextForAlias(contexts, ref)
+ return context ? contextAliases(context) : [ref]
+ })
+ )
const preservedUnownedContextIds = assignedContextIds.filter(
contextId => contextId && !ownedContextIds.has(contextId)
)
@@ -51,7 +103,11 @@ export function planAgentAccessUpdate(
)
const selectedAgentContextIds = normalizedAgents
.map(agentName => hostByName.get(agentName))
- .map(host => (host ? hostContextRef(host) : ''))
+ .map(host => {
+ const ref = host ? hostContextRef(host) : ''
+ const context = contextForAlias(contexts, ref)
+ return context ? contextResourceName(context) : ref
+ })
.filter(Boolean)
return {
diff --git a/control-ui/lib/contextIdentity.ts b/control-ui/lib/contextIdentity.ts
index 7d83abf96..ff3b9cf18 100644
--- a/control-ui/lib/contextIdentity.ts
+++ b/control-ui/lib/contextIdentity.ts
@@ -21,6 +21,11 @@ export function contextWireId(context: ContextResource): string {
return normalized(context.spec?.contextId) || normalized(context.metadata?.name)
}
+/** Stable identifier accepted by Context resource CRUD endpoints. */
+export function contextResourceName(context: ContextResource): string {
+ return normalized(context.metadata?.name) || normalized(context.spec?.contextId)
+}
+
export function contextForAlias(
contexts: readonly ContextResource[],
alias: string
@@ -29,3 +34,11 @@ export function contextForAlias(
if (!normalizedAlias) return undefined
return contexts.find(context => contextAliases(context).includes(normalizedAlias))
}
+
+export function contextResourceNameForAlias(
+ contexts: readonly ContextResource[],
+ alias: string
+): string {
+ const context = contextForAlias(contexts, alias)
+ return context ? contextResourceName(context) : normalized(alias)
+}
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index e86cb73a8..6ab3204d6 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.496",
+ "version": "0.1.497",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.496",
+ "version": "0.1.497",
"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.json
index f97d9fd97..bb9ba48c2 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.496",
+ "version": "0.1.497",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",