Skip to content

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

TypeScript
35.5 KB
Raw Blame
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 HostDetailsPage from '../../app/hosts/[name]/page'
import * as api from '../../lib/api'
import {
  listCodexConnectionModels,
  listCodexSubscriptionConnections,
} from '../../lib/codexSubscription'
import {
  listGrokConnectionModels,
  listGrokSubscriptionConnections,
} from '../../lib/grokSubscription'
import {
  __resetReadRequestCacheForTests,
  setReadRequestPrincipal,
} from '../../lib/readRequestCache'
import { ToastProvider } from '../Toast'

// Capability consumers load only for a principal confirmed by /me (AuthContext).
beforeEach(() => {
  setReadRequestPrincipal('admin-one', 'admin')
})
afterEach(() => {
  __resetReadRequestCacheForTests()
})

const replaceMock = vi.fn()
const pushMock = vi.fn()
let mockParams: { name: string; tab?: string } = { name: 'foo' }

vi.mock('next/navigation', () => ({
  useParams: () => mockParams,
  usePathname: () => '/agents/foo',
  useRouter: () => ({ push: pushMock, replace: replaceMock }),
  useSearchParams: () => new URLSearchParams(),
}))

vi.mock('../AuthContext', () => ({
  useAuth: () => ({ logout: vi.fn() }),
}))

vi.mock('../Sidebar', () => ({
  Sidebar: () => <aside data-testid="sidebar" />,
}))

vi.mock('../HostIdentityTab', () => ({
  HostIdentityTab: ({ hostName }: { hostName: string }) => (
    <div data-testid="identity-tab">Identity editor for {hostName}</div>
  ),
}))

vi.mock('../HostAccessTab', () => ({
  HostAccessTab: ({ hostName }: { hostName: string }) => (
    <div data-testid="access-tab">Access editor for {hostName}</div>
  ),
}))

vi.mock('../../lib/codexSubscription', async importOriginal => {
  const actual = await importOriginal<typeof import('../../lib/codexSubscription')>()
  return {
    ...actual,
    listCodexSubscriptionConnections: vi.fn().mockResolvedValue([]),
    listCodexConnectionModels: vi.fn().mockResolvedValue([]),
  }
})

vi.mock('../../lib/grokSubscription', async importOriginal => {
  const actual = await importOriginal<typeof import('../../lib/grokSubscription')>()
  return {
    ...actual,
    listGrokSubscriptionConnections: vi.fn().mockRejectedValue({ status: 404 }),
    listGrokConnectionModels: vi.fn().mockResolvedValue([]),
  }
})

vi.mock('../../lib/api', () => ({
  apiGet: vi.fn(),
  apiSend: vi.fn(),
  getAdminTeamAgents: vi.fn(),
  getAdminUserAgents: vi.fn(),
  getAgentTeams: vi.fn(),
  getAgentUsers: vi.fn(),
  getHost: vi.fn(),
  getHostDetailBundle: vi.fn(),
  getMcpServers: vi.fn(),
  updateAdminTeamAgents: vi.fn(),
  updateAdminUserAgents: vi.fn(),
  updateContext: vi.fn(),
  // The model picker loads the operator allowlist via useLlmAllowedModels.
  getLlmModels: vi.fn().mockResolvedValue({ rows: [] }),
  isSilentApiError: vi.fn().mockReturnValue(false),
}))

const host = {
  metadata: { name: 'foo', creationTimestamp: '2026-08-25T12:34:56Z' },
  spec: {
    approval: { tools: { shell_exec: true } },
    channels: ['telegram'],
    description:
      'This agent coordinates customer support requests, gathers the relevant context, and routes each case to the right workflow for follow-up.',
    contextRef: 'ctx',
    host: 'foo-display',
    memory: { enabled: true },
    model: { name: 'gpt-5.4', provider: 'openai' },
    personalization: {
      enabled: true,
      agents: 'Use tools.',
      identity: 'I am Clerum.',
      soul: 'Be helpful.',
      user: 'User context.',
    },
    secretRef: 'openai-secret',
  },
}

