Skip to content

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

7.3 KB
Raw Blame
import ContentCopy from "@mui/icons-material/ContentCopy";
import DoneOutline from "@mui/icons-material/DoneOutline";
import {
  Alert,
  Box,
  Button,
  CircularProgress,
  Dialog,
  DialogActions,
  DialogContent,
  DialogContentText,
  DialogTitle,
  IconButton,
  Stack,
  TextField,
  Tooltip,
  Typography,
} from "@mui/material";
import { useEffect, useState } from "react";
import {
  createEnrollmentCode,
  type EnrollmentCode,
  enrollCommand,
  installCommand,
  MAX_MACHINE_DESCRIPTION,
  MAX_MACHINE_NAME,
} from "../../data/management";
import { MONO_SX, formatDate } from "../../theme/hootFormat";

function CopyBlock({ text, label }: { text: string; label: string }) {
  const [copied, setCopied] = useState(false);
  const copy = async () => {
    await navigator.clipboard.writeText(text);
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  return (
    <Stack
      direction="row"
      alignItems="center"
      spacing={1}
      sx={{ p: 1.5, borderRadius: 1, bgcolor: "action.hover" }}
    >
      <Typography component="code" sx={{ ...MONO_SX, flexGrow: 1, wordBreak: "break-all" }}>
        {text}
      </Typography>
      <Tooltip title={copied ? "Copied!" : label}>
        <IconButton size="small" aria-label={label} onClick={copy}>
          {copied ? <DoneOutline fontSize="small" color="success" /> : <ContentCopy fontSize="small" />}
        </IconButton>
      </Tooltip>
    </Stack>
  );
}

/**
 * Issues a one-time enrollment code and shows the commands that install a
 * machine's agent controller and enroll it with that code. The code is shown
 * once: closing the dialog discards it, and a new open issues a new one. The
 * optional name and description go into the commands, so the machine enrolls
 * with them.
 */
export default function AddMachineDialog({
  open,
  onClose,
}: {
  open: boolean;
  onClose: () => void;
}) {
  const [enrollment, setEnrollment] = useState<EnrollmentCode | null>(null);
  const [error, setError] = useState<string | null>(null);
  const [name, setName] = useState("");
  const [description, setDescription] = useState("");

  const nameError =
    name.trim().length > MAX_MACHINE_NAME ? `At most ${MAX_MACHINE_NAME} characters.` : null;
  const descriptionError =
    description.trim().length > MAX_MACHINE_DESCRIPTION
      ? `At most ${MAX_MACHINE_DESCRIPTION} characters.`
      : null;

  useEffect(() => {
    if (!open) return;
    let cancelled = false;
    setEnrollment(null);
    setError(null);
    setName("");
    setDescription("");
    createEnrollmentCode()
      .then((issued) => {
        if (!cancelled) setEnrollment(issued);
      })
      .catch((err: unknown) => {
        if (!cancelled) setError(err instanceof Error ? err.message : String(err));
      });
    return () => {
      cancelled = true;
    };
  }, [open]);

  return (
    <Dialog open={open} onClose={onClose} maxWidth="md" fullWidth>
      <DialogTitle>Add a device</DialogTitle>
      <DialogContent>
        <DialogContentText sx={{ mb: 2 }}>
          Run the agent controller on the device that should run your agents (a laptop, a
          desktop or your own VM). Enroll it once with the code below; it then runs whatever agents
          you place on it here. It needs Linux or macOS with Node 22.13 or later, and the CLI of
          each provider your agents use (such as <code>claude</code> or <code>codex</code>),
          signed in as the user the controller runs as.
        </DialogContentText>
        {error && <Alert severity="error">Could not issue an enrollment code: {error}</Alert>}
        {!error && !enrollment && <CircularProgress size={24} />}
        {enrollment && (
          <Stack spacing={2}>
            <Stack spacing={2}>
              <TextField
                label="Name (optional)"
                value={name}
                onChange={(e) => setName(e.target.value)}
                error={nameError !== null}
                helperText={nameError ?? "Defaults to the device's host name."}
                size="small"
                fullWidth
              />
              <TextField
                label="Description (optional)"
                value={description}
                onChange={(e) => setDescription(e.target.value)}
                error={descriptionError !== null}
                helperText={descriptionError ?? "What the device is for, e.g. the build box in the office."}
                size="small"
                fullWidth
              />
            </Stack>
            <Box>
              {enrollment.server_url && (nameError || descriptionError) ? (
                <Alert severity="warning">Shorten the name or description to see the commands.</Alert>
              ) : enrollment.server_url ? (
                <Stack spacing={2}>
                  <Box>
                    <Typography variant="subtitle2" gutterBottom>
                      Install, enroll and start
                    </Typography>
                    <CopyBlock
                      text={installCommand(enrollment.server_url, enrollment.code, { name, description })}
                      label="Copy install command"
                    />
                    <Typography variant="caption" color="text.secondary">
                      Installs the newest controller with npm, enrolls this device, and runs the
                      controller as a service of your user. <code>--server</code> is this Switch's
                      API address. If the device reaches Switch at a different address, change it
                      to that one.
                    </Typography>
                  </Box>
                  <Box>
                    <Typography variant="subtitle2" gutterBottom>
                      Already installed
                    </Typography>
                    <CopyBlock
                      text={enrollCommand(enrollment.server_url, enrollment.code, { name, description })}
                      label="Copy enroll command"
                    />
                    <Typography variant="caption" color="text.secondary">
                      Then start it with <code>switch-agent-controller install-service</code>.
                    </Typography>
                  </Box>
                </Stack>
              ) : (
                <Alert severity="warning">
                  Switch does not say where its API is, so no enrollment command can be
                  shown. Set <code>GATEWAY_PUBLIC_URL</code> in Switch&apos;s configuration to its
                  API address, or enroll with{" "}
                  <code>switch-agent-controller enroll --server &lt;Switch API URL&gt; --code</code>{" "}
                  and the code below. This page's address is not it.
                </Alert>
              )}
            </Box>
            <Box>
              <Typography variant="subtitle2" gutterBottom>
                Code only
              </Typography>
              <CopyBlock text={enrollment.code} label="Copy code" />
            </Box>
            <Alert severity="info">
              Single use, valid until {formatDate(enrollment.expires_at)}. The device appears in
              the list once its controller reports. If it does not, run{" "}
              <code>switch-agent-controller doctor</code> on it to see what is missing.
            </Alert>
          </Stack>
        )}
      </DialogContent>
      <DialogActions>
        <Button onClick={onClose}>Done</Button>
      </DialogActions>
    </Dialog>
  );
}