fix: address release v2 reviews

This commit is contained in:
ajnart committed 2026-08-14 02:18:46 +02:00
1 parent 4905ea6738
commit 32732680e5
55 files changed
+925 -294

No files matched your search

@@ -27,4 +27,37 @@ describe("getTrackedFeatureProperties", () => {
userId: "user-1",
});
});
test("discards setup values outside the closed telemetry contract", () => {
expect(
getTrackedFeatureProperties(
"setup:widget-completed",
{
entryPoint: "https://private.example",
intent: "secret-id",
outcome: "credential",
elapsedMs: Number.POSITIVE_INFINITY,
hasBoardContext: "true",
canResolveInline: 1,
},
"session-user",
),
).toEqual({});
});
test("keeps known widget intents and bounded elapsed times", () => {
expect(
getTrackedFeatureProperties(
"setup:widget-completed",
{ entryPoint: "board", intent: "weather", outcome: "completed", elapsedMs: 0, canResolveInline: false },
"session-user",
),
).toEqual({ entryPoint: "board", intent: "weather", outcome: "completed", elapsedMs: 0, canResolveInline: false });
});
test("keeps the app intent used by Universal Create", () => {
expect(
getTrackedFeatureProperties("setup:intent-selected", { entryPoint: "header", intent: "app" }, "user-1"),
).toEqual({ entryPoint: "header", intent: "app" });
});
});
+27 -10
View File
@@ -1,11 +1,30 @@
const setupPropertyKeys = new Set([
"entryPoint",
"intent",
"outcome",
"elapsedMs",
"hasBoardContext",
"canResolveInline",
import { widgetKinds } from "@homarr/definitions";
const setupEntryPoints = new Set(["header", "spotlight", "board", "assistant", "docker", "management"]);
const setupIntents = new Set([
...widgetKinds,
"widget",
"app",
"integration",
"container",
"board",
"workshop",
"customWidget",
"add-compatible-widget",
]);
const setupOutcomes = new Set(["completed", "blocked", "continued"]);
const maximumSetupElapsedMs = 24 * 60 * 60 * 1_000;
const isValidSetupProperty = (key: string, value: unknown) => {
if (key === "entryPoint") return typeof value === "string" && setupEntryPoints.has(value);
if (key === "intent") return typeof value === "string" && setupIntents.has(value);
if (key === "outcome") return typeof value === "string" && setupOutcomes.has(value);
if (key === "elapsedMs") {
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= maximumSetupElapsedMs;
}
if (key === "hasBoardContext" || key === "canResolveInline") return typeof value === "boolean";
return false;
};
export const getTrackedFeatureProperties = (
feature: string,
@@ -15,8 +34,6 @@ export const getTrackedFeatureProperties = (
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),
),
Object.entries(properties ?? {}).filter(([key, value]) => isValidSetupProperty(key, value)),
);
};
+1 -1
View File
@@ -562,7 +562,7 @@ export const boardRouter = createTRPCRouter({
mcp: {
enabled: true,
description:
"Create a new board with a name, column count (1-24), and isPublic flag. Returns { boardId }. Requires board-create permission",
"Create a new board with a name, column count (1-24), and isPublic flag. Returns { boardId, name, layoutId }. Requires board-create permission",
},
})
.input(boardCreateSchema)
@@ -26,6 +26,11 @@ export const getDockerReconciliationAsync = async (db: Database) => {
}),
db.query.apps.findMany(),
]);
const normalizedIntegrations = integrations.map((integration) => ({
integration,
normalizedUrl: normalizeDockerServiceUrl(integration.url),
}));
const normalizedApps = apps.map((app) => ({ app, normalizedUrl: normalizeDockerServiceUrl(app.href) }));
const containerNameCounts = new Map<string, number>();
for (const container of data.containers) {
const name = normalizeName(container.name);
@@ -44,13 +49,16 @@ export const getDockerReconciliationAsync = async (db: Database) => {
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 sameKindIntegrations = match
? normalizedIntegrations.filter(({ integration }) => integration.kind === match.kind)
: [];
const exactIntegrationMatches = sameKindIntegrations
.filter(({ normalizedUrl }) => normalizedUrl !== null && candidateUrls.has(normalizedUrl))
.map(({ integration }) => integration);
const nameIntegrationMatches = uniqueName
? sameKindIntegrations.filter(({ name }) => normalizeName(name) === normalizeName(container.name))
? sameKindIntegrations
.filter(({ integration }) => normalizeName(integration.name) === normalizeName(container.name))
.map(({ integration }) => integration)
: [];
const exactIntegration = exactIntegrationMatches.length === 1 ? exactIntegrationMatches[0] : undefined;
const nameIntegration =
@@ -58,10 +66,9 @@ export const getDockerReconciliationAsync = async (db: Database) => {
? nameIntegrationMatches[0]
: undefined;
const integration = exactIntegration ?? nameIntegration;
const exactAppMatches = apps.filter(({ href }) => {
const normalizedUrl = normalizeDockerServiceUrl(href);
return normalizedUrl ? candidateUrls.has(normalizedUrl) : false;
});
const exactAppMatches = normalizedApps
.filter(({ normalizedUrl }) => normalizedUrl !== null && candidateUrls.has(normalizedUrl))
.map(({ app }) => app);
const nameAppMatches = uniqueName
? apps.filter(({ name }) => normalizeName(name) === normalizeName(container.name))
: [];
@@ -19,18 +19,40 @@ const dockerContainerTargetSchema = z.object({
endpointId: z.string().min(1),
id: z.string().min(1),
});
const dockerContainerTargetsSchema = z.array(dockerContainerTargetSchema).min(1).max(100);
export const dockerRouter = createTRPCRouter({
reconcileServices: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description:
"Reconcile Docker container inventory with Homarr integrations and apps, including URL matches and recommended setup or repair actions. Requires admin permission.",
},
})
.concat(dockerMiddleware())
.query(async ({ ctx }) => await getDockerReconciliationAsync(ctx.db)),
getServiceHealth: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description:
"Get Docker endpoint and discovered-service health projected across Docker, integration, app, and widget setup layers. Requires admin permission.",
},
})
.concat(dockerMiddleware())
.query(async ({ ctx }) => await getDockerServiceHealthAsync(ctx.db)),
refreshInventory: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description:
"Invalidate the cached Docker inventory so the next Docker query performs a fresh user-requested discovery. Requires admin permission.",
},
})
.concat(dockerMiddleware())
.mutation(() => {
dockerContainersRequestHandler.invalidateCache();
@@ -65,7 +87,7 @@ export const dockerRouter = createTRPCRouter({
},
})
.concat(dockerMiddleware())
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.input(z.object({ targets: dockerContainerTargetsSchema }))
.mutation(async ({ input }) => {
return await performDockerContainerActionsAsync(input.targets, "start");
}),
@@ -78,7 +100,7 @@ export const dockerRouter = createTRPCRouter({
},
})
.concat(dockerMiddleware())
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.input(z.object({ targets: dockerContainerTargetsSchema }))
.mutation(async ({ input }) => {
return await performDockerContainerActionsAsync(input.targets, "stop");
}),
@@ -91,7 +113,7 @@ export const dockerRouter = createTRPCRouter({
},
})
.concat(dockerMiddleware())
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.input(z.object({ targets: dockerContainerTargetsSchema }))
.mutation(async ({ input }) => {
return await performDockerContainerActionsAsync(input.targets, "restart");
}),
@@ -105,7 +127,7 @@ export const dockerRouter = createTRPCRouter({
},
})
.concat(dockerMiddleware())
.input(z.object({ targets: z.array(dockerContainerTargetSchema) }))
.input(z.object({ targets: dockerContainerTargetsSchema }))
.mutation(async ({ input }) => {
return await performDockerContainerActionsAsync(input.targets, "remove");
}),
@@ -280,7 +280,7 @@ export const integrationRouter = createTRPCRouter({
mcp: {
enabled: true,
description:
"Create a new integration (connection to an external service). REQUIRED fields: name, url (http/https), kind, secrets, attemptSearchEngineCreation. The 'secrets' field is REQUIRED and must be a non-empty array — call integration_getKinds first to see which secret kinds each integration type needs. Example for Radarr: secrets=[{kind:'apiKey', value:'your-radarr-api-key'}]. Example for Proxmox: secrets=[{kind:'tokenId', value:'...'}, {kind:'personalAccessToken', value:'...'}, {kind:'realm', value:'pam'}]. The connection is tested before saving — if secrets are wrong, an error is returned. Set attemptSearchEngineCreation to false unless explicitly requested. The 'app' field is optional — pass {id:'...'} to link to an existing app, or omit it.",
"Create a new integration (connection to an external service). REQUIRED fields: name, url (http/https), kind, secrets, attemptSearchEngineCreation. The 'secrets' field is REQUIRED and must be a non-empty array — call integration_getKinds first to see which secret kinds each integration type needs. Example for Radarr: secrets=[{kind:'apiKey', value:'your-radarr-api-key'}]. Example for Proxmox: secrets=[{kind:'tokenId', value:'...'}, {kind:'personalAccessToken', value:'...'}, {kind:'realm', value:'pam'}]. The connection is tested before saving — if secrets are wrong, an error is returned. Set attemptSearchEngineCreation to false unless explicitly requested. The 'app' field is optional — pass {id:'...'} to link to an existing app, or omit it. Returns integration details and appId, which is null when no app is linked or created.",
},
})
.input(integrationCreateSchema)
@@ -99,6 +99,30 @@ describe("KubernetesClientRegistry", () => {
}
});
test("aborts a timed-out node metrics request", async () => {
vi.useFakeTimers();
try {
const client = createRegistry().getClient("home");
let observedSignal: AbortSignal | undefined;
vi.spyOn(client.metricsProbeApi, "listClusterCustomObject").mockImplementation(async (_request, options) => {
const middleware = (
options as { middleware?: { pre?: (request: unknown) => { toPromise: () => Promise<unknown> } }[] }
).middleware?.[0];
await middleware?.pre?.({ setSignal: (signal: AbortSignal) => (observedSignal = signal) }).toPromise();
return await new Promise<never>(() => undefined);
});
const resultPromise = client.getNodeMetricsAsync(50);
const rejection = expect(resultPromise).rejects.toThrow("Kubernetes context probe timed out");
await vi.advanceTimersByTimeAsync(50);
await rejection;
expect(observedSignal?.aborted).toBe(true);
} finally {
vi.useRealTimers();
}
});
test("rejects unknown context IDs", () => {
expect(() => createRegistry().getClient("missing")).toThrow(KubernetesContextNotFoundError);
});
@@ -1,6 +1,6 @@
import * as fs from "fs";
import type { RequestContext, ResponseContext } from "@kubernetes/client-node";
import { CoreV1Api, CustomObjectsApi, KubeConfig, Metrics, NetworkingV1Api, VersionApi } from "@kubernetes/client-node";
import type { NodeMetricsList, RequestContext, ResponseContext } from "@kubernetes/client-node";
import { CoreV1Api, CustomObjectsApi, KubeConfig, NetworkingV1Api, VersionApi } from "@kubernetes/client-node";
import { of } from "@kubernetes/client-node/dist/gen/rxjsStub.js";
import { env } from "../../env";
@@ -55,7 +55,6 @@ export class KubernetesClient {
public kubeConfig: KubeConfig;
public coreApi: CoreV1Api;
public networkingApi: NetworkingV1Api;
public metricsApi: Metrics;
public metricsProbeApi: CustomObjectsApi;
public versionApi: VersionApi;
@@ -63,11 +62,22 @@ export class KubernetesClient {
this.kubeConfig = kubeConfig;
this.coreApi = kubeConfig.makeApiClient(CoreV1Api);
this.networkingApi = kubeConfig.makeApiClient(NetworkingV1Api);
this.metricsApi = new Metrics(kubeConfig);
this.metricsProbeApi = kubeConfig.makeApiClient(CustomObjectsApi);
this.versionApi = kubeConfig.makeApiClient(VersionApi);
}
public async getNodeMetricsAsync(timeoutMs = kubernetesContextProbeTimeoutMs): Promise<NodeMetricsList> {
const result: unknown = await withKubernetesProbeTimeoutAsync(
async (signal) =>
await this.metricsProbeApi.listClusterCustomObject(
{ group: "metrics.k8s.io", version: "v1beta1", plural: "nodes" },
abortableKubernetesRequest(signal),
),
timeoutMs,
);
return result as NodeMetricsList;
}
public static getInstance(contextId: string): KubernetesClient {
return KubernetesClient.getRegistry().getClient(contextId);
}
@@ -125,14 +135,7 @@ export class KubernetesClientRegistry {
async (signal) => await client.versionApi.getCode(undefined, abortableKubernetesRequest(signal)),
timeoutMs,
),
withKubernetesProbeTimeoutAsync(
async (signal) =>
await client.metricsProbeApi.listClusterCustomObject(
{ group: "metrics.k8s.io", version: "v1beta1", plural: "nodes" },
abortableKubernetesRequest(signal),
),
timeoutMs,
),
client.getNodeMetricsAsync(timeoutMs),
]);
const status =
api.status === "rejected" ? "unavailable" : metrics.status === "rejected" ? "degraded" : "available";
@@ -16,14 +16,15 @@ export const clusterRouter = createTRPCRouter({
.concat(kubernetesMiddleware())
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesCluster> => {
const { coreApi, metricsApi, versionApi, kubeConfig } = getKubernetesClient(input.contextId);
const client = getKubernetesClient(input.contextId);
const { coreApi, versionApi, kubeConfig } = client;
try {
const [versionInfo, nodes, listPodForAllNamespaces, nodeMetricsClient] = await Promise.all([
versionApi.getCode(),
coreApi.listNode(),
coreApi.listPodForAllNamespaces(),
metricsApi.getNodeMetrics().catch(() => null),
client.getNodeMetricsAsync().catch(() => null),
]);
let totalCPUCapacity = 0;
@@ -5,6 +5,13 @@ import { KubernetesClient } from "../kubernetes-client";
export const contextsRouter = createTRPCRouter({
getContexts: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description:
"List configured Kubernetes contexts with availability, metrics status, and default-context metadata. Requires admin permission.",
},
})
.concat(kubernetesMiddleware())
.query(async () => await KubernetesClient.getContextsAsync()),
});
@@ -10,6 +10,13 @@ import { getKubernetesClient, kubernetesContextInput } from "../kubernetes-conte
export const ingressesRouter = createTRPCRouter({
getIngresses: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description:
"List Kubernetes ingress inventory for a context. Get the required contextId from kubernetes_contexts_getContexts. Requires admin permission.",
},
})
.concat(kubernetesMiddleware())
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesIngress[]> => {
@@ -15,12 +15,13 @@ export const nodesRouter = createTRPCRouter({
.concat(kubernetesMiddleware())
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesNode[]> => {
const { coreApi, metricsApi } = getKubernetesClient(input.contextId);
const client = getKubernetesClient(input.contextId);
const { coreApi } = client;
try {
const [nodes, nodeMetricsClient] = await Promise.all([
coreApi.listNode(),
metricsApi.getNodeMetrics().catch(() => null),
client.getNodeMetricsAsync().catch(() => null),
]);
const cpuResourceParser = new CpuResourceParser();
const memoryResourceParser = new MemoryResourceParser();
@@ -14,6 +14,13 @@ const logger = createLogger({ module: "podsRouter" });
export const podsRouter = createTRPCRouter({
getPods: permissionRequiredProcedure
.requiresPermission("admin")
.meta({
mcp: {
enabled: true,
description:
"List Kubernetes pod inventory and inferred workload types for a context. Get the required contextId from kubernetes_contexts_getContexts. Requires admin permission.",
},
})
.concat(kubernetesMiddleware())
.input(kubernetesContextInput)
.query(async ({ input }): Promise<KubernetesPod[]> => {
@@ -184,6 +184,20 @@ describe("All procedures should only be accessible for users with admin permissi
});
describe("Docker action targeting", () => {
test.each(["startAll", "stopAll", "restartAll", "removeAll"] as const)(
"%s requires a bounded non-empty target list",
async (procedure) => {
const caller = createAdminCaller();
await expect(caller[procedure]({ targets: [] })).rejects.toThrow();
await expect(
caller[procedure]({
targets: Array.from({ length: 101 }, (_, index) => ({ endpointId: "endpoint", id: String(index) })),
}),
).rejects.toThrow();
},
);
test("enforces endpoint capabilities before running a lifecycle action", async () => {
hasDockerEndpointCapabilityMock.mockReturnValueOnce(false);
+3 -3
View File
@@ -89,7 +89,7 @@ const parseTransport = (value: unknown, index: number): DockerEndpointTransport
};
const parseCapabilities = (value: unknown, index: number): DockerEndpointCapability[] => {
if (value === undefined) return allCapabilities;
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`);
}
@@ -136,7 +136,7 @@ export const createLegacySocketDescriptor = (path: string): DockerEndpointDescri
name: path,
kind: path.toLowerCase().includes("podman") ? "podman" : "docker",
transport: { type: "socket", path },
capabilities: allCapabilities,
capabilities: [...allCapabilities],
scope: "admin",
source: "legacy",
});
@@ -146,7 +146,7 @@ export const createLegacyTcpDescriptor = (host: string, port: number): DockerEnd
name: `${host}:${port}`,
kind: "docker",
transport: { type: "tcp", host, port, allowInsecure: true },
capabilities: allCapabilities,
capabilities: [...allCapabilities],
scope: "admin",
source: "legacy",
});
+2 -2
View File
@@ -1,7 +1,7 @@
import type Docker from "dockerode";
import type { DockerEndpointCapability } from "./endpoint-descriptor";
export type { DockerInstance } from "./singleton";
export type { DockerEndpointInitializationFailure, DockerInstance } from "./singleton";
export { DockerSingleton } from "./singleton";
export * from "./endpoint-descriptor";
export type { ContainerInfo, Container, Port } from "dockerode";
@@ -19,7 +19,7 @@ export interface DockerContainerTarget {
export interface DockerEndpointStatus {
id: string;
name: string;
status: "available" | "unavailable";
status: "available" | "degraded" | "unavailable";
kind?: "docker" | "podman";
transport?: "socket" | "tcp" | "tls";
capabilities?: DockerEndpointCapability[];
+45 -5
View File
@@ -1,6 +1,9 @@
import { readFileSync } from "node:fs";
import Docker from "dockerode";
import { createLogger } from "@homarr/core/infrastructure/logs";
import { ErrorWithMetadata } from "@homarr/core/infrastructure/logs/error";
import { env } from "./env";
import type { DockerEndpointCapability, DockerEndpointDescriptor } from "./endpoint-descriptor";
import {
@@ -18,11 +21,40 @@ export interface DockerInstance {
instance: Docker;
}
export interface DockerEndpointInitializationFailure {
descriptor: DockerEndpointDescriptor;
host: string;
}
const logger = createLogger({ module: "dockerSingleton" });
export class DockerSingleton {
private static instances: DockerInstance[] | null = null;
private static initializationFailures: DockerEndpointInitializationFailure[] = [];
private createInstanceSafely(descriptor: DockerEndpointDescriptor): DockerInstance[] {
try {
return [createInstance(descriptor)];
} catch (error) {
const host = getDockerEndpointHost(descriptor);
DockerSingleton.initializationFailures.push({ descriptor, host });
logger.warn(
new ErrorWithMetadata(
"Failed to initialize Docker endpoint",
{ endpointId: descriptor.id, host },
{ cause: error },
),
);
return [];
}
}
private createInstances() {
if (env.DOCKER_ENDPOINTS) return parseDockerEndpointDescriptors(env.DOCKER_ENDPOINTS).map(createInstance);
if (env.DOCKER_ENDPOINTS) {
return parseDockerEndpointDescriptors(env.DOCKER_ENDPOINTS).flatMap((descriptor) =>
this.createInstanceSafely(descriptor),
);
}
const socketPaths = env.DOCKER_SOCKET_PATHS;
const hostVariable = env.DOCKER_HOSTNAMES;
@@ -30,7 +62,9 @@ export class DockerSingleton {
// Socket instances from DOCKER_SOCKET_PATHS
const socketInstances: DockerInstance[] = socketPaths
? socketPaths.split(",").map((socketPath) => createInstance(createLegacySocketDescriptor(socketPath)))
? socketPaths
.split(",")
.flatMap((socketPath) => this.createInstanceSafely(createLegacySocketDescriptor(socketPath)))
: [];
// TCP instances from existing DOCKER_HOSTNAMES/DOCKER_PORTS
@@ -43,9 +77,9 @@ export class DockerSingleton {
throw new Error("The number of hosts and ports must match");
}
tcpInstances = hostnames.map((host, i) =>
tcpInstances = hostnames.flatMap((host, i) =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
createInstance(createLegacyTcpDescriptor(host, parseInt(ports[i]!, 10))),
this.createInstanceSafely(createLegacyTcpDescriptor(host, parseInt(ports[i]!, 10))),
);
}
@@ -59,7 +93,7 @@ export class DockerSingleton {
name: "Local Docker",
source: "default" as const,
};
return [{ ...createInstance(descriptor), host: "socket", instance: new Docker() }];
return [createInstance(descriptor)];
}
return instances;
@@ -78,9 +112,15 @@ export class DockerSingleton {
return this.instances;
}
this.initializationFailures = [];
this.instances = new DockerSingleton().createInstances();
return this.instances;
}
public static getInitializationFailures(): DockerEndpointInitializationFailure[] {
this.getInstances();
return [...this.initializationFailures];
}
}
const createInstance = (descriptor: DockerEndpointDescriptor): DockerInstance => ({
@@ -57,4 +57,15 @@ describe("parseDockerEndpointDescriptors", () => {
),
).toThrow("must include inventory");
});
test("returns independent default capability arrays", () => {
const [first, second] = parseDockerEndpointDescriptors(
JSON.stringify([
{ id: "first", name: "First", transport: { type: "socket", path: "/first.sock" } },
{ id: "second", name: "Second", transport: { type: "socket", path: "/second.sock" } },
]),
);
expect(first?.capabilities).not.toBe(second?.capabilities);
});
});
+19 -1
View File
@@ -40,8 +40,10 @@ describe("DockerSingleton", () => {
const instances = DockerSingleton.getInstances();
expect(instances).toHaveLength(1);
expect(instances[0]?.host).toBe("socket");
expect(instances[0]?.host).toBe("/var/run/docker.sock");
expect(instances[0]).toMatchObject({ endpointId: "socket:default", endpointName: "Local Docker" });
const options = (instances[0]?.instance as unknown as { opts: { socketPath: string } } | undefined)?.opts;
expect(options?.socketPath).toBe("/var/run/docker.sock");
});
test("should return TCP instances only when DOCKER_HOSTNAMES and DOCKER_PORTS set", () => {
@@ -131,4 +133,20 @@ describe("DockerSingleton", () => {
expect(DockerSingleton.hasCapability("readonly-podman", "logs")).toBe(true);
expect(DockerSingleton.hasCapability("readonly-podman", "remove")).toBe(false);
});
test("isolates an unreadable TLS endpoint from healthy endpoints", () => {
mockEnv.DOCKER_ENDPOINTS = JSON.stringify([
{ id: "local", name: "Local", transport: { type: "socket", path: "/var/run/docker.sock" } },
{
id: "broken-tls",
name: "Broken TLS",
transport: { type: "tls", host: "broken.example", port: 2376, caPath: "/missing/docker-ca.pem" },
},
]);
expect(DockerSingleton.getInstances().map(({ endpointId }) => endpointId)).toEqual(["local"]);
expect(DockerSingleton.getInitializationFailures()).toEqual([
expect.objectContaining({ descriptor: expect.objectContaining({ id: "broken-tls" }) }),
]);
});
});
@@ -68,4 +68,41 @@ describe("ConfirmModal", () => {
expect(confirmButton.disabled).toBe(false);
expect(closeModal).not.toHaveBeenCalled();
});
test("waits for a rejecting confirmation button callback", async () => {
const closeModal = vi.fn();
const onConfirm = vi.fn();
let rejectClick!: (error: Error) => void;
const onClick = vi.fn(
() =>
new Promise<void>((_resolve, reject) => {
rejectClick = reject;
}),
);
await act(async () =>
root.render(
<MantineProvider>
<ConfirmModalComponent
actions={{ closeModal }}
innerProps={{ children: "Remove containers?", confirmProps: { onClick }, onConfirm }}
/>
</MantineProvider>,
),
);
const confirmButton = host.querySelectorAll("button").item(1);
await act(async () => confirmButton.click());
expect(confirmButton.disabled).toBe(true);
expect(onConfirm).not.toHaveBeenCalled();
await act(async () => {
rejectClick(new Error("Callback failed"));
await Promise.resolve();
});
expect(confirmButton.disabled).toBe(false);
expect(onConfirm).not.toHaveBeenCalled();
expect(closeModal).not.toHaveBeenCalled();
});
});
+1 -1
View File
@@ -61,7 +61,7 @@ export const ConfirmModal = createModal<Omit<ConfirmModalProps, "title">>(({ act
setLoading(true);
try {
if (typeof confirmProps?.onClick === "function") {
confirmProps.onClick(event);
await confirmProps.onClick(event);
}
if (typeof onConfirm === "function") {
+65 -33
View File
@@ -41,7 +41,7 @@ const withDockerTimeoutAsync = async <T>(
}
};
const isDemoMode = ["1", "yes", "t", "true"].includes((process.env.DEMO_MODE ?? "").toLowerCase());
const isDemoMode = () => ["1", "yes", "t", "true"].includes((process.env.DEMO_MODE ?? "").toLowerCase());
const port = (privatePort: number, publicPort: number, type: string): Port => ({
IP: "0.0.0.0",
@@ -197,7 +197,7 @@ const mockContainers: {
export const dockerContainersRequestHandler = createWidgetRequestHandler({
async requestAsync() {
if (isDemoMode) {
if (isDemoMode()) {
return {
containers: mockContainers.map((container) => ({
...container,
@@ -228,7 +228,10 @@ const extractImage = (container: ContainerInfo) => extractContainerImageName(con
export const hasDockerEndpointCapability = (
endpointId: string,
capability: "inventory" | "logs" | "lifecycle" | "remove",
) => DockerSingleton.hasCapability(endpointId, capability);
) =>
isDemoMode()
? endpointId === "demo" && capability === "inventory"
: DockerSingleton.hasCapability(endpointId, capability);
export const findDockerContainerAsync = async (
{ endpointId, id }: DockerContainerTarget,
@@ -302,6 +305,7 @@ export const streamContainerLogsAsync = async (
export async function getContainersWithStatsAsync(timeoutMs = dockerWidgetEndpointTimeoutMs) {
const dockerInstances = DockerSingleton.getInstances();
const initializationFailures = DockerSingleton.getInitializationFailures();
const results = await Promise.allSettled(
dockerInstances.map(async ({ instance, host, endpointId, endpointName }) => {
const instanceContainers = await withDockerTimeoutAsync(
@@ -315,20 +319,32 @@ export async function getContainersWithStatsAsync(timeoutMs = dockerWidgetEndpoi
}),
);
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 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" as const) : ("unavailable" as const),
kind: dockerInstance.descriptor.kind,
transport: dockerInstance.descriptor.transport.type,
capabilities: dockerInstance.descriptor.capabilities,
source: dockerInstance.descriptor.source,
scope: dockerInstance.descriptor.scope,
} satisfies DockerEndpointStatus;
}),
...initializationFailures.map(({ descriptor }) => ({
id: descriptor.id,
name: descriptor.name,
status: "unavailable" as const,
kind: descriptor.kind,
transport: descriptor.transport.type,
capabilities: descriptor.capabilities,
source: descriptor.source,
scope: descriptor.scope,
})),
] satisfies DockerEndpointStatus[];
const containers = results.flatMap((result, index) => {
if (result.status === "fulfilled") return result.value;
@@ -354,24 +370,35 @@ export async function getContainersWithStatsAsync(timeoutMs = dockerWidgetEndpoi
})
: [];
const degradedEndpointIds = new Set<string>();
const containerStatsPromises = containers.map(async (container) => {
const instance = DockerSingleton.findInstance(container.endpointId)?.instance;
if (!instance) return null;
const stats = await withDockerTimeoutAsync(
async (signal) => {
const options = { stream: false as const, "one-shot": true, abortSignal: signal };
return await instance.getContainer(container.Id).stats(options);
},
`Timed out reading Docker container stats for ${container.Id}`,
timeoutMs,
).catch(
() =>
({
cpu_stats: { online_cpus: 0, cpu_usage: { total_usage: 0 }, system_cpu_usage: 0 },
memory_stats: { usage: 0 },
}) as ContainerStats,
);
let stats: ContainerStats;
try {
stats = await withDockerTimeoutAsync(
async (signal) => {
const options = { stream: false as const, "one-shot": true, abortSignal: signal };
return await instance.getContainer(container.Id).stats(options);
},
`Timed out reading Docker container stats for ${container.Id}`,
timeoutMs,
);
} catch (error) {
degradedEndpointIds.add(container.endpointId);
logger.warn(
new ErrorWithMetadata(
"Failed to read Docker container stats",
{ endpointId: container.endpointId, containerId: container.Id, host: container.instance },
{ cause: error },
),
);
stats = {
cpu_stats: { online_cpus: 0, cpu_usage: { total_usage: 0 }, system_cpu_usage: 0 },
memory_stats: { usage: 0 },
} as ContainerStats;
}
const cpuUsage = calculateCpuUsage(stats);
const memoryUsage = calculateMemoryUsage(stats);
@@ -392,9 +419,14 @@ export async function getContainersWithStatsAsync(timeoutMs = dockerWidgetEndpoi
};
});
const resolvedContainers = (await Promise.all(containerStatsPromises)).filter((container) => container !== null);
return {
containers: (await Promise.all(containerStatsPromises)).filter((container) => container !== null),
endpoints,
containers: resolvedContainers,
endpoints: endpoints.map((endpoint) =>
endpoint.status === "available" && degradedEndpointIds.has(endpoint.id)
? { ...endpoint, status: "degraded" as const }
: endpoint,
),
};
}
@@ -4,7 +4,12 @@ import { describe, expect, test, vi } from "vitest";
import { createDb } from "@homarr/db/test";
import { DockerSingleton } from "@homarr/docker";
import { calculateCpuUsage, calculateMemoryUsage, getContainersWithStatsAsync } from "../docker";
import {
calculateCpuUsage,
calculateMemoryUsage,
getContainersWithStatsAsync,
hasDockerEndpointCapability,
} from "../docker";
vi.mock("@homarr/db", async (importActual) => {
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
@@ -144,7 +149,7 @@ describe("getContainersWithStatsAsync", () => {
}
});
test("returns a container with zeroed stats when its stats request times out", async () => {
test("marks an endpoint degraded and returns zeroed stats when its stats request times out", async () => {
vi.useFakeTimers();
try {
const dockerInstance = createDockerInstance("healthy", async () => [
@@ -173,11 +178,50 @@ describe("getContainersWithStatsAsync", () => {
expect(observedSignal?.aborted).toBe(true);
expect(result.containers).toEqual([expect.objectContaining({ id: "container-1", cpuUsage: 0, memoryUsage: 0 })]);
expect(result.endpoints).toEqual([expect.objectContaining({ id: "healthy", status: "degraded" })]);
} finally {
vi.useRealTimers();
vi.restoreAllMocks();
}
});
test("includes endpoints that failed during TLS initialization", async () => {
vi.spyOn(DockerSingleton, "getInstances").mockReturnValue([]);
vi.spyOn(DockerSingleton, "getInitializationFailures").mockReturnValue([
{
host: "broken.example:2376",
descriptor: {
id: "broken-tls",
name: "Broken TLS",
kind: "docker",
transport: { type: "tls", host: "broken.example", port: 2376, caPath: "/missing/ca.pem" },
capabilities: ["inventory"],
scope: "admin",
source: "environment",
},
},
]);
const result = await getContainersWithStatsAsync(50);
expect(result.endpoints).toEqual([
expect.objectContaining({ id: "broken-tls", status: "unavailable", transport: "tls" }),
]);
vi.restoreAllMocks();
});
});
test("demo capabilities match the advertised inventory-only endpoint", () => {
const previousDemoMode = process.env.DEMO_MODE;
process.env.DEMO_MODE = "true";
try {
expect(hasDockerEndpointCapability("demo", "inventory")).toBe(true);
expect(hasDockerEndpointCapability("demo", "logs")).toBe(false);
expect(hasDockerEndpointCapability("other", "inventory")).toBe(false);
} finally {
if (previousDemoMode === undefined) delete process.env.DEMO_MODE;
else process.env.DEMO_MODE = previousDemoMode;
}
});
const createDockerInstance = (endpointId: string, listContainers: () => Promise<unknown[]>) => ({
+93 -6
View File
@@ -1,4 +1,73 @@
{
"featureWorkbench": {
"page": {
"title": "Native feature state workbench",
"description": "A development-only fixture surface for reviewing shared catalog and integration response states without live services."
},
"catalog": {
"title": "Catalog item states",
"description": "Compare the shared selection surface with stable service and interaction fixtures.",
"serviceState": "Service state",
"interactionState": "Interaction state",
"loading": "Loading",
"loadingAriaLabel": "Loading catalog item",
"semanticOutput": "Semantic output",
"instructions": "Tab to the item to inspect its visible focus ring. Select it with Enter or Space.",
"interaction": {
"default": "Default",
"selected": "Selected",
"loading": "Loading",
"disabled": "Disabled"
},
"state": {
"ready": {
"label": "Ready service",
"status": "Ready",
"description": "Configured and available to three widgets."
},
"needsSetup": {
"label": "Service needing setup",
"status": "Needs setup",
"description": "Credentials or a service URL are still required."
},
"noConnection": {
"label": "Standalone feature",
"status": "No connection required",
"description": "This feature works without a configured integration."
},
"error": {
"label": "Unreachable service",
"status": "Connection failed",
"description": "The saved connection could not be reached."
}
}
},
"response": {
"title": "Integration response contract",
"description": "Inspect waiting, accepted, and rejected response fixtures using the same parser contract as generated integrations.",
"fixtureLabel": "Response fixture",
"checking": "Checking response",
"contractPassed": "Fixture contract passed",
"contractFailed": "Fixture contract failed",
"state": {
"loading": {
"label": "Loading",
"title": "Checking response",
"description": "The parser is waiting for the integration response."
},
"success": {
"label": "Success",
"title": "Response accepted",
"description": "The upstream payload matched the integration contract."
},
"failure": {
"label": "Failure",
"title": "Response rejected",
"description": "The upstream payload failed schema validation and stays isolated from the widget."
}
}
}
},
"init": {
"studio": {
"navigationLabel": "Onboarding sections",
@@ -241,6 +310,7 @@
},
"universalCreate": {
"title": "Create",
"analyticsError": "Usage metrics could not be recorded. Your action was not affected.",
"trigger": {
"label": "Create something",
"description": "Add content, connect a service, or create a board from one place."
@@ -2703,7 +2773,8 @@
"notification": {
"success": {
"title": "Widget added",
"message": "{name} was added to this board."
"message": "{name} was added to this board.",
"relocatedMessage": "{name} was added to {destination} because the selected destination was unavailable."
},
"error": {
"title": "Unable to add item",
@@ -7051,7 +7122,9 @@
},
"url": {
"label": "Service address",
"manual": "Enter an address manually"
"inputLabel": "Service URL",
"manual": "Enter an address manually",
"invalid": "Enter a valid HTTP or HTTPS URL"
},
"reason": {
"publishedAddress": "Published address reported by Docker",
@@ -7083,12 +7156,21 @@
},
"action": {
"refresh": "Refresh",
"retry": "Try again",
"dismiss": "Dismiss",
"restoreDismissed": "Restore dismissed ({count})",
"setupIntegration": "Set up integration",
"createApp": "Create app",
"reviewIntegration": "Review integration",
"viewRepresentation": "View setup"
},
"loadError": {
"title": "Service setup could not be loaded",
"message": "Docker service information is unavailable. Try again without leaving this page."
},
"refreshError": {
"title": "Containers not refreshed",
"message": "Something went wrong while refreshing the containers"
}
},
"table": {
@@ -7187,8 +7269,8 @@
"label": "Remove",
"confirm": "Click again to remove permanently",
"confirmation": {
"title": "Remove {count} container(s)?",
"message": "This permanently removes {count} container(s): {names}"
"title": "{count, plural, one {Remove # container?} other {Remove # containers?}}",
"message": "{count, plural, one {This permanently removes # container: {names}} other {This permanently removes # containers: {names}}}"
},
"notification": {
"success": {
@@ -7204,7 +7286,7 @@
"result": {
"failure": {
"title": "Some container actions failed",
"message": "{failed} of {total} action(s) failed: {names}"
"message": "{total, plural, one {{failed} of # action failed: {names}} other {{failed} of # actions failed: {names}}}"
}
},
"refresh": {
@@ -7239,13 +7321,18 @@
},
"error": {
"internalServerError": "Failed to fetch Docker containers",
"endpointUnavailable": "{count} Docker endpoint(s) unavailable: {names}",
"endpointUnavailable": "{count, plural, one {# Docker endpoint unavailable: {names}} other {# Docker endpoints unavailable: {names}}}",
"noColumns": "Select at least one column in the widget settings"
}
},
"kubernetes": {
"context": {
"label": "Kubernetes context",
"loadError": {
"title": "Kubernetes contexts could not be loaded",
"message": "Context information is unavailable. Try again without leaving this page.",
"retry": "Try again"
},
"status": {
"available": "Available",
"degraded": "Metrics unavailable",
@@ -84,7 +84,7 @@ describe("CatalogItem", () => {
expect(getCatalogKeyboardDirection("Enter")).toBeNull();
});
it("offers arrow-key movement without replacing native Enter and Space activation", async () => {
it("moves focus only for navigation keys", async () => {
const onSelect = vi.fn();
const onMoveFocus = vi.fn();
await act(async () =>
@@ -102,6 +102,7 @@ describe("CatalogItem", () => {
expect(onMoveFocus).toHaveBeenCalledWith("next");
await act(async () => button?.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true })));
await act(async () => button?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", bubbles: true })));
expect(onMoveFocus).toHaveBeenCalledOnce();
});
@@ -259,6 +259,12 @@ export default function DockerWidget({
utils.docker.getServiceHealth.invalidate(),
]);
},
onError() {
showErrorNotification({
title: t("action.refresh.notification.error.title"),
message: t("action.refresh.notification.error.message"),
});
},
});
const containers = useMemo(() => data?.containers ?? [], [data?.containers]);
const timestamp = useMemo(() => data?.timestamp ?? new Date(), [data?.timestamp]);
@@ -1,6 +1,6 @@
"use client";
import { useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import type { FormEvent } from "react";
import { Button, Group, Stack, Tabs, Text } from "@mantine/core";
import { schemaResolver } from "@mantine/form";
@@ -70,7 +70,7 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
const integrationsRequired =
innerProps.integrationSupport &&
(!("integrationsRequired" in definition) || definition.integrationsRequired !== false);
const maxIntegrations = (definition as { maxIntegrations?: number }).maxIntegrations ?? Infinity;
const maxIntegrations = "maxIntegrations" in definition ? (definition.maxIntegrations ?? Infinity) : Infinity;
const options = definition.createOptions(innerProps.settings) as Record<string, OptionsBuilderResult[string]>;
const optionsSuperRefine = (options as Record<symbol, unknown>)[OPTIONS_SUPER_REFINE] as
| ((data: Record<string, unknown>, ctx: z.RefinementCtx) => void)
@@ -120,6 +120,12 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
const selectedIntegrations = getSelectedWidgetIntegrations(innerProps.integrationData, form.values.integrationIds);
const showIntegrationTab = Boolean(innerProps.onEditIntegration) && selectedIntegrations.length > 0;
const showResourceTabs = showAppTab || showIntegrationTab;
const [activeTab, setActiveTab] = useState<string | null>("widget");
useEffect(() => {
if (activeTab === "integration" && !showIntegrationTab) setActiveTab("widget");
if (activeTab === "app" && !showAppTab) setActiveTab("widget");
}, [activeTab, showAppTab, showIntegrationTab]);
const handleSubmit = form.onSubmit(async (values) => {
setIsSubmitting(true);
@@ -223,7 +229,7 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
<FormProvider form={form}>
{showResourceTabs ? (
<Stack>
<Tabs defaultValue="widget">
<Tabs value={activeTab} onChange={setActiveTab}>
<Tabs.List grow>
<Tabs.Tab value="widget">{t("item.edit.tab.widget")}</Tabs.Tab>
{showAppTab && <Tabs.Tab value="app">{t("item.edit.tab.app")}</Tabs.Tab>}
@@ -141,7 +141,7 @@ export const WidgetIntegrationSelect = ({
combobox.closeDropdown();
return;
}
if (event.key === "Backspace" && multiSelectValues.length > 0) {
if (event.key === "Backspace" && canSelectMultiple && multiSelectValues.length > 0) {
event.preventDefault();
const lastValue = multiSelectValues.at(-1);
if (lastValue) handleValueRemove(lastValue);