Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
125 changes: 125 additions & 0 deletions frontend/e2e/datasets.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { expect, test, type Page } from "./_fixtures";
import { mockVersion } from "./_compatibility";
import { READY_RUNTIME } from "./_runtime";

const LONG_HARM_CATEGORY = "cybersecurity_credentials_and_privileged_information_disclosure";

const DATASET = {
name: "harmbench",
selection_key: "dataset:named:harmbench",
loaded: true,
provider_available: true,
logical_examples: 12,
seed_pieces: 12,
objectives: 1,
modalities: ["text"],
harm_categories: [LONG_HARM_CATEGORY],
has_unlabeled_harm_categories: false,
};

async function mockDatasetCatalog(page: Page): Promise<void> {
await page.route("**/api/**", async (route) => {
const apiPath = new URL(route.request().url()).pathname.replace(/^\/api/, "");
const body = (payload: unknown) => ({
status: 200,
contentType: "application/json",
body: JSON.stringify(payload),
});

if (apiPath === "/datasets") {
await route.fulfill(body({ items: [DATASET] }));
return;
}
if (apiPath === "/runtime") {
await route.fulfill(body(READY_RUNTIME));
return;
}
if (apiPath === "/version") {
await route.fulfill(body(mockVersion()));
return;
}
if (apiPath === "/auth/config") {
await route.fulfill(body({ clientId: "", tenantId: "", allowedGroupIds: "" }));
return;
}
if (apiPath === "/auth/access") {
await route.fulfill(body({ isAdmin: false }));
return;
}
if (apiPath === "/health") {
await route.fulfill(body({ status: "healthy" }));
return;
}
if (apiPath === "/targets" || apiPath === "/converters" || apiPath === "/converters/types") {
await route.fulfill(body({ items: [] }));
return;
}
if (apiPath === "/targets/types") {
await route.fulfill(body({ items: [] }));
return;
}
if (apiPath === "/labels") {
await route.fulfill(body({ source: "attacks", labels: {} }));
return;
}

throw new Error(`Unhandled dataset catalog request: ${route.request().method()} ${apiPath}`);
});
}

async function expectLongLabelStaysInsideCard(page: Page): Promise<void> {
const card = page.getByRole("article", { name: "harmbench" });
await expect(card).toBeVisible();
await expect(card.getByText(LONG_HARM_CATEGORY)).toBeVisible();

const metrics = await card.evaluate((article, label) => {
const badge = Array.from(article.querySelectorAll("*")).find((element) => element.textContent === label);
const textHost = badge ?? article;
const range = document.createRange();
range.selectNodeContents(textHost);
const text = range.getBoundingClientRect();
const cardBox = article.getBoundingClientRect();
const badgeBox = textHost.getBoundingClientRect();
return {
cardWidth: cardBox.width,
cardRight: cardBox.right,
cardLeft: cardBox.left,
cardTop: cardBox.top,
cardBottom: cardBox.bottom,
textLeft: text.left,
textRight: text.right,
textTop: text.top,
textBottom: text.bottom,
badgeHeight: badgeBox.height,
scrollWidth: textHost.scrollWidth,
clientWidth: textHost.clientWidth,
};
}, LONG_HARM_CATEGORY);

expect(metrics.cardWidth).toBeLessThanOrEqual(360);
expect(metrics.textLeft).toBeGreaterThanOrEqual(metrics.cardLeft - 1);
expect(metrics.textRight).toBeLessThanOrEqual(metrics.cardRight + 1);
expect(metrics.textTop).toBeGreaterThanOrEqual(metrics.cardTop - 1);
expect(metrics.textBottom).toBeLessThanOrEqual(metrics.cardBottom + 1);
expect(metrics.badgeHeight).toBeGreaterThan(20);
expect(metrics.scrollWidth).toBeLessThanOrEqual(metrics.clientWidth + 1);
}

