Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-ui): give agent hooks their own advanced tab and table
Andy Paviae9504b49fb35
diff --git a/control-ui/app/hosts/[name]/page.tsx b/control-ui/app/hosts/[name]/page.tsxindex d93ca9cc8..541bddb42 100644--- a/control-ui/app/hosts/[name]/page.tsx+++ b/control-ui/app/hosts/[name]/page.tsx@@ -9,7 +9,6 @@ import { HOST_DEFAULT_TAB, HOST_TABS } from '@constants/hostDetails'import { CONTROL_ROUTES } from '@constants/routes'import { HostAccessTab } from '../../../components/HostAccessTab'import { HostAdvancedTab } from '../../../components/HostAdvancedTab'-import { HostGuardrailsSection } from '../../../components/HostGuardrailsSection'import type { HostGuardrails } from '../../../components/HostGuardrailsSection/types'import { HostIdentityTab } from '../../../components/HostIdentityTab'import { LlmProviderConfig } from '../../../components/LlmProviderConfig'@@ -1017,25 +1016,15 @@ export default function HostDetailsPage() {)}{activeTab === 'advanced' && (- <>- <HostAdvancedTab- busy={busy}- hostName={routeName}- initialLoading={initialLoading}- initialTools={approvalToolsData}- onSaveApprovalTools={persistApprovalTools}- />- {!initialLoading && (- <HostGuardrailsSection- initialGuardrails={guardrailsData}- onSave={persistGuardrails}- busy={busy}- canWrite={- true /* TODO: wire to actual host:write check if/when per-field RBAC lands */- }- />- )}- </>+ <HostAdvancedTab+ busy={busy}+ hostName={routeName}+ initialGuardrails={guardrailsData}+ initialLoading={initialLoading}+ initialTools={approvalToolsData}+ onSaveApprovalTools={persistApprovalTools}+ onSaveGuardrails={persistGuardrails}+ />)}{activeTab === 'contexts' && (diff --git a/control-ui/components/HostAdvancedTab/index.tsx b/control-ui/components/HostAdvancedTab/index.tsxindex fca1d989d..3d542ac6a 100644--- a/control-ui/components/HostAdvancedTab/index.tsx+++ b/control-ui/components/HostAdvancedTab/index.tsx@@ -3,22 +3,28 @@import React, { useState } from 'react'import { HostApprovalSection } from '@components/HostApprovalSection'import { HostEnvTable } from '@components/HostEnvTable'+import { HostGuardrailsSection } from '@components/HostGuardrailsSection'import { TabBar } from '@components/TabBar'import type { AdvancedSubTab, HostAdvancedTabProps } from './types'const ADVANCED_SUB_TABS: { key: AdvancedSubTab; label: string }[] = [+ { key: 'hooks', label: 'Hooks' },{ key: 'approvals', label: 'Per-tool approval' },{ key: 'env', label: 'Env vars' },]+const DEFAULT_SUB_TAB: AdvancedSubTab = 'hooks'+export function HostAdvancedTab({busy,hostName,+ initialGuardrails,initialLoading,initialTools,onSaveApprovalTools,+ onSaveGuardrails,}: HostAdvancedTabProps) {- const [subTab, setSubTab] = useState<AdvancedSubTab>('approvals')+ const [subTab, setSubTab] = useState<AdvancedSubTab>(DEFAULT_SUB_TAB)return (<section className="cu-advanced-tab" aria-label="Advanced">@@ -31,32 +37,25 @@ export function HostAdvancedTab({/><div className="cu-advanced-section">- {subTab === 'approvals' ? (- initialLoading ? (- <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>+ {subTab === 'hooks' &&+ (initialLoading ? (+ <div className="cu-empty" role="status" aria-label="Loading guardrail hooks">+ Loading…</div>+ ) : (+ <HostGuardrailsSection+ busy={busy}+ canWrite={+ true /* TODO: wire to actual host:write check if/when per-field RBAC lands */+ }+ initialGuardrails={initialGuardrails}+ onSave={onSaveGuardrails}+ />+ ))}++ {subTab === 'approvals' &&+ (initialLoading ? (+ <ApprovalToolsSkeleton />) : (<HostApprovalSectionbusy={busy}@@ -65,11 +64,39 @@ export function HostAdvancedTab({initialTools={initialTools}onSave={onSaveApprovalTools}/>- )- ) : (- <HostEnvTable hostRef={hostName} />- )}+ ))}++ {subTab === 'env' && <HostEnvTable hostRef={hostName} />}</div></section>)}++function ApprovalToolsSkeleton() {+ return (+ <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>+ )+}diff --git a/control-ui/components/HostAdvancedTab/types.ts b/control-ui/components/HostAdvancedTab/types.tsindex 1f0e534dd..e793d009a 100644--- a/control-ui/components/HostAdvancedTab/types.ts+++ b/control-ui/components/HostAdvancedTab/types.ts@@ -1,6 +1,7 @@import type { HostApprovalSectionProps } from '../HostApprovalSection/types'+import type { HostGuardrailsSectionProps } from '../HostGuardrailsSection/types'-export type AdvancedSubTab = 'approvals' | 'env'+export type AdvancedSubTab = 'hooks' | 'approvals' | 'env'export type HostAdvancedTabProps = {busy: boolean@@ -8,4 +9,6 @@ export type HostAdvancedTabProps = {initialLoading: booleaninitialTools: HostApprovalSectionProps['initialTools']onSaveApprovalTools: HostApprovalSectionProps['onSave']+ initialGuardrails: HostGuardrailsSectionProps['initialGuardrails']+ onSaveGuardrails: HostGuardrailsSectionProps['onSave']}diff --git a/control-ui/components/HostGuardrailsSection/constants.ts b/control-ui/components/HostGuardrailsSection/constants.tsindex 2b2e611ab..47c22b7f8 100644--- a/control-ui/components/HostGuardrailsSection/constants.ts+++ b/control-ui/components/HostGuardrailsSection/constants.ts@@ -1,4 +1,4 @@-import type { GuardrailBuiltinType, GuardrailPhase } from './types'+import type { GuardrailPhase } from './types'// Render/iteration order for the hook phases.export const GUARDRAIL_PHASES: readonly GuardrailPhase[] = [@@ -18,12 +18,3 @@ export const GUARDRAIL_PHASE_LABELS: Record<GuardrailPhase, string> = {postCallSuccess: 'Post-call success',onError: 'On error',}--// Curated built-in types offered by the minimal add UI.-export const GUARDRAIL_BUILTIN_OPTIONS: ReadonlyArray<{- value: GuardrailBuiltinType- label: string-}> = [- { value: 'prompt-shaping', label: 'Prompt shaping' },- { value: 'token-trim', label: 'Token trim' },-] as constdiff --git a/control-ui/components/HostGuardrailsSection/index.tsx b/control-ui/components/HostGuardrailsSection/index.tsxindex 35ce08bcd..a85a67814 100644--- a/control-ui/components/HostGuardrailsSection/index.tsx+++ b/control-ui/components/HostGuardrailsSection/index.tsx@@ -1,26 +1,51 @@'use client'-import React, { useMemo, useState } from 'react'+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useRouter } from 'next/navigation'+import { useConfirmDialog } from '@components/ConfirmDialog'+import { SelectionModal } from '@components/SelectionModal'+import { useToast } from '@components/Toast'+import { IconX } from '@components/icons'+import { GUARDRAIL_ENTRY_TYPE } from '@constants/marketplaceEntryTypes'import { CONTROL_ROUTES } from '@constants/routes'-import { IconX } from '../icons'-import { Button, SelectInput, TextInput } from '../ui'-import { GUARDRAIL_BUILTIN_OPTIONS, GUARDRAIL_PHASES, GUARDRAIL_PHASE_LABELS } from './constants'+import { type LlmHookResource, getLlmHooks } from '@lib/api'+import { GUARDRAIL_PHASES, GUARDRAIL_PHASE_LABELS } from './constants'import type {- GuardrailBuiltin,- GuardrailBuiltinType,GuardrailHookRef,+ GuardrailHookRow,GuardrailPhase,HostGuardrails,HostGuardrailsSectionProps,} from './types'-function cloneGuardrails(source: HostGuardrails | undefined): HostGuardrails {- return {- ...source,- hooks: source?.hooks ? { ...source.hooks } : {},- builtins: source?.builtins ? source.builtins.map(builtin => ({ ...builtin })) : [],- }+// The picker only offers hooks already installed on the cluster, so keep the+// route that installs new ones reachable from the section itself — it is the+// path the old "Add hook" button used to take.+const INSTALL_HOOK_ROUTE = CONTROL_ROUTES.marketplace.orgEntriesFiltered({+ type: GUARDRAIL_ENTRY_TYPE,+})++// The phases an installed hook declares it runs at. A hook is attached to every+// phase it declares, so the operator picks the hook and never the phase.+function hookPhases(hook: LlmHookResource): GuardrailPhase[] {+ const raw = (hook.spec as { lifecyclePoints?: unknown } | undefined)?.lifecyclePoints+ if (!Array.isArray(raw)) return []+ return raw.filter((point): point is GuardrailPhase =>+ GUARDRAIL_PHASES.includes(point as GuardrailPhase)+ )+}++function hookName(hook: LlmHookResource): string {+ return hook.metadata?.name ?? ''+}++// Every field this section does not edit rides along untouched — dropping+// `builtins` or `limits` here would silently wipe them from the Host spec.+function withHooks(+ source: HostGuardrails | undefined,+ hooks: HostGuardrails['hooks']+): HostGuardrails {+ return { ...source, hooks }}export function HostGuardrailsSection({@@ -28,310 +53,230 @@ export function HostGuardrailsSection({onSave,busy,canWrite,- defaultEditing = false,}: HostGuardrailsSectionProps) {const router = useRouter()- const [editing, setEditing] = useState(defaultEditing)- const [draft, setDraft] = useState<HostGuardrails>(() => cloneGuardrails(initialGuardrails))+ const { confirm, confirmDialog } = useConfirmDialog()+ const { showToast } = useToast()+ const mountedRef = useRef(true)- // Re-seed the draft whenever the saved guardrails change (reload after save).- const initialKey = JSON.stringify(initialGuardrails ?? {})- React.useEffect(() => {- setDraft(cloneGuardrails(initialGuardrails))- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [initialKey])+ const [installedHooks, setInstalledHooks] = useState<LlmHookResource[]>([])+ const [showAddHook, setShowAddHook] = useState(false)+ const [selectedHookNames, setSelectedHookNames] = useState<string[]>([])+ const [saving, setSaving] = useState(false)- const isDirty = useMemo(- () => JSON.stringify(draft) !== JSON.stringify(cloneGuardrails(initialGuardrails)),- [draft, initialGuardrails]- )+ useEffect(() => {+ mountedRef.current = true+ return () => {+ mountedRef.current = false+ }+ }, [])++ // The installed LlmHooks are the pool this agent can reference. A load+ // failure only empties the picker — the rows below come from the Host spec+ // and stay readable either way.+ useEffect(() => {+ void (async () => {+ try {+ const result = await getLlmHooks()+ if (!mountedRef.current) return+ setInstalledHooks(Array.isArray(result.items) ? result.items : [])+ } catch {+ if (mountedRef.current) setInstalledHooks([])+ }+ })()+ }, [])++ const rows = useMemo<GuardrailHookRow[]>(() => {+ const hooks = initialGuardrails?.hooks ?? {}+ return GUARDRAIL_PHASES.flatMap(phase => (hooks[phase] ?? []).map(ref => ({ phase, ref })))+ }, [initialGuardrails])- const hookPhases = useMemo(+ const referencedIds = useMemo(() => new Set(rows.map(row => row.ref.id)), [rows])++ const addOptions = useMemo(() =>- GUARDRAIL_PHASES.map(phase => ({- phase,- refs: draft.hooks?.[phase] ?? [],- })).filter(entry => entry.refs.length > 0),- [draft.hooks]+ installedHooks+ .filter(hook => hookName(hook) && !referencedIds.has(hookName(hook)))+ .map(hook => {+ const phases = hookPhases(hook)+ return {+ value: hookName(hook),+ label: hookName(hook),+ description: phases.length+ ? phases.map(phase => GUARDRAIL_PHASE_LABELS[phase]).join(' · ')+ : 'No lifecycle points declared',+ }+ }),+ [installedHooks, referencedIds])- const builtins = draft.builtins ?? []- const hasAny = hookPhases.length > 0 || builtins.length > 0- function removeHookRef(phase: GuardrailPhase, id: string) {- setDraft(current => {- const currentRefs = current.hooks?.[phase] ?? []- const nextRefs = currentRefs.filter(ref => ref.id !== id)- const nextHooks: HostGuardrails['hooks'] = { ...current.hooks }- if (nextRefs.length > 0) nextHooks[phase] = nextRefs- else delete nextHooks[phase]- return { ...current, hooks: nextHooks }- })- }+ const persist = useCallback(+ async (nextHooks: HostGuardrails['hooks'], successMessage: string) => {+ setSaving(true)+ try {+ await onSave(withHooks(initialGuardrails, nextHooks))+ if (mountedRef.current) showToast(successMessage, { tone: 'success' })+ return true+ } catch {+ // The parent already surfaced the error/conflict banner.+ return false+ } finally {+ if (mountedRef.current) setSaving(false)+ }+ },+ [initialGuardrails, onSave, showToast]+ )- function addBuiltin(builtin: GuardrailBuiltin) {- setDraft(current => ({- ...current,- builtins: [...(current.builtins ?? []), builtin],- }))- }+ async function addSelectedHooks() {+ const chosen = installedHooks.filter(hook => selectedHookNames.includes(hookName(hook)))+ const nextHooks: HostGuardrails['hooks'] = { ...(initialGuardrails?.hooks ?? {}) }- function removeBuiltin(index: number) {- setDraft(current => ({- ...current,- builtins: (current.builtins ?? []).filter((_, i) => i !== index),- }))- }+ for (const hook of chosen) {+ const id = hookName(hook)+ // Pin the digest the cluster actually reconciled, matching how existing+ // references are stored. An unpinned reference would float across hook+ // image updates.+ const ref: GuardrailHookRef = { id }+ const digest = hook.status?.observedDigest+ if (digest) ref.digest = digest- function handleCancel() {- setDraft(cloneGuardrails(initialGuardrails))- setEditing(defaultEditing)- }+ for (const phase of hookPhases(hook)) {+ nextHooks[phase] = [...(nextHooks[phase] ?? []), ref]+ }+ }- async function handleSave() {- try {- await onSave(draft)- setEditing(defaultEditing)- } catch {- // Parent surfaced an error/conflict banner. Stay in edit mode so the- // operator's draft survives the failure.+ const added = chosen.length+ const ok = await persist(+ nextHooks,+ added === 1 ? `${hookName(chosen[0])} added to this agent.` : `${added} hooks added.`+ )+ if (ok && mountedRef.current) {+ setSelectedHookNames([])+ setShowAddHook(false)}}- return (- <div className="cu-host-approval-section">- <p className="cu-muted cu-host-approval-section__description">- Installed guardrail hooks referenced by this agent, plus built-in guardrails. Use{' '}- <strong>Add hook</strong> to install a guardrail from the Marketplace onto this agent, add a- built-in, or remove a hook reference. Manage installed guardrails cluster-wide from the- Installed Guardrails section.- </p>+ async function removeHook(row: GuardrailHookRow) {+ const shouldRemove = await confirm({+ title: 'Remove guardrail hook',+ message: `Remove ${row.ref.id} from ${GUARDRAIL_PHASE_LABELS[row.phase]} on this agent? The hook stays installed on the cluster.`,+ confirmLabel: 'Remove',+ tone: 'danger',+ })+ if (!shouldRemove) return- <div className="cu-host-approval-section__content">- {!editing ? (- !hasAny ? (- <div className="cu-empty">- No guardrail hooks or built-ins configured for this agent.- </div>- ) : (- <div>- {hookPhases.map(({ phase, refs }) => (- <div key={phase} className="cu-access-row">- <span>{GUARDRAIL_PHASE_LABELS[phase]}</span>- <div className="cu-expandable-tags">- {refs.map(ref => (- <span- key={ref.id}- className="cu-registry-tag"- title={ref.digest ? `digest ${ref.digest}` : undefined}- >- {ref.id}- </span>- ))}- </div>- </div>- ))}- {builtins.map((builtin, index) => (- <div key={`${builtin.type}-${index}`} className="cu-access-row">- <span>Built-in · {builtin.type}</span>- <span>- order {typeof builtin.order === 'number' ? builtin.order : '—'} · fail{' '}- {builtin.failMode ?? 'open'}- </span>- </div>- ))}- </div>- )- ) : (- <EditMode- hookPhases={hookPhases}- builtins={builtins}- busy={busy}- onRemoveHookRef={removeHookRef}- onAddBuiltin={addBuiltin}- onRemoveBuiltin={removeBuiltin}- />- )}- </div>+ const currentRefs = initialGuardrails?.hooks?.[row.phase] ?? []+ const nextRefs = currentRefs.filter(ref => ref.id !== row.ref.id)+ const nextHooks: HostGuardrails['hooks'] = { ...(initialGuardrails?.hooks ?? {}) }+ if (nextRefs.length > 0) nextHooks[row.phase] = nextRefs+ else delete nextHooks[row.phase]- <div className="cu-host-approval-section__actions">- {editing ? (- <>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={handleCancel}- disabled={busy}- >- Cancel- </button>- <button- type="button"- className="cu-btn cu-btn--primary"- onClick={handleSave}- disabled={busy || !isDirty}- >- {busy ? 'Saving…' : 'Save'}- </button>- </>- ) : canWrite ? (- <>+ await persist(nextHooks, `${row.ref.id} removed from this agent.`)+ }++ const disabled = busy || saving++ return (+ <section className="cu-guardrails-tab" aria-label="Hooks">+ <div className="cu-access-section">+ <div className="cu-access-section__header">+ <p className="cu-muted cu-access-section__description">+ Guardrail hooks installed on the cluster and referenced by this agent.{' '}+ <a className="cu-link" href={INSTALL_HOOK_ROUTE}>+ Browse the Marketplace+ </a>{' '}+ to install more.+ </p>+ {canWrite ? (<buttontype="button"className="cu-btn cu-btn--primary cu-btn--sm"- onClick={() => router.push(CONTROL_ROUTES.marketplace.orgEntries)}- disabled={busy}+ onClick={() => setShowAddHook(true)}+ disabled={disabled}>Add hook</button>- <button- type="button"- className="cu-btn cu-btn--ghost cu-btn--sm"- onClick={() => setEditing(true)}- disabled={busy}- >- Edit- </button>- </>- ) : null}- </div>- </div>- )-}--interface EditModeProps {- hookPhases: Array<{ phase: GuardrailPhase; refs: GuardrailHookRef[] }>- builtins: GuardrailBuiltin[]- busy: boolean- onRemoveHookRef: (phase: GuardrailPhase, id: string) => void- onAddBuiltin: (builtin: GuardrailBuiltin) => void- onRemoveBuiltin: (index: number) => void-}--function EditMode({- hookPhases,- builtins,- busy,- onRemoveHookRef,- onAddBuiltin,- onRemoveBuiltin,-}: EditModeProps) {- const [builtinType, setBuiltinType] = useState<GuardrailBuiltinType>('prompt-shaping')- const [orderValue, setOrderValue] = useState('0')- const [failMode, setFailMode] = useState<'open' | 'closed'>('open')-- function handleAdd() {- const parsedOrder = Number.parseInt(orderValue, 10)- onAddBuiltin({- type: builtinType,- order: Number.isFinite(parsedOrder) ? parsedOrder : 0,- failMode,- })- setOrderValue('0')- setFailMode('open')- setBuiltinType('prompt-shaping')- }+ ) : null}+ </div>- return (- <>- <div className="cu-field">- <label>Referenced hooks</label>- {hookPhases.length === 0 ? (- <div className="cu-empty">No installed hooks are referenced by this agent.</div>- ) : (- hookPhases.map(({ phase, refs }) => (- <div key={phase} className="cu-access-row">- <span>{GUARDRAIL_PHASE_LABELS[phase]}</span>- <div className="cu-expandable-tags">- {refs.map(ref => (- <span key={ref.id} className="cu-guardrails-ref-chip">- <span- className="cu-registry-tag"- title={ref.digest ? `digest ${ref.digest}` : undefined}- >- {ref.id}- </span>- <button- type="button"- className="cu-btn cu-btn--icon cu-btn--danger-icon"- aria-label={`Remove hook ${ref.id} from ${GUARDRAIL_PHASE_LABELS[phase]}`}- onClick={() => onRemoveHookRef(phase, ref.id)}- disabled={busy}- >- <IconX />- </button>- </span>- ))}- </div>- </div>- ))- )}+ <div className="cu-table-wrap">+ <table className="cu-table cu-table--header-band">+ <thead>+ <tr>+ <th>Hook</th>+ <th>Phase</th>+ <th className="cu-table__col-actions">Actions</th>+ </tr>+ </thead>+ <tbody>+ {rows.length === 0 ? (+ <tr>+ <td colSpan={3} className="cu-empty">+ No guardrail hooks on this agent yet.+ </td>+ </tr>+ ) : (+ rows.map(row => (+ <tr key={`${row.phase}:${row.ref.id}`}>+ <td>+ <button+ type="button"+ className="cu-link"+ title={row.ref.digest ? `digest ${row.ref.digest}` : undefined}+ onClick={() => router.push(CONTROL_ROUTES.guardrails.detail(row.ref.id))}+ >+ {row.ref.id}+ </button>+ </td>+ <td>{GUARDRAIL_PHASE_LABELS[row.phase]}</td>+ <td className="cu-table__cell-actions">+ <div className="cu-row-actions">+ {canWrite ? (+ <button+ type="button"+ className="cu-btn cu-btn--icon cu-btn--danger-icon"+ onClick={() => void removeHook(row)}+ disabled={disabled}+ title="Remove"+ aria-label={`Remove hook ${row.ref.id} from ${GUARDRAIL_PHASE_LABELS[row.phase]}`}+ >+ <IconX width={16} height={16} />+ </button>+ ) : null}+ </div>+ </td>+ </tr>+ ))+ )}+ </tbody>+ </table>+ </div></div>- <div className="cu-field">- <label>Built-in guardrails</label>- {builtins.length === 0 ? (- <div className="cu-empty">No built-in guardrails configured.</div>- ) : (- builtins.map((builtin, index) => (- <div key={`${builtin.type}-${index}`} className="cu-access-row">- <span>- {builtin.type} · order {typeof builtin.order === 'number' ? builtin.order : '—'} ·- fail {builtin.failMode ?? 'open'}- </span>- <button- type="button"- className="cu-btn cu-btn--icon cu-btn--danger-icon"- aria-label={`Remove built-in ${builtin.type}`}- onClick={() => onRemoveBuiltin(index)}- disabled={busy}- >- <IconX />- </button>- </div>- ))- )}- </div>+ {showAddHook ? (+ <SelectionModal+ busy={disabled}+ emptyLabel="No installed guardrail hooks are available."+ id="agent-hook-picker"+ label="Hooks"+ onChange={setSelectedHookNames}+ onClose={() => {+ setSelectedHookNames([])+ setShowAddHook(false)+ }}+ onConfirm={addSelectedHooks}+ options={addOptions}+ placeholder="Select hooks"+ searchPlaceholder="Search hooks..."+ selectionLabel="Selected hooks"+ submitLabel={selectedHookNames.length > 1 ? 'Add hooks' : 'Add hook'}+ title="Add hook"+ titleId="add-hook-title"+ value={selectedHookNames}+ />+ ) : null}- <div className="cu-field">- <label htmlFor="guardrail-builtin-type">Add built-in</label>- <div className="cu-guardrails-add-row">- <SelectInput- id="guardrail-builtin-type"- compact- value={builtinType}- onChange={e => setBuiltinType(e.target.value as GuardrailBuiltinType)}- disabled={busy}- >- {GUARDRAIL_BUILTIN_OPTIONS.map(option => (- <option key={option.value} value={option.value}>- {option.label}- </option>- ))}- </SelectInput>- <TextInput- type="number"- compact- narrow- value={orderValue}- onChange={e => setOrderValue(e.target.value)}- disabled={busy}- aria-label="Built-in order"- />- <SelectInput- compact- value={failMode}- onChange={e => setFailMode(e.target.value as 'open' | 'closed')}- disabled={busy}- aria-label="Built-in fail mode"- >- <option value="open">Fail open</option>- <option value="closed">Fail closed</option>- </SelectInput>- <Button variant="ghost" size="sm" onClick={handleAdd} disabled={busy}>- Add- </Button>- </div>- </div>- </>+ {confirmDialog}+ </section>)}diff --git a/control-ui/components/HostGuardrailsSection/types.ts b/control-ui/components/HostGuardrailsSection/types.tsindex 32033c992..4b0a51b91 100644--- a/control-ui/components/HostGuardrailsSection/types.ts+++ b/control-ui/components/HostGuardrailsSection/types.ts@@ -10,10 +10,6 @@ export type GuardrailPhase =export type GuardrailHookRef = { id: string; digest?: string }-// Built-in guardrails supported by the minimal add UI. The stored `type` is a-// free string on the CR; the picker offers this curated subset.-export type GuardrailBuiltinType = 'prompt-shaping' | 'token-trim'-export type GuardrailBuiltin = {type: stringorder?: number@@ -23,8 +19,8 @@ export type GuardrailBuiltin = {}// Structured view over `Host.spec.guardrails` (typed `AnyRecord` in lib/api).-// Fields this section does not edit (rules, trust level, ceiling, limits) are-// carried through untouched so a save never drops them.+// This section edits `hooks` and nothing else — `builtins`, rules, trust level,+// ceiling and limits are carried through untouched so a save never drops them.export type HostGuardrails = {rules?: unknown[]hooks?: Partial<Record<GuardrailPhase, GuardrailHookRef[]>>@@ -34,14 +30,19 @@ export type HostGuardrails = {limits?: Record<string, unknown>}+// One table row: a single hook reference under a single phase. A hook that runs+// at two phases is two rows, which is also how it is stored.+export type GuardrailHookRow = {+ phase: GuardrailPhase+ ref: GuardrailHookRef+}+export interface HostGuardrailsSectionProps {initialGuardrails: HostGuardrails | undefined// Persist the full guardrails object (parent merges it into the Host spec// under the resourceVersion precondition). Rejects on failure so the section- // keeps the operator's draft.+ // can leave the operator's view untouched.onSave: (next: HostGuardrails) => Promise<void>busy: booleancanWrite: boolean- // Render the editable list immediately instead of the read-only summary.- defaultEditing?: boolean}diff --git a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsxindex f112c249c..c6e9ba36a 100644--- a/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx+++ b/control-ui/components/__tests__/HostDetailsPage.identity.test.tsx@@ -46,6 +46,8 @@ vi.mock('../../lib/api', () => ({getAgentUsers: vi.fn(),getHost: vi.fn(),getHostDetailBundle: vi.fn(),+ // The Hooks sub-tab loads the installed LlmHooks to populate its picker.+ getLlmHooks: vi.fn().mockResolvedValue({ items: [] }),updateAdminTeamAgents: vi.fn(),updateAdminUserAgents: vi.fn(),// The model picker loads the operator allowlist via useLlmAllowedModels.@@ -148,10 +150,27 @@ describe('HostDetailsPage identity integration', () => {expect(container.querySelector('.cu-agent-detail-card .cu-agent-detail-scroll')).not.toBeNull()})+ it('opens Advanced on the Hooks sub-tab', async () => {+ mockParams = { name: 'foo', tab: 'advanced' }+ render(<HostDetailsPage />)++ const hooksTab = await screen.findByRole('tab', { name: 'Hooks' })+ expect(hooksTab).toHaveAttribute('aria-selected', 'true')+ expect(screen.getByRole('tab', { name: 'Per-tool approval' })).toHaveAttribute(+ 'aria-selected',+ 'false'+ )+ expect(await screen.findByText('No guardrail hooks on this agent yet.')).toBeInTheDocument()+ // The approval editor stays unmounted until its sub-tab is selected.+ expect(screen.queryByLabelText('http_request')).toBeNull()+ })+it('keeps Per-tool approval actions in the top toolbar without a duplicate title', async () => {mockParams = { name: 'foo', tab: 'advanced' }const { container } = render(<HostDetailsPage />)+ fireEvent.click(await screen.findByRole('tab', { name: 'Per-tool approval' }))+expect(await screen.findByLabelText('http_request')).toBeInTheDocument()expect(screen.getByRole('button', { name: 'Save' }).closest('.cu-host-approval-section__actions')diff --git a/control-ui/components/__tests__/HostGuardrailsSection.test.tsx b/control-ui/components/__tests__/HostGuardrailsSection.test.tsxnew file mode 100644index 000000000..a743e7260--- /dev/null+++ b/control-ui/components/__tests__/HostGuardrailsSection.test.tsx@@ -0,0 +1,206 @@+import React from 'react'+import type { ReactNode } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ cleanup,+ fireEvent,+ render as rtlRender,+ screen,+ waitFor,+ within,+} from '@testing-library/react'+import * as api from '../../lib/api'+import { HostGuardrailsSection } from '../HostGuardrailsSection'+import type { HostGuardrails } from '../HostGuardrailsSection/types'+import { ToastProvider } from '../Toast'++vi.mock('../../lib/api', () => ({+ getLlmHooks: vi.fn(),+}))++const confirmMock = vi.hoisted(() => vi.fn())+vi.mock('../ConfirmDialog', () => ({+ useConfirmDialog: () => ({ confirm: confirmMock, confirmDialog: null }),+}))++const navigation = vi.hoisted(() => ({ push: vi.fn() }))+vi.mock('next/navigation', () => ({+ useRouter: () => ({ push: navigation.push }),+}))++const COMPACTOR = {+ metadata: { name: 'hook-token-compactor' },+ spec: { lifecyclePoints: ['preCall'] },+ status: { observedDigest: 'sha256:aaa' },+}+const RECORDER = {+ metadata: { name: 'hook-tool-use-recorder' },+ spec: { lifecyclePoints: ['postCallSuccess'] },+ status: { observedDigest: 'sha256:bbb' },+}++// A hook already attached to the agent, plus fields this section must never+// touch on save.+const GUARDRAILS: HostGuardrails = {+ hooks: { preCall: [{ id: 'hook-token-compactor', digest: 'sha256:aaa' }] },+ builtins: [{ type: 'prompt-shaping', order: 0, failMode: 'open' }],+ limits: { maxHooksPerPhase: 8 },+}++function render(children: ReactNode) {+ return rtlRender(<ToastProvider>{children}</ToastProvider>)+}++afterEach(cleanup)+beforeEach(() => {+ vi.clearAllMocks()+ confirmMock.mockResolvedValue(true)+ vi.mocked(api.getLlmHooks).mockResolvedValue({ items: [COMPACTOR, RECORDER] } as never)+})++describe('HostGuardrailsSection', () => {+ it('lists one row per referenced hook and phase', async () => {+ render(+ <HostGuardrailsSection+ busy={false}+ canWrite+ initialGuardrails={GUARDRAILS}+ onSave={vi.fn()}+ />+ )++ expect(await screen.findByText('hook-token-compactor')).toBeInTheDocument()+ expect(screen.getByText('Pre-call')).toBeInTheDocument()+ expect(screen.queryByText(/no guardrail hooks on this agent/i)).toBeNull()+ })++ it('clicking a hook opens its guardrail detail page', async () => {+ render(+ <HostGuardrailsSection+ busy={false}+ canWrite+ initialGuardrails={GUARDRAILS}+ onSave={vi.fn()}+ />+ )++ fireEvent.click(await screen.findByRole('button', { name: 'hook-token-compactor' }))++ expect(navigation.push).toHaveBeenCalledWith('/guardrails/hook-token-compactor')+ })++ it('a hook stays clickable for an operator who cannot write', async () => {+ render(+ <HostGuardrailsSection+ busy={false}+ canWrite={false}+ initialGuardrails={GUARDRAILS}+ onSave={vi.fn()}+ />+ )++ fireEvent.click(await screen.findByRole('button', { name: 'hook-token-compactor' }))++ expect(navigation.push).toHaveBeenCalledWith('/guardrails/hook-token-compactor')+ })++ it('empty state when the agent references no hooks', async () => {+ render(<HostGuardrailsSection busy={false} canWrite initialGuardrails={{}} onSave={vi.fn()} />)++ expect(await screen.findByText(/no guardrail hooks on this agent yet/i)).toBeInTheDocument()+ })++ it('Add hook offers only unreferenced hooks and saves with the declared phase and digest', async () => {+ const onSave = vi.fn().mockResolvedValue(undefined)+ render(+ <HostGuardrailsSection busy={false} canWrite initialGuardrails={GUARDRAILS} onSave={onSave} />+ )++ fireEvent.click(await screen.findByRole('button', { name: 'Add hook' }))++ // The already-attached hook must not be offered a second time.+ const option = await screen.findByRole('option', { name: 'hook-tool-use-recorder' })+ expect(screen.queryByRole('option', { name: 'hook-token-compactor' })).toBeNull()++ fireEvent.click(option)+ // Both the section header and the modal footer read "Add hook" — submit is+ // the one inside the dialog.+ fireEvent.click(within(screen.getByRole('dialog')).getByRole('button', { name: 'Add hook' }))++ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1))+ const saved = onSave.mock.calls[0][0] as HostGuardrails+ expect(saved.hooks?.postCallSuccess).toEqual([+ { id: 'hook-tool-use-recorder', digest: 'sha256:bbb' },+ ])+ // The phase the operator never chose stays exactly as it was...+ expect(saved.hooks?.preCall).toEqual([{ id: 'hook-token-compactor', digest: 'sha256:aaa' }])+ // ...and so does everything this section does not edit.+ expect(saved.builtins).toEqual(GUARDRAILS.builtins)+ expect(saved.limits).toEqual(GUARDRAILS.limits)+ })++ it('removing the last hook of a phase drops the phase key rather than leaving it empty', async () => {+ const onSave = vi.fn().mockResolvedValue(undefined)+ render(+ <HostGuardrailsSection busy={false} canWrite initialGuardrails={GUARDRAILS} onSave={onSave} />+ )++ fireEvent.click(+ await screen.findByRole('button', {+ name: 'Remove hook hook-token-compactor from Pre-call',+ })+ )++ await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1))+ const saved = onSave.mock.calls[0][0] as HostGuardrails+ expect(saved.hooks).toEqual({})+ expect(saved.builtins).toEqual(GUARDRAILS.builtins)+ })++ it('a declined confirm leaves the hook in place', async () => {+ confirmMock.mockResolvedValue(false)+ const onSave = vi.fn().mockResolvedValue(undefined)+ render(+ <HostGuardrailsSection busy={false} canWrite initialGuardrails={GUARDRAILS} onSave={onSave} />+ )++ fireEvent.click(+ await screen.findByRole('button', {+ name: 'Remove hook hook-token-compactor from Pre-call',+ })+ )++ await waitFor(() => expect(confirmMock).toHaveBeenCalled())+ expect(onSave).not.toHaveBeenCalled()+ })++ it('offers no write controls when the operator cannot write', async () => {+ render(+ <HostGuardrailsSection+ busy={false}+ canWrite={false}+ initialGuardrails={GUARDRAILS}+ onSave={vi.fn()}+ />+ )++ expect(await screen.findByText('hook-token-compactor')).toBeInTheDocument()+ expect(screen.queryByRole('button', { name: 'Add hook' })).toBeNull()+ expect(screen.queryByRole('button', { name: /^Remove hook/ })).toBeNull()+ })++ it('no longer exposes built-in guardrail editing', async () => {+ render(+ <HostGuardrailsSection+ busy={false}+ canWrite+ initialGuardrails={GUARDRAILS}+ onSave={vi.fn()}+ />+ )++ await screen.findByText('hook-token-compactor')+ expect(screen.queryByText(/built-in/i)).toBeNull()+ expect(screen.queryByRole('button', { name: 'Edit' })).toBeNull()+ })+})diff --git a/control-ui/e2e/host-approval-tools-e2e.spec.ts b/control-ui/e2e/host-approval-tools-e2e.spec.tsindex 03100cfac..654da223d 100644--- a/control-ui/e2e/host-approval-tools-e2e.spec.ts+++ b/control-ui/e2e/host-approval-tools-e2e.spec.ts@@ -74,8 +74,12 @@ async function gotoHostDetails(page: Page) {// The Per-tool approval editor now lives under the consolidated Advanced// tab. The old `/approvals` slug is still served via a 308 redirect, but// navigating to the canonical URL directly keeps this E2E independent of- // that compatibility shim.+ // that compatibility shim. Advanced opens on the Hooks sub-tab, so select+ // Per-tool approval explicitly — the guardrails panel reuses the+ // `.cu-host-approval-section` class, and waiting on it before switching+ // sub-tabs would match the wrong section.await page.goto(`${BASE_UI}/hosts/${encodeURIComponent(HOST_NAME)}/advanced`)+ await page.locator('.cu-advanced-tabs button:has-text("Per-tool approval")').click()await page.waitForSelector('.cu-host-approval-section', { timeout: 20_000 })}