function setupApiMocks() {
  ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
    host,
    contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
    secrets: [{ name: 'openai-secret', keys: ['openai-api-key'] }],
    users: [],
    teams: [],
    agentUsers: [],
    agentTeams: [],
  })
  ;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(host)
  ;(api.apiSend as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({})
}

function render(children: ReactNode) {
  return rtlRender(<ToastProvider>{children}</ToastProvider>)
}

function mockGrokGrant() {
  vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
    {
      connectionKey: 'team-grok',
      displayName: 'Team Grok',
      status: 'connected',
      credentialRevision: 2,
      catalogRevision: 5,
      accountFingerprint: 'fp',
      catalogStatus: 'ready',
      catalogSyncedAt: '2026-08-20T00:00:00.000Z',
      lastRefreshAt: '2026-08-20T00:00:00.000Z',
      lastAuthAt: '2026-08-20T00:00:00.000Z',
      refreshLockHeld: false,
      defaultModel: 'grok-4.6',
    },
  ])
  vi.mocked(listGrokConnectionModels).mockResolvedValue([
    { model: 'grok-4.6', enabled: true, stale: false },
  ])
}

function mockCodexGrant() {
  vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
    {
      connectionKey: 'codex-aaa',
      displayName: 'Team A',
      status: 'connected',
      credentialRevision: 1,
      catalogRevision: 1,
      accountFingerprint: 'fp',
      catalogStatus: 'ready',
      catalogSyncedAt: '2026-08-20T00:00:00.000Z',
      lastRefreshAt: '2026-08-20T00:00:00.000Z',
      lastAuthAt: '2026-08-20T00:00:00.000Z',
      refreshLockHeld: false,
      defaultModel: 'gpt-5.1',
    },
  ])
  vi.mocked(listCodexConnectionModels).mockResolvedValue([
    { model: 'gpt-5.1', enabled: true, stale: false },
  ])
}

// Grok primary with a same-broker Grok fallback AND a static OpenAI fallback:
// only the static fallback needs the linked Secret.
function grokFallbackHost(opts: { secretRef: string }) {
  return {
    ...host,
    spec: {
      ...host.spec,
      secretRef: opts.secretRef,
      model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: 'team-grok' },
      llmPolicy: {
        fallbacks: [
          { provider: 'grok-subscription', model: 'grok-4.6' },
          { provider: 'openai', model: 'gpt-4o' },
        ],
      },
    },
  }
}

function mockHostBundle(hostResource: unknown, secrets: Array<{ name: string; keys?: string[] }>) {
  ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
    host: hostResource,
    contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
    secrets,
    users: [],
    teams: [],
    agentUsers: [],
    agentTeams: [],
  })
  ;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(hostResource)
  // Earlier tests override the allowlist; these cases exercise the Secret gate only.
  ;(api.getLlmModels as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({ rows: [] })
}

async function findGrokProviderOption(): Promise<HTMLElement> {
  let option: HTMLElement | null = null
  await waitFor(() => {
    const trigger = screen.getByLabelText('Provider', { selector: '#llm-primary-provider' })
    if (trigger.getAttribute('aria-expanded') !== 'true') fireEvent.click(trigger)
    option = screen.getByRole('option', { name: 'xAI Grok Subscription' })
  })
  return option as unknown as HTMLElement
}

afterEach(() => {
  cleanup()
})