test.describe("dataset catalog layout", () => {
test.beforeEach(async ({ page }) => {
await mockDatasetCatalog(page);
});

test("wraps a long harm category inside the card on a narrow desktop column", async ({ page }) => {
await page.setViewportSize({ width: 430, height: 800 });
await page.goto("/datasets");
await expectLongLabelStaysInsideCard(page);
});

test("wraps a long harm category inside the card on a 390px mobile viewport", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.goto("/datasets");
await expectLongLabelStaysInsideCard(page);
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(390);
});
});
3 changes: 2 additions & 1 deletion frontend/e2e/scenario-history.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -530,13 +530,14 @@ test.describe("Scenario catalog, history, and live run routing", () => {
const primaryNavigation = page.getByRole("navigation", { name: "Primary" });
const primaryButtons = primaryNavigation.getByRole("button");
await expect(primaryNavigation.getByRole("button", { name: "Configuration" })).toBeVisible();
await expect(primaryButtons).toHaveCount(6);
await expect(primaryButtons).toHaveCount(7);
expect(await primaryButtons.evaluateAll((buttons) =>
buttons.map((button) => button.getAttribute("aria-label")))).toEqual([
"Home",
"Chat",
"History",
"Scanner",
"Datasets",
"Registry",
"Configuration",
]);
Expand Down
37 changes: 37 additions & 0 deletions frontend/e2e/touch-targets.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -374,6 +374,27 @@ async function installTouchTargetMocks(page: Page): Promise<void> {
await route.fulfill(jsonResponse({ converter_types: [] }));
return;
}
if (apiPath === "/datasets") {
await route.fulfill(
jsonResponse({
items: [
{
name: "harmbench",
selection_key: "dataset:named:harmbench",
loaded: true,
provider_available: true,
logical_examples: 12,
seed_pieces: 12,
objectives: 1,
modalities: ["text"],
harm_categories: ["hate"],
has_unlabeled_harm_categories: false,
},
],
})
);
return;
}
if (apiPath === "/scenarios/catalog" || apiPath === "/scenarios/runs") {
await route.fulfill(
jsonResponse({
Expand Down Expand Up @@ -751,6 +772,16 @@ test.describe("Mobile touch targets", () => {
await expectNoDocumentOverflow(page);
});

test("keeps closed dataset filters at least 44px", async ({ page }) => {
await page.goto("/datasets");
await expect(page.getByRole("heading", { name: "Datasets" })).toBeVisible();

await expectMinimumTouchTarget(page.getByRole("combobox", { name: "Modalities" }));
await expectMinimumTouchTarget(page.getByRole("combobox", { name: "Harm categories" }));
await expectMinimumTouchTarget(page.getByRole("combobox", { name: "Sort datasets" }));
await expectNoDocumentOverflow(page);
});

test("keeps every tour action at least 44px without changing containment", async ({
page,
}) => {
Expand Down Expand Up @@ -886,4 +917,10 @@ test("preserves compact desktop controls and existing sidebar dimensions", async
await openAttack.scrollIntoViewIfNeeded();
await expectCompactDesktopTarget(openAttack);
await expectCompactDesktopTarget(page.getByTestId("next-page-btn"));

await page.goto("/datasets");
await expect(page.getByRole("heading", { name: "Datasets" })).toBeVisible();
await expectCompactDesktopTarget(page.getByRole("combobox", { name: "Modalities" }));
await expectCompactDesktopTarget(page.getByRole("combobox", { name: "Harm categories" }));
await expectCompactDesktopTarget(page.getByRole("combobox", { name: "Sort datasets" }));
});
65 changes: 65 additions & 0 deletions frontend/src/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,9 @@ jest.mock("./components/Layout/MainLayout", () => {
<button onClick={() => onNavigate("scenarios")} data-testid="nav-scenarios">
Scenarios
</button>
<button onClick={() => onNavigate("datasets")} data-testid="nav-datasets">
Datasets
</button>
{children}
</div>
);
Expand Down Expand Up @@ -386,6 +389,33 @@ jest.mock("./components/Home/Home", () => {
};
});

jest.mock("./components/Datasets/DatasetCatalog", () => {
const MockDatasetCatalog = () => <div data-testid="dataset-catalog" />;
MockDatasetCatalog.displayName = "MockDatasetCatalog";
return {
__esModule: true,
default: MockDatasetCatalog,
};
});

jest.mock("./components/Datasets/DatasetSelection", () => {
const { useLocation } = jest.requireActual<typeof import("react-router")>("react-router");
const MockDatasetSelection = () => {
const location = useLocation();
return (
<div
data-testid="dataset-selection"
data-location={`${location.pathname}${location.search}`}
/>
);
};
MockDatasetSelection.displayName = "MockDatasetSelection";
return {
__esModule: true,
default: MockDatasetSelection,
};
});

jest.mock("./components/Scenarios/ScenarioCatalog", () => {
const MockScenarioCatalog = () => <div data-testid="scenario-catalog" />;
MockScenarioCatalog.displayName = "MockScenarioCatalog";
Expand Down Expand Up @@ -637,6 +667,41 @@ describe("App", () => {
expect(screen.getByTestId("attack-history")).toBeInTheDocument();
});

it("renders the dataset catalog when deep-linked to /datasets", () => {
renderApp("/datasets");

expect(screen.getByTestId("main-layout")).toHaveAttribute(
"data-current-view",
"datasets"
);
expect(screen.getByTestId("dataset-catalog")).toBeInTheDocument();
});

it("keeps the dataset selection query on the datasets view", () => {
renderApp("/datasets/detail?selection_key=dataset%3Aunnamed");

expect(screen.getByTestId("main-layout")).toHaveAttribute(
"data-current-view",
"datasets"
);
expect(screen.getByTestId("dataset-selection")).toHaveAttribute(
"data-location",
"/datasets/detail?selection_key=dataset%3Aunnamed"
);
});

it("switches to the datasets view via the sidebar", () => {
renderApp();

fireEvent.click(screen.getByTestId("nav-datasets"));

expect(screen.getByTestId("main-layout")).toHaveAttribute(
"data-current-view",
"datasets"
);
expect(screen.getByTestId("dataset-catalog")).toBeInTheDocument();
});

it("renders the scenario catalog when deep-linked to /scanner", () => {
renderApp("/scanner");

Expand Down
13 changes: 13 additions & 0 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ import ScenarioHistory from './components/History/ScenarioHistory'
import ScenarioCatalog from './components/Scenarios/ScenarioCatalog'
import ScenarioDetail from './components/Scenarios/ScenarioDetail'
import ScenarioRunPage from './components/Scenarios/ScenarioRunPage'
import DatasetCatalog from './components/Datasets/DatasetCatalog'
import DatasetSelection from './components/Datasets/DatasetSelection'
import FeedbackDialog from './components/Feedback/FeedbackDialog'
import type { HistoryFilters } from './components/History/historyFilters'
import { ConnectionBanner } from './components/ConnectionBanner'
Expand Down Expand Up @@ -54,6 +56,8 @@ import { useTour } from './hooks/useTour'
import {
attackConversationRoutePath,
attackRoutePath,
DATASET_DETAIL_PATH,
DATASETS_PATH,
routerPathParamValue,
scenarioRunProvenance,
scenarioRunRoutePath,
Expand All @@ -70,6 +74,7 @@ const VIEW_PATHS: Record<ViewName, string> = {
history: HISTORY_ATTACKS_PATH,
registry: '/registry/targets',
scenarios: '/scanner',
datasets: DATASETS_PATH,
configuration: '/config',
}

Expand All @@ -92,6 +97,12 @@ function viewFromPath(pathname: string): ViewName {
) {
return 'scenarios'
}
if (
pathname === VIEW_PATHS.datasets
|| pathname.startsWith(`${VIEW_PATHS.datasets}/`)
) {
return 'datasets'
}
const match = (Object.entries(VIEW_PATHS) as [ViewName, string][]).find(
([, path]) => path === pathname,
)
Expand Down Expand Up @@ -735,6 +746,8 @@ function AppContent({ operatorAlias }: { operatorAlias: string | null }) {
</Route>
<Route path="/targets" element={<Navigate to="/registry/targets" replace />} />
<Route path="/scanner" element={<ScenarioCatalog />} />
<Route path={DATASETS_PATH} element={<DatasetCatalog />} />
<Route path={DATASET_DETAIL_PATH} element={<DatasetSelection />} />
<Route
path="/scanner/:scenarioName"
element={
Expand Down
Loading