Skip to content

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

TypeScript

feat(control-ui): remove contexts section behind agent-resolving redirects (Phase 3 / Category A)

Miguelon Peluchon5214579f0310
diff --git a/control-ui/app/constants/createFlowLoading.ts b/control-ui/app/constants/createFlowLoading.ts
index f8ccb5501..65bb4bf50 100644
--- a/control-ui/app/constants/createFlowLoading.ts
+++ b/control-ui/app/constants/createFlowLoading.ts
@@ -17,14 +17,6 @@ export const CREATE_FLOW_LOADING = {
steps: ['Channel', 'Routing'],
stepFlowClassName: 'cu-create-step-flow--2',
},
- createContext: {
- iconKey: 'group-work',
- title: 'Create context',
- subtitle: 'Define a new context and attach connectors.',
- backLabel: 'Back to contexts',
- steps: ['Context', 'Connectors'],
- stepFlowClassName: 'cu-create-step-flow--2',
- },
createControlAdmin: {
iconKey: 'settings',
title: 'Invite admin',
diff --git a/control-ui/app/constants/routes.ts b/control-ui/app/constants/routes.ts
index 21b26ed55..a033ad4e2 100644
--- a/control-ui/app/constants/routes.ts
+++ b/control-ui/app/constants/routes.ts
@@ -38,13 +38,6 @@ export const CONTROL_ROUTES = {
edit: (name: string) => `/connectors/${segment(name)}/edit`,
editTab: (name: string, tab: string) => `/connectors/${segment(name)}/edit/${segment(tab)}`,
},
- contexts: {
- root: '/contexts',
- new: '/contexts/new',
- detail: (name: string) => `/contexts/${segment(name)}`,
- tab: (name: string, tab: string) => `/contexts/${segment(name)}/${segment(tab)}`,
- connectors: (name: string) => `/contexts/${segment(name)}/connectors`,
- },
costAndUsage: {
base: '/cost-and-usage',
root: '/cost-and-usage/usage',
diff --git a/control-ui/app/contexts/[[...slug]]/page.tsx b/control-ui/app/contexts/[[...slug]]/page.tsx
new file mode 100644
index 000000000..5a7eb1e36
--- /dev/null
+++ b/control-ui/app/contexts/[[...slug]]/page.tsx
@@ -0,0 +1,74 @@
+'use client'
+
+import { useEffect } from 'react'
+import { useParams, useRouter } from 'next/navigation'
+import { CONTROL_ROUTES } from '@constants/routes'
+import { getHosts } from '@lib/api'
+
+// Legacy deep-link resolver for the removed Contexts section.
+//
+// The k8s Context resource still exists (agents keep their private connector
+// scopes), but it has no UI of its own anymore. Old links land here and are
+// forwarded to the closest user-facing destination:
+// /contexts, /contexts/new → the Agents list
+// /contexts/<private-slug>[/any/tab] → the owning agent's Connectors tab
+// /contexts/<unknown-slug>[/any/tab] → the Agents list (fail-safe)
+//
+// Lookup failures also fall back to the Agents list so a bookmark never dead-
+// ends. The write model is untouched: this page only navigates.
+export default function LegacyContextRedirectPage() {
+ const router = useRouter()
+ const params = useParams<{ slug?: string[] | string }>()
+
+ useEffect(() => {
+ let cancelled = false
+
+ const fallback = () => {
+ if (!cancelled) router.replace(CONTROL_ROUTES.agents.root)
+ }
+
+ void (async () => {
+ try {
+ const raw = Array.isArray(params?.slug) ? params.slug[0] : params?.slug
+ const slug = decodeURIComponent(raw ?? '').trim()
+ if (!slug || slug === 'new') {
+ fallback()
+ return
+ }
+
+ const hostsResponse = await getHosts()
+ const owner = (
+ (hostsResponse.items ?? []) as Array<{
+ metadata?: { name?: string }
+ spec?: { contextRef?: string }
+ }>
+ ).find(host => String(host.spec?.contextRef ?? '').trim() === slug)
+
+ if (!owner?.metadata?.name) {
+ fallback()
+ return
+ }
+ if (!cancelled) {
+ router.replace(CONTROL_ROUTES.agents.tab(owner.metadata.name, 'connectors'))
+ }
+ } catch {
+ fallback()
+ }
+ })()
+
+ return () => {
+ cancelled = true
+ }
+ }, [params?.slug, router])
+
+ return (
+ <div
+ role="status"
+ aria-label="Redirecting"
+ className="cu-empty"
+ style={{ margin: '2rem auto', maxWidth: '24rem', textAlign: 'center' }}
+ >
+ Taking you to the right place…
+ </div>
+ )
+}
diff --git a/control-ui/app/contexts/[name]/[tab]/page.tsx b/control-ui/app/contexts/[name]/[tab]/page.tsx
deleted file mode 100644
index 92f47551d..000000000
--- a/control-ui/app/contexts/[name]/[tab]/page.tsx
+++ /dev/null
@@ -1,15 +0,0 @@
-import { notFound } from 'next/navigation'
-import ContextDetailsPage from '../page'
-
-interface ContextTabPageProps {
- params: Promise<{ tab: string }>
-}
-
-const CONTEXT_DETAIL_TABS = ['connectors', 'agent-files', 'agents', 'teams', 'members']
-
-export default async function ContextTabPage({ params }: ContextTabPageProps) {
- const { tab } = await params
- if (!CONTEXT_DETAIL_TABS.includes(tab)) notFound()
-
- return <ContextDetailsPage />
-}
diff --git a/control-ui/app/contexts/[name]/page.tsx b/control-ui/app/contexts/[name]/page.tsx
deleted file mode 100644
index 9dc15e465..000000000
--- a/control-ui/app/contexts/[name]/page.tsx
+++ /dev/null
@@ -1,1676 +0,0 @@
-'use client'
-
-import React, { useEffect, useMemo, useRef, useState } from 'react'
-import Link from 'next/link'
-import { useParams, useRouter } from 'next/navigation'
-import { useConfirmDialog } from '@components/ConfirmDialog'
-import { CreateFlowPanel } from '@components/CreateFlowPanel'
-import { CreatePageHeader } from '@components/CreatePageHeader'
-import { SelectionDropdown } from '@components/SelectionDropdown'
-import { TabBar } from '@components/TabBar'
-import { TableHeaderRow } from '@components/TableHeaderRow'
-import type { TableHeaderColumn } from '@components/TableHeaderRow/types'
-import { useToast } from '@components/Toast'
-import { CONTROL_ROUTES } from '@constants/routes'
-import { getAgentDisplayName } from '@lib/agentName'
-import { buildContextUpdatePayload, contextMutationError } from '@lib/contextMutation'
-import { DashboardLayout } from '../../../components/DashboardLayout'
-import { IconFolder, IconGroupWork } from '../../../components/Sidebar/icons'
-import { IconMoreHorizontal, IconX } from '../../../components/icons'
-import {
- AdminUser,
- ContextResource,
- ContextSharedFileSystemRef,
- ContextSpec,
- ContextTeam,
- ContextUser,
- HostResource,
- SharedFileSystemResource,
- TeamListItem,
- apiSend,
- createContext,
- deleteContext,
- getAdminTeamContexts,
- getAdminTeams,
- getAdminUserContexts,
- getAdminUsers,
- getContext,
- getContextTeams,
- getContextUsers,
- getHosts,
- getMcpServers,
- getSharedFileSystems,
- updateAdminTeamContexts,
- updateAdminUserContexts,
- updateContext,
-} from '../../../lib/api'
-
-type ContextTab = 'connectors' | 'agent-files' | 'agents' | 'teams' | 'members'
-const CONTEXT_TABS: ContextTab[] = ['connectors', 'agents', 'teams', 'members']
-
-const TAB_LABELS: Record<ContextTab, string> = {
- connectors: 'Connectors',
- 'agent-files': 'Agent Files',
- agents: 'Agents',
- teams: 'Teams',
- members: 'Members',
-}
-
-function parseContextTab(value: string | undefined): ContextTab {
- return CONTEXT_TABS.includes(value as ContextTab) ? (value as ContextTab) : 'connectors'
-}
-
-const CONNECTOR_COLUMNS: TableHeaderColumn[] = [
- { key: 'connector', label: 'Connector', minWidth: '14rem' },
- { key: 'actions', label: 'Actions', width: '6rem', align: 'right' },
-]
-
-const SHARED_FILE_COLUMNS: TableHeaderColumn[] = [
- { key: 'shared-filesystem', label: 'SharedFileSystem', minWidth: '14rem' },
- { key: 'mount-path', label: 'Mount path' },
- { key: 'actions', label: 'Actions', width: '6rem', align: 'right' },
-]
-
-const AGENT_COLUMNS: TableHeaderColumn[] = [
- { key: 'agent', label: 'Agent', minWidth: '14rem' },
- { key: 'namespace', label: 'Namespace', width: '12rem' },
-]
-
-const TEAM_COLUMNS: TableHeaderColumn[] = [
- { key: 'team', label: 'Team', minWidth: '14rem' },
- { key: 'actions', label: 'Actions', width: '6rem', align: 'right' },
-]
-
-const MEMBER_COLUMNS: TableHeaderColumn[] = [
- { key: 'member', label: 'Member', minWidth: '14rem' },
- { key: 'email', label: 'Email' },
- { key: 'actions', label: 'Actions', width: '6rem', align: 'right' },
-]
-
-function ContextActionsMenu({
- busy,
- editing,
- onEdit,
- onDelete,
-}: {
- busy: boolean
- editing: boolean
- onEdit: () => void
- onDelete: () => void
-}) {
- const [open, setOpen] = useState(false)
- const ref = useRef<HTMLDivElement>(null)
-
- useEffect(() => {
- if (!open) return
- function handleDocClick(event: MouseEvent) {
- if (!ref.current?.contains(event.target as Node)) setOpen(false)
- }
- function handleEsc(event: KeyboardEvent) {
- if (event.key === 'Escape') setOpen(false)
- }
- document.addEventListener('mousedown', handleDocClick)
- document.addEventListener('keydown', handleEsc)
- return () => {
- document.removeEventListener('mousedown', handleDocClick)
- document.removeEventListener('keydown', handleEsc)
- }
- }, [open])
-
- return (
- <div ref={ref} className="cu-kebab">
- <button
- type="button"
- aria-label="Context actions"
- aria-haspopup="menu"
- aria-expanded={open}
- className="cu-btn cu-btn--icon cu-btn--ghost cu-kebab__trigger"
- onClick={() => setOpen(value => !value)}
- disabled={busy}
- >
- <IconMoreHorizontal width={16} height={16} />
- </button>
- {open ? (
- <div role="menu" className="cu-kebab__menu">
- <button
- type="button"
- role="menuitem"
- className="cu-kebab__item"
- disabled={editing}
- onClick={() => {
- setOpen(false)
- onEdit()
- }}
- >
- Edit context
- </button>
- <button
- type="button"
- role="menuitem"
- className="cu-kebab__item cu-kebab__item--danger"
- onClick={() => {
- setOpen(false)
- onDelete()
- }}
- >
- Delete
- </button>
- </div>
- ) : null}
- </div>
- )
-}
-
-export default function ContextDetailsPage() {
- const params = useParams<{ name: string; tab?: string }>()
- const router = useRouter()
- const { showToast } = useToast()
-
- const routeName = decodeURIComponent(params.name || '')
- const isNew = routeName === 'new'
-
- const [busy, setBusy] = useState(false)
- const [loaded, setLoaded] = useState(false)
- const [error, setError] = useState('')
- const [availableServers, setAvailableServers] = useState<string[]>([])
- const [allHosts, setAllHosts] = useState<HostResource[]>([])
- const [linkedHosts, setLinkedHosts] = useState<Array<{ name: string; namespace: string }>>([])
- const [contextUsers, setContextUsers] = useState<ContextUser[]>([])
- const [contextTeams, setContextTeams] = useState<ContextTeam[]>([])
- const [resolvedContextId, setResolvedContextId] = useState(isNew ? '' : routeName)
- const [contextResourceVersion, setContextResourceVersion] = useState<string | undefined>()
-
- const [contextNameDraft, setContextNameDraft] = useState(isNew ? '' : routeName)
- const [displayNameDraft, setDisplayNameDraft] = useState('')
- const [descriptionDraft, setDescriptionDraft] = useState('')
- // The raw spec exactly as it arrived from the server. A context PUT is a
- // full-replace: spreading this on save preserves any additive spec field the
- // form doesn't model yet (e.g. spec.gfs) instead of dropping it on a rename.
- const [loadedSpec, setLoadedSpec] = useState<Record<string, unknown>>({})
- const [mcpServersDraft, setMcpServersDraft] = useState<string[]>([])
- const [sharedFileSystemsDraft, setSharedFileSystemsDraft] = useState<
- ContextSharedFileSystemRef[]
- >([])
- const [availableSfses, setAvailableSfses] = useState<string[]>([])
- const [sfsAddName, setSfsAddName] = useState('')
- const [sfsAddMount, setSfsAddMount] = useState('')
-
- const [editing, setEditing] = useState(isNew)
- const [savedDescription, setSavedDescription] = useState('')
- const [savedContextName, setSavedContextName] = useState('')
- const [savedDisplayName, setSavedDisplayName] = useState('')
-
- const [activeTab, setActiveTab] = useState<ContextTab>(() => parseContextTab(params.tab))
-
- const [allTeams, setAllTeams] = useState<TeamListItem[]>([])
- const [allUsers, setAllUsers] = useState<AdminUser[]>([])
- const [selectedTeamIdsToAdd, setSelectedTeamIdsToAdd] = useState<string[]>([])
- const [selectedUserIdsToAdd, setSelectedUserIdsToAdd] = useState<string[]>([])
-
- const [showAddTeam, setShowAddTeam] = useState(false)
- const [showAddUser, setShowAddUser] = useState(false)
- const [showAddMcpServer, setShowAddMcpServer] = useState(false)
- const [showAddAgent, setShowAddAgent] = useState(false)
- const [selectedAgentNamesToAdd, setSelectedAgentNamesToAdd] = useState<string[]>([])
- const [selectedMcpServerNamesToAdd, setSelectedMcpServerNamesToAdd] = useState<string[]>([])
- const { confirm, confirmDialog } = useConfirmDialog()
-
- useEffect(() => {
- setContextNameDraft(isNew ? '' : routeName)
- setResolvedContextId(isNew ? '' : routeName)
- }, [isNew, routeName])
-
- useEffect(() => {
- if (isNew) {
- router.replace(CONTROL_ROUTES.contexts.new)
- }
- }, [isNew, router])
-
- useEffect(() => {
- setActiveTab(parseContextTab(params.tab))
- }, [params.tab])
-
- function contextTabHref(tab: ContextTab): string {
- return CONTROL_ROUTES.contexts.tab(routeName, tab)
- }
-
- function selectTab(tab: ContextTab) {
- setActiveTab(tab)
- router.replace(contextTabHref(tab))
- }
-
- useEffect(() => {
- async function loadReferenceData() {
- try {
- const [serversData, teamsData, usersData] = await Promise.all([
- getMcpServers(),
- getAdminTeams(),
- getAdminUsers(''),
- ])
- const names = (serversData.items || [])
- .map(item => item.metadata?.name || '')
- .filter(Boolean)
- .sort((a, b) => a.localeCompare(b))
- setAvailableServers(names)
- setAllTeams(Array.isArray(teamsData.items) ? teamsData.items : [])
- setAllUsers(Array.isArray(usersData.items) ? usersData.items : [])
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to load reference data')
- }
- }
- void loadReferenceData()
- }, [])
-
- useEffect(() => {
- if (isNew) {
- setLoaded(true)
- return
- }
-
- async function loadContextDetails() {
- setBusy(true)
- setError('')
- try {
- const context = await getContext(routeName)
- const spec = (context.spec || {}) as Partial<ContextSpec>
- setLoadedSpec((context.spec || {}) as Record<string, unknown>)
- const metadata = (context.metadata || {}) as ContextResource['metadata']
- const resolvedName = metadata?.name || spec.contextId || routeName
- const resolvedContext = spec.contextId || resolvedName
- setContextResourceVersion(metadata?.resourceVersion)
- setContextNameDraft(resolvedName)
- setSavedContextName(resolvedName)
- setResolvedContextId(resolvedContext)
- setDisplayNameDraft(spec.displayName || '')
- setSavedDisplayName(spec.displayName || '')
- setDescriptionDraft(spec.description || '')
- setSavedDescription(spec.description || '')
- const servers = Array.isArray(spec.mcpServers)
- ? Array.from(
- new Set(
- spec.mcpServers
- .map(String)
- .map(v => v.trim())
- .filter(Boolean)
- )
- )
- : []
- setMcpServersDraft(servers)
- const sfsRefs = Array.isArray(spec.sharedFileSystems)
- ? spec.sharedFileSystems
- .filter((r): r is ContextSharedFileSystemRef => Boolean(r && r.name && r.mountPath))
- .map(r => ({ name: r.name, mountPath: r.mountPath }))
- : []
- setSharedFileSystemsDraft(sfsRefs)
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to load context')
- } finally {
- setBusy(false)
- setLoaded(true)
- }
- }
-
- void loadContextDetails()
- }, [isNew, routeName])
-
- // Pull the cluster's SharedFileSystems once for the "attach" picker.
- useEffect(() => {
- let cancelled = false
- async function loadSfses() {
- try {
- const r = await getSharedFileSystems()
- if (cancelled) return
- const names = ((r.items || []) as SharedFileSystemResource[])
- .map(s => s.metadata?.name || '')
- .filter(Boolean)
- .sort((a, b) => a.localeCompare(b))
- setAvailableSfses(names)
- } catch {
- // Non-fatal — picker just won't suggest names.
- }
- }
- void loadSfses()
- return () => {
- cancelled = true
- }
- }, [])
-
- useEffect(() => {
- if (isNew || !resolvedContextId.trim()) {
- setAllHosts([])
- setLinkedHosts([])
- setContextUsers([])
- setContextTeams([])
- return
- }
-
- async function loadAssociations() {
- setError('')
- try {
- const [hostsData, usersData, teamsData] = await Promise.all([
- getHosts(),
- getContextUsers(resolvedContextId),
- getContextTeams(resolvedContextId),
- ])
- const hosts = (hostsData.items || []) as HostResource[]
- setAllHosts(hosts)
- const linked = hosts
- .filter(host => String(host.spec?.contextRef || '').trim() === resolvedContextId)
- .map(host => ({
- name: host.metadata?.name || '-',
- namespace: host.metadata?.namespace || 'default',
- }))
- .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`))
- setLinkedHosts(linked)
- setContextUsers(Array.isArray(usersData.items) ? usersData.items : [])
- setContextTeams(Array.isArray(teamsData.items) ? teamsData.items : [])
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to load context associations')
- }
- }
-
- void loadAssociations()
- }, [isNew, resolvedContextId])
-
- const availableAgentsToAttach = useMemo(
- () =>
- allHosts
- .map(host => ({
- name: String(host.metadata?.name || '').trim(),
- contextRef: String(host.spec?.contextRef || '').trim(),
- displayName: getAgentDisplayName(String(host.metadata?.name || ''), allHosts),
- }))
- .filter(agent => agent.name && agent.contextRef !== resolvedContextId)
- .sort((a, b) => a.displayName.localeCompare(b.displayName) || a.name.localeCompare(b.name)),
- [allHosts, resolvedContextId]
- )
-
- function toggleServer(name: string) {
- setMcpServersDraft(prev => {
- return prev.includes(name) ? prev.filter(v => v !== name) : [...prev, name]
- })
- }
-
- const canSave = useMemo(
- () => !busy && contextNameDraft.trim().length > 0,
- [busy, contextNameDraft]
- )
-
- function startEditing() {
- setSavedDescription(descriptionDraft)
- setSavedContextName(contextNameDraft)
- setSavedDisplayName(displayNameDraft)
- setEditing(true)
- }
-
- function cancelEditing() {
- setDescriptionDraft(savedDescription)
- setContextNameDraft(savedContextName)
- setDisplayNameDraft(savedDisplayName)
- setEditing(false)
- setError('')
- }
-
- async function save() {
- if (!canSave) return
- const trimmedDisplay = displayNameDraft.trim()
- const contextId = contextNameDraft.trim()
-
- setBusy(true)
- setError('')
- try {
- if (isNew) {
- // Create: no prior server spec to preserve — build a fresh spec.
- // The visible name lives in spec.displayName; omit it when empty so an
- // unset display stays absent, not "".
- const createSpec: ContextSpec = {
- contextId,
- ...(trimmedDisplay ? { displayName: trimmedDisplay } : {}),
- description: descriptionDraft.trim(),
- mcpServers: mcpServersDraft,
- sharedFileSystems: sharedFileSystemsDraft,
- }
- await createContext({ metadata: { name: contextId }, spec: createSpec })
- const nextName = encodeURIComponent(contextId)
- router.replace(CONTROL_ROUTES.contexts.detail(nextName))
- } else {
- // Full-replace PUT: spread the spec exactly as it was loaded so additive
- // fields the form doesn't model (e.g. spec.gfs) survive a rename, then
- // overwrite only the fields the form owns.
- const nextSpec: Record<string, unknown> = {
- ...loadedSpec,
- contextId,
- description: descriptionDraft.trim(),
- mcpServers: mcpServersDraft,
- sharedFileSystems: sharedFileSystemsDraft,
- }
- // Clearing the display name must REMOVE it, not leave the spread's stale
- // value — so a delete is required, the empty-omit ternary no longer suffices.
- if (trimmedDisplay) nextSpec.displayName = trimmedDisplay
- else delete nextSpec.displayName
- // Optimistic concurrency: carry the loaded resourceVersion so a stale
- // edit 409s instead of clobbering a concurrent write, and track the
- // version the server echoes back for the next save.
- const updated = await updateContext(
- routeName,
- buildContextUpdatePayload(contextResourceVersion, nextSpec as unknown as ContextSpec)
- )
- setContextResourceVersion(updated.metadata?.resourceVersion ?? contextResourceVersion)
- setResolvedContextId(contextId)
- setSavedDescription(descriptionDraft)
- setSavedContextName(contextNameDraft)
- setSavedDisplayName(trimmedDisplay)
- setEditing(false)
- }
- showToast('Context saved.', { tone: 'success' })
- } catch (e) {
- setError(contextMutationError(e, 'Failed to save context'))
- } finally {
- setBusy(false)
- }
- }
-
- async function saveMcpServers(nextServers: string[]) {
- setBusy(true)
- setError('')
- try {
- // Full-replace PUT: spread the loaded spec so additive fields the form
- // doesn't model (e.g. spec.gfs) survive a connector edit, then overwrite
- // only the fields this handler owns (all re-echoed from current state).
- const nextSpec: Record<string, unknown> = {
- ...loadedSpec,
- contextId: resolvedContextId,
- description: descriptionDraft.trim(),
- mcpServers: nextServers,
- sharedFileSystems: sharedFileSystemsDraft,
- }
- // Echo the persisted display name; a cleared name must REMOVE it, not leave
- // the spread's stale value — so a delete is required (mirrors save()).
- if (savedDisplayName.trim()) nextSpec.displayName = savedDisplayName.trim()
- else delete nextSpec.displayName
- const updated = await updateContext(
- routeName,
- buildContextUpdatePayload(contextResourceVersion, nextSpec as unknown as ContextSpec)
- )
- setContextResourceVersion(updated.metadata?.resourceVersion ?? contextResourceVersion)
- setMcpServersDraft(nextServers)
- showToast('Connectors updated.', { tone: 'success' })
- } catch (e) {
- setError(contextMutationError(e, 'Failed to update connectors'))
- } finally {
- setBusy(false)
- }
- }
-
- async function saveSharedFileSystems(nextRefs: ContextSharedFileSystemRef[]) {
- setBusy(true)
- setError('')
- try {
- // Full-replace PUT: spread the loaded spec so additive fields the form
- // doesn't model (e.g. spec.gfs) survive an SFS edit, then overwrite only
- // the fields this handler owns (all re-echoed from current state).
- const nextSpec: Record<string, unknown> = {
- ...loadedSpec,
- contextId: resolvedContextId,
- description: descriptionDraft.trim(),
- mcpServers: mcpServersDraft,
- sharedFileSystems: nextRefs,
- }
- // Echo the persisted display name; a cleared name must REMOVE it, not leave
- // the spread's stale value — so a delete is required (mirrors save()).
- if (savedDisplayName.trim()) nextSpec.displayName = savedDisplayName.trim()
- else delete nextSpec.displayName
- const updated = await updateContext(
- routeName,
- buildContextUpdatePayload(contextResourceVersion, nextSpec as unknown as ContextSpec)
- )
- setContextResourceVersion(updated.metadata?.resourceVersion ?? contextResourceVersion)
- setSharedFileSystemsDraft(nextRefs)
- showToast('Shared filesystems updated.', { tone: 'success' })
- } catch (e) {
- setError(contextMutationError(e, 'Failed to update shared filesystems'))
- } finally {
- setBusy(false)
- }
- }
-
- async function addTeamsToContext() {
- if (selectedTeamIdsToAdd.length === 0 || !resolvedContextId) return
- setBusy(true)
- setError('')
- try {
- await Promise.all(
- selectedTeamIdsToAdd.map(async teamId => {
- const current = await getAdminTeamContexts(teamId)
- const next = Array.from(new Set([...(current.contextIds || []), resolvedContextId]))
- await updateAdminTeamContexts(teamId, next)
- })
- )
- const addedCount = selectedTeamIdsToAdd.length
- setSelectedTeamIdsToAdd([])
- showToast(
- addedCount === 1 ? 'Team added to context.' : `${addedCount} teams added to context.`,
- { tone: 'success' }
- )
- const refreshed = await getContextTeams(resolvedContextId)
- setContextTeams(Array.isArray(refreshed.items) ? refreshed.items : [])
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to add teams')
- } finally {
- setBusy(false)
- }
- }
-
- async function removeTeamFromContext(teamId: string) {
- if (!resolvedContextId) return
- const team = contextTeams.find(item => item.id === teamId)
- const shouldRemove = await confirm({
- title: 'Remove Team From Context',
- message: `Remove ${team?.name || 'this team'} from ${resolvedContextId}?`,
- confirmLabel: 'Remove team',
- tone: 'danger',
- })
- if (!shouldRemove) return
-
- setBusy(true)
- setError('')
- try {
- const current = await getAdminTeamContexts(teamId)
- const next = (current.contextIds || []).filter(id => id !== resolvedContextId)
- await updateAdminTeamContexts(teamId, next)
- showToast('Team removed from context.', { tone: 'success' })
- setContextTeams(prev => prev.filter(t => t.id !== teamId))
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to remove team')
- } finally {
- setBusy(false)
- }
- }
-
- async function addUsersToContext() {
- if (selectedUserIdsToAdd.length === 0 || !resolvedContextId) return
- setBusy(true)
- setError('')
- try {
- await Promise.all(
- selectedUserIdsToAdd.map(async userId => {
- const current = await getAdminUserContexts(userId)
- const next = Array.from(new Set([...(current.contextIds || []), resolvedContextId]))
- await updateAdminUserContexts(userId, next)
- })
- )
- const addedCount = selectedUserIdsToAdd.length
- setSelectedUserIdsToAdd([])
- showToast(
- addedCount === 1 ? 'Member added to context.' : `${addedCount} members added to context.`,
- { tone: 'success' }
- )
- const refreshed = await getContextUsers(resolvedContextId)
- setContextUsers(Array.isArray(refreshed.items) ? refreshed.items : [])
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to add members')
- } finally {
- setBusy(false)
- }
- }
-
- async function removeUserFromContext(userId: string) {
- if (!resolvedContextId) return
- const user = contextUsers.find(item => item.id === userId)
- const shouldRemove = await confirm({
- title: 'Remove Member From Context',
- message: `Remove ${user?.displayName || user?.name || user?.email || 'this member'} from ${resolvedContextId}?`,
- confirmLabel: 'Remove member',
- tone: 'danger',
- })
- if (!shouldRemove) return
-
- setBusy(true)
- setError('')
- try {
- const current = await getAdminUserContexts(userId)
- const next = (current.contextIds || []).filter(id => id !== resolvedContextId)
- await updateAdminUserContexts(userId, next)
- showToast('Member removed from context.', { tone: 'success' })
- setContextUsers(prev => prev.filter(u => u.id !== userId))
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to remove member')
- } finally {
- setBusy(false)
- }
- }
-
- async function addAgentsToContext() {
- if (selectedAgentNamesToAdd.length === 0 || !resolvedContextId.trim()) return
-
- const hostsByName = new Map(
- allHosts.map(host => [String(host.metadata?.name || '').trim(), host] as const)
- )
- const selectedHosts = selectedAgentNamesToAdd
- .map(agentName => hostsByName.get(agentName))
- .filter((host): host is HostResource => Boolean(host))
- if (selectedHosts.length !== selectedAgentNamesToAdd.length) {
- setError('One or more selected agents could not be loaded. Please refresh and try again.')
- return
- }
-
- const movingAgents = selectedHosts
- .map(host => ({
- name: String(host.metadata?.name || '').trim(),
- contextRef: String(host.spec?.contextRef || '').trim(),
- }))
- .filter(agent => agent.contextRef && agent.contextRef !== resolvedContextId)
-
- setBusy(true)
- setError('')
- try {
- await Promise.all(
- selectedHosts.map(host =>
- apiSend('PUT', `/api/v1/admin/hosts/${encodeURIComponent(host.metadata?.name || '')}`, {
- spec: {
- ...(host.spec || {}),
- contextRef: resolvedContextId,
- },
- })
- )
- )
-
- const refreshedHostsData = await getHosts()
- const refreshedHosts = (refreshedHostsData.items || []) as HostResource[]
- setAllHosts(refreshedHosts)
- const linked = refreshedHosts
- .filter(item => String(item.spec?.contextRef || '').trim() === resolvedContextId)
- .map(item => ({
- name: item.metadata?.name || '-',
- namespace: item.metadata?.namespace || 'default',
- }))
- .sort((a, b) => `${a.namespace}/${a.name}`.localeCompare(`${b.namespace}/${b.name}`))
- setLinkedHosts(linked)
- setSelectedAgentNamesToAdd([])
- showToast(
- selectedHosts.length === 1
- ? movingAgents.length === 1
- ? 'Agent moved to context.'
- : 'Agent added to context.'
- : `${selectedHosts.length} agents added to context.`,
- { tone: 'success' }
- )
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to add agents')
- } finally {
- setBusy(false)
- }
- }
-
- async function onDelete() {
- if (isNew) return
- const shouldDelete = await confirm({
- title: 'Delete Context',
- message: `Delete context ${routeName}?`,
- confirmLabel: 'Delete',
- tone: 'danger',
- })
- if (!shouldDelete) return
-
- setBusy(true)
- setError('')
- try {
- await deleteContext(routeName)
- showToast(`Context ${routeName} deleted.`, { tone: 'success' })
- router.push(CONTROL_ROUTES.contexts.root)
- } catch (e) {
- setError(e instanceof Error ? e.message : 'Failed to delete context')
- } finally {
- setBusy(false)
- }
- }
-
- const teamIdsInContext = useMemo(() => new Set(contextTeams.map(t => t.id)), [contextTeams])
- const userIdsInContext = useMemo(() => new Set(contextUsers.map(u => u.id)), [contextUsers])
- const teamOptions = useMemo(
- () =>
- allTeams
- .filter(team => !teamIdsInContext.has(team.id))
- .map(team => ({ value: team.id, label: team.name })),
- [allTeams, teamIdsInContext]
- )
- const memberOptions = useMemo(
- () =>
- allUsers
- .filter(user => !userIdsInContext.has(user.id))
- .map(user => ({
- value: user.id,
- label: user.displayName || user.name || user.email || user.id,
- description: user.email || user.id,
- badge: user.activeTeamCount === 1 ? '1 team' : `${user.activeTeamCount} teams`,
- })),
- [allUsers, userIdsInContext]
- )
- const agentOptions = useMemo(
- () =>
- availableAgentsToAttach.map(agent => ({
- value: agent.name,
- label: agent.displayName,
- description: agent.contextRef ? `Currently in ${agent.contextRef}` : agent.name,
- })),
- [availableAgentsToAttach]
- )
- const connectorOptions = useMemo(
- () =>
- availableServers
- .filter(server => !mcpServersDraft.includes(server))
- .map(server => ({ value: server, label: server })),
- [availableServers, mcpServersDraft]
- )
-
- if (!loaded && !isNew) {
- return (
- <DashboardLayout isDetailPage>
- <CreateFlowPanel
- className="cu-detail-flow-panel"
- header={
- <CreatePageHeader
- icon={<IconGroupWork />}
- title={routeName || 'Context'}
- subtitle="Loading context details..."
- backLabel="Back to contexts"
- onBack={() => router.push(CONTROL_ROUTES.contexts.root)}
- backDisabled
- actions={
- <div
- className="cu-skeleton cu-skeleton--cell"
- style={{ width: '2rem', height: '2rem' }}
- />
- }
- />
- }
- >
- <TabBar<ContextTab>
- ariaLabel="Context sections"
- activeValue={activeTab}
- className="cu-tabs--compact"
- onChange={selectTab}
- options={CONTEXT_TABS.map(tab => ({
- value: tab,
- label: TAB_LABELS[tab],
- href: contextTabHref(tab),
- disabled: true,
- }))}
- />
- </CreateFlowPanel>
- <div className="cu-card">
- <div className="cu-card__body">
- <div
- className="cu-skeleton cu-skeleton--cell"
- style={{ width: '6rem', height: '0.75rem', marginBottom: '1rem' }}
- />
- <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '1rem' }}>
- <div>
- <div
- className="cu-skeleton cu-skeleton--cell"
- style={{ width: '100%', height: '2.5rem', marginBottom: '0.75rem' }}
- />
- <div
- className="cu-skeleton cu-skeleton--cell"
- style={{ width: '80%', height: '2.5rem' }}
- />
- </div>
- <div>
- <div
- className="cu-skeleton cu-skeleton--cell"
- style={{ width: '90%', height: '2.5rem', marginBottom: '0.75rem' }}
- />
- <div
- className="cu-skeleton cu-skeleton--cell"
- style={{ width: '70%', height: '2.5rem' }}
- />
- </div>
- </div>
- </div>
- </div>
- </DashboardLayout>
- )
- }
- if (isNew) {
- return (
- <DashboardLayout isDetailPage>
- <div className="cu-card">
- <div className="cu-card__body">Redirecting to the dedicated create-context page...</div>
- </div>
- </DashboardLayout>
- )
- }
-
- return (
- <DashboardLayout isDetailPage>
- <CreateFlowPanel
- className="cu-detail-flow-panel"
- header={
- <CreatePageHeader
- icon={<IconGroupWork />}
- title={savedDisplayName.trim() || routeName}
- subtitle="Review details, manage connectors, agents, teams, and members."
- backLabel="Back to contexts"
- onBack={() => router.push(CONTROL_ROUTES.contexts.root)}
- titleActions={
- <ContextActionsMenu
- busy={busy}
- editing={editing}
- onEdit={startEditing}
- onDelete={() => void onDelete()}
- />
- }
- />
- }
- >
- <TabBar<ContextTab>
- ariaLabel="Context sections"
- activeValue={activeTab}
- className="cu-tabs--compact"
- onChange={selectTab}
- options={CONTEXT_TABS.map(tab => ({
- value: tab,
- label: TAB_LABELS[tab],
- href: contextTabHref(tab),
- }))}
- />
- </CreateFlowPanel>
-
- {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}
- <div className="cu-card">
- <div className="cu-card__body">
- {activeTab === 'connectors' && (
- <>
- <div
- style={{
- display: 'flex',
- flexWrap: 'wrap',
- justifyContent: 'space-between',
- alignItems: 'center',
- gap: '0.5rem',
- marginBottom: '1rem',
- }}
- >
- <p className="cu-muted" style={{ fontSize: '0.875rem', margin: 0 }}>
- connectors attached to this context.
- </p>
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={() => setShowAddMcpServer(true)}
- disabled={busy}
- >
- Add connector
- </button>
- </div>
- {mcpServersDraft.length === 0 ? (
- <div className="cu-empty" style={{ padding: '0 0 1rem' }}>
- No connectors assigned yet.
- </div>
- ) : (
- <div className="cu-table-wrap">
- <table className="cu-table">
- <thead>
- <TableHeaderRow columns={CONNECTOR_COLUMNS} />
- </thead>
- <tbody>
- {mcpServersDraft.map(server => (
- <tr key={server}>
- <td>{server}</td>
- <td className="cu-table__cell-actions">
- <div className="cu-row-actions">
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--danger-icon"
- onClick={() =>
- void saveMcpServers(mcpServersDraft.filter(s => s !== server))
- }
- disabled={busy}
- aria-label={`Remove connector ${server}`}
- >
- <IconX width={16} height={16} />
- </button>
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </>
- )}
-
- {activeTab === 'agent-files' && (
- <>
- {sharedFileSystemsDraft.length === 0 ? (
- <div className="cu-empty">No SharedFileSystems attached.</div>
- ) : (
- <div className="cu-table-wrap">
- <table className="cu-table">
- <thead>
- <TableHeaderRow columns={SHARED_FILE_COLUMNS} />
- </thead>
- <tbody>
- {sharedFileSystemsDraft.map(ref => (
- <tr key={`${ref.name}@${ref.mountPath}`}>
- <td>
- <Link
- className="cu-link"
- href={CONTROL_ROUTES.agentFiles.detail(ref.name)}
- style={{
- display: 'inline-flex',
- alignItems: 'center',
- gap: '0.35rem',
- }}
- >
- <IconFolder />
- {ref.name}
- </Link>
- </td>
- <td>
- <code style={{ fontSize: '0.85rem' }}>{ref.mountPath}</code>
- </td>
- <td className="cu-table__cell-actions">
- <div className="cu-row-actions">
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--danger-icon"
- disabled={busy}
- onClick={() =>
- void saveSharedFileSystems(
- sharedFileSystemsDraft.filter(
- r => !(r.name === ref.name && r.mountPath === ref.mountPath)
- )
- )
- }
- aria-label={`Detach shared filesystem ${ref.name}`}
- >
- <IconX width={16} height={16} />
- </button>
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
-
- <div className="cu-divider" />
-
- <div
- style={{
- display: 'flex',
- gap: '0.5rem',
- flexWrap: 'wrap',
- alignItems: 'flex-end',
- }}
- >
- <div className="cu-field" style={{ flex: '1 1 14rem', marginBottom: 0 }}>
- <label htmlFor="ctx-sfs-name">SharedFileSystem</label>
- <select
- id="ctx-sfs-name"
- className="cu-input"
- value={sfsAddName}
- onChange={e => {
- const v = e.target.value
- setSfsAddName(v)
- if (v && !sfsAddMount.trim()) setSfsAddMount(`/workspace/${v}`)
- }}
- disabled={busy}
- >
- <option value="">Select…</option>
- {availableSfses
- .filter(n => !sharedFileSystemsDraft.some(r => r.name === n))
- .map(n => (
- <option key={n} value={n}>
- {n}
- </option>
- ))}
- </select>
- </div>
- <div className="cu-field" style={{ flex: '2 1 18rem', marginBottom: 0 }}>
- <label htmlFor="ctx-sfs-mount">Mount path</label>
- <input
- id="ctx-sfs-mount"
- className="cu-input"
- value={sfsAddMount}
- placeholder="/workspace/<sfs-name>"
- onChange={e => setSfsAddMount(e.target.value)}
- disabled={busy}
- />
- </div>
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- disabled={
- busy ||
- !sfsAddName.trim() ||
- !sfsAddMount.trim() ||
- sharedFileSystemsDraft.some(r => r.name === sfsAddName.trim())
- }
- onClick={() => {
- const next = [
- ...sharedFileSystemsDraft,
- { name: sfsAddName.trim(), mountPath: sfsAddMount.trim() },
- ]
- setSfsAddName('')
- setSfsAddMount('')
- void saveSharedFileSystems(next)
- }}
- >
- Attach
- </button>
- </div>
- </>
- )}
-
- {activeTab === 'agents' && (
- <>
- <div
- style={{
- display: 'flex',
- flexWrap: 'wrap',
- justifyContent: 'space-between',
- alignItems: 'center',
- gap: '0.5rem',
- marginBottom: '1rem',
- }}
- >
- <p className="cu-muted" style={{ fontSize: '0.875rem', margin: 0 }}>
- Agents using this context.
- </p>
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={() => setShowAddAgent(true)}
- disabled={busy}
- >
- Add agent
- </button>
- </div>
- {linkedHosts.length === 0 ? (
- <div className="cu-empty" style={{ padding: '0 0 1rem' }}>
- No agents reference this context.
- </div>
- ) : (
- <div className="cu-table-wrap">
- <table className="cu-table">
- <thead>
- <TableHeaderRow columns={AGENT_COLUMNS} />
- </thead>
- <tbody>
- {linkedHosts.map(host => (
- <tr key={`${host.namespace}/${host.name}`}>
- <td>
- <button
- type="button"
- className="cu-link"
- onClick={() => router.push(CONTROL_ROUTES.agents.detail(host.name))}
- >
- {host.name}
- </button>
- </td>
- <td className="cu-table__cell-muted">{host.namespace}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </>
- )}
-
- {activeTab === 'teams' && (
- <>
- <div
- style={{
- display: 'flex',
- flexWrap: 'wrap',
- justifyContent: 'space-between',
- alignItems: 'center',
- gap: '0.5rem',
- marginBottom: '1rem',
- }}
- >
- <p className="cu-muted" style={{ fontSize: '0.875rem', margin: 0 }}>
- Teams with access to this context.
- </p>
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={() => setShowAddTeam(true)}
- disabled={busy}
- >
- Add team
- </button>
- </div>
- {contextTeams.length === 0 ? (
- <div className="cu-empty" style={{ padding: '0 0 1rem' }}>
- No teams mapped to this context.
- </div>
- ) : (
- <div className="cu-table-wrap">
- <table className="cu-table">
- <thead>
- <TableHeaderRow columns={TEAM_COLUMNS} />
- </thead>
- <tbody>
- {contextTeams.map(team => (
- <tr key={team.id}>
- <td>
- <button
- type="button"
- className="cu-link"
- onClick={() =>
- router.push(CONTROL_ROUTES.usersAndTeams.team(team.id))
- }
- >
- {team.name}
- </button>
- </td>
- <td className="cu-table__cell-actions">
- <div className="cu-row-actions">
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--danger-icon"
- onClick={() => void removeTeamFromContext(team.id)}
- disabled={busy}
- aria-label={`Remove team ${team.name}`}
- >
- <IconX width={16} height={16} />
- </button>
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </>
- )}
-
- {activeTab === 'members' && (
- <>
- <div
- style={{
- display: 'flex',
- flexWrap: 'wrap',
- justifyContent: 'space-between',
- alignItems: 'center',
- gap: '0.5rem',
- marginBottom: '1rem',
- }}
- >
- <p className="cu-muted" style={{ fontSize: '0.875rem', margin: 0 }}>
- Members with access to this context.
- </p>
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={() => setShowAddUser(true)}
- disabled={busy}
- >
- Add member
- </button>
- </div>
- {contextUsers.length === 0 ? (
- <div className="cu-empty" style={{ padding: '0 0 1rem' }}>
- No members mapped to this context.
- </div>
- ) : (
- <div className="cu-table-wrap">
- <table className="cu-table">
- <thead>
- <TableHeaderRow columns={MEMBER_COLUMNS} />
- </thead>
- <tbody>
- {contextUsers.map(user => {
- const memberLabel = user.displayName || user.name || user.email || user.id
- return (
- <tr key={user.id}>
- <td>
- <button
- type="button"
- className="cu-link"
- onClick={() =>
- router.push(CONTROL_ROUTES.usersAndTeams.user(user.id))
- }
- >
- {memberLabel}
- </button>
- </td>
- <td className="cu-table__cell-muted">{user.email || user.id}</td>
- <td className="cu-table__cell-actions">
- <div className="cu-row-actions">
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--danger-icon"
- onClick={() => void removeUserFromContext(user.id)}
- disabled={busy}
- aria-label={`Remove member ${memberLabel}`}
- >
- <IconX width={16} height={16} />
- </button>
- </div>
- </td>
- </tr>
- )
- })}
- </tbody>
- </table>
- </div>
- )}
- </>
- )}
- </div>
- </div>
-
- {editing ? (
- <div
- className="cu-modal-backdrop"
- role="presentation"
- onClick={event => {
- if (event.target === event.currentTarget && !busy) cancelEditing()
- }}
- >
- <div
- className="cu-modal-panel cu-modal-panel--narrow"
- role="dialog"
- aria-modal="true"
- aria-labelledby="edit-context-title"
- onClick={event => event.stopPropagation()}
- >
- <div className="cu-modal-panel__head">
- <h3 id="edit-context-title" className="cu-modal-panel__title">
- Edit context
- </h3>
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--ghost"
- onClick={cancelEditing}
- disabled={busy}
- aria-label="Close edit context"
- >
- <IconX width={16} height={16} />
- </button>
- </div>
- <div className="cu-modal-panel__body">
- <div className="cu-field" style={{ marginBottom: 0 }}>
- <label htmlFor="ctx-name">Name</label>
- <input id="ctx-name" className="cu-input" value={contextNameDraft} readOnly />
- <span className="cu-field__hint">
- This is the context identifier, not editable.
- </span>
- </div>
- <div className="cu-field" style={{ marginBottom: 0 }}>
- <label htmlFor="ctx-display">Display name</label>
- <input
- id="ctx-display"
- className="cu-input"
- value={displayNameDraft}
- onChange={event => setDisplayNameDraft(event.target.value)}
- disabled={busy}
- placeholder="Human-readable name"
- autoFocus
- />
- </div>
- <div className="cu-field" style={{ marginBottom: 0 }}>
- <label htmlFor="ctx-desc">Description</label>
- <textarea
- id="ctx-desc"
- className="cu-input"
- value={descriptionDraft}
- onChange={event => setDescriptionDraft(event.target.value)}
- disabled={busy}
- rows={3}
- placeholder="Human-readable context description"
- />
- </div>
- </div>
- <div className="cu-modal-panel__foot">
- <button
- type="button"
- className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={cancelEditing}
- disabled={busy}
- >
- Cancel
- </button>
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={() => void save()}
- disabled={!canSave}
- >
- {busy ? 'Saving…' : 'Save'}
- </button>
- </div>
- </div>
- </div>
- ) : null}
-
- {showAddAgent && (
- <div
- style={{
- position: 'fixed',
- inset: 0,
- background: 'var(--cu-overlay)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000,
- padding: '1rem',
- }}
- role="presentation"
- onClick={e => {
- if (e.target === e.currentTarget && !busy) setShowAddAgent(false)
- }}
- >
- <div
- className="cu-modal-panel cu-modal-panel--selection"
- role="dialog"
- aria-labelledby="add-agent-title"
- onClick={e => e.stopPropagation()}
- >
- <div className="cu-modal-panel__head">
- <strong id="add-agent-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>
- Add agent to context
- </strong>
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--ghost"
- onClick={() => setShowAddAgent(false)}
- disabled={busy}
- aria-label="Close"
- >
- <IconX width={18} height={18} />
- </button>
- </div>
-
- <div className="cu-field">
- <label htmlFor="context-agent-picker">Agents</label>
- <SelectionDropdown
- id="context-agent-picker"
- inline
- value={selectedAgentNamesToAdd}
- onChange={setSelectedAgentNamesToAdd}
- options={agentOptions}
- placeholder="Select agents"
- searchPlaceholder="Search agents..."
- selectionLabel="Selected agents"
- emptyLabel="No available agents."
- disabled={busy}
- />
- </div>
-
- <div className="cu-modal-panel__foot">
- <button
- type="button"
- className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={() => setShowAddAgent(false)}
- disabled={busy}
- >
- Cancel
- </button>
- <button
- type="button"
- className="cu-btn cu-btn--primary"
- onClick={async () => {
- await addAgentsToContext()
- setShowAddAgent(false)
- }}
- disabled={busy || selectedAgentNamesToAdd.length === 0}
- >
- {selectedAgentNamesToAdd.length > 1 ? 'Add agents' : 'Add agent'}
- </button>
- </div>
- </div>
- </div>
- )}
-
- {showAddTeam && (
- <div
- style={{
- position: 'fixed',
- inset: 0,
- background: 'rgba(0, 0, 0, 0.6)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000,
- padding: '1rem',
- }}
- role="presentation"
- onClick={e => {
- if (e.target === e.currentTarget && !busy) setShowAddTeam(false)
- }}
- >
- <div
- className="cu-modal-panel cu-modal-panel--selection"
- role="dialog"
- aria-labelledby="add-team-title"
- onClick={e => e.stopPropagation()}
- >
- <div className="cu-modal-panel__head">
- <strong id="add-team-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>
- Add team to context
- </strong>
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--ghost"
- onClick={() => setShowAddTeam(false)}
- disabled={busy}
- aria-label="Close"
- >
- <IconX width={18} height={18} />
- </button>
- </div>
-
- <div className="cu-field">
- <label htmlFor="context-team-picker">Team</label>
- <SelectionDropdown
- id="context-team-picker"
- inline
- value={selectedTeamIdsToAdd}
- onChange={setSelectedTeamIdsToAdd}
- options={teamOptions}
- placeholder="Select teams"
- searchPlaceholder="Search teams..."
- selectionLabel="Selected teams"
- emptyLabel="No available teams."
- disabled={busy}
- />
- </div>
-
- <div className="cu-modal-panel__foot">
- <button
- type="button"
- className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={() => setShowAddTeam(false)}
- disabled={busy}
- >
- Cancel
- </button>
- <button
- type="button"
- className="cu-btn cu-btn--primary"
- onClick={async () => {
- await addTeamsToContext()
- setShowAddTeam(false)
- }}
- disabled={busy || selectedTeamIdsToAdd.length === 0}
- >
- {selectedTeamIdsToAdd.length > 1 ? 'Add teams' : 'Add team'}
- </button>
- </div>
- </div>
- </div>
- )}
-
- {showAddUser && (
- <div
- style={{
- position: 'fixed',
- inset: 0,
- background: 'rgba(0, 0, 0, 0.6)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000,
- padding: '1rem',
- }}
- role="presentation"
- onClick={e => {
- if (e.target === e.currentTarget && !busy) setShowAddUser(false)
- }}
- >
- <div
- className="cu-modal-panel cu-modal-panel--selection"
- role="dialog"
- aria-labelledby="add-member-title"
- onClick={e => e.stopPropagation()}
- >
- <div className="cu-modal-panel__head">
- <strong id="add-member-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>
- Add member to context
- </strong>
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--ghost"
- onClick={() => setShowAddUser(false)}
- disabled={busy}
- aria-label="Close"
- >
- <IconX width={18} height={18} />
- </button>
- </div>
-
- <div className="cu-field">
- <label htmlFor="context-member-picker">Members</label>
- <SelectionDropdown
- id="context-member-picker"
- inline
- value={selectedUserIdsToAdd}
- onChange={setSelectedUserIdsToAdd}
- options={memberOptions}
- placeholder="Select members"
- searchPlaceholder="Search members..."
- selectionLabel="Selected members"
- emptyLabel="No available members."
- disabled={busy}
- />
- </div>
-
- <div className="cu-modal-panel__foot">
- <button
- type="button"
- className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={() => setShowAddUser(false)}
- disabled={busy}
- >
- Cancel
- </button>
- <button
- type="button"
- className="cu-btn cu-btn--primary"
- onClick={async () => {
- await addUsersToContext()
- setShowAddUser(false)
- }}
- disabled={busy || selectedUserIdsToAdd.length === 0}
- >
- {selectedUserIdsToAdd.length > 1 ? 'Add members' : 'Add member'}
- </button>
- </div>
- </div>
- </div>
- )}
-
- {showAddMcpServer && (
- <div
- style={{
- position: 'fixed',
- inset: 0,
- background: 'rgba(0, 0, 0, 0.6)',
- display: 'flex',
- alignItems: 'center',
- justifyContent: 'center',
- zIndex: 1000,
- padding: '1rem',
- }}
- role="presentation"
- onClick={e => {
- if (e.target === e.currentTarget && !busy) setShowAddMcpServer(false)
- }}
- >
- <div
- className="cu-modal-panel cu-modal-panel--selection"
- role="dialog"
- aria-labelledby="add-mcp-title"
- onClick={e => e.stopPropagation()}
- >
- <div className="cu-modal-panel__head">
- <strong id="add-mcp-title" style={{ fontSize: '1rem', lineHeight: 1.35 }}>
- Add connector to context
- </strong>
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--ghost"
- onClick={() => setShowAddMcpServer(false)}
- disabled={busy}
- aria-label="Close"
- >
- <IconX width={18} height={18} />
- </button>
- </div>
-
- <div className="cu-field">
- <label htmlFor="context-connector-picker">Connectors</label>
- <SelectionDropdown
- id="context-connector-picker"
- inline
- value={selectedMcpServerNamesToAdd}
- onChange={setSelectedMcpServerNamesToAdd}
- options={connectorOptions}
- placeholder="Select connectors"
- searchPlaceholder="Search connectors..."
- selectionLabel="Selected connectors"
- emptyLabel="No available connectors."
- disabled={busy}
- />
- </div>
-
- <div className="cu-modal-panel__foot">
- <button
- type="button"
- className="cu-btn cu-btn--ghost cu-btn--sm"
- onClick={() => setShowAddMcpServer(false)}
- disabled={busy}
- >
- Cancel
- </button>
- <button
- type="button"
- className="cu-btn cu-btn--primary"
- onClick={async () => {
- if (selectedMcpServerNamesToAdd.length > 0) {
- await saveMcpServers([...mcpServersDraft, ...selectedMcpServerNamesToAdd])
- setSelectedMcpServerNamesToAdd([])
- }
- setShowAddMcpServer(false)
- }}
- disabled={busy || selectedMcpServerNamesToAdd.length === 0}
- >
- {selectedMcpServerNamesToAdd.length > 1 ? 'Add connectors' : 'Add connector'}
- </button>
- </div>
- </div>
- </div>
- )}
- {confirmDialog}
- </DashboardLayout>
- )
-}
diff --git a/control-ui/app/contexts/__tests__/ContextDetail.name.test.tsx b/control-ui/app/contexts/__tests__/ContextDetail.name.test.tsx
deleted file mode 100644
index 394d4ae17..000000000
--- a/control-ui/app/contexts/__tests__/ContextDetail.name.test.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-import React from 'react'
-import type { ReactNode } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
-import { ToastProvider } from '../../../components/Toast'
-import * as api from '../../../lib/api'
-import ContextDetailsPage from '../[name]/page'
-
-const replaceMock = vi.fn()
-const pushMock = vi.fn()
-let mockParams: { name: string; tab?: string } = { name: 'prod-ctx' }
-
-vi.mock('next/navigation', () => ({
- useParams: () => mockParams,
- usePathname: () => '/contexts/prod-ctx',
- useRouter: () => ({ push: pushMock, replace: replaceMock }),
- useSearchParams: () => new URLSearchParams(),
-}))
-
-// Render the frame as a passthrough so the form is the unit under test.
-vi.mock('../../../components/DashboardLayout', () => ({
- DashboardLayout: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('../../../lib/api', () => ({
- apiSend: vi.fn().mockResolvedValue({}),
- createContext: vi.fn().mockResolvedValue({}),
- deleteContext: vi.fn().mockResolvedValue({}),
- getAdminTeamContexts: vi.fn().mockResolvedValue({ contextIds: [] }),
- getAdminTeams: vi.fn().mockResolvedValue({ items: [] }),
- getAdminUserContexts: vi.fn().mockResolvedValue({ contextIds: [] }),
- getAdminUsers: vi.fn().mockResolvedValue({ items: [] }),
- getContext: vi.fn(),
- getContextTeams: vi.fn().mockResolvedValue({ items: [] }),
- getContextUsers: vi.fn().mockResolvedValue({ items: [] }),
- getHosts: vi.fn().mockResolvedValue({ items: [] }),
- getMcpServers: vi.fn().mockResolvedValue({ items: [] }),
- getSharedFileSystems: vi.fn().mockResolvedValue({ items: [] }),
- updateAdminTeamContexts: vi.fn().mockResolvedValue({}),
- updateAdminUserContexts: vi.fn().mockResolvedValue({}),
- updateContext: vi.fn().mockResolvedValue({}),
-}))
-
-type TestContext = {
- metadata: { name: string; resourceVersion?: string }
- spec: Record<string, unknown>
-}
-
-function mockContext(ctx: TestContext) {
- // dev's contexts page now uses optimistic concurrency: buildContextUpdatePayload
- // requires the loaded resourceVersion, so the load fixture must carry one or
- // every save throws "Context version is unavailable" before the PUT.
- const withVersion = {
- ...ctx,
- metadata: { resourceVersion: 'rv-context-read', ...ctx.metadata },
- }
- ;(api.getContext as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(withVersion)
-}
-
-function render(children: ReactNode) {
- return rtlRender(<ToastProvider>{children}</ToastProvider>)
-}
-
-async function openEditModal() {
- fireEvent.click(await screen.findByRole('button', { name: 'Context actions' }))
- fireEvent.click(screen.getByRole('menuitem', { name: 'Edit context' }))
-}
-
-afterEach(() => {
- cleanup()
-})
-
-describe('ContextDetailsPage display name (UT-10)', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockParams = { name: 'prod-ctx' }
- })
-
- it('shows a readonly identifier and edits the display name via a single PUT (no cascade)', async () => {
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: 'Original description',
- mcpServers: ['srv-a'],
- displayName: 'Prod Ctx',
- },
- })
-
- render(<ContextDetailsPage />)
-
- // The visible name (display) is shown in the header.
- expect(await screen.findByText('Prod Ctx')).toBeInTheDocument()
-
- await openEditModal()
-
- // Identifier is present but readonly, with a hint.
- const nameField = screen.getByLabelText('Name')
- expect(nameField).toHaveAttribute('readonly')
- expect(nameField).toHaveValue('prod-ctx')
- expect(screen.getByText(/identifier, not editable/i)).toBeInTheDocument()
-
- // The display name is the editable field, seeded from spec.displayName.
- const displayField = screen.getByLabelText('Display name')
- expect(displayField).toHaveValue('Prod Ctx')
- fireEvent.change(displayField, { target: { value: 'Prod Ctx 2' } })
-
- fireEvent.click(screen.getByRole('button', { name: 'Save' }))
-
- await waitFor(() => expect(api.updateContext).toHaveBeenCalled())
- const [name, payload] = (api.updateContext as unknown as ReturnType<typeof vi.fn>).mock
- .calls[0] as [string, { spec: Record<string, unknown> }]
- // Identifier / contextId untouched; the PUT targets the same slug.
- expect(name).toBe('prod-ctx')
- expect(payload.spec.contextId).toBe('prod-ctx')
- // Full-replace safety: the spec echoes its other fields, not just displayName.
- expect(payload.spec.displayName).toBe('Prod Ctx 2')
- expect(payload.spec.mcpServers).toEqual(['srv-a'])
-
- // No cascade: hosts are never re-written to chase a rename.
- expect(api.apiSend).not.toHaveBeenCalledWith(
- 'PUT',
- expect.stringContaining('/api/v1/admin/hosts/'),
- expect.anything()
- )
- expect(await screen.findByText('Context saved.')).toBeInTheDocument()
- })
-
- it('still saves the description through the same PUT', async () => {
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: 'Original description',
- mcpServers: [],
- displayName: 'Prod Ctx',
- },
- })
-
- render(<ContextDetailsPage />)
- await screen.findByText('Prod Ctx')
- await openEditModal()
-
- fireEvent.change(screen.getByLabelText('Description'), {
- target: { value: 'Updated description' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'Save' }))
-
- await waitFor(() => expect(api.updateContext).toHaveBeenCalled())
- const [, payload] = (api.updateContext as unknown as ReturnType<typeof vi.fn>).mock
- .calls[0] as [string, { spec: Record<string, unknown> }]
- expect(payload.spec.description).toBe('Updated description')
- expect(payload.spec.contextId).toBe('prod-ctx')
- })
-
- it('falls back to metadata.name when spec.displayName is absent (the only fallback)', async () => {
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: '',
- mcpServers: [],
- // no displayName
- },
- })
-
- render(<ContextDetailsPage />)
-
- // With no display name, the identifier is shown as the visible name.
- expect(await screen.findByText('prod-ctx')).toBeInTheDocument()
-
- await openEditModal()
- // The display name field is empty (ready to be filled), not the slug.
- expect(screen.getByLabelText('Display name')).toHaveValue('')
- })
-})
diff --git a/control-ui/app/contexts/__tests__/ContextDetail.spec-preserve.test.tsx b/control-ui/app/contexts/__tests__/ContextDetail.spec-preserve.test.tsx
deleted file mode 100644
index 1a1e134bf..000000000
--- a/control-ui/app/contexts/__tests__/ContextDetail.spec-preserve.test.tsx
+++ /dev/null
@@ -1,252 +0,0 @@
-import React from 'react'
-import type { ReactNode } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
-import { ToastProvider } from '../../../components/Toast'
-import * as api from '../../../lib/api'
-import ContextDetailsPage from '../[name]/page'
-
-const replaceMock = vi.fn()
-const pushMock = vi.fn()
-let mockParams: { name: string; tab?: string } = { name: 'prod-ctx' }
-
-vi.mock('next/navigation', () => ({
- useParams: () => mockParams,
- usePathname: () => '/contexts/prod-ctx',
- useRouter: () => ({ push: pushMock, replace: replaceMock }),
- useSearchParams: () => new URLSearchParams(),
-}))
-
-// Render the frame as a passthrough so the form is the unit under test.
-vi.mock('../../../components/DashboardLayout', () => ({
- DashboardLayout: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('../../../lib/api', () => ({
- apiSend: vi.fn().mockResolvedValue({}),
- createContext: vi.fn().mockResolvedValue({}),
- deleteContext: vi.fn().mockResolvedValue({}),
- getAdminTeamContexts: vi.fn().mockResolvedValue({ contextIds: [] }),
- getAdminTeams: vi.fn().mockResolvedValue({ items: [] }),
- getAdminUserContexts: vi.fn().mockResolvedValue({ contextIds: [] }),
- getAdminUsers: vi.fn().mockResolvedValue({ items: [] }),
- getContext: vi.fn(),
- getContextTeams: vi.fn().mockResolvedValue({ items: [] }),
- getContextUsers: vi.fn().mockResolvedValue({ items: [] }),
- getHosts: vi.fn().mockResolvedValue({ items: [] }),
- getMcpServers: vi.fn().mockResolvedValue({ items: [] }),
- getSharedFileSystems: vi.fn().mockResolvedValue({ items: [] }),
- updateAdminTeamContexts: vi.fn().mockResolvedValue({}),
- updateAdminUserContexts: vi.fn().mockResolvedValue({}),
- updateContext: vi.fn().mockResolvedValue({}),
-}))
-
-type TestContext = {
- metadata: { name: string; resourceVersion?: string }
- spec: Record<string, unknown>
-}
-
-function mockContext(ctx: TestContext) {
- // dev's contexts page now uses optimistic concurrency: buildContextUpdatePayload
- // requires the loaded resourceVersion, so the load fixture must carry one or
- // every save throws "Context version is unavailable" before the PUT.
- const withVersion = {
- ...ctx,
- metadata: { resourceVersion: 'rv-context-read', ...ctx.metadata },
- }
- ;(api.getContext as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(withVersion)
-}
-
-function render(children: ReactNode) {
- return rtlRender(<ToastProvider>{children}</ToastProvider>)
-}
-
-async function openEditModal() {
- fireEvent.click(await screen.findByRole('button', { name: 'Context actions' }))
- fireEvent.click(screen.getByRole('menuitem', { name: 'Edit context' }))
-}
-
-function lastPutSpec(): Record<string, unknown> {
- const calls = (api.updateContext as unknown as ReturnType<typeof vi.fn>).mock.calls
- const [, payload] = calls[calls.length - 1] as [string, { spec: Record<string, unknown> }]
- return payload.spec
-}
-
-afterEach(() => {
- cleanup()
-})
-
-describe('ContextDetailsPage spec preservation on update (R5-M2)', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- mockParams = { name: 'prod-ctx' }
- })
-
- it('(a) preserves a spec field the form does not model on a display-only rename', async () => {
- // spec.gfs is a real additive field of the context CRD that this form has no
- // input for. A full-replace PUT built only from form state would drop it.
- const gfs = {
- mounts: [{ drive: 'main', target: '/data/shared', scopes: ['gfs.read'] }],
- }
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: 'Original description',
- mcpServers: ['srv-a'],
- displayName: 'Prod Ctx',
- gfs,
- },
- })
-
- render(<ContextDetailsPage />)
- await screen.findByText('Prod Ctx')
- await openEditModal()
-
- fireEvent.change(screen.getByLabelText('Display name'), { target: { value: 'Prod Ctx 2' } })
- fireEvent.click(screen.getByRole('button', { name: 'Save' }))
-
- await waitFor(() => expect(api.updateContext).toHaveBeenCalled())
- const spec = lastPutSpec()
- // The unknown-to-the-form field survives the rename.
- expect(spec.gfs).toEqual(gfs)
- // And the field the user actually changed is applied.
- expect(spec.displayName).toBe('Prod Ctx 2')
- expect(spec.contextId).toBe('prod-ctx')
- })
-
- it('(b) removes displayName from the PUT body when the user clears it', async () => {
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: 'Original description',
- mcpServers: ['srv-a'],
- displayName: 'Prod Ctx',
- },
- })
-
- render(<ContextDetailsPage />)
- await screen.findByText('Prod Ctx')
- await openEditModal()
-
- fireEvent.change(screen.getByLabelText('Display name'), { target: { value: ' ' } })
- fireEvent.click(screen.getByRole('button', { name: 'Save' }))
-
- await waitFor(() => expect(api.updateContext).toHaveBeenCalled())
- const spec = lastPutSpec()
- // Cleared display name must be absent, not the stale value from the spread.
- expect('displayName' in spec).toBe(false)
- expect(spec.contextId).toBe('prod-ctx')
- })
-
- it('(c) still reflects edited description and preserves the loaded mcpServers/sharedFileSystems', async () => {
- const sharedFileSystems = [{ name: 'sfs-a', mountPath: '/workspace/sfs-a' }]
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: 'Original description',
- mcpServers: ['srv-a', 'srv-b'],
- sharedFileSystems,
- displayName: 'Prod Ctx',
- },
- })
-
- render(<ContextDetailsPage />)
- await screen.findByText('Prod Ctx')
- await openEditModal()
-
- fireEvent.change(screen.getByLabelText('Description'), {
- target: { value: 'Updated description' },
- })
- fireEvent.click(screen.getByRole('button', { name: 'Save' }))
-
- await waitFor(() => expect(api.updateContext).toHaveBeenCalled())
- const spec = lastPutSpec()
- expect(spec.description).toBe('Updated description')
- expect(spec.mcpServers).toEqual(['srv-a', 'srv-b'])
- expect(spec.sharedFileSystems).toEqual(sharedFileSystems)
- expect(spec.displayName).toBe('Prod Ctx')
- })
-})
-
-describe('ContextDetailsPage spec preservation on connector/SFS edits (R5-M3)', () => {
- // spec.gfs — modeled on the real context CRD (charts/clerum-crds/crds/context.yaml,
- // spec.gfs.mounts[].{drive,target,scopes}) — is an additive field the form has no
- // input for. saveMcpServers / saveSharedFileSystems build a full-replace PUT, so
- // without a spread of the loaded spec they silently drop it.
- const gfs = {
- mounts: [{ drive: 'main', target: '/data/shared', scopes: ['gfs.read'] }],
- }
-
- beforeEach(() => {
- vi.clearAllMocks()
- mockParams = { name: 'prod-ctx' }
- })
-
- it('saveMcpServers preserves an unmodeled spec field (gfs) while applying the connector change', async () => {
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: 'Original description',
- mcpServers: ['srv-a', 'srv-b'],
- displayName: 'Prod Ctx',
- gfs,
- },
- })
-
- render(<ContextDetailsPage />)
- // Connectors is the default tab — remove one connector to trigger saveMcpServers.
- fireEvent.click(await screen.findByRole('button', { name: 'Remove connector srv-b' }))
-
- await waitFor(() => expect(api.updateContext).toHaveBeenCalled())
- const spec = lastPutSpec()
- // The unmodeled field survives the connector edit.
- expect(spec.gfs).toEqual(gfs)
- // The change the handler owns is applied…
- expect(spec.mcpServers).toEqual(['srv-a'])
- // …and the echoed fields are intact.
- expect(spec.displayName).toBe('Prod Ctx')
- expect(spec.contextId).toBe('prod-ctx')
- })
-
- // SKIPPED by the dev sync: dev removed the 'agent-files' tab from the context
- // page (CONTEXT_TABS dropped it) and moved SharedFileSystem management to the
- // dedicated /agent-files route — same restructure as channels → the detach
- // control this test drives no longer renders here. The R5-M3 invariant
- // (unmodeled spec fields survive an edit via the loadedSpec spread) is still
- // enforced in saveSharedFileSystems' code and is covered on the reachable path
- // by the saveMcpServers case above. Un-skip and retarget only if the SFS UI is
- // reinstated on the context page.
- it.skip('saveSharedFileSystems preserves an unmodeled spec field (gfs) while applying the SFS change', async () => {
- // Land directly on the agent-files tab, where the detach control lives.
- mockParams = { name: 'prod-ctx', tab: 'agent-files' }
- mockContext({
- metadata: { name: 'prod-ctx' },
- spec: {
- contextId: 'prod-ctx',
- description: 'Original description',
- mcpServers: ['srv-a'],
- sharedFileSystems: [{ name: 'sfs-a', mountPath: '/workspace/sfs-a' }],
- displayName: 'Prod Ctx',
- gfs,
- },
- })
-
- render(<ContextDetailsPage />)
- fireEvent.click(await screen.findByRole('button', { name: 'Detach shared filesystem sfs-a' }))
-
- await waitFor(() => expect(api.updateContext).toHaveBeenCalled())
- const spec = lastPutSpec()
- // The unmodeled field survives the SFS edit.
- expect(spec.gfs).toEqual(gfs)
- // The change the handler owns is applied…
- expect(spec.sharedFileSystems).toEqual([])
- // …and the echoed fields are intact.
- expect(spec.mcpServers).toEqual(['srv-a'])
- expect(spec.displayName).toBe('Prod Ctx')
- expect(spec.contextId).toBe('prod-ctx')
- })
-})
diff --git a/control-ui/app/contexts/__tests__/CreateContextPage.rfc1123-display-gate.test.tsx b/control-ui/app/contexts/__tests__/CreateContextPage.rfc1123-display-gate.test.tsx
deleted file mode 100644
index 25b308aa5..000000000
--- a/control-ui/app/contexts/__tests__/CreateContextPage.rfc1123-display-gate.test.tsx
+++ /dev/null
@@ -1,123 +0,0 @@
-import React from 'react'
-import type { ReactNode } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
-import { ToastProvider } from '../../../components/Toast'
-import * as api from '../../../lib/api'
-import CreateContextPage from '../new/page'
-
-/**
- * Regression guard for the context-create page's gate — the sibling of R4-H1 /
- * R5-H1 in HostWizard (phase 4 of the display-field mini-spec).
- *
- * D-A: canSubmit/canContinue/canSelectStep must gate on the FULL RFC1123 rule
- * (isValidResourceSlug), not just `toKebabCase(name).length > 0`. A name
- * whose derived slug is >63 chars trims/kebabs non-empty but the server
- * rejects it (invalid_name).
- * D-B: the free-text `spec.displayName` (contextName.trim()) must be validated
- * with the shared @clerum/display-field rule the server applies. A bidi/
- * control char survives into displayName (toKebabCase strips it from the
- * slug) or a >120-char display is rejected server-side.
- *
- * These tests FAIL against the pre-fix head, where the gates read only
- * `toKebabCase(contextName).length > 0`: the over-long slug and the bidi/long
- * display names all enabled Continue and let a doomed create escape.
- */
-
-const replaceMock = vi.fn()
-const pushMock = vi.fn()
-
-vi.mock('next/navigation', () => ({
- useRouter: () => ({ push: pushMock, replace: replaceMock }),
-}))
-
-vi.mock('@components/AuthGate', () => ({
- AuthGate: ({ children }: { children: ReactNode }) => <>{children}</>,
-}))
-
-vi.mock('../../../components/DashboardLayout', () => ({
- DashboardLayout: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('../../../lib/api', () => ({
- createContext: vi.fn().mockResolvedValue({}),
- getMcpServers: vi.fn().mockResolvedValue({ items: [] }),
-}))
-
-function render(children: ReactNode) {
- return rtlRender(<ToastProvider>{children}</ToastProvider>)
-}
-
-async function typeName(value: string) {
- render(<CreateContextPage />)
- await waitFor(() => expect(api.getMcpServers).toHaveBeenCalled())
- fireEvent.change(screen.getByPlaceholderText('Context 1'), { target: { value } })
-}
-
-afterEach(() => {
- cleanup()
-})
-
-describe('CreateContextPage — RFC1123 slug + displayName gate (D-A / D-B)', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- // INV-1 (D-A): a name whose derived slug exceeds 63 chars must block.
- it('blocks an over-long (>63) derived slug and never calls createContext', async () => {
- await typeName('a'.repeat(64)) // toKebabCase() → 64 chars, > RFC1123 limit
-
- const continueBtn = screen.getByRole('button', { name: 'Continue' })
- expect(continueBtn).toBeDisabled()
- expect(screen.getByText(/at most 63 characters/i)).toBeInTheDocument()
-
- fireEvent.click(continueBtn)
- expect(api.createContext).not.toHaveBeenCalled()
- })
-
- // INV-2 (D-B): the R5-H1 vector — a bidi override char. toKebabCase strips it,
- // so the slug (`ctxname`) is valid, but it survives into spec.displayName.
- it('blocks a name with a bidi formatting char (valid slug, invalid display)', async () => {
- await typeName('ctx‮name') // slug → "ctxname" (valid); display keeps U+202E
-
- const continueBtn = screen.getByRole('button', { name: 'Continue' })
- expect(continueBtn).toBeDisabled()
- expect(screen.getByText(/control or formatting characters/i)).toBeInTheDocument()
-
- // Observable result (T4): no create request escapes with a rejected display.
- fireEvent.click(continueBtn)
- expect(api.createContext).not.toHaveBeenCalled()
- })
-
- // INV-3 (D-B): a >120-char display value with a still-valid ≤63 slug.
- it('blocks a display value longer than 120 chars even when the slug is valid', async () => {
- // trim() length 131; toKebabCase() strips the dots → "a" (valid ≤63 slug).
- await typeName('a' + '.'.repeat(130))
-
- const continueBtn = screen.getByRole('button', { name: 'Continue' })
- expect(continueBtn).toBeDisabled()
- expect(screen.getByText(/too long \(max 120 characters\)/i)).toBeInTheDocument()
-
- fireEvent.click(continueBtn)
- expect(api.createContext).not.toHaveBeenCalled()
- })
-
- // Positive control: a clean name still enables Continue and creates.
- it('enables Continue for a valid name and shows the derived identifier', async () => {
- await typeName('My Context')
-
- const continueBtn = screen.getByRole('button', { name: 'Continue' })
- expect(continueBtn).not.toBeDisabled()
- expect(screen.getByText('my-context')).toBeInTheDocument()
-
- fireEvent.click(continueBtn)
- fireEvent.click(screen.getByRole('button', { name: 'Create context' }))
-
- await waitFor(() => expect(api.createContext).toHaveBeenCalled())
- const [payload] = (api.createContext as unknown as ReturnType<typeof vi.fn>).mock.calls[0] as [
- { metadata: { name: string }; spec: { contextId: string; displayName?: string } },
- ]
- expect(payload.metadata.name).toBe('my-context')
- expect(payload.spec.displayName).toBe('My Context')
- })
-})
diff --git a/control-ui/app/contexts/__tests__/CreateContextPage.slug-gate.test.tsx b/control-ui/app/contexts/__tests__/CreateContextPage.slug-gate.test.tsx
deleted file mode 100644
index 942e9f34b..000000000
--- a/control-ui/app/contexts/__tests__/CreateContextPage.slug-gate.test.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-import React from 'react'
-import type { ReactNode } from 'react'
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { cleanup, fireEvent, render as rtlRender, screen, waitFor } from '@testing-library/react'
-import { ToastProvider } from '../../../components/Toast'
-import * as api from '../../../lib/api'
-import CreateContextPage from '../new/page'
-
-/**
- * Regression guard for R1-M5 (class sibling of R1-B1): the context-create wizard
- * gates (canSubmit / canContinue / canSelectStep) must validate the DERIVED slug
- * (toKebabCase), not the raw trimmed text. A name with no ASCII alphanumerics
- * ("!!!", whitespace) trims non-empty but toKebabCase()s to "" — which would
- * POST metadata.name/contextId: "".
- *
- * These tests FAIL against the pre-fix head (c3ac3e40), where the gates read
- * `contextName.trim().length > 0` (so "!!!" enabled Continue and let create run).
- */
-
-const replaceMock = vi.fn()
-const pushMock = vi.fn()
-
-vi.mock('next/navigation', () => ({
- useRouter: () => ({ push: pushMock, replace: replaceMock }),
-}))
-
-vi.mock('@components/AuthGate', () => ({
- AuthGate: ({ children }: { children: ReactNode }) => <>{children}</>,
-}))
-
-vi.mock('../../../components/DashboardLayout', () => ({
- DashboardLayout: ({ children }: { children: ReactNode }) => <div>{children}</div>,
-}))
-
-vi.mock('../../../lib/api', () => ({
- createContext: vi.fn().mockResolvedValue({}),
- getMcpServers: vi.fn().mockResolvedValue({ items: [] }),
-}))
-
-function render(children: ReactNode) {
- return rtlRender(<ToastProvider>{children}</ToastProvider>)
-}
-
-afterEach(() => {
- cleanup()
-})
-
-describe('CreateContextPage — gates on the derived slug (R1-M5)', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- })
-
- it('keeps Continue DISABLED and never calls createContext for a symbols-only name', async () => {
- render(<CreateContextPage />)
- await waitFor(() => expect(api.getMcpServers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText('Context 1'), { target: { value: '!!!' } })
-
- const continueBtn = screen.getByRole('button', { name: 'Continue' })
- expect(continueBtn).toBeDisabled()
- expect(screen.getByText(/Context name must contain letters or numbers/i)).toBeInTheDocument()
-
- // The observable end result: no create request escapes with an empty slug.
- fireEvent.click(continueBtn)
- expect(api.createContext).not.toHaveBeenCalled()
- })
-
- it('keeps Continue DISABLED for a whitespace-only name', async () => {
- render(<CreateContextPage />)
- await waitFor(() => expect(api.getMcpServers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText('Context 1'), { target: { value: ' ' } })
-
- expect(screen.getByRole('button', { name: 'Continue' })).toBeDisabled()
- })
-
- it('enables Continue and creates with a non-empty slug for a valid name', async () => {
- render(<CreateContextPage />)
- await waitFor(() => expect(api.getMcpServers).toHaveBeenCalled())
-
- fireEvent.change(screen.getByPlaceholderText('Context 1'), { target: { value: 'My Ctx' } })
-
- const continueBtn = screen.getByRole('button', { name: 'Continue' })
- expect(continueBtn).not.toBeDisabled()
-
- // Advance to step 1 and create.
- fireEvent.click(continueBtn)
- fireEvent.click(screen.getByRole('button', { name: 'Create context' }))
-
- await waitFor(() => expect(api.createContext).toHaveBeenCalled())
- const [payload] = (api.createContext as unknown as ReturnType<typeof vi.fn>).mock.calls[0] as [
- { metadata: { name: string }; spec: { contextId: string } },
- ]
- expect(payload.metadata.name).toBe('my-ctx')
- expect(payload.spec.contextId).toBe('my-ctx')
- })
-})
diff --git a/control-ui/app/contexts/new/loading.tsx b/control-ui/app/contexts/new/loading.tsx
deleted file mode 100644
index 56676c32b..000000000
--- a/control-ui/app/contexts/new/loading.tsx
+++ /dev/null
@@ -1,6 +0,0 @@
-import { CreateFlowLoadingScreen } from '@components/CreateFlowSkeleton'
-import { CREATE_FLOW_LOADING } from '@constants/createFlowLoading'
-
-export default function Loading() {
- return <CreateFlowLoadingScreen {...CREATE_FLOW_LOADING.createContext} />
-}
diff --git a/control-ui/app/contexts/new/page.tsx b/control-ui/app/contexts/new/page.tsx
deleted file mode 100644
index 3bef1bdf4..000000000
--- a/control-ui/app/contexts/new/page.tsx
+++ /dev/null
@@ -1,304 +0,0 @@
-'use client'
-
-import React, { useEffect, useMemo, useState } from 'react'
-import { useRouter } from 'next/navigation'
-import {
- CONTROL_CHAR_RE,
- DISPLAY_FIELD_MAX_LENGTH,
- validateDisplayField,
-} from '@clerum/display-field'
-import { AuthGate } from '@components/AuthGate'
-import { CreateFlowPanel } from '@components/CreateFlowPanel'
-import { CreatePageHeader } from '@components/CreatePageHeader'
-import { CreateStepFlow } from '@components/CreateStepFlow'
-import { DashboardLayout } from '@components/DashboardLayout'
-import { SelectionDropdown } from '@components/SelectionDropdown'
-import { IconGroupWork } from '@components/Sidebar/icons'
-import { Button, Field, TextAreaInput, TextInput } from '@components/ui'
-import { CONTROL_ROUTES } from '@constants/routes'
-import { createContext, getMcpServers } from '@lib/api'
-import { RFC1123_MAX_LENGTH, isValidResourceSlug, toKebabCase } from '@lib/string'
-
-const STEPS = ['Context', 'Connectors'] as const
-
-// The exact free-text value the create call writes to spec.displayName. Only a
-// non-empty trimmed name is sent (an empty one is omitted from the payload), so
-// the display gate mirrors precisely what the server will validate.
-function displayNameValue(rawName: string): string {
- return rawName.trim()
-}
-
-// True when the derived slug AND the displayName the server would receive are
-// both acceptable. Mirrors the two server constraints client-side:
-// - slug: RFC1123 DNS label ≤63 (isValidResourceSlug, same as HostWizard).
-// - display: the shared @clerum/display-field rule (D4 — the RULE lives in the
-// package, the same one the server applies; here we only consume it). Empty
-// display is valid: it is omitted from the payload, and the empty case is
-// already blocked by the slug gate.
-function contextNameIsValid(rawName: string): boolean {
- if (!isValidResourceSlug(rawName)) return false
- const display = displayNameValue(rawName)
- if (display.length === 0) return true
- return validateDisplayField(display, 'spec.displayName') === null
-}
-
-// Human-readable reason the derived slug fails the server RFC1123 constraint, or
-// null when valid (or empty — the empty case is surfaced by the field's own
-// "must contain letters or numbers" message). Matches HostWizard.slugConstraintMessage.
-function slugConstraintMessage(rawName: string): string | null {
- const slug = toKebabCase(rawName)
- if (slug.length === 0) return null
- if (slug.length > RFC1123_MAX_LENGTH) return 'Identifier must be at most 63 characters.'
- if (!isValidResourceSlug(rawName)) return 'Identifier must be a valid RFC1123 identifier.'
- return null
-}
-
-// Human-readable reason the free-text spec.displayName value is rejected, or null
-// when acceptable. The RULE of validity is owned by @clerum/display-field (the
-// SAME rule the server applies, D4); this only maps the machine issue to a
-// message. Empty is intentionally NOT surfaced here — it is omitted from the
-// payload and the empty case is covered by the slug message.
-function displayNamePreflightMessage(rawName: string): string | null {
- const value = displayNameValue(rawName)
- if (value.length === 0) return null
- if (!validateDisplayField(value, 'spec.displayName')) return null
- if (CONTROL_CHAR_RE.test(value))
- return "Context name can't contain control or formatting characters."
- if (value.trim().length > DISPLAY_FIELD_MAX_LENGTH)
- return `Context name is too long (max ${DISPLAY_FIELD_MAX_LENGTH} characters).`
- return null
-}
-
-const STEP_DETAILS = [
- {
- description: 'Name and describe it',
- title: 'Context identity',
- subtitle: 'Define the context that agents will reference.',
- },
- {
- description: 'Attach connector tools',
- title: 'Connector allowlist',
- subtitle: 'Choose the connectors this context can expose to agents.',
- },
-] as const
-
-export default function CreateContextPage() {
- const router = useRouter()
-
- const [step, setStep] = useState(0)
- const [busy, setBusy] = useState(false)
- const [loadingServers, setLoadingServers] = useState(true)
- const [error, setError] = useState('')
- const [contextName, setContextName] = useState('')
- const [description, setDescription] = useState('')
- const [availableServers, setAvailableServers] = useState<string[]>([])
- const [selectedServers, setSelectedServers] = useState<string[]>([])
- const connectorOptions = useMemo(
- () =>
- availableServers.map(serverName => ({
- value: serverName,
- label: serverName,
- description: 'Connector',
- })),
- [availableServers]
- )
-
- useEffect(() => {
- async function loadServers() {
- setLoadingServers(true)
- setError('')
- try {
- const response = await getMcpServers()
- const names = (response.items || [])
- .map(item => item.metadata?.name || '')
- .filter(Boolean)
- .sort((a, b) => a.localeCompare(b))
- setAvailableServers(names)
- } catch (loadError) {
- setError(loadError instanceof Error ? loadError.message : 'Failed to load connectors')
- } finally {
- setLoadingServers(false)
- }
- }
-
- void loadServers()
- }, [])
-
- // Gate on the FULL server rules, not just "derived slug non-empty": the slug
- // must be a valid RFC1123 label (≤63) AND the free-text displayName the server
- // will receive must satisfy @clerum/display-field. A name that only clears
- // "non-empty slug" — an over-long slug, or a bidi/control/over-120 display —
- // passes the client and the server then rejects it (invalid_name / display).
- const canSubmit = useMemo(() => contextNameIsValid(contextName) && !busy, [busy, contextName])
- const canContinue = step === 0 ? contextNameIsValid(contextName) : true
-
- function canSelectStep(targetStep: number) {
- if (targetStep <= step) return true
- return contextNameIsValid(contextName)
- }
-
- async function handleCreateContext() {
- if (!canSubmit) return
- setBusy(true)
- setError('')
- try {
- const nextName = toKebabCase(contextName)
- const trimmedDisplay = contextName.trim()
- // Hard guard (defense if the gate is bypassed): the displayName is free
- // text the server validates with @clerum/display-field (D4 — the RULE is
- // the package's, the same one the server applies). Fail before any write
- // instead of round-tripping a doomed create.
- if (trimmedDisplay && validateDisplayField(trimmedDisplay, 'spec.displayName')) {
- setError(displayNamePreflightMessage(contextName) || 'Context name is not valid.')
- return
- }
- await createContext({
- metadata: { name: nextName },
- spec: {
- contextId: nextName,
- // Store the free-text name the user typed as the visible display name;
- // metadata.name/contextId stay the derived RFC1123 slug.
- ...(trimmedDisplay ? { displayName: trimmedDisplay } : {}),
- description: description.trim(),
- mcpServers: selectedServers,
- },
- })
- router.replace(CONTROL_ROUTES.contexts.detail(nextName))
- } catch (createError) {
- setError(createError instanceof Error ? createError.message : 'Failed to create context')
- } finally {
- setBusy(false)
- }
- }
-
- return (
- <AuthGate>
- <DashboardLayout isDetailPage>
- <CreateFlowPanel
- header={
- <CreatePageHeader
- icon={<IconGroupWork />}
- title="Create context"
- subtitle="Define a new context and attach connectors."
- backLabel="Back to contexts"
- onBack={() => router.push(CONTROL_ROUTES.contexts.root)}
- />
- }
- >
- <CreateStepFlow
- ariaLabel="Create context steps"
- className="cu-create-step-flow--2"
- currentStep={step}
- onStepChange={setStep}
- canSelectStep={canSelectStep}
- steps={STEP_DETAILS}
- stepLabels={STEPS}
- titleId="create-context-step-title"
- >
- {step === 0 ? (
- <div className="cu-form-stack cu-agent-form-stack">
- <Field label="Context name" htmlFor="ctx-name" required>
- <TextInput
- id="ctx-name"
- value={contextName}
- onChange={event => setContextName(event.target.value)}
- disabled={busy}
- placeholder="Context 1"
- autoFocus
- />
- {!toKebabCase(contextName) ? (
- contextName.trim() ? (
- <span className="cu-field__error">
- Context name must contain letters or numbers.
- </span>
- ) : null
- ) : slugConstraintMessage(contextName) ? (
- <span className="cu-field__error">{slugConstraintMessage(contextName)}</span>
- ) : displayNamePreflightMessage(contextName) ? (
- <span className="cu-field__error">
- {displayNamePreflightMessage(contextName)}
- </span>
- ) : (
- <span className="cu-field__hint">
- Identifier: <code>{toKebabCase(contextName)}</code>
- </span>
- )}
- </Field>
-
- <Field label="Description" htmlFor="ctx-description">
- <TextAreaInput
- id="ctx-description"
- value={description}
- onChange={event => setDescription(event.target.value)}
- disabled={busy}
- rows={3}
- placeholder="Human-readable context description"
- />
- </Field>
- </div>
- ) : null}
-
- {step === 1 ? (
- <div className="cu-form-stack cu-agent-form-stack">
- <Field label="Connectors">
- {loadingServers ? (
- <p className="cu-muted cu-muted-note--compact">Loading connectors...</p>
- ) : availableServers.length === 0 ? (
- <p className="cu-muted cu-muted-note--compact">No connectors found.</p>
- ) : (
- <SelectionDropdown
- id="new-context-connectors"
- inline
- value={selectedServers}
- onChange={setSelectedServers}
- options={connectorOptions}
- placeholder="Select connectors"
- searchPlaceholder="Search connectors..."
- selectionLabel="Selected connectors"
- emptyLabel="No connectors match your search."
- disabled={busy}
- />
- )}
- </Field>
- </div>
- ) : null}
-
- {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}
-
- <div className="cu-create-actions">
- <Button
- variant="ghost"
- size="sm"
- onClick={() =>
- step === 0 ? router.push(CONTROL_ROUTES.contexts.root) : setStep(step - 1)
- }
- disabled={busy}
- >
- {step === 0 ? 'Cancel' : 'Back'}
- </Button>
- {step < STEPS.length - 1 ? (
- <Button
- variant="primary"
- size="sm"
- onClick={() => setStep(current => Math.min(STEPS.length - 1, current + 1))}
- disabled={busy || !canContinue}
- >
- Continue
- </Button>
- ) : (
- <Button
- variant="primary"
- size="sm"
- onClick={() => void handleCreateContext()}
- disabled={!canSubmit}
- >
- {busy ? 'Creating…' : 'Create context'}
- </Button>
- )}
- </div>
- </CreateStepFlow>
- </CreateFlowPanel>
- </DashboardLayout>
- </AuthGate>
- )
-}
diff --git a/control-ui/app/contexts/page.tsx b/control-ui/app/contexts/page.tsx
deleted file mode 100644
index d71e2afe4..000000000
--- a/control-ui/app/contexts/page.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-'use client'
-
-import { useEffect, useState } from 'react'
-import { useRouter } from 'next/navigation'
-import { AuthGate } from '@components/AuthGate'
-import { useConfirmDialog } from '@components/ConfirmDialog'
-import { ContextTable } from '@components/ContextTable'
-import { DashboardLayout } from '@components/DashboardLayout'
-import { useToast } from '@components/Toast'
-import { CONTROL_ROUTES } from '@constants/routes'
-import { apiSend, getContexts, isSilentApiError } from '@lib/api'
-import type { ContextResource } from '@lib/api'
-
-type ContextRef = { name: string }
-
-export default function ContextsPage() {
- const router = useRouter()
- const [contexts, setContexts] = useState<ContextResource[]>([])
- const [loading, setLoading] = useState(true)
- const [error, setError] = useState('')
- const [deletingKey, setDeletingKey] = useState<string | null>(null)
- const { confirm, confirmDialog } = useConfirmDialog()
- const { showToast } = useToast()
-
- async function loadAll() {
- setLoading(true)
- setError('')
- try {
- const response = await getContexts()
- setContexts(response.items || [])
- } catch (nextError) {
- if (isSilentApiError(nextError)) return
- setError(nextError instanceof Error ? nextError.message : 'Failed to load contexts')
- } finally {
- setLoading(false)
- }
- }
-
- useEffect(() => {
- void loadAll()
- }, [])
-
- async function handleDeleteContext(context: ContextRef) {
- const shouldDelete = await confirm({
- title: 'Delete Context',
- message: `Delete context ${context.name}?`,
- confirmLabel: 'Delete',
- tone: 'danger',
- })
- if (!shouldDelete) return
-
- setDeletingKey(context.name)
- setError('')
- try {
- await apiSend('DELETE', `/api/v1/admin/contexts/${encodeURIComponent(context.name)}`)
- await loadAll()
- showToast(`Context ${context.name} deleted.`, { tone: 'success' })
- } catch (nextError) {
- if (isSilentApiError(nextError)) return
- setError(
- nextError instanceof Error ? nextError.message : `Failed to delete context ${context.name}`
- )
- } finally {
- setDeletingKey(null)
- }
- }
-
- return (
- <AuthGate>
- <DashboardLayout>
- {error ? <div className="cu-banner cu-banner--error">{error}</div> : null}
- <ContextTable
- items={contexts}
- onView={context => router.push(CONTROL_ROUTES.contexts.connectors(context.name))}
- onEdit={context => router.push(CONTROL_ROUTES.contexts.connectors(context.name))}
- onDelete={handleDeleteContext}
- deletingKey={deletingKey}
- onRefresh={loadAll}
- onCreate={() => router.push(CONTROL_ROUTES.contexts.new)}
- refreshing={loading}
- loading={loading}
- />
- {confirmDialog}
- </DashboardLayout>
- </AuthGate>
- )
-}
diff --git a/control-ui/components/ContextTable.tsx b/control-ui/components/ContextTable.tsx
deleted file mode 100644
index d1ed0edec..000000000
--- a/control-ui/components/ContextTable.tsx
+++ /dev/null
@@ -1,196 +0,0 @@
-'use client'
-
-import React, { useMemo, useState } from 'react'
-import { ContextResource } from '../lib/api'
-import { RowActionsMenu } from './RowActionsMenu'
-import { SectionSearchInput } from './SectionSearchInput'
-import { IconGroupWork } from './Sidebar/icons'
-import { SkeletonTableRows } from './SkeletonTableRows'
-import { TableHeaderRow } from './TableHeaderRow'
-import type { TableHeaderColumn } from './TableHeaderRow/types'
-import { TablePanelHeader } from './TablePanelHeader'
-import { IconRefresh } from './icons'
-
-type ContextRef = { name: string }
-
-const CONTEXT_COLUMNS: TableHeaderColumn[] = [
- { key: 'name', label: 'Context Name' },
- { key: 'servers', label: 'Connectors', width: '7rem' },
- { key: 'actions', label: 'Actions', width: '8rem', align: 'right' },
-]
-
-export function ContextTable({
- items,
- onView,
- onEdit,
- onDelete,
- deletingKey,
- onRefresh,
- onCreate,
- refreshing,
- loading,
-}: {
- items: ContextResource[]
- onView: (context: ContextRef) => void
- onEdit: (context: ContextRef) => void
- onDelete: (context: ContextRef) => Promise<void>
- deletingKey: string | null
- onRefresh: () => void
- onCreate: () => void
- refreshing: boolean
- loading?: boolean
-}) {
- const [searchQuery, setSearchQuery] = useState('')
- const rows = useMemo(
- () =>
- items.map(item => {
- const name = item.metadata?.name || 'unknown'
- // Visible name is the optional spec.displayName; fall back to the slug
- // (metadata.name) when it is absent OR blank-after-trim — a displayName
- // written out-of-band (e.g. kubectl) as '' or ' ' must not render a
- // blank label. Mirrors HostTable.tsx (`.trim() || name`).
- const displayName = (item.spec?.displayName ?? '').trim() || name
- const key = name
- const mcpServers = Array.isArray(item.spec?.mcpServers) ? item.spec?.mcpServers : []
- return { key, name, displayName, item, mcpServers }
- }),
- [items]
- )
- const normalizedSearch = searchQuery.trim().toLowerCase()
- const filteredRows = useMemo(() => {
- if (!normalizedSearch) return rows
- return rows.filter(({ name, displayName, item, mcpServers }) => {
- const description = String(item.spec?.description || '').trim()
- return [name, displayName, description, String(mcpServers.length), ...mcpServers.map(String)]
- .join(' ')
- .toLowerCase()
- .includes(normalizedSearch)
- })
- }, [normalizedSearch, rows])
-
- const isInitialLoad = loading && items.length === 0
-
- function openContext(name: string) {
- onView({ name })
- }
-
- function handleRowKeyDown(event: React.KeyboardEvent<HTMLTableRowElement>, name: string) {
- if (event.key === 'Enter' || event.key === ' ') {
- event.preventDefault()
- openContext(name)
- }
- }
-
- return (
- <div className="cu-card cu-card--viewport-fill" style={{ marginBottom: '1.25rem' }}>
- <TablePanelHeader
- title={
- <>
- <IconGroupWork />
- {isInitialLoad ? 'Contexts' : `Contexts (${filteredRows.length})`}
- </>
- }
- subtitle="Group connectors into reusable access scopes."
- actions={
- <>
- <SectionSearchInput
- value={searchQuery}
- onChange={setSearchQuery}
- placeholder="Search contexts"
- ariaLabel="Search contexts"
- disabled={isInitialLoad}
- />
- <button
- type="button"
- className="cu-btn cu-btn--icon cu-btn--toolbar"
- onClick={() => void onRefresh()}
- disabled={refreshing || isInitialLoad}
- aria-label={refreshing ? 'Refreshing…' : 'Reload contexts'}
- >
- <IconRefresh className={refreshing ? 'cu-spin' : undefined} width={18} height={18} />
- </button>
- <button
- type="button"
- className="cu-btn cu-btn--primary cu-btn--sm"
- onClick={onCreate}
- disabled={isInitialLoad}
- >
- Create context
- </button>
- </>
- }
- />
- {isInitialLoad ? (
- <div className="cu-table-wrap">
- <table className="cu-table cu-table--header-band">
- <thead>
- <TableHeaderRow columns={CONTEXT_COLUMNS} />
- </thead>
- <tbody>
- <SkeletonTableRows columns={CONTEXT_COLUMNS.length} rows={4} />
- </tbody>
- </table>
- </div>
- ) : filteredRows.length === 0 ? (
- <div className="cu-empty">
- {normalizedSearch ? 'No contexts match this search.' : 'No contexts found.'}
- </div>
- ) : (
- <div className="cu-table-wrap">
- <table className="cu-table cu-table--header-band">
- <thead>
- <TableHeaderRow columns={CONTEXT_COLUMNS} />
- </thead>
- <tbody>
- {filteredRows.map(({ key, name, displayName, item, mcpServers }) => (
- <tr
- key={key}
- className="cu-table__row cu-table__row--clickable"
- onClick={() => openContext(name)}
- onKeyDown={event => handleRowKeyDown(event, name)}
- tabIndex={0}
- aria-label={`Open context ${name}`}
- >
- <td>
- <span className="cu-expandable-row__name">{displayName}</span>
- {displayName !== name ? (
- <div className="cu-table__cell-subtle">{name}</div>
- ) : null}
- <div className="cu-registry-description" title={item.spec?.description || '—'}>
- {item.spec?.description || '—'}
- </div>
- </td>
- <td style={{ color: 'var(--cu-text-muted)', fontVariantNumeric: 'tabular-nums' }}>
- {mcpServers.length}
- </td>
- <td style={{ textAlign: 'right' }}>
- <div className="cu-table-actions">
- <RowActionsMenu
- ariaLabel={`Actions for context ${name}`}
- horizontalTrigger
- actions={[
- {
- key: 'edit',
- label: 'Edit',
- onClick: () => onEdit({ name }),
- },
- {
- key: 'delete',
- label: deletingKey === key ? 'Deleting…' : 'Delete',
- danger: true,
- disabled: deletingKey === key,
- onClick: () => void onDelete({ name }),
- },
- ]}
- />
- </div>
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- )}
- </div>
- )
-}
diff --git a/control-ui/components/DashboardLayout.tsx b/control-ui/components/DashboardLayout.tsx
index 89fa9335c..1b577b882 100644
--- a/control-ui/components/DashboardLayout.tsx
+++ b/control-ui/components/DashboardLayout.tsx
@@ -69,9 +69,6 @@ function PersistentDashboardFrame({ children }: Pick<DashboardLayoutProps, 'chil
if (isControlRouteSection(pathname, CONTROL_ROUTES.agents.root)) {
return 'hosts'
}
- if (isControlRouteSection(pathname, CONTROL_ROUTES.contexts.root)) {
- return 'contexts'
- }
if (isControlRouteSection(pathname, CONTROL_ROUTES.usersAndTeams.base)) {
return 'profile-admin'
}
diff --git a/control-ui/components/Sidebar/constants.tsx b/control-ui/components/Sidebar/constants.tsx
index 95b26aa9d..b19dc5444 100644
--- a/control-ui/components/Sidebar/constants.tsx
+++ b/control-ui/components/Sidebar/constants.tsx
@@ -5,7 +5,6 @@ import {
IconBroadcast,
IconCable,
IconFolder,
- IconGroupWork,
IconInfrastructureTrace,
IconKey,
IconLlmPrices,
@@ -32,7 +31,6 @@ export const SIDEBAR_TABS: Record<SidebarTab, SidebarItem> = {
href: CONTROL_ROUTES.connectors.root,
icon: <IconCable />,
},
- contexts: { label: 'Contexts', href: CONTROL_ROUTES.contexts.root, icon: <IconGroupWork /> },
guardrails: {
label: 'Installed Guardrails',
href: CONTROL_ROUTES.guardrails.root,
@@ -138,7 +136,6 @@ export const SIDEBAR_TABS: Record<SidebarTab, SidebarItem> = {
export const SIDEBAR_TAB_ORDER: SidebarTab[] = [
'profile-admin',
'hosts',
- 'contexts',
'registry-catalog',
'mcp-servers',
'workflow-recipes',
diff --git a/control-ui/components/Sidebar/types.ts b/control-ui/components/Sidebar/types.ts
index 1bbae3048..3b7268572 100644
--- a/control-ui/components/Sidebar/types.ts
+++ b/control-ui/components/Sidebar/types.ts
@@ -2,7 +2,6 @@ import type { ReactNode } from 'react'
export type SidebarTab =
| 'hosts'
- | 'contexts'
| 'guardrails'
| 'mcp-servers'
| 'directories'
diff --git a/control-ui/components/__tests__/AuthContext.test.tsx b/control-ui/components/__tests__/AuthContext.test.tsx
index d447fdd1f..cadca4949 100644
--- a/control-ui/components/__tests__/AuthContext.test.tsx
+++ b/control-ui/components/__tests__/AuthContext.test.tsx
@@ -370,7 +370,7 @@ describe('AuthProvider session expiry handling', () => {
})
it('clears legacy storage without a toast when no cookie session exists on mount', async () => {
- window.history.pushState({}, '', '/contexts/context1')
+ window.history.pushState({}, '', '/agents/context1')
window.localStorage.setItem('controlUiAdminToken', 'expired-token')
const fetchMock = vi.fn().mockResolvedValue(response(401, { error: 'expired' }))
vi.stubGlobal('fetch', fetchMock)
diff --git a/control-ui/components/__tests__/ContextTable.test.tsx b/control-ui/components/__tests__/ContextTable.test.tsx
deleted file mode 100644
index dc83b36e5..000000000
--- a/control-ui/components/__tests__/ContextTable.test.tsx
+++ /dev/null
@@ -1,139 +0,0 @@
-import { describe, expect, it, vi } from 'vitest'
-import { fireEvent, render, screen } from '@testing-library/react'
-import { buildContextResource } from '../../test/fixtures/contextResource'
-import { ContextTable } from '../ContextTable'
-
-const contexts = [
- buildContextResource({
- metadata: { name: 'business' },
- spec: { description: 'Business context', mcpServers: ['server-a', 'server-b'] },
- }),
-]
-
-describe('ContextTable', () => {
- it('opens a context from the whole row', () => {
- const onView = vi.fn()
- render(
- <ContextTable
- items={contexts}
- onView={onView}
- onEdit={vi.fn()}
- onDelete={vi.fn().mockResolvedValue(undefined)}
- deletingKey={null}
- onRefresh={vi.fn()}
- onCreate={vi.fn()}
- refreshing={false}
- />
- )
-
- const row = screen.getByLabelText('Open context business')
-
- fireEvent.click(row)
- expect(onView).toHaveBeenCalledWith({ name: 'business' })
-
- onView.mockClear()
- fireEvent.keyDown(row, { key: 'Enter' })
- expect(onView).toHaveBeenCalledWith({ name: 'business' })
- })
-
- it('stacks a non-link context name and its description in one cell', () => {
- const { container } = render(
- <ContextTable
- items={contexts}
- onView={vi.fn()}
- onEdit={vi.fn()}
- onDelete={vi.fn().mockResolvedValue(undefined)}
- deletingKey={null}
- onRefresh={vi.fn()}
- onCreate={vi.fn()}
- refreshing={false}
- />
- )
-
- expect(screen.getByText('business')).toHaveClass('cu-expandable-row__name')
- expect(screen.getByText('Business context')).toHaveClass('cu-registry-description')
- expect(container.querySelectorAll('thead th')).toHaveLength(3)
- expect(screen.queryByRole('button', { name: 'business' })).not.toBeInTheDocument()
- })
-
- it('renders the identifier (metadata.name) when displayName is blank/whitespace (R4-M1 / R1-L4)', () => {
- // A displayName written out-of-band as whitespace (' ') must fall back to
- // the identifier, not render a blank label. dev restructured the cell to a
- // non-link span (cu-expandable-row__name), so assert the observable rendered
- // name text (T4), not a button role and not the intermediate spec value.
- render(
- <ContextTable
- items={[
- buildContextResource({
- metadata: { name: 'business' },
- spec: { displayName: ' ', description: '', mcpServers: [] },
- }),
- ]}
- onView={vi.fn()}
- onEdit={vi.fn()}
- onDelete={vi.fn().mockResolvedValue(undefined)}
- deletingKey={null}
- onRefresh={vi.fn()}
- onCreate={vi.fn()}
- refreshing={false}
- />
- )
-
- // The visible name span renders the identifier, not a blank/whitespace label.
- expect(screen.getByText('business')).toHaveClass('cu-expandable-row__name')
- })
-
- it('does not open a context from the row actions kebab', () => {
- const onView = vi.fn()
- const onEdit = vi.fn()
- const onDelete = vi.fn().mockResolvedValue(undefined)
- render(
- <ContextTable
- items={contexts}
- onView={onView}
- onEdit={onEdit}
- onDelete={onDelete}
- deletingKey={null}
- onRefresh={vi.fn()}
- onCreate={vi.fn()}
- refreshing={false}
- />
- )
-
- fireEvent.click(screen.getByRole('button', { name: 'Actions for context business' }))
-
- fireEvent.click(screen.getByRole('menuitem', { name: 'Edit' }))
- expect(onEdit).toHaveBeenCalledWith({ name: 'business' })
- expect(onView).not.toHaveBeenCalled()
-
- fireEvent.click(screen.getByRole('button', { name: 'Actions for context business' }))
- fireEvent.click(screen.getByRole('menuitem', { name: 'Delete' }))
- expect(onDelete).toHaveBeenCalledWith({ name: 'business' })
- expect(onView).not.toHaveBeenCalled()
- })
-
- it('disables only the Delete item while deleting and renames it to Deleting…', () => {
- const onEdit = vi.fn()
- const onDelete = vi.fn().mockResolvedValue(undefined)
- render(
- <ContextTable
- items={contexts}
- onView={vi.fn()}
- onEdit={onEdit}
- onDelete={onDelete}
- deletingKey="business"
- onRefresh={vi.fn()}
- onCreate={vi.fn()}
- refreshing={false}
- />
- )
-
- fireEvent.click(screen.getByRole('button', { name: 'Actions for context business' }))
-
- const editItem = screen.getByRole('menuitem', { name: 'Edit' })
- const deletingItem = screen.getByRole('menuitem', { name: 'Deleting…' })
-
- expect(editItem).not.toBeDisabled()
- expect(deletingItem).toBeDisabled()
- })
-})
diff --git a/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx b/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx
index feb104582..e74cc394d 100644
--- a/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx
+++ b/control-ui/components/__tests__/HostDetailsPage.connectors.test.tsx
@@ -147,6 +147,57 @@ describe('HostDetailsPage connectors', () => {
expect(await screen.findByText('mcp-new')).toBeInTheDocument()
})
+ // Re-homed from app/contexts/__tests__/ContextDetail.spec-preserve.test.tsx
+ // (deleted with the Contexts section): every context PUT from the surviving
+ // agent-side writer must preserve un-modeled spec fields (e.g. spec.gfs
+ // written by other controllers) and carry the loaded resourceVersion.
+ it('preserves unknown spec fields on connector updates through the agent writer', async () => {
+ const contextWithGfs = {
+ ...baseContext,
+ spec: {
+ ...baseContext.spec,
+ gfs: [{ name: 'team-docs', readOnly: true }],
+ },
+ } as unknown as typeof baseContext
+ ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
+ host: {
+ metadata: { name: activeHostName, resourceVersion: 'rv-host-1' },
+ spec: {
+ contextRef: contextName,
+ host: 'Foo',
+ model: { name: 'gpt-5.4-mini', provider: 'openai' },
+ },
+ },
+ contexts: [contextWithGfs],
+ secrets: [],
+ users: [],
+ teams: [],
+ agentUsers: [],
+ agentTeams: [],
+ })
+
+ renderPage()
+
+ const actionsButton = await screen.findByRole('button', {
+ name: 'Actions for connector mcp-existing',
+ })
+ fireEvent.click(actionsButton)
+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove connector' }))
+ fireEvent.click(await screen.findByRole('button', { name: 'Remove connector' }))
+
+ await waitFor(() => expect(api.updateContext).toHaveBeenCalledTimes(1))
+ expect(api.updateContext).toHaveBeenCalledWith(
+ contextName,
+ expect.objectContaining({
+ metadata: { resourceVersion: 'rv-context-1' },
+ spec: expect.objectContaining({
+ gfs: [{ name: 'team-docs', readOnly: true }],
+ mcpServers: [],
+ }),
+ })
+ )
+ })
+
it('confirms connector removal and updates the private context membership', async () => {
renderPage()
diff --git a/control-ui/components/__tests__/Sidebar.test.tsx b/control-ui/components/__tests__/Sidebar.test.tsx
index 0a6a6fd07..db24a8fe1 100644
--- a/control-ui/components/__tests__/Sidebar.test.tsx
+++ b/control-ui/components/__tests__/Sidebar.test.tsx
@@ -64,7 +64,6 @@ describe('Sidebar publisher gating', () => {
expect(labels).toEqual([
'Users & Teams',
'Agents',
- 'Contexts',
'Marketplace',
'Installed Connectors',
'Installed Plugins',
diff --git a/control-ui/e2e/qa-recorder-connector-edit.spec.ts b/control-ui/e2e/qa-recorder-connector-edit.spec.ts
index e30a205be..3963094ce 100644
--- a/control-ui/e2e/qa-recorder-connector-edit.spec.ts
+++ b/control-ui/e2e/qa-recorder-connector-edit.spec.ts
@@ -1,9 +1,11 @@
// control-ui/e2e/qa-recorder-connector-edit.spec.ts
//
-// MUTATING journey: creates a context + stdio discovery connector (reusing the
-// spec-2 creation flow inline), then edits the connector to add external CIDR
-// egress. Guarded by QA_RECORDER_CONFIRM_MUTATIONS; connector then context are
-// deleted via the Control API in a finally.
+// MUTATING journey: stages a context through the Control API, creates a stdio
+// discovery connector through the create-connector wizard (which also
+// provisions the connector's own private access scope), then edits the
+// connector to add external CIDR egress. Guarded by
+// QA_RECORDER_CONFIRM_MUTATIONS; the connector and both contexts are deleted
+// via the Control API in a finally.
import { type Page, expect, test } from '@playwright/test'
import {
CONTROL_API_URL,
@@ -30,35 +32,21 @@ async function fieldSelect(page: Page, fieldLabelText: string, value: string): P
await field.locator('select').selectOption(value)
}
+// The /contexts UI is gone; stage the context out-of-band through the Control
+// API (same pattern as the rotation test below).
async function createEmptyContext(page: Page, contextName: string): Promise<void> {
- await page.getByRole('link', { name: 'Contexts', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts\/new$/, { timeout: 20_000 })
- await page.getByPlaceholder('context1').fill(contextName)
- await page
- .getByPlaceholder('Human-readable context description')
- .fill('QA recorder temporary context')
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
- await expect(
- page
- .getByText('No connectors found.', { exact: true })
- .or(page.getByPlaceholder('Search connectors...'))
- ).toBeVisible({ timeout: 20_000 })
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
- await expect(page).toHaveURL(new RegExp(`/contexts/${contextName}$`), { timeout: 20_000 })
- await expect(
- page.getByText('Review details, manage connectors, agents, teams, and members.', {
- exact: true,
- })
- ).toBeVisible({ timeout: 20_000 })
+ const res = await api(page.request, 'POST', '/api/v1/admin/contexts', {
+ metadata: { name: contextName },
+ spec: {
+ contextId: contextName,
+ description: 'QA recorder temporary context',
+ mcpServers: [],
+ },
+ })
+ expect(res.status, `create context: ${JSON.stringify(res.data)}`).toBeLessThan(300)
}
-async function createDiscoveryConnector(
- page: Page,
- connectorName: string,
- contextName: string
-): Promise<void> {
+async function createDiscoveryConnector(page: Page, connectorName: string): Promise<void> {
await page.getByRole('link', { name: 'Installed Connectors', exact: true }).click()
await expect(page).toHaveURL(/\/connectors$/, { timeout: 20_000 })
await page.getByRole('button', { name: 'Create Connector', exact: true }).click()
@@ -72,28 +60,24 @@ async function createDiscoveryConnector(
.getByPlaceholder('Optional description of this connector')
.fill('QA recorder discovery-only connector')
- const contextDropdown = page.locator('.cu-selection-dropdown__button')
- await expect(contextDropdown).toBeEnabled({ timeout: 20_000 })
- await contextDropdown.click()
- await expect(page.getByPlaceholder('Search contexts...')).toBeVisible({ timeout: 20_000 })
- const contextOption = page.getByRole('option', { name: contextName, exact: true })
- await expect(contextOption).toBeVisible({ timeout: 20_000 })
- await contextOption.click()
-
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
-
+ // Runtime settings now live behind the collapsible Advanced options on the
+ // Connector step.
+ await page.getByText('Advanced options', { exact: true }).click()
await fieldSelect(page, 'Transport Type', 'stdio')
await expect(page.locator('input[type="number"]')).toHaveCount(0)
await fieldSelect(page, 'Managed', 'false')
await page.getByRole('button', { name: 'Continue', exact: true }).click()
- await expect(page.getByText('External Egress', { exact: true })).toBeVisible({ timeout: 20_000 })
+ // Access step: the agents multi-select is optional — skip it.
+ await expect(page.getByRole('heading', { name: 'Agent access', exact: true })).toBeVisible({
+ timeout: 20_000,
+ })
await page.getByRole('button', { name: 'Continue', exact: true }).click()
- await expect(
- page.getByRole('checkbox', { name: 'Use Kubernetes Secret for credentials', exact: true })
- ).not.toBeChecked()
+ // Secrets step: explicitly pick the keyless credential mode — the wizard
+ // keeps Create connector disabled until a credential choice is made.
+ await page.getByText('No credentials required', { exact: true }).click()
await page.getByRole('button', { name: 'Create connector', exact: true }).click()
await expect(page.getByText('Connector created successfully.', { exact: true })).toBeVisible({
@@ -116,37 +100,52 @@ test.describe('optional QA recorder: Control UI connector edit', () => {
const credentials = adminCredentials()
const contextName = uniqueE2EName('qa-recorder-context')
const connectorName = uniqueE2EName('qa-recorder-connector')
+ let connectorContextName = ''
try {
await loginThroughUi(page, credentials)
await createEmptyContext(page, contextName)
- await createDiscoveryConnector(page, connectorName, contextName)
+ await createDiscoveryConnector(page, connectorName)
+
+ // The wizard provisions the connector's private access scope out of
+ // band; capture its name so the finally can tear it down too.
+ const createdRes = await api(
+ page.request,
+ 'GET',
+ `/api/v1/admin/mcp-servers/${encodeURIComponent(connectorName)}`
+ )
+ expect(createdRes.status, `read connector: ${JSON.stringify(createdRes.data)}`).toBe(200)
+ connectorContextName = String(
+ (createdRes.data.spec as { contextRef?: string } | undefined)?.contextRef || ''
+ )
+ expect(connectorContextName).toMatch(new RegExp(`^${connectorName}-[0-9]{5}$`))
await page.goto(`${CONTROL_UI_URL}/connectors/${encodeURIComponent(connectorName)}/edit`)
await expect(
page.getByRole('heading', { name: `Edit Connector: ${connectorName}`, exact: true })
).toBeVisible({ timeout: 20_000 })
- // Context is a read-only final tab. It mirrors the selected context's
- // Users, Teams, and Agents access preview without offering a mutation.
- await page.getByRole('tab', { name: 'Context', exact: true }).click()
+ // Access is a read-only final tab. It mirrors the agents, teams, and
+ // users that can already reach this connector without offering a
+ // mutation.
+ await page.getByRole('tab', { name: 'Access', exact: true }).click()
await expect(page).toHaveURL(
- new RegExp(`/connectors/${encodeURIComponent(connectorName)}/edit/context$`)
+ new RegExp(`/connectors/${encodeURIComponent(connectorName)}/edit/access$`)
)
- await expect(page.getByRole('heading', { name: 'Context access', exact: true })).toBeVisible({
+ await expect(page.getByRole('heading', { name: 'Agent access', exact: true })).toBeVisible({
timeout: 20_000,
})
- await expect(page.getByLabel('Connector context').getByText(contextName)).toBeVisible()
- await expect(page.getByLabel('Context access')).toBeVisible()
+ await expect(page.getByLabel('Agent access')).toBeVisible()
await page.getByRole('tab', { name: 'External Egress', exact: true }).click()
- // Image and Context are rendered as static read-only text (not editable inputs).
+ // Image and access scopes are rendered as static read-only text (not
+ // editable inputs).
const meta = page.locator('.cu-connector-edit-meta')
await expect(meta).toBeVisible({ timeout: 20_000 })
await expect(meta.getByText('qa-recorder/example:dev')).toBeVisible()
- await expect(meta.getByText(contextName)).toBeVisible()
+ await expect(meta.getByText(connectorContextName)).toBeVisible()
// External Egress: switch to exact-CIDR mode and add one public CIDR + port.
// 8.8.8.8/32 is a valid public target; the model rejects private/doc ranges.
@@ -174,6 +173,13 @@ test.describe('optional QA recorder: Control UI connector edit', () => {
'DELETE',
`/api/v1/admin/mcp-servers/${encodeURIComponent(connectorName)}`
)
+ if (connectorContextName) {
+ await api(
+ page.request,
+ 'DELETE',
+ `/api/v1/admin/contexts/${encodeURIComponent(connectorContextName)}`
+ )
+ }
await api(page.request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(contextName)}`)
}
})
diff --git a/control-ui/e2e/qa-recorder-connectors.spec.ts b/control-ui/e2e/qa-recorder-connectors.spec.ts
index e65f3a80c..dd8b60ab3 100644
--- a/control-ui/e2e/qa-recorder-connectors.spec.ts
+++ b/control-ui/e2e/qa-recorder-connectors.spec.ts
@@ -34,7 +34,7 @@ test.describe('optional QA recorder: Control UI connectors journey', () => {
// Shell proof: the TablePanelHeader subtitle is unique and renders regardless of
// whether the inventory is loading, populated, or empty.
await expect(
- page.getByText('Browse connector deployments and context bindings.', { exact: true })
+ page.getByText('Browse connector deployments and agent access.', { exact: true })
).toBeVisible({ timeout: 20_000 })
// Panel title is "Connectors" while loading/empty, or "Connectors (N)" once populated.
diff --git a/control-ui/e2e/qa-recorder-context-connector-budget.spec.ts b/control-ui/e2e/qa-recorder-context-connector-budget.spec.ts
deleted file mode 100644
index 7795d877a..000000000
--- a/control-ui/e2e/qa-recorder-context-connector-budget.spec.ts
+++ /dev/null
@@ -1,160 +0,0 @@
-// control-ui/e2e/qa-recorder-context-connector-budget.spec.ts
-//
-// Mutating QA recorder combo: context + discovery connector (bound to the
-// context) + global token budget + verify both land. Creates and tears down
-// every resource. Requires QA_RECORDER_CONFIRM_MUTATIONS=1 in .env.qa-recorder.
-import { expect, test } from '@playwright/test'
-import {
- CONTROL_API_URL,
- CONTROL_UI_URL,
- adminCredentials,
- api,
- assertAllowedTarget,
- loginThroughUi,
- requireRecorderConfirm,
- screenshotAndLog,
- uniqueE2EName,
-} from './qa-recorder-helpers'
-
-type BudgetRow = { id?: string; name?: string }
-
-async function waitForBudgetId(
- request: import('@playwright/test').APIRequestContext,
- name: string
-): Promise<string> {
- for (let attempt = 0; attempt < 20; attempt += 1) {
- const { status, data } = await api<{ rows?: BudgetRow[] }>(
- request,
- 'GET',
- '/api/v1/admin/budgets'
- )
- if (status === 200) {
- const found = (data.rows ?? []).find(row => row.name === name)
- if (found?.id) return found.id
- }
- await new Promise(resolve => setTimeout(resolve, 500))
- }
- throw new Error(`Created budget "${name}" did not become visible through Control API.`)
-}
-
-test.describe('optional QA recorder: Control UI context connector budget combo', () => {
- test('records the context + connector + global budget combo', async ({ page }, testInfo) => {
- requireRecorderConfirm(
- 'QA_RECORDER_CONFIRM_MUTATIONS',
- 'This journey creates and deletes a context, a connector, and a token budget.'
- )
- assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
- assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
-
- const credentials = adminCredentials()
- const contextName = uniqueE2EName('qa-recorder-ctx')
- const connectorName = uniqueE2EName('qa-recorder-connector')
- const budgetName = uniqueE2EName('qa-recorder-global-budget')
- let budgetId = ''
-
- try {
- await loginThroughUi(page, credentials)
-
- // step 1: create a context (name only).
- await page.goto(`${CONTROL_UI_URL}/contexts/new`)
- await expect(page).toHaveURL(/\/contexts\/new$/, { timeout: 20_000 })
- await page.getByLabel('Context name').fill(contextName)
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
- await expect(page).toHaveURL(new RegExp(`/contexts/${contextName}$`), { timeout: 20_000 })
-
- // step 2: register a discovery connector bound to the context (stdio,
- // not managed, no secret).
- await page.goto(`${CONTROL_UI_URL}/connectors/new`)
- await expect(page).toHaveURL(/\/connectors\/new$/, { timeout: 20_000 })
- await expect(
- page.getByRole('heading', { name: 'Create connector', exact: true })
- ).toBeVisible({ timeout: 20_000 })
- await page.getByPlaceholder('my-mcp-server', { exact: true }).fill(connectorName)
- await page
- .getByPlaceholder('us-central1-docker.pkg.dev/my-project/repo/mcp-server:latest', {
- exact: true,
- })
- .fill('qa-recorder/example:dev')
- const contextDropdown = page.locator('.cu-selection-dropdown__button')
- await expect(contextDropdown).toBeVisible({ timeout: 10_000 })
- await contextDropdown.click()
- await page.getByPlaceholder('Search contexts...').fill(contextName)
- const contextOption = page.getByRole('option', { name: contextName, exact: true })
- await expect(contextOption).toBeVisible({ timeout: 10_000 })
- await contextOption.click()
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
- // Runtime: stdio transport + discovery only (Managed = No).
- await page
- .locator('.cu-field')
- .filter({ hasText: 'Transport Type' })
- .locator('select')
- .selectOption('stdio')
- await page
- .locator('.cu-field')
- .filter({ hasText: /^Managed$/ })
- .locator('select')
- .selectOption('false')
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
- // Network egress: leave empty, continue.
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
- // Secrets: leave unchecked, create the connector.
- await page.getByRole('button', { name: 'Create connector', exact: true }).click()
- await expect(page).toHaveURL(/\/connectors\/?$/, { timeout: 20_000 })
-
- // step 3: verify the connector appears on the context detail Connectors tab.
- await page.goto(`${CONTROL_UI_URL}/contexts/${encodeURIComponent(contextName)}/connectors`)
- await expect(page).toHaveURL(/\/contexts\/.+\/connectors$/, { timeout: 20_000 })
- await expect(
- page.getByText('Review details, manage connectors, agents, teams, and members.', {
- exact: true,
- })
- ).toBeVisible({ timeout: 20_000 })
- await expect(page.getByText(connectorName, { exact: true })).toBeVisible({ timeout: 15_000 })
-
- // step 4: create a global token budget (no scope).
- await page.goto(`${CONTROL_UI_URL}/cost-and-usage/token-budgets/new`)
- await expect(page).toHaveURL(/\/cost-and-usage\/token-budgets\/new$/, { timeout: 20_000 })
- await page.locator('#budget-name').fill(budgetName)
- await page.locator('#budget-limit').fill('10')
- await page.getByRole('button', { name: 'Create budget', exact: true }).click()
- await expect(page).toHaveURL(/\/cost-and-usage\/token-budgets$/, { timeout: 20_000 })
- budgetId = await waitForBudgetId(page.request, budgetName)
-
- // step 5: verify the budget lists on the token budgets page.
- await expect(
- page.getByText(
- 'Spend caps per dimension, shown against live usage. P0c runs in observation mode (warn).',
- { exact: true }
- )
- ).toBeVisible({ timeout: 20_000 })
- await expect(page.getByText(budgetName, { exact: true })).toBeVisible({ timeout: 15_000 })
-
- await screenshotAndLog(page, testInfo, 'control-ui-context-connector-budget')
- } finally {
- const request = page.request
- // Reverse-order cleanup: budget → connector → context (best-effort each).
- if (budgetId) {
- try {
- await api(request, 'DELETE', `/api/v1/admin/budgets/${encodeURIComponent(budgetId)}`)
- } catch {
- // best-effort
- }
- }
- try {
- await api(
- request,
- 'DELETE',
- `/api/v1/admin/mcp-servers/${encodeURIComponent(connectorName)}`
- )
- } catch {
- // best-effort
- }
- try {
- await api(request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(contextName)}`)
- } catch {
- // best-effort
- }
- }
- })
-})
diff --git a/control-ui/e2e/qa-recorder-context-connector.spec.ts b/control-ui/e2e/qa-recorder-context-connector.spec.ts
deleted file mode 100644
index ce022d725..000000000
--- a/control-ui/e2e/qa-recorder-context-connector.spec.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-// control-ui/e2e/qa-recorder-context-connector.spec.ts
-//
-// MUTATING journey: creates a context plus a stdio discovery-only connector and
-// attaches the connector to the context. Self-contained (no external creds).
-// Guarded by QA_RECORDER_CONFIRM_MUTATIONS; connector then context are deleted
-// via the Control API in a finally.
-import { type Page, expect, test } from '@playwright/test'
-import {
- CONTROL_API_URL,
- CONTROL_UI_URL,
- adminCredentials,
- api,
- assertAllowedTarget,
- loginThroughUi,
- requireRecorderConfirm,
- screenshotAndLog,
- uniqueE2EName,
-} from './qa-recorder-helpers'
-
-// The connector-form selects are not label-associated (no htmlFor/id), so scope
-// to the wrapping `.cu-field` by its visible label text and drive its <select>.
-async function fieldSelect(page: Page, fieldLabelText: string, value: string): Promise<void> {
- const field = page.locator('.cu-field', { hasText: fieldLabelText }).first()
- await field.locator('select').selectOption(value)
-}
-
-async function createEmptyContext(page: Page, contextName: string): Promise<void> {
- await page.getByRole('link', { name: 'Contexts', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts\/new$/, { timeout: 20_000 })
- await page.getByPlaceholder('context1').fill(contextName)
- await page
- .getByPlaceholder('Human-readable context description')
- .fill('QA recorder temporary context')
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
- await expect(
- page
- .getByText('No connectors found.', { exact: true })
- .or(page.getByPlaceholder('Search connectors...'))
- ).toBeVisible({ timeout: 20_000 })
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
- await expect(page).toHaveURL(new RegExp(`/contexts/${contextName}$`), { timeout: 20_000 })
- await expect(
- page.getByText('Review details, manage connectors, agents, teams, and members.', {
- exact: true,
- })
- ).toBeVisible({ timeout: 20_000 })
-}
-
-async function createDiscoveryConnector(
- page: Page,
- connectorName: string,
- contextName: string
-): Promise<void> {
- await page.getByRole('link', { name: 'Installed Connectors', exact: true }).click()
- await expect(page).toHaveURL(/\/connectors$/, { timeout: 20_000 })
- await page.getByRole('button', { name: 'Create Connector', exact: true }).click()
- await expect(page).toHaveURL(/\/connectors\/new$/, { timeout: 20_000 })
-
- // Step Connector.
- await page.getByPlaceholder('my-mcp-server').fill(connectorName)
- await page
- .getByPlaceholder('us-central1-docker.pkg.dev/my-project/repo/mcp-server:latest')
- .fill('qa-recorder/example:dev')
- await page
- .getByPlaceholder('Optional description of this connector')
- .fill('QA recorder discovery-only connector')
-
- // Context single-select is disabled while contexts load; wait, then pick ours.
- const contextDropdown = page.locator('.cu-selection-dropdown__button')
- await expect(contextDropdown).toBeEnabled({ timeout: 20_000 })
- await contextDropdown.click()
- await expect(page.getByPlaceholder('Search contexts...')).toBeVisible({ timeout: 20_000 })
- const contextOption = page.getByRole('option', { name: contextName, exact: true })
- await expect(contextOption).toBeVisible({ timeout: 20_000 })
- await contextOption.click()
-
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
-
- // Step Runtime: stdio hides the Port field; discovery-only means Not managed.
- await fieldSelect(page, 'Transport Type', 'stdio')
- await expect(page.locator('input[type="number"]')).toHaveCount(0)
- await fieldSelect(page, 'Managed', 'false')
-
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
-
- // Step Network: EgressEditor renders closed-by-default; leave egress empty.
- await expect(page.getByText('External Egress', { exact: true })).toBeVisible({ timeout: 20_000 })
- await expect(page.getByText('Egress mode', { exact: true })).toBeVisible({ timeout: 20_000 })
-
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
-
- // Step Secrets: envSecret stays off for this discovery connector.
- await expect(
- page.getByRole('checkbox', { name: 'Use Kubernetes Secret for credentials', exact: true })
- ).not.toBeChecked()
-
- await page.getByRole('button', { name: 'Create connector', exact: true }).click()
- await expect(page.getByText('Connector created successfully.', { exact: true })).toBeVisible({
- timeout: 20_000,
- })
- await expect(page).toHaveURL(/\/connectors$/, { timeout: 20_000 })
-}
-
-test.describe('optional QA recorder: Control UI context and connector', () => {
- test('records creating a context plus a stdio discovery connector and attaching it', async ({
- page,
- }, testInfo) => {
- requireRecorderConfirm(
- 'QA_RECORDER_CONFIRM_MUTATIONS',
- 'This journey creates and deletes local context and connector resources.'
- )
- assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
- assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
-
- const credentials = adminCredentials()
- const contextName = uniqueE2EName('qa-recorder-context')
- const connectorName = uniqueE2EName('qa-recorder-connector')
-
- try {
- await loginThroughUi(page, credentials)
-
- await createEmptyContext(page, contextName)
- await createDiscoveryConnector(page, connectorName, contextName)
-
- // The create flow auto-attaches the connector; verify it on the context's
- // Connectors tab.
- await page.getByRole('link', { name: 'Contexts', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
- await page.getByRole('row', { name: `Open context ${contextName}`, exact: true }).click()
- await expect(page).toHaveURL(new RegExp(`/contexts/${contextName}/connectors$`), {
- timeout: 20_000,
- })
- await expect(page.getByRole('row').filter({ hasText: connectorName })).toBeVisible({
- timeout: 20_000,
- })
-
- await screenshotAndLog(page, testInfo, 'control-ui-context-connector')
- } finally {
- await api(
- page.request,
- 'DELETE',
- `/api/v1/admin/mcp-servers/${encodeURIComponent(connectorName)}`
- )
- await api(page.request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(contextName)}`)
- }
- })
-})
diff --git a/control-ui/e2e/qa-recorder-context-create.spec.ts b/control-ui/e2e/qa-recorder-context-create.spec.ts
deleted file mode 100644
index 771cdcc6a..000000000
--- a/control-ui/e2e/qa-recorder-context-create.spec.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-// control-ui/e2e/qa-recorder-context-create.spec.ts
-//
-// MUTATING journey: creates a context with an empty connector allowlist, then
-// tours every context-detail tab. Guarded by QA_RECORDER_CONFIRM_MUTATIONS and
-// cleaned up via the Control API (`/api/v1/admin/contexts/<name>`) in a finally.
-import { expect, test } from '@playwright/test'
-import {
- CONTROL_API_URL,
- CONTROL_UI_URL,
- adminCredentials,
- api,
- assertAllowedTarget,
- loginThroughUi,
- requireRecorderConfirm,
- screenshotAndLog,
- uniqueE2EName,
-} from './qa-recorder-helpers'
-
-test.describe('optional QA recorder: Control UI context create', () => {
- test('records context creation with an empty allowlist and a full detail tab tour', async ({
- page,
- }, testInfo) => {
- requireRecorderConfirm(
- 'QA_RECORDER_CONFIRM_MUTATIONS',
- 'This journey creates and deletes a local context resource.'
- )
- assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
- assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
-
- const credentials = adminCredentials()
- const name = uniqueE2EName('qa-recorder-context')
- try {
- await loginThroughUi(page, credentials)
-
- await page.getByRole('link', { name: 'Contexts', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
-
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts\/new$/, { timeout: 20_000 })
- await expect(page.getByRole('heading', { name: 'Create context', exact: true })).toBeVisible({
- timeout: 20_000,
- })
- await expect(
- page.getByText('Define a new context and attach connectors.', { exact: true })
- ).toBeVisible({ timeout: 20_000 })
-
- // Step Context: identity.
- await page.getByPlaceholder('context1').fill(name)
- await page
- .getByPlaceholder('Human-readable context description')
- .fill('QA recorder temporary context')
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
-
- // Step Connectors: the multi-select renders when connectors exist, otherwise
- // the empty hint. Either is valid for an empty allowlist; leave it unselected.
- await expect(
- page
- .getByText('No connectors found.', { exact: true })
- .or(page.getByPlaceholder('Search connectors...'))
- ).toBeVisible({ timeout: 20_000 })
-
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
-
- await expect(page).toHaveURL(new RegExp(`/contexts/${name}$`), { timeout: 20_000 })
- await expect(
- page.getByText('Review details, manage connectors, agents, teams, and members.', {
- exact: true,
- })
- ).toBeVisible({ timeout: 20_000 })
-
- // Tour every detail tab; Members is the final stop and must be selected.
- for (const tabLabel of ['Connectors', 'Agent Files', 'Agents', 'Teams', 'Members']) {
- const tab = page.getByRole('tab', { name: tabLabel, exact: true })
- await expect(tab).toBeVisible({ timeout: 20_000 })
- await tab.click()
- }
- await expect(page.getByRole('tab', { name: 'Members', exact: true })).toHaveAttribute(
- 'aria-selected',
- 'true'
- )
-
- await screenshotAndLog(page, testInfo, 'control-ui-context-create')
- } finally {
- await api(page.request, 'DELETE', `/api/v1/admin/contexts/${encodeURIComponent(name)}`)
- }
- })
-})
diff --git a/control-ui/e2e/qa-recorder-contexts.spec.ts b/control-ui/e2e/qa-recorder-contexts.spec.ts
deleted file mode 100644
index f0cea2824..000000000
--- a/control-ui/e2e/qa-recorder-contexts.spec.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { expect, test } from '@playwright/test'
-import {
- CONTROL_API_URL,
- CONTROL_UI_URL,
- type NamedResource,
- adminCredentials,
- api,
- assertAllowedTarget,
- loginThroughUi,
- resourceName,
- screenshotAndLog,
-} from './qa-recorder-helpers'
-
-test.describe('optional QA recorder: Control UI contexts journey', () => {
- test('optional QA recorder: Control UI contexts list journey', async ({ page }, testInfo) => {
- assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
- assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
-
- const credentials = adminCredentials()
- await loginThroughUi(page, credentials)
-
- await page.getByRole('link', { name: 'Contexts', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
-
- // List shell (TablePanelHeader subtitle) renders regardless of row count.
- await expect(
- page.getByText('Group connectors into reusable access scopes.', { exact: true })
- ).toBeVisible({ timeout: 20_000 })
-
- // The title span reads "Contexts" during initial load and "Contexts (N)" once loaded;
- // either is a valid shell. Prefer a single concrete selector to avoid strict-mode matches.
- await expect(page.getByPlaceholder('Search contexts')).toBeVisible({ timeout: 20_000 })
-
- await screenshotAndLog(page, testInfo, 'control-ui-contexts')
- })
-
- test('optional QA recorder: Control UI context detail and tab journey', async ({
- page,
- }, testInfo) => {
- assertAllowedTarget('CONTROL_UI_URL', CONTROL_UI_URL)
- assertAllowedTarget('CONTROL_API_URL', CONTROL_API_URL)
-
- const credentials = adminCredentials()
- await loginThroughUi(page, credentials)
-
- // Read the inventory through the Control UI proxy (admin session cookie) so the
- // detail step only runs when a real context exists. Resilient to empty environments.
- const { status, data } = await api<{ items?: NamedResource[] }>(
- page.request,
- 'GET',
- '/api/v1/admin/contexts'
- )
- const contextNames = status === 200 ? (data.items ?? []).map(resourceName).filter(Boolean) : []
- test.skip(
- contextNames.length === 0,
- 'No contexts available in this environment; skipping context detail journey.'
- )
- const contextName = contextNames[0]
-
- await page.getByRole('link', { name: 'Contexts', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
- await expect(
- page.getByText('Group connectors into reusable access scopes.', { exact: true })
- ).toBeVisible({ timeout: 20_000 })
-
- // Open the detail for a known context. onView routes to the connectors tab.
- await page.getByRole('row', { name: `Open context ${contextName}`, exact: true }).click()
-
- // Detail shell (CreatePageHeader): the <h2> title is the context name and the
- // subtitle is stable copy that renders once the context has loaded.
- await expect(page).toHaveURL(new RegExp(`/contexts/.+`), { timeout: 20_000 })
- await expect(page.getByRole('heading', { name: contextName, exact: true })).toBeVisible({
- timeout: 20_000,
- })
- await expect(
- page.getByText('Review details, manage connectors, agents, teams, and members.', {
- exact: true,
- })
- ).toBeVisible({ timeout: 20_000 })
-
- await screenshotAndLog(page, testInfo, 'control-ui-context-detail')
-
- // Exercise a tab switch (Connectors is the default landing tab). Clicking the
- // Agents tab navigates to /contexts/<name>/agents and renders its panel shell.
- const agentsTab = page.getByRole('tab', { name: 'Agents', exact: true })
- await expect(agentsTab).toBeVisible({ timeout: 20_000 })
- await agentsTab.click()
- await expect(page).toHaveURL(/\/contexts\/.+\/agents$/, { timeout: 20_000 })
- await expect(agentsTab).toHaveAttribute('aria-selected', 'true')
- await expect(page.getByText('Agents using this context.', { exact: true })).toBeVisible({
- timeout: 20_000,
- })
-
- await screenshotAndLog(page, testInfo, 'control-ui-context-detail-agents')
- })
-})
diff --git a/control-ui/e2e/qa-recorder-create-form-smoke.spec.ts b/control-ui/e2e/qa-recorder-create-form-smoke.spec.ts
index 1972b8e02..4a91a7f82 100644
--- a/control-ui/e2e/qa-recorder-create-form-smoke.spec.ts
+++ b/control-ui/e2e/qa-recorder-create-form-smoke.spec.ts
@@ -39,22 +39,6 @@ test.describe('optional QA recorder: Control UI create-form smoke', () => {
await continueButton.click()
}
- test('Create context form mounts and steps to the connectors step', async ({
- page,
- }, testInfo) => {
- await openCreatePage(page, '/contexts/new')
- await expectShell(page, 'Create context', 'Define a new context and attach connectors.')
- await expect(page.locator('#ctx-name')).toBeVisible({ timeout: 20_000 })
-
- await page.locator('#ctx-name').fill('qa-smoke-context')
- await clickContinue(page)
- await expect(
- page.getByText('Choose the connectors this context can expose to agents.', { exact: true })
- ).toBeVisible({ timeout: 20_000 })
-
- await screenshotAndLog(page, testInfo, 'control-ui-create-context')
- })
-
test('Create connector form mounts on the identity step', async ({ page }, testInfo) => {
await openCreatePage(page, '/connectors/new')
await expectShell(
@@ -223,7 +207,7 @@ test.describe('optional QA recorder: Control UI create-form smoke', () => {
await expectShell(
page,
'Create SharedFileSystem',
- 'Provision workspace storage that Contexts can mount read-only into agent pods.'
+ 'Provision workspace storage that agents can mount read-only into their pods.'
)
await expect(page.locator('#shared-filesystem-name')).toBeVisible({ timeout: 20_000 })
@@ -258,7 +242,7 @@ test.describe('optional QA recorder: Control UI create-form smoke', () => {
await expectShell(
page,
'Install from Marketplace',
- 'Install a Marketplace entry into your cluster and bind it to a context.'
+ 'Install a Marketplace entry into your cluster.'
)
// Without entry/version query params the page renders a graceful error
// state beneath the header instead of a form.
diff --git a/control-ui/e2e/qa-recorder-navigation.spec.ts b/control-ui/e2e/qa-recorder-navigation.spec.ts
index d1943f0fc..eefb335f0 100644
--- a/control-ui/e2e/qa-recorder-navigation.spec.ts
+++ b/control-ui/e2e/qa-recorder-navigation.spec.ts
@@ -52,26 +52,17 @@ test.describe('optional QA recorder: Control UI navigation', () => {
await expectPersistentSidebar()
await screenshotAndLog(page, testInfo, 'control-ui-navigation-agents')
- // 2) Contexts — /contexts is a real App Router segment; URL is stable.
- await mainNav.getByRole('link', { name: 'Contexts', exact: true }).click()
- await expect(page).toHaveURL(/\/contexts$/, { timeout: 20_000 })
- await expect(
- page.getByText('Group connectors into reusable access scopes.', { exact: true })
- ).toBeVisible({ timeout: 20_000 })
- await expectPersistentSidebar()
- await screenshotAndLog(page, testInfo, 'control-ui-navigation-contexts')
-
- // 3) Connectors — sidebar href is /connectors (rewritten from /mcp-servers);
+ // 2) Connectors — sidebar href is /connectors (rewritten from /mcp-servers);
// the browser URL stays /connectors.
await mainNav.getByRole('link', { name: 'Installed Connectors', exact: true }).click()
await expect(page).toHaveURL(/\/connectors\/?$/, { timeout: 20_000 })
await expect(
- page.getByText('Browse connector deployments and context bindings.', { exact: true })
+ page.getByText('Browse connector deployments and agent access.', { exact: true })
).toBeVisible({ timeout: 20_000 })
await expectPersistentSidebar()
await screenshotAndLog(page, testInfo, 'control-ui-navigation-connectors')
- // 4) External Channels — sidebar href is /external-channels (rewritten from
+ // 3) External Channels — sidebar href is /external-channels (rewritten from
// /communication-channels); the browser URL stays /external-channels.
await mainNav.getByRole('link', { name: 'External Channels', exact: true }).click()
await expect(page).toHaveURL(/\/external-channels$/, { timeout: 20_000 })
@@ -81,7 +72,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {
await expectPersistentSidebar()
await screenshotAndLog(page, testInfo, 'control-ui-navigation-external-channels')
- // 5) LLM Models — Catalog and Discovery Review share one tabbed operator
+ // 4) LLM Models — Catalog and Discovery Review share one tabbed operator
// surface, so the sidebar uses one direct link.
await mainNav.getByRole('link', { name: 'LLM Models', exact: true }).click()
await expect(page).toHaveURL(/\/llm-models/, { timeout: 20_000 })
@@ -92,7 +83,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {
await expectPersistentSidebar()
await screenshotAndLog(page, testInfo, 'control-ui-navigation-llm-models')
- // 6) Users & Teams — sidebar href is /users-and-teams/users (rewritten from
+ // 5) Users & Teams — sidebar href is /users-and-teams/users (rewritten from
// /profile-admin/users); the browser URL stays /users-and-teams/users.
await mainNav.getByRole('link', { name: 'Users & Teams', exact: true }).click()
await expect(page).toHaveURL(/\/users-and-teams\/users$/, { timeout: 20_000 })
@@ -105,7 +96,7 @@ test.describe('optional QA recorder: Control UI navigation', () => {
await expectPersistentSidebar()
await screenshotAndLog(page, testInfo, 'control-ui-navigation-users-teams')
- // 7) Settings — rendered in the sidebar FOOTER (outside 'Main sections').
+ // 6) Settings — rendered in the sidebar FOOTER (outside 'Main sections').
// Sidebar href is /settings/ui (rewritten from /settings); the browser
// URL stays /settings/ui. Target the link globally since it is not in the
// mainNav region.
diff --git a/control-ui/e2e/qa-recorder-onboarding-combo.spec.ts b/control-ui/e2e/qa-recorder-onboarding-combo.spec.ts
index 8116cd63f..ebade78ec 100644
--- a/control-ui/e2e/qa-recorder-onboarding-combo.spec.ts
+++ b/control-ui/e2e/qa-recorder-onboarding-combo.spec.ts
@@ -1,7 +1,8 @@
// control-ui/e2e/qa-recorder-onboarding-combo.spec.ts
//
// Mutating QA recorder combo: new-team onboarding (team → member invite →
-// context → grant context to team). Creates and tears down every resource.
+// context staged through the Control API → grant access to the team). Creates
+// and tears down every resource.
// Requires QA_RECORDER_CONFIRM_MUTATIONS=1 in .env.qa-recorder.
import { expect, test } from '@playwright/test'
import {
@@ -95,39 +96,43 @@ test.describe('optional QA recorder: Control UI onboarding combo', () => {
timeout: 20_000,
})
await expect(
- page.getByText('Members, contexts, and agent access.', { exact: true })
+ page.getByText('Members, connector access, and agents.', { exact: true })
).toBeVisible({ timeout: 20_000 })
await expect(page.getByText(memberEmail, { exact: true })).toBeVisible({ timeout: 15_000 })
- // step 4: create a context (name only).
- await page.goto(`${CONTROL_UI_URL}/contexts/new`)
- await expect(page).toHaveURL(/\/contexts\/new$/, { timeout: 20_000 })
- await page.getByLabel('Context name').fill(contextName)
- await page.getByRole('button', { name: 'Continue', exact: true }).click()
- await page.getByRole('button', { name: 'Create context', exact: true }).click()
- await expect(page).toHaveURL(new RegExp(`/contexts/${contextName}$`), { timeout: 20_000 })
+ // step 4: create a context (name only) through the Control API — the
+ // /contexts UI is gone.
+ const ctxRes = await api(page.request, 'POST', '/api/v1/admin/contexts', {
+ metadata: { name: contextName },
+ spec: {
+ contextId: contextName,
+ description: 'QA recorder combo context',
+ mcpServers: [],
+ },
+ })
+ expect(ctxRes.status, `create context: ${JSON.stringify(ctxRes.data)}`).toBeLessThan(300)
- // step 5: grant the context to the team from the team Contexts tab.
+ // step 5: grant the access scope to the team from the team Access tab.
await page.goto(
- `${CONTROL_UI_URL}/users-and-teams/teams/${encodeURIComponent(teamId)}/contexts`
+ `${CONTROL_UI_URL}/users-and-teams/teams/${encodeURIComponent(teamId)}/access`
)
- await expect(page).toHaveURL(/\/users-and-teams\/teams\/.+\/contexts$/, {
+ await expect(page).toHaveURL(/\/users-and-teams\/teams\/.+\/access$/, {
timeout: 20_000,
})
await expect(
- page.getByText('Members, contexts, and agent access.', { exact: true })
+ page.getByText('Members, connector access, and agents.', { exact: true })
).toBeVisible({ timeout: 20_000 })
- await page.getByRole('button', { name: 'Add context', exact: true }).click()
- await expect(page.locator('#team-context-picker')).toBeVisible({ timeout: 5_000 })
- await page.locator('#team-context-picker').fill(contextName)
- const contextOption = page.getByRole('option', { name: contextName, exact: true })
- await expect(contextOption).toBeVisible({ timeout: 10_000 })
- await contextOption.click()
+ await page.getByRole('button', { name: 'Add access', exact: true }).click()
+ await expect(page.locator('#team-access-picker')).toBeVisible({ timeout: 5_000 })
+ await page.locator('#team-access-picker').fill(contextName)
+ const accessOption = page.getByRole('option', { name: contextName, exact: true })
+ await expect(accessOption).toBeVisible({ timeout: 10_000 })
+ await accessOption.click()
await page
.getByRole('dialog')
- .getByRole('button', { name: 'Add context', exact: true })
+ .getByRole('button', { name: 'Add access', exact: true })
.click()
- await expect(page.getByRole('button', { name: contextName, exact: true })).toBeVisible({
+ await expect(page.getByText('Team access updated.', { exact: true })).toBeVisible({
timeout: 15_000,
})
diff --git a/control-ui/e2e/qa-recorder-shared-fs-upload.spec.ts b/control-ui/e2e/qa-recorder-shared-fs-upload.spec.ts
index 8f6d34b47..27add238c 100644
--- a/control-ui/e2e/qa-recorder-shared-fs-upload.spec.ts
+++ b/control-ui/e2e/qa-recorder-shared-fs-upload.spec.ts
@@ -45,7 +45,7 @@ test.describe('optional QA recorder: Control UI SharedFileSystem', () => {
).toBeVisible({ timeout: 20_000 })
await expect(
page.getByText(
- 'Provision workspace storage that Contexts can mount read-only into agent pods.',
+ 'Provision workspace storage that agents can mount read-only into their pods.',
{ exact: true }
)
).toBeVisible({ timeout: 20_000 })
diff --git a/control-ui/e2e/qa-recorder-team-create.spec.ts b/control-ui/e2e/qa-recorder-team-create.spec.ts
index 22bcaf99e..d8014b6b4 100644
--- a/control-ui/e2e/qa-recorder-team-create.spec.ts
+++ b/control-ui/e2e/qa-recorder-team-create.spec.ts
@@ -65,7 +65,7 @@ test.describe('optional QA recorder: Control UI team creation', () => {
await continueWizard(page)
await expect(
- page.getByText('Select the contexts this team can access.', { exact: true })
+ page.getByText('Choose the agents and connector scopes this team can use.', { exact: true })
).toBeVisible({ timeout: 20_000 })
await continueWizard(page)
@@ -93,13 +93,13 @@ test.describe('optional QA recorder: Control UI team creation', () => {
timeout: 20_000,
})
- const contextsTab = page.getByRole('tab', { name: 'Contexts', exact: true })
- await contextsTab.click()
- await expect(page).toHaveURL(/\/users-and-teams\/teams\/[^/]+\/contexts$/, {
+ const accessTab = page.getByRole('tab', { name: 'Access', exact: true })
+ await accessTab.click()
+ await expect(page).toHaveURL(/\/users-and-teams\/teams\/[^/]+\/access$/, {
timeout: 20_000,
})
- await expect(contextsTab).toHaveAttribute('aria-selected', 'true')
- await expect(page.getByRole('button', { name: 'Add context', exact: true })).toBeVisible({
+ await expect(accessTab).toHaveAttribute('aria-selected', 'true')
+ await expect(page.getByRole('button', { name: 'Add access', exact: true })).toBeVisible({
timeout: 20_000,
})
diff --git a/control-ui/next.config.js b/control-ui/next.config.js
index ab9b105b8..cb091ac52 100644
--- a/control-ui/next.config.js
+++ b/control-ui/next.config.js
@@ -159,11 +159,6 @@ const nextConfig = {
},
{ source: '/outputs', destination: '/agent-outputs/recipe-artifacts', permanent: true },
{ source: '/outputs/:path*', destination: '/agent-outputs/:path*', permanent: true },
- {
- source: '/contexts/:name/shared-files',
- destination: '/contexts/:name/agent-files',
- permanent: true,
- },
{ source: '/secrets', destination: '/secrets/llm', permanent: true },
{ source: '/settings', destination: '/settings/ui', permanent: true },
{ source: '/traces/hosts', destination: '/traces', permanent: true },
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 886a7d583..ecd63b31d 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.460",
+ "version": "0.1.461",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.460",
+ "version": "0.1.461",
"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 94a5d9dd2..c7fd2e391 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.460",
+ "version": "0.1.461",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
@@ -11,7 +11,6 @@
"qa:recorder:login": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-login.spec.ts",
"qa:recorder:navigation": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-navigation.spec.ts",
"qa:recorder:agents": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-agents.spec.ts",
- "qa:recorder:contexts": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-contexts.spec.ts",
"qa:recorder:connectors": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-connectors.spec.ts",
"qa:recorder:external-channels": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-external-channels.spec.ts",
"qa:recorder:llm-models": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-llm-models.spec.ts",
@@ -20,8 +19,6 @@
"qa:recorder:traces": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-traces.spec.ts",
"qa:recorder:settings": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-settings.spec.ts",
"qa:recorder:marketplace": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-marketplace.spec.ts",
- "qa:recorder:context-create": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-context-create.spec.ts",
- "qa:recorder:context-connector": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-context-connector.spec.ts",
"qa:recorder:connector-edit": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-connector-edit.spec.ts",
"qa:recorder:llm-model-lifecycle": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-llm-model-lifecycle.spec.ts",
"qa:recorder:secret-recipe": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-secret-recipe.spec.ts",
@@ -38,7 +35,6 @@
"qa:recorder:llm-price": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-llm-price.spec.ts",
"qa:recorder:onboarding-combo": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-onboarding-combo.spec.ts",
"qa:recorder:cost-governance": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-cost-governance.spec.ts",
- "qa:recorder:context-connector-budget": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-context-connector-budget.spec.ts",
"qa:recorder:settings-account": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-settings-account.spec.ts",
"qa:recorder:settings-password": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-settings-password.spec.ts",
"qa:recorder:settings-email": "PLAYWRIGHT_BROWSERS_PATH=../.local-notes/qa-recorder/browsers playwright test --config=playwright.qa-recorder.config.ts qa-recorder-settings-email.spec.ts",
diff --git a/docs/features/control-ui-context-removal.md b/docs/features/control-ui-context-removal.md
index 363fd60df..58f7447b4 100644
--- a/docs/features/control-ui-context-removal.md
+++ b/docs/features/control-ui-context-removal.md
@@ -193,7 +193,8 @@ 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`). |
-| 2026-08-26 | 2 | Category C implemented. Member + team detail "Contexts" tabs → route `access` / label **"Access"**; rows now show resolved labels (owning agent name(s) → context `displayName` → muted raw id) and no longer link into `/contexts`; confirm/toast/error copy reworded ("Access updated.", "Removed access" for deleted mappings); add-modal relabeled with resolved-label picker, writing context IDs unchanged. Team wizard step "Contexts" → **"Access"** with resolved-label options; `createFlowLoading.createTeam` updated. Legacy `ProfileAdminPanel.tsx` deleted (zero importers). `ProfileAdminHome` "Contexts" column → **"Access"** (same sort/count source `teamContextCounts`); org-delete warning reworded. Redirects added for `/users-and-teams/{users,teams}/:id/contexts` → `…/access`. Full vitest + `tsc` green. No backend changes (GET/PUT `/admin/{users,teams}/:id/contexts` payloads byte-identical). |
+| 2026-08-26 | 2 | Category C implemented. Member + team detail "Contexts" tabs → route `access` / label **"Access"**; rows show resolved labels (owning agent name(s) → context `displayName` → muted raw id), no `/contexts` links; confirm/toast/error copy reworded ("Access updated.", "Removed access"); add-modal relabeled with resolved-label picker, writing context IDs unchanged. Team wizard step "Contexts" → **"Access"**. Legacy `ProfileAdminPanel.tsx` deleted (zero importers). `ProfileAdminHome` "Contexts" column → **"Access"** (same sort/count source). Redirects for `/users-and-teams/{users,teams}/:id/contexts` → `…/access`. No backend changes (GET/PUT `/admin/{users,teams}/:id/contexts` payloads byte-identical). |
+| 2026-08-26 | 3 | Category A implemented + e2e migration for phases 0–3. Deleted: `/contexts` pages (`page`, `new`, `[name]`, `[name]/[tab]`), `components/ContextTable.tsx`, sidebar item/type/order, `DashboardLayout` branch, `CONTROL_ROUTES.contexts` builders, `createFlowLoading.createContext`, stale `/contexts/:name/shared-files` redirect. Added `app/contexts/[[...slug]]/page.tsx` legacy resolver (slug → owning agent's Connectors tab via `spec.contextRef` join; unknown/`new`/failures → `/agents`). Tests: contexts suites + `ContextTable.test.tsx` deleted; **spec-preservation contract re-homed** to `HostDetailsPage.connectors.test.tsx` (unknown `spec.gfs` + `resourceVersion` survive agent-side connector PUTs); RFC1123 generation stays covered by `lib/__tests__/agentContext.test.ts`; `Sidebar.test.tsx` order, `AuthContext.test.tsx` URL fixture updated. E2e: main `contexts.spec.ts` rewritten as redirect/no-sidebar regression; `auth.spec.ts`, `channels.spec.ts`, `mcp-servers.spec.ts`, `helpers/selectors.ts` cleaned. QA-recorder: 4 context specs deleted + their npm scripts; connector-edit/navigation/onboarding-combo/team-create/create-form-smoke/connectors/shared-fs-upload migrated to agent-access flows (API-created contexts where a context fixture is needed). Full vitest (1700) + `tsc` green. No backend changes. |
## 11. Open questions / follow-ups (non-blocking)
diff --git a/tests/e2e/playwright/control-ui/auth.spec.ts b/tests/e2e/playwright/control-ui/auth.spec.ts
index 7afe055cc..8675494f4 100644
--- a/tests/e2e/playwright/control-ui/auth.spec.ts
+++ b/tests/e2e/playwright/control-ui/auth.spec.ts
@@ -71,7 +71,7 @@ test.describe('Control UI — Auth', () => {
// All main tabs visible
await expect(page.locator(CUI_DASHBOARD.TAB_AGENTS)).toBeVisible()
- await expect(page.locator(CUI_DASHBOARD.TAB_CONTEXTS)).toBeVisible()
+ await expect(page.locator(CUI_DASHBOARD.TAB_MARKETPLACE)).toBeVisible()
await expect(page.locator(CUI_DASHBOARD.TAB_MCP_SERVERS)).toBeVisible()
await expect(page.locator(CUI_DASHBOARD.TAB_CHANNELS)).toBeVisible()
await expect(page.locator(CUI_DASHBOARD.TAB_MEMBERS_TEAMS)).toBeVisible()
diff --git a/tests/e2e/playwright/control-ui/channels.spec.ts b/tests/e2e/playwright/control-ui/channels.spec.ts
index c713ac857..c70192af9 100644
--- a/tests/e2e/playwright/control-ui/channels.spec.ts
+++ b/tests/e2e/playwright/control-ui/channels.spec.ts
@@ -40,9 +40,8 @@ test.describe('Control UI — External Channels', () => {
authedPage,
}) => {
// CommunicationChannelsTable has its own CRUD — check what's visible
- // The tab should NOT show the Hosts or Contexts specific buttons
+ // The tab should NOT show the Hosts-specific create button
await expect(authedPage.locator(CUI_DASHBOARD.CREATE_HOST_BUTTON)).toBeHidden()
- await expect(authedPage.locator(CUI_DASHBOARD.CREATE_CONTEXT_BUTTON)).toBeHidden()
})
test('shows the CommunicationChannel CRDs returned by the API', async ({ authedPage }) => {
diff --git a/tests/e2e/playwright/control-ui/contexts.spec.ts b/tests/e2e/playwright/control-ui/contexts.spec.ts
index 5958b5e7e..988aa73c5 100644
--- a/tests/e2e/playwright/control-ui/contexts.spec.ts
+++ b/tests/e2e/playwright/control-ui/contexts.spec.ts
@@ -1,50 +1,46 @@
/**
- * Control UI — Contexts tab tests
+ * Control UI — Contexts section removal tests
*
- * Validates the Contexts table and navigation to context detail page.
+ * The /contexts section is gone from the UI; legacy deep links resolve
+ * client-side to user-facing destinations instead of dead-ending.
*/
import { expect, test } from '../helpers/auth-fixture'
-import { CUI_CONTEXTS, CUI_DASHBOARD } from '../helpers/selectors'
+import { CUI_DASHBOARD } from '../helpers/selectors'
-test.describe('Control UI — Contexts', () => {
+const CONTROL_UI_URL = process.env.CONTROL_UI_URL ?? 'http://127.0.0.1:3000'
+
+test.describe('Control UI — Contexts removal', () => {
test.beforeEach(async ({ authedPage }) => {
await expect(authedPage.locator(CUI_DASHBOARD.HEADING)).toBeVisible()
- await authedPage.click(CUI_DASHBOARD.TAB_CONTEXTS)
- })
-
- test('Contexts tab shows table with correct columns', async ({ authedPage }) => {
- const table = authedPage.locator(CUI_CONTEXTS.TABLE)
- await expect(table).toBeVisible({ timeout: 15_000 })
- await expect(authedPage.locator(CUI_CONTEXTS.TABLE_HEADER_NAME)).toBeVisible()
- await expect(authedPage.locator(CUI_CONTEXTS.TABLE_HEADER_MCP_SERVERS)).toBeVisible()
- })
-
- test('shows context1 from cluster', async ({ authedPage }) => {
- await expect(authedPage.locator('table')).toBeVisible({ timeout: 15_000 })
- const contextRow = authedPage.locator('tbody tr').filter({ hasText: 'context1' }).first()
- await expect(contextRow).toBeVisible({ timeout: 15_000 })
- await expect(contextRow.getByRole('button', { name: /^context1$/ })).toBeVisible()
})
- test('Create Context button is visible on Contexts tab', async ({ authedPage }) => {
- await expect(authedPage.locator(CUI_DASHBOARD.CREATE_CONTEXT_BUTTON)).toBeVisible()
+ test('sidebar has no Contexts item', async ({ authedPage }) => {
+ await expect(authedPage.locator('.cu-sidebar__item', { hasText: 'Contexts' })).toHaveCount(0)
})
- test('clicking Create Context navigates to /contexts/new', async ({ authedPage }) => {
- await authedPage.click(CUI_DASHBOARD.CREATE_CONTEXT_BUTTON)
- await authedPage.waitForURL('**/contexts/new', { timeout: 10_000 })
- expect(authedPage.url()).toContain('/contexts/new')
+ test('/contexts redirects to the Agents list', async ({ authedPage }) => {
+ // authedPage runs in a manual browser context without baseURL, so
+ // navigation needs the absolute URL (see helpers/auth-fixture.ts).
+ await authedPage.goto(`${CONTROL_UI_URL}/contexts`)
+ await authedPage.waitForURL('**/agents', { timeout: 15_000 })
+ expect(authedPage.url()).toContain('/agents')
+ await expect(
+ authedPage
+ .locator('main')
+ .getByText(/^Agents( \(\d+\))?$/)
+ .first()
+ ).toBeVisible({ timeout: 15_000 })
})
- test('clicking a context name navigates to context detail', async ({ authedPage }) => {
- await expect(authedPage.locator('table')).toBeVisible({ timeout: 15_000 })
- const firstLink = authedPage.locator('tbody tr:first-child td:first-child .cu-link')
- if ((await firstLink.count()) > 0) {
- await firstLink.first().click()
- await authedPage.waitForURL('**/contexts/**', { timeout: 10_000 })
- expect(authedPage.url()).toMatch(/\/contexts\/.+/)
- } else {
- test.skip() // No contexts in cluster yet
- }
+ test('/contexts/<unknown-slug> redirects to the Agents list', async ({ authedPage }) => {
+ await authedPage.goto(`${CONTROL_UI_URL}/contexts/nonexistent-slug-xyz`)
+ await authedPage.waitForURL('**/agents', { timeout: 15_000 })
+ expect(authedPage.url()).toContain('/agents')
+ await expect(
+ authedPage
+ .locator('main')
+ .getByText(/^Agents( \(\d+\))?$/)
+ .first()
+ ).toBeVisible({ timeout: 15_000 })
})
})
diff --git a/tests/e2e/playwright/control-ui/mcp-servers.spec.ts b/tests/e2e/playwright/control-ui/mcp-servers.spec.ts
index cd6c15c17..a04f0aa1b 100644
--- a/tests/e2e/playwright/control-ui/mcp-servers.spec.ts
+++ b/tests/e2e/playwright/control-ui/mcp-servers.spec.ts
@@ -26,7 +26,6 @@ test.describe('Control UI — MCP Servers', () => {
await expect(authedPage.getByRole('button', { name: 'Install from Registry' })).toBeVisible()
await expect(authedPage.getByRole('button', { name: 'Create MCP Server' })).toBeVisible()
await expect(authedPage.locator(CUI_DASHBOARD.CREATE_HOST_BUTTON)).toBeHidden()
- await expect(authedPage.locator(CUI_DASHBOARD.CREATE_CONTEXT_BUTTON)).toBeHidden()
await expect(
authedPage
.locator('tbody tr')
@@ -35,10 +34,9 @@ test.describe('Control UI — MCP Servers', () => {
).toBeVisible()
})
- test('shows at least the chatllm MCP server entries from context1', async ({ authedPage }) => {
- // context1 should have MCP servers configured via the cluster
+ test('shows at least the chatllm MCP server entries', async ({ authedPage }) => {
const tableOrEmpty = authedPage.locator('table, p, div').filter({
- hasText: /context1|chatllm|mongodb|No MCP/i,
+ hasText: /chatllm|mongodb|No MCP/i,
})
await expect(tableOrEmpty.first()).toBeVisible({ timeout: 15_000 })
})
diff --git a/tests/e2e/playwright/helpers/selectors.ts b/tests/e2e/playwright/helpers/selectors.ts
index 3cd56e8c4..572a52992 100644
--- a/tests/e2e/playwright/helpers/selectors.ts
+++ b/tests/e2e/playwright/helpers/selectors.ts
@@ -37,7 +37,7 @@ export const CUI_DASHBOARD = {
TAB_AGENTS: '.cu-sidebar__item:has-text("Agents")',
TAB_HOSTS: '.cu-sidebar__item:has-text("Agents")',
- TAB_CONTEXTS: '.cu-sidebar__item:has-text("Contexts")',
+ TAB_MARKETPLACE: '.cu-sidebar__item:has-text("Marketplace")',
TAB_MCP_SERVERS: '.cu-sidebar__item:has-text("Connectors")',
TAB_CHANNELS: '.cu-sidebar__item:has-text("External Channels")',
TAB_MEMBERS_TEAMS: '.cu-sidebar__item:has-text("Users & Teams")',
@@ -45,7 +45,6 @@ export const CUI_DASHBOARD = {
TAB_WORKFLOW_RECIPES: '.cu-sidebar__item:has-text("Plugins")',
CREATE_HOST_BUTTON: 'button:has-text("Create agent")',
- CREATE_CONTEXT_BUTTON: 'button:has-text("Create context")',
LOADING_INDICATOR: 'div:has-text("Loading...")',
} as const
@@ -59,13 +58,6 @@ export const CUI_HOSTS = {
WIZARD_CLOSE_BUTTON: 'button[aria-label="Close"]',
} as const
-// ── Control UI — Contexts table ───────────────────────────────────────────────
-export const CUI_CONTEXTS = {
- TABLE: 'table',
- TABLE_HEADER_NAME: 'th:has-text("Context Name")',
- TABLE_HEADER_MCP_SERVERS: 'th:has-text("MCP servers")',
-} as const
-
// ── Control UI — Users & Teams ────────────────────────────────────────────────
// IMPORTANT: scope sub-tab selectors to <section> — the main nav has a
// "Members & Teams" tab that would match 'button:has-text("Members|Teams")' globally.
diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.json
index 6c6c236b5..01a816aa6 100644
--- a/tests/e2e/playwright/package-lock.json
+++ b/tests/e2e/playwright/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.21",
+ "version": "0.1.22",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-playwright-tests",
- "version": "0.1.21",
+ "version": "0.1.22",
"devDependencies": {
"@playwright/test": "^1.50.0",
"@types/node": "^22.0.0"
diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.json
index 23fc8d8a9..a28713483 100644
--- a/tests/e2e/playwright/package.json
+++ b/tests/e2e/playwright/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-playwright-tests",
- "version": "0.1.21",
+ "version": "0.1.22",
"private": true,
"description": "Playwright E2E tests for Control UI and Desktop App",
"scripts": {