feat!: release v2 (#6545)

Co-authored-by: Artur <145776561+arturict@users.noreply.github.com>
Co-authored-by: arturict <arturict@users.noreply.github.com>
Co-authored-by: Thomas <thomas@ajnart.fr>
Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com>
Co-authored-by: Danura30082 <danura30082+github@gmail.com>
Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com>
Co-authored-by: ajnart <thomas@ajnart.fr>
Co-authored-by: ajnart <thomas@ajnart.dev>
Co-authored-by: chenjun <chenjun@foxmail.com>
Co-authored-by: Wikibear <wikibear@users.noreply.github.com>
Co-authored-by: Bergasha <bergasha@gmail.com>
Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com>
Co-authored-by: Lucas Araujo <lucas.lra@gmail.com>
Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com>
Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social>
Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com>
Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com>
Co-authored-by: thrawnx <tight.bulb9384@fastmail.com>
Co-authored-by: Chris <58918656+nordada@users.noreply.github.com>
Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com>
Co-authored-by: Yanis <naamaneyanis@gmail.com>
Co-authored-by: Wikibear <me@sej.de>
Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386 -139176

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
import { mkdir } from "node:fs/promises";
import path from "node:path";
import { chromium, expect } from "@playwright/test";
import type { Browser } from "@playwright/test";
import type { StartedTestContainer } from "testcontainers";
import { describe, test } from "vitest";
import * as sqliteSchema from "../packages/db/schema/sqlite";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import { seedAdminUserAsync } from "./shared/seed-admin-user";
const adminCredentials = {
username: "admin",
password: "Comp(exP4sswOrd",
};
// Run this opt-in asset generator with pnpm test:docs-screenshots when the documented UI changes.
describe.skipIf(process.env.UPDATE_DOCS_SCREENSHOTS !== "true")("Assistant documentation screenshots", () => {
test("captures the management page and conversation panel", async () => {
const { db, localMountPath } = await createSqliteDbFileAsync();
await seedAdminUserAsync(db, adminCredentials);
await db.insert(sqliteSchema.assistantConfigurations).values({
id: "default",
enabled: true,
provider: "openrouter",
baseUrl: "https://openrouter.ai/api/v1",
modelDiscoveryPath: null,
encryptedApiKey: "encrypted.key",
modelId: "deepseek/deepseek-v4-flash",
});
const outputDirectory = path.resolve("apps/docs/static/img/assistant");
await mkdir(outputDirectory, { recursive: true });
let homarrContainer: StartedTestContainer | undefined;
let browser: Browser | undefined;
try {
homarrContainer = await createHomarrContainer({
environment: { AUTH_PROVIDERS: "credentials" },
mounts: { "/appdata": localMountPath },
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
browser = await chromium.launch();
const context = await browser.newContext({
colorScheme: "dark",
deviceScaleFactor: 1,
viewport: { width: 1440, height: 1000 },
});
const page = await context.newPage();
await page.goto(`${baseUrl}/auth/login`);
await page.getByLabel("Username").fill(adminCredentials.username);
await page.locator("#password").fill(adminCredentials.password);
await page.getByRole("button", { name: "Login" }).click();
await expect(page).not.toHaveURL(/\/auth\/login/, { timeout: 30_000 });
await page.goto(`${baseUrl}/manage/assistant`);
await expect(page.getByRole("heading", { name: "Assistant" })).toBeVisible();
await expect(page.getByText("Connection ready")).toBeVisible();
await page
.getByRole("main")
.first()
.screenshot({
animations: "disabled",
path: path.join(outputDirectory, "configuration.png"),
});
await page.goto(baseUrl);
await expect(page.getByRole("main").first()).toBeVisible();
await page.locator("body").click({ position: { x: 12, y: 12 } });
await page.keyboard.press("Shift+A");
const assistantDialog = page.getByRole("dialog", { name: "Homarr Assistant" });
await expect(assistantDialog).toBeVisible();
await assistantDialog.screenshot({
animations: "disabled",
path: path.join(outputDirectory, "conversation.png"),
});
await db.update(sqliteSchema.assistantConfigurations).set({
provider: "homarr",
baseUrl: "https://homarr.dev/api/ai/v1",
modelDiscoveryPath: "/models",
encryptedApiKey: null,
modelId: "homarr/model",
});
await page.goto(`${baseUrl}/manage/assistant`);
await expect(page.getByRole("heading", { name: "Assistant" })).toBeVisible();
await expect(page.getByText("Homarr", { exact: true }).first()).toBeVisible();
await expect(page.getByRole("button", { name: "Refresh models" })).toBeVisible({ timeout: 15_000 });
await expect(page.getByText("Homarr model")).toBeVisible();
} finally {
await Promise.allSettled([browser?.close(), homarrContainer?.stop()]);
}
}, 120_000);
});
+72
View File
@@ -0,0 +1,72 @@
import { chromium, expect } from "@playwright/test";
import { describe, test } from "vitest";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import { loginAsync } from "./shared/login";
import { seedAdminUserAsync } from "./shared/seed-admin-user";
import * as sqliteSchema from "../packages/db/schema/sqlite";
const adminCredentials = {
username: "admin",
password: "Comp(exP4sswOrd",
};
describe("Assistant management", () => {
test("keeps provider actions clear and responsive", async () => {
const { db, localMountPath } = await createSqliteDbFileAsync();
await seedAdminUserAsync(db, adminCredentials);
await db.insert(sqliteSchema.assistantConfigurations).values({
id: "default",
enabled: true,
provider: "openrouter",
baseUrl: "https://openrouter.ai/api/v1",
modelDiscoveryPath: null,
encryptedApiKey: "encrypted.key",
modelId: "deepseek/deepseek-v4-flash",
});
const homarrContainer = await createHomarrContainer({
environment: {
AUTH_PROVIDERS: "credentials",
},
mounts: {
"/appdata": localMountPath,
},
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
const browser = await chromium.launch();
const context = await browser.newContext({ viewport: { width: 1440, height: 1000 } });
const page = await context.newPage();
try {
await loginAsync({ page, baseUrl, credentials: adminCredentials, destination: "/manage/assistant" });
await expect(page.getByRole("heading", { name: "Assistant" })).toBeVisible();
await expect(page.getByText("Connection ready")).toBeVisible();
await expect(page.getByText("Encrypted API key saved")).toBeVisible();
await expect(page.getByRole("button", { name: "Remove saved API key" })).toBeVisible();
await page.getByRole("button", { name: "Additional request headers" }).click();
await expect(page.getByRole("button", { name: "Add header" })).toBeVisible();
await page.getByRole("button", { name: "Remove saved API key" }).click();
await expect(page.getByText("Remove the saved API key?")).toBeVisible();
await expect(page.getByRole("button", { name: "Remove API key" })).toBeVisible();
await page.getByRole("button", { name: "Keep saved key" }).click();
await expect(page.getByText("Remove the saved API key?")).toBeHidden();
await page.setViewportSize({ width: 390, height: 844 });
await page.reload();
await expect(page.getByRole("heading", { name: "Assistant" })).toBeVisible();
await expect(page.getByRole("button", { name: "Remove saved API key" })).toBeVisible();
await expect(page.getByRole("button", { name: "Save assistant" })).toBeVisible();
const hasHorizontalOverflow = await page.evaluate(
() => document.documentElement.scrollWidth > document.documentElement.clientWidth,
);
expect(hasHorizontalOverflow).toBe(false);
} finally {
await browser.close();
await homarrContainer.stop();
}
}, 120_000);
});
-86
View File
@@ -1,86 +0,0 @@
import { chromium, expect } from "@playwright/test";
import { describe, test } from "vitest";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import { startMockApiServerAsync } from "./shared/mock-api-server";
import { seedAdminUserAsync } from "./shared/seed-admin-user";
const adminCredentials = {
username: "admin",
password: "Comp(exP4sswOrd",
};
const initialTemplate =
'<Stack gap="xs"><Title order={4}>{data.title}</Title><Badge color="blue">{data.status}</Badge></Stack>';
const updatedTemplate = '<Stack gap="xs"><Text>{data.title}</Text><Badge color="green">{data.value}</Badge></Stack>';
describe("Custom JSX custom widgets", () => {
test("creates, previews, and edits a customJsx widget", async () => {
const mockApi = await startMockApiServerAsync({
title: "E2E Widget",
status: "online",
value: 42,
});
const { db, localMountPath } = await createSqliteDbFileAsync();
await seedAdminUserAsync(db, adminCredentials);
const homarrContainer = await createHomarrContainer({
environment: {
AUTH_PROVIDERS: "credentials",
},
mounts: {
"/appdata": localMountPath,
},
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
try {
await page.goto(`${baseUrl}/auth/login`);
await page.getByLabel("Username").fill(adminCredentials.username);
await page.locator("#password").fill(adminCredentials.password);
const loginNavigation = page.waitForURL((url) => url.origin === baseUrl && url.pathname !== "/auth/login", {
timeout: 60_000,
waitUntil: "commit",
});
await page.locator("css=button[type='submit']").click();
await loginNavigation;
await page.goto(`${baseUrl}/manage/custom-widgets/new`);
await page.waitForURL("**/manage/custom-widgets/new", { timeout: 15_000 });
await page.getByRole("textbox", { name: "Name" }).fill("E2E Custom JSX");
await page.getByRole("textbox", { name: "URL", exact: true }).fill(`${mockApi.url}/status`);
await page.getByRole("combobox", { name: "Display Type" }).click();
await page.getByRole("option", { name: "Custom JSX" }).click();
await page.getByLabel("JSX Template").fill(initialTemplate);
await page.getByRole("button", { name: "Test" }).first().click();
const previewPanel = page.locator(".mantine-Card-root").filter({ hasText: "Preview" });
await expect(previewPanel.getByRole("heading", { name: "E2E Widget" }).first()).toBeVisible({
timeout: 15_000,
});
await page.getByRole("button", { name: "Create" }).first().click();
await expect(page.getByText('Widget "E2E Custom JSX" created successfully.')).toBeVisible({ timeout: 15_000 });
await page.waitForURL("**/manage/custom-widgets/edit/**", { timeout: 15_000 });
await expect(page.getByLabel("JSX Template")).toHaveValue(initialTemplate);
await page.getByLabel("JSX Template").fill(updatedTemplate);
await expect(page.getByLabel("JSX Template")).toHaveValue(updatedTemplate);
await page.getByRole("button", { name: "Save" }).first().click();
await expect(page.getByText('Widget "E2E Custom JSX" updated successfully.')).toBeVisible({ timeout: 15_000 });
await expect(page.getByLabel("JSX Template")).toHaveValue(updatedTemplate);
} finally {
await browser.close();
await homarrContainer.stop();
await mockApi.close();
}
}, 120_000);
});
+7 -2
View File
@@ -4,9 +4,12 @@ import { createHomarrContainer } from "./shared/create-homarr-container";
import { createRedisContainer } from "./shared/redis-container";
describe("Health checks", () => {
test("ready and live should return 200 OK with normal image and no extra configuration", async () => {
test("ready and live should return 200 OK with normal image and no extra configuration", async ({
onTestFinished,
}) => {
// Arrange
const homarrContainer = await createHomarrContainer().start();
onTestFinished(() => homarrContainer.stop());
try {
// Act
@@ -21,9 +24,10 @@ describe("Health checks", () => {
}
}, 60_000);
test("ready and live should return 200 OK with external redis", async () => {
test("ready and live should return 200 OK with external redis", async ({ onTestFinished }) => {
// Arrange
const redisContainer = await createRedisContainer().start();
onTestFinished(() => redisContainer.stop());
const homarrContainer = await createHomarrContainer({
environment: {
REDIS_IS_EXTERNAL: "true",
@@ -32,6 +36,7 @@ describe("Health checks", () => {
REDIS_PASSWORD: redisContainer.getPassword(),
},
}).start();
onTestFinished(() => homarrContainer.stop());
try {
// Act
-20
View File
@@ -1,20 +0,0 @@
import { describe, expect, test } from "vitest";
import { createHomarrContainer } from "./shared/create-homarr-container";
describe("Home", () => {
test("should open with status code 200", async () => {
// Arrange
const homarrContainer = await createHomarrContainer().start();
try {
// Act
const homeResponse = await fetch(`http://localhost:${homarrContainer.getMappedPort(7575)}/`);
// Assert
expect(homeResponse.status).toBe(200);
} finally {
await homarrContainer.stop();
}
}, 60_000);
});
+125 -35
View File
@@ -1,5 +1,6 @@
import { createId } from "@paralleldrive/cuid2";
import { chromium, expect } from "@playwright/test";
import type { Route } from "@playwright/test";
import { eq } from "drizzle-orm";
import { stringify } from "superjson";
import { describe, test } from "vitest";
@@ -7,6 +8,7 @@ import { describe, test } from "vitest";
import * as sqliteSchema from "../packages/db/schema/sqlite";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import { loginAsync } from "./shared/login";
import { seedAdminUserAsync } from "./shared/seed-admin-user";
const adminCredentials = {
@@ -21,7 +23,9 @@ describe("lazy widget application graph", () => {
const boardId = createId();
const layoutId = createId();
const sectionId = createId();
const itemId = createId();
const clockItemId = createId();
const downloadsItemId = createId();
const mockIntegrationId = createId();
await db.insert(sqliteSchema.boards).values({
id: boardId,
@@ -41,26 +45,56 @@ describe("lazy widget application graph", () => {
xOffset: 0,
yOffset: 0,
});
await db.insert(sqliteSchema.items).values({
id: itemId,
boardId,
kind: "clock",
options: stringify({ showSeconds: true }),
await db.insert(sqliteSchema.integrations).values({
id: mockIntegrationId,
name: "Mock downloads",
url: "http://mock.local",
kind: "mock",
});
await db.insert(sqliteSchema.itemLayouts).values({
itemId,
sectionId,
layoutId,
xOffset: 0,
yOffset: 0,
width: 4,
height: 2,
await db.insert(sqliteSchema.items).values([
{
id: clockItemId,
boardId,
kind: "clock",
options: stringify({ showSeconds: true }),
},
{
id: downloadsItemId,
boardId,
kind: "downloads",
options: stringify({}),
},
]);
await db.insert(sqliteSchema.itemLayouts).values([
{
itemId: clockItemId,
sectionId,
layoutId,
xOffset: 0,
yOffset: 0,
width: 4,
height: 2,
},
{
itemId: downloadsItemId,
sectionId,
layoutId,
xOffset: 0,
yOffset: 2,
width: 8,
height: 5,
},
]);
await db.insert(sqliteSchema.integrationItems).values({
itemId: downloadsItemId,
integrationId: mockIntegrationId,
});
await db.update(sqliteSchema.users).set({ homeBoardId: boardId }).where(eq(sqliteSchema.users.id, userId));
const homarrContainer = await createHomarrContainer({
environment: {
AUTH_PROVIDERS: "credentials",
UNSAFE_ENABLE_MOCK_INTEGRATION: "true",
},
mounts: {
"/appdata": localMountPath,
@@ -69,42 +103,98 @@ describe("lazy widget application graph", () => {
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
const browser = await chromium.launch();
const context = await browser.newContext();
const context = await browser.newContext({ serviceWorkers: "block" });
const page = await context.newPage();
const pageErrors: Error[] = [];
const hydrationErrors: string[] = [];
page.on("pageerror", (error) => pageErrors.push(error));
const hydrationErrorPattern = /hydrat|did not match|react\.dev\/errors\/4(18|2[1235])|react error #4(18|2[1235])/i;
page.on("console", (message) => {
if (message.type() === "error" && hydrationErrorPattern.test(message.text())) {
hydrationErrors.push(message.text());
}
});
let releaseRefresh: (() => void) | undefined;
try {
await page.goto(`${baseUrl}/auth/login`);
await page.getByLabel("Username").fill(adminCredentials.username);
await page.locator("#password").fill(adminCredentials.password);
await page.locator("css=button[type='submit']").click();
await loginAsync({ page, baseUrl, credentials: adminCredentials });
await expect(page.locator("[data-homarr-dev-benchmark-board]")).toBeVisible({ timeout: 30_000 });
await expect(page.locator(`[data-id="${itemId}"] .clock-widget-container`)).toBeVisible({ timeout: 15_000 });
const visibleBoard = page.locator("[data-homarr-dev-benchmark-board]").filter({ visible: true }).first();
await expect(visibleBoard).toBeVisible({ timeout: 30_000 });
const clockWidget = page.locator(
`[data-id="${clockItemId}"] .clock-widget-container, [data-grid-item-id="${clockItemId}"] .clock-widget-container`,
);
await expect(clockWidget.filter({ visible: true }).first()).toBeVisible({ timeout: 30_000 });
await expect(clockWidget.locator("time").filter({ visible: true }).first()).not.toHaveText("--:--", {
timeout: 30_000,
});
const downloadsWidget = page
.locator(`[data-id="${downloadsItemId}"], [data-grid-item-id="${downloadsItemId}"]`)
.filter({ visible: true })
.first();
const cachedDownload = downloadsWidget.getByText("Big.Buck.Bunny.2008.1080p.BluRay.x264");
await expect(cachedDownload).toBeVisible({ timeout: 30_000 });
await expect(page.locator("[data-homarr-dev-benchmark-spotlight-preloaded]")).toHaveCount(1, {
timeout: 15_000,
});
await page.keyboard.press("Control+K");
await expect(page.locator("[data-homarr-dev-benchmark-spotlight]")).toBeVisible();
await expect(page.locator("[data-homarr-dev-benchmark-spotlight-feedback]")).toHaveCount(0);
await expect(page.locator("[data-homarr-dev-benchmark-spotlight]")).toBeVisible({ timeout: 15_000 });
await page.keyboard.press("Escape");
await expect(page.locator("[data-homarr-dev-benchmark-spotlight]")).not.toBeVisible();
await expect
.poll(
async () =>
await page.evaluate(async () => {
const registrations = await navigator.serviceWorker.getRegistrations();
return registrations[0]?.scope ?? null;
}),
{ timeout: 15_000 },
)
.toBe(`${baseUrl}/`);
let refreshRequestStarted = false;
const refreshGate = new Promise<void>((resolve) => {
releaseRefresh = resolve;
});
const downloadsRequestPattern = "**/*widget.downloads.getJobsAndStatuses*";
const delayDownloadsRefresh = async (route: Route) => {
refreshRequestStarted = true;
await refreshGate;
await route.continue();
};
await page.route(downloadsRequestPattern, delayDownloadsRefresh);
await page.reload();
await expect(page.locator(`[data-id="${itemId}"] .clock-widget-container`)).toBeVisible({ timeout: 15_000 });
await page.reload({ waitUntil: "domcontentloaded" });
await expect(clockWidget.filter({ visible: true }).first()).toBeVisible({ timeout: 30_000 });
await expect(clockWidget.locator("time").filter({ visible: true }).first()).not.toHaveText("--:--", {
timeout: 30_000,
});
await expect.poll(() => refreshRequestStarted, { timeout: 10_000 }).toBe(true);
await expect(cachedDownload).toBeVisible({ timeout: 5_000 });
const refreshedDownloadsResponse = page.waitForResponse(
(response) => response.url().includes("widget.downloads.getJobsAndStatuses") && response.ok(),
);
releaseRefresh();
releaseRefresh = undefined;
await refreshedDownloadsResponse;
await page.unroute(downloadsRequestPattern, delayDownloadsRefresh);
expect(pageErrors).toEqual([]);
expect(hydrationErrors).toEqual([]);
const serviceWorkerContext = await browser.newContext();
const serviceWorkerPage = await serviceWorkerContext.newPage();
try {
await serviceWorkerPage.goto(`${baseUrl}/auth/login`);
await expect
.poll(
async () =>
await serviceWorkerPage.evaluate(async () => {
const registrations = await navigator.serviceWorker.getRegistrations();
return registrations[0]?.scope ?? null;
}),
{ timeout: 15_000 },
)
.toBe(`${baseUrl}/`);
} finally {
await serviceWorkerContext.close();
}
} finally {
releaseRefresh?.();
await browser.close();
await homarrContainer.stop();
}
}, 120_000);
}, 180_000);
});
+148
View File
@@ -0,0 +1,148 @@
import { mkdir } from "node:fs/promises";
import path from "node:path";
import { chromium } from "@playwright/test";
import type { Page } from "@playwright/test";
import { stringify as stringifySuperJSON } from "superjson";
import { describe, expect, test } from "vitest";
import * as sqliteSchema from "../packages/db/schema/sqlite";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import { loginAsync } from "./shared/login";
import { seedAdminUserAsync } from "./shared/seed-admin-user";
const credentials = { username: "admin", password: "Comp(exP4sswOrd" };
const captureScreenshotAsync = async (page: Page, name: string) => {
const directory = process.env.HOMARR_E2E_SCREENSHOT_DIR?.trim();
if (!directory) return;
await mkdir(directory, { recursive: true });
await page.screenshot({ path: path.join(directory, `manage-${name}.png`), fullPage: true });
};
describe("Management collections", () => {
test("renders unified collections and a compact board preview on desktop and mobile", async () => {
const { db, localMountPath } = await createSqliteDbFileAsync();
const { userId } = await seedAdminUserAsync(db, credentials);
const boardId = "manage-board";
const layoutId = "manage-layout";
const sectionId = "manage-section";
const appId = "manage-app";
await db.insert(sqliteSchema.apps).values({
id: appId,
name: "Very long service name used to verify responsive management rows",
description: "A useful service with enough detail to exercise the shared collection description slot.",
iconUrl: "/favicon.ico",
href: "https://service.example.internal/a/very/long/reverse/proxy/path/that/must/not/overflow",
pingUrl: "https://service.example.internal/health",
});
await db.insert(sqliteSchema.integrations).values({
id: "manage-integration",
name: "Living room Sonarr",
url: "https://sonarr.example.internal/a/long/reverse/proxy/path",
kind: "sonarr",
appId,
});
await db.insert(sqliteSchema.searchEngines).values({
id: "manage-search-engine",
iconUrl: "/favicon.ico",
name: "Internal documentation",
short: "docs",
description: "Search private documentation from Spotlight.",
urlTemplate: "https://docs.example.internal/search?q=%s",
type: "generic",
});
await db.insert(sqliteSchema.boards).values({
id: boardId,
name: "management-preview",
creatorId: userId,
isPublic: false,
});
await db.insert(sqliteSchema.layouts).values({
id: layoutId,
name: "Base",
boardId,
columnCount: 10,
breakpoint: 768,
role: "base",
});
await db.insert(sqliteSchema.sections).values({
id: sectionId,
boardId,
kind: "empty",
xOffset: 0,
yOffset: 0,
});
await db.insert(sqliteSchema.items).values([
{
id: "manage-clock",
boardId,
kind: "clock",
options: stringifySuperJSON({ is24HourFormat: true }),
},
{
id: "manage-app-item",
boardId,
kind: "app",
options: stringifySuperJSON({ appId, openInNewTab: true, showTitle: true }),
},
]);
await db.insert(sqliteSchema.itemLayouts).values([
{ itemId: "manage-clock", sectionId, layoutId, xOffset: 0, yOffset: 0, width: 2, height: 2 },
{ itemId: "manage-app-item", sectionId, layoutId, xOffset: 2, yOffset: 0, width: 1, height: 1 },
]);
const homarrContainer = await createHomarrContainer({
environment: { AUTH_PROVIDERS: "credentials" },
mounts: { "/appdata": localMountPath },
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
const browser = await chromium.launch();
const context = await browser.newContext({ viewport: { width: 1280, height: 900 }, reducedMotion: "reduce" });
const page = await context.newPage();
try {
await loginAsync({ page, baseUrl, credentials, destination: "/manage/apps" });
await page.getByRole("heading", { name: "Apps", exact: true }).waitFor();
expect(await page.getByRole("list", { name: "Configured apps" }).getByRole("listitem").count()).toBe(1);
const editApp = page.getByRole("link", { name: /Edit Very long service name/ });
await editApp.focus();
expect(await editApp.evaluate((element) => element === document.activeElement)).toBe(true);
expect((await editApp.boundingBox())?.height).toBeGreaterThanOrEqual(44);
await page.goto(`${baseUrl}/manage/integrations`);
await page.getByRole("heading", { name: "Integrations", exact: true }).waitFor();
expect(await page.getByRole("list", { name: "Configured integrations" }).getByRole("listitem").count()).toBe(1);
expect(
await page
.getByRole("list", { name: "Configured integrations" })
.getByRole("listitem")
.getByText("Sonarr", { exact: true })
.isVisible(),
).toBe(true);
await page.goto(`${baseUrl}/manage/search-engines`);
await page.getByRole("heading", { name: "Search engines", exact: true }).waitFor();
expect(await page.getByRole("list", { name: "Configured search engines" }).getByRole("listitem").count()).toBe(1);
await page.goto(`${baseUrl}/manage/boards`);
await page.getByRole("heading", { name: "Your boards", exact: true }).waitFor();
const preview = page.getByRole("img", { name: "Layout preview for management-preview, with 2 items" });
await preview.waitFor();
expect(await preview.locator('[data-lane="main"]').count()).toBe(1);
await captureScreenshotAsync(page, "desktop-boards");
await page.setViewportSize({ width: 375, height: 812 });
for (const route of ["apps", "integrations", "search-engines", "boards"]) {
await page.goto(`${baseUrl}/manage/${route}`);
await page.locator("h1:visible").last().waitFor();
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true);
}
await captureScreenshotAsync(page, "mobile-boards");
} finally {
await Promise.all([browser.close(), homarrContainer.stop()]);
}
}, 90_000);
});
+178
View File
@@ -0,0 +1,178 @@
import path from "node:path";
import type { Browser } from "@playwright/test";
import { chromium, expect } from "@playwright/test";
import { createId } from "@paralleldrive/cuid2";
import { eq } from "drizzle-orm";
import { stringify } from "superjson";
import { afterAll, beforeAll, describe, test } from "vitest";
import {
boards,
integrationItems,
integrations,
itemLayouts,
items,
layouts,
sections,
users,
} from "../packages/db/schema/sqlite";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import { loginAsync } from "./shared/login";
import { seedAdminUserAsync } from "./shared/seed-admin-user";
const credentials = { username: "owner", password: "Comp(exP4sswOrd" };
const boardName = "media-server-layout-e2e";
describe("Media server widget layout", () => {
let browser: Browser;
let baseUrl: string;
let stopContainerAsync: (() => Promise<void>) | undefined;
beforeAll(async () => {
const { db, localMountPath } = await createSqliteDbFileAsync();
const { userId } = await seedAdminUserAsync(db, credentials);
const boardId = createId();
const layoutId = createId();
const sectionId = createId();
const mediaItemId = createId();
const clockItemId = createId();
const integrationId = createId();
await db.insert(boards).values({ id: boardId, name: boardName, creatorId: userId, isPublic: false });
await db.insert(layouts).values({ id: layoutId, name: "Base", columnCount: 12, breakpoint: 0, boardId });
await db.insert(sections).values({ id: sectionId, kind: "empty", xOffset: 0, yOffset: 0, boardId });
await db.insert(integrations).values({
id: integrationId,
name: "Demo Integration",
url: "https://demo.homarr.dev",
kind: "mock",
appId: null,
});
await db.insert(items).values([
{
id: mediaItemId,
kind: "mediaServer",
boardId,
options: stringify({ showOnlyPlaying: true, showBitrate: true, showLocation: true }),
advancedOptions: stringify({ title: null, customCssClasses: [], borderColor: "" }),
},
{
id: clockItemId,
kind: "clock",
boardId,
options: stringify({ is24HourFormat: true, showSeconds: false, showDate: true }),
advancedOptions: stringify({ title: null, customCssClasses: [], borderColor: "" }),
},
]);
await db.insert(integrationItems).values({ itemId: mediaItemId, integrationId });
await db.insert(itemLayouts).values([
{ itemId: mediaItemId, sectionId, layoutId, xOffset: 0, yOffset: 0, width: 8, height: 2 },
{ itemId: clockItemId, sectionId, layoutId, xOffset: 0, yOffset: 2, width: 8, height: 2 },
]);
await db
.update(users)
.set({ homeBoardId: boardId, completedBoardTour: true, completedManageTour: true })
.where(eq(users.id, userId));
const container = await createHomarrContainer({
environment: { AUTH_PROVIDERS: "credentials" },
mounts: { "/appdata": localMountPath },
}).start();
stopContainerAsync = async () => {
await container.stop();
};
baseUrl = `http://${container.getHost()}:${container.getMappedPort(7575)}`;
browser = await chromium.launch();
}, 120_000);
afterAll(async () => {
await browser?.close();
await stopContainerAsync?.();
});
test("clips overflowing sessions to the grid cell", async () => {
const context = await browser.newContext({ reducedMotion: "reduce", viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
try {
await loginAsync({ page, baseUrl, credentials, destination: `/boards/${boardName}` });
const entry = page.locator("[data-grid-item-id][data-kind='mediaServer']").first();
const streamViewport = entry.locator("[data-media-server-streams]");
await expect(streamViewport.getByText("Interstellar")).toBeVisible({ timeout: 15_000 });
const geometry = await entry.evaluate((element) => {
const card = element.querySelector<HTMLElement>("[data-grid-item-content]");
const viewport = element.querySelector<HTMLElement>("[data-media-server-streams]");
if (!card || !viewport) throw new Error("Media stream viewport did not render");
const entryBounds = element.getBoundingClientRect();
const cardBounds = card.getBoundingClientRect();
const viewportBounds = viewport.getBoundingClientRect();
const elementBelow = document.elementFromPoint(entryBounds.left + 8, entryBounds.bottom + 8);
return {
entryBottom: entryBounds.bottom,
cardBottom: cardBounds.bottom,
viewportBottom: viewportBounds.bottom,
viewportClientHeight: viewport.clientHeight,
viewportScrollHeight: viewport.scrollHeight,
leaksBelow: Boolean(elementBelow?.closest("[data-media-server-streams]")),
};
});
expect(geometry.cardBottom).toBeLessThanOrEqual(geometry.entryBottom + 1);
expect(geometry.viewportBottom).toBeLessThanOrEqual(geometry.entryBottom + 1);
expect(geometry.viewportScrollHeight).toBeGreaterThan(geometry.viewportClientHeight);
expect(geometry.leaksBelow).toBe(false);
const screenshotDirectory = process.env.HOMARR_E2E_SCREENSHOT_DIR?.trim();
if (screenshotDirectory) {
await page.screenshot({ path: path.join(screenshotDirectory, "media-server-layout.png"), fullPage: true });
}
const advancedTrigger = entry.getByRole("button", { name: "Open advanced view" });
await advancedTrigger.focus();
await page.keyboard.press("Shift+Enter");
const advancedDialog = page.getByRole("dialog", { name: "Current media server streams advanced view" });
await expect(advancedDialog).toBeVisible();
await expect(advancedDialog.getByRole("textbox", { name: "Search for anything" })).toBeVisible();
const advancedGeometry = await advancedDialog.evaluate((element) => {
const viewport = element.querySelector<HTMLElement>("[data-media-server-streams]");
if (!viewport) throw new Error("Advanced media stream viewport did not render");
const dialogBounds = element.getBoundingClientRect();
const viewportBounds = viewport.getBoundingClientRect();
return {
dialog: {
top: dialogBounds.top,
right: dialogBounds.right,
bottom: dialogBounds.bottom,
left: dialogBounds.left,
},
viewport: {
top: viewportBounds.top,
right: viewportBounds.right,
bottom: viewportBounds.bottom,
left: viewportBounds.left,
},
};
});
expect(advancedGeometry.viewport.top).toBeGreaterThanOrEqual(advancedGeometry.dialog.top - 1);
expect(advancedGeometry.viewport.right).toBeLessThanOrEqual(advancedGeometry.dialog.right + 1);
expect(advancedGeometry.viewport.bottom).toBeLessThanOrEqual(advancedGeometry.dialog.bottom + 1);
expect(advancedGeometry.viewport.left).toBeGreaterThanOrEqual(advancedGeometry.dialog.left - 1);
if (screenshotDirectory) {
await page.screenshot({
path: path.join(screenshotDirectory, "media-server-advanced-layout.png"),
fullPage: true,
});
}
} finally {
await context.close();
}
}, 60_000);
});
+161
View File
@@ -0,0 +1,161 @@
import { execFile } from "node:child_process";
import { mkdir, mkdtemp, readdir, rm } from "node:fs/promises";
import { promisify } from "node:util";
import path from "node:path";
import { chromium, expect as expectBrowser } from "@playwright/test";
import Database from "better-sqlite3";
import { expect, test } from "vitest";
import { decryptSecretWithKey } from "../packages/common/src/encryption";
import { convert } from "../tools/mysql-to-sqlite/src/convert.mjs";
import {
createFixture,
fixtureBoard,
fixtureCiphertext,
fixtureMedia,
fixturePassword,
fixtureSecret,
fixtureUser,
} from "../tools/mysql-to-sqlite/test/fixture.mjs";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { loginAsync } from "./shared/login";
// This deliberately starts from the supported MySQL release, not a freshly seeded v2 database.
test("converted MySQL data boots, authenticates and survives a v2 restart", async () => {
const root = path.join(__dirname, "tmp");
await mkdir(root, { recursive: true });
const appdata = await mkdtemp(path.join(root, "mysql-conversion-"));
const output = path.join(appdata, "db", "db.sqlite");
await mkdir(path.dirname(output));
const fixture = await createFixture();
try {
await convert({ connectionOptions: fixture.connectionOptions, output, homarrStopped: true });
const browser = await chromium.launch();
try {
for (let boot = 0; boot < 2; boot++) {
const container = await createHomarrContainer({ mounts: { "/appdata": appdata } }).start();
const context = await browser.newContext();
try {
const baseUrl = `http://${container.getHost()}:${container.getMappedPort(7575)}`;
const page = await context.newPage();
await loginAsync({
page,
baseUrl,
credentials: { username: fixtureUser, password: fixturePassword },
destination: "/boards/converted-board",
});
await page.locator('[data-testid="board-canvas"][data-board-hydrated="true"]').waitFor({ timeout: 30_000 });
expect(page.url()).toContain("/boards/converted-board");
const clock = page
.locator(
'[data-id="migration-item"] .clock-widget-container, [data-grid-item-id="migration-item"] .clock-widget-container',
)
.filter({ visible: true })
.first();
await expectBrowser(clock).toBeVisible({ timeout: 30_000 });
await expectBrowser(clock.locator("time").filter({ visible: true }).first()).not.toHaveText("--:--", {
timeout: 30_000,
});
const media = await context.request.get(`${baseUrl}/api/user-medias/migration-media`);
expect(media.status()).toBe(200);
expect(media.headers()["content-type"]).toContain("application/octet-stream");
expect(await media.body()).toEqual(fixtureMedia);
} finally {
await context.close();
await container.stop();
}
// Inspect after shutdown so WAL data is settled; the second boot proves persisted state.
const db = new Database(output, { readonly: true });
try {
expect(db.pragma("integrity_check", { simple: true })).toBe("ok");
expect(db.pragma("foreign_key_check")).toEqual([]);
expect(db.prepare("SELECT id, name FROM board WHERE id = ?").get(fixtureBoard)).toEqual({
id: fixtureBoard,
name: "converted-board",
});
const secret = db
.prepare('SELECT value FROM "integrationSecret" WHERE integration_id = ? AND kind = ?')
.get("migration-integration", "apiKey") as { value: `${string}.${string}` };
expect(secret.value).toBe(fixtureCiphertext);
expect(decryptSecretWithKey(secret.value, Buffer.alloc(32))).toBe(fixtureSecret);
expect(
db
.prepare(
"SELECT section_id, x_offset, y_offset, width, height FROM item_layout WHERE item_id = ? AND layout_id = ?",
)
.get("migration-item", "migration-layout"),
).toEqual({ section_id: "migration-section", x_offset: 0, y_offset: 0, width: 3, height: 2 });
expect(
db
.prepare(
"SELECT id, name, url, enabled, auth_type, method, display_type, display_config FROM custom_widget_definition WHERE id = ?",
)
.get("migration-custom"),
).toEqual({
id: "migration-custom",
name: "Legacy weather",
url: "https://example.test/weather",
enabled: 0,
auth_type: "bearer",
method: "GET",
display_type: "singleValue",
display_config: '{"type":"singleValue","jsonPath":"$.temperature"}',
});
expect(
db
.prepare("SELECT value FROM custom_widget_secret WHERE definition_id = ? AND kind = ?")
.get("migration-custom", "apiKey"),
).toEqual({ value: fixtureCiphertext });
} finally {
db.close();
}
}
} finally {
await browser.close();
}
} finally {
await fixture.cleanup();
await rm(appdata, { recursive: true, force: true });
}
}, 180_000);
test("retired MySQL settings fail before creating application data", async () => {
const root = path.join(__dirname, "tmp");
await mkdir(root, { recursive: true });
const image = process.env.HOMARR_E2E_IMAGE?.trim() || "homarr-e2e";
for (const setting of ["DB_DRIVER=mysql2", "DB_DIALECT=mysql", "DB_URL=mysql://unused.invalid/homarr"]) {
const appdata = await mkdtemp(path.join(root, "mysql-rejection-"));
const containerName = path.basename(appdata);
try {
await expect(
promisify(execFile)(
"docker",
[
"run",
"--rm",
"--name",
containerName,
"--network",
"none",
"--mount",
`type=bind,source=${appdata},target=/appdata`,
"-e",
setting,
image,
],
{ timeout: 15_000 },
),
).rejects.toMatchObject({
code: 1,
stdout: expect.stringContaining("MySQL is no longer supported in v2. Use the MySQL-to-SQLite converter"),
});
expect(await readdir(appdata)).toEqual([]);
} finally {
await promisify(execFile)("docker", ["rm", "--force", containerName]).catch(() => undefined);
await rm(appdata, { recursive: true, force: true });
}
}
}, 60_000);
+282 -10
View File
@@ -1,15 +1,179 @@
import { chromium } from "@playwright/test";
import { describe, test } from "vitest";
import { mkdir, rm } from "node:fs/promises";
import path from "node:path";
import { chromium } from "@playwright/test";
import type { Page } from "@playwright/test";
import { createId } from "@paralleldrive/cuid2";
import { describe, expect, test } from "vitest";
import * as sqliteSchema from "../packages/db/schema/sqlite";
import { OnboardingActions } from "./shared/actions/onboarding-actions";
import { OnboardingAssertions } from "./shared/assertions/onboarding-assertions";
import { createHomarrContainer } from "./shared/create-homarr-container";
import { createSqliteDbFileAsync } from "./shared/e2e-db";
import { loginAsync } from "./shared/login";
import { seedAdminUserAsync } from "./shared/seed-admin-user";
const captureScreenshotAsync = async (page: Page, name: string) => {
const directory = process.env.HOMARR_E2E_SCREENSHOT_DIR?.trim();
if (!directory) return;
await mkdir(directory, { recursive: true });
await page.screenshot({ path: path.join(directory, `onboarding-${name}.png`), fullPage: true });
};
type SqliteTestDatabase = Awaited<ReturnType<typeof createSqliteDbFileAsync>>;
const cleanupSqliteDbAsync = async ({ db, localMountPath }: SqliteTestDatabase) => {
if (db.$client.open) db.$client.close();
await rm(localMountPath, { recursive: true, force: true });
};
describe("Onboarding", () => {
test("External provider onboarding setup should be successful", async () => {
test.each([
{ name: "mobile", width: 320, height: 740 },
{ name: "tablet", width: 768, height: 1024 },
{ name: "desktop", width: 1440, height: 900 },
])(
"Onboarding is usable at the $name viewport",
async ({ name, width, height }) => {
const sqlite = await createSqliteDbFileAsync();
const { localMountPath } = sqlite;
const homarrContainer = await createHomarrContainer({ mounts: { "/appdata": localMountPath } }).start();
const browser = await chromium.launch();
const context = await browser.newContext({ viewport: { width, height }, reducedMotion: "reduce" });
const page = await context.newPage();
try {
await page.goto(`http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}/init`);
await page.getByRole("heading", { name: "Welcome home." }).waitFor();
const start = page.getByRole("button", { name: "Get started" });
await start.focus();
await start.press("Enter");
await page.getByRole("heading", { name: "Create your administrator" }).waitFor();
await page.getByLabel("Administrator username").fill("admin");
await page.getByLabel("Password", { exact: true }).fill("Comp(exP4sswOrd");
await page.getByLabel("Confirm password").fill("Comp(exP4sswOrd");
await page.locator("css=button[type='submit']").click();
await page.getByRole("heading", { name: "Start with familiar defaults" }).waitFor({ timeout: 30_000 });
const serverOrigin = page.getByRole("textbox", { name: "Usual server address" });
await serverOrigin.fill("https://home.example/homarr");
await page.getByLabel("Default language").click();
await page.getByRole("option", { name: /Français/ }).click();
expect(await serverOrigin.inputValue()).toBe("https://home.example/homarr");
expect(await page.getByRole("heading", { name: "Start with familiar defaults" }).isVisible()).toBe(true);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true);
await captureScreenshotAsync(page, `${name}-studio`);
const activeSection = page.locator('[aria-current="step"]');
await activeSection.focus();
await activeSection.press("ArrowLeft");
await page.getByRole("heading", { name: "One board, built around your services" }).waitFor();
expect(await activeSection.evaluate((element) => element === document.activeElement)).toBe(true);
await activeSection.press("ArrowRight");
await page.getByRole("heading", { name: "Start with familiar defaults" }).waitFor();
expect(await activeSection.evaluate((element) => element === document.activeElement)).toBe(true);
await activeSection.press("End");
await page.getByRole("heading", { name: "One board, built around your services" }).waitFor();
await activeSection.press("Home");
await page.getByRole("heading", { name: "Start with familiar defaults" }).waitFor();
expect(await activeSection.evaluate((element) => element === document.activeElement)).toBe(true);
const sections = [
["Discover", "See what this installation can actually reach"],
["Connect", "Connect what makes the board useful"],
["Board", "Shape the board before it is built"],
["Extend", "Advanced features"],
] as const;
for (const [section, heading] of sections) {
await page.getByRole("button", { name: new RegExp(`^${section}`) }).click();
await page.getByRole("heading", { name: heading }).waitFor();
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true);
}
await page.getByRole("button", { name: /^Board/ }).click();
const boardPreview = page.locator('figure[aria-label="Live preview of the first board layout"]');
expect(await boardPreview.getAttribute("data-layout-role")).toBe("base");
expect(await boardPreview.getAttribute("data-layout-columns")).toBe("10");
const columnSlider = page.getByRole("slider", { name: "Board columns" });
await columnSlider.press("ArrowRight");
await columnSlider.press("ArrowRight");
expect(await boardPreview.getAttribute("data-layout-columns")).toBe("12");
await page.getByRole("button", { name: /^Connect/ }).click();
const sonarr = page.locator('button[aria-label="Sonarr"]');
await sonarr.click();
await page.getByLabel("Service URL").waitFor();
await captureScreenshotAsync(page, `${name}-integration-details`);
await sonarr.click();
await page.getByLabel("Service URL").waitFor({ state: "detached" });
await activeSection.focus();
await activeSection.press("End");
await page.getByRole("heading", { name: "One board, built around your services" }).waitFor();
await captureScreenshotAsync(page, `${name}-review`);
await page.getByRole("button", { name: "Build my board" }).click();
await page.getByRole("heading", { name: "Your first board is ready." }).waitFor({ timeout: 30_000 });
await captureScreenshotAsync(page, `${name}-finish`);
await page.getByRole("link", { name: "Open my board" }).click();
await page.waitForURL(/\/boards\/dashboard(?:[/?#]|$)/);
const boardCanvas = page.locator('[data-testid="board-canvas"][data-board-hydrated="true"]');
await boardCanvas.waitFor({ timeout: 30_000 });
expect(await boardCanvas.locator("[data-grid-item-id]").count()).toBeGreaterThanOrEqual(3);
expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBe(true);
} finally {
try {
await Promise.all([browser.close(), homarrContainer.stop()]);
} finally {
await cleanupSqliteDbAsync(sqlite);
}
}
},
90_000,
);
test("Credentials onboarding recovers when automatic sign-in fails after account creation", async () => {
const sqlite = await createSqliteDbFileAsync();
const { db, localMountPath } = sqlite;
const homarrContainer = await createHomarrContainer({ mounts: { "/appdata": localMountPath } }).start();
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
try {
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
await page.goto(`${baseUrl}/init`);
await page.getByRole("button", { name: "Get started" }).click();
await page.getByRole("heading", { name: "Create your administrator" }).waitFor();
await page.route(/\/api\/auth\/callback\/credentials(?:\?.*)?$/, (route) => route.abort("failed"));
await page.getByLabel("Administrator username").fill("admin");
await page.getByLabel("Password", { exact: true }).fill("Comp(exP4sswOrd");
await page.getByLabel("Confirm password").fill("Comp(exP4sswOrd");
await page.locator("button[type='submit']").click();
await page.getByRole("heading", { name: "Administrator account created" }).waitFor();
const recovery = page.getByRole("link", { name: "Sign in and continue" });
expect(await recovery.getAttribute("href")).toBe("/auth/login?callbackUrl=/init");
expect(await recovery.evaluate((element) => element === document.activeElement)).toBe(true);
expect((await db.query.users.findMany()).length).toBe(1);
expect((await db.query.onboarding.findFirst())?.step).toBe("setup");
} finally {
try {
await Promise.all([browser.close(), homarrContainer.stop()]);
} finally {
await cleanupSqliteDbAsync(sqlite);
}
}
}, 60_000);
test("External provider onboarding requires sign-in before privileged setup", async () => {
// Arrange
const { db, localMountPath } = await createSqliteDbFileAsync();
const sqlite = await createSqliteDbFileAsync();
const { db, localMountPath } = sqlite;
const homarrContainer = await createHomarrContainer({
environment: {
AUTH_PROVIDERS: "ldap",
@@ -33,19 +197,127 @@ describe("Onboarding", () => {
try {
// Act
await page.goto(`http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`);
await actions.startOnboardingAsync("scratch");
await actions.startOnboardingAsync();
await actions.processExternalGroupStepAsync({
name: externalGroupName,
});
await actions.processSettingsStepAsync();
await actions.processIntegrationsStepAsync();
// Assert
await assertions.assertFinishStepVisibleAsync();
await page.getByRole("heading", { name: "Administrator sign-in required" }).waitFor();
expect(await page.getByRole("link", { name: "Sign in" }).getAttribute("href")).toBe(
"/auth/login?callbackUrl=%2Finit",
);
await assertions.assertExternalGroupInsertedAsync(externalGroupName);
await assertions.assertDbOnboardingStepAsync("finish");
await assertions.assertDbOnboardingStepAsync("setup");
} finally {
await Promise.all([browser.close(), homarrContainer.stop()]);
try {
await Promise.all([browser.close(), homarrContainer.stop()]);
} finally {
await cleanupSqliteDbAsync(sqlite);
}
}
}, 60_000);
test("Legacy setup requires sign-in without exposing private board metadata", async () => {
const credentials = { username: "admin", password: "Comp(exP4sswOrd" };
const sqlite = await createSqliteDbFileAsync();
const { db, localMountPath } = sqlite;
await seedAdminUserAsync(db, credentials);
await db.update(sqliteSchema.onboarding).set({ step: "import" as never });
const privateBoardName = "private-board-must-not-leak";
await db.insert(sqliteSchema.boards).values({ id: createId(), name: privateBoardName, isPublic: false });
const privateWorkshopApiUrl = "http://internal-workshop-api.invalid";
const privateWorkshopWebUrl = "http://internal-workshop-web.invalid";
const homarrContainer = await createHomarrContainer({
environment: {
WORKSHOP_API_URL: privateWorkshopApiUrl,
WORKSHOP_WEB_URL: privateWorkshopWebUrl,
},
mounts: { "/appdata": localMountPath },
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
const browser = await chromium.launch();
const context = await browser.newContext();
const page = await context.newPage();
try {
const response = await context.request.get(`${baseUrl}/init`);
expect(response.ok()).toBe(true);
expect(response.url()).toBe(`${baseUrl}/init`);
const responseBody = await response.text();
expect(responseBody).not.toContain(privateBoardName);
expect(responseBody).not.toContain(privateWorkshopApiUrl);
expect(responseBody).not.toContain(privateWorkshopWebUrl);
await page.goto(`${baseUrl}/init`);
await page.getByRole("heading", { name: "Administrator sign-in required" }).waitFor();
expect(await page.getByRole("link", { name: "Sign in and resume" }).getAttribute("href")).toBe(
"/auth/login?callbackUrl=%2Finit",
);
await loginAsync({ page, baseUrl, credentials, destination: "/init" });
await page.getByRole("heading", { name: "Welcome home." }).waitFor();
await page.getByRole("button", { name: "Get started" }).click();
await page.getByRole("heading", { name: "Start with familiar defaults" }).waitFor();
expect(await page.getByRole("heading", { name: "Create your administrator" }).count()).toBe(0);
} finally {
try {
await Promise.all([browser.close(), homarrContainer.stop()]);
} finally {
await cleanupSqliteDbAsync(sqlite);
}
}
}, 90_000);
test("Assistant setup restores saved configuration and accepts a manual model", async () => {
const credentials = { username: "admin", password: "Comp(exP4sswOrd" };
const sqlite = await createSqliteDbFileAsync();
const { db, localMountPath } = sqlite;
await seedAdminUserAsync(db, credentials);
await db.update(sqliteSchema.onboarding).set({ step: "setup", previousStep: "group" });
await db.insert(sqliteSchema.assistantConfigurations).values({
id: "default",
enabled: true,
provider: "custom",
baseUrl: "http://assistant.local/v1",
modelDiscoveryPath: null,
modelId: "local-model",
});
const configuredWorkshopApiUrl = "http://authenticated-workshop-api.invalid";
const homarrContainer = await createHomarrContainer({
environment: { WORKSHOP_API_URL: configuredWorkshopApiUrl },
mounts: { "/appdata": localMountPath },
}).start();
const baseUrl = `http://${homarrContainer.getHost()}:${homarrContainer.getMappedPort(7575)}`;
const browser = await chromium.launch();
const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });
const page = await context.newPage();
try {
await loginAsync({ page, baseUrl, credentials, destination: "/init" });
expect(await page.locator('meta[name="homarr-workshop-api-url"]').getAttribute("content")).toBe(
configuredWorkshopApiUrl,
);
await page.getByRole("button", { name: "Extend (5/6)" }).click();
await page.getByRole("heading", { name: "Advanced features" }).waitFor();
await page.getByRole("tab", { name: "Assistant" }).click();
await page.getByLabel("API base URL").waitFor();
const provider = page.getByRole("combobox", { name: "Provider", exact: true });
await expect.poll(() => provider.inputValue(), { timeout: 10_000 }).toBe("Custom endpoint");
expect(await page.getByLabel("API base URL").inputValue()).toBe("http://assistant.local/v1");
expect(await page.locator('input[value="local-model"]').inputValue()).toBe("local-model");
expect(await page.getByText("Discovery is unavailable. You can still enter a model ID manually.").count()).toBe(
1,
);
} finally {
try {
await Promise.all([browser.close(), homarrContainer.stop()]);
} finally {
await cleanupSqliteDbAsync(sqlite);
}
}
}, 90_000);
});
+9 -10
View File
@@ -27,14 +27,14 @@ export class OnboardingActions {
}
}
public async startOnboardingAsync(type: "scratch" | "before 1.0") {
await this.page.locator("button", { hasText: type }).click();
public async startOnboardingAsync() {
await this.page.getByRole("button", { name: "Get started" }).click();
}
public async processUserStepAsync(input: { username: string; password: string; confirmPassword: string }) {
await this.page.waitForSelector("text=administrator user");
await this.page.getByRole("heading", { name: "Create your administrator" }).waitFor();
await this.page.getByLabel("Username").fill(input.username);
await this.page.getByLabel("Administrator username").fill(input.username);
await this.page.getByLabel("Password", { exact: true }).fill(input.password);
await this.page.getByLabel("Confirm password").fill(input.confirmPassword);
@@ -42,18 +42,17 @@ export class OnboardingActions {
}
public async processExternalGroupStepAsync(input: { name: string }) {
await this.page.waitForSelector("text=external provider");
await this.page.locator("input").fill(input.name);
await this.page.getByRole("heading", { name: "Connect your administrator group" }).waitFor();
await this.page.getByLabel("External administrator group").fill(input.name);
await this.page.locator("css=button[type='submit']").click();
}
public async processSettingsStepAsync() {
await this.page.waitForSelector("text=Analytics");
await this.page.locator("css=button[type='submit']").click();
await this.page.getByRole("heading", { name: "Start with familiar defaults" }).waitFor();
}
public async processIntegrationsStepAsync() {
await this.page.waitForSelector("text=integrations you'd like to connect");
await this.page.locator("button", { hasText: "Skip for now" }).click();
await this.page.getByRole("button", { name: "Review (6/6)" }).click();
await this.page.getByRole("button", { name: "Build my board" }).click();
}
}
@@ -57,6 +57,6 @@ export class OnboardingAssertions {
}
public async assertFinishStepVisibleAsync() {
await this.page.waitForSelector("text=completed the setup", { timeout: 30_000 });
await this.page.getByRole("heading", { name: "Your first board is ready." }).waitFor({ timeout: 30_000 });
}
}
+6 -4
View File
@@ -1,5 +1,5 @@
import { GenericContainer, Wait } from "testcontainers";
import { Environment } from "testcontainers/build/types";
import type { Environment } from "testcontainers/build/types";
export const createHomarrContainer = (
options: {
@@ -10,11 +10,13 @@ export const createHomarrContainer = (
};
} = {},
) => {
if (!process.env.CI) {
throw new Error("This test should only be run in CI or with a homarr image named 'homarr-e2e'");
const configuredImage = process.env.HOMARR_E2E_IMAGE?.trim();
const image = configuredImage || "homarr-e2e";
if (!process.env.CI && !configuredImage) {
throw new Error(`This test should only be run in CI or with a local Homarr image (configured: '${image}')`);
}
const container = new GenericContainer("homarr-e2e")
const container = new GenericContainer(image)
.withExposedPorts(7575)
.withEnvironment({
...options.environment,
+36
View File
@@ -0,0 +1,36 @@
import type { Page } from "@playwright/test";
interface LoginInput {
page: Page;
baseUrl: string;
credentials: {
username: string;
password: string;
};
destination?: string;
}
export const loginAsync = async ({ page, baseUrl, credentials, destination = "/" }: LoginInput) => {
const destinationUrl = new URL(destination, baseUrl);
const loginUrl = new URL("/auth/login", baseUrl);
loginUrl.searchParams.set("callbackUrl", `${destinationUrl.pathname}${destinationUrl.search}${destinationUrl.hash}`);
await page.goto(loginUrl.href, { waitUntil: "load" });
await page.waitForFunction(() => {
const form = document.querySelector("form");
return form !== null && Object.keys(form).some((key) => key.startsWith("__reactProps$"));
});
await page.getByLabel("Username").fill(credentials.username);
await page.locator("#password").fill(credentials.password);
const destinationNavigation = page.waitForURL(
(url) =>
url.origin === destinationUrl.origin &&
url.pathname === destinationUrl.pathname &&
url.search === destinationUrl.search &&
url.hash === destinationUrl.hash,
{ timeout: 60_000 },
);
await page.locator("button[type='submit']").click();
await destinationNavigation;
};
-35
View File
@@ -1,35 +0,0 @@
import { createServer } from "node:http";
import type { Server } from "node:http";
export interface MockApiServer {
url: string;
port: number;
close: () => Promise<void>;
}
export const startMockApiServerAsync = async (responseBody: unknown): Promise<MockApiServer> => {
const body = JSON.stringify(responseBody);
const server: Server = await new Promise((resolve) => {
const s = createServer((_req, res) => {
res.writeHead(200, { "Content-Type": "application/json" });
res.end(body);
});
s.listen(0, "0.0.0.0", () => resolve(s));
});
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("Failed to start mock API server");
}
return {
port: address.port,
url: `http://host.docker.internal:${address.port}`,
close: () =>
new Promise((resolve, reject) => {
server.close((error) => (error ? reject(error) : resolve()));
}),
};
};
+4 -2
View File
@@ -17,13 +17,13 @@ export const seedAdminUserAsync = async (db: SqliteDatabase, input: SeedAdminUse
if (existingOnboarding) {
await db.update(sqliteSchema.onboarding).set({
step: "finish",
previousStep: "settings",
previousStep: "setup",
});
} else {
await db.insert(sqliteSchema.onboarding).values({
id: createId(),
step: "finish",
previousStep: "settings",
previousStep: "setup",
});
}
@@ -36,6 +36,8 @@ export const seedAdminUserAsync = async (db: SqliteDatabase, input: SeedAdminUse
name: input.username,
provider: "credentials",
password: await hashPasswordAsync(input.password),
completedManageTour: true,
completedBoardTour: true,
});
await db.insert(sqliteSchema.groups).values({