This commit is contained in:
1 parent
e3a713d2df
commit
e842177d9b
163 files changed
+7390
-1240
No files matched your search
@@ -0,0 +1,63 @@
|
||||
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",
|
||||
});
|
||||
});
|
||||
|
||||
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" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
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,
|
||||
properties: Record<string, unknown> | undefined,
|
||||
userId: string,
|
||||
) => {
|
||||
if (!feature.startsWith("setup:")) return { ...properties, userId };
|
||||
|
||||
return Object.fromEntries(
|
||||
Object.entries(properties ?? {}).filter(([key, value]) => isValidSetupProperty(key, value)),
|
||||
);
|
||||
};
|
||||
@@ -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 }) => {
|
||||
|
||||
@@ -562,13 +562,15 @@ 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)
|
||||
.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")
|
||||
@@ -747,19 +749,17 @@ export const boardRouter = createTRPCRouter({
|
||||
|
||||
const sectionLayoutsToInsert: InferInsertModel<typeof sectionLayouts>[] = boardSections
|
||||
.flatMap((section) =>
|
||||
section.layouts.map(
|
||||
(layoutSection): InferInsertModel<typeof sectionLayouts> => ({
|
||||
...layoutSection,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
layoutId: layoutsMap.get(layoutSection.layoutId)!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionId: sectionMap.get(layoutSection.sectionId)!,
|
||||
parentSectionId: layoutSection.parentSectionId
|
||||
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionMap.get(layoutSection.parentSectionId)!
|
||||
: layoutSection.parentSectionId,
|
||||
}),
|
||||
),
|
||||
section.layouts.map((layoutSection): InferInsertModel<typeof sectionLayouts> => ({
|
||||
...layoutSection,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
layoutId: layoutsMap.get(layoutSection.layoutId)!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionId: sectionMap.get(layoutSection.sectionId)!,
|
||||
parentSectionId: layoutSection.parentSectionId
|
||||
? // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionMap.get(layoutSection.parentSectionId)!
|
||||
: layoutSection.parentSectionId,
|
||||
})),
|
||||
)
|
||||
.concat(
|
||||
(generatedMobilePositions?.sectionLayouts ?? []).map((layoutSection) => ({
|
||||
@@ -776,13 +776,11 @@ export const boardRouter = createTRPCRouter({
|
||||
);
|
||||
const sectionCollapseStatesToInsert: InferInsertModel<typeof sectionCollapseStates>[] = boardSections.flatMap(
|
||||
(section) =>
|
||||
section.collapseStates.map(
|
||||
(collapseState): InferInsertModel<typeof sectionCollapseStates> => ({
|
||||
...collapseState,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionId: sectionMap.get(collapseState.sectionId)!,
|
||||
}),
|
||||
),
|
||||
section.collapseStates.map((collapseState): InferInsertModel<typeof sectionCollapseStates> => ({
|
||||
...collapseState,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionId: sectionMap.get(collapseState.sectionId)!,
|
||||
})),
|
||||
);
|
||||
|
||||
const itemMap = new Map<string, string>(boardItems.map((item) => [item.id, createId()]));
|
||||
@@ -797,17 +795,15 @@ export const boardRouter = createTRPCRouter({
|
||||
|
||||
const itemLayoutsToInsert: InferInsertModel<typeof itemLayouts>[] = boardItems
|
||||
.flatMap((item) =>
|
||||
item.layouts.map(
|
||||
(layoutSection): InferInsertModel<typeof itemLayouts> => ({
|
||||
...layoutSection,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionId: sectionMap.get(layoutSection.sectionId)!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
itemId: itemMap.get(layoutSection.itemId)!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
layoutId: layoutsMap.get(layoutSection.layoutId)!,
|
||||
}),
|
||||
),
|
||||
item.layouts.map((layoutSection): InferInsertModel<typeof itemLayouts> => ({
|
||||
...layoutSection,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
sectionId: sectionMap.get(layoutSection.sectionId)!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
itemId: itemMap.get(layoutSection.itemId)!,
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
layoutId: layoutsMap.get(layoutSection.layoutId)!,
|
||||
})),
|
||||
)
|
||||
.concat(
|
||||
(generatedMobilePositions?.itemSectionLayouts ?? []).map((layoutSection) => ({
|
||||
@@ -1527,17 +1523,15 @@ export const boardRouter = createTRPCRouter({
|
||||
const sectionLayoutsToInsert = addedSections
|
||||
.filter((section) => section.kind === "container")
|
||||
.flatMap((section) =>
|
||||
section.layouts.map(
|
||||
(sectionLayout): InferInsertModel<typeof schema.sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
}),
|
||||
),
|
||||
section.layouts.map((sectionLayout): InferInsertModel<typeof schema.sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
})),
|
||||
);
|
||||
|
||||
if (sectionLayoutsToInsert.length > 0) {
|
||||
@@ -1559,17 +1553,15 @@ export const boardRouter = createTRPCRouter({
|
||||
);
|
||||
await transaction.insert(schema.itemLayouts).values(
|
||||
addedItems.flatMap((item) =>
|
||||
item.layouts.map(
|
||||
(layoutSection): InferInsertModel<typeof schema.itemLayouts> => ({
|
||||
layoutId: layoutSection.layoutId,
|
||||
sectionId: layoutSection.sectionId,
|
||||
itemId: item.id,
|
||||
height: layoutSection.height,
|
||||
width: layoutSection.width,
|
||||
xOffset: layoutSection.xOffset,
|
||||
yOffset: layoutSection.yOffset,
|
||||
}),
|
||||
),
|
||||
item.layouts.map((layoutSection): InferInsertModel<typeof schema.itemLayouts> => ({
|
||||
layoutId: layoutSection.layoutId,
|
||||
sectionId: layoutSection.sectionId,
|
||||
itemId: item.id,
|
||||
height: layoutSection.height,
|
||||
width: layoutSection.width,
|
||||
xOffset: layoutSection.xOffset,
|
||||
yOffset: layoutSection.yOffset,
|
||||
})),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1727,17 +1719,15 @@ export const boardRouter = createTRPCRouter({
|
||||
const sectionLayoutsToInsert = addedSections
|
||||
.filter((section) => section.kind === "container")
|
||||
.flatMap((section) =>
|
||||
section.layouts.map(
|
||||
(sectionLayout): InferInsertModel<typeof sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
}),
|
||||
),
|
||||
section.layouts.map((sectionLayout): InferInsertModel<typeof sectionLayouts> => ({
|
||||
layoutId: sectionLayout.layoutId,
|
||||
sectionId: section.id,
|
||||
parentSectionId: sectionLayout.parentSectionId,
|
||||
height: sectionLayout.height,
|
||||
width: sectionLayout.width,
|
||||
xOffset: sectionLayout.xOffset,
|
||||
yOffset: sectionLayout.yOffset,
|
||||
})),
|
||||
);
|
||||
|
||||
if (sectionLayoutsToInsert.length > 0) {
|
||||
@@ -1764,17 +1754,15 @@ export const boardRouter = createTRPCRouter({
|
||||
.insert(itemLayouts)
|
||||
.values(
|
||||
addedItems.flatMap((item) =>
|
||||
item.layouts.map(
|
||||
(layoutSection): InferInsertModel<typeof itemLayouts> => ({
|
||||
layoutId: layoutSection.layoutId,
|
||||
sectionId: layoutSection.sectionId,
|
||||
itemId: item.id,
|
||||
height: layoutSection.height,
|
||||
width: layoutSection.width,
|
||||
xOffset: layoutSection.xOffset,
|
||||
yOffset: layoutSection.yOffset,
|
||||
}),
|
||||
),
|
||||
item.layouts.map((layoutSection): InferInsertModel<typeof itemLayouts> => ({
|
||||
layoutId: layoutSection.layoutId,
|
||||
sectionId: layoutSection.sectionId,
|
||||
itemId: item.id,
|
||||
height: layoutSection.height,
|
||||
width: layoutSection.width,
|
||||
xOffset: layoutSection.xOffset,
|
||||
yOffset: layoutSection.yOffset,
|
||||
})),
|
||||
),
|
||||
)
|
||||
.run();
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
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 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);
|
||||
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
|
||||
? 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(({ integration }) => normalizeName(integration.name) === normalizeName(container.name))
|
||||
.map(({ integration }) => integration)
|
||||
: [];
|
||||
const exactIntegration = exactIntegrationMatches.length === 1 ? exactIntegrationMatches[0] : undefined;
|
||||
const nameIntegration =
|
||||
exactIntegrationMatches.length === 0 && nameIntegrationMatches.length === 1
|
||||
? nameIntegrationMatches[0]
|
||||
: undefined;
|
||||
const integration = exactIntegration ?? nameIntegration;
|
||||
const exactAppMatches = normalizedApps
|
||||
.filter(({ normalizedUrl }) => normalizedUrl !== null && candidateUrls.has(normalizedUrl))
|
||||
.map(({ app }) => app);
|
||||
const nameAppMatches = uniqueName
|
||||
? apps.filter(({ name }) => normalizeName(name) === normalizeName(container.name))
|
||||
: [];
|
||||
const exactApp = exactAppMatches.length === 1 ? exactAppMatches[0] : undefined;
|
||||
const nameApp = exactAppMatches.length === 0 && 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 integrationMoved = Boolean(integration && !exactIntegration);
|
||||
const integrationAmbiguous =
|
||||
exactIntegrationMatches.length > 1 || (exactIntegrationMatches.length === 0 && nameIntegrationMatches.length > 1);
|
||||
const appAmbiguous =
|
||||
!linkedApp && (exactAppMatches.length > 1 || (exactAppMatches.length === 0 && nameAppMatches.length > 1));
|
||||
const ambiguous = integrationAmbiguous || appAmbiguous;
|
||||
const state: DockerReconciliationState = integrationMoved
|
||||
? "moved"
|
||||
: linked
|
||||
? "linked"
|
||||
: integration || app
|
||||
? "represented"
|
||||
: match
|
||||
? "newRecognized"
|
||||
: "newApp";
|
||||
|
||||
return {
|
||||
candidateKey: container.resourceId,
|
||||
endpointId: container.endpointId,
|
||||
endpointName: container.endpointName,
|
||||
nativeId: container.id,
|
||||
container,
|
||||
match,
|
||||
urlCandidates,
|
||||
state,
|
||||
nextAction: integrationAmbiguous
|
||||
? ("reviewIntegration" as const)
|
||||
: appAmbiguous
|
||||
? ("viewRepresentation" as const)
|
||||
: 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,
|
||||
exactIntegrationUrl: Boolean(exactIntegration),
|
||||
exactAppUrl: Boolean(exactApp),
|
||||
nameMatch: Boolean(nameIntegration || nameApp),
|
||||
linked,
|
||||
ambiguous,
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
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.nextAction === "reviewIntegration"
|
||||
? ("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.nextAction === "reviewIntegration"
|
||||
? ("reviewIntegration" 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)
|
||||
: candidate.representation.signals.ambiguous && candidate.nextAction === "viewRepresentation"
|
||||
? ("viewRepresentation" 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);
|
||||
};
|
||||
@@ -2,19 +2,64 @@ 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 type { ContainerState, DockerContainerTarget, Port } from "@homarr/docker";
|
||||
import { DockerSingleton } from "@homarr/docker";
|
||||
import {
|
||||
dockerContainersRequestHandler,
|
||||
findDockerContainerAsync,
|
||||
getContainerLogsAsync,
|
||||
getDockerEndpointsAsync,
|
||||
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),
|
||||
});
|
||||
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(() => {
|
||||
DockerSingleton.reset();
|
||||
dockerContainersRequestHandler.invalidateCache();
|
||||
}),
|
||||
getContainers: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
@@ -31,67 +76,59 @@ export const dockerRouter = createTRPCRouter({
|
||||
const { data, timestamp } = result;
|
||||
|
||||
return {
|
||||
containers: data satisfies DockerContainer[],
|
||||
containers: data.containers satisfies DockerContainer[],
|
||||
endpoints: data.endpoints,
|
||||
timestamp,
|
||||
};
|
||||
}),
|
||||
getEndpoints: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.meta({
|
||||
mcp: {
|
||||
enabled: true,
|
||||
description: "List configured Docker endpoints with their availability and capabilities",
|
||||
},
|
||||
})
|
||||
.concat(dockerMiddleware())
|
||||
.query(async () => getDockerEndpointsAsync()),
|
||||
startAll: permissionRequiredProcedure
|
||||
.requiresPermission("admin")
|
||||
.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: dockerContainerTargetsSchema }))
|
||||
.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: dockerContainerTargetsSchema }))
|
||||
.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: dockerContainerTargetsSchema }))
|
||||
.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 +136,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: dockerContainerTargetsSchema }))
|
||||
.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 +150,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 +180,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 +193,7 @@ export const dockerRouter = createTRPCRouter({
|
||||
const initializeStreamAsync = async () => {
|
||||
try {
|
||||
cleanupFn = await streamContainerLogsAsync(
|
||||
input.id,
|
||||
input,
|
||||
input.tail ?? 200,
|
||||
(data) => {
|
||||
if (isSubscribed) {
|
||||
@@ -200,36 +233,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;
|
||||
|
||||
@@ -90,21 +90,14 @@ export const integrationRouter = createTRPCRouter({
|
||||
});
|
||||
return integrations
|
||||
.map((integration) => {
|
||||
const permissions = integration.userPermissions
|
||||
.map(({ permission }) => permission)
|
||||
.concat(integration.groupPermissions.map(({ permission }) => permission));
|
||||
const permissions = constructIntegrationPermissions(integration, ctx.session);
|
||||
|
||||
return {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
kind: integration.kind,
|
||||
url: integration.url,
|
||||
permissions: {
|
||||
hasUseAccess:
|
||||
permissions.includes("use") || permissions.includes("interact") || permissions.includes("full"),
|
||||
hasInteractAccess: permissions.includes("interact") || permissions.includes("full"),
|
||||
hasFullAccess: permissions.includes("full"),
|
||||
},
|
||||
permissions,
|
||||
};
|
||||
})
|
||||
.toSorted(
|
||||
@@ -138,21 +131,14 @@ export const integrationRouter = createTRPCRouter({
|
||||
});
|
||||
return integrationsFromDb
|
||||
.map((integration) => {
|
||||
const permissions = integration.userPermissions
|
||||
.map(({ permission }) => permission)
|
||||
.concat(integration.groupPermissions.map(({ permission }) => permission));
|
||||
const permissions = constructIntegrationPermissions(integration, ctx.session);
|
||||
|
||||
return {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
kind: integration.kind,
|
||||
url: integration.url,
|
||||
permissions: {
|
||||
hasUseAccess:
|
||||
permissions.includes("use") || permissions.includes("interact") || permissions.includes("full"),
|
||||
hasInteractAccess: permissions.includes("interact") || permissions.includes("full"),
|
||||
hasFullAccess: permissions.includes("full"),
|
||||
},
|
||||
permissions,
|
||||
};
|
||||
})
|
||||
.toSorted(
|
||||
@@ -189,21 +175,14 @@ export const integrationRouter = createTRPCRouter({
|
||||
});
|
||||
return integrationsFromDb
|
||||
.map((integration) => {
|
||||
const permissions = integration.userPermissions
|
||||
.map(({ permission }) => permission)
|
||||
.concat(integration.groupPermissions.map(({ permission }) => permission));
|
||||
const permissions = constructIntegrationPermissions(integration, ctx.session);
|
||||
|
||||
return {
|
||||
id: integration.id,
|
||||
name: integration.name,
|
||||
kind: integration.kind,
|
||||
url: integration.url,
|
||||
permissions: {
|
||||
hasUseAccess:
|
||||
permissions.includes("use") || permissions.includes("interact") || permissions.includes("full"),
|
||||
hasInteractAccess: permissions.includes("interact") || permissions.includes("full"),
|
||||
hasFullAccess: permissions.includes("full"),
|
||||
},
|
||||
permissions,
|
||||
};
|
||||
})
|
||||
.toSorted(
|
||||
@@ -301,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)
|
||||
@@ -368,6 +347,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,148 @@
|
||||
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.metricsProbeApi, "listClusterCustomObject").mockResolvedValue({ items: [] } as never);
|
||||
}
|
||||
registry.getClient("remote").versionApi.getCode = vi.fn().mockRejectedValue(new Error("offline"));
|
||||
registry.getClient("metrics-degraded").metricsProbeApi.listClusterCustomObject = 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("times out an unresponsive context without delaying healthy contexts", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
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.metricsProbeApi, "listClusterCustomObject").mockResolvedValue({ items: [] } as never);
|
||||
}
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
vi.spyOn(registry.getClient("remote").versionApi, "getCode").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 = registry.getContextsAsync(50);
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(observedSignal?.aborted).toBe(true);
|
||||
expect(result.contexts).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ contextId: "home", status: "available" }),
|
||||
expect.objectContaining({ contextId: "remote", status: "unavailable" }),
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
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.metricsProbeApi, "listClusterCustomObject").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 }));
|
||||
});
|
||||
});
|
||||
@@ -1,71 +1,196 @@
|
||||
import * as fs from "fs";
|
||||
import { CoreV1Api, 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";
|
||||
|
||||
export interface KubernetesContextStatus {
|
||||
contextId: string;
|
||||
name: string;
|
||||
status: "available" | "degraded" | "unavailable";
|
||||
metricsStatus: "available" | "unavailable" | "unknown";
|
||||
isDefault: boolean;
|
||||
}
|
||||
|
||||
export const kubernetesContextProbeTimeoutMs = 5_000;
|
||||
|
||||
const withKubernetesProbeTimeoutAsync = async <T>(
|
||||
operation: (signal: AbortSignal) => Promise<T>,
|
||||
timeoutMs: number,
|
||||
) => {
|
||||
const controller = new AbortController();
|
||||
const timeoutError = new Error("Kubernetes context probe timed out");
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
operation(controller.signal),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
controller.abort(timeoutError);
|
||||
reject(timeoutError);
|
||||
}, timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
}
|
||||
};
|
||||
|
||||
const abortableKubernetesRequest = (signal: AbortSignal) => ({
|
||||
middleware: [
|
||||
{
|
||||
pre: (request: RequestContext) => {
|
||||
request.setSignal(signal);
|
||||
return of(request);
|
||||
},
|
||||
post: (response: ResponseContext) => of(response),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
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 metricsProbeApi: CustomObjectsApi;
|
||||
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.metricsProbeApi = kubeConfig.makeApiClient(CustomObjectsApi);
|
||||
this.versionApi = kubeConfig.makeApiClient(VersionApi);
|
||||
}
|
||||
|
||||
public static getInstance(): KubernetesClient {
|
||||
KubernetesClient.instance ??= new KubernetesClient();
|
||||
return KubernetesClient.instance;
|
||||
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);
|
||||
}
|
||||
|
||||
public static getDefaultInstance(): KubernetesClient {
|
||||
return KubernetesClient.getRegistry().getDefaultClient();
|
||||
}
|
||||
|
||||
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 getDefaultClient() {
|
||||
return this.getClient(this.defaultContextId);
|
||||
}
|
||||
|
||||
public async getContextsAsync(timeoutMs = kubernetesContextProbeTimeoutMs) {
|
||||
const contexts = await Promise.all(
|
||||
[...this.clients.entries()].map(async ([contextId, client]): Promise<KubernetesContextStatus> => {
|
||||
const [api, metrics] = await Promise.allSettled([
|
||||
withKubernetesProbeTimeoutAsync(
|
||||
async (signal) => await client.versionApi.getCode(undefined, abortableKubernetesRequest(signal)),
|
||||
timeoutMs,
|
||||
),
|
||||
client.getNodeMetricsAsync(timeoutMs),
|
||||
]);
|
||||
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,18 @@ 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 client = getKubernetesClient(input.contextId);
|
||||
const { coreApi, versionApi, kubeConfig } = client;
|
||||
|
||||
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(),
|
||||
client.getNodeMetricsAsync().catch(() => null),
|
||||
]);
|
||||
|
||||
let totalCPUCapacity = 0;
|
||||
let totalCPUAllocatable = 0;
|
||||
@@ -48,7 +53,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 +66,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 +78,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 +149,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,17 @@
|
||||
import { kubernetesMiddleware } from "../../../middlewares/kubernetes";
|
||||
import { createTRPCRouter, permissionRequiredProcedure } from "../../../trpc";
|
||||
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()),
|
||||
});
|
||||
@@ -5,14 +5,22 @@ 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")
|
||||
.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())
|
||||
.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,16 @@ 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 client = getKubernetesClient(input.contextId);
|
||||
const { coreApi } = client;
|
||||
|
||||
try {
|
||||
const nodes = await coreApi.listNode();
|
||||
const nodeMetricsClient = await metricsApi.getNodeMetrics();
|
||||
const [nodes, nodeMetricsClient] = await Promise.all([
|
||||
coreApi.listNode(),
|
||||
client.getNodeMetricsAsync().catch(() => null),
|
||||
]);
|
||||
const cpuResourceParser = new CpuResourceParser();
|
||||
const memoryResourceParser = new MemoryResourceParser();
|
||||
|
||||
@@ -34,20 +39,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,16 +7,24 @@ 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" });
|
||||
|
||||
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())
|
||||
.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();
|
||||
|
||||
@@ -41,7 +41,7 @@ export const probeRuntimeCapabilitiesAsync = async ({
|
||||
workshopApiUrl,
|
||||
fetchImpl = fetch,
|
||||
getKubernetesVersionAsync = async (signal) =>
|
||||
await KubernetesClient.getInstance().versionApi.getCode({
|
||||
await KubernetesClient.getDefaultInstance().versionApi.getCode({
|
||||
middleware: [
|
||||
{
|
||||
pre: async (request: RequestContext) => {
|
||||
|
||||
@@ -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,45 @@ 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 invalidateDockerCacheMock = vi.hoisted(() => vi.fn());
|
||||
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", () => ({
|
||||
@@ -27,9 +62,13 @@ vi.mock("@homarr/docker", () => ({
|
||||
},
|
||||
},
|
||||
],
|
||||
reset: () => undefined,
|
||||
},
|
||||
}));
|
||||
vi.mock("@homarr/request-handler/docker", () => ({
|
||||
findDockerContainerAsync: findDockerContainerAsyncMock,
|
||||
hasDockerEndpointCapability: hasDockerEndpointCapabilityMock,
|
||||
getDockerEndpointsAsync: () => [],
|
||||
getContainerLogsAsync: async () => {
|
||||
await Promise.resolve();
|
||||
return "logs";
|
||||
@@ -39,10 +78,9 @@ vi.mock("@homarr/request-handler/docker", () => ({
|
||||
return () => undefined;
|
||||
},
|
||||
dockerContainersRequestHandler: {
|
||||
invalidateCache: invalidateDockerCacheMock,
|
||||
handler: () => ({
|
||||
getDataAsync: async () => {
|
||||
return await Promise.resolve({ data: [], timestamp: new Date() });
|
||||
},
|
||||
getDataAsync: getDockerDataAsyncMock,
|
||||
}),
|
||||
},
|
||||
}));
|
||||
@@ -67,20 +105,45 @@ const procedureKeys = objectKeys(dockerRouter._def.procedures);
|
||||
const validInputs: {
|
||||
[key in (typeof procedureKeys)[number]]: RouterInputs["docker"][key];
|
||||
} = {
|
||||
reconcileServices: undefined,
|
||||
getServiceHealth: undefined,
|
||||
refreshInventory: undefined,
|
||||
getEndpoints: 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 +185,383 @@ 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.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);
|
||||
|
||||
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");
|
||||
expect(result.candidates[0]?.nextAction).toBe("reviewIntegration");
|
||||
});
|
||||
|
||||
test("prefers a unique exact integration match over duplicate name matches", 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: "exact",
|
||||
name: "Primary",
|
||||
kind: "sonarr",
|
||||
url: "http://home.example:8989",
|
||||
appId: null,
|
||||
items: [],
|
||||
secrets: [],
|
||||
},
|
||||
{
|
||||
id: "name-one",
|
||||
name: "sonarr",
|
||||
kind: "sonarr",
|
||||
url: "http://other.example:8989",
|
||||
appId: null,
|
||||
items: [],
|
||||
secrets: [],
|
||||
},
|
||||
{
|
||||
id: "name-two",
|
||||
name: "sonarr",
|
||||
kind: "sonarr",
|
||||
url: "http://third.example:8989",
|
||||
appId: null,
|
||||
items: [],
|
||||
secrets: [],
|
||||
},
|
||||
]);
|
||||
|
||||
const result = await createAdminCaller().reconcileServices();
|
||||
|
||||
expect(result.candidates[0]?.representation.integration?.id).toBe("exact");
|
||||
expect(result.candidates[0]?.representation.signals.ambiguous).toBe(false);
|
||||
});
|
||||
|
||||
test("does not fall back to a unique name when exact integration matches are ambiguous", 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: "named", name: "sonarr", kind: "sonarr", url: "http://home.example:8989", appId: null },
|
||||
{ id: "other", name: "Other", 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]?.nextAction).toBe("reviewIntegration");
|
||||
});
|
||||
|
||||
test("prefers an explicitly linked app over duplicate app matches", 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: "linked",
|
||||
items: [],
|
||||
secrets: [],
|
||||
},
|
||||
]);
|
||||
findAppsAsyncMock.mockResolvedValueOnce([
|
||||
{ id: "linked", name: "Sonarr", href: "http://home.example:8989", iconUrl: "" },
|
||||
{ id: "duplicate", name: "Sonarr duplicate", href: "http://home.example:8989", iconUrl: "" },
|
||||
]);
|
||||
|
||||
const result = await createAdminCaller().reconcileServices();
|
||||
|
||||
expect(result.candidates[0]?.representation.app?.id).toBe("linked");
|
||||
expect(result.candidates[0]?.representation.signals.ambiguous).toBe(false);
|
||||
expect(result.candidates[0]?.state).toBe("linked");
|
||||
});
|
||||
|
||||
test("marks a linked integration as moved when only its app URL still matches", 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://old.example:8989",
|
||||
appId: "linked",
|
||||
items: [],
|
||||
secrets: [],
|
||||
},
|
||||
]);
|
||||
findAppsAsyncMock.mockResolvedValueOnce([
|
||||
{ id: "linked", name: "Sonarr", href: "http://home.example:8989", iconUrl: "" },
|
||||
]);
|
||||
|
||||
const result = await createAdminCaller().reconcileServices();
|
||||
|
||||
expect(result.candidates[0]?.state).toBe("moved");
|
||||
expect(result.candidates[0]?.nextAction).toBe("reviewIntegration");
|
||||
expect(result.candidates[0]?.representation.signals).toMatchObject({
|
||||
exactIntegrationUrl: false,
|
||||
exactAppUrl: true,
|
||||
linked: true,
|
||||
});
|
||||
});
|
||||
|
||||
test("does not offer to create an app when existing app matches are ambiguous", async () => {
|
||||
const dockerData = {
|
||||
data: {
|
||||
containers: [createInventoryContainer({ endpointId: "home", id: "one", name: "sonarr", publicPort: 8989 })],
|
||||
endpoints: [{ id: "home", name: "Home", status: "available" }],
|
||||
},
|
||||
timestamp: new Date(),
|
||||
} satisfies Awaited<ReturnType<typeof getDockerDataAsyncMock>>;
|
||||
getDockerDataAsyncMock.mockResolvedValueOnce(dockerData).mockResolvedValueOnce(dockerData);
|
||||
const apps = [
|
||||
{ id: "first", name: "Sonarr one", href: "http://home.example:8989", iconUrl: "" },
|
||||
{ id: "second", name: "Sonarr two", href: "http://home.example:8989", iconUrl: "" },
|
||||
] satisfies Awaited<ReturnType<typeof findAppsAsyncMock>>;
|
||||
findAppsAsyncMock.mockResolvedValueOnce(apps).mockResolvedValueOnce(apps);
|
||||
|
||||
const reconciliation = await createAdminCaller().reconcileServices();
|
||||
const health = await createAdminCaller().getServiceHealth();
|
||||
|
||||
expect(reconciliation.candidates[0]?.representation.app).toBeNull();
|
||||
expect(reconciliation.candidates[0]?.representation.signals.ambiguous).toBe(true);
|
||||
expect(reconciliation.candidates[0]?.nextAction).toBe("viewRepresentation");
|
||||
expect(health.services[0]?.layers).toContainEqual({
|
||||
layer: "appRepresentation",
|
||||
status: "missing",
|
||||
nextAction: "viewRepresentation",
|
||||
});
|
||||
});
|
||||
|
||||
test("invalidates the shared Docker inventory on explicit refresh", async () => {
|
||||
await createAdminCaller().refreshInventory();
|
||||
|
||||
expect(invalidateDockerCacheMock).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
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" }],
|
||||
});
|
||||
@@ -56,6 +56,7 @@ describe("all should return all integrations", () => {
|
||||
expect(result.length).toBe(2);
|
||||
expect(result[0]!.kind).toBe("plex");
|
||||
expect(result[1]!.kind).toBe("homeAssistant");
|
||||
expect(result.every(({ permissions }) => permissions.hasFullAccess && permissions.hasUseAccess)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -312,7 +313,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 +328,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 +357,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 +373,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();
|
||||
});
|
||||
|
||||
@@ -38,7 +38,10 @@ const MCP_TOOL_ALLOWLIST = {
|
||||
"customWidget_workshopSearch",
|
||||
"dnsHole_summary",
|
||||
"docker_getContainers",
|
||||
"docker_getEndpoints",
|
||||
"docker_getServiceHealth",
|
||||
"docker_logs",
|
||||
"docker_reconcileServices",
|
||||
"downloads_getJobsAndStatuses",
|
||||
"healthMonitoring_getClusterHealthStatus",
|
||||
"healthMonitoring_getSystemHealthStatus",
|
||||
@@ -82,6 +85,7 @@ const MCP_TOOL_ALLOWLIST = {
|
||||
"customWidget_templatePatch",
|
||||
"dnsHole_disable",
|
||||
"dnsHole_enable",
|
||||
"docker_refreshInventory",
|
||||
"docker_removeAll",
|
||||
"docker_restartAll",
|
||||
"docker_startAll",
|
||||
|
||||
@@ -15,14 +15,15 @@ export const constructIntegrationPermissions = (integration: IntegrationPermissi
|
||||
const permissions = integration.userPermissions
|
||||
.concat(integration.groupPermissions)
|
||||
.map(({ permission }) => permission);
|
||||
const hasGlobalFullAccess = session?.user.permissions.includes("integration-full-all") ?? false;
|
||||
const hasGlobalInteractAccess =
|
||||
hasGlobalFullAccess || (session?.user.permissions.includes("integration-interact-all") ?? false);
|
||||
const hasGlobalUseAccess =
|
||||
hasGlobalInteractAccess || (session?.user.permissions.includes("integration-use-all") ?? false);
|
||||
|
||||
return {
|
||||
hasFullAccess:
|
||||
(session?.user.permissions.includes("integration-full-all") ?? false) || permissions.includes("full"),
|
||||
hasInteractAccess:
|
||||
permissions.includes("full") ||
|
||||
permissions.includes("interact") ||
|
||||
(session?.user.permissions.includes("integration-interact-all") ?? false),
|
||||
hasUseAccess: permissions.length >= 1 || (session?.user.permissions.includes("integration-use-all") ?? false),
|
||||
hasFullAccess: hasGlobalFullAccess || permissions.includes("full"),
|
||||
hasInteractAccess: hasGlobalInteractAccess || permissions.includes("full") || permissions.includes("interact"),
|
||||
hasUseAccess: hasGlobalUseAccess || permissions.length >= 1,
|
||||
};
|
||||
};
|
||||
@@ -30,6 +30,18 @@ describe("constructIntegrationPermissions", () => {
|
||||
expect(result.hasUseAccess).toBe(true);
|
||||
});
|
||||
|
||||
test("should derive lower access levels from an unexpanded full permission", () => {
|
||||
const result = constructIntegrationPermissions(
|
||||
{ userPermissions: [], groupPermissions: [] },
|
||||
{
|
||||
user: { id: "2", permissions: ["integration-full-all"], colorScheme: "light" },
|
||||
expires: new Date().toISOString(),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toEqual({ hasFullAccess: true, hasInteractAccess: true, hasUseAccess: true });
|
||||
});
|
||||
|
||||
test("should return hasInteractAccess as true when session permissions include integration-interact-all", () => {
|
||||
// Arrange
|
||||
const integration = {
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
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
|
||||
: isUsablePublishedAddress(endpointHostname ?? undefined)
|
||||
? endpointHostname
|
||||
: null;
|
||||
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 => {
|
||||
if (!value) return false;
|
||||
const host = value.toLowerCase().replace(/^\[|\]$/gu, "");
|
||||
return (
|
||||
!["0.0.0.0", "::", "::0", "::1", "localhost"].includes(host) &&
|
||||
!host.endsWith(".localhost") &&
|
||||
!/^127(?:\.\d{1,3}){3}$/.test(host) &&
|
||||
!host.startsWith("::ffff:127.")
|
||||
);
|
||||
};
|
||||
|
||||
const getEndpointHostname = (host: string) => {
|
||||
if (host === "socket" || host.startsWith("/") || /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(host)) return null;
|
||||
try {
|
||||
return new URL(`http://${host}`).hostname || null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const formatUrlHost = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
|
||||
@@ -332,6 +332,7 @@ export type HomarrDocumentationPath =
|
||||
| "/docs/integrations/peanut"
|
||||
| "/docs/integrations/beszel"
|
||||
| "/docs/integrations/traefik"
|
||||
| "/docs/integrations/archiveteam-warrior"
|
||||
| "/docs/integrations/whats-up-docker"
|
||||
| "/docs/widgets/clock"
|
||||
| "/docs/widgets/weather"
|
||||
|
||||
@@ -53,7 +53,7 @@ export const integrationDocSlugs: Record<IntegrationKind, string | null> = {
|
||||
peaNut: "peanut",
|
||||
beszel: "beszel",
|
||||
traefik: "traefik",
|
||||
archiveTeamWarrior: null,
|
||||
archiveTeamWarrior: "archiveteam-warrior",
|
||||
wud: "whats-up-docker",
|
||||
mock: null,
|
||||
};
|
||||
@@ -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";
|
||||
@@ -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,93 @@
|
||||
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",
|
||||
});
|
||||
});
|
||||
|
||||
test.each(["127.0.0.1", "127.12.0.9", "::1", "::ffff:127.0.0.1", "localhost"])(
|
||||
"does not advertise loopback address %s to browsers",
|
||||
(address) => {
|
||||
const candidates = buildDockerServiceUrlCandidates({
|
||||
containerName: "sonarr",
|
||||
endpointHost: "socket",
|
||||
preferredPort: 8989,
|
||||
ports: [{ IP: address, PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
|
||||
});
|
||||
|
||||
expect(candidates.some(({ source }) => source === "publishedAddress")).toBe(false);
|
||||
expect(candidates.some(({ url, scopes }) => url.includes(address) && scopes.includes("browser"))).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
test("does not use a loopback Docker endpoint as a browser URL", () => {
|
||||
const candidates = buildDockerServiceUrlCandidates({
|
||||
containerName: "sonarr",
|
||||
endpointHost: "[::1]:2375",
|
||||
preferredPort: 8989,
|
||||
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
|
||||
});
|
||||
|
||||
expect(candidates.some(({ source }) => source === "endpointHost")).toBe(false);
|
||||
});
|
||||
|
||||
test.each(["tcp://10.0.0.5:2375", "unix:///var/run/docker.sock", "https://10.0.0.5"])(
|
||||
"rejects a scheme-bearing endpoint host %s as a browser URL",
|
||||
(endpointHost) => {
|
||||
const candidates = buildDockerServiceUrlCandidates({
|
||||
containerName: "sonarr",
|
||||
endpointHost,
|
||||
preferredPort: 8989,
|
||||
ports: [{ IP: "0.0.0.0", PrivatePort: 8989, PublicPort: 8989, Type: "tcp" }],
|
||||
});
|
||||
|
||||
expect(candidates.some(({ source }) => source === "endpointHost")).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,10 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { objectEntries } from "@homarr/common";
|
||||
|
||||
import { integrationDefs } from "../integration";
|
||||
|
||||
describe("Icon url's of integrations should be valid and return 200", () => {
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal(
|
||||
"fetch",
|
||||
vi.fn(async () => new Response(null, { status: 200 })),
|
||||
);
|
||||
});
|
||||
|
||||
objectEntries(integrationDefs).forEach(([integration, { iconUrl }]) => {
|
||||
it(`should return 200 for ${integration}`, { concurrent: true, retry: 2, timeout: 15_000 }, async () => {
|
||||
const res = await fetch(iconUrl);
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
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({
|
||||
"smartHome-entityState": 1,
|
||||
"smartHome-executeAutomation": 1,
|
||||
mediaTranscoding: 1,
|
||||
"immich-serverStats": 1,
|
||||
"immich-albumCarousel": 1,
|
||||
paperlessNgx: 1,
|
||||
patchmon: 1,
|
||||
bazarr: 1,
|
||||
audioStats: 1,
|
||||
umami: 1,
|
||||
archiveTeamWarrior: 1,
|
||||
anchorNote: 1,
|
||||
wud: 1,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,69 +1,105 @@
|
||||
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"),
|
||||
serverMaxIntegrations: 1,
|
||||
},
|
||||
"smartHome-executeAutomation": {
|
||||
integrations: getIntegrationKindsByCategory("smartHomeServer"),
|
||||
serverMaxIntegrations: 1,
|
||||
},
|
||||
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"), serverMaxIntegrations: 1 },
|
||||
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"], serverMaxIntegrations: 1 },
|
||||
"immich-albumCarousel": { integrations: ["immich"], serverMaxIntegrations: 1 },
|
||||
paperlessNgx: { integrations: ["paperlessNgx"], serverMaxIntegrations: 1 },
|
||||
patchmon: { integrations: ["patchmon"], serverMaxIntegrations: 1 },
|
||||
bazarr: { integrations: ["bazarr"], serverMaxIntegrations: 1 },
|
||||
tracearr: { integrations: ["tracearr"] },
|
||||
speedtestTracker: { integrations: ["speedtestTracker"] },
|
||||
uptimeKuma: { integrations: ["uptimeKuma"] },
|
||||
audioStats: { integrations: ["navidrome", "audiobookshelf"], serverMaxIntegrations: 1 },
|
||||
umami: { integrations: ["umami"], serverMaxIntegrations: 1 },
|
||||
vpn: { integrations: getIntegrationKindsByCategory("vpn") },
|
||||
ups: { integrations: getIntegrationKindsByCategory("ups") },
|
||||
archiveTeamWarrior: { integrations: ["archiveTeamWarrior"], serverMaxIntegrations: 1 },
|
||||
anchorNote: { integrations: ["anchor"], serverMaxIntegrations: 1 },
|
||||
traefik: { integrations: ["traefik"] },
|
||||
wud: { integrations: ["wud"], serverMaxIntegrations: 1 },
|
||||
} 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 +134,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;
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
@@ -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),
|
||||
},
|
||||
|
||||
@@ -1,12 +1,31 @@
|
||||
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";
|
||||
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" | "degraded" | "unavailable";
|
||||
kind?: "docker" | "podman";
|
||||
transport?: "socket" | "tcp" | "tls";
|
||||
capabilities?: DockerEndpointCapability[];
|
||||
source?: "environment" | "legacy" | "default";
|
||||
scope?: "admin";
|
||||
}
|
||||
|
||||
export * from "./labels";
|
||||
export * from "./discovery";
|
||||
@@ -1,26 +1,70 @@
|
||||
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 {
|
||||
createLegacySocketDescriptor,
|
||||
createLegacyTcpDescriptor,
|
||||
getDockerEndpointHost,
|
||||
parseDockerEndpointDescriptors,
|
||||
} from "./endpoint-descriptor";
|
||||
|
||||
export interface DockerInstance {
|
||||
endpointId: string;
|
||||
endpointName: string;
|
||||
host: string;
|
||||
descriptor: DockerEndpointDescriptor;
|
||||
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).flatMap((descriptor) =>
|
||||
this.createInstanceSafely(descriptor),
|
||||
);
|
||||
}
|
||||
|
||||
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(",")
|
||||
.flatMap((socketPath) => this.createInstanceSafely(createLegacySocketDescriptor(socketPath)))
|
||||
: [];
|
||||
|
||||
// TCP instances from existing DOCKER_HOSTNAMES/DOCKER_PORTS
|
||||
@@ -33,25 +77,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.flatMap((host, i) =>
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
instance: new Docker({ host, port: parseInt(ports[i]!, 10) }),
|
||||
}));
|
||||
this.createInstanceSafely(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)];
|
||||
}
|
||||
|
||||
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[] {
|
||||
@@ -59,7 +112,41 @@ 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];
|
||||
}
|
||||
|
||||
public static reset(): void {
|
||||
this.instances = null;
|
||||
this.initializationFailures = [];
|
||||
}
|
||||
}
|
||||
|
||||
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,71 @@
|
||||
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");
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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,13 +33,17 @@ 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", () => {
|
||||
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", () => {
|
||||
@@ -60,6 +65,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 +92,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 +114,39 @@ 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);
|
||||
});
|
||||
|
||||
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" }) }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -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,43 @@
|
||||
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("treats a fixture without expected or rejects as a successful parse assertion", async () => {
|
||||
const results = await simulateResponseContractAsync(parser, [{ name: "parses only", payload: { count: 5 } }]);
|
||||
|
||||
expect(results).toEqual([{ name: "parses only", 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 = "expected" in fixture ? isDeepStrictEqual(actual, fixture.expected) : true;
|
||||
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";
|
||||
@@ -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";
|
||||
@@ -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,25 +1,30 @@
|
||||
import { useMemo, useState } from "react";
|
||||
import { Box, Button, Card, Center, Group, Stack, Text, Tooltip } from "@mantine/core";
|
||||
import { IconPlus } from "@tabler/icons-react";
|
||||
import { Button, Center, Group, Stack, Text, Tooltip } from "@mantine/core";
|
||||
import { IconCheck, IconPlus, IconApps } 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";
|
||||
|
||||
type SelectableApp = RouterOutputs["app"]["selectable"][number];
|
||||
|
||||
interface AppSelectModalProps {
|
||||
onSelect?: (app: RouterOutputs["app"]["selectable"][number]) => void;
|
||||
onSelect?: (app: SelectableApp) => void;
|
||||
onSelectMany?: (apps: SelectableApp[]) => void;
|
||||
withCreate: boolean;
|
||||
}
|
||||
|
||||
export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, innerProps }) => {
|
||||
const [search, setSearch] = useState("");
|
||||
const [selectedAppIds, setSelectedAppIds] = useState<Set<string>>(new Set());
|
||||
const t = useI18n();
|
||||
const { data: apps = [], isPending } = clientApi.app.selectable.useQuery();
|
||||
const { openModal: openQuickAddAppModal } = useModalAction(QuickAddAppModal);
|
||||
const multiSelect = Boolean(innerProps.onSelectMany);
|
||||
|
||||
const filteredApps = useMemo(
|
||||
() =>
|
||||
@@ -29,14 +34,42 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
|
||||
[apps, search],
|
||||
);
|
||||
|
||||
const handleSelect = (app: RouterOutputs["app"]["selectable"][number]) => {
|
||||
const selectedApps = useMemo(() => apps.filter((app) => selectedAppIds.has(app.id)), [apps, selectedAppIds]);
|
||||
|
||||
const handleSelect = (app: SelectableApp) => {
|
||||
if (multiSelect) {
|
||||
setSelectedAppIds((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(app.id)) next.delete(app.id);
|
||||
else next.add(app.id);
|
||||
return next;
|
||||
});
|
||||
return;
|
||||
}
|
||||
innerProps.onSelect?.(app);
|
||||
actions.closeModal();
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
if (multiSelect) {
|
||||
innerProps.onSelectMany?.(selectedApps);
|
||||
actions.closeModal();
|
||||
return;
|
||||
}
|
||||
const [first] = filteredApps;
|
||||
if (first) {
|
||||
innerProps.onSelect?.(first);
|
||||
actions.closeModal();
|
||||
}
|
||||
};
|
||||
|
||||
const handleAddNewApp = () => {
|
||||
openQuickAddAppModal({
|
||||
onClose(app) {
|
||||
if (multiSelect) {
|
||||
setSelectedAppIds((current) => new Set(current).add(app.id));
|
||||
return;
|
||||
}
|
||||
innerProps.onSelect?.(app);
|
||||
actions.closeModal();
|
||||
},
|
||||
@@ -44,104 +77,97 @@ export const AppSelectModal = createModal<AppSelectModalProps>(({ actions, inner
|
||||
};
|
||||
|
||||
return (
|
||||
<SelectGridLayout
|
||||
search={search}
|
||||
onSearchChange={setSearch}
|
||||
placeholder={`${t("app.action.select.search")}...`}
|
||||
ariaLabel={t("app.action.select.search")}
|
||||
onSearchKeyDown={(event) => {
|
||||
if (event.key === "Enter" && filteredApps.length === 1 && filteredApps[0]) {
|
||||
handleSelect(filteredApps[0]);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{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")}
|
||||
>
|
||||
<Stack h="100%" gap="xs">
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
<IconPlus size={22} style={{ flexShrink: 0, marginTop: 2 }} />
|
||||
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
|
||||
{t("app.action.create.title")}
|
||||
</Text>
|
||||
</Group>
|
||||
<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%)",
|
||||
}}
|
||||
<>
|
||||
<SelectGridLayout
|
||||
search={search}
|
||||
onSearchChange={setSearch}
|
||||
placeholder={`${t("app.action.select.search")}...`}
|
||||
ariaLabel={t("app.action.select.search")}
|
||||
onSearchKeyDown={(event) => {
|
||||
if (event.key === "Enter" && filteredApps.length === 1 && filteredApps[0]) {
|
||||
handleSelect(filteredApps[0]);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{innerProps.withCreate && (
|
||||
<CatalogItem
|
||||
height={selectGridCardHeight}
|
||||
label={t("app.action.create.title")}
|
||||
status={t("app.action.create.action")}
|
||||
onSelect={handleAddNewApp}
|
||||
>
|
||||
<Button onClick={handleAddNewApp} variant="light" size="xs" fullWidth>
|
||||
{t("app.action.create.action")}
|
||||
</Button>
|
||||
</Box>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{filteredApps.map((app) => (
|
||||
<Card
|
||||
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")}
|
||||
>
|
||||
<Stack h="100%" gap="xs">
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
<img src={app.iconUrl} alt={app.name} width={22} height={22} style={{ flexShrink: 0, marginTop: 2 }} />
|
||||
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
|
||||
{app.name}
|
||||
</Text>
|
||||
</Group>
|
||||
<Tooltip label={app.description} multiline w={250} disabled={!app.description}>
|
||||
<Stack h="100%" gap="xs">
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
<IconPlus size={22} style={{ flexShrink: 0, marginTop: 2 }} />
|
||||
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
|
||||
{t("app.action.create.title")}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
|
||||
{app.description ?? ""}
|
||||
{t("app.action.create.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>
|
||||
{t("app.action.select.action", { app: app.name })}
|
||||
</Button>
|
||||
</Box>
|
||||
</Card>
|
||||
))}
|
||||
<Text size="xs" c="blue" fw={500} mt="auto">
|
||||
{t("app.action.create.action")}
|
||||
</Text>
|
||||
</Stack>
|
||||
</CatalogItem>
|
||||
)}
|
||||
|
||||
{filteredApps.length === 0 && !isPending && (
|
||||
<Center p="xl">
|
||||
<Text c="dimmed">{t("app.action.select.noResults")}</Text>
|
||||
</Center>
|
||||
{filteredApps.map((app) => (
|
||||
<CatalogItem
|
||||
key={app.id}
|
||||
height={selectGridCardHeight}
|
||||
label={app.name}
|
||||
status={
|
||||
multiSelect
|
||||
? selectedAppIds.has(app.id)
|
||||
? t("app.action.select.selected")
|
||||
: t("app.action.select.toggle")
|
||||
: t("app.action.select.action", { app: app.name })
|
||||
}
|
||||
selected={multiSelect ? selectedAppIds.has(app.id) : undefined}
|
||||
onSelect={() => handleSelect(app)}
|
||||
>
|
||||
<Stack h="100%" gap="xs">
|
||||
<Group gap="sm" wrap="nowrap" align="flex-start">
|
||||
<img src={app.iconUrl} alt={app.name} width={22} height={22} style={{ flexShrink: 0, marginTop: 2 }} />
|
||||
<Text lh={1.2} style={{ whiteSpace: "normal" }} fw={500} size="sm" lineClamp={2}>
|
||||
{app.name}
|
||||
</Text>
|
||||
{multiSelect && selectedAppIds.has(app.id) && (
|
||||
<IconCheck size={18} color="var(--mantine-primary-color-filled)" />
|
||||
)}
|
||||
</Group>
|
||||
<Tooltip label={app.description} multiline w={250} disabled={!app.description}>
|
||||
<Text lh={1.2} style={{ whiteSpace: "normal" }} size="xs" c="dimmed" lineClamp={1}>
|
||||
{app.description ?? ""}
|
||||
</Text>
|
||||
</Tooltip>
|
||||
<Text size="xs" c="blue" fw={500} mt="auto">
|
||||
{multiSelect
|
||||
? selectedAppIds.has(app.id)
|
||||
? t("app.action.select.selected")
|
||||
: t("app.action.select.toggle")
|
||||
: t("app.action.select.action", { app: app.name })}
|
||||
</Text>
|
||||
</Stack>
|
||||
</CatalogItem>
|
||||
))}
|
||||
|
||||
{filteredApps.length === 0 && !isPending && (
|
||||
<Center p="xl">
|
||||
<Text c="dimmed">{t("app.action.select.noResults")}</Text>
|
||||
</Center>
|
||||
)}
|
||||
</SelectGridLayout>
|
||||
{multiSelect && (
|
||||
<Group justify="flex-end" mt="md">
|
||||
<Button leftSection={<IconApps size={16} />} disabled={selectedAppIds.size === 0} onClick={handleSubmit}>
|
||||
{t("app.action.select.multiple", { count: String(selectedAppIds.size) })}
|
||||
</Button>
|
||||
</Group>
|
||||
)}
|
||||
</SelectGridLayout>
|
||||
</>
|
||||
);
|
||||
}).withOptions({
|
||||
defaultTitle: (t) => t("app.action.select.title"),
|
||||
|
||||
@@ -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;
|
||||
const candidates = buildDockerServiceUrlCandidates({
|
||||
containerName: container.name,
|
||||
endpointHost: container.host,
|
||||
ports: container.ports,
|
||||
}).filter(({ url }) => url.length > 0);
|
||||
|
||||
return candidates.find(({ scopes }) => scopes.includes("browser"))?.url ?? candidates[0]?.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";
|
||||
@@ -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";
|
||||
@@ -0,0 +1,108 @@
|
||||
// @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, test, vi } from "vitest";
|
||||
|
||||
import { ConfirmModal } from "./confirm-modal";
|
||||
|
||||
const ConfirmModalComponent = ConfirmModal.component;
|
||||
|
||||
vi.mock("@homarr/translation/client", () => ({
|
||||
useI18n: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
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("ConfirmModal", () => {
|
||||
test("clears loading and stays open when confirmation rejects", async () => {
|
||||
const closeModal = vi.fn();
|
||||
let rejectConfirmation!: (error: Error) => void;
|
||||
const pendingConfirmation = new Promise<void>((_resolve, reject) => {
|
||||
rejectConfirmation = reject;
|
||||
});
|
||||
const onConfirm = vi.fn(() => pendingConfirmation);
|
||||
|
||||
await act(async () =>
|
||||
root.render(
|
||||
<MantineProvider>
|
||||
<ConfirmModalComponent actions={{ closeModal }} innerProps={{ children: "Remove containers?", onConfirm }} />
|
||||
</MantineProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
const confirmButton = host.querySelectorAll("button").item(1);
|
||||
await act(async () => confirmButton.click());
|
||||
expect(confirmButton.disabled).toBe(true);
|
||||
|
||||
await act(async () => {
|
||||
rejectConfirmation(new Error("Removal failed"));
|
||||
await Promise.resolve();
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -36,8 +36,8 @@ export const ConfirmModal = createModal<Omit<ConfirmModalProps, "title">>(({ act
|
||||
const closeOnConfirm = innerProps.closeOnConfirm ?? true;
|
||||
const closeOnCancel = innerProps.closeOnCancel ?? true;
|
||||
|
||||
const cancelLabel = labels?.cancel ?? ((t: TranslationFunction) => t("common.action.cancel"));
|
||||
const confirmLabel = labels?.confirm ?? ((t: TranslationFunction) => t("common.action.confirm"));
|
||||
const cancelLabel = labels?.cancel ?? ((translate: TranslationFunction) => translate("common.action.cancel"));
|
||||
const confirmLabel = labels?.confirm ?? ((translate: TranslationFunction) => translate("common.action.confirm"));
|
||||
|
||||
const handleCancel = useCallback(
|
||||
async (event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
@@ -59,19 +59,23 @@ export const ConfirmModal = createModal<Omit<ConfirmModalProps, "title">>(({ act
|
||||
const handleConfirm = useCallback(
|
||||
async (event: React.MouseEvent<HTMLButtonElement>) => {
|
||||
setLoading(true);
|
||||
try {
|
||||
if (typeof confirmProps?.onClick === "function") {
|
||||
await confirmProps.onClick(event);
|
||||
}
|
||||
|
||||
if (typeof confirmProps?.onClick === "function") {
|
||||
confirmProps.onClick(event);
|
||||
}
|
||||
if (typeof onConfirm === "function") {
|
||||
await onConfirm();
|
||||
}
|
||||
|
||||
if (typeof onConfirm === "function") {
|
||||
await onConfirm();
|
||||
if (closeOnConfirm) {
|
||||
actions.closeModal();
|
||||
}
|
||||
} catch {
|
||||
// Keep the modal open. Callers own action-specific error feedback.
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
if (closeOnConfirm) {
|
||||
actions.closeModal();
|
||||
}
|
||||
setLoading(false);
|
||||
},
|
||||
[confirmProps, onConfirm, closeOnConfirm, actions],
|
||||
);
|
||||
|
||||
@@ -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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
@@ -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> {
|
||||
|
||||
@@ -8,15 +8,40 @@ 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";
|
||||
import { createWidgetRequestHandler } from "./lib/widget-request-handler";
|
||||
|
||||
const logger = createLogger({ module: "dockerRequestHandler" });
|
||||
export const dockerWidgetEndpointTimeoutMs = 5_000;
|
||||
|
||||
const isDemoMode = ["1", "yes", "t", "true"].includes((process.env.DEMO_MODE ?? "").toLowerCase());
|
||||
const withDockerTimeoutAsync = async <T>(
|
||||
operation: (signal: AbortSignal) => Promise<T>,
|
||||
message: string,
|
||||
timeoutMs: number,
|
||||
) => {
|
||||
const controller = new AbortController();
|
||||
const timeoutError = new Error(message);
|
||||
let timeout: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
try {
|
||||
return await Promise.race([
|
||||
operation(controller.signal),
|
||||
new Promise<never>((_, reject) => {
|
||||
timeout = setTimeout(() => {
|
||||
controller.abort(timeoutError);
|
||||
reject(timeoutError);
|
||||
}, timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timeout) clearTimeout(timeout);
|
||||
}
|
||||
};
|
||||
|
||||
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",
|
||||
@@ -172,8 +197,27 @@ const mockContainers: {
|
||||
|
||||
export const dockerContainersRequestHandler = createWidgetRequestHandler({
|
||||
async requestAsync() {
|
||||
if (isDemoMode) {
|
||||
return mockContainers;
|
||||
if (isDemoMode()) {
|
||||
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 +225,29 @@ 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",
|
||||
) =>
|
||||
isDemoMode()
|
||||
? endpointId === "demo" && capability === "inventory"
|
||||
: 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 +263,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 +303,85 @@ export const streamContainerLogsAsync = async (
|
||||
};
|
||||
};
|
||||
|
||||
async function getContainersWithStatsAsync() {
|
||||
export const getDockerEndpointsAsync = (): DockerEndpointStatus[] => {
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const initializationFailures = DockerSingleton.getInitializationFailures();
|
||||
|
||||
return [
|
||||
...dockerInstances.map(({ endpointId, endpointName, descriptor }) => ({
|
||||
id: endpointId,
|
||||
name: endpointName,
|
||||
status: "available" as const,
|
||||
kind: descriptor.kind,
|
||||
transport: descriptor.transport.type,
|
||||
capabilities: descriptor.capabilities,
|
||||
source: descriptor.source,
|
||||
scope: descriptor.scope,
|
||||
})),
|
||||
...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,
|
||||
})),
|
||||
];
|
||||
};
|
||||
|
||||
export async function getContainersWithStatsAsync(timeoutMs = dockerWidgetEndpointTimeoutMs) {
|
||||
const dockerInstances = DockerSingleton.getInstances();
|
||||
const initializationFailures = DockerSingleton.getInitializationFailures();
|
||||
const results = await Promise.allSettled(
|
||||
dockerInstances.map(async ({ instance, host }) => {
|
||||
const instanceContainers = await instance.listContainers({ all: true });
|
||||
dockerInstances.map(async ({ instance, host, endpointId, endpointName }) => {
|
||||
const instanceContainers = await withDockerTimeoutAsync(
|
||||
async (signal) => await instance.listContainers({ all: true, abortSignal: signal }),
|
||||
`Timed out listing containers from Docker host ${host}`,
|
||||
timeoutMs,
|
||||
);
|
||||
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" 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;
|
||||
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 },
|
||||
),
|
||||
@@ -294,26 +398,44 @@ async function getContainersWithStatsAsync() {
|
||||
})
|
||||
: [];
|
||||
|
||||
const degradedEndpointIds = new Set<string>();
|
||||
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
|
||||
.getContainer(container.Id)
|
||||
.stats({ stream: false, "one-shot": true })
|
||||
.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);
|
||||
|
||||
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 +447,15 @@ async function getContainersWithStatsAsync() {
|
||||
};
|
||||
});
|
||||
|
||||
return (await Promise.all(containerStatsPromises)).filter((container) => container !== null);
|
||||
const resolvedContainers = (await Promise.all(containerStatsPromises)).filter((container) => container !== null);
|
||||
return {
|
||||
containers: resolvedContainers,
|
||||
endpoints: endpoints.map((endpoint) =>
|
||||
endpoint.status === "available" && degradedEndpointIds.has(endpoint.id)
|
||||
? { ...endpoint, status: "degraded" as const }
|
||||
: endpoint,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function calculateCpuUsage(stats: ContainerStats): number {
|
||||
|
||||
@@ -2,8 +2,14 @@ import type { ContainerStats } from "dockerode";
|
||||
import { describe, expect, test, vi } from "vitest";
|
||||
|
||||
import { createDb } from "@homarr/db/test";
|
||||
import { DockerSingleton } from "@homarr/docker";
|
||||
|
||||
import { calculateCpuUsage, calculateMemoryUsage } from "../docker";
|
||||
import {
|
||||
calculateCpuUsage,
|
||||
calculateMemoryUsage,
|
||||
getContainersWithStatsAsync,
|
||||
hasDockerEndpointCapability,
|
||||
} from "../docker";
|
||||
|
||||
vi.mock("@homarr/db", async (importActual) => {
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-imports
|
||||
@@ -119,3 +125,115 @@ describe("calculateMemoryUsage", () => {
|
||||
expect(calculateMemoryUsage(stats)).toBe(512);
|
||||
});
|
||||
});
|
||||
|
||||
describe("getContainersWithStatsAsync", () => {
|
||||
test("marks a timed-out endpoint unavailable without blocking healthy endpoints", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
vi.spyOn(DockerSingleton, "getInstances").mockReturnValue([
|
||||
createDockerInstance("stalled", () => new Promise(() => undefined)),
|
||||
createDockerInstance("healthy", async () => []),
|
||||
] as never);
|
||||
|
||||
const resultPromise = getContainersWithStatsAsync(50);
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(result.endpoints).toEqual([
|
||||
expect.objectContaining({ id: "stalled", status: "unavailable" }),
|
||||
expect.objectContaining({ id: "healthy", status: "available" }),
|
||||
]);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
|
||||
test("marks an endpoint degraded and returns zeroed stats when its stats request times out", async () => {
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
const dockerInstance = createDockerInstance("healthy", async () => [
|
||||
{
|
||||
Id: "container-1",
|
||||
Image: "sonarr:latest",
|
||||
Labels: {},
|
||||
Names: ["/sonarr"],
|
||||
State: "running",
|
||||
Ports: [],
|
||||
},
|
||||
]);
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
dockerInstance.instance.getContainer = (() => ({
|
||||
stats: (options: { abortSignal?: AbortSignal }) => {
|
||||
observedSignal = options.abortSignal;
|
||||
return new Promise(() => undefined);
|
||||
},
|
||||
})) as never;
|
||||
vi.spyOn(DockerSingleton, "getInstances").mockReturnValue([dockerInstance] as never);
|
||||
vi.spyOn(DockerSingleton, "findInstance").mockReturnValue(dockerInstance as never);
|
||||
|
||||
const resultPromise = getContainersWithStatsAsync(50);
|
||||
await vi.advanceTimersByTimeAsync(50);
|
||||
const result = await resultPromise;
|
||||
|
||||
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[]>) => ({
|
||||
endpointId,
|
||||
endpointName: endpointId,
|
||||
host: endpointId,
|
||||
descriptor: {
|
||||
kind: "docker",
|
||||
transport: { type: "socket" },
|
||||
capabilities: ["inventory"],
|
||||
source: "environment",
|
||||
scope: "admin",
|
||||
},
|
||||
instance: { listContainers, getContainer: () => ({}) },
|
||||
});
|
||||
@@ -1,14 +1,17 @@
|
||||
import { usePathname, useRouter, useSearchParams } from "next/navigation";
|
||||
import { Group, Text } from "@mantine/core";
|
||||
import {
|
||||
IconBox,
|
||||
IconCategoryPlus,
|
||||
IconMailForward,
|
||||
IconPlus,
|
||||
IconPlug,
|
||||
IconUserPlus,
|
||||
IconUsersGroup,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { useSession } from "@homarr/auth/client";
|
||||
import type { GroupPermissionKey } from "@homarr/definitions";
|
||||
import { useModalAction } from "@homarr/modals";
|
||||
import { AddBoardModal, AddGroupModal, InviteCreateModal } from "@homarr/modals-collection";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
@@ -47,8 +50,29 @@ 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 });
|
||||
},
|
||||
};
|
||||
},
|
||||
hidden: !["board-create", "app-create", "integration-create"].some((permission) =>
|
||||
session?.user.permissions.includes(permission as GroupPermissionKey),
|
||||
),
|
||||
},
|
||||
{
|
||||
commandKey: "newBoard",
|
||||
icon: IconCategoryPlus,
|
||||
|
||||
@@ -241,6 +241,61 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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."
|
||||
},
|
||||
"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"
|
||||
},
|
||||
"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",
|
||||
@@ -792,7 +847,10 @@
|
||||
"search": "Search for an app",
|
||||
"noResults": "No results",
|
||||
"action": "Select {app}",
|
||||
"title": "Select an app to add to this board"
|
||||
"title": "Select an app to add to this board",
|
||||
"toggle": "Click to select",
|
||||
"selected": "Selected",
|
||||
"multiple": "Add {count}"
|
||||
},
|
||||
"create": {
|
||||
"title": "Create new app",
|
||||
@@ -1501,6 +1559,23 @@
|
||||
}
|
||||
},
|
||||
"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",
|
||||
@@ -1600,6 +1675,10 @@
|
||||
"label": "Create app",
|
||||
"description": "Create an app with the same name and icon as the integration. Leave the input field below empty to create the app with the integration URL."
|
||||
},
|
||||
"linkApp": {
|
||||
"label": "Link an existing app",
|
||||
"description": "Connect this integration to an app you can already use."
|
||||
},
|
||||
"appHref": {
|
||||
"placeholder": "Custom app URL"
|
||||
},
|
||||
@@ -2054,7 +2133,8 @@
|
||||
"tryAgain": "Try again",
|
||||
"loading": "Loading",
|
||||
"show": "Show",
|
||||
"hide": "Hide"
|
||||
"hide": "Hide",
|
||||
"undo": "Undo"
|
||||
},
|
||||
"here": "here",
|
||||
"iconPicker": {
|
||||
@@ -2497,6 +2577,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",
|
||||
@@ -2665,7 +2746,28 @@
|
||||
"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.",
|
||||
"relocatedMessage": "{name} was added to {destination} because the selected destination was unavailable."
|
||||
},
|
||||
"error": {
|
||||
"title": "Unable to add item",
|
||||
"message": "The item could not be added to this board"
|
||||
@@ -2707,18 +2809,29 @@
|
||||
"title": "Edit item",
|
||||
"tab": {
|
||||
"widget": "Edit widget",
|
||||
"app": "Edit app"
|
||||
"app": "Edit app",
|
||||
"integration": "Edit integration"
|
||||
},
|
||||
"app": {
|
||||
"propagationNotice": "Changes to this app will be applied everywhere it is used across all dashboards."
|
||||
},
|
||||
"integration": {
|
||||
"action": "Edit connection",
|
||||
"description": "Test or repair a selected connection without leaving this widget.",
|
||||
"editLabel": "Edit {name} integration",
|
||||
"fullAccessRequired": "Full access required",
|
||||
"propagationNotice": "Changes to this integration apply everywhere it is used. The connection is tested before it is saved.",
|
||||
"loading": "Loading integration",
|
||||
"loadError": "This integration could not be loaded. Try again before changing its connection settings."
|
||||
},
|
||||
"advancedOptions": {
|
||||
"label": "Advanced options",
|
||||
"title": "Advanced item options"
|
||||
},
|
||||
"field": {
|
||||
"integrations": {
|
||||
"label": "Integrations"
|
||||
"label": "Integrations",
|
||||
"removeLabel": "Remove {name} integration"
|
||||
},
|
||||
"title": {
|
||||
"label": "Title"
|
||||
@@ -3651,6 +3764,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."
|
||||
},
|
||||
@@ -3945,7 +4059,8 @@
|
||||
},
|
||||
"integration": {
|
||||
"noData": "No integration found",
|
||||
"description": "Click <here></here> to create a new integration"
|
||||
"description": "Click <here></here> to create a new integration",
|
||||
"manage": "Manage integrations"
|
||||
},
|
||||
"app": {
|
||||
"noData": "No app found",
|
||||
@@ -5596,10 +5711,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.",
|
||||
@@ -6907,6 +7070,84 @@
|
||||
},
|
||||
"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",
|
||||
"inputLabel": "Service URL",
|
||||
"manual": "Enter an address manually",
|
||||
"invalid": "Enter a valid HTTP or HTTPS URL"
|
||||
},
|
||||
"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",
|
||||
"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": {
|
||||
"updated": "Updated {when}",
|
||||
"refresh": {
|
||||
@@ -7002,6 +7243,10 @@
|
||||
"remove": {
|
||||
"label": "Remove",
|
||||
"confirm": "Click again to remove permanently",
|
||||
"confirmation": {
|
||||
"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": {
|
||||
"title": "Containers removed",
|
||||
@@ -7013,6 +7258,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"result": {
|
||||
"failure": {
|
||||
"title": "Some container actions failed",
|
||||
"message": "{total, plural, one {{failed} of # action failed: {names}} other {{failed} of # actions failed: {names}}}"
|
||||
}
|
||||
},
|
||||
"refresh": {
|
||||
"label": "Refresh",
|
||||
"notification": {
|
||||
@@ -7045,10 +7296,26 @@
|
||||
},
|
||||
"error": {
|
||||
"internalServerError": "Failed to fetch Docker containers",
|
||||
"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",
|
||||
"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",
|
||||
@@ -7057,6 +7324,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"
|
||||
@@ -7077,6 +7345,7 @@
|
||||
"nodes": {
|
||||
"label": "Nodes",
|
||||
"field": {
|
||||
"metricsUnavailable": "Unavailable",
|
||||
"name": {
|
||||
"label": "Name"
|
||||
},
|
||||
@@ -7507,6 +7776,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,136 @@
|
||||
// @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("moves focus only for navigation keys", 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 })));
|
||||
await act(async () => button?.dispatchEvent(new KeyboardEvent("keydown", { key: " ", 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;
|
||||
};
|
||||
@@ -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";
|
||||
|
||||
@@ -11,4 +11,13 @@ describe("buildSortedIntegrations", () => {
|
||||
expect(kinds).toHaveLength(integrationKinds.length - 1);
|
||||
expect(kinds).not.toContain("mock");
|
||||
});
|
||||
|
||||
it("limits the grid to the allowed integration kinds", () => {
|
||||
const kinds = buildSortedIntegrations({ allowedKinds: ["jellyfin", "sonarr"] }).map(
|
||||
(integration) => integration.kind,
|
||||
);
|
||||
|
||||
expect(kinds).toEqual(expect.arrayContaining(["jellyfin", "sonarr"]));
|
||||
expect(kinds).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -47,10 +47,15 @@ export interface IntegrationGridItem {
|
||||
}
|
||||
|
||||
export const buildSortedIntegrations = (
|
||||
options: { enableMockIntegration?: boolean; onboarding?: boolean } = {},
|
||||
options: {
|
||||
enableMockIntegration?: boolean;
|
||||
onboarding?: boolean;
|
||||
allowedKinds?: readonly IntegrationKind[];
|
||||
} = {},
|
||||
): IntegrationGridItem[] =>
|
||||
integrationKinds
|
||||
.filter((kind) => {
|
||||
if (options.allowedKinds && !options.allowedKinds.includes(kind)) return false;
|
||||
if (options.onboarding && hiddenFromOnboarding.has(kind)) return false;
|
||||
if (!options.enableMockIntegration && kind === "mock") return false;
|
||||
return true;
|
||||
|
||||
@@ -15,12 +15,20 @@ import classes from "./integration-select-grid.module.css";
|
||||
export interface IntegrationSelectGridProps {
|
||||
onSelect: (kind: IntegrationKind) => void;
|
||||
enableMockIntegration?: boolean;
|
||||
allowedKinds?: readonly IntegrationKind[];
|
||||
}
|
||||
|
||||
export const IntegrationSelectGrid = ({ onSelect, enableMockIntegration = false }: IntegrationSelectGridProps) => {
|
||||
export const IntegrationSelectGrid = ({
|
||||
onSelect,
|
||||
enableMockIntegration = false,
|
||||
allowedKinds,
|
||||
}: IntegrationSelectGridProps) => {
|
||||
const [search, setSearch] = useState("");
|
||||
const t = useI18n();
|
||||
const integrations = useMemo(() => buildSortedIntegrations({ enableMockIntegration }), [enableMockIntegration]);
|
||||
const integrations = useMemo(
|
||||
() => buildSortedIntegrations({ enableMockIntegration, allowedKinds }),
|
||||
[allowedKinds, enableMockIntegration],
|
||||
);
|
||||
const filtered = useMemo(() => filterIntegrations(integrations, search), [integrations, search]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -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,14 +241,31 @@ 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;
|
||||
const isAdvanced = displayMode === "advanced";
|
||||
|
||||
const utils = clientApi.useUtils();
|
||||
const containersQuery = clientApi.docker.getContainers.useQuery();
|
||||
const data = getUsableWidgetQueryData(containersQuery);
|
||||
const { refetch, isFetching } = containersQuery;
|
||||
const { isFetching } = containersQuery;
|
||||
const refreshInventory = clientApi.docker.refreshInventory.useMutation({
|
||||
async onSuccess() {
|
||||
await Promise.all([
|
||||
utils.docker.getContainers.invalidate(),
|
||||
utils.docker.reconcileServices.invalidate(),
|
||||
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]);
|
||||
const relativeTime = useTimeAgo(timestamp);
|
||||
@@ -254,12 +276,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 +294,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 +387,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 +412,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();
|
||||
@@ -417,8 +453,8 @@ export default function DockerWidget({
|
||||
size="sm"
|
||||
variant="transparent"
|
||||
c="var(--mantine-color-text)"
|
||||
loading={isFetching}
|
||||
onClick={() => void refetch()}
|
||||
loading={isFetching || refreshInventory.isPending}
|
||||
onClick={() => refreshInventory.mutate()}
|
||||
aria-label={t("table.refresh.lastUpdated", { when: relativeTime })}
|
||||
>
|
||||
<IconRefresh size={16} />
|
||||
@@ -475,7 +511,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 +526,7 @@ function ContainerActionItems({
|
||||
</Menu.Label>
|
||||
<Menu.Item
|
||||
leftSection={<IconFileText size={14} />}
|
||||
disabled={!handlers.canUse(container, "logs")}
|
||||
onClick={() => {
|
||||
handlers.onOpenLogs(container);
|
||||
onClose();
|
||||
@@ -502,22 +538,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 +573,9 @@ function ContainerActionItems({
|
||||
);
|
||||
}
|
||||
|
||||
const endpointHasCapability = (endpoint: DockerEndpoint | undefined, capability: DockerEndpointCapability) =>
|
||||
endpoint && "capabilities" in endpoint ? endpoint.capabilities.includes(capability) : true;
|
||||
|
||||
function ContainerContextMenu({
|
||||
state,
|
||||
handlers,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState } from "react";
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { FormEvent } from "react";
|
||||
import { Button, Group, Stack, Tabs } from "@mantine/core";
|
||||
import { Box, Button, Group, Stack, Tabs, Text } from "@mantine/core";
|
||||
import { schemaResolver } from "@mantine/form";
|
||||
import { IconPencil } from "@tabler/icons-react";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { objectEntries } from "@homarr/common";
|
||||
@@ -13,6 +14,7 @@ import type { WidgetKind } from "@homarr/definitions";
|
||||
import { createModal, ModalFormFooter, modalSizeForm, useModalAction } from "@homarr/modals";
|
||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { IntegrationAvatar } from "@homarr/ui";
|
||||
import { zodErrorMap } from "@homarr/validation/form/i18n";
|
||||
|
||||
import { getInputForType } from "../_inputs";
|
||||
@@ -44,8 +46,15 @@ export interface WidgetEditModalProps<TSort extends WidgetKind> {
|
||||
itemId?: string;
|
||||
boardId?: string;
|
||||
appId?: string;
|
||||
onEditIntegration?: (integrationId: string) => void;
|
||||
onIntegrationSaved?: () => void;
|
||||
}
|
||||
|
||||
export const getSelectedWidgetIntegrations = (
|
||||
integrationData: readonly IntegrationSelectOption[],
|
||||
selectedIds: readonly string[],
|
||||
) => integrationData.filter((integration) => selectedIds.includes(integration.id));
|
||||
|
||||
export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({ actions, innerProps }) => {
|
||||
const t = useI18n();
|
||||
const board = useOptionalBoard();
|
||||
@@ -61,6 +70,7 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
const integrationsRequired =
|
||||
innerProps.integrationSupport &&
|
||||
(!("integrationsRequired" in definition) || definition.integrationsRequired !== false);
|
||||
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)
|
||||
@@ -79,13 +89,17 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
? z.object(optionsFieldSchema).superRefine(optionsSuperRefine)
|
||||
: z.object(optionsFieldSchema);
|
||||
|
||||
let integrationIdsSchema = z.array(z.string());
|
||||
if (integrationsRequired) integrationIdsSchema = integrationIdsSchema.min(1);
|
||||
if (Number.isFinite(maxIntegrations)) integrationIdsSchema = integrationIdsSchema.max(maxIntegrations);
|
||||
|
||||
const form = useForm({
|
||||
mode: "controlled",
|
||||
initialValues: innerProps.value,
|
||||
validate: schemaResolver(
|
||||
z.object({
|
||||
options: optionsSchema,
|
||||
integrationIds: integrationsRequired ? z.array(z.string()).min(1) : z.array(z.string()),
|
||||
integrationIds: integrationIdsSchema,
|
||||
advancedOptions: z.object({
|
||||
customCssClasses: z.array(z.string()),
|
||||
borderColor: z.string(),
|
||||
@@ -102,6 +116,27 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
const canConfigureWidget = innerProps.kind !== "customApi" || (session?.user.permissions.includes("admin") ?? false);
|
||||
const appId = innerProps.appId;
|
||||
const showAppTab = innerProps.kind === "app" && canModifyApps && Boolean(appId);
|
||||
const canModifyAllIntegrations = session?.user.permissions.includes("integration-full-all") ?? false;
|
||||
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 handleTabChange = (value: string | null) => {
|
||||
if (value === "integration" && selectedIntegrations.length === 1) {
|
||||
const integration = selectedIntegrations[0];
|
||||
if (integration) {
|
||||
innerProps.onEditIntegration?.(integration.id);
|
||||
return;
|
||||
}
|
||||
}
|
||||
setActiveTab(value);
|
||||
};
|
||||
|
||||
const handleSubmit = form.onSubmit(async (values) => {
|
||||
setIsSubmitting(true);
|
||||
@@ -132,7 +167,7 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
<WidgetIntegrationSelect
|
||||
label={t("item.edit.field.integrations.label")}
|
||||
data={innerProps.integrationData}
|
||||
canSelectMultiple={((definition as { maxIntegrations?: number }).maxIntegrations ?? Infinity) > 1}
|
||||
canSelectMultiple={maxIntegrations > 1}
|
||||
withAsterisk={integrationsRequired}
|
||||
{...form.getInputProps("integrationIds")}
|
||||
/>
|
||||
@@ -165,20 +200,14 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{showAppTab ? (
|
||||
{showResourceTabs ? (
|
||||
<Button
|
||||
variant="subtle"
|
||||
type="button"
|
||||
onClick={() =>
|
||||
openModal({
|
||||
advancedOptions,
|
||||
onSuccess(options) {
|
||||
setAdvancedOptions(options);
|
||||
innerProps.onSuccessfulEdit({
|
||||
...innerProps.value,
|
||||
advancedOptions: options,
|
||||
});
|
||||
},
|
||||
onSuccess: setAdvancedOptions,
|
||||
})
|
||||
}
|
||||
>
|
||||
@@ -194,13 +223,7 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
onClick={() =>
|
||||
openModal({
|
||||
advancedOptions,
|
||||
onSuccess(options) {
|
||||
setAdvancedOptions(options);
|
||||
innerProps.onSuccessfulEdit({
|
||||
...innerProps.value,
|
||||
advancedOptions: options,
|
||||
});
|
||||
},
|
||||
onSuccess: setAdvancedOptions,
|
||||
})
|
||||
}
|
||||
>
|
||||
@@ -215,28 +238,86 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
return (
|
||||
<form onSubmit={onFormSubmit}>
|
||||
<FormProvider form={form}>
|
||||
{showAppTab ? (
|
||||
{showResourceTabs ? (
|
||||
<Stack>
|
||||
<Tabs defaultValue="widget">
|
||||
<Tabs value={activeTab} onChange={handleTabChange}>
|
||||
<Tabs.List grow>
|
||||
<Tabs.Tab value="widget">{t("item.edit.tab.widget")}</Tabs.Tab>
|
||||
<Tabs.Tab value="app">{t("item.edit.tab.app")}</Tabs.Tab>
|
||||
{showAppTab && <Tabs.Tab value="app">{t("item.edit.tab.app")}</Tabs.Tab>}
|
||||
{showIntegrationTab && <Tabs.Tab value="integration">{t("item.edit.tab.integration")}</Tabs.Tab>}
|
||||
</Tabs.List>
|
||||
<Tabs.Panel value="widget" pt="md">
|
||||
{widgetFormContent}
|
||||
</Tabs.Panel>
|
||||
<Tabs.Panel value="app" pt="md">
|
||||
{appId && <EmbeddedAppEditForm appId={appId} handleRef={appEditRef} />}
|
||||
</Tabs.Panel>
|
||||
{showAppTab && (
|
||||
<Tabs.Panel value="app" pt="md">
|
||||
{appId && <EmbeddedAppEditForm appId={appId} handleRef={appEditRef} />}
|
||||
</Tabs.Panel>
|
||||
)}
|
||||
{showIntegrationTab && (
|
||||
<Tabs.Panel value="integration" pt="md">
|
||||
<Stack>
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("item.edit.integration.description")}
|
||||
</Text>
|
||||
{selectedIntegrations.map((integration) => {
|
||||
const canEdit = canModifyAllIntegrations || integration.permissions?.hasFullAccess === true;
|
||||
return (
|
||||
<Group key={integration.id} justify="space-between" wrap="nowrap" gap="sm">
|
||||
<Group gap="sm" wrap="nowrap" style={{ minWidth: 0 }}>
|
||||
<IntegrationAvatar kind={integration.kind} size="sm" />
|
||||
<Stack gap={0} style={{ minWidth: 0 }}>
|
||||
<Text fw={600} size="sm" truncate>
|
||||
{integration.name}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" truncate>
|
||||
{integration.url}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
{canEdit ? (
|
||||
<Button
|
||||
type="button"
|
||||
variant="light"
|
||||
leftSection={<IconPencil size={16} />}
|
||||
onClick={() => innerProps.onEditIntegration?.(integration.id)}
|
||||
aria-label={t("item.edit.integration.editLabel", { name: integration.name })}
|
||||
>
|
||||
{t("item.edit.integration.action")}
|
||||
</Button>
|
||||
) : (
|
||||
<Text size="xs" c="dimmed" ta="end">
|
||||
{t("item.edit.integration.fullAccessRequired")}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
</Tabs.Panel>
|
||||
)}
|
||||
</Tabs>
|
||||
<Group justify="end">
|
||||
<Button onClick={actions.closeModal} variant="subtle" color="gray">
|
||||
{t("common.action.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
{t("common.action.saveChanges")}
|
||||
</Button>
|
||||
</Group>
|
||||
<Box
|
||||
pos="sticky"
|
||||
bottom={0}
|
||||
style={{
|
||||
marginInline: "calc(var(--mantine-spacing-md) * -1)",
|
||||
marginBottom: "calc(var(--mantine-spacing-md) * -1)",
|
||||
paddingInline: "var(--mantine-spacing-md)",
|
||||
paddingBlock: "var(--mantine-spacing-sm)",
|
||||
background: "var(--mantine-color-body)",
|
||||
borderTop: "1px solid var(--mantine-color-default-border)",
|
||||
}}
|
||||
>
|
||||
<Group justify="end">
|
||||
<Button onClick={actions.closeModal} variant="subtle" color="gray">
|
||||
{t("common.action.cancel")}
|
||||
</Button>
|
||||
<Button type="submit" loading={isSubmitting}>
|
||||
{t("common.action.saveChanges")}
|
||||
</Button>
|
||||
</Group>
|
||||
</Box>
|
||||
</Stack>
|
||||
) : (
|
||||
widgetFormContent
|
||||
@@ -250,4 +331,6 @@ export const WidgetEditModal = createModal<WidgetEditModalProps<WidgetKind>>(({
|
||||
return t("item.edit.title");
|
||||
},
|
||||
size: modalSizeForm,
|
||||
presentation: "inspector",
|
||||
closeOnClickOutside: false,
|
||||
});
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
CloseButton,
|
||||
Combobox,
|
||||
Group,
|
||||
Input,
|
||||
Pill,
|
||||
PillsInput,
|
||||
Stack,
|
||||
@@ -38,6 +37,7 @@ export const WidgetIntegrationSelect = ({
|
||||
data,
|
||||
onChange,
|
||||
value: valueProp,
|
||||
label,
|
||||
canSelectMultiple = true,
|
||||
withAsterisk = false,
|
||||
...props
|
||||
@@ -79,6 +79,7 @@ export const WidgetIntegrationSelect = ({
|
||||
option={option}
|
||||
onRemove={() => handleValueRemove(item)}
|
||||
showRemoveButton={canSelectMultiple}
|
||||
removeLabel={t("item.edit.field.integrations.removeLabel", { name: option.name })}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -92,7 +93,7 @@ export const WidgetIntegrationSelect = ({
|
||||
<Avatar src={getIconUrl(item.kind)} size="sm" />
|
||||
<Stack gap={0}>
|
||||
<span>{item.name}</span>
|
||||
<Text size="xs" c="gray.6">
|
||||
<Text size="xs" c="dimmed">
|
||||
{item.url}
|
||||
</Text>
|
||||
</Stack>
|
||||
@@ -109,33 +110,42 @@ export const WidgetIntegrationSelect = ({
|
||||
inputWrapperOrder={["label", "input", "description", "error"]}
|
||||
description={
|
||||
<Text size="xs" span>
|
||||
{t.rich("widget.common.integration.description", {
|
||||
here: () => (
|
||||
<Anchor size="xs" component={Link} target="_blank" href="/manage/integrations">
|
||||
{t("common.here")}
|
||||
</Anchor>
|
||||
),
|
||||
})}
|
||||
<Anchor size="xs" component={Link} target="_blank" href="/manage/integrations">
|
||||
{t("widget.common.integration.manage")}
|
||||
</Anchor>
|
||||
</Text>
|
||||
}
|
||||
pointer
|
||||
onClick={() => combobox.toggleDropdown()}
|
||||
onClick={() => combobox.openDropdown()}
|
||||
label={label}
|
||||
withAsterisk={withAsterisk}
|
||||
{...props}
|
||||
>
|
||||
<Pill.Group>
|
||||
{values.length > 0 ? values : <Input.Placeholder>{t("common.multiSelect.placeholder")}</Input.Placeholder>}
|
||||
{values}
|
||||
|
||||
<Combobox.EventsTarget>
|
||||
<PillsInput.Field
|
||||
type="hidden"
|
||||
readOnly
|
||||
aria-label={label}
|
||||
placeholder={values.length === 0 ? t("common.multiSelect.placeholder") : undefined}
|
||||
onFocus={() => combobox.openDropdown()}
|
||||
onBlur={() => combobox.closeDropdown()}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key !== "Backspace") return;
|
||||
|
||||
event.preventDefault();
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
handleValueRemove(multiSelectValues[multiSelectValues.length - 1]!);
|
||||
if (["ArrowDown", "Enter", " "].includes(event.key)) {
|
||||
event.preventDefault();
|
||||
combobox.openDropdown();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
combobox.closeDropdown();
|
||||
return;
|
||||
}
|
||||
if (event.key === "Backspace" && canSelectMultiple && multiSelectValues.length > 0) {
|
||||
event.preventDefault();
|
||||
const lastValue = multiSelectValues.at(-1);
|
||||
if (lastValue) handleValueRemove(lastValue);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</Combobox.EventsTarget>
|
||||
@@ -163,22 +173,38 @@ export interface IntegrationSelectOption {
|
||||
name: string;
|
||||
url: string;
|
||||
kind: IntegrationKind;
|
||||
permissions?: {
|
||||
hasUseAccess: boolean;
|
||||
hasInteractAccess: boolean;
|
||||
hasFullAccess: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
interface IntegrationPillProps {
|
||||
option: IntegrationSelectOption;
|
||||
onRemove: () => void;
|
||||
showRemoveButton: boolean;
|
||||
removeLabel: string;
|
||||
}
|
||||
|
||||
const IntegrationPill = ({ option, onRemove, showRemoveButton }: IntegrationPillProps) => (
|
||||
const IntegrationPill = ({ option, onRemove, showRemoveButton, removeLabel }: IntegrationPillProps) => (
|
||||
<Group align="center" wrap="nowrap" gap={0} className={classes.pill} mih={24} pr={!showRemoveButton ? 10 : undefined}>
|
||||
<Avatar src={getIconUrl(option.kind)} size={14} mr={6} />
|
||||
<Text span size="xs" lh={1} fw={500}>
|
||||
{option.name}
|
||||
</Text>
|
||||
{showRemoveButton && (
|
||||
<CloseButton onMouseDown={onRemove} variant="transparent" color="gray" size={22} iconSize={14} tabIndex={-1} />
|
||||
<CloseButton
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onRemove();
|
||||
}}
|
||||
aria-label={removeLabel}
|
||||
variant="transparent"
|
||||
color="gray"
|
||||
size={24}
|
||||
iconSize={14}
|
||||
/>
|
||||
)}
|
||||
</Group>
|
||||
);
|
||||
Reference in new issue
Block a user