Skip to content

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

TypeScript
20.7 KB
Raw Blame
'use client'

import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { useRouter } from 'next/navigation'
import { DataTable, DialogShell, TableViewport } from '@clerum/frontend-components'
import { useConfirmDialog } from '@components/ConfirmDialog'
import { RowActionsMenu } from '@components/RowActionsMenu'
import { SelectionDropdown } from '@components/SelectionDropdown'
import { TabBar } from '@components/TabBar'
import { useToast } from '@components/Toast'
import { CONTROL_ROUTES } from '@constants/routes'
import { applyAgentAccessCompatibilityUpdate } from '@lib/agentAccessCompatibility'
import {
  getAdminTeamAgents,
  getAdminTeamContexts,
  getAdminTeams,
  getAdminUserAgents,
  getAdminUserContexts,
  getAdminUsers,
  getAgentTeams,
  getAgentUsers,
  getContexts,
  getHosts,
  updateAdminTeamAgents,
  updateAdminTeamContexts,
  updateAdminUserAgents,
  updateAdminUserContexts,
} from '@lib/api'
import type {
  AccessSubTab,
  AccessTeamDirectoryRow,
  AccessTeamRow,
  AccessUserRow,
  HostAccessTabProps,
} from './types'

const ACCESS_SUB_TABS: { key: AccessSubTab; label: string }[] = [
  { key: 'members', label: 'Members' },
  { key: 'teams', label: 'Teams' },
]

