Skip to content

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

TypeScript

Merge origin/dev into feat/teams-setup-prereqs

Jose Ramirez89847b7899d5
diff --cc channel-reader/package-lock.json
index 274d0c9ac,a2bb6529a..1c9eee879
--- a/channel-reader/package-lock.json
+++ b/channel-reader/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-channel-reader",
- "version": "0.1.104",
- "version": "0.1.101",
++ "version": "0.1.105",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-channel-reader",
- "version": "0.1.104",
- "version": "0.1.101",
++ "version": "0.1.105",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@kubernetes/client-node": "^1.0.0",
diff --cc channel-reader/package.json
index 74f0bd3ea,92b6e2a83..d1dcd22a4
--- a/channel-reader/package.json
+++ b/channel-reader/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-channel-reader",
- "version": "0.1.104",
- "version": "0.1.101",
++ "version": "0.1.105",
"description": "Watches CommunicationChannel CRDs and fetches messages from Telegram, Email, and Slack",
"main": "dist/main.js",
"engines": {
diff --cc control-api/test/middleware.externalGfsRateLimit.test.ts
index 000000000,58087ce1a..2efc419d7
mode 000000,100644..100644
--- a/control-api/test/middleware.externalGfsRateLimit.test.ts
+++ b/control-api/test/middleware.externalGfsRateLimit.test.ts
@@@ -1,0 -1,461 +1,446 @@@
+ import { beforeEach, describe, expect, it, vi } from 'vitest'
+ import express from 'express'
+ import { createHash } from 'node:crypto'
+ import request from 'supertest'
+ import {
+ externalGfsOperationFor,
+ externalGfsPreResolutionRateLimit,
+ externalGfsResolvedOperationRateLimit,
+ externalGfsSourceIp,
+ } from '../src/middleware/externalGfsRateLimit.js'
+
+ const checkAndIncrement = vi.hoisted(() => vi.fn())
+ const metrics = vi.hoisted(() => ({
+ externalGfsRateLimitRequestsTotal: { inc: vi.fn() },
+ externalGfsRateLimitDurationSeconds: { observe: vi.fn() },
+ }))
+ const logger = vi.hoisted(() => ({
+ rootLogger: { debug: vi.fn(), warn: vi.fn() },
+ }))
+
+ vi.mock('../src/config.js', () => ({
+ config: {
+ externalGfsIngressRlPerMin: 1800,
+ externalGfsTokenUserRlPerMin: 10,
+ externalGfsTokenIpRlPerMin: 600,
+ externalGfsIpRlPerMin: 1200,
+ externalGfsReadRlPerMin: 120,
+ externalGfsOperationRlPerMin: 30,
+ },
+ }))
+ vi.mock('../src/services/rateLimiterService.js', () => ({
+ checkAndIncrement: (...args: unknown[]) => checkAndIncrement(...args),
+ }))
+ vi.mock('../src/observability/metrics.js', () => metrics)
+ vi.mock('../src/observability/logger.js', () => logger)
+
+ const DESKTOP_USER_ID = '11111111-aaaa-4aaa-8aaa-111111111111'
+ const CONTROL_ADMIN_ID = '22222222-bbbb-4bbb-8bbb-222222222222'
+ const RESOURCE_ID = '33333333-cccc-4ccc-8ccc-333333333333'
+
+ function allowed(limit = 30, remaining = limit - 1) {
+ return {
+ allowed: true,
+ remaining,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: limit - remaining,
+ }
+ }
+
+ function denied(limit = 30) {
+ return {
+ allowed: false,
+ remaining: 0,
+ resetMs: Date.now() + 30_000,
+ windowStartMs: Date.now(),
+ count: limit + 1,
+ }
+ }
+
+ function buildApp() {
+ const resolver = vi.fn()
+ const handler = vi.fn()
+ const app = express()
+
+ app.use('/external/gfs', (req, _res, next) => {
+ ;(req as typeof req & { externalAuth?: { userId: string } }).externalAuth = {
+ userId: DESKTOP_USER_ID,
+ }
+ next()
+ })
+ app.use('/external/gfs', externalGfsPreResolutionRateLimit)
+ app.use('/external/gfs', (req, _res, next) => {
+ resolver()
+ ;(
+ req as typeof req & {
+ gfsAuthority?: {
+ kind: 'linked-admin'
+ tokenSubject: string
+ desktopUserId: string
+ controlAdminId: string
+ authoritySource: 'initial_setup'
+ }
+ }
+ ).gfsAuthority = {
+ kind: 'linked-admin',
+ tokenSubject: CONTROL_ADMIN_ID,
+ desktopUserId: DESKTOP_USER_ID,
+ controlAdminId: CONTROL_ADMIN_ID,
+ authoritySource: 'initial_setup',
+ }
+ next()
+ })
+ app.use('/external/gfs', externalGfsResolvedOperationRateLimit)
+ app.use('/external/gfs', (_req, res) => {
+ handler()
+ res.status(204).end()
+ })
+
+ return { app, resolver, handler }
+ }
+
+ describe('external GFS rate boundary', () => {
+ beforeEach(() => {
+ checkAndIncrement.mockReset()
+ checkAndIncrement.mockResolvedValue(allowed())
+ metrics.externalGfsRateLimitRequestsTotal.inc.mockReset()
+ metrics.externalGfsRateLimitDurationSeconds.observe.mockReset()
+ logger.rootLogger.debug.mockReset()
+ logger.rootLogger.warn.mockReset()
+ })
+
+ it.each([
+ ['POST', '/token', 'token', '/external/gfs/token'],
+ ['GET', '/capabilities', 'resource', '/external/gfs/capabilities'],
+ ['POST', '/uploads', 'resource-mutation', '/external/gfs/uploads'],
- [
- 'HEAD',
- `/uploads/${RESOURCE_ID}`,
- 'resource',
- '/external/gfs/uploads/:id',
- ],
- [
- 'GET',
- `/uploads/${RESOURCE_ID}/status`,
- 'resource',
- '/external/gfs/uploads/:id/status',
- ],
++ ['HEAD', `/uploads/${RESOURCE_ID}`, 'resource', '/external/gfs/uploads/:id'],
++ ['GET', `/uploads/${RESOURCE_ID}/status`, 'resource', '/external/gfs/uploads/:id/status'],
+ [
+ 'PUT',
+ `/uploads/${RESOURCE_ID}/parts/0`,
+ 'resource-mutation',
+ '/external/gfs/uploads/:id/parts/:part',
+ ],
+ [
+ 'POST',
+ `/uploads/${RESOURCE_ID}/complete`,
+ 'resource-mutation',
+ '/external/gfs/uploads/:id/:action',
+ ],
- [
- 'DELETE',
- `/uploads/${RESOURCE_ID}`,
- 'resource-mutation',
- '/external/gfs/uploads/:id',
- ],
++ ['DELETE', `/uploads/${RESOURCE_ID}`, 'resource-mutation', '/external/gfs/uploads/:id'],
+ ['GET', '/resolve', 'resource', '/external/gfs/resolve'],
+ ['GET', '/resources', 'resource', '/external/gfs/resources'],
+ [
+ 'GET',
+ `/resources/${RESOURCE_ID}/children`,
+ 'resource',
+ '/external/gfs/resources/:id/children',
+ ],
+ [
+ 'GET',
+ `/resources/${RESOURCE_ID}/affordances`,
+ 'resource',
+ '/external/gfs/resources/:id/affordances',
+ ],
+ ['GET', `/proxy/${RESOURCE_ID}`, 'proxy-read', '/external/gfs/proxy/:rid'],
+ ['PATCH', `/resources/${RESOURCE_ID}`, 'resource-mutation', '/external/gfs/resources/:id'],
+ [
+ 'POST',
+ `/resources/${RESOURCE_ID}/children`,
+ 'resource-mutation',
+ '/external/gfs/resources/:id/children',
+ ],
+ [
+ 'PUT',
+ `/resources/${RESOURCE_ID}/content`,
+ 'resource-mutation',
+ '/external/gfs/resources/:id/content',
+ ],
+ ['DELETE', `/resources/${RESOURCE_ID}`, 'resource-mutation', '/external/gfs/resources/:id'],
+ ['GET', '/grants', 'grants-read', '/external/gfs/grants'],
+ ['PUT', '/grants', 'grants-mutation', '/external/gfs/grants'],
+ ['DELETE', `/grants/${RESOURCE_ID}`, 'grants-mutation', '/external/gfs/grants/:id'],
+ ['GET', '/shares', 'shares-read', '/external/gfs/shares'],
+ ['POST', '/shares', 'shares-mutation', '/external/gfs/shares'],
+ ['DELETE', `/shares/${RESOURCE_ID}`, 'shares-mutation', '/external/gfs/shares/:id'],
+ ] as const)('classifies %s /external/gfs%s as %s', (method, path, operationClass, route) => {
+ expect(
+ externalGfsOperationFor({
+ method,
+ baseUrl: '/external/gfs',
+ path,
+ originalUrl: `/external/gfs${path}`,
+ })
+ ).toEqual({ operationClass, route })
+ })
+
+ it('keeps unclassified paths outside the authority resolver', async () => {
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .post('/external/gfs/unclassified')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(404)
+ expect(response.body).toEqual({ error: 'Not Found' })
+ expect(checkAndIncrement).not.toHaveBeenCalled()
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it('rejects before resolution and handler work when the pre-resolution session bucket is exhausted', async () => {
+ checkAndIncrement.mockResolvedValueOnce(denied(120))
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(429)
+ expect(response.headers['x-ratelimit-limit']).toBe('120')
+ expect(checkAndIncrement).toHaveBeenCalledWith(
+ expect.stringMatching(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/),
+ 120
+ )
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ expect(metrics.externalGfsRateLimitRequestsTotal.inc).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operation_class: 'resource',
+ route: '/external/gfs/resources',
+ outcome: 'denied',
+ phase: 'pre-resolution',
+ authority_resolution_avoided: 'true',
+ })
+ )
+ expect(metrics.externalGfsRateLimitDurationSeconds.observe).toHaveBeenCalledWith(
+ expect.objectContaining({ phase: 'pre-resolution', outcome: 'denied' }),
+ expect.any(Number)
+ )
+ expect(logger.rootLogger.warn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationClass: 'resource',
+ route: '/external/gfs/resources',
+ outcome: 'denied',
+ phase: 'pre-resolution',
+ hashedKey: expect.stringMatching(/^[0-9a-f]{64}$/),
+ latencyMs: expect.any(Number),
+ authorityResolutionAvoided: true,
+ }),
+ 'external GFS rate limit denied'
+ )
+ })
+
+ it('enforces the fixed 10/min user ceiling before minting a GFS token', async () => {
+ checkAndIncrement.mockResolvedValueOnce(denied(10))
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(429)
+ expect(response.headers['x-ratelimit-limit']).toBe('10')
+ expect(checkAndIncrement).toHaveBeenCalledWith(`gfs-ext:pre:token:user:${DESKTOP_USER_ID}`, 10)
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it('enforces the fixed 600/min token source-IP ceiling after an allowed token user bucket', async () => {
+ checkAndIncrement.mockResolvedValueOnce(allowed(600, 599)).mockResolvedValueOnce(denied(600))
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(429)
+ expect(response.headers['x-ratelimit-limit']).toBe('600')
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 1,
+ `gfs-ext:pre:token:user:${DESKTOP_USER_ID}`,
+ 10
+ )
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 2,
+ expect.stringMatching(/^gfs-ext:pre:token:ip:[0-9a-f]{64}$/),
+ 600
+ )
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it('uses the authenticated external-rest client IP before the funnel-appended peer address', async () => {
+ checkAndIncrement.mockResolvedValueOnce(allowed(9)).mockResolvedValueOnce(denied())
+ const { app } = buildApp()
+ const clientIp = '203.0.113.42'
+ const clientIpDigest = createHash('sha256').update(clientIp).digest('hex')
+
+ const response = await request(app)
+ .post('/external/gfs/token')
+ .set('x-user-session-token', 'session-one')
+ .set('x-forwarded-for', `${clientIp}, 10.42.0.18`)
+
+ expect(response.status).toBe(429)
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 2,
+ `gfs-ext:pre:token:ip:${clientIpDigest}`,
+ 600
+ )
+ })
+
+ it('uses only a valid first forwarded IP and rejects a spoofed first fragment', () => {
+ const requestWithSpoofedForwarding = {
+ header: (name: string) =>
+ name.toLowerCase() === 'x-forwarded-for' ? 'not-an-ip, 198.51.100.99' : undefined,
+ ip: '203.0.113.41',
+ socket: { remoteAddress: '10.42.0.18' },
+ } as unknown as import('express').Request
+
+ expect(externalGfsSourceIp(requestWithSpoofedForwarding)).toBe('203.0.113.41')
+ })
+
+ it('uses distinct session, source-IP, and effective-actor buckets for each operation class', async () => {
+ const { app } = buildApp()
+
+ await request(app).get('/external/gfs/resources').set('x-user-session-token', 'session-one')
+ await request(app)
+ .get(`/external/gfs/proxy/${RESOURCE_ID}`)
+ .set('x-user-session-token', 'session-two')
+
+ const keys = checkAndIncrement.mock.calls.map(call => String(call[0]))
+ const limits = checkAndIncrement.mock.calls.map(call => Number(call[1]))
+ expect(keys).toContainEqual(
+ expect.stringMatching(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/)
+ )
+ expect(keys).toContainEqual(expect.stringMatching(/^gfs-ext:pre:resource:ip:[0-9a-f]{64}$/))
+ expect(keys).toContainEqual(expect.stringMatching(/^gfs-ext:pre:ip:[0-9a-f]{64}$/))
+ expect(keys).toContain(`gfs-ext:resolved:resource:actor:linked-admin:${CONTROL_ADMIN_ID}`)
+ expect(keys).toContainEqual(
+ expect.stringMatching(/^gfs-ext:pre:proxy-read:session:[0-9a-f]{64}$/)
+ )
+ expect(keys).toContainEqual(expect.stringMatching(/^gfs-ext:pre:proxy-read:ip:[0-9a-f]{64}$/))
+ expect(keys).toContain(`gfs-ext:resolved:proxy-read:actor:linked-admin:${CONTROL_ADMIN_ID}`)
+ expect(limits.filter(limit => limit === 120).length).toBe(6)
+ expect(limits.filter(limit => limit === 1200).length).toBe(2)
+ expect(limits.filter(limit => limit === 30).length).toBe(0)
+ })
+
+ it('keeps read and mutation budgets independent at every limiter phase', async () => {
+ const { app } = buildApp()
+
+ await request(app).get('/external/gfs/resources').set('x-user-session-token', 'session-read')
+ await request(app)
+ .patch(`/external/gfs/resources/${RESOURCE_ID}`)
+ .set('x-user-session-token', 'session-mutation')
+
+ const calls = checkAndIncrement.mock.calls.map(call => [String(call[0]), Number(call[1])])
+ expect(calls).toContainEqual([expect.stringMatching(/^gfs-ext:pre:resource:session:/), 120])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:pre:resource-mutation:session:/),
+ 30,
+ ])
+ expect(calls).toContainEqual([expect.stringMatching(/^gfs-ext:resolved:resource:actor:/), 120])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:resolved:resource-mutation:actor:/),
+ 30,
+ ])
+ expect(calls.filter(([, limit]) => limit === 1200)).toHaveLength(2)
+ })
+
+ it('assigns ACL listing to the read budget and ACL writes to the mutation budget', async () => {
+ const { app } = buildApp()
+
+ await request(app).get('/external/gfs/grants').set('x-user-session-token', 'session-acl-read')
+ await request(app).put('/external/gfs/grants').set('x-user-session-token', 'session-acl-write')
+ await request(app).get('/external/gfs/shares').set('x-user-session-token', 'session-acl-read')
+ await request(app).post('/external/gfs/shares').set('x-user-session-token', 'session-acl-write')
+
+ const calls = checkAndIncrement.mock.calls.map(call => [String(call[0]), Number(call[1])])
+ expect(calls).toContainEqual([expect.stringMatching(/^gfs-ext:pre:grants-read:session:/), 120])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:resolved:grants-read:actor:/),
+ 120,
+ ])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:pre:grants-mutation:session:/),
+ 30,
+ ])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:resolved:grants-mutation:actor:/),
+ 30,
+ ])
+ expect(calls).toContainEqual([expect.stringMatching(/^gfs-ext:pre:shares-read:session:/), 120])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:resolved:shares-read:actor:/),
+ 120,
+ ])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:pre:shares-mutation:session:/),
+ 30,
+ ])
+ expect(calls).toContainEqual([
+ expect.stringMatching(/^gfs-ext:resolved:shares-mutation:actor:/),
+ 30,
+ ])
+ })
+
+ it('enforces the 1200/min aggregate IP ceiling after the 120/min read buckets', async () => {
+ checkAndIncrement.mockImplementation((key: string, limit: number) => {
+ if (key.startsWith('gfs-ext:pre:ip:')) return denied(1200)
+ return allowed(limit, limit - 1)
+ })
+ const { app, resolver, handler } = buildApp()
+
+ const response = await request(app)
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'session-one')
+
+ expect(response.status).toBe(429)
+ expect(response.headers['x-ratelimit-limit']).toBe('1200')
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringMatching(/^gfs-ext:pre:resource:session:[0-9a-f]{64}$/),
+ 120
+ )
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 2,
+ expect.stringMatching(/^gfs-ext:pre:resource:ip:[0-9a-f]{64}$/),
+ 120
+ )
+ expect(checkAndIncrement).toHaveBeenNthCalledWith(
+ 3,
+ expect.stringMatching(/^gfs-ext:pre:ip:[0-9a-f]{64}$/),
+ 1200
+ )
+ expect(resolver).not.toHaveBeenCalled()
+ expect(handler).not.toHaveBeenCalled()
+ })
+
+ it('keeps the resolved actor bucket stable when a Desktop session is renewed', async () => {
+ checkAndIncrement.mockImplementation((key: string) =>
+ key.startsWith('gfs-ext:resolved:resource:actor:') ? denied() : allowed()
+ )
+ const { app, resolver, handler } = buildApp()
+
+ const first = await request(app)
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'session-before-renewal')
+ const second = await request(app)
+ .get('/external/gfs/resources')
+ .set('x-user-session-token', 'session-after-renewal')
+
+ expect(first.status).toBe(429)
+ expect(second.status).toBe(429)
+ const resolvedKeys = checkAndIncrement.mock.calls
+ .map(call => String(call[0]))
+ .filter(key => key.startsWith('gfs-ext:resolved:resource:actor:'))
+ expect(resolvedKeys).toEqual([
+ `gfs-ext:resolved:resource:actor:linked-admin:${CONTROL_ADMIN_ID}`,
+ `gfs-ext:resolved:resource:actor:linked-admin:${CONTROL_ADMIN_ID}`,
+ ])
+ expect(resolver).toHaveBeenCalledTimes(2)
+ expect(handler).not.toHaveBeenCalled()
+ })
+ })
diff --cc control-ui/components/HostAdvancedTab/index.tsx
index 000000000,a70c79b2d..fca1d989d
mode 000000,100644..100644
--- a/control-ui/components/HostAdvancedTab/index.tsx
+++ b/control-ui/components/HostAdvancedTab/index.tsx
@@@ -1,0 -1,79 +1,75 @@@
+ 'use client'
+
+ import React, { useState } from 'react'
+ import { HostApprovalSection } from '@components/HostApprovalSection'
+ import { HostEnvTable } from '@components/HostEnvTable'
+ import { TabBar } from '@components/TabBar'
+ import type { AdvancedSubTab, HostAdvancedTabProps } from './types'
+
+ const ADVANCED_SUB_TABS: { key: AdvancedSubTab; label: string }[] = [
+ { key: 'approvals', label: 'Per-tool approval' },
+ { key: 'env', label: 'Env vars' },
+ ]
+
+ export function HostAdvancedTab({
+ busy,
+ hostName,
+ initialLoading,
+ initialTools,
+ onSaveApprovalTools,
+ }: HostAdvancedTabProps) {
+ const [subTab, setSubTab] = useState<AdvancedSubTab>('approvals')
+
+ return (
+ <section className="cu-advanced-tab" aria-label="Advanced">
+ <TabBar<AdvancedSubTab>
+ activeValue={subTab}
+ ariaLabel="Advanced settings"
+ className="cu-tabs--compact cu-advanced-tabs"
+ onChange={setSubTab}
+ options={ADVANCED_SUB_TABS.map(tab => ({ label: tab.label, value: tab.key }))}
+ />
+
+ <div className="cu-advanced-section">
+ {subTab === 'approvals' ? (
+ initialLoading ? (
- <div
- className="cu-table-wrap"
- role="status"
- aria-label="Loading approval tools"
- >
++ <div className="cu-table-wrap" role="status" aria-label="Loading approval tools">
+ <table className="cu-table cu-table--header-band cu-table--static-rows">
+ <thead>
+ <tr>
+ <th>Tool</th>
+ <th>Default</th>
+ <th className="cu-table__col-actions">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {[1, 2, 3, 4].map(i => (
+ <tr key={i}>
+ <td>
+ <div className="cu-skeleton cu-skeleton--cell" style={{ width: '8rem' }} />
+ </td>
+ <td>
+ <div className="cu-skeleton cu-skeleton--cell" style={{ width: '6rem' }} />
+ </td>
+ <td />
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ ) : (
+ <HostApprovalSection
+ busy={busy}
+ canWrite
+ defaultEditing
+ initialTools={initialTools}
+ onSave={onSaveApprovalTools}
+ />
+ )
+ ) : (
+ <HostEnvTable hostRef={hostName} />
+ )}
+ </div>
+ </section>
+ )
+ }
diff --cc control-ui/components/HostTable.tsx
index 706c4808e,ffbc9455e..0ca83ebc7
--- a/control-ui/components/HostTable.tsx
+++ b/control-ui/components/HostTable.tsx
@@@ -1,8 -1,9 +1,9 @@@
'use client'
import React, { useMemo, useState } from 'react'
-import { LlmProviderIcon } from './LlmProviderIcon'
import { getProviderLabel } from '../lib/llm'
import type { HostItem, HostLifecycleInfo, HostRef } from './HostTable.types'
++import { LlmProviderIcon } from './LlmProviderIcon'
import { SectionSearchInput } from './SectionSearchInput'
import { IconRobot } from './Sidebar/icons'
import { SkeletonTableRows } from './SkeletonTableRows'
@@@ -49,6 -49,31 +49,27 @@@ function getHostLifecycleInfo(host: Hos
}
}
+ export function collectProviderIds(spec: Record<string, unknown>): string[] {
- const primary = String(
- (spec.model as { provider?: string } | undefined)?.provider || ''
- ).trim()
++ const primary = String((spec.model as { provider?: string } | undefined)?.provider || '').trim()
+ const fallbacks = Array.isArray(
+ (spec.llmPolicy as { fallbacks?: Array<{ provider?: string }> } | undefined)?.fallbacks
+ )
- ? (
- spec.llmPolicy as { fallbacks: Array<{ provider?: string }> }
- ).fallbacks
++ ? (spec.llmPolicy as { fallbacks: Array<{ provider?: string }> }).fallbacks
+ .map(f => String(f.provider || '').trim())
+ .filter(Boolean)
+ : []
+ // Primary first, then fallbacks in declared order; dedup so the same provider
+ // doesn't render twice if it appears in both the model and the fallback list.
+ const seen = new Set<string>()
+ const out: string[] = []
+ for (const id of [primary, ...fallbacks]) {
+ if (!id || seen.has(id)) continue
+ seen.add(id)
+ out.push(id)
+ }
+ return out
+ }
+
function HostLifecycleBadge({ lifecycle }: { lifecycle: HostLifecycleInfo }) {
return (
<span
diff --cc control-ui/components/__tests__/HostTable.test.tsx
index d345294af,0deaea959..ed9c2e7d2
--- a/control-ui/components/__tests__/HostTable.test.tsx
+++ b/control-ui/components/__tests__/HostTable.test.tsx
@@@ -1,6 -1,6 +1,6 @@@
import { describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, within } from '@testing-library/react'
- import { HostTable } from '../HostTable'
-import { collectProviderIds, HostTable } from '../HostTable'
++import { HostTable, collectProviderIds } from '../HostTable'
import type { HostItem } from '../HostTable.types'
function makeHost(overrides: {
@@@ -88,3 -88,199 +88,197 @@@ describe('HostTable lifecycle column',
expect(screen.getByLabelText('Open agent chatllm-stateless')).toBeInTheDocument()
})
})
+
+ // Pure-function invariants for collectProviderIds — exported so the ordering
+ // and deduplication contract is verifiable independently of the DOM.
+ describe('collectProviderIds (HostTable provider extraction)', () => {
+ it('returns just the primary provider when no fallbacks are configured', () => {
+ expect(collectProviderIds({ model: { provider: 'openai' } })).toEqual(['openai'])
+ })
+
+ it('returns primary first then fallbacks in declared order', () => {
+ expect(
+ collectProviderIds({
+ model: { provider: 'openai' },
+ llmPolicy: { fallbacks: [{ provider: 'claude' }, { provider: 'zai' }] },
+ })
+ ).toEqual(['openai', 'claude', 'zai'])
+ })
+
+ it('deduplicates when the primary provider is also listed as a fallback', () => {
+ expect(
+ collectProviderIds({
+ model: { provider: 'openai' },
+ llmPolicy: { fallbacks: [{ provider: 'openai' }, { provider: 'zai' }] },
+ })
+ ).toEqual(['openai', 'zai'])
+ })
+
+ it('deduplicates when the same fallback provider appears twice', () => {
+ expect(
+ collectProviderIds({
+ model: { provider: 'openai' },
+ llmPolicy: { fallbacks: [{ provider: 'claude' }, { provider: 'claude' }] },
+ })
+ ).toEqual(['openai', 'claude'])
+ })
+
+ it('drops empty fallback entries', () => {
+ expect(
+ collectProviderIds({
+ model: { provider: 'openai' },
+ llmPolicy: { fallbacks: [{ provider: '' }, { provider: ' ' }, { provider: 'zai' }] },
+ })
+ ).toEqual(['openai', 'zai'])
+ })
+
+ it('returns an empty list when neither model nor fallbacks are present', () => {
+ expect(collectProviderIds({})).toEqual([])
+ expect(collectProviderIds({ model: {} })).toEqual([])
+ expect(collectProviderIds({ llmPolicy: { fallbacks: [] } })).toEqual([])
+ })
+
+ it('preserves fallback order even when the primary duplicates an earlier fallback', () => {
+ expect(
+ collectProviderIds({
+ model: { provider: 'zai' },
+ llmPolicy: { fallbacks: [{ provider: 'claude' }, { provider: 'zai' }] },
+ })
+ ).toEqual(['zai', 'claude'])
+ })
+ })
+
+ // Rendered coverage: the cell exposes the collected provider ids through
+ // aria-label, and renders one chip per unique provider in order. These
+ // assertions bind the cell's DOM contract to the helper's output.
+ describe('HostTable providers column rendering', () => {
+ function chipTitles(cell: HTMLElement): string[] {
- return Array.from(
- cell.querySelectorAll<HTMLElement>('.cu-host-providers__chip')
- ).map(chip => chip.getAttribute('title') || '')
++ return Array.from(cell.querySelectorAll<HTMLElement>('.cu-host-providers__chip')).map(
++ chip => chip.getAttribute('title') || ''
++ )
+ }
+
+ function providersCell(row: HTMLElement): HTMLElement {
+ return within(row).getByLabelText(/^Providers:/)
+ }
+
+ function hostWithModel(
+ name: string,
+ model: Record<string, unknown>,
+ fallbacks?: Array<{ provider?: string }>
+ ): HostItem {
+ return {
+ metadata: { name, namespace: 'mcp-host' },
+ spec: {
+ contextRef: 'context1',
+ model: model as { provider?: string; name?: string },
+ llmPolicy: fallbacks ? ({ fallbacks } as Record<string, unknown>) : undefined,
+ },
+ }
+ }
+
+ it('renders one icon per unique provider in primary-then-fallback order', () => {
+ renderHostTable([
- hostWithModel(
- 'chatllm',
- { provider: 'openai' },
- [{ provider: 'claude' }, { provider: 'zai' }]
- ),
++ hostWithModel('chatllm', { provider: 'openai' }, [
++ { provider: 'claude' },
++ { provider: 'zai' },
++ ]),
+ ])
+
+ const row = screen.getByLabelText('Open agent chatllm')
+ const cell = providersCell(row)
+
+ // aria-label lists every collected label in order.
+ expect(cell).toHaveAttribute('aria-label', 'Providers: OpenAI, Anthropic, Z.AI')
+
+ // Each chip exposes its label as the native title (hover tooltip).
+ expect(chipTitles(cell)).toEqual(['OpenAI', 'Anthropic', 'Z.AI'])
+ })
+
+ it('renders a single icon when a fallback duplicates the primary', () => {
+ renderHostTable([
- hostWithModel(
- 'chatllm',
++ hostWithModel('chatllm', { provider: 'openai' }, [
+ { provider: 'openai' },
- [{ provider: 'openai' }, { provider: 'zai' }]
- ),
++ { provider: 'zai' },
++ ]),
+ ])
+
+ const row = screen.getByLabelText('Open agent chatllm')
+ const cell = providersCell(row)
+ expect(cell).toHaveAttribute('aria-label', 'Providers: OpenAI, Z.AI')
+ expect(chipTitles(cell)).toEqual(['OpenAI', 'Z.AI'])
+ })
+
+ it('renders no chips when the host has no provider', () => {
+ renderHostTable([
+ {
+ metadata: { name: 'providerless' },
+ spec: { contextRef: 'context1' },
+ },
+ ])
+
+ const row = screen.getByLabelText('Open agent providerless')
+ expect(within(row).queryByLabelText(/^Providers:/)).not.toBeInTheDocument()
+ expect(within(row).getByText('-')).toBeInTheDocument()
+ })
+ })
+
+ // UT-9 — the row shows the editable display name (spec.host) as the primary
+ // label, with the immutable identifier (metadata.name / slug) as visible
+ // secondary text; the search haystack matches BOTH.
+ describe('HostTable display name column (UT-9)', () => {
+ function makeDisplayHost(name: string, displayName: string): HostItem {
+ return {
+ metadata: { name, namespace: 'mcp-host' },
+ spec: {
+ host: displayName,
+ contextRef: 'context1',
+ model: { provider: 'zai', name: 'glm-5.1' },
+ },
+ }
+ }
+
+ it('renders the display name as primary and the slug as secondary', () => {
+ renderHostTable([makeDisplayHost('prod-x', 'Prod X')])
+
+ const row = screen.getByLabelText('Open agent prod-x')
+ expect(within(row).getByText('Prod X')).toBeInTheDocument()
+ expect(within(row).getByText('prod-x')).toBeInTheDocument()
+ })
+
+ it('falls back to the slug as the primary label when spec.host is blank', () => {
+ renderHostTable([makeDisplayHost('prod-x', ' ')])
+
+ const row = screen.getByLabelText('Open agent prod-x')
+ // Only the slug renders — no separate secondary line duplicating it.
+ expect(within(row).getAllByText('prod-x')).toHaveLength(1)
+ })
+
+ it('filters rows by the display name', () => {
+ renderHostTable([
+ makeDisplayHost('prod-x', 'Prod X'),
+ makeDisplayHost('sales-agent', 'Sales Agent'),
+ ])
+
+ fireEvent.change(screen.getByRole('searchbox', { name: 'Search agents' }), {
+ target: { value: 'Prod' },
+ })
+
+ expect(screen.getByText('Prod X')).toBeInTheDocument()
+ expect(screen.queryByText('Sales Agent')).not.toBeInTheDocument()
+ })
+
+ it('filters rows by the slug identifier', () => {
+ renderHostTable([
+ makeDisplayHost('prod-x', 'Prod X'),
+ makeDisplayHost('sales-agent', 'Sales Agent'),
+ ])
+
+ fireEvent.change(screen.getByRole('searchbox', { name: 'Search agents' }), {
+ target: { value: 'sales-agent' },
+ })
+
+ expect(screen.getByText('Sales Agent')).toBeInTheDocument()
+ expect(screen.queryByText('Prod X')).not.toBeInTheDocument()
+ })
+ })
diff --cc control-ui/components/__tests__/HostWizard.test.tsx
index 3fc83fa88,8bcdc74a3..3c63bbb79
--- a/control-ui/components/__tests__/HostWizard.test.tsx
+++ b/control-ui/components/__tests__/HostWizard.test.tsx
@@@ -579,3 -631,115 +631,111 @@@ describe('HostWizard — Agent type (st
expect('workflowControl' in payload.spec).toBe(false)
})
})
+
+ describe('HostWizard — create-only seam + compensation (R5-C1/R5-B1, V-1, V-7)', () => {
+ it('surfaces the friendly collision message and rolls back the created secret when the context POST 409s WITHOUT a body code', async () => {
+ // Code-less 409 from a create-only POST = unambiguous AlreadyExists collision.
+ const collision = await build409({
+ error: 'contexts.mcp.evenfire.io "ctx1" already exists',
+ })
+ vi.mocked(api.apiSend).mockImplementation(async (method: string, path: string) => {
+ if (method === 'POST' && path === '/api/v1/admin/contexts') throw collision
+ return {}
+ })
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'coll-agent', contextName: 'ctx1' })
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ // Observable (T4): the friendly per-resource collision message is shown —
+ // NOT the raw K8s AlreadyExists text.
+ await waitFor(() => {
+ expect(screen.getByText(/A context named "ctx1" already exists/i)).toBeInTheDocument()
+ })
+ // Observable (T4): the already-created secret is compensated with an inverse DELETE.
+ expect(api.apiSend).toHaveBeenCalledWith('DELETE', '/api/v1/admin/secrets/coll-agent-llm')
+ // The Host was never POSTed (the seam aborted before the boundary).
+ expect(
- vi
- .mocked(api.apiSend)
- .mock.calls.some(c => c[0] === 'POST' && c[1] === '/api/v1/admin/hosts')
++ vi.mocked(api.apiSend).mock.calls.some(c => c[0] === 'POST' && c[1] === '/api/v1/admin/hosts')
+ ).toBe(false)
+ })
+
+ it('rolls back the created secret AND context in inverse order when the HOST create fails', async () => {
+ const hostErr = await build409({
+ error: 'hosts.mcp.evenfire.io "hostfail" already exists',
+ })
+ vi.mocked(api.apiSend).mockImplementation(async (method: string, path: string) => {
+ if (method === 'POST' && path === '/api/v1/admin/hosts') throw hostErr
+ return {}
+ })
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'hostfail', contextName: 'ctx1' })
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ await waitFor(() => {
+ expect(screen.getByText(/That agent name is already in use/i)).toBeInTheDocument()
+ })
+ // Inverse order: created = [secret, context] → compensate context THEN secret.
+ const deletePaths = vi
+ .mocked(api.apiSend)
+ .mock.calls.filter(c => c[0] === 'DELETE')
+ .map(c => c[1])
+ expect(deletePaths).toEqual([
+ '/api/v1/admin/contexts/ctx1',
+ '/api/v1/admin/secrets/hostfail-llm',
+ ])
+ })
+
+ it('rolls back NOTHING when a GRANT fails after the host is created (V-7)', async () => {
+ // The grant runs AFTER hostCreated=true; its failure must not trigger any
+ // sibling rollback — the host + siblings stay and grants retry from detail.
+ // vi.clearAllMocks() resets call history but NOT implementations, so pin a
+ // clean all-resolving apiSend for this test (prior tests set throwing ones).
+ vi.mocked(api.apiSend).mockImplementation(async () => ({}))
+ vi.mocked(api.updateAgentUsers).mockRejectedValueOnce(new Error('grant boom'))
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'grantfail', contextName: 'ctx1' })
+ // Select a user so updateAgentUsers is invoked.
+ fireEvent.click(screen.getByLabelText(/alice/i))
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ // The grant error is surfaced verbatim (no 409 remap at the top level).
+ await waitFor(() => {
+ expect(screen.getByText(/grant boom/i)).toBeInTheDocument()
+ })
+ // The host WAS created...
+ expect(
- vi
- .mocked(api.apiSend)
- .mock.calls.some(c => c[0] === 'POST' && c[1] === '/api/v1/admin/hosts')
++ vi.mocked(api.apiSend).mock.calls.some(c => c[0] === 'POST' && c[1] === '/api/v1/admin/hosts')
+ ).toBe(true)
+ // ...so NO compensation DELETE runs.
+ expect(vi.mocked(api.apiSend).mock.calls.some(c => c[0] === 'DELETE')).toBe(false)
+ })
+
+ it('re-throws the server message untouched on a CODED 409 (CRD-outdated) — no collision remap', async () => {
+ // 409 WITH a body `code` = CRD-outdated, NOT a collision: keep the server's
+ // human message, do not remap to the friendly "already exists" text.
+ const crdErr = await build409({
+ error: 'context CRD is outdated; apply the latest CRDs and retry',
+ code: 'context_crd_outdated',
+ })
+ vi.mocked(api.apiSend).mockImplementation(async (method: string, path: string) => {
+ if (method === 'POST' && path === '/api/v1/admin/contexts') throw crdErr
+ return {}
+ })
+
+ await renderWizard()
+ await walkToAccessStepNewSecret({ agentName: 'crd-agent', contextName: 'ctx1' })
+ fireEvent.click(screen.getByRole('button', { name: /Create Agent/i }))
+
+ await waitFor(() => {
+ expect(screen.getByText(/context CRD is outdated/i)).toBeInTheDocument()
+ })
+ // The friendly collision text must NOT appear (coded 409 is not a collision).
+ expect(screen.queryByText(/A context named .* already exists/i)).not.toBeInTheDocument()
+ // Boundary rule still applies: the secret created before the failing context
+ // is compensated (host never created), but nothing beyond that.
+ expect(api.apiSend).toHaveBeenCalledWith('DELETE', '/api/v1/admin/secrets/crd-agent-llm')
+ })
+ })
diff --cc control-ui/next.config.js
index 7b9bee733,6baa3f99a..8be20d4e7
--- a/control-ui/next.config.js
+++ b/control-ui/next.config.js
@@@ -111,6 -111,16 +111,20 @@@ const nextConfig =
{ source: '/publisher/:path*', destination: '/marketplace/org/entries', permanent: true },
{ source: '/cost', destination: '/cost-and-usage/usage', permanent: true },
{ source: '/cost/:path*', destination: '/cost-and-usage/:path*', permanent: true },
+ // Host detail tab consolidation (R1-H1 in feat/agent-ux-polish PR
+ // review): the old top-level tabs are now sub-tabs under the new
+ // `access` and `advanced` parents. Send each old slug to its new
+ // parent so bookmarks, shared links, and the approval-tools E2E
+ // (which navigates to /hosts/<name>/approvals) still reach the
+ // section they used to.
- { source: '/agents/:name/member-access', destination: '/agents/:name/access', permanent: true },
++ {
++ source: '/agents/:name/member-access',
++ destination: '/agents/:name/access',
++ permanent: true,
++ },
+ { source: '/agents/:name/team-access', destination: '/agents/:name/access', permanent: true },
+ { source: '/agents/:name/approvals', destination: '/agents/:name/advanced', permanent: true },
+ { source: '/agents/:name/env-vars', destination: '/agents/:name/advanced', permanent: true },
{ source: '/marketplace', destination: '/marketplace/connectors', permanent: true },
{ source: '/cost-and-usage', destination: '/cost-and-usage/usage', permanent: true },
{
diff --cc control-ui/package-lock.json
index 6df31884f,0661c711b..7148e15d0
--- a/control-ui/package-lock.json
+++ b/control-ui/package-lock.json
@@@ -1,13 -1,14 +1,14 @@@
{
"name": "clerum-control-ui",
- "version": "0.1.432",
- "version": "0.1.430",
++ "version": "0.1.433",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-ui",
- "version": "0.1.432",
- "version": "0.1.430",
++ "version": "0.1.433",
"dependencies": {
+ "@clerum/display-field": "file:../packages/display-field",
"@clerum/llm-providers": "file:../packages/llm-providers",
"@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",
"@uiw/react-md-editor": "^4.1.0",
diff --cc control-ui/package.json
index 2812499dd,ac5504573..2ac54986b
--- a/control-ui/package.json
+++ b/control-ui/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-control-ui",
- "version": "0.1.432",
- "version": "0.1.430",
++ "version": "0.1.433",
"private": true,
"scripts": {
"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",
diff --cc external-rest-api/test/routes.gfs.test.ts
index 472104e5c,9b812bf20..6befe274e
--- a/external-rest-api/test/routes.gfs.test.ts
+++ b/external-rest-api/test/routes.gfs.test.ts
@@@ -8,10 -8,16 +8,13 @@@ const { ControlApiError, clientMock }
constructor(
message: string,
public status: number,
- public body: unknown
+ public body: unknown,
+ headers: Record<string, string> | Headers = {}
) {
super(message)
- this.headers =
- headers instanceof Headers
- ? Object.fromEntries(headers.entries())
- : headers
++ this.headers = headers instanceof Headers ? Object.fromEntries(headers.entries()) : headers
}
+ public headers: Record<string, string>
}
return {
ControlApiError,
diff --cc host-context-controller/package-lock.json
index 770f7c707,770f7c707..e9b28c157
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-host-context-controller",
-- "version": "0.1.169",
++ "version": "0.1.170",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
-- "version": "0.1.169",
++ "version": "0.1.170",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/image-policy": "file:../packages/image-policy",
diff --cc host-context-controller/package.json
index 04b826ebf,04b826ebf..17c98b81a
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-host-context-controller",
-- "version": "0.1.169",
++ "version": "0.1.170",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --cc mcp-host/package-lock.json
index a62cdc464,a62cdc464..8519e148d
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@@ -1,12 -1,12 +1,12 @@@
{
"name": "clerum-mcp-host",
-- "version": "0.1.238",
++ "version": "0.1.239",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
-- "version": "0.1.238",
++ "version": "0.1.239",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --cc mcp-host/package.json
index 2b209bb31,2b209bb31..2dcb39dec
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@@ -1,6 -1,6 +1,6 @@@
{
"name": "clerum-mcp-host",
-- "version": "0.1.238",
++ "version": "0.1.239",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {