fix: address v2 stack review findings

This commit is contained in:
ajnart committed 2026-08-20 13:08:54 +02:00
1 parent 53b518960c
commit 263702210a
48 files changed
+1235 -530

No files matched your search

@@ -5,3 +5,4 @@ export {
serializeCustomWidgetDefinition,
} from "./router/custom-widget/stored-definition";
export { configureCustomWidgetSourceFromRequest } from "./router/custom-widget/secret-persistence";
export { invalidateCustomWidgetResponseCache } from "./router/custom-widget/request-executor";
+5 -4
View File
@@ -5,6 +5,7 @@ import { z } from "zod/v4";
import { constructIntegrationPermissions } from "@homarr/auth/shared";
import { createId } from "@homarr/common";
import { decryptSecret, encryptSecret } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { and, asc, desc, eq, handleTransactionsAsync, inArray } from "@homarr/db";
import type { Database } from "@homarr/db";
import {
@@ -33,7 +34,7 @@ import { fetchOpenRouterGenerationTelemetryAsync } from "../assistant-generation
import { env } from "../env";
import { orderMessagesByParent } from "../assistant-message-order";
import { verifyAssistantGenerationAccessToken } from "../assistant-generation-access";
import { createTRPCRouter, isDemoMode, permissionRequiredProcedure, protectedProcedure } from "../trpc";
import { createTRPCRouter, isDemoMode, isDemoReadOnly, permissionRequiredProcedure, protectedProcedure } from "../trpc";
import { boardRouter, getHomeIdBoardAsync } from "./board";
const adminProcedure = permissionRequiredProcedure.requiresPermission("admin");
@@ -206,9 +207,9 @@ const fetchModelsAsync = async (configuration: AssistantConfiguration) => {
}
const endpoint = `${configuration.baseUrl}${configuration.modelDiscoveryPath}`;
let response: Response;
let response: Awaited<ReturnType<typeof fetchWithTrustedCertificatesAsync>>;
try {
response = await fetch(endpoint, {
response = await fetchWithTrustedCertificatesAsync(endpoint, {
headers: getProviderHeaders(configuration),
signal: AbortSignal.timeout(15_000),
});
@@ -454,7 +455,7 @@ const addFeedbackToMessageContent = (serializedContent: string, type: "positive"
export const assistantRouter = createTRPCRouter({
getAvailability: protectedProcedure.query(async ({ ctx }) => {
if (isDemoMode) {
return { enabled: true };
return { enabled: !isDemoReadOnly };
}
const configuration = await getConfigurationAsync(ctx.db);
const requiresApiKey = configuration ? assistantProviderRequiresApiKey(configuration.provider) : false;
@@ -64,7 +64,7 @@ export const previewActionProcedures = {
kind: "action",
});
if (response.ok && request.invalidates?.length) {
invalidateCustomWidgetResponseCache(
await invalidateCustomWidgetResponseCache(
request.invalidates.map((requestId) => `custom-jsx:preview:${session.id}:${requestId}:`),
);
}
@@ -19,7 +19,7 @@ export const previewQueryProcedures = {
.input(z.object({ sessionId: z.string().min(1) }))
.mutation(async ({ ctx, input }) => {
const session = await getPreviewSession(input.sessionId, ctx.session.user.id);
invalidateCustomWidgetResponseCache([`custom-jsx:preview:${session.id}:`]);
await invalidateCustomWidgetResponseCache([`custom-jsx:preview:${session.id}:`]);
}),
previewQuery: permissionRequiredProcedure
@@ -16,6 +16,7 @@ import {
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "@homarr/custom-widgets/server";
import { toTrpcError } from "./domain-error";
import { executeWithCustomWidgetResponseCache, invalidateSharedCustomWidgetResponseCache } from "./response-cache";
export type {
CustomWidgetAuthConfig,
@@ -74,14 +75,18 @@ export async function resolveAndValidateHost(hostname: string, scope: CustomWidg
export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest): Promise<CustomWidgetHttpResponse> {
try {
return await executeDomainRequest({
...input,
logError: (event) => logger.error("Custom widget request failed", event),
});
return await executeWithCustomWidgetResponseCache(input, (request) =>
executeDomainRequest({
...request,
logError: (event) => logger.error("Custom widget request failed", event),
}),
);
} catch (error) {
toTrpcError(error);
}
}
export const invalidateCustomWidgetResponseCache = (prefixes: readonly string[]) =>
export async function invalidateCustomWidgetResponseCache(prefixes: readonly string[]) {
invalidateDomainResponseCache(prefixes);
await invalidateSharedCustomWidgetResponseCache(prefixes);
}
@@ -0,0 +1,154 @@
import { Buffer } from "node:buffer";
import { createHash } from "node:crypto";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { createRedisClient } from "@homarr/core/infrastructure/redis";
import type { RedisClient } from "@homarr/core/infrastructure/redis";
import type { CustomWidgetHttpRequest, CustomWidgetHttpResponse } from "@homarr/custom-widgets/server";
const ENTRY_PREFIX = "custom-widget:response-cache:v2:entry:";
const GENERATION_KEY = "custom-widget:response-cache:v2:generation";
const LRU_KEY = "custom-widget:response-cache:v2:lru";
const SIZE_KEY = "custom-widget:response-cache:v2:sizes";
const TOTAL_BYTES_KEY = "custom-widget:response-cache:v2:bytes";
const MAX_ENTRIES = 1_000;
const MAX_BYTES = 64 * 1024 * 1024;
const STORE_SCRIPT = `
local previousSize = tonumber(redis.call('HGET', KEYS[2], ARGV[1]) or '0')
if previousSize > 0 then redis.call('DECRBY', KEYS[3], previousSize) end
redis.call('SET', ARGV[1], ARGV[2], 'PX', ARGV[3])
redis.call('ZADD', KEYS[1], ARGV[4], ARGV[1])
redis.call('HSET', KEYS[2], ARGV[1], ARGV[5])
local totalBytes = redis.call('INCRBY', KEYS[3], ARGV[5])
while redis.call('ZCARD', KEYS[1]) > tonumber(ARGV[6]) or totalBytes > tonumber(ARGV[7]) do
local evicted = redis.call('ZPOPMIN', KEYS[1], 1)
if #evicted == 0 then break end
local evictedKey = evicted[1]
local evictedSize = tonumber(redis.call('HGET', KEYS[2], evictedKey) or '0')
redis.call('DEL', evictedKey)
redis.call('HDEL', KEYS[2], evictedKey)
if evictedSize > 0 then totalBytes = redis.call('DECRBY', KEYS[3], evictedSize) end
end
return totalBytes
`;
const logger = createLogger({ module: "custom-widget:response-cache" });
const inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
let redis: RedisClient | undefined;
const useSharedCache = () => process.env.NODE_ENV !== "test";
const getRedis = () => {
redis ??= createRedisClient();
return redis;
};
const getGeneration = async (client: RedisClient) => Number((await client.get(GENERATION_KEY)) ?? 0);
const getEntryKey = (generation: number, cacheKey: string) => {
const digest = createHash("sha256").update(cacheKey).digest("hex");
return `${ENTRY_PREFIX}${generation}:${digest}`;
};
const readCachedResponse = async (client: RedisClient, entryKey: string) => {
const serialized = await client.get(entryKey);
if (serialized === null) return undefined;
await client.zadd(LRU_KEY, Date.now(), entryKey);
try {
return JSON.parse(serialized) as CustomWidgetHttpResponse;
} catch {
await client.del(entryKey);
return undefined;
}
};
const storeCachedResponse = async (
client: RedisClient,
entryKey: string,
response: CustomWidgetHttpResponse,
ttlSeconds: number,
) => {
const serialized = JSON.stringify(response);
const size = Buffer.byteLength(serialized, "utf8");
await client.eval(
STORE_SCRIPT,
3,
LRU_KEY,
SIZE_KEY,
TOTAL_BYTES_KEY,
entryKey,
serialized,
ttlSeconds * 1_000,
Date.now(),
size,
MAX_ENTRIES,
MAX_BYTES,
);
};
export async function executeWithCustomWidgetResponseCache(
input: CustomWidgetHttpRequest,
execute: (input: CustomWidgetHttpRequest) => Promise<CustomWidgetHttpResponse>,
): Promise<CustomWidgetHttpResponse> {
const cacheKey = input.kind === "query" ? input.cacheKey : undefined;
if (!cacheKey) return execute(input);
if (!useSharedCache()) return execute(input);
let client: RedisClient;
let generation: number;
try {
client = getRedis();
generation = await getGeneration(client);
if ((input.cacheTtlSeconds ?? 0) > 0) {
const cached = await readCachedResponse(client, getEntryKey(generation, cacheKey));
if (cached) return cached;
}
} catch (error) {
logger.error("Shared custom widget response cache is unavailable", {
errorName: error instanceof Error ? error.name : "UnknownError",
});
return execute({ ...input, cacheKey: undefined });
}
const pendingKey = `${generation}:${cacheKey}`;
const pending = inFlight.get(pendingKey);
if (pending) return pending;
let request: Promise<CustomWidgetHttpResponse>;
request = execute({ ...input, cacheKey: undefined })
.then(async (response) => {
const ttlSeconds = input.cacheTtlSeconds ?? 0;
if (!response.ok || ttlSeconds <= 0) return response;
try {
const currentGeneration = await getGeneration(client);
if (currentGeneration === generation) {
await storeCachedResponse(client, getEntryKey(generation, cacheKey), response, ttlSeconds);
}
} catch (error) {
logger.error("Failed to store a custom widget response", {
errorName: error instanceof Error ? error.name : "UnknownError",
});
}
return response;
})
.finally(() => {
if (inFlight.get(pendingKey) === request) inFlight.delete(pendingKey);
});
inFlight.set(pendingKey, request);
return request;
}
export async function invalidateSharedCustomWidgetResponseCache(prefixes: readonly string[]) {
if (prefixes.length === 0 || !useSharedCache()) return;
for (const key of inFlight.keys()) {
if (prefixes.some((prefix) => key.includes(prefix))) inFlight.delete(key);
}
try {
await getRedis().incr(GENERATION_KEY);
} catch (error) {
logger.error("Failed to invalidate the shared custom widget response cache", {
errorName: error instanceof Error ? error.name : "UnknownError",
});
}
}
@@ -118,8 +118,8 @@ describe("Custom JSX v2 board router", () => {
});
test("refreshes the server response cache for a placed widget", async () => {
const { db, itemId } = await setup();
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: null });
const { db, itemId, ownerId } = await setup();
const caller = customApiRouter.createCaller({ db, deviceType: undefined, session: createSession(ownerId) });
await caller.refresh({ itemId });
+13 -7
View File
@@ -2,6 +2,7 @@ import { TRPCError } from "@trpc/server";
import { parse as parseSuperJson } from "superjson";
import { z } from "zod/v4";
import { mapWithConcurrency } from "@homarr/common";
import { decryptSecret } from "@homarr/common/server";
import { eq } from "@homarr/db";
import { boards, customWidgetDefinitions, items, legacyCustomWidgetDefinitions } from "@homarr/db/schema";
@@ -13,6 +14,7 @@ import {
validateCustomWidgetOptions,
} from "@homarr/custom-widgets/core";
import type { CustomJsxRequest, CustomWidgetSource } from "@homarr/custom-widgets/core";
import { CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT } from "@homarr/custom-widgets/server";
import { createTRPCRouter, protectedProcedure, publicProcedure } from "../../trpc";
import { throwIfActionForbiddenAsync } from "../board/board-access";
@@ -40,7 +42,7 @@ interface CustomWidgetItemOptions {
refreshInterval?: number;
}
type RouterContext = Parameters<typeof throwIfActionForbiddenAsync>[0];
type RouterContext = Parameters<typeof throwIfActionForbiddenAsync>[0] & { ipAddress?: string };
type ResolvedDefinition = Awaited<ReturnType<typeof resolvePlacedDefinitionAsync>>;
const parseItemOptions = (raw: string): CustomWidgetItemOptions => {
@@ -154,6 +156,7 @@ const withRequestLimit = async <T>(
const release = await acquireCustomWidgetRequestLimit({
category: request.kind === "query" ? "query" : request.method === "DELETE" ? "delete" : "action",
userId: ctx.session?.user.id,
anonymousId: ctx.ipAddress,
itemId: resolved.item.id,
definitionId: resolved.stored.id,
});
@@ -194,9 +197,9 @@ const executeRequest = async (
};
export const customApiRouter = createTRPCRouter({
refresh: publicProcedure.input(itemInputSchema).mutation(async ({ ctx, input }) => {
refresh: protectedProcedure.input(itemInputSchema).mutation(async ({ ctx, input }) => {
const resolved = await resolvePlacedDefinitionAsync(ctx, input.itemId);
invalidateCustomWidgetResponseCache([
await invalidateCustomWidgetResponseCache([
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:`,
]);
}),
@@ -206,8 +209,10 @@ export const customApiRouter = createTRPCRouter({
const loadRequests = Object.entries(resolved.definition.requests).filter(
([, request]) => request.kind === "query" && request.trigger === "load",
);
const entries = await Promise.all(
loadRequests.map(async ([requestId, request]) => {
const entries = await mapWithConcurrency(
loadRequests,
CUSTOM_WIDGET_USER_ITEM_CONCURRENCY_LIMIT,
async ([requestId, request]) => {
try {
const response = await executeRequest(ctx, resolved, { id: requestId, ...request }, {});
return [
@@ -237,12 +242,13 @@ export const customApiRouter = createTRPCRouter({
},
] as const;
}
}),
},
);
return {
type: "customJsx" as const,
template: resolved.definition.template,
canRefresh: ctx.session !== null,
data: Object.fromEntries(entries.map(([id, result]) => [id, result.data])),
status: Object.fromEntries(entries.map(([id, result]) => [id, result.status])),
options: resolved.configuration,
@@ -285,7 +291,7 @@ export const customApiRouter = createTRPCRouter({
}
const response = await executeRequest(ctx, resolved, request, input.params);
if (response.ok && request.invalidates?.length) {
invalidateCustomWidgetResponseCache(
await invalidateCustomWidgetResponseCache(
request.invalidates.flatMap((requestId) => [
`custom-jsx:${resolved.item.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${requestId}:`,
`custom-widget:options:${resolved.stored.id}:${getCustomWidgetCacheVersion(resolved.stored)}:${requestId}:`,
+3 -1
View File
@@ -13,7 +13,7 @@ import { ZodError } from "zod/v4";
import type { Session } from "@homarr/auth";
import { extractBaseUrlFromHeaders, FlattenError } from "@homarr/common";
import { userAgent } from "@homarr/common/server";
import { ipAddressFromHeaders, userAgent } from "@homarr/common/server";
import type { DeviceType } from "@homarr/common/server";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { db } from "@homarr/db";
@@ -43,6 +43,7 @@ interface ApiContext {
deviceType: DeviceType;
baseUrl?: `${string}://${string}`;
onboardingClaimToken?: string;
ipAddress?: string;
db: typeof db;
}
@@ -60,6 +61,7 @@ export const createTRPCContext = (opts: { headers: Headers; session: Session | n
session,
deviceType: userAgent(opts.headers).device.type,
baseUrl: extractBaseUrlFromHeaders(opts.headers),
ipAddress: ipAddressFromHeaders(opts.headers) ?? undefined,
onboardingClaimToken: getOnboardingClaimTokenFromCookieHeader(opts.headers.get("cookie")),
db,
};
+23
View File
@@ -0,0 +1,23 @@
export async function mapWithConcurrency<T, U>(
values: readonly T[],
concurrency: number,
mapper: (value: T, index: number) => Promise<U>,
): Promise<U[]> {
if (!Number.isSafeInteger(concurrency) || concurrency < 1) {
throw new Error("Concurrency must be a positive integer");
}
const results: U[] = [];
let nextIndex = 0;
const workerCount = Math.min(concurrency, values.length);
const workers = Array.from({ length: workerCount }, async () => {
while (nextIndex < values.length) {
const index = nextIndex;
nextIndex += 1;
results[index] = await mapper(values[index] as T, index);
}
});
await Promise.all(workers);
return results;
}
+1
View File
@@ -13,3 +13,4 @@ export * from "./theme";
export * from "./function";
export * from "./grid-algorithm";
export * from "./id";
export * from "./async";
@@ -24,6 +24,10 @@ export interface RenderSafeJsxOptions {
budgets?: SafeJsxBudgets;
}
export interface RenderCompiledSafeJsxOptions extends Omit<RenderSafeJsxOptions, "template"> {
root: AstNode;
}
export interface SafeJsxRenderResult {
node: ReactNode;
warnings: string[];
@@ -351,11 +355,23 @@ class Interpreter {
}
}
export function renderSafeJsx({ template, components, bindings, budgets }: RenderSafeJsxOptions): SafeJsxRenderResult {
export function compileSafeJsx(template: string): AstNode {
return parseCustomJsxTemplate(template);
}
export function renderCompiledSafeJsx({
root,
components,
bindings,
budgets,
}: RenderCompiledSafeJsxOptions): SafeJsxRenderResult {
const limits: EvaluationBudgets = { ...DEFAULT_BUDGETS, ...budgets };
for (const [name, value] of Object.entries(limits)) {
if (!Number.isSafeInteger(value) || value <= 0) throw new SafeJsxError(`Invalid interpreter budget: ${name}`);
}
const root = parseCustomJsxTemplate(template);
return new Interpreter(components, new Environment(bindings), limits).render(root);
}
export function renderSafeJsx({ template, ...options }: RenderSafeJsxOptions): SafeJsxRenderResult {
return renderCompiledSafeJsx({ ...options, root: compileSafeJsx(template) });
}
@@ -68,7 +68,7 @@ export function emitJsxElement(
child.type === "JSXExpressionContainer" ? asNode(child.expression, "JSX child expression") : null;
if (resolvedTag === "SubFetch" && expression?.type === "ArrowFunctionExpression") {
const callback = context.createCallback(expression, environment);
return (value: unknown) => context.renderCallback(callback, [value], depth + 1);
return (value: unknown, metadata: unknown) => context.renderCallback(callback, [value, metadata], depth + 1);
}
return context.evaluate(child, environment, depth + 1);
});
@@ -3,12 +3,14 @@ import { Component, useCallback, useEffect, useId, useMemo, useState } from "rea
import { Alert, Box, Stack, Text } from "@mantine/core";
import { IconAlertTriangle } from "@tabler/icons-react";
import { renderSafeJsx } from "../jsx/interpreter";
import { compileSafeJsx, renderCompiledSafeJsx } from "../jsx/interpreter";
import { CustomJsxInputsProvider } from "../jsx/runtime-components";
import type { WidgetInputType, WidgetInputValue } from "../jsx/runtime-components";
import type { CustomJsxRequestCapability } from "./types";
const EMPTY_RECORD: Record<string, never> = {};
const referenceIds = new WeakMap<object, number>();
let nextReferenceId = 1;
const methodColors: Readonly<Record<string, string>> = {
GET: "blue",
@@ -162,12 +164,27 @@ function CustomJsxRendererSession({
},
[inputTypes],
);
const compiled = useMemo(() => {
try {
return { root: compileSafeJsx(template), error: null };
} catch (error) {
return { root: null, error: error instanceof Error ? error : new Error(String(error)) };
}
}, [template]);
const rendered = useMemo(() => {
if (compiled.error || !compiled.root) {
return {
node: null,
warnings: [],
boundaryKey: `${template.length}:compile-error`,
error: compiled.error ?? new Error("Template compilation failed"),
};
}
try {
const bindings = { ...createBindings(data), status, options, inputs };
return {
...renderSafeJsx({ template, components, bindings }),
boundaryKey: createBoundaryKey(template, bindings),
...renderCompiledSafeJsx({ root: compiled.root, components, bindings }),
boundaryKey: createBoundaryKey(template, [data, status, options, inputs]),
error: null,
};
} catch (error) {
@@ -178,7 +195,7 @@ function CustomJsxRendererSession({
error: error instanceof Error ? error : new Error(String(error)),
};
}
}, [components, createBindings, data, inputs, options, status, template]);
}, [compiled, components, createBindings, data, inputs, options, status, template]);
useEffect(() => setParseErrors([]), [rendered.boundaryKey, template]);
const handleError = useCallback(
(error: Error) =>
@@ -228,9 +245,20 @@ function CustomJsxRendererSession({
);
}
function createBoundaryKey(template: string, bindings: Readonly<Record<string, unknown>>) {
let hash = 0;
const value = `${template}\0${JSON.stringify(bindings)}`;
for (let index = 0; index < value.length; index += 1) hash = (hash * 31 + value.charCodeAt(index)) | 0;
return `${template.length}:${hash}`;
function createBoundaryKey(template: string, values: readonly unknown[]) {
return `${template.length}:${values.map(referenceKey).join(":")}`;
}
function referenceKey(value: unknown): string {
if ((typeof value === "object" && value !== null) || typeof value === "function") {
const reference = value as object;
let id = referenceIds.get(reference);
if (!id) {
id = nextReferenceId;
nextReferenceId += 1;
referenceIds.set(reference, id);
}
return `r${id}`;
}
return `${typeof value}:${String(value)}`;
}
@@ -37,7 +37,7 @@ export function RefreshButton({ label, color = "gray", variant = "subtle", size
size={size as never}
onClick={() => void refresh()}
loading={loading}
disabled={(!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
disabled={!runtime.canRefresh || (!runtime.itemId && !runtime.previewSessionId) || runtime.isEditMode}
>
<IconRefresh size={16} />
</ActionIcon>
@@ -82,6 +82,7 @@ export interface CustomWidgetRuntimeValue {
previewSessionId?: string;
previewLiveActions?: boolean;
queriesDisabled?: boolean;
canRefresh?: boolean;
isEditMode: boolean;
requestCapabilities: readonly CustomJsxRequestCapability[];
port: CustomWidgetRuntimePort;
@@ -33,6 +33,7 @@ export const MAX_REQUEST_BODY_BYTES = 10 * 1024;
const REQUEST_TIMEOUT_MS = 10_000;
const MAX_QUERY_REDIRECTS = 3;
const MAX_RESPONSE_CACHE_ENTRIES = 1_000;
const MAX_RESPONSE_CACHE_BYTES = 64 * 1024 * 1024;
export const MAX_REQUEST_DURATION_MS = 45_000;
const TIMEOUT_ERROR_CODES = new Set(["UND_ERR_CONNECT_TIMEOUT", "UND_ERR_HEADERS_TIMEOUT", "UND_ERR_BODY_TIMEOUT"]);
const RESPONSE_TOO_LARGE_ERROR_CODE = "UND_ERR_RES_EXCEEDED_MAX_SIZE";
@@ -63,9 +64,10 @@ export interface CustomWidgetHttpResponse {
statusText: string;
data: unknown;
}
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse }>();
const cache = new Map<string, { expiresAt: number; response: CustomWidgetHttpResponse; size: number }>();
const inFlight = new Map<string, Promise<CustomWidgetHttpResponse>>();
let cacheEpoch = 0;
let cacheBytes = 0;
type RequestHopResult =
| { kind: "response"; response: CustomWidgetHttpResponse }
@@ -256,8 +258,12 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
const key = input.kind === "query" ? input.cacheKey : undefined;
if (!key) return performRequest(input);
const cached = cache.get(key);
if (cached && cached.expiresAt > Date.now()) return cached.response;
if (cached) cache.delete(key);
if (cached && cached.expiresAt > Date.now()) {
cache.delete(key);
cache.set(key, cached);
return cached.response;
}
if (cached) deleteCachedResponse(key);
const pending = inFlight.get(key);
if (pending) return pending;
const requestEpoch = cacheEpoch;
@@ -265,8 +271,12 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
request = performRequest(input)
.then((response) => {
if (response.ok && (input.cacheTtlSeconds ?? 0) > 0 && requestEpoch === cacheEpoch) {
pruneCache();
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response });
const size = Buffer.byteLength(JSON.stringify(response), "utf8");
if (size <= MAX_RESPONSE_CACHE_BYTES) {
pruneCache(size);
cache.set(key, { expiresAt: Date.now() + (input.cacheTtlSeconds ?? 0) * 1000, response, size });
cacheBytes += size;
}
}
return response;
})
@@ -280,15 +290,22 @@ export async function executeCustomWidgetRequest(input: CustomWidgetHttpRequest)
export function invalidateCustomWidgetResponseCache(prefixes: readonly string[]): void {
if (prefixes.length === 0) return;
cacheEpoch += 1;
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) cache.delete(key);
for (const key of cache.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) deleteCachedResponse(key);
for (const key of inFlight.keys()) if (prefixes.some((prefix) => key.startsWith(prefix))) inFlight.delete(key);
}
function pruneCache(): void {
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) cache.delete(key);
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES) {
function pruneCache(incomingSize: number): void {
for (const [key, entry] of cache) if (entry.expiresAt <= Date.now()) deleteCachedResponse(key);
while (cache.size >= MAX_RESPONSE_CACHE_ENTRIES || cacheBytes + incomingSize > MAX_RESPONSE_CACHE_BYTES) {
const key = cache.keys().next().value as string | undefined;
if (!key) return;
cache.delete(key);
deleteCachedResponse(key);
}
}
function deleteCachedResponse(key: string): void {
const cached = cache.get(key);
if (!cached) return;
cache.delete(key);
cacheBytes = Math.max(0, cacheBytes - cached.size);
}
@@ -1,5 +1,6 @@
import dayjs from "dayjs";
import { mapWithConcurrency } from "@homarr/common";
import { ResponseError } from "@homarr/common/server";
import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";
import { createLogger } from "@homarr/core/infrastructure/logs";
@@ -32,6 +33,7 @@ const UMAMI_CUSTOM_EVENT_TYPE = 2;
const UMAMI_EVENT_NAME_LIMIT = 5_000;
const UMAMI_EVENT_PAGE_SIZE = 5_000;
const UMAMI_EVENT_PAGE_MAX = 20;
const UMAMI_EVENT_REQUEST_CONCURRENCY = 4;
const logger = createLogger({ module: "umami-integration" });
@@ -245,8 +247,7 @@ export class UmamiIntegration extends Integration {
): Promise<UmamiEventSeries[]> {
const authHeaders = await this.getAuthHeadersAsync();
const { startAt, endAt, unit } = this.computeTimeRange(timeFrame);
const results: UmamiEventSeries[] = [];
for (const eventName of eventNames) {
return mapWithConcurrency(eventNames, UMAMI_EVENT_REQUEST_CONCURRENCY, async (eventName) => {
const dataPoints = await this.getWebsiteEventTimeSeriesAsync(
websiteId,
startAt,
@@ -255,9 +256,8 @@ export class UmamiIntegration extends Integration {
eventName,
authHeaders,
);
results.push({ eventName, dataPoints: dataPoints ?? [] });
}
return results;
return { eventName, dataPoints: dataPoints ?? [] };
});
}
private async getWebsiteEventMetricsAsync(
+174 -157
View File
@@ -16,9 +16,9 @@ import {
CopyButton,
Fieldset,
Group,
Modal,
Paper,
PasswordInput,
Popover,
Progress,
Select,
SimpleGrid,
@@ -160,6 +160,9 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
const sounds = useOnboardingSounds();
const [activeSection, setActiveSection] = useState<StudioSection>("essentials");
const [incompleteIntegrationConfirmationOpened, setIncompleteIntegrationConfirmationOpened] = useState(false);
const [confirmedIncompleteIntegrationSignature, setConfirmedIncompleteIntegrationSignature] = useState<string | null>(
null,
);
const [selectedLocale, setSelectedLocale] = useState(currentLocale);
const [serverOrigin, setServerOrigin] = useState(environment.serverOrigin);
const [urlMode, setUrlMode] = useState<UrlTemplateMode>("hostPort");
@@ -184,6 +187,7 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
const [isApplying, setIsApplying] = useState(false);
const [applyProgress, setApplyProgress] = useState(0);
const [applyMessage, setApplyMessage] = useState("");
const [applyError, setApplyError] = useState<string | null>(null);
const [appError, setAppError] = useState<string | null>(null);
const sectionHeadingRef = useRef<HTMLHeadingElement>(null);
const sectionButtonRefs = useRef<(HTMLButtonElement | null)[]>([]);
@@ -201,11 +205,7 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
retry: false,
refetchOnWindowFocus: false,
});
const complete = clientApi.onboard.completeSetup.useMutation({
onError(error) {
showErrorNotification({ title: t("review.errorTitle"), message: error.message });
},
});
const complete = clientApi.onboard.completeSetup.useMutation();
const dockerData = docker.data;
const discoveredIntegrations = dockerData?.integrations ?? emptyDiscoveredIntegrations;
const discoveredApps = dockerData?.apps ?? emptyDiscoveredApps;
@@ -234,6 +234,18 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
() => new Set(discoveredIntegrations.map((integration) => integration.kind)),
[discoveredIntegrations],
);
const incompleteIntegrationSignature = JSON.stringify(
drafts
.filter((draft) => !isIntegrationDraftComplete(draft))
.map((draft) => ({
id: draft.id,
hasUrl: draft.url.trim().length > 0,
secrets: draft.secrets.map((secret) => ({ kind: secret.kind, hasValue: secret.value.trim().length > 0 })),
})),
);
const hasIncompleteIntegrations = incompleteIntegrationSignature !== "[]";
const incompleteIntegrationsConfirmed =
hasIncompleteIntegrations && confirmedIncompleteIntegrationSignature === incompleteIntegrationSignature;
useEffect(() => {
if (!docker.data) return;
@@ -326,11 +338,30 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
if (next) selectSection(next.id);
};
const selectSection = (section: StudioSection) => {
const changeSection = (section: StudioSection) => {
if (section !== activeSection) sounds.swoosh();
setActiveSection(section);
};
const selectSection = (section: StudioSection) => {
if (
section === "review" &&
activeSection !== "review" &&
hasIncompleteIntegrations &&
!incompleteIntegrationsConfirmed
) {
setIncompleteIntegrationConfirmationOpened(true);
return;
}
changeSection(section);
};
const confirmReviewNavigation = () => {
setConfirmedIncompleteIntegrationSignature(incompleteIntegrationSignature);
setIncompleteIntegrationConfirmationOpened(false);
changeSection("review");
};
const handleSectionKeyDown = (event: KeyboardEvent<HTMLButtonElement>, index: number) => {
const nextIndex =
event.key === "Home"
@@ -368,7 +399,12 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
const applySetupAsync = async () => {
if (isApplying) return;
if (hasIncompleteIntegrations && !incompleteIntegrationsConfirmed) {
setIncompleteIntegrationConfirmationOpened(true);
return;
}
setIsApplying(true);
setApplyError(null);
setAppError(null);
setAppErrorSourceId(null);
setApplyProgress(5);
@@ -483,8 +519,14 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
setApplyMessage(t("review.progress.done"));
setApplyProgress(100);
await revalidatePathActionAsync("/init");
} catch {
} catch (error) {
let message = t("common.unknownError");
if (error instanceof Error && error.message.trim().length > 0) {
message = error.message;
}
sounds.error();
setApplyError(message);
showErrorNotification({ title: t("review.errorTitle"), message });
setApplyProgress(0);
setIsApplying(false);
}
@@ -570,10 +612,10 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
},
applyProgress,
applyMessage,
applyError,
appError,
appErrorSourceId,
};
const hasIncompleteIntegrations = drafts.some((draft) => !isIntegrationDraftComplete(draft));
const selectedAppWithoutAddress = discoveredApps.find(
(app) => selectedAppIds.includes(app.sourceId) && (discoveredAppUrls[app.sourceId] ?? "").trim().length === 0,
);
@@ -590,153 +632,122 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
}
setAppError(null);
setAppErrorSourceId(null);
if (hasIncompleteIntegrations) {
setIncompleteIntegrationConfirmationOpened(true);
} else {
move(1);
}
move(1);
} else {
move(1);
}
};
return (
<main
className={classes.page}
style={
{
"--studio-glow-color": primaryColor,
"--studio-secondary-glow-color": secondaryColor,
} as CSSProperties
}
>
<OnboardingBackdrop />
<div className={classes.shell}>
<Group className={classes.topbar} justify="center" mb="lg">
<OnboardingWordmark
primaryColor={primaryColor}
secondaryColor={secondaryColor.toLowerCase() === initialSecondaryColor ? undefined : secondaryColor}
/>
</Group>
<>
<Modal
opened={incompleteIntegrationConfirmationOpened}
onClose={() => setIncompleteIntegrationConfirmationOpened(false)}
title={t("connect.incompleteConfirmation")}
centered
>
<Stack gap="md">
<Text size="sm">{t("connect.incompleteConfirmation")}</Text>
<Group justify="flex-end" gap="xs">
<Button variant="default" onClick={() => setIncompleteIntegrationConfirmationOpened(false)}>
{tCommon("cancel")}
</Button>
<Button onClick={confirmReviewNavigation}>{tCommon("confirm")}</Button>
</Group>
</Stack>
</Modal>
<main
className={classes.page}
style={
{
"--studio-glow-color": primaryColor,
"--studio-secondary-glow-color": secondaryColor,
} as CSSProperties
}
>
<OnboardingBackdrop />
<div className={classes.shell}>
<Group className={classes.topbar} justify="center" mb="lg">
<OnboardingWordmark
primaryColor={primaryColor}
secondaryColor={secondaryColor.toLowerCase() === initialSecondaryColor ? undefined : secondaryColor}
/>
</Group>
<Paper className={classes.studio} radius="lg">
<div className={classes.studioGrid}>
<nav className={classes.rail} aria-label={t("navigationLabel")}>
<Timeline
active={activeIndex}
bulletSize={32}
lineWidth={2}
color={primaryColor}
className={classes.timeline}
classNames={{ itemBullet: classes.timelineBullet }}
>
{sectionDefinitions.map((section, index) => {
const Icon = section.icon;
const active = section.id === activeSection;
return (
<Timeline.Item
key={section.id}
bullet={<Icon size={16} aria-hidden />}
title={
<UnstyledButton
ref={(node) => {
sectionButtonRefs.current[index] = node;
}}
className={classes.timelineButton}
data-active={active}
onClick={() => selectSection(section.id)}
onKeyDown={(event) => handleSectionKeyDown(event, index)}
aria-label={`${t(`navigation.${section.id}`)} (${index + 1}/${sectionDefinitions.length})`}
aria-current={active ? "step" : undefined}
aria-controls="onboarding-studio-section"
tabIndex={active ? 0 : -1}
>
<Stack gap={0} align="flex-start">
<Text className={classes.timelineLabel} size="sm" fw={active ? 650 : 500}>
{t(`navigation.${section.id}`)}
</Text>
<Text className={classes.timelineLabel} size="xs" c="dimmed">
{index + 1} / {sectionDefinitions.length}
</Text>
</Stack>
</UnstyledButton>
}
/>
);
})}
</Timeline>
</nav>
<section id="onboarding-studio-section" className={classes.content} aria-labelledby="studio-section-title">
<div key={activeSection}>
<StudioSectionContent section={activeSection} {...sectionProps} />
</div>
<Group className={classes.stickyActions} justify="space-between" wrap="nowrap">
<Button
className={classes.backAction}
size="sm"
variant="default"
leftSection={<IconArrowLeft size={16} />}
aria-label={t("back")}
disabled={activeIndex === 0 || isApplying}
onClick={() => move(-1)}
<Paper className={classes.studio} radius="lg">
<div className={classes.studioGrid}>
<nav className={classes.rail} aria-label={t("navigationLabel")}>
<Timeline
active={activeIndex}
bulletSize={32}
lineWidth={2}
color={primaryColor}
className={classes.timeline}
classNames={{ itemBullet: classes.timelineBullet }}
>
{t("back")}
</Button>
{activeSection === "review" ? (
<Button size="sm" loading={isApplying} onClick={continueOnboarding}>
{t("buildBoard")}
</Button>
) : (
<Group className={classes.primaryActions} gap="xs" wrap="nowrap">
{activeSection === "connect" && hasIncompleteIntegrations ? (
<Popover
opened={incompleteIntegrationConfirmationOpened}
onDismiss={() => setIncompleteIntegrationConfirmationOpened(false)}
transitionProps={{ duration: 0 }}
position="top-end"
width={320}
shadow="md"
withArrow
trapFocus
>
<Popover.Target>
<Button
size="sm"
disabled={continueDisabled}
rightSection={<IconArrowRight size={16} />}
aria-haspopup="dialog"
aria-expanded={incompleteIntegrationConfirmationOpened}
onClick={() => setIncompleteIntegrationConfirmationOpened((opened) => !opened)}
{sectionDefinitions.map((section, index) => {
const Icon = section.icon;
const active = section.id === activeSection;
return (
<Timeline.Item
key={section.id}
bullet={<Icon size={16} aria-hidden />}
title={
<UnstyledButton
ref={(node) => {
sectionButtonRefs.current[index] = node;
}}
className={classes.timelineButton}
data-active={active}
onClick={() => selectSection(section.id)}
onKeyDown={(event) => handleSectionKeyDown(event, index)}
aria-label={`${t(`navigation.${section.id}`)} (${index + 1}/${sectionDefinitions.length})`}
aria-current={active ? "step" : undefined}
aria-controls="onboarding-studio-section"
tabIndex={active ? 0 : -1}
>
{t("continue")}
</Button>
</Popover.Target>
<Popover.Dropdown role="dialog" aria-label={t("connect.incompleteConfirmation")}>
<Stack gap="sm">
<Text size="sm">{t("connect.incompleteConfirmation")}</Text>
<Group justify="flex-end" gap="xs">
<Button
size="xs"
variant="default"
onClick={() => setIncompleteIntegrationConfirmationOpened(false)}
>
{tCommon("cancel")}
</Button>
<Button
size="xs"
onClick={() => {
setIncompleteIntegrationConfirmationOpened(false);
move(1);
}}
>
{tCommon("confirm")}
</Button>
</Group>
</Stack>
</Popover.Dropdown>
</Popover>
) : (
<Stack gap={0} align="flex-start">
<Text className={classes.timelineLabel} size="sm" fw={active ? 650 : 500}>
{t(`navigation.${section.id}`)}
</Text>
<Text className={classes.timelineLabel} size="xs" c="dimmed">
{index + 1} / {sectionDefinitions.length}
</Text>
</Stack>
</UnstyledButton>
}
/>
);
})}
</Timeline>
</nav>
<section
id="onboarding-studio-section"
className={classes.content}
aria-labelledby="studio-section-title"
>
<div key={activeSection}>
<StudioSectionContent section={activeSection} {...sectionProps} />
</div>
<Group className={classes.stickyActions} justify="space-between" wrap="nowrap">
<Button
className={classes.backAction}
size="sm"
variant="default"
leftSection={<IconArrowLeft size={16} />}
aria-label={t("back")}
disabled={activeIndex === 0 || isApplying}
onClick={() => move(-1)}
>
{t("back")}
</Button>
{activeSection === "review" ? (
<Button size="sm" loading={isApplying} onClick={continueOnboarding}>
{t("buildBoard")}
</Button>
) : (
<Group className={classes.primaryActions} gap="xs" wrap="nowrap">
<Button
size="sm"
disabled={continueDisabled}
@@ -745,15 +756,15 @@ export const SetupStudio = ({ environment, assistantConfiguration }: OnboardingS
>
{t("continue")}
</Button>
)}
</Group>
)}
</Group>
</section>
</div>
</Paper>
</div>
</main>
</Group>
)}
</Group>
</section>
</div>
</Paper>
</div>
</main>
</>
);
};
@@ -807,6 +818,7 @@ interface StudioSectionProps {
setRightSidebar: (value: boolean) => void;
applyProgress: number;
applyMessage: string;
applyError: string | null;
appError: string | null;
appErrorSourceId: string | null;
}
@@ -1920,6 +1932,11 @@ const Review = (props: StudioSectionProps) => {
</Stack>
</Paper>
) : null}
{props.applyError ? (
<Alert color="red" icon={<IconAlertCircle size={18} />} title={t("errorTitle")} role="alert">
{props.applyError}
</Alert>
) : null}
</Stack>
);
};
+2 -1
View File
@@ -2416,7 +2416,8 @@
"image": {
"loading": "Loading image",
"failed": "This image could not be loaded.",
"retry": "Try image again"
"retry": "Try image again",
"loadExternal": "Load external image from {host}"
},
"quoteSelection": "Quote",
"dismissQuote": "Remove quote",
@@ -1,16 +1,24 @@
import { Image, Marquee, SimpleGrid } from "@mantine/core";
import { splitToNChunks } from "@homarr/common";
import { integrationDefs } from "@homarr/definitions";
import classes from "./integration-marquee.module.css";
const iconGroups = splitToNChunks(
Object.values(integrationDefs)
.filter((integration) => integration.name !== "Mock")
.map((integration) => integration.iconUrl),
3,
);
const localIconPaths = [
"/images/apps/sonarr.svg",
"/images/apps/radarr.svg",
"/images/apps/lidarr.svg",
"/images/apps/readarr.svg",
"/images/apps/nextcloud.svg",
"/images/apps/truenas.svg",
"/images/apps/unraid-alt.svg",
"/images/apps/imdb.svg",
"/images/apps/lastfm.svg",
"/images/apps/tmdb.svg",
"/images/apps/the-tvdb.svg",
"/images/apps/vgmdb.svg",
];
const iconGroups = splitToNChunks(localIconPaths, 3);
const animationDuration = iconGroups.flat().length * 2;
export const IntegrationMarquee = ({ className }: { className?: string }) => (
@@ -36,7 +44,16 @@ export const IntegrationMarquee = ({ className }: { className?: string }) => (
classNames={{ content: classes.content }}
>
{icons.map((icon) => (
<Image key={`${icon}-${columnIndex}`} src={icon} alt="" fit="contain" w={52} h={52} />
<Image
key={`${icon}-${columnIndex}`}
src={icon}
alt=""
fit="contain"
w={52}
h={52}
loading="lazy"
decoding="async"
/>
))}
</Marquee>
))}
@@ -69,6 +69,7 @@ export default function CustomJsxDisplay({ data }: { data: Record<string, unknow
previewSessionId={previewSessionId}
previewLiveActions={data.previewLiveActions === true}
queriesDisabled={data.queriesDisabled === true}
canRefresh={data.canRefresh === true}
isEditMode={data.isEditMode === true}
requestCapabilities={capabilities}
setQueryState={publishQueryState}
@@ -21,6 +21,7 @@ interface WidgetDefinitionProviderProps {
previewSessionId?: string;
previewLiveActions?: boolean;
queriesDisabled?: boolean;
canRefresh?: boolean;
isEditMode?: boolean;
requestCapabilities?: readonly CustomJsxRequestCapability[];
setQueryState?(requestId: string, value: CustomWidgetPublishedQueryState | null): void;
@@ -170,6 +171,7 @@ export function WidgetDefinitionProvider(props: WidgetDefinitionProviderProps) {
previewSessionId={props.previewSessionId}
previewLiveActions={props.previewLiveActions}
queriesDisabled={props.queriesDisabled}
canRefresh={Boolean(props.previewSessionId) || props.canRefresh === true}
isEditMode={props.isEditMode ?? false}
requestCapabilities={props.requestCapabilities ?? []}
port={port}
@@ -1,7 +1,7 @@
"use client";
import type { ReactNode } from "react";
import { useEffect, useState } from "react";
import { useEffect, useRef, useState } from "react";
import {
Badge,
Box,
@@ -58,6 +58,10 @@ export default function MediaMissingWidget({
});
const data = getUsableWidgetQueryData(mediaQuery);
const [selectedTab, setSelectedTab] = useState<MediaMissingTab>(showMissing ? "missing" : "queued");
const tabScrollPositionsRef = useRef<Record<MediaMissingTab, { x: number; y: number }>>({
missing: { x: 0, y: 0 },
queued: { x: 0, y: 0 },
});
const activeTab = resolveMediaMissingTab(selectedTab, showMissing, showQueued);
useEffect(() => {
@@ -92,10 +96,18 @@ export default function MediaMissingWidget({
const tabLabel = (label: string, shown: number, total: number) => (isThin ? total : `${label} (${shown}/${total})`);
const renderPanel = (
tab: MediaMissingTab,
entries: { item: MissingMediaItem | QueuedMediaItem; integrationId: string }[],
emptyLabel: string,
) => (
<ScrollArea h="100%" scrollbarSize={4}>
<ScrollArea
h="100%"
scrollbarSize={4}
startScrollPosition={tabScrollPositionsRef.current[tab]}
onScrollPositionChange={(position) => {
tabScrollPositionsRef.current[tab] = position;
}}
>
<Box p="xs">
{entries.length === 0 ? (
<Text size="sm" c="dimmed" ta="center" py="md">
@@ -146,7 +158,7 @@ export default function MediaMissingWidget({
{tabLabel(t("tab.missing"), missing.length, missingCount)}
</Text>
</Group>
<Box h="calc(100% - 40px)">{renderPanel(missing, t("empty.missing"))}</Box>
<Box h="calc(100% - 40px)">{renderPanel("missing", missing, t("empty.missing"))}</Box>
</Paper>
)}
{showQueued && (
@@ -157,7 +169,7 @@ export default function MediaMissingWidget({
{tabLabel(t("tab.queued"), queued.length, queuedCount)}
</Text>
</Group>
<Box h="calc(100% - 40px)">{renderPanel(queued, t("empty.queued"))}</Box>
<Box h="calc(100% - 40px)">{renderPanel("queued", queued, t("empty.queued"))}</Box>
</Paper>
)}
</SimpleGrid>
@@ -181,12 +193,20 @@ export default function MediaMissingWidget({
</Group>
<Tabs.List grow>
{showMissing && (
<Tabs.Tab value="missing" px={isThin ? 6 : undefined} leftSection={<IconQuestionMark size="var(--mantine-font-size-sm)" />}>
<Tabs.Tab
value="missing"
px={isThin ? 6 : undefined}
leftSection={<IconQuestionMark size="var(--mantine-font-size-sm)" />}
>
{tabLabel(t("tab.missing"), missing.length, missingCount)}
</Tabs.Tab>
)}
{showQueued && (
<Tabs.Tab value="queued" px={isThin ? 6 : undefined} leftSection={<IconDownload size="var(--mantine-font-size-sm)" />}>
<Tabs.Tab
value="queued"
px={isThin ? 6 : undefined}
leftSection={<IconDownload size="var(--mantine-font-size-sm)" />}
>
{tabLabel(t("tab.queued"), queued.length, queuedCount)}
</Tabs.Tab>
)}
@@ -194,12 +214,12 @@ export default function MediaMissingWidget({
{showMissing && (
<Tabs.Panel value="missing" flex={1} style={{ overflow: "hidden" }}>
{activeTab === "missing" && renderPanel(missing, t("empty.missing"))}
{activeTab === "missing" && renderPanel("missing", missing, t("empty.missing"))}
</Tabs.Panel>
)}
{showQueued && (
<Tabs.Panel value="queued" flex={1} style={{ overflow: "hidden" }}>
{activeTab === "queued" && renderPanel(queued, t("empty.queued"))}
{activeTab === "queued" && renderPanel("queued", queued, t("empty.queued"))}
</Tabs.Panel>
)}
</Tabs>