Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(control-ui): R3-B1 derive guardrail fixtures from producers
Ma41602855977
diff --git a/control-ui/app/guardrails/[name]/__tests__/page.test.tsx b/control-ui/app/guardrails/[name]/__tests__/page.test.tsxindex b991eb8e4..c2a266cf4 100644--- a/control-ui/app/guardrails/[name]/__tests__/page.test.tsx+++ b/control-ui/app/guardrails/[name]/__tests__/page.test.tsx@@ -1,6 +1,7 @@import type { ReactNode } from 'react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { buildGuardrailDetailScenario } from '../../../../test/fixtures/guardrailProducer'import GuardrailTabPage from '../[tab]/page'import GuardrailDetailPage from '../page'@@ -45,19 +46,9 @@ vi.mock('@components/DashboardLayout', () => ({beforeEach(() => {vi.clearAllMocks()navigation.params.tab = 'details'- api.getLlmHook.mockResolvedValue({- metadata: { name: 'sample-hook' },- spec: { path: '/check', lifecyclePoints: ['preCall'] },- status: { conditions: [{ type: 'Ready', status: 'True' }] },- })- api.getHosts.mockResolvedValue({- items: [- {- metadata: { name: 'sample-agent' },- spec: { guardrails: { hooks: { preCall: [{ id: 'sample-hook' }] } } },- },- ],- })+ const { hook, hosts } = buildGuardrailDetailScenario()+ api.getLlmHook.mockResolvedValue(hook)+ api.getHosts.mockResolvedValue(hosts)})afterEach(cleanup)diff --git a/control-ui/e2e/guardrail-tab-navigation.spec.ts b/control-ui/e2e/guardrail-tab-navigation.spec.tsindex b2391b9cd..e06391178 100644--- a/control-ui/e2e/guardrail-tab-navigation.spec.ts+++ b/control-ui/e2e/guardrail-tab-navigation.spec.ts@@ -1,41 +1,50 @@import { expect, test } from '@playwright/test'+import { buildGuardrailDetailScenario } from '../test/fixtures/guardrailProducer'if (process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH) {test.use({ launchOptions: { executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH } })}-const hook = {- metadata: { name: 'sample-hook' },- spec: { path: '/check', lifecyclePoints: ['preCall'], failMode: 'open' },- status: { conditions: [{ type: 'Ready', status: 'True' }] },-}+const scenario = buildGuardrailDetailScenario()+let unexpectedApiPaths: string[] = []test.beforeEach(async ({ page }) => {+ unexpectedApiPaths = []await page.route('**/control-api/**', async route => {const path = new URL(route.request().url()).pathname- const body = path.endsWith('/api/v1/admin/auth/me')- ? { me: { id: 'admin-1', username: 'admin', email: '[email protected]' } }- : path.endsWith('/api/v1/admin/llm-hooks/sample-hook')- ? hook- : path.endsWith('/api/v1/admin/hosts')- ? {- items: [- {- metadata: { name: 'sample-agent' },- spec: { guardrails: { hooks: { preCall: [{ id: 'sample-hook' }] } } },- },- ],- }- : path.endsWith('/api/v1/admin/control-admin-bridge/status')- ? {- admin: { id: 'admin-1', email: '[email protected]', username: 'admin' },- member: { id: 'member-1', email: '[email protected]' },- }- : {}+ let body: unknown+ if (path === '/control-api/api/v1/admin/auth/me') {+ body = { me: { id: 'admin-1', username: 'admin', email: '[email protected]' } }+ } else if (path === '/control-api/api/v1/admin/llm-hooks/sample-hook') {+ body = scenario.hook+ } else if (path === '/control-api/api/v1/admin/hosts') {+ body = scenario.hosts+ } else if (path === '/control-api/api/v1/admin/settings/bridge-status') {+ body = {+ admin: {+ id: 'admin-1',+ username: 'admin',+ email: '[email protected]',+ emailConfirmed: true,+ pendingEmailChange: null,+ },+ member: { id: 'member-1', email: '[email protected]' },+ }+ } else if (path === '/control-api/api/v1/admin/registry/publish-scope') {+ body = { scope: null, curator: false, orgName: null }+ } else {+ unexpectedApiPaths.push(path)+ await route.fulfill({ status: 500, body: `Unexpected API request: ${path}` })+ return+ }await route.fulfill({ contentType: 'application/json', body: JSON.stringify(body) })})})+test.afterEach(() => {+ expect(unexpectedApiPaths).toEqual([])+})+test('guardrail tab links support deep links and browser Back', async ({ page }) => {await page.goto('/guardrails/sample-hook/agents')await expect(page.getByRole('tab', { name: 'Agents with access' })).toHaveAttribute(diff --git a/control-ui/test/fixtures/__tests__/guardrailProducer.contract.test.ts b/control-ui/test/fixtures/__tests__/guardrailProducer.contract.test.tsnew file mode 100644index 000000000..06413256c--- /dev/null+++ b/control-ui/test/fixtures/__tests__/guardrailProducer.contract.test.ts@@ -0,0 +1,39 @@+import { describe, expect, it } from 'vitest'+import { buildGuardrailDetailScenario } from '../guardrailProducer'++describe('guardrail detail producer fixture', () => {+ it('tracks the Control API registry payload, Host reference, and HCC condition', () => {+ const { hook, hosts } = buildGuardrailDetailScenario()++ expect(hook.metadata).toMatchObject({+ name: 'sample-hook',+ namespace: 'llm-hooks',+ resourceVersion: 'rv-hook-read',+ })+ expect(hook.spec).toEqual({+ target: { service: { name: 'sample-hook-service', namespace: 'llm-hooks', port: 8080 } },+ path: '/check',+ lifecyclePoints: ['preCall'],+ order: 100,+ failMode: 'open',+ })+ expect(hook.status?.conditions).toEqual([+ {+ type: 'Ready',+ status: 'True',+ reason: 'NoWorkload',+ message: 'No workload deployed for service/remote target',+ lastTransitionTime: '2026-01-01T00:00:00.000Z',+ observedGeneration: 1,+ },+ ])+ expect(hosts.items).toHaveLength(1)+ expect(hosts.items[0].metadata).toMatchObject({+ name: 'sample-agent',+ namespace: 'mcp-host',+ })+ expect(hosts.items[0].spec?.guardrails).toEqual({+ hooks: { preCall: [{ id: 'sample-hook' }] },+ })+ })+})diff --git a/control-ui/test/fixtures/guardrailProducer.ts b/control-ui/test/fixtures/guardrailProducer.tsnew file mode 100644index 000000000..c2073dcde--- /dev/null+++ b/control-ui/test/fixtures/guardrailProducer.ts@@ -0,0 +1,190 @@+import { readFileSync } from 'node:fs'+import path from 'node:path'+import ts from 'typescript'+import type { HostResource, LlmHookCondition, LlmHookResource, LlmHookStatus } from '../../lib/api'+import { materializeHostResource } from './contextResource'++const root = path.resolve(__dirname, '../../..')++function readProducer(relativePath: string): ts.SourceFile {+ const filePath = path.join(root, relativePath)+ return ts.createSourceFile(filePath, readFileSync(filePath, 'utf8'), ts.ScriptTarget.Latest, true)+}++function compile<T>(body: string): T {+ const javascript = ts.transpileModule(body, {+ compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.None },+ }).outputText+ return new Function(`${javascript}\nreturn produce;`)() as T+}++function registryHookProducer(): (name: string) => LlmHookResource {+ const source = readProducer('control-api/src/routes/admin/registry.ts')+ const blocks: ts.Block[] = []+ let resourcePayload: ts.Expression | undefined++ function visit(node: ts.Node): void {+ if (ts.isBlock(node)) {+ const names = node.statements.map(statement =>+ ts.isVariableStatement(statement)+ ? statement.declarationList.declarations[0]?.name.getText(source)+ : undefined+ )+ if (names.includes('targetSpec') && names.includes('hookSpec')) blocks.push(node)+ }+ if (+ ts.isCallExpression(node) &&+ node.expression.getText(source) === 'gateway.createResource' &&+ node.arguments[0]?.getText(source) === "'llmhooks'"+ ) {+ resourcePayload = node.arguments[1]+ }+ ts.forEachChild(node, visit)+ }+ visit(source)++ if (blocks.length !== 1 || !resourcePayload || !ts.isObjectLiteralExpression(resourcePayload)) {+ throw new Error('Registry LlmHook producer changed; rederive the frontend fixture')+ }+ const block = blocks[0]+ const names = block.statements.map(statement =>+ ts.isVariableStatement(statement)+ ? statement.declarationList.declarations[0]?.name.getText(source)+ : undefined+ )+ const first = names.indexOf('targetSpec')+ const last = names.indexOf('hookSpec')+ if (first < 0 || last <= first) {+ throw new Error('Registry LlmHook spec construction changed')+ }++ const specStatements = block.statements+ .slice(first, last + 1)+ .map(statement => statement.getText(source))+ .join('\n')+ const buildSpec = compile<(hookMeta: unknown, body: unknown) => Record<string, unknown>>(+ `function produce(hookMeta, body) {+ const image = undefined, secretCreated = false, hasEgress = false, attachPullSecret = false;+ const failMode = 'open', capabilities = [];+ ${specStatements}+ return hookSpec;+ }`+ )+ const buildPayload = compile<+ (+ crName: string,+ registryLabels: Record<string, string>,+ registryAnnotations: Record<string, string>,+ hookSpec: Record<string, unknown>+ ) => LlmHookResource+ >(+ `const produce = (crName, registryLabels, registryAnnotations, hookSpec) =>+ (${resourcePayload.getText(source)});`+ )++ return name => {+ const hookMeta = {+ target: { service: { name: 'sample-hook-service', namespace: 'llm-hooks', port: 8080 } },+ path: '/check',+ lifecyclePoints: ['preCall'],+ }+ const spec = buildSpec(hookMeta, { order: 100 })+ const payload = buildPayload(name, {}, {}, spec)+ return {+ ...payload,+ metadata: { ...payload.metadata, namespace: 'llm-hooks', resourceVersion: 'rv-hook-read' },+ status: hccReadyStatus(),+ }+ }+}++function hostHookReferenceProducer(): (hookId: string) => { id: string; digest?: string } {+ const source = readProducer('control-api/src/services/hostGuardrailRefs.ts')+ let reference: ts.Expression | undefined++ function visit(node: ts.Node): void {+ if (+ ts.isCallExpression(node) &&+ node.expression.getText(source) === 'arr.push' &&+ node.arguments.length === 1 &&+ ts.isObjectLiteralExpression(node.arguments[0])+ ) {+ reference = node.arguments[0]+ }+ ts.forEachChild(node, visit)+ }+ visit(source)+ if (!reference) {+ throw new Error('Control API Host guardrail reference producer changed')+ }+ const produce = compile<(hookId: string, digest: undefined) => { id: string; digest?: string }>(+ `const produce = (hookId, digest) => (${reference.getText(source)});`+ )+ return hookId => produce(hookId, undefined)+}++function hccReadyStatus(): LlmHookStatus {+ const source = readProducer('host-context-controller/src/llmHookReconciler.ts')+ let conditionFactory: ts.FunctionDeclaration | undefined+ let mergedCondition: ts.Expression | undefined++ function visit(node: ts.Node): void {+ if (ts.isFunctionDeclaration(node) && node.name?.text === 'condition') {+ conditionFactory = node+ }+ if (ts.isVariableDeclaration(node) && node.name.getText(source) === 'merged') {+ mergedCondition = node.initializer+ }+ ts.forEachChild(node, visit)+ }+ visit(source)+ if (!conditionFactory || !mergedCondition || !ts.isObjectLiteralExpression(mergedCondition)) {+ throw new Error('HCC LlmHook condition producer changed')+ }+ const condition = compile<+ (+ status: 'True',+ reason: 'NoWorkload',+ message: string+ ) => Omit<LlmHookCondition, 'lastTransitionTime'>+ >(`${conditionFactory.getText(source)}\nconst produce = condition;`)+ const merge = compile<+ (+ condition: Omit<LlmHookCondition, 'lastTransitionTime'>,+ now: string,+ hook: { generation: number }+ ) => LlmHookCondition+ >(+ `const produce = (condition, now, hook) => {+ const lastTransitionTime = now;+ return (${mergedCondition.getText(source)});+ };`+ )+ const ready = condition('True', 'NoWorkload', 'No workload deployed for service/remote target')+ return { conditions: [merge(ready, '2026-01-01T00:00:00.000Z', { generation: 1 })] }+}++const buildHook = registryHookProducer()+const buildHostHookReference = hostHookReferenceProducer()++/** Registry install payload, Control API Host mutation, and HCC status wire shape. */+export function buildGuardrailDetailScenario(+ hookName = 'sample-hook',+ hostName = 'sample-agent'+): { hook: LlmHookResource; hosts: { items: HostResource[] } } {+ const hook = buildHook(hookName)+ const host = materializeHostResource(+ {+ metadata: { name: hostName },+ spec: {+ host: hostName,+ contextRef: 'default',+ secretRef: 'sample-secret',+ channels: [],+ model: { provider: 'openai', name: 'sample-model' },+ },+ },+ { spec: { guardrails: { hooks: { preCall: [buildHostHookReference(hookName)] } } } }+ )+ return { hook, hosts: { items: [host] } }+}