Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

11.7 KB
Raw Blame
import AddLinkOutlined from "@mui/icons-material/AddLinkOutlined";
import AddOutlined from "@mui/icons-material/AddOutlined";
import DeleteOutline from "@mui/icons-material/DeleteOutline";
import GroupsOutlined from "@mui/icons-material/GroupsOutlined";
import {
  Alert,
  Box,
  Button,
  Chip,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogTitle,
  IconButton,
  Stack,
  Switch,
  Tooltip,
  Typography,
} from "@mui/material";
import type { GridColDef } from "@mui/x-data-grid";
import { useCallback, useMemo, useState } from "react";
import DataTable from "../../components/DataTable";
import {
  type BridgeDetail,
  beginAppInstall,
  updateBridge,
} from "../../data/api";
import { useAuth } from "../../data/AuthContext";
import { useBridges, useInstallablePlatforms } from "../../data/hooks";
import { formatDate, platformLabel, sentenceCase } from "../../theme/hootFormat";
import AddToChatDialog from "./AddToChatDialog";
import AttentionBanner from "./AttentionBanner";
import DeleteConnectionText from "./DeleteConnectionText";
import { deleteConnection, mayHoldChats } from "./deleteConnection";
import InstalledAppsSection from "./InstalledAppsSection";
import RegisterMessagingAppDialog from "./RegisterMessagingAppDialog";
import TeamsPlacementDialog from "./TeamsPlacementDialog";

type BridgeRow = BridgeDetail & { id: string };

const STATUS_COLOR: Record<string, "success" | "error" | "default"> = {
  active: "success",
  error: "error",
  inactive: "default",
};

export default function CollaborationsPage() {
  const { canAdminTenant: isAdmin } = useAuth();
  const { data: bridges, loading, refetch } = useBridges();
  const { data: installablePlatforms } = useInstallablePlatforms();
  const [deleteTarget, setDeleteTarget] = useState<BridgeDetail | null>(null);
  const [deleting, setDeleting] = useState(false);
  const [deleteError, setDeleteError] = useState<string | null>(null);
  const [savingId, setSavingId] = useState<string | null>(null);
  const [registerOpen, setRegisterOpen] = useState(false);
  const [installTarget, setInstallTarget] = useState<BridgeDetail | null>(null);
  const [teamsTarget, setTeamsTarget] = useState<BridgeDetail | null>(null);
  const [approvingId, setApprovingId] = useState<string | null>(null);
  const [approveError, setApproveError] = useState<string | null>(null);
  // Bumped to reload the installed apps after deleting a connection
  // disconnected its chats.
  const [installsVersion, setInstallsVersion] = useState(0);

  const handleDelete = useCallback(async () => {
    if (!deleteTarget) return;
    setDeleting(true);
    setDeleteError(null);
    try {
      await deleteConnection(deleteTarget);
      setDeleteTarget(null);
      refetch();
    } catch (e) {
      // A connection an install created is refused here, and the refusal says
      // to disconnect the app instead. Closing the dialog on it would leave
      // the operator clicking Delete at a row that will never go.
      setDeleteError(e instanceof Error ? e.message : "Failed to delete");
    } finally {
      setDeleting(false);
      // Its chats were disconnected on the way, however far it got, so the
      // installed apps listed below are stale.
      if (mayHoldChats(deleteTarget)) setInstallsVersion((v) => v + 1);
    }
  }, [deleteTarget, refetch]);

  const handleToggleGreetings = useCallback(
    async (bridgeId: string, enabled: boolean) => {
      setSavingId(bridgeId);
      await updateBridge(bridgeId, { agent_greetings_enabled: enabled });
      setSavingId(null);
      refetch();
    },
    [refetch],
  );

  const handleToggleChannelCreation = useCallback(
    async (bridgeId: string, enabled: boolean) => {
      setSavingId(bridgeId);
      await updateBridge(bridgeId, { channel_creation_enabled: enabled });
      setSavingId(null);
      refetch();
    },
    [refetch],
  );

  // Re-approval is the same install flow the "Add to..." button starts: the
  // same workspace approving again refreshes the existing install, it does
  // not create a second one.
  const handleApproveAgain = useCallback(async (bridgeId: string, platform: string) => {
    setApprovingId(bridgeId);
    setApproveError(null);
    try {
      window.location.href = await beginAppInstall(platform);
    } catch (e) {
      setApproveError(e instanceof Error ? e.message : "Failed to start the install");
      setApprovingId(null);
    }
  }, []);

  const rows = useMemo<BridgeRow[]>(
    () => (bridges ?? []).map((b) => ({ ...b, id: b.bridge_id })),
    [bridges],
  );

  const columns = useMemo<GridColDef<BridgeRow>[]>(
    () => [
      {
        field: "display_name",
        headerName: "Name",
        flex: 1,
        minWidth: 160,
      },
      {
        field: "bridge_type",
        headerName: "Type",
        width: 130,
        renderCell: ({ value }) => (
          <Chip label={platformLabel(String(value))} size="small" />
        ),
      },
      {
        field: "status",
        headerName: "Status",
        width: 130,
        renderCell: ({ value }) => (
          <Chip
            label={sentenceCase(String(value))}
            size="small"
            color={STATUS_COLOR[value as string] ?? "default"}
          />
        ),
      },
      { field: "room_count", headerName: "Rooms", width: 90, type: "number" },
      {
        field: "agent_greetings_enabled",
        headerName: "Agent greetings",
        width: 150,
        sortable: false,
        renderCell: ({ row }: { row: BridgeRow }) => (
          <Switch
            size="small"
            checked={row.agent_greetings_enabled}
            disabled={!row.can_manage || savingId === row.bridge_id}
            onChange={(e) =>
              handleToggleGreetings(row.bridge_id, e.target.checked)
            }
          />
        ),
      },
      {
        field: "channel_creation_enabled",
        headerName: "Channel creation",
        width: 160,
        sortable: false,
        renderCell: ({ row }: { row: BridgeRow }) => {
          const control = (
            <Switch
              size="small"
              checked={row.channel_creation_supported && row.channel_creation_enabled}
              disabled={
                !row.can_manage || savingId === row.bridge_id || !row.channel_creation_supported
              }
              onChange={(e) =>
                handleToggleChannelCreation(row.bridge_id, e.target.checked)
              }
            />
          );
          if (row.channel_creation_supported) return control;
          return (
            <Tooltip title={`${row.display_name} cannot create channels from Switch.`}>
              <span>{control}</span>
            </Tooltip>
          );
        },
      },
      {
        field: "created_at",
        headerName: "Created",
        width: 140,
        valueFormatter: (value) => formatDate(value as string),
      },
      ...(rows.some((row) => row.can_manage || row.can_delete)
        ? [
            {
              field: "actions" as const,
              headerName: "",
              width: 140,
              sortable: false,
              filterable: false,
              // Right-aligned and bottom-anchored to the same edge on every
              // row: a row carries between one and three icons depending on
              // what the platform offers, and without this the delete
              // buttons sit at different x positions down the column.
              align: "right" as const,
              renderCell: ({ row }: { row: BridgeRow }) => (
                <Stack
                  direction="row"
                  spacing={0.5}
                  alignItems="center"
                  justifyContent="flex-end"
                  height="100%"
                >
                  {row.can_manage && row.team_placement_supported && (
                    <Tooltip title="Choose which teams this app is in">
                      <IconButton size="small" onClick={() => setTeamsTarget(row)}>
                        <GroupsOutlined fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  )}
                  {row.can_manage && (row.install_links ?? []).length > 0 && (
                    <Tooltip title="Add this app to a chat">
                      <IconButton
                        size="small"
                        onClick={() => setInstallTarget(row)}
                      >
                        <AddLinkOutlined fontSize="small" />
                      </IconButton>
                    </Tooltip>
                  )}
                  {row.can_delete && (
                    <IconButton
                      size="small"
                      onClick={() => setDeleteTarget(row)}
                      aria-label={`Delete ${row.display_name}`}
                    >
                      <DeleteOutline fontSize="small" />
                    </IconButton>
                  )}
                </Stack>
              ),
            },
          ]
        : []),
    ],
    [rows, savingId, handleToggleGreetings, handleToggleChannelCreation],
  );

  const needsAttention = useMemo(
    () => rows.filter((b) => !!b.attention),
    [rows],
  );

  return (
    <Box>
      <Stack direction="row" alignItems="center" mb={2}>
        <Typography variant="h5">Messaging apps</Typography>
        {isAdmin && (
          <Button
            variant="contained"
            startIcon={<AddOutlined />}
            sx={{ ml: "auto" }}
            onClick={() => setRegisterOpen(true)}
          >
            Add messaging app
          </Button>
        )}
      </Stack>

      {approveError && (
        <Alert severity="error" sx={{ mb: 1 }} onClose={() => setApproveError(null)}>
          {approveError}
        </Alert>
      )}

      {needsAttention.map((b) => (
        <AttentionBanner
          key={b.bridge_id}
          displayName={b.display_name}
          message={b.attention ?? ""}
          canApproveAgain={
            b.can_manage &&
            b.team_placement_supported &&
            (installablePlatforms ?? []).includes(b.bridge_type)
          }
          approving={approvingId === b.bridge_id}
          onApproveAgain={() => handleApproveAgain(b.bridge_id, b.bridge_type)}
        />
      ))}

      {loading ? (
        <CircularProgress />
      ) : (
        <DataTable rows={rows} columns={columns} />
      )}

      <InstalledAppsSection key={installsVersion} onConnectionsChanged={refetch} />

      <RegisterMessagingAppDialog
        open={registerOpen}
        onClose={() => setRegisterOpen(false)}
        onSuccess={() => refetch()}
      />

      <AddToChatDialog
        bridge={installTarget}
        onClose={() => setInstallTarget(null)}
      />

      <TeamsPlacementDialog
        bridge={teamsTarget}
        onClose={() => setTeamsTarget(null)}
        onChanged={refetch}
      />

      <Dialog
        open={!!deleteTarget}
        onClose={() => {
          if (deleting) return;
          setDeleteError(null);
          setDeleteTarget(null);
        }}
      >
        <DialogTitle>Delete collaboration bridge</DialogTitle>
        <DialogContent>
          {deleteTarget && <DeleteConnectionText bridge={deleteTarget} />}
          {deleteError && (
            <Alert severity="error" sx={{ mt: 2 }}>
              {deleteError}
            </Alert>
          )}
        </DialogContent>
        <DialogActions>
          <Button
            onClick={() => {
              setDeleteError(null);
              setDeleteTarget(null);
            }}
            disabled={deleting}
          >
            Cancel
          </Button>
          <Button
            color="error"
            variant="contained"
            onClick={handleDelete}
            disabled={deleting}
            startIcon={deleting ? <CircularProgress size={16} /> : undefined}
          >
            Delete
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}