Skip to content

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

TypeScript
28.4 KB
Raw Blame
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'
import {
  type GfsMutationResponse,
  type GfsSubjectInput,
  apiGet,
  deleteGfsGrant,
  deleteGfsShare,
  getAdminTeams,
  getAdminUsers,
  getGfsGrants,
  getGfsShares,
  getHosts,
  getRecipes,
  putGfsGrant,
} from '@lib/api'
import { GfsGrantPanel } from '../GfsGrantPanel'
import { ToastProvider } from '../Toast'

vi.mock('@lib/api', () => ({
  apiGet: vi.fn(),
  getAdminTeams: vi.fn(),
  getAdminUsers: vi.fn(),
  getHosts: vi.fn(),
  getRecipes: vi.fn(),
  getGfsGrants: vi.fn(),
  getGfsShares: vi.fn(),
  deleteGfsGrant: vi.fn(),
  deleteGfsShare: vi.fn(),
  putGfsGrant: vi.fn(),
}))

const mockApiGet = vi.mocked(apiGet)
const mockGetAdminUsers = vi.mocked(getAdminUsers)
const mockGetAdminTeams = vi.mocked(getAdminTeams)
const mockGetHosts = vi.mocked(getHosts)
const mockGetRecipes = vi.mocked(getRecipes)
const mockGetGfsGrants = vi.mocked(getGfsGrants)
const mockGetGfsShares = vi.mocked(getGfsShares)
const mockDeleteGfsGrant = vi.mocked(deleteGfsGrant)
const mockDeleteGfsShare = vi.mocked(deleteGfsShare)
const mockPutGfsGrant = vi.mocked(putGfsGrant)

const resource = {
  resourceId: 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa',
  name: 'report.md',
  gfsUri: 'gfs://main/report',
  kind: 'file',
}

const userSubject = { type: 'user', id: '11111111-1111-1111-1111-111111111111' } as const
const userRowTestId = `gfs-access-row-user:${userSubject.id}`
const teamSubject = { type: 'team', id: '22222222-2222-2222-2222-222222222222' } as const
const statefulHostSubject = { type: 'host', id: '1st:mcp-host/chatllm' } as const
const statelessHostSubject = { type: 'host', id: '1st:mcp-host/chatllm-stateless' } as const
const workflowHostSubject = {
  type: 'host',
  id: '3rd:sandbox-recipes/sandbox-ui-hello',
} as const
const operatorSubject = { type: 'operator' } as const

function successfulMutation(...updated: GfsSubjectInput[]): GfsMutationResponse {
  return { ok: true, resourceId: resource.resourceId, updated, count: updated.length }
}

function renderPanel(target = resource) {
  return render(
    <ToastProvider>
      <GfsGrantPanel resource={target} />
    </ToastProvider>
  )
}

async function openSubjectPicker() {
  const input = await screen.findByRole('combobox', {
    name: 'Add people, teams, agents, or workflows',
  })
  fireEvent.mouseDown(input)
  fireEvent.focus(input)
  return screen.findByRole('listbox', { name: 'Available grant subjects' })
}

async function chooseSubjects(...names: string[]) {
  await openSubjectPicker()
  for (const name of names) fireEvent.click(screen.getByRole('option', { name }))
}

function selectPermission(name: string) {
  fireEvent.click(screen.getByRole('button', { name: 'Access role for selected recipients' }))
  fireEvent.click(screen.getByRole('option', { name: name === 'Read' ? 'Read' : 'Editor' }))
}

async function submit(action: 'Share') {
  fireEvent.click(screen.getByRole('button', { name: action }))
}

