Skip to content

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

perf(dashboard): prioritize cached startup and parallel refreshes (#7176)

Thomas01d42762e03a
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_cached-widget-refresh.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_cached-widget-refresh.tsx
new file mode 100644
index 000000000..affab3489
--- /dev/null
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_cached-widget-refresh.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { useEffect } from "react";
+import { useQueryClient } from "@tanstack/react-query";
+import { getUntypedClient } from "@trpc/client";
+
+import { clientApi } from "@homarr/api/client";
+
+export const CachedWidgetRefresh = ({ queryHashes }: { queryHashes: string[] }) => {
+ const queryClient = useQueryClient();
+ const utils = clientApi.useUtils();
+ const trpcClient = getUntypedClient(utils.client);
+
+ useEffect(() => {
+ // Start every refresh together, including widgets whose modules have not
+ // mounted yet. fetchQuery joins a fetch already in progress.
+ for (const hash of queryHashes) {
+ const query = queryClient.getQueryCache().get(hash);
+ if (!query) continue;
+ const [path, details] = query.queryKey;
+ if (!Array.isArray(path) || path.length === 0 || !path.every((part) => typeof part === "string")) continue;
+ if (!details || typeof details !== "object" || !("input" in details)) continue;
+ query.invalidate();
+ void queryClient
+ .fetchQuery({
+ queryKey: query.queryKey,
+ staleTime: 0,
+ queryFn: ({ signal }) => trpcClient.query(path.join("."), details.input, { signal }),
+ })
+ .catch(() => undefined);
+ }
+ }, [queryClient, queryHashes, trpcClient]);
+
+ return null;
+};
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx b/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx
index a2805af26..186745592 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_creator.tsx
@@ -22,6 +22,7 @@ import { env } from "~/env";
import { createBoardLayout, getInitialViewportWidthAsync } from "../_layout-creator";
import type { Board, Item } from "../_types";
import { ClientBoard } from "./_client";
+import { CachedWidgetRefresh } from "./_cached-widget-refresh";
import { BoardContentEditAction, BoardContentSettingsAction } from "./_header-actions";
import { createBoardQuerySnapshot } from "./_query-snapshot";
import { WidgetResourcePreload } from "./_widget-resource-preload";
@@ -61,25 +62,6 @@ const DeferredWidgetHydration = async ({
);
};
-const RefreshedQueryHydration = async ({
- queryClient,
- queryHashes,
- promises,
-}: {
- queryClient: QueryClient;
- queryHashes: Set<string>;
- promises: Promise<unknown>[];
-}) => {
- await Promise.allSettled(promises);
- return (
- <HydrationBoundary
- state={dehydrate(queryClient, {
- shouldDehydrateQuery: (query) => queryHashes.has(query.queryHash) && query.state.status === "success",
- })}
- />
- );
-};
-
export const createBoardContentPage = <TParams extends Record<string, unknown>>({
getInitialBoardAsync: getInitialBoard,
}: Props<TParams>) => {
@@ -173,13 +155,7 @@ export const createBoardContentPage = <TParams extends Record<string, unknown>>(
<WidgetResourcePreload kinds={getInitiallyVisibleWidgetKinds(board, layoutId)} />
<HydrationBoundary state={dehydrate(queryClient)}>
{restoredRefreshes.length > 0 && (
- <Suspense fallback={null}>
- <RefreshedQueryHydration
- queryClient={queryClient}
- queryHashes={restoredQueryHashes}
- promises={restoredRefreshes.map(({ promise }) => promise)}
- />
- </Suspense>
+ <CachedWidgetRefresh queryHashes={restoredRefreshes.map(({ queryHash }) => queryHash)} />
)}
{dependentQueries.length > 0 && (
<Suspense fallback={null}>
diff --git a/apps/nextjs/src/app/[locale]/boards/(content)/_query-snapshot.ts b/apps/nextjs/src/app/[locale]/boards/(content)/_query-snapshot.ts
index 062eb0f64..b98dce482 100644
--- a/apps/nextjs/src/app/[locale]/boards/(content)/_query-snapshot.ts
+++ b/apps/nextjs/src/app/[locale]/boards/(content)/_query-snapshot.ts
@@ -56,10 +56,12 @@ const getQueryIntegrationIds = (queryKey: QueryKey, board: Board) => {
if (path.join(".") === "widget.rssFeed.getFeeds") {
if (!("urls" in input) || !Array.isArray(input.urls)) return null;
if (!("maximumAmountPosts" in input) || typeof input.maximumAmountPosts !== "number") return null;
+ if (!("descriptionMaxLength" in input) || typeof input.descriptionMaxLength !== "number") return null;
const urls: unknown[] = input.urls;
const matchesBoardItem = board.items.some((item) => {
if (item.kind !== "rssFeed" || !Array.isArray(item.options.feedUrls)) return false;
if (Number(item.options.maximumAmountPosts ?? 100) !== input.maximumAmountPosts) return false;
+ if (Number(item.options.descriptionMaxLength ?? 250) !== input.descriptionMaxLength) return false;
return (
item.options.feedUrls.length === urls.length && item.options.feedUrls.every((url, index) => url === urls[index])
);
diff --git a/apps/nextjs/src/components/assistant/assistant-auto-approval.tsx b/apps/nextjs/src/components/assistant/assistant-auto-approval.tsx
index 64b4a3ec6..f80777545 100644
--- a/apps/nextjs/src/components/assistant/assistant-auto-approval.tsx
+++ b/apps/nextjs/src/components/assistant/assistant-auto-approval.tsx
@@ -41,7 +41,7 @@ interface AssistantAutoApprovalContextValue {
retryRevision: number;
}
-const AssistantAutoApprovalContext = createContext<AssistantAutoApprovalContextValue | null>(null);
+export const AssistantAutoApprovalContext = createContext<AssistantAutoApprovalContextValue | null>(null);
export const AssistantAutoApprovalProvider = ({
children,
diff --git a/apps/nextjs/src/components/assistant/assistant-gate.tsx b/apps/nextjs/src/components/assistant/assistant-gate.tsx
index 18e458926..20944e13d 100644
--- a/apps/nextjs/src/components/assistant/assistant-gate.tsx
+++ b/apps/nextjs/src/components/assistant/assistant-gate.tsx
@@ -2,26 +2,15 @@
import type { PropsWithChildren } from "react";
import { useMemo } from "react";
-import dynamic from "next/dynamic";
import { useI18n } from "@homarr/translation/client";
import { AssistantWidgetRendererProvider } from "@homarr/widgets/assistant/context";
import { AssistantContext } from "./assistant-context";
+import { AssistantLauncher } from "./assistant-launcher";
import { AssistantBoardWidgetLazy } from "./assistant-widget-lazy";
import { useRegisterAssistantSpotlightPlaceholder } from "./assistant-spotlight-placeholder";
-/**
- * The enabled runtime is the expensive half of the assistant (assistant-ui, Lexical, Markdown,
- * Mermaid). Loading it through `next/dynamic` puts it in its own chunk that is only requested when
- * this component actually renders. Availability is resolved alongside other root-layout reads on
- * the server, so enabled instances render children in their final provider from the initial HTML
- * without remounting the board after hydration.
- */
-const EnabledAssistantRoot = dynamic(() =>
- import("./assistant-provider").then((module) => ({ default: module.EnabledAssistantRoot })),
-);
-
const DisabledAssistant = ({ children, description }: PropsWithChildren<{ description: string }>) => {
useRegisterAssistantSpotlightPlaceholder(description);
const value = useMemo(
@@ -74,7 +63,7 @@ export const AssistantGate = ({ availability, children }: AssistantGateProps) =>
const t = useI18n("assistant");
if (availability === "enabled") {
- return <EnabledAssistantRoot>{children}</EnabledAssistantRoot>;
+ return <AssistantLauncher>{children}</AssistantLauncher>;
}
return <DisabledAssistant description={t(unavailableMessageKeys[availability])}>{children}</DisabledAssistant>;
diff --git a/apps/nextjs/src/components/assistant/assistant-launcher.tsx b/apps/nextjs/src/components/assistant/assistant-launcher.tsx
new file mode 100644
index 000000000..b5c95d033
--- /dev/null
+++ b/apps/nextjs/src/components/assistant/assistant-launcher.tsx
@@ -0,0 +1,173 @@
+"use client";
+
+import type { PropsWithChildren, ReactNode } from "react";
+import { createContext, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from "react";
+import dynamic from "next/dynamic";
+import { useHotkeys } from "@mantine/hooks";
+
+import { hotkeys } from "@homarr/definitions";
+import { useRegisterSpotlightContextResults } from "@homarr/spotlight";
+import { closeSpotlight } from "@homarr/spotlight/store";
+import { useI18n } from "@homarr/translation/client";
+import type { WidgetComponentProps } from "@homarr/widgets";
+import { AssistantWidgetRendererProvider } from "@homarr/widgets/assistant/context";
+
+import { AssistantContext } from "./assistant-context";
+import type { AssistantContextValue } from "./assistant-context";
+import { createAssistantPromptInteraction } from "./assistant-spotlight";
+
+const EnabledAssistantRoot = dynamic(
+ () => import("./assistant-provider").then((module) => ({ default: module.EnabledAssistantRoot })),
+ { ssr: false },
+);
+
+export type AssistantWidgetRender = (props: WidgetComponentProps<"assistant">) => ReactNode;
+
+const AssistantWidgetMountContext = createContext<{
+ register: (id: string) => void;
+ unregister: (id: string) => void;
+ render: AssistantWidgetRender | null;
+} | null>(null);
+
+const DeferredAssistantWidget = (props: WidgetComponentProps<"assistant">) => {
+ const mounts = useContext(AssistantWidgetMountContext);
+ const generatedId = useId();
+ const widgetId = props.itemId ?? generatedId;
+ const register = mounts?.register;
+ const unregister = mounts?.unregister;
+
+ useEffect(() => {
+ register?.(widgetId);
+ return () => unregister?.(widgetId);
+ }, [register, unregister, widgetId]);
+
+ if (mounts?.render) return mounts.render(props);
+ return <div style={{ width: "100%", height: "100%" }} />;
+};
+
+const DeferredAssistantSpotlight = ({ sendPrompt }: Pick<AssistantContextValue, "sendPrompt">) => {
+ const t = useI18n("assistant");
+ const item = useMemo(
+ () => ({
+ id: "homarr-assistant",
+ name: t("spotlight"),
+ icon: "/logo/logo.png",
+ description: t("spotlightDescription"),
+ alwaysVisible: true,
+ placement: "fallback" as const,
+ interaction: (prompt: string) =>
+ createAssistantPromptInteraction({ sendPrompt, prompt, onPromptAccepted: closeSpotlight }),
+ }),
+ [sendPrompt, t],
+ );
+ useRegisterSpotlightContextResults("homarr-assistant", [item], [item]);
+ return null;
+};
+
+export const AssistantLauncher = ({ children }: PropsWithChildren) => {
+ const [activated, setActivated] = useState(false);
+ const [opened, setOpened] = useState(false);
+ const [pendingPrompt, setPendingPrompt] = useState<string | null>(null);
+ const pendingPromptRef = useRef<string | null>(null);
+ const [runtimeValue, setRuntimeValue] = useState<AssistantContextValue | null>(null);
+ const runtimeRef = useRef<AssistantContextValue | null>(null);
+ const [widgets, setWidgets] = useState<Set<string>>(() => new Set());
+ const [renderWidget, setRenderWidget] = useState<AssistantWidgetRender | null>(null);
+ const onWidgetRender = useCallback((render: AssistantWidgetRender) => setRenderWidget(() => render), []);
+ const onOpen = useCallback(() => setOpened(true), []);
+ const close = useCallback(() => setOpened(false), []);
+ const open = useCallback(() => {
+ setActivated(true);
+ if (runtimeRef.current) runtimeRef.current.open();
+ else setOpened(true);
+ }, []);
+ const toggle = useCallback(() => {
+ if (opened) close();
+ else open();
+ }, [close, open, opened]);
+ const queuePrompt = useCallback((prompt: string) => {
+ const text = prompt.trim();
+ if (!text || pendingPromptRef.current !== null) return false;
+ pendingPromptRef.current = text;
+ setPendingPrompt(text);
+ setActivated(true);
+ return true;
+ }, []);
+ const sendPrompt = useCallback(
+ (prompt: string) => {
+ if (runtimeRef.current) return runtimeRef.current.sendPrompt(prompt);
+ return queuePrompt(prompt);
+ },
+ [queuePrompt],
+ );
+ const onPromptHandled = useCallback(() => {
+ pendingPromptRef.current = null;
+ setPendingPrompt(null);
+ }, []);
+ const onStateChange = useCallback((value: AssistantContextValue) => {
+ runtimeRef.current = value;
+ setRuntimeValue(value);
+ }, []);
+ const register = useCallback((id: string) => {
+ setActivated(true);
+ setWidgets((current) => {
+ if (current.has(id)) return current;
+ return new Set([...current, id]);
+ });
+ }, []);
+ const unregister = useCallback((id: string) => {
+ setWidgets((current) => {
+ if (!current.has(id)) return current;
+ const next = new Set(current);
+ next.delete(id);
+ return next;
+ });
+ }, []);
+ const mounts = useMemo(() => ({ register, unregister, render: renderWidget }), [register, renderWidget, unregister]);
+ useHotkeys([[hotkeys.openAssistant, open, { preventDefault: true }]]);
+
+ const value = useMemo<AssistantContextValue>(
+ () => ({
+ enabled: true,
+ unavailableDescription: null,
+ isRefreshing: false,
+ unreadCount: 0,
+ hasVisibleWidget: false,
+ activeWidgetId: null,
+ refreshCurrentView: () => Promise.resolve(),
+ setWidgetVisible: () => undefined,
+ activateWidget: () => undefined,
+ ...runtimeValue,
+ opened,
+ isRunning: pendingPrompt !== null || runtimeValue?.isRunning === true,
+ open,
+ close,
+ toggle,
+ sendPrompt,
+ }),
+ [close, open, opened, pendingPrompt, runtimeValue, sendPrompt, toggle],
+ );
+ const active = opened || widgets.size > 0 || pendingPrompt !== null || runtimeValue?.isRunning === true;
+
+ return (
+ <AssistantContext.Provider value={value}>
+ <AssistantWidgetMountContext.Provider value={mounts}>
+ <AssistantWidgetRendererProvider renderer={DeferredAssistantWidget}>{children}</AssistantWidgetRendererProvider>
+ {!activated && <DeferredAssistantSpotlight sendPrompt={sendPrompt} />}
+ {activated && (
+ <EnabledAssistantRoot
+ opened={opened}
+ onOpen={onOpen}
+ onClose={close}
+ onStateChange={onStateChange}
+ onWidgetRender={onWidgetRender}
+ onRequestPrompt={queuePrompt}
+ pendingPrompt={pendingPrompt}
+ onPromptHandled={onPromptHandled}
+ active={active}
+ />
+ )}
+ </AssistantWidgetMountContext.Provider>
+ </AssistantContext.Provider>
+ );
+};
diff --git a/apps/nextjs/src/components/assistant/assistant-provider.tsx b/apps/nextjs/src/components/assistant/assistant-provider.tsx
index c8b150c78..40cb7e638 100644
--- a/apps/nextjs/src/components/assistant/assistant-provider.tsx
+++ b/apps/nextjs/src/components/assistant/assistant-provider.tsx
@@ -19,26 +19,33 @@ import {
useAuiState,
useRemoteThreadListRuntime,
WebSpeechSynthesisAdapter,
+ AuiProvider,
+ AuiConfig,
} from "@assistant-ui/react";
import { useChat } from "@ai-sdk/react";
import { AssistantChatTransport, useAISDKRuntime } from "@assistant-ui/react-ai-sdk";
-import { useHotkeys } from "@mantine/hooks";
import { createAssistantStream } from "assistant-stream";
import { clientApi, fetchApi } from "@homarr/api/client";
import { createId } from "@homarr/common";
-import { assistantHomarrProviderTokenHeader, hotkeys } from "@homarr/definitions";
+import { assistantHomarrProviderTokenHeader } from "@homarr/definitions";
import { showErrorNotification, showWarningNotification } from "@homarr/notifications";
import { closeSpotlight } from "@homarr/spotlight/store";
import { useI18n } from "@homarr/translation/client";
import { openMediaRequestSearch, openSpotlight, useRegisterSpotlightContextResults } from "@homarr/spotlight";
-import { AssistantWidgetRendererProvider } from "@homarr/widgets/assistant/context";
+import type { WidgetComponentProps } from "@homarr/widgets";
import { createWorkshopClient } from "~/components/workshop/workshop-client";
import { AssistantContext, AssistantPreferencesContext, useAssistantPreferences } from "./assistant-context";
+import type { AssistantContextValue } from "./assistant-context";
+import type { AssistantWidgetRender } from "./assistant-launcher";
import { shouldAutomaticallyContinueAssistant } from "./assistant-auto-submit";
import { getAssistantProviderQuotaRefreshDelay, isAssistantProviderUnavailable } from "./assistant-provider-quota";
-import { AssistantAutoApprovalProvider } from "./assistant-auto-approval";
+import {
+ AssistantAutoApprovalContext,
+ AssistantAutoApprovalProvider,
+ useAssistantAutoApproval,
+} from "./assistant-auto-approval";
import { getRunningAssistantPartType } from "./assistant-activity-state";
import { prepareAssistantRequestBody } from "./assistant-attachment-payload";
import { createAssistantBrowserToolExecutors } from "./assistant-browser-tool-executors";
@@ -134,15 +141,17 @@ const createAssistantAttachmentAdapter = (allowImages: boolean): AttachmentAdapt
};
};
-const AssistantPreferencesProvider = ({ children }: PropsWithChildren) => {
+const AssistantPreferencesProvider = ({ children, active }: PropsWithChildren<{ active: boolean }>) => {
const t = useI18n("assistant");
const { data, isLoading } = clientApi.assistant.getRuntimeOptions.useQuery(undefined, {
staleTime: 10 * 60_000,
+ enabled: active,
});
const [modelId, setModelIdState] = useState<string | null>(null);
const [reasoning, setReasoningState] = useState<AssistantReasoningMode>("auto");
const workshopClient = useMemo(createWorkshopClient, []);
const [providerUser, setProviderUser] = useState(workshopClient.currentUser);
+ const [providerAuthReady, setProviderAuthReady] = useState(false);
const [quota, setQuota] = useState<Awaited<ReturnType<typeof workshopClient.getAssistantUsage>> | null>(null);
const [quotaLoading, setQuotaLoading] = useState(false);
const [quotaError, setQuotaError] = useState<string | null>(null);
@@ -195,6 +204,7 @@ const AssistantPreferencesProvider = ({ children }: PropsWithChildren) => {
return token ? { [assistantHomarrProviderTokenHeader]: token } : {};
}, [data?.provider, workshopClient]);
const refreshQuota = useCallback(async () => {
+ if (!active) return;
quotaRequestRef.current?.abort();
if (data?.provider !== "homarr" || !workshopClient.authToken) {
quotaRequestRef.current = null;
@@ -220,7 +230,7 @@ const AssistantPreferencesProvider = ({ children }: PropsWithChildren) => {
setQuotaLoading(false);
}
}
- }, [data?.provider, t, workshopClient]);
+ }, [active, data?.provider, t, workshopClient]);
const signInToProvider = useCallback(async () => {
setQuotaLoading(true);
setQuotaError(null);
@@ -251,19 +261,33 @@ const AssistantPreferencesProvider = ({ children }: PropsWithChildren) => {
}, [data]);
useEffect(() => {
+ if (!active) {
+ setProviderAuthReady(false);
+ return;
+ }
if (data?.provider !== "homarr") {
setProviderUser(null);
setQuota(null);
setQuotaError(null);
return;
}
+ let disposed = false;
const unsubscribe = workshopClient.subscribeToAuth(setProviderUser);
void workshopClient
.refreshAuth()
- .then(setProviderUser)
- .catch(() => undefined);
- return unsubscribe;
- }, [data?.provider, workshopClient]);
+ .then((user) => {
+ if (disposed) return;
+ setProviderUser(user);
+ setProviderAuthReady(true);
+ })
+ .catch(() => {
+ if (!disposed) setProviderAuthReady(true);
+ });
+ return () => {
+ disposed = true;
+ unsubscribe();
+ };
+ }, [active, data?.provider, workshopClient]);
useEffect(
() => () => {
@@ -273,15 +297,22 @@ const AssistantPreferencesProvider = ({ children }: PropsWithChildren) => {
);
useEffect(() => {
- if (data?.provider !== "homarr" || !providerUser) return;
+ if (!active || !providerAuthReady || data?.provider !== "homarr" || !providerUser) return;
void refreshQuota();
- }, [data?.provider, providerUser, refreshQuota]);
+ }, [active, data?.provider, providerAuthReady, providerUser, refreshQuota]);
useEffect(() => {
- if (data?.provider !== "homarr" || !providerUser || !quota) return;
+ if (!active || data?.provider !== "homarr" || !providerUser || !quota) return;
const timeout = window.setTimeout(() => void refreshQuota(), getAssistantProviderQuotaRefreshDelay(quota.resetsAt));
return () => window.clearTimeout(timeout);
- }, [data?.provider, providerUser, quota, refreshQuota]);
+ }, [active, data?.provider, providerUser, quota, refreshQuota]);
+
+ useEffect(() => {
+ if (active) return;
+ quotaRequestRef.current?.abort();
+ quotaRequestRef.current = null;
+ setQuotaLoading(false);
+ }, [active]);
const value = useMemo(
() => ({
@@ -290,7 +321,7 @@ const AssistantPreferencesProvider = ({ children }: PropsWithChildren) => {
modelId,
models,
reasoning,
- isLoading,
+ isLoading: isLoading || (active && data?.provider === "homarr" && !providerAuthReady),
providerUser,
quota,
quotaLoading,
@@ -308,6 +339,8 @@ const AssistantPreferencesProvider = ({ children }: PropsWithChildren) => {
getRequestBody,
getRequestHeaders,
isLoading,
+ active,
+ providerAuthReady,
modelId,
models,
providerUser,
@@ -678,9 +711,30 @@ const getNotificationKey = (message: ThreadMessage | undefined) => {
return `${message.id}:${message.status.type}:${"reason" in message.status ? message.status.reason : ""}`;
};
-const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
+interface EnabledAssistantRootProps {
+ active: boolean;
+ opened: boolean;
+ onOpen: () => void;
+ onClose: () => void;
+ onStateChange: (value: AssistantContextValue) => void;
+ onWidgetRender: (render: AssistantWidgetRender) => void;
+ onRequestPrompt: (prompt: string) => boolean;
+ pendingPrompt: string | null;
+ onPromptHandled: () => void;
+}
+
+const EnabledAssistantProvider = ({
+ active,
+ opened,
+ onOpen,
+ onClose,
+ onStateChange,
+ onWidgetRender,
+ onRequestPrompt,
+ pendingPrompt,
+ onPromptHandled,
+}: EnabledAssistantRootProps) => {
const t = useI18n("assistant");
- const [opened, setOpened] = useState(false);
const [activityDismissed, setActivityDismissed] = useState(true);
const [unreadCount, setUnreadCount] = useState(0);
const [visibleWidgetIds, setVisibleWidgetIds] = useState<Set<string>>(() => new Set());
@@ -733,9 +787,9 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
const open = useCallback(() => {
markRead();
setActivityDismissed(false);
- setOpened(true);
- }, [markRead]);
- const close = useCallback(() => setOpened(false), []);
+ onOpen();
+ }, [markRead, onOpen]);
+ const close = onClose;
const setWidgetVisible = useCallback((widgetId: string, visible: boolean) => {
if (visible) markReadRef.current();
setVisibleWidgetIds((current) => {
@@ -760,6 +814,7 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
(prompt: string) => {
const text = prompt.trim();
if (text.length === 0) return false;
+ if (!active) return onRequestPrompt(text);
if (providerUnavailable) {
showWarningNotification({
title: t("providerQuota.title"),
@@ -783,7 +838,17 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
}
return sendPromptThroughRuntime(aui, text);
},
- [assistantIsRunning, aui, isLoading, latestStatus?.type, preferences.providerUser, providerUnavailable, t],
+ [
+ active,
+ assistantIsRunning,
+ aui,
+ isLoading,
+ latestStatus?.type,
+ onRequestPrompt,
+ preferences.providerUser,
+ providerUnavailable,
+ t,
+ ],
);
const selectModel = useCallback(
(modelId: string) => {
@@ -795,6 +860,12 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
[aui, preferences],
);
+ useEffect(() => {
+ if (pendingPrompt === null || isLoading || preferences.isLoading) return;
+ sendPrompt(pendingPrompt);
+ onPromptHandled();
+ }, [isLoading, onPromptHandled, pendingPrompt, preferences.isLoading, sendPrompt]);
+
useEffect(() => {
if (assistantIsRunning) setActivityDismissed(false);
}, [assistantIsRunning]);
@@ -847,8 +918,6 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
});
}, [conversationId, isLoading, refreshCurrentView, successfulMutationIds, t]);
- useHotkeys([[hotkeys.openAssistant, open, { preventDefault: true }]]);
-
const spotlightItem = useMemo(() => {
const canSend = !providerUnavailable && !assistantIsRunning && latestStatus?.type !== "requires-action";
return {
@@ -910,11 +979,13 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
],
);
+ useEffect(() => onStateChange(value), [onStateChange, value]);
+
return (
<AssistantAutoApprovalProvider conversationId={conversationId}>
<AssistantContext.Provider value={value}>
<AssistantComposerRuntimeProvider>
- <AssistantWidgetRendererProvider renderer={AssistantBoardWidget}>{children}</AssistantWidgetRendererProvider>
+ <AssistantWidgetScope onRender={onWidgetRender} />
<AssistantComposerSurfaceBoundary surfaceId="assistant-panel">
<AssistantPanel
opened={opened}
@@ -950,15 +1021,54 @@ const EnabledAssistantProvider = ({ children }: PropsWithChildren) => {
};
/**
- * The enabled half of the assistant. Only rendered (and only downloaded) when the instance has the
- * assistant configured and the visitor is signed in - see `assistant-gate`.
+ * Keep the runtime separate from dashboard children so activating it does not
+ * remount the board. Board widgets reuse its scopes inside their existing tree.
*/
-export const EnabledAssistantRoot = ({ children }: PropsWithChildren) => (
- <AssistantPreferencesProvider>
+export const EnabledAssistantRoot = (props: EnabledAssistantRootProps) => (
+ <AssistantPreferencesProvider active={props.active}>
<AssistantViewRefreshProvider>
<AssistantRuntime>
- <EnabledAssistantProvider>{children}</EnabledAssistantProvider>
+ <EnabledAssistantProvider {...props} />
</AssistantRuntime>
</AssistantViewRefreshProvider>
</AssistantPreferencesProvider>
);
+
+interface AssistantWidgetScopeValue {
+ aui: ReturnType<typeof useAui>;
+ preferences: ReturnType<typeof useAssistantPreferences>;
+ approval: ReturnType<typeof useAssistantAutoApproval>;
+}
+
+const ScopedAssistantBoardWidget = ({
+ scope,
+ widget,
+}: {
+ scope: AssistantWidgetScopeValue;
+ widget: WidgetComponentProps<"assistant">;
+}) => {
+ const config = useMemo(() => AuiConfig({}), []);
+ return (
+ <AuiProvider extends={scope.aui} config={config}>
+ <AssistantPreferencesContext.Provider value={scope.preferences}>
+ <AssistantAutoApprovalContext.Provider value={scope.approval}>
+ <AssistantBoardWidget {...widget} />
+ </AssistantAutoApprovalContext.Provider>
+ </AssistantPreferencesContext.Provider>
+ </AuiProvider>
+ );
+};
+
+const AssistantWidgetScope = ({ onRender }: { onRender: (render: AssistantWidgetRender) => void }) => {
+ const aui = useAui();
+ const preferences = useAssistantPreferences();
+ const approval = useAssistantAutoApproval();
+ const render = useCallback(
+ (widget: WidgetComponentProps<"assistant">) => (
+ <ScopedAssistantBoardWidget scope={{ aui, preferences, approval }} widget={widget} />
+ ),
+ [approval, aui, preferences],
+ );
+ useEffect(() => onRender(render), [onRender, render]);
+ return null;
+};
diff --git a/apps/nextjs/src/components/layout/header/button.tsx b/apps/nextjs/src/components/layout/header/button.tsx
index 49c67d883..459eb5f20 100644
--- a/apps/nextjs/src/components/layout/header/button.tsx
+++ b/apps/nextjs/src/components/layout/header/button.tsx
@@ -34,6 +34,7 @@ export const HeaderButton = forwardRef<HTMLButtonElement, HeaderButtonProps>((pr
<ActionIcon
ref={ref as ForwardedRef<HTMLAnchorElement>}
component={Link}
+ prefetch={false}
{...props}
{...headerButtonActionIconProps}
>
diff --git a/apps/nextjs/src/components/layout/header/header-logo.tsx b/apps/nextjs/src/components/layout/header/header-logo.tsx
index bb0da24ef..6215bceab 100644
--- a/apps/nextjs/src/components/layout/header/header-logo.tsx
+++ b/apps/nextjs/src/components/layout/header/header-logo.tsx
@@ -22,7 +22,14 @@ export const HeaderLogo = ({ display, logo, logoWithTitle, label }: HeaderLogoPr
if (display === "logoAndText") content = logoWithTitle;
return (
- <UnstyledButton component={Link} href={href} className={classes.root} data-display={display} aria-label={label}>
+ <UnstyledButton
+ component={Link}
+ href={href}
+ prefetch={false}
+ className={classes.root}
+ data-display={display}
+ aria-label={label}
+ >
{content}
</UnstyledButton>
);
diff --git a/packages/integrations/src/jellyfin/jellyfin-integration.ts b/packages/integrations/src/jellyfin/jellyfin-integration.ts
index 7f6effdb6..07fe2d131 100644
--- a/packages/integrations/src/jellyfin/jellyfin-integration.ts
+++ b/packages/integrations/src/jellyfin/jellyfin-integration.ts
@@ -1,6 +1,7 @@
import { BlockList, isIP } from "node:net";
import { Jellyfin } from "@jellyfin/sdk";
import { BaseItemKind } from "@jellyfin/sdk/lib/generated-client/models";
+import type { BaseItemDto } from "@jellyfin/sdk/lib/generated-client/models";
import { getSessionApi } from "@jellyfin/sdk/lib/utils/api/session-api";
import { getSystemApi } from "@jellyfin/sdk/lib/utils/api/system-api";
import { getUserApi } from "@jellyfin/sdk/lib/utils/api/user-api";
@@ -251,7 +252,7 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
releaseDate: new Date(item.PremiereDate ?? item.DateCreated!),
imageUrls: {
poster: super.externalUrl(`/Items/${item.Id}/Images/Primary?maxHeight=492&maxWidth=328&quality=90`).toString(),
- backdrop: super.externalUrl(`/Items/${item.Id}/Images/Backdrop/0?maxWidth=960&quality=70`).toString(),
+ backdrop: this.getMediaReleaseBackdropUrl(item),
},
producer: item.Studios?.at(0)?.Name ?? undefined,
rating: item.CommunityRating?.toFixed(1),
@@ -260,6 +261,14 @@ export class JellyfinIntegration extends Integration implements IMediaServerInte
}));
}
+ private getMediaReleaseBackdropUrl(item: BaseItemDto) {
+ let itemId: string | undefined;
+ if (item.BackdropImageTags?.length) itemId = item.Id;
+ else if (item.ParentBackdropImageTags?.length) itemId = item.ParentBackdropItemId ?? undefined;
+ if (!itemId) return undefined;
+ return super.externalUrl(`/Items/${itemId}/Images/Backdrop/0?maxWidth=960&quality=70`).toString();
+ }
+
private mapMediaReleaseType(type: BaseItemKind | undefined): MediaType {
switch (type) {
case "Audio":
diff --git a/packages/integrations/src/overseerr/overseerr-integration.ts b/packages/integrations/src/overseerr/overseerr-integration.ts
index 505e31b35..125fdac10 100644
--- a/packages/integrations/src/overseerr/overseerr-integration.ts
+++ b/packages/integrations/src/overseerr/overseerr-integration.ts
@@ -178,8 +178,8 @@ export class OverseerrIntegration
name: information.name,
status: this.mapRequestStatus(request.status),
availability: this.mapAvailability(request.media.status, inProgress),
- backdropImageUrl: `https://image.tmdb.org/t/p/original/${information.backdropPath}`,
- posterImagePath: `https://image.tmdb.org/t/p/w600_and_h900_bestv2/${information.posterPath}`,
+ backdropImageUrl: `https://image.tmdb.org/t/p/w780/${information.backdropPath}`,
+ posterImagePath: `https://image.tmdb.org/t/p/w154/${information.posterPath}`,
href: this.externalUrl(`/${request.type}/${request.media.tmdbId}`).toString(),
type: request.type,
createdAt: request.createdAt,
diff --git a/packages/ui/src/components/masked-or-normal-image.tsx b/packages/ui/src/components/masked-or-normal-image.tsx
index af60b28d9..a6548990e 100644
--- a/packages/ui/src/components/masked-or-normal-image.tsx
+++ b/packages/ui/src/components/masked-or-normal-image.tsx
@@ -49,6 +49,9 @@ export const MaskedOrNormalImage = ({
src={imageUrl}
alt={alt}
fit={fit}
+ loading="lazy"
+ decoding="async"
+ fetchPriority="low"
style={{ ...style }}
/>
);
diff --git a/packages/widgets/src/beszel/_shared/chart.tsx b/packages/widgets/src/beszel/_shared/chart.tsx
index e2c75a380..7693b034b 100644
--- a/packages/widgets/src/beszel/_shared/chart.tsx
+++ b/packages/widgets/src/beszel/_shared/chart.tsx
@@ -1,9 +1,10 @@
"use client";
-import { memo, useMemo, useRef } from "react";
-import { Group, Stack, Text } from "@mantine/core";
+import { memo, useDeferredValue, useEffect, useMemo, useRef, useState } from "react";
+import { Box, Group, Stack, Text } from "@mantine/core";
import type { AreaChartProps } from "@mantine/charts";
import { AreaChart } from "@mantine/charts";
+import { useInViewport } from "@mantine/hooks";
import dayjs from "dayjs";
import type { BeszelTimePeriod } from "@homarr/definitions/beszel";
@@ -11,6 +12,7 @@ import { defaultBeszelTimePeriod } from "@homarr/definitions/beszel";
import type { BeszelContainerStatsRecord, BeszelGPUData, BeszelSystemStatsRecord } from "@homarr/integrations/types";
import { formatLocalizedDate } from "../../common/locale";
+import { WidgetQueryLoadingState } from "../../common/query-state-indicator";
import { containerChartColor } from "./colors";
import classes from "./chart.module.css";
@@ -105,6 +107,14 @@ const chartStyle = {
zoom: "var(--board-canvas-inverse-scale, 1)",
} as const;
const panelStyle = { minWidth: 0 } as const;
+const chartContainerStyle = {
+ minWidth: 0,
+ minHeight: 1,
+ display: "flex",
+ flexDirection: "column",
+ flexGrow: 1,
+ flexShrink: 0,
+} as const;
const chartMargin = { top: 12, right: 5, bottom: 0, left: 0 } as const;
export const CPU_Y_AXIS_DOMAIN: [number, string] = [0, "auto"];
@@ -114,21 +124,53 @@ interface BeszelChartPanelProps {
chartProps: BeszelAreaChartProps;
}
-export const BeszelChartPanel = memo(({ title, subtitle, chartProps }: BeszelChartPanelProps) => (
- <Stack gap={4} style={panelStyle}>
- <Group gap="xs" wrap="nowrap">
- <Text size="sm" fw={600} style={{ flexShrink: 0 }}>
- {title}
- </Text>
- {subtitle && (
- <Text size="xs" c="dimmed" truncate style={{ minWidth: 0 }}>
- {subtitle}
+export const BeszelChartPanel = memo(({ title, subtitle, chartProps }: BeszelChartPanelProps) => {
+ const { ref, inViewport } = useInViewport<HTMLDivElement>();
+ const [hasBeenVisible, setHasBeenVisible] = useState(false);
+ const isVisible = inViewport || typeof IntersectionObserver === "undefined";
+
+ useEffect(() => {
+ if (isVisible) setHasBeenVisible(true);
+ }, [isVisible]);
+
+ return (
+ <Stack gap={4} style={panelStyle}>
+ <Group gap="xs" wrap="nowrap">
+ <Text size="sm" fw={600} style={{ flexShrink: 0 }}>
+ {title}
</Text>
- )}
- </Group>
- <BeszelAreaChart {...chartProps} />
- </Stack>
-));
+ {subtitle && (
+ <Text size="xs" c="dimmed" truncate style={{ minWidth: 0 }}>
+ {subtitle}
+ </Text>
+ )}
+ </Group>
+ <Box ref={ref} style={chartContainerStyle}>
+ {(inViewport || hasBeenVisible) && <DeferredBeszelChart chartProps={chartProps} isVisible={isVisible} />}
+ {!inViewport && !hasBeenVisible && <BeszelChartPlaceholder height={chartProps.h} />}
+ </Box>
+ </Stack>
+ );
+});
+
+const BeszelChartPlaceholder = ({ height }: { height: AreaChartProps["h"] }) => (
+ <Box h={height} className={classes.chart} style={chartStyle}>
+ <WidgetQueryLoadingState />
+ </Box>
+);
+
+const DeferredBeszelChart = memo(
+ ({ chartProps }: { chartProps: BeszelAreaChartProps; isVisible: boolean }) => {
+ // Let the dashboard hydrate and handle input before mounting or refreshing SVG charts.
+ const deferredChartProps = useDeferredValue(chartProps, null);
+ if (!deferredChartProps) {
+ return <BeszelChartPlaceholder height={chartProps.h} />;
+ }
+ return <BeszelAreaChart {...deferredChartProps} />;
+ },
+ // Retain mounted charts while offscreen; apply the latest data when they re-enter view.
+ (previous, next) => !next.isVisible || previous.chartProps === next.chartProps,
+);
type BeszelAreaChartProps = Omit<AreaChartProps, "dataKey" | "curveType" | "withDots" | "withYAxis"> & {
yAxisFormatter: (value: number) => string;
diff --git a/packages/widgets/src/beszel/_shared/stats-view.tsx b/packages/widgets/src/beszel/_shared/stats-view.tsx
index a82d3c488..a50e5776c 100644
--- a/packages/widgets/src/beszel/_shared/stats-view.tsx
+++ b/packages/widgets/src/beszel/_shared/stats-view.tsx
@@ -36,6 +36,7 @@ import { useDemoReadOnly } from "../../demo-read-only";
const CHART_HEIGHT = 180;
const MEBIBYTE = 1024 * 1024;
const GIBIBYTE = 1024 * MEBIBYTE;
+const dockerAreaChartProps = { reverseStackOrder: true };
export interface BeszelStatsVisibility {
cpu: boolean;
@@ -474,7 +475,7 @@ export function BeszelStatsView({
data: dockerCpuData,
type: "stacked",
series: containerCpuSeries,
- areaChartProps: { reverseStackOrder: true },
+ areaChartProps: dockerAreaChartProps,
yAxisFormatter: formatPercent,
tooltipProps: tooltips.percentTotal,
}}
@@ -490,7 +491,7 @@ export function BeszelStatsView({
data: dockerMemoryData,
type: "stacked",
series: containerMemorySeries,
- areaChartProps: { reverseStackOrder: true },
+ areaChartProps: dockerAreaChartProps,
yAxisFormatter: formatters.memoryAxis,
tooltipProps: tooltips.memory,
}}
@@ -506,7 +507,7 @@ export function BeszelStatsView({
data: dockerNetworkData,
series: containerNetworkSeries,
type: "stacked",
- areaChartProps: { reverseStackOrder: true },
+ areaChartProps: dockerAreaChartProps,
yAxisFormatter: formatters.rateAxis,
tooltipProps: tooltips.rate,
}}
diff --git a/packages/widgets/src/common/locale.ts b/packages/widgets/src/common/locale.ts
index 3d1c6bf3f..5dda699f6 100644
--- a/packages/widgets/src/common/locale.ts
+++ b/packages/widgets/src/common/locale.ts
@@ -1,6 +1,8 @@
export type LocalizedDateValue = Date | number | string;
const dateOnlyPattern = /^\d{4}-\d{2}-\d{2}$/;
+const dateFormatters = new Map<string, Intl.DateTimeFormat>();
+const maxDateFormatters = 64;
interface LocalizedTimeOptions {
hour12?: boolean;
@@ -29,7 +31,17 @@ export const formatLocalizedDate = (
typeof value === "string" && dateOnlyPattern.test(value) && options.timeZone === undefined
? { ...options, timeZone: "UTC" }
: options;
- return new Intl.DateTimeFormat(locale, normalizedOptions).format(date);
+ const key = JSON.stringify([locale, normalizedOptions]);
+ let formatter = dateFormatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.DateTimeFormat(locale, normalizedOptions);
+ if (dateFormatters.size >= maxDateFormatters) {
+ const oldestKey = dateFormatters.keys().next().value;
+ if (oldestKey !== undefined) dateFormatters.delete(oldestKey);
+ }
+ dateFormatters.set(key, formatter);
+ }
+ return formatter.format(date);
};
export const formatLocalizedTime = (
diff --git a/packages/widgets/src/media-releases/component.tsx b/packages/widgets/src/media-releases/component.tsx
index c947f3d9c..5aebdd285 100644
--- a/packages/widgets/src/media-releases/component.tsx
+++ b/packages/widgets/src/media-releases/component.tsx
@@ -151,19 +151,20 @@ const Item = ({ item, options, isAdvanced, formatDate }: ItemProps) => {
: undefined
}
>
- {!isAdvanced && options.layout === "backdrop" && (
- <Box
+ {!isAdvanced && options.layout === "backdrop" && item.imageUrls.backdrop && (
+ <Image
+ src={item.imageUrls.backdrop}
+ alt=""
+ loading="lazy"
+ decoding="async"
+ fetchPriority="low"
w="100%"
h="100%"
pos="absolute"
top={0}
left={0}
style={{
- backgroundImage: `url(${item.imageUrls.backdrop})`,
borderRadius: 8,
- backgroundRepeat: "no-repeat",
- backgroundSize: "cover",
- backgroundPosition: "center",
opacity: 0.2,
}}
/>
diff --git a/packages/widgets/src/media-requests/list/component.tsx b/packages/widgets/src/media-requests/list/component.tsx
index 59d2e14be..7226be3bd 100644
--- a/packages/widgets/src/media-requests/list/component.tsx
+++ b/packages/widgets/src/media-requests/list/component.tsx
@@ -138,6 +138,9 @@ const MediaRequestCard = ({ request, isTiny, showIntegrationSource, canInteract,
top={0}
left={0}
alt=""
+ loading="lazy"
+ decoding="async"
+ fetchPriority="low"
/>
<Group
className="mediaRequests-list-item-contents"
@@ -156,6 +159,9 @@ const MediaRequestCard = ({ request, isTiny, showIntegrationSource, canInteract,
w="auto"
radius="md"
alt=""
+ loading="lazy"
+ decoding="async"
+ fetchPriority="low"
style={{ flexShrink: 0 }}
/>
)}
diff --git a/packages/widgets/src/server-prefetch.ts b/packages/widgets/src/server-prefetch.ts
index 093dfc35e..525d5cc6a 100644
--- a/packages/widgets/src/server-prefetch.ts
+++ b/packages/widgets/src/server-prefetch.ts
@@ -245,6 +245,7 @@ export const prefetchInitialWidgetData = (
trpc.widget.rssFeed.getFeeds.queryOptions({
urls: options.feedUrls,
maximumAmountPosts: Number(options.maximumAmountPosts ?? 100),
+ descriptionMaxLength: Number(options.descriptionMaxLength ?? 250),
}),
);
break;