Skip to content

A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.

10.7 KB
Raw Blame
"use client";

import { useState } from "react";
import { ComposerPrimitive, ThreadPrimitive, useAui, useAuiState } from "@assistant-ui/react";
import { LexicalComposerInput } from "@assistant-ui/react-lexical";
import { ActionIcon, Box, Button, Group, Stack, Text, ThemeIcon, Tooltip } from "@mantine/core";
import {
  IconArrowUp,
  IconMessage,
  IconPaperclip,
  IconPlayerStop,
  IconPlus,
  IconQuote,
  IconX,
} from "@tabler/icons-react";

import { useI18n } from "@homarr/translation/client";
import { showErrorNotification } from "@homarr/notifications";

import classes from "./assistant-panel.module.css";
import { ComposerTriggers } from "./assistant-composer-triggers";
import type { AssistantConversationControls } from "./assistant-conversation-controls";
import { ConversationContext } from "./assistant-conversation-context";
import { useAssistantPreferences } from "./assistant-context";
import { AutoApprovalControl } from "./assistant-panel-controls";
import { Attachment, ContextDirectiveChip } from "./assistant-message-content";
import type { AssistantPendingAction } from "./assistant-pending-action";
import { isAssistantProviderUnavailable } from "./assistant-provider-quota";
import { HomarrProviderQuota, RuntimeControls } from "./assistant-runtime-controls";
import { useAssistantHistoryState } from "./assistant-history-state";
import { AssistantCommandPlugin } from "./assistant-command-plugin";

type ComposerProps = AssistantConversationControls & {
  pendingAction: AssistantPendingAction | undefined;
  compact?: boolean;
};

export const Composer = (props: ComposerProps) => {
  const t = useI18n("assistant");
  const preferences = useAssistantPreferences();
  const aui = useAui();
  const conversationId = useAuiState((state) => state.threadListItem.id);
  const { failedThreadIds } = useAssistantHistoryState();
  const historyLoadFailed = failedThreadIds.has(conversationId);
  const [retryingHistory, setRetryingHistory] = useState(false);
  const running = useAuiState((state) => state.thread.isRunning);
  const hasPendingAction = props.pendingAction !== undefined;
  const providerUnavailable = isAssistantProviderUnavailable({
    provider: preferences.provider,
    signedIn: preferences.providerUser !== null,
    remaining: preferences.quota?.remaining,
  });
  const sendBlocked = historyLoadFailed || hasPendingAction || providerUnavailable;
  let sendLabel = t("send");
  if (providerUnavailable) sendLabel = t("providerQuota.unavailableDescription");
  if (hasPendingAction) sendLabel = t("pendingAction.sendBlocked");
  if (historyLoadFailed) sendLabel = t("historyError.loadMessages");
  const composerLabel = t("composerPlaceholder");
  const actionSize = props.compact ? "sm" : "lg";
  const sendSize = props.compact ? "md" : "lg";
  const attachmentAction = (
    <Tooltip label={t("attachments.add")}>
      <ComposerPrimitive.AddAttachment multiple asChild>
        <ActionIcon
          variant="subtle"
          color="gray"
          size={actionSize}
          radius={props.compact ? "xl" : undefined}
          aria-label={t("attachments.add")}
        >
          {props.compact ? <IconPlus size="1em" /> : <IconPaperclip size="1em" />}
        </ActionIcon>
      </ComposerPrimitive.AddAttachment>
    </Tooltip>
  );
  const sendAction = running ? (
    <ComposerPrimitive.Cancel asChild>
      <ActionIcon
        color="red"
        variant="light"
        size={sendSize}
        radius={props.compact ? "xl" : undefined}
        aria-label={t("stop")}
      >
        <IconPlayerStop size="1em" />
      </ActionIcon>
    </ComposerPrimitive.Cancel>
  ) : (
    <ComposerPrimitive.Send asChild>
      <ActionIcon
        variant="filled"
        size={sendSize}
        radius={props.compact ? "xl" : undefined}
        aria-label={sendLabel}
        disabled={sendBlocked}
      >
        <IconArrowUp size="1em" />
      </ActionIcon>
    </ComposerPrimitive.Send>
  );

  return (
    <Box className={classes.composerWrap}>
      {historyLoadFailed && (
        <Stack gap="xs" p="sm" role="alert">
          <Text size="sm" c="red">
            {t("historyError.loadMessages")}
          </Text>
          <Button
            variant="light"
            size="compact-sm"
            loading={retryingHistory}
            onClick={async () => {
              setRetryingHistory(true);
              try {
                await aui.threads().reloadMainThread();
              } catch {
                showErrorNotification({ title: t("historyError.title"), message: t("historyError.loadMessages") });
              } finally {
                setRetryingHistory(false);
              }
            }}
          >
            {t("historyError.retry")}
          </Button>
        </Stack>
      )}
      <ComposerPrimitive.TriggerPopoverRoot>
        <ComposerPrimitive.AttachmentDropzone className={classes.composerDropzone}>
          <ComposerPrimitive.Root
            className={classes.composer}
            data-pending-action={hasPendingAction || undefined}
            onSubmit={(event) => {
              if (sendBlocked) event.preventDefault();
            }}
          >
            <ComposerTriggers />
            <ComposerPrimitive.Quote className={classes.composerQuote}>
              <IconQuote size={15} />
              <ComposerPrimitive.QuoteText className={classes.composerQuoteText} />
              <ComposerPrimitive.QuoteDismiss asChild>
                <ActionIcon variant="subtle" color="gray" size="xs" aria-label={t("dismissQuote")}>
                  <IconX size={12} />
                </ActionIcon>
              </ComposerPrimitive.QuoteDismiss>
            </ComposerPrimitive.Quote>
            <Box className={classes.composerAttachments}>
              <ComposerPrimitive.Attachments>{() => <Attachment removable />}</ComposerPrimitive.Attachments>
            </Box>
            <Box className={classes.composerMain}>
              {props.compact ? (
                <LexicalComposerInput
                  className={`${classes.composerInput} ${classes.composerWidgetInput}`}
                  data-assistant-composer-input
                  placeholder={composerLabel}
                  directiveChip={ContextDirectiveChip}
                  // oxlint-disable-next-line jsx-a11y/no-autofocus -- opening the assistant is an explicit intent to compose
                  autoFocus={props.autoFocusComposer}
                  data-autofocus={props.autoFocusComposer ? true : undefined}
                >
                  <AssistantCommandPlugin />
                </LexicalComposerInput>
              ) : (
                <Group className={classes.composerRow} gap="xs" wrap="nowrap" align="center">
                  <Group gap={2} wrap="nowrap">
                    {attachmentAction}
                  </Group>
                  <LexicalComposerInput
                    className={classes.composerInput}
                    data-assistant-composer-input
                    placeholder={composerLabel}
                    directiveChip={ContextDirectiveChip}
                    // oxlint-disable-next-line jsx-a11y/no-autofocus -- opening the assistant is an explicit intent to compose
                    autoFocus={props.autoFocusComposer}
                    data-autofocus={props.autoFocusComposer ? true : undefined}
                  >
                    <AssistantCommandPlugin />
                  </LexicalComposerInput>
                  {sendAction}
                </Group>
              )}
              <Group className={classes.composerFooter} justify="space-between" gap="xs" wrap="nowrap">
                {props.compact ? (
                  <>
                    <Group className={classes.composerLeading} gap="xs" wrap="nowrap">
                      {attachmentAction}
                      <AutoApprovalControl compact />
                    </Group>
                    <Group className={classes.composerTrailing} gap={0} wrap="nowrap">
                      <ConversationContext compact />
                      <RuntimeControls {...props} compact />
                      {sendAction}
                    </Group>
                  </>
                ) : (
                  <Group className={classes.composerControls} gap={5} wrap="nowrap">
                    <RuntimeControls {...props} />
                    <HomarrProviderQuota />
                    <ConversationContext />
                  </Group>
                )}
              </Group>
            </Box>
          </ComposerPrimitive.Root>
        </ComposerPrimitive.AttachmentDropzone>
      </ComposerPrimitive.TriggerPopoverRoot>
    </Box>
  );
};

export const usePendingActionCopy = (action: AssistantPendingAction | undefined) => {
  const t = useI18n("assistant");
  if (!action) return undefined;
  if (action.kind === "question") {
    return { title: t("pendingAction.answerTitle"), detail: action.detail ?? t("pendingAction.answerFallback") };
  }
  if (action.kind === "form") {
    const isBoardSettings = action.toolName === "configure_board_settings";
    return {
      title: isBoardSettings ? t("pendingAction.boardFormTitle") : t("pendingAction.formTitle"),
      detail: action.detail ?? (isBoardSettings ? t("configureBoardSettings.title") : t("configureApp.title")),
    };
  }
  const tool = action.toolName.replaceAll("_", " ");
  return { title: t("activity.approval"), detail: action.detail ? `${tool} · ${action.detail}` : tool };
};

export const PendingActionBanner = ({ pendingAction }: { pendingAction: AssistantPendingAction | undefined }) => {
  const t = useI18n("assistant");
  const copy = usePendingActionCopy(pendingAction);
  if (!copy || pendingAction?.kind === "question") return null;

  return (
    <Box component="output" className={classes.pendingActionBanner}>
      <Group gap="sm" wrap="nowrap">
        <ThemeIcon variant="light" color="yellow" radius="xl">
          <IconMessage size={17} />
        </ThemeIcon>
        <Stack gap={0} flex={1} miw={0}>
          <Text size="sm" fw={700}>
            {copy.title}
          </Text>
          <Text size="xs" c="dimmed" lineClamp={1}>
            {copy.detail}
          </Text>
        </Stack>
        <ThreadPrimitive.ScrollToBottom asChild>
          <Button variant="light" color="yellow" size="compact-sm">
            {t("pendingAction.review")}
          </Button>
        </ThreadPrimitive.ScrollToBottom>
      </Group>
    </Box>
  );
};

export const PendingQuestionDock = ({
  pendingAction,
  setTarget,
}: {
  pendingAction: AssistantPendingAction | undefined;
  setTarget: (target: HTMLDivElement | null) => void;
}) => {
  const t = useI18n("assistant");
  if (pendingAction?.kind !== "question") return null;

  return (
    <Box component="section" className={classes.pendingQuestionDock} aria-label={t("pendingAction.answerTitle")}>
      <div ref={setTarget} className={classes.pendingQuestionTarget} />
    </Box>
  );
};