enhance release v2 experience

This commit is contained in:
ajnart committed 2026-08-14 02:18:46 +02:00
1 parent 9b4970583e
commit ef2ed6c602
152 files changed
+7236 -764

No files matched your search

@@ -0,0 +1,30 @@
import { describe, expect, test } from "vitest";
import { getTrackedFeatureProperties } from "./analytics-properties";
describe("getTrackedFeatureProperties", () => {
test("keeps setup telemetry anonymous and strips configuration-shaped properties", () => {
expect(
getTrackedFeatureProperties(
"setup:widget-completed",
{
entryPoint: "board",
outcome: "completed",
elapsedMs: 1200,
hasBoardContext: true,
userId: "supplied-user",
url: "https://private.example",
recordId: "secret-id",
},
"session-user",
),
).toEqual({ entryPoint: "board", outcome: "completed", elapsedMs: 1200, hasBoardContext: true });
});
test("preserves the existing identified contract for non-setup events", () => {
expect(getTrackedFeatureProperties("theme-changed", { theme: "dark" }, "user-1")).toEqual({
theme: "dark",
userId: "user-1",
});
});
});
@@ -0,0 +1,22 @@
const setupPropertyKeys = new Set([
"entryPoint",
"intent",
"outcome",
"elapsedMs",
"hasBoardContext",
"canResolveInline",
]);
export const getTrackedFeatureProperties = (
feature: string,
properties: Record<string, unknown> | undefined,
userId: string,
) => {
if (!feature.startsWith("setup:")) return { ...properties, userId };
return Object.fromEntries(
Object.entries(properties ?? {}).filter(
([key, value]) => setupPropertyKeys.has(key) && ["string", "number", "boolean"].includes(typeof value),
),
);
};
+6 -4
View File
@@ -7,6 +7,7 @@ import { db } from "@homarr/db";
import { getServerSettingByKeyAsync } from "@homarr/db/queries";
import { createTRPCRouter, permissionRequiredProcedure, protectedProcedure } from "../trpc";
import { getTrackedFeatureProperties } from "./analytics-properties";
const getInstanceId = async (): Promise<string | null> => {
if (env.NO_EXTERNAL_CONNECTION) return null;
@@ -34,10 +35,11 @@ export const analyticsRouter = createTRPCRouter({
const instanceId = await getInstanceId();
if (!instanceId) return;
trackEvent(instanceId, `feature:${input.feature}`, {
...input.properties,
userId: ctx.session.user.id,
});
trackEvent(
instanceId,
`feature:${input.feature}`,
getTrackedFeatureProperties(input.feature, input.properties, ctx.session.user.id),
);
}),
heartbeat: protectedProcedure.mutation(async ({ ctx }) => {
+6 -4
View File
@@ -566,9 +566,11 @@ export const boardRouter = createTRPCRouter({
},
})
.input(boardCreateSchema)
.output(z.object({ boardId: z.string() }))
.output(z.object({ boardId: z.string(), name: z.string(), layoutId: z.string() }))
.mutation(async ({ ctx, input }) => {
const boardId = createId();
const mobileLayoutId = createId();
const baseLayoutId = createId();
const user = await ctx.db.query.users.findFirst({
where: eq(users.id, ctx.session.user.id),
@@ -594,7 +596,7 @@ export const boardRouter = createTRPCRouter({
});
createBoardCollection.layouts.push(
{
id: createId(),
id: mobileLayoutId,
name: "Mobile",
columnCount: 3,
leftGutterColumnCount: 0,
@@ -604,7 +606,7 @@ export const boardRouter = createTRPCRouter({
boardId,
},
{
id: createId(),
id: baseLayoutId,
name: "Base",
columnCount: input.columnCount,
leftGutterColumnCount: 0,
@@ -621,7 +623,7 @@ export const boardRouter = createTRPCRouter({
await ctx.db.update(users).set({ homeBoardId: boardId }).where(eq(users.id, ctx.session.user.id));
}
return { boardId };
return { boardId, name: input.name, layoutId: baseLayoutId };
}),
duplicateBoard: permissionRequiredProcedure
.requiresPermission("board-create")
@@ -0,0 +1,222 @@
import type { Database } from "@homarr/db";
import type { IntegrationKind } from "@homarr/definitions";
import {
buildDockerServiceUrlCandidates,
getIntegrationDefaultPort,
matchDockerService,
normalizeDockerServiceUrl,
} from "@homarr/definitions";
import { dockerContainersRequestHandler } from "@homarr/request-handler/docker";
export type DockerReconciliationState = "newRecognized" | "newApp" | "represented" | "linked" | "moved";
export type DockerReconciliationNextAction =
| "setupIntegration"
| "createApp"
| "viewRepresentation"
| "reviewIntegration";
export const getDockerReconciliationAsync = async (db: Database) => {
const [{ data, timestamp }, integrations, apps] = await Promise.all([
dockerContainersRequestHandler.handler({}).getDataAsync(),
db.query.integrations.findMany({
with: {
items: { columns: { itemId: true } },
secrets: { columns: { kind: true } },
},
}),
db.query.apps.findMany(),
]);
const containerNameCounts = new Map<string, number>();
for (const container of data.containers) {
const name = normalizeName(container.name);
containerNameCounts.set(name, (containerNameCounts.get(name) ?? 0) + 1);
}
const candidates = data.containers.map((container) => {
const match = matchDockerService(container);
const urlCandidates = buildDockerServiceUrlCandidates({
containerName: container.name,
endpointHost: container.host,
ports: container.ports,
preferredPort: match ? getIntegrationDefaultPort(match.kind) : undefined,
});
const candidateUrls = new Set(
urlCandidates.map(({ url }) => normalizeDockerServiceUrl(url)).filter((url) => url !== null),
);
const uniqueName = containerNameCounts.get(normalizeName(container.name)) === 1;
const sameKindIntegrations = match ? integrations.filter(({ kind }) => kind === match.kind) : [];
const exactIntegrationMatches = sameKindIntegrations.filter(({ url }) => {
const normalizedUrl = normalizeDockerServiceUrl(url);
return normalizedUrl ? candidateUrls.has(normalizedUrl) : false;
});
const nameIntegrationMatches = uniqueName
? sameKindIntegrations.filter(({ name }) => normalizeName(name) === normalizeName(container.name))
: [];
const exactIntegration = exactIntegrationMatches.length === 1 ? exactIntegrationMatches[0] : undefined;
const nameIntegration = nameIntegrationMatches.length === 1 ? nameIntegrationMatches[0] : undefined;
const integration = exactIntegration ?? nameIntegration;
const exactAppMatches = apps.filter(({ href }) => {
const normalizedUrl = normalizeDockerServiceUrl(href);
return normalizedUrl ? candidateUrls.has(normalizedUrl) : false;
});
const nameAppMatches = uniqueName
? apps.filter(({ name }) => normalizeName(name) === normalizeName(container.name))
: [];
const exactApp = exactAppMatches.length === 1 ? exactAppMatches[0] : undefined;
const nameApp = nameAppMatches.length === 1 ? nameAppMatches[0] : undefined;
const linkedApp = integration?.appId ? apps.find(({ id }) => id === integration.appId) : undefined;
const app = linkedApp ?? exactApp ?? nameApp;
const exactUrl = Boolean(exactIntegration || exactApp);
const linked = Boolean(integration?.appId && linkedApp);
const state: DockerReconciliationState = linked
? "linked"
: integration && !exactUrl
? "moved"
: integration || app
? "represented"
: match
? "newRecognized"
: "newApp";
return {
candidateKey: container.resourceId,
endpointId: container.endpointId,
endpointName: container.endpointName,
nativeId: container.id,
container,
match,
urlCandidates,
state,
nextAction: nextActionForState(state),
representation: {
integration: integration
? {
id: integration.id,
name: integration.name,
kind: integration.kind,
url: integration.url,
appId: integration.appId,
itemCount: integration.items.length,
configuredSecretKinds: integration.secrets.map(({ kind }) => kind),
}
: null,
app: app ? { id: app.id, name: app.name, href: app.href } : null,
signals: {
exactUrl,
nameMatch: Boolean(nameIntegration || nameApp),
linked,
ambiguous:
exactIntegrationMatches.length > 1 ||
nameIntegrationMatches.length > 1 ||
exactAppMatches.length > 1 ||
nameAppMatches.length > 1,
},
},
};
});
return { candidates, endpoints: data.endpoints, timestamp };
};
export const getDockerServiceHealthAsync = async (db: Database) => {
const reconciliation = await getDockerReconciliationAsync(db);
return {
timestamp: reconciliation.timestamp,
endpoints: reconciliation.endpoints.map((endpoint) => ({
key: `endpoint:${endpoint.id}`,
identity: { endpointId: endpoint.id, name: endpoint.name },
layer: "docker" as const,
status: endpoint.status,
nextAction: endpoint.status === "unavailable" ? ("checkEndpoint" as const) : ("none" as const),
})),
services: reconciliation.candidates.map((candidate) => ({
key: candidate.candidateKey,
identity: {
endpointId: candidate.endpointId,
nativeId: candidate.nativeId,
name: candidate.container.name,
integration: candidate.representation.integration,
app: candidate.representation.app,
},
layers: [
{ layer: "docker" as const, status: "available" as const, nextAction: "none" as const },
{
layer: "integrationConfiguration" as const,
status: integrationHealthStatus(
candidate.state,
candidate.match?.kind,
Boolean(candidate.representation.integration),
),
nextAction:
candidate.state === "moved"
? ("reviewIntegration" as const)
: candidate.state === "newRecognized"
? ("setupIntegration" as const)
: ("none" as const),
},
{
layer: "authentication" as const,
status: "notObserved" as const,
nextAction: candidate.representation.integration
? ("testConnection" as const)
: candidate.match
? ("setupIntegration" as const)
: ("none" as const),
},
{
layer: "apiRequest" as const,
status: "notObserved" as const,
nextAction: candidate.representation.integration
? ("openIntegrationDiagnostics" as const)
: ("none" as const),
},
{
layer: "appRepresentation" as const,
status: candidate.representation.app ? ("linked" as const) : ("missing" as const),
nextAction: candidate.representation.app ? ("none" as const) : ("createApp" as const),
},
{
layer: "widgetConfiguration" as const,
status: candidate.representation.integration
? candidate.representation.integration.itemCount > 0
? ("linked" as const)
: ("unused" as const)
: ("notApplicable" as const),
nextAction:
candidate.representation.integration && candidate.representation.integration.itemCount === 0
? ("addWidget" as const)
: ("none" as const),
},
{
layer: "widgetQuery" as const,
status: "notObserved" as const,
nextAction:
candidate.representation.integration && candidate.representation.integration.itemCount > 0
? ("openBoard" as const)
: ("none" as const),
},
],
status: candidate.state,
nextAction: candidate.nextAction,
})),
};
};
const normalizeName = (value: string) => value.trim().toLowerCase();
const nextActionForState = (state: DockerReconciliationState): DockerReconciliationNextAction => {
if (state === "newRecognized") return "setupIntegration";
if (state === "newApp") return "createApp";
if (state === "moved") return "reviewIntegration";
return "viewRepresentation";
};
const integrationHealthStatus = (
state: DockerReconciliationState,
kind: IntegrationKind | undefined,
hasIntegration: boolean,
) => {
if (!kind) return "notApplicable" as const;
if (state === "moved") return "changed" as const;
return hasIntegration ? ("configured" as const) : ("missing" as const);
};
+75 -70
View File
@@ -2,19 +2,33 @@ import { TRPCError } from "@trpc/server";
import { observable } from "@trpc/server/observable";
import { z } from "zod/v4";
import type { Container, ContainerState, Docker, Port } from "@homarr/docker";
import { DockerSingleton } from "@homarr/docker";
import type { ContainerState, DockerContainerTarget, Port } from "@homarr/docker";
import {
dockerContainersRequestHandler,
findDockerContainerAsync,
getContainerLogsAsync,
hasDockerEndpointCapability,
streamContainerLogsAsync,
} from "@homarr/request-handler/docker";
import { dockerMiddleware } from "../../middlewares/docker";
import { createTRPCRouter, permissionRequiredProcedure } from "../../trpc";
import { throwIfDockerOperationsFailed } from "./docker-operation-results";
import { getDockerReconciliationAsync, getDockerServiceHealthAsync } from "./docker-reconciliation";
const dockerContainerTargetSchema = z.object({
endpointId: z.string().min(1),
id: z.string().min(1),
});
export const dockerRouter = createTRPCRouter({
reconcileServices: permissionRequiredProcedure
.requiresPermission("admin")
.concat(dockerMiddleware())
.query(async ({ ctx }) => await getDockerReconciliationAsync(ctx.db)),
getServiceHealth: permissionRequiredProcedure
.requiresPermission("admin")
.concat(dockerMiddleware())
.query(async ({ ctx }) => await getDockerServiceHealthAsync(ctx.db)),
getContainers: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
@@ -31,7 +45,8 @@ export const dockerRouter = createTRPCRouter({
const { data, timestamp } = result;
return {
containers: data satisfies DockerContainer[],
containers: data.containers satisfies DockerContainer[],
endpoints: data.endpoints,
timestamp,
};
}),
@@ -40,58 +55,39 @@ export const dockerRouter = createTRPCRouter({
.meta({
mcp: {
enabled: true,
description: "Start Docker containers. REQUIRED: ids (array of container ID strings from docker_getContainers)",
description: "Start Docker containers. REQUIRED: targets (endpointId and id pairs from docker_getContainers)",
},
})
.concat(dockerMiddleware())
.input(z.object({ ids: z.array(z.string()) }))
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.mutation(async ({ input }) => {
const results = await Promise.allSettled(
input.ids.map(async (id) => {
const container = await getContainerOrThrowAsync(id);
await container.start();
}),
);
throwIfDockerOperationsFailed(results);
return await performDockerContainerActionsAsync(input.targets, "start");
}),
stopAll: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description: "Stop Docker containers. REQUIRED: ids (array of container ID strings from docker_getContainers)",
description: "Stop Docker containers. REQUIRED: targets (endpointId and id pairs from docker_getContainers)",
},
})
.concat(dockerMiddleware())
.input(z.object({ ids: z.array(z.string()) }))
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.mutation(async ({ input }) => {
const results = await Promise.allSettled(
input.ids.map(async (id) => {
const container = await getContainerOrThrowAsync(id);
await container.stop();
}),
);
throwIfDockerOperationsFailed(results);
return await performDockerContainerActionsAsync(input.targets, "stop");
}),
restartAll: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description:
"Restart Docker containers. REQUIRED: ids (array of container ID strings from docker_getContainers)",
description: "Restart Docker containers. REQUIRED: targets (endpointId and id pairs from docker_getContainers)",
},
})
.concat(dockerMiddleware())
.input(z.object({ ids: z.array(z.string()) }))
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.mutation(async ({ input }) => {
const results = await Promise.allSettled(
input.ids.map(async (id) => {
const container = await getContainerOrThrowAsync(id);
await container.restart();
}),
);
throwIfDockerOperationsFailed(results);
return await performDockerContainerActionsAsync(input.targets, "restart");
}),
removeAll: permissionRequiredProcedure
.requiresPermission("admin")
@@ -99,19 +95,13 @@ export const dockerRouter = createTRPCRouter({
mcp: {
enabled: true,
description:
"Remove/delete Docker containers. REQUIRED: ids (array of container ID strings from docker_getContainers)",
"Remove/delete Docker containers. REQUIRED: targets (endpointId and id pairs from docker_getContainers)",
},
})
.concat(dockerMiddleware())
.input(z.object({ ids: z.array(z.string()) }))
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.mutation(async ({ input }) => {
const results = await Promise.allSettled(
input.ids.map(async (id) => {
const container = await getContainerOrThrowAsync(id);
await container.remove();
}),
);
throwIfDockerOperationsFailed(results);
return await performDockerContainerActionsAsync(input.targets, "remove");
}),
logs: permissionRequiredProcedure
.requiresPermission("admin")
@@ -119,18 +109,19 @@ export const dockerRouter = createTRPCRouter({
mcp: {
enabled: true,
description:
"Fetch logs from a Docker container. REQUIRED: id (container ID from docker_getContainers). OPTIONAL: tail (number 1-1000, default 200)",
"Fetch logs from a Docker container. REQUIRED: endpointId and id from docker_getContainers. OPTIONAL: tail (number 1-1000, default 200)",
},
})
.concat(dockerMiddleware())
.input(
z.object({
id: z.string(),
...dockerContainerTargetSchema.shape,
tail: z.number().min(1).max(1000).optional(),
}),
)
.query(async ({ input }) => {
const logs = await getContainerLogsAsync(input.id, input.tail ?? 200);
assertDockerEndpointCapability(input.endpointId, "logs");
const logs = await getContainerLogsAsync(input, input.tail ?? 200);
if (!logs) {
throw new TRPCError({
@@ -148,11 +139,12 @@ export const dockerRouter = createTRPCRouter({
.concat(dockerMiddleware())
.input(
z.object({
id: z.string(),
...dockerContainerTargetSchema.shape,
tail: z.number().min(1).max(1000).optional(),
}),
)
.subscription(({ input }) => {
assertDockerEndpointCapability(input.endpointId, "logs");
return observable<string>((emit) => {
let cleanupFn: (() => void) | undefined;
let isSubscribed = true;
@@ -160,7 +152,7 @@ export const dockerRouter = createTRPCRouter({
const initializeStreamAsync = async () => {
try {
cleanupFn = await streamContainerLogsAsync(
input.id,
input,
input.tail ?? 200,
(data) => {
if (isSubscribed) {
@@ -200,36 +192,49 @@ export const dockerRouter = createTRPCRouter({
}),
});
const getContainerOrDefaultAsync = async (instance: Docker, id: string) => {
const container = instance.getContainer(id);
type DockerContainerAction = "start" | "stop" | "restart" | "remove";
return await new Promise<Container | null>((resolve) => {
container.inspect((err, data) => {
if (err || !data) {
resolve(null);
} else {
resolve(container);
export const performDockerContainerActionsAsync = async (
targets: DockerContainerTarget[],
action: DockerContainerAction,
) =>
await Promise.all(
targets.map(async (target) => {
try {
const capability = action === "remove" ? "remove" : "lifecycle";
if (!hasDockerEndpointCapability(target.endpointId, capability)) {
return { target, success: false as const, error: `Endpoint does not permit ${capability} actions` };
}
const container = await findDockerContainerAsync(target, capability);
if (!container) return { target, success: false as const, error: "Container not found" };
if (action === "start") await container.start();
else if (action === "stop") await container.stop();
else if (action === "restart") await container.restart();
else await container.remove();
return { target, success: true as const };
} catch (error) {
return {
target,
success: false as const,
error: error instanceof Error ? error.message : "Docker action failed",
};
}
});
});
};
}),
);
const getContainerOrThrowAsync = async (id: string) => {
const dockerInstances = DockerSingleton.getInstances();
const containers = await Promise.all(dockerInstances.map(({ instance }) => getContainerOrDefaultAsync(instance, id)));
const foundContainer = containers.find((container) => container) ?? null;
if (!foundContainer) {
throw new TRPCError({
code: "NOT_FOUND",
message: "Container not found",
});
}
return foundContainer;
const assertDockerEndpointCapability = (
endpointId: string,
capability: "inventory" | "logs" | "lifecycle" | "remove",
) => {
if (hasDockerEndpointCapability(endpointId, capability)) return;
throw new TRPCError({ code: "FORBIDDEN", message: `Docker endpoint does not permit ${capability} access` });
};
interface DockerContainer {
endpointId: string;
endpointName: string;
resourceId: string;
name: string;
id: string;
host: string;
@@ -368,6 +368,16 @@ export const integrationRouter = createTRPCRouter({
kind: input.kind,
url: input.url,
});
return {
integration: {
id: integrationId,
name: input.name,
kind: input.kind,
url: input.url,
},
appId,
};
}),
update: protectedProcedure.input(integrationUpdateSchema).mutation(async ({ ctx, input }) => {
await throwIfActionForbiddenAsync(ctx, eq(integrations.id, input.id), "full");
@@ -0,0 +1,90 @@
import { KubeConfig } from "@kubernetes/client-node";
import { describe, expect, test, vi } from "vitest";
import { KubernetesClientRegistry, KubernetesContextNotFoundError } from "./kubernetes-client";
const createRegistry = () => {
const kubeConfig = new KubeConfig();
const contextNames = ["home", "remote", "metrics-degraded"];
kubeConfig.loadFromOptions({
clusters: contextNames.map((name) => ({ name, server: `https://${name}.example` })),
users: contextNames.map((name) => ({ name, token: `${name}-token` })),
contexts: contextNames.map((name) => ({ name, cluster: name, user: name })),
currentContext: "home",
});
return new KubernetesClientRegistry(kubeConfig);
};
describe("KubernetesClientRegistry", () => {
test("isolates duplicate resource names by context", async () => {
const registry = createRegistry();
const home = registry.getClient("home");
const remote = registry.getClient("remote");
vi.spyOn(home.coreApi, "listNamespace").mockResolvedValue({ items: [{ metadata: { name: "default" } }] } as never);
vi.spyOn(remote.coreApi, "listNamespace").mockResolvedValue({
items: [{ metadata: { name: "default" } }],
} as never);
const [homeNamespaces, remoteNamespaces] = await Promise.all([
home.coreApi.listNamespace(),
remote.coreApi.listNamespace(),
]);
expect(homeNamespaces.items[0]?.metadata?.name).toBe("default");
expect(remoteNamespaces.items[0]?.metadata?.name).toBe("default");
expect(home).not.toBe(remote);
expect(home.kubeConfig.getCurrentContext()).toBe("home");
expect(remote.kubeConfig.getCurrentContext()).toBe("remote");
});
test("lists unavailable and metrics-degraded contexts without failing healthy contexts", async () => {
const registry = createRegistry();
for (const contextId of ["home", "remote", "metrics-degraded"]) {
const client = registry.getClient(contextId);
vi.spyOn(client.versionApi, "getCode").mockResolvedValue({} as never);
vi.spyOn(client.metricsApi, "getNodeMetrics").mockResolvedValue({ items: [] } as never);
}
registry.getClient("remote").versionApi.getCode = vi.fn().mockRejectedValue(new Error("offline"));
registry.getClient("metrics-degraded").metricsApi.getNodeMetrics = vi
.fn()
.mockRejectedValue(new Error("no metrics"));
const result = await registry.getContextsAsync();
expect(result.defaultContextId).toBe("home");
expect(result.contexts).toEqual([
{ contextId: "home", name: "home", status: "available", metricsStatus: "available", isDefault: true },
{ contextId: "remote", name: "remote", status: "unavailable", metricsStatus: "unknown", isDefault: false },
{
contextId: "metrics-degraded",
name: "metrics-degraded",
status: "degraded",
metricsStatus: "unavailable",
isDefault: false,
},
]);
});
test("rejects unknown context IDs", () => {
expect(() => createRegistry().getClient("missing")).toThrow(KubernetesContextNotFoundError);
});
test("uses the first configured context when current-context is empty", async () => {
const kubeConfig = new KubeConfig();
kubeConfig.loadFromOptions({
clusters: [{ name: "first", server: "https://first.example" }],
users: [{ name: "first", token: "token" }],
contexts: [{ name: "first", cluster: "first", user: "first" }],
currentContext: "",
});
const registry = new KubernetesClientRegistry(kubeConfig);
const client = registry.getClient("first");
vi.spyOn(client.versionApi, "getCode").mockResolvedValue({} as never);
vi.spyOn(client.metricsApi, "getNodeMetrics").mockResolvedValue({ items: [] } as never);
const result = await registry.getContextsAsync();
expect(result.defaultContextId).toBe("first");
expect(result.contexts[0]).toEqual(expect.objectContaining({ contextId: "first", isDefault: true }));
});
});
@@ -3,69 +3,132 @@ import { CoreV1Api, KubeConfig, Metrics, NetworkingV1Api, VersionApi } from "@ku
import { env } from "../../env";
export interface KubernetesContextStatus {
contextId: string;
name: string;
status: "available" | "degraded" | "unavailable";
metricsStatus: "available" | "unavailable" | "unknown";
isDefault: boolean;
}
export class KubernetesClient {
private static instance: KubernetesClient | null = null;
private static registry: KubernetesClientRegistry | null = null;
public kubeConfig: KubeConfig;
public coreApi: CoreV1Api;
public networkingApi: NetworkingV1Api;
public metricsApi: Metrics;
public versionApi: VersionApi;
private constructor() {
this.kubeConfig = new KubeConfig();
if (process.env.NODE_ENV === "development") {
this.kubeConfig.loadFromDefault();
} else {
this.kubeConfig.loadFromCluster();
const currentCluster = this.kubeConfig.getCurrentCluster();
if (!currentCluster) throw new Error("No cluster configuration found");
const token = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8");
const caData = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt", "utf8");
const clusterWithCA = {
...currentCluster,
name: `${currentCluster.name}-service-account`,
caData,
};
const serviceAccountUser = {
name: env.KUBERNETES_SERVICE_ACCOUNT_NAME ?? "default-sa",
token,
};
this.kubeConfig.clusters = [];
this.kubeConfig.users = [];
this.kubeConfig.addCluster(clusterWithCA);
this.kubeConfig.addUser(serviceAccountUser);
const currentContext = this.kubeConfig.getCurrentContext();
const originalContext = this.kubeConfig.getContextObject(currentContext);
if (!originalContext) throw new Error("No context found");
const updatedContext = {
...originalContext,
name: `${originalContext.name}-service-account`,
cluster: clusterWithCA.name,
user: serviceAccountUser.name,
};
this.kubeConfig.contexts = [];
this.kubeConfig.addContext(updatedContext);
this.kubeConfig.setCurrentContext(updatedContext.name);
}
this.coreApi = this.kubeConfig.makeApiClient(CoreV1Api);
this.networkingApi = this.kubeConfig.makeApiClient(NetworkingV1Api);
this.metricsApi = new Metrics(this.kubeConfig);
this.versionApi = this.kubeConfig.makeApiClient(VersionApi);
public constructor(kubeConfig: KubeConfig) {
this.kubeConfig = kubeConfig;
this.coreApi = kubeConfig.makeApiClient(CoreV1Api);
this.networkingApi = kubeConfig.makeApiClient(NetworkingV1Api);
this.metricsApi = new Metrics(kubeConfig);
this.versionApi = kubeConfig.makeApiClient(VersionApi);
}
public static getInstance(): KubernetesClient {
KubernetesClient.instance ??= new KubernetesClient();
return KubernetesClient.instance;
public static getInstance(contextId: string): KubernetesClient {
return KubernetesClient.getRegistry().getClient(contextId);
}
public static async getContextsAsync() {
return await KubernetesClient.getRegistry().getContextsAsync();
}
private static getRegistry() {
KubernetesClient.registry ??= new KubernetesClientRegistry(loadKubeConfig());
return KubernetesClient.registry;
}
}
export class KubernetesClientRegistry {
private readonly clients = new Map<string, KubernetesClient>();
private readonly defaultContextId: string;
public constructor(kubeConfig: KubeConfig) {
const defaultContextId = kubeConfig.getCurrentContext() || kubeConfig.contexts[0]?.name;
if (!defaultContextId) throw new Error("No Kubernetes context is configured");
this.defaultContextId = defaultContextId;
for (const context of kubeConfig.contexts) {
const contextConfig = new KubeConfig();
contextConfig.loadFromOptions({
clusters: kubeConfig.clusters,
users: kubeConfig.users,
contexts: kubeConfig.contexts,
currentContext: context.name,
});
this.clients.set(context.name, new KubernetesClient(contextConfig));
}
}
public getClient(contextId: string) {
const client = this.clients.get(contextId);
if (!client) throw new KubernetesContextNotFoundError(contextId);
return client;
}
public async getContextsAsync() {
const contexts = await Promise.all(
[...this.clients.entries()].map(async ([contextId, client]): Promise<KubernetesContextStatus> => {
const [api, metrics] = await Promise.allSettled([
client.versionApi.getCode(),
client.metricsApi.getNodeMetrics(),
]);
const status =
api.status === "rejected" ? "unavailable" : metrics.status === "rejected" ? "degraded" : "available";
return {
contextId,
name: contextId,
status,
metricsStatus:
api.status === "rejected" ? "unknown" : metrics.status === "rejected" ? "unavailable" : "available",
isDefault: contextId === this.defaultContextId,
};
}),
);
return { contexts, defaultContextId: this.defaultContextId };
}
}
export class KubernetesContextNotFoundError extends Error {
public constructor(contextId: string) {
super(`Kubernetes context '${contextId}' was not found`);
}
}
const loadKubeConfig = () => {
const kubeConfig = new KubeConfig();
if (process.env.NODE_ENV === "development" || process.env.KUBECONFIG) {
kubeConfig.loadFromDefault();
return kubeConfig;
}
kubeConfig.loadFromCluster();
const currentCluster = kubeConfig.getCurrentCluster();
if (!currentCluster) throw new Error("No cluster configuration found");
const token = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/token", "utf8");
const caData = fs.readFileSync("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt", "utf8");
const clusterWithCA = { ...currentCluster, name: `${currentCluster.name}-service-account`, caData };
const serviceAccountUser = { name: env.KUBERNETES_SERVICE_ACCOUNT_NAME ?? "default-sa", token };
const currentContext = kubeConfig.getContextObject(kubeConfig.getCurrentContext());
if (!currentContext) throw new Error("No context found");
const updatedContext = {
...currentContext,
name: `${currentContext.name}-service-account`,
cluster: clusterWithCA.name,
user: serviceAccountUser.name,
};
kubeConfig.loadFromOptions({
clusters: [clusterWithCA],
users: [serviceAccountUser],
contexts: [updatedContext],
currentContext: updatedContext.name,
});
return kubeConfig;
};
@@ -0,0 +1,17 @@
import { TRPCError } from "@trpc/server";
import { z } from "zod/v4";
import { KubernetesClient, KubernetesContextNotFoundError } from "./kubernetes-client";
export const kubernetesContextInput = z.object({ contextId: z.string().min(1) });
export const getKubernetesClient = (contextId: string) => {
try {
return KubernetesClient.getInstance(contextId);
} catch (error) {
if (error instanceof KubernetesContextNotFoundError) {
throw new TRPCError({ code: "NOT_FOUND", message: error.message });
}
throw error;
}
};
@@ -0,0 +1,13 @@
import { describe, expect, test } from "vitest";
import { calculateResourcePercentage } from "./resource-percentage";
describe("calculateResourcePercentage", () => {
test("calculates a rounded percentage", () => {
expect(calculateResourcePercentage(1, 3)).toBe(33.33);
});
test("returns zero when no capacity is available", () => {
expect(calculateResourcePercentage(1, 0)).toBe(0);
});
});
@@ -0,0 +1,2 @@
export const calculateResourcePercentage = (used: number, available: number) =>
available > 0 ? Number(((used / available) * 100).toFixed(2)) : 0;
@@ -5,7 +5,8 @@ import type { ClusterResourceCount, KubernetesCluster } from "@homarr/definition
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
import { calculateResourcePercentage } from "../resource-percentage";
import { CpuResourceParser } from "../resource-parser/cpu-resource-parser";
import { MemoryResourceParser } from "../resource-parser/memory-resource-parser";
@@ -13,14 +14,17 @@ export const clusterRouter = createTRPCRouter({
getCluster: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesCluster> => {
const { coreApi, metricsApi, versionApi, kubeConfig } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesCluster> => {
const { coreApi, metricsApi, versionApi, kubeConfig } = getKubernetesClient(input.contextId);
try {
const versionInfo = await versionApi.getCode();
const nodes = await coreApi.listNode();
const nodeMetricsClient = await metricsApi.getNodeMetrics();
const listPodForAllNamespaces = await coreApi.listPodForAllNamespaces();
const [versionInfo, nodes, listPodForAllNamespaces, nodeMetricsClient] = await Promise.all([
versionApi.getCode(),
coreApi.listNode(),
coreApi.listPodForAllNamespaces(),
metricsApi.getNodeMetrics().catch(() => null),
]);
let totalCPUCapacity = 0;
let totalCPUAllocatable = 0;
@@ -48,7 +52,7 @@ export const clusterRouter = createTRPCRouter({
totalMemoryAllocatable += memoryAllocatable;
const nodeName = node.metadata?.name;
const nodeMetric = nodeMetricsClient.items.find((metric) => metric.metadata.name === nodeName);
const nodeMetric = nodeMetricsClient?.items.find((metric) => metric.metadata.name === nodeName);
if (nodeMetric) {
const cpuUsage = cpuResourceParser.parse(nodeMetric.usage.cpu);
totalCPUUsage += cpuUsage;
@@ -61,13 +65,11 @@ export const clusterRouter = createTRPCRouter({
const reservedCPU = totalCPUCapacity - totalCPUAllocatable;
const reservedMemory = totalMemoryCapacity - totalMemoryAllocatable;
const reservedCPUPercentage = (reservedCPU / totalCPUCapacity) * 100;
const reservedMemoryPercentage = (reservedMemory / totalMemoryCapacity) * 100;
const usagePercentageAllocatable = (totalCPUUsage / totalCPUAllocatable) * 100;
const usagePercentageMemoryAllocatable = (totalMemoryUsage / totalMemoryAllocatable) * 100;
const usedPodsPercentage = (listPodForAllNamespaces.items.length / totalCapacityPods) * 100;
const reservedCPUPercentage = calculateResourcePercentage(reservedCPU, totalCPUCapacity);
const reservedMemoryPercentage = calculateResourcePercentage(reservedMemory, totalMemoryCapacity);
const usagePercentageAllocatable = calculateResourcePercentage(totalCPUUsage, totalCPUAllocatable);
const usagePercentageMemoryAllocatable = calculateResourcePercentage(totalMemoryUsage, totalMemoryAllocatable);
const usedPodsPercentage = calculateResourcePercentage(listPodForAllNamespaces.items.length, totalCapacityPods);
return {
name: kubeConfig.getCurrentContext(),
@@ -75,50 +77,59 @@ export const clusterRouter = createTRPCRouter({
kubernetesVersion: versionInfo.gitVersion,
architecture: versionInfo.platform,
nodeCount: nodes.items.length,
metricsAvailable: nodeMetricsClient !== null,
capacity: [
{
type: "CPU",
resourcesStats: [
{
percentageValue: Number(reservedCPUPercentage.toFixed(2)),
percentageValue: reservedCPUPercentage,
type: "Reserved",
capacityUnit: "Cores",
usedValue: Number(reservedCPU.toFixed(2)),
maxUsedValue: Number(totalCPUCapacity.toFixed(2)),
},
{
percentageValue: Number(usagePercentageAllocatable.toFixed(2)),
type: "Used",
capacityUnit: "Cores",
usedValue: Number(totalCPUUsage.toFixed(2)),
maxUsedValue: Number(totalCPUAllocatable.toFixed(2)),
},
...(nodeMetricsClient
? [
{
percentageValue: usagePercentageAllocatable,
type: "Used" as const,
capacityUnit: "Cores",
usedValue: Number(totalCPUUsage.toFixed(2)),
maxUsedValue: Number(totalCPUAllocatable.toFixed(2)),
},
]
: []),
],
},
{
type: "Memory",
resourcesStats: [
{
percentageValue: Number(reservedMemoryPercentage.toFixed(2)),
percentageValue: reservedMemoryPercentage,
type: "Reserved",
capacityUnit: "GiB",
usedValue: Number(reservedMemory.toFixed(2)),
maxUsedValue: Number(totalMemoryCapacity.toFixed(2)),
},
{
percentageValue: Number(usagePercentageMemoryAllocatable.toFixed(2)),
type: "Used",
capacityUnit: "GiB",
usedValue: Number(totalMemoryUsage.toFixed(2)),
maxUsedValue: Number(totalMemoryAllocatable.toFixed(2)),
},
...(nodeMetricsClient
? [
{
percentageValue: usagePercentageMemoryAllocatable,
type: "Used" as const,
capacityUnit: "GiB",
usedValue: Number(totalMemoryUsage.toFixed(2)),
maxUsedValue: Number(totalMemoryAllocatable.toFixed(2)),
},
]
: []),
],
},
{
type: "Pods",
resourcesStats: [
{
percentageValue: Number(usedPodsPercentage.toFixed(2)),
percentageValue: usedPodsPercentage,
type: "Used",
usedValue: listPodForAllNamespaces.items.length,
maxUsedValue: totalCapacityPods,
@@ -137,8 +148,10 @@ export const clusterRouter = createTRPCRouter({
}),
getClusterResourceCounts: permissionRequiredProcedure
.requiresPermission("admin")
.query(async (): Promise<ClusterResourceCount[]> => {
const { coreApi, networkingApi } = KubernetesClient.getInstance();
.concat(kubernetesMiddleware())
.input(kubernetesContextInput)
.query(async ({ input }): Promise<ClusterResourceCount[]> => {
const { coreApi, networkingApi } = getKubernetesClient(input.contextId);
try {
const [pods, ingresses, services, configMaps, namespaces, nodes, secrets, volumes] = await Promise.all([
@@ -4,14 +4,15 @@ import type { KubernetesBaseResource } from "@homarr/definitions";
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
export const configMapsRouter = createTRPCRouter({
getConfigMaps: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesBaseResource[]> => {
const { coreApi } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesBaseResource[]> => {
const { coreApi } = getKubernetesClient(input.contextId);
try {
const configMaps = await coreApi.listConfigMapForAllNamespaces();
@@ -0,0 +1,10 @@
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
export const contextsRouter = createTRPCRouter({
getContexts: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async () => await KubernetesClient.getContextsAsync()),
});
@@ -5,14 +5,15 @@ import type { KubernetesIngress, KubernetesIngressPath, KubernetesIngressRuleAnd
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
export const ingressesRouter = createTRPCRouter({
getIngresses: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesIngress[]> => {
const { networkingApi } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesIngress[]> => {
const { networkingApi } = getKubernetesClient(input.contextId);
try {
const ingresses = await networkingApi.listIngressForAllNamespaces();
@@ -3,6 +3,7 @@ import { lazy } from "@trpc/server";
import { createTRPCRouter } from "../../../trpc";
export const kubernetesRouter = createTRPCRouter({
contexts: lazy(() => import("./contexts").then((mod) => mod.contextsRouter)),
nodes: lazy(() => import("./nodes").then((mod) => mod.nodesRouter)),
cluster: lazy(() => import("./cluster").then((mod) => mod.clusterRouter)),
namespaces: lazy(() => import("./namespaces").then((mod) => mod.namespacesRouter)),
@@ -4,14 +4,15 @@ import type { KubernetesNamespace, KubernetesNamespaceState } from "@homarr/defi
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
export const namespacesRouter = createTRPCRouter({
getNamespaces: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesNamespace[]> => {
const { coreApi } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesNamespace[]> => {
const { coreApi } = getKubernetesClient(input.contextId);
try {
const namespaces = await coreApi.listNamespace();
@@ -4,7 +4,8 @@ import type { KubernetesNode, KubernetesNodeState } from "@homarr/definitions";
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
import { calculateResourcePercentage } from "../resource-percentage";
import { CpuResourceParser } from "../resource-parser/cpu-resource-parser";
import { MemoryResourceParser } from "../resource-parser/memory-resource-parser";
@@ -12,12 +13,15 @@ export const nodesRouter = createTRPCRouter({
getNodes: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesNode[]> => {
const { coreApi, metricsApi } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesNode[]> => {
const { coreApi, metricsApi } = getKubernetesClient(input.contextId);
try {
const nodes = await coreApi.listNode();
const nodeMetricsClient = await metricsApi.getNodeMetrics();
const [nodes, nodeMetricsClient] = await Promise.all([
coreApi.listNode(),
metricsApi.getNodeMetrics().catch(() => null),
]);
const cpuResourceParser = new CpuResourceParser();
const memoryResourceParser = new MemoryResourceParser();
@@ -34,20 +38,26 @@ export const nodesRouter = createTRPCRouter({
let cpuUsage = 0;
let memoryUsage = 0;
const nodeMetric = nodeMetricsClient.items.find((metric) => metric.metadata.name === name);
const nodeMetric = nodeMetricsClient?.items.find((metric) => metric.metadata.name === name);
if (nodeMetric) {
cpuUsage += cpuResourceParser.parse(nodeMetric.usage.cpu);
memoryUsage += memoryResourceParser.parse(nodeMetric.usage.memory);
}
const usagePercentageCPUAllocatable = (cpuUsage / cpuAllocatable) * 100;
const usagePercentageMemoryAllocatable = (memoryUsage / memoryAllocatable) * 100;
const usagePercentageCPUAllocatable = nodeMetric
? calculateResourcePercentage(cpuUsage, cpuAllocatable)
: null;
const usagePercentageMemoryAllocatable = nodeMetric
? calculateResourcePercentage(memoryUsage, memoryAllocatable)
: null;
return {
name,
status,
allocatableCpuPercentage: Number(usagePercentageCPUAllocatable.toFixed(0)),
allocatableRamPercentage: Number(usagePercentageMemoryAllocatable.toFixed(0)),
allocatableCpuPercentage:
usagePercentageCPUAllocatable === null ? null : Math.round(usagePercentageCPUAllocatable),
allocatableRamPercentage:
usagePercentageMemoryAllocatable === null ? null : Math.round(usagePercentageMemoryAllocatable),
podsCount: Number(node.status?.capacity?.pods),
operatingSystem: node.status?.nodeInfo?.operatingSystem,
architecture: node.status?.nodeInfo?.architecture,
@@ -7,7 +7,7 @@ import type { KubernetesPod } from "@homarr/definitions";
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
const logger = createLogger({ module: "podsRouter" });
@@ -15,8 +15,9 @@ export const podsRouter = createTRPCRouter({
getPods: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesPod[]> => {
const { coreApi, kubeConfig } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesPod[]> => {
const { coreApi, kubeConfig } = getKubernetesClient(input.contextId);
try {
const podsResp = await coreApi.listPodForAllNamespaces();
@@ -4,14 +4,15 @@ import type { KubernetesSecret } from "@homarr/definitions";
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
export const secretsRouter = createTRPCRouter({
getSecrets: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesSecret[]> => {
const { coreApi } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesSecret[]> => {
const { coreApi } = getKubernetesClient(input.contextId);
try {
const secrets = await coreApi.listSecretForAllNamespaces();
@@ -4,14 +4,15 @@ import type { KubernetesService } from "@homarr/definitions";
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
export const servicesRouter = createTRPCRouter({
getServices: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesService[]> => {
const { coreApi } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesService[]> => {
const { coreApi } = getKubernetesClient(input.contextId);
try {
const services = await coreApi.listServiceForAllNamespaces();
@@ -4,14 +4,15 @@ import type { KubernetesVolume } from "@homarr/definitions";
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
import { KubernetesClient } from "../kubernetes-client";
import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-context";
export const volumesRouter = createTRPCRouter({
getVolumes: permissionRequiredProcedure
.requiresPermission("admin")
.concat(kubernetesMiddleware())
.query(async (): Promise<KubernetesVolume[]> => {
const { coreApi } = KubernetesClient.getInstance();
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesVolume[]> => {
const { coreApi } = getKubernetesClient(input.contextId);
try {
const volumes = await coreApi.listPersistentVolumeClaimForAllNamespaces();
+6 -1
View File
@@ -636,7 +636,7 @@ describe("createBoard should create a new board", () => {
});
// Act
await caller.createBoard({ name: "newBoard", columnCount: 24, isPublic: true });
const result = await caller.createBoard({ name: "newBoard", columnCount: 24, isPublic: true });
// Assert
const dbBoard = await db.query.boards.findFirst({
@@ -663,6 +663,11 @@ describe("createBoard should create a new board", () => {
expect.objectContaining({ name: "Base", role: "base", columnCount: 24, breakpoint: 768 }),
]),
);
expect(result).toEqual({
boardId: dbBoard?.id,
name: "newBoard",
layoutId: dbBoard?.layouts.find((layout) => layout.role === "base")?.id,
});
});
test("should throw error when user has no board-create permission", async () => {
@@ -6,10 +6,44 @@ import { objectKeys } from "@homarr/common";
import type { Database } from "@homarr/db";
import type { GroupPermissionKey } from "@homarr/definitions";
import { getPermissionsWithChildren } from "@homarr/definitions";
import type { DockerEndpointStatus } from "@homarr/docker";
import type { RouterInputs } from "../../..";
import type { RouterInputs, RouterOutputs } from "../../..";
import { dockerRouter } from "../../docker/docker-router";
const findDockerContainerAsyncMock = vi.hoisted(() => vi.fn());
const hasDockerEndpointCapabilityMock = vi.hoisted(() => vi.fn(() => true));
const getDockerDataAsyncMock = vi.hoisted(() =>
vi.fn<
() => Promise<{
data: {
containers: RouterOutputs["docker"]["getContainers"]["containers"];
endpoints: DockerEndpointStatus[];
};
timestamp: Date;
}>
>(async () => ({
data: { containers: [], endpoints: [] },
timestamp: new Date(),
})),
);
const findIntegrationsAsyncMock = vi.fn(
async (): Promise<
{
id: string;
name: string;
kind: "sonarr";
url: string;
appId: string | null;
items?: { itemId: string }[];
secrets?: { kind: "apiKey" }[];
}[]
> => [],
);
const findAppsAsyncMock = vi.fn(
async (): Promise<{ id: string; name: string; href: string | null; iconUrl: string }[]> => [],
);
// Mock the auth module to return an empty session
vi.mock("@homarr/auth", () => ({ auth: () => ({}) as Session }));
vi.mock("@homarr/docker", () => ({
@@ -30,6 +64,8 @@ vi.mock("@homarr/docker", () => ({
},
}));
vi.mock("@homarr/request-handler/docker", () => ({
findDockerContainerAsync: findDockerContainerAsyncMock,
hasDockerEndpointCapability: hasDockerEndpointCapabilityMock,
getContainerLogsAsync: async () => {
await Promise.resolve();
return "logs";
@@ -40,9 +76,7 @@ vi.mock("@homarr/request-handler/docker", () => ({
},
dockerContainersRequestHandler: {
handler: () => ({
getDataAsync: async () => {
return await Promise.resolve({ data: [], timestamp: new Date() });
},
getDataAsync: getDockerDataAsyncMock,
}),
},
}));
@@ -67,20 +101,43 @@ const procedureKeys = objectKeys(dockerRouter._def.procedures);
const validInputs: {
[key in (typeof procedureKeys)[number]]: RouterInputs["docker"][key];
} = {
reconcileServices: undefined,
getServiceHealth: undefined,
getContainers: undefined,
startAll: { ids: ["1"] },
stopAll: { ids: ["1"] },
restartAll: { ids: ["1"] },
removeAll: { ids: ["1"] },
logs: { id: "1", tail: 200 },
subscribeLogs: { id: "1", tail: 200 },
startAll: { targets: [{ endpointId: "one", id: "1" }] },
stopAll: { targets: [{ endpointId: "one", id: "1" }] },
restartAll: { targets: [{ endpointId: "one", id: "1" }] },
removeAll: { targets: [{ endpointId: "one", id: "1" }] },
logs: { endpointId: "one", id: "1", tail: 200 },
subscribeLogs: { endpointId: "one", id: "1", tail: 200 },
};
const database = {
query: {
integrations: { findMany: findIntegrationsAsyncMock },
apps: { findMany: findAppsAsyncMock },
},
} as unknown as Database;
const createDockerContainer = () => ({
start: vi.fn().mockResolvedValue(undefined),
stop: vi.fn().mockResolvedValue(undefined),
restart: vi.fn().mockResolvedValue(undefined),
remove: vi.fn().mockResolvedValue(undefined),
});
const createAdminCaller = () =>
dockerRouter.createCaller({
db: database,
deviceType: undefined,
session: createSessionWithPermissions("admin"),
});
describe("All procedures should only be accessible for users with admin permission", () => {
test.each(procedureKeys)("Procedure %s should be accessible for users with admin permission", async (procedure) => {
// Arrange
const caller = dockerRouter.createCaller({
db: null as unknown as Database,
db: database,
deviceType: undefined,
session: createSessionWithPermissions("admin"),
});
@@ -122,3 +179,205 @@ describe("All procedures should only be accessible for users with admin permissi
await expect(act()).rejects.toThrow(new TRPCError({ code: "UNAUTHORIZED" }));
});
});
describe("Docker action targeting", () => {
test("enforces endpoint capabilities before running a lifecycle action", async () => {
hasDockerEndpointCapabilityMock.mockReturnValueOnce(false);
const result = await createAdminCaller().stopAll({ targets: [{ endpointId: "readonly", id: "one" }] });
expect(result).toEqual([
{
target: { endpointId: "readonly", id: "one" },
success: false,
error: "Endpoint does not permit lifecycle actions",
},
]);
expect(findDockerContainerAsyncMock).not.toHaveBeenCalled();
});
test("targets duplicate container IDs on their explicit endpoints", async () => {
const first = createDockerContainer();
const second = createDockerContainer();
findDockerContainerAsyncMock.mockImplementation(async ({ endpointId }) =>
endpointId === "first" ? first : second,
);
const result = await createAdminCaller().startAll({
targets: [
{ endpointId: "first", id: "duplicate" },
{ endpointId: "second", id: "duplicate" },
],
});
expect(first.start).toHaveBeenCalledOnce();
expect(second.start).toHaveBeenCalledOnce();
expect(result).toEqual([
{ target: { endpointId: "first", id: "duplicate" }, success: true },
{ target: { endpointId: "second", id: "duplicate" }, success: true },
]);
});
test("reports partial failures per target", async () => {
const healthy = createDockerContainer();
const failing = createDockerContainer();
failing.restart.mockRejectedValue(new Error("proxy denied restart"));
findDockerContainerAsyncMock.mockImplementation(async ({ endpointId }) =>
endpointId === "healthy" ? healthy : failing,
);
const result = await createAdminCaller().restartAll({
targets: [
{ endpointId: "healthy", id: "one" },
{ endpointId: "failing", id: "two" },
],
});
expect(result).toEqual([
{ target: { endpointId: "healthy", id: "one" }, success: true },
{
target: { endpointId: "failing", id: "two" },
success: false,
error: "proxy denied restart",
},
]);
});
});
test("distinguishes unavailable endpoints from an empty inventory", async () => {
getDockerDataAsyncMock.mockResolvedValueOnce({
data: {
containers: [],
endpoints: [{ id: "remote", name: "Remote Docker", status: "unavailable" }],
},
timestamp: new Date(),
});
const result = await createAdminCaller().getContainers();
expect(result.containers).toEqual([]);
expect(result.endpoints).toEqual([{ id: "remote", name: "Remote Docker", status: "unavailable" }]);
});
test("keeps multiple recognized services of the same integration kind", async () => {
getDockerDataAsyncMock.mockResolvedValueOnce({
data: {
containers: [
createInventoryContainer({ endpointId: "home", id: "one", name: "sonarr-home", publicPort: 8989 }),
createInventoryContainer({ endpointId: "remote", id: "two", name: "sonarr-remote", publicPort: 18989 }),
],
endpoints: [
{ id: "home", name: "Home", status: "available" },
{ id: "remote", name: "Remote", status: "available" },
] satisfies DockerEndpointStatus[],
},
timestamp: new Date(),
});
const result = await createAdminCaller().reconcileServices();
expect(result.candidates).toHaveLength(2);
expect(result.candidates.map(({ match }) => match?.kind)).toEqual(["sonarr", "sonarr"]);
expect(result.candidates.map(({ candidateKey }) => candidateKey)).toEqual(["home:one", "remote:two"]);
});
test("preserves unavailable endpoints beside available service candidates", async () => {
getDockerDataAsyncMock.mockResolvedValueOnce({
data: {
containers: [createInventoryContainer({ endpointId: "home", id: "one", name: "sonarr", publicPort: 8989 })],
endpoints: [
{ id: "home", name: "Home", status: "available" },
{ id: "remote", name: "Remote", status: "unavailable" },
] satisfies DockerEndpointStatus[],
},
timestamp: new Date(),
});
const result = await createAdminCaller().reconcileServices();
expect(result.candidates).toHaveLength(1);
expect(result.endpoints).toContainEqual({ id: "remote", name: "Remote", status: "unavailable" });
});
test("does not adopt an ambiguous existing integration", async () => {
getDockerDataAsyncMock.mockResolvedValueOnce({
data: {
containers: [createInventoryContainer({ endpointId: "home", id: "one", name: "sonarr", publicPort: 8989 })],
endpoints: [{ id: "home", name: "Home", status: "available" }],
},
timestamp: new Date(),
});
findIntegrationsAsyncMock.mockResolvedValueOnce([
{ id: "first", name: "Sonarr one", kind: "sonarr", url: "http://home.example:8989", appId: null },
{ id: "second", name: "Sonarr two", kind: "sonarr", url: "http://home.example:8989", appId: null },
]);
const result = await createAdminCaller().reconcileServices();
expect(result.candidates[0]?.representation.integration).toBeNull();
expect(result.candidates[0]?.representation.signals.ambiguous).toBe(true);
expect(result.candidates[0]?.state).toBe("newRecognized");
});
test("projects persisted service layers without inventing runtime health", async () => {
getDockerDataAsyncMock.mockResolvedValueOnce({
data: {
containers: [createInventoryContainer({ endpointId: "home", id: "one", name: "sonarr", publicPort: 8989 })],
endpoints: [{ id: "home", name: "Home", status: "available" }],
},
timestamp: new Date(),
});
findIntegrationsAsyncMock.mockResolvedValueOnce([
{
id: "integration",
name: "Sonarr",
kind: "sonarr",
url: "http://home.example:8989",
appId: "app",
items: [{ itemId: "widget" }],
secrets: [{ kind: "apiKey" }],
},
]);
findAppsAsyncMock.mockResolvedValueOnce([
{ id: "app", name: "Sonarr", href: "http://home.example:8989", iconUrl: "" },
]);
const result = await createAdminCaller().getServiceHealth();
expect(result.services[0]?.layers).toEqual(
expect.arrayContaining([
{ layer: "docker", status: "available", nextAction: "none" },
{ layer: "integrationConfiguration", status: "configured", nextAction: "none" },
{ layer: "authentication", status: "notObserved", nextAction: "testConnection" },
{ layer: "apiRequest", status: "notObserved", nextAction: "openIntegrationDiagnostics" },
{ layer: "appRepresentation", status: "linked", nextAction: "none" },
{ layer: "widgetConfiguration", status: "linked", nextAction: "none" },
{ layer: "widgetQuery", status: "notObserved", nextAction: "openBoard" },
]),
);
});
const createInventoryContainer = ({
endpointId,
id,
name,
publicPort,
}: {
endpointId: string;
id: string;
name: string;
publicPort: number;
}) => ({
id,
endpointId,
endpointName: endpointId,
resourceId: `${endpointId}:${id}`,
name,
host: `${endpointId}.example:2375`,
state: "running" as const,
image: "lscr.io/linuxserver/sonarr:latest",
iconUrl: null,
cpuUsage: 0,
memoryUsage: 0,
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: publicPort, Type: "tcp" }],
});
@@ -312,7 +312,7 @@ describe("create should create a new integration", () => {
const fakeNow = new Date("2023-07-01T00:00:00Z");
vi.useFakeTimers();
vi.setSystemTime(fakeNow);
await caller.create(input);
const result = await caller.create(input);
vi.useRealTimers();
const dbIntegration = await db.query.integrations.findFirst();
@@ -327,6 +327,15 @@ describe("create should create a new integration", () => {
expect(dbSecret!.kind).toBe(input.secrets[0]!.kind);
expect(dbSecret!.value).toMatch(/^[a-f0-9]+.[a-f0-9]+$/);
expect(dbSecret!.updatedAt).toEqual(fakeNow);
expect(result).toEqual({
integration: {
id: dbIntegration!.id,
name: input.name,
kind: input.kind,
url: input.url,
},
appId: null,
});
});
test("with create integration access should not create a search engine for media request search integrations", async () => {
@@ -347,7 +356,7 @@ describe("create should create a new integration", () => {
const fakeNow = new Date("2023-07-01T00:00:00Z");
vi.useFakeTimers();
vi.setSystemTime(fakeNow);
await caller.create(input);
const result = await caller.create(input);
vi.useRealTimers();
const dbIntegration = await db.query.integrations.findFirst();
@@ -363,6 +372,7 @@ describe("create should create a new integration", () => {
expect(dbSecret!.kind).toBe(input.secrets[0]!.kind);
expect(dbSecret!.value).toMatch(/^[a-f0-9]+.[a-f0-9]+$/);
expect(dbSecret!.updatedAt).toEqual(fakeNow);
expect(result).toMatchObject({ appId: dbIntegration!.appId, integration: { id: dbIntegration!.id } });
expect(dbSearchEngine).toBeUndefined();
});
@@ -0,0 +1,135 @@
import {
extractContainerImageName,
matchIntegrationKind,
matchIntegrationKindFromContainer,
} from "./docker-integration-match";
import type { IntegrationKind } from "./integration";
export type DockerServiceMatchConfidence = "high" | "medium";
export type DockerServiceMatchSource = "image" | "name";
export type DockerUrlCandidateSource = "publishedAddress" | "endpointHost" | "containerDns" | "manual";
export type DockerUrlCandidateScope = "browser" | "server";
export type DockerUrlCandidateReason =
| "publishedAddress"
| "dockerEndpointHost"
| "sharedContainerNetwork"
| "manualHostRequired";
export interface DockerServiceMatch {
kind: IntegrationKind;
confidence: DockerServiceMatchConfidence;
source: DockerServiceMatchSource;
}
export interface DockerServicePort {
IP?: string;
PrivatePort: number;
PublicPort?: number;
Type: string;
}
export interface DockerServiceUrlCandidate {
id: string;
url: string;
rank: number;
source: DockerUrlCandidateSource;
scopes: DockerUrlCandidateScope[];
reason: DockerUrlCandidateReason;
}
export const matchDockerService = (container: { image: string; name: string }): DockerServiceMatch | null => {
const kind = matchIntegrationKindFromContainer(container);
if (!kind) return null;
const imageMatch = matchIntegrationKind(extractContainerImageName(container.image));
return imageMatch === kind
? { kind, confidence: "high", source: "image" }
: { kind, confidence: "medium", source: "name" };
};
export const buildDockerServiceUrlCandidates = ({
containerName,
endpointHost,
ports,
preferredPort,
}: {
containerName: string;
endpointHost: string;
ports: DockerServicePort[] | undefined;
preferredPort?: number;
}): DockerServiceUrlCandidate[] => {
const candidates: DockerServiceUrlCandidate[] = [];
const endpointHostname = getEndpointHostname(endpointHost);
const tcpPorts = (ports ?? [])
.filter((port) => port.Type.toLowerCase() === "tcp")
.toSorted(
(left, right) => Number(right.PrivatePort === preferredPort) - Number(left.PrivatePort === preferredPort),
);
const addCandidate = (candidate: Omit<DockerServiceUrlCandidate, "id">) => {
if (candidates.some(({ url, scopes }) => url === candidate.url && scopes.join() === candidate.scopes.join()))
return;
candidates.push({
...candidate,
id: `${candidate.source}:${candidate.scopes.join("-")}:${candidate.url || "manual"}`,
});
};
for (const port of tcpPorts) {
if (port.PublicPort) {
const publishedHost = isUsablePublishedAddress(port.IP) ? port.IP : endpointHostname;
if (publishedHost) {
addCandidate({
url: `http://${formatUrlHost(publishedHost)}:${port.PublicPort}`,
rank: port.PrivatePort === preferredPort ? 1 : 2,
source: isUsablePublishedAddress(port.IP) ? "publishedAddress" : "endpointHost",
scopes: ["browser", "server"],
reason: isUsablePublishedAddress(port.IP) ? "publishedAddress" : "dockerEndpointHost",
});
}
}
addCandidate({
url: `http://${containerName}:${port.PrivatePort}`,
rank: port.PrivatePort === preferredPort ? 3 : 4,
source: "containerDns",
scopes: ["server"],
reason: "sharedContainerNetwork",
});
}
addCandidate({
url: "",
rank: 99,
source: "manual",
scopes: ["browser"],
reason: "manualHostRequired",
});
return candidates.toSorted((left, right) => left.rank - right.rank);
};
export const normalizeDockerServiceUrl = (value: string | null | undefined) => {
if (!value) return null;
try {
const url = new URL(value);
url.hash = "";
return url.toString().replace(/\/$/, "").toLowerCase();
} catch {
return value.trim().replace(/\/$/, "").toLowerCase() || null;
}
};
const isUsablePublishedAddress = (value: string | undefined): value is string =>
Boolean(value && !["0.0.0.0", "::", "::0"].includes(value));
const getEndpointHostname = (host: string) => {
if (host === "socket" || host.startsWith("/")) return null;
try {
return new URL(`http://${host}`).hostname || null;
} catch {
return null;
}
};
const formatUrlHost = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
+1
View File
@@ -16,6 +16,7 @@ export * from "./widget-integration-map";
export * from "./emptysuperjson";
export * from "./hotkeys";
export * from "./docker-integration-match";
export * from "./docker-service-discovery";
export * from "./integration-url-template";
export * from "./release-provider";
export * from "./assistant";
+3 -2
View File
@@ -73,8 +73,8 @@ export interface KubernetesNamespace extends KubernetesBaseResource {
export interface KubernetesNode {
name: string;
status: KubernetesNodeState;
allocatableCpuPercentage: number;
allocatableRamPercentage: number;
allocatableCpuPercentage: number | null;
allocatableRamPercentage: number | null;
podsCount: number;
operatingSystem?: string;
architecture?: string;
@@ -88,6 +88,7 @@ export interface KubernetesCluster {
kubernetesVersion: string;
architecture: string;
nodeCount: number;
metricsAvailable: boolean;
capacity: KubernetesCapacity[];
}
@@ -0,0 +1,53 @@
import { describe, expect, test } from "vitest";
import { buildDockerServiceUrlCandidates, matchDockerService } from "../docker-service-discovery";
describe("matchDockerService", () => {
test("reports image matches with high confidence and name fallbacks with medium confidence", () => {
expect(matchDockerService({ image: "linuxserver/sonarr:latest", name: "media" })).toEqual({
kind: "sonarr",
confidence: "high",
source: "image",
});
expect(matchDockerService({ image: "custom/media:latest", name: "sonarr" })).toEqual({
kind: "sonarr",
confidence: "medium",
source: "name",
});
});
});
describe("buildDockerServiceUrlCandidates", () => {
test("never emits wildcard or socket-path browser URLs", () => {
const candidates = buildDockerServiceUrlCandidates({
containerName: "sonarr",
endpointHost: "/var/run/docker.sock",
preferredPort: 8989,
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
});
expect(candidates.map(({ url }) => url)).not.toContain("http://0.0.0.0:8989");
expect(candidates.map(({ url }) => url)).not.toContain("http:///var/run/docker.sock:8989");
expect(candidates[0]).toMatchObject({
url: "http://sonarr:8989",
scopes: ["server"],
reason: "sharedContainerNetwork",
});
expect(candidates.at(-1)).toMatchObject({ url: "", reason: "manualHostRequired" });
});
test("uses a remote Docker endpoint hostname for wildcard published ports", () => {
const candidates = buildDockerServiceUrlCandidates({
containerName: "sonarr",
endpointHost: "docker.example.test:2375",
preferredPort: 8989,
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
});
expect(candidates[0]).toMatchObject({
url: "http://docker.example.test:8989",
scopes: ["browser", "server"],
reason: "dockerEndpointHost",
});
});
});
@@ -0,0 +1,33 @@
import { describe, expect, test } from "vitest";
import { integrationKinds } from "../integration";
import {
getWidgetKindsForIntegration,
integrationWidgetSupport,
nativeFeatureCapabilities,
widgetIntegrationLimits,
widgetIntegrationSupport,
widgetKindsWithOptionalIntegrations,
} from "../widget-integration-map";
describe("native feature capability descriptor", () => {
test("derives forward and reverse support without losing relationships", () => {
for (const [widgetKind, capability] of Object.entries(nativeFeatureCapabilities)) {
expect(widgetIntegrationSupport[widgetKind as keyof typeof widgetIntegrationSupport]).toEqual(
capability.integrations,
);
for (const integrationKind of capability.integrations) {
expect(integrationWidgetSupport[integrationKind]).toContain(widgetKind);
}
}
for (const integrationKind of integrationKinds) {
expect(getWidgetKindsForIntegration(integrationKind)).toEqual(integrationWidgetSupport[integrationKind]);
}
});
test("derives optional connections and server selection limits", () => {
expect(widgetKindsWithOptionalIntegrations).toEqual(new Set(["calendar"]));
expect(widgetIntegrationLimits).toEqual({ audioStats: 1 });
});
});
@@ -1,69 +1,99 @@
import { createDocumentationLink } from "./docs";
import type { IntegrationKind } from "./integration";
import { getIntegrationKindsByCategory } from "./integration";
import { getIntegrationKindsByCategory, integrationKinds } from "./integration";
import type { WidgetKind } from "./widget";
import { widgetDefaultSizes } from "./widget";
/**
* Static mapping of widget kinds to the integration kinds they support.
* Mirrors the supportedIntegrations declared in each widget definition
* but lives in @homarr/definitions so server-side code (API layer)
* can use it without importing @homarr/widgets.
* Server-safe capability metadata shared by the API and widget catalog.
* Keep this intentionally small: presentation, options, and request contracts
* remain owned by their feature packages.
*/
export const widgetIntegrationSupport: Partial<Record<WidgetKind, readonly IntegrationKind[]>> = {
dnsHoleSummary: getIntegrationKindsByCategory("dnsHole"),
dnsHoleControls: getIntegrationKindsByCategory("dnsHole"),
"smartHome-entityState": getIntegrationKindsByCategory("smartHomeServer"),
"smartHome-executeAutomation": getIntegrationKindsByCategory("smartHomeServer"),
mediaServer: getIntegrationKindsByCategory("mediaService"),
calendar: getIntegrationKindsByCategory("calendar"),
downloads: getIntegrationKindsByCategory("downloadClient"),
"mediaRequests-requestList": getIntegrationKindsByCategory("mediaRequest"),
"mediaRequests-requestStats": getIntegrationKindsByCategory("mediaRequest"),
mediaTranscoding: getIntegrationKindsByCategory("mediaTranscoding"),
mediaMissing: getIntegrationKindsByCategory("mediaOrganizer"),
networkControllerSummary: getIntegrationKindsByCategory("networkController"),
networkControllerStatus: getIntegrationKindsByCategory("networkController"),
indexerManager: getIntegrationKindsByCategory("indexerManager"),
healthMonitoring: getIntegrationKindsByCategory("healthMonitoring").filter(
(kind) => kind !== "patchmon" && kind !== "wud",
),
firewall: getIntegrationKindsByCategory("firewall"),
notifications: getIntegrationKindsByCategory("notifications"),
mediaReleases: ["mock", "emby", "jellyfin", "plex"],
systemResources: ["dashDot", "openmediavault", "truenas", "unraid", "glances", "synology"],
systemDisks: ["dashDot", "openmediavault", "truenas", "unraid", "synology"],
beszelAlerts: ["beszel", "mock"],
beszelSystemGrid: ["beszel", "mock"],
beszelSystemStats: ["beszel", "mock"],
beszelSystemTable: ["beszel", "mock"],
coolify: ["coolify"],
"immich-serverStats": ["immich"],
"immich-albumCarousel": ["immich"],
paperlessNgx: ["paperlessNgx"],
patchmon: ["patchmon"],
bazarr: ["bazarr"],
tracearr: ["tracearr"],
speedtestTracker: ["speedtestTracker"],
uptimeKuma: ["uptimeKuma"],
audioStats: ["navidrome", "audiobookshelf"],
umami: ["umami"],
vpn: getIntegrationKindsByCategory("vpn"),
ups: getIntegrationKindsByCategory("ups"),
archiveTeamWarrior: ["archiveTeamWarrior"],
anchorNote: ["anchor"],
traefik: ["traefik"],
wud: ["wud"],
export interface NativeFeatureCapabilityDescriptor {
integrations: readonly IntegrationKind[];
connectionOptional?: true;
serverMaxIntegrations?: number;
}
export const nativeFeatureCapabilities = {
dnsHoleSummary: { integrations: getIntegrationKindsByCategory("dnsHole") },
dnsHoleControls: { integrations: getIntegrationKindsByCategory("dnsHole") },
"smartHome-entityState": { integrations: getIntegrationKindsByCategory("smartHomeServer") },
"smartHome-executeAutomation": { integrations: getIntegrationKindsByCategory("smartHomeServer") },
mediaServer: { integrations: getIntegrationKindsByCategory("mediaService") },
calendar: { integrations: getIntegrationKindsByCategory("calendar"), connectionOptional: true },
downloads: { integrations: getIntegrationKindsByCategory("downloadClient") },
"mediaRequests-requestList": { integrations: getIntegrationKindsByCategory("mediaRequest") },
"mediaRequests-requestStats": { integrations: getIntegrationKindsByCategory("mediaRequest") },
mediaTranscoding: { integrations: getIntegrationKindsByCategory("mediaTranscoding") },
mediaMissing: { integrations: getIntegrationKindsByCategory("mediaOrganizer") },
networkControllerSummary: { integrations: getIntegrationKindsByCategory("networkController") },
networkControllerStatus: { integrations: getIntegrationKindsByCategory("networkController") },
indexerManager: { integrations: getIntegrationKindsByCategory("indexerManager") },
healthMonitoring: {
integrations: getIntegrationKindsByCategory("healthMonitoring").filter(
(kind) => kind !== "patchmon" && kind !== "wud",
),
},
firewall: { integrations: getIntegrationKindsByCategory("firewall") },
notifications: { integrations: getIntegrationKindsByCategory("notifications") },
mediaReleases: { integrations: ["mock", "emby", "jellyfin", "plex"] },
systemResources: { integrations: ["dashDot", "openmediavault", "truenas", "unraid", "glances", "synology"] },
systemDisks: { integrations: ["dashDot", "openmediavault", "truenas", "unraid", "synology"] },
beszelAlerts: { integrations: ["beszel", "mock"] },
beszelSystemGrid: { integrations: ["beszel", "mock"] },
beszelSystemStats: { integrations: ["beszel", "mock"] },
beszelSystemTable: { integrations: ["beszel", "mock"] },
coolify: { integrations: ["coolify"] },
"immich-serverStats": { integrations: ["immich"] },
"immich-albumCarousel": { integrations: ["immich"] },
paperlessNgx: { integrations: ["paperlessNgx"] },
patchmon: { integrations: ["patchmon"] },
bazarr: { integrations: ["bazarr"] },
tracearr: { integrations: ["tracearr"] },
speedtestTracker: { integrations: ["speedtestTracker"] },
uptimeKuma: { integrations: ["uptimeKuma"] },
audioStats: { integrations: ["navidrome", "audiobookshelf"], serverMaxIntegrations: 1 },
umami: { integrations: ["umami"] },
vpn: { integrations: getIntegrationKindsByCategory("vpn") },
ups: { integrations: getIntegrationKindsByCategory("ups") },
archiveTeamWarrior: { integrations: ["archiveTeamWarrior"] },
anchorNote: { integrations: ["anchor"] },
traefik: { integrations: ["traefik"] },
wud: { integrations: ["wud"] },
} as const satisfies Partial<Record<WidgetKind, NativeFeatureCapabilityDescriptor>>;
const nativeFeatureCapabilityEntries = Object.entries(nativeFeatureCapabilities) as [
WidgetKind,
NativeFeatureCapabilityDescriptor,
][];
const createWidgetIntegrationSupport = () => {
const result: Partial<Record<WidgetKind, readonly IntegrationKind[]>> = {};
for (const [kind, capability] of nativeFeatureCapabilityEntries) result[kind] = capability.integrations;
return result;
};
export const widgetIntegrationSupport = createWidgetIntegrationSupport();
/** Widgets that remain useful without a configured integration. */
export const widgetKindsWithOptionalIntegrations = new Set<WidgetKind>(["calendar"]);
export const widgetKindsWithOptionalIntegrations = new Set<WidgetKind>(
nativeFeatureCapabilityEntries
.filter(([, capability]) => capability.connectionOptional === true)
.map(([kind]) => kind),
);
/** Widgets that support fewer integrations than the default unlimited selection. */
export const widgetIntegrationLimits: Partial<Record<WidgetKind, number>> = {
audioStats: 1,
const createWidgetIntegrationLimits = () => {
const result: Partial<Record<WidgetKind, number>> = {};
for (const [kind, capability] of nativeFeatureCapabilityEntries) {
if (capability.serverMaxIntegrations !== undefined) result[kind] = capability.serverMaxIntegrations;
}
return result;
};
export const widgetIntegrationLimits = createWidgetIntegrationLimits();
export type WidgetIntegrationIssue =
| { code: "integration-not-supported" }
| { code: "integration-required" }
@@ -98,16 +128,23 @@ export const getWidgetIntegrationIssueMessage = (widgetKind: WidgetKind, issue:
return `${widgetKind} does not support integration kind${issue.incompatibleKinds.length === 1 ? "" : "s"}: ${issue.incompatibleKinds.join(", ")}`;
};
export const getWidgetKindsForIntegration = (integrationKind: IntegrationKind): WidgetKind[] => {
const result: WidgetKind[] = [];
for (const [widgetKind, supportedIntegrations] of Object.entries(widgetIntegrationSupport)) {
if (supportedIntegrations.includes(integrationKind)) {
result.push(widgetKind as WidgetKind);
}
/** Reverse capability index generated from nativeFeatureCapabilities. */
const createIntegrationWidgetSupport = () => {
const result = {} as Record<IntegrationKind, readonly WidgetKind[]>;
for (const integrationKind of integrationKinds) {
result[integrationKind] = nativeFeatureCapabilityEntries
.filter(([, capability]) => capability.integrations.includes(integrationKind))
.map(([widgetKind]) => widgetKind);
}
return result;
};
export const integrationWidgetSupport = createIntegrationWidgetSupport();
export const getWidgetKindsForIntegration = (integrationKind: IntegrationKind): WidgetKind[] => [
...integrationWidgetSupport[integrationKind],
];
export interface DefaultWidgetConfig {
kind: WidgetKind;
width: number;
+152
View File
@@ -0,0 +1,152 @@
export const dockerEndpointCapabilities = ["inventory", "logs", "lifecycle", "remove"] as const;
export type DockerEndpointCapability = (typeof dockerEndpointCapabilities)[number];
export type DockerEndpointTransport =
| { type: "socket"; path: string }
| { type: "tcp"; host: string; port: number; allowInsecure: true }
| {
type: "tls";
host: string;
port: number;
caPath: string;
certPath?: string;
keyPath?: string;
};
export interface DockerEndpointDescriptor {
id: string;
name: string;
kind: "docker" | "podman";
transport: DockerEndpointTransport;
capabilities: DockerEndpointCapability[];
scope: "admin";
source: "environment" | "legacy" | "default";
}
const allCapabilities = [...dockerEndpointCapabilities];
export const parseDockerEndpointDescriptors = (value: string): DockerEndpointDescriptor[] => {
let input: unknown;
try {
input = JSON.parse(value);
} catch (error) {
throw new Error("DOCKER_ENDPOINTS must be valid JSON", { cause: error });
}
if (!Array.isArray(input) || input.length === 0) {
throw new Error("DOCKER_ENDPOINTS must be a non-empty JSON array");
}
const descriptors = input.map((entry, index) => parseDescriptor(entry, index));
const ids = new Set(descriptors.map(({ id }) => id));
if (ids.size !== descriptors.length) throw new Error("DOCKER_ENDPOINTS ids must be unique");
return descriptors;
};
const parseDescriptor = (value: unknown, index: number): DockerEndpointDescriptor => {
const entry = getRecord(value, `DOCKER_ENDPOINTS[${index}]`);
const id = getNonEmptyString(entry.id, `DOCKER_ENDPOINTS[${index}].id`);
const name = getNonEmptyString(entry.name, `DOCKER_ENDPOINTS[${index}].name`);
const kind =
entry.kind === "podman" ? "podman" : entry.kind === "docker" || entry.kind === undefined ? "docker" : null;
if (!kind) throw new Error(`DOCKER_ENDPOINTS[${index}].kind must be docker or podman`);
const transport = parseTransport(entry.transport, index);
const capabilities = parseCapabilities(entry.capabilities, index);
return { id, name, kind, transport, capabilities, scope: "admin", source: "environment" };
};
const parseTransport = (value: unknown, index: number): DockerEndpointTransport => {
const transport = getRecord(value, `DOCKER_ENDPOINTS[${index}].transport`);
if (transport.type === "socket") {
return { type: "socket", path: getAbsolutePath(transport.path, `DOCKER_ENDPOINTS[${index}].transport.path`) };
}
if (transport.type === "tcp") {
if (transport.allowInsecure !== true) {
throw new Error(`DOCKER_ENDPOINTS[${index}] plaintext TCP requires allowInsecure: true`);
}
return {
type: "tcp",
host: getNonEmptyString(transport.host, `DOCKER_ENDPOINTS[${index}].transport.host`),
port: getPort(transport.port, index),
allowInsecure: true,
};
}
if (transport.type === "tls") {
const certPath = getOptionalAbsolutePath(transport.certPath, `DOCKER_ENDPOINTS[${index}].transport.certPath`);
const keyPath = getOptionalAbsolutePath(transport.keyPath, `DOCKER_ENDPOINTS[${index}].transport.keyPath`);
if (Boolean(certPath) !== Boolean(keyPath)) {
throw new Error(`DOCKER_ENDPOINTS[${index}] TLS certPath and keyPath must be provided together`);
}
return {
type: "tls",
host: getNonEmptyString(transport.host, `DOCKER_ENDPOINTS[${index}].transport.host`),
port: getPort(transport.port, index),
caPath: getAbsolutePath(transport.caPath, `DOCKER_ENDPOINTS[${index}].transport.caPath`),
...(certPath && keyPath ? { certPath, keyPath } : {}),
};
}
throw new Error(`DOCKER_ENDPOINTS[${index}].transport.type must be socket, tcp, or tls`);
};
const parseCapabilities = (value: unknown, index: number): DockerEndpointCapability[] => {
if (value === undefined) return allCapabilities;
if (!Array.isArray(value) || value.some((capability) => !dockerEndpointCapabilities.includes(capability))) {
throw new Error(`DOCKER_ENDPOINTS[${index}].capabilities contains an unsupported capability`);
}
const capabilities = [...new Set(value)] as DockerEndpointCapability[];
if (!capabilities.includes("inventory")) {
throw new Error(`DOCKER_ENDPOINTS[${index}].capabilities must include inventory`);
}
return capabilities;
};
const getRecord = (value: unknown, path: string): Record<string, unknown> => {
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${path} must be an object`);
return value as Record<string, unknown>;
};
const getNonEmptyString = (value: unknown, path: string) => {
if (typeof value !== "string" || value.trim().length === 0) throw new Error(`${path} must be a non-empty string`);
return value.trim();
};
const getAbsolutePath = (value: unknown, path: string) => {
const result = getNonEmptyString(value, path);
if (!result.startsWith("/")) throw new Error(`${path} must be an absolute path`);
return result;
};
const getOptionalAbsolutePath = (value: unknown, path: string) =>
value === undefined ? undefined : getAbsolutePath(value, path);
const getPort = (value: unknown, index: number) => {
if (!Number.isInteger(value) || Number(value) < 1 || Number(value) > 65_535) {
throw new Error(`DOCKER_ENDPOINTS[${index}].transport.port must be an integer from 1 to 65535`);
}
return Number(value);
};
export const getDockerEndpointHost = (descriptor: DockerEndpointDescriptor) =>
descriptor.transport.type === "socket"
? descriptor.transport.path
: `${descriptor.transport.host}:${descriptor.transport.port}`;
export const createLegacySocketDescriptor = (path: string): DockerEndpointDescriptor => ({
id: `socket:${path}`,
name: path,
kind: path.toLowerCase().includes("podman") ? "podman" : "docker",
transport: { type: "socket", path },
capabilities: allCapabilities,
scope: "admin",
source: "legacy",
});
export const createLegacyTcpDescriptor = (host: string, port: number): DockerEndpointDescriptor => ({
id: `tcp:${host}:${port}`,
name: `${host}:${port}`,
kind: "docker",
transport: { type: "tcp", host, port, allowInsecure: true },
capabilities: allCapabilities,
scope: "admin",
source: "legacy",
});
+2
View File
@@ -9,6 +9,8 @@ export const env = createEnv({
DOCKER_PORTS: z.string().optional(),
// Comma separated paths to Docker-compatible Unix sockets (e.g., /var/run/docker.sock,/run/user/1000/podman/podman.sock)
DOCKER_SOCKET_PATHS: z.string().optional(),
// JSON descriptors for friendly names, TLS, Podman identity, and per-endpoint capabilities.
DOCKER_ENDPOINTS: z.string().optional(),
ENABLE_DOCKER: createBooleanSchema(true),
ENABLE_KUBERNETES: createBooleanSchema(false),
},
+19
View File
@@ -1,12 +1,31 @@
import type Docker from "dockerode";
import type { DockerEndpointCapability } from "./endpoint-descriptor";
export type { DockerInstance } from "./singleton";
export { DockerSingleton } from "./singleton";
export * from "./endpoint-descriptor";
export type { ContainerInfo, Container, Port } from "dockerode";
export type { Docker };
export const containerStates = ["created", "running", "paused", "restarting", "exited", "removing", "dead"] as const;
export type ContainerState = (typeof containerStates)[number];
export interface DockerContainerTarget {
endpointId: string;
id: string;
}
export interface DockerEndpointStatus {
id: string;
name: string;
status: "available" | "unavailable";
kind?: "docker" | "podman";
transport?: "socket" | "tcp" | "tls";
capabilities?: DockerEndpointCapability[];
source?: "environment" | "legacy" | "default";
scope?: "admin";
}
export * from "./labels";
export * from "./discovery";
+53 -11
View File
@@ -1,9 +1,20 @@
import { readFileSync } from "node:fs";
import Docker from "dockerode";
import { env } from "./env";
import type { DockerEndpointCapability, DockerEndpointDescriptor } from "./endpoint-descriptor";
import {
createLegacySocketDescriptor,
createLegacyTcpDescriptor,
getDockerEndpointHost,
parseDockerEndpointDescriptors,
} from "./endpoint-descriptor";
export interface DockerInstance {
endpointId: string;
endpointName: string;
host: string;
descriptor: DockerEndpointDescriptor;
instance: Docker;
}
@@ -11,16 +22,15 @@ export class DockerSingleton {
private static instances: DockerInstance[] | null = null;
private createInstances() {
if (env.DOCKER_ENDPOINTS) return parseDockerEndpointDescriptors(env.DOCKER_ENDPOINTS).map(createInstance);
const socketPaths = env.DOCKER_SOCKET_PATHS;
const hostVariable = env.DOCKER_HOSTNAMES;
const portVariable = env.DOCKER_PORTS;
// Socket instances from DOCKER_SOCKET_PATHS
const socketInstances: DockerInstance[] = socketPaths
? socketPaths.split(",").map((socketPath) => ({
host: socketPath,
instance: new Docker({ socketPath }),
}))
? socketPaths.split(",").map((socketPath) => createInstance(createLegacySocketDescriptor(socketPath)))
: [];
// TCP instances from existing DOCKER_HOSTNAMES/DOCKER_PORTS
@@ -33,25 +43,34 @@ export class DockerSingleton {
throw new Error("The number of hosts and ports must match");
}
tcpInstances = hostnames.map((host, i) => ({
host: `${host}:${ports[i]}`,
tcpInstances = hostnames.map((host, i) =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
instance: new Docker({ host, port: parseInt(ports[i]!, 10) }),
}));
createInstance(createLegacyTcpDescriptor(host, parseInt(ports[i]!, 10))),
);
}
const instances = [...socketInstances, ...tcpInstances];
// Default: local socket if nothing else configured
if (instances.length === 0) {
return [{ host: "socket", instance: new Docker() }];
const descriptor = {
...createLegacySocketDescriptor("/var/run/docker.sock"),
id: "socket:default",
name: "Local Docker",
source: "default" as const,
};
return [{ ...createInstance(descriptor), host: "socket", instance: new Docker() }];
}
return instances;
}
public static findInstance(host: string): DockerInstance | undefined {
return this.instances?.find((instance) => instance.host === host);
public static findInstance(endpointId: string): DockerInstance | undefined {
return this.getInstances().find((instance) => instance.endpointId === endpointId);
}
public static hasCapability(endpointId: string, capability: DockerEndpointCapability): boolean {
return this.findInstance(endpointId)?.descriptor.capabilities.includes(capability) ?? false;
}
public static getInstances(): DockerInstance[] {
@@ -63,3 +82,26 @@ export class DockerSingleton {
return this.instances;
}
}
const createInstance = (descriptor: DockerEndpointDescriptor): DockerInstance => ({
endpointId: descriptor.id,
endpointName: descriptor.name,
host: getDockerEndpointHost(descriptor),
descriptor,
instance: new Docker(createDockerOptions(descriptor)),
});
const createDockerOptions = (descriptor: DockerEndpointDescriptor) => {
const transport = descriptor.transport;
if (transport.type === "socket") return { socketPath: transport.path };
if (transport.type === "tcp") return { host: transport.host, port: transport.port, protocol: "http" as const };
return {
host: transport.host,
port: transport.port,
protocol: "https" as const,
ca: readFileSync(transport.caPath),
...(transport.certPath && transport.keyPath
? { cert: readFileSync(transport.certPath), key: readFileSync(transport.keyPath) }
: {}),
};
};
@@ -0,0 +1,60 @@
import { describe, expect, test } from "vitest";
import { parseDockerEndpointDescriptors } from "../endpoint-descriptor";
describe("parseDockerEndpointDescriptors", () => {
test("parses friendly TLS and read-only Podman endpoints", () => {
const descriptors = parseDockerEndpointDescriptors(
JSON.stringify([
{
id: "nas",
name: "NAS Docker",
transport: { type: "tls", host: "nas.internal", port: 2376, caPath: "/run/secrets/docker-ca" },
},
{
id: "podman",
name: "Build host",
kind: "podman",
transport: { type: "socket", path: "/run/podman/podman.sock" },
capabilities: ["inventory", "logs"],
},
]),
);
expect(descriptors).toEqual([
expect.objectContaining({ id: "nas", name: "NAS Docker", kind: "docker", source: "environment" }),
expect.objectContaining({ id: "podman", kind: "podman", capabilities: ["inventory", "logs"] }),
]);
});
test("requires an explicit opt-in for plaintext TCP", () => {
expect(() =>
parseDockerEndpointDescriptors(
JSON.stringify([{ id: "nas", name: "NAS", transport: { type: "tcp", host: "nas", port: 2375 } }]),
),
).toThrow("allowInsecure: true");
});
test("rejects duplicate identities and capabilities without inventory", () => {
expect(() =>
parseDockerEndpointDescriptors(
JSON.stringify([
{ id: "same", name: "A", transport: { type: "socket", path: "/a" } },
{ id: "same", name: "B", transport: { type: "socket", path: "/b" } },
]),
),
).toThrow("ids must be unique");
expect(() =>
parseDockerEndpointDescriptors(
JSON.stringify([
{
id: "limited",
name: "Limited",
transport: { type: "socket", path: "/run/docker.sock" },
capabilities: ["logs"],
},
]),
),
).toThrow("must include inventory");
});
});
@@ -6,6 +6,7 @@ const mockEnv = vi.hoisted(() => ({
DOCKER_SOCKET_PATHS: undefined as string | undefined,
DOCKER_HOSTNAMES: undefined as string | undefined,
DOCKER_PORTS: undefined as string | undefined,
DOCKER_ENDPOINTS: undefined as string | undefined,
ENABLE_DOCKER: true,
ENABLE_KUBERNETES: false,
}));
@@ -32,6 +33,7 @@ describe("DockerSingleton", () => {
mockEnv.DOCKER_SOCKET_PATHS = undefined;
mockEnv.DOCKER_HOSTNAMES = undefined;
mockEnv.DOCKER_PORTS = undefined;
mockEnv.DOCKER_ENDPOINTS = undefined;
});
test("should return default socket when no env vars set", () => {
@@ -39,6 +41,7 @@ describe("DockerSingleton", () => {
expect(instances).toHaveLength(1);
expect(instances[0]?.host).toBe("socket");
expect(instances[0]).toMatchObject({ endpointId: "socket:default", endpointName: "Local Docker" });
});
test("should return TCP instances only when DOCKER_HOSTNAMES and DOCKER_PORTS set", () => {
@@ -60,6 +63,7 @@ describe("DockerSingleton", () => {
expect(instances).toHaveLength(2);
expect(instances[0]?.host).toBe("host1:2375");
expect(instances[1]?.host).toBe("host2:2376");
expect(instances.map(({ endpointId }) => endpointId)).toEqual(["tcp:host1:2375", "tcp:host2:2376"]);
});
test("should throw when hostname and port counts do not match", () => {
@@ -86,6 +90,7 @@ describe("DockerSingleton", () => {
expect(instances).toHaveLength(2);
expect(instances[0]?.host).toBe("/var/run/docker.sock");
expect(instances[1]?.host).toBe("/run/user/1000/podman/podman.sock");
expect(DockerSingleton.findInstance("socket:/run/user/1000/podman/podman.sock")).toBe(instances[1]);
});
test("should combine socket and TCP instances", () => {
@@ -107,4 +112,23 @@ describe("DockerSingleton", () => {
expect(first).toBe(second);
});
test("uses the structured endpoint descriptor and exposes scoped capabilities", () => {
mockEnv.DOCKER_ENDPOINTS = JSON.stringify([
{
id: "readonly-podman",
name: "Read-only Podman",
kind: "podman",
transport: { type: "socket", path: "/run/podman/podman.sock" },
capabilities: ["inventory", "logs"],
},
]);
const [endpoint] = DockerSingleton.getInstances();
expect(endpoint).toMatchObject({ endpointId: "readonly-podman", endpointName: "Read-only Podman" });
expect(endpoint?.descriptor).toMatchObject({ kind: "podman", source: "environment" });
expect(DockerSingleton.hasCapability("readonly-podman", "logs")).toBe(true);
expect(DockerSingleton.hasCapability("readonly-podman", "remove")).toBe(false);
});
});
+1 -1
View File
@@ -13,8 +13,8 @@
},
"exports": {
".": "./index.ts",
"./response-contract": "./src/base/response-contract.ts",
"./test-connection": "./src/base/test-connection/index.ts",
"./client": "./src/client.ts",
"./types": "./src/types.ts"
},
"scripts": {
@@ -0,0 +1,37 @@
import { describe, expect, test } from "vitest";
import { z } from "zod/v4";
import { simulateResponseContractAsync } from "./response-contract";
const parser = async (response: { json: () => Promise<unknown> }) =>
z.object({ count: z.number() }).parse(await response.json());
describe("simulateResponseContractAsync", () => {
test("runs valid, mapped, and rejected payload fixtures", async () => {
const results = await simulateResponseContractAsync(
parser,
[
{ name: "valid response", payload: { count: 2 }, expected: { total: 2 } },
{ name: "invalid response", payload: { count: "two" }, rejects: true },
],
(value) => ({ total: value.count }),
);
expect(results).toEqual([
{ name: "valid response", passed: true, message: undefined },
{ name: "invalid response", passed: true, message: undefined },
]);
});
test("reports actionable mismatches without throwing away later fixtures", async () => {
const results = await simulateResponseContractAsync(parser, [
{ name: "wrong output", payload: { count: 2 }, expected: { count: 3 } },
{ name: "unexpected success", payload: { count: 4 }, rejects: true },
]);
expect(results).toEqual([
{ name: "wrong output", passed: false, message: "Parsed output did not match expected." },
{ name: "unexpected success", passed: false, message: "Expected parser rejection, but parsing succeeded." },
]);
});
});
@@ -0,0 +1,51 @@
export type ResponseContractParser<TResult> = (response: { json: () => Promise<unknown> }) => Promise<TResult>;
export interface ResponseContractFixture<TResult> {
name: string;
payload: unknown;
expected?: TResult;
rejects?: true;
}
/**
* Runs JSON-like fixtures through the same parser used by an integration.
* This keeps contribution fixtures transport-free and deterministic while
* still exercising schema validation and response mapping.
*/
export const simulateResponseContractAsync = async <TParsed, TResult = TParsed>(
parser: ResponseContractParser<TParsed>,
fixtures: readonly ResponseContractFixture<TResult>[],
map: (parsed: TParsed) => TResult = (parsed) => parsed as unknown as TResult,
) => {
const results: { name: string; passed: boolean; message?: string }[] = [];
for (const fixture of fixtures) {
try {
const parsed = await parser({ json: () => Promise.resolve(structuredClone(fixture.payload)) });
if (fixture.rejects) {
results.push({
name: fixture.name,
passed: false,
message: "Expected parser rejection, but parsing succeeded.",
});
continue;
}
const actual = map(parsed);
const passed = isDeepStrictEqual(actual, fixture.expected);
results.push({
name: fixture.name,
passed,
message: passed ? undefined : "Parsed output did not match expected.",
});
} catch (error) {
results.push({
name: fixture.name,
passed: fixture.rejects === true,
message: fixture.rejects ? undefined : error instanceof Error ? error.message : String(error),
});
}
}
return results;
};
import { isDeepStrictEqual } from "node:util";
+2
View File
@@ -102,3 +102,5 @@ export { downloadClientItemSchema } from "./interfaces/downloads/download-client
// Helpers
export { createIntegrationAsync } from "./base/creator";
export { simulateResponseContractAsync } from "./base/response-contract";
export type { ResponseContractFixture, ResponseContractParser } from "./base/response-contract";
+1
View File
@@ -23,6 +23,7 @@
"dependencies": {
"@homarr/api": "workspace:^0.1.0",
"@homarr/common": "workspace:^0.1.0",
"@homarr/definitions": "workspace:^0.1.0",
"@homarr/form": "workspace:^0.1.0",
"@homarr/forms-collection": "workspace:^0.1.0",
"@homarr/modals": "workspace:^0.1.0",
@@ -1,12 +1,12 @@
import { useMemo, useState } from "react";
import { Box, Button, Card, Center, Group, Stack, Text, Tooltip } from "@mantine/core";
import { Center, Group, Stack, Text, Tooltip } from "@mantine/core";
import { IconPlus } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { createModal, modalSizeSelect, useModalAction } from "@homarr/modals";
import { useI18n } from "@homarr/translation/client";
import { SelectGridLayout, selectGridCardHeight } from "@homarr/ui";
import { CatalogItem, SelectGridLayout, selectGridCardHeight } from "@homarr/ui";
import { QuickAddAppModal } from "./quick-add-app/quick-add-app-modal";
@@ -56,13 +56,11 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
}}
>
{innerProps.withCreate && (
<Card
h={selectGridCardHeight}
withBorder
pos="relative"
style={{ overflow: "hidden", "--_hover-opacity": "0" }}
onMouseEnter={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "1")}
onMouseLeave={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "0")}
<CatalogItem
height={selectGridCardHeight}
label={t("app.action.create.title")}
status={t("app.action.create.action")}
onSelect={handleAddNewApp}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
@@ -74,35 +72,20 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
{t("app.action.create.description")}
</Text>
</Stack>
<Box
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
style={{
opacity: "var(--_hover-opacity)",
transition: "opacity 150ms ease",
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={handleAddNewApp} variant="light" size="xs" fullWidth>
<Text size="xs" c="blue" fw={500} mt="auto">
{t("app.action.create.action")}
</Button>
</Box>
</Card>
</Text>
</Stack>
</CatalogItem>
)}
{filteredApps.map((app) => (
<Card
<CatalogItem
key={app.id}
h={selectGridCardHeight}
withBorder
pos="relative"
style={{ overflow: "hidden", "--_hover-opacity": "0" }}
onMouseEnter={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "1")}
onMouseLeave={(e) => e.currentTarget.style.setProperty("--_hover-opacity", "0")}
height={selectGridCardHeight}
label={app.name}
status={t("app.action.select.action", { app: app.name })}
onSelect={() => handleSelect(app)}
>
<Stack h="100%" gap="xs">
<Group gap="sm" wrap="nowrap" align="flex-start">
@@ -116,24 +99,11 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
{app.description ?? ""}
</Text>
</Tooltip>
</Stack>
<Box
pos="absolute"
bottom={0}
left={0}
right={0}
p="xs"
style={{
opacity: "var(--_hover-opacity)",
transition: "opacity 150ms ease",
background: "linear-gradient(transparent, var(--mantine-color-body) 30%)",
}}
>
<Button onClick={() => handleSelect(app)} variant="light" size="xs" fullWidth>
<Text size="xs" c="blue" fw={500} mt="auto">
{t("app.action.select.action", { app: app.name })}
</Button>
</Box>
</Card>
</Text>
</Stack>
</CatalogItem>
))}
{filteredApps.length === 0 && !isPending && (
@@ -1,3 +1,4 @@
import { useRouter } from "next/navigation";
import { Button, Group, InputWrapper, Slider, Stack, Switch, TextInput } from "@mantine/core";
import { useDebouncedValue } from "@mantine/hooks";
import { IconAlertTriangle, IconCircleCheck } from "@tabler/icons-react";
@@ -12,6 +13,7 @@ import { boardColumnCountSchema, boardCreateSchema, boardNameSchema } from "@hom
export const AddBoardModal = createModal(({ actions }) => {
const t = useI18n();
const router = useRouter();
const form = useZodForm(boardCreateSchema, {
mode: "controlled",
initialValues: {
@@ -34,17 +36,20 @@ export const AddBoardModal = createModal(({ actions }) => {
// Prevent submit before name availability check
if (!boardNameStatus.canSubmit) return;
mutate(values, {
onSuccess: () => {
onSuccess: (result) => {
actions.closeModal();
showSuccessNotification({
title: "Board created",
message: `Board ${values.name} has been created`,
title: t("board.action.create.notification.success.title"),
message: t("board.action.create.notification.success.message", { name: values.name }),
});
const name = encodeURIComponent(result.name);
const layoutId = encodeURIComponent(result.layoutId);
router.push(`/boards/${name}?layout=${layoutId}&edit=true&add=true`);
},
onError() {
showErrorNotification({
title: "Failed to create board",
message: `Board ${values.name} could not be created`,
title: t("board.action.create.notification.error.title"),
message: t("board.action.create.notification.error.message", { name: values.name }),
});
},
});
@@ -110,7 +115,7 @@ export const useBoardNameStatus = (name: string) => {
? undefined
: isLoading
? {
label: "Checking availability...",
label: t("board.action.create.availability.checking"),
}
: boardExists === undefined
? undefined
@@ -122,7 +127,7 @@ export const useBoardNameStatus = (name: string) => {
}
: {
icon: IconCircleCheck,
label: `${debouncedName} is available`,
label: t("board.action.create.availability.available", { name: debouncedName }),
color: "green",
},
};
@@ -3,6 +3,7 @@ import { z } from "zod/v4";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { buildDockerServiceUrlCandidates } from "@homarr/definitions";
import { useZodForm } from "@homarr/form";
import { createModal } from "@homarr/modals";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
@@ -10,6 +11,7 @@ import { useI18n } from "@homarr/translation/client";
interface AddDockerAppToHomarrProps {
selectedContainers: RouterOutputs["docker"]["getContainers"]["containers"];
initialUrls?: string[];
}
export const AddDockerAppToHomarrModal = createModal<AddDockerAppToHomarrProps>(({ actions, innerProps }) => {
@@ -20,12 +22,17 @@ export const AddDockerAppToHomarrModal = createModal<AddDockerAppToHomarrProps>(
}),
{
initialValues: {
containerUrls: innerProps.selectedContainers.map((container) => {
if (Array.isArray(container.ports) && container.ports[0]) {
return `http://${container.ports[0].IP}:${container.ports[0].PublicPort}`;
}
containerUrls: innerProps.selectedContainers.map((container, index) => {
const initialUrl = innerProps.initialUrls?.[index];
if (initialUrl) return initialUrl;
return null;
return (
buildDockerServiceUrlCandidates({
containerName: container.name,
endpointHost: container.host,
ports: container.ports,
}).find(({ url, scopes }) => url.length > 0 && scopes.includes("browser"))?.url ?? null
);
}),
},
},
@@ -0,0 +1,19 @@
import { describe, expect, test, vi } from "vitest";
import { createDockerRemovalConfirmation } from "./confirm-docker-container-removal";
describe("createDockerRemovalConfirmation", () => {
test("does not remove containers before explicit confirmation", () => {
const remove = vi.fn();
const t = vi.fn((key: string, values?: Record<string, string>) => `${key}:${JSON.stringify(values)}`);
const confirmation = createDockerRemovalConfirmation([{ name: "sonarr" }, { name: "radarr" }], t as never, remove);
expect(remove).not.toHaveBeenCalled();
expect(confirmation.title).toContain('"count":"2"');
expect(confirmation.children).toContain('"names":"sonarr, radarr"');
confirmation.onConfirm();
expect(remove).toHaveBeenCalledOnce();
});
});
@@ -0,0 +1,36 @@
"use client";
import { useCallback } from "react";
import { useConfirmModal } from "@homarr/modals";
import { useScopedI18n } from "@homarr/translation/client";
interface DockerContainerName {
name: string;
}
export const createDockerRemovalConfirmation = (
containers: DockerContainerName[],
t: ReturnType<typeof useScopedI18n<"docker.action.remove">>,
onConfirm: () => void | Promise<void>,
) => ({
title: t("confirmation.title", { count: String(containers.length) }),
children: t("confirmation.message", {
count: String(containers.length),
names: containers.map(({ name }) => name).join(", "),
}),
confirmProps: { children: t("label"), color: "red.9" },
onConfirm,
});
export const useDockerContainerRemovalConfirmation = () => {
const t = useScopedI18n("docker.action.remove");
const { openConfirmModal } = useConfirmModal();
return useCallback(
(containers: DockerContainerName[], onConfirm: () => void | Promise<void>) => {
openConfirmModal(createDockerRemovalConfirmation(containers, t, onConfirm));
},
[openConfirmModal, t],
);
};
@@ -1 +1,5 @@
export { AddDockerAppToHomarrModal as AddDockerAppToHomarr } from "./add-docker-app-to-homarr";
export {
createDockerRemovalConfirmation,
useDockerContainerRemovalConfirmation,
} from "./confirm-docker-container-removal";
+1
View File
@@ -2,3 +2,4 @@ export { ModalProvider, useModalAction, useConfirmModal } from "./src";
export { createModal } from "./src/creator";
export { ModalFormFooter } from "./src/modal-form-footer";
export { modalSizeForm, modalSizeSelect } from "./src/modal-sizes";
export type { ModalPresentation } from "./src/modal-presentation";
+8 -1
View File
@@ -14,6 +14,8 @@ import { ConfirmModal } from "./confirm-modal";
import type { ModalsState, ModalStateWithReference } from "./reducer";
import { modalReducer } from "./reducer";
import type { inferInnerProps, ModalDefinition } from "./type";
import presentationClasses from "./modal-presentation.module.css";
import { getModalPresentationClassNames } from "./modal-presentation";
interface ModalContextProps {
openModalInner: <TModal extends ModalDefinition>(props: {
@@ -94,7 +96,11 @@ const ActiveModal = ({ modal, state, handleCloseModal }: ActiveModalProps) => {
setTimeout(() => setOpened(true), 0);
}, []);
const { defaultTitle: _ignored, ...otherModalProps } = modal.reference.modalProps;
const { defaultTitle: _ignored, presentation, ...otherModalProps } = modal.reference.modalProps;
const presentationClassNames = getModalPresentationClassNames(presentation, {
inner: presentationClasses.inspectorInner,
content: presentationClasses.inspectorContent,
});
return (
<Modal
@@ -113,6 +119,7 @@ const ActiveModal = ({ modal, state, handleCloseModal }: ActiveModalProps) => {
},
}}
trapFocus={modal.id === state.current?.id}
classNames={presentationClassNames}
{...otherModalProps}
title={translateIfNecessary(t, modal.props.defaultTitle)}
opened={opened}
@@ -0,0 +1,30 @@
.inspectorInner {
align-items: flex-end;
justify-content: center;
padding: 0;
}
.inspectorContent {
--modal-content-flex: 0 0 100%;
--modal-content-max-height: min(88dvh, 52rem);
width: 100%;
max-width: 100%;
border-radius: var(--mantine-radius-lg) var(--mantine-radius-lg) 0 0;
}
@media (min-width: 48em) {
.inspectorInner {
align-items: stretch;
justify-content: flex-end;
}
.inspectorContent {
--modal-content-flex: 0 0 min(34rem, 46vw);
--modal-content-height: 100dvh;
--modal-content-max-height: 100dvh;
width: min(34rem, 46vw);
border-radius: 0;
}
}
@@ -0,0 +1,5 @@
declare const classes: {
readonly inspectorInner: string;
readonly inspectorContent: string;
};
export default classes;
@@ -0,0 +1,19 @@
import { describe, expect, test } from "vitest";
import { getModalPresentationClassNames } from "./modal-presentation";
describe("getModalPresentationClassNames", () => {
const inspectorClassNames = { inner: "inspector-inner", content: "inspector-content" };
test("leaves the default modal presentation unchanged", () => {
expect(getModalPresentationClassNames("default", inspectorClassNames)).toBeUndefined();
expect(getModalPresentationClassNames(undefined, inspectorClassNames)).toBeUndefined();
});
test("selects the dock and sheet selectors for inspector modals", () => {
expect(getModalPresentationClassNames("inspector", inspectorClassNames)).toEqual({
inner: "inspector-inner",
content: "inspector-content",
});
});
});
+18
View File
@@ -0,0 +1,18 @@
export type ModalPresentation = "default" | "inspector";
interface InspectorClassNames {
inner: string;
content: string;
}
export const getModalPresentationClassNames = (
presentation: ModalPresentation | undefined,
inspectorClassNames: InspectorClassNames,
) => {
if (presentation !== "inspector") return undefined;
return {
inner: inspectorClassNames.inner,
content: inspectorClassNames.content,
};
};
+4
View File
@@ -3,6 +3,8 @@ import type { ModalProps } from "@mantine/core";
import type { stringOrTranslation } from "@homarr/translation";
import type { ModalPresentation } from "./modal-presentation";
export type ModalComponent<TInnerProps> = (props: {
actions: { closeModal: () => void };
innerProps: TInnerProps;
@@ -23,6 +25,7 @@ export type CreateModalOptions = Pick<
| "closeOnEscape"
> & {
defaultTitle: stringOrTranslation;
presentation?: ModalPresentation;
};
export interface ModalDefinition {
@@ -34,6 +37,7 @@ export interface ModalDefinition {
type ModalOptions<TInnerProps> = Partial<Omit<ModalProps, "opened">> & {
innerProps: TInnerProps;
defaultTitle?: stringOrTranslation;
presentation?: ModalPresentation;
};
export interface ModalState<TModal extends ModalDefinition = ModalDefinition> {
+67 -30
View File
@@ -8,7 +8,7 @@ import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { db, like, or } from "@homarr/db";
import { icons } from "@homarr/db/schema";
import { extractContainerImageName } from "@homarr/definitions";
import type { ContainerState, Port } from "@homarr/docker";
import type { ContainerState, DockerContainerTarget, DockerEndpointStatus, Port } from "@homarr/docker";
import { dockerLabels, DockerSingleton } from "@homarr/docker";
import { createDockerLogStreamProcessor, decodeDockerLogs } from "./docker-log-decode";
@@ -173,7 +173,26 @@ const mockContainers: {
export const dockerContainersRequestHandler = createWidgetRequestHandler({
async requestAsync() {
if (isDemoMode) {
return mockContainers;
return {
containers: mockContainers.map((container) => ({
...container,
endpointId: "demo",
endpointName: "Demo Docker",
resourceId: `demo:${container.id}`,
})),
endpoints: [
{
id: "demo",
name: "Demo Docker",
status: "available",
kind: "docker",
transport: "socket",
capabilities: ["inventory"],
source: "default",
scope: "admin",
},
] satisfies DockerEndpointStatus[],
};
}
return await getContainersWithStatsAsync();
},
@@ -181,29 +200,26 @@ export const dockerContainersRequestHandler = createWidgetRequestHandler({
const extractImage = (container: ContainerInfo) => extractContainerImageName(container.Image);
const findContainerByIdAsync = async (id: string) => {
const dockerInstances = DockerSingleton.getInstances();
const containers = await Promise.all(
dockerInstances.map(async ({ instance }) => {
const container = instance.getContainer(id);
export const hasDockerEndpointCapability = (
endpointId: string,
capability: "inventory" | "logs" | "lifecycle" | "remove",
) => DockerSingleton.hasCapability(endpointId, capability);
return await new Promise<Container | null>((resolve) => {
container.inspect((err, data) => {
if (err || !data) {
resolve(null);
} else {
resolve(container);
}
});
});
}),
);
export const findDockerContainerAsync = async (
{ endpointId, id }: DockerContainerTarget,
requiredCapability: "inventory" | "logs" | "lifecycle" | "remove" = "inventory",
) => {
const dockerInstance = DockerSingleton.findInstance(endpointId);
if (!dockerInstance || !hasDockerEndpointCapability(endpointId, requiredCapability)) return null;
return containers.find((container) => container) ?? null;
const container = dockerInstance.instance.getContainer(id);
return await new Promise<Container | null>((resolve) => {
container.inspect((err, data) => resolve(err || !data ? null : container));
});
};
export const getContainerLogsAsync = async (id: string, tail = 200) => {
const container = await findContainerByIdAsync(id);
export const getContainerLogsAsync = async (target: DockerContainerTarget, tail = 200) => {
const container = await findDockerContainerAsync(target, "logs");
if (!container) {
return null;
}
@@ -219,12 +235,12 @@ export const getContainerLogsAsync = async (id: string, tail = 200) => {
};
export const streamContainerLogsAsync = async (
id: string,
target: DockerContainerTarget,
tail: number,
onData: (data: string) => void,
onError: (err: Error) => void,
) => {
const container = await findContainerByIdAsync(id);
const container = await findDockerContainerAsync(target, "logs");
if (!container) {
onError(new Error("Container not found"));
return () => undefined;
@@ -259,25 +275,40 @@ export const streamContainerLogsAsync = async (
};
};
async function getContainersWithStatsAsync() {
export async function getContainersWithStatsAsync() {
const dockerInstances = DockerSingleton.getInstances();
const results = await Promise.allSettled(
dockerInstances.map(async ({ instance, host }) => {
dockerInstances.map(async ({ instance, host, endpointId, endpointName }) => {
const instanceContainers = await instance.listContainers({ all: true });
return instanceContainers
.filter((container) => !(dockerLabels.hide in container.Labels))
.map((container) => ({ ...container, instance: host }));
.map((container) => ({ ...container, instance: host, endpointId, endpointName }));
}),
);
const endpoints = results.map((result, index) => {
const dockerInstance = dockerInstances.at(index);
if (!dockerInstance) throw new Error("Docker endpoint result did not match a configured endpoint");
return {
id: dockerInstance.endpointId,
name: dockerInstance.endpointName,
status: result.status === "fulfilled" ? "available" : "unavailable",
kind: dockerInstance.descriptor.kind,
transport: dockerInstance.descriptor.transport.type,
capabilities: dockerInstance.descriptor.capabilities,
source: dockerInstance.descriptor.source,
scope: dockerInstance.descriptor.scope,
} satisfies DockerEndpointStatus;
});
const containers = results.flatMap((result, index) => {
if (result.status === "fulfilled") return result.value;
const dockerInstance = dockerInstances.at(index);
logger.warn(
new ErrorWithMetadata(
"Failed to list containers from Docker host",
{
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
host: dockerInstances[index]!.host,
host: dockerInstance?.host ?? "unknown",
},
{ cause: result.reason },
),
@@ -295,7 +326,7 @@ async function getContainersWithStatsAsync() {
: [];
const containerStatsPromises = containers.map(async (container) => {
const instance = dockerInstances.find(({ host }) => host === container.instance)?.instance;
const instance = DockerSingleton.findInstance(container.endpointId)?.instance;
if (!instance) return null;
const stats = await instance
@@ -314,6 +345,9 @@ async function getContainersWithStatsAsync() {
return {
id: container.Id,
endpointId: container.endpointId,
endpointName: container.endpointName,
resourceId: `${container.endpointId}:${container.Id}`,
name: container.Names[0]?.split("/")[1] ?? "Unknown",
host: container.instance,
state: container.State as ContainerState,
@@ -325,7 +359,10 @@ async function getContainersWithStatsAsync() {
};
});
return (await Promise.all(containerStatsPromises)).filter((container) => container !== null);
return {
containers: (await Promise.all(containerStatsPromises)).filter((container) => container !== null),
endpoints,
};
}
export function calculateCpuUsage(stats: ContainerStats): number {
@@ -1,8 +1,10 @@
import { usePathname, useRouter, useSearchParams } from "next/navigation";
import { Group, Text } from "@mantine/core";
import {
IconBox,
IconCategoryPlus,
IconMailForward,
IconPlus,
IconPlug,
IconUserPlus,
IconUsersGroup,
@@ -47,8 +49,26 @@ export const globalCommandGroup = createGroup<Command>({
useOptions() {
const tOption = useScopedI18n("search.mode.command.group.globalCommand.option");
const { data: session } = useSession();
const pathname = usePathname();
const router = useRouter();
const searchParams = useSearchParams();
const commands: (Command & { hidden?: boolean })[] = [
{
commandKey: "create",
icon: IconPlus,
name: tOption("create.label"),
useInteraction() {
return {
type: "javaScript",
onSelect() {
const nextSearchParams = new URLSearchParams(searchParams.toString());
nextSearchParams.set("create", "true");
router.replace(`${pathname}?${nextSearchParams.toString()}`, { scroll: false });
},
};
},
},
{
commandKey: "newBoard",
icon: IconCategoryPlus,
+240
View File
@@ -239,6 +239,65 @@
}
}
},
"universalCreate": {
"title": "Create",
"trigger": {
"label": "Create something",
"description": "Add content, connect a service, or create a board from one place."
},
"search": {
"label": "Search create actions",
"placeholder": "What do you want to create?",
"noResults": "No matching actions"
},
"group": {
"currentBoard": "Current board",
"library": "Apps and services",
"boards": "Boards"
},
"action": {
"widget": {
"label": "Add widget",
"description": "Add live information or controls to this board.",
"keywords": "item dashboard content"
},
"app": {
"label": "Add or create app",
"description": "Place an app shortcut on this board or create one for your library.",
"keywords": "shortcut bookmark application"
},
"integration": {
"label": "Connect service",
"description": "Connect a service so widgets can use its data.",
"keywords": "integration provider connection"
},
"container": {
"label": "Add container",
"description": "Group related board content into a resizable section.",
"keywords": "section group layout"
},
"board": {
"label": "Create board",
"description": "Start a new dashboard and add its first widget.",
"keywords": "dashboard page"
},
"importBoard": {
"label": "Import board",
"description": "Bring an existing Homarr board configuration into this instance.",
"keywords": "upload oldmarr migrate"
},
"workshop": {
"label": "Browse Workshop",
"description": "Discover community-built widgets and install them.",
"keywords": "community discover install"
},
"customWidget": {
"label": "Create custom widget",
"description": "Build a widget tailored to your own workflow.",
"keywords": "code jsx developer"
}
}
},
"user": {
"title": "Users",
"name": "User",
@@ -1443,6 +1502,23 @@
"installedDescription": "{name} is ready to configure."
},
"integration": {
"completion": {
"modalTitle": "Service ready",
"title": "{name} is connected",
"description": "The connection passed its test. Choose what to show on this board next.",
"connectionReady": "Service connection is ready",
"appReady": "App shortcut is ready",
"compatibleWidgets": "{count, plural, =0 {No compatible widgets} one {# compatible widget} other {# compatible widgets}} available",
"chooseWidget": "Choose widget",
"recipes": {
"title": "Recommended for this board",
"description": "Based on connected services and widgets already on this board.",
"newConnectionReason": "Now available through {integration}",
"existingConnectionReason": "Works with a service you already connected",
"add": "Add",
"dismiss": "Dismiss recommendations for this service on this board"
}
},
"page": {
"list": {
"title": "Integrations",
@@ -1997,6 +2073,7 @@
"loading": "Loading",
"show": "Show",
"hide": "Hide"
,"undo": "Undo"
},
"here": "here",
"iconPicker": {
@@ -2439,6 +2516,7 @@
"retry": "Try again",
"noIntegrationTitle": "A compatible integration is required",
"noIntegrationDescription": "Configure an integration supported by this widget before adding it to the dashboard.",
"connectIntegration": "Connect service",
"manageIntegrations": "Manage integrations",
"skip": "Do not add",
"errorTitle": "Widget settings could not be prepared",
@@ -2607,7 +2685,27 @@
"search": "Filter items",
"addToBoard": "Add to board",
"addAtPosition": "Add item here",
"destination": {
"label": "Add to",
"description": "Choose where the widget should appear. You can still move it later.",
"mainCanvas": "Main canvas",
"leftRail": "Left rail",
"rightRail": "Right rail"
},
"connectionStatus": {
"ready": "Ready",
"needsSetup": "Needs setup",
"noConnectionRequired": "No connection required"
},
"missingIntegration": {
"title": "Connect a service first",
"noPermission": "This widget needs a compatible service connection. Ask an administrator to connect one, then try again."
},
"notification": {
"success": {
"title": "Widget added",
"message": "{name} was added to this board."
},
"error": {
"title": "Unable to add item",
"message": "The item could not be added to this board"
@@ -3586,6 +3684,7 @@
},
"error": {
"internalServerError": "Failed to fetch containers stats",
"endpointsUnavailable": "Docker endpoints are unavailable",
"layoutSaveTitle": "Table layout not saved",
"layoutSaveMessage": "The Docker table layout could not be saved. Try moving or resizing the column again."
},
@@ -5554,10 +5653,58 @@
}
},
"board": {
"emptyState": {
"title": "Build your first view",
"description": "Add a widget or app, or connect a service and use its data on this board.",
"addWidget": "Add widget",
"addApp": "Add app",
"connectService": "Connect service"
},
"setupChecklist": {
"title": "Make this board useful",
"description": "Pick up where you left off. Progress follows the content already on this board.",
"collapse": "Collapse setup checklist",
"resume": "Continue setup ({completed}/{total})",
"progress": "Board setup progress",
"step": {
"content": {
"label": "Add useful content",
"description": "Choose a widget and configure it before it is placed.",
"action": "Add"
},
"app": {
"label": "Pin an app",
"description": "Keep a service or tool one click away from this board.",
"action": "Add"
},
"service": {
"label": "Connect a service",
"description": "Unlock live data and actions for compatible widgets.",
"permissionDescription": "An administrator can connect a service to unlock live data.",
"action": "Connect"
}
}
},
"action": {
"addContent": "Add board content",
"settings": "Board settings",
"switch": "Switch board",
"create": {
"availability": {
"checking": "Checking availability…",
"available": "{name} is available"
},
"notification": {
"success": {
"title": "Board created",
"message": "Board {name} has been created"
},
"error": {
"title": "Unable to create board",
"message": "Board {name} could not be created"
}
}
},
"duplicate": {
"title": "Duplicate board",
"message": "This will duplicate the board {name} with all its content. If widgets reference integrations, that you are not allowed to use, they will be removed.",
@@ -6866,6 +7013,73 @@
},
"docker": {
"title": "Containers",
"reconciliation": {
"title": "Service setup",
"description": "Docker services are compared with your apps and integrations. Review every suggestion before Homarr changes anything.",
"attention": "{count} need attention",
"endpointUnavailable": "Some services could not be checked because these endpoints are unavailable: {names}",
"empty": "No visible Docker services were found.",
"emptyFilter": "No services match this view.",
"ambiguous": "More than one existing item could match this service. Homarr will not choose one automatically.",
"match": "{confidence} confidence match",
"filter": {
"attention": "Needs attention",
"represented": "Already set up",
"all": "All"
},
"confidence": {
"high": "High",
"medium": "Medium"
},
"state": {
"newRecognized": "Ready to connect",
"newApp": "New service",
"represented": "Already represented",
"linked": "Linked",
"moved": "Address changed"
},
"url": {
"label": "Service address",
"manual": "Enter an address manually"
},
"reason": {
"publishedAddress": "Published address reported by Docker",
"dockerEndpointHost": "Docker endpoint host combined with the published port",
"sharedContainerNetwork": "Server-only address for services sharing the container network",
"manualHostRequired": "Enter the address that your browser or Homarr server can reach"
},
"health": {
"title": "Observed service layers",
"layer": {
"docker": "Docker",
"integrationConfiguration": "Integration",
"authentication": "Authentication",
"apiRequest": "API",
"appRepresentation": "App",
"widgetConfiguration": "Widget",
"widgetQuery": "Widget query"
},
"status": {
"available": "Available",
"configured": "Configured",
"linked": "Linked",
"missing": "Missing",
"changed": "Changed",
"unused": "Not used",
"notApplicable": "Not applicable",
"notObserved": "Not observed"
}
},
"action": {
"refresh": "Refresh",
"dismiss": "Dismiss",
"restoreDismissed": "Restore dismissed ({count})",
"setupIntegration": "Set up integration",
"createApp": "Create app",
"reviewIntegration": "Review integration",
"viewRepresentation": "View setup"
}
},
"table": {
"updated": "Updated {when}",
"refresh": {
@@ -6961,6 +7175,10 @@
"remove": {
"label": "Remove",
"confirm": "Click again to remove permanently",
"confirmation": {
"title": "Remove {count} container(s)?",
"message": "This permanently removes {count} container(s): {names}"
},
"notification": {
"success": {
"title": "Containers removed",
@@ -6972,6 +7190,12 @@
}
}
},
"result": {
"failure": {
"title": "Some container actions failed",
"message": "{failed} of {total} action(s) failed: {names}"
}
},
"refresh": {
"label": "Refresh",
"notification": {
@@ -7004,10 +7228,21 @@
},
"error": {
"internalServerError": "Failed to fetch Docker containers",
"endpointUnavailable": "{count} Docker endpoint(s) unavailable: {names}",
"noColumns": "Select at least one column in the widget settings"
}
},
"kubernetes": {
"context": {
"label": "Kubernetes context",
"status": {
"available": "Available",
"degraded": "Metrics unavailable",
"unavailable": "Unavailable"
},
"unavailable": "This Kubernetes context cannot be reached. Select another context or verify its credentials and endpoint.",
"metricsUnavailable": "This context is reachable, but Metrics Server is unavailable. Inventory remains available without live CPU and memory usage."
},
"cluster": {
"title": "Cluster Dashboard",
"label": "Cluster",
@@ -7016,6 +7251,7 @@
"architecture": "Architecture",
"capacity": {
"title": "Capacity",
"metricsUnavailable": "Metrics Server is unavailable. Inventory and reserved capacity remain visible, but live CPU and memory usage cannot be shown.",
"resource": {
"reserved": "Reserved",
"used": "Used"
@@ -7036,6 +7272,7 @@
"nodes": {
"label": "Nodes",
"field": {
"metricsUnavailable": "Unavailable",
"name": {
"label": "Name"
},
@@ -7463,6 +7700,9 @@
"globalCommand": {
"title": "Global commands",
"option": {
"create": {
"label": "Create something"
},
"colorScheme": {
"auto": "Toggle appearance mode",
"light": "Switch to light mode",
@@ -0,0 +1,29 @@
.root {
width: 100%;
color: inherit;
font: inherit;
text-align: start;
cursor: pointer;
}
.root:focus-visible {
outline: 2px solid var(--mantine-primary-color-filled);
outline-offset: 2px;
}
.root[data-selected] {
border-color: var(--mantine-primary-color-filled);
border-width: 2px;
}
.root:disabled {
cursor: not-allowed;
opacity: 0.6;
}
@media (forced-colors: active) {
.root:focus-visible,
.root[data-selected] {
outline: 2px solid Highlight;
}
}
@@ -0,0 +1,2 @@
declare const classes: Record<string, string>;
export default classes;
@@ -0,0 +1,135 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot } from "react-dom/client";
import type { Root } from "react-dom/client";
import { MantineProvider } from "@mantine/core";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { CatalogItem, getCatalogKeyboardDirection } from "./catalog-item";
let root: Root;
let host: HTMLDivElement;
beforeEach(() => {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
window.matchMedia = vi.fn().mockImplementation(() => ({
matches: false,
media: "",
onchange: null,
addListener: vi.fn(),
removeListener: vi.fn(),
addEventListener: vi.fn(),
removeEventListener: vi.fn(),
dispatchEvent: vi.fn(),
}));
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(async () => {
await act(() => root.unmount());
host.remove();
});
describe("CatalogItem", () => {
it("uses one native button surface with selected and status semantics", async () => {
const onSelect = vi.fn();
await act(async () =>
root.render(
<MantineProvider>
<CatalogItem label="Sonarr" status="Ready" selected onSelect={onSelect}>
Sonarr
</CatalogItem>
</MantineProvider>,
),
);
const button = host.querySelector("button");
expect(button?.type).toBe("button");
expect(button?.getAttribute("aria-label")).toBe("Sonarr, Ready");
expect(button?.getAttribute("aria-pressed")).toBe("true");
await act(async () => button?.click());
expect(onSelect).toHaveBeenCalledOnce();
});
it("exposes busy state and blocks duplicate selection", async () => {
const onSelect = vi.fn();
await act(async () =>
root.render(
<MantineProvider>
<CatalogItem label="Weather" busy onSelect={onSelect}>
Weather
</CatalogItem>
</MantineProvider>,
),
);
const button = host.querySelector("button");
expect(button?.disabled).toBe(true);
expect(button?.getAttribute("aria-busy")).toBe("true");
await act(async () => button?.click());
expect(onSelect).not.toHaveBeenCalled();
});
it("normalizes grid navigation keys for catalog roving focus", () => {
expect(getCatalogKeyboardDirection("ArrowRight")).toBe("next");
expect(getCatalogKeyboardDirection("ArrowDown")).toBe("next");
expect(getCatalogKeyboardDirection("ArrowLeft")).toBe("previous");
expect(getCatalogKeyboardDirection("Home")).toBe("first");
expect(getCatalogKeyboardDirection("End")).toBe("last");
expect(getCatalogKeyboardDirection("Enter")).toBeNull();
});
it("offers arrow-key movement without replacing native Enter and Space activation", async () => {
const onSelect = vi.fn();
const onMoveFocus = vi.fn();
await act(async () =>
root.render(
<MantineProvider>
<CatalogItem label="Sonarr" onSelect={onSelect} onMoveFocus={onMoveFocus}>
Sonarr
</CatalogItem>
</MantineProvider>,
),
);
const button = host.querySelector("button");
await act(async () => button?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })));
expect(onMoveFocus).toHaveBeenCalledWith("next");
await act(async () => button?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
expect(onMoveFocus).toHaveBeenCalledOnce();
});
it("moves focus between enabled sibling catalog items by default", async () => {
await act(async () =>
root.render(
<MantineProvider>
<div>
<CatalogItem label="First" onSelect={vi.fn()}>
First
</CatalogItem>
<CatalogItem label="Disabled" disabled onSelect={vi.fn()}>
Disabled
</CatalogItem>
<CatalogItem label="Last" onSelect={vi.fn()}>
Last
</CatalogItem>
</div>
</MantineProvider>,
),
);
const [first, , last] = host.querySelectorAll("button");
first?.focus();
await act(async () => first?.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true })));
expect(document.activeElement).toBe(last);
await act(async () => last?.dispatchEvent(new KeyboardEvent("keydown", { key: "Home", bubbles: true })));
expect(document.activeElement).toBe(first);
});
});
@@ -0,0 +1,88 @@
import type { KeyboardEvent, ReactNode } from "react";
import { Card } from "@mantine/core";
import classes from "./catalog-item.module.css";
interface CatalogItemProps {
label: string;
status?: string;
selected?: boolean;
disabled?: boolean;
busy?: boolean;
height?: number;
onSelect: () => void;
onFocus?: () => void;
onPointerEnter?: () => void;
onMoveFocus?: (direction: "next" | "previous" | "first" | "last") => void;
children: ReactNode;
}
export const CatalogItem = ({
label,
status,
selected,
disabled = false,
busy = false,
height,
onSelect,
onFocus,
onPointerEnter,
onMoveFocus,
children,
}: CatalogItemProps) => {
const handleKeyDown = (event: KeyboardEvent<HTMLButtonElement>) => {
const direction = getCatalogKeyboardDirection(event.key);
if (!direction) return;
event.preventDefault();
if (onMoveFocus) onMoveFocus(direction);
else moveCatalogFocus(event.currentTarget, direction);
};
return (
<Card
component="button"
type="button"
className={classes.root}
h={height}
withBorder
disabled={disabled || busy}
aria-busy={busy || undefined}
aria-label={status ? `${label}, ${status}` : label}
aria-pressed={selected}
data-catalog-item
data-selected={selected || undefined}
onClick={onSelect}
onFocus={onFocus}
onPointerEnter={onPointerEnter}
onKeyDown={handleKeyDown}
>
{children}
</Card>
);
};
export const moveCatalogFocus = (current: HTMLButtonElement, direction: "next" | "previous" | "first" | "last") => {
const items = Array.from(
current.parentElement?.querySelectorAll<HTMLButtonElement>("button[data-catalog-item]:not(:disabled)") ?? [],
);
if (items.length === 0) return;
const currentIndex = items.indexOf(current);
const targetIndex =
direction === "first"
? 0
: direction === "last"
? items.length - 1
: direction === "next"
? (currentIndex + 1) % items.length
: (currentIndex - 1 + items.length) % items.length;
items[targetIndex]?.focus();
};
export const getCatalogKeyboardDirection = (key: string) => {
if (key === "ArrowRight" || key === "ArrowDown") return "next" as const;
if (key === "ArrowLeft" || key === "ArrowUp") return "previous" as const;
if (key === "Home") return "first" as const;
if (key === "End") return "last" as const;
return null;
};
+1
View File
@@ -12,6 +12,7 @@ export { UserAvatarGroup } from "./user-avatar-group";
export { CustomPasswordInput } from "./password-input/password-input";
export { IntegrationAvatar } from "./integration-avatar";
export { BetaBadge } from "./beta-badge";
export { CatalogItem } from "./catalog-item";
export { MaskedImage } from "./masked-image";
export { MaskedOrNormalImage } from "./masked-or-normal-image";
export { LanguageIcon } from "./language-icon";
-1
View File
@@ -16,7 +16,6 @@
"./_inputs/json-path-tree-picker": "./src/_inputs/json-path-tree-picker.tsx",
"./custom-api/component": "./src/custom-api/component.tsx",
"./custom-api/custom-jsx-display": "./src/custom-api/custom-jsx-display.tsx",
"./custom-api/extract-display-data": "./src/custom-api/extract-display-data.ts",
"./assistant/context": "./src/assistant/context.tsx",
"./catalog": "./src/catalog.ts",
"./definition": "./src/definition.ts",
+54 -26
View File
@@ -35,10 +35,10 @@ import { useSession } from "@homarr/auth/client";
import { constructBoardPermissions } from "@homarr/auth/shared";
import { useOptionalBoard } from "@homarr/boards/context";
import { formatBytes, useTimeAgo } from "@homarr/common";
import type { ContainerState } from "@homarr/docker";
import type { ContainerState, DockerEndpointCapability } from "@homarr/docker";
import { containerStateColorMap, cpuUsageColor, memoryUsageColor, safeValue } from "@homarr/docker/shared";
import { useModalAction } from "@homarr/modals";
import { AddDockerAppToHomarr } from "@homarr/modals-collection";
import { AddDockerAppToHomarr, useDockerContainerRemovalConfirmation } from "@homarr/modals-collection";
import { showErrorNotification, showSuccessNotification } from "@homarr/notifications";
import { useScopedI18n } from "@homarr/translation/client";
@@ -50,6 +50,7 @@ import { usePersistedTableLayout, useTableLayoutPersistence } from "../common/us
import { getDockerColumnVisibility, getDockerFooterVisibility } from "./layout";
type DockerContainer = RouterOutputs["docker"]["getContainers"]["containers"][number];
type DockerEndpoint = RouterOutputs["docker"]["getContainers"]["endpoints"][number];
type ContainerAction = "start" | "stop" | "restart" | "remove";
interface ContextMenuState {
@@ -59,6 +60,7 @@ interface ContextMenuState {
}
interface ContainerActionHandlers {
canUse: (container: DockerContainer, capability: DockerEndpointCapability) => boolean;
onAction: (action: ContainerAction, container: DockerContainer) => void;
onAddToHomarr: (container: DockerContainer) => void;
onOpenLogs: (container: DockerContainer) => void;
@@ -67,8 +69,10 @@ interface ContainerActionHandlers {
const columnAccessors = ["name", "state", "host", "cpuUsage", "memoryUsage", "actions"] as const;
const containerMenuWidth = 240;
const createContainerLogsPath = (container: Pick<DockerContainer, "id" | "name">) =>
`/manage/tools/docker/logs/${container.id}?name=${encodeURIComponent(container.name)}`;
const createContainerLogsPath = (container: Pick<DockerContainer, "endpointId" | "id" | "name">) =>
`/manage/tools/docker/logs/${container.id}?name=${encodeURIComponent(container.name)}&endpointId=${encodeURIComponent(container.endpointId)}`;
const getContainerTarget = ({ endpointId, id }: DockerContainer) => ({ endpointId, id });
const ContainerStateBadge = ({ state }: { state: ContainerState }) => {
const t = useScopedI18n("docker.field.state.option");
@@ -209,10 +213,11 @@ const useContainerAction = (action: ContainerAction) => {
async onSettled() {
await utils.docker.getContainers.invalidate();
},
onSuccess() {
showSuccessNotification({
title: t(`${action}.notification.success.title`),
message: t(`${action}.notification.success.message`),
onSuccess(results) {
const failed = results.some((result) => !result.success);
(failed ? showErrorNotification : showSuccessNotification)({
title: t(`${action}.notification.${failed ? "error" : "success"}.title`),
message: t(`${action}.notification.${failed ? "error" : "success"}.message`),
});
},
onError() {
@@ -236,6 +241,7 @@ export default function DockerWidget({
const t = useScopedI18n("docker");
const tWidget = useScopedI18n("widget.dockerContainers");
const { openModal } = useModalAction(AddDockerAppToHomarr);
const confirmRemoval = useDockerContainerRemovalConfirmation();
const board = useOptionalBoard();
const { data: session } = useSession();
const hasChangeAccess = board ? constructBoardPermissions(board, session).hasChangeAccess : false;
@@ -254,12 +260,13 @@ export default function DockerWidget({
const { mutate: removeContainer } = useContainerAction("remove");
const handleContainerAction = useCallback(
(action: ContainerAction, container: DockerContainer) => {
if (action === "start") startContainer({ ids: [container.id] });
else if (action === "stop") stopContainer({ ids: [container.id] });
else if (action === "restart") restartContainer({ ids: [container.id] });
else removeContainer({ ids: [container.id] });
const target = { targets: [getContainerTarget(container)] };
if (action === "start") startContainer(target);
else if (action === "stop") stopContainer(target);
else if (action === "restart") restartContainer(target);
else confirmRemoval([container], () => removeContainer(target));
},
[removeContainer, restartContainer, startContainer, stopContainer],
[confirmRemoval, removeContainer, restartContainer, startContainer, stopContainer],
);
const handleOpenLogs = useCallback(
(container: DockerContainer) => window.location.assign(createContainerLogsPath(container)),
@@ -271,11 +278,16 @@ export default function DockerWidget({
);
const actionHandlers = useMemo<ContainerActionHandlers>(
() => ({
canUse: (container, capability) =>
endpointHasCapability(
data?.endpoints.find(({ id }) => id === container.endpointId),
capability,
),
onAction: handleContainerAction,
onAddToHomarr: handleAddToHomarr,
onOpenLogs: handleOpenLogs,
}),
[handleAddToHomarr, handleContainerAction, handleOpenLogs],
[data?.endpoints, handleAddToHomarr, handleContainerAction, handleOpenLogs],
);
const { mutate: saveItemOptions } = clientApi.widget.options.saveItemOptions.useMutation({
@@ -359,6 +371,14 @@ export default function DockerWidget({
);
}
if (containers.length === 0 && data?.endpoints.some(({ status }) => status === "unavailable")) {
return (
<Center h="100%">
<Text>{tWidget("error.endpointsUnavailable")}</Text>
</Center>
);
}
const footerVisibility = getDockerFooterVisibility(width, isAdvanced);
return (
@@ -376,7 +396,7 @@ export default function DockerWidget({
storeColumnsKey={storeKey}
sortStatus={sortStatus}
onSortStatusChange={(isAdvanced || options.enableRowSorting) && !isEditMode ? setSortStatus : undefined}
idAccessor="id"
idAccessor="resourceId"
onRowContextMenu={isEditMode ? undefined : handleContextMenu}
onScroll={() => {
if (contextMenu) closeContextMenu();
@@ -475,7 +495,6 @@ function ContainerActionItems({
onClose: () => void;
}) {
const t = useScopedI18n("docker.action");
const [confirmRemove, setConfirmRemove] = useState(false);
const stateAction = container.state === "running" ? "stop" : "start";
const StateIcon = stateAction === "stop" ? IconPlayerStop : IconPlayerPlay;
@@ -491,6 +510,7 @@ function ContainerActionItems({
</Menu.Label>
<Menu.Item
leftSection={<IconFileText size={14} />}
disabled={!handlers.canUse(container, "logs")}
onClick={() => {
handlers.onOpenLogs(container);
onClose();
@@ -502,22 +522,27 @@ function ContainerActionItems({
<Menu.Item
color={stateAction === "start" ? "green" : "red"}
leftSection={<StateIcon size={14} />}
disabled={!handlers.canUse(container, "lifecycle")}
onClick={() => invokeAction(stateAction)}
>
{t(`${stateAction}.label`)}
</Menu.Item>
<Menu.Item color="orange" leftSection={<IconRotateClockwise size={14} />} onClick={() => invokeAction("restart")}>
<Menu.Item
color="orange"
leftSection={<IconRotateClockwise size={14} />}
disabled={!handlers.canUse(container, "lifecycle")}
onClick={() => invokeAction("restart")}
>
{t("restart.label")}
</Menu.Item>
{!confirmRemove ? (
<Menu.Item color="red" leftSection={<IconTrash size={14} />} onClick={() => setConfirmRemove(true)}>
{t("remove.label")}
</Menu.Item>
) : (
<Menu.Item color="red" leftSection={<IconTrash size={14} />} onClick={() => invokeAction("remove")}>
{t("remove.confirm")}
</Menu.Item>
)}
<Menu.Item
color="red"
leftSection={<IconTrash size={14} />}
disabled={!handlers.canUse(container, "remove")}
onClick={() => invokeAction("remove")}
>
{t("remove.label")}
</Menu.Item>
<Menu.Divider />
<Menu.Item
leftSection={<IconCategoryPlus size={14} />}
@@ -532,6 +557,9 @@ function ContainerActionItems({
);
}
const endpointHasCapability = (endpoint: DockerEndpoint | undefined, capability: DockerEndpointCapability) =>
endpoint && "capabilities" in endpoint ? endpoint.capabilities.includes(capability) : true;
function ContainerContextMenu({
state,
handlers,
@@ -172,13 +172,7 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
onClick={() =>
openModal({
advancedOptions,
onSuccess(options) {
setAdvancedOptions(options);
innerProps.onSuccessfulEdit({
...innerProps.value,
advancedOptions: options,
});
},
onSuccess: setAdvancedOptions,
})
}
>
@@ -194,13 +188,7 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
onClick={() =>
openModal({
advancedOptions,
onSuccess(options) {
setAdvancedOptions(options);
innerProps.onSuccessfulEdit({
...innerProps.value,
advancedOptions: options,
});
},
onSuccess: setAdvancedOptions,
})
}
>
@@ -250,4 +238,6 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
return t("item.edit.title");
},
size: modalSizeForm,
presentation: "inspector",
closeOnClickOutside: false,
});