describe('GfsGrantPanel bulk access', () => {
  beforeEach(() => {
    vi.clearAllMocks()
    // The bulk suite exercises direct rows; resolve any path-less target to a
    // root-level resource so the inherited walk has zero ancestors to derive.
    mockApiGet.mockResolvedValue({ resourceId: resource.resourceId, path: '/', kind: 'file' })
    mockGetAdminUsers.mockResolvedValue({
      items: [
        {
          id: '11111111-1111-1111-1111-111111111111',
          email: '[email protected]',
          name: 'Ada Lovelace',
          displayName: 'Ada Lovelace',
          picture: null,
          activeTeamCount: 1,
        },
      ],
    })
    mockGetAdminTeams.mockResolvedValue({
      items: [{ id: '22222222-2222-2222-2222-222222222222', name: 'Research', memberCount: 2 }],
    })
    mockGetHosts.mockResolvedValue({
      items: [
        { metadata: { namespace: 'mcp-host', name: 'chatllm' } },
        {
          metadata: { namespace: 'mcp-host', name: 'chatllm-stateless' },
          spec: { lifecycle: { stateless: true } },
        },
      ],
    })
    mockGetRecipes.mockResolvedValue({
      items: [{ metadata: { namespace: 'sandbox-recipes', name: 'sandbox-ui-hello' } }],
    })
    mockGetGfsGrants.mockResolvedValue({ items: [] })
    mockGetGfsShares.mockResolvedValue({ items: [] })
    mockDeleteGfsGrant.mockResolvedValue(undefined)
    mockDeleteGfsShare.mockResolvedValue(undefined)
  })

  it('loads direct access on mount and revokes the selected persisted row', async () => {
    mockGetGfsGrants
      .mockResolvedValueOnce({
        items: [
          {
            id: '33333333-3333-3333-3333-333333333333',
            drive: 'main',
            resourceId: resource.resourceId,
            subject: userSubject,
            permissions: ['read', 'write'],
            inherit: false,
          },
        ],
      })
      .mockResolvedValueOnce({ items: [] })
    renderPanel()

    const existing = await screen.findByRole('region', { name: 'People with access' })
    expect(within(existing).getByText('Ada Lovelace')).toBeTruthy()
    const userRow = within(existing).getByTestId(userRowTestId)
    expect(userRow.querySelector('[data-subject-kind="user"] svg')).not.toBeNull()
    expect(within(userRow).queryByText(/direct grant|\buser\b/i)).toBeNull()
    expect(
      within(existing).getByRole('button', { name: 'Access role for Ada Lovelace' })
    ).toHaveTextContent('Editor')
    fireEvent.click(within(existing).getByRole('button', { name: 'Actions for Ada Lovelace' }))
    fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove access' }))
    const dialog = await screen.findByRole('alertdialog')
    fireEvent.click(within(dialog).getByRole('button', { name: 'Remove access' }))

    await waitFor(() =>
      expect(mockDeleteGfsGrant).toHaveBeenCalledWith('33333333-3333-3333-3333-333333333333')
    )
    await waitFor(() => expect(within(existing).getByText('No one has access yet.')).toBeTruthy())
    expect(mockGetGfsGrants).toHaveBeenCalledTimes(2)
    expect(mockGetGfsShares).toHaveBeenCalledTimes(2)
  })

  it('shows each existing principal with its entity icon and no access-source metadata', async () => {
    mockGetGfsGrants.mockResolvedValue({
      items: [
        {
          id: '10000000-0000-0000-0000-000000000001',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          inherit: false,
        },
        {
          id: '10000000-0000-0000-0000-000000000002',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: teamSubject,
          permissions: ['read'],
          inherit: false,
        },
        {
          id: '10000000-0000-0000-0000-000000000003',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: statefulHostSubject,
          permissions: ['read'],
          inherit: false,
        },
        {
          id: '10000000-0000-0000-0000-000000000004',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: workflowHostSubject,
          permissions: ['read'],
          inherit: false,
        },
        {
          id: '10000000-0000-0000-0000-000000000005',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: operatorSubject,
          permissions: ['read'],
          inherit: false,
        },
      ],
    })
    renderPanel()

    const expectedKinds = [
      ['Ada Lovelace', 'user'],
      ['Research', 'team'],
      ['chatllm (Stateful)', 'agent'],
      ['sandbox-ui-hello', 'workflow'],
      ['Operator', 'operator'],
    ] as const
    for (const [label, kind] of expectedKinds) {
      const row = (await screen.findByText(label)).closest('[data-testid^="gfs-access-row-"]')
      expect(row?.querySelector(`[data-subject-kind="${kind}"] svg`)).not.toBeNull()
    }
    expect(screen.queryByText(/direct grant|direct share/i)).toBeNull()
  })

  it('changes an existing member between Editor and Read', async () => {
    const persistedGrant = {
      id: '33333333-3333-3333-3333-333333333333',
      drive: 'main',
      resourceId: resource.resourceId,
      subject: userSubject,
      permissions: ['read', 'write', 'delete', 'manage_acl', 'share'],
      inherit: false,
    }
    mockGetGfsGrants
      .mockResolvedValueOnce({ items: [persistedGrant] })
      .mockResolvedValueOnce({ items: [{ ...persistedGrant, permissions: ['read', 'share'] }] })
    mockPutGfsGrant.mockResolvedValue(successfulMutation(userSubject))
    renderPanel()

    const role = await screen.findByRole('button', { name: 'Access role for Ada Lovelace' })
    expect(role).toHaveTextContent('Editor')
    fireEvent.click(role)
    expect(screen.getByRole('listbox').parentElement?.parentElement).toBe(document.body)
    fireEvent.click(screen.getByRole('option', { name: 'Read' }))

    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenCalledWith({
        drive: 'main',
        resourceId: resource.resourceId,
        subject: userSubject,
        permissions: ['read', 'share'],
        inherit: false,
      })
    )
    await waitFor(() =>
      expect(
        screen.getByRole('button', { name: 'Access role for Ada Lovelace' })
      ).toHaveTextContent('Read')
    )
  })

  it('merges a legacy grant and share for the same principal into one toggleable row', async () => {
    mockGetGfsGrants.mockResolvedValue({
      items: [
        {
          id: '33333333-3333-3333-3333-333333333333',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          inherit: false,
        },
      ],
    })
    mockGetGfsShares.mockResolvedValue({
      items: [
        {
          id: '44444444-4444-4444-4444-444444444444',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          includeDescendants: true,
        },
      ],
    })
    mockPutGfsGrant.mockResolvedValue(successfulMutation(userSubject))

    renderPanel()

    const existing = await screen.findByRole('region', { name: 'People with access' })
    // ONE row for the principal — not one per backend row kind.
    expect(within(existing).getAllByText('Ada Lovelace')).toHaveLength(1)
    expect(within(existing).queryByText(/direct grant|direct share|\buser\b/i)).toBeNull()
    expect(within(existing).getByRole('button', { name: 'Actions for Ada Lovelace' })).toBeTruthy()
    // The descendant-coverage badge stays out of the row.
    expect(within(existing).queryByText('Includes contents')).toBeNull()

    // R1-M5: a role change rewrites only the grant row — with its OWN scope
    // flag (false here; the share's includeDescendants is never OR'd in) —
    // and the legacy share row survives.
    fireEvent.click(within(existing).getByRole('button', { name: 'Access role for Ada Lovelace' }))
    fireEvent.click(screen.getByRole('option', { name: 'Editor' }))

    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenCalledWith({
        drive: 'main',
        resourceId: resource.resourceId,
        subject: userSubject,
        permissions: ['read', 'write', 'delete', 'manage_acl', 'share'],
        inherit: false,
      })
    )
    expect(mockDeleteGfsShare).not.toHaveBeenCalled()
  })

  // RP-032 — a Read DOWNGRADE on a merged grant+share row revokes the
  // sharing entry that still grants Editor (the server has no share-update
  // surface), while the grant is rewritten with its OWN scope flag. A Read
  // sharing entry is not a conflict and survives.
  it('revokes the conflicting sharing entry when a merged grant and share row is downgraded', async () => {
    const EDITOR_SHARE_ID = '55555555-5555-4555-8555-555555555555'
    const READ_SHARE_ID = '66666666-6666-4666-8666-666666666666'
    mockGetGfsGrants.mockResolvedValue({
      items: [
        {
          id: '33333333-3333-3333-3333-333333333333',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read', 'write'],
          inherit: false,
        },
      ],
    })
    mockGetGfsShares.mockResolvedValue({
      items: [
        {
          id: EDITOR_SHARE_ID,
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read', 'write'],
          includeDescendants: true,
        },
        {
          id: READ_SHARE_ID,
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          includeDescendants: true,
        },
      ],
    })
    mockPutGfsGrant.mockResolvedValue(successfulMutation(userSubject))

    renderPanel()

    const existing = await screen.findByRole('region', { name: 'People with access' })
    fireEvent.click(within(existing).getByRole('button', { name: 'Access role for Ada Lovelace' }))
    fireEvent.click(screen.getByRole('option', { name: 'Read' }))

    // The grant keeps its OWN scope flag (false) — the shares' descendant
    // coverage is never OR'd into the grant write.
    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenCalledWith({
        drive: 'main',
        resourceId: resource.resourceId,
        subject: userSubject,
        permissions: ['read', 'share'],
        inherit: false,
      })
    )
    // Only the CONFLICTING entry is revoked; the Read entry survives.
    await waitFor(() => expect(mockDeleteGfsShare).toHaveBeenCalledWith(EDITOR_SHARE_ID))
    expect(mockDeleteGfsShare).not.toHaveBeenCalledWith(READ_SHARE_ID)
    expect(mockDeleteGfsShare).toHaveBeenCalledTimes(1)
  })

  // R1-M5 — a share-only principal has no grant to rewrite and no
  // share-update surface: the role control is disabled and a role change can
  // never migrate the share into a grant. Explicit grant creation through the
  // composer is the only path that creates grants.
  it('disables the role toggle for a share-only principal instead of migrating it', async () => {
    mockGetGfsShares.mockResolvedValue({
      items: [
        {
          id: '44444444-4444-4444-4444-444444444444',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          includeDescendants: true,
        },
      ],
    })
    mockPutGfsGrant.mockResolvedValue(successfulMutation(userSubject))

    renderPanel()

    const existing = await screen.findByRole('region', { name: 'People with access' })
    const role = await within(existing).findByRole('button', {
      name: 'Access role for Ada Lovelace',
    })
    expect(role).toHaveTextContent('Read')
    expect(within(existing).queryByText(/direct share|\buser\b/i)).toBeNull()

    // The dropdown is disabled: no selection, no migration, no deletion.
    expect(role.hasAttribute('disabled')).toBe(true)
    fireEvent.click(role)
    expect(screen.queryByRole('option', { name: 'Editor' })).toBeNull()
    await waitFor(() => expect(mockPutGfsGrant).not.toHaveBeenCalled())
    expect(mockDeleteGfsShare).not.toHaveBeenCalled()
  })

  it('sorts access records by visible principal identity', async () => {
    mockGetAdminUsers.mockResolvedValue({
      items: [
        {
          id: '11111111-1111-1111-1111-111111111111',
          email: '[email protected]',
          name: 'Ada Lovelace',
          displayName: 'Ada Lovelace',
          picture: null,
          activeTeamCount: 1,
        },
        {
          id: '11111111-1111-1111-1111-111111111110',
          email: '[email protected]',
          name: 'Ada Lovelace',
          displayName: 'Ada Lovelace',
          picture: null,
          activeTeamCount: 1,
        },
      ],
    })
    mockGetGfsGrants.mockResolvedValue({
      items: [
        {
          id: '77777777-7777-7777-7777-777777777777',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: { type: 'operator' },
          permissions: ['read'],
          inherit: false,
        },
        {
          id: '33333333-3333-3333-3333-333333333333',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          inherit: false,
        },
        {
          id: '22222222-2222-2222-2222-222222222222',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: { type: 'user', id: '11111111-1111-1111-1111-111111111110' },
          permissions: ['read'],
          inherit: false,
        },
      ],
    })
    renderPanel()

    const list = await screen.findByRole('list', { name: 'Resource access' })
    await waitFor(() => expect(within(list).getAllByText('Ada Lovelace')).toHaveLength(2))
    const rows = within(list).getAllByRole('listitem')
    expect(rows.map(row => row.textContent)).toEqual([
      expect.stringContaining('Ada Lovelace'),
      expect.stringContaining('Ada Lovelace'),
      expect.stringContaining('Operator'),
    ])
    expect(rows.map(row => row.getAttribute('data-access-id'))).toEqual([
      '22222222-2222-2222-2222-222222222222',
      '33333333-3333-3333-3333-333333333333',
      '77777777-7777-7777-7777-777777777777',
    ])
  })

  it('self-heals a row that another admin already revoked without hiding other errors', async () => {
    mockGetGfsGrants
      .mockResolvedValueOnce({
        items: [
          {
            id: '55555555-5555-5555-5555-555555555555',
            drive: 'main',
            resourceId: resource.resourceId,
            subject: userSubject,
            permissions: ['read'],
            inherit: false,
          },
        ],
      })
      .mockResolvedValueOnce({ items: [] })
    mockDeleteGfsGrant.mockRejectedValueOnce(
      Object.assign(new Error('404 grant_not_found'), {
        status: 404,
        code: 'grant_not_found',
      })
    )
    renderPanel()
    const existing = await screen.findByRole('region', { name: 'People with access' })
    fireEvent.click(within(existing).getByRole('button', { name: 'Actions for Ada Lovelace' }))
    fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove access' }))
    const dialog = await screen.findByRole('alertdialog')
    fireEvent.click(within(dialog).getByRole('button', { name: 'Remove access' }))

    expect(await screen.findByText('Access was already removed.')).toBeTruthy()
    await waitFor(() => expect(within(existing).getByText('No one has access yet.')).toBeTruthy())
    expect(screen.queryByRole('alert')).toBeNull()
    expect(mockGetGfsGrants).toHaveBeenCalledTimes(2)
  })

  it('surfaces a non-idempotent revoke failure and keeps the persisted row visible', async () => {
    mockGetGfsGrants.mockResolvedValue({
      items: [
        {
          id: '66666666-6666-6666-6666-666666666666',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          inherit: false,
        },
      ],
    })
    mockDeleteGfsGrant.mockRejectedValueOnce(
      Object.assign(new Error('403 not_manager'), {
        status: 403,
        code: 'not_manager',
      })
    )
    renderPanel()
    const existing = await screen.findByRole('region', { name: 'People with access' })
    fireEvent.click(within(existing).getByRole('button', { name: 'Actions for Ada Lovelace' }))
    fireEvent.click(await screen.findByRole('menuitem', { name: 'Remove access' }))
    const dialog = await screen.findByRole('alertdialog')
    fireEvent.click(within(dialog).getByRole('button', { name: 'Remove access' }))

    expect(await screen.findByRole('alert')).toHaveTextContent('403 not_manager')
    expect(within(existing).getByText('Ada Lovelace')).toBeTruthy()
    expect(screen.queryByText('Access was already removed.')).toBeNull()
    expect(mockGetGfsGrants).toHaveBeenCalledTimes(1)
  })

  it('keeps the newest post-mutation hydration when the initial request resolves late', async () => {
    let resolveInitialGrants!: (value: Awaited<ReturnType<typeof getGfsGrants>>) => void
    const initialGrants = new Promise<Awaited<ReturnType<typeof getGfsGrants>>>(resolve => {
      resolveInitialGrants = resolve
    })
    mockGetGfsGrants.mockReturnValueOnce(initialGrants).mockResolvedValueOnce({
      items: [
        {
          id: '44444444-4444-4444-4444-444444444444',
          drive: 'main',
          resourceId: resource.resourceId,
          subject: userSubject,
          permissions: ['read'],
          inherit: false,
        },
      ],
    })
    mockPutGfsGrant.mockResolvedValue(successfulMutation(userSubject))
    renderPanel()
    await waitFor(() => expect(mockGetGfsGrants).toHaveBeenCalledTimes(1))
    const initialSignal = mockGetGfsGrants.mock.calls[0][2]
    await chooseSubjects('Ada Lovelace')
    selectPermission('Read')
    await submit('Share')

    const existing = await screen.findByRole('region', { name: 'People with access' })
    expect(await within(existing).findByTestId(userRowTestId)).toBeTruthy()
    expect(initialSignal?.aborted).toBe(true)
    resolveInitialGrants({ items: [] })

    await waitFor(() => expect(within(existing).getByText('Ada Lovelace')).toBeTruthy())
    expect(within(existing).queryByText('No one has access yet.')).toBeNull()
  })

  it('aborts the active access hydration when the panel unmounts', async () => {
    mockGetGfsGrants.mockReturnValueOnce(new Promise(() => undefined))
    const panel = renderPanel()
    await waitFor(() => expect(mockGetGfsGrants).toHaveBeenCalledTimes(1))
    const signal = mockGetGfsGrants.mock.calls[0][2]

    panel.unmount()

    expect(signal?.aborted).toBe(true)
  })

  it('offers users, teams, canonical hosts, and singular operator without contexts', async () => {
    renderPanel()
    const listbox = await openSubjectPicker()

    expect(within(listbox).getByRole('option', { name: 'Ada Lovelace' })).toBeTruthy()
    expect(within(listbox).getByRole('option', { name: 'Research' })).toBeTruthy()
    expect(within(listbox).getByRole('option', { name: 'chatllm (Stateful)' })).toBeTruthy()
    expect(
      within(listbox).getByRole('option', { name: 'chatllm-stateless (Stateless)' })
    ).toBeTruthy()
    expect(within(listbox).queryByRole('option', { name: 'First-party agent runtime' })).toBeNull()
    expect(within(listbox).getByRole('option', { name: 'sandbox-ui-hello' })).toBeTruthy()
    expect(within(listbox).getByRole('option', { name: 'Operator' })).toBeTruthy()
    expect(within(listbox).queryByRole('option', { name: /context/i })).toBeNull()
  })

  it('submits one ordered mixed bulk grant and enforces the host UI permission matrix', async () => {
    mockPutGfsGrant.mockResolvedValue(
      successfulMutation(
        userSubject,
        teamSubject,
        statefulHostSubject,
        statelessHostSubject,
        workflowHostSubject
      )
    )
    renderPanel()
    await chooseSubjects('Ada Lovelace', 'Research')
    selectPermission('Editor')
    await chooseSubjects('chatllm (Stateful)', 'chatllm-stateless (Stateless)', 'sandbox-ui-hello')

    expect(screen.getByText(/use read\/write access only/i)).toBeTruthy()
    expect(
      screen.getByRole('button', { name: 'Access role for selected recipients' })
    ).toHaveTextContent('Editor')
    await submit('Share')

    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenCalledWith({
        drive: 'main',
        resourceId: resource.resourceId,
        subjects: [
          { type: 'user', id: '11111111-1111-1111-1111-111111111111' },
          { type: 'team', id: '22222222-2222-2222-2222-222222222222' },
          { type: 'host', id: '1st:mcp-host/chatllm' },
          { type: 'host', id: '1st:mcp-host/chatllm-stateless' },
          { type: 'host', id: '3rd:sandbox-recipes/sandbox-ui-hello' },
        ],
        permissions: ['read', 'write'],
        inherit: false,
      })
    )
    await waitFor(() => expect(mockGetGfsGrants).toHaveBeenCalledTimes(2))
  })

  it('shows scope and role only after a recipient is selected', async () => {
    const directory = { ...resource, name: 'reports', kind: 'directory' as const }
    renderPanel(directory)
    expect(screen.queryByRole('button', { name: 'Share' })).toBeNull()
    expect(screen.queryByRole('checkbox', { name: /Include contents/ })).toBeNull()
    await chooseSubjects('Ada Lovelace', 'Research')
    expect(screen.getByRole('button', { name: 'Share' })).toBeEnabled()
    expect(screen.getByRole('checkbox', { name: /Include contents/ })).toBeChecked()
    expect(
      screen.getByRole('button', { name: 'Access role for selected recipients' })
    ).toHaveTextContent('Read')
  })

  it('keeps operator singular and prevents mixing it with bulk subjects', async () => {
    mockPutGfsGrant.mockResolvedValue(successfulMutation(operatorSubject))
    renderPanel()
    await chooseSubjects('Ada Lovelace', 'Operator')

    expect(screen.queryByRole('button', { name: 'Remove Ada Lovelace' })).toBeNull()
    expect(screen.getByRole('button', { name: 'Remove Operator' })).toBeTruthy()
    selectPermission('Read')
    await submit('Share')

    await waitFor(() =>
      expect(mockPutGfsGrant).toHaveBeenCalledWith({
        drive: 'main',
        resourceId: resource.resourceId,
        subject: { type: 'operator' },
        permissions: ['read', 'share'],
        inherit: false,
      })
    )
  })

  it('preserves the form after rejection and resets it only after success', async () => {
    mockPutGfsGrant
      .mockRejectedValueOnce(
        Object.assign(new Error('403 escalation_rejected'), {
          code: 'escalation_rejected',
          serverMessage: 'Requested permissions exceed operator authority.',
          invalidIndexes: [1],
        })
      )
      .mockResolvedValueOnce(successfulMutation(userSubject, teamSubject))
    renderPanel()
    await chooseSubjects('Ada Lovelace', 'Research')
    selectPermission('Write')
    await submit('Share')

    expect(await screen.findByRole('alert')).toHaveTextContent(
      'escalation_rejected: Requested permissions exceed operator authority. (invalid indexes: 1)'
    )
    expect(screen.getByRole('button', { name: 'Remove Ada Lovelace' })).toBeTruthy()
    expect(screen.getByRole('button', { name: 'Remove Research' })).toBeTruthy()
    expect(
      screen.getByRole('button', { name: 'Access role for selected recipients' })
    ).toHaveTextContent('Editor')

    await submit('Share')
    await waitFor(() => expect(mockPutGfsGrant).toHaveBeenCalledTimes(2))
    expect(screen.queryByRole('button', { name: 'Remove Ada Lovelace' })).toBeNull()
    expect(screen.queryByRole('button', { name: 'Access role for selected recipients' })).toBeNull()
  })

  it('does not duplicate the machine code when the server message matches it', async () => {
    mockPutGfsGrant.mockRejectedValue(
      Object.assign(new Error('400 subjects_invalid'), {
        code: 'subjects_invalid',
        serverMessage: 'subjects_invalid',
      })
    )
    renderPanel()
    await chooseSubjects('Ada Lovelace')
    selectPermission('Read')
    await submit('Share')

    const alert = await screen.findByRole('alert')
    expect(alert).toHaveTextContent('subjects_invalid')
    expect(alert).not.toHaveTextContent('subjects_invalid: subjects_invalid')
  })

  it('adapts the Editor role to the read/write-only host permission model', async () => {
    renderPanel()
    await chooseSubjects('Ada Lovelace')
    selectPermission('Editor')
    await chooseSubjects('chatllm (Stateful)')

    expect(screen.getByText(/use read\/write access only/i)).toBeTruthy()
    fireEvent.click(screen.getByRole('button', { name: 'Remove chatllm (Stateful)' }))

    expect(
      screen.getByRole('button', { name: 'Access role for selected recipients' })
    ).toHaveTextContent('Editor')
    selectPermission('Read')
  })

  it('caps the UI selection at 100 subjects', async () => {
    mockGetAdminUsers.mockResolvedValue({
      items: Array.from({ length: 101 }, (_, index) => ({
        id: `10000000-0000-0000-0000-${String(index).padStart(12, '0')}`,
        email: `user-${index + 1}@example.test`,
        name: `Bulk User ${String(index + 1).padStart(3, '0')}`,
        displayName: `Bulk User ${String(index + 1).padStart(3, '0')}`,
        picture: null,
        activeTeamCount: 0,
      })),
    })
    renderPanel()
    const listbox = await openSubjectPicker()
    for (let index = 1; index <= 101; index += 1) {
      const option = listbox.querySelector<HTMLButtonElement>('[role="option"]')
      expect(option).not.toBeNull()
      fireEvent.click(option!)
    }

    expect(await screen.findByRole('alert')).toHaveTextContent('You can select up to 100 subjects.')
    expect(screen.getAllByRole('button', { name: /^Remove Bulk User/ })).toHaveLength(100)
    expect(screen.queryByRole('button', { name: 'Remove Bulk User 101' })).toBeNull()
  }, 15_000)
})