export function HostAccessTab({ hostName, onActionsChange }: HostAccessTabProps) {
  const router = useRouter()
  const { confirm, confirmDialog } = useConfirmDialog()
  const { showToast } = useToast()
  const mountedRef = useRef(true)
  const loadRequestId = useRef(0)

  const [subTab, setSubTab] = useState<AccessSubTab>('members')
  const [allUsers, setAllUsers] = useState<AccessUserRow[]>([])
  const [allTeams, setAllTeams] = useState<AccessTeamDirectoryRow[]>([])
  const [usersWithAccess, setUsersWithAccess] = useState<AccessUserRow[]>([])
  const [teamsWithAccess, setTeamsWithAccess] = useState<AccessTeamRow[]>([])
  const [selectedUserIdsToGrant, setSelectedUserIdsToGrant] = useState<string[]>([])
  const [selectedTeamIdsToGrant, setSelectedTeamIdsToGrant] = useState<string[]>([])
  const [showAddUser, setShowAddUser] = useState(false)
  const [showAddTeam, setShowAddTeam] = useState(false)
  const [initialLoading, setInitialLoading] = useState(true)
  const [busy, setBusy] = useState(false)
  const [error, setError] = useState('')

  useEffect(() => {
    mountedRef.current = true
    return () => {
      mountedRef.current = false
    }
  }, [])

  const loadAccess = useCallback(async () => {
    const requestId = loadRequestId.current + 1
    loadRequestId.current = requestId
    setInitialLoading(true)
    setError('')
    try {
      // Four lightweight endpoints instead of the full host detail bundle —
      // page.tsx already loads the bundle on mount, so reusing it here would
      // fetch the whole payload twice.
      const [usersResult, teamsResult, agentUsersResult, agentTeamsResult] = await Promise.all([
        getAdminUsers(),
        getAdminTeams(),
        getAgentUsers(hostName),
        getAgentTeams(hostName),
      ])
      if (!mountedRef.current || requestId !== loadRequestId.current) return
      setAllUsers(Array.isArray(usersResult.items) ? usersResult.items : [])
      setAllTeams(Array.isArray(teamsResult.items) ? teamsResult.items : [])
      setUsersWithAccess(Array.isArray(agentUsersResult.items) ? agentUsersResult.items : [])
      setTeamsWithAccess(Array.isArray(agentTeamsResult.items) ? agentTeamsResult.items : [])
    } catch (e) {
      if (!mountedRef.current || requestId !== loadRequestId.current) return
      const message = e instanceof Error ? e.message : 'Failed to load access data'
      setError(message)
      showToast(message, { tone: 'error' })
    } finally {
      if (mountedRef.current && requestId === loadRequestId.current) {
        setInitialLoading(false)
      }
    }
  }, [hostName, showToast])

  useEffect(() => {
    void loadAccess()
    return () => {
      loadRequestId.current += 1
    }
  }, [loadAccess])

  const userIdsWithAccess = useMemo(
    () => new Set(usersWithAccess.map(u => u.id)),
    [usersWithAccess]
  )
  const teamIdsWithAccess = useMemo(
    () => new Set(teamsWithAccess.map(t => t.id)),
    [teamsWithAccess]
  )
  const memberGrantOptions = useMemo(
    () =>
      allUsers
        .filter(user => !userIdsWithAccess.has(user.id))
        .map(user => ({
          value: user.id,
          label: user.displayName || user.name || user.email || user.id,
          badge: user.email || user.id,
        })),
    [allUsers, userIdsWithAccess]
  )
  const teamGrantOptions = useMemo(
    () =>
      allTeams
        .filter(team => !teamIdsWithAccess.has(team.id))
        .map(team => ({
          value: team.id,
          label: team.name,
          badge: team.memberCount === 1 ? '1 member' : `${team.memberCount} members`,
        })),
    [allTeams, teamIdsWithAccess]
  )

  async function loadCompatibilityResources() {
    const [contextsData, hostsData] = await Promise.all([getContexts(), getHosts()])
    return {
      contexts: Array.isArray(contextsData.items) ? contextsData.items : [],
      hosts: Array.isArray(hostsData.items) ? hostsData.items : [],
    }
  }

  async function grantUserAccess() {
    if (selectedUserIdsToGrant.length === 0) return false
    setBusy(true)
    setError('')
    try {
      const compatibility = await loadCompatibilityResources()
      await Promise.all(
        selectedUserIdsToGrant.map(async userId => {
          const current = await getAdminUserAgents(userId)
          const next = Array.from(new Set([...(current.agentNames || []), hostName]))
          await applyAgentAccessCompatibilityUpdate({
            ...compatibility,
            loadCurrentContextIds: async () => {
              const contexts = await getAdminUserContexts(userId)
              return Array.isArray(contexts.contextIds) ? contexts.contextIds : []
            },
            nextGrantedAgentNames: next,
            updateAgents: agentNames =>
              updateAdminUserAgents(userId, agentNames, [
                ...(current.agentNames || []),
                ...(current.deletedAgentNames || []),
              ]),
            updateContexts: contextIds => updateAdminUserContexts(userId, contextIds),
          })
        })
      )
      const grantedUserIds = selectedUserIdsToGrant
      const grantedUser = allUsers.find(u => u.id === grantedUserIds[0])
      const refreshed = await getAgentUsers(hostName)
      if (!mountedRef.current) return false
      setUsersWithAccess(Array.isArray(refreshed.items) ? refreshed.items : [])
      setSelectedUserIdsToGrant([])
      showToast(
        grantedUserIds.length === 1
          ? `${grantedUser?.displayName || grantedUser?.name || grantedUserIds[0]} can now use this agent.`
          : `${grantedUserIds.length} members can now use this agent.`,
        { tone: 'success' }
      )
      return true
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to grant member access')
      return false
    } finally {
      if (mountedRef.current) setBusy(false)
    }
  }

  async function revokeUserAccess(userId: string) {
    const user = usersWithAccess.find(item => item.id === userId)
    const shouldRevoke = await confirm({
      title: 'Revoke Member Access',
      message: `Revoke ${user?.displayName || user?.name || user?.email || 'this member'}'s access to ${hostName}?`,
      confirmLabel: 'Revoke',
      tone: 'danger',
    })
    if (!shouldRevoke) return

    setBusy(true)
    setError('')
    try {
      const compatibility = await loadCompatibilityResources()
      const current = await getAdminUserAgents(userId)
      const next = (current.agentNames || []).filter(name => name !== hostName)
      await applyAgentAccessCompatibilityUpdate({
        ...compatibility,
        loadCurrentContextIds: async () => {
          const contexts = await getAdminUserContexts(userId)
          return Array.isArray(contexts.contextIds) ? contexts.contextIds : []
        },
        nextGrantedAgentNames: next,
        updateAgents: agentNames =>
          updateAdminUserAgents(userId, agentNames, [
            ...(current.agentNames || []),
            ...(current.deletedAgentNames || []),
          ]),
        updateContexts: contextIds => updateAdminUserContexts(userId, contextIds),
      })
      if (!mountedRef.current) return
      const removedUser = usersWithAccess.find(u => u.id === userId)
      setUsersWithAccess(prev => prev.filter(u => u.id !== userId))
      showToast(
        `${removedUser?.displayName || removedUser?.name || userId} can no longer use this agent.`,
        { tone: 'success' }
      )
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to revoke member access')
    } finally {
      if (mountedRef.current) setBusy(false)
    }
  }

  async function grantTeamAccess() {
    if (selectedTeamIdsToGrant.length === 0) return false
    setBusy(true)
    setError('')
    try {
      const compatibility = await loadCompatibilityResources()
      await Promise.all(
        selectedTeamIdsToGrant.map(async teamId => {
          const current = await getAdminTeamAgents(teamId)
          const next = Array.from(new Set([...(current.agentNames || []), hostName]))
          await applyAgentAccessCompatibilityUpdate({
            ...compatibility,
            loadCurrentContextIds: async () => {
              const contexts = await getAdminTeamContexts(teamId)
              return Array.isArray(contexts.contextIds) ? contexts.contextIds : []
            },
            nextGrantedAgentNames: next,
            updateAgents: agentNames =>
              updateAdminTeamAgents(teamId, agentNames, [
                ...(current.agentNames || []),
                ...(current.deletedAgentNames || []),
              ]),
            updateContexts: contextIds => updateAdminTeamContexts(teamId, contextIds),
          })
        })
      )
      const grantedTeamIds = selectedTeamIdsToGrant
      const grantedTeam = allTeams.find(t => t.id === grantedTeamIds[0])
      const refreshed = await getAgentTeams(hostName)
      if (!mountedRef.current) return false
      setTeamsWithAccess(Array.isArray(refreshed.items) ? refreshed.items : [])
      setSelectedTeamIdsToGrant([])
      showToast(
        grantedTeamIds.length === 1
          ? `${grantedTeam?.name || grantedTeamIds[0]} can now use this agent.`
          : `${grantedTeamIds.length} teams can now use this agent.`,
        { tone: 'success' }
      )
      return true
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to grant team access')
      return false
    } finally {
      if (mountedRef.current) setBusy(false)
    }
  }

  async function revokeTeamAccess(teamId: string) {
    const team = teamsWithAccess.find(item => item.id === teamId)
    const shouldRevoke = await confirm({
      title: 'Revoke Team Access',
      message: `Revoke ${team?.name || 'this team'}'s access to ${hostName}?`,
      confirmLabel: 'Revoke',
      tone: 'danger',
    })
    if (!shouldRevoke) return

    setBusy(true)
    setError('')
    try {
      const compatibility = await loadCompatibilityResources()
      const current = await getAdminTeamAgents(teamId)
      const next = (current.agentNames || []).filter(name => name !== hostName)
      await applyAgentAccessCompatibilityUpdate({
        ...compatibility,
        loadCurrentContextIds: async () => {
          const contexts = await getAdminTeamContexts(teamId)
          return Array.isArray(contexts.contextIds) ? contexts.contextIds : []
        },
        nextGrantedAgentNames: next,
        updateAgents: agentNames =>
          updateAdminTeamAgents(teamId, agentNames, [
            ...(current.agentNames || []),
            ...(current.deletedAgentNames || []),
          ]),
        updateContexts: contextIds => updateAdminTeamContexts(teamId, contextIds),
      })
      if (!mountedRef.current) return
      const removedTeam = teamsWithAccess.find(t => t.id === teamId)
      setTeamsWithAccess(prev => prev.filter(team => team.id !== teamId))
      showToast(`${removedTeam?.name || teamId} can no longer use this agent.`, {
        tone: 'success',
      })
    } catch (e) {
      setError(e instanceof Error ? e.message : 'Failed to revoke team access')
    } finally {
      if (mountedRef.current) setBusy(false)
    }
  }

  function closeAddAccessDialog() {
    setShowAddUser(false)
    setShowAddTeam(false)
    setSelectedUserIdsToGrant([])
    setSelectedTeamIdsToGrant([])
    setError('')
  }

  function openAddAccessDialog() {
    setError('')
    if (subTab === 'members') {
      setSelectedUserIdsToGrant([])
      setShowAddUser(true)
    } else {
      setSelectedTeamIdsToGrant([])
      setShowAddTeam(true)
    }
  }

  async function submitAddAccessDialog() {
    const granted = showAddUser ? await grantUserAccess() : await grantTeamAccess()
    if (granted) closeAddAccessDialog()
  }

  const subTabDescription =
    subTab === 'members'
      ? 'Grant or revoke which members can use this agent.'
      : 'Grant or revoke team-level access to this agent.'

  useEffect(() => {
    if (!onActionsChange) return
    onActionsChange(
      <button
        type="button"
        className="cu-btn cu-btn--primary cu-btn--sm"
        onClick={openAddAccessDialog}
        disabled={busy || initialLoading}
      >
        {subTab === 'members' ? 'Add member' : 'Add team'}
      </button>
    )
    return () => onActionsChange(null)
  }, [busy, onActionsChange, subTab])

  return (
    <section className="cu-access-tab" aria-label="Access">
      {error ? (
        <div className="cu-banner cu-banner--error" style={{ marginBottom: '0.75rem' }}>
          {error}
        </div>
      ) : null}

      <TabBar<AccessSubTab>
        activeValue={subTab}
        ariaLabel="Access type"
        className="cu-tabs--compact cu-access-tabs"
        onChange={setSubTab}
        options={ACCESS_SUB_TABS.map(tab => ({ label: tab.label, value: tab.key }))}
      />

      <div className="cu-access-section">
        <div className="cu-access-section__header">
          <p className="cu-muted cu-access-section__description">{subTabDescription}</p>
          {!onActionsChange ? (
            <button
              type="button"
              className="cu-btn cu-btn--primary cu-btn--sm"
              onClick={openAddAccessDialog}
              disabled={busy || initialLoading}
            >
              {subTab === 'members' ? 'Add member' : 'Add team'}
            </button>
          ) : null}
        </div>

        <TableViewport className="cu-table-wrap">
          <DataTable className="eft-table cu-table cu-table--header-band">
            <thead>
              <tr>
                <th>{subTab === 'members' ? 'Member' : 'Team'}</th>
                <th className="cu-table__col-actions">Actions</th>
              </tr>
            </thead>
            <tbody>
              {initialLoading ? (
                [1, 2, 3].map(i => (
                  <tr key={i}>
                    <td>
                      <div
                        className="cu-skeleton cu-skeleton--cell"
                        style={{ width: '10rem' }}
                      ></div>
                    </td>
                    <td></td>
                  </tr>
                ))
              ) : subTab === 'members' ? (
                usersWithAccess.length === 0 ? (
                  <tr>
                    <td colSpan={2} className="cu-empty">
                      No members have access yet.
                    </td>
                  </tr>
                ) : (
                  usersWithAccess.map(user => (
                    <tr key={user.id}>
                      <td>
                        <button
                          type="button"
                          className="cu-link"
                          onClick={() => router.push(CONTROL_ROUTES.usersAndTeams.user(user.id))}
                        >
                          {user.displayName || user.name || user.email}
                        </button>
                      </td>
                      <td className="cu-table__cell-actions">
                        <RowActionsMenu
                          ariaLabel={`Actions for member ${user.displayName || user.name || user.email}`}
                          actions={[
                            {
                              key: 'view',
                              label: 'View details',
                              onClick: () =>
                                router.push(CONTROL_ROUTES.usersAndTeams.user(user.id)),
                            },
                            {
                              key: 'revoke',
                              label: 'Revoke access',
                              onClick: () => void revokeUserAccess(user.id),
                              disabled: busy,
                              danger: true,
                            },
                          ]}
                        />
                      </td>
                    </tr>
                  ))
                )
              ) : teamsWithAccess.length === 0 ? (
                <tr>
                  <td colSpan={2} className="cu-empty">
                    No teams have access yet.
                  </td>
                </tr>
              ) : (
                teamsWithAccess.map(team => (
                  <tr key={team.id}>
                    <td>
                      <button
                        type="button"
                        className="cu-link"
                        onClick={() => router.push(CONTROL_ROUTES.usersAndTeams.team(team.id))}
                      >
                        {team.name}
                      </button>
                    </td>
                    <td className="cu-table__cell-actions">
                      <RowActionsMenu
                        ariaLabel={`Actions for team ${team.name}`}
                        actions={[
                          {
                            key: 'view',
                            label: 'View details',
                            onClick: () => router.push(CONTROL_ROUTES.usersAndTeams.team(team.id)),
                          },
                          {
                            key: 'revoke',
                            label: 'Revoke access',
                            onClick: () => void revokeTeamAccess(team.id),
                            disabled: busy,
                            danger: true,
                          },
                        ]}
                      />
                    </td>
                  </tr>
                ))
              )}
            </tbody>
          </DataTable>
        </TableViewport>
      </div>

      <DialogShell
        open={showAddUser || showAddTeam}
        title={showAddUser ? 'Add members' : 'Add teams'}
        description={
          showAddUser
            ? 'Select the members who can use this agent.'
            : 'Select the teams that can use this agent.'
        }
        size="large"
        busy={busy}
        error={error || undefined}
        onDismiss={closeAddAccessDialog}
        footer={
          <>
            <button
              className="eft-dialog__button eft-dialog__button--secondary"
              disabled={busy}
              onClick={closeAddAccessDialog}
              type="button"
            >
              Cancel
            </button>
            <button
              className="eft-dialog__button eft-dialog__button--primary"
              disabled={
                busy || (showAddUser ? selectedUserIdsToGrant : selectedTeamIdsToGrant).length === 0
              }
              onClick={() => void submitAddAccessDialog()}
              type="button"
            >
              {busy
                ? 'Adding…'
                : showAddUser
                  ? selectedUserIdsToGrant.length > 1
                    ? 'Add members'
                    : 'Add member'
                  : selectedTeamIdsToGrant.length > 1
                    ? 'Add teams'
                    : 'Add team'}
            </button>
          </>
        }
      >
        <div className="cu-field">
          <label htmlFor={showAddUser ? 'agent-member-picker' : 'agent-team-picker'}>
            {showAddUser ? 'Members' : 'Teams'}
          </label>
          <SelectionDropdown
            id={showAddUser ? 'agent-member-picker' : 'agent-team-picker'}
            inline
            value={showAddUser ? selectedUserIdsToGrant : selectedTeamIdsToGrant}
            onChange={showAddUser ? setSelectedUserIdsToGrant : setSelectedTeamIdsToGrant}
            options={showAddUser ? memberGrantOptions : teamGrantOptions}
            placeholder={showAddUser ? 'Select members' : 'Select teams'}
            searchPlaceholder={showAddUser ? 'Search members...' : 'Search teams...'}
            selectionLabel={showAddUser ? 'Selected members' : 'Selected teams'}
            emptyLabel={showAddUser ? 'No available members.' : 'No available teams.'}
            disabled={busy}
          />
        </div>
      </DialogShell>

      {confirmDialog}
    </section>
  )
}