describe('HostDetailsPage identity integration', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    vi.mocked(api.apiGet).mockResolvedValue({
      providers: {
        'codex-subscription': { enabled: true },
        'grok-subscription': { enabled: true },
      },
    })
    mockParams = { name: 'foo' }
    setupApiMocks()
  })

  it('renders the Identity section tab with the current host name', async () => {
    mockParams = { name: 'foo', tab: 'identity' }
    const { container } = render(<HostDetailsPage />)
    expect(await screen.findByTestId('identity-tab')).toHaveTextContent('Identity editor for foo')
    expect(container.querySelector('.cu-agent-detail-card')).not.toBeNull()
  })

  // QA: the header title leads with the display name (spec.host) and NEVER
  // flashes the route slug while loading — a skeleton holds the slot until the
  // first Overview read lands. The eyebrow route URL was removed by product.
  it('skeletonizes the header title while loading, then shows the display name', async () => {
    let resolveBundle: (value: unknown) => void = () => {}
    ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockReturnValue(
      new Promise(resolve => {
        resolveBundle = resolve
      })
    )

    render(<HostDetailsPage />)

    // Loading: skeleton in the title slot; no slug, no route-URL eyebrow.
    expect(document.querySelector('.cu-agent-detail-title-skeleton')).not.toBeNull()
    expect(screen.queryByText('Agent: foo')).toBeNull()
    expect(screen.queryByText('/agents/foo')).toBeNull()

    // QA follow-up: the Overview tab's editable identity card skeletons its
    // name too (two skeletons total) — the slug never flashes there either —
    // and the edit pencil stays hidden until a real name is on screen.
    expect(document.querySelectorAll('.cu-agent-detail-title-skeleton')).toHaveLength(2)
    expect(document.querySelector('.cu-host-overview-identity__name')?.textContent).not.toContain(
      'foo'
    )
    expect(screen.queryByRole('button', { name: 'Edit agent name' })).not.toBeInTheDocument()

    resolveBundle({
      host,
      contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
      secrets: [{ name: 'openai-secret', keys: ['openai-api-key'] }],
      users: [],
      teams: [],
      agentUsers: [],
      agentTeams: [],
    })

    expect(await screen.findByRole('heading', { name: 'Agent: foo-display' })).toBeInTheDocument()
    expect(document.querySelector('.cu-agent-detail-title-skeleton')).toBeNull()
    expect(screen.queryByText('/agents/foo')).toBeNull()

    // Overview identity card now shows the display name with its edit control.
    expect(
      await screen.findByText('foo-display', {
        selector: '.cu-host-overview-identity__name',
      })
    ).toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Edit agent name' })).toBeInTheDocument()
  })

  it('renders the agent detail tabs in order', async () => {
    render(<HostDetailsPage />)

    const tabs = await screen.findAllByRole('tab')

    expect(tabs.map(tab => tab.textContent)).toEqual([
      'Overview',
      'Identity',
      'Models & creds',
      'Connectors',
      'Access',
      'Advanced',
    ])
    expect(tabs.find(tab => tab.textContent === 'Connectors')).toHaveAttribute(
      'href',
      '/agents/foo/connectors'
    )
  })

  it('shows the provider model configuration and routes the pencil to the secret editor page', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    const { container } = render(<HostDetailsPage />)

    const summary = await screen.findByRole('region', { name: 'LLM configuration summary' })
    expect(summary).toHaveTextContent('Primary provider')
    expect(summary).toHaveTextContent('OpenAI')
    expect(summary).toHaveTextContent('gpt-5.4')
    expect(summary).toHaveTextContent('Allowed models · OpenAI')
    expect(summary).toHaveTextContent('All enabled models')
    expect(screen.queryByText('Model name')).not.toBeInTheDocument()
    expect(screen.getByText('LLM Secret')).toBeInTheDocument()
    // Static summary: the credential display uses the same read-only value box
    // as the provider summary (credential + provider + current model).
    expect(container.querySelectorAll('.cu-llm-summary__value')).toHaveLength(3)
    expect(container.querySelector('.cu-agent-detail-card')).toBeNull()
    expect(container.querySelector('.cu-agent-detail-heading')).not.toBeNull()
    expect(container.querySelector('.cu-agent-detail-toolbar')).toBeNull()

    // The secret editor is a full-screen route opened from inside the model
    // editor dialog; nothing stacks on this page.
    fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
    const editorDialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })
    fireEvent.click(
      within(editorDialog).getByRole('button', { name: 'Edit LLM Secret credentials' })
    )

    expect(pushMock).toHaveBeenCalledWith(
      '/secrets/llm/openai-secret/edit?from=%2Fagents%2Ffoo%2Fmodel'
    )
    expect(container.querySelector('.cu-agent-detail-card')).toBeNull()
  })

  it('uses a custom LLM Secret picker with the enabled provider icons', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
      host,
      contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
      secrets: [
        { name: 'openai-secret', keys: ['openai-api-key', 'claude-api-key'] },
        { name: 'zai-secret', keys: ['zai-api-key'] },
      ],
      users: [],
      teams: [],
      agentUsers: [],
      agentTeams: [],
    })

    render(<HostDetailsPage />)

    // Summary: static value display with the provider icons — not a dropdown.
    const summaryName = await screen.findByText('openai-secret')
    const staticValue = summaryName.closest('.cu-llm-summary__value') as HTMLElement
    expect(staticValue).not.toBeNull()
    expect(staticValue.querySelectorAll('img')).toHaveLength(2)
    expect(staticValue.querySelector('img')).toHaveAttribute('src', '/provider-icons/openai.svg')
    expect(staticValue.querySelectorAll('img')[1]).toHaveAttribute(
      'src',
      '/provider-icons/claude.svg'
    )
    expect(screen.queryByRole('button', { name: 'LLM Secret' })).not.toBeInTheDocument()
    expect(
      screen.queryByRole('button', { name: 'Edit LLM Secret credentials' })
    ).not.toBeInTheDocument()
    expect(screen.queryByRole('combobox')).toBeNull()

    fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
    const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })
    const editorPicker = within(dialog).getByRole('button', { name: 'LLM Secret' })
    expect(editorPicker).toBeEnabled()
    fireEvent.click(editorPicker)

    const zaiOption = screen.getByRole('option', { name: /zai-secret/ })
    expect(zaiOption).toHaveTextContent('Z.AI')
    expect(zaiOption.querySelector('img')).toHaveAttribute('src', '/provider-icons/zai.svg')
  })

  it('links the pencil to the shared full-screen editor for the linked secret', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    render(<HostDetailsPage />)

    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })
    const pencil = within(dialog).getByRole('button', { name: 'Edit LLM Secret credentials' })
    expect(pencil).toBeEnabled()
    fireEvent.click(pencil)

    // The additional-provider credential journey itself lives on the
    // secrets/llm/[name]/edit page suite; this page only hands off.
    expect(pushMock).toHaveBeenCalledWith(
      '/secrets/llm/openai-secret/edit?from=%2Fagents%2Ffoo%2Fmodel'
    )
    expect(screen.queryByText('Update LLM secret openai-secret')).not.toBeInTheDocument()
  })

  it('shows a complete ChatGPT assignment without requiring Edit', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
      {
        connectionKey: 'codex-aaa',
        displayName: 'Team A',
        status: 'connected',
        credentialRevision: 1,
        catalogRevision: 1,
        accountFingerprint: 'fp',
        catalogStatus: 'ready',
        catalogSyncedAt: '2026-08-20T00:00:00.000Z',
        lastRefreshAt: '2026-08-20T00:00:00.000Z',
        lastAuthAt: '2026-08-20T00:00:00.000Z',
        refreshLockHeld: false,
        defaultModel: 'gpt-5.1',
      },
    ])
    vi.mocked(listCodexConnectionModels).mockResolvedValue([
      { model: 'gpt-5.1', enabled: true, stale: false },
    ])
    const codexHost = {
      ...host,
      spec: {
        ...host.spec,
        secretRef: undefined,
        model: {
          provider: 'codex-subscription',
          name: 'gpt-5.1',
          connectionRef: 'codex-aaa',
        },
      },
    }
    ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
      host: codexHost,
      contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
      secrets: [],
      users: [],
      teams: [],
      agentUsers: [],
      agentTeams: [],
    })
    render(<HostDetailsPage />)

    const summary = await screen.findByRole('region', { name: 'LLM configuration summary' })
    expect(summary).toHaveTextContent('Current model')
    expect(summary).toHaveTextContent('gpt-5.1')
    expect(screen.getByText('codex-aaa')).toBeInTheDocument()
    expect(screen.queryByText('Team A')).not.toBeInTheDocument()
    expect(listCodexSubscriptionConnections).not.toHaveBeenCalled()
    expect(screen.getByText('Credential')).toBeInTheDocument()
    expect(screen.queryByText('Secret reference')).not.toBeInTheDocument()
    expect(screen.queryByText('Broker-backed — no LLM secret required')).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
    expect(screen.queryByRole('button', { name: 'Save' })).not.toBeInTheDocument()
  })

  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')
    ).not.toBeNull()
    expect(container.querySelector('.cu-host-approval-section .cu-section-title')).toBeNull()
  })

  it('shows the agent description in place of the identifier and truncates long copy', async () => {
    const { container } = render(<HostDetailsPage />)
    const description = await screen.findByTitle(host.spec.description)

    expect(description).toHaveClass('cu-host-overview-identity__description')
    expect(description.textContent).toHaveLength(100)
    expect(description.textContent?.endsWith('…')).toBe(true)
    expect(screen.getByRole('button', { name: 'Edit agent name' })).toBeInTheDocument()
    expect(screen.getByText('Created').nextElementSibling).toHaveTextContent(/2026/)
    expect(screen.queryByText('Last updated')).not.toBeInTheDocument()
    expect(container.querySelector('.cu-host-overview-identity__slug')).toBeNull()
    expect(container.querySelector('.cu-agent-detail-card')).toBeNull()
  })

  it('edits the agent name in a scalar dialog via one PUT without changing the agent slug', async () => {
    render(<HostDetailsPage />)

    expect(screen.queryByLabelText('Agent name')).not.toBeInTheDocument()
    fireEvent.click(await screen.findByRole('button', { name: 'Edit agent name' }))
    expect(screen.getByRole('dialog', { name: 'Edit agent name' })).toBeInTheDocument()
    const nameField = screen.getByLabelText('Agent name')
    expect(nameField).toHaveValue('foo-display')
    fireEvent.change(nameField, { target: { value: 'Product Agents' } })
    fireEvent.click(screen.getByRole('button', { name: 'Save agent name' }))

    await waitFor(() =>
      expect(api.apiSend).toHaveBeenCalledWith('PUT', '/api/v1/admin/hosts/foo', expect.any(Object))
    )

    const calls = (api.apiSend as unknown as ReturnType<typeof vi.fn>).mock.calls
    const puts = calls.filter(c => c[0] === 'PUT' && c[1] === '/api/v1/admin/hosts/foo')
    expect(puts).toHaveLength(1)
    const payload = puts[0][2]
    expect(payload.spec.host).toBe('Product Agents')
    expect(payload.metadata?.name).toBeUndefined()
    expect(calls.some(c => c[0] === 'POST')).toBe(false)
    expect(calls.some(c => c[0] === 'DELETE')).toBe(false)
    expect(replaceMock).not.toHaveBeenCalledWith('/agents/Product Agents')
    expect(pushMock).not.toHaveBeenCalledWith('/agents/Product Agents')
  })

  it('discards an agent-name dialog draft without persisting it', async () => {
    render(<HostDetailsPage />)

    fireEvent.click(await screen.findByRole('button', { name: 'Edit agent name' }))
    fireEvent.change(screen.getByLabelText('Agent name'), {
      target: { value: 'Discarded Draft' },
    })
    fireEvent.click(screen.getByRole('button', { name: 'Cancel editing agent name' }))

    expect(screen.queryByRole('dialog', { name: 'Edit agent name' })).not.toBeInTheDocument()
    expect(screen.getByText('foo-display')).toBeInTheDocument()
    expect(screen.queryByText('Discarded Draft')).not.toBeInTheDocument()
    expect(api.apiSend).not.toHaveBeenCalled()
  })

  it('saves a Codex-only Host without secretRef and keeps metadata.name as identity', async () => {
    const { secretRef: _omit, ...specWithoutSecret } = host.spec
    void _omit
    const codexHost = {
      ...host,
      spec: {
        ...specWithoutSecret,
        model: { provider: 'codex-subscription', name: 'gpt-5.1' },
      },
    }
    ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
      host: codexHost,
      contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
      secrets: [{ name: 'openai-secret' }],
      users: [],
      teams: [],
      agentUsers: [],
      agentTeams: [],
    })
    ;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(codexHost)
    ;(api.getLlmModels as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
      rows: [
        {
          id: 'm-codex',
          provider: 'codex-subscription',
          model: 'gpt-5.1',
          vendor: 'OpenAI',
          display_name: null,
          context_window_tokens: null,
          enabled: true,
          stale: false,
          created_at: '',
          updated_at: '',
        },
      ],
    })
    mockParams = { name: 'foo', tab: 'model' }
    render(<HostDetailsPage />)

    expect(await screen.findByText('No credential assigned')).toBeInTheDocument()
    expect(screen.getByText('Credential')).toBeInTheDocument()
    expect(screen.queryByText('Secret reference')).not.toBeInTheDocument()
    expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()
    fireEvent.click(screen.getByRole('button', { name: 'Edit' }))
    const dialog = screen.getByRole('dialog', { name: 'Edit model & credentials' })
    expect(within(dialog).getByLabelText('Credential')).toBeInTheDocument()
    expect(screen.queryByRole('radio', { name: /ChatGPT subscription/i })).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))
    expect(api.apiSend).not.toHaveBeenCalledWith(
      'PUT',
      '/api/v1/admin/hosts/foo',
      expect.objectContaining({
        spec: expect.objectContaining({
          model: expect.objectContaining({ connectionRef: 'unassigned' }),
        }),
      })
    )
    expect(screen.queryByText('OpenAI Codex Subscription')).not.toBeInTheDocument()
  })

  it('persists a Grok Host connectionRef on save', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    vi.mocked(listGrokSubscriptionConnections).mockResolvedValue([
      {
        connectionKey: 'team-grok',
        displayName: 'Team Grok',
        status: 'connected',
        credentialRevision: 2,
        catalogRevision: 5,
        accountFingerprint: 'fp',
        catalogStatus: 'ready',
        catalogSyncedAt: '2026-08-20T00:00:00.000Z',
        lastRefreshAt: '2026-08-20T00:00:00.000Z',
        lastAuthAt: '2026-08-20T00:00:00.000Z',
        refreshLockHeld: false,
        defaultModel: 'grok-4.6',
      },
    ])
    vi.mocked(listGrokConnectionModels).mockResolvedValue([
      { model: 'grok-4.6', enabled: true, stale: false },
    ])
    const grokHost = {
      ...host,
      spec: {
        ...host.spec,
        secretRef: undefined,
        model: {
          provider: 'grok-subscription',
          name: 'grok-4.6',
          connectionRef: 'team-grok',
        },
      },
    }
    ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
      host: grokHost,
      contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
      secrets: [],
      users: [],
      teams: [],
      agentUsers: [],
      agentTeams: [],
    })
    ;(api.getHost as unknown as ReturnType<typeof vi.fn>).mockResolvedValue(grokHost)
    render(<HostDetailsPage />)
    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    await waitFor(() => expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled())
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))
    await waitFor(() => {
      expect(api.apiSend).toHaveBeenCalledWith(
        'PUT',
        '/api/v1/admin/hosts/foo',
        expect.objectContaining({
          spec: expect.objectContaining({
            model: {
              provider: 'grok-subscription',
              name: 'grok-4.6',
              connectionRef: 'team-grok',
            },
          }),
        })
      )
    })
  })

  it('blocks saving a Grok Host whose static fallback Secret lacks the fallback credential', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    mockGrokGrant()
    const grokHost = grokFallbackHost({ secretRef: 'claude-secret' })
    mockHostBundle(grokHost, [{ name: 'claude-secret', keys: ['claude-api-key'] }])
    render(<HostDetailsPage />)
    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
    })
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))
    expect(
      await screen.findAllByText(/does not contain a usable OpenAI credential/i)
    ).not.toHaveLength(0)
    expect(api.apiSend).not.toHaveBeenCalledWith(
      'PUT',
      '/api/v1/admin/hosts/foo',
      expect.anything()
    )
  })

  it('saves a Grok Host with a same-broker fallback and a static fallback whose Secret is usable', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    mockGrokGrant()
    const grokHost = grokFallbackHost({ secretRef: 'openai-secret' })
    mockHostBundle(grokHost, [{ name: 'openai-secret', keys: ['openai-api-key'] }])
    render(<HostDetailsPage />)
    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
    })
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))
    await waitFor(() => {
      expect(api.apiSend).toHaveBeenCalledWith(
        'PUT',
        '/api/v1/admin/hosts/foo',
        expect.objectContaining({
          spec: expect.objectContaining({
            secretRef: 'openai-secret',
            model: {
              provider: 'grok-subscription',
              name: 'grok-4.6',
              connectionRef: 'team-grok',
            },
          }),
        })
      )
    })
  })

  it('blocks saving a Codex Host whose static fallback Secret lacks the fallback credential', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    mockCodexGrant()
    const codexHost = {
      ...host,
      spec: {
        ...host.spec,
        secretRef: 'claude-secret',
        model: { provider: 'codex-subscription', name: 'gpt-5.1', connectionRef: 'codex-aaa' },
        llmPolicy: { fallbacks: [{ provider: 'openai', model: 'gpt-4o' }] },
      },
    }
    mockHostBundle(codexHost, [{ name: 'claude-secret', keys: ['claude-api-key'] }])
    render(<HostDetailsPage />)
    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    await waitFor(() => {
      expect(screen.getByRole('button', { name: 'Save' })).toBeEnabled()
    })
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))
    expect(
      await screen.findAllByText(/does not contain a usable OpenAI credential/i)
    ).not.toHaveLength(0)
    expect(api.apiSend).not.toHaveBeenCalledWith(
      'PUT',
      '/api/v1/admin/hosts/foo',
      expect.anything()
    )
  })

  it('drops the Codex grant when the primary switches to Grok and blocks Save until a Grok grant is chosen', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    mockCodexGrant()
    mockGrokGrant()
    const codexHost = {
      ...host,
      spec: {
        ...host.spec,
        secretRef: undefined,
        model: { provider: 'codex-subscription', name: 'gpt-5.1', connectionRef: 'codex-aaa' },
      },
    }
    mockHostBundle(codexHost, [])
    render(<HostDetailsPage />)
    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    await waitFor(() => {
      expect(listCodexConnectionModels).toHaveBeenCalledWith(
        'codex-aaa',
        expect.objectContaining({ signal: expect.any(AbortSignal) })
      )
    })
    fireEvent.click(await findGrokProviderOption())
    await waitFor(() => {
      expect(
        screen.getByLabelText('Provider', { selector: '#llm-primary-provider' })
      ).toHaveTextContent('xAI Grok Subscription')
    })
    expect(listGrokConnectionModels).not.toHaveBeenCalledWith('codex-aaa')
    expect(screen.queryByText(/codex-aaa \(unavailable\)/)).not.toBeInTheDocument()
    expect(screen.queryByText(/Could not load Grok grant models/)).not.toBeInTheDocument()
    expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
    fireEvent.click(screen.getByRole('button', { name: 'Save' }))
    expect(api.apiSend).not.toHaveBeenCalledWith(
      'PUT',
      '/api/v1/admin/hosts/foo',
      expect.anything()
    )
  })

  it('keeps Save disabled while the assigned Grok grant catalog has not offered the model', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    mockGrokGrant()
    vi.mocked(listGrokConnectionModels).mockReturnValue(new Promise(() => undefined))
    const grokHost = {
      ...host,
      spec: {
        ...host.spec,
        secretRef: undefined,
        model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: 'team-grok' },
      },
    }
    mockHostBundle(grokHost, [])
    render(<HostDetailsPage />)
    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    await waitFor(() => {
      expect(listGrokConnectionModels).toHaveBeenCalledWith(
        'team-grok',
        expect.objectContaining({ signal: expect.any(AbortSignal) })
      )
    })
    expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled()
  })

  it('hides the Grok provider option when the Grok capability probe reports disabled', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    vi.mocked(api.apiGet).mockResolvedValue({
      providers: {
        'codex-subscription': { enabled: true },
        'grok-subscription': { enabled: false },
      },
    })
    vi.mocked(listGrokSubscriptionConnections).mockRejectedValue({ status: 404 })
    render(<HostDetailsPage />)
    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    await waitFor(() => {
      expect(api.apiGet).toHaveBeenCalledWith(
        '/api/v1/admin/llm/providers/capabilities',
        {},
        expect.objectContaining({ metadataRead: 'subscription-capabilities' })
      )
    })
    fireEvent.click(screen.getByLabelText('Provider', { selector: '#llm-primary-provider' }))
    expect(screen.getByRole('option', { name: /^OpenAI$/ })).toBeInTheDocument()
    expect(screen.queryByRole('option', { name: /xAI Grok Subscription/ })).not.toBeInTheDocument()
  })

  it('does not surface a page error when ChatGPT subscriptions are disabled', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    const err = Object.assign(new Error('disabled'), { status: 404, code: 'disabled' })
    vi.mocked(listCodexSubscriptionConnections).mockRejectedValue(err)
    render(<HostDetailsPage />)

    await screen.findByRole('region', { name: 'LLM configuration summary' })
    expect(screen.queryByText('Could not load ChatGPT subscriptions')).not.toBeInTheDocument()
    expect(screen.queryByText('disabled')).not.toBeInTheDocument()
  })

  it('keeps a second LLM Secret field in existing control-ui styles when Codex has a static fallback', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    vi.mocked(listCodexSubscriptionConnections).mockResolvedValue([
      {
        connectionKey: 'codex-aaa',
        displayName: 'Team A',
        status: 'connected',
        credentialRevision: 1,
        catalogRevision: 1,
        accountFingerprint: 'fp',
        catalogStatus: 'ready',
        catalogSyncedAt: '2026-08-20T00:00:00.000Z',
        lastRefreshAt: '2026-08-20T00:00:00.000Z',
        lastAuthAt: '2026-08-20T00:00:00.000Z',
        refreshLockHeld: false,
        defaultModel: 'gpt-5.1',
      },
    ])
    vi.mocked(listCodexConnectionModels).mockResolvedValue([
      { model: 'gpt-5.1', enabled: true, stale: false },
    ])
    const fallbackHost = {
      ...host,
      spec: {
        ...host.spec,
        secretRef: 'openai-secret',
        model: {
          provider: 'codex-subscription',
          name: 'gpt-5.1',
          connectionRef: 'codex-aaa',
        },
        llmPolicy: { fallbacks: [{ provider: 'openai', model: 'gpt-4o' }] },
      },
    }
    ;(api.getHostDetailBundle as unknown as ReturnType<typeof vi.fn>).mockResolvedValue({
      host: fallbackHost,
      contexts: [{ metadata: { name: 'ctx' }, spec: { contextId: 'ctx' } }],
      secrets: [{ name: 'openai-secret', keys: ['openai-api-key'] }],
      users: [],
      teams: [],
      agentUsers: [],
      agentTeams: [],
    })
    render(<HostDetailsPage />)

    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })
    expect(within(dialog).getByLabelText('Credential')).toBeInTheDocument()
    expect(within(dialog).getByLabelText('LLM Secret')).toBeInTheDocument()
    expect(within(dialog).getByLabelText('Credential')).toBeEnabled()
    expect(within(dialog).getByLabelText('LLM Secret')).toBeEnabled()
    expect(dialog.querySelectorAll('.cu-llm-secret-control')).toHaveLength(2)
    expect(dialog.querySelectorAll('.cu-field__hint').length).toBeGreaterThanOrEqual(2)
    expect(
      within(dialog).getByRole('button', { name: 'Edit LLM Secret credentials' })
    ).toBeInTheDocument()
  })

  it('collapses the fallback providers section by default in the model editor', async () => {
    mockParams = { name: 'foo', tab: 'model' }
    render(<HostDetailsPage />)

    fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
    const dialog = await screen.findByRole('dialog', { name: 'Edit model & credentials' })

    // Collapsed by default: the toggle is closed and the policy editor
    // (including its add-fallback affordance) is not rendered.
    const toggle = within(dialog).getByRole('button', { name: /Fallback providers/ })
    expect(toggle).toHaveAttribute('aria-expanded', 'false')
    expect(
      within(dialog).queryByRole('region', { name: 'Fallback policy' })
    ).not.toBeInTheDocument()

    // Expanding still reveals the full editor.
    fireEvent.click(toggle)
    expect(toggle).toHaveAttribute('aria-expanded', 'true')
    expect(within(dialog).getByRole('region', { name: 'Fallback policy' })).toBeInTheDocument()
    expect(
      within(dialog).getByRole('button', { name: 'Add fallback provider' })
    ).toBeInTheDocument()
  })
})