feat: polish release v2 experience (#6800)
This commit is contained in:
1 parent
925b0fb801
commit
a4a903d7c3
295 files changed
+10627
-7115
No files matched your search
@@ -8,6 +8,8 @@ import type { QueryClient } from "@tanstack/react-query";
|
||||
import { useQueryClient } from "@tanstack/react-query";
|
||||
import { ReactQueryDevtoolsPanel } from "@tanstack/react-query-devtools";
|
||||
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
|
||||
const valueStyle = { fontFamily: "monospace", overflowWrap: "anywhere" } as const;
|
||||
const metricStyle = {
|
||||
background: "color-mix(in srgb, currentColor 4%, transparent)",
|
||||
@@ -33,11 +35,9 @@ const readDiagnostics = (queryClient: QueryClient) => {
|
||||
total: queries.length,
|
||||
readyWidgets,
|
||||
widgetItems,
|
||||
scriptKiB: Math.round(
|
||||
resources
|
||||
.filter((resource) => resource.initiatorType === "script")
|
||||
.reduce((total, resource) => total + resource.decodedBodySize, 0) / 1024,
|
||||
),
|
||||
scriptBytes: resources
|
||||
.filter((resource) => resource.initiatorType === "script")
|
||||
.reduce((total, resource) => total + resource.decodedBodySize, 0),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -51,6 +51,7 @@ const Metric = ({ label, value }: { label: string; value: number | string }) =>
|
||||
const HomarrDevtoolsPanel = ({ active }: { active: boolean }) => {
|
||||
const pathname = usePathname();
|
||||
const queryClient = useQueryClient();
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const [diagnostics, setDiagnostics] = useState(() => readDiagnostics(queryClient));
|
||||
|
||||
useEffect(() => {
|
||||
@@ -95,7 +96,7 @@ const HomarrDevtoolsPanel = ({ active }: { active: boolean }) => {
|
||||
<Metric label="Errors" value={diagnostics.errors} />
|
||||
<Metric label="Mutations" value={diagnostics.pendingMutations} />
|
||||
<Metric label="Widgets ready" value={`${diagnostics.readyWidgets}/${diagnostics.widgetItems}`} />
|
||||
<Metric label="Script KiB" value={diagnostics.scriptKiB} />
|
||||
<Metric label="Script" value={formatBytes(diagnostics.scriptBytes)} />
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
|
||||
@@ -7,7 +7,6 @@ import type { z } from "zod/v4";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { useUpdateBoard } from "@homarr/boards/updater";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { env } from "@homarr/common/env";
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useSettings } from "@homarr/settings";
|
||||
@@ -17,6 +16,7 @@ import { boardSaveLayoutsSchema, boardSavePartialSettingsSchema } from "@homarr/
|
||||
import { homarrLogoPath } from "~/components/layout/logo/constants";
|
||||
import { SectionCard } from "~/components/manage/section-card";
|
||||
import { UnsavedChangesBar } from "~/components/manage/unsaved-changes-bar";
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
|
||||
import type { Board } from "../../_types";
|
||||
import { ColorSettingsContent } from "./_appereance";
|
||||
@@ -107,8 +107,7 @@ export const BoardSettingsForm = ({ board, permissions, hasFullAccess, hideVisib
|
||||
const initialValuesRef = useRef(buildInitialValues(board));
|
||||
const lastSavedRef = useRef({ pageTitle: board.pageTitle, logoImageUrl: board.logoImageUrl });
|
||||
|
||||
const isDirtyRef = useRef(false);
|
||||
isDirtyRef.current = form.isDirty();
|
||||
useUnsavedChangesGuard(form.isDirty());
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
@@ -120,15 +119,6 @@ export const BoardSettingsForm = ({ board, permissions, hasFullAccess, hideVisib
|
||||
};
|
||||
}, [updateBoard]);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: BeforeUnloadEvent) => {
|
||||
if (env.NODE_ENV === "development") return;
|
||||
if (isDirtyRef.current) event.preventDefault();
|
||||
};
|
||||
window.addEventListener("beforeunload", handler);
|
||||
return () => window.removeEventListener("beforeunload", handler);
|
||||
}, []);
|
||||
|
||||
const saveSettingsAsync = async (values: FormValues): Promise<FormValues | null> => {
|
||||
const defaults = initialValuesRef.current;
|
||||
const changed = <TKey extends keyof FormValues>(...fields: TKey[]) =>
|
||||
|
||||
@@ -25,7 +25,7 @@ const searchParamsSchema = z.object({
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
.pipe(z.number().int().positive().max(100))
|
||||
.catch(10),
|
||||
page: z
|
||||
.string()
|
||||
@@ -52,6 +52,13 @@ export default async function AppsPage(props: AppsPageProps) {
|
||||
const { items: apps, totalCount } = canManageAll
|
||||
? await api.app.getPaginated(searchParams)
|
||||
: { items: [], totalCount: 0 };
|
||||
const totalPages = Math.ceil(totalCount / searchParams.pageSize);
|
||||
|
||||
if (totalPages > 0 && searchParams.page > totalPages) {
|
||||
const params = createPaginationSearchParams(searchParams.search, searchParams.pageSize, totalPages);
|
||||
redirect(`/manage/apps?${params.toString()}`);
|
||||
}
|
||||
|
||||
const t = await getI18n("app");
|
||||
const tCommon = await getI18n("common");
|
||||
const hasSearch = canManageAll && Boolean(searchParams.search?.trim());
|
||||
@@ -104,11 +111,7 @@ export default async function AppsPage(props: AppsPageProps) {
|
||||
/>
|
||||
) : undefined
|
||||
}
|
||||
footer={
|
||||
totalCount > searchParams.pageSize ? (
|
||||
<TablePagination total={Math.ceil(totalCount / searchParams.pageSize)} />
|
||||
) : undefined
|
||||
}
|
||||
footer={totalPages > 1 ? <TablePagination total={totalPages} /> : undefined}
|
||||
floatingPrimaryAction={canCreate}
|
||||
>
|
||||
{apps.map((app) => (
|
||||
@@ -187,3 +190,12 @@ const AppItem = ({ app, canDelete, editLabel }: AppItemProps) => {
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const createPaginationSearchParams = (search: string | undefined, pageSize: number, page: number) => {
|
||||
const params = new URLSearchParams({ page: page.toString() });
|
||||
|
||||
if (search) params.set("search", search);
|
||||
if (pageSize !== 10) params.set("pageSize", pageSize.toString());
|
||||
|
||||
return params;
|
||||
};
|
||||
@@ -11,11 +11,13 @@ import {
|
||||
IconDownload,
|
||||
IconPlayerPause,
|
||||
IconPlayerPlay,
|
||||
IconPlugConnected,
|
||||
IconSparkles,
|
||||
IconTrash,
|
||||
IconUpload,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { formatCustomWidgetImportIssues, parseCustomWidgetClipboardDetailed } from "@homarr/custom-widgets/core";
|
||||
@@ -29,15 +31,15 @@ import { downloadJson } from "~/components/custom-widgets/download";
|
||||
|
||||
const iconProps = { size: 16, stroke: 1.5 };
|
||||
|
||||
interface WidgetRef {
|
||||
id: string;
|
||||
name: string;
|
||||
enabled: boolean;
|
||||
valid: boolean;
|
||||
migrationRequired: boolean;
|
||||
type WidgetListItem = RouterOutputs["customWidget"]["list"][number];
|
||||
type WidgetRef = Pick<WidgetListItem, "id" | "name" | "enabled" | "valid" | "migrationRequired">;
|
||||
|
||||
interface CustomWidgetRowActionsProps {
|
||||
widget: WidgetRef;
|
||||
onConfigureSources(): void;
|
||||
}
|
||||
|
||||
export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
|
||||
export const CustomWidgetRowActions = ({ widget, onConfigureSources }: CustomWidgetRowActionsProps) => {
|
||||
const t = useI18n("customWidget");
|
||||
const tCommon = useI18n("common");
|
||||
const deleteMutation = clientApi.customWidget.delete.useMutation();
|
||||
@@ -210,6 +212,9 @@ export const CustomWidgetRowActions = ({ widget }: { widget: WidgetRef }) => {
|
||||
>
|
||||
{widget.enabled ? t("action.disable") : t("action.enable")}
|
||||
</Menu.Item>
|
||||
<Menu.Item onClick={onConfigureSources} leftSection={<IconPlugConnected {...iconProps} />}>
|
||||
{t("action.configureSources")}
|
||||
</Menu.Item>
|
||||
<Menu.Divider />
|
||||
<Menu.Item
|
||||
onClick={handleDuplicate}
|
||||
|
||||
@@ -20,10 +20,10 @@ import {
|
||||
import { getCustomWidgetDefaultOptions } from "@homarr/custom-widgets/core";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
import { useCustomWidgetFormDocumentDirty } from "./_custom-widget-form-state";
|
||||
import { areCustomWidgetValuesEqual } from "./_custom-widget-value-equality";
|
||||
import { useCustomWidgetFormAnalysisField } from "./_use-custom-widget-form-analysis";
|
||||
import { useUnsavedChangesGuard } from "./_use-unsaved-changes-guard";
|
||||
import classes from "./_custom-widget-form.module.css";
|
||||
|
||||
const sectionLinks = [
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { fetchApi } from "@homarr/api/client";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import {
|
||||
customWidgetDefinitionSchema,
|
||||
getCustomWidgetDefaultOptions,
|
||||
@@ -12,6 +13,8 @@ import type { UseFormReturnType } from "@mantine/form";
|
||||
|
||||
export type CustomWidgetWorkbenchForm = UseFormReturnType<CustomWidgetFormValues>;
|
||||
|
||||
export { isRecord };
|
||||
|
||||
const PREVIEW_QUERY_CONCURRENCY = 4;
|
||||
|
||||
export function buildDefinition(values: CustomWidgetFormValues) {
|
||||
@@ -83,10 +86,6 @@ export function parseJson(value: string): unknown {
|
||||
}
|
||||
}
|
||||
|
||||
export function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function getCustomWidgetPreviewOptionIssues(definition: HomarrCustomWidgetV2, options: Record<string, unknown>) {
|
||||
return validateCustomWidgetOptions(definition.options, options);
|
||||
}
|
||||
|
||||
@@ -101,6 +101,7 @@ function CustomWidgetRow({ widget }: { widget: WidgetDef }) {
|
||||
</Button>
|
||||
)}
|
||||
<CustomWidgetRowActions
|
||||
onConfigureSources={sourceSetupControls.open}
|
||||
widget={{
|
||||
id: widget.id,
|
||||
name: widget.name,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export interface CustomWidgetSaveIssue {
|
||||
path?: string;
|
||||
message: string;
|
||||
@@ -58,7 +60,5 @@ function uniqueIssues(issues: CustomWidgetSaveIssue[]) {
|
||||
}
|
||||
|
||||
function asRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value)
|
||||
? (value as Record<string, unknown>)
|
||||
: null;
|
||||
return isRecord(value) ? value : null;
|
||||
}
|
||||
+2
-4
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export function getDependentRequestIds(requestsJson: string, sourceId: string) {
|
||||
const requests = parseRequestRecord(requestsJson);
|
||||
return Object.entries(requests).flatMap(([requestId, request]) =>
|
||||
@@ -21,7 +23,3 @@ function parseRequestRecord(requestsJson: string): Record<string, unknown> {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export function areCustomWidgetValuesEqual(left: unknown, right: unknown): boolean {
|
||||
if (Object.is(left, right)) return true;
|
||||
|
||||
@@ -12,7 +14,3 @@ export function areCustomWidgetValuesEqual(left: unknown, right: unknown): boole
|
||||
if (leftKeys.length !== rightKeys.length) return false;
|
||||
return leftKeys.every((key) => Object.hasOwn(right, key) && areCustomWidgetValuesEqual(left[key], right[key]));
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { registerUnsavedChangesGuard } from "./_unsaved-changes-guard";
|
||||
import { registerUnsavedChangesGuard } from "~/components/manage/unsaved-changes-guard";
|
||||
|
||||
const cleanups: Array<() => void> = [];
|
||||
|
||||
|
||||
+6
-2
@@ -26,10 +26,11 @@ import {
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { Link } from "@homarr/ui";
|
||||
import { useWorkshopCreateMutation } from "@homarr/workshop/backend";
|
||||
import { workshopScreenshotsSchema } from "@homarr/workshop/schema";
|
||||
import { MAX_WORKSHOP_SCREENSHOT_BYTES, workshopScreenshotsSchema } from "@homarr/workshop/schema";
|
||||
|
||||
import { ManagePageLayout } from "~/components/manage/manage-page-layout";
|
||||
import { ManageStickyFooter } from "~/components/manage/manage-sticky-footer";
|
||||
@@ -47,6 +48,7 @@ const listHref = "/manage/custom-widgets";
|
||||
export function WorkshopPublishForm({ widget }: { widget: { id: string; name: string } }) {
|
||||
const t = useI18n("workshop");
|
||||
const tCommon = useI18n("common");
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const session = useWorkshopSession();
|
||||
const [title, setTitle] = useState(widget.name);
|
||||
const [description, setDescription] = useState("");
|
||||
@@ -70,7 +72,9 @@ export function WorkshopPublishForm({ widget }: { widget: { id: string; name: st
|
||||
setError(null);
|
||||
try {
|
||||
if (!definition.data) throw new Error(t("publish.error"));
|
||||
if (!workshopScreenshotsSchema.safeParse(screenshots).success) throw new Error(t("publish.invalidScreenshot"));
|
||||
if (!workshopScreenshotsSchema.safeParse(screenshots).success) {
|
||||
throw new Error(t("publish.invalidScreenshot", { maxSize: formatBytes(MAX_WORKSHOP_SCREENSHOT_BYTES) }));
|
||||
}
|
||||
|
||||
let submissionId: string | null = null;
|
||||
const result = await publishWorkshopDefinition({
|
||||
|
||||
@@ -12,6 +12,7 @@ interface CopyMediaProps {
|
||||
|
||||
export const CopyMedia = ({ media }: CopyMediaProps) => {
|
||||
const t = useI18n("media");
|
||||
const label = t("action.copy.labelNamed", { name: media.name });
|
||||
|
||||
const url = typeof window !== "undefined" ? `${window.location.origin}/api/user-medias/${media.id}` : "";
|
||||
|
||||
@@ -23,8 +24,8 @@ export const CopyMedia = ({ media }: CopyMediaProps) => {
|
||||
return (
|
||||
<CopyButton value={url}>
|
||||
{({ copy, copied }) => (
|
||||
<Tooltip label={t("action.copy.label")} openDelay={500}>
|
||||
<ActionIcon onClick={copy} color={copied ? "teal" : "gray"} variant="subtle">
|
||||
<Tooltip label={label} openDelay={500}>
|
||||
<ActionIcon aria-label={label} onClick={copy} color={copied ? "teal" : "gray"} variant="subtle">
|
||||
{copied ? <IconCheck size={16} stroke={1.5} /> : <IconCopy size={16} stroke={1.5} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
|
||||
@@ -1,24 +1,28 @@
|
||||
import { notFound } from "next/navigation";
|
||||
import { notFound, redirect } from "next/navigation";
|
||||
import {
|
||||
ActionIcon,
|
||||
Anchor,
|
||||
Group,
|
||||
Image,
|
||||
Table,
|
||||
TableScrollContainer,
|
||||
TableTbody,
|
||||
TableTd,
|
||||
TableTh,
|
||||
TableThead,
|
||||
TableTr,
|
||||
Tooltip,
|
||||
VisuallyHidden,
|
||||
} from "@mantine/core";
|
||||
import { IconExternalLink, IconPhoto } from "@tabler/icons-react";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { api } from "@homarr/api/server";
|
||||
import { getRscUserSettingsAsync } from "@homarr/api/user-server";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import { defaultByteUnitSystem, formatBytes } from "@homarr/common";
|
||||
import type { ByteUnitSystem } from "@homarr/common";
|
||||
import type { inferSearchParamsFromSchema } from "@homarr/common/types";
|
||||
import { createLocalImageUrl } from "@homarr/icons/local";
|
||||
import { getI18n } from "@homarr/translation/server";
|
||||
@@ -36,11 +40,21 @@ const searchParamsSchema = z.object({
|
||||
search: z.string().optional(),
|
||||
includeFromAllUsers: z
|
||||
.string()
|
||||
.regex(/true|false/)
|
||||
.regex(/^(?:true|false)$/u)
|
||||
.catch("false")
|
||||
.transform((value) => value === "true"),
|
||||
pageSize: z.string().regex(/\d+/).transform(Number).catch(10),
|
||||
page: z.string().regex(/\d+/).transform(Number).catch(1),
|
||||
pageSize: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive().max(100))
|
||||
.catch(10),
|
||||
page: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
.catch(1),
|
||||
});
|
||||
|
||||
interface MediaListPageProps {
|
||||
@@ -57,7 +71,17 @@ export default async function MediaListPage(props: MediaListPageProps) {
|
||||
const tMedia = await getI18n("media");
|
||||
const [tCommon, tEntities] = await Promise.all([getI18n("common"), getI18n("common.entity")]);
|
||||
const searchParams = searchParamsSchema.parse(await props.searchParams);
|
||||
const { items: medias, totalCount } = await api.media.getPaginated(searchParams);
|
||||
const [{ items: medias, totalCount }, userSettings] = await Promise.all([
|
||||
api.media.getPaginated(searchParams),
|
||||
getRscUserSettingsAsync(session.user.id),
|
||||
]);
|
||||
const totalPages = Math.ceil(totalCount / searchParams.pageSize);
|
||||
|
||||
if (totalPages > 0 && searchParams.page > totalPages) {
|
||||
const params = createPaginationSearchParams(searchParams, totalPages);
|
||||
redirect(`/manage/medias?${params.toString()}`);
|
||||
}
|
||||
|
||||
const canUpload = session.user.permissions.includes("media-upload");
|
||||
|
||||
return (
|
||||
@@ -82,27 +106,37 @@ export default async function MediaListPage(props: MediaListPageProps) {
|
||||
)}
|
||||
</Group>
|
||||
}
|
||||
footer={<TablePagination total={Math.ceil(totalCount / searchParams.pageSize)} />}
|
||||
footer={totalPages > 1 ? <TablePagination total={totalPages} /> : undefined}
|
||||
floatingPrimaryAction={canUpload}
|
||||
>
|
||||
{medias.length === 0 && <NoResults icon={IconPhoto} title={tMedia("noResults.title")} />}
|
||||
{medias.length > 0 && (
|
||||
<Table striped highlightOnHover>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh></TableTh>
|
||||
<TableTh>{tCommon("field.name")}</TableTh>
|
||||
<TableTh>{tMedia("field.size")}</TableTh>
|
||||
<TableTh>{tMedia("field.creator")}</TableTh>
|
||||
<TableTh></TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{medias.map((media) => (
|
||||
<Row key={media.id} media={media} />
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
<TableScrollContainer minWidth={680}>
|
||||
<Table striped highlightOnHover>
|
||||
<TableThead>
|
||||
<TableTr>
|
||||
<TableTh>
|
||||
<VisuallyHidden>{tMedia("field.preview")}</VisuallyHidden>
|
||||
</TableTh>
|
||||
<TableTh>{tCommon("field.name")}</TableTh>
|
||||
<TableTh>{tMedia("field.size")}</TableTh>
|
||||
<TableTh>{tMedia("field.creator")}</TableTh>
|
||||
<TableTh>
|
||||
<VisuallyHidden>{tMedia("field.actions")}</VisuallyHidden>
|
||||
</TableTh>
|
||||
</TableTr>
|
||||
</TableThead>
|
||||
<TableTbody>
|
||||
{medias.map((media) => (
|
||||
<Row
|
||||
key={media.id}
|
||||
media={media}
|
||||
byteUnitSystem={userSettings?.byteUnitSystem ?? defaultByteUnitSystem}
|
||||
/>
|
||||
))}
|
||||
</TableTbody>
|
||||
</Table>
|
||||
</TableScrollContainer>
|
||||
)}
|
||||
</ManagePageLayout>
|
||||
);
|
||||
@@ -110,9 +144,10 @@ export default async function MediaListPage(props: MediaListPageProps) {
|
||||
|
||||
interface RowProps {
|
||||
media: RouterOutputs["media"]["getPaginated"]["items"][number];
|
||||
byteUnitSystem: ByteUnitSystem;
|
||||
}
|
||||
|
||||
const Row = async ({ media }: RowProps) => {
|
||||
const Row = async ({ media, byteUnitSystem }: RowProps) => {
|
||||
const session = await auth();
|
||||
const tMedia = await getI18n("media");
|
||||
const canDelete = media.creatorId === session?.user.id || session?.user.permissions.includes("media-full-all");
|
||||
@@ -129,8 +164,8 @@ const Row = async ({ media }: RowProps) => {
|
||||
fit="contain"
|
||||
/>
|
||||
</TableTd>
|
||||
<TableTd>{media.name}</TableTd>
|
||||
<TableTd>{formatBytes(media.size)}</TableTd>
|
||||
<TableTh scope="row">{media.name}</TableTh>
|
||||
<TableTd>{formatBytes(media.size, { unit: byteUnitSystem })}</TableTd>
|
||||
<TableTd>
|
||||
{media.creator ? (
|
||||
<Group gap="sm">
|
||||
@@ -146,11 +181,13 @@ const Row = async ({ media }: RowProps) => {
|
||||
<TableTd w={64}>
|
||||
<Group wrap="nowrap" gap="xs">
|
||||
<CopyMedia media={media} />
|
||||
<Tooltip label={tMedia("action.open.label")} openDelay={500}>
|
||||
<Tooltip label={tMedia("action.open.labelNamed", { name: media.name })} openDelay={500}>
|
||||
<ActionIcon
|
||||
aria-label={tMedia("action.open.labelNamed", { name: media.name })}
|
||||
component="a"
|
||||
href={createLocalImageUrl(media.id)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
color="gray"
|
||||
variant="subtle"
|
||||
>
|
||||
@@ -163,3 +200,13 @@ const Row = async ({ media }: RowProps) => {
|
||||
</TableTr>
|
||||
);
|
||||
};
|
||||
|
||||
const createPaginationSearchParams = (searchParams: z.infer<typeof searchParamsSchema>, page: number) => {
|
||||
const params = new URLSearchParams({ page: page.toString() });
|
||||
|
||||
if (searchParams.search) params.set("search", searchParams.search);
|
||||
if (searchParams.includeFromAllUsers) params.set("includeFromAllUsers", "true");
|
||||
if (searchParams.pageSize !== 10) params.set("pageSize", searchParams.pageSize.toString());
|
||||
|
||||
return params;
|
||||
};
|
||||
@@ -18,8 +18,18 @@ import { SearchEngineDeleteButton } from "./_search-engine-delete-button";
|
||||
|
||||
const searchParamsSchema = z.object({
|
||||
search: z.string().optional(),
|
||||
pageSize: z.string().regex(/\d+/).transform(Number).catch(10),
|
||||
page: z.string().regex(/\d+/).transform(Number).catch(1),
|
||||
pageSize: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive().max(100))
|
||||
.catch(10),
|
||||
page: z
|
||||
.string()
|
||||
.regex(/^[1-9]\d*$/u)
|
||||
.transform(Number)
|
||||
.pipe(z.number().int().positive())
|
||||
.catch(1),
|
||||
});
|
||||
|
||||
interface SearchEnginesPageProps {
|
||||
@@ -32,6 +42,13 @@ export default async function SearchEnginesPage(props: SearchEnginesPageProps) {
|
||||
|
||||
const searchParams = searchParamsSchema.parse(await props.searchParams);
|
||||
const { items: searchEngines, totalCount } = await api.searchEngine.getPaginated(searchParams);
|
||||
const totalPages = Math.ceil(totalCount / searchParams.pageSize);
|
||||
|
||||
if (totalPages > 0 && searchParams.page > totalPages) {
|
||||
const params = createPaginationSearchParams(searchParams.search, searchParams.pageSize, totalPages);
|
||||
redirect(`/manage/search-engines?${params.toString()}`);
|
||||
}
|
||||
|
||||
const t = await getI18n("search.engine");
|
||||
const tCommon = await getI18n("common");
|
||||
const canCreate = session.user.permissions.includes("search-engine-create");
|
||||
@@ -80,11 +97,7 @@ export default async function SearchEnginesPage(props: SearchEnginesPageProps) {
|
||||
flexExpand
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
totalCount > searchParams.pageSize ? (
|
||||
<TablePagination total={Math.ceil(totalCount / searchParams.pageSize)} />
|
||||
) : undefined
|
||||
}
|
||||
footer={totalPages > 1 ? <TablePagination total={totalPages} /> : undefined}
|
||||
floatingPrimaryAction={canCreate}
|
||||
>
|
||||
{searchEngines.map((searchEngine) => (
|
||||
@@ -172,3 +185,12 @@ const SearchEngineItem = async ({ searchEngine, canModify, canDelete }: SearchEn
|
||||
/>
|
||||
);
|
||||
};
|
||||
|
||||
const createPaginationSearchParams = (search: string | undefined, pageSize: number, page: number) => {
|
||||
const params = new URLSearchParams({ page: page.toString() });
|
||||
|
||||
if (search) params.set("search", search);
|
||||
if (pageSize !== 10) params.set("pageSize", pageSize.toString());
|
||||
|
||||
return params;
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useRef, useState } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import { Button, Stack } from "@mantine/core";
|
||||
import { z } from "zod/v4";
|
||||
@@ -8,7 +8,6 @@ import { z } from "zod/v4";
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { env } from "@homarr/common/env";
|
||||
import { colorSchemes } from "@homarr/definitions";
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
@@ -17,6 +16,7 @@ import { brandingServerSettingsSchema } from "@homarr/server-settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { UnsavedChangesBar } from "~/components/manage/unsaved-changes-bar";
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
import { AnalyticsSettings } from "./analytics.settings";
|
||||
import { AppearanceSettingsForm } from "./appearance-settings-form";
|
||||
import { BoardSettingsForm } from "./board-settings-form";
|
||||
@@ -80,8 +80,7 @@ export const SettingsForm = ({ initialData, selectableBoards, selectableSearchEn
|
||||
initialValues,
|
||||
});
|
||||
|
||||
const isDirtyRef = useRef(false);
|
||||
isDirtyRef.current = form.isDirty();
|
||||
useUnsavedChangesGuard(form.isDirty());
|
||||
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
|
||||
@@ -91,15 +90,6 @@ export const SettingsForm = ({ initialData, selectableBoards, selectableSearchEn
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (event: BeforeUnloadEvent) => {
|
||||
if (env.NODE_ENV === "development") return;
|
||||
if (isDirtyRef.current) event.preventDefault();
|
||||
};
|
||||
window.addEventListener("beforeunload", handler);
|
||||
return () => window.removeEventListener("beforeunload", handler);
|
||||
}, []);
|
||||
|
||||
const handleSubmitAsync = async (values: FormValues) => {
|
||||
const defaults = initialValuesRef.current;
|
||||
const changed = <TKey extends keyof FormValues>(...fields: TKey[]) =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
Accordion,
|
||||
AccordionControl,
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
ListItem,
|
||||
Stack,
|
||||
Text,
|
||||
TextInput,
|
||||
ThemeIcon,
|
||||
Title,
|
||||
} from "@mantine/core";
|
||||
@@ -29,6 +30,7 @@ import {
|
||||
IconLock,
|
||||
IconPlus,
|
||||
IconPlugConnected,
|
||||
IconSearch,
|
||||
IconSparkles,
|
||||
IconTerminal,
|
||||
IconTools,
|
||||
@@ -59,6 +61,8 @@ export function McpInstructions({ baseUrl, hasApiKeys, toolGroups, onApiKeyCreat
|
||||
const t = useI18n("management.page.tool.api.tab.mcp");
|
||||
const tCommon = useI18n("common");
|
||||
const [newApiKey, setNewApiKey] = useState<string | null>(null);
|
||||
const [toolSearch, setToolSearch] = useState("");
|
||||
const [openToolGroups, setOpenToolGroups] = useState<string[]>([]);
|
||||
const { mutate: createApiKey, isPending } = clientApi.apiKeys.create.useMutation({
|
||||
onSuccess(data) {
|
||||
setNewApiKey(data.apiKey);
|
||||
@@ -70,6 +74,25 @@ export function McpInstructions({ baseUrl, hasApiKeys, toolGroups, onApiKeyCreat
|
||||
await revalidatePathActionAsync("/manage/tools/api");
|
||||
}, []);
|
||||
const mcpUrl = `${baseUrl}/api/mcp`;
|
||||
const normalizedToolSearch = toolSearch.trim().toLowerCase();
|
||||
const filteredToolGroups = useMemo(() => {
|
||||
if (!normalizedToolSearch) return toolGroups;
|
||||
|
||||
return toolGroups.flatMap((group) => {
|
||||
const namespaceMatches = group.namespace.toLowerCase().includes(normalizedToolSearch);
|
||||
const tools = namespaceMatches
|
||||
? group.tools
|
||||
: group.tools.filter((tool) => `${tool.name} ${tool.description}`.toLowerCase().includes(normalizedToolSearch));
|
||||
|
||||
if (tools.length === 0) return [];
|
||||
return [{ ...group, tools }];
|
||||
});
|
||||
}, [normalizedToolSearch, toolGroups]);
|
||||
const filteredToolCount = filteredToolGroups.reduce((sum, group) => sum + group.tools.length, 0);
|
||||
const filteredToolGroupNames = filteredToolGroups.map((group) => group.namespace);
|
||||
const accordionStateProps = normalizedToolSearch
|
||||
? { defaultValue: filteredToolGroupNames }
|
||||
: { value: openToolGroups, onChange: setOpenToolGroups };
|
||||
|
||||
const streamableHttpConfig = JSON.stringify(
|
||||
{
|
||||
@@ -291,45 +314,64 @@ export function McpInstructions({ baseUrl, hasApiKeys, toolGroups, onApiKeyCreat
|
||||
</Group>
|
||||
</Title>
|
||||
<Text size="sm" c="dimmed" mb="sm">
|
||||
{t("availableTools.description", {
|
||||
count: String(toolGroups.reduce((sum, g) => sum + g.tools.length, 0)),
|
||||
})}
|
||||
{normalizedToolSearch
|
||||
? t("availableTools.filteredDescription", { count: String(filteredToolCount) })
|
||||
: t("availableTools.description", { count: String(filteredToolCount) })}
|
||||
</Text>
|
||||
<Accordion variant="separated" multiple>
|
||||
{toolGroups.map((group) => (
|
||||
<AccordionItem key={group.namespace} value={group.namespace}>
|
||||
<AccordionControl>
|
||||
<Group gap="xs">
|
||||
<Text size="sm" fw={600}>
|
||||
{group.namespace}
|
||||
</Text>
|
||||
<Badge size="xs" variant="light" circle>
|
||||
{group.tools.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
</AccordionControl>
|
||||
<AccordionPanel>
|
||||
<Stack gap={6}>
|
||||
{group.tools.map((tool) => (
|
||||
<div key={tool.name} className={classes.toolRow}>
|
||||
<Badge size="sm" w={50} radius="xs" color={toolTypeDisplay[tool.type].color} variant="light">
|
||||
{toolTypeDisplay[tool.type].method}
|
||||
</Badge>
|
||||
<div>
|
||||
<Code fz="xs" fw={600}>
|
||||
{tool.name}
|
||||
</Code>
|
||||
<Text size="xs" c="dimmed" lh={1.4}>
|
||||
{tool.description}
|
||||
</Text>
|
||||
<TextInput
|
||||
value={toolSearch}
|
||||
onChange={(event) => setToolSearch(event.currentTarget.value)}
|
||||
leftSection={<IconSearch size={16} />}
|
||||
placeholder={t("availableTools.search")}
|
||||
aria-label={t("availableTools.search")}
|
||||
mb="sm"
|
||||
/>
|
||||
{filteredToolGroups.length === 0 ? (
|
||||
<Alert variant="light" color="gray" title={t("availableTools.noResults.title")}>
|
||||
<Stack gap="sm" align="flex-start">
|
||||
<Text size="sm">{t("availableTools.noResults.description", { search: toolSearch.trim() })}</Text>
|
||||
<Button size="compact-sm" variant="default" onClick={() => setToolSearch("")}>
|
||||
{tCommon("action.clearSearch")}
|
||||
</Button>
|
||||
</Stack>
|
||||
</Alert>
|
||||
) : (
|
||||
<Accordion key={normalizedToolSearch} variant="separated" multiple {...accordionStateProps}>
|
||||
{filteredToolGroups.map((group) => (
|
||||
<AccordionItem key={group.namespace} value={group.namespace}>
|
||||
<AccordionControl>
|
||||
<Group gap="xs">
|
||||
<Text size="sm" fw={600}>
|
||||
{group.namespace}
|
||||
</Text>
|
||||
<Badge size="xs" variant="light" circle>
|
||||
{group.tools.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
</AccordionControl>
|
||||
<AccordionPanel>
|
||||
<Stack gap={6}>
|
||||
{group.tools.map((tool) => (
|
||||
<div key={tool.name} className={classes.toolRow}>
|
||||
<Badge size="sm" w={50} radius="xs" color={toolTypeDisplay[tool.type].color} variant="light">
|
||||
{toolTypeDisplay[tool.type].method}
|
||||
</Badge>
|
||||
<div>
|
||||
<Code fz="xs" fw={600}>
|
||||
{tool.name}
|
||||
</Code>
|
||||
<Text size="xs" c="dimmed" lh={1.4}>
|
||||
{tool.description}
|
||||
</Text>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</Stack>
|
||||
</AccordionPanel>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
))}
|
||||
</Stack>
|
||||
</AccordionPanel>
|
||||
</AccordionItem>
|
||||
))}
|
||||
</Accordion>
|
||||
)}
|
||||
</div>
|
||||
</Stack>
|
||||
);
|
||||
|
||||
@@ -19,13 +19,14 @@ import { MantineReactTable } from "mantine-react-table";
|
||||
|
||||
import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatBytes, useTimeAgo } from "@homarr/common";
|
||||
import { useTimeAgo } from "@homarr/common";
|
||||
import { invariantTechnicalLabels } from "@homarr/definitions";
|
||||
import type { ContainerState, DockerEndpointCapability } from "@homarr/docker";
|
||||
import { containerStateColorMap, cpuUsageColor, memoryUsageColor, safeValue } from "@homarr/docker/shared";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { AddDockerAppToHomarr, useDockerContainerRemovalConfirmation } from "@homarr/modals-collection";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import type { ScopedTranslationFunction } from "@homarr/translation";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import type { TablerIcon } from "@homarr/ui";
|
||||
@@ -72,6 +73,7 @@ const showContainerActionResult = (
|
||||
const createColumns = (
|
||||
tDocker: ScopedTranslationFunction<"docker">,
|
||||
tCommon: ScopedTranslationFunction<"common">,
|
||||
formatBytes: (bytes: number) => string,
|
||||
): MRT_ColumnDef<DockerContainer>[] => [
|
||||
{
|
||||
accessorKey: "name",
|
||||
@@ -194,6 +196,7 @@ export function DockerTable({ initialData }: DockerTableProps) {
|
||||
const tDocker = useI18n("docker");
|
||||
const tCommon = useI18n("common");
|
||||
const utils = clientApi.useUtils();
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const { data, isFetching } = clientApi.docker.getContainers.useQuery(undefined, {
|
||||
initialData,
|
||||
refetchOnMount: false,
|
||||
@@ -282,7 +285,7 @@ export function DockerTable({ initialData }: DockerTableProps) {
|
||||
);
|
||||
},
|
||||
|
||||
columns: createColumns(tDocker, tCommon),
|
||||
columns: createColumns(tDocker, tCommon, formatBytes),
|
||||
});
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { ActionIcon, Badge, Button, Group, Select, Text } from "@mantine/core";
|
||||
import { ActionIcon, Badge, Button, Group, Select, Text, Tooltip } from "@mantine/core";
|
||||
import { useMap } from "@mantine/hooks";
|
||||
import { IconPlayerPlay, IconPower, IconRefresh } from "@tabler/icons-react";
|
||||
import type { MRT_ColumnDef } from "mantine-react-table";
|
||||
@@ -84,6 +84,34 @@ type JobData = RouterOutputs["cronJobs"]["getJobs"][number] & {
|
||||
lastExecutionTime?: string;
|
||||
};
|
||||
|
||||
type TaskControl = "interval" | "toggle" | "trigger";
|
||||
|
||||
const restoreTaskControlFocus = (jobName: string, action: TaskControl, originalControl: HTMLElement | null) => {
|
||||
const focusWhenEnabled = (attemptsRemaining: number) => {
|
||||
if (document.activeElement && document.activeElement !== document.body) return;
|
||||
|
||||
let control: HTMLElement | null = null;
|
||||
if (originalControl?.isConnected && originalControl !== document.body) control = originalControl;
|
||||
if (!control) {
|
||||
const controls = document.querySelectorAll<HTMLElement>(`[data-task-action="${action}"]`);
|
||||
for (const candidate of controls) {
|
||||
if (candidate.dataset.taskName !== jobName) continue;
|
||||
control = candidate;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (control && !control.matches(":disabled")) {
|
||||
control.focus();
|
||||
return;
|
||||
}
|
||||
if (attemptsRemaining <= 0) return;
|
||||
window.setTimeout(() => focusWhenEnabled(attemptsRemaining - 1), 100);
|
||||
};
|
||||
|
||||
window.setTimeout(() => focusWhenEnabled(50), 0);
|
||||
};
|
||||
|
||||
const createColumns = (
|
||||
tCommon: ScopedTranslationFunction<"common">,
|
||||
tTasks: ScopedTranslationFunction<"management.page.tool.tasks">,
|
||||
@@ -119,7 +147,7 @@ const createColumns = (
|
||||
Cell({ row }) {
|
||||
if (row.original.preventCustomInterval) return null;
|
||||
|
||||
const handleIntervalChange = (newCron: string | null) => {
|
||||
const handleIntervalChange = async (newCron: string | null, originalControl: HTMLElement | null) => {
|
||||
if (!newCron || newCron === row.original.cron) return;
|
||||
|
||||
const currentStates = loadingStates.get(row.original.name) ?? {
|
||||
@@ -133,10 +161,12 @@ const createColumns = (
|
||||
});
|
||||
|
||||
try {
|
||||
updateIntervalMutation.mutate({
|
||||
await updateIntervalMutation.mutateAsync({
|
||||
name: row.original.name,
|
||||
cron: newCron,
|
||||
});
|
||||
} catch {
|
||||
// The mutation callback displays the error notification.
|
||||
} finally {
|
||||
const updatedStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -147,17 +177,24 @@ const createColumns = (
|
||||
...updatedStates,
|
||||
interval: false,
|
||||
});
|
||||
restoreTaskControlFocus(row.original.name, "interval", originalControl);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Select
|
||||
value={row.original.cron}
|
||||
onChange={handleIntervalChange}
|
||||
onChange={(newCron) => {
|
||||
let originalControl: HTMLElement | null = null;
|
||||
if (document.activeElement instanceof HTMLElement) originalControl = document.activeElement;
|
||||
void handleIntervalChange(newCron, originalControl);
|
||||
}}
|
||||
data={cronExpressions.map(({ value, label }) => ({
|
||||
value,
|
||||
label: label(tTasks),
|
||||
}))}
|
||||
data-task-action="interval"
|
||||
data-task-name={row.original.name}
|
||||
size="sm"
|
||||
disabled={loadingStates.get(row.original.name)?.interval ?? false}
|
||||
style={{ minWidth: 180 }}
|
||||
@@ -188,8 +225,14 @@ const createColumns = (
|
||||
enableSorting: false,
|
||||
Cell({ row }) {
|
||||
const status = jobStatusMap.get(row.original.name);
|
||||
const jobLabel = tTasks(`job.${row.original.name}.label`);
|
||||
const triggerPending = loadingStates.get(row.original.name)?.trigger ?? false;
|
||||
const togglePending = loadingStates.get(row.original.name)?.toggle ?? false;
|
||||
const triggerLabel = tTasks("action.run", { name: jobLabel });
|
||||
let toggleLabel = tTasks("action.enable", { name: jobLabel });
|
||||
if (row.original.isEnabled) toggleLabel = tTasks("action.disable", { name: jobLabel });
|
||||
|
||||
const handleToggleEnabled = () => {
|
||||
const handleToggleEnabled = async (originalControl: HTMLButtonElement) => {
|
||||
const currentStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
trigger: false,
|
||||
@@ -201,10 +244,12 @@ const createColumns = (
|
||||
});
|
||||
try {
|
||||
if (row.original.isEnabled) {
|
||||
disableMutation.mutate(row.original.name);
|
||||
await disableMutation.mutateAsync(row.original.name);
|
||||
} else {
|
||||
enableMutation.mutate(row.original.name);
|
||||
await enableMutation.mutateAsync(row.original.name);
|
||||
}
|
||||
} catch {
|
||||
// The mutation callback displays the error notification.
|
||||
} finally {
|
||||
const updatedStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -215,11 +260,12 @@ const createColumns = (
|
||||
...updatedStates,
|
||||
toggle: false,
|
||||
});
|
||||
restoreTaskControlFocus(row.original.name, "toggle", originalControl);
|
||||
}
|
||||
};
|
||||
|
||||
const handleTrigger = () => {
|
||||
if (status?.status === "running") return;
|
||||
const handleTrigger = async (originalControl: HTMLButtonElement) => {
|
||||
if (status?.status === "running" || triggerPending) return;
|
||||
|
||||
const currentStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -231,7 +277,9 @@ const createColumns = (
|
||||
trigger: true,
|
||||
});
|
||||
try {
|
||||
triggerMutation.mutate(row.original.name);
|
||||
await triggerMutation.mutateAsync(row.original.name);
|
||||
} catch {
|
||||
// The mutation callback displays the error notification.
|
||||
} finally {
|
||||
const updatedStates = loadingStates.get(row.original.name) ?? {
|
||||
toggle: false,
|
||||
@@ -242,32 +290,44 @@ const createColumns = (
|
||||
...updatedStates,
|
||||
trigger: false,
|
||||
});
|
||||
restoreTaskControlFocus(row.original.name, "trigger", originalControl);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Group gap="xs">
|
||||
{!row.original.preventManualExecution && (
|
||||
<Tooltip label={triggerLabel} openDelay={500}>
|
||||
<ActionIcon
|
||||
aria-label={triggerLabel}
|
||||
onClick={(event) => void handleTrigger(event.currentTarget)}
|
||||
data-task-action="trigger"
|
||||
data-task-name={row.original.name}
|
||||
disabled={status?.status === "running" || triggerPending}
|
||||
loading={triggerPending}
|
||||
variant="light"
|
||||
color="green"
|
||||
size="md"
|
||||
>
|
||||
<IconPlayerPlay size={16} />
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Tooltip label={toggleLabel} openDelay={500}>
|
||||
<ActionIcon
|
||||
onClick={handleTrigger}
|
||||
disabled={status?.status === "running"}
|
||||
loading={loadingStates.get(row.original.name)?.trigger ?? false}
|
||||
aria-label={toggleLabel}
|
||||
onClick={(event) => void handleToggleEnabled(event.currentTarget)}
|
||||
data-task-action="toggle"
|
||||
data-task-name={row.original.name}
|
||||
disabled={togglePending}
|
||||
loading={togglePending}
|
||||
variant="light"
|
||||
color="green"
|
||||
color={row.original.isEnabled ? "green" : "gray"}
|
||||
size="md"
|
||||
>
|
||||
<IconPlayerPlay size={16} />
|
||||
{row.original.isEnabled ? <IconPower size={16} /> : <IconPowerOff size={16} />}
|
||||
</ActionIcon>
|
||||
)}
|
||||
<ActionIcon
|
||||
onClick={handleToggleEnabled}
|
||||
loading={loadingStates.get(row.original.name)?.toggle ?? false}
|
||||
variant="light"
|
||||
color={row.original.isEnabled ? "green" : "gray"}
|
||||
size="md"
|
||||
>
|
||||
{row.original.isEnabled ? <IconPower size={16} /> : <IconPowerOff size={16} />}
|
||||
</ActionIcon>
|
||||
</Tooltip>
|
||||
</Group>
|
||||
);
|
||||
},
|
||||
|
||||
+37
-13
@@ -1,7 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useEffect, useMemo, useRef } from "react";
|
||||
import { useMemo, useRef } from "react";
|
||||
import { useRouter } from "next/navigation";
|
||||
import {
|
||||
Box,
|
||||
Button,
|
||||
@@ -26,13 +27,13 @@ import type { RouterOutputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import type { BoardPreviewData } from "@homarr/boards/layout-preview";
|
||||
import { revalidatePathActionAsync } from "@homarr/common/client";
|
||||
import { env } from "@homarr/common/env";
|
||||
import { useZodForm } from "@homarr/form";
|
||||
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import {
|
||||
headerPreferencesSchema,
|
||||
parseHeaderPreferences,
|
||||
userByteUnitSystemSchema,
|
||||
userChangeHomeBoardsSchema,
|
||||
userChangeSearchPreferencesSchema,
|
||||
userEditProfileSchema,
|
||||
@@ -43,6 +44,7 @@ import {
|
||||
|
||||
import { BoardSelect } from "~/components/board/board-select";
|
||||
import { CurrentLanguageCombobox } from "~/components/language/current-language-combobox";
|
||||
import { useUnsavedChangesGuard } from "~/components/manage/use-unsaved-changes-guard";
|
||||
import { HeaderComposer } from "./header-composer";
|
||||
|
||||
dayjs.extend(localeData);
|
||||
@@ -55,6 +57,7 @@ const userGeneralSettingsSchema = z.object({
|
||||
defaultSearchEngineId: userChangeSearchPreferencesSchema.shape.defaultSearchEngineId,
|
||||
openInNewTab: userChangeSearchPreferencesSchema.shape.openInNewTab,
|
||||
ddgBangsEnabled: userChangeSearchPreferencesSchema.shape.ddgBangsEnabled,
|
||||
byteUnitSystem: userByteUnitSystemSchema.shape.byteUnitSystem,
|
||||
firstDayOfWeek: userFirstDayOfWeekSchema.shape.firstDayOfWeek,
|
||||
pingIconsEnabled: userPingIconsEnabledSchema.shape.pingIconsEnabled,
|
||||
enableRightClickOnWidgets: userEnableRightClickOnWidgetsSchema.shape.enableRightClickOnWidgets,
|
||||
@@ -85,6 +88,7 @@ const buildInitialValues = (user: RouterOutputs["user"]["getById"]): FormValues
|
||||
defaultSearchEngineId: user.defaultSearchEngineId,
|
||||
openInNewTab: user.openSearchInNewTab,
|
||||
ddgBangsEnabled: user.ddgBangs,
|
||||
byteUnitSystem: user.byteUnitSystem,
|
||||
firstDayOfWeek: user.firstDayOfWeek as DayOfWeek,
|
||||
pingIconsEnabled: user.pingIconsEnabled,
|
||||
enableRightClickOnWidgets: user.enableRightClickOnWidgets,
|
||||
@@ -102,11 +106,13 @@ export const UserGeneralSettingsForm = ({
|
||||
const tCommon = useI18n("common");
|
||||
const tUserManagement = useI18n("management.page.user");
|
||||
const tGeneral = useI18n("management.page.user.setting.general");
|
||||
const router = useRouter();
|
||||
const isCredentialsUser = user.provider === "credentials";
|
||||
|
||||
const editProfileMutation = clientApi.user.editProfile.useMutation();
|
||||
const changeHomeBoardsMutation = clientApi.user.changeHomeBoards.useMutation();
|
||||
const changeSearchPreferencesMutation = clientApi.user.changeSearchPreferences.useMutation();
|
||||
const changeByteUnitSystemMutation = clientApi.user.changeByteUnitSystem.useMutation();
|
||||
const changeFirstDayOfWeekMutation = clientApi.user.changeFirstDayOfWeek.useMutation();
|
||||
const changePingIconsEnabledMutation = clientApi.user.changePingIconsEnabled.useMutation();
|
||||
const changeEnableRightClickOnWidgetsMutation = clientApi.user.changeEnableRightClickOnWidgets.useMutation();
|
||||
@@ -119,8 +125,7 @@ export const UserGeneralSettingsForm = ({
|
||||
initialValues,
|
||||
});
|
||||
|
||||
const isDirtyRef = useRef(false);
|
||||
isDirtyRef.current = form.isDirty();
|
||||
useUnsavedChangesGuard(form.isDirty());
|
||||
|
||||
const weekDays = useMemo(() => dayjs.weekdays(false), []);
|
||||
|
||||
@@ -128,6 +133,7 @@ export const UserGeneralSettingsForm = ({
|
||||
editProfileMutation,
|
||||
changeHomeBoardsMutation,
|
||||
changeSearchPreferencesMutation,
|
||||
changeByteUnitSystemMutation,
|
||||
changeFirstDayOfWeekMutation,
|
||||
changePingIconsEnabledMutation,
|
||||
changeEnableRightClickOnWidgetsMutation,
|
||||
@@ -135,15 +141,6 @@ export const UserGeneralSettingsForm = ({
|
||||
];
|
||||
const isPending = mutations.some((m) => m.isPending);
|
||||
|
||||
useEffect(() => {
|
||||
const handler = (e: BeforeUnloadEvent) => {
|
||||
if (env.NODE_ENV === "development") return;
|
||||
if (isDirtyRef.current) e.preventDefault();
|
||||
};
|
||||
window.addEventListener("beforeunload", handler);
|
||||
return () => window.removeEventListener("beforeunload", handler);
|
||||
}, []);
|
||||
|
||||
const handleSubmitAsync = async (values: FormValues) => {
|
||||
const parsed = userGeneralSettingsSchema.safeParse(values);
|
||||
if (!parsed.success) return;
|
||||
@@ -177,6 +174,14 @@ export const UserGeneralSettingsForm = ({
|
||||
ddgBangsEnabled: parsed.data.ddgBangsEnabled,
|
||||
}),
|
||||
},
|
||||
{
|
||||
when: changed("byteUnitSystem"),
|
||||
action: () =>
|
||||
changeByteUnitSystemMutation.mutateAsync({
|
||||
id: user.id,
|
||||
byteUnitSystem: parsed.data.byteUnitSystem,
|
||||
}),
|
||||
},
|
||||
{
|
||||
when: changed("firstDayOfWeek"),
|
||||
action: () =>
|
||||
@@ -215,6 +220,7 @@ export const UserGeneralSettingsForm = ({
|
||||
form.setInitialValues(newValues);
|
||||
form.resetDirty();
|
||||
await revalidatePathActionAsync(`/manage/users/${user.id}`);
|
||||
router.refresh();
|
||||
showSuccessNotification({
|
||||
title: tCommon("notification.update.success"),
|
||||
message: tCommon("notification.update.success"),
|
||||
@@ -344,6 +350,24 @@ export const UserGeneralSettingsForm = ({
|
||||
</Group>
|
||||
</Radio.Group>
|
||||
<Divider my="xs" />
|
||||
<Select
|
||||
label={tUser("field.byteUnitSystem.label")}
|
||||
description={tUser("field.byteUnitSystem.description")}
|
||||
data={[
|
||||
{
|
||||
value: "decimal",
|
||||
label: `${tUser("field.byteUnitSystem.options.decimal")} (KB, MB, GB)`,
|
||||
},
|
||||
{
|
||||
value: "binary",
|
||||
label: `${tUser("field.byteUnitSystem.options.binary")} (KiB, MiB, GiB)`,
|
||||
},
|
||||
]}
|
||||
allowDeselect={false}
|
||||
comboboxProps={{ withinPortal: true }}
|
||||
{...form.getInputProps("byteUnitSystem")}
|
||||
/>
|
||||
<Divider my="xs" />
|
||||
<Title order={4}>{tGeneral("item.accessibility")}</Title>
|
||||
<Switch
|
||||
label={tUser("field.pingIconsEnabled.label")}
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ export const UserProfileAvatarForm = ({ user }: UserProfileAvatarForm) => {
|
||||
if (error.shape?.data.code === "BAD_REQUEST") {
|
||||
showErrorNotification({
|
||||
title: tManageAvatar("changeImage.notification.toLarge.title"),
|
||||
message: tManageAvatar("changeImage.notification.toLarge.message", { size: "256KB" }),
|
||||
message: tManageAvatar("changeImage.notification.toLarge.message", { size: "256 KiB" }),
|
||||
});
|
||||
} else {
|
||||
showErrorNotification({
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export type AssistantMentionReference = {
|
||||
type: "app" | "integration" | "board" | "widget";
|
||||
id: string;
|
||||
@@ -20,9 +22,8 @@ const mentionPattern = /:(app|integration|board|widget)\[([^\]\n]{1,1024})\](?:\
|
||||
const getMessageText = (message: { parts: unknown[] }) =>
|
||||
message.parts
|
||||
.flatMap((part) => {
|
||||
if (!part || typeof part !== "object" || Array.isArray(part)) return [];
|
||||
const value = part as Record<string, unknown>;
|
||||
return value.type === "text" && typeof value.text === "string" ? [value.text] : [];
|
||||
if (!isRecord(part)) return [];
|
||||
return part.type === "text" && typeof part.text === "string" ? [part.text] : [];
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
|
||||
@@ -1,13 +1,11 @@
|
||||
import { convertToModelMessages, pruneMessages } from "ai";
|
||||
import type { ModelMessage, UIMessage } from "ai";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { isCustomWidgetToolName } from "@homarr/custom-widgets/core";
|
||||
|
||||
import { getAssistantToolOutputMaxCharacters, toAssistantToolOutput } from "./assistant-tool-output";
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
const reloadableCustomWidgetResourceToolNames = [
|
||||
"customWidget_getSkill",
|
||||
"customWidget_schema",
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const openRouterWebSearchTool = {
|
||||
type: "openrouter:web_search",
|
||||
parameters: {
|
||||
@@ -16,8 +18,7 @@ export interface OpenRouterWebSearchSource {
|
||||
|
||||
const maximumWebSearchSources = 12;
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | undefined =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
const asRecord = (value: unknown): Record<string, unknown> | undefined => (isRecord(value) ? value : undefined);
|
||||
|
||||
const getSafeWebSourceUrl = (value: unknown) => {
|
||||
if (typeof value !== "string" || !URL.canParse(value)) return undefined;
|
||||
@@ -100,7 +101,7 @@ export const withOpenRouterToolRequestOptions = (
|
||||
});
|
||||
|
||||
export const getOpenRouterWebSearchRequests = (value: unknown) => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) return undefined;
|
||||
if (!isRecord(value)) return undefined;
|
||||
const usage = "usage" in value && typeof value.usage === "object" && value.usage !== null ? value.usage : undefined;
|
||||
const serverToolUse =
|
||||
usage && "server_tool_use" in usage && typeof usage.server_tool_use === "object" && usage.server_tool_use !== null
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null => (isRecord(value) ? value : null);
|
||||
|
||||
const getStatusCode = (error: unknown): number | undefined => {
|
||||
const record = asRecord(error);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const asErrorRecord = (value: unknown): Record<string, unknown> | undefined =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const asErrorRecord = (value: unknown): Record<string, unknown> | undefined => (isRecord(value) ? value : undefined);
|
||||
|
||||
const getErrorChain = (error: unknown) => {
|
||||
const chain: Record<string, unknown>[] = [];
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { normalizeCustomWidgetLifecycleToolInput } from "@homarr/custom-widgets/core";
|
||||
|
||||
interface AssistantToolCallInput {
|
||||
@@ -97,7 +98,7 @@ const repairMultilineToolInput = <T extends AssistantToolCallInput>(toolCall: T)
|
||||
if (customWidgetNoInputToolNames.has(toolCall.toolName)) {
|
||||
try {
|
||||
const input = JSON.parse(toolCall.input) as unknown;
|
||||
if (typeof input === "object" && input !== null && !Array.isArray(input) && Object.keys(input).length === 0) {
|
||||
if (isRecord(input) && Object.keys(input).length === 0) {
|
||||
return null;
|
||||
}
|
||||
} catch {
|
||||
@@ -124,8 +125,8 @@ const repairCustomWidgetLifecycleInput = <T extends AssistantToolCallInput>(tool
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (typeof input !== "object" || input === null || Array.isArray(input)) return null;
|
||||
const normalized = normalizeCustomWidgetLifecycleToolInput(toolCall.toolName, input as Record<string, unknown>);
|
||||
if (!isRecord(input)) return null;
|
||||
const normalized = normalizeCustomWidgetLifecycleToolInput(toolCall.toolName, input);
|
||||
if (normalized === input) return null;
|
||||
return { ...toolCall, input: JSON.stringify(normalized) };
|
||||
};
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { serialize } from "superjson";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export const customWidgetPreviewQueryOutputMaxCharacters = 8_000;
|
||||
export const assistantToolOutputMaxCharacters = 24_000;
|
||||
const customWidgetAuthoringResourceOutputMaxCharacters = 60_000;
|
||||
@@ -38,10 +40,7 @@ export const toAssistantToolOutput = (value: unknown, options: AssistantToolOutp
|
||||
const serialized = JSON.stringify(output);
|
||||
if (serialized === undefined || serialized.length <= options.maxCharacters) return output;
|
||||
|
||||
const outputRecord =
|
||||
typeof output === "object" && output !== null && !Array.isArray(output)
|
||||
? (output as Record<string, unknown>)
|
||||
: undefined;
|
||||
const outputRecord = isRecord(output) ? output : undefined;
|
||||
const metadata = outputRecord
|
||||
? Object.fromEntries(
|
||||
["ok", "status", "statusText", "error"].flatMap((key) =>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const compactTemplateToolNames = new Set(["customWidget_validateTemplate", "customWidget_previewReviseTemplate"]);
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null => (isRecord(value) ? value : null);
|
||||
|
||||
export const getAssistantToolInputSchema = (toolName: string, inputSchema: Record<string, unknown>) => {
|
||||
if (!compactTemplateToolNames.has(toolName)) return inputSchema;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { UIMessage } from "ai";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { getCustomWidgetPhaseToolNames } from "@homarr/custom-widgets/core";
|
||||
|
||||
export { getCustomWidgetPhaseToolNames };
|
||||
@@ -17,9 +18,6 @@ const customWidgetContextToolBudgets: Readonly<Record<string, number>> = {
|
||||
customWidget_getExample: 1,
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
|
||||
export const createCustomWidgetDiscoveryPhaseController = (limit = maxFocusedComponentSearchesPerPhase) => {
|
||||
const calls = new Map<string, number>();
|
||||
const reset = () => {
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
getSelectedModelDetailsAsync,
|
||||
} from "@homarr/api/assistant";
|
||||
import { auth } from "@homarr/auth/next";
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { env } from "@homarr/common/env";
|
||||
import { decryptSecret } from "@homarr/common/server";
|
||||
import { createLogger } from "@homarr/core/infrastructure/logs";
|
||||
@@ -168,8 +169,7 @@ const webSearchInstructions = `
|
||||
|
||||
OpenRouter web search is available. Use it only when current external information or unsupplied API documentation is needed. Prefer primary documentation, keep the search focused, and cite the sources that support the answer or generated artifact.`;
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null => (isRecord(value) ? value : null);
|
||||
|
||||
const asFiniteNumber = (value: unknown) => {
|
||||
const number = typeof value === "number" ? value : typeof value === "string" ? Number(value) : Number.NaN;
|
||||
@@ -527,13 +527,8 @@ export async function POST(request: Request) {
|
||||
};
|
||||
}
|
||||
let executionInput = input;
|
||||
if (
|
||||
mcpTool.name.startsWith("customWidget_") &&
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
!Array.isArray(input)
|
||||
) {
|
||||
executionInput = normalizeCustomWidgetLifecycleToolInput(mcpTool.name, input as Record<string, unknown>);
|
||||
if (mcpTool.name.startsWith("customWidget_") && isRecord(input)) {
|
||||
executionInput = normalizeCustomWidgetLifecycleToolInput(mcpTool.name, input);
|
||||
}
|
||||
const contextRequestKey = getCustomWidgetContextRequestKey(mcpTool.name, executionInput);
|
||||
if (contextRequestKey !== null && loadedCustomWidgetContextRequests.has(contextRequestKey)) {
|
||||
|
||||
@@ -48,7 +48,7 @@ const readBoundedRequestBodyAsync = async (request: Request): Promise<Uint8Array
|
||||
throw new Error("Invalid Content-Length header");
|
||||
}
|
||||
if (parsedLength > MAX_MULTIPART_REQUEST_BYTES) {
|
||||
throw new BackupTooLargeError("Backup upload exceeds the 256 MB limit");
|
||||
throw new BackupTooLargeError("Backup upload exceeds the 256 MiB limit");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -66,7 +66,7 @@ const readBoundedRequestBodyAsync = async (request: Request): Promise<Uint8Array
|
||||
totalBytes += value.byteLength;
|
||||
if (totalBytes > MAX_MULTIPART_REQUEST_BYTES) {
|
||||
await reader.cancel();
|
||||
throw new BackupTooLargeError("Backup upload exceeds the 256 MB limit");
|
||||
throw new BackupTooLargeError("Backup upload exceeds the 256 MiB limit");
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
@@ -103,18 +103,18 @@ const assertArchiveSizeLimits = (zip: AdmZip) => {
|
||||
}
|
||||
totalSize += entrySize;
|
||||
if (totalSize > MAX_UNCOMPRESSED_ARCHIVE_BYTES) {
|
||||
throw new BackupTooLargeError("Uncompressed backup archive exceeds the 514 MB limit");
|
||||
throw new BackupTooLargeError("Uncompressed backup archive exceeds the 514 MiB limit");
|
||||
}
|
||||
}
|
||||
|
||||
const dbEntry = zip.getEntry("db.sqlite");
|
||||
if (dbEntry && dbEntry.header.size > MAX_UNCOMPRESSED_DATABASE_BYTES) {
|
||||
throw new BackupTooLargeError("Uncompressed SQLite database exceeds the 512 MB limit");
|
||||
throw new BackupTooLargeError("Uncompressed SQLite database exceeds the 512 MiB limit");
|
||||
}
|
||||
|
||||
const metadataEntry = zip.getEntry("metadata.json");
|
||||
if (metadataEntry && metadataEntry.header.size > MAX_METADATA_BYTES) {
|
||||
throw new BackupTooLargeError("Backup metadata exceeds the 1 MB limit");
|
||||
throw new BackupTooLargeError("Backup metadata exceeds the 1 MiB limit");
|
||||
}
|
||||
|
||||
const encryptionKeyEntry = zip.getEntry("encryption-key.txt");
|
||||
@@ -255,7 +255,7 @@ export async function POST(req: Request) {
|
||||
return NextResponse.json({ error: "No file provided" }, { status: 400 });
|
||||
}
|
||||
if (file.size > MAX_COMPRESSED_BACKUP_BYTES) {
|
||||
return NextResponse.json({ error: "Backup upload exceeds the 256 MB limit" }, { status: 413 });
|
||||
return NextResponse.json({ error: "Backup upload exceeds the 256 MiB limit" }, { status: 413 });
|
||||
}
|
||||
|
||||
let zip: AdmZip;
|
||||
|
||||
@@ -6,20 +6,17 @@ import { db } from "@homarr/db";
|
||||
import { handshakeAsync } from "@homarr/redis";
|
||||
|
||||
const logger = createLogger({ module: "healthLiveRoute" });
|
||||
const noStoreHeaders = { "Cache-Control": "no-store" };
|
||||
const healthStatusCodes = { healthy: 200, unhealthy: 500 } as const;
|
||||
|
||||
export async function GET() {
|
||||
const timeBeforeHealthCheck = performance.now();
|
||||
const response = await executeAndAggregateAllHealthChecksAsync();
|
||||
logger.info("Completed healthcheck", { elapsed: `${performance.now() - timeBeforeHealthCheck}ms` });
|
||||
logger.debug("Completed healthcheck", { elapsed: `${performance.now() - timeBeforeHealthCheck}ms` });
|
||||
|
||||
if (response.status === "healthy") {
|
||||
return new Response(JSON.stringify(response), {
|
||||
status: 200,
|
||||
});
|
||||
}
|
||||
|
||||
return new Response(JSON.stringify(response), {
|
||||
status: 500,
|
||||
return Response.json(response, {
|
||||
status: healthStatusCodes[response.status],
|
||||
headers: noStoreHeaders,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -63,8 +60,8 @@ const executeHealthCheckSafelyAsync = async (
|
||||
name: string,
|
||||
callback: () => Promise<object>,
|
||||
): Promise<HealthCheckResult> => {
|
||||
const currentTimeBeforeCallback = performance.now();
|
||||
try {
|
||||
const currentTimeBeforeCallback = performance.now();
|
||||
const values = await callback();
|
||||
return {
|
||||
name,
|
||||
@@ -79,7 +76,7 @@ const executeHealthCheckSafelyAsync = async (
|
||||
return {
|
||||
status: "unhealthy",
|
||||
values: {
|
||||
error,
|
||||
latency: performance.now() - currentTimeBeforeCallback,
|
||||
},
|
||||
name,
|
||||
};
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
"use client";
|
||||
|
||||
import type { PropsWithChildren } from "react";
|
||||
import { useCallback } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import type { AccordionProps } from "@mantine/core";
|
||||
import { Accordion } from "@mantine/core";
|
||||
import { useShallowEffect } from "@mantine/hooks";
|
||||
|
||||
type ActiveTabAccordionProps = PropsWithChildren<Omit<AccordionProps<false>, "onChange">>;
|
||||
|
||||
// Replace state without fetchign new data
|
||||
const replace = (newUrl: string) => {
|
||||
window.history.replaceState({ ...window.history.state, as: newUrl, url: newUrl }, "", newUrl);
|
||||
};
|
||||
|
||||
export const ActiveTabAccordion = ({ children, ...props }: ActiveTabAccordionProps) => {
|
||||
const pathname = usePathname();
|
||||
const onChange = useCallback((tab: string | null) => (tab ? replace(`?tab=${tab}`) : replace(pathname)), [pathname]);
|
||||
|
||||
useShallowEffect(() => {
|
||||
if (props.defaultValue) {
|
||||
replace(`?tab=${props.defaultValue}`);
|
||||
}
|
||||
}, [props.defaultValue]);
|
||||
|
||||
return (
|
||||
<Accordion {...props} onChange={onChange}>
|
||||
{children}
|
||||
</Accordion>
|
||||
);
|
||||
};
|
||||
@@ -1,9 +1,8 @@
|
||||
import type { UIMessage } from "ai";
|
||||
|
||||
const inlineAttachmentUrlPattern = /^data:[^,]+;base64,/u;
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
const inlineAttachmentUrlPattern = /^data:[^,]+;base64,/u;
|
||||
|
||||
const isFilePart = (value: unknown): value is Record<string, unknown> & { type: "file" } =>
|
||||
isRecord(value) && value.type === "file";
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export interface AssistantConversationExportMessage {
|
||||
id: string;
|
||||
parentId: string | null;
|
||||
@@ -25,8 +27,7 @@ const bearerTokenPattern = /\bBearer\s+[A-Za-z0-9._~+/-]{16,}=*/giu;
|
||||
const commonApiKeyPattern = /\bsk-(?:or-v1-)?[A-Za-z0-9_-]{16,}\b/giu;
|
||||
const maxDebugStringLength = 12_000;
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null => (isRecord(value) ? value : null);
|
||||
|
||||
const redactDebugValue = (value: unknown, key?: string): unknown => {
|
||||
if (key && sensitiveKeyPattern.test(key)) return "[redacted]";
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { UIMessage } from "ai";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
export type AssistantUsage = {
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
@@ -140,12 +142,11 @@ const getWebSearchSources = (value: unknown): AssistantWebSearchSource[] => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
const sources = new Map<string, AssistantWebSearchSource>();
|
||||
for (const item of value) {
|
||||
if (!item || typeof item !== "object" || Array.isArray(item)) continue;
|
||||
const candidate = item as Record<string, unknown>;
|
||||
if (typeof candidate.url !== "string" || !URL.canParse(candidate.url)) continue;
|
||||
const url = new URL(candidate.url);
|
||||
if (!isRecord(item)) continue;
|
||||
if (typeof item.url !== "string" || !URL.canParse(item.url)) continue;
|
||||
const url = new URL(item.url);
|
||||
if ((url.protocol !== "http:" && url.protocol !== "https:") || url.username || url.password) continue;
|
||||
const title = typeof candidate.title === "string" ? candidate.title.trim().slice(0, 200) : "";
|
||||
const title = typeof item.title === "string" ? item.title.trim().slice(0, 200) : "";
|
||||
if (!sources.has(url.href)) sources.set(url.href, { url: url.href, ...(title ? { title } : {}) });
|
||||
if (sources.size >= 12) break;
|
||||
}
|
||||
@@ -153,10 +154,10 @@ const getWebSearchSources = (value: unknown): AssistantWebSearchSource[] => {
|
||||
};
|
||||
|
||||
export const getAssistantUsage = (metadata: unknown): AssistantUsage | null => {
|
||||
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata) || !("usage" in metadata)) return null;
|
||||
if (!isRecord(metadata) || !("usage" in metadata)) return null;
|
||||
const usage = metadata.usage;
|
||||
if (!usage || typeof usage !== "object" || Array.isArray(usage)) return null;
|
||||
const value = usage as Record<string, unknown>;
|
||||
if (!isRecord(usage)) return null;
|
||||
const value = usage;
|
||||
return {
|
||||
...(getFiniteNonNegativeNumber(value.inputTokens) !== undefined
|
||||
? { inputTokens: getFiniteNonNegativeNumber(value.inputTokens) }
|
||||
@@ -180,11 +181,11 @@ export const getAssistantUsage = (metadata: unknown): AssistantUsage | null => {
|
||||
};
|
||||
|
||||
export const getAssistantTelemetry = (metadata: unknown): AssistantRequestTelemetry | null => {
|
||||
if (!metadata || typeof metadata !== "object" || Array.isArray(metadata)) return null;
|
||||
const custom = (metadata as { custom?: unknown }).custom;
|
||||
if (!custom || typeof custom !== "object" || Array.isArray(custom)) return null;
|
||||
const telemetry = (custom as { telemetry?: unknown }).telemetry;
|
||||
if (!telemetry || typeof telemetry !== "object" || Array.isArray(telemetry)) return null;
|
||||
if (!isRecord(metadata)) return null;
|
||||
const custom = metadata.custom;
|
||||
if (!isRecord(custom)) return null;
|
||||
const telemetry = custom.telemetry;
|
||||
if (!isRecord(telemetry)) return null;
|
||||
const value = telemetry as Partial<AssistantRequestTelemetry>;
|
||||
if (
|
||||
typeof value.requestId !== "string" ||
|
||||
@@ -196,8 +197,8 @@ export const getAssistantTelemetry = (metadata: unknown): AssistantRequestTeleme
|
||||
}
|
||||
const steps = Array.isArray(value.steps)
|
||||
? value.steps.flatMap((step): AssistantRequestStep[] => {
|
||||
if (!step || typeof step !== "object" || Array.isArray(step)) return [];
|
||||
const candidate = step as Record<string, unknown>;
|
||||
if (!isRecord(step)) return [];
|
||||
const candidate = step;
|
||||
const index = getFiniteNonNegativeNumber(candidate.index);
|
||||
const durationMs = getFiniteNonNegativeNumber(candidate.durationMs);
|
||||
const modelDurationMs = getFiniteNonNegativeNumber(candidate.modelDurationMs);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : null;
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | null => (isRecord(value) ? value : null);
|
||||
|
||||
export const getAssistantIconSearchQuery = (toolName: string, args: unknown) => {
|
||||
if (toolName !== "icon_findIcons") return null;
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
import { IconCheck, IconChevronDown, IconLink, IconRobot, IconX } from "@tabler/icons-react";
|
||||
import { useRouter } from "next/navigation";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import classes from "./assistant-panel.module.css";
|
||||
@@ -154,9 +155,9 @@ const ToolResultPresentation = ({ result, toolName }: { result: unknown; toolNam
|
||||
};
|
||||
|
||||
const getToolResultNavigation = (result: unknown) => {
|
||||
if (typeof result !== "object" || result === null || Array.isArray(result)) return [];
|
||||
if (!isRecord(result)) return [];
|
||||
|
||||
const record = result as Record<string, unknown>;
|
||||
const record = result;
|
||||
const candidates = [
|
||||
{ href: record.previewPath, translationKey: "toolNavigation.openPreview" as const },
|
||||
{ href: record.managementPath, translationKey: "toolNavigation.openWidget" as const },
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const collectionKeys = [
|
||||
"items",
|
||||
"results",
|
||||
@@ -86,8 +88,7 @@ interface ToolResultPresentationOptions {
|
||||
toolName?: string;
|
||||
}
|
||||
|
||||
const asRecord = (value: unknown): Record<string, unknown> | undefined =>
|
||||
typeof value === "object" && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
|
||||
const asRecord = (value: unknown): Record<string, unknown> | undefined => (isRecord(value) ? value : undefined);
|
||||
|
||||
const toDisplayValue = (value: unknown): ToolResultPrimitive | undefined => {
|
||||
if (typeof value === "string") {
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { isRecord } from "@homarr/common";
|
||||
|
||||
const targetKeys = ["name", "title", "query", "searchText", "appName", "widgetName"] as const;
|
||||
|
||||
export const getAssistantToolTraceTarget = (args: unknown): string | null => {
|
||||
if (!args || typeof args !== "object" || Array.isArray(args)) return null;
|
||||
const record = args as Record<string, unknown>;
|
||||
if (!isRecord(args)) return null;
|
||||
const record = args;
|
||||
|
||||
for (const key of targetKeys) {
|
||||
const value = record[key];
|
||||
|
||||
@@ -8,6 +8,7 @@ import { IconAlertTriangle, IconArrowRight, IconFileZip, IconUpload, IconX } fro
|
||||
|
||||
import "@mantine/dropzone/styles.css"; // oxlint-disable-line import/no-unassigned-import
|
||||
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { RestoreStep } from "./types";
|
||||
@@ -26,6 +27,7 @@ const DEFAULT_RESTART_DELAY_MS = 500;
|
||||
const RESTART_READINESS_TIMEOUT_MS = 45_000;
|
||||
const RESTART_POLL_INTERVAL_MS = 750;
|
||||
const RESTART_REQUEST_TIMEOUT_MS = 5_000;
|
||||
const MAX_BACKUP_FILE_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
export type ServerReadinessResult = "ready" | "timedOut" | "aborted";
|
||||
|
||||
@@ -105,6 +107,7 @@ export const waitForServerReadinessAsync = async ({
|
||||
export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: DatabaseRestoreFlowProps) => {
|
||||
const t = useI18n("management.page.tool.backup.restore");
|
||||
const tCommon = useI18n("common");
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const [file, setFile] = useState<FileWithPath | null>(null);
|
||||
const [step, setStep] = useState<RestoreStep>("upload");
|
||||
const [importError, setImportError] = useState<string | null>(null);
|
||||
@@ -221,7 +224,7 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
|
||||
rejectColor="red.6"
|
||||
accept={[MIME_TYPES.zip, "application/x-zip-compressed"]}
|
||||
multiple={false}
|
||||
maxSize={1024 * 1024 * 256}
|
||||
maxSize={MAX_BACKUP_FILE_BYTES}
|
||||
radius="md"
|
||||
>
|
||||
<Group justify="center" gap="xl" mih={variant === "standalone" ? 200 : 160} style={{ pointerEvents: "none" }}>
|
||||
@@ -245,7 +248,7 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
|
||||
{t("dropzone.title")}
|
||||
</Text>
|
||||
<Text size="sm" c="dimmed" inline mt={7}>
|
||||
{t("dropzone.description")}
|
||||
{t("dropzone.description", { maxSize: formatBytes(MAX_BACKUP_FILE_BYTES) })}
|
||||
</Text>
|
||||
</div>
|
||||
</Group>
|
||||
@@ -264,7 +267,7 @@ export const DatabaseRestoreFlow = ({ variant = "card", onRestoreComplete }: Dat
|
||||
{file?.name}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
{file ? `${(file.size / 1024 / 1024).toFixed(2)} MB` : ""}
|
||||
{file ? formatBytes(file.size) : ""}
|
||||
</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { QueryKey } from "@tanstack/react-query";
|
||||
|
||||
import { isRecord } from "@homarr/common";
|
||||
import type { WidgetQueryMatcher, WidgetQueryMatcherScope } from "@homarr/widgets/definition";
|
||||
import { normalizeWidgetQuery, widgetQueryValueEquals } from "@homarr/widgets/definition";
|
||||
|
||||
@@ -78,6 +79,3 @@ const containsValue = (container: unknown, expected: unknown, seen = new WeakSet
|
||||
|
||||
return Object.values(container).some((value) => containsValue(value, expected, seen));
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
value !== null && typeof value === "object" && !Array.isArray(value);
|
||||
+9
-5
@@ -16,11 +16,7 @@ export function registerUnsavedChangesGuard({ isDirty, confirmNavigation }: Unsa
|
||||
const destination = new URL(anchor.href, window.location.href);
|
||||
const current = new URL(window.location.href);
|
||||
if (destination.origin !== current.origin) return;
|
||||
if (
|
||||
destination.pathname === current.pathname &&
|
||||
destination.search === current.search &&
|
||||
destination.hash !== current.hash
|
||||
) {
|
||||
if (destination.pathname === current.pathname && destination.search === current.search) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -39,6 +35,14 @@ export function registerUnsavedChangesGuard({ isDirty, confirmNavigation }: Unsa
|
||||
currentHref = destination;
|
||||
return;
|
||||
}
|
||||
|
||||
const destinationUrl = new URL(destination, window.location.origin);
|
||||
const currentUrl = new URL(currentHref, window.location.origin);
|
||||
if (destinationUrl.pathname === currentUrl.pathname && destinationUrl.search === currentUrl.search) {
|
||||
currentHref = destination;
|
||||
return;
|
||||
}
|
||||
|
||||
window.history.pushState(window.history.state, "", currentHref);
|
||||
confirmNavigation(destination);
|
||||
};
|
||||
+17
-7
@@ -5,7 +5,7 @@ import { useRouter } from "next/navigation";
|
||||
|
||||
import { useConfirmModal } from "@homarr/modals";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { registerUnsavedChangesGuard } from "./_unsaved-changes-guard";
|
||||
import { registerUnsavedChangesGuard } from "./unsaved-changes-guard";
|
||||
|
||||
export function useUnsavedChangesGuard(isDirty: boolean) {
|
||||
const tConfirmLeave = useI18n("board.action.edit.confirmLeave");
|
||||
@@ -13,15 +13,25 @@ export function useUnsavedChangesGuard(isDirty: boolean) {
|
||||
const router = useRouter();
|
||||
const { openConfirmModal } = useConfirmModal();
|
||||
const dirtyRef = useRef(isDirty);
|
||||
const confirmationOpenRef = useRef(false);
|
||||
const confirmNavigationRef = useRef<(href: string) => void>(() => undefined);
|
||||
dirtyRef.current = isDirty;
|
||||
confirmNavigationRef.current = (href) => {
|
||||
openConfirmModal({
|
||||
title: tConfirmLeave("title"),
|
||||
children: tConfirmLeave("message"),
|
||||
confirmProps: { children: tCommon("action.discard") },
|
||||
onConfirm: () => router.push(href),
|
||||
});
|
||||
if (confirmationOpenRef.current) return;
|
||||
confirmationOpenRef.current = true;
|
||||
openConfirmModal(
|
||||
{
|
||||
title: tConfirmLeave("title"),
|
||||
children: tConfirmLeave("message"),
|
||||
confirmProps: { children: tCommon("action.discard") },
|
||||
onConfirm: () => router.push(href),
|
||||
},
|
||||
{
|
||||
onClose: () => {
|
||||
confirmationOpenRef.current = false;
|
||||
},
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
useEffect(
|
||||
Reference in new issue
Block a user