feat: add Homarr assistant
This commit is contained in:
1 parent
3b6de1f91f
commit
fd69cd28f0
27 files changed
+5210
-772
No files matched your search
@@ -0,0 +1,175 @@
|
||||
.drawer {
|
||||
--assistant-panel-width: min(32rem, 100vw);
|
||||
}
|
||||
|
||||
.content {
|
||||
height: 100dvh;
|
||||
background: var(--mantine-color-body);
|
||||
}
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
height: calc(100dvh - 4.25rem);
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.shell {
|
||||
position: relative;
|
||||
display: flex;
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.history {
|
||||
width: 15rem;
|
||||
flex: 0 0 15rem;
|
||||
border-inline-end: 1px solid var(--mantine-color-default-border);
|
||||
background: color-mix(in srgb, var(--mantine-color-body) 92%, var(--mantine-color-gray-6));
|
||||
transition: transform 180ms ease;
|
||||
}
|
||||
|
||||
.historyItem {
|
||||
border-radius: var(--mantine-radius-md);
|
||||
}
|
||||
|
||||
.historyItem:hover {
|
||||
background: var(--mantine-color-default-hover);
|
||||
}
|
||||
|
||||
.thread {
|
||||
position: relative;
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.viewport {
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
scroll-behavior: smooth;
|
||||
}
|
||||
|
||||
.messages {
|
||||
width: 100%;
|
||||
max-width: 52rem;
|
||||
margin-inline: auto;
|
||||
padding: 1.25rem 1rem 8.75rem;
|
||||
}
|
||||
|
||||
.message {
|
||||
margin-block: 1rem;
|
||||
}
|
||||
|
||||
.userMessage {
|
||||
width: fit-content;
|
||||
max-width: 90%;
|
||||
margin-inline-start: auto;
|
||||
padding: 0.7rem 0.9rem;
|
||||
border-radius: 1rem 1rem 0.3rem 1rem;
|
||||
background: var(--mantine-color-red-light);
|
||||
}
|
||||
|
||||
.assistantMessage {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.messageText {
|
||||
line-height: 1.65;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.tool {
|
||||
margin-block: 0.5rem;
|
||||
padding: 0.7rem 0.8rem;
|
||||
border: 1px solid var(--mantine-color-default-border);
|
||||
border-radius: var(--mantine-radius-md);
|
||||
background: var(--mantine-color-default);
|
||||
}
|
||||
|
||||
.composerWrap {
|
||||
position: absolute;
|
||||
inset-inline: 0;
|
||||
bottom: 0;
|
||||
padding: 2.5rem 1rem 1rem;
|
||||
background: var(--mantine-color-body);
|
||||
border-top: 1px solid var(--mantine-color-default-border);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.composer {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
max-width: 52rem;
|
||||
margin-inline: auto;
|
||||
align-items: flex-end;
|
||||
gap: 0.5rem;
|
||||
padding: 0.45rem;
|
||||
border: 1px solid var(--mantine-color-default-border);
|
||||
border-radius: 1rem;
|
||||
background: var(--mantine-color-body);
|
||||
box-shadow: var(--mantine-shadow-lg);
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.composerInput {
|
||||
min-height: 2.5rem;
|
||||
max-height: 12rem;
|
||||
flex: 1;
|
||||
resize: none;
|
||||
border: 0;
|
||||
outline: 0;
|
||||
padding: 0.55rem 0.65rem;
|
||||
color: var(--mantine-color-text);
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.empty {
|
||||
display: flex;
|
||||
min-height: 60vh;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.mobileHistoryButton,
|
||||
.historyClose {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@media (max-width: 48em) {
|
||||
.history {
|
||||
position: absolute;
|
||||
z-index: 4;
|
||||
inset-block: 0;
|
||||
inset-inline-start: 0;
|
||||
width: min(20rem, 88vw);
|
||||
transform: translateX(-105%);
|
||||
box-shadow: var(--mantine-shadow-xl);
|
||||
}
|
||||
|
||||
[dir="rtl"] .history {
|
||||
transform: translateX(105%);
|
||||
}
|
||||
|
||||
.history[data-opened="true"] {
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.mobileHistoryButton {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
top: 0.65rem;
|
||||
inset-inline-start: 0.65rem;
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
.historyClose {
|
||||
display: inline-flex;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,355 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import type { ToolCallMessagePartProps } from "@assistant-ui/react";
|
||||
import {
|
||||
ActionBarPrimitive,
|
||||
ComposerPrimitive,
|
||||
MessagePartPrimitive,
|
||||
MessagePrimitive,
|
||||
ThreadListItemPrimitive,
|
||||
ThreadListPrimitive,
|
||||
ThreadPrimitive,
|
||||
useAuiState,
|
||||
} from "@assistant-ui/react";
|
||||
import { ActionIcon, Box, Button, Drawer, Group, ScrollArea, Stack, Text, ThemeIcon, Tooltip } from "@mantine/core";
|
||||
import {
|
||||
IconArchive,
|
||||
IconArrowUp,
|
||||
IconCheck,
|
||||
IconCopy,
|
||||
IconMenu2,
|
||||
IconHistory,
|
||||
IconPlayerStop,
|
||||
IconPlus,
|
||||
IconRefresh,
|
||||
IconRestore,
|
||||
IconRobot,
|
||||
IconTrash,
|
||||
IconX,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import classes from "./assistant-panel.module.css";
|
||||
|
||||
interface AssistantPanelProps {
|
||||
opened: boolean;
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
const TextPart = () => <MessagePartPrimitive.Text className={classes.messageText} />;
|
||||
|
||||
const ToolPart = ({
|
||||
toolName,
|
||||
args,
|
||||
result,
|
||||
isError,
|
||||
status,
|
||||
approval,
|
||||
respondToApproval,
|
||||
}: ToolCallMessagePartProps) => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
const completed = status?.type === "complete";
|
||||
const awaitingApproval = approval !== undefined && approval.approved === undefined && !approval.resolution;
|
||||
const denied = approval?.approved === false;
|
||||
const failed =
|
||||
!denied &&
|
||||
(isError === true ||
|
||||
status?.type === "incomplete" ||
|
||||
(typeof result === "object" && result !== null && "error" in result));
|
||||
const successful = completed && !denied && !failed;
|
||||
return (
|
||||
<Box className={classes.tool}>
|
||||
<Group justify="space-between" wrap="nowrap" gap="xs">
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThemeIcon
|
||||
size="sm"
|
||||
radius="xl"
|
||||
variant="light"
|
||||
color={denied || failed ? "red" : successful ? "green" : "gray"}
|
||||
>
|
||||
{denied || failed ? <IconX size={13} /> : successful ? <IconCheck size={13} /> : <IconRobot size={13} />}
|
||||
</ThemeIcon>
|
||||
<Text size="sm" fw={600}>
|
||||
{toolName.replaceAll("_", " ")}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{awaitingApproval
|
||||
? t("approvalRequired")
|
||||
: denied
|
||||
? t("denied")
|
||||
: failed
|
||||
? t("failed")
|
||||
: successful
|
||||
? t("complete")
|
||||
: t("working")}
|
||||
</Text>
|
||||
</Group>
|
||||
{awaitingApproval && (
|
||||
<Stack gap="xs" mt="sm">
|
||||
<Text size="sm">{t("approvalDescription")}</Text>
|
||||
<Text size="xs" c="dimmed" ff="monospace">
|
||||
{JSON.stringify(args)}
|
||||
</Text>
|
||||
<Group gap="xs">
|
||||
<Button size="compact-sm" onClick={() => respondToApproval({ approved: true })}>
|
||||
{t("allowOnce")}
|
||||
</Button>
|
||||
<Button size="compact-sm" variant="default" onClick={() => respondToApproval({ approved: false })}>
|
||||
{t("deny")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Stack>
|
||||
)}
|
||||
{!awaitingApproval && !denied && result !== undefined && (
|
||||
<Text size="xs" c="dimmed" mt={6} lineClamp={3}>
|
||||
{typeof result === "string" ? result : JSON.stringify(result)}
|
||||
</Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
const MessageActions = () => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
return (
|
||||
<ActionBarPrimitive.Root hideWhenRunning>
|
||||
<Group gap={2}>
|
||||
<Tooltip label={t("copy")}>
|
||||
<ActionBarPrimitive.Copy asChild>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm">
|
||||
<IconCopy size={14} />
|
||||
</ActionIcon>
|
||||
</ActionBarPrimitive.Copy>
|
||||
</Tooltip>
|
||||
<Tooltip label={t("regenerate")}>
|
||||
<ActionBarPrimitive.Reload asChild>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm">
|
||||
<IconRefresh size={14} />
|
||||
</ActionIcon>
|
||||
</ActionBarPrimitive.Reload>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
</ActionBarPrimitive.Root>
|
||||
);
|
||||
};
|
||||
|
||||
const UserMessage = () => (
|
||||
<MessagePrimitive.Root className={`${classes.message} ${classes.userMessage}`}>
|
||||
<MessagePrimitive.Parts components={{ Text: TextPart }} />
|
||||
</MessagePrimitive.Root>
|
||||
);
|
||||
|
||||
const AssistantMessage = () => (
|
||||
<MessagePrimitive.Root className={`${classes.message} ${classes.assistantMessage}`}>
|
||||
<MessagePrimitive.Parts
|
||||
components={{
|
||||
Text: TextPart,
|
||||
tools: { Fallback: ToolPart },
|
||||
}}
|
||||
/>
|
||||
<MessageActions />
|
||||
</MessagePrimitive.Root>
|
||||
);
|
||||
|
||||
const ThreadListItem = () => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
return (
|
||||
<ThreadListItemPrimitive.Root className={classes.historyItem}>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<ThreadListItemPrimitive.Trigger asChild>
|
||||
<Button variant="subtle" color="gray" size="compact-sm" justify="flex-start" flex={1} style={{ minWidth: 0 }}>
|
||||
<ThreadListItemPrimitive.Title fallback={t("newConversation")} />
|
||||
</Button>
|
||||
</ThreadListItemPrimitive.Trigger>
|
||||
<ThreadListItemPrimitive.Archive asChild>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm" aria-label={t("archive")}>
|
||||
<IconArchive size={14} />
|
||||
</ActionIcon>
|
||||
</ThreadListItemPrimitive.Archive>
|
||||
<ThreadListItemPrimitive.Delete asChild>
|
||||
<ActionIcon variant="subtle" color="red" size="sm" aria-label={t("delete")}>
|
||||
<IconTrash size={14} />
|
||||
</ActionIcon>
|
||||
</ThreadListItemPrimitive.Delete>
|
||||
</Group>
|
||||
</ThreadListItemPrimitive.Root>
|
||||
);
|
||||
};
|
||||
|
||||
const ArchivedThreadListItem = () => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
return (
|
||||
<ThreadListItemPrimitive.Root className={classes.historyItem}>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<ThreadListItemPrimitive.Trigger asChild>
|
||||
<Button variant="subtle" color="gray" size="compact-sm" justify="flex-start" flex={1} style={{ minWidth: 0 }}>
|
||||
<ThreadListItemPrimitive.Title fallback={t("archivedConversation")} />
|
||||
</Button>
|
||||
</ThreadListItemPrimitive.Trigger>
|
||||
<ThreadListItemPrimitive.Unarchive asChild>
|
||||
<ActionIcon variant="subtle" color="gray" size="sm" aria-label={t("restore")}>
|
||||
<IconRestore size={14} />
|
||||
</ActionIcon>
|
||||
</ThreadListItemPrimitive.Unarchive>
|
||||
<ThreadListItemPrimitive.Delete asChild>
|
||||
<ActionIcon variant="subtle" color="red" size="sm" aria-label={t("delete")}>
|
||||
<IconTrash size={14} />
|
||||
</ActionIcon>
|
||||
</ThreadListItemPrimitive.Delete>
|
||||
</Group>
|
||||
</ThreadListItemPrimitive.Root>
|
||||
);
|
||||
};
|
||||
|
||||
const ThreadHistory = ({ opened, onClose }: { opened: boolean; onClose: () => void }) => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
return (
|
||||
<Stack className={classes.history} gap="xs" p="sm" data-opened={opened}>
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
<ThreadListPrimitive.New asChild>
|
||||
<Button variant="light" leftSection={<IconPlus size={16} />} fullWidth onClick={onClose}>
|
||||
{t("newConversation")}
|
||||
</Button>
|
||||
</ThreadListPrimitive.New>
|
||||
<ActionIcon
|
||||
className={classes.historyClose}
|
||||
variant="subtle"
|
||||
color="gray"
|
||||
onClick={onClose}
|
||||
aria-label={t("closeHistory")}
|
||||
>
|
||||
<IconX size={17} />
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
<Group gap="xs" px="xs" mt="xs">
|
||||
<IconHistory size={14} />
|
||||
<Text size="xs" fw={700} c="dimmed" tt="uppercase">
|
||||
{t("conversations")}
|
||||
</Text>
|
||||
</Group>
|
||||
<ScrollArea flex={1} type="auto">
|
||||
<Stack gap={3}>
|
||||
<ThreadListPrimitive.Items components={{ ThreadListItem }} />
|
||||
<Text size="xs" fw={700} c="dimmed" tt="uppercase" px="xs" mt="sm">
|
||||
{t("archived")}
|
||||
</Text>
|
||||
<ThreadListPrimitive.Items archived components={{ ThreadListItem: ArchivedThreadListItem }} />
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
|
||||
const EmptyThread = () => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
return (
|
||||
<ThreadPrimitive.Empty>
|
||||
<Box className={classes.empty}>
|
||||
<Stack align="center" gap="sm" maw={340}>
|
||||
<ThemeIcon size={52} radius="xl" variant="light" color="red">
|
||||
<IconRobot size={27} />
|
||||
</ThemeIcon>
|
||||
<Text size="xl" fw={700}>
|
||||
{t("emptyTitle")}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("emptyDescription")}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Box>
|
||||
</ThreadPrimitive.Empty>
|
||||
);
|
||||
};
|
||||
|
||||
const Composer = () => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
const running = useAuiState((state) => state.thread.isRunning);
|
||||
return (
|
||||
<Box className={classes.composerWrap}>
|
||||
<ComposerPrimitive.Root className={classes.composer}>
|
||||
<ComposerPrimitive.Input className={classes.composerInput} placeholder={t("composerPlaceholder")} rows={1} />
|
||||
{running ? (
|
||||
<ComposerPrimitive.Cancel asChild>
|
||||
<ActionIcon color="red" variant="light" size="lg" aria-label={t("stop")}>
|
||||
<IconPlayerStop size={18} />
|
||||
</ActionIcon>
|
||||
</ComposerPrimitive.Cancel>
|
||||
) : (
|
||||
<ComposerPrimitive.Send asChild>
|
||||
<ActionIcon color="red" variant="filled" size="lg" aria-label={t("send")}>
|
||||
<IconArrowUp size={18} />
|
||||
</ActionIcon>
|
||||
</ComposerPrimitive.Send>
|
||||
)}
|
||||
</ComposerPrimitive.Root>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
export const AssistantPanel = ({ opened, onClose }: AssistantPanelProps) => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
const [historyOpened, setHistoryOpened] = useState(false);
|
||||
return (
|
||||
<Drawer
|
||||
opened={opened}
|
||||
onClose={onClose}
|
||||
position="right"
|
||||
size="min(52rem, 100vw)"
|
||||
zIndex={300}
|
||||
className={classes.drawer}
|
||||
classNames={{ content: classes.content, body: classes.body }}
|
||||
title={
|
||||
<Group gap="xs">
|
||||
<ThemeIcon variant="light" color="red" radius="xl">
|
||||
<IconRobot size={18} />
|
||||
</ThemeIcon>
|
||||
<div>
|
||||
<Text fw={700} lh={1.1}>
|
||||
{t("title")}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("subtitle")}
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
}
|
||||
closeButtonProps={{ icon: <IconX size={18} />, "aria-label": t("close") }}
|
||||
>
|
||||
<Box className={classes.shell}>
|
||||
<ThreadHistory opened={historyOpened} onClose={() => setHistoryOpened(false)} />
|
||||
<ThreadPrimitive.Root className={classes.thread}>
|
||||
<ActionIcon
|
||||
className={classes.mobileHistoryButton}
|
||||
variant="default"
|
||||
onClick={() => setHistoryOpened(true)}
|
||||
aria-label={t("openHistory")}
|
||||
>
|
||||
<IconMenu2 size={17} />
|
||||
</ActionIcon>
|
||||
<ThreadPrimitive.Viewport className={classes.viewport}>
|
||||
<Box className={classes.messages}>
|
||||
<EmptyThread />
|
||||
<ThreadPrimitive.Messages components={{ UserMessage, AssistantMessage }} />
|
||||
</Box>
|
||||
<ThreadPrimitive.ScrollToBottom asChild>
|
||||
<ActionIcon
|
||||
pos="absolute"
|
||||
bottom={110}
|
||||
left="50%"
|
||||
variant="default"
|
||||
radius="xl"
|
||||
aria-label={t("scrollToLatest")}
|
||||
>
|
||||
<IconArrowUp size={16} style={{ transform: "rotate(180deg)" }} />
|
||||
</ActionIcon>
|
||||
</ThreadPrimitive.ScrollToBottom>
|
||||
</ThreadPrimitive.Viewport>
|
||||
<Composer />
|
||||
</ThreadPrimitive.Root>
|
||||
</Box>
|
||||
</Drawer>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,306 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { createContext, useCallback, useContext, useMemo, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { useChat } from "@ai-sdk/react";
|
||||
import type { MessageFormatAdapter, RemoteThreadListAdapter, ThreadHistoryAdapter, Toolkit } from "@assistant-ui/react";
|
||||
import {
|
||||
AssistantRuntimeProvider,
|
||||
defineToolkit,
|
||||
Tools,
|
||||
useAui,
|
||||
useAuiState,
|
||||
useRemoteThreadListRuntime,
|
||||
} from "@assistant-ui/react";
|
||||
import { AssistantChatTransport, useAISDKRuntime } from "@assistant-ui/react-ai-sdk";
|
||||
import { useHotkeys } from "@mantine/hooks";
|
||||
import { createAssistantStream } from "assistant-stream";
|
||||
import type { UIMessage } from "ai";
|
||||
import { lastAssistantMessageIsCompleteWithApprovalResponses } from "ai";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { clientApi, fetchApi } from "@homarr/api/client";
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import { hotkeys } from "@homarr/definitions";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import {
|
||||
openMediaRequestSearch,
|
||||
openSpotlight,
|
||||
useRegisterSpotlightContextActions,
|
||||
useRegisterSpotlightContextResults,
|
||||
} from "@homarr/spotlight";
|
||||
|
||||
import { AssistantPanel } from "./assistant-panel";
|
||||
|
||||
interface AssistantContextValue {
|
||||
enabled: boolean;
|
||||
opened: boolean;
|
||||
open: () => void;
|
||||
close: () => void;
|
||||
toggle: () => void;
|
||||
}
|
||||
|
||||
const AssistantContext = createContext<AssistantContextValue | null>(null);
|
||||
|
||||
export const useHomarrAssistant = () => {
|
||||
const value = useContext(AssistantContext);
|
||||
if (!value) {
|
||||
throw new Error("useHomarrAssistant must be used within AssistantProvider");
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
export const useOptionalHomarrAssistant = () => useContext(AssistantContext);
|
||||
|
||||
const threadAdapter: RemoteThreadListAdapter = {
|
||||
async list() {
|
||||
const threads = await fetchApi.assistant.listThreads.query();
|
||||
return {
|
||||
threads: threads.map((thread) => ({
|
||||
remoteId: thread.id,
|
||||
status: thread.status,
|
||||
title: thread.title ?? undefined,
|
||||
lastMessageAt: thread.updatedAt,
|
||||
custom: { modelId: thread.modelId },
|
||||
})),
|
||||
};
|
||||
},
|
||||
async initialize(localId) {
|
||||
const thread = await fetchApi.assistant.createThread.mutate({ localId });
|
||||
return { remoteId: thread.id, externalId: undefined };
|
||||
},
|
||||
async fetch(threadId) {
|
||||
const { thread } = await fetchApi.assistant.getThread.query({ threadId });
|
||||
return {
|
||||
remoteId: thread.id,
|
||||
status: thread.status,
|
||||
title: thread.title ?? undefined,
|
||||
lastMessageAt: thread.updatedAt,
|
||||
custom: { modelId: thread.modelId },
|
||||
};
|
||||
},
|
||||
async rename(threadId, title) {
|
||||
await fetchApi.assistant.renameThread.mutate({ threadId, title });
|
||||
},
|
||||
async archive(threadId) {
|
||||
await fetchApi.assistant.setThreadStatus.mutate({ threadId, status: "archived" });
|
||||
},
|
||||
async unarchive(threadId) {
|
||||
await fetchApi.assistant.setThreadStatus.mutate({ threadId, status: "regular" });
|
||||
},
|
||||
async delete(threadId) {
|
||||
await fetchApi.assistant.deleteThread.mutate({ threadId });
|
||||
},
|
||||
async generateTitle(_threadId, messages) {
|
||||
const firstUserMessage = messages.find((message) => message.role === "user");
|
||||
const text =
|
||||
firstUserMessage?.content
|
||||
.filter((part) => part.type === "text")
|
||||
.map((part) => part.text)
|
||||
.join(" ")
|
||||
.trim()
|
||||
.slice(0, 72) || "New conversation";
|
||||
return createAssistantStream((controller) => controller.appendText(text));
|
||||
},
|
||||
};
|
||||
|
||||
const createHistoryAdapter = (threadId: string | undefined): ThreadHistoryAdapter => ({
|
||||
async load() {
|
||||
return { messages: [] };
|
||||
},
|
||||
async append() {
|
||||
// AI SDK runtimes use the typed adapter returned by withFormat below.
|
||||
},
|
||||
withFormat<TMessage, TStorageFormat extends Record<string, unknown>>(
|
||||
formatAdapter: MessageFormatAdapter<TMessage, TStorageFormat>,
|
||||
) {
|
||||
if (formatAdapter.format !== "ai-sdk/v6") {
|
||||
throw new Error(`Unsupported assistant message format: ${formatAdapter.format}`);
|
||||
}
|
||||
const storageFormat = formatAdapter.format;
|
||||
return {
|
||||
async load() {
|
||||
if (!threadId) return { messages: [] };
|
||||
const { messages } = await fetchApi.assistant.getThread.query({ threadId });
|
||||
return {
|
||||
messages: messages
|
||||
.filter((message) => message.format === formatAdapter.format)
|
||||
.map(
|
||||
(message) =>
|
||||
formatAdapter.decode({
|
||||
id: message.id,
|
||||
parent_id: message.parentId,
|
||||
format: message.format,
|
||||
content: message.content as TStorageFormat,
|
||||
}) as { parentId: string | null; message: TMessage },
|
||||
),
|
||||
};
|
||||
},
|
||||
async append(item) {
|
||||
if (!threadId) return;
|
||||
await fetchApi.assistant.appendMessage.mutate({
|
||||
threadId,
|
||||
id: (formatAdapter as MessageFormatAdapter<unknown, TStorageFormat>).getId(item.message),
|
||||
parentId: item.parentId,
|
||||
format: storageFormat,
|
||||
content: (formatAdapter as MessageFormatAdapter<unknown, TStorageFormat>).encode(
|
||||
item as { parentId: string | null; message: unknown },
|
||||
),
|
||||
});
|
||||
},
|
||||
async update(item, localMessageId) {
|
||||
if (!threadId) return;
|
||||
const erasedFormatAdapter = formatAdapter as MessageFormatAdapter<unknown, TStorageFormat>;
|
||||
const id = erasedFormatAdapter.getId(item.message);
|
||||
await fetchApi.assistant.appendMessage.mutate({
|
||||
threadId,
|
||||
id,
|
||||
parentId: item.parentId,
|
||||
format: storageFormat,
|
||||
content: erasedFormatAdapter.encode(item as { parentId: string | null; message: unknown }),
|
||||
});
|
||||
if (localMessageId !== id) {
|
||||
await fetchApi.assistant.deleteMessages.mutate({ threadId, ids: [localMessageId] });
|
||||
}
|
||||
},
|
||||
async delete(items) {
|
||||
if (!threadId || items.length === 0) return;
|
||||
await fetchApi.assistant.deleteMessages.mutate({
|
||||
threadId,
|
||||
ids: items.map((item) =>
|
||||
(formatAdapter as MessageFormatAdapter<unknown, TStorageFormat>).getId(item.message),
|
||||
),
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const AssistantThreadRuntime = () => {
|
||||
const localThreadId = useAuiState((state) => state.threadListItem.id);
|
||||
const threadId = useAuiState((state) => state.threadListItem.remoteId);
|
||||
const aui = useAui();
|
||||
const transport = useMemo(() => new AssistantChatTransport({ api: "/api/assistant/chat" }), []);
|
||||
const chat = useChat<UIMessage>({
|
||||
id: localThreadId,
|
||||
transport,
|
||||
sendAutomaticallyWhen: lastAssistantMessageIsCompleteWithApprovalResponses,
|
||||
});
|
||||
const history = useMemo(() => createHistoryAdapter(threadId), [threadId]);
|
||||
const runtime = useAISDKRuntime(chat, { adapters: { history } });
|
||||
|
||||
transport.setRuntime(runtime);
|
||||
transport["__internal_setGetThreadListItem"](() => (aui.threadListItem.source ? aui.threadListItem() : undefined));
|
||||
|
||||
return runtime;
|
||||
};
|
||||
|
||||
const AssistantRuntime = ({ children }: PropsWithChildren) => {
|
||||
const router = useRouter();
|
||||
const runtime = useRemoteThreadListRuntime({
|
||||
adapter: threadAdapter,
|
||||
runtimeHook: AssistantThreadRuntime,
|
||||
});
|
||||
|
||||
const toolkit = useMemo(
|
||||
() =>
|
||||
defineToolkit({
|
||||
navigate_to_route: {
|
||||
type: "frontend",
|
||||
description:
|
||||
"Navigate the current Homarr tab to a safe internal route. Only paths beginning with a single slash are accepted.",
|
||||
parameters: z.object({
|
||||
path: z.string().describe("An internal Homarr route, for example /manage/apps"),
|
||||
}),
|
||||
execute: async ({ path }) => {
|
||||
if (!path.startsWith("/") || path.startsWith("//")) {
|
||||
return { success: false, error: "Only internal Homarr paths are allowed." };
|
||||
}
|
||||
router.push(path);
|
||||
return { success: true, path };
|
||||
},
|
||||
renderText: {
|
||||
running: ({ args }) => `Opening ${args.path}…`,
|
||||
complete: ({ args }) => `Opened ${args.path}`,
|
||||
},
|
||||
},
|
||||
open_command_menu: {
|
||||
type: "frontend",
|
||||
description: "Open Homarr's command and search menu.",
|
||||
parameters: z.object({}),
|
||||
execute: async () => {
|
||||
openSpotlight();
|
||||
return { success: true };
|
||||
},
|
||||
renderText: { running: "Opening command menu…", complete: "Command menu opened" },
|
||||
},
|
||||
open_media_request_search: {
|
||||
type: "frontend",
|
||||
description: "Open Homarr's media request search interface.",
|
||||
parameters: z.object({}),
|
||||
execute: async () => {
|
||||
openMediaRequestSearch();
|
||||
return { success: true };
|
||||
},
|
||||
renderText: { running: "Opening media search…", complete: "Media search opened" },
|
||||
},
|
||||
}) as Toolkit,
|
||||
[router],
|
||||
);
|
||||
|
||||
return (
|
||||
<AssistantRuntimeProvider runtime={runtime}>
|
||||
<AssistantTools toolkit={toolkit} />
|
||||
{children}
|
||||
</AssistantRuntimeProvider>
|
||||
);
|
||||
};
|
||||
|
||||
const AssistantTools = ({ toolkit }: { toolkit: Toolkit }) => {
|
||||
useAui({ tools: Tools({ toolkit }) });
|
||||
return null;
|
||||
};
|
||||
|
||||
export const AssistantProvider = ({ children }: PropsWithChildren) => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
const session = useSession();
|
||||
const [opened, setOpened] = useState(false);
|
||||
const { data } = clientApi.assistant.getAvailability.useQuery(undefined, {
|
||||
enabled: session.status === "authenticated",
|
||||
staleTime: 60_000,
|
||||
});
|
||||
const enabled = Boolean(data?.enabled && session.status === "authenticated");
|
||||
|
||||
const open = useCallback(() => setOpened(true), []);
|
||||
const close = useCallback(() => setOpened(false), []);
|
||||
const toggle = useCallback(() => setOpened((current) => !current), []);
|
||||
useHotkeys([[hotkeys.openAssistant, open]]);
|
||||
|
||||
const spotlightItem = useMemo(
|
||||
() => ({
|
||||
id: "homarr-assistant",
|
||||
name: t("spotlight"),
|
||||
icon: "/logo/logo.png",
|
||||
interaction: () => ({ type: "javaScript" as const, onSelect: open }),
|
||||
}),
|
||||
[open, t],
|
||||
);
|
||||
useRegisterSpotlightContextResults("homarr-assistant", enabled ? [spotlightItem] : [], [enabled, spotlightItem]);
|
||||
useRegisterSpotlightContextActions("homarr-assistant", enabled ? [spotlightItem] : [], [enabled, spotlightItem]);
|
||||
|
||||
const value = useMemo(() => ({ enabled, opened, open, close, toggle }), [close, enabled, open, opened, toggle]);
|
||||
|
||||
return (
|
||||
<AssistantContext.Provider value={value}>
|
||||
{enabled ? (
|
||||
<AssistantRuntime>
|
||||
{children}
|
||||
<AssistantPanel opened={opened} onClose={close} />
|
||||
</AssistantRuntime>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</AssistantContext.Provider>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,23 @@
|
||||
"use client";
|
||||
|
||||
import { Tooltip } from "@mantine/core";
|
||||
import { IconRobot } from "@tabler/icons-react";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { HeaderButton } from "../layout/header/button";
|
||||
import { useOptionalHomarrAssistant } from "./assistant-provider";
|
||||
|
||||
export const AssistantHeaderButton = () => {
|
||||
const t = useScopedI18n("common.assistant");
|
||||
const assistant = useOptionalHomarrAssistant();
|
||||
if (!assistant?.enabled) return null;
|
||||
|
||||
return (
|
||||
<Tooltip label={`${t("title")} (Mod+Shift+K)`} position="bottom">
|
||||
<HeaderButton onClick={assistant.open} aria-label={t("open")}>
|
||||
<IconRobot size={20} />
|
||||
</HeaderButton>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
@@ -4,6 +4,7 @@ import { AppShellHeader, Group, UnstyledButton } from "@mantine/core";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { ClientBurger } from "./header/burger";
|
||||
import { AssistantHeaderButton } from "../assistant/assistant-trigger";
|
||||
import { DesktopSearchInput, MobileSearchButton } from "./header/search";
|
||||
import { TourTarget } from "./header/tour-target";
|
||||
import { UserButton } from "./header/user";
|
||||
@@ -37,6 +38,7 @@ export const MainHeader = ({ logo, actions, hasNavigation = true }: Props) => {
|
||||
</TourTarget>
|
||||
<Group h="100%" align="center" justify="end" style={{ flex: 1 }} wrap="nowrap">
|
||||
{actions}
|
||||
<AssistantHeaderButton />
|
||||
<MobileSearchButton />
|
||||
<TourTarget id="board-user-menu">
|
||||
<UserButton />
|
||||
|
||||
@@ -2,16 +2,26 @@
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { Menu } from "@mantine/core";
|
||||
import { IconBrandDocker, IconHome, IconLogin, IconLogout, IconSettings, IconTool } from "@tabler/icons-react";
|
||||
import { Badge, Indicator, Kbd, Loader, Menu, Text } from "@mantine/core";
|
||||
import {
|
||||
IconBrandDocker,
|
||||
IconHome,
|
||||
IconLogin,
|
||||
IconLogout,
|
||||
IconSettings,
|
||||
IconRobot,
|
||||
IconTool,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { signOut, useSession } from "@homarr/auth/client";
|
||||
import { hotkeys } from "@homarr/definitions";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
|
||||
import { useAuthContext } from "~/app/[locale]/_client-providers/session";
|
||||
import { useOptionalHomarrAssistant } from "./assistant/assistant-context";
|
||||
import { CurrentColorSchemeCombobox } from "./color-scheme/current-color-scheme-combobox";
|
||||
import { CurrentLanguageCombobox } from "./language/current-language-combobox";
|
||||
import { DockerQuickAccessModal } from "./layout/header/docker-quick-access-modal";
|
||||
@@ -25,6 +35,12 @@ interface UserAvatarMenuProps {
|
||||
onOpenChange: (opened: boolean) => void;
|
||||
}
|
||||
|
||||
const formatHotkeyLabel = (hotkey: string, modifierLabel: string) =>
|
||||
hotkey
|
||||
.split("+")
|
||||
.map((key) => (key === "mod" ? modifierLabel : `${key.charAt(0).toUpperCase()}${key.slice(1)}`))
|
||||
.join(" + ");
|
||||
|
||||
export const UserAvatarMenu = ({
|
||||
children,
|
||||
availableUpdates,
|
||||
@@ -37,6 +53,7 @@ export const UserAvatarMenu = ({
|
||||
|
||||
const { logoutUrl } = useAuthContext();
|
||||
const { openModal: openDockerModal } = useModalAction(DockerQuickAccessModal);
|
||||
const assistant = useOptionalHomarrAssistant();
|
||||
|
||||
const handleSignout = useCallback(async () => {
|
||||
const redirectUrl = logoutUrl ?? "/auth/login";
|
||||
@@ -65,6 +82,29 @@ export const UserAvatarMenu = ({
|
||||
<Menu.Divider />
|
||||
{Boolean(session.data) && (
|
||||
<>
|
||||
{assistant?.enabled && (
|
||||
<Menu.Item
|
||||
leftSection={
|
||||
assistant.isRunning ? <Loader type="bars" color="red" size="xs" /> : <IconRobot size="1rem" />
|
||||
}
|
||||
rightSection={
|
||||
assistant.unreadCount > 0 ? (
|
||||
<Badge size="sm" variant="filled" color="red" circle>
|
||||
{assistant.unreadCount > 99 ? "99+" : assistant.unreadCount}
|
||||
</Badge>
|
||||
) : assistant.isRunning ? (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("assistantThinking")}
|
||||
</Text>
|
||||
) : (
|
||||
<Kbd size="xs">{formatHotkeyLabel(hotkeys.openAssistant, t("modifier"))}</Kbd>
|
||||
)
|
||||
}
|
||||
onClick={assistant.open}
|
||||
>
|
||||
{t("assistant")}
|
||||
</Menu.Item>
|
||||
)}
|
||||
<Menu.Item
|
||||
component={Link}
|
||||
href={`/manage/users/${session.data?.user.id}/general`}
|
||||
@@ -94,7 +134,28 @@ export const UserAvatarMenu = ({
|
||||
</Menu.Item>
|
||||
)}
|
||||
</Menu.Dropdown>
|
||||
<Menu.Target>{children}</Menu.Target>
|
||||
<Menu.Target>
|
||||
<Indicator
|
||||
inline
|
||||
disabled={!assistant?.isRunning && !assistant?.unreadCount}
|
||||
color="red"
|
||||
size={20}
|
||||
offset={4}
|
||||
label={
|
||||
assistant?.isRunning ? (
|
||||
<Loader type="bars" color="white" size={10} />
|
||||
) : assistant?.unreadCount ? (
|
||||
assistant.unreadCount > 99 ? (
|
||||
"99+"
|
||||
) : (
|
||||
assistant.unreadCount
|
||||
)
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</Indicator>
|
||||
</Menu.Target>
|
||||
</Menu>
|
||||
);
|
||||
};
|
||||
Reference in new issue
Block a user