Skip to content

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

TypeScript

test(control-ui): add generated contract coverage

Miguelon Peluchonbf122418070d
diff --git a/control-ui/components/__tests__/ConnectorEditContext.test.tsx b/control-ui/components/__tests__/ConnectorEditContext.test.tsx
index ec3411bfc..57e8d238d 100644
--- a/control-ui/components/__tests__/ConnectorEditContext.test.tsx
+++ b/control-ui/components/__tests__/ConnectorEditContext.test.tsx
@@ -3,6 +3,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import EditMcpServerPage from '../../app/mcp-servers/[name]/edit/page'
import * as api from '../../lib/api'
+import { buildContextList, buildContextResource } from '../../test/fixtures/contextResource'
const replace = vi.fn()
const push = vi.fn()
@@ -58,14 +59,14 @@ describe('connector edit Context access', () => {
metadata: { name: 'search' },
spec: { contextRef: 'removed-context', image: 'example/search:latest' },
})
- vi.mocked(api.getContexts).mockResolvedValue({
- items: [
- {
+ vi.mocked(api.getContexts).mockResolvedValue(
+ buildContextList([
+ buildContextResource({
metadata: { name: 'removed-context', resourceVersion: 'rv-2' },
- spec: { contextId: 'removed-context', mcpServers: [] },
- },
- ],
- })
+ spec: { mcpServers: [] },
+ }),
+ ])
+ )
render(<EditMcpServerPage />)
diff --git a/control-ui/components/__tests__/ContextTable.test.tsx b/control-ui/components/__tests__/ContextTable.test.tsx
index d01b5a961..c5d2e2bb7 100644
--- a/control-ui/components/__tests__/ContextTable.test.tsx
+++ b/control-ui/components/__tests__/ContextTable.test.tsx
@@ -1,17 +1,13 @@
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen } from '@testing-library/react'
-import type { ContextResource } from '../../lib/api'
+import { buildContextResource } from '../../test/fixtures/contextResource'
import { ContextTable } from '../ContextTable'
-const contexts: ContextResource[] = [
- {
+const contexts = [
+ buildContextResource({
metadata: { name: 'business' },
- spec: {
- contextId: 'business',
- description: 'Business context',
- mcpServers: ['server-a', 'server-b'],
- },
- },
+ spec: { description: 'Business context', mcpServers: ['server-a', 'server-b'] },
+ }),
]
describe('ContextTable', () => {
diff --git a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
index e09212d36..1739dbf00 100644
--- a/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
+++ b/control-ui/components/__tests__/CreateMcpServerForm.test.tsx
@@ -6,32 +6,32 @@ import { CreateMcpServerForm } from '../CreateMcpServerForm'
import { ToastProvider } from '../Toast'
// vi.mock is hoisted before imports; factory runs lazily so references to `api` are safe.
-vi.mock('../../lib/api', () => ({
- createMcpServer: vi.fn().mockResolvedValue({ metadata: { name: 'test-server' } }),
- createMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),
- deleteMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),
- getContexts: vi.fn().mockResolvedValue({
- items: [
- {
- metadata: { name: 'context1', resourceVersion: 'rv-context1' },
- spec: { contextId: 'context1', mcpServers: [] },
- },
- {
- metadata: { name: 'research', resourceVersion: 'rv-research' },
- spec: { contextId: 'research', mcpServers: [] },
- },
- ],
- }),
- getContext: vi.fn().mockResolvedValue({
+vi.mock('../../lib/api', async () => {
+ const { buildContextList, buildContextResource } =
+ await import('../../test/fixtures/contextResource')
+ const context1 = buildContextResource({
metadata: { name: 'context1', resourceVersion: 'rv-context1' },
- spec: { contextId: 'context1', mcpServers: [] },
- }),
- getContextTeams: vi.fn().mockResolvedValue({ items: [] }),
- getContextUsers: vi.fn().mockResolvedValue({ items: [] }),
- listOrgImages: vi.fn().mockResolvedValue({ org: 'evenfire-dev', images: [] }),
- getHosts: vi.fn().mockResolvedValue({ items: [] }),
- updateContext: vi.fn().mockResolvedValue({}),
-}))
+ })
+ return {
+ createMcpServer: vi.fn().mockResolvedValue({ metadata: { name: 'test-server' } }),
+ createMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),
+ deleteMcpSecret: vi.fn().mockResolvedValue({ name: 'test-credentials' }),
+ getContexts: vi.fn().mockResolvedValue(
+ buildContextList([
+ context1,
+ buildContextResource({
+ metadata: { name: 'research', resourceVersion: 'rv-research' },
+ }),
+ ])
+ ),
+ getContext: vi.fn().mockResolvedValue(context1),
+ getContextTeams: vi.fn().mockResolvedValue({ items: [] }),
+ getContextUsers: vi.fn().mockResolvedValue({ items: [] }),
+ listOrgImages: vi.fn().mockResolvedValue({ org: 'evenfire-dev', images: [] }),
+ getHosts: vi.fn().mockResolvedValue({ items: [] }),
+ updateContext: vi.fn().mockResolvedValue({}),
+ }
+})
afterEach(() => {
cleanup()
diff --git a/control-ui/components/__tests__/HostWizard.test.tsx b/control-ui/components/__tests__/HostWizard.test.tsx
index c1213d5a6..3fc83fa88 100644
--- a/control-ui/components/__tests__/HostWizard.test.tsx
+++ b/control-ui/components/__tests__/HostWizard.test.tsx
@@ -2,6 +2,8 @@ import React from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import * as api from '../../lib/api'
+import { buildContextList, buildContextResource } from '../../test/fixtures/contextResource'
+import { buildSecretSummary } from '../../test/fixtures/secretSummary'
import { HostWizard } from '../HostWizard'
import { ToastProvider } from '../Toast'
@@ -91,7 +93,7 @@ async function renderWizard(props?: {
<ToastProvider>
<HostWizard
mcpServers={props?.mcpServers ?? [{ metadata: { name: 'mcp-a' } }]}
- existingSecrets={props?.existingSecrets ?? [{ name: 'secret-a' }]}
+ existingSecrets={props?.existingSecrets ?? [buildSecretSummary({ name: 'secret-a' })]}
onCreated={onCreated}
onClose={onClose}
/>
@@ -156,10 +158,10 @@ describe('HostWizard — credential draft is projected onto the active provider
it('shows every provider with complete credentials for an existing Secret', async () => {
await renderWizard({
existingSecrets: [
- {
+ buildSecretSummary({
name: 'shared-llm-keys',
keys: ['openai-api-key', 'aws-access-key-id', 'aws-secret-access-key'],
- },
+ }),
],
})
await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
@@ -178,8 +180,11 @@ describe('HostWizard — credential draft is projected onto the active provider
it('matches the primary provider to the selected credential', async () => {
await renderWizard({
existingSecrets: [
- { name: 'zai-only', keys: ['zai-api-key'] },
- { name: 'anthropic-and-zai', keys: ['claude-api-key', 'zai-api-key'] },
+ buildSecretSummary({ name: 'zai-only', keys: ['zai-api-key'] }),
+ buildSecretSummary({
+ name: 'anthropic-and-zai',
+ keys: ['claude-api-key', 'zai-api-key'],
+ }),
],
})
await waitFor(() => expect(api.getAdminUsers).toHaveBeenCalled())
@@ -294,14 +299,14 @@ describe('HostWizard — credential draft is projected onto the active provider
describe('HostWizard — Context creation', () => {
it('titles the existing context selector and shows attached MCP servers as chips', async () => {
vi.mocked(api.apiGet)
- .mockResolvedValueOnce({
- items: [
- {
+ .mockResolvedValueOnce(
+ buildContextList([
+ buildContextResource({
metadata: { name: 'business', namespace: 'mcp-host' },
- spec: { contextId: 'business', mcpServers: ['mcp-a', 'mcp-b'] },
- },
- ],
- })
+ spec: { mcpServers: ['mcp-a', 'mcp-b'] },
+ }),
+ ])
+ )
.mockResolvedValueOnce({ items: [] })
await renderWizard()
diff --git a/control-ui/components/__tests__/McpServerTable.test.tsx b/control-ui/components/__tests__/McpServerTable.test.tsx
index 7cd1ecc0f..5049e964f 100644
--- a/control-ui/components/__tests__/McpServerTable.test.tsx
+++ b/control-ui/components/__tests__/McpServerTable.test.tsx
@@ -1,5 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { buildContextResource } from '../../test/fixtures/contextResource'
import { McpServerTable } from '../McpServerTable'
afterEach(() => {
@@ -57,6 +58,22 @@ function makeItem(overrides: {
return item
}
+function makeContextBinding(options: {
+ name: string
+ description?: string
+ mcpServers?: string[]
+}) {
+ const context = buildContextResource({
+ metadata: { name: options.name },
+ spec: { description: options.description ?? '', mcpServers: options.mcpServers ?? [] },
+ })
+ return {
+ name: context.metadata.name,
+ description: context.spec.description,
+ mcpServers: context.spec.mcpServers,
+ }
+}
+
// ─────────────────────────────────────────────────────────────────────────────
// StatusBadge precedence
// ─────────────────────────────────────────────────────────────────────────────
@@ -365,8 +382,8 @@ describe('McpServerTable — context membership', () => {
<McpServerTable
items={[makeItem({ name: 'airtable-server', contextRef: 'removed-context' })]}
contexts={[
- { name: 'removed-context', mcpServers: [] },
- { name: 'active-context', mcpServers: ['another-server'] },
+ makeContextBinding({ name: 'removed-context' }),
+ makeContextBinding({ name: 'active-context', mcpServers: ['another-server'] }),
]}
accessByConnectorKey={{}}
/>
@@ -388,8 +405,12 @@ describe('McpServerTable — context membership', () => {
<McpServerTable
items={items}
contexts={[
- { name: 'research', description: 'Research tools', mcpServers: ['airtable-server'] },
- { name: 'sales', mcpServers: [] },
+ makeContextBinding({
+ name: 'research',
+ description: 'Research tools',
+ mcpServers: ['airtable-server'],
+ }),
+ makeContextBinding({ name: 'sales' }),
]}
onAddToContexts={vi.fn().mockResolvedValue(undefined)}
onRemoveFromContext={onRemoveFromContext}
@@ -420,8 +441,8 @@ describe('McpServerTable — context membership', () => {
<McpServerTable
items={items}
contexts={[
- { name: 'research', mcpServers: ['airtable-server'] },
- { name: 'sales', description: 'Sales tools', mcpServers: [] },
+ makeContextBinding({ name: 'research', mcpServers: ['airtable-server'] }),
+ makeContextBinding({ name: 'sales', description: 'Sales tools' }),
]}
onAddToContexts={onAddToContexts}
onRemoveFromContext={vi.fn().mockResolvedValue(undefined)}
diff --git a/control-ui/components/__tests__/RegistryInstallForm.test.tsx b/control-ui/components/__tests__/RegistryInstallForm.test.tsx
index 6517fbc66..ac9e8411a 100644
--- a/control-ui/components/__tests__/RegistryInstallForm.test.tsx
+++ b/control-ui/components/__tests__/RegistryInstallForm.test.tsx
@@ -6,15 +6,17 @@ import { RegistryInstallForm } from '../RegistryInstallForm'
import { ToastProvider } from '../Toast'
vi.mock('../../lib/api', async () => {
+ const { buildContextList, buildContextResource } =
+ await import('../../test/fixtures/contextResource')
const mod: Record<string, unknown> = {}
mod.getRegistryCredentialSchema = vi.fn().mockResolvedValue({
required: false,
authType: 'none',
keys: [],
})
- mod.getContexts = vi.fn().mockResolvedValue({
- items: [{ metadata: { name: 'context1' } }],
- })
+ mod.getContexts = vi
+ .fn()
+ .mockResolvedValue(buildContextList([buildContextResource({ metadata: { name: 'context1' } })]))
mod.getContextUsers = vi.fn().mockResolvedValue({ items: [] })
mod.getContextTeams = vi.fn().mockResolvedValue({ items: [] })
mod.getHosts = vi.fn().mockResolvedValue({ items: [] })
diff --git a/control-ui/components/__tests__/SecretsTable.test.tsx b/control-ui/components/__tests__/SecretsTable.test.tsx
index 702c8f039..00b7284a1 100644
--- a/control-ui/components/__tests__/SecretsTable.test.tsx
+++ b/control-ui/components/__tests__/SecretsTable.test.tsx
@@ -9,6 +9,7 @@ import {
within,
} from '@testing-library/react'
import { apiSend, getMcpServers, getRecipeSecrets, getRecipes } from '../../lib/api'
+import { buildSecretSummary } from '../../test/fixtures/secretSummary'
import { SecretsTable } from '../SecretsTable'
import { ToastProvider } from '../Toast'
@@ -77,7 +78,7 @@ describe('SecretsTable — LLM secret update payload', () => {
<ToastProvider>
<SecretsTable
activeScope="llm"
- items={[{ name: SECRET, keys }]}
+ items={[buildSecretSummary({ name: SECRET, keys })]}
onChanged={async () => {}}
onCreateLlmSecret={() => {}}
onCreateMcpSecret={() => {}}
diff --git a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
index 9b982bac4..1608a8e4c 100644
--- a/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
+++ b/control-ui/components/__tests__/UpdateConnectorCredentials.test.tsx
@@ -8,6 +8,7 @@ import {
} from '@components/UpdateConnectorCredentials'
import { getMcpServer, getMcpServers, getRegistryCredentialSchema, updateMcpSecret } from '@lib/api'
import type { EnvSecret, McpServerResource } from '@lib/api'
+import { buildSecretSummary } from '../../test/fixtures/secretSummary'
vi.mock('@lib/api', () => ({
getMcpServer: vi.fn(),
@@ -32,6 +33,14 @@ const ENV_SECRET: EnvSecret = {
],
}
+function secretRotationResponse(keys: string[], affectedConnectors = [SERVER_NAME]) {
+ return {
+ ...buildSecretSummary({ name: ENV_SECRET.name, keys }),
+ namespace: 'mcp-server',
+ affectedConnectors,
+ }
+}
+
function serverWithCondition(condition?: {
status: 'True' | 'False'
message: string
@@ -177,12 +186,7 @@ describe('UpdateConnectorCredentials — masked inputs', () => {
})
it('never renders a stored credential value — inputs stay empty through a full rotation cycle', async () => {
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
status: 'True',
@@ -204,12 +208,7 @@ describe('UpdateConnectorCredentials — masked inputs', () => {
describe('UpdateConnectorCredentials — partial payload', () => {
it('sends only the filled keys, never the untouched ones', async () => {
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key', 'workspace-id'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key', 'workspace-id']))
mockGetMcpServer.mockResolvedValue(serverWithCondition(undefined))
await renderPanel(ENV_SECRET)
@@ -260,12 +259,7 @@ describe('UpdateConnectorCredentials — PUT rejection', () => {
// ─── Polling / DeploymentReady correlation — the CRD contract (Fase 3 §6) ───
describe('UpdateConnectorCredentials — rollout polling', () => {
it('reports success once a FRESH DeploymentReady=True is observed after the PUT', async () => {
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
// First poll: a False condition that predates the PUT (stale) — must NOT
// be read as an outcome of this rotation.
mockGetMcpServer.mockResolvedValueOnce(
@@ -309,12 +303,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
// reason WaitingForReplicas (fresh, post-PUT) for the whole rollout window,
// then True once the new pod is Ready. The UI must NOT read the transitory
// False as failure — doing so would abort almost every successful rotation.
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
// First two polls: transitory False, timestamped AFTER the PUT.
mockGetMcpServer
.mockResolvedValueOnce(
@@ -370,12 +359,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
// failure on the first sighting; it reports failure only when its OWN
// POLL_TIMEOUT_MS expires with the diagnostic still uncorrected — and then
// with the HCC's rollout numbers, never a bare "timed out".
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
status: 'False',
@@ -414,12 +398,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
// still observing". The UI must keep polling and report SUCCESS on the later
// True, not latch 'failed' on the first RolloutIncomplete. This is the
// false-negative a slow/loaded cluster reproduces (convergence 120s..180s).
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
mockGetMcpServer
.mockResolvedValueOnce(
serverWithCondition({
@@ -460,12 +439,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
})
it('keeps waiting when DeploymentReady=True predates the PUT (stale success must not count)', async () => {
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
status: 'True',
@@ -486,12 +460,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
})
it('reports failure with the condition message when RolloutIncomplete persists after the PUT', async () => {
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
status: 'False',
@@ -529,12 +498,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
// this condition is judged stale, the rotation wedges until timeout, and
// this assertion goes red — which the pre-existing success test (whose
// timestamp sits AFTER system time) could not detect.
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
status: 'True',
@@ -555,12 +519,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
})
it('reports a bounded timeout — never success — when the condition never transitions', async () => {
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key']))
// Always stale: predates the PUT on every single poll.
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
@@ -590,12 +549,7 @@ describe('UpdateConnectorCredentials — rollout polling', () => {
// them (a false-positive: SERVER_NAME could converge while the other pod
// CrashLoopBackOffs, yet the old banner said both "restarted and is serving").
const OTHER = 'other-connector-b'
- mockUpdateMcpSecret.mockResolvedValue({
- name: ENV_SECRET.name,
- namespace: 'mcp-server',
- keys: ['api-key'],
- affectedConnectors: [SERVER_NAME, OTHER],
- })
+ mockUpdateMcpSecret.mockResolvedValue(secretRotationResponse(['api-key'], [SERVER_NAME, OTHER]))
mockGetMcpServer.mockResolvedValue(
serverWithCondition({
status: 'True',
diff --git a/control-ui/lib/__tests__/connectorAccess.test.ts b/control-ui/lib/__tests__/connectorAccess.test.ts
index 9907cf676..e932ef823 100644
--- a/control-ui/lib/__tests__/connectorAccess.test.ts
+++ b/control-ui/lib/__tests__/connectorAccess.test.ts
@@ -1,6 +1,12 @@
import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
import type { ConnectorAccessSummary } from '../../components/McpServerTable.types'
-import { contextNamesForConnector, mergeAccessSummaries } from '../connectorAccess'
+import type { ContextResource } from '../api'
+import {
+ contextNamesForConnector,
+ mergeAccessSummaries,
+ sortAccessPrincipals,
+} from '../connectorAccess'
function permutations<T>(items: readonly T[]): T[][] {
if (items.length <= 1) return [[...items]]
@@ -9,6 +15,23 @@ function permutations<T>(items: readonly T[]): T[][] {
)
}
+const shortString = fc.string({ maxLength: 16 })
+const principalArbitrary = fc.record({ id: shortString, label: shortString })
+const accessSummaryArbitrary: fc.Arbitrary<ConnectorAccessSummary> = fc.record({
+ agents: fc.array(principalArbitrary, { maxLength: 12 }),
+ users: fc.array(principalArbitrary, { maxLength: 12 }),
+ teams: fc.array(principalArbitrary, { maxLength: 12 }),
+})
+
+const accessGroups = ['agents', 'users', 'teams'] as const
+
+function comparePrincipals(
+ left: { id: string; label: string },
+ right: { id: string; label: string }
+) {
+ return left.label.localeCompare(right.label) || left.id.localeCompare(right.id)
+}
+
describe('mergeAccessSummaries invariants', () => {
const summaries: ConnectorAccessSummary[] = [
{
@@ -49,6 +72,82 @@ describe('mergeAccessSummaries invariants', () => {
}
expect(mergeAccessSummaries([expected, expected])).toEqual(expected)
})
+
+ it('uniquely preserves and deterministically orders arbitrary principal unions', () => {
+ fc.assert(
+ fc.property(fc.array(accessSummaryArbitrary, { maxLength: 20 }), summaries => {
+ const merged = mergeAccessSummaries(summaries)
+
+ for (const group of accessGroups) {
+ const inputIds = new Set(
+ summaries.flatMap(summary => summary[group].map(item => item.id))
+ )
+ const outputIds = merged[group].map(item => item.id)
+ expect(new Set(outputIds).size).toBe(outputIds.length)
+ expect(new Set(outputIds)).toEqual(inputIds)
+ expect(merged[group]).toEqual(sortAccessPrincipals(merged[group]))
+ expect(merged[group]).toEqual([...merged[group]].sort(comparePrincipals))
+ }
+
+ expect(mergeAccessSummaries([merged])).toEqual(merged)
+ })
+ )
+ })
+
+ it('is permutation-stable and idempotent for arbitrary summaries', () => {
+ fc.assert(
+ fc.property(
+ fc.array(accessSummaryArbitrary, { maxLength: 15 }).chain(summaries =>
+ fc
+ .shuffledSubarray(summaries, {
+ minLength: summaries.length,
+ maxLength: summaries.length,
+ })
+ .map(shuffled => ({ shuffled, summaries }))
+ ),
+ ({ shuffled, summaries }) => {
+ expect(mergeAccessSummaries(shuffled)).toEqual(mergeAccessSummaries(summaries))
+ if (summaries.length > 0) {
+ const [summary] = summaries
+ expect(mergeAccessSummaries([summary, summary])).toEqual(
+ mergeAccessSummaries([summary])
+ )
+ }
+ }
+ )
+ )
+ })
+
+ it('chooses the compare-min principal for duplicate ids regardless of order', () => {
+ fc.assert(
+ fc.property(shortString, shortString, shortString, (id, firstLabel, secondLabel) => {
+ const first = { id, label: firstLabel }
+ const second = { id, label: secondLabel }
+ const expected = [first, second].sort(comparePrincipals)[0]
+ const summary = (agents: (typeof first)[]): ConnectorAccessSummary => ({
+ agents,
+ users: [],
+ teams: [],
+ })
+
+ expect(mergeAccessSummaries([summary([first, second])]).agents).toEqual([expected])
+ expect(mergeAccessSummaries([summary([second, first])]).agents).toEqual([expected])
+ })
+ )
+ })
+
+ it('sorts arbitrary principals deterministically without mutating the input', () => {
+ fc.assert(
+ fc.property(fc.array(principalArbitrary, { maxLength: 50 }), principals => {
+ const snapshot = principals.map(principal => ({ ...principal }))
+ const expected = [...principals].sort(comparePrincipals)
+
+ expect(sortAccessPrincipals(principals)).toEqual(expected)
+ expect(sortAccessPrincipals(principals)).toEqual(sortAccessPrincipals(principals))
+ expect(principals).toEqual(snapshot)
+ })
+ )
+ })
})
describe('contextNamesForConnector invariants', () => {
@@ -74,4 +173,77 @@ describe('contextNamesForConnector invariants', () => {
}
expect(contextNamesForConnector(contexts, 'removed-from-all-contexts')).toEqual([])
})
+
+ it('returns only unique, non-blank, sorted names from arbitrary current allowlists', () => {
+ const contextArbitrary: fc.Arbitrary<ContextResource> = shortString.chain(contextName =>
+ fc.record({
+ metadata: fc.constant({ name: contextName }),
+ spec: fc.record({
+ contextId: fc.constant(contextName),
+ description: shortString,
+ mcpServers: fc.array(shortString, { maxLength: 12 }),
+ sharedFileSystems: fc.constant([]),
+ }),
+ status: fc.constant({ sharedFileSystems: [] }),
+ })
+ )
+
+ fc.assert(
+ fc.property(
+ fc.array(contextArbitrary, { maxLength: 30 }),
+ shortString,
+ (generatedContexts, connectorName) => {
+ const actual = contextNamesForConnector(generatedContexts, connectorName)
+ const expected = Array.from(
+ new Set(
+ generatedContexts
+ .filter(context => context.spec?.mcpServers.includes(connectorName))
+ .map(context => String(context.metadata?.name ?? '').trim())
+ .filter(Boolean)
+ )
+ ).sort((left, right) => left.localeCompare(right))
+
+ expect(actual).toEqual(expected)
+ expect(actual.every(contextName => contextName.trim().length > 0)).toBe(true)
+ expect(new Set(actual).size).toBe(actual.length)
+ }
+ )
+ )
+ })
+
+ it('is permutation-stable and returns none when arbitrary allowlists omit the connector', () => {
+ const namedContextArbitrary = fc.record({
+ name: shortString,
+ connectors: fc.array(shortString, { maxLength: 10 }),
+ })
+
+ fc.assert(
+ fc.property(
+ fc
+ .array(namedContextArbitrary, { maxLength: 25 })
+ .chain(entries =>
+ fc
+ .shuffledSubarray(entries, { minLength: entries.length, maxLength: entries.length })
+ .map(shuffled => ({ entries, shuffled }))
+ ),
+ shortString,
+ ({ entries, shuffled }, connectorName) => {
+ const toContexts = (items: typeof entries): ContextResource[] =>
+ items.map(({ name, connectors }) => ({
+ metadata: { name },
+ spec: { contextId: name, mcpServers: connectors },
+ }))
+ expect(contextNamesForConnector(toContexts(shuffled), connectorName)).toEqual(
+ contextNamesForConnector(toContexts(entries), connectorName)
+ )
+
+ const withoutConnector = entries.map(entry => ({
+ ...entry,
+ connectors: entry.connectors.filter(name => name !== connectorName),
+ }))
+ expect(contextNamesForConnector(toContexts(withoutConnector), connectorName)).toEqual([])
+ }
+ )
+ )
+ })
})
diff --git a/control-ui/lib/__tests__/contextMutation.test.ts b/control-ui/lib/__tests__/contextMutation.test.ts
index bd6294b69..b475ae7b9 100644
--- a/control-ui/lib/__tests__/contextMutation.test.ts
+++ b/control-ui/lib/__tests__/contextMutation.test.ts
@@ -1,4 +1,6 @@
import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
+import type { ContextSpec } from '../api'
import { buildContextUpdatePayload, contextMutationError } from '../contextMutation'
const spec = {
@@ -8,6 +10,16 @@ const spec = {
sharedFileSystems: [],
}
+const contextSpecArbitrary: fc.Arbitrary<ContextSpec> = fc.record({
+ contextId: fc.string(),
+ description: fc.option(fc.string(), { nil: undefined }),
+ mcpServers: fc.array(fc.string(), { maxLength: 20 }),
+ sharedFileSystems: fc.option(
+ fc.array(fc.record({ name: fc.string(), mountPath: fc.string() }), { maxLength: 10 }),
+ { nil: undefined }
+ ),
+})
+
describe('Context optimistic concurrency payloads', () => {
it('carries the resourceVersion from the read into the complete replacement', () => {
expect(buildContextUpdatePayload('rv-read', spec)).toEqual({
@@ -26,4 +38,49 @@ describe('Context optimistic concurrency payloads', () => {
/changed since it was loaded/i
)
})
+
+ it('round-trips arbitrary specs by reference with a trimmed non-blank version', () => {
+ fc.assert(
+ fc.property(
+ fc.string().filter(version => version.trim().length > 0),
+ contextSpecArbitrary,
+ (resourceVersion, generatedSpec) => {
+ const payload = buildContextUpdatePayload(` \t${resourceVersion}\n `, generatedSpec)
+ expect(payload).toEqual({
+ metadata: { resourceVersion: resourceVersion.trim() },
+ spec: generatedSpec,
+ })
+ expect(payload.spec).toBe(generatedSpec)
+ }
+ )
+ )
+ })
+
+ it('fails closed for arbitrary missing and whitespace-only versions', () => {
+ const blankVersion = fc.oneof(
+ fc.constant(undefined),
+ fc
+ .array(fc.constantFrom(' ', '\t', '\n', '\r'), { maxLength: 30 })
+ .map(parts => parts.join(''))
+ )
+ fc.assert(
+ fc.property(blankVersion, contextSpecArbitrary, (resourceVersion, generatedSpec) => {
+ expect(() => buildContextUpdatePayload(resourceVersion, generatedSpec)).toThrow(
+ /version is unavailable/i
+ )
+ })
+ )
+ })
+
+ it('maps arbitrary conflicts, ordinary errors, and non-errors to the promised copy', () => {
+ fc.assert(
+ fc.property(fc.string(), fc.string(), (message, fallback) => {
+ expect(contextMutationError({ status: 409, message }, fallback)).toMatch(
+ /changed since it was loaded/i
+ )
+ expect(contextMutationError(new Error(message), fallback)).toBe(message)
+ expect(contextMutationError({ status: 500, message }, fallback)).toBe(fallback)
+ })
+ )
+ })
})
diff --git a/control-ui/lib/__tests__/registryCredentialDraft.test.ts b/control-ui/lib/__tests__/registryCredentialDraft.test.ts
index 52a3b4eb5..93da094aa 100644
--- a/control-ui/lib/__tests__/registryCredentialDraft.test.ts
+++ b/control-ui/lib/__tests__/registryCredentialDraft.test.ts
@@ -1,8 +1,23 @@
import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
import {
areRequiredCredentialRowsComplete,
reconcileCredentialRows,
} from '../registryCredentialDraft'
+import type { CredentialDraftRow, RegistryCredentialKey } from '../registryCredentialDraft.types'
+
+const token = fc.stringMatching(/^[A-Z][A-Z0-9_]{0,11}$/)
+const shortString = fc.string({ maxLength: 20 })
+const schemaKeysArbitrary: fc.Arbitrary<RegistryCredentialKey[]> = fc.uniqueArray(
+ fc.record({ name: token, label: shortString }),
+ { maxLength: 12, selector: key => key.name }
+)
+const rowArbitrary: fc.Arbitrary<CredentialDraftRow> = fc.record({
+ id: shortString,
+ secretKey: fc.oneof(token, shortString),
+ value: shortString,
+ label: fc.option(shortString, { nil: undefined }),
+})
describe('registry credential drafts', () => {
const schemaKeys = [
@@ -91,4 +106,95 @@ describe('registry credential drafts', () => {
expect(areRequiredCredentialRowsComplete([...complete].reverse(), schemaKeys)).toBe(true)
expect(areRequiredCredentialRowsComplete([...complete, complete[0]], schemaKeys)).toBe(true)
})
+
+ it('places every arbitrary schema key exactly once at the front and is idempotent', () => {
+ fc.assert(
+ fc.property(
+ fc.array(rowArbitrary, { maxLength: 30 }),
+ schemaKeysArbitrary,
+ (currentRows, generatedSchemaKeys) => {
+ const reconciled = reconcileCredentialRows(currentRows, generatedSchemaKeys)
+ const schemaNames = generatedSchemaKeys.map(key => key.name)
+ const boundRows = reconciled.slice(0, schemaNames.length)
+
+ expect(boundRows.map(row => row.secretKey)).toEqual(schemaNames)
+ expect(new Set(boundRows.map(row => row.secretKey)).size).toBe(schemaNames.length)
+ expect(reconcileCredentialRows(reconciled, generatedSchemaKeys)).toEqual(reconciled)
+ }
+ )
+ )
+ })
+
+ it('preserves arbitrary uniquely-bound values and is stable under their permutation', () => {
+ fc.assert(
+ fc.property(
+ schemaKeysArbitrary.chain(generatedSchemaKeys =>
+ fc.tuple(...generatedSchemaKeys.map(() => shortString)).chain(values => {
+ const rows = generatedSchemaKeys.map((key, index) => ({
+ id: `row-${index}`,
+ secretKey: key.name,
+ value: values[index] ?? '',
+ }))
+ return fc
+ .shuffledSubarray(rows, { minLength: rows.length, maxLength: rows.length })
+ .map(shuffled => ({ generatedSchemaKeys, rows, shuffled }))
+ })
+ ),
+ ({ generatedSchemaKeys, rows, shuffled }) => {
+ const expected = reconcileCredentialRows(rows, generatedSchemaKeys)
+ expect(reconcileCredentialRows(shuffled, generatedSchemaKeys)).toEqual(expected)
+ for (const row of rows) {
+ expect(expected.find(item => item.secretKey === row.secretKey)?.value).toBe(row.value)
+ }
+ }
+ )
+ )
+ })
+
+ it('adopts at most one arbitrary unbound filled row', () => {
+ fc.assert(
+ fc.property(
+ schemaKeysArbitrary,
+ fc.uniqueArray(
+ fc.record({
+ id: shortString,
+ value: shortString.filter(value => value.trim().length > 0),
+ }),
+ { maxLength: 10, selector: row => row.id }
+ ),
+ (generatedSchemaKeys, unboundRows) => {
+ const currentRows = unboundRows.map(row => ({ ...row, secretKey: '' }))
+ const reconciled = reconcileCredentialRows(currentRows, generatedSchemaKeys)
+ const adoptedIds = new Set(currentRows.map(row => row.id))
+ const adoptedSchemaRows = reconciled
+ .slice(0, generatedSchemaKeys.length)
+ .filter(row => adoptedIds.has(row.id))
+ expect(adoptedSchemaRows.length).toBeLessThanOrEqual(1)
+ }
+ )
+ )
+ })
+
+ it('agrees with reconciled values and remains complete under arbitrary duplicate reordering', () => {
+ fc.assert(
+ fc.property(
+ fc.array(rowArbitrary, { maxLength: 30 }),
+ schemaKeysArbitrary,
+ (rows, generatedSchemaKeys) => {
+ const reconciled = reconcileCredentialRows(rows, generatedSchemaKeys)
+ const expectedComplete = reconciled
+ .slice(0, generatedSchemaKeys.length)
+ .every(row => row.value.trim().length > 0)
+ expect(areRequiredCredentialRowsComplete(reconciled, generatedSchemaKeys)).toBe(
+ expectedComplete
+ )
+
+ const duplicatedAndReordered = [...rows, ...rows].reverse()
+ expect(
+ areRequiredCredentialRowsComplete(duplicatedAndReordered, generatedSchemaKeys)
+ ).toBe(areRequiredCredentialRowsComplete(rows, generatedSchemaKeys))
+ }
+ )
+ )
+ })
})
diff --git a/control-ui/lib/__tests__/tableSort.test.ts b/control-ui/lib/__tests__/tableSort.test.ts
index e236bb941..eee34b62e 100644
--- a/control-ui/lib/__tests__/tableSort.test.ts
+++ b/control-ui/lib/__tests__/tableSort.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from 'vitest'
+import fc from 'fast-check'
import { compareNullsLast } from '../tableSort'
function permutations<T>(items: readonly T[]): T[][] {
@@ -16,6 +17,17 @@ function sortNumbersNullLast(values: Array<number | null | undefined>, direction
})
}
+const nullableInteger = fc.oneof(fc.integer(), fc.constant(null), fc.constant(undefined))
+
+function multiset(values: Array<number | null | undefined>) {
+ const counts = new Map<string, number>()
+ for (const value of values) {
+ const key = value === null ? 'null' : value === undefined ? 'undefined' : `number:${value}`
+ counts.set(key, (counts.get(key) ?? 0) + 1)
+ }
+ return [...counts.entries()].sort(([left], [right]) => left.localeCompare(right))
+}
+
describe('compareNullsLast invariants', () => {
const values = [7, null, 2, undefined, 5]
@@ -36,4 +48,62 @@ describe('compareNullsLast invariants', () => {
expect(compareNullsLast(null, undefined)).toBe(0)
expect(compareNullsLast(1, 2)).toBeNull()
})
+
+ it('keeps arbitrary nullish values last while preserving and idempotently sorting the multiset', () => {
+ fc.assert(
+ fc.property(fc.array(nullableInteger, { maxLength: 100 }), values => {
+ for (const direction of ['asc', 'desc'] as const) {
+ const sorted = sortNumbersNullLast(values, direction)
+ const firstNullish = sorted.findIndex(value => value == null)
+
+ expect(firstNullish < 0 || sorted.slice(firstNullish).every(value => value == null)).toBe(
+ true
+ )
+ expect(multiset(sorted)).toEqual(multiset(values))
+ expect(sortNumbersNullLast(sorted, direction)).toEqual(sorted)
+ expect(sortNumbersNullLast(values, direction)).toEqual(sorted)
+ }
+ })
+ )
+ })
+
+ it('has a permutation-stable non-null projection for arbitrary arrays', () => {
+ fc.assert(
+ fc.property(
+ fc
+ .array(nullableInteger, { maxLength: 50 })
+ .chain(values =>
+ fc
+ .shuffledSubarray(values, { minLength: values.length, maxLength: values.length })
+ .map(shuffled => ({ values, shuffled }))
+ ),
+ ({ values, shuffled }) => {
+ for (const direction of ['asc', 'desc'] as const) {
+ const project = (input: Array<number | null | undefined>) =>
+ sortNumbersNullLast(input, direction).filter(
+ (value): value is number => value != null
+ )
+ expect(project(shuffled)).toEqual(project(values))
+ }
+ }
+ )
+ )
+ })
+
+ it('obeys the null-delegation and antisymmetry contract for arbitrary pairs', () => {
+ fc.assert(
+ fc.property(nullableInteger, nullableInteger, (left, right) => {
+ const comparison = compareNullsLast(left, right)
+ const reverse = compareNullsLast(right, left)
+ if (left == null && right == null) {
+ expect(comparison).toBe(0)
+ } else if (left != null && right != null) {
+ expect(comparison).toBeNull()
+ expect(reverse).toBeNull()
+ } else {
+ expect(comparison).toBe(-reverse!)
+ }
+ })
+ )
+ })
})
diff --git a/control-ui/package-lock.json b/control-ui/package-lock.json
index 2dab034a7..a1107c082 100644
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-ui",
- "version": "0.1.393",
+ "version": "0.1.394",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.393",
+ "version": "0.1.394",
"dependencies": {
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
@@ -25,6 +25,7 @@
"@types/node": "^24.3.0",
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
+ "fast-check": "^4.9.0",
"jsdom": "^28.1.0",
"typescript": "^5.9.2",
"vitest": "^4.0.18"
@@ -108,7 +109,6 @@
"integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"@babel/helper-validator-identifier": "^7.28.5",
"js-tokens": "^4.0.0",
@@ -124,7 +124,6 @@
"integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=6.9.0"
}
@@ -247,6 +246,7 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=20.19.0"
},
@@ -295,32 +295,11 @@
}
],
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=20.19.0"
}
},
- "node_modules/@emnapi/core": {
- "version": "1.11.1",
- "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.11.1.tgz",
- "integrity": "sha512-RSvbQmHzdKzNsLYa/wHrbc3KN4sYLKAdPZxqiM2HATqv/SBk2/ENSHpvXGaLOMcsAyz0poEGqkmmKYG3OWiJEQ==",
- "dev": true,
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "@emnapi/wasi-threads": "1.2.2",
- "tslib": "^2.4.0"
- }
- },
- "node_modules/@emnapi/runtime": {
- "version": "1.11.1",
- "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.11.1.tgz",
- "integrity": "sha512-vgj7R3y3Wgx24IQaGPA/R6YFXLHVMOZ0uVEyIQPaWs+rd1AzfEMXlAC22FYwO1XkKR6NPsq7mUandH8oIRdZFw==",
- "license": "MIT",
- "optional": true,
- "dependencies": {
- "tslib": "^2.4.0"
- }
- },
"node_modules/@emnapi/wasi-threads": {
"version": "1.2.2",
"resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.2.tgz",
@@ -1027,6 +1006,7 @@
"integrity": "sha512-PG6q63nQg5c9rIi4/Z5lR5IVF7yU5MqmKaPOe0HSc0O2cX1fPi96sUQu5j7eo4gKCkB2AnNGoWt7y4/Xx3Kcqg==",
"devOptional": true,
"license": "Apache-2.0",
+ "peer": true,
"dependencies": {
"playwright": "1.59.1"
},
@@ -1464,8 +1444,7 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/@types/chai": {
"version": "5.2.3",
@@ -1602,6 +1581,7 @@
"integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"undici-types": "~7.16.0"
}
@@ -1623,6 +1603,7 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.28.tgz",
"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.2.2"
@@ -1634,6 +1615,7 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"dev": true,
"license": "MIT",
+ "peer": true,
"peerDependencies": {
"@types/react": "^18.0.0"
}
@@ -1841,7 +1823,6 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=8"
}
@@ -1852,7 +1833,6 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
- "peer": true,
"engines": {
"node": ">=10"
},
@@ -2327,8 +2307,7 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/entities": {
"version": "8.0.0",
@@ -2414,6 +2393,29 @@
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
+ "node_modules/fast-check": {
+ "version": "4.9.0",
+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.9.0.tgz",
+ "integrity": "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "pure-rand": "^8.0.0"
+ },
+ "engines": {
+ "node": ">=12.17.0"
+ }
+ },
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -2436,6 +2438,7 @@
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+ "dev": true,
"hasInstallScript": true,
"license": "MIT",
"optional": true,
@@ -2925,6 +2928,7 @@
"integrity": "sha512-0+MoQNYyr2rBHqO1xilltfDjV9G7ymYGlAUazgcDLQaUf8JDHbuGwsxN6U9qWaElZ4w1B2r7yEGIL3GdeW3Rug==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"@acemir/cssom": "^0.9.31",
"@asamuzakjp/dom-selector": "^6.8.1",
@@ -3259,7 +3263,6 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
- "peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@@ -4297,6 +4300,7 @@
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"dev": true,
"license": "MIT",
+ "peer": true,
"engines": {
"node": ">=12"
},
@@ -4370,7 +4374,6 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
- "peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@@ -4385,8 +4388,7 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
- "license": "MIT",
- "peer": true
+ "license": "MIT"
},
"node_modules/property-information": {
"version": "7.1.0",
@@ -4408,11 +4410,29 @@
"node": ">=6"
}
},
+ "node_modules/pure-rand": {
+ "version": "8.4.2",
+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-8.4.2.tgz",
+ "integrity": "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "individual",
+ "url": "https://github.com/sponsors/dubzzz"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fast-check"
+ }
+ ],
+ "license": "MIT"
+ },
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -4425,6 +4445,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -4472,6 +4493,7 @@
"resolved": "https://registry.npmjs.org/react-redux/-/react-redux-9.2.0.tgz",
"integrity": "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g==",
"license": "MIT",
+ "peer": true,
"dependencies": {
"@types/use-sync-external-store": "^0.0.6",
"use-sync-external-store": "^1.4.0"
@@ -4538,7 +4560,8 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
"integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==",
- "license": "MIT"
+ "license": "MIT",
+ "peer": true
},
"node_modules/redux-thunk": {
"version": "3.1.0",
@@ -5401,6 +5424,7 @@
"integrity": "sha512-7ULLwsCdYx/nRyrpiEwvqb5TFHrMVZyBt+rg/OAXT7rgj/z+DtTDyKFeLAdDkubDVDKD8jOsndmy7m55XcfUsw==",
"dev": true,
"license": "MIT",
+ "peer": true,
"dependencies": {
"lightningcss": "^1.32.0",
"picomatch": "^4.0.5",
@@ -5675,6 +5699,7 @@
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.0.tgz",
"integrity": "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA==",
"license": "ISC",
+ "peer": true,
"bin": {
"yaml": "bin.mjs"
},
diff --git a/control-ui/package.json b/control-ui/package.json
index dd8c70fc9..de62d1b8b 100644
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-ui",
- "version": "0.1.393",
+ "version": "0.1.394",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
@@ -70,6 +70,7 @@
"@types/node": "^24.3.0",
"@types/react": "^18.3.5",
"@types/react-dom": "^18.3.0",
+ "fast-check": "^4.9.0",
"jsdom": "^28.1.0",
"typescript": "^5.9.2",
"vitest": "^4.0.18"
diff --git a/control-ui/test/fixtures/__tests__/contextResource.contract.test.ts b/control-ui/test/fixtures/__tests__/contextResource.contract.test.ts
new file mode 100644
index 000000000..7ff54a976
--- /dev/null
+++ b/control-ui/test/fixtures/__tests__/contextResource.contract.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it } from 'vitest'
+import { buildContextList, buildContextResource } from '../contextResource'
+
+describe('Context producer fixture contract', () => {
+ it('locks the exact control-api Context list wire shape', () => {
+ const context = buildContextResource({
+ metadata: {
+ name: 'research',
+ namespace: 'mcp-server',
+ resourceVersion: 'rv-context-read',
+ },
+ spec: {
+ contextId: 'research',
+ description: 'Research tools',
+ mcpServers: ['search'],
+ sharedFileSystems: [{ name: 'docs', mountPath: '/docs' }],
+ },
+ status: { sharedFileSystems: [] },
+ })
+
+ expect(buildContextList([context])).toEqual({
+ items: [
+ {
+ metadata: {
+ name: 'research',
+ namespace: 'mcp-server',
+ resourceVersion: 'rv-context-read',
+ },
+ spec: {
+ contextId: 'research',
+ description: 'Research tools',
+ mcpServers: ['search'],
+ sharedFileSystems: [{ name: 'docs', mountPath: '/docs' }],
+ },
+ status: { sharedFileSystems: [] },
+ },
+ ],
+ })
+ expect(Object.keys(context).sort()).toEqual(['metadata', 'spec', 'status'])
+ expect(Object.keys(context.metadata).sort()).toEqual(['name', 'namespace', 'resourceVersion'])
+ })
+})
diff --git a/control-ui/test/fixtures/__tests__/secretSummary.contract.test.ts b/control-ui/test/fixtures/__tests__/secretSummary.contract.test.ts
new file mode 100644
index 000000000..407918bec
--- /dev/null
+++ b/control-ui/test/fixtures/__tests__/secretSummary.contract.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { buildSecretList, buildSecretSummary } from '../secretSummary'
+
+describe('Secret producer fixture contract', () => {
+ it('locks the exact control-api Secret list wire shape without sensitive fields', () => {
+ const secret = buildSecretSummary({ name: 's1', keys: ['openai-api-key'] })
+
+ expect(buildSecretList([secret])).toEqual({
+ items: [{ name: 's1', keys: ['openai-api-key'] }],
+ })
+ expect(Object.keys(secret).sort()).toEqual(['keys', 'name'])
+ expect(secret).not.toHaveProperty('value')
+ expect(secret).not.toHaveProperty('values')
+ expect(secret).not.toHaveProperty('metadata')
+ })
+})
diff --git a/control-ui/test/fixtures/contextResource.ts b/control-ui/test/fixtures/contextResource.ts
new file mode 100644
index 000000000..45370d46f
--- /dev/null
+++ b/control-ui/test/fixtures/contextResource.ts
@@ -0,0 +1,50 @@
+import type { ContextSharedFileSystemRef, ContextSharedFileSystemStatus } from '../../lib/api'
+
+export type ProducerContextResource = {
+ metadata: {
+ name: string
+ namespace: string
+ resourceVersion: string
+ }
+ spec: {
+ contextId: string
+ description: string
+ mcpServers: string[]
+ sharedFileSystems: ContextSharedFileSystemRef[]
+ }
+ status: {
+ sharedFileSystems: ContextSharedFileSystemStatus[]
+ }
+}
+
+export type ContextResourceOverrides = {
+ metadata?: Partial<ProducerContextResource['metadata']>
+ spec?: Partial<ProducerContextResource['spec']>
+ status?: Partial<ProducerContextResource['status']>
+}
+
+export function buildContextResource(
+ overrides: ContextResourceOverrides = {}
+): ProducerContextResource {
+ const name = overrides.metadata?.name ?? overrides.spec?.contextId ?? 'research'
+ return {
+ metadata: {
+ name,
+ namespace: overrides.metadata?.namespace ?? 'mcp-server',
+ resourceVersion: overrides.metadata?.resourceVersion ?? 'rv-context-read',
+ },
+ spec: {
+ contextId: overrides.spec?.contextId ?? name,
+ description: overrides.spec?.description ?? '',
+ mcpServers: [...(overrides.spec?.mcpServers ?? [])],
+ sharedFileSystems: [...(overrides.spec?.sharedFileSystems ?? [])],
+ },
+ status: {
+ sharedFileSystems: [...(overrides.status?.sharedFileSystems ?? [])],
+ },
+ }
+}
+
+export function buildContextList(items: readonly ProducerContextResource[] = []) {
+ return { items: [...items] }
+}
diff --git a/control-ui/test/fixtures/secretSummary.ts b/control-ui/test/fixtures/secretSummary.ts
new file mode 100644
index 000000000..15290542c
--- /dev/null
+++ b/control-ui/test/fixtures/secretSummary.ts
@@ -0,0 +1,15 @@
+export type ProducerSecretSummary = {
+ name: string
+ keys: string[]
+}
+
+export function buildSecretSummary(input: {
+ name: string
+ keys?: readonly string[]
+}): ProducerSecretSummary {
+ return { name: input.name, keys: [...(input.keys ?? [])] }
+}
+
+export function buildSecretList(items: readonly ProducerSecretSummary[] = []) {
+ return { items: [...items] }
+}
diff --git a/control-ui/vitest.config.ts b/control-ui/vitest.config.ts
index 6f274125b..87699ccfe 100644
--- a/control-ui/vitest.config.ts
+++ b/control-ui/vitest.config.ts
@@ -24,6 +24,7 @@ export default defineConfig({
'lib/**/__tests__/**/*.{test,spec}.{ts,tsx}',
'lib/__tests__/**/*.{test,spec}.{ts,tsx}',
'components/__tests__/**/*.{test,spec}.{ts,tsx}',
+ 'test/**/__tests__/**/*.{test,spec}.{ts,tsx}',
],
exclude: ['node_modules', '.next'],
},
diff --git a/docs/features/control-ui-contract-test-hardening.md b/docs/features/control-ui-contract-test-hardening.md
new file mode 100644
index 000000000..7b4643a49
--- /dev/null
+++ b/docs/features/control-ui-contract-test-hardening.md
@@ -0,0 +1,68 @@
+# Control UI Contract Test Hardening — Mini-spec
+
+> **Status:** Pre-implementation design record for PR #298.
+>
+> **Scope:** Test methodology and test fixtures in `control-ui`. Production
+> behavior and API wire contracts do not change.
+
+## Problem
+
+The control UI has deterministic merge, sorting, credential reconciliation, and
+optimistic-concurrency helpers. Its current tests use hand-picked examples, so
+they do not exercise the broader input domain. Several consumer tests also
+repeat Context and Secret API response literals, allowing those fixtures to
+drift independently of the producer contracts pinned in `control-api` tests.
+
+## Design decisions
+
+### Generated invariant coverage
+
+`fast-check` is a `control-ui` development dependency. Existing example tests
+remain as readable regressions; generated properties supplement them.
+
+The locked properties are:
+
+- Null-last sorting preserves the input multiset, keeps nullish values last in
+ both directions, is deterministic and idempotent, and delegates comparisons
+ between two non-null values.
+- Connector access merging is unique by principal ID, union-complete,
+ deterministically sorted by label then ID, permutation-stable, and idempotent.
+ Duplicate IDs deterministically retain the minimum principal by that order.
+- Connector Context names come only from current Context allowlists, are
+ non-blank, unique, sorted, and independent of Context input order.
+- Credential reconciliation emits each schema key once at the front in schema
+ order, preserves already-bound values, adopts at most one unbound value,
+ remains stable for uniquely bound rows, and agrees with required-field
+ completeness after reconciliation.
+- Context update payloads preserve the exact spec reference and a trimmed,
+ non-blank `resourceVersion`. Missing versions fail closed. HTTP 409 errors map
+ to the stale-write conflict copy; other errors retain their message or use the
+ caller fallback.
+
+### Producer-shaped consumer fixtures
+
+Two shared factories under `control-ui/test/fixtures` are the only place UI
+tests construct these producer response shapes:
+
+- Context resources contain `metadata.name`, `metadata.namespace`,
+ `metadata.resourceVersion`, the complete Context `spec`, and `status`.
+- Secret summaries contain only `name` and `keys`; they never contain values or
+ Kubernetes metadata.
+
+Consumer tests import these factories instead of hand-writing list responses.
+Contract-lock tests assert the factories' complete key sets against the wire
+shapes pinned by `control-api/test/routes.resources.test.ts` and
+`control-api/test/routes.secrets.test.ts`.
+
+## Validation
+
+1. Run the four generated-property test files directly.
+2. Run both fixture contract-lock tests.
+3. Run every migrated Context and Secret consumer test.
+4. Run full `control-ui` TypeScript checking and the complete Vitest suite.
+
+## Non-goals
+
+- Moving serializers across the `control-api` and `control-ui` package boundary.
+- Changing Context or Secret production response formats.
+- Changing the behavior of the four helper groups.