"use client";
import { useEffect, useMemo, useRef, useState } from "react";
import type { MessageStatus } from "@assistant-ui/react";
import {
ActionBarMorePrimitive,
ActionBarPrimitive,
AuiIf,
BranchPickerPrimitive,
ChainOfThoughtByIndicesProvider,
ComposerPrimitive,
ErrorPrimitive,
MessagePrimitive,
SelectionToolbarPrimitive,
ThreadListPrimitive,
ThreadPrimitive,
useAui,
useAuiState,
} from "@assistant-ui/react";
import { ActionIcon, Badge, Box, Button, Group, Stack, Text, ThemeIcon, Tooltip, UnstyledButton } from "@mantine/core";
import { useReducedMotion, useWindowEvent } from "@mantine/hooks";
import {
IconAlertTriangle,
IconArrowUp,
IconArrowsMaximize,
IconCheck,
IconChevronLeft,
IconChevronRight,
IconChevronUp,
IconCopy,
IconDotsVertical,
IconFileExport,
IconMinus,
IconPencil,
IconPlus,
IconQuote,
IconRefresh,
IconThumbDown,
IconThumbUp,
IconVolume,
IconVolumeOff,
IconX,
} from "@tabler/icons-react";
import { useI18n } from "@homarr/translation/client";
import { getAssistantActivityState } from "./assistant-activity-state";
import { Composer, PendingActionBanner, PendingQuestionDock, usePendingActionCopy } from "./assistant-composer";
import type { AssistantConversationControls } from "./assistant-conversation-controls";
import { ProviderMessageInfo } from "./assistant-conversation-context";
import { buildAssistantMessageMarkdown } from "./assistant-conversation-export";
import { AssistantDotMatrix } from "./assistant-dot-matrix";
import { ConversationHistory, downloadAssistantMarkdown } from "./assistant-history";
import {
AssistantDirectiveEntitiesProvider,
AssistantMessagePending,
AssistantTextPart,
FilePart,
HiddenMessagePart,
ImagePart,
ReasoningPart,
ReasoningVisibilityContext,
SentAttachment,
SourcePart,
UserTextPart,
} from "./assistant-message-content";
import { assistantMessageGroupBy } from "./assistant-message-grouping";
import { AutoApprovalControl, EmptyThread, ViewRefreshAction } from "./assistant-panel-controls";
import classes from "./assistant-panel.module.css";
import type { AssistantPendingAction } from "./assistant-pending-action";
import { AssistantQuestionPortalProvider } from "./assistant-question-portal";
import { AgentTraceToolGroup, AssistantChainOfThought, ToolPart } from "./assistant-tool-rendering";
import { isEscapeOwnedByNestedOverlay } from "../board/advanced-focus/escape";
export type { AssistantConversationControls } from "./assistant-conversation-controls";
interface AssistantPanelProps extends AssistantConversationControls {
opened: boolean;
onOpen: () => void;
onClose: () => void;
onDismissActivity: () => void;
activityDismissed: boolean;
hasVisibleWidget: boolean;
isRunning: boolean;
unreadCount: number;
latestAssistantText: string;
latestAssistantPartType: string | undefined;
latestUserText: string;
latestStatus: MessageStatus | undefined;
pendingAction: AssistantPendingAction | undefined;
}
const BranchPicker = () => {
const t = useI18n("assistant");
return (
/
);
};
const AssistantMessageActions = () => {
const t = useI18n("assistant");
const aui = useAui();
const exportMessage = () => {
const message = aui.message().getState();
const markdown = buildAssistantMessageMarkdown({
id: message.id,
parentId: message.parentId,
format: "assistant-ui/runtime",
content: message,
createdAt: message.createdAt,
});
downloadAssistantMarkdown(markdown, `assistant-message-${message.id.slice(0, 8)}.md`);
};
return (
!state.message.isCopied}>
state.message.isCopied}>
{t("helpful")}
{t("notHelpful")}
state.thread.capabilities.speech && state.message.speech === undefined}>
{t("readAloud")}
state.message.speech !== undefined}>
{t("stopReading")}
exportMessage()} asChild>
{t("exportMarkdown")}
);
};
const UserMessageActions = () => {
const t = useI18n("assistant");
return (
);
};
const EditComposer = () => {
const t = useI18n("assistant");
const actionT = useI18n("common.action");
return (
);
};
const UserMessage = () => {
const isEditing = useAuiState((state) => state.composer.isEditing);
if (isEditing) return ;
return (
{(quote) => (
{quote.text}
)}
);
};
const RuntimeError = () => {
const t = useI18n("assistant");
const actionT = useI18n("common.action");
return (
{t("responseError.title")}
}
>
{actionT("tryAgain")}
);
};
const AssistantMessage = () => {
const isComplete = useAuiState((state) => state.message.status?.type === "complete");
return (
{({ part, children }) => {
switch (part.type) {
case "group-agent-trace": {
const startIndex = part.indices[0];
const endIndex = part.indices.at(-1);
if (startIndex === undefined || endIndex === undefined) return null;
return (
{children}
);
}
case "group-reasoning":
return <>{children}>;
case "group-tool":
return {children};
case "indicator":
return ;
case "text":
return ;
case "reasoning":
return ;
case "tool-call":
return part.toolUI ?? ;
case "source":
return ;
case "file":
return ;
case "image":
return ;
case "data":
return part.dataRendererUI;
default:
return null;
}
}}
);
};
const assistantThreadMessageComponents = { UserMessage, AssistantMessage };
const getActivityColor = (needsApproval: boolean, failed: boolean, isRunning: boolean) => {
if (needsApproval) return "yellow";
if (failed || isRunning) return "red";
return "green";
};
const AssistantActivityBar = ({
isRunning,
unreadCount,
latestAssistantText,
latestAssistantPartType,
latestUserText,
latestStatus,
pendingAction,
onOpen,
onDismissActivity,
activityDismissed,
}: Pick<
AssistantPanelProps,
| "isRunning"
| "unreadCount"
| "latestAssistantText"
| "latestAssistantPartType"
| "latestUserText"
| "latestStatus"
| "pendingAction"
| "onOpen"
| "onDismissActivity"
| "activityDismissed"
>) => {
const t = useI18n("assistant");
const pendingCopy = usePendingActionCopy(pendingAction);
const needsApproval = pendingAction !== undefined || latestStatus?.type === "requires-action";
const failed = latestStatus?.type === "incomplete" && latestStatus.reason !== "cancelled";
const visible =
!activityDismissed &&
(isRunning || unreadCount > 0 || needsApproval || latestStatus !== undefined || latestAssistantText.length > 0);
if (!visible) return null;
let title = t("activity.ready");
if (failed) title = t("activity.failed");
if (needsApproval) title = t("activity.approval");
if (pendingCopy) title = pendingCopy.title;
if (isRunning) title = t("activity.thinking");
let fallbackDetail = t("activity.completed");
if (failed) fallbackDetail = t("responseError.description");
let detail = pendingCopy?.detail || latestAssistantText || fallbackDetail;
if (isRunning) detail = latestUserText || t("activity.working");
const activityState = getAssistantActivityState({
isRunning,
latestPartType: latestAssistantPartType,
needsApproval,
failed,
});
const activityColor = getActivityColor(needsApproval, failed, isRunning);
return (
{title}
{unreadCount > 0 && (
{unreadCount > 99 ? "99+" : unreadCount}
)}
{detail}
{needsApproval ? (
{t("pendingAction.review")}
) : (
)}
{!isRunning && !needsApproval && (
)}
);
};
interface AssistantConversationSurfaceProps extends AssistantConversationControls {
variant?: "widget" | "panel";
isRunning: boolean;
pendingAction: AssistantPendingAction | undefined;
onExpand?: () => void;
onMinimize?: () => void;
onDismiss?: () => void;
}
export const AssistantConversationSurface = ({
variant = "panel",
isRunning,
pendingAction,
modelId,
models,
modelOptionsLoading,
reasoning,
isRefreshing,
autoFocusComposer,
onRefresh,
onModelChange,
onReasoningChange,
onExpand,
onMinimize,
onDismiss,
}: AssistantConversationSurfaceProps) => {
const t = useI18n("assistant");
const reducedMotion = useReducedMotion();
const [questionPortalTarget, setQuestionPortalTarget] = useState(null);
const [reasoningCollapsed, setReasoningCollapsed] = useState(false);
const reasoningVisibility = useMemo(
() => ({ collapsed: reasoningCollapsed, setCollapsed: setReasoningCollapsed }),
[reasoningCollapsed],
);
const scrollToLatestBehavior = isRunning || reducedMotion ? "instant" : "smooth";
return (
{variant === "widget" && (
{t("title")}
)}
{variant !== "widget" && }
{onExpand && (
)}
{onMinimize && (
)}
{onDismiss && (
)}
}>
{t("quoteSelection")}
);
};
export const AssistantPanel = ({
opened,
onOpen,
onClose,
onDismissActivity,
activityDismissed,
hasVisibleWidget,
isRunning,
unreadCount,
latestAssistantText,
latestAssistantPartType,
latestUserText,
latestStatus,
pendingAction,
modelId,
models,
modelOptionsLoading,
reasoning,
isRefreshing,
onRefresh,
onModelChange,
onReasoningChange,
}: AssistantPanelProps) => {
const t = useI18n("assistant");
const aui = useAui();
const previousFocusRef = useRef(null);
const panelRef = useRef(null);
const stopSpeechWithoutSurface = () => {
if (hasVisibleWidget) return;
const thread = aui.thread();
if (thread.getState().speech !== undefined) thread.stopSpeaking();
};
const minimize = () => {
stopSpeechWithoutSurface();
onClose();
};
useWindowEvent("keydown", (event) => {
if (
!opened ||
event.key !== "Escape" ||
event.defaultPrevented ||
event.isComposing ||
isEscapeOwnedByNestedOverlay(event.target, panelRef.current)
)
return;
event.preventDefault();
minimize();
});
useEffect(() => {
if (!opened) {
const rememberOutsideFocus = () => {
if (document.activeElement instanceof HTMLElement) {
previousFocusRef.current = document.activeElement;
}
};
rememberOutsideFocus();
document.addEventListener("focusin", rememberOutsideFocus);
return () => document.removeEventListener("focusin", rememberOutsideFocus);
}
const restoreTarget = previousFocusRef.current;
return () => {
restoreTarget?.focus();
previousFocusRef.current = null;
};
}, [opened]);
return (
<>
{!opened && !hasVisibleWidget && (
)}
{opened && (
)}
>
);
};