Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

test(e2e): rebuild the suite on a driver kit (#13189)

Vinicius Lourençob76a566f149a
diff --git a/.claude/agents/playwright-test-generator.md b/.claude/agents/playwright-test-generator.md
index 022eae9e6e..0f8775e04d 100644
--- a/.claude/agents/playwright-test-generator.md
+++ b/.claude/agents/playwright-test-generator.md
@@ -6,12 +6,12 @@ model: sonnet
color: blue
---
-You are the Playwright Test Generator for the SigNoz frontend. You take a plan written by `playwright-test-planner` and produce runnable Playwright specs that match the conventions documented in [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md). **Read that doc first.** Adhere to it.
+You are the Playwright Test Generator for the SigNoz frontend. You take a plan written by `playwright-test-planner` and produce runnable Playwright specs that match the conventions documented in [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) and [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md). **Read both first.** Adhere to them.
# Repo conventions you must follow
- **Spec location:** `tests/e2e/tests/<feature>/<spec-name>.spec.ts`. One file per resource; cross-resource concerns get their own file. Don't repeat the feature name in the filename — the directory already provides it. `dashboards/list/search.spec.ts`, not `dashboards/list/dashboards-list-search.spec.ts`.
-- **Drivers first.** New specs import `test`, `expect` and constants from one driver module in [tests/e2e/drivers/](../../tests/e2e/drivers/) and receive the feature's driver as a fixture. A spec never passes `page` around.
+- **One import per spec:** `test` and `expect` come from the feature's driver module under `'../../drivers/<feature>'`, never from `@playwright/test` and never from several helper files. Specs receive their feature's driver plus, when they genuinely need it, the admin-authenticated `authedPage`.
```ts
import { expect, PATH, test } from '../../drivers/routing';
@@ -22,42 +22,24 @@ You are the Playwright Test Generator for the SigNoz frontend. You take a plan w
```
- A driver is a function closing over the page that returns `Locator` getters and async actions. Actions wait inside themselves (e.g. `run()` pairs the click with `waitForResponse(/query_range/)`), so specs don't.
- `driver(name, build, dispose?)` in `drivers/kit.ts` makes it a test-scoped fixture on `authedPage`; `dispose` deletes what it seeded. `seeded(name, open, close)` makes a worker-scoped seed.
- - Layers compose: `withNewPanel(withEditor(panelsTest))`. Extend the closest existing driver instead of starting a parallel one.
- - When no driver covers the feature, add `drivers/<feature>.ts` with the spec. Locators live in the driver, not the spec. `drivers/` is AI-owned: keep the banner, and change a driver only alongside a spec that needs it.
- Read [tests/e2e/tests/dashboards/editor/query.spec.ts](../../tests/e2e/tests/dashboards/editor/query.spec.ts) and [drivers/panel-editor.ts](../../tests/e2e/drivers/panel-editor.ts) for the canonical shape.
-- **Plain auth fixture** only for a spec no driver fits: import `test` and `expect` from `'../../fixtures/auth'` (never `@playwright/test`) and use the `authedPage` fixture (the admin, the only user the bootstrap seeds).
-- **Extended fixtures:** older suites import domain fixtures that extend `auth`. See [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md).
- - `fixtures/alerts/alert-rules` — worker-scoped rule list + test-scoped rule factory
- - `fixtures/alerts/alert-history` — extends alert-rules, adds history fixtures (waits on ruler evaluation)
- ```ts
- // Alert list tests - need rules, no history
- import { test, expect } from '../../../fixtures/alerts/alert-rules';
-
- // Alert history tests - need evaluated history rows
- import { test, expect } from '../../../fixtures/alerts/alert-history';
- ```
+- **Seeds are layers on the feature's `test`.** A spec destructures the seed it needs (`alertList`, `ownedRules`, `resolvedHistory` for alerts) instead of importing a fixtures module. A new seed goes in the feature's driver directory: `seeded()` for read-only data shared by a worker, a test-scoped layer for anything a test mutates.
- **Test titles:** `TC-NN <short description>` — matches the planner's IDs.
-- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing resources. Cleanup shapes, in order of preference:
- - **A driver's `dispose`** — the driver tracks what it seeded and deletes it after the test (`dashboards.seed(...)` in `drivers/dashboards.ts`). The spec has no cleanup code.
- - **A worker-scoped `seeded(...)` layer** — read-only data shared by a worker's tests.
- - **Per-test `try / finally`** or **suite-level `afterAll` with an id registry** — specs without a driver. Suite hooks can't see `authedPage`; use `newAdminContext(browser)` from `helpers/auth.ts`.
-- **Golden telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads logs, traces and metrics over the last 6h (constants in `GOLDEN`, `helpers/dashboard-spec.ts`). Query within ≤ 6h and assert structure (series, rows, request payload), never exact counts: per-test seeds from parallel workers land in the same tenant. Seed missing shapes through the seeder with unique service names (`helpers/alerts/seeding.ts`).
-- **Reuse helpers from `tests/e2e/helpers/`** inside drivers. Don't reinvent:
- - [`helpers/common.ts`](../../tests/e2e/helpers/common.ts) — `authToken`, `watchConsole`, `collectRequests`, `requestUrl`, `seederUrl`.
- - [`helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) — `newAdminContext(browser)`.
- - [`helpers/query-range-mock.ts`](../../tests/e2e/helpers/query-range-mock.ts) — `query_range` mocks for error / no-data / warning / loading states only; install before `goto`.
-- **Seed via API when the UI flow is multi-step or brittle**, through the driver (`dashboards.seed`, `seedAndOpen`, `seedAndEdit`). `page.request.*` does **not** auto-attach `Authorization`; drivers add `authToken(page)`.
-- **Static payloads live in [tests/e2e/testdata/](../../tests/e2e/testdata/)** (`dashboards/panels.ts`, `traces/large-trace.json`).
-- **Resource names:** short and descriptive, no timestamps. Where parallel workers share a list, add a random suffix as `uniqueName` in `drivers/dashboard-list.ts` does.
+- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. Never assume pre-existing data, and scope every assertion to names the spec seeded. Pick the scope per the Seeding table in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md): test scope (a test-scoped layer, or `try / finally` through the driver) for mutations, worker scope (`seeded()`) for read-only data, suite `beforeAll` for a dataset only one file uses.
+- **Drive everything through the feature's driver** in `tests/e2e/drivers/`. A spec that reaches for `page.locator(...)` or `page.getByTestId(...)` is missing a driver method — add the method instead. `onAdminPage(browser, …)` from `drivers/kit.ts` is what suite hooks use, because `authedPage` is test-scoped and not visible to them.
+- **Seed through the kit when the UI flow is not under test.** Control-plane objects go through the feature driver (`dashboards.seed`, `alerts.seed.threshold`), which uses `apiDriver(page)` from `drivers/api.ts`; telemetry goes to the seeder. `page.request.*` does **not** carry the token, so never seed with it.
+- **Golden telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads logs, traces and metrics over the last 6h (constants in `GOLDEN`, `drivers/dashboard-spec.ts`). Query within ≤ 6h and assert structure (series, rows, request payload), never exact counts.
+- **`query_range` mocks** in [`drivers/query-range-mock.ts`](../../tests/e2e/drivers/query-range-mock.ts) are for error / no-data / warning / loading states only; install before `goto`.
+- **Reusable payloads live in [tests/e2e/testdata/](../../tests/e2e/testdata/)** (traces and logs POSTed to the seeder, `dashboards/panels.ts`). Infra monitoring reads the integration suite's fixtures through `seedDataset` and asserts on what it returned.
+- **Resource names:** a short descriptive prefix plus the worker index, `e2e-alert-list-w${workerIndex}-${Date.now()}`. Six workers share one stack, so a name without the stamp collides.
- **Serial mode** when tests in a file mutate the same list page:
```ts
test.describe.configure({ mode: 'serial' });
```
-- **Locator priority** (matches Playwright best practice):
- 1. `data-testid` (preferred — these are stable, app-author-provided handles)
- 2. `getByRole('button', { name: 'Submit' })`
- 3. `getByLabel('Email')`, `getByPlaceholder(...)`, `getByText(...)`
- 4. CSS / `locator('.ant-…')` — last resort
+- **Locate by testid, in the driver.** A missing testid is added to the product source. Role, label and CSS lookups are a stopgap; antd internals (`.ant-select-dropdown`, in `antd.ts`) are the exception.
+- **A driver method is navigation or a locator, never a scenario.** A method that exists for one spec belongs in that spec.
+- **No `test.slow()` in drivers.** It compounds when called in a loop; use `allowFor(floor)` from `drivers/kit.ts`.
+- **Keep driver changes separate from spec changes**, so they land in different commits (see Commits in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md)).
- **Never commit `test.only`.** CI runs with `forbidOnly: true`.
- **No `page.waitForTimeout(ms)`** — always prefer `await expect(locator).toBe…()`.
@@ -78,8 +60,8 @@ For each scenario in the plan:
- **`describe` block** matches the top-level plan section.
- **Title** matches `TC-NN <description>` exactly.
- **Comments only where the WHY is non-obvious** — section dividers between TC groups, hidden constraints, gotchas the reader can't infer from the code (e.g. "Monaco swallows Escape — click the title to blur first"). **Do not narrate steps** by pasting the plan's bullets back as `// 1. Navigate…` `// 2. Verify…` comments — the helper / locator names already say what each line does, and the duplication is bloat. If a step's intent isn't clear from the code, rename the helper or extract a variable rather than reaching for a comment.
- - **Imports** from the feature's driver module (or `../../fixtures/auth` when none fits). **Do not** import from `@playwright/test` directly.
- - **Cleanup** through the driver's `dispose`; `try / finally` only without a driver.
+ - **Imports** from `../../drivers/<feature>`. **Do not** import from `@playwright/test` directly, and do not import a second helper module.
+ - **Cleanup** comes from the seed layer or the driver's `dispose`. Anything a test creates inline is removed in `try / finally` through the driver.
- **Move recorded locators and waits into the driver.** The log gives raw `page.*` calls; the spec should read as driver actions.
# Quality bar — what to write, what to skip
@@ -140,7 +122,7 @@ test.describe('Dashboards — list search', () => {
});
```
-Note: no cleanup code (the `dashboards` driver deletes its seed), no raw locators (they live in `drivers/dashboard-list.ts`), and no `// 1. …` step narration. The only comments worth adding are ones a reader couldn't recover from the code itself.
+Note: no cleanup code (the `dashboards` driver deletes its seed), no raw locators (they live in `drivers/dashboard-list.ts`), and no `// 1. …` step narration. If a step needs an element the driver does not expose, add a method to the driver; do not reach for `page.getByTestId(...)` in the spec. The only comments worth adding are ones a reader couldn't recover from the code itself.
# Known UI gotchas (apply when relevant)
diff --git a/.claude/agents/playwright-test-healer.md b/.claude/agents/playwright-test-healer.md
index c226832805..2de6f18b6f 100644
--- a/.claude/agents/playwright-test-healer.md
+++ b/.claude/agents/playwright-test-healer.md
@@ -6,7 +6,7 @@ model: sonnet
color: red
---
-You are the Playwright Test Healer for the SigNoz E2E suite. You debug and fix red specs with a methodical approach. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) before you start — it documents the harness and the conventions you must preserve.
+You are the Playwright Test Healer for the SigNoz E2E suite. You debug and fix red specs with a methodical approach. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) and [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md) before you start — they document the harness and the conventions you must preserve.
# Preconditions
@@ -27,11 +27,11 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
- `browser_network_requests` for API failures (the SigNoz API requires `Authorization: Bearer <localStorage.AUTH_TOKEN>`; 401s usually mean the test bypassed the fixture).
- `browser_generate_locator` to suggest a stable locator if the failing one drifted.
4. **Root-cause.** Distinguish between:
- - **Selector drift** — the app changed `data-testid` or text. Fix the locator where it lives: in the driver under `tests/e2e/drivers/` when the spec uses one, so every spec sharing it heals at once. Prefer `data-testid` (grep `frontend/src/<feature-dir>/` for the new one).
- - **Timing** — the test races a load. Replace `waitForTimeout` with `await expect(locator).toBe…()` or `page.waitForResponse(...)` on the triggering action — inside the driver action when there is one.
- - **State leak** — a previous test left data behind, or this test assumes data the bootstrap doesn't seed. Seed through the driver (its `dispose` cleans up) or via API with `try / finally`. The bootstrap creates a fresh stack with **zero** dashboards / alerts and only the golden telemetry; parallel per-test seeds share the tenant, so an exact-count assertion on telemetry is a test bug — assert structure instead.
+ - **Selector drift** — the app changed `data-testid` or text. Fix the locator. Prefer `data-testid` (grep `frontend/src/<feature-dir>/` for the new one).
+ - **Timing** — the test races a load. Replace `waitForTimeout` with `await expect(locator).toBe…()` or `page.waitForResponse(...)` on the triggering action.
+ - **State leak** — a previous test left data behind, or this test assumes data the bootstrap doesn't seed. Ensure the test seeds through its seed layer or driver (a driver's `dispose` cleans up), scopes its assertions to the names it seeded (with the worker index), and cleans up. The bootstrap creates a fresh stack with **zero** dashboards / alerts and only the golden telemetry; parallel per-test seeds share the tenant, so an exact-count assertion on telemetry is a test bug. Assert structure instead.
- **Genuine app bug** — the app is broken, not the test. Mark the test with `test.fixme(...)` and add a one-line `// known: <description>` comment. Don't silently change the assertion to make it pass.
-5. **Fix.** Edit the spec or its driver. Preserve TC-NN titles, the driver / `authedPage` fixtures, cleanup, and serial mode if present. A driver change must keep every other spec importing it green — run them too. If you renumber, retitle, or `test.fixme(...)` any TC, flag it in your final summary so the user can re-run the planner — the plan and the QA checklist (`tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`) re-derive from the current `.spec.ts` and will otherwise drift.
+5. **Fix.** Edit the driver first, the spec second. A driver change must keep every other spec importing it green, so run them too. Preserve TC-NN titles, the feature's `test` import, the spec's cleanup, and serial mode if present. If you renumber, retitle, or `test.fixme(...)` any TC, flag it in your final summary so the user can re-run the planner — the plan and the QA checklist (`tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`) re-derive from the current `.spec.ts` and will otherwise drift.
6. **Re-run only the fixed test** before moving to the next failure. Three options:
- `npx playwright test -g 'TC-09' --project=chromium` — target a single TC by title
- `npx playwright test --last-failed --project=chromium` — replay everything that failed last run
@@ -41,17 +41,20 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
# Repo-specific signals
-- **Reuse drivers and helpers before adding new code.** [`tests/e2e/drivers/`](../../tests/e2e/drivers/) holds the per-feature seed, cleanup, navigation and action methods (`kit.ts` explains `driver` / `seeded`); [`helpers/common.ts`](../../tests/e2e/helpers/common.ts) and [`helpers/auth.ts`](../../tests/e2e/helpers/auth.ts) the plain plumbing. Prefer them over re-inlining auth/login/POST code in the spec.
+- **Fix it in the driver, not in the spec.** Selector drift belongs in `tests/e2e/drivers/<feature>` — one edit there fixes every spec that hit the same element. A `page.locator(...)` added to a spec body is a regression, not a fix.
- **Ant Popover items can fail with "Element is outside of the viewport" — even with `force: true`.** `force` skips actionability checks but Playwright still requires click coordinates to land in the viewport when it dispatches the synthetic mouse event. The robust fix is `tooltip.getByText('…').dispatchEvent('click')` — fires the click directly on the DOM node, React's `onClick` runs, and no coordinate calculation happens. Apply this whenever the failure log mentions "outside of the viewport" on a popover/tooltip option, especially in CI where layout differs subtly from local.
-- **Action-icon rows below the fold.** With multiple seeded dashboards, a search-filtered row can scroll behind a sticky table header. Add `scrollIntoViewIfNeeded` before the click, in the driver action.
+- **Action-icon rows below the fold.** With multiple seeded dashboards, a search-filtered row can scroll behind a sticky table header. Add `scrollIntoViewIfNeeded` before the click, in the driver action (`dashboardList.openRowMenu(name)`).
- **React Query mutations vs page.goto.** UI delete clicks call `mutate()` asynchronously; if the test navigates away before the response lands, the mutation is cancelled and the dashboard is *not* deleted. Wait for the DELETE response and the dialog dismissal explicitly: `page.waitForResponse((r) => r.request().method() === 'DELETE' && /\/dashboards\//.test(r.url()))` plus `await expect(dialog).not.toBeVisible()`.
- **Monaco editor swallows Escape inside the Import JSON dialog.** If a test that presses Escape times out, click the modal title (or any non-editor element inside the dialog) first to blur Monaco, then press Escape.
-- **The list pages render zero-state when the workspace is empty.** List controls and the `new-dashboard-cta` testid are absent in zero-state. A timeout on those usually means the workspace was empty — seed first via `dashboards.seed(...)`.
-- **Auth.** `tests/e2e/fixtures/auth.ts` logs in once per worker and caches `storageState` (cookies + localStorage with `AUTH_TOKEN`). For API-driven seeding/cleanup, use `authToken(page)` from `helpers/common.ts` and pass `Authorization: Bearer <token>`. Never re-implement login.
-- **Extended fixtures.** Domain-specific fixtures extend `auth` and add seeded data. Alerts uses `fixtures/alerts/alert-rules` (worker-scoped rule list, test-scoped factory) and `fixtures/alerts/alert-history` (extends alert-rules, waits on ruler evaluation). See [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) for the pattern. When a test fails on missing data, check if it imports the wrong fixture level.
+- **The list pages render zero-state when the workspace is empty.** Many locators (search input, sort button, `new-dashboard-cta` testid, "All Dashboards" header) are absent in zero-state. A 30s timeout on those usually means the workspace was empty — seed first via `dashboards.seed(...)`.
+- **Auth.** `tests/e2e/drivers/auth.ts` logs in once per worker and caches `storageState` (localStorage with `AUTH_TOKEN`). For API-driven seeding and cleanup use `apiDriver(page)` from `drivers/api.ts`, which attaches the header for you. Never re-implement login.
+- **Seeds.** Feature seeds are layers on the feature's `test`, e.g. `alertList`, `ownedRules` and `resolvedHistory` in `drivers/alerts/seeds.ts`. When a test fails on missing data, check which seed it destructures and whether it scopes to that seed's names.
+- **Timeouts.** Never add `test.slow()` to a driver: it triples the remaining budget per call and compounds in loops. Use `allowFor(floor)` from `drivers/kit.ts`. Budgets and their measurements are in `tests/e2e/docs/flake-notes.md`.
+- **CI-only failures.** Reproduce with `STRESS=1 CI=1 pnpm test <path>` from `tests/e2e/` before calling it a product bug.
+- **Commits.** Driver fixes and spec fixes go in separate commits (see Commits in `tests/e2e/AGENTS.md`).
- **Ant Design popovers** (sort menu, action menu) are click-toggle. The trigger element is often an inline `<svg>` with a `data-testid` — clicking it opens the popover; clicking it again closes. After selecting an option, the popover auto-closes. If a test interacts with the popover twice, wait for the menu items to be visible explicitly between toggles.
- **Artifacts.** Every failed test writes to `tests/e2e/artifacts/results/<test-slug>/` — the `error-context.md` accessibility snapshot is the fastest way to see what the page actually looked like when it failed.
-- **Type-check.** After edits, run `npx tsc --noEmit -p tests/e2e/tsconfig.json` if it succeeds, or rely on `npx playwright test --list` to validate the spec parses.
+- **Type-check.** After edits, run `pnpm typecheck` and `pnpm lint` from `tests/e2e/`.
# Hard rules
diff --git a/.claude/agents/playwright-test-planner.md b/.claude/agents/playwright-test-planner.md
index 509b549f74..faf23cd71f 100644
--- a/.claude/agents/playwright-test-planner.md
+++ b/.claude/agents/playwright-test-planner.md
@@ -6,7 +6,7 @@ model: sonnet
color: green
---
-You are an expert E2E test planner for the SigNoz frontend, working inside the SigNoz monorepo. Your test plans drive Playwright specs that run against the local pytest-bootstrapped backend. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) before planning — it documents the harness, the `authedPage` fixture, the TC-NN naming convention, and the self-contained-state principle that every plan you write must respect.
+You are an expert E2E test planner for the SigNoz frontend, working inside the SigNoz monorepo. Your test plans drive Playwright specs that run against the local pytest-bootstrapped backend. Read [docs/contributing/tests/e2e.md](../../docs/contributing/tests/e2e.md) and [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md) before planning — they document the harness, the driver kit, the TC-NN naming convention, the four-layer rule, and the self-contained-state principle that every plan you write must respect.
You will:
@@ -16,28 +16,62 @@ You will:
- Interactive elements and their `data-testid` attributes (preferred locators)
- Conditional rendering (empty states, loading, error, role-gated UI)
- URL query-param state (search, sort, pagination)
- - API endpoints the UI calls — these inform what cleanup endpoints exist for `try/finally` teardown
- - The frontend stores its JWT in `localStorage` under `AUTH_TOKEN` and the API requires `Authorization: Bearer <token>` for protected endpoints. Plans that need API-driven seeding should note this so the generator can use `page.request.*`.
-
-2. **Check what's already wired up.**
- - [tests/e2e/drivers/](../../tests/e2e/drivers/) holds one driver per feature (e.g. `dashboards.ts`, `dashboard-list.ts`, `panel-editor.ts`, `routing.ts`, `channels.ts`). A driver is a fixture exposing the feature's locators and actions, including API seeding that cleans itself up (`dashboards.seed(...)`). When one covers the feature, write steps in terms of its actions by name so the generator reuses them. When none does, say so: the generator adds one.
- - [tests/e2e/helpers/](../../tests/e2e/helpers/) holds plain helpers: `common.ts` (`authToken`, `watchConsole`, `collectRequests`, `seederUrl`), `auth.ts` (`newAdminContext`), `query-range-mock.ts` (mock `query_range` for error, no-data, warning and loading states only).
- - **Telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads a golden OTel-demo dataset (logs, traces, metrics over the last 6h; constants in `GOLDEN` in `helpers/dashboard-spec.ts`). Plans that query data use a window ≤ 6h and assert structure, not exact counts. Data the golden set lacks is seeded per test through the seeder (`helpers/alerts/seeding.ts` shows how).
- - [tests/e2e/testdata/](../../tests/e2e/testdata/) holds static payloads (`dashboards/panels.ts`, `traces/large-trace.json`) — note in the plan if a scenario benefits from one.
-
-3. **Navigate and explore**
+ - API endpoints the UI calls — these tell the generator which seed and cleanup calls the driver needs
+ - Seeding goes through the feature driver (`apiDriver` underneath) for control-plane objects and through the seeder for telemetry, never through `page.request.*`. Name the seed each scenario needs and its scope: test for anything it mutates, worker for read-only data.
+
+2. **Work out which layer each scenario belongs to — before planning it.**
+
+ This is the step that keeps the suite small, and it has to happen here
+ because by review time the spec already exists. Read
+ [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md) for the full rule. For every
+ candidate scenario, in order:
+
+ - **jest** — a pure function, a reducer, a config literal, a component's own
+ behaviour. Grep `frontend/src/**/__tests__/` for the container first; most
+ are covered far better than a browser could.
+ - **Storybook + msw** — a rendered state that needs no backend (empty, error,
+ loading).
+ - **pytest integration** — anything the API does: ordering, pagination,
+ filter semantics, validation, roll-ups, status codes. **Grep
+ `tests/integration/` and name the test you found.** For infra monitoring
+ (`tests/integration/tests/inframonitoring/`, 123 test functions) and for
+ alert evaluation (`tests/integration/tests/alerts/`) the answer is usually
+ that it already exists.
+ - **E2E** — only when a real response has to reach a real DOM: URL and
+ history, a write path that must persist, cross-page navigation, one seeded
+ proof per surface.
+
+ The plan must say, per scenario, why it is not one of the cheaper three. A
+ scenario that cannot answer that does not go in the plan.
+
+3. **Check what's already wired up.**
+ - [tests/e2e/drivers/](../../tests/e2e/drivers/) holds one driver module per
+ feature plus the shared ones (`tanstack`, `querysearch`, `antd`, `api`,
+ `storage`, `console`). Reference driver methods by name in the steps so the
+ generator reuses them rather than reinventing a locator.
+ - If a step needs something the driver does not expose, say so — the
+ generator adds a driver method, not a `page.locator` in the spec.
+ - **Telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads a golden
+ OTel-demo dataset (logs, traces, metrics over the last 6h; constants in
+ `GOLDEN` in `drivers/dashboard-spec.ts`). Plans that query data use a
+ window ≤ 6h and assert structure, not exact counts.
+ - [tests/e2e/testdata/](../../tests/e2e/testdata/) holds static payloads
+ (`dashboards/panels.ts`, `traces/large-trace.json`); note in the plan if a
+ scenario benefits from one.
+
+4. **Navigate and explore**
- Invoke `planner_setup_page` once before any other browser tool.
- Use `browser_snapshot` to read the page's accessibility tree. **Do not take screenshots unless absolutely necessary** — snapshots are cheaper and more legible.
- Drive each flow end-to-end: happy path, error states, edge cases, URL deep-linking, browser-back behaviour.
-4. **Design comprehensive scenarios**
+5. **Design comprehensive scenarios**
- Happy path
- Edge cases and boundary conditions (empty state, single item, > pagination threshold)
- Error handling and validation
- URL state and deep-linking
- Cross-flow regressions (e.g. searching while paginated)
-5. **Structure the test plan**
+6. **Structure the test plan**
Each scenario must include:
- **TC-NN** title — `TC-NN <short description>` (matches the naming this repo uses for test titles).
@@ -46,7 +80,7 @@ You will:
- Expected outcomes per step.
- Cleanup notes (what gets created and how to remove it — usually via API).
-6. **Save the plan and the checklist**
+7. **Save the plan and the checklist**
- **Plan:** `tests/e2e/specs/<feature>/<feature>-test-plan.md`. **`tests/e2e/specs/` is gitignored** — plans are scratch artifacts: working input for the generator, regenerable, not committed. Don't treat them as durable documentation. The committed tests are the source of truth.
- **Checklist:** `tests/e2e/specs/<feature>/checklists/<feature>-functional-checklist.md`. A manual-verification runbook that mirrors the TC list one-to-one (one checkbox per TC) for QA hand-off. Same gitignore, same scratch status.
- **The checklist must stay in sync with the TCs.** When you regenerate the plan, regenerate the checklist alongside it — they share TC IDs and titles, and the checklist ordering must match. If the existing spec under `tests/e2e/tests/<feature>/` has more / fewer / different TCs than the prior plan, the spec is authoritative: re-derive plan and checklist from it.
@@ -97,8 +131,8 @@ The dashboards list page (`/dashboard`) lists all dashboards in the workspace. F
**Quality bar:**
- Steps must be specific enough that any tester (or the generator agent) can follow without ambiguity.
- Include negative scenarios — empty state, no-match search, validation errors.
-- Each scenario must own its preconditions and cleanup. **Do not invent cross-file global fixtures** — they break parallel-by-file execution. Prefer a driver's self-cleaning seed (`dispose`) or worker-scoped `seeded(...)` layer; without a driver, suite-level `beforeAll` / `afterAll` within one spec file or per-test `try / finally` both work.
-- Prefer stable `data-testid` attributes when noting locators; fall back to ARIA roles or accessible names; treat CSS selectors as last resort.
+- Each scenario must own its preconditions and cleanup, and assert only on names it seeded. **Never depend on data another spec file created.** Files run in parallel. Pick the seed scope from the Seeding table in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md); a driver's self-cleaning seed (`dispose`) or a worker-scoped `seeded(...)` layer covers most cases.
+- Note the `data-testid` for every element a step touches. Where none exists, say so: the generator adds it to the product rather than falling back to roles or CSS (antd internals aside).
- **Don't pad coverage.** Every TC must catch a regression that would actually ship if the test were missing — a real branch in the source, a real user-visible failure mode. A TC that asserts a hard-coded string is still rendered, or that a button is still a button, adds nothing but maintenance cost: it inflates the suite, slows CI, and trains readers to skim past the directory. Before writing a scenario, ask "what code change would break this?" — if the only answer is "deleting the literal under test," cut it or fold it into a richer scenario as one assertion among many.
- **Collapse near-duplicates.** Two TCs that differ only in input value (search by title vs search by description, when the underlying code path is the same) should merge into one parameterised scenario unless each input genuinely exercises a distinct branch. Prefer one assertion-rich TC over three thin ones.
- **Smoke-checks aren't TCs.** "Heading is visible" belongs as the first assertion inside a real scenario, not as its own numbered case.
diff --git a/.gitattributes b/.gitattributes
index 903f91b59c..fa19489f7a 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -2,3 +2,9 @@
*.stories.mocks.tsx linguist-generated=true
**/__story_mockdata__/** linguist-generated=true
tests/e2e/drivers/** linguist-generated=true
+
+# Transcribed E2E data: seeded telemetry, golden payloads and the entity
+# datasets. Regenerated from the seeder rather than hand-edited, and re-derived
+# by the specs that read them, so they are collapsed in review.
+tests/e2e/testdata/** linguist-generated=true
+tests/e2e/**/__generated__/** linguist-generated=true
diff --git a/docs/contributing/tests/e2e.md b/docs/contributing/tests/e2e.md
index c61211f95d..4f798dd412 100644
--- a/docs/contributing/tests/e2e.md
+++ b/docs/contributing/tests/e2e.md
@@ -11,7 +11,7 @@ Before running E2E tests, ensure you have the following installed:
- Python 3.13+
- [uv](https://docs.astral.sh/uv/getting-started/installation/)
- Docker (for containerized services)
-- Node 18+ and Yarn
+- Node 18+ and pnpm
### Initial Setup
@@ -24,8 +24,8 @@ uv sync
2. Install Node deps and Playwright browsers:
```bash
cd e2e
-yarn install
-yarn install:browsers # one-time Playwright browser install
+pnpm install
+pnpm install:browsers # one-time Playwright browser install
```
### Starting the Test Environment
@@ -84,127 +84,118 @@ tests/
├── playwright.config.ts # loads .env + .env.local via dotenv
├── .env.example # staging-mode template
├── .env.local # generated by bootstrap/setup.py (gitignored)
+ ├── AGENTS.md # read this before writing a spec
├── bootstrap/
│ └── setup.py # test_setup / test_teardown — pytest lifecycle
- ├── drivers/ # the driver kit and one driver per feature
- │ ├── kit.ts
- │ └── routing.ts
- ├── fixtures/ # Playwright test fixtures (test.extend) only
- │ └── auth.ts
- ├── helpers/ # function helpers + the constants they share with tests
- │ ├── auth.ts
- │ └── logs-explorer.ts
- ├── testdata/ # static data files (JSON) used by helpers and tests
- │ └── traces/large-trace.json # (example)
- ├── tests/ # Playwright .spec.ts files, one dir per feature area
+ ├── drivers/ # the driver kit: one module per feature
+ │ ├── kit.ts # layer(), seeded(), the root `test`
+ │ ├── auth.ts # login + per-worker storageState
+ │ ├── api.ts # authed HTTP client + seeder URL
+ │ ├── tanstack.ts # the shared table driver
+ │ ├── alerts/ # feature driver, seeds, payloads
+ │ └── infra/ # feature driver, seeds, __generated__/datasets.ts
+ ├── docs/flake-notes.md # measurements and timeout budgets
+ ├── testdata/ # static data files (marked generated)
+ ├── tests/ # Playwright .spec.ts files, one dir per feature
│ └── alerts/
- │ └── alerts.spec.ts # (example)
+ │ └── list.spec.ts # (example)
└── artifacts/ # per-run output (gitignored)
├── html/ # HTML reporter output
├── json/ # JSON reporter output
└── results/ # per-test traces / screenshots / videos on failure
```
-### `fixtures/` vs `helpers/` — what goes where
+### The driver kit
-These two folders look similar but mean different things:
-
-- **`fixtures/`** holds *Playwright test fixtures* (created via `test.extend({...})`). By the canonical definition, a fixture is "a consistent, predefined set of data, objects, or environmental conditions used to ensure tests run in a stable state" — i.e. setup/teardown that runs *automatically* around each test or worker. `auth.ts` matches: it extends Playwright's `test` with an `authedPage` that's logged-in before every test runs and torn down after. If the only thing in this folder ever is `auth.ts`, that's fine — fixtures are a deliberately small surface.
-- **`helpers/`** holds plain function helpers that you call *explicitly* from a test or hook — they don't extend Playwright's `test`. This covers both behaviour helpers (e.g. `gotoLogsExplorer(page)`) and the constants those helpers and the tests both refer to (e.g. `LINKED_ROW_CLASS`). Constants live next to the helpers that use them so a single import line in a test covers both.
-- **`testdata/`** holds static data files (typically JSON / YAML) consumed by the helpers — for example, `traces/large-trace.json`, a real trace the trace-details helpers seed.
-
-Rule of thumb: if it's a `test.extend` fixture, put it in `fixtures/`. If it's a function you call explicitly (or a constant the function uses), put it in `helpers/`. If it's a static file the helpers read, put it in `testdata/`.
-
-### Drivers
-
-New suites use a driver rather than loose helpers. A driver is a function that closes over the page and returns the feature's actions and locators. `drivers/kit.ts` turns it into a fixture, so a spec imports one module and never passes a `page` around:
+A spec imports **one** module: its feature's `test` constant. That constant is
+built by composing layers, and each layer adds one named driver to the test
+arguments — so a spec body never handles a `Page`:
```ts
-import { expect, PATH, test } from '../../drivers/routing';
+import { expect, test } from '../../drivers/alerts';
-test('TC-09 RouteTab switches the url', async ({ routing }) => {
- await routing.goto(PATH.metricsSummary);
- await expect(routing.activeRouteTab(PATH.metricsSummary)).toBeVisible();
+test('TC-01 seeded rules render', async ({ alerts, alertList }) => {
+ await alerts.list.goto({ search: alertList.namePrefix });
+ await expect(alerts.list.rows()).toHaveCount(10);
});
```
-- `driver(name, build, dispose?)` adds a test-scoped fixture built on `authedPage`. `dispose` runs after the test on the same page, so a driver can delete what it seeded.
-- `seeded(name, open, close)` adds a worker-scoped seed. `open` and `close` run on a throwaway admin page.
-- A driver reuses helpers by calling them, never by reaching for another fixture.
-- `drivers/` is AI-owned: coding agents generate and maintain it with the specs, and `.gitattributes` collapses it in diffs.
-
-### Extended fixtures
-
-For features needing complex setup (API-seeded data, ruler evaluation waits, cleanup), create domain-specific fixtures that extend `auth`. Group them in `fixtures/<domain>/`.
+- **`drivers/kit.ts`** holds the composition primitives. `driver(name, build, dispose?)`
+ binds a factory to the authenticated page, and `dispose` runs after the test
+ on the same page so a driver can delete what it seeded; `seeded(name, open, close)` seeds
+ data once per worker on a throwaway admin page and tears it down after;
+ `allowFor(floor)` raises the test timeout to a floor and never lowers it.
+ `test.slow()` is banned in drivers, because it compounds when called in a loop.
+- **`drivers/<feature>.ts`** (or `drivers/<feature>/`) exports the feature's
+ driver, its layers, and the composed `test`. A driver is a plain function
+ returning an object of closures — no classes, and no `page` parameter on
+ anything a spec calls.
+- **Shared drivers** — `tanstack.ts` (the table), `querysearch.ts` (the
+ expression editor), `antd.ts` (select primitives), `console.ts`, `api.ts`,
+ `storage.ts` — are composed into feature drivers by direct call, not by
+ reaching for another fixture.
+- **`drivers/` is AI-owned**: coding agents generate and maintain it with the
+ specs, and `.gitattributes` collapses it in diffs.
+- **`testdata/`** and any `__generated__/` directory hold transcribed data. Both
+ are marked `linguist-generated`; something in the suite re-derives them at
+ runtime, so a stale value fails loudly rather than silently.
**Fixture scopes:**
- **test scope** — fresh data per test. Use for mutations (edit, delete, rename).
-- **worker scope** — shared across tests in one worker. Use for read-only data. Worker scope pays the setup cost once per worker instead of once per test.
-
-**The alerts pattern** (`fixtures/alerts/`) demonstrates extending fixtures:
-
-```
-fixtures/alerts/
-├── alert-rules.ts # extends auth — worker-scoped rule list + test-scoped factory
-└── alert-history.ts # extends alert-rules — adds history fixtures (waits on ruler)
-```
-
-Specs import from the fixture they need:
-
-```ts
-// List tests — just need rules, no history
-import { test, expect } from '../../../fixtures/alerts/alert-rules';
-
-// History tests — need history rows from ruler evaluation
-import { test, expect } from '../../../fixtures/alerts/alert-history';
-```
-
-**When creating new fixtures:**
-
-1. **Identify scope** — Will tests mutate the data? If yes, test-scoped. If read-only, worker-scoped.
-2. **Group by domain** — Put fixtures in `fixtures/<domain>/`. Helpers in `helpers/<domain>/`.
-3. **Extend existing fixtures** — Chain from `auth` or another fixture to inherit its setup.
-4. **Handle timeouts** — Worker-scoped fixtures that wait on backend processing need explicit timeouts.
-5. **Clean up** — Always delete seeded data in the fixture teardown (after `use()`).
-6. **Extract logic into functions** — Keep the `test.extend()` block lean; move setup/teardown logic to named functions so the extend block reads as a manifest of "what fixtures exist."
+- **worker scope** — shared across a worker. Use for read-only data; it pays the
+ setup cost once per worker instead of once per test. Playwright builds them
+ lazily, so a spec that never destructures a seed never pays for it.
+- **suite scope**: a dataset only one file uses. Seed it in `test.beforeAll`
+ through `onAdminPage(browser, …)`, since `authedPage` is test-scoped.
+
+### Which layer does this test belong to?
+
+Four layers run against this codebase, in cost order: **jest → Storybook + msw →
+pytest integration → Playwright**. Before writing an E2E, check the cheaper
+three. [`tests/e2e/AGENTS.md`](../../../tests/e2e/AGENTS.md) has the full rule;
+the short version:
+
+- A pure function, a reducer, a config literal or a component's own behaviour is
+ a **jest** test. Most containers under `frontend/src/container/` already have
+ one.
+- A rendered state that needs no backend (empty, error, loading) is a
+ **Storybook** story or a jest test with a fixed mock.
+- Anything the **API** does — ordering, pagination, filter semantics, validation,
+ roll-ups — is a pytest integration test, and for infra monitoring and alert
+ evaluation it very likely already exists. Grep `tests/integration/` first.
+- An **E2E** is for a real response reaching a real DOM: URL and history, write
+ paths that must persist, cross-page navigation, and one seeded proof per
+ surface.
Each spec follows these principles:
1. **Directory per feature**: `tests/e2e/tests/<feature>/*.spec.ts`. Cross-resource junction concerns (e.g. cascade-delete) go in their own file, not packed into one giant spec.
2. **Test titles use `TC-NN`**: `test('TC-01 alerts page — tabs render', ...)`. Preserves ordering at a glance and maps to external coverage tracking.
-3. **UI-first**: drive flows through the UI. Playwright traces capture every BE request/response the UI triggers, so asserting on UI outcomes implicitly validates BE contracts. Reach for direct `page.request.*` only when the test's *purpose* is asserting a response contract (use `page.waitForResponse` on a UI click) or when a specific UI step is structurally flaky (e.g. Ant DatePicker calendar-cell indices) — and even then try UI first.
-4. **Self-contained state**: each spec seeds its own data and cleans up at suite teardown. The pytest harness creates a fresh stack with **zero** dashboards / alerts / etc. — never assume pre-existing data. Patterns, in order of preference:
- - **Driver `dispose`** — the driver tracks what it seeded and deletes it after the test, so the spec has no cleanup code. See `dashboards.seed(...)` in `tests/e2e/drivers/dashboards.ts`.
- - **Per-test seed + cleanup in `try / finally`** — small specs without a driver, where each test owns its data.
- - **Suite-level seed + `afterAll` teardown** — larger specs without a driver. One `test.afterAll(...)` deletes everything the suite seeded. See `tests/e2e/tests/llm-o11y/llm-pricing.spec.ts`. `test.beforeAll` / `test.afterAll` cannot use `authedPage` directly (it's test-scoped); use `newAdminContext(browser)` from `helpers/auth.ts` instead — it performs one fresh login per suite hook.
-5. **Seed via API when the UI flow is multi-step or brittle.** The frontend stores its JWT in `localStorage` under `AUTH_TOKEN`; `page.request.*` inherits the auth fixture's storage state. A typical pattern:
- ```ts
- const token = await page.evaluate(
- () => (globalThis as any).localStorage.getItem('AUTH_TOKEN') || '',
- );
- await page.request.post('/api/v1/dashboards', {
- data: { title: 'my-name', uploadedGrafana: false },
- headers: { Authorization: `Bearer ${token}` },
- });
- ```
- This is faster and more reliable than a multi-step UI seed. Reach for the UI flow only when the test's *purpose* is asserting that flow.
-6. **Reusable static data lives in `tests/e2e/testdata/`.** For example, `traces/large-trace.json` is a real trace that `loadLargeTrace` (in `helpers/trace-details.ts`) seeds for the trace-details tests.
+3. **UI-first**: drive flows through the UI. Playwright traces capture every BE request/response the UI triggers, so asserting on UI outcomes implicitly validates BE contracts. To assert a write, attach `page.waitForResponse` before the click, then reload and re-read from the server.
+4. **Self-contained state**: each spec seeds its own data, scopes its assertions to the names it seeded, and cleans up. The pytest harness creates a fresh stack with **zero** dashboards / alerts / etc. Names carry the worker index, so parallel workers never collide. Pick the scope from the list above.
+5. **Seed through the kit when the UI flow is not under test.** `apiDriver(page)` (`drivers/api.ts`) creates control-plane objects with the session's token, and the seeder takes telemetry. The JWT lives in `localStorage`, so a spec never improvises with `page.request.*`. Feature drivers wrap both (`dashboards.seed`, `alerts.seed.threshold`).
+6. **Reusable static data lives in `tests/e2e/testdata/`.** For example, `traces/large-trace.json` is POSTed to the seeder by `drivers/traces.ts`. Infra monitoring reads the integration suite's fixtures through `seedDataset` (`drivers/infra/seed.ts`) instead of keeping a copy, and asserts on what it returned.
+7. **Locate by testid, in the driver.** A missing testid is added to the product in the same change. Role, label and CSS lookups are a stopgap, converted as that code is touched; antd internals (`.ant-select-dropdown`) are the exception, since the markup is not ours.
## How to write an E2E test?
Create a new file `tests/e2e/tests/alerts/smoke.spec.ts`:
```typescript
-import { test, expect } from '../../fixtures/auth';
+import { ALERT_LIST_PAGE_SIZE, expect, test } from '../../drivers/alerts';
-test('TC-01 alerts page — tabs render', async ({ authedPage: page }) => {
- await page.goto('/alerts');
- await expect(page.getByRole('tab', { name: /alert rules/i })).toBeVisible();
- await expect(page.getByRole('tab', { name: /configuration/i })).toBeVisible();
+test('TC-01 seeded rules render and paginate', async ({ alerts, alertList }) => {
+ await alerts.list.goto({ search: alertList.namePrefix });
+ await expect(alerts.list.table.totalCount()).toContainText(`of ${alertList.count}`);
+ await expect(alerts.list.rows()).toHaveCount(ALERT_LIST_PAGE_SIZE);
});
```
-The `authedPage` fixture (from `tests/e2e/fixtures/auth.ts`) gives you a `Page` whose browser context is already authenticated as the admin user. First use per worker triggers one login; the resulting `storageState` is held in memory and reused for later requests.
+`alertList` is a worker-scoped seed: the rules exist before the test starts, are
+shared by every test in the worker that asks for them, and are deleted when the
+worker ends.
+
+The `authedPage` fixture (from `tests/e2e/drivers/kit.ts`, re-exported by every feature's `test`) gives you a `Page` whose browser context is already authenticated as the admin user. First use per worker triggers one login; the resulting `storageState` is held in memory and reused for later requests. Take it only when the driver genuinely does not cover what you need — navigation, `goBack`, `waitForResponse`, a second tab.
To run just this test (assuming the stack is up via `test_setup`):
@@ -213,52 +204,56 @@ cd tests/e2e
npx playwright test tests/alerts/smoke.spec.ts --project=chromium
```
-Here's a more comprehensive example that exercises a CRUD flow via the UI:
+Here's a more comprehensive example, driven entirely through the feature's
+driver:
```typescript
-import { test, expect } from '../../fixtures/auth';
-
-test.describe.configure({ mode: 'serial' });
-
-test('TC-02 alerts list — create, toggle, delete', async ({ authedPage: page }) => {
- await page.goto('/alerts?tab=AlertRules');
- const name = 'smoke-rule';
-
- // Seed via UI — click "New Alert", fill form, save.
- await page.getByRole('button', { name: /new alert/i }).click();
- await page.getByTestId('alert-name-input').fill(name);
- // ... fill metric / threshold / save ...
-
- // Find the row and exercise the action menu.
- const row = page.locator('tr', { hasText: name });
- await expect(row).toBeVisible();
- await row.locator('[data-testid="alert-actions"] button').first().click();
-
- // waitForResponse captures the network call the UI triggers — no parallel fetch needed.
- const patchWait = page.waitForResponse(
- (r) => r.url().includes('/rules/') && r.request().method() === 'PATCH',
- );
- await page.getByRole('menuitem').filter({ hasText: /^disable$/i }).click();
- await patchWait;
- await expect(row).toContainText(/disabled/i);
+import { expect, test } from '../../drivers/alerts';
+
+test('TC-02 row actions persist: disable, then enable', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+}) => {
+ const name = `smoke-rule-${Date.now()}`;
+ const ruleId = await ownedRules.threshold(name);
+
+ await alerts.list.goto({ search: name });
+ await expect(alerts.list.stateCell(ruleId)).toHaveText('OK');
+
+ await alerts.list.openFirstRowActions();
+ await Promise.all([
+ // waitForResponse captures the call the UI triggers — no parallel fetch.
+ page.waitForResponse(
+ (res) =>
+ res.url().includes(`/api/v2/rules/${ruleId}`) &&
+ res.request().method() === 'PATCH',
+ ),
+ alerts.list.menuItem('Disable').click(),
+ ]);
+
+ // Re-read from the server rather than trusting the optimistic update.
+ await page.reload();
+ await expect(alerts.list.stateCell(ruleId)).toHaveText('Disabled');
});
```
-### Locator priority
+`ownedRules` is a test-scoped seed: every rule it creates is deleted when the
+test finishes, so the spec owns its data and nothing leaks into the next one.
+
+### Commits
-1. `getByTestId('...')` — preferred when the source exposes one. Stable, app-author-provided handle that survives copy-edits.
-2. `getByRole('button', { name: 'Submit' })`
-3. `getByLabel('Email')`
-4. `getByPlaceholder('...')`
-5. `getByText('...')`
-6. `locator('.ant-select')` — last resort (Ant Design dropdowns often have no semantic alternative)
+Commit driver changes apart from specs, product testids and tests moved to
+another layer, so each commit can be reviewed on its own.
+[`tests/e2e/AGENTS.md`](../../../tests/e2e/AGENTS.md#commits) has the order.
+`pnpm typecheck`, `pnpm lint` and `pnpm fmt:check` gate the suite.
## Agents
Three Claude agents in `.claude/agents/` accelerate writing and maintaining E2E specs:
- **`playwright-test-planner`** — explores a feature in a real browser plus the local frontend source and writes a test plan as a scratch markdown file (under `tests/e2e/specs/`, which is gitignored — plans are working artifacts for the generator, not committed docs).
-- **`playwright-test-generator`** — converts a test plan into Playwright spec files under `tests/e2e/tests/<feature>/`. Drives each scenario through MCP browser tools and emits TC-NN-titled tests using the `authedPage` fixture and the API-seed pattern.
+- **`playwright-test-generator`** — converts a test plan into Playwright spec files under `tests/e2e/tests/<feature>/`. Drives each scenario through MCP browser tools and emits TC-NN-titled tests on the feature's driver, adding the driver methods and seeds the plan needs.
- **`playwright-test-healer`** — runs failing specs, debugs them with snapshots / console / network introspection, and edits the spec to fix selector drift, timing, or state-leak issues.
The agents rely on the Playwright-test MCP server (`mcp__playwright-test__*` tools). Configure it in your Claude MCP settings; the permission allowlist lives in [.claude/settings.local.json](../../../.claude/settings.local.json).
@@ -270,15 +265,15 @@ The agents rely on the Playwright-test MCP server (`mcp__playwright-test__*` too
With the stack already up, from `tests/e2e/`:
```bash
-yarn test # headless, all projects
+pnpm test # headless, all projects
```
### Running Specific Projects
```bash
-yarn test:chromium # chromium only
-yarn test:firefox
-yarn test:webkit
+pnpm test:chromium # chromium only
+pnpm test:firefox
+pnpm test:webkit
```
### Running Specific Tests
@@ -296,17 +291,17 @@ npx playwright test tests/alerts/history/ --project=chromium
npx playwright test tests/alerts/page.spec.ts --project=chromium
# Single test by title grep
-npx playwright test --project=chromium -g "AL-01"
+npx playwright test --project=chromium -g "TC-01"
```
### Iterative modes
```bash
-yarn test:ui # Playwright UI mode — watch + step through
-yarn test:headed # headed browser
-yarn test:debug # Playwright inspector, pause-on-breakpoint
-yarn codegen # record-and-replay locator generation
-yarn report # open the last HTML report (artifacts/html)
+pnpm test:ui # Playwright UI mode — watch + step through
+pnpm test:headed # headed browser
+pnpm test:debug # Playwright inspector, pause-on-breakpoint
+pnpm codegen # record-and-replay locator generation
+pnpm report # open the last HTML report (artifacts/html)
```
### Staging fallback
@@ -316,7 +311,7 @@ Point `SIGNOZ_E2E_BASE_URL` at a remote env via `.env` — no local backend brin
```bash
cd tests/e2e
cp .env.example .env # fill SIGNOZ_E2E_USERNAME / PASSWORD
-yarn test:staging
+pnpm test:staging
```
## How to configure different options for E2E tests?
@@ -364,12 +359,14 @@ The same pytest flags integration tests expose work here, since E2E reuses the s
- **Always use the `--reuse` flag** when setting up the E2E stack. `--with-web` adds a ~4 min frontend build on a cold start; later builds are incremental.
- **Changed backend or frontend code? Re-run the setup command** — it passes `--rebuild`, swapping the SigNoz container for one built from your current sources while the rest of the stack stays up.
- **Don't teardown before setup.** `--reuse` correctly handles partially-set-up state, so chaining teardown → setup wastes time.
-- **Prefer UI-driven flows.** Playwright captures BE requests in the trace; a parallel `fetch` probe is almost always redundant. Drop to `page.request.*` only when the UI can't reach what you need.
+- **Prefer UI-driven flows.** Playwright captures BE requests in the trace; a parallel `fetch` probe is almost always redundant. Seed through the kit, never with `page.request.*`.
- **Use `page.waitForResponse` on UI clicks** to assert BE contracts — it still exercises the UI trigger path.
- **Title every test `TC-NN <short description>`** — keeps the suite navigable and reportable.
- **Split by resource, not by regression suite.** One spec per feature resource; cross-resource junction concerns (cascade-delete, linked-edit) get their own file.
-- **Use short descriptive resource names** (`alerts-list-rule`, `labels-rule`, `downtime-once`) — no timestamp disambiguation. Each test owns its resources and cleans up in `try/finally`.
+- **Name resources by what they are, plus the worker index** (`e2e-alert-list-w${workerIndex}-${Date.now()}`). Six workers share one stack, so assert only on names you seeded.
- **Never commit `test.only`** — a pre-commit check or CI runs with `forbidOnly: true`.
- **Prefer explicit waits over `page.waitForTimeout(ms)`.** `await expect(locator).toBeVisible()` is always better than `waitForTimeout(5000)`.
- **Unique test names won't save you from shared-tenant state.** When two tests hit the same list page, either serialize (`describe.configure({ mode: 'serial' })`) or isolate cleanup religiously.
+- **Green locally, red on CI?** Run `STRESS=1 CI=1 pnpm test <path>` (4x CPU throttle, 2 workers, 2 retries) before filing a product bug.
+- **Commit drivers apart from specs.** One concern per commit; see [Commits](#commits).
- **Artifacts go to `tests/e2e/artifacts/`** — HTML report at `artifacts/html`, traces at `artifacts/results/<test>/`. All gitignored; archive the dir in CI.
diff --git a/frontend/src/components/Alerts/LabelColumn/LabelColumn.test.tsx b/frontend/src/components/Alerts/LabelColumn/LabelColumn.test.tsx
index bd89b1c1c7..5b82162ede 100644
--- a/frontend/src/components/Alerts/LabelColumn/LabelColumn.test.tsx
+++ b/frontend/src/components/Alerts/LabelColumn/LabelColumn.test.tsx
@@ -2,6 +2,13 @@ import { act, render, screen } from '@testing-library/react';
import LabelColumn from './LabelColumn';
+// The global CSS mock maps every class to undefined; keep the names so overflow is assertable.
+jest.mock('./LabelColumn.module.scss', () => ({
+ labelColumn: 'labelColumn',
+ overflowed: 'overflowed',
+ shrinkable: 'shrinkable',
+}));
+
const BADGE_WIDTH = 60;
let resizeCallbacks: ResizeObserverCallback[] = [];
@@ -77,6 +84,20 @@ describe('LabelColumn', () => {
expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
});
+ it('should hide the labels past the visible count', () => {
+ const labels = ['env', 'service', 'region', 'team', 'owner', 'version'];
+
+ // 3 badges (180px) + overflow reserve (40px)
+ mockLayout(220);
+ renderWithProviders(<LabelColumn labels={labels} />);
+
+ const isHidden = (label: string): boolean =>
+ screen.getByTestId(`label-tag-${label}`).closest('.overflowed') !== null;
+
+ expect(labels.filter(isHidden)).toStrictEqual(['team', 'owner', 'version']);
+ expect(screen.getByTestId('label-overflow-badge')).toHaveTextContent('+3');
+ });
+
it('should render label with value when value prop provided', () => {
const labels = ['env'];
const value = { env: 'production' };
diff --git a/frontend/src/components/AuthError/AuthError.tsx b/frontend/src/components/AuthError/AuthError.tsx
index dab8dbc0ae..bdbc34fa0d 100644
--- a/frontend/src/components/AuthError/AuthError.tsx
+++ b/frontend/src/components/AuthError/AuthError.tsx
@@ -10,7 +10,7 @@ interface AuthErrorProps {
function AuthError({ error }: AuthErrorProps): JSX.Element {
return (
- <div className="auth-error-container">
+ <div className="auth-error-container" data-testid="auth-error">
<ErrorContent
error={error}
icon={<CircleAlert size={12} className="auth-error-icon" />}
diff --git a/frontend/src/components/CeleryOverview/CeleryOverviewTable/CeleryOverviewTable.tsx b/frontend/src/components/CeleryOverview/CeleryOverviewTable/CeleryOverviewTable.tsx
index 6974627b0e..4226154dc4 100644
--- a/frontend/src/components/CeleryOverview/CeleryOverviewTable/CeleryOverviewTable.tsx
+++ b/frontend/src/components/CeleryOverview/CeleryOverviewTable/CeleryOverviewTable.tsx
@@ -512,6 +512,7 @@ export default function CeleryOverviewTable({
allowClear
/>
<ResizeTable
+ data-testid="mq-overview-table"
className="celery-overview-table"
pagination={paginationConfig}
size="middle"
diff --git a/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx b/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx
index 2f7805a614..3371545396 100644
--- a/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx
+++ b/frontend/src/components/CeleryTask/CeleryTaskConfigOptions/CeleryTaskConfigOptions.tsx
@@ -28,6 +28,7 @@ function CeleryTaskConfigOptions(): JSX.Element {
Task Name
</Typography.Text>
<Select
+ data-testid="celery-task-name-select"
placeholder="Task Name"
showSearch
mode="multiple"
diff --git a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraphGrid.tsx b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraphGrid.tsx
index a70bc36157..a1aab57f86 100644
--- a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraphGrid.tsx
+++ b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskGraphGrid.tsx
@@ -105,7 +105,10 @@ export default function CeleryTaskGraphGrid({
};
return (
- <div className="celery-task-graph-grid-container">
+ <div
+ className="celery-task-graph-grid-container"
+ data-testid="celery-graph-grid"
+ >
<div className="metric-based-graphs">
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<div className="row-panel">
diff --git a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskStateGraphConfig.tsx b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskStateGraphConfig.tsx
index bf08866886..c44d4f9cce 100644
--- a/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskStateGraphConfig.tsx
+++ b/frontend/src/components/CeleryTask/CeleryTaskGraph/CeleryTaskStateGraphConfig.tsx
@@ -80,6 +80,7 @@ function CeleryTaskStateGraphConfig({
{tabs.map((tab, index) => (
<Col
key={tab.key}
+ data-testid={`celery-state-tab-${tab.key}`}
onClick={(): void => handleTabClick(tab.key as CeleryTaskState)}
className={`celery-task-states__tab ${
tab.key === barState ? 'celery-task-states__tab--selected' : ''
diff --git a/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx b/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
index 41861a5938..003322eb02 100644
--- a/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
+++ b/frontend/src/components/CustomTimePicker/CustomTimePickerPopoverContent.tsx
@@ -251,6 +251,7 @@ function CustomTimePickerPopoverContent({
<Button
className={cx('data-time-live', isLiveLogsEnabled ? 'active' : '')}
type="text"
+ data-testid="time-picker-live"
onClick={handleGoLive}
>
Live
diff --git a/frontend/src/components/CustomTimePicker/TimezonePicker.tsx b/frontend/src/components/CustomTimePicker/TimezonePicker.tsx
index ff51a90031..bd0b694c52 100644
--- a/frontend/src/components/CustomTimePicker/TimezonePicker.tsx
+++ b/frontend/src/components/CustomTimePicker/TimezonePicker.tsx
@@ -88,6 +88,7 @@ function TimezoneItem({
return (
<button
type="button"
+ data-testid={`timezone-item-${timezone.value}`}
className={cx('timezone-picker__item', {
selected: isSelected,
'has-divider': timezone.hasDivider,
diff --git a/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.test.tsx b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.test.tsx
index 535c8b37c0..059be064ec 100644
--- a/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.test.tsx
+++ b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.test.tsx
@@ -1,6 +1,7 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import { message } from 'antd';
import configureStore from 'redux-mock-store';
import store from 'store';
@@ -194,6 +195,23 @@ describe.each([
});
});
+ it('sends the chosen jsonl format and 30k row limit', async () => {
+ renderWithStore(dataSource);
+ await userEvent.click(screen.getByTestId(testId));
+ await userEvent.click(screen.getByRole('radio', { name: 'jsonl' }));
+ await userEvent.click(screen.getByRole('radio', { name: '30k' }));
+ await userEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(mockDownloadExportData).toHaveBeenCalledTimes(1);
+ });
+ const callArgs = mockDownloadExportData.mock.calls[0][0];
+ expect(callArgs.format).toBe(DownloadFormats.JSONL);
+ expect(callArgs.body.compositeQuery.queries[0].spec.limit).toBe(
+ DownloadRowCounts.THIRTY_K,
+ );
+ });
+
it('clears groupBy and having in the export payload', async () => {
const mockQuery = createMockStagedQuery(dataSource);
mockQuery.builder.queryData[0].groupBy = [
diff --git a/frontend/src/components/EditMemberDrawer/DeleteMemberDialog.tsx b/frontend/src/components/EditMemberDrawer/DeleteMemberDialog.tsx
index c95e4d9bbd..21f556a1e4 100644
--- a/frontend/src/components/EditMemberDrawer/DeleteMemberDialog.tsx
+++ b/frontend/src/components/EditMemberDrawer/DeleteMemberDialog.tsx
@@ -52,6 +52,7 @@ function DeleteMemberDialog({
variant="solid"
color="danger"
onClick={onConfirm}
+ testId="member-delete-confirm-btn"
loading={isDeleting}
prefix={<Trash2 size={12} />}
>
diff --git a/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx b/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx
index 36fb0bc8ee..c9ce4ac1b7 100644
--- a/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx
+++ b/frontend/src/components/EditMemberDrawer/EditMemberDrawer.tsx
@@ -624,6 +624,7 @@ function EditMemberDrawer({
disabledTooltip={getDeleteTooltip(isRootUser, isSelf)}
size="md"
onClick={(): void => setShowDeleteConfirm(true)}
+ testId="member-delete-btn"
disabled={isRootUser || isSelf}
variant="link"
color="danger"
@@ -637,6 +638,7 @@ function EditMemberDrawer({
disabledTooltip={ROOT_USER_TOOLTIP}
size="md"
onClick={handleGenerateResetLink}
+ testId="member-reset-link-btn"
disabled={isRootUser}
loading={isGeneratingLink || isLoadingTokenStatus}
variant="link"
@@ -674,6 +676,7 @@ function EditMemberDrawer({
color="primary"
disabled={!isDirty || isRootUser}
onClick={handleSave}
+ testId="member-save-btn"
loading={isSaving}
>
{isSaving ? 'Saving...' : 'Save Member Details'}
diff --git a/frontend/src/components/EditMemberDrawer/ResetLinkDialog.tsx b/frontend/src/components/EditMemberDrawer/ResetLinkDialog.tsx
index 516d55868a..3f29890e5c 100644
--- a/frontend/src/components/EditMemberDrawer/ResetLinkDialog.tsx
+++ b/frontend/src/components/EditMemberDrawer/ResetLinkDialog.tsx
@@ -42,7 +42,12 @@ function ResetLinkDialog({
</p>
<div className="reset-link-dialog__link-row">
<div className="reset-link-dialog__link-text-wrap">
- <span className="reset-link-dialog__link-text">{resetLink}</span>
+ <span
+ className="reset-link-dialog__link-text"
+ data-testid="reset-link-text"
+ >
+ {resetLink}
+ </span>
</div>
<Button
size="md"
diff --git a/frontend/src/components/ExportMenu/__tests__/ExportMenu.test.tsx b/frontend/src/components/ExportMenu/__tests__/ExportMenu.test.tsx
index f0fa07371a..1a90283983 100644
--- a/frontend/src/components/ExportMenu/__tests__/ExportMenu.test.tsx
+++ b/frontend/src/components/ExportMenu/__tests__/ExportMenu.test.tsx
@@ -1,5 +1,5 @@
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
-import { fireEvent, render, screen } from 'tests/test-utils';
+import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import ExportMenu from '../ExportMenu';
@@ -76,6 +76,17 @@ describe('ExportMenu', () => {
expect(mockHandleExport).toHaveBeenCalledWith({ format: 'jsonl' });
});
+ it('exports the picked jsonl format and closes the popover', async () => {
+ renderMenu();
+ await userEvent.click(screen.getByTestId(TEST_ID));
+ await userEvent.click(screen.getByRole('radio', { name: 'jsonl' }));
+ await userEvent.click(screen.getByRole('button', { name: 'Export' }));
+
+ expect(mockHandleExport).toHaveBeenCalledTimes(1);
+ expect(mockHandleExport).toHaveBeenCalledWith({ format: 'jsonl' });
+ expect(screen.queryByText('FORMAT')).not.toBeInTheDocument();
+ });
+
it('disables the trigger while an export is in progress', () => {
mockIsExporting = true;
renderMenu();
diff --git a/frontend/src/components/LogDetail/index.tsx b/frontend/src/components/LogDetail/index.tsx
index f6cd93bf62..69853c4ac7 100644
--- a/frontend/src/components/LogDetail/index.tsx
+++ b/frontend/src/components/LogDetail/index.tsx
@@ -308,7 +308,11 @@ function LogDetailInner({
placement="left"
mouseLeaveDelay={0}
>
- <div className="log-body" dangerouslySetInnerHTML={htmlBody} />
+ <div
+ className="log-body"
+ data-testid="log-detail-body"
+ dangerouslySetInnerHTML={htmlBody}
+ />
</Tooltip>
<div className="log-overflow-shadow">&nbsp;</div>
diff --git a/frontend/src/components/Logs/ListLogView/index.tsx b/frontend/src/components/Logs/ListLogView/index.tsx
index d597817fb7..97d9004e62 100644
--- a/frontend/src/components/Logs/ListLogView/index.tsx
+++ b/frontend/src/components/Logs/ListLogView/index.tsx
@@ -182,6 +182,7 @@ function ListLogView({
return (
<>
<Container
+ data-testid={`logs-list-row-${logData.id}`}
$isActiveLog={isHighlighted || activeLog?.id === logData.id}
$isDarkMode={isDarkMode}
$logType={logType}
diff --git a/frontend/src/components/Logs/LogLinesActionButtons/LogLinesActionButtons.tsx b/frontend/src/components/Logs/LogLinesActionButtons/LogLinesActionButtons.tsx
index 8d148e92d4..0f4d71f54c 100644
--- a/frontend/src/components/Logs/LogLinesActionButtons/LogLinesActionButtons.tsx
+++ b/frontend/src/components/Logs/LogLinesActionButtons/LogLinesActionButtons.tsx
@@ -23,6 +23,7 @@ function LogLinesActionButtons({
icon={<TextSelect size={14} />}
className="show-context-btn"
onClick={handleShowContext}
+ data-testid="log-line-show-context"
/>
</Tooltip>
<Tooltip title="Copy Link">
@@ -31,6 +32,7 @@ function LogLinesActionButtons({
icon={<Link size={14} />}
onClick={onLogCopy}
className="copy-log-btn"
+ data-testid="log-line-copy-link"
/>
</Tooltip>
</div>
diff --git a/frontend/src/components/Logs/RawLogView/index.tsx b/frontend/src/components/Logs/RawLogView/index.tsx
index a488b47822..9c436396ac 100644
--- a/frontend/src/components/Logs/RawLogView/index.tsx
+++ b/frontend/src/components/Logs/RawLogView/index.tsx
@@ -156,6 +156,7 @@ function RawLogView({
return (
<RawLogViewContainer
+ data-testid={`logs-raw-row-${data.id}`}
onClick={handleClickExpand}
wrap={false}
align="middle"
diff --git a/frontend/src/components/LogsFormatOptionsMenu/LogsFormatOptionsMenu.tsx b/frontend/src/components/LogsFormatOptionsMenu/LogsFormatOptionsMenu.tsx
index 8fc85d14ed..fcafe3ce2f 100644
--- a/frontend/src/components/LogsFormatOptionsMenu/LogsFormatOptionsMenu.tsx
+++ b/frontend/src/components/LogsFormatOptionsMenu/LogsFormatOptionsMenu.tsx
@@ -182,6 +182,7 @@ function OptionsMenu({
<div
className="item"
key={item.label}
+ data-testid={`format-option-${item.key}`}
onClick={(): void => handleMenuItemClick(item.key)}
>
<div className={cx('item-label')}>
diff --git a/frontend/src/components/MarkdownEditor/__tests__/InsertVariableMenu.test.tsx b/frontend/src/components/MarkdownEditor/__tests__/InsertVariableMenu.test.tsx
new file mode 100644
index 0000000000..d29e06559d
--- /dev/null
+++ b/frontend/src/components/MarkdownEditor/__tests__/InsertVariableMenu.test.tsx
@@ -0,0 +1,72 @@
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+
+import { READ_ONLY_TOOLTIP } from '../constants';
+import InsertVariableMenu from '../InsertVariableMenu';
+import type { EditorVariable } from '../types';
+
+const VARIABLES: EditorVariable[] = [
+ { name: 'environment', badge: 'QUERY' },
+ { name: 'service', badge: 'CUSTOM' },
+ { name: 'service_version' },
+];
+
+function renderMenu(disabled = false): jest.Mock {
+ const onSelect = jest.fn();
+ render(
+ <InsertVariableMenu
+ variables={VARIABLES}
+ onSelect={onSelect}
+ disabled={disabled}
+ />,
+ );
+ return onSelect;
+}
+
+function rowNames(): string[] {
+ return screen
+ .queryAllByTestId(/^markdown-variable-/)
+ .map((row) => row.getAttribute('data-testid') ?? '');
+}
+
+describe('InsertVariableMenu', () => {
+ it('narrows the rows to names matching the search', async () => {
+ renderMenu();
+ await userEvent.click(screen.getByTestId('markdown-insert-variable'));
+ await screen.findByTestId('markdown-variable-environment');
+ expect(rowNames()).toHaveLength(3);
+
+ await userEvent.type(screen.getByPlaceholderText('Search variables'), 'SERV');
+
+ await waitFor(() =>
+ expect(rowNames()).toStrictEqual([
+ 'markdown-variable-service',
+ 'markdown-variable-service_version',
+ ]),
+ );
+ });
+
+ it('hands the clicked variable name to onSelect', async () => {
+ const onSelect = renderMenu();
+ await userEvent.click(screen.getByTestId('markdown-insert-variable'));
+ await userEvent.click(await screen.findByTestId('markdown-variable-service'));
+
+ expect(onSelect).toHaveBeenCalledTimes(1);
+ expect(onSelect).toHaveBeenCalledWith('service');
+ });
+
+ it('stays closed and explains why when read-only', async () => {
+ const onSelect = renderMenu(true);
+ const trigger = screen.getByTestId('markdown-insert-variable');
+ expect(trigger).toHaveAttribute('aria-disabled', 'true');
+
+ await userEvent.click(trigger);
+ expect(screen.queryByRole('menu')).not.toBeInTheDocument();
+ expect(rowNames()).toHaveLength(0);
+
+ await userEvent.hover(trigger);
+ await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
+ READ_ONLY_TOOLTIP,
+ );
+ expect(onSelect).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsx b/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsx
index cb0767acf2..bb9f8ad485 100644
--- a/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsx
+++ b/frontend/src/components/NewSelect/__test__/CustomMultiSelect.comprehensive.test.tsx
@@ -1,5 +1,5 @@
import { VirtuosoMockContext } from 'react-virtuoso';
-import { render, screen, waitFor } from '@testing-library/react';
+import { render, screen, waitFor, within } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import CustomMultiSelect from '../CustomMultiSelect';
@@ -678,6 +678,64 @@ describe('CustomMultiSelect - Comprehensive Tests', () => {
expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['backend']);
});
+ it('UI-03c: clicking an option checkbox toggles it exactly once', async () => {
+ renderWithVirtuoso(
+ <CustomMultiSelect
+ options={mockOptions}
+ onChange={mockOnChange}
+ value={['frontend']}
+ />,
+ );
+
+ await user.click(screen.getByRole('combobox'));
+ const backendRow = (await screen.findByText('Backend')).closest(
+ '[role="option"]',
+ ) as HTMLElement;
+ mockOnChange.mockClear();
+ await user.click(within(backendRow).getByRole('checkbox'));
+
+ expect(mockOnChange).toHaveBeenCalledTimes(1);
+ expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['frontend', 'backend']);
+ });
+
+ it('UI-03d: clicking an option label toggles it exactly once', async () => {
+ renderWithVirtuoso(
+ <CustomMultiSelect
+ options={mockOptions}
+ onChange={mockOnChange}
+ value={['frontend']}
+ />,
+ );
+
+ await user.click(screen.getByRole('combobox'));
+ const backendLabel = await screen.findByText('Backend');
+ mockOnChange.mockClear();
+ await user.click(backendLabel);
+
+ expect(mockOnChange).toHaveBeenCalledTimes(1);
+ expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['frontend', 'backend']);
+ });
+
+ it('UI-03e: clicking "Toggle" does not also toggle the wrapping checkbox', async () => {
+ renderWithVirtuoso(
+ <CustomMultiSelect
+ options={mockOptions}
+ onChange={mockOnChange}
+ value={['frontend', 'backend']}
+ />,
+ );
+
+ await user.click(screen.getByRole('combobox'));
+ const backendRow = (await screen.findByText('Backend')).closest(
+ '[role="option"]',
+ ) as HTMLElement;
+ mockOnChange.mockClear();
+ await user.click(within(backendRow).getByText('Toggle'));
+
+ expect(mockOnChange).toHaveBeenCalledTimes(1);
+ expect(mockOnChange.mock.calls[0][0]).toStrictEqual(['frontend']);
+ });
+
it('UI-04: Should display values with loading info at bottom', async () => {
renderWithVirtuoso(
<CustomMultiSelect options={mockOptions} onChange={mockOnChange} loading />,
diff --git a/frontend/src/components/OrderBy/ListViewOrderBy.tsx b/frontend/src/components/OrderBy/ListViewOrderBy.tsx
index ea498ead46..2b8f2ddb2e 100644
--- a/frontend/src/components/OrderBy/ListViewOrderBy.tsx
+++ b/frontend/src/components/OrderBy/ListViewOrderBy.tsx
@@ -112,6 +112,7 @@ function ListViewOrderBy({
placeholder="Select a field"
style={{ width: 200 }}
options={selectOptions}
+ data-testid="list-view-order-by"
filterOption={(input, option): boolean =>
(option?.value ?? '').toLowerCase().includes(input.trim().toLowerCase())
}
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QueryV2.test.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QueryV2.test.tsx
index 101e62511c..831f7963f2 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QueryV2.test.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/__tests__/QueryV2.test.tsx
@@ -1,9 +1,12 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { jest } from '@jest/globals';
import { fireEvent, waitFor } from '@testing-library/react';
+import { ENVIRONMENT } from 'constants/env';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
import { render, screen, userEvent } from 'tests/test-utils';
import {
Having,
@@ -53,6 +56,15 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
let baseQBContext: QueryBuilderContextType;
beforeEach(() => {
+ server.use(
+ rest.get(`${ENVIRONMENT.baseURL}/api/v1/fields/keys`, (_req, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({ status: 'success', data: { complete: true, keys: {} } }),
+ ),
+ ),
+ );
+
const mockCloneQuery = jest.fn() as jest.MockedFunction<
(type: string, q: IBuilderQuery) => void
>;
@@ -235,6 +247,71 @@ describe('QueryBuilderV2 + QueryV2 - base render', () => {
).not.toBeInTheDocument();
});
+ describe('query actions menu', () => {
+ const openQueryActions = async (): Promise<void> => {
+ const trigger = document.querySelector(
+ '.query-actions-container [aria-haspopup="menu"]',
+ ) as HTMLElement;
+ expect(trigger).toBeInTheDocument();
+ await userEvent.click(trigger);
+ };
+
+ it('Clone calls cloneQuery with the query', async () => {
+ render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
+
+ await openQueryActions();
+ await userEvent.click(
+ await screen.findByRole('menuitem', { name: 'Clone' }),
+ );
+
+ expect(baseQBContext.cloneQuery).toHaveBeenCalledTimes(1);
+ expect(baseQBContext.cloneQuery).toHaveBeenCalledWith(
+ 'query',
+ expect.objectContaining({ queryName: 'A' }),
+ );
+ });
+
+ it('hides Delete when there is a single query', async () => {
+ render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
+
+ await openQueryActions();
+ await screen.findByRole('menuitem', { name: 'Clone' });
+
+ expect(
+ screen.queryByRole('menuitem', { name: 'Delete' }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('shows Delete with more than one query and deletes on click', async () => {
+ const currentQueryBase = baseQBContext.currentQuery as Query;
+ const [queryA] = currentQueryBase.builder.queryData;
+ mockedUseQueryBuilder.mockReturnValue({
+ ...baseQBContext,
+ currentQuery: {
+ ...currentQueryBase,
+ builder: {
+ ...currentQueryBase.builder,
+ queryData: [queryA, { ...queryA, queryName: 'B', legend: 'B' }],
+ },
+ },
+ });
+ const handleDeleteQuery = jest.fn();
+ mockedUseQueryOperations.mockReturnValue({
+ ...mockedUseQueryOperations({} as Parameters<UseQueryOperations>[0]),
+ handleDeleteQuery,
+ });
+
+ render(<QueryBuilderV2 panelType={PANEL_TYPES.TABLE} version="v4" />);
+
+ await openQueryActions();
+ await userEvent.click(
+ await screen.findByRole('menuitem', { name: 'Delete' }),
+ );
+
+ expect(handleDeleteQuery).toHaveBeenCalledTimes(1);
+ });
+ });
+
it('fx button is disabled when functions already exist', () => {
const currentQueryBase = baseQBContext.currentQuery as Query;
const supersetQueryBase = baseQBContext.supersetQuery as Query;
diff --git a/frontend/src/components/QuickFilters/FilterRenderers/Checkbox/v2/CheckboxFilterV2.tsx b/frontend/src/components/QuickFilters/FilterRenderers/Checkbox/v2/CheckboxFilterV2.tsx
index 5ef9fd2c33..94867fd14f 100644
--- a/frontend/src/components/QuickFilters/FilterRenderers/Checkbox/v2/CheckboxFilterV2.tsx
+++ b/frontend/src/components/QuickFilters/FilterRenderers/Checkbox/v2/CheckboxFilterV2.tsx
@@ -183,7 +183,11 @@ export default function CheckboxFilterV2(
wasSearchShown.current = isSearchShown;
return (
- <div className={styles.checkboxFilter} data-testid="checkbox-filter-v2">
+ <div
+ className={styles.checkboxFilter}
+ data-testid="checkbox-filter-v2"
+ data-filter-key={filter.attributeKey.key}
+ >
<CheckboxFilterV2Header
title={filter.title}
isOpen={isOpen}
diff --git a/frontend/src/components/ServiceAccountDrawer/AddKeyModal/KeyCreatedPhase.tsx b/frontend/src/components/ServiceAccountDrawer/AddKeyModal/KeyCreatedPhase.tsx
index db7f9b34c3..85977e4db4 100644
--- a/frontend/src/components/ServiceAccountDrawer/AddKeyModal/KeyCreatedPhase.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/AddKeyModal/KeyCreatedPhase.tsx
@@ -22,7 +22,9 @@ function KeyCreatedPhase({
<div className="add-key-modal__field">
<span className="add-key-modal__label">Key</span>
<div className="add-key-modal__key-display">
- <span className="add-key-modal__key-text">{createdKey.key}</span>
+ <span className="add-key-modal__key-text" data-testid="created-key-value">
+ {createdKey.key}
+ </span>
<Button
size="md"
variant="link"
diff --git a/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx b/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx
index 1a3917b7c4..94fb81c125 100644
--- a/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/RevokeKeyModal.tsx
@@ -61,6 +61,7 @@ export function RevokeKeyFooter({
color="danger"
loading={isRevoking}
onClick={onConfirm}
+ testId="revoke-key-confirm-btn"
prefix={<Trash2 size={12} />}
>
Revoke Key
diff --git a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
index cf2b8845b0..a9993b41b2 100644
--- a/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
+++ b/frontend/src/components/ServiceAccountDrawer/ServiceAccountDrawer.tsx
@@ -384,6 +384,7 @@ function ServiceAccountDrawer({
void setIsDeleteOpen(true);
}}
prefix={<Trash2 size={12} />}
+ testId="sa-delete-btn"
>
Delete Service Account
</AuthZButton>
@@ -409,6 +410,7 @@ function ServiceAccountDrawer({
loading={isSaving}
disabled={!isDirty}
onClick={handleSave}
+ testId="sa-save-btn"
>
Save Changes
</AuthZButton>
@@ -437,6 +439,7 @@ function ServiceAccountDrawer({
type="single"
value={activeTab}
size="sm"
+ testId="sa-tab"
onChange={(val: string): void => {
if (val) {
void setActiveTab(val as ServiceAccountDrawerTab);
@@ -478,6 +481,7 @@ function ServiceAccountDrawer({
void setIsAddKeyOpen(true);
}}
prefix={<Plus size={12} />}
+ testId="sa-add-key-btn"
>
Add Key
</AuthZButton>
diff --git a/frontend/src/components/TanStackTableView/__tests__/useColumnStore.test.ts b/frontend/src/components/TanStackTableView/__tests__/useColumnStore.test.ts
index 0c8ac69147..c5b30625c0 100644
--- a/frontend/src/components/TanStackTableView/__tests__/useColumnStore.test.ts
+++ b/frontend/src/components/TanStackTableView/__tests__/useColumnStore.test.ts
@@ -263,6 +263,33 @@ describe('useColumnStore', () => {
expect(result.current).toBe(firstSnapshot);
});
+ it.each([
+ ['only hiddenColumnIds', { hiddenColumnIds: ['persisted'] }],
+ ['only columnOrder', { columnOrder: ['a', 'b'] }],
+ ['an empty object', {}],
+ ['a wrong-typed hiddenColumnIds', { hiddenColumnIds: 'nope' }],
+ ])(
+ 'normalises a persisted value carrying %s so selectors never yield undefined',
+ (_label, stored) => {
+ localStorage.setItem(
+ '@signoz/table-columns/test-table',
+ JSON.stringify(stored),
+ );
+
+ act(() => {
+ useColumnStore.getState().initializeFromDefaults(TEST_KEY, []);
+ });
+
+ const hidden = renderHook(() => useHiddenColumnIds(TEST_KEY));
+ const order = renderHook(() => useColumnOrder(TEST_KEY));
+ const sizing = renderHook(() => useColumnSizing(TEST_KEY));
+
+ expect(Array.isArray(hidden.result.current)).toBe(true);
+ expect(Array.isArray(order.result.current)).toBe(true);
+ expect(typeof sizing.result.current).toBe('object');
+ },
+ );
+
it('useColumnSizing returns sizing', () => {
act(() => {
useColumnStore.getState().initializeFromDefaults(TEST_KEY, []);
diff --git a/frontend/src/components/TanStackTableView/useColumnStore.ts b/frontend/src/components/TanStackTableView/useColumnStore.ts
index 0234c51d69..81b2777ef2 100644
--- a/frontend/src/components/TanStackTableView/useColumnStore.ts
+++ b/frontend/src/components/TanStackTableView/useColumnStore.ts
@@ -66,7 +66,19 @@ const loadTableFromStorage = (tableKey: string): ColumnState | null => {
return cached.parsed;
}
- const parsed = JSON.parse(raw) as ColumnState;
+ // Selectors read these fields directly, so a value persisted under an older
+ // schema must be filled in rather than handed to callers as `undefined`.
+ const stored = JSON.parse(raw) as Partial<ColumnState> | null;
+ const parsed: ColumnState = {
+ hiddenColumnIds: Array.isArray(stored?.hiddenColumnIds)
+ ? stored.hiddenColumnIds
+ : [],
+ columnOrder: Array.isArray(stored?.columnOrder) ? stored.columnOrder : [],
+ columnSizing:
+ stored?.columnSizing && typeof stored.columnSizing === 'object'
+ ? stored.columnSizing
+ : {},
+ };
persistedTableCache.set(tableKey, { raw, parsed });
return parsed;
} catch {
diff --git a/frontend/src/components/TimePreferenceDropDown/__tests__/TimePreferenceDropDown.test.tsx b/frontend/src/components/TimePreferenceDropDown/__tests__/TimePreferenceDropDown.test.tsx
new file mode 100644
index 0000000000..a8cf009bdf
--- /dev/null
+++ b/frontend/src/components/TimePreferenceDropDown/__tests__/TimePreferenceDropDown.test.tsx
@@ -0,0 +1,27 @@
+import { timeItems } from 'constants/timePreference';
+import { render, screen, userEvent } from 'tests/test-utils';
+
+import TimePreference from '../index';
+
+describe('TimePreferenceDropDown', () => {
+ it('calls setSelectedTime with the clicked item', async () => {
+ const setSelectedTime = jest.fn();
+ render(
+ <TimePreference
+ selectedTime={timeItems[0]}
+ setSelectedTime={setSelectedTime}
+ />,
+ );
+
+ await userEvent.click(screen.getByRole('button', { name: /Global Time/ }));
+ await userEvent.click(
+ await screen.findByRole('menuitem', { name: 'Last 15 min' }),
+ );
+
+ expect(setSelectedTime).toHaveBeenCalledTimes(1);
+ expect(setSelectedTime).toHaveBeenCalledWith({
+ name: 'Last 15 min',
+ enum: 'LAST_15_MIN',
+ });
+ });
+});
diff --git a/frontend/src/container/AIAssistant/components/ActionsSection/__tests__/ActionsSection.test.tsx b/frontend/src/container/AIAssistant/components/ActionsSection/__tests__/ActionsSection.test.tsx
new file mode 100644
index 0000000000..bc4ce1bbd5
--- /dev/null
+++ b/frontend/src/container/AIAssistant/components/ActionsSection/__tests__/ActionsSection.test.tsx
@@ -0,0 +1,83 @@
+import { undoExecution } from 'api/ai-assistant/chat';
+import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+import { MessageActionKindDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+
+import ActionsSection from '../ActionsSection';
+
+jest.mock('api/ai-assistant/chat', () => ({
+ undoExecution: jest.fn(),
+ revertExecution: jest.fn(),
+ restoreExecution: jest.fn(),
+}));
+jest.mock('api/common/logEvent', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+const mockUndo = undoExecution as jest.MockedFunction<typeof undoExecution>;
+
+const UNDO_ACTION = {
+ kind: MessageActionKindDTO.undo,
+ label: 'Undo change',
+ actionMetadataId: 'exec-1',
+} as MessageActionDTO;
+
+function renderUndoChip(): HTMLElement {
+ render(<ActionsSection actions={[UNDO_ACTION]} messageId="m1" />);
+ return screen.getByRole('button', { name: 'Undo change' });
+}
+
+describe('ActionsSection rollback chip', () => {
+ beforeEach(() => {
+ mockUndo.mockReset();
+ });
+
+ it('ignores clicks while the rollback is in flight', async () => {
+ const user = userEvent.setup();
+ mockUndo.mockReturnValue(new Promise(() => {}));
+ const chip = renderUndoChip();
+
+ await user.click(chip);
+ await waitFor(() => expect(chip).toHaveAttribute('aria-busy', 'true'));
+ await user.click(chip);
+
+ expect(mockUndo).toHaveBeenCalledTimes(1);
+ expect(mockUndo).toHaveBeenCalledWith('exec-1');
+ });
+
+ it('disables the chip after success and says why', async () => {
+ const user = userEvent.setup();
+ mockUndo.mockResolvedValue({} as Awaited<ReturnType<typeof undoExecution>>);
+ const chip = renderUndoChip();
+
+ await user.click(chip);
+ await waitFor(() => expect(chip).toHaveAttribute('aria-disabled', 'true'));
+
+ await user.click(chip);
+ expect(mockUndo).toHaveBeenCalledTimes(1);
+
+ // A click closes a Base UI tooltip until the pointer leaves the trigger.
+ await user.unhover(chip);
+ await user.hover(chip);
+ await expect(
+ screen.findByText('This action already ran'),
+ ).resolves.toBeInTheDocument();
+ });
+
+ it('shows the error text when the rollback fails', async () => {
+ const user = userEvent.setup();
+ mockUndo.mockRejectedValue(new Error('Execution already reverted'));
+ const chip = renderUndoChip();
+
+ await user.click(chip);
+ await waitFor(() => expect(chip).not.toHaveAttribute('aria-busy', 'true'));
+ expect(chip).not.toHaveAttribute('aria-disabled', 'true');
+
+ await user.unhover(chip);
+ await user.hover(chip);
+ await expect(
+ screen.findByText('Execution already reverted'),
+ ).resolves.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/container/AllError/index.tsx b/frontend/src/container/AllError/index.tsx
index be7fbef513..0bcd71cbfa 100644
--- a/frontend/src/container/AllError/index.tsx
+++ b/frontend/src/container/AllError/index.tsx
@@ -340,6 +340,7 @@ function AllErrors(): JSX.Element {
render: (value, record): JSX.Element => (
<Tooltip overlay={(): JSX.Element => value}>
<AppLink
+ data-testid="exception-row-link"
to={`${ROUTES.ERROR_DETAIL}?groupId=${
record.groupID
}&timestamp=${getNanoSeconds(record.lastSeen)}`}
@@ -486,6 +487,7 @@ function AllErrors(): JSX.Element {
return (
<ResizeTable
+ data-testid="exceptions-table"
columns={columns}
tableLayout="fixed"
dataSource={data?.payload as Exception[]}
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/DomainDetails.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/DomainDetails.tsx
index dedcb71441..749c10945d 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/DomainDetails.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/DomainDetails.tsx
@@ -161,7 +161,7 @@ function DomainDetails({
<Divider type="vertical" />
{domainData?.domainName && (
- <Typography.Text className="title">
+ <Typography.Text className="title" testId="domain-details-title">
{domainData.domainName}
</Typography.Text>
)}
@@ -214,6 +214,7 @@ function DomainDetails({
background: 'var(--l1-background)',
}}
className="domain-detail-drawer"
+ data-testid="domain-details-drawer"
destroyOnClose
closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
>
@@ -233,9 +234,21 @@ function DomainDetails({
value={selectedView}
size="md"
items={[
- { value: VIEW_TYPES.ALL_ENDPOINTS, label: 'All Endpoints' },
- { value: VIEW_TYPES.ENDPOINT_STATS, label: 'Endpoint(s) Stats' },
- { value: VIEW_TYPES.TOP_ERRORS, label: 'Top 10 Errors' },
+ {
+ value: VIEW_TYPES.ALL_ENDPOINTS,
+ label: 'All Endpoints',
+ testId: `domain-view-${VIEW_TYPES.ALL_ENDPOINTS}`,
+ },
+ {
+ value: VIEW_TYPES.ENDPOINT_STATS,
+ label: 'Endpoint(s) Stats',
+ testId: `domain-view-${VIEW_TYPES.ENDPOINT_STATS}`,
+ },
+ {
+ value: VIEW_TYPES.TOP_ERRORS,
+ label: 'Top 10 Errors',
+ testId: `domain-view-${VIEW_TYPES.TOP_ERRORS}`,
+ },
]}
/>
</div>
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
index 9776537f87..2bff3a9d52 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/TopErrors.tsx
@@ -176,6 +176,7 @@ function TopErrors({
textPlacement="right"
value={showStatusCodeErrors}
onChange={setShowStatusCodeErrors}
+ testId="top-errors-status-message-toggle"
/>
<span style={{ color: 'white', fontSize: '14px' }}>
Status Message Exists
@@ -186,7 +187,7 @@ function TopErrors({
</div>
</div>
- <div className="endpoints-table-container">
+ <div className="endpoints-table-container" data-testid="top-errors-table">
<div className="endpoints-table-header">
{showStatusCodeErrors ? 'Errors with Status Message' : 'All Errors'}{' '}
<Tooltip
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DependentServices.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DependentServices.tsx
index e59db81c70..78995f0f0a 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DependentServices.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DependentServices.tsx
@@ -64,7 +64,10 @@ function DependentServices({
return (
<div className="top-services-content">
- <div className="dependent-services-container">
+ <div
+ className="dependent-services-container"
+ data-testid="dependent-services-table"
+ >
<Table
loading={isLoading || isRefetching}
dataSource={dependentServicesData || []}
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx
index b176aeedc0..918e0fd998 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/DomainMetrics.tsx
@@ -86,7 +86,7 @@ function DomainMetrics({
}
return (
- <div className="domain-detail-drawer__endpoint">
+ <div className="domain-detail-drawer__endpoint" data-testid="domain-metrics">
<div className="domain-details-grid">
<div className="labels-row">
<Typography.Text color="muted" className="domain-details-metadata-label">
@@ -103,7 +103,7 @@ function DomainMetrics({
</Typography.Text>
</div>
- <div className="values-row">
+ <div className="values-row" data-testid="domain-metrics-values">
<Typography.Text className="domain-details-metadata-value">
{isLoading || isRefetching ? (
<Skeleton.Button active size="small" />
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeTable.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeTable.tsx
index c82b18c9ee..f44fae8d4b 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeTable.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainDetails/components/StatusCodeTable.tsx
@@ -35,7 +35,10 @@ function StatusCodeTable({
}
return (
- <div className="status-code-table-container">
+ <div
+ className="status-code-table-container"
+ data-testid="endpoint-status-code-table"
+ >
<Table
loading={isLoading || isRefetching}
dataSource={statusCodeData || []}
diff --git a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainList.tsx b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainList.tsx
index 67702c4d48..843c80d127 100644
--- a/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainList.tsx
+++ b/frontend/src/container/ApiMonitoring/Explorer/Domains/DomainList.tsx
@@ -166,7 +166,10 @@ function DomainList(): JSX.Element {
!isFetching &&
!isLoading &&
formattedDataForTable.length === 0 && (
- <div className="no-filtered-domains-message-container">
+ <div
+ className="no-filtered-domains-message-container"
+ data-testid="api-monitoring-empty-state"
+ >
<div className="no-filtered-domains-message-content">
<img
src={emptyStateUrl}
@@ -200,6 +203,7 @@ function DomainList(): JSX.Element {
{(isFetching || isLoading || formattedDataForTable.length > 0) && (
<Table
className="api-monitoring-domain-list-table"
+ data-testid="api-monitoring-domain-table"
dataSource={isFetching || isLoading ? [] : formattedDataForTable}
columns={columnsConfig}
loading={{
@@ -210,7 +214,10 @@ function DomainList(): JSX.Element {
}}
scroll={{ x: true }}
tableLayout="fixed"
- onRow={(record, index): { onClick: () => void; className: string } => ({
+ onRow={(
+ record,
+ index,
+ ): { onClick: () => void; className: string; 'data-testid': string } => ({
onClick: (): void => {
if (index !== undefined) {
const dataIndex = formattedDataForTable.findIndex(
@@ -222,6 +229,7 @@ function DomainList(): JSX.Element {
}
},
className: 'expanded-clickable-row',
+ 'data-testid': `domain-row-${record.domainName}`,
})}
rowClassName={(_, index): string =>
index % 2 === 0 ? 'table-row-dark' : 'table-row-light'
diff --git a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
index f55bdbff53..3001820795 100644
--- a/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
+++ b/frontend/src/container/CreateAlertV2/AlertCondition/__tests__/AlertThreshold.test.tsx
@@ -5,6 +5,10 @@ import { AlertTypes } from 'types/api/alerts/alertTypes';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import { CreateAlertProvider } from '../../context';
+import {
+ THRESHOLD_MATCH_TYPE_OPTIONS,
+ THRESHOLD_OPERATOR_OPTIONS,
+} from '../../context/constants';
import AlertThreshold from '../AlertThreshold';
const mockChannels: ChannelOption[] = [];
@@ -289,4 +293,49 @@ describe('AlertThreshold', () => {
verifySelectRenders(TEST_STRINGS.IS_ABOVE);
verifySelectRenders(TEST_STRINGS.AT_LEAST_ONCE);
});
+
+ it.each([
+ [
+ 'operator',
+ THRESHOLD_OPERATOR_OPTIONS,
+ [
+ 'ABOVE',
+ 'BELOW',
+ 'EQUAL TO',
+ 'NOT EQUAL TO',
+ 'ABOVE OR EQUAL TO',
+ 'BELOW OR EQUAL TO',
+ ],
+ ],
+ [
+ 'match type',
+ THRESHOLD_MATCH_TYPE_OPTIONS,
+ ['AT LEAST ONCE', 'ALL THE TIME', 'ON AVERAGE', 'IN TOTAL', 'LAST'],
+ ],
+ ])(
+ 'the %s select offers exactly its documented options',
+ (_label, options, expected) => {
+ // Asserted on the options the select is fed rather than on the rendered
+ // dropdown: antd virtualises its list, so in jsdom (zero-height viewport)
+ // only the first two items exist in the DOM and their text is the wire
+ // value, not the label.
+ expect(options.map((option) => option.label)).toStrictEqual(expected);
+
+ renderAlertThreshold();
+ expect(screen.getByText(options[0].label)).toBeInTheDocument();
+ },
+ );
+
+ it('never renders the recovery threshold control', () => {
+ // `showRecoveryThreshold` starts false and its only setter is commented
+ // out, so neither the input nor its remove button can appear.
+ renderAlertThreshold();
+
+ expect(
+ screen.queryByTestId('recovery-threshold-value-input'),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.queryByTestId('remove-recovery-threshold-button'),
+ ).not.toBeInTheDocument();
+ });
});
diff --git a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx
index a520e66875..a2edfd2850 100644
--- a/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx
+++ b/frontend/src/container/CreateAlertV2/CreateAlertHeader/__tests__/LabelsInput.test.tsx
@@ -106,6 +106,41 @@ describe('LabelsInput', () => {
expect(mockOnLabelsChange).toHaveBeenCalledWith({ severity: 'high' });
});
+ it('rejects a key that already exists, before validating it', () => {
+ // Both rejection branches raise an antd notification rather than an
+ // inline message, so the observable outcome is that nothing is added and
+ // the editor stays on the key phase. The duplicate check short-circuits
+ // ahead of `validateLabelsKey`.
+ renderLabelsInput({ labels: { severity: 'high' } });
+
+ fireEvent.click(screen.getByText(ADD_LABELS_TEXT));
+ const input = screen.getByPlaceholderText(ENTER_KEY_PLACEHOLDER);
+ fireEvent.change(input, { target: { value: 'severity' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ expect(mockValidateLabelsKey).not.toHaveBeenCalled();
+ expect(mockOnLabelsChange).not.toHaveBeenCalled();
+ expect(
+ screen.queryByPlaceholderText(ENTER_VALUE_PLACEHOLDER),
+ ).not.toBeInTheDocument();
+ });
+
+ it('rejects a key the validator refuses', () => {
+ mockValidateLabelsKey.mockReturnValue('Cannot use a group-by key');
+ renderLabelsInput();
+
+ fireEvent.click(screen.getByText(ADD_LABELS_TEXT));
+ const input = screen.getByPlaceholderText(ENTER_KEY_PLACEHOLDER);
+ fireEvent.change(input, { target: { value: 'service.name' } });
+ fireEvent.keyDown(input, { key: 'Enter' });
+
+ expect(mockValidateLabelsKey).toHaveBeenCalledWith('service.name');
+ expect(mockOnLabelsChange).not.toHaveBeenCalled();
+ expect(
+ screen.queryByPlaceholderText(ENTER_VALUE_PLACEHOLDER),
+ ).not.toBeInTheDocument();
+ });
+
it('does not switch to value input if key is empty', () => {
renderLabelsInput();
diff --git a/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx b/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx
index 32940787e6..f4a8b4cc4c 100644
--- a/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx
+++ b/frontend/src/container/CreateAlertV2/context/__tests__/CreateAlertProvider.prefill.test.tsx
@@ -173,6 +173,45 @@ describe('CreateAlertProvider — edit mode ignores URL prefill', () => {
expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
});
+
+ it('ignores prefill params that are present on an edit URL', () => {
+ // A deep link into the editor can carry the create form's prefill params.
+ // The loaded rule has to win, or opening an edited rule from such a link
+ // would silently rewrite its condition.
+ const initialAlertState = {
+ ...INITIAL_CREATE_ALERT_STATE,
+ threshold: {
+ ...INITIAL_CREATE_ALERT_STATE.threshold,
+ matchType: AlertThresholdMatchType.AT_LEAST_ONCE,
+ thresholds: [
+ {
+ ...INITIAL_CREATE_ALERT_STATE.threshold.thresholds[0],
+ thresholdValue: 245,
+ },
+ ],
+ },
+ };
+
+ render(
+ <CreateAlertProvider
+ initialAlertType={AlertTypes.METRICS_BASED_ALERT}
+ isEditMode
+ ruleId="r1"
+ initialAlertState={initialAlertState}
+ >
+ <Probe />
+ </CreateAlertProvider>,
+ undefined,
+ {
+ initialRoute: `/alerts/overview?ruleId=r1&matchType=in_total&compareOp=below&thresholds=${serializeThreshold(
+ 90,
+ )}`,
+ },
+ );
+
+ expect(screen.getByTestId('threshold-value')).toHaveTextContent('245');
+ expect(screen.getByTestId('match-type')).toHaveTextContent('at_least_once');
+ });
});
function ThresholdSetter(): JSX.Element {
diff --git a/frontend/src/container/ErrorDetails/index.tsx b/frontend/src/container/ErrorDetails/index.tsx
index cad18f82a0..7de410fa34 100644
--- a/frontend/src/container/ErrorDetails/index.tsx
+++ b/frontend/src/container/ErrorDetails/index.tsx
@@ -148,13 +148,19 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
return (
<div className="error-details-container">
- <Typography.Title level={4}>{errorDetail.exceptionType}</Typography.Title>
- <Typography.Text>{errorDetail.exceptionMessage}</Typography.Text>
+ <Typography.Title level={4} testId="error-details-type">
+ {errorDetail.exceptionType}
+ </Typography.Title>
+ <Typography.Text testId="error-details-message">
+ {errorDetail.exceptionMessage}
+ </Typography.Text>
<Divider />
<EventContainer>
<div>
- <Typography>Event {errorDetail.errorId}</Typography>
+ <Typography testId="error-details-event-id">
+ Event {errorDetail.errorId}
+ </Typography>
<Typography>
{formatTimezoneAdjustedTimestamp(
errorDetail.timestamp,
@@ -165,6 +171,7 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
<div>
<Space align="end" direction="horizontal">
<Button
+ data-testid="error-details-older"
loading={nextPrevStatus === 'loading'}
disabled={nextPrevData?.payload?.prevErrorID.length === 0}
onClick={(): Promise<void> =>
@@ -177,6 +184,7 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
{t('older')}
</Button>
<Button
+ data-testid="error-details-newer"
loading={nextPrevStatus === 'loading'}
disabled={nextPrevData?.payload?.nextErrorID.length === 0}
onClick={(): Promise<void> =>
@@ -194,17 +202,21 @@ function ErrorDetails(props: ErrorDetailsProps): JSX.Element {
<DashedContainer>
<Typography>{t('see_trace_graph')}</Typography>
- <Button onClick={onClickTraceHandler} type="primary">
+ <Button
+ data-testid="error-details-view-trace"
+ onClick={onClickTraceHandler}
+ type="primary"
+ >
{t('see_error_in_trace_graph')}
</Button>
</DashedContainer>
<Typography.Title level={4}>{t('stack_trace')}</Typography.Title>
- <div className="error-container">
+ <div className="error-container" data-testid="error-details-stacktrace">
<Editor value={stackTraceValue} readOnly />
</div>
- <EditorContainer>
+ <EditorContainer data-testid="error-details-attributes-table">
<Space direction="vertical">
<ResizeTable columns={columns} tableLayout="fixed" dataSource={data} />
</Space>
diff --git a/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx b/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx
index 3718ee7a3e..308f205f0d 100644
--- a/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx
+++ b/frontend/src/container/ForgotPassword/__tests__/ForgotPassword.test.tsx
@@ -406,4 +406,76 @@ describe('ForgotPassword Component', () => {
expect(submitButton).toHaveAttribute('aria-disabled', 'true');
});
});
+
+ // The email input is disabled and Enter in the org Select opens it, so Enter
+ // only reaches the form through the focused submit button.
+ describe('Enter key submission', () => {
+ function mockForgot(delayMs = 0): { forgotCalls: () => number } {
+ let calls = 0;
+ server.use(
+ rest.post(FORGOT_PASSWORD_ENDPOINT, (_req, res, ctx) => {
+ calls += 1;
+ return res(
+ ctx.delay(delayMs),
+ ctx.status(200),
+ ctx.json({ status: 'success' }),
+ );
+ }),
+ );
+ return { forgotCalls: (): number => calls };
+ }
+
+ it('sends the reset link once on Enter on the submit button', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { forgotCalls } = mockForgot();
+
+ render(<ForgotPassword {...defaultProps} />);
+
+ await user.tab();
+ await user.tab();
+ expect(screen.getByTestId('forgot-password-submit')).toHaveFocus();
+ await user.keyboard('{enter}');
+
+ await expect(
+ screen.findByText(/check your email/i),
+ ).resolves.toBeInTheDocument();
+ expect(forgotCalls()).toBe(1);
+ });
+
+ it('does not send on Enter while no organization is selected', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { forgotCalls } = mockForgot();
+
+ render(<ForgotPassword {...multiOrgProps} />);
+
+ const submitButton = screen.getByTestId('forgot-password-submit');
+ expect(submitButton).toHaveAttribute('aria-disabled', 'true');
+ submitButton.focus();
+ await user.keyboard('{enter}');
+
+ // Give a wrongly sent request time to land before asserting it never did.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(forgotCalls()).toBe(0);
+ });
+
+ it('does not send again on Enter while the first request is loading', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { forgotCalls } = mockForgot(1000);
+
+ render(<ForgotPassword {...defaultProps} />);
+
+ const submitButton = screen.getByTestId('forgot-password-submit');
+ submitButton.focus();
+ await user.keyboard('{enter}');
+
+ await screen.findByText(/sending\.\.\./i);
+ expect(submitButton).toHaveAttribute('aria-disabled', 'true');
+ await user.keyboard('{enter}');
+
+ await expect(
+ screen.findByText(/check your email/i, undefined, { timeout: 2000 }),
+ ).resolves.toBeInTheDocument();
+ expect(forgotCalls()).toBe(1);
+ });
+ });
});
diff --git a/frontend/src/container/Home/AlertRules/AlertRules.tsx b/frontend/src/container/Home/AlertRules/AlertRules.tsx
index afa845f54f..3d681462fc 100644
--- a/frontend/src/container/Home/AlertRules/AlertRules.tsx
+++ b/frontend/src/container/Home/AlertRules/AlertRules.tsx
@@ -219,7 +219,12 @@ export default function AlertRules({
<Card className="alert-rules-card home-data-card">
{rulesExist && (
<Card.Header>
- <div className="alert-rules-header home-data-card-header">Alerts</div>
+ <div
+ className="alert-rules-header home-data-card-header"
+ data-testid="home-section-alerts"
+ >
+ Alerts
+ </div>
</Card.Header>
)}
<Card.Content>
diff --git a/frontend/src/container/Home/Dashboards/Dashboards.tsx b/frontend/src/container/Home/Dashboards/Dashboards.tsx
index 83841fe7b3..d6464be3d3 100644
--- a/frontend/src/container/Home/Dashboards/Dashboards.tsx
+++ b/frontend/src/container/Home/Dashboards/Dashboards.tsx
@@ -202,7 +202,12 @@ export default function Dashboards({
<Card className="dashboards-list-card home-data-card">
{dashboardsExist && (
<Card.Header>
- <div className="dashboards-header home-data-card-header">Dashboards</div>
+ <div
+ className="dashboards-header home-data-card-header"
+ data-testid="home-section-dashboards"
+ >
+ Dashboards
+ </div>
</Card.Header>
)}
<Card.Content>
diff --git a/frontend/src/container/Home/Home.tsx b/frontend/src/container/Home/Home.tsx
index 85ae431280..130a624e6d 100644
--- a/frontend/src/container/Home/Home.tsx
+++ b/frontend/src/container/Home/Home.tsx
@@ -278,7 +278,7 @@ export default function Home(): JSX.Element {
}, []);
return (
- <div className="home-container">
+ <div className="home-container" data-testid="home-page">
{getIsNoAuthMode() && <NoAuthBanner />}
<div className="sticky-header">
<Header
@@ -316,6 +316,7 @@ export default function Home(): JSX.Element {
variant="solid"
color="secondary"
prefix={<ClipboardList size={14} />}
+ testId="welcome-checklist-btn"
>
Welcome checklist
</Button>
@@ -662,7 +663,10 @@ export default function Home(): JSX.Element {
exit={{ opacity: 0, scale: 0 }}
key="box"
>
- <div className="checklist-container">
+ <div
+ className="checklist-container"
+ data-testid="home-checklist-card"
+ >
<div className="checklist-items-container">
<StepsProgress checklistItems={checklistItems} />
@@ -701,6 +705,7 @@ export default function Home(): JSX.Element {
color="secondary"
onClick={handleWillDoThisLater}
loading={updatingUserPreferences}
+ testId="checklist-do-later-btn"
>
I&apos;ll do this later
</Button>
diff --git a/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx b/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx
index b2404c01dc..ee4f4e9aff 100644
--- a/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx
+++ b/frontend/src/container/Home/HomeChecklist/HomeChecklist.tsx
@@ -68,6 +68,7 @@ function HomeChecklist({
{whatsNextChecklistItems.map((item, index) => (
<div
key={item.id}
+ data-testid={`checklist-item-${item.id}`}
className={`whats-next-checklist-item ${
item.isSkipped && !item.completed ? 'skipped' : ''
} ${
@@ -129,6 +130,7 @@ function HomeChecklist({
<Button
type="link"
className="periscope-btn link skip-btn"
+ data-testid={`checklist-skip-${item.id}`}
onClick={(): void => {
logEvent('Welcome Checklist: Skip clicked', {
step: item.id,
diff --git a/frontend/src/container/Home/SavedViews/SavedViews.tsx b/frontend/src/container/Home/SavedViews/SavedViews.tsx
index c7c173c945..06459c6b9a 100644
--- a/frontend/src/container/Home/SavedViews/SavedViews.tsx
+++ b/frontend/src/container/Home/SavedViews/SavedViews.tsx
@@ -301,7 +301,10 @@ export default function SavedViews({
<Card className="saved-views-list-card home-data-card">
{hasSavedViews && (
<Card.Header>
- <div className="saved-views-header home-data-card-header">
+ <div
+ className="saved-views-header home-data-card-header"
+ data-testid="home-section-saved-views"
+ >
Saved Views
<div className="saved-views-header-actions">
<Button.Group className="views-tabs">
diff --git a/frontend/src/container/Home/Services/ServiceMetrics.tsx b/frontend/src/container/Home/Services/ServiceMetrics.tsx
index dc8a7cfde4..121c4ab24a 100644
--- a/frontend/src/container/Home/Services/ServiceMetrics.tsx
+++ b/frontend/src/container/Home/Services/ServiceMetrics.tsx
@@ -315,7 +315,10 @@ function ServiceMetrics({
<Card className="services-list-card home-data-card">
{servicesExist && (
<Card.Header>
- <div className="services-header home-data-card-header">
+ <div
+ className="services-header home-data-card-header"
+ data-testid="home-section-services"
+ >
{' '}
Services
<div className="services-header-actions">
diff --git a/frontend/src/container/Home/Services/ServiceTraces.tsx b/frontend/src/container/Home/Services/ServiceTraces.tsx
index 77c86103a4..dfc2cac88e 100644
--- a/frontend/src/container/Home/Services/ServiceTraces.tsx
+++ b/frontend/src/container/Home/Services/ServiceTraces.tsx
@@ -218,7 +218,10 @@ export default function ServiceTraces({
<Card className="dashboards-list-card home-data-card">
{servicesExist && (
<Card.Header>
- <div className="services-header home-data-card-header">
+ <div
+ className="services-header home-data-card-header"
+ data-testid="home-section-services"
+ >
Services
<div className="services-header-actions">
<Select
diff --git a/frontend/src/container/InfraMonitoringHostsV2/Hosts.tsx b/frontend/src/container/InfraMonitoringHostsV2/Hosts.tsx
index 9ebdc80eee..e91c6e1b9d 100644
--- a/frontend/src/container/InfraMonitoringHostsV2/Hosts.tsx
+++ b/frontend/src/container/InfraMonitoringHostsV2/Hosts.tsx
@@ -213,6 +213,7 @@ function Hosts(): JSX.Element {
className="periscope-btn ghost"
type="text"
size="small"
+ data-testid="quick-filters-toggle"
onClick={handleFilterVisibilityChange}
>
<Filter size={14} />
@@ -239,6 +240,7 @@ function Hosts(): JSX.Element {
style={{ rotate: '270deg', cursor: 'pointer' }}
onClick={handleFilterVisibilityChange}
size="md"
+ data-testid="quick-filters-toggle"
/>
</Tooltip>
</div>
diff --git a/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.tsx b/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.tsx
index 9c572dfb77..c23ceda7f6 100644
--- a/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.tsx
+++ b/frontend/src/container/InfraMonitoringHostsV2/StatusFilter.tsx
@@ -53,6 +53,7 @@ function StatusFilter(): JSX.Element {
items={statusOptions.map((option) => ({
value: option.value,
label: option.label,
+ testId: `status-filter-${option.value}`,
prefix: (
<span
className={`${styles.statusDot} ${
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetails.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetails.tsx
index bbe78185ff..a547659889 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetails.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetails.tsx
@@ -296,6 +296,7 @@ export default function K8sBaseDetails<T>({
<DrawerWrapper
open={!!selectedItem}
onOpenChange={handleOpenChange}
+ testId="drawer-wrapper"
direction="right"
title={drawerTitle}
showCloseButton={false}
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetailsContent.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetailsContent.tsx
index c8e5460389..0696e1b9f0 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetailsContent.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseDetailsContent.tsx
@@ -301,6 +301,7 @@ export default function K8sBaseDetailsContent<T>({
type="single"
onChange={handleTabChange}
value={effectiveView}
+ testId="drawer-tab-bar"
items={[
...(tabVisibility.showOverview
? [
@@ -387,6 +388,7 @@ export default function K8sBaseDetailsContent<T>({
size="sm"
icon
color="secondary"
+ testId="open-logs-explorer"
onClick={handleExplorePagesRedirect}
>
<Compass size={18} />
@@ -401,6 +403,7 @@ export default function K8sBaseDetailsContent<T>({
size="sm"
icon
color="secondary"
+ testId="open-traces-explorer"
onClick={handleExplorePagesRedirect}
>
<Compass size={18} />
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx
index 1e80b2e9dc..8695faf81f 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sBaseList.tsx
@@ -396,6 +396,11 @@ export function K8sBaseList<
const isGroupedByAttribute = groupBy.length > 0;
+ const getRowTestId = useCallback(
+ (record: T): string => `row-${getRowKey(record)}`,
+ [getRowKey],
+ );
+
// Filter columns for expanded row based on parent's hidden columns
const expandedRowColumns = useMemo(
() => tableColumns.filter((col) => !hiddenColumnIds.includes(col.id)),
@@ -417,6 +422,7 @@ export function K8sBaseList<
extraQueryKeyParts={extraQueryKeyParts}
getRowKey={getRowKey}
getItemKey={getItemKey}
+ getRowTestId={getRowTestId}
detailsQueryKeyPrefix={detailsQueryKeyPrefix}
/>
),
@@ -425,6 +431,7 @@ export function K8sBaseList<
fetchListData,
getRowKey,
getItemKey,
+ getRowTestId,
expandedRowColumns,
extraQueryKeyParts,
detailsQueryKeyPrefix,
@@ -506,6 +513,7 @@ export function K8sBaseList<
isLoading={showTableLoadingState}
getRowKey={getRowKey}
getItemKey={getItemKey}
+ getRowTestId={getRowTestId}
groupBy={groupBy.map((g) => ({ key: g }))}
getGroupKey={getGroupKeyFn}
onRowClick={handleRowClick}
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sEmptyState.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sEmptyState.tsx
index c7cf6fe4c1..f9b4ddffa2 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sEmptyState.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sEmptyState.tsx
@@ -21,7 +21,7 @@ export function K8sEmptyState({
if (isError || error) {
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="k8s-error-state">
<div className={styles.errorContent}>
<ErrorContent
error={
@@ -38,7 +38,7 @@ export function K8sEmptyState({
if (endTimeBeforeRetention) {
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="k8s-empty-state-retention">
<div className={styles.content}>
<img className={styles.eyesEmoji} src={eyesEmojiUrl} alt="eyes emoji" />
<div className={styles.noDataMessage}>
@@ -56,7 +56,7 @@ export function K8sEmptyState({
}
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="k8s-empty-state">
<div className={styles.content}>
<img
src={emptyStateUrl}
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx
index 42ed824c43..5733120b90 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sExpandedRow.tsx
@@ -69,6 +69,7 @@ export type K8sExpandedRowProps<T, TItemKey = string> = {
getRowKey?: (record: T) => string;
/** Function to get the item key used for selection. Defaults to getRowKey if not provided. */
getItemKey?: (record: T) => TItemKey;
+ getRowTestId?: (record: T) => string;
/** Query key prefix for pre-caching detail data on row click */
detailsQueryKeyPrefix?: string;
};
@@ -85,6 +86,7 @@ export function K8sExpandedRow<
extraQueryKeyParts = [],
getRowKey,
getItemKey,
+ getRowTestId,
detailsQueryKeyPrefix,
}: K8sExpandedRowProps<T, TItemKey>): JSX.Element {
const fontSize = useInfraMonitoringFontSize();
@@ -321,6 +323,7 @@ export function K8sExpandedRow<
isLoading={isLoading}
getRowKey={getRowKey}
getItemKey={getItemKey}
+ getRowTestId={getRowTestId}
onRowClick={handleRowClick}
onSort={handleSort}
enableQueryParams={{
diff --git a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx
index d0faa70eec..72ba1d3343 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/Base/K8sHeader.tsx
@@ -141,6 +141,7 @@ function K8sHeader({
isLoadingQueries={isFetching}
onStageRunQuery={handleStageRunQuery}
handleCancelQuery={handleCancelQuery}
+ testId="list-run-query-btn"
/>
</div>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityDateTimeSelector/EntityDateTimeSelector.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityDateTimeSelector/EntityDateTimeSelector.tsx
index 503f25268b..cacc0bb2d9 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityDateTimeSelector/EntityDateTimeSelector.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityDateTimeSelector/EntityDateTimeSelector.tsx
@@ -51,7 +51,7 @@ function EntityDateTimeSelector({
);
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="drawer-time-selection">
{hasTimeChanged && (
<Tooltip title="Reset to list time" side="bottom">
<Button
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEmptyState/EntityEmptyState.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEmptyState/EntityEmptyState.tsx
index 5b46d4e983..b1d7e8ba19 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEmptyState/EntityEmptyState.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEmptyState/EntityEmptyState.tsx
@@ -12,7 +12,7 @@ export default function EntityEmptyState({
hasFilters,
}: EntityEmptyStateProps): JSX.Element {
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="entity-empty-state">
<div className={styles.content}>
<img src={emptyStateUrl} alt="empty-state" className={styles.icon} />
{hasFilters ? (
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx
index 09eabfae4c..833008bc17 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityError/EntityError.tsx
@@ -20,7 +20,7 @@ export default function EntityError(): JSX.Element {
};
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="entity-error-state">
<div className={styles.content}>
<img src={awwSnapUrl} alt="error" className={styles.icon} />
<Typography.Text>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EntityEvents.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
index 0cdfc04b8c..7af5bc25cc 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EntityEvents.tsx
@@ -242,6 +242,7 @@ function EntityEventsContent({
isLoadingQueries={isFetching}
onStageRunQuery={(): void => handleRunQuery()}
handleCancelQuery={cancel}
+ testId="entity-events-run-query-btn"
/>
</div>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EventsNotConfigured.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EventsNotConfigured.tsx
index 39c3dfa9fc..831469f9d9 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EventsNotConfigured.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityEvents/EventsNotConfigured.tsx
@@ -15,7 +15,7 @@ export default function EventsNotConfigured(): JSX.Element {
};
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="events-not-configured">
<div className={styles.content}>
<img src={emptyStateUrl} alt="not-configured" className={styles.icon} />
<Typography.Text>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityLogs/EntityLogs.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
index 7d6f2fe49e..82c1ef8dc0 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityLogs/EntityLogs.tsx
@@ -287,6 +287,7 @@ function EntityLogsContent({
isLoadingQueries={isFetching}
onStageRunQuery={(): void => handleRunQuery()}
handleCancelQuery={cancel}
+ testId="entity-logs-run-query-btn"
/>
</div>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx
index 0494bc4789..665ff14a45 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityMetrics/EntityMetrics.tsx
@@ -152,13 +152,16 @@ function EntityMetrics<T>({
}
const panelType = queryPayloads[idx]?.graphType;
+ const isNoData =
+ !query.isLoading && !query?.data?.payload?.data?.result?.length;
return (
<div
className={cx(styles.chartContainer, {
- [styles.noDataContainer]:
- !query.isLoading && !query?.data?.payload?.data?.result?.length,
+ [styles.noDataContainer]: isNoData,
})}
+ data-testid="entity-metrics-chart"
+ data-has-data={isNoData ? 'false' : 'true'}
>
{panelType === PANEL_TYPES.TABLE ? (
<MetricsTable
diff --git a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityTraces/EntityTraces.tsx b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityTraces/EntityTraces.tsx
index ad5fea1099..7876563fba 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityTraces/EntityTraces.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/EntityDetailsUtils/EntityTraces/EntityTraces.tsx
@@ -181,6 +181,7 @@ function EntityTracesContent({
isLoadingQueries={isFetching}
onStageRunQuery={(): void => handleRunQuery()}
handleCancelQuery={cancel}
+ testId="entity-traces-run-query-btn"
/>
</div>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx b/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx
index 3236de78fa..f0678382e0 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/InfraMonitoringK8s.tsx
@@ -257,6 +257,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
size="sm"
icon
color="secondary"
+ testId="quick-filters-toggle"
onClick={handleFilterVisibilityChange}
>
<Filter size={14} />
@@ -287,6 +288,7 @@ export default function InfraMonitoringK8s(): JSX.Element {
style={{ transform: 'rotate(270deg)' }}
onClick={handleFilterVisibilityChange}
size="md"
+ data-testid="quick-filters-toggle"
/>
</Tooltip>
</div>
diff --git a/frontend/src/container/InfraMonitoringK8sV2/__tests__/entityConfig.test.ts b/frontend/src/container/InfraMonitoringK8sV2/__tests__/entityConfig.test.ts
new file mode 100644
index 0000000000..6473dbf57b
--- /dev/null
+++ b/frontend/src/container/InfraMonitoringK8sV2/__tests__/entityConfig.test.ts
@@ -0,0 +1,155 @@
+import { hostColumnsConfig } from 'container/InfraMonitoringHostsV2/table.config';
+
+import { k8sClustersColumnsConfig } from '../Clusters/table.config';
+import {
+ ENTITY_FILTER_PLACEHOLDERS,
+ InfraMonitoringEntity,
+ METRIC_NAMESPACE_BY_ENTITY,
+} from '../constants';
+import { k8sDaemonSetsColumnsConfig } from '../DaemonSets/table.config';
+import { k8sDeploymentsColumnsConfig } from '../Deployments/table.config';
+import { k8sJobsColumnsConfig } from '../Jobs/table.config';
+import { k8sNamespacesColumnsConfig } from '../Namespaces/table.config';
+import { k8sNodesColumnsConfig } from '../Nodes/table.config';
+import { k8sPodColumnsConfig } from '../Pods/table.config';
+import { k8sStatefulSetsColumnsConfig } from '../StatefulSets/table.config';
+import { k8sVolumesColumnsConfig } from '../Volumes/table.config';
+
+/**
+ * The per-entity config, asserted from the source rather than through a browser.
+ *
+ * `K8sBaseList` and `K8sBaseDetails` do not branch on entity — the only thing
+ * that varies between the ten is the config object they are handed. So the
+ * question "is entity N wired up correctly" is a property of these literals, and
+ * running the same rendered list ten times over a seeded stack answers it at
+ * about a thousand times the cost. The E2E suite drives one entity; this is what
+ * covers the other nine.
+ */
+
+interface EntityConfig {
+ entity: InfraMonitoringEntity;
+ /** The column whose id is the entity's name attribute. */
+ nameColumnId: string;
+ /** The group-row column, which every entity renders first and pins left. */
+ groupColumnId: string;
+ columns: { id: string; enableSort?: boolean; pin?: string }[];
+}
+
+const ENTITIES: EntityConfig[] = [
+ {
+ entity: InfraMonitoringEntity.HOSTS,
+ nameColumnId: 'host.name',
+ groupColumnId: 'hostGroup',
+ columns: hostColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.PODS,
+ nameColumnId: 'k8s.pod.name',
+ groupColumnId: 'podGroup',
+ columns: k8sPodColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.NODES,
+ nameColumnId: 'k8s.node.name',
+ groupColumnId: 'nodeGroup',
+ columns: k8sNodesColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.NAMESPACES,
+ nameColumnId: 'k8s.namespace.name',
+ groupColumnId: 'namespaceGroup',
+ columns: k8sNamespacesColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.CLUSTERS,
+ nameColumnId: 'k8s.cluster.name',
+ groupColumnId: 'clusterGroup',
+ columns: k8sClustersColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.DEPLOYMENTS,
+ nameColumnId: 'k8s.deployment.name',
+ groupColumnId: 'deploymentGroup',
+ columns: k8sDeploymentsColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.STATEFULSETS,
+ nameColumnId: 'k8s.statefulset.name',
+ groupColumnId: 'statefulSetGroup',
+ columns: k8sStatefulSetsColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.DAEMONSETS,
+ nameColumnId: 'k8s.daemonset.name',
+ groupColumnId: 'daemonSetGroup',
+ columns: k8sDaemonSetsColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.JOBS,
+ nameColumnId: 'k8s.job.name',
+ groupColumnId: 'jobGroup',
+ columns: k8sJobsColumnsConfig,
+ },
+ {
+ entity: InfraMonitoringEntity.VOLUMES,
+ nameColumnId: 'k8s.persistentvolumeclaim.name',
+ groupColumnId: 'volumeGroup',
+ columns: k8sVolumesColumnsConfig,
+ },
+];
+
+describe('infra monitoring entity config', () => {
+ it.each(ENTITIES)(
+ '$entity has a filter placeholder and a metric namespace',
+ ({ entity }) => {
+ // A missing placeholder renders an empty search box; a missing namespace
+ // makes the field-suggestion calls return everything.
+ expect(ENTITY_FILTER_PLACEHOLDERS[entity]).toMatch(
+ /^Enter your filter query/,
+ );
+ expect(METRIC_NAMESPACE_BY_ENTITY[entity]).toMatch(/\.$/);
+ },
+ );
+
+ it.each(ENTITIES)(
+ '$entity has unique, non-empty column ids',
+ ({ columns }) => {
+ const ids = columns.map((column) => column.id);
+ expect(ids.every(Boolean)).toBe(true);
+ // A duplicate id makes TanStack drop one of the columns silently, and the
+ // persisted hidden/order state then addresses the wrong one.
+ expect(new Set(ids).size).toBe(ids.length);
+ },
+ );
+
+ it.each(ENTITIES)(
+ '$entity pins its group and name columns left',
+ ({ columns, groupColumnId, nameColumnId }) => {
+ // Both are `pin: 'left'` so they survive a horizontal scroll; the group
+ // column is also what the expand chevron lives in.
+ const byId = new Map(columns.map((column) => [column.id, column]));
+ expect(byId.get(groupColumnId)?.pin).toBe('left');
+ expect(byId.get(nameColumnId)?.pin).toBe('left');
+ },
+ );
+
+ it.each(ENTITIES)(
+ '$entity sorts by its name column and not by its group column',
+ ({ columns, groupColumnId, nameColumnId }) => {
+ const byId = new Map(columns.map((column) => [column.id, column]));
+ expect(byId.get(nameColumnId)?.enableSort).toBe(true);
+ // The group column holds an aggregate, so there is nothing to sort by.
+ expect(byId.get(groupColumnId)?.enableSort).toBe(false);
+ },
+ );
+
+ it('every entity with a config is covered here', () => {
+ // Containers is in the enum with fixtures behind it, but has no entity
+ // config and no tab yet — the day it ships, this fails.
+ const covered = new Set(ENTITIES.map(({ entity }) => entity));
+ const missing = Object.values(InfraMonitoringEntity).filter(
+ (entity) => !covered.has(entity),
+ );
+ expect(missing).toStrictEqual([InfraMonitoringEntity.CONTAINERS]);
+ });
+});
diff --git a/frontend/src/container/InfraMonitoringK8sV2/components/ExpandButtonWrapper.tsx b/frontend/src/container/InfraMonitoringK8sV2/components/ExpandButtonWrapper.tsx
index 915d6bd982..9450e46d01 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/components/ExpandButtonWrapper.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/components/ExpandButtonWrapper.tsx
@@ -26,6 +26,8 @@ export function ExpandButtonWrapper({
aria-label={localIsExpanded ? 'Collapse' : 'Expand'}
variant="ghost"
color="secondary"
+ testId="expand-row-button"
+ aria-expanded={localIsExpanded}
onClick={(e): void => {
e.stopPropagation();
setLocalIsExpanded((v) => !v);
diff --git a/frontend/src/container/InfraMonitoringK8sV2/components/GroupedStatusCounts.tsx b/frontend/src/container/InfraMonitoringK8sV2/components/GroupedStatusCounts.tsx
index 412ce6bfcd..e2b42da73f 100644
--- a/frontend/src/container/InfraMonitoringK8sV2/components/GroupedStatusCounts.tsx
+++ b/frontend/src/container/InfraMonitoringK8sV2/components/GroupedStatusCounts.tsx
@@ -111,7 +111,7 @@ export function GroupedStatusCounts({
}
return (
- <div className={styles.container}>
+ <div className={styles.container} data-testid="grouped-status-counts">
{visibleItems.map((item) => (
<TanStackTable.HoverTooltip
key={item.label}
diff --git a/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx b/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
index 90484a5d10..11b9bf809d 100644
--- a/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
+++ b/frontend/src/container/IngestionSettings/MultiIngestionSettings.tsx
@@ -1705,6 +1705,7 @@ function MultiIngestionSettings(): JSX.Element {
prefix={<Plus size={14} />}
onClick={showAddModal}
width="200px"
+ testId="ingestion-key-add-btn"
>
New Ingestion key
</Button>
diff --git a/frontend/src/container/Integrations/CloudIntegration/AlertMessage.tsx b/frontend/src/container/Integrations/CloudIntegration/AlertMessage.tsx
index 9316e64a12..6ae60a6233 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AlertMessage.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AlertMessage.tsx
@@ -29,6 +29,7 @@ function AlertMessage({
}
type="info"
showIcon={false}
+ testId="cloud-connect-waiting"
/>
);
case ModalStateEnum.ERROR:
@@ -40,6 +41,7 @@ function AlertMessage({
</div>
}
type="error"
+ testId="cloud-connect-error"
/>
);
default:
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx
index 05e9e36ac9..50061469f2 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AccountActions/AccountActions.tsx
@@ -69,6 +69,8 @@ function AccountActionsRenderer({
<span className="account-selector">
<Select
+ data-testid="cloud-account-selector"
+ aria-label="Cloud account"
value={activeAccount?.providerAccountId}
options={selectOptions}
rootClassName={cx('cloud-account-selector', {
@@ -88,6 +90,7 @@ function AccountActionsRenderer({
color="secondary"
prefix={<PencilLine size={14} />}
onClick={onAccountSettingsModalOpen}
+ testId="cloud-edit-account-btn"
>
Edit Account
</Button>
@@ -98,6 +101,7 @@ function AccountActionsRenderer({
color="secondary"
onClick={onIntegrationModalOpen}
prefix={<Plus size={14} />}
+ testId="cloud-add-account-btn"
>
Add New Account
</Button>
@@ -112,6 +116,7 @@ function AccountActionsRenderer({
prefix={<Plug size={14} />}
onClick={onIntegrationModalOpen}
size="sm"
+ testId="cloud-integrate-now-btn"
>
Integrate Now
</Button>
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AddNewAccount/CloudAccountSetupModal.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AddNewAccount/CloudAccountSetupModal.tsx
index 138ee250c1..09115e4bdd 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AddNewAccount/CloudAccountSetupModal.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/AddNewAccount/CloudAccountSetupModal.tsx
@@ -93,6 +93,7 @@ function CloudAccountSetupModal({
color="primary"
prefix={<SquareArrowOutUpRight size={17} color={Color.BG_VANILLA_100} />}
onClick={handleSubmit}
+ testId="aws-launch-cfn-btn"
disabled={
selectedRegions.length === 0 || modalState === ModalStateEnum.WAITING
}
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx
index 16bc8b7e7f..7e57852af4 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/EditAccount/AccountSettingsModal.tsx
@@ -146,6 +146,7 @@ function AccountSettingsModal({
onClick={handleSubmit}
loading={isLoading}
prefix={<Save size={14} />}
+ testId="aws-update-account-btn"
>
Update Changes
</Button>
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/IntegrateNowFormSections.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/IntegrateNowFormSections.tsx
index 6f71645da9..c5de2e2818 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/IntegrateNowFormSections.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/IntegrateNowFormSections.tsx
@@ -31,6 +31,7 @@ function RegionDeploymentSection({
className="cloud-account-setup-form__form-item"
>
<Select
+ data-testid="aws-deployment-region-select"
placeholder="e.g. US East (N. Virginia)"
suffixIcon={<ChevronDown size={16} color={Color.BG_VANILLA_400} />}
className="cloud-account-setup-form__select integrations-select"
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/RegionForm/RegionSelector.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/RegionForm/RegionSelector.tsx
index 35d63d729f..e14ab16e09 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/RegionForm/RegionSelector.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/RegionForm/RegionSelector.tsx
@@ -32,6 +32,7 @@ export function RegionSelector({
<div className="select-all">
<Checkbox
color="primary"
+ testId="aws-select-all-regions"
value={allSelected ? true : someSelected ? 'indeterminate' : false}
onChange={(checked): void => handleSelectAll(checked === true)}
>
@@ -47,6 +48,7 @@ export function RegionSelector({
<Checkbox
color="primary"
key={subRegion.id}
+ testId={`aws-region-${subRegion.id}`}
value={selectedRegions.includes(subRegion.id)}
onChange={(): void => handleRegionSelect(subRegion.id)}
>
diff --git a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/ServiceDetails/ServiceDetails.tsx b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/ServiceDetails/ServiceDetails.tsx
index c7f3c051b0..f8142e09cd 100644
--- a/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/ServiceDetails/ServiceDetails.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/AmazonWebServices/ServiceDetails/ServiceDetails.tsx
@@ -409,6 +409,7 @@ function ServiceDetails({
}
value={field.value}
disabled={isUpdatingServiceConfig || isReadOnly}
+ testId="cloud-service-logs-switch"
onChange={(checked): void => {
field.onChange(checked);
}}
@@ -457,6 +458,7 @@ function ServiceDetails({
}
value={field.value}
disabled={isUpdatingServiceConfig || isReadOnly}
+ testId="cloud-service-metrics-switch"
onChange={field.onChange}
/>
)}
@@ -472,6 +474,7 @@ function ServiceDetails({
disabledTooltip="Wait for the changes to save"
variant="solid"
color="secondary"
+ testId="cloud-service-discard-btn"
onClick={handleDiscard}
disabled={isUpdatingServiceConfig}
size="sm"
@@ -488,6 +491,7 @@ function ServiceDetails({
size="sm"
width={100}
prefix={<Save size={14} />}
+ testId="cloud-service-save-btn"
type="submit"
loading={isUpdatingServiceConfig}
disabled={isS3SyncBucketsMissing}
diff --git a/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx b/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx
index 5822e82a76..63119f23dd 100644
--- a/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/Header/Header.tsx
@@ -12,6 +12,7 @@ function Header({ type }: { type: IntegrationType }): JSX.Element {
<div className="cloud-header">
<div className="cloud-header__navigation">
<Breadcrumb
+ data-testid="cloud-header-breadcrumb"
className="cloud-header__breadcrumb"
items={[
{
diff --git a/frontend/src/container/Integrations/CloudIntegration/RemoveAccount/RemoveIntegrationAccount.tsx b/frontend/src/container/Integrations/CloudIntegration/RemoveAccount/RemoveIntegrationAccount.tsx
index 49bc7fa2e4..0c9159712f 100644
--- a/frontend/src/container/Integrations/CloudIntegration/RemoveAccount/RemoveIntegrationAccount.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/RemoveAccount/RemoveIntegrationAccount.tsx
@@ -124,6 +124,7 @@ function RemoveIntegrationAccount({
prefix={<Unlink size={14} />}
onClick={handleDisconnect}
loading={isRemoveIntegrationLoading}
+ testId="cloud-disconnect-account-btn"
>
Disconnect
</Button>
@@ -138,6 +139,7 @@ function RemoveIntegrationAccount({
okButtonProps={{
danger: true,
loading: isRemoveIntegrationLoading,
+ 'data-testid': 'cloud-remove-account-confirm',
}}
>
{modalDescription}
diff --git a/frontend/src/container/Integrations/CloudIntegration/ServiceDashboards/DashboardCard.tsx b/frontend/src/container/Integrations/CloudIntegration/ServiceDashboards/DashboardCard.tsx
index 5879e3f741..379862ba67 100644
--- a/frontend/src/container/Integrations/CloudIntegration/ServiceDashboards/DashboardCard.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/ServiceDashboards/DashboardCard.tsx
@@ -47,6 +47,7 @@ function DashboardCard({
? 'aws-service-dashboard-item-clickable'
: 'aws-service-dashboard-item-disabled'
} `}
+ data-testid={`cloud-service-dashboard-${dashboardId ?? dashboard.title}`}
{...interactiveProps}
>
<div className="aws-service-dashboard-item-content">
diff --git a/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx b/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx
index 5173837918..63b93a5893 100644
--- a/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx
+++ b/frontend/src/container/Integrations/CloudIntegration/ServicesList.tsx
@@ -137,6 +137,7 @@ function ServicesList({
active: service.id === activeService,
})}
key={service.id}
+ data-testid={`cloud-service-item-${service.id}`}
onClick={(): void => handleActiveService(service.id)}
>
<img
@@ -155,7 +156,7 @@ function ServicesList({
<div className="aws-services-list-view">
<div className="aws-services-list-view-sidebar">
<div className="aws-services-list-view-sidebar-content">
- <div className="aws-services-enabled">
+ <div className="aws-services-enabled" data-testid="cloud-services-enabled">
<div className="aws-services-list-view-sidebar-content-header">
Enabled
</div>
@@ -169,7 +170,10 @@ function ServicesList({
</div>
{!isNotEnabledServicesEmpty && (
- <div className="aws-services-not-enabled">
+ <div
+ className="aws-services-not-enabled"
+ data-testid="cloud-services-not-enabled"
+ >
<div className="aws-services-list-view-sidebar-content-header">
Not Enabled
</div>
diff --git a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Configure.tsx b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Configure.tsx
index afe5569118..a2a8bc2b7c 100644
--- a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Configure.tsx
+++ b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Configure.tsx
@@ -48,6 +48,7 @@ function Configure(props: ConfigurationProps): JSX.Element {
{configuration.map((config, index) => (
<Button
key={config.title}
+ data-testid="integration-configure-step"
type="text"
className={cx('configure-menu-item', {
active: selectedConfigStep === index,
diff --git a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/DataCollected.tsx b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/DataCollected.tsx
index c529c92d2d..ebec414aa1 100644
--- a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/DataCollected.tsx
+++ b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/DataCollected.tsx
@@ -57,6 +57,7 @@ function DataCollected(props: DataCollectedProps): JSX.Element {
<Typography.Text>Logs</Typography.Text>
</div>
<Table
+ data-testid="integration-logs-table"
columns={logsColumns}
rowClassName={(_, index): string =>
index % 2 === 0 ? 'table-row-dark' : ''
@@ -72,6 +73,7 @@ function DataCollected(props: DataCollectedProps): JSX.Element {
<Typography.Text>Metrics</Typography.Text>
</div>
<Table
+ data-testid="integration-metrics-table"
columns={metricsColumns}
rowClassName={(_, index): string =>
index % 2 === 0 ? 'table-row-dark' : ''
diff --git a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Overview.tsx b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Overview.tsx
index 5085e88a32..7677858cdd 100644
--- a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Overview.tsx
+++ b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailContentTabs/Overview.tsx
@@ -32,7 +32,11 @@ function Overview(props: OverviewProps): JSX.Element {
<Typography.Text className="heading">Category</Typography.Text>
<div className="category-tabs">
{categories.map((category) => (
- <div key={category} className="category-tab">
+ <div
+ key={category}
+ className="category-tab"
+ data-testid="integration-category"
+ >
{category}
</div>
))}
@@ -40,7 +44,7 @@ function Overview(props: OverviewProps): JSX.Element {
</div>
<div className="integration-detail-overview-assets">
<Typography.Text className="heading">Assets</Typography.Text>
- <ul className="assets-list">
+ <ul className="assets-list" data-testid="integration-assets">
{assetsCount.map((count, index) => {
if (count === 0) {
return undefined;
diff --git a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailHeader.tsx b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailHeader.tsx
index a6e242ddc3..74aed05bf4 100644
--- a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailHeader.tsx
+++ b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationDetailHeader.tsx
@@ -143,6 +143,7 @@ function IntegrationDetailHeader(
</div>
</div>
<Button
+ data-testid="integration-connect-btn"
className={cx(
'configure-btn',
!isConnectionStateNotInstalled && 'test-connection',
@@ -191,6 +192,7 @@ function IntegrationDetailHeader(
)}
>
<Button
+ data-testid="integration-modal-secondary-btn"
type="text"
icon={
isConnectionStateNotInstalled ? <ConfigureIcon /> : <Check size={14} />
@@ -211,6 +213,7 @@ function IntegrationDetailHeader(
</Button>
{isConnectionStatePending && (
<Button
+ data-testid="integration-modal-primary-btn"
type="primary"
icon={
isConnectionStateNotInstalled ? <Check size={14} /> : <ConfigureIcon />
diff --git a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationsUninstallBar.tsx b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationsUninstallBar.tsx
index c7d059477a..ddc685842a 100644
--- a/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationsUninstallBar.tsx
+++ b/frontend/src/container/Integrations/IntegrationDetailPage/IntegrationsUninstallBar.tsx
@@ -76,6 +76,7 @@ function IntergrationsUninstallBar(
</Typography.Text>
</div>
<Button
+ data-testid="integration-remove-btn"
className="uninstall-integration-btn"
icon={<X size={14} />}
onClick={(): void => showModal()}
@@ -92,6 +93,7 @@ function IntergrationsUninstallBar(
okButtonProps={{
danger: true,
disabled: isUninstallLoading,
+ 'data-testid': 'integration-remove-confirm',
}}
>
<Typography.Text className="remove-integration-text">
diff --git a/frontend/src/container/Integrations/IntegrationDetailPage/TestConnection.tsx b/frontend/src/container/Integrations/IntegrationDetailPage/TestConnection.tsx
index 65fde44829..2c7ed8850a 100644
--- a/frontend/src/container/Integrations/IntegrationDetailPage/TestConnection.tsx
+++ b/frontend/src/container/Integrations/IntegrationDetailPage/TestConnection.tsx
@@ -24,7 +24,11 @@ interface TestConnectionProps {
function TestConnection(props: TestConnectionProps): JSX.Element {
const { connectionState } = props;
return (
- <div className={cx('connection-container', connectionState)}>
+ <div
+ className={cx('connection-container', connectionState)}
+ data-testid="integration-connection-status"
+ data-state={connectionState}
+ >
<ul className="connection-text">
<li>{ConnectionStatesLabelMap[connectionState]}</li>
</ul>
diff --git a/frontend/src/container/Integrations/IntegrationsList/IntegrationsList.tsx b/frontend/src/container/Integrations/IntegrationsList/IntegrationsList.tsx
index 0ac9ebe6d8..a0e7abeb7b 100644
--- a/frontend/src/container/Integrations/IntegrationsList/IntegrationsList.tsx
+++ b/frontend/src/container/Integrations/IntegrationsList/IntegrationsList.tsx
@@ -138,6 +138,7 @@ function IntegrationsList(props: IntegrationsListProps): JSX.Element {
<div
className="integrations-list-item"
key={integration.id}
+ data-testid={`integration-row-${integration.id}`}
onClick={(): void => handleSelectedIntegration(integration)}
>
<div className="integrations-list-item-column title-column">
@@ -157,7 +158,10 @@ function IntegrationsList(props: IntegrationsListProps): JSX.Element {
<div className="integrations-list-item-published-by">SigNoz</div>
</div>
<div className="integrations-list-item-column">
- <div className="integrations-list-item-installation-status">
+ <div
+ className="integrations-list-item-installation-status"
+ data-testid="integration-row-status"
+ >
<Badge
color={integration.is_installed ? 'success' : 'warning'}
variant="outlined"
diff --git a/frontend/src/container/Integrations/OneClickIntegrations/OneClickIntegrations.tsx b/frontend/src/container/Integrations/OneClickIntegrations/OneClickIntegrations.tsx
index 4ce91645e9..4e523d0563 100644
--- a/frontend/src/container/Integrations/OneClickIntegrations/OneClickIntegrations.tsx
+++ b/frontend/src/container/Integrations/OneClickIntegrations/OneClickIntegrations.tsx
@@ -71,6 +71,7 @@ function OneClickIntegrations(props: OneClickIntegrationsProps): JSX.Element {
<div
className="one-click-integrations-list-item"
key={integration.id}
+ data-testid={`one-click-integration-${integration.id}`}
onClick={(): void => handleSelectedIntegration(integration)}
>
<div className="one-click-integrations-list-item-title">
diff --git a/frontend/src/container/LiveLogs/LiveLogsList/index.tsx b/frontend/src/container/LiveLogs/LiveLogsList/index.tsx
index 202e0bebe2..3663ee4d03 100644
--- a/frontend/src/container/LiveLogs/LiveLogsList/index.tsx
+++ b/frontend/src/container/LiveLogs/LiveLogsList/index.tsx
@@ -187,7 +187,7 @@ function LiveLogsList({
);
return (
- <div className="live-logs-list">
+ <div className="live-logs-list" data-testid="live-logs-list">
{(formattedLogs.length === 0 || isLoading || isLoadingList) &&
renderLoading()}
@@ -204,6 +204,7 @@ function LiveLogsList({
cellTypographySize={options.fontSize}
data={formattedLogs}
isLoading={false}
+ getRowTestId={(log): string => `logs-table-row-${log.id}`}
isRowActive={(log): boolean => log.id === activeLog?.id}
getRowClassName={(log): string =>
log.id === activeLogId ? 'logs-linked-row' : ''
diff --git a/frontend/src/container/LiveLogs/LiveLogsPauseResume/LiveLogsPauseResume.tsx b/frontend/src/container/LiveLogs/LiveLogsPauseResume/LiveLogsPauseResume.tsx
index e5c85f9df2..432be9c748 100644
--- a/frontend/src/container/LiveLogs/LiveLogsPauseResume/LiveLogsPauseResume.tsx
+++ b/frontend/src/container/LiveLogs/LiveLogsPauseResume/LiveLogsPauseResume.tsx
@@ -80,6 +80,7 @@ function LiveLogsPauseResume(): JSX.Element {
onClick={onLiveButtonClick}
type="primary"
className={`periscope-btn ${isPlaying ? 'warning' : 'success'}`}
+ data-testid="live-logs-pause-resume"
>
{isPlaying ? 'Pause' : 'Resume'}
</Button>
diff --git a/frontend/src/container/LogDetailedView/ContextView/ContextLogRenderer.tsx b/frontend/src/container/LogDetailedView/ContextView/ContextLogRenderer.tsx
index 4745ffaadf..4e5a9f9785 100644
--- a/frontend/src/container/LogDetailedView/ContextView/ContextLogRenderer.tsx
+++ b/frontend/src/container/LogDetailedView/ContextView/ContextLogRenderer.tsx
@@ -129,6 +129,7 @@ function ContextLogRenderer({
type="text"
size="small"
className="context-log-renderer__item"
+ data-testid={`context-log-item-${logTorender.id}`}
onClick={(): void => {
handleLogClick(logTorender.id);
}}
diff --git a/frontend/src/container/Login/__tests__/Login.test.tsx b/frontend/src/container/Login/__tests__/Login.test.tsx
index 039bd81ad4..668458809b 100644
--- a/frontend/src/container/Login/__tests__/Login.test.tsx
+++ b/frontend/src/container/Login/__tests__/Login.test.tsx
@@ -988,4 +988,195 @@ describe('Login Component', () => {
});
});
});
+
+ describe('Enter key submission', () => {
+ const EMAIL_PASSWORD_ENDPOINT = '*/api/v2/sessions/email_password';
+
+ async function typeEmail(
+ user: ReturnType<typeof userEvent.setup>,
+ email: string,
+ ): Promise<HTMLElement> {
+ const emailInput = await waitFor(() => {
+ const input = screen.getByTestId('email');
+ expect(input).not.toBeDisabled();
+ return input;
+ });
+ await user.type(emailInput, email);
+ return emailInput;
+ }
+
+ it('fetches the sessions context once on Enter in the email field', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let contextCalls = 0;
+
+ server.use(
+ rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) => {
+ contextCalls += 1;
+ return res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth }));
+ }),
+ );
+
+ render(<Login />);
+
+ await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
+
+ await screen.findByTestId('password');
+ expect(contextCalls).toBe(1);
+ });
+
+ // Bug: the email onPressEnter calls onNextHandler without checking isEmailValid (container/Login/index.tsx:329).
+ it.skip('does not fetch the sessions context on Enter with an invalid email', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let contextCalls = 0;
+
+ server.use(
+ rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) => {
+ contextCalls += 1;
+ return res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth }));
+ }),
+ );
+
+ render(<Login />);
+
+ await typeEmail(user, 'not-an-email');
+ expect(screen.getByTestId('initiate_login')).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ await user.keyboard('{enter}');
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(contextCalls).toBe(0);
+ });
+
+ it('signs in once on Enter in the password field', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let loginCalls = 0;
+
+ server.use(
+ rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
+ ),
+ rest.post(EMAIL_PASSWORD_ENDPOINT, (_, res, ctx) => {
+ loginCalls += 1;
+ return res(
+ ctx.status(200),
+ ctx.json({ status: 'success', data: mockEmailPasswordResponse }),
+ );
+ }),
+ );
+
+ render(<Login />);
+
+ await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
+ await user.type(
+ await screen.findByTestId('password'),
+ 'testpassword{enter}',
+ );
+
+ await waitFor(() => {
+ expect(localStorage.getItem('AUTH_TOKEN')).toBe('mock-access-token');
+ });
+ expect(loginCalls).toBe(1);
+ });
+
+ it('does not sign in on Enter while the password is empty', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let loginCalls = 0;
+
+ server.use(
+ rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
+ ),
+ rest.post(EMAIL_PASSWORD_ENDPOINT, (_, res, ctx) => {
+ loginCalls += 1;
+ return res(
+ ctx.status(200),
+ ctx.json({ status: 'success', data: mockEmailPasswordResponse }),
+ );
+ }),
+ );
+
+ render(<Login />);
+
+ await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
+ const passwordInput = await screen.findByTestId('password');
+ expect(screen.getByTestId('password_authn_submit')).toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+
+ await user.type(passwordInput, '{enter}');
+
+ // Give a wrongly sent request time to land before asserting it never did.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(loginCalls).toBe(0);
+ });
+
+ it('does not sign in again on Enter while the first sign in is loading', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let loginCalls = 0;
+
+ server.use(
+ rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: mockSingleOrgPasswordAuth })),
+ ),
+ rest.post(EMAIL_PASSWORD_ENDPOINT, (_, res, ctx) => {
+ loginCalls += 1;
+ return res(
+ ctx.delay(1000),
+ ctx.status(200),
+ ctx.json({ status: 'success', data: mockEmailPasswordResponse }),
+ );
+ }),
+ );
+
+ render(<Login />);
+
+ const emailInput = await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
+ await user.type(
+ await screen.findByTestId('password'),
+ 'testpassword{enter}',
+ );
+
+ const submitButton = screen.getByTestId('password_authn_submit');
+ await waitFor(() => {
+ expect(submitButton).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ // The password input is disabled while submitting; the email input is not.
+ await user.type(emailInput, '{enter}');
+
+ await waitFor(() => {
+ expect(localStorage.getItem('AUTH_TOKEN')).toBe('mock-access-token');
+ });
+ expect(loginCalls).toBe(1);
+ });
+
+ it('redirects to the SSO url on Enter for a callback org', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ Object.defineProperty(window, 'location', {
+ value: { href: 'http://localhost/' },
+ writable: true,
+ });
+
+ server.use(
+ rest.get(SESSIONS_CONTEXT_ENDPOINT, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: mockSingleOrgCallbackAuth })),
+ ),
+ );
+
+ render(<Login />);
+
+ const emailInput = await typeEmail(user, `${PASSWORD_AUTHN_EMAIL}{enter}`);
+ await screen.findByTestId('callback_authn_submit');
+
+ await user.type(emailInput, '{enter}');
+
+ await waitFor(() => {
+ expect(window.location.href).toBe(CALLBACK_AUTHN_URL);
+ });
+ });
+ });
});
diff --git a/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx b/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx
index 009094216f..ad05237c34 100644
--- a/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx
+++ b/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx
@@ -67,6 +67,7 @@ function LogsActionsContainer({
textPlacement="right"
value={showFrequencyChart}
onChange={handleToggleFrequencyChart}
+ testId="logs-frequency-chart-toggle"
/>
</div>
</div>
diff --git a/frontend/src/container/LogsExplorerViews/index.tsx b/frontend/src/container/LogsExplorerViews/index.tsx
index d1f963ae03..c733f26bdd 100644
--- a/frontend/src/container/LogsExplorerViews/index.tsx
+++ b/frontend/src/container/LogsExplorerViews/index.tsx
@@ -217,8 +217,16 @@ function LogsExplorerViewsContainer({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [data?.payload, data?.warning]);
+ const isNextPageRequestedRef = useRef(false);
+
+ useEffect(() => {
+ if (!isFetching) {
+ isNextPageRequestedRef.current = false;
+ }
+ }, [isFetching]);
+
const handleEndReached = useCallback(() => {
- if (!listQuery) {
+ if (!listQuery || isNextPageRequestedRef.current) {
return;
}
@@ -247,6 +255,8 @@ function LogsExplorerViewsContainer({
pageSize: nextPageSize,
});
+ isNextPageRequestedRef.current = true;
+
setPage((prevPage) => prevPage + 1);
setRequestData(newRequestData);
diff --git a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerEndReached.test.tsx b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerEndReached.test.tsx
new file mode 100644
index 0000000000..f60881e7f5
--- /dev/null
+++ b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerEndReached.test.tsx
@@ -0,0 +1,166 @@
+import { VirtuosoMockContext } from 'react-virtuoso';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import ROUTES from 'constants/routes';
+import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQueryRange';
+import { PreferenceContextProvider } from 'providers/preferences/context/PreferenceContextProvider';
+import { QueryBuilderContext } from 'providers/QueryBuilder';
+import { mockAppLocation } from 'tests/router-mocks';
+import { act, render } from 'tests/test-utils';
+import { Query } from 'types/api/queryBuilder/queryBuilderData';
+
+import LogsExplorerViews from '..';
+import {
+ logsQueryRangeSuccessNewFormatResponse,
+ mockQueryBuilderContextValue,
+} from './mock';
+
+let mockOnEndReached: () => void = () => {};
+let mockIsFetching = false;
+
+mockAppLocation({ pathname: ROUTES.LOGS_EXPLORER });
+
+jest.mock('hooks/queryBuilder/useGetExplorerQueryRange', () => ({
+ __esModule: true,
+ useGetExplorerQueryRange: jest.fn(),
+}));
+
+jest.mock('hooks/useSafeNavigate', () => ({
+ useSafeNavigate: (): any => ({ safeNavigate: jest.fn() }),
+}));
+
+jest.mock('hooks/useUrlQueryData', () => {
+ const actual = jest.requireActual('hooks/useUrlQueryData');
+ return {
+ __esModule: true,
+ default: (key: string, ...rest: unknown[]): unknown =>
+ key === 'pageSize'
+ ? { queryData: 1, redirectWithQuery: jest.fn() }
+ : actual.default(key, ...rest),
+ };
+});
+
+jest.mock('hooks/logs/useCopyLogLink', () => ({
+ useCopyLogLink: jest.fn().mockReturnValue({ activeLogId: undefined }),
+}));
+
+jest.mock('providers/preferences/sync/usePreferenceSync', () => ({
+ usePreferenceSync: (): any => ({
+ preferences: {
+ columns: [],
+ formatting: { maxLines: 1, format: 'table', fontSize: 'small', version: 1 },
+ },
+ loading: false,
+ error: null,
+ updateColumns: jest.fn(),
+ updateFormatting: jest.fn(),
+ }),
+}));
+
+jest.mock('container/LogsExplorerChart', () => (): JSX.Element => <div />);
+
+jest.mock(
+ 'container/LogsExplorerList',
+ () =>
+ function MockLogsExplorerList({
+ onEndReached,
+ }: {
+ onEndReached: () => void;
+ }): JSX.Element {
+ mockOnEndReached = onEndReached;
+ return <div>list</div>;
+ },
+);
+
+const getRequestedOffsets = (): number[] => {
+ const offsets: number[] = [];
+ (useGetExplorerQueryRange as jest.Mock).mock.calls.forEach(([query]) => {
+ const offset = (query as Query | null)?.builder.queryData[0]?.offset;
+ if (typeof offset === 'number' && offsets[offsets.length - 1] !== offset) {
+ offsets.push(offset);
+ }
+ });
+ return offsets;
+};
+
+function views(): JSX.Element {
+ return (
+ <VirtuosoMockContext.Provider
+ value={{ viewportHeight: 300, itemHeight: 100 }}
+ >
+ <QueryBuilderContext.Provider
+ value={{
+ ...mockQueryBuilderContextValue,
+ panelType: PANEL_TYPES.LIST,
+ }}
+ >
+ <PreferenceContextProvider>
+ <LogsExplorerViews
+ setIsLoadingQueries={(): void => {}}
+ listQueryKeyRef={{ current: {} }}
+ chartQueryKeyRef={{ current: {} }}
+ setWarning={(): void => {}}
+ showLiveLogs={false}
+ handleChangeSelectedView={(): void => {}}
+ />
+ </PreferenceContextProvider>
+ </QueryBuilderContext.Provider>
+ </VirtuosoMockContext.Provider>
+ );
+}
+
+describe('LogsExplorerViews infinite scroll', () => {
+ beforeEach(() => {
+ (useGetExplorerQueryRange as jest.Mock).mockReset();
+ mockIsFetching = false;
+ const resultByQuery = new WeakMap<object, object>();
+ (useGetExplorerQueryRange as jest.Mock).mockImplementation(
+ (query: Query | null) => {
+ const key = query ?? resultByQuery;
+ if (!resultByQuery.has(key)) {
+ resultByQuery.set(key, {
+ data: { payload: logsQueryRangeSuccessNewFormatResponse },
+ isLoading: false,
+ });
+ }
+ return { ...resultByQuery.get(key), isFetching: mockIsFetching };
+ },
+ );
+ });
+
+ it('requests each page once when the end is reached again before the page loads', () => {
+ render(views());
+
+ act(() => {
+ mockOnEndReached();
+ });
+ act(() => {
+ mockOnEndReached();
+ });
+ act(() => {
+ mockOnEndReached();
+ });
+
+ expect(getRequestedOffsets()).toStrictEqual([0, 1]);
+ });
+
+ it('requests the next page once the previous one has loaded', () => {
+ const { rerender } = render(views());
+
+ act(() => {
+ mockIsFetching = true;
+ mockOnEndReached();
+ });
+ act(() => {
+ mockOnEndReached();
+ });
+ act(() => {
+ mockIsFetching = false;
+ rerender(views());
+ });
+ act(() => {
+ mockOnEndReached();
+ });
+
+ expect(getRequestedOffsets()).toStrictEqual([0, 1, 2]);
+ });
+});
diff --git a/frontend/src/container/MembersSettings/MembersSettings.tsx b/frontend/src/container/MembersSettings/MembersSettings.tsx
index 72b2e4cbaf..4bd0a525a3 100644
--- a/frontend/src/container/MembersSettings/MembersSettings.tsx
+++ b/frontend/src/container/MembersSettings/MembersSettings.tsx
@@ -184,6 +184,7 @@ function MembersSettings(): JSX.Element {
suffix={
<ChevronDown size={12} className="members-filter-trigger__chevron" />
}
+ testId="members-filter-trigger"
>
<span>{filterLabel}</span>
</Button>
@@ -200,6 +201,7 @@ function MembersSettings(): JSX.Element {
}}
className="members-search-input"
name="members-search"
+ testId="members-search-input"
/>
</div>
@@ -209,6 +211,7 @@ function MembersSettings(): JSX.Element {
color="primary"
onClick={(): void => void setIsInviteModalOpen(true)}
prefix={<Plus size={12} />}
+ testId="invite-member-btn"
>
Invite member
</Button>
diff --git a/frontend/src/container/MembersSettings/components/InviteMembersModal/InviteMembersModal.tsx b/frontend/src/container/MembersSettings/components/InviteMembersModal/InviteMembersModal.tsx
index 595e2522cf..22979fcf1b 100644
--- a/frontend/src/container/MembersSettings/components/InviteMembersModal/InviteMembersModal.tsx
+++ b/frontend/src/container/MembersSettings/components/InviteMembersModal/InviteMembersModal.tsx
@@ -66,6 +66,7 @@ function InviteMembersModal({
disabled={!canSubmit}
disabledTooltip="Add at least one team member to invite"
loading={isSubmitting}
+ testId="invite-submit-btn"
>
{isSubmitting ? 'Inviting...' : 'Invite Team Members'}
</Button>
diff --git a/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx b/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx
index 179e71ea3f..302aeccead 100644
--- a/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx
+++ b/frontend/src/container/MeterExplorer/Breakdown/BreakDown.tsx
@@ -94,7 +94,10 @@ function Section(section: MetricSection): JSX.Element {
);
return (
- <div className="meter-column-graph">
+ <div
+ className="meter-column-graph"
+ data-testid={`meter-breakdown-section-${title.toLowerCase()}`}
+ >
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<Typography.Text className="section-title">{title}</Typography.Text>
</CardContainer>
diff --git a/frontend/src/container/MetricsApplication/TopOperationsTable.tsx b/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
index d75e82e408..19a51e60ce 100644
--- a/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
+++ b/frontend/src/container/MetricsApplication/TopOperationsTable.tsx
@@ -117,6 +117,7 @@ function TopOperationsTable({
render: (text: string): JSX.Element => (
<Tooltip placement="topLeft" title={text}>
<Typography.Link
+ testId="top-operation-link"
onClick={(e): void => {
e.stopPropagation();
e.preventDefault();
@@ -201,7 +202,7 @@ function TopOperationsTable({
};
return (
- <div className="top-operation">
+ <div className="top-operation" data-testid="top-operations">
<div className="top-operation__controls">
<div className="top-operation__download">
<Download
@@ -212,6 +213,8 @@ function TopOperationsTable({
</div>
<div className="top-operation__entry-point">
<Switch
+ testId="top-operations-entrypoint-toggle"
+ aria-label="Entrypoint Spans"
color="primary"
textPlacement="right"
value={isEntryPoint}
diff --git a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
index 4a28041816..0ad58354c2 100644
--- a/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
+++ b/frontend/src/container/MetricsExplorer/Explorer/Explorer.tsx
@@ -317,6 +317,7 @@ function Explorer(): JSX.Element {
)}
<span>1 chart/query</span>
<Switch
+ testId="metrics-explorer-one-chart-per-query"
color="primary"
textPlacement="right"
value={showOneChartPerQuery}
diff --git a/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx b/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx
index 56cccf2421..1d0c5950af 100644
--- a/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx
+++ b/frontend/src/container/MetricsExplorer/Explorer/__tests__/Explorer.test.tsx
@@ -309,7 +309,7 @@ describe('Explorer', () => {
renderExplorer();
const oneChartPerQueryToggle = screen.getByRole('switch');
- expect(oneChartPerQueryToggle).toBeEnabled();
+ expect(oneChartPerQueryToggle).not.toHaveAttribute('aria-disabled', 'true');
});
it('one chart per query toggle should be enabled when multiple metrics have no unit', () => {
@@ -352,7 +352,7 @@ describe('Explorer', () => {
const oneChartPerQueryToggle = screen.getByRole('switch');
// Toggle should be enabled (not forced/disabled) since both metrics
// have the same unit (no unit) and should be viewable on the same graph
- expect(oneChartPerQueryToggle).toBeEnabled();
+ expect(oneChartPerQueryToggle).not.toHaveAttribute('aria-disabled', 'true');
expect(oneChartPerQueryToggle).not.toBeChecked();
});
diff --git a/frontend/src/container/MetricsExplorer/Inspect/GraphView.tsx b/frontend/src/container/MetricsExplorer/Inspect/GraphView.tsx
index 8ac93a4688..d78ee9659e 100644
--- a/frontend/src/container/MetricsExplorer/Inspect/GraphView.tsx
+++ b/frontend/src/container/MetricsExplorer/Inspect/GraphView.tsx
@@ -200,13 +200,19 @@ function GraphView({
>
{metricName}
</Button>
- <Button className="time-series-button-label" size="middle" disabled>
+ <Button
+ className="time-series-button-label"
+ size="middle"
+ disabled
+ data-testid="inspect-time-series-count"
+ >
{/* First time series in that of timestamps. Hence -1 */}
{`${formattedInspectMetricsTimeSeries.length - 1} time series`}
</Button>
</Button.Group>
<div className="view-toggle-button">
<Switch
+ testId="inspect-view-toggle"
color="primary"
textPlacement="right"
value={viewType === 'graph'}
diff --git a/frontend/src/container/MetricsExplorer/Inspect/Inspect.tsx b/frontend/src/container/MetricsExplorer/Inspect/Inspect.tsx
index 45d487492a..1ee9c825db 100644
--- a/frontend/src/container/MetricsExplorer/Inspect/Inspect.tsx
+++ b/frontend/src/container/MetricsExplorer/Inspect/Inspect.tsx
@@ -304,7 +304,10 @@ function Inspect({
className="inspect-metrics-modal"
destroyOnClose
>
- <div className="inspect-metrics-content">
+ <div
+ className="inspect-metrics-content"
+ data-testid="inspect-metrics-content"
+ >
<div className="inspect-metrics-content-first-col">
{chartArea}
<QueryBuilder
diff --git a/frontend/src/container/MetricsExplorer/Inspect/QueryBuilder.tsx b/frontend/src/container/MetricsExplorer/Inspect/QueryBuilder.tsx
index cdb414d560..9d41c5a6e7 100644
--- a/frontend/src/container/MetricsExplorer/Inspect/QueryBuilder.tsx
+++ b/frontend/src/container/MetricsExplorer/Inspect/QueryBuilder.tsx
@@ -52,6 +52,7 @@ function QueryBuilder({
onStageRunQuery={applyInspectionOptions}
handleCancelQuery={handleCancelQuery}
isLoadingQueries={isLoadingQueries}
+ testId="inspect-run-query"
/>
</div>
<Card className="inspect-metrics-query-builder-content">
diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx
index bde6f4da8f..3eab59b8ba 100644
--- a/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx
+++ b/frontend/src/container/MetricsExplorer/MetricDetails/AllAttributes.tsx
@@ -218,7 +218,7 @@ function AllAttributes({
}
}}
>
- <Button type="text">
+ <Button type="text" data-testid={`attribute-key-${field.label}`}>
<Typography.Text>{field.label}</Typography.Text>
</Button>
</Popover>
@@ -273,6 +273,7 @@ function AllAttributes({
</Tooltip>
</div>
<Input
+ data-testid="all-attributes-search"
className="all-attributes-search-input"
placeholder="Search"
value={searchString}
@@ -291,6 +292,7 @@ function AllAttributes({
key: 'all-attributes',
children: (
<ResizeTable
+ data-testid="all-attributes-table"
columns={columns}
loading={isLoadingAttributes}
tableLayout="fixed"
diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx
index 2036b920da..d73e9ca916 100644
--- a/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx
+++ b/frontend/src/container/MetricsExplorer/MetricDetails/Metadata.tsx
@@ -298,6 +298,7 @@ function Metadata({
type="text"
onClick={cancelEdit}
disabled={isUpdatingMetricsMetadata}
+ data-testid="metadata-cancel-button"
>
<X size={14} />
<Typography.Text>Cancel</Typography.Text>
@@ -310,6 +311,7 @@ function Metadata({
handleSave();
}}
disabled={isUpdatingMetricsMetadata}
+ data-testid="metadata-save-button"
>
<Save size={14} />
<Typography.Text>Save</Typography.Text>
@@ -330,6 +332,7 @@ function Metadata({
setIsEditing(true);
}}
disabled={isUpdatingMetricsMetadata || isLoadingMetricMetadata}
+ data-testid="metadata-edit-button"
>
<PenLine size={14} />
<Typography.Text>Edit</Typography.Text>
@@ -368,6 +371,7 @@ function Metadata({
</div>
) : (
<ResizeTable
+ data-testid="metric-metadata-table"
columns={columns}
tableLayout="fixed"
dataSource={tableData}
diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsx
index 5a7128235e..f4b03891d0 100644
--- a/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsx
+++ b/frontend/src/container/MetricsExplorer/MetricDetails/MetricDetails.tsx
@@ -139,7 +139,7 @@ function MetricDetails({
width="60%"
title={
<div className="metric-details-header">
- <div className="metric-details-title">
+ <div className="metric-details-title" data-testid="metric-details-title">
<Divider type="vertical" />
<Typography.Text>{metricName}</Typography.Text>
</div>
diff --git a/frontend/src/container/MetricsExplorer/Summary/MetricNameSearch.tsx b/frontend/src/container/MetricsExplorer/Summary/MetricNameSearch.tsx
index 474390bdeb..54ca7a4662 100644
--- a/frontend/src/container/MetricsExplorer/Summary/MetricNameSearch.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/MetricNameSearch.tsx
@@ -204,6 +204,7 @@ function MetricNameSearch({
ref={inputRef}
onKeyDown={handleKeyDown}
placeholder="Search..."
+ data-testid="metric-name-search-input"
value={searchString}
onChange={handleInputChange}
bordered
@@ -233,6 +234,8 @@ function MetricNameSearch({
<Button
type="text"
shape="circle"
+ data-testid="metric-name-search-button"
+ aria-label="Search metric name"
onClick={(e): void => {
e.stopPropagation();
}}
diff --git a/frontend/src/container/MetricsExplorer/Summary/MetricsSearch.tsx b/frontend/src/container/MetricsExplorer/Summary/MetricsSearch.tsx
index c5d0e465f1..89a7c5e832 100644
--- a/frontend/src/container/MetricsExplorer/Summary/MetricsSearch.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/MetricsSearch.tsx
@@ -60,6 +60,7 @@ function MetricsSearch({
onStageRunQuery={handleStageAndRunQuery}
isLoadingQueries={isLoading}
handleCancelQuery={handleCancelQuery}
+ testId="metrics-summary-run-query"
/>
<div className="metrics-search-options">
<DateTimeSelectionV2
diff --git a/frontend/src/container/MetricsExplorer/Summary/MetricsTable.tsx b/frontend/src/container/MetricsExplorer/Summary/MetricsTable.tsx
index e7d92e18e1..0672eb7a50 100644
--- a/frontend/src/container/MetricsExplorer/Summary/MetricsTable.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/MetricsTable.tsx
@@ -73,6 +73,7 @@ function MetricsTable({
<ErrorInPlace error={error} />
) : (
<Table
+ data-testid="metrics-table"
loading={{
spinning: isLoading,
indicator: (
diff --git a/frontend/src/container/MetricsExplorer/Summary/MetricsTreemap.tsx b/frontend/src/container/MetricsExplorer/Summary/MetricsTreemap.tsx
index 1de39bfb07..4a2d2efa8f 100644
--- a/frontend/src/container/MetricsExplorer/Summary/MetricsTreemap.tsx
+++ b/frontend/src/container/MetricsExplorer/Summary/MetricsTreemap.tsx
@@ -156,6 +156,7 @@ function MetricsTreemapInternal({
placement="top"
>
<foreignObject
+ data-testid={`metrics-treemap-tile-${node.data.id}`}
width={nodeWidth}
height={nodeHeight}
onClick={(): void => openMetricDetails(node.data.id, 'treemap')}
@@ -201,6 +202,7 @@ function MetricsTreemap({
</Tooltip>
</div>
<Select
+ data-testid="metrics-treemap-view-select"
options={TREEMAP_VIEW_OPTIONS}
value={viewType}
onChange={setHeatmapView}
diff --git a/frontend/src/container/MetricsExplorer/VolumeControl/components/VolumeControlBadge.tsx b/frontend/src/container/MetricsExplorer/VolumeControl/components/VolumeControlBadge.tsx
index 5e668f8864..0ec9f872fd 100644
--- a/frontend/src/container/MetricsExplorer/VolumeControl/components/VolumeControlBadge.tsx
+++ b/frontend/src/container/MetricsExplorer/VolumeControl/components/VolumeControlBadge.tsx
@@ -11,7 +11,7 @@ interface VolumeControlBadgeProps {
function VolumeControlBadge({ rule }: VolumeControlBadgeProps): JSX.Element {
const badge = (
<Badge
- testId="vc-badge-active"
+ testId={rule.active ? 'vc-badge-active' : 'vc-badge-pending'}
variant="outlined"
color={rule.active ? 'success' : 'warning'}
prefix={<Gauge size={12} />}
diff --git a/frontend/src/container/MySettings/TimezoneAdaptation/TimezoneAdaptation.tsx b/frontend/src/container/MySettings/TimezoneAdaptation/TimezoneAdaptation.tsx
index d9addc21d3..2ebbede7e1 100644
--- a/frontend/src/container/MySettings/TimezoneAdaptation/TimezoneAdaptation.tsx
+++ b/frontend/src/container/MySettings/TimezoneAdaptation/TimezoneAdaptation.tsx
@@ -80,6 +80,7 @@ function TimezoneAdaptation(): JSX.Element {
<button
type="button"
className="timezone-adaption__clear-override"
+ data-testid="timezone-clear-override"
onClick={handleOverrideClear}
>
<Delete height={12} width={12} color={Color.BG_ROBIN_300} />
diff --git a/frontend/src/container/MySettings/UserInfo/index.tsx b/frontend/src/container/MySettings/UserInfo/index.tsx
index de63b95e31..8258af7499 100644
--- a/frontend/src/container/MySettings/UserInfo/index.tsx
+++ b/frontend/src/container/MySettings/UserInfo/index.tsx
@@ -124,7 +124,9 @@ function UserInfo(): JSX.Element {
return (
<div className="user-info-card">
<div className="user-info">
- <div className="user-name">{user.displayName}</div>
+ <div className="user-name" data-testid="user-info-name">
+ {user.displayName}
+ </div>
<div className="user-info-subsection">
<div className="user-email">
@@ -143,6 +145,7 @@ function UserInfo(): JSX.Element {
className="periscope-btn secondary"
icon={<FileTerminal size={16} />}
onClick={(): void => setIsUpdateNameModalOpen(true)}
+ data-testid="update-name-open-btn"
>
Update name
</Button>
@@ -152,6 +155,7 @@ function UserInfo(): JSX.Element {
className="periscope-btn secondary"
icon={<FileTerminal size={16} />}
onClick={(): void => setIsResetPasswordModalOpen(true)}
+ data-testid="reset-password-open-btn"
>
Reset password
</Button>
@@ -180,6 +184,7 @@ function UserInfo(): JSX.Element {
<div className="update-name-input">
<Input
placeholder="e.g. John Doe"
+ data-testid="update-name-input"
value={changedName}
disabled={isLoading}
onChange={(e): void => setChangedName(e.target.value)}
diff --git a/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx b/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx
index b46e32d3bc..7601837b30 100644
--- a/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx
+++ b/frontend/src/container/OnboardingQuestionaire/__tests__/OnboardingQuestionaire.test.tsx
@@ -1,5 +1,7 @@
+import ROUTES from 'constants/routes';
+import { navigate } from 'lib/router/navigation';
import { rest, server } from 'mocks-server/server';
-import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import OnboardingQuestionaire from '../index';
@@ -9,6 +11,21 @@ jest.mock('lib/router/navigation', () => ({
navigate: jest.fn(),
}));
+const mockNavigate = navigate as jest.MockedFunction<typeof navigate>;
+
+const mockNotificationError = jest.fn();
+
+jest.mock('hooks/useNotifications', () => ({
+ useNotifications: (): unknown => ({
+ notifications: {
+ success: jest.fn(),
+ error: mockNotificationError,
+ warning: jest.fn(),
+ info: jest.fn(),
+ },
+ }),
+}));
+
// API Endpoints
const ORG_PREFERENCES_ENDPOINT = '*/api/v1/org/preferences/list';
const UPDATE_ORG_PREFERENCE_ENDPOINT = '*/api/v1/org/preferences/name/update';
@@ -346,4 +363,409 @@ describe('OnboardingQuestionaire Component', () => {
).resolves.toBeInTheDocument();
});
});
+
+ describe('Profile payload', () => {
+ it('sends the typed tool, the typed interest and the slider values', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let profileBody: Record<string, unknown> | undefined;
+
+ server.use(
+ rest.put(UPDATE_PROFILE_ENDPOINT, async (req, res, ctx) => {
+ profileBody = await req.json();
+ return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
+ }),
+ );
+
+ render(<OnboardingQuestionaire />);
+
+ await user.click(screen.getByText('Others'));
+ await user.type(
+ await screen.findByPlaceholderText(/what tool do you currently use/i),
+ 'Dynatrace',
+ );
+ await user.click(screen.getByRole('radio', { name: /just exploring/i }));
+ await user.click(screen.getByRole('radio', { name: /yes/i }));
+ await user.click(screen.getByRole('button', { name: /next/i }));
+
+ await user.type(
+ await screen.findByPlaceholderText(/e\.g\., I asked ChatGPT/i),
+ 'Found via Google',
+ );
+ await user.click(
+ screen.getByRole('checkbox', { name: /lowering observability costs/i }),
+ );
+ await user.click(screen.getByRole('checkbox', { name: /^others$/i }));
+ await user.type(
+ await screen.findByPlaceholderText(/what got you interested in signoz/i),
+ 'Better pricing',
+ );
+ await user.click(screen.getByRole('button', { name: /next/i }));
+
+ const [logsSlider, hostsSlider] = await screen.findAllByRole('slider');
+ logsSlider.focus();
+ await user.keyboard('{End}');
+ hostsSlider.focus();
+ await user.keyboard('{End}');
+ await user.click(screen.getByRole('button', { name: /next/i }));
+
+ await waitFor(() => expect(profileBody).toBeDefined());
+ expect(profileBody).toStrictEqual({
+ uses_otel: true,
+ has_existing_observability_tool: true,
+ existing_observability_tool: 'Dynatrace',
+ where_did_you_discover_signoz: 'Found via Google',
+ timeline_for_migrating_to_signoz: 'justExploring',
+ reasons_for_interest_in_signoz: ['loweringCosts', 'Better pricing'],
+ logs_scale_per_day_in_gb: 10000,
+ number_of_hosts: 10000,
+ number_of_services: 0,
+ });
+ }, 15000);
+ });
+
+ describe('Step 4: Finish onboarding', () => {
+ const ORG_ONBOARDING_ENDPOINT = '*/api/v1/org/preferences/org_onboarding';
+ const LIST_PREFERENCES_ENDPOINT = '*/api/v1/org/preferences';
+ const refreshedPreferences = [{ name: 'org_onboarding', value: true }];
+
+ async function goToStep4(
+ user: ReturnType<typeof userEvent.setup>,
+ ): Promise<void> {
+ await user.click(screen.getByRole('radio', { name: /datadog/i }));
+ await user.click(screen.getByRole('radio', { name: /yes/i }));
+ await user.click(screen.getByRole('radio', { name: /just exploring/i }));
+ await user.click(screen.getByRole('button', { name: /next/i }));
+
+ await user.type(
+ await screen.findByPlaceholderText(/e\.g\., I asked ChatGPT/i),
+ 'Found via Google',
+ );
+ await user.click(
+ screen.getByRole('checkbox', { name: /lowering observability costs/i }),
+ );
+ await user.click(screen.getByRole('button', { name: /next/i }));
+
+ await user.click(
+ await screen.findByRole('button', { name: /i'll do this later/i }),
+ );
+ await screen.findByTestId('do-later-button');
+ }
+
+ function mockFinish(status = 204): {
+ bodies: unknown[];
+ listCalls: () => number;
+ } {
+ const bodies: unknown[] = [];
+ let listCalls = 0;
+ server.use(
+ rest.put(ORG_ONBOARDING_ENDPOINT, async (req, res, ctx) => {
+ bodies.push(await req.json());
+ if (status >= 400) {
+ return res(
+ ctx.status(status),
+ ctx.json({
+ error: { code: 'internal', message: 'could not save onboarding' },
+ }),
+ );
+ }
+ return res(ctx.status(status));
+ }),
+ rest.get(LIST_PREFERENCES_ENDPOINT, (_, res, ctx) => {
+ listCalls += 1;
+ return res(
+ ctx.status(200),
+ ctx.json({ status: 'success', data: refreshedPreferences }),
+ );
+ }),
+ );
+ return { bodies, listCalls: (): number => listCalls };
+ }
+
+ it('marks onboarding done, refetches preferences and redirects on "do later"', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const updateOrgPreferences = jest.fn();
+ const { bodies, listCalls } = mockFinish();
+
+ render(<OnboardingQuestionaire />, undefined, {
+ appContextOverrides: { updateOrgPreferences },
+ });
+ await goToStep4(user);
+
+ await user.click(screen.getByTestId('do-later-button'));
+
+ await waitFor(() => {
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.GET_STARTED_WITH_CLOUD);
+ });
+ expect(bodies).toStrictEqual([{ value: true }]);
+ expect(listCalls()).toBe(1);
+ expect(updateOrgPreferences).toHaveBeenCalledWith(refreshedPreferences);
+ }, 15000);
+
+ it('marks onboarding done and redirects after the invites are sent', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let inviteCalls = 0;
+ const { bodies, listCalls } = mockFinish();
+ server.use(
+ rest.post(CREATE_USER_ENDPOINT, (_, res, ctx) => {
+ inviteCalls += 1;
+ return res(ctx.status(201), ctx.json({ data: { id: 'user-123' } }));
+ }),
+ );
+
+ render(<OnboardingQuestionaire />);
+ await goToStep4(user);
+
+ await user.type(
+ screen.getAllByPlaceholderText('e.g. [email protected]')[0],
+ );
+ await user.click(screen.getAllByText('Select roles')[0]);
+ await user.click(await screen.findByTitle('Viewer'));
+ await user.click(screen.getByTestId('send-invites-button'));
+
+ await waitFor(
+ () => {
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.GET_STARTED_WITH_CLOUD);
+ },
+ { timeout: 3000 },
+ );
+ expect(inviteCalls).toBe(1);
+ expect(bodies).toStrictEqual([{ value: true }]);
+ expect(listCalls()).toBe(1);
+ }, 15000);
+
+ it('shows an error and stops loading when saving onboarding fails', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { listCalls } = mockFinish(500);
+
+ render(<OnboardingQuestionaire />);
+ await goToStep4(user);
+
+ const doLaterButton = screen.getByTestId('do-later-button');
+ await user.click(doLaterButton);
+
+ await waitFor(() => {
+ expect(mockNotificationError).toHaveBeenCalledWith({
+ message: 'could not save onboarding',
+ });
+ });
+ await waitFor(() => {
+ expect(doLaterButton).not.toHaveAttribute('aria-busy');
+ });
+ expect(listCalls()).toBe(0);
+ expect(mockNavigate).not.toHaveBeenCalled();
+ }, 15000);
+ });
+
+ describe('OrgQuestions: Others tool input', () => {
+ function toolRadioGroup(): HTMLElement {
+ return screen.getAllByRole('radiogroup')[0];
+ }
+
+ function checkedTools(): HTMLElement[] {
+ return within(toolRadioGroup())
+ .getAllByRole('radio')
+ .filter((radio) => radio.getAttribute('aria-checked') === 'true');
+ }
+
+ it('keeps Others selected while typing Space and arrow keys in its input', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(<OnboardingQuestionaire />);
+
+ await user.click(screen.getByText('Others'));
+ const otherToolInput = await screen.findByPlaceholderText(
+ /what tool do you currently use/i,
+ );
+ const othersRadio = checkedTools()[0];
+
+ await user.type(
+ otherToolInput,
+ 'Dyna trace{ArrowLeft}{ArrowRight}{ArrowRight}{ArrowDown}{ArrowUp}{ArrowLeft}',
+ );
+
+ expect(otherToolInput).toHaveValue('Dyna trace');
+ expect(screen.getByPlaceholderText(/what tool do you currently use/i)).toBe(
+ otherToolInput,
+ );
+ expect(checkedTools()).toStrictEqual([othersRadio]);
+ });
+
+ it('clears the typed tool when switching to another tool', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(<OnboardingQuestionaire />);
+
+ await user.click(screen.getByText('Others'));
+ await user.type(
+ await screen.findByPlaceholderText(/what tool do you currently use/i),
+ 'Dynatrace',
+ );
+ await user.click(screen.getByRole('radio', { name: /datadog/i }));
+ expect(
+ screen.queryByPlaceholderText(/what tool do you currently use/i),
+ ).not.toBeInTheDocument();
+
+ await user.click(screen.getByText('Others'));
+
+ await expect(
+ screen.findByPlaceholderText(/what tool do you currently use/i),
+ ).resolves.toHaveValue('');
+ });
+
+ it('resets the migration timeline when None is chosen', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(<OnboardingQuestionaire />);
+
+ await user.click(screen.getByRole('radio', { name: /datadog/i }));
+ await user.click(screen.getByRole('radio', { name: /just exploring/i }));
+ await user.click(
+ screen.getByRole('radio', { name: /none\/starting fresh/i }),
+ );
+
+ expect(
+ screen.queryByText(/what is your timeline for migrating to signoz/i),
+ ).not.toBeInTheDocument();
+
+ await user.click(screen.getByRole('radio', { name: /datadog/i }));
+
+ await expect(
+ screen.findByRole('radio', { name: /just exploring/i }),
+ ).resolves.toHaveAttribute('aria-checked', 'false');
+ });
+ });
+
+ describe('Next button disabled reasons', () => {
+ async function expectNextDisabledWith(
+ user: ReturnType<typeof userEvent.setup>,
+ reason: string,
+ ): Promise<void> {
+ const nextButton = screen.getByRole('button', { name: /next/i });
+ expect(nextButton).toHaveAttribute('aria-disabled', 'true');
+ await user.hover(nextButton);
+ await waitFor(() => {
+ expect(
+ screen
+ .getAllByRole('tooltip')
+ .some((tooltip) => tooltip.textContent?.includes(reason)),
+ ).toBe(true);
+ });
+ await user.unhover(nextButton);
+ }
+
+ it('step 1 explains each missing answer until all are given', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(<OnboardingQuestionaire />);
+
+ await expectNextDisabledWith(user, 'Select the observability tool you use');
+
+ await user.click(screen.getByRole('radio', { name: /datadog/i }));
+ await expectNextDisabledWith(user, 'Select your migration timeline');
+
+ await user.click(screen.getByRole('radio', { name: /just exploring/i }));
+ await expectNextDisabledWith(
+ user,
+ 'Tell us if you already use OpenTelemetry',
+ );
+
+ await user.click(screen.getByRole('radio', { name: /^no$/i }));
+ expect(screen.getByRole('button', { name: /next/i })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+
+ await user.click(screen.getByText('Others'));
+ await expectNextDisabledWith(user, 'Enter the observability tool you use');
+
+ await user.type(
+ screen.getByPlaceholderText(/what tool do you currently use/i),
+ 'Dynatrace',
+ );
+ expect(screen.getByRole('button', { name: /next/i })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ }, 15000);
+
+ it('step 2 explains each missing answer until all are given', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ render(<OnboardingQuestionaire />);
+
+ await user.click(
+ screen.getByRole('radio', { name: /none\/starting fresh/i }),
+ );
+ await user.click(screen.getByRole('radio', { name: /^no$/i }));
+ await user.click(screen.getByRole('button', { name: /next/i }));
+
+ const discoverInput = await screen.findByPlaceholderText(
+ /e\.g\., I asked ChatGPT/i,
+ );
+ await expectNextDisabledWith(
+ user,
+ 'Tell us how you first came across SigNoz',
+ );
+
+ await user.type(discoverInput, 'Found via Google');
+ await expectNextDisabledWith(
+ user,
+ 'Select what got you interested in SigNoz',
+ );
+
+ await user.click(screen.getByRole('checkbox', { name: /^others$/i }));
+ await expectNextDisabledWith(
+ user,
+ 'Describe what got you interested in SigNoz',
+ );
+
+ await user.type(
+ await screen.findByPlaceholderText(/what got you interested in signoz/i),
+ 'Better pricing',
+ );
+ expect(screen.getByRole('button', { name: /next/i })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ }, 15000);
+
+ it('step 3 keeps Next disabled while every slider is 0', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ let profileCalls = 0;
+ server.use(
+ rest.put(UPDATE_PROFILE_ENDPOINT, (_, res, ctx) => {
+ profileCalls += 1;
+ return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
+ }),
+ );
+
+ render(<OnboardingQuestionaire />);
+
+ await user.click(
+ screen.getByRole('radio', { name: /none\/starting fresh/i }),
+ );
+ await user.click(screen.getByRole('radio', { name: /^no$/i }));
+ await user.click(screen.getByRole('button', { name: /next/i }));
+ await user.type(
+ await screen.findByPlaceholderText(/e\.g\., I asked ChatGPT/i),
+ 'Found via Google',
+ );
+ await user.click(
+ screen.getByRole('checkbox', { name: /lowering observability costs/i }),
+ );
+ await user.click(screen.getByRole('button', { name: /next/i }));
+
+ const [, , servicesSlider] = await screen.findAllByRole('slider');
+ await expectNextDisabledWith(user, 'Set at least one of the values above');
+
+ await user.click(screen.getByRole('button', { name: /next/i }));
+ expect(profileCalls).toBe(0);
+
+ servicesSlider.focus();
+ await user.keyboard('{ArrowRight}');
+
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: /next/i })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+ });
+ }, 15000);
+ });
});
diff --git a/frontend/src/container/OrganizationSettings/DisplayName/index.tsx b/frontend/src/container/OrganizationSettings/DisplayName/index.tsx
index f091a60d22..60964dd83e 100644
--- a/frontend/src/container/OrganizationSettings/DisplayName/index.tsx
+++ b/frontend/src/container/OrganizationSettings/DisplayName/index.tsx
@@ -95,6 +95,7 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
<Input
{...field}
id="displayName"
+ data-testid="org-display-name-input"
size="large"
placeholder={t('signoz')}
status={fieldState.error ? 'error' : ''}
@@ -112,6 +113,7 @@ function DisplayName({ index, id: orgId }: DisplayNameProps): JSX.Element {
disabled={isDisabled}
type="primary"
htmlType="submit"
+ data-testid="org-display-name-submit"
>
Submit
</Button>
diff --git a/frontend/src/container/PipelinePage/PipelineListsView/AddNewProcessor/FormFields/TypeSelect.tsx b/frontend/src/container/PipelinePage/PipelineListsView/AddNewProcessor/FormFields/TypeSelect.tsx
index ca14316184..2ee33f7493 100644
--- a/frontend/src/container/PipelinePage/PipelineListsView/AddNewProcessor/FormFields/TypeSelect.tsx
+++ b/frontend/src/container/PipelinePage/PipelineListsView/AddNewProcessor/FormFields/TypeSelect.tsx
@@ -21,6 +21,7 @@ function TypeSelect({ onChange, value }: TypeSelectProps): JSX.Element {
<StyledSelect
onChange={(value: string | unknown): void => onChange(value)}
value={value}
+ data-testid="processor-type-select"
>
{processorTypes.map(({ value, label }) => (
<Select.Option key={value + label} value={value}>
diff --git a/frontend/src/container/PipelinePage/PipelineListsView/PipelineListsView.tsx b/frontend/src/container/PipelinePage/PipelineListsView/PipelineListsView.tsx
index 0335722cd2..a5684141ec 100644
--- a/frontend/src/container/PipelinePage/PipelineListsView/PipelineListsView.tsx
+++ b/frontend/src/container/PipelinePage/PipelineListsView/PipelineListsView.tsx
@@ -62,7 +62,10 @@ import './styles.scss';
function PipelinesListEmptyState(): JSX.Element {
const { t } = useTranslation(['pipeline']);
return (
- <div className="logs-pipelines-empty-state-centered-container">
+ <div
+ className="logs-pipelines-empty-state-centered-container"
+ data-testid="pipelines-empty-state"
+ >
<Card size="small">
<div className="logs-pipelines-empty-state-centered-container">
<iframe
diff --git a/frontend/src/container/PipelinePage/PipelineListsView/Preview/PipelineProcessingPreview/index.tsx b/frontend/src/container/PipelinePage/PipelineListsView/Preview/PipelineProcessingPreview/index.tsx
index 4c0f5c88ce..44bf9efca9 100644
--- a/frontend/src/container/PipelinePage/PipelineListsView/Preview/PipelineProcessingPreview/index.tsx
+++ b/frontend/src/container/PipelinePage/PipelineListsView/Preview/PipelineProcessingPreview/index.tsx
@@ -34,13 +34,19 @@ function PipelineProcessingPreview({
onChange={setLogsSampleQueryInterval}
/>
</div>
- <div className="pipeline-preview-logs-container">
+ <div
+ className="pipeline-preview-logs-container"
+ data-testid="pipeline-preview-samples"
+ >
<SampleLogsResponseDisplay response={sampleLogsResponse} />
</div>
<div className="pipeline-preview-section-header">
<div>Processed Output</div>
</div>
- <div className="pipeline-preview-logs-container">
+ <div
+ className="pipeline-preview-logs-container"
+ data-testid="pipeline-preview-output"
+ >
<LogsProcessingSimulator inputLogs={sampleLogs} pipeline={pipeline} />
</div>
</div>
diff --git a/frontend/src/container/PipelinePage/PipelineListsView/Preview/components/LogsList/index.tsx b/frontend/src/container/PipelinePage/PipelineListsView/Preview/components/LogsList/index.tsx
index b7d2480588..60f89b7024 100644
--- a/frontend/src/container/PipelinePage/PipelineListsView/Preview/components/LogsList/index.tsx
+++ b/frontend/src/container/PipelinePage/PipelineListsView/Preview/components/LogsList/index.tsx
@@ -19,7 +19,11 @@ function LogsList({ logs }: LogsListProps): JSX.Element {
return (
<div className="logs-preview-list-container">
{logs.map((log) => (
- <div key={log.id} className="logs-preview-list-item">
+ <div
+ key={log.id}
+ className="logs-preview-list-item"
+ data-testid="pipeline-preview-log"
+ >
<div className="logs-preview-list-item-timestamp">
{formatTimezoneAdjustedTimestamp(
log.timestamp,
diff --git a/frontend/src/container/PipelinePage/tests/__snapshots__/PipelinePageLayout.test.tsx.snap b/frontend/src/container/PipelinePage/tests/__snapshots__/PipelinePageLayout.test.tsx.snap
index a6ea733863..7e65ca2531 100644
--- a/frontend/src/container/PipelinePage/tests/__snapshots__/PipelinePageLayout.test.tsx.snap
+++ b/frontend/src/container/PipelinePage/tests/__snapshots__/PipelinePageLayout.test.tsx.snap
@@ -53,6 +53,7 @@ exports[`PipelinePage container test should render PipelinePageLayout section 1`
>
<div
class="logs-pipelines-empty-state-centered-container"
+ data-testid="pipelines-empty-state"
>
<div
class="ant-card ant-card-bordered ant-card-small css-dev-only-do-not-override-2i2tap"
diff --git a/frontend/src/container/PlannedDowntime/__test__/PlannedDowntimeForm.test.tsx b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntimeForm.test.tsx
new file mode 100644
index 0000000000..d46b4dde8f
--- /dev/null
+++ b/frontend/src/container/PlannedDowntime/__test__/PlannedDowntimeForm.test.tsx
@@ -0,0 +1,100 @@
+import { Form } from 'antd';
+import type { AlertmanagertypesPlannedMaintenanceDTO } from 'api/generated/services/sigNoz.schemas';
+import { render, screen, userEvent } from 'tests/test-utils';
+
+import { PlannedDowntimeForm } from '../PlannedDowntimeForm';
+import { createMockDowntime } from './testUtils';
+
+jest.mock('api/generated/services/downtimeschedules', () => ({
+ createDowntimeSchedule: jest.fn(),
+ updateDowntimeScheduleByID: jest.fn(),
+}));
+
+const ALERT_OPTIONS = [
+ { label: 'High CPU', value: 'rule-1' },
+ { label: 'Disk full', value: 'rule-2' },
+];
+
+const RULE_PICKER_PLACEHOLDER = 'Search for alert rules or groups...';
+
+function FormHarness({
+ initialValues,
+}: {
+ initialValues: Partial<AlertmanagertypesPlannedMaintenanceDTO>;
+}): JSX.Element {
+ const [form] = Form.useForm();
+ return (
+ <PlannedDowntimeForm
+ initialValues={initialValues}
+ alertOptions={ALERT_OPTIONS}
+ isError={false}
+ isLoading={false}
+ isOpen
+ setIsOpen={jest.fn()}
+ refetchAllSchedules={jest.fn()}
+ isEditMode
+ form={form}
+ />
+ );
+}
+
+describe('PlannedDowntimeForm alert rule scope', () => {
+ it('checks "All alert rules" when editing a downtime with no alert ids', async () => {
+ render(
+ <FormHarness
+ initialValues={createMockDowntime({
+ id: 'd1',
+ name: 'Nightly',
+ alertIds: [],
+ })}
+ />,
+ );
+
+ await expect(
+ screen.findByRole('radio', { name: 'All alert rules' }),
+ ).resolves.toBeChecked();
+ expect(
+ screen.getByRole('radio', { name: 'Specific alert rules' }),
+ ).not.toBeChecked();
+ expect(screen.queryByText(RULE_PICKER_PLACEHOLDER)).not.toBeInTheDocument();
+ });
+
+ it('shows the rule picker after switching to specific alert rules', async () => {
+ const user = userEvent.setup();
+ render(
+ <FormHarness
+ initialValues={createMockDowntime({
+ id: 'd1',
+ name: 'Nightly',
+ alertIds: [],
+ })}
+ />,
+ );
+
+ await user.click(
+ await screen.findByRole('radio', { name: 'Specific alert rules' }),
+ );
+
+ expect(
+ screen.getByRole('radio', { name: 'Specific alert rules' }),
+ ).toBeChecked();
+ expect(screen.getByText(RULE_PICKER_PLACEHOLDER)).toBeInTheDocument();
+ });
+
+ it('checks "Specific alert rules" and lists them when editing a scoped downtime', async () => {
+ render(
+ <FormHarness
+ initialValues={createMockDowntime({
+ id: 'd2',
+ name: 'Scoped',
+ alertIds: ['rule-1'],
+ })}
+ />,
+ );
+
+ await expect(
+ screen.findByRole('radio', { name: 'Specific alert rules' }),
+ ).resolves.toBeChecked();
+ expect(screen.getByText('High CPU')).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/container/QueryBuilder/components/HavingFilterTag/__tests__/HavingFilterTag.test.tsx b/frontend/src/container/QueryBuilder/components/HavingFilterTag/__tests__/HavingFilterTag.test.tsx
new file mode 100644
index 0000000000..35c997e2ca
--- /dev/null
+++ b/frontend/src/container/QueryBuilder/components/HavingFilterTag/__tests__/HavingFilterTag.test.tsx
@@ -0,0 +1,55 @@
+import { render, screen, userEvent } from 'tests/test-utils';
+
+import { HavingFilterTag } from '../HavingFilterTag';
+
+// Badge renders its suffix inside an aria-hidden span.
+const getRemoveButton = (): HTMLElement =>
+ screen.getByRole('button', { name: 'Remove', hidden: true });
+
+function renderTag(closable: boolean): {
+ onClose: jest.Mock;
+ onUpdate: jest.Mock;
+} {
+ const onClose = jest.fn();
+ const onUpdate = jest.fn();
+ render(
+ <HavingFilterTag
+ label="count() > 5"
+ value="count() > 5"
+ disabled={false}
+ closable={closable}
+ onClose={onClose}
+ onUpdate={onUpdate}
+ />,
+ );
+ return { onClose, onUpdate };
+}
+
+describe('HavingFilterTag', () => {
+ it('calls onClose once when the remove button is clicked', async () => {
+ const { onClose, onUpdate } = renderTag(true);
+
+ await userEvent.click(getRemoveButton());
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onUpdate).not.toHaveBeenCalled();
+ });
+
+ it('renders no remove button when not closable', () => {
+ renderTag(false);
+
+ expect(
+ screen.queryByRole('button', { name: 'Remove', hidden: true }),
+ ).not.toBeInTheDocument();
+ });
+
+ it('calls onUpdate with the value when the chip body is clicked', async () => {
+ const { onClose, onUpdate } = renderTag(true);
+
+ await userEvent.click(screen.getByText('count() > 5'));
+
+ expect(onUpdate).toHaveBeenCalledTimes(1);
+ expect(onUpdate).toHaveBeenCalledWith('count() > 5');
+ expect(onClose).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/container/QueryBuilder/components/RunQueryBtn/RunQueryBtn.tsx b/frontend/src/container/QueryBuilder/components/RunQueryBtn/RunQueryBtn.tsx
index 86cf4ecea0..9632cb9a9f 100644
--- a/frontend/src/container/QueryBuilder/components/RunQueryBtn/RunQueryBtn.tsx
+++ b/frontend/src/container/QueryBuilder/components/RunQueryBtn/RunQueryBtn.tsx
@@ -15,6 +15,7 @@ type RunQueryBtnProps = {
label?: string;
disabled?: boolean;
disabledTooltip?: ReactNode;
+ testId?: string;
} & (
| {
onStageRunQuery: () => void;
@@ -35,6 +36,7 @@ function RunQueryBtn({
onStageRunQuery,
disabled,
disabledTooltip,
+ testId,
}: RunQueryBtnProps): JSX.Element {
const isMac = getUserOperatingSystem() === UserOperatingSystem.MACOS;
const isLoading = isLoadingQueries ?? false;
@@ -48,6 +50,7 @@ function RunQueryBtn({
data-run-query-btn
prefix={<LoaderCircle size={14} className="loading-icon animate-spin" />}
onClick={handleCancelQuery}
+ testId={testId ? `${testId}-cancel` : undefined}
>
Cancel
</Button>
@@ -58,6 +61,7 @@ function RunQueryBtn({
color="primary"
type="button"
data-run-query-btn
+ testId={testId}
disabled={disabled}
disabledTooltip={disabledTooltip}
onClick={onStageRunQuery}
diff --git a/frontend/src/container/QueryBuilder/components/ToolbarActions/LeftToolbarActions.tsx b/frontend/src/container/QueryBuilder/components/ToolbarActions/LeftToolbarActions.tsx
index 8cedbda91b..f19eb16643 100644
--- a/frontend/src/container/QueryBuilder/components/ToolbarActions/LeftToolbarActions.tsx
+++ b/frontend/src/container/QueryBuilder/components/ToolbarActions/LeftToolbarActions.tsx
@@ -52,6 +52,8 @@ export default function LeftToolbarActions({
selectedView === list.key ? activeTab : '',
)}
onClick={(): void => onChangeSelectedView(list.key)}
+ data-testid="explorer-view-list"
+ aria-pressed={selectedView === list.key}
>
<SquareMousePointer size={14} data-testid="search-view" />
List View
@@ -69,6 +71,8 @@ export default function LeftToolbarActions({
selectedView === trace.key ? activeTab : '',
)}
onClick={(): void => onChangeSelectedView(trace.key)}
+ data-testid="explorer-view-trace"
+ aria-pressed={selectedView === trace.key}
>
<SquareMousePointer size={14} data-testid="trace-view" />
Trace View
@@ -86,6 +90,8 @@ export default function LeftToolbarActions({
selectedView === timeseries.key ? activeTab : '',
)}
onClick={(): void => onChangeSelectedView(timeseries.key)}
+ data-testid="explorer-view-timeseries"
+ aria-pressed={selectedView === timeseries.key}
>
<Atom size={14} data-testid="query-builder-view" />
Time Series
@@ -120,6 +126,8 @@ export default function LeftToolbarActions({
selectedView === table.key ? activeTab : '',
)}
onClick={(): void => onChangeSelectedView(table.key)}
+ data-testid="explorer-view-table"
+ aria-pressed={selectedView === table.key}
>
<Binoculars size={14} data-testid="query-builder-view-v2" />
Table
diff --git a/frontend/src/container/QueryBuilder/components/ToolbarActions/RightToolbarActions.tsx b/frontend/src/container/QueryBuilder/components/ToolbarActions/RightToolbarActions.tsx
index 0ae6bac524..0684fabaf4 100644
--- a/frontend/src/container/QueryBuilder/components/ToolbarActions/RightToolbarActions.tsx
+++ b/frontend/src/container/QueryBuilder/components/ToolbarActions/RightToolbarActions.tsx
@@ -37,7 +37,11 @@ export default function RightToolbarActions({
if (showLiveLogs) {
return (
<div className="right-toolbar-actions-container">
- <RunQueryBtn disabled disabledTooltip="Not available in live mode" />
+ <RunQueryBtn
+ disabled
+ disabledTooltip="Not available in live mode"
+ testId="explorer-run-query-btn"
+ />
</div>
);
}
@@ -48,6 +52,7 @@ export default function RightToolbarActions({
isLoadingQueries={isLoadingQueries}
handleCancelQuery={handleCancelQuery}
onStageRunQuery={onStageRunQuery}
+ testId="explorer-run-query-btn"
/>
</div>
);
diff --git a/frontend/src/container/QueryBuilder/filters/QueryBuilderSearchV2/__test__/QueryBuilderSearchV2.test.tsx b/frontend/src/container/QueryBuilder/filters/QueryBuilderSearchV2/__test__/QueryBuilderSearchV2.test.tsx
index 15d5ca286a..dd251f8f8b 100644
--- a/frontend/src/container/QueryBuilder/filters/QueryBuilderSearchV2/__test__/QueryBuilderSearchV2.test.tsx
+++ b/frontend/src/container/QueryBuilder/filters/QueryBuilderSearchV2/__test__/QueryBuilderSearchV2.test.tsx
@@ -279,3 +279,56 @@ describe('Dynamic Variable Suggestions', () => {
);
});
});
+
+describe('Filter chips', () => {
+ const CHIP_LABEL = 'http.status = 200';
+ const queryWithFilter = {
+ ...defaultProps.query,
+ filters: {
+ op: 'AND',
+ items: [
+ {
+ id: 'f1',
+ key: {
+ key: 'http.status',
+ dataType: DataTypes.String,
+ type: TYPE_TAG,
+ id: 'http.status--string--tag--false',
+ },
+ op: '=',
+ value: '200',
+ },
+ ],
+ },
+ };
+
+ beforeEach(() => {
+ mockOnChange.mockClear();
+ });
+
+ it('removes the filter once when the chip close button is clicked', async () => {
+ const user = userEvent.setup({ delay: null });
+ renderWithContext({ query: queryWithFilter });
+
+ await user.click(
+ screen.getByRole('button', { name: `Remove ${CHIP_LABEL}` }),
+ );
+
+ expect(mockOnChange).toHaveBeenCalledTimes(1);
+ expect(mockOnChange).toHaveBeenCalledWith(
+ expect.objectContaining({ items: [] }),
+ );
+ });
+
+ it('moves the filter into the search input when the chip body is clicked', async () => {
+ const user = userEvent.setup({ delay: null });
+ renderWithContext({ query: queryWithFilter });
+
+ await user.click(screen.getByText(CHIP_LABEL));
+
+ expect(
+ screen.queryByRole('button', { name: `Remove ${CHIP_LABEL}` }),
+ ).not.toBeInTheDocument();
+ expect(getSearchCombobox()).toHaveDisplayValue(CHIP_LABEL);
+ });
+});
diff --git a/frontend/src/container/QueryTable/QueryTable.tsx b/frontend/src/container/QueryTable/QueryTable.tsx
index d0ecf11f4c..8e62a6f11e 100644
--- a/frontend/src/container/QueryTable/QueryTable.tsx
+++ b/frontend/src/container/QueryTable/QueryTable.tsx
@@ -160,7 +160,7 @@ export function QueryTable({
return (
<>
- <div className="query-table">
+ <div className="query-table" data-testid="query-table">
{isDownloadEnabled && (
<div className="query-table--download">
<Download
diff --git a/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx b/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx
index 050227ca1d..f46c5d1abe 100644
--- a/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx
+++ b/frontend/src/container/ResetPassword/__tests__/ResetPassword.test.tsx
@@ -422,4 +422,109 @@ describe('ResetPassword Component', () => {
});
});
});
+
+ describe('Enter key submission', () => {
+ function mockReset(delayMs = 0): { resetCalls: () => number } {
+ let calls = 0;
+ server.use(
+ rest.post(RESET_PASSWORD_ENDPOINT, (_req, res, ctx) => {
+ calls += 1;
+ return res(
+ ctx.delay(delayMs),
+ ctx.status(200),
+ ctx.json({ status: 'success', message: 'Password reset successfully' }),
+ );
+ }),
+ );
+ return { resetCalls: (): number => calls };
+ }
+
+ async function typeMatchingPasswords(
+ user: ReturnType<typeof userEvent.setup>,
+ ): Promise<HTMLElement> {
+ await user.type(
+ screen.getByPlaceholderText(/enter new password/i),
+ 'newPassword123',
+ );
+ const confirmPasswordInput = screen.getByPlaceholderText(
+ /confirm your new password/i,
+ );
+ await user.type(confirmPasswordInput, 'newPassword123');
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: /reset password/i }),
+ ).not.toHaveAttribute('aria-disabled', 'true');
+ });
+ return confirmPasswordInput;
+ }
+
+ it('resets once on Enter in the confirm password field', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { resetCalls } = mockReset();
+
+ render(<ResetPassword version="1.0.0" />, undefined, {
+ initialRoute: '/password-reset?token=reset-token-123',
+ });
+
+ const confirmPasswordInput = await typeMatchingPasswords(user);
+ await user.type(confirmPasswordInput, '{enter}');
+
+ await waitFor(() => {
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
+ });
+ expect(resetCalls()).toBe(1);
+ });
+
+ it('does not reset on Enter while the passwords do not match', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { resetCalls } = mockReset();
+
+ render(<ResetPassword version="1.0.0" />, undefined, {
+ initialRoute: '/password-reset?token=reset-token-123',
+ });
+
+ await user.type(
+ screen.getByPlaceholderText(/enter new password/i),
+ 'password123',
+ );
+ await user.type(
+ screen.getByPlaceholderText(/confirm your new password/i),
+ 'password456{enter}',
+ );
+ expect(
+ screen.getByRole('button', { name: /reset password/i }),
+ ).toHaveAttribute('aria-disabled', 'true');
+
+ // Give a wrongly sent request time to land before asserting it never did.
+ await new Promise((resolve) => setTimeout(resolve, 150));
+ expect(resetCalls()).toBe(0);
+ });
+
+ it('does not reset again on Enter while the first reset is loading', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { resetCalls } = mockReset(1000);
+
+ render(<ResetPassword version="1.0.0" />, undefined, {
+ initialRoute: '/password-reset?token=reset-token-123',
+ });
+
+ const confirmPasswordInput = await typeMatchingPasswords(user);
+ await user.type(confirmPasswordInput, '{enter}');
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: /reset password/i }),
+ ).toHaveAttribute('aria-disabled', 'true');
+ });
+ await user.type(confirmPasswordInput, '{enter}');
+
+ await waitFor(
+ () => {
+ expect(mockNavigate).toHaveBeenCalledWith(ROUTES.LOGIN);
+ },
+ { timeout: 2000 },
+ );
+ expect(resetCalls()).toBe(1);
+ });
+ });
});
diff --git a/frontend/src/container/ResetPassword/index.tsx b/frontend/src/container/ResetPassword/index.tsx
index 8077e9a91e..382fd4401f 100644
--- a/frontend/src/container/ResetPassword/index.tsx
+++ b/frontend/src/container/ResetPassword/index.tsx
@@ -164,6 +164,7 @@ function ResetPassword({ version }: ResetPasswordProps): JSX.Element {
color="primary"
type="submit"
data-attr="reset-password"
+ testId="reset-password-submit"
loading={isLoading}
disabled={!isValidPassword}
disabledTooltip="Enter matching passwords in both fields"
diff --git a/frontend/src/container/ResourceAttributesFilter/components/QueryChip/__tests__/QueryChip.test.tsx b/frontend/src/container/ResourceAttributesFilter/components/QueryChip/__tests__/QueryChip.test.tsx
new file mode 100644
index 0000000000..4ae9b2057b
--- /dev/null
+++ b/frontend/src/container/ResourceAttributesFilter/components/QueryChip/__tests__/QueryChip.test.tsx
@@ -0,0 +1,50 @@
+import { getResourceDeploymentKeys } from 'hooks/useResourceAttribute/utils';
+import { render, screen, userEvent } from 'tests/test-utils';
+
+import QueryChip from '../QueryChip';
+
+// Badge renders its suffix inside an aria-hidden span.
+const getRemoveButton = (): HTMLElement =>
+ screen.getByRole('button', { name: 'Remove', hidden: true });
+
+describe('QueryChip', () => {
+ it('calls onClose once with the query id when the remove button is clicked', async () => {
+ const onClose = jest.fn();
+ render(
+ <QueryChip
+ queryData={{
+ id: 'q1',
+ tagKey: 'resource_service_name',
+ operator: 'IN',
+ tagValue: ['frontend', 'backend'],
+ }}
+ onClose={onClose}
+ />,
+ );
+
+ expect(screen.getByText('frontend, backend')).toBeInTheDocument();
+ await userEvent.click(getRemoveButton());
+
+ expect(onClose).toHaveBeenCalledTimes(1);
+ expect(onClose).toHaveBeenCalledWith('q1');
+ });
+
+ it('renders no remove button for the deployment environment chip', () => {
+ render(
+ <QueryChip
+ queryData={{
+ id: 'q2',
+ tagKey: getResourceDeploymentKeys(),
+ operator: 'IN',
+ tagValue: ['prod'],
+ }}
+ onClose={jest.fn()}
+ />,
+ );
+
+ expect(screen.getByText('prod')).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Remove', hidden: true }),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/container/RolesSettings/DeleteRoleModal/DeleteRoleModal.tsx b/frontend/src/container/RolesSettings/DeleteRoleModal/DeleteRoleModal.tsx
index e7b2360022..869555c9f0 100644
--- a/frontend/src/container/RolesSettings/DeleteRoleModal/DeleteRoleModal.tsx
+++ b/frontend/src/container/RolesSettings/DeleteRoleModal/DeleteRoleModal.tsx
@@ -37,6 +37,7 @@ function DeleteRoleModal({
onConfirm={onConfirm}
onCancel={onCancel}
disableOutsideClick
+ testId="delete-role-modal"
>
<Typography>
Are you sure you want to delete the role <strong>{roleName}</strong>? This
diff --git a/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx b/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx
index 59d0de1e72..9848435da7 100644
--- a/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx
+++ b/frontend/src/container/RolesSettings/RolesComponents/RolesListingTable.tsx
@@ -179,6 +179,7 @@ function RolesListContent({ searchQuery }: RolesListContentProps): JSX.Element {
const renderRow = (role: AuthtypesGettableRoleDTO): JSX.Element => (
<div
key={role.id}
+ data-testid={`role-row-${role.name}`}
className={cx(styles.tableRow, {
[styles.tableRowClickable]: isRolesEnabled,
})}
diff --git a/frontend/src/container/RolesSettings/RolesSettings.tsx b/frontend/src/container/RolesSettings/RolesSettings.tsx
index 57386e20e3..69d1e0ef46 100644
--- a/frontend/src/container/RolesSettings/RolesSettings.tsx
+++ b/frontend/src/container/RolesSettings/RolesSettings.tsx
@@ -51,6 +51,7 @@ function RolesSettings(): JSX.Element {
placeholder="Search for roles..."
value={searchQuery}
onChange={(e): void => setSearchQuery(e.target.value)}
+ testId="roles-search-input"
/>
</AuthZTooltip>
{isRolesEnabled && (
@@ -62,6 +63,7 @@ function RolesSettings(): JSX.Element {
width={156}
onClick={(): void => navigate(ROUTES.ROLE_CREATE)}
prefix={<Plus size={14} />}
+ testId="create-custom-role-btn"
>
Custom role
</AuthZButton>
diff --git a/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx b/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx
index c749a892f3..7dd9d2e6d7 100644
--- a/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx
+++ b/frontend/src/container/ServiceAccountsSettings/ServiceAccountsSettings.tsx
@@ -243,6 +243,7 @@ function ServiceAccountsSettings(): JSX.Element {
loading={isAuthZLoading}
disabled={!canListServiceAccounts}
disabledTooltip={undefined}
+ testId="sa-filter-trigger"
suffix={
<ChevronDown
size={12}
@@ -271,6 +272,7 @@ function ServiceAccountsSettings(): JSX.Element {
void setPage(1);
}}
className="sa-settings-search-input"
+ testId="sa-search-input"
disabled={controlsDisabled}
/>
</AuthZTooltip>
@@ -285,6 +287,7 @@ function ServiceAccountsSettings(): JSX.Element {
await setIsCreateModalOpen(true);
}}
prefix={<Plus size={12} />}
+ testId="new-sa-btn"
>
New Service Account
</AuthZButton>
diff --git a/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx b/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx
index dd9a879214..9aca0b999f 100644
--- a/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx
+++ b/frontend/src/container/ServiceApplication/Columns/GetColumnSearchProps.tsx
@@ -77,6 +77,7 @@ export const getColumnSearchProps = (
)}
<AppLink
+ data-testid={`service-link-${metrics}`}
to={`${ROUTES.APPLICATION}/${encodeURIComponent(
metrics,
)}?${queryString.join('')}`}
diff --git a/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx b/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx
index 7ca68f420e..badf2429e7 100644
--- a/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx
+++ b/frontend/src/container/ServiceApplication/ServiceMetrics/ServiceMetricTable.tsx
@@ -102,7 +102,7 @@ function ServiceMetricTable({
`${range[0]}-${range[1]} of ${total} items`,
};
return (
- <div className="service-metric-table-container">
+ <div className="service-metric-table-container" data-testid="services-table">
{RPS > MAX_RPS_LIMIT && (
<Flex justify="left">
<Typography.Title level={5} color="warning" style={{ marginTop: 0 }}>
diff --git a/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx b/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx
index e505cc6fa8..03ab29536d 100644
--- a/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx
+++ b/frontend/src/container/ServiceApplication/ServiceTraces/ServiceTracesTable.tsx
@@ -54,7 +54,7 @@ function ServiceTraceTable({
`${range[0]}-${range[1]} of ${total} items`,
};
return (
- <div className="service-traces-table-container">
+ <div className="service-traces-table-container" data-testid="services-table">
{RPS > MAX_RPS_LIMIT && (
<Flex justify="left">
<Typography.Title level={5} color="warning" style={{ marginTop: 0 }}>
diff --git a/frontend/src/container/SideNav/NavItem/NavItem.tsx b/frontend/src/container/SideNav/NavItem/NavItem.tsx
index e7ac5efc17..5356127a86 100644
--- a/frontend/src/container/SideNav/NavItem/NavItem.tsx
+++ b/frontend/src/container/SideNav/NavItem/NavItem.tsx
@@ -91,6 +91,8 @@ export default function NavItem({
className="nav-item-pin-icon"
onClick={handleTogglePinClick}
color="var(--Vanilla-400, #c0c1c3)"
+ data-testid={`nav-item-pin-${item.itemKey}`}
+ aria-label="Add to shortcuts"
/>
</Tooltip>
)}
@@ -102,6 +104,8 @@ export default function NavItem({
className="nav-item-pin-icon"
onClick={handleTogglePinClick}
color="var(--Vanilla-400, #c0c1c3)"
+ data-testid={`nav-item-pin-${item.itemKey}`}
+ aria-label="Remove from shortcuts"
/>
</Tooltip>
)}
diff --git a/frontend/src/container/SideNav/SideNav.tsx b/frontend/src/container/SideNav/SideNav.tsx
index 66d3a2955a..507f934f28 100644
--- a/frontend/src/container/SideNav/SideNav.tsx
+++ b/frontend/src/container/SideNav/SideNav.tsx
@@ -110,6 +110,7 @@ function SortableFilter({ item }: { item: SidebarItem }): JSX.Element {
{...listeners}
className="reorder-shortcut-nav-item drag-handle"
key={item.key}
+ data-testid={`reorder-item-${item.itemKey}`}
>
<div className="reorder-shortcut-nav-item-grab-icon">
<GripVertical size={16} />
@@ -806,6 +807,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
handleMenuItemClick(event, item);
}}
isPinned={isPinnedItem(item)}
+ dataTestId={item.itemKey ? `nav-item-${item.itemKey}` : undefined}
/>
))}
</>
@@ -952,6 +954,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
type: 'item',
value: String(item.key),
label: item.label ?? '',
+ testId: item.itemKey ? `help-menu-${item.itemKey}` : undefined,
prefix: isValidElement(item.icon) ? item.icon : undefined,
onClick: (event: MouseEvent): void => {
handleHelpSupportMenuItemClick({
@@ -984,6 +987,8 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
)}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
+ data-testid="sidenav"
+ data-collapsed={isCollapsed}
>
<div className="brand-container">
<div className="brand">
@@ -1040,6 +1045,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
<span
className={cx('version', changelog && 'version-clickable')}
onClick={onClickVersionHandler}
+ data-testid="sidenav-version"
>
{currentVersion}
</span>
@@ -1089,6 +1095,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
{(pinnedMenuItems.length > 0 || !isCollapsed) && (
<div
className={cx('shortcut-nav-items', isCollapsed && 'sidebar-collapsed')}
+ data-testid="sidenav-shortcuts"
>
{!isCollapsed && (
<div className="nav-title-section">
@@ -1103,6 +1110,7 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
<Tooltip title="Manage shortcuts" placement="right">
<div
className="nav-section-title-icon reorder"
+ data-testid="manage-shortcuts-btn"
onClick={(): void => {
void logEvent('Sidebar V2: Manage shortcuts clicked', {});
setIsReorderShortcutNavItemsModalOpen(true);
@@ -1140,11 +1148,14 @@ function SideNav({ isPinned }: { isPinned: boolean }): JSX.Element {
isMoreMenuCollapsed ? 'collapsed' : 'expanded',
isCollapsed && 'sidebar-collapsed',
)}
+ data-testid="sidenav-more"
>
{!isCollapsed && (
<div className="nav-title-section">
<div
className="nav-section-title"
+ data-testid="more-nav-toggle"
+ aria-expanded={!isMoreMenuCollapsed}
onClick={(): void => {
// Only allow toggling when sidebar is open (pinned, hovered, or dropdown open)
if (isCollapsed) {
diff --git a/frontend/src/container/SideNav/__tests__/SideNav.settingsDropdown.test.tsx b/frontend/src/container/SideNav/__tests__/SideNav.settingsDropdown.test.tsx
new file mode 100644
index 0000000000..6ef586c30b
--- /dev/null
+++ b/frontend/src/container/SideNav/__tests__/SideNav.settingsDropdown.test.tsx
@@ -0,0 +1,114 @@
+import { Logout } from 'api/utils';
+import ROUTES from 'constants/routes';
+import { mockNavigate } from 'tests/router-mocks';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+import { openInNewTab } from 'utils/navigation';
+
+import SideNav from '../SideNav';
+import { WORKSPACE_LOCKED_TOOLTIP } from '../menuItems';
+
+jest.mock('api/utils', () => ({
+ ...jest.requireActual('api/utils'),
+ Logout: jest.fn(),
+}));
+
+jest.mock('utils/navigation', () => ({
+ ...jest.requireActual('utils/navigation'),
+ openInNewTab: jest.fn(),
+}));
+
+jest.mock('providers/cmdKProvider', () => ({
+ useCmdK: (): { openCmdK: jest.Mock } => ({ openCmdK: jest.fn() }),
+}));
+
+jest.mock('hooks/hotkeys/useKeyboardHotkeys', () => ({
+ useKeyboardHotkeys: (): Record<string, jest.Mock> => ({
+ registerShortcut: jest.fn(),
+ deregisterShortcut: jest.fn(),
+ }),
+}));
+
+const BLOCKED_TRIAL_INFO = {
+ trialStart: -1,
+ trialEnd: -1,
+ onTrial: false,
+ workSpaceBlock: true,
+ trialConvertedToSubscription: false,
+ gracePeriodEnd: -1,
+};
+
+async function openSettingsMenu(
+ user: ReturnType<typeof userEvent.setup>,
+): Promise<void> {
+ await user.click(screen.getByTestId('settings-nav-item'));
+ await screen.findByRole('menu');
+}
+
+describe('SideNav settings dropdown', () => {
+ let mockNavigateFn: ReturnType<typeof mockNavigate>;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockNavigateFn = mockNavigate();
+ });
+
+ it('disables the workspace item with its reason when the workspace is blocked', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ render(<SideNav isPinned />, undefined, {
+ appContextOverrides: { trialInfo: BLOCKED_TRIAL_INFO },
+ });
+ await openSettingsMenu(user);
+
+ const workspaceItem = screen.getByTestId('workspace-settings-nav-item');
+ expect(workspaceItem).toHaveAttribute('aria-disabled', 'true');
+
+ await user.hover(workspaceItem);
+ await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
+ WORKSPACE_LOCKED_TOOLTIP,
+ );
+
+ await user.click(workspaceItem);
+ expect(mockNavigateFn).not.toHaveBeenCalledWith(ROUTES.SETTINGS);
+ });
+
+ it('keeps the workspace item enabled when the workspace is not blocked', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ render(<SideNav isPinned />);
+ await openSettingsMenu(user);
+
+ const workspaceItem = screen.getByTestId('workspace-settings-nav-item');
+ expect(workspaceItem).not.toHaveAttribute('aria-disabled', 'true');
+
+ await user.click(workspaceItem);
+ expect(mockNavigateFn).toHaveBeenCalledWith(ROUTES.SETTINGS);
+ });
+
+ it('signs out from the logout item', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ render(<SideNav isPinned />);
+ await openSettingsMenu(user);
+
+ await user.click(screen.getByTestId('logout-nav-item'));
+
+ expect(Logout).toHaveBeenCalledTimes(1);
+ });
+
+ it('opens a settings link in a new tab on a modifier click', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+
+ render(<SideNav isPinned />);
+ await openSettingsMenu(user);
+
+ await user.keyboard('{Control>}');
+ await user.click(screen.getByTestId('account-settings-nav-item'));
+ await user.keyboard('{/Control}');
+
+ await waitFor(() => {
+ expect(openInNewTab).toHaveBeenCalledWith(ROUTES.MY_SETTINGS);
+ });
+ expect(mockNavigateFn).not.toHaveBeenCalledWith(ROUTES.MY_SETTINGS);
+ });
+});
diff --git a/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx b/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx
index 7b837f8f76..78b4f7047b 100644
--- a/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx
+++ b/frontend/src/container/TopNav/AutoRefreshV2/__tests__/AutoRefresh.test.tsx
@@ -1,6 +1,7 @@
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
import { act, render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
import set from 'api/browser/localstorage/set';
import { DASHBOARD_TIME_IN_DURATION } from 'constants/app';
import configureStore, { MockStoreEnhanced } from 'redux-mock-store';
@@ -114,3 +115,33 @@ describe('AutoRefresh', () => {
expect(tickCount(store)).toBe(0);
});
});
+
+describe('AutoRefresh disabled checkbox', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ });
+
+ it('explains why it is disabled and ignores clicks', async () => {
+ const user = userEvent.setup();
+ const store = renderAutoRefresh(
+ createGlobalTimeState({ isAutoRefreshDisabled: true }),
+ );
+
+ await user.click(screen.getByTitle('Set auto refresh'));
+ const checkbox = await screen.findByRole('checkbox', {
+ name: 'Auto Refresh',
+ });
+ expect(checkbox).toHaveAttribute('aria-disabled', 'true');
+
+ await user.hover(checkbox);
+ await expect(
+ screen.findByText('Auto refresh is not available for a custom time range'),
+ ).resolves.toBeInTheDocument();
+
+ await user.click(checkbox);
+
+ expect(checkbox).not.toBeChecked();
+ expect(localStorage.getItem(DASHBOARD_TIME_IN_DURATION)).toBeNull();
+ expect(tickCount(store)).toBe(0);
+ });
+});
diff --git a/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx b/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx
index 3f0480c617..4d3fe85016 100644
--- a/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx
+++ b/frontend/src/container/TracesExplorer/TracesTable/TracesTable.tsx
@@ -98,6 +98,7 @@ function TracesTable({
onRowClick={handleRowClick}
onRowClickNewTab={handleRowClickNewTab}
getRowTestId={(row): string => `traces-table-row-${row.id}`}
+ testId={`traces-table-${panelType.toLowerCase()}`}
/>
</div>
)}
diff --git a/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx b/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx
index 630411a921..0c5fe61af4 100644
--- a/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx
+++ b/frontend/src/container/WidgetCard/Header/__tests__/WidgetHeader.test.tsx
@@ -83,6 +83,19 @@ const render = (ui: React.ReactElement): ReturnType<typeof rtlRender> =>
</TestRouter>,
);
+const mockSafeNavigate = jest.fn();
+jest.mock('hooks/useSafeNavigate', () => ({
+ useSafeNavigate: (): { safeNavigate: jest.Mock } => ({
+ safeNavigate: mockSafeNavigate,
+ }),
+}));
+
+const mockComponentPermission = jest.fn((): boolean[] => [true, true]);
+jest.mock('hooks/useComponentPermission', () => ({
+ __esModule: true,
+ default: (): boolean[] => mockComponentPermission(),
+}));
+
jest.mock('hooks/queryBuilder/useCreateAlerts', () => ({
__esModule: true,
default: jest.fn(() => jest.fn()),
@@ -529,3 +542,140 @@ describe('WidgetHeader', () => {
});
});
});
+
+describe('WidgetHeader menu rows', () => {
+ const ALL_ROWS = [
+ MenuItemKeys.View,
+ MenuItemKeys.Edit,
+ MenuItemKeys.Clone,
+ MenuItemKeys.Delete,
+ ];
+ const tableWidget = { ...mockWidget, panelTypes: PANEL_TYPES.TABLE };
+ const tableProcessedDataRef: MutableRefObject<RowData[]> = {
+ current: [{ timestamp: 1, key: 'k', col1: 'v1' }],
+ };
+
+ interface Props {
+ onView: jest.Mock;
+ onClone: jest.Mock;
+ onDelete: jest.Mock;
+ }
+
+ function renderHeader(): Props {
+ const props = {
+ onView: jest.fn(),
+ onClone: jest.fn(),
+ onDelete: jest.fn(),
+ };
+ render(
+ <WidgetHeader
+ title={TABLE_WIDGET_TITLE}
+ widget={tableWidget}
+ queryResponse={mockQueryResponse}
+ isWarning={false}
+ isFetchingResponse={false}
+ tableProcessedDataRef={tableProcessedDataRef}
+ setSearchTerm={jest.fn()}
+ headerMenuList={ALL_ROWS}
+ {...props}
+ />,
+ );
+ return props;
+ }
+
+ async function openMenu(): Promise<void> {
+ await userEvent.click(screen.getByTestId(WIDGET_HEADER_OPTIONS_ID));
+ }
+
+ async function clickRow(name: string): Promise<void> {
+ await openMenu();
+ await userEvent.click(await screen.findByRole('menuitem', { name }));
+ }
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockComponentPermission.mockReturnValue([true, true]);
+ });
+
+ it.each([
+ ['View', 'onView'],
+ ['Clone', 'onClone'],
+ ['Delete', 'onDelete'],
+ ] as const)('%s calls %s only', async (name, prop) => {
+ const props = renderHeader();
+ await clickRow(name);
+
+ for (const key of ['onView', 'onClone', 'onDelete'] as const) {
+ expect(props[key]).toHaveBeenCalledTimes(key === prop ? 1 : 0);
+ }
+ expect(mockSafeNavigate).not.toHaveBeenCalled();
+ });
+
+ it('Edit navigates to the panel editor for this widget', async () => {
+ const props = renderHeader();
+ await clickRow('Edit');
+
+ expect(mockSafeNavigate).toHaveBeenCalledTimes(1);
+ const url = mockSafeNavigate.mock.calls[0][0] as string;
+ expect(url).toContain('new?');
+ expect(url).toContain(`widgetId=${tableWidget.id}`);
+ expect(url).toContain(`graphType=${PANEL_TYPES.TABLE}`);
+ expect(props.onView).not.toHaveBeenCalled();
+ expect(props.onClone).not.toHaveBeenCalled();
+ });
+
+ it('Download as CSV saves the table rows as a csv file', async () => {
+ const createObjectURL = jest.fn((_blob: Blob) => 'blob:csv');
+ Object.defineProperty(URL, 'createObjectURL', {
+ value: createObjectURL,
+ configurable: true,
+ });
+ const clicked: { download: string; href: string }[] = [];
+ const anchorClick = jest
+ .spyOn(HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(function (this: HTMLAnchorElement) {
+ clicked.push({ download: this.download, href: this.href });
+ });
+ const props = renderHeader();
+
+ await clickRow('Download as CSV');
+
+ expect(createObjectURL).toHaveBeenCalledTimes(1);
+ expect(createObjectURL.mock.calls[0][0].type).toBe('text/csv;charset=utf-8;');
+ expect(clicked).toStrictEqual([
+ { download: `${TABLE_WIDGET_TITLE}.csv`, href: 'blob:csv' },
+ ]);
+ expect(props.onView).not.toHaveBeenCalled();
+ anchorClick.mockRestore();
+ });
+
+ it.each([
+ ['Edit', 'You do not have permission to edit this panel'],
+ ['Clone', 'You do not have permission to clone this panel'],
+ ['Delete', 'You do not have permission to delete this panel'],
+ ])(
+ '%s is disabled with its reason when the role lacks permission',
+ async (name, reason) => {
+ mockComponentPermission.mockReturnValue([false, false]);
+ const props = renderHeader();
+ await openMenu();
+
+ const row = await screen.findByRole('menuitem', { name });
+ expect(row).toHaveAttribute('aria-disabled', 'true');
+ expect(screen.getByRole('menuitem', { name: 'View' })).not.toHaveAttribute(
+ 'aria-disabled',
+ 'true',
+ );
+
+ await userEvent.click(row);
+ expect(props.onClone).not.toHaveBeenCalled();
+ expect(props.onDelete).not.toHaveBeenCalled();
+ expect(mockSafeNavigate).not.toHaveBeenCalled();
+
+ await userEvent.hover(row);
+ await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
+ reason,
+ );
+ },
+ );
+});
diff --git a/frontend/src/container/WidgetCard/Panels/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap b/frontend/src/container/WidgetCard/Panels/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap
index d7e8cb060a..cdb4c93f82 100644
--- a/frontend/src/container/WidgetCard/Panels/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap
+++ b/frontend/src/container/WidgetCard/Panels/__tests__/__snapshots__/TablePanelWrapper.test.tsx.snap
@@ -54,6 +54,7 @@ exports[`Table panel wrappper tests table should render fine with the query resp
>
<div
class="query-table"
+ data-testid="query-table"
>
<div
class="ant-table-wrapper resize-main-table css-dev-only-do-not-override-2i2tap"
diff --git a/frontend/src/modules/Servicemap/ServiceMap.tsx b/frontend/src/modules/Servicemap/ServiceMap.tsx
index 57445daaf6..5cabf410d7 100644
--- a/frontend/src/modules/Servicemap/ServiceMap.tsx
+++ b/frontend/src/modules/Servicemap/ServiceMap.tsx
@@ -93,14 +93,14 @@ function ServiceMap(props: ServiceMapProps): JSX.Element {
}
if (serviceMap.items.length === 0) {
- return <Card>No Service Found</Card>;
+ return <Card data-testid="service-map-empty">No Service Found</Card>;
}
return <Map fgRef={fgRef} serviceMap={serviceMap} />;
};
return (
- <Container className="service-map-container">
+ <Container className="service-map-container" data-testid="service-map">
<ResourceAttributesFilter
suffixIcon={
<TextToolTip
diff --git a/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/CeleryOverviewDetails.tsx b/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/CeleryOverviewDetails.tsx
index 25ad03d1e5..5937209cdc 100644
--- a/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/CeleryOverviewDetails.tsx
+++ b/frontend/src/pages/Celery/CeleryOverview/CeleryOverviewDetail/CeleryOverviewDetails.tsx
@@ -54,6 +54,7 @@ export default function CeleryOverviewDetails({
return (
<Drawer
+ data-testid="mq-overview-details-drawer"
width="60%"
title={
<div>
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/__tests__/DashboardActions.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/__tests__/DashboardActions.test.tsx
new file mode 100644
index 0000000000..ee365b33b2
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardPageToolbar/DashboardActions/__tests__/DashboardActions.test.tsx
@@ -0,0 +1,177 @@
+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
+import { cloneDashboardV2 } from 'api/generated/services/dashboard';
+import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
+import { server } from 'mocks-server/server';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+
+import DashboardActions from '../DashboardActions';
+
+const DASHBOARD_ID = 'dash-1';
+
+const dashboard = {
+ id: DASHBOARD_ID,
+ createdBy: '[email protected]',
+ locked: false,
+ spec: { display: { name: 'D' }, panels: {}, layouts: [], variables: [] },
+} as unknown as DashboardtypesGettableDashboardV2DTO;
+
+jest.mock(
+ 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
+ () => ({
+ useDashboardEditContext: (): unknown => ({
+ isEditable: true,
+ editChecks: [],
+ areOtherPermissionsLoading: false,
+ deleteChecks: [],
+ isLocked: false,
+ canEditDashboard: true,
+ canDeleteDashboard: true,
+ editDisabledTooltip: '',
+ deleteDisabledTooltip: '',
+ }),
+ }),
+);
+
+const mockSafeNavigate = jest.fn();
+jest.mock('hooks/useSafeNavigate', () => ({
+ useSafeNavigate: (): { safeNavigate: jest.Mock } => ({
+ safeNavigate: mockSafeNavigate,
+ }),
+}));
+
+const mockConfirmDelete = jest.fn();
+jest.mock('../useDeleteDashboardAction', () => ({
+ useDeleteDashboardAction: (): unknown => ({
+ contextHolder: null,
+ confirmDeleteDashboard: mockConfirmDelete,
+ }),
+}));
+
+jest.mock('api/generated/services/dashboard', () => ({
+ ...jest.requireActual('api/generated/services/dashboard'),
+ cloneDashboardV2: jest.fn(),
+}));
+
+interface Handlers {
+ onLockToggle: jest.Mock;
+ onOpenRename: jest.Mock;
+ enter: jest.Mock;
+}
+
+function renderActions(isDashboardLocked = false): Handlers {
+ const handlers = {
+ onLockToggle: jest.fn(),
+ onOpenRename: jest.fn(),
+ enter: jest.fn(),
+ };
+ render(
+ <DashboardActions
+ title="D"
+ dashboard={dashboard}
+ handle={
+ {
+ active: false,
+ enter: handlers.enter,
+ exit: jest.fn(),
+ node: { current: null },
+ } as never
+ }
+ isDashboardLocked={isDashboardLocked}
+ onAddPanel={jest.fn()}
+ onLockToggle={handlers.onLockToggle}
+ onOpenRename={handlers.onOpenRename}
+ />,
+ );
+ return handlers;
+}
+
+async function clickRow(testId: string): Promise<void> {
+ await userEvent.click(screen.getByRole('button', { name: /Actions/ }));
+ const row = await screen.findByTestId(testId);
+ await waitFor(() => {
+ expect(row).not.toHaveAttribute('data-loading');
+ expect(row).not.toHaveAttribute('data-disabled');
+ });
+ await userEvent.click(row);
+}
+
+describe('DashboardActions menu rows', () => {
+ beforeEach(() => {
+ server.use(setupAuthzAdmin());
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ server.resetHandlers();
+ });
+
+ it('Rename calls onOpenRename only', async () => {
+ const handlers = renderActions();
+ await clickRow('dashboard-action-rename');
+
+ expect(handlers.onOpenRename).toHaveBeenCalledTimes(1);
+ expect(handlers.onLockToggle).not.toHaveBeenCalled();
+ expect(handlers.enter).not.toHaveBeenCalled();
+ expect(mockConfirmDelete).not.toHaveBeenCalled();
+ });
+
+ it('Clone clones the dashboard and navigates to the copy', async () => {
+ (cloneDashboardV2 as jest.Mock).mockResolvedValue({
+ data: { id: 'dash-copy' },
+ });
+ const handlers = renderActions();
+ await clickRow('dashboard-action-clone');
+
+ await waitFor(() =>
+ expect(cloneDashboardV2).toHaveBeenCalledWith({ id: DASHBOARD_ID }),
+ );
+ await waitFor(() =>
+ expect(mockSafeNavigate).toHaveBeenCalledWith('/dashboard/dash-copy'),
+ );
+ expect(handlers.onOpenRename).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [false, 'Lock dashboard'],
+ [true, 'Unlock dashboard'],
+ ])('locked=%s shows "%s" and calls onLockToggle', async (locked, label) => {
+ const handlers = renderActions(locked);
+ await clickRow('dashboard-action-lock');
+
+ expect(handlers.onLockToggle).toHaveBeenCalledTimes(1);
+ expect(handlers.onOpenRename).not.toHaveBeenCalled();
+ await userEvent.click(screen.getByRole('button', { name: /Actions/ }));
+ await expect(
+ screen.findByTestId('dashboard-action-lock'),
+ ).resolves.toHaveTextContent(label);
+ });
+
+ it('Full screen enters full screen', async () => {
+ const handlers = renderActions();
+ await clickRow('dashboard-action-fullscreen');
+
+ expect(handlers.enter).toHaveBeenCalledTimes(1);
+ expect(handlers.onLockToggle).not.toHaveBeenCalled();
+ });
+
+ it('New section opens the section title modal', async () => {
+ const handlers = renderActions();
+ expect(screen.queryByTestId('section-title-cancel')).not.toBeInTheDocument();
+
+ await clickRow('dashboard-action-new-section');
+
+ await expect(
+ screen.findByTestId('section-title-cancel'),
+ ).resolves.toBeInTheDocument();
+ expect(handlers.onOpenRename).not.toHaveBeenCalled();
+ });
+
+ it('Delete asks for delete confirmation', async () => {
+ const handlers = renderActions();
+ await clickRow('dashboard-action-delete');
+
+ expect(mockConfirmDelete).toHaveBeenCalledTimes(1);
+ expect(handlers.onOpenRename).not.toHaveBeenCalled();
+ expect(handlers.onLockToggle).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/VariableForm/VariableForm.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/VariableForm/VariableForm.tsx
index 71a77e9ab7..5d809440ef 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/VariableForm/VariableForm.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/VariableForm/VariableForm.tsx
@@ -205,6 +205,7 @@ function VariableForm({
color="secondary"
prefix={<X size={14} />}
onClick={onClose}
+ testId="variable-discard"
>
Discard
</Button>
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/VariableForm/__tests__/VariableTypeTabs.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/VariableForm/__tests__/VariableTypeTabs.test.tsx
new file mode 100644
index 0000000000..6989170ac7
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/Variables/VariableForm/__tests__/VariableTypeTabs.test.tsx
@@ -0,0 +1,40 @@
+import { render, screen, userEvent } from 'tests/test-utils';
+
+import VariableTypeTabs from '../VariableTypeTabs';
+
+const panels = {
+ DYNAMIC: <div>dynamic panel</div>,
+ TEXT: <div>text panel</div>,
+ CUSTOM: <div>custom panel</div>,
+ QUERY: <div>query panel</div>,
+};
+
+describe('VariableTypeTabs', () => {
+ it.each([
+ ['variable-type-custom', 'CUSTOM'],
+ ['variable-type-textbox', 'TEXT'],
+ ['variable-type-query', 'QUERY'],
+ ])('clicking %s calls onChange(%s)', async (testId, type) => {
+ const onChange = jest.fn();
+ render(
+ <VariableTypeTabs value="DYNAMIC" onChange={onChange} panels={panels} />,
+ );
+
+ await userEvent.click(screen.getByTestId(testId));
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(type);
+ });
+
+ it('shows the panel of the controlled value', () => {
+ render(
+ <VariableTypeTabs value="CUSTOM" onChange={jest.fn()} panels={panels} />,
+ );
+
+ expect(screen.getByText('custom panel')).toBeVisible();
+ expect(screen.getByTestId('variable-type-custom')).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ });
+});
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/__tests__/DashboardSettings.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/__tests__/DashboardSettings.test.tsx
new file mode 100644
index 0000000000..f906c8e62b
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/DashboardSettings/__tests__/DashboardSettings.test.tsx
@@ -0,0 +1,76 @@
+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
+import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
+import { server } from 'mocks-server/server';
+import { render, screen } from 'tests/test-utils';
+
+import { useDashboardStore } from '../../store/useDashboardStore';
+import DashboardSettings from '../index';
+
+const dashboard = {
+ id: 'dash-1',
+ spec: { display: { name: 'D' }, panels: {}, layouts: [], variables: [] },
+} as unknown as DashboardtypesGettableDashboardV2DTO;
+
+jest.mock('hooks/useGetTenantLicense', () => ({
+ useGetTenantLicense: (): unknown => ({
+ isCloudUser: true,
+ isEnterpriseSelfHostedUser: false,
+ }),
+}));
+
+jest.mock(
+ 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
+ () => ({
+ useDashboardEditContext: (): unknown => ({
+ isEditable: true,
+ editChecks: [],
+ areOtherPermissionsLoading: false,
+ deleteChecks: [],
+ isLocked: false,
+ canEditDashboard: true,
+ canDeleteDashboard: true,
+ editDisabledTooltip: '',
+ deleteDisabledTooltip: '',
+ }),
+ }),
+);
+
+describe('DashboardSettings initial tab', () => {
+ beforeEach(() => {
+ server.use(setupAuthzAdmin());
+ });
+
+ afterEach(() => {
+ useDashboardStore.getState().clearSettingsRequest();
+ server.resetHandlers();
+ });
+
+ it('opens on Overview without a settings request', async () => {
+ render(<DashboardSettings dashboard={dashboard} />);
+
+ await expect(
+ screen.findByRole('tab', { name: /Overview/ }),
+ ).resolves.toHaveAttribute('aria-selected', 'true');
+ expect(screen.getByRole('tab', { name: /Variables/ })).toHaveAttribute(
+ 'aria-selected',
+ 'false',
+ );
+ });
+
+ it.each(['Variables', 'Publish'] as const)(
+ 'opens on the %s tab a settings request names',
+ async (tab) => {
+ useDashboardStore.getState().requestSettings({ tab });
+
+ render(<DashboardSettings dashboard={dashboard} />);
+
+ await expect(
+ screen.findByRole('tab', { name: new RegExp(tab) }),
+ ).resolves.toHaveAttribute('aria-selected', 'true');
+ expect(screen.getByRole('tab', { name: /Overview/ })).toHaveAttribute(
+ 'aria-selected',
+ 'false',
+ );
+ },
+ );
+});
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/ConfigPane.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/ConfigPane.tsx
index 0edced3d70..d54bce518f 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/ConfigPane.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/ConfigPane/ConfigPane.tsx
@@ -99,7 +99,7 @@ function ConfigPane({
onChangeSpec({ ...spec, display: { ...spec.display, [field]: value } });
return (
- <div className={styles.config}>
+ <div className={styles.config} data-testid="panel-editor-v2-config">
<header className={styles.heading}>
<span className={styles.marker} />
<Typography.Text>Panel Details</Typography.Text>
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/PanelEditorQueryBuilder.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/PanelEditorQueryBuilder.tsx
index 515a234503..a4ca1a5782 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/PanelEditorQueryBuilder.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelEditor/PanelEditorQueryBuilder/PanelEditorQueryBuilder.tsx
@@ -200,6 +200,7 @@ function PanelEditorQueryBuilder({
<TextToolTip text="This will temporarily save the current query and graph state. This will persist across tab change" />
<RunQueryBtn
label="Run Query"
+ testId="panel-editor-v2-run-query"
onStageRunQuery={onStageRunQuery}
isLoadingQueries={isLoadingQueries}
handleCancelQuery={onCancelQuery}
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/Panel.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/Panel.tsx
index ab120b85e3..8792e57b17 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/Panel.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/Panel.tsx
@@ -47,6 +47,7 @@ function Panel({
// Stable locator so the "Download as PNG" action can find this node to
// capture, without threading a ref through the header/actions chain.
data-panel-root={panelId}
+ data-testid={`panel-${panelId}`}
>
{panelDefinition.mode === 'static' ? (
<StaticPanelContent
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/PanelActionsMenu.test.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/PanelActionsMenu.test.tsx
new file mode 100644
index 0000000000..77d4e9f86f
--- /dev/null
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/PanelsAndSectionsLayout/Panel/PanelActionsMenu/__tests__/PanelActionsMenu.test.tsx
@@ -0,0 +1,163 @@
+import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
+import type { PanelQueryData } from 'pages/DashboardPage/DashboardContainer/queryV5/types';
+import { render, screen, userEvent } from 'tests/test-utils';
+
+import type { DashboardSection } from '../../../../utils';
+import PanelActionsMenu from '../PanelActionsMenu';
+
+jest.mock(
+ 'pages/DashboardPage/DashboardContainer/hooks/useDashboardEditContext',
+ () => ({
+ useDashboardEditContext: (): unknown => ({
+ isEditable: true,
+ editChecks: [],
+ areOtherPermissionsLoading: false,
+ deleteChecks: [],
+ isLocked: false,
+ canEditDashboard: true,
+ canDeleteDashboard: true,
+ editDisabledTooltip: '',
+ deleteDisabledTooltip: '',
+ }),
+ }),
+);
+
+jest.mock(
+ 'pages/DashboardPage/DashboardContainer/hooks/useOpenPanelEditor',
+ () => ({ useOpenPanelEditor: (): jest.Mock => jest.fn() }),
+);
+
+jest.mock('../../hooks/useViewPanel', () => ({
+ useViewPanel: (): unknown => ({
+ openView: jest.fn(),
+ closeView: jest.fn(),
+ expandedPanelId: null,
+ }),
+}));
+
+const mockMovePanel = jest.fn();
+jest.mock('../../hooks/useMovePanelToSection', () => ({
+ useMovePanelToSection: (): jest.Mock => mockMovePanel,
+}));
+
+jest.mock('../../hooks/useDeletePanel', () => ({
+ useDeletePanel: (): jest.Mock => jest.fn(),
+}));
+
+jest.mock('../../hooks/useClonePanel', () => ({
+ useClonePanel: (): jest.Mock => jest.fn(),
+}));
+
+jest.mock('../../hooks/useCreateAlertFromPanel', () => ({
+ useCreateAlertFromPanel: (): jest.Mock => jest.fn(),
+}));
+
+const mockDownloadImage = jest.fn();
+jest.mock('../../hooks/useDownloadPanelImage', () => ({
+ useDownloadPanelImage: (): { downloadPanelImage: jest.Mock } => ({
+ downloadPanelImage: mockDownloadImage,
+ }),
+}));
+
+const mockDownloadCsv = jest.fn();
+jest.mock('../../hooks/useDownloadPanelCsv', () => ({
+ useDownloadPanelCsv: (): jest.Mock => mockDownloadCsv,
+}));
+
+function section(
+ layoutIndex: number,
+ title: string | undefined,
+): DashboardSection {
+ return {
+ id: `section-${layoutIndex}`,
+ layoutIndex,
+ title,
+ items: [],
+ repeatVariable: undefined,
+ };
+}
+
+const tablePanel = {
+ kind: 'Panel',
+ spec: {
+ display: { name: 'Requests' },
+ plugin: { kind: 'signoz/TablePanel', spec: {} },
+ queries: [],
+ },
+} as unknown as DashboardtypesPanelDTO;
+
+const data = {
+ response: undefined,
+ requestPayload: undefined,
+ legendMap: {},
+} as PanelQueryData;
+
+function renderMenu(): void {
+ render(
+ <PanelActionsMenu
+ panelId="panel-1"
+ panel={tablePanel}
+ data={data}
+ panelActions={{
+ currentLayoutIndex: 1,
+ sections: [section(0, undefined), section(1, 'A'), section(2, 'B')],
+ }}
+ />,
+ );
+}
+
+async function openSubmenu(name: string): Promise<void> {
+ await userEvent.click(screen.getByRole('button', { name: 'Panel actions' }));
+ await userEvent.click(await screen.findByRole('menuitem', { name }));
+}
+
+describe('PanelActionsMenu submenus', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it.each([
+ ['Download as PNG', 'png'],
+ ['Download as SVG', 'svg'],
+ ])('"%s" downloads the panel image as %s', async (label, format) => {
+ renderMenu();
+ await openSubmenu('Download');
+ await userEvent.click(await screen.findByRole('menuitem', { name: label }));
+
+ expect(mockDownloadImage).toHaveBeenCalledTimes(1);
+ expect(mockDownloadImage).toHaveBeenCalledWith('panel-1', 'Requests', format);
+ expect(mockDownloadCsv).not.toHaveBeenCalled();
+ });
+
+ it('"Download as CSV" exports the table data, not an image', async () => {
+ renderMenu();
+ await openSubmenu('Download');
+ await userEvent.click(
+ await screen.findByRole('menuitem', { name: 'Download as CSV' }),
+ );
+
+ expect(mockDownloadCsv).toHaveBeenCalledTimes(1);
+ expect(mockDownloadImage).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ ['Dashboard (root)', 0],
+ ['B', 2],
+ ])('Move to "%s" moves the panel to layout %s', async (label, target) => {
+ renderMenu();
+ await openSubmenu('Move to section');
+
+ const row = await screen.findByRole('menuitem', { name: label });
+ // The panel already sits in "A".
+ expect(screen.queryByRole('menuitem', { name: 'A' })).not.toBeInTheDocument();
+
+ await userEvent.click(row);
+
+ expect(mockMovePanel).toHaveBeenCalledTimes(1);
+ expect(mockMovePanel).toHaveBeenCalledWith({
+ panelId: 'panel-1',
+ fromLayoutIndex: 1,
+ toLayoutIndex: target,
+ });
+ });
+});
diff --git a/frontend/src/pages/DashboardPage/DashboardContainer/components/ConfirmDeleteDialog/ConfirmDeleteDialog.tsx b/frontend/src/pages/DashboardPage/DashboardContainer/components/ConfirmDeleteDialog/ConfirmDeleteDialog.tsx
index 14dba8cc59..91cb74bd7c 100644
--- a/frontend/src/pages/DashboardPage/DashboardContainer/components/ConfirmDeleteDialog/ConfirmDeleteDialog.tsx
+++ b/frontend/src/pages/DashboardPage/DashboardContainer/components/ConfirmDeleteDialog/ConfirmDeleteDialog.tsx
@@ -37,6 +37,7 @@ function ConfirmDeleteDialog({
color="secondary"
onClick={onClose}
prefix={<X size={12} />}
+ testId="confirm-delete-cancel"
>
Cancel
</Button>
diff --git a/frontend/src/pages/DashboardsListPage/components/DashboardRow/DashboardRow.actions.test.tsx b/frontend/src/pages/DashboardsListPage/components/DashboardRow/DashboardRow.actions.test.tsx
new file mode 100644
index 0000000000..5da3925cf1
--- /dev/null
+++ b/frontend/src/pages/DashboardsListPage/components/DashboardRow/DashboardRow.actions.test.tsx
@@ -0,0 +1,102 @@
+import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
+import { server } from 'mocks-server/server';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+
+import type { DashboardListItem } from '../../utils/helpers';
+
+import DashboardRow from './DashboardRow';
+
+const mockSafeNavigate = jest.fn();
+jest.mock('hooks/useSafeNavigate', () => ({
+ useSafeNavigate: (): { safeNavigate: jest.Mock } => ({
+ safeNavigate: mockSafeNavigate,
+ }),
+}));
+
+const mockSetCopy = jest.fn();
+jest.mock('react-use', () => ({
+ ...jest.requireActual('react-use'),
+ useCopyToClipboard: (): [unknown, jest.Mock] => [{}, mockSetCopy],
+}));
+
+jest.mock('api/common/logEvent', () => ({
+ __esModule: true,
+ default: jest.fn(),
+}));
+
+const dashboard = {
+ id: 'dash-1',
+ legacy: false,
+ pinned: false,
+ locked: false,
+ image: '',
+ createdBy: '[email protected]',
+ updatedBy: '[email protected]',
+ createdAt: '2024-01-01T00:00:00Z',
+ updatedAt: '2024-01-02T00:00:00Z',
+ tags: [{ key: 'team', value: 'infra' }],
+ spec: { display: { name: 'My Dashboard' } },
+} as unknown as DashboardListItem;
+
+async function clickRow(testId: string): Promise<void> {
+ render(
+ <DashboardRow
+ dashboard={dashboard}
+ index={0}
+ showUpdatedAt={false}
+ showUpdatedBy={false}
+ />,
+ );
+ await userEvent.click(screen.getByTestId('dashboard-action-icon'));
+ const row = await screen.findByTestId(testId);
+ await waitFor(() => {
+ expect(row).not.toHaveAttribute('data-loading');
+ expect(row).not.toHaveAttribute('data-disabled');
+ });
+ await userEvent.click(row);
+}
+
+describe('DashboardRow actions menu', () => {
+ beforeEach(() => {
+ server.use(setupAuthzAdmin());
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ server.resetHandlers();
+ });
+
+ it('Rename opens the rename modal without navigating', async () => {
+ await clickRow('dashboard-action-rename');
+
+ await expect(
+ screen.findByTestId('rename-dashboard-input'),
+ ).resolves.toBeInTheDocument();
+ expect(screen.queryByTestId('edit-dashboard-tags')).not.toBeInTheDocument();
+ expect(mockSafeNavigate).not.toHaveBeenCalled();
+ });
+
+ it('Edit Tags opens the tags modal without navigating', async () => {
+ await clickRow('dashboard-action-edit-tags');
+
+ await expect(
+ screen.findByTestId('edit-dashboard-tags'),
+ ).resolves.toBeInTheDocument();
+ expect(
+ screen.queryByTestId('rename-dashboard-input'),
+ ).not.toBeInTheDocument();
+ expect(mockSafeNavigate).not.toHaveBeenCalled();
+ });
+
+ it('Copy Link copies the absolute dashboard URL without navigating', async () => {
+ await clickRow('dashboard-action-copy-link');
+
+ expect(mockSetCopy).toHaveBeenCalledTimes(1);
+ expect(mockSetCopy.mock.calls[0][0]).toMatch(/\/dashboard\/dash-1$/);
+ expect(mockSafeNavigate).not.toHaveBeenCalled();
+ expect(
+ screen.queryByTestId('rename-dashboard-input'),
+ ).not.toBeInTheDocument();
+ expect(screen.queryByTestId('edit-dashboard-tags')).not.toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/pages/ErrorBoundaryFallback/ErrorBoundaryFallback.tsx b/frontend/src/pages/ErrorBoundaryFallback/ErrorBoundaryFallback.tsx
index 3e22adae11..45d0d0a4e2 100644
--- a/frontend/src/pages/ErrorBoundaryFallback/ErrorBoundaryFallback.tsx
+++ b/frontend/src/pages/ErrorBoundaryFallback/ErrorBoundaryFallback.tsx
@@ -23,7 +23,10 @@ function ErrorBoundaryFallback(): JSX.Element {
}, [isCloudUserVal]);
return (
- <div className="error-boundary-fallback-container">
+ <div
+ className="error-boundary-fallback-container"
+ data-testid="error-boundary-fallback"
+ >
<div className="error-boundary-fallback-content">
<div className="error-icon">
<img src={cloudUrl} alt="error-cloud-icon" />
diff --git a/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx b/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx
index a3027e828e..5d3b68f4fc 100644
--- a/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetailPage/MQDetailPage.tsx
@@ -88,6 +88,7 @@ function MQDetailPage(): JSX.Element {
Kafka / views /
</div>
<Select
+ data-testid="mq-view-select"
className="messaging-queue-options"
defaultValue={MessagingQueuesViewType.consumerLag.value}
popupClassName="messaging-queue-options-popup"
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx b/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx
index 7bb916e809..45a38f7f60 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/DropRateView/DropRateView.tsx
@@ -256,6 +256,7 @@ function DropRateView(): JSX.Element {
<EvaluationTimeSelector setInterval={setInterval} />
</div>
<Table
+ data-testid="mq-drop-rate-table"
className={cx('mq-table', 'pagination-left')}
pagination={paginationConfig}
size="middle"
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/MQDetails.tsx b/frontend/src/pages/MessagingQueues/MQDetails/MQDetails.tsx
index ce1e2efbbd..35a9777f87 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/MQDetails.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/MQDetails.tsx
@@ -62,6 +62,7 @@ function MessagingQueuesOptions({
return (
<ToggleGroup
+ testId="mq-detail-type-toggle"
variant="outlined"
color="secondary"
size="sm"
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx b/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx
index 2b92cb2a7b..205cd15699 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/MQTables/MQTables.tsx
@@ -329,6 +329,7 @@ function MessagingQueuesTable({
</div>
)}
<Table
+ data-testid={`mq-table-${type.toLowerCase()}`}
className={cx(
'mq-table',
type !== 'Detail' ? 'mq-overview-row-clickable' : 'pagination-left',
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx b/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx
index b0ebd06cb9..5c9a512351 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/MessagingQueueOverview.tsx
@@ -35,6 +35,7 @@ function ProducerLatencyTabs({
return (
<ToggleGroup
+ testId="mq-producer-latency-toggle"
variant="outlined"
color="secondary"
size="sm"
diff --git a/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPage.tsx b/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPage.tsx
index 74312b6c01..3ac339032a 100644
--- a/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPage.tsx
+++ b/frontend/src/pages/MessagingQueues/MQDetails/MetricPage/MetricPage.tsx
@@ -140,7 +140,7 @@ function MetricPage(): JSX.Element {
}, []);
return (
- <div className="metric-page">
+ <div className="metric-page" data-testid="mq-metric-page">
<MetricColumnGraphs checkIfDataExists={checkIfDataExists} />
{metricSections.map(({ key, title, description, graphCount }) => (
<CollapsibleMetricSection
diff --git a/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx b/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx
index 3964499e49..5b67282c98 100644
--- a/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx
+++ b/frontend/src/pages/MessagingQueues/MQGraph/MQGraph.tsx
@@ -80,6 +80,7 @@ function MessagingQueuesGraph(): JSX.Element {
};
return (
<Card
+ data-testid="mq-consumer-lag-graph"
isDarkMode={isDarkMode}
$panelType={PANEL_TYPES.TIME_SERIES}
className="mq-graph"
diff --git a/frontend/src/pages/MessagingQueues/MessagingQueues.tsx b/frontend/src/pages/MessagingQueues/MessagingQueues.tsx
index 6b68297ad5..c76beec3e7 100644
--- a/frontend/src/pages/MessagingQueues/MessagingQueues.tsx
+++ b/frontend/src/pages/MessagingQueues/MessagingQueues.tsx
@@ -159,6 +159,7 @@ function MessagingQueues(): JSX.Element {
</div>
<div className="button-grp">
<Button
+ data-testid="mq-view-details-consumerLag"
type="default"
onClick={(e): void =>
redirectToDetailsPage(MessagingQueuesViewType.consumerLag.value, e)
@@ -177,6 +178,7 @@ function MessagingQueues(): JSX.Element {
</div>
<div className="button-grp">
<Button
+ data-testid="mq-view-details-producerLatency"
type="default"
onClick={(e): void =>
redirectToDetailsPage(MessagingQueuesViewType.producerLatency.value, e)
@@ -195,6 +197,7 @@ function MessagingQueues(): JSX.Element {
</div>
<div className="button-grp">
<Button
+ data-testid="mq-view-details-partitionLatency"
type="default"
onClick={(e): void =>
redirectToDetailsPage(
@@ -216,6 +219,7 @@ function MessagingQueues(): JSX.Element {
</div>
<div className="button-grp">
<Button
+ data-testid="mq-view-details-dropRate"
type="default"
onClick={(e): void =>
redirectToDetailsPage(MessagingQueuesViewType.dropRate.value, e)
@@ -234,6 +238,7 @@ function MessagingQueues(): JSX.Element {
</div>
<div className="button-grp">
<Button
+ data-testid="mq-view-details-metricPage"
type="default"
onClick={(e): void =>
redirectToDetailsPage(MessagingQueuesViewType.metricPage.value, e)
diff --git a/frontend/src/pages/ServiceTopLevelOperations/index.tsx b/frontend/src/pages/ServiceTopLevelOperations/index.tsx
index 91cf50be11..daafe0d2ea 100644
--- a/frontend/src/pages/ServiceTopLevelOperations/index.tsx
+++ b/frontend/src/pages/ServiceTopLevelOperations/index.tsx
@@ -119,7 +119,10 @@ export default function ServiceTopLevelOperations(): JSX.Element {
)}
{!isLoading && (
- <div className="top-level-operations-list">
+ <div
+ className="top-level-operations-list"
+ data-testid="top-level-operations-table"
+ >
<Table
columns={columns}
bordered
diff --git a/frontend/src/pages/Shortcuts/Shortcuts.tsx b/frontend/src/pages/Shortcuts/Shortcuts.tsx
index 8e217b5fac..be69852b55 100644
--- a/frontend/src/pages/Shortcuts/Shortcuts.tsx
+++ b/frontend/src/pages/Shortcuts/Shortcuts.tsx
@@ -10,7 +10,11 @@ function Shortcuts(): JSX.Element {
const tableData = generateTableData(shortcutSection);
return (
- <section key={shortcutSection} className="shortcut-section">
+ <section
+ key={shortcutSection}
+ className="shortcut-section"
+ data-testid={`shortcut-section-${shortcutSection}`}
+ >
<Typography.Text className="shortcut-section-heading">
{shortcutSection}
</Typography.Text>
@@ -26,7 +30,7 @@ function Shortcuts(): JSX.Element {
}
return (
- <div className="keyboard-shortcuts">
+ <div className="keyboard-shortcuts" data-testid="keyboard-shortcuts-page">
{Object.keys(ALL_SHORTCUTS).map((shortcutSection) =>
getShortcutTable(shortcutSection),
)}
diff --git a/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx b/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx
index 8465bb441e..effc76aad6 100644
--- a/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx
+++ b/frontend/src/pages/SignUp/__tests__/SignUp.test.tsx
@@ -256,4 +256,110 @@ describe('SignUp Component - Regular Signup', () => {
expect(errorCallouts.length).toBeGreaterThan(0);
});
});
+
+ describe('Enter key submission', () => {
+ function mockSignup(delayMs = 0): { registerCalls: () => number } {
+ let calls = 0;
+ server.use(
+ rest.post(REGISTER_ENDPOINT, (_req, res, ctx) => {
+ calls += 1;
+ return res(
+ ctx.delay(delayMs),
+ ctx.status(200),
+ ctx.json({ data: mockSignupResponse, status: 'success' }),
+ );
+ }),
+ rest.post(EMAIL_PASSWORD_ENDPOINT, (_req, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({ data: mockTokenResponse, status: 'success' }),
+ ),
+ ),
+ );
+ return { registerCalls: (): number => calls };
+ }
+
+ it('submits once on Enter in the confirm password field', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { registerCalls } = mockSignup();
+
+ render(<SignUp />, undefined, { initialRoute: '/signup' });
+
+ await user.type(screen.getByLabelText(/email address/i), '[email protected]');
+ await user.type(
+ screen.getByPlaceholderText(/enter new password/i),
+ 'password123',
+ );
+ await user.type(
+ screen.getByPlaceholderText(/confirm your new password/i),
+ 'password123{enter}',
+ );
+
+ await waitFor(() => {
+ expect(mockAfterLogin).toHaveBeenCalledWith(
+ 'mock-access-token',
+ 'mock-refresh-token',
+ );
+ });
+ expect(registerCalls()).toBe(1);
+ });
+
+ it('does not submit on Enter while the passwords do not match', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { registerCalls } = mockSignup();
+
+ render(<SignUp />, undefined, { initialRoute: '/signup' });
+
+ await user.type(screen.getByLabelText(/email address/i), '[email protected]');
+ await user.type(
+ screen.getByPlaceholderText(/enter new password/i),
+ 'password123',
+ );
+ await user.type(
+ screen.getByPlaceholderText(/confirm your new password/i),
+ 'password456',
+ );
+ expect(
+ screen.getByRole('button', { name: /access my workspace/i }),
+ ).toHaveAttribute('aria-disabled', 'true');
+
+ await user.keyboard('{enter}');
+
+ // Give a wrongly sent request time to land before asserting it never did.
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ expect(registerCalls()).toBe(0);
+ });
+
+ it('does not submit again on Enter while the first submit is loading', async () => {
+ const user = userEvent.setup({ pointerEventsCheck: 0 });
+ const { registerCalls } = mockSignup(1000);
+
+ render(<SignUp />, undefined, { initialRoute: '/signup' });
+
+ const emailInput = screen.getByLabelText(/email address/i);
+ await user.type(emailInput, '[email protected]');
+ await user.type(
+ screen.getByPlaceholderText(/enter new password/i),
+ 'password123',
+ );
+ await user.type(
+ screen.getByPlaceholderText(/confirm your new password/i),
+ 'password123{enter}',
+ );
+
+ await waitFor(() => {
+ expect(
+ screen.getByRole('button', { name: /access my workspace/i }),
+ ).toHaveAttribute('aria-disabled', 'true');
+ });
+
+ // The password inputs are disabled while loading; the email input is not.
+ await user.type(emailInput, '{enter}');
+
+ await waitFor(() => {
+ expect(mockAfterLogin).toHaveBeenCalled();
+ });
+ expect(registerCalls()).toBe(1);
+ });
+ });
});
diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/__tests__/DockModeSwitcher.test.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/__tests__/DockModeSwitcher.test.tsx
new file mode 100644
index 0000000000..d5477ce32c
--- /dev/null
+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/__tests__/DockModeSwitcher.test.tsx
@@ -0,0 +1,42 @@
+import { render, screen, userEvent } from 'tests/test-utils';
+
+import { SpanDetailVariant } from '../constants';
+import DockModeSwitcher from '../DockModeSwitcher';
+
+describe('DockModeSwitcher', () => {
+ it.each([
+ [SpanDetailVariant.DIALOG, SpanDetailVariant.DOCKED],
+ [SpanDetailVariant.DOCKED, SpanDetailVariant.DIALOG],
+ [SpanDetailVariant.DOCKED_RIGHT, SpanDetailVariant.DIALOG],
+ ])(
+ 'calls onChange with %s when its item is clicked',
+ async (target, current) => {
+ const onChange = jest.fn();
+ render(<DockModeSwitcher value={current} onChange={onChange} />);
+
+ await userEvent.click(screen.getByTestId(`dock-mode-${target}`));
+
+ expect(onChange).toHaveBeenCalledTimes(1);
+ expect(onChange).toHaveBeenCalledWith(target);
+ },
+ );
+
+ it('marks the current mode pressed and ignores a click on it', async () => {
+ const onChange = jest.fn();
+ render(
+ <DockModeSwitcher
+ value={SpanDetailVariant.DOCKED_RIGHT}
+ onChange={onChange}
+ />,
+ );
+
+ const current = screen.getByTestId(
+ `dock-mode-${SpanDetailVariant.DOCKED_RIGHT}`,
+ );
+ expect(current).toHaveAttribute('aria-pressed', 'true');
+
+ await userEvent.click(current);
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/__tests__/SpanDetailsPanel.test.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/__tests__/SpanDetailsPanel.test.tsx
index 44671dd384..2ec2d7e0c0 100644
--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/__tests__/SpanDetailsPanel.test.tsx
+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/__tests__/SpanDetailsPanel.test.tsx
@@ -107,12 +107,15 @@ const createMockSpan = (): SpanV3 => ({
const panelState = { isOpen: true, open: jest.fn(), close: jest.fn() };
-function renderPanel(width: number): ReturnType<typeof render> {
+function renderPanel(
+ width: number,
+ span: SpanV3 = createMockSpan(),
+): ReturnType<typeof render> {
mockWidth = width;
return render(
<SpanDetailsPanel
panelState={panelState}
- selectedSpan={createMockSpan()}
+ selectedSpan={span}
variant={SpanDetailVariant.DOCKED}
traceStartTime={1}
traceEndTime={101}
@@ -166,6 +169,32 @@ describe('SpanDetailsPanel – tabs', () => {
});
});
+describe('SpanDetailsPanel – Events count badge', () => {
+ const makeEvent = (name: string): SpanV3['events'][number] => ({
+ name,
+ timeUnixNano: 1_700_000_000_000_000_000,
+ attributeMap: {},
+ isError: false,
+ });
+
+ it('shows the number of span events on the Events tab', () => {
+ renderPanel(400, {
+ ...createMockSpan(),
+ events: [makeEvent('a'), makeEvent('b')],
+ });
+
+ const eventsTab = screen.getByRole('tab', { name: /events/i });
+ expect(within(eventsTab).getByText('2')).toBeInTheDocument();
+ });
+
+ it('shows no count when the span has no events', () => {
+ renderPanel(400);
+
+ const eventsTab = screen.getByRole('tab', { name: /events/i });
+ expect(eventsTab).toHaveTextContent(/^Events$/);
+ });
+});
+
// The footer lives on the panel body (not inside the tab content) so it stays
// pinned to the panel's visible bottom edge; it should track the active tab.
describe('SpanDetailsPanel – Open in Logs Explorer footer', () => {
diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/AddSpanToFunnelModal/AddSpanToFunnelModal.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/AddSpanToFunnelModal/AddSpanToFunnelModal.tsx
index 830409e234..d9502a90c4 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/AddSpanToFunnelModal/AddSpanToFunnelModal.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/AddSpanToFunnelModal/AddSpanToFunnelModal.tsx
@@ -265,6 +265,7 @@ function AddSpanToFunnelModal({
disabledTooltip="No changes to save"
size="md"
key="save"
+ testId="add-span-save-btn"
variant="solid"
color="primary"
width="135px"
diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx
index 14d30968d2..08ed93b7ca 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx
@@ -268,7 +268,11 @@ function Filters({
const pill = (
/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */
- <div className={styles.pill} onClick={onExpand}>
+ <div
+ className={styles.pill}
+ onClick={onExpand}
+ data-testid="waterfall-filter-pill"
+ >
<Search size={12} />
<span className={styles.pillText}>{expression || 'Search...'}</span>
{expression && <span className={styles.pillIndicator} />}
@@ -303,6 +307,7 @@ function Filters({
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
<div
className={cx(styles.root, isExpanded && styles.isExpanded)}
+ data-testid="waterfall-filters"
ref={containerRef}
onBlur={(e): void => {
const relatedTarget = e.relatedTarget as Node | null;
@@ -372,7 +377,7 @@ function Filters({
{hasExpression && (
<Tooltip title="Clear filter">
<Button
- aria-label="Action"
+ aria-label="Clear filter"
variant="ghost"
size="sm"
icon
@@ -386,7 +391,8 @@ function Filters({
)}
<Tooltip title="Collapse filters">
<Button
- aria-label="Action"
+ aria-label="Collapse filters"
+ testId="waterfall-filter-collapse"
variant="ghost"
size="sm"
icon
diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/QueryResult.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/QueryResult.tsx
index 68c90aff2e..fbaaab0a93 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/QueryResult.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/QueryResult.tsx
@@ -41,11 +41,15 @@ function QueryResult({
// Prefer count over loader on refresh so stale results stay visible.
content = (
<>
- <Typography.Text className={styles.resultNavCount}>
+ <Typography.Text
+ className={styles.resultNavCount}
+ testId="waterfall-filter-count"
+ >
{currentIndex + 1} / {total}
</Typography.Text>
<Button
- aria-label="Action"
+ aria-label="Previous match"
+ testId="waterfall-filter-prev"
disabledTooltip="This is the first result"
variant="ghost"
size="sm"
@@ -57,7 +61,8 @@ function QueryResult({
<ChevronUp size={14} />
</Button>
<Button
- aria-label="Action"
+ aria-label="Next match"
+ testId="waterfall-filter-next"
disabledTooltip="This is the last result"
variant="ghost"
size="sm"
@@ -83,7 +88,10 @@ function QueryResult({
);
} else if (noData) {
content = (
- <Typography.Text className={styles.filterStatus}>
+ <Typography.Text
+ className={styles.filterStatus}
+ testId="waterfall-filter-no-results"
+ >
No results found
</Typography.Text>
);
diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsx
index 9c68fd4a65..b9683bed44 100644
--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsx
+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsx
@@ -353,7 +353,7 @@ const SpanOverview = memo(function SpanOverview({
<span className={styles.rowActions}>
<Tooltip title="Copy Span Link">
<Button
- aria-label="Action"
+ aria-label="Copy span link"
variant="ghost"
size="sm"
icon
@@ -365,7 +365,8 @@ const SpanOverview = memo(function SpanOverview({
</Tooltip>
<Tooltip title="Add to Trace Funnel">
<Button
- aria-label="Action"
+ aria-label="Add to Trace Funnel"
+ testId="span-add-to-funnel-btn"
variant="ghost"
size="sm"
icon
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelConfiguration.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelConfiguration.tsx
index 95de88a18d..9765877784 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelConfiguration.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelConfiguration.tsx
@@ -95,7 +95,9 @@ function FunnelConfiguration({
<>
{!isTraceDetailsPage && (
<div className="funnel-configuration__description-wrapper">
- <div className="funnel-title">{funnel.funnel_name}</div>
+ <div className="funnel-title" data-testid="funnel-title">
+ {funnel.funnel_name}
+ </div>
<div className="funnel-description">
{funnel?.description ?? 'No description added.'}
</div>
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsx
index 8cc37a87ae..3c33aa8330 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsx
@@ -80,6 +80,7 @@ function FunnelStep({
return (
<div
+ data-testid={`funnel-step-${index}`}
className={cx('funnel-step', {
'funnel-step--readonly': !hasEditPermission,
})}
@@ -140,7 +141,10 @@ function FunnelStep({
<div className="funnel-step__content">
<div className="filters">
<div className="filters__service-and-span">
- <div className="service">
+ <div
+ className="service"
+ data-testid={`funnel-step-service-select-${index}`}
+ >
<Form.Item name={['steps', stepData.id, 'service_name']}>
<FilterSelect
placeholder="Select Service"
@@ -159,7 +163,7 @@ function FunnelStep({
/>
</Form.Item>
</div>
- <div className="span">
+ <div className="span" data-testid={`funnel-step-span-select-${index}`}>
<Form.Item name={['steps', stepData.id, 'span_name']}>
<FilterSelect
placeholder="Select Span name"
@@ -200,6 +204,7 @@ function FunnelStep({
<div className="error">
<Switch
color="primary"
+ testId={`funnel-step-errors-switch-${index}`}
textPlacement="right"
disabledTooltip="You need edit permissions to change this step"
value={stepData.has_errors}
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStepPopover.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStepPopover.tsx
index f678a1f850..ff05efb7e9 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStepPopover.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStepPopover.tsx
@@ -66,6 +66,7 @@ function FunnelStepActions({
type="text"
className="funnel-item__action-btn funnel-item__action-btn--delete"
icon={<Trash2 size={14} />}
+ data-testid="funnel-step-action-delete"
disabled={stepsCount <= 2 || !hasEditPermission}
onClick={(): void => {
if (stepsCount > 2) {
@@ -137,6 +138,8 @@ function FunnelStepPopover({
'funnel-item__action-icon--active': isPopoverOpen,
})}
size={14}
+ data-testid="funnel-step-actions"
+ aria-label="Step actions"
/>
</Popover>
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsContent.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsContent.tsx
index a2a7cae243..c89907b1e5 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsContent.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsContent.tsx
@@ -94,6 +94,7 @@ function StepsContent({
<Button
type="default"
className="steps-content__add-btn"
+ data-testid="funnel-add-step-btn"
onClick={isTraceDetailsPage ? handleAddForNewStep : handleAddStep}
icon={<Plus size={14} />}
disabled={!hasEditPermission}
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsFooter.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsFooter.tsx
index 0266a3c631..290a88506d 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsFooter.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/StepsFooter.tsx
@@ -27,13 +27,21 @@ function ValidTracesCount(): JSX.Element {
if (hasAllEmptyStepFields) {
return (
- <span className="steps-footer__valid-traces">No service / span names</span>
+ <span
+ className="steps-footer__valid-traces"
+ data-testid="funnel-valid-traces-status"
+ >
+ No service / span names
+ </span>
);
}
if (hasIncompleteStepFields) {
return (
- <span className="steps-footer__valid-traces">
+ <span
+ className="steps-footer__valid-traces"
+ data-testid="funnel-valid-traces-status"
+ >
Missing service / span names
</span>
);
@@ -45,13 +53,23 @@ function ValidTracesCount(): JSX.Element {
if (validTracesCount === 0) {
return (
- <span className="steps-footer__valid-traces steps-footer__valid-traces--none">
+ <span
+ className="steps-footer__valid-traces steps-footer__valid-traces--none"
+ data-testid="funnel-valid-traces-status"
+ >
No valid traces found
</span>
);
}
- return <span className="steps-footer__valid-traces">Valid traces found</span>;
+ return (
+ <span
+ className="steps-footer__valid-traces"
+ data-testid="funnel-valid-traces-status"
+ >
+ Valid traces found
+ </span>
+ );
}
function StepsFooter({ stepsCount, isSaving }: StepsFooterProps): JSX.Element {
@@ -62,7 +80,7 @@ function StepsFooter({ stepsCount, isSaving }: StepsFooterProps): JSX.Element {
<div className="steps-footer">
<div className="steps-footer__left">
<Cone className="funnel-icon" size={14} />
- <span>{stepsCount} steps</span>
+ <span data-testid="funnel-steps-count">{stepsCount} steps</span>
<span>·</span>
<ValidTracesCount />
</div>
@@ -70,6 +88,7 @@ function StepsFooter({ stepsCount, isSaving }: StepsFooterProps): JSX.Element {
<Button
disabled={hasIncompleteStepFields || !hasUnsavedChanges}
onClick={handleSaveFunnel}
+ data-testid="funnel-save-btn"
type="primary"
className="steps-footer__button steps-footer__button--run"
icon={<Check size={14} />}
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelResults.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelResults.tsx
index 2dd3302f37..f30ac39bee 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelResults.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelResults.tsx
@@ -51,7 +51,7 @@ function FunnelResults(): JSX.Element {
}
return (
- <div className="funnel-results">
+ <div className="funnel-results" data-testid="funnel-results">
<OverallMetrics />
<FunnelGraph />
<StepsTransitionResults />
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTable.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTable.tsx
index 13f4e1a983..ee4d25b0be 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTable.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTable.tsx
@@ -10,6 +10,7 @@ interface FunnelTableProps {
columns: Array<ColumnProps<any>>;
title: string;
tooltip?: string;
+ testId?: string;
}
function FunnelTable({
@@ -18,9 +19,10 @@ function FunnelTable({
columns = [],
title,
tooltip,
+ testId,
}: FunnelTableProps): JSX.Element {
return (
- <div className="funnel-table">
+ <div className="funnel-table" data-testid={testId}>
<div className="funnel-table__header">
<div className="funnel-table__title">{title}</div>
<div className="funnel-table__actions">
@@ -51,6 +53,7 @@ FunnelTable.defaultProps = {
loading: false,
data: [],
tooltip: '',
+ testId: undefined,
};
export default FunnelTable;
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTopTracesTable.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTopTracesTable.tsx
index 66dff7c7d4..c4c16911c1 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTopTracesTable.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/FunnelTopTracesTable.tsx
@@ -26,6 +26,7 @@ interface FunnelTopTracesTableProps {
Error
>;
steps: FunnelStepData[];
+ testId: string;
}
function FunnelTopTracesTable({
@@ -36,6 +37,7 @@ function FunnelTopTracesTable({
tooltip,
steps,
useQueryHook,
+ testId,
}: FunnelTopTracesTableProps): JSX.Element {
const { startTime, endTime } = useFunnelContext();
const payload = useMemo(
@@ -70,6 +72,7 @@ function FunnelTopTracesTable({
<FunnelTable
title={title}
tooltip={tooltip}
+ testId={testId}
columns={topTracesTableColumns}
data={data}
loading={isLoading || isFetching}
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopSlowestTraces.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopSlowestTraces.tsx
index bfe410d508..c54b04795c 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopSlowestTraces.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopSlowestTraces.tsx
@@ -15,6 +15,7 @@ function TopSlowestTraces(props: TopSlowestTracesProps): JSX.Element {
<FunnelTopTracesTable
{...props}
title="Slowest 5 traces"
+ testId="funnel-slowest-traces"
tooltip="A list of the slowest traces in the funnel"
useQueryHook={useFunnelSlowTraces}
/>
diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopTracesWithErrors.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopTracesWithErrors.tsx
index 166ffeb35f..275a743d78 100644
--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopTracesWithErrors.tsx
+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelResults/TopTracesWithErrors.tsx
@@ -15,6 +15,7 @@ function TopTracesWithErrors(props: TopTracesWithErrorsProps): JSX.Element {
<FunnelTopTracesTable
{...props}
title="Traces with errors"
+ testId="funnel-error-traces"
tooltip="A list of the traces with errors in the funnel"
useQueryHook={useFunnelErrorTraces}
/>
diff --git a/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx b/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx
index b0c03d4929..2711bf6755 100644
--- a/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx
+++ b/frontend/src/pages/TracesFunnels/components/CreateFunnel/CreateFunnel.tsx
@@ -124,7 +124,7 @@ function CreateFunnel({
getContainer={document.getElementById('root') || undefined}
destroyOnClose
>
- <div className="funnel-modal-content">
+ <div className="funnel-modal-content" data-testid="create-funnel-modal">
<span className="funnel-modal-content__label">Enter funnel name</span>
<Input
className={`funnel-modal-content__input${
@@ -133,10 +133,16 @@ function CreateFunnel({
value={funnelName}
onChange={handleInputChange}
placeholder="Eg. checkout dropoff funnel"
+ testId="create-funnel-name-input"
autoFocus
/>
{inputError && (
- <span className="funnel-modal-content__error">{inputError}</span>
+ <span
+ className="funnel-modal-content__error"
+ data-testid="create-funnel-error"
+ >
+ {inputError}
+ </span>
)}
</div>
</SignozModal>
diff --git a/frontend/src/pages/TracesFunnels/components/FunnelsEmptyState/FunnelsEmptyState.tsx b/frontend/src/pages/TracesFunnels/components/FunnelsEmptyState/FunnelsEmptyState.tsx
index 2108211b8d..86dac8b637 100644
--- a/frontend/src/pages/TracesFunnels/components/FunnelsEmptyState/FunnelsEmptyState.tsx
+++ b/frontend/src/pages/TracesFunnels/components/FunnelsEmptyState/FunnelsEmptyState.tsx
@@ -40,6 +40,7 @@ function FunnelsEmptyState({
icon={<Plus size={16} />}
onClick={onCreateFunnel}
className="funnels-empty__new-btn"
+ data-testid="traces-funnels-empty-new-btn"
>
New funnel
</Button>
diff --git a/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelItemPopover.tsx b/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelItemPopover.tsx
index e60a3ffe4a..c6771d255d 100644
--- a/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelItemPopover.tsx
+++ b/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelItemPopover.tsx
@@ -32,6 +32,7 @@ function FunnelItemActions({
type="text"
className="funnel-item__action-btn"
icon={<PencilLine size={14} />}
+ data-testid="funnel-action-rename"
onClick={(): void => {
setIsPopoverOpen(false);
setIsRenameModalOpen(true);
@@ -43,6 +44,7 @@ function FunnelItemActions({
type="text"
className="funnel-item__action-btn funnel-item__action-btn--delete"
icon={<Trash2 size={14} />}
+ data-testid="funnel-action-delete"
onClick={(): void => {
setIsPopoverOpen(false);
setIsDeleteModalOpen(true);
@@ -113,6 +115,8 @@ function FunnelItemPopover({
'funnel-item__action-icon--active': isPopoverOpen,
})}
size={14}
+ data-testid="funnel-actions-trigger"
+ aria-label="Funnel actions"
/>
</Popover>
diff --git a/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx b/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx
index 7b39899be4..9e834e5c9a 100644
--- a/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx
+++ b/frontend/src/pages/TracesFunnels/components/FunnelsList/FunnelsList.tsx
@@ -81,12 +81,17 @@ export function FunnelListItem({
<button
type="button"
className="funnel-item"
+ data-testid={`funnel-item-${funnel.funnel_id}`}
onClick={(): void => onFunnelClick(funnel)}
>
{content}
</button>
) : (
- <AppLink to={funnelDetailsLink} className="funnel-item">
+ <AppLink
+ to={funnelDetailsLink}
+ className="funnel-item"
+ data-testid={`funnel-item-${funnel.funnel_id}`}
+ >
{content}
</AppLink>
);
diff --git a/frontend/src/pages/TracesFunnels/components/RenameFunnel/RenameFunnel.tsx b/frontend/src/pages/TracesFunnels/components/RenameFunnel/RenameFunnel.tsx
index fca4464264..ccdf2a034b 100644
--- a/frontend/src/pages/TracesFunnels/components/RenameFunnel/RenameFunnel.tsx
+++ b/frontend/src/pages/TracesFunnels/components/RenameFunnel/RenameFunnel.tsx
@@ -90,6 +90,7 @@ function RenameFunnel({
<span className="funnel-modal-content__label">Enter a new name</span>
<Input
className="funnel-modal-content__input"
+ testId="rename-funnel-name-input"
value={newFunnelName}
onChange={(e): void => setNewFunnelName(e.target.value)}
autoFocus
diff --git a/frontend/src/pages/TracesFunnels/components/SearchBar/SearchBar.tsx b/frontend/src/pages/TracesFunnels/components/SearchBar/SearchBar.tsx
index 7c89bfc19c..19f491acbf 100644
--- a/frontend/src/pages/TracesFunnels/components/SearchBar/SearchBar.tsx
+++ b/frontend/src/pages/TracesFunnels/components/SearchBar/SearchBar.tsx
@@ -57,13 +57,18 @@ function SearchBar({
placement="bottomRight"
arrow={false}
>
- <Button type="text" className="search__sort-btn">
+ <Button
+ type="text"
+ className="search__sort-btn"
+ data-testid="traces-funnels-sort-btn"
+ >
<ArrowDownWideNarrow size={12} data-testid="sort-by" />
<div className="search__sort-btn-text">Sort</div>
</Button>
</Popover>
<Input
className="search__input"
+ testId="traces-funnels-search"
placeholder="Search by name, description, or tags..."
prefix={
<Search
@@ -86,6 +91,7 @@ function SearchBar({
type="primary"
icon={<Plus size={16} />}
className="search__new-btn"
+ data-testid="traces-funnels-new-btn"
onClick={onCreateFunnel}
disabled={!hasEditPermission}
>
diff --git a/frontend/src/periscope/components/PrettyView/PrettyView.tsx b/frontend/src/periscope/components/PrettyView/PrettyView.tsx
index fbcd1b4f9b..bb10bdae63 100644
--- a/frontend/src/periscope/components/PrettyView/PrettyView.tsx
+++ b/frontend/src/periscope/components/PrettyView/PrettyView.tsx
@@ -244,7 +244,13 @@ function PrettyView({
align="start"
side="bottom"
>
- <span className="pretty-view__actions" role="button" tabIndex={0}>
+ <span
+ className="pretty-view__actions"
+ role="button"
+ tabIndex={0}
+ aria-label={`Actions for ${fieldKey}`}
+ data-testid={`pretty-view-actions-${fieldKey}`}
+ >
<Ellipsis size={12} />
</span>
</Dropdown>
diff --git a/frontend/src/providers/App/App.tsx b/frontend/src/providers/App/App.tsx
index 28ba2c043c..05adb758ab 100644
--- a/frontend/src/providers/App/App.tsx
+++ b/frontend/src/providers/App/App.tsx
@@ -300,22 +300,32 @@ export function AppProvider({ children }: PropsWithChildren): JSX.Element {
}, [orgPreferencesData, isFetchingOrgPreferences]);
// now since org preferences data is dependent on user being loaded as well so we added extra safety net for user.email to be set as well
- const { data: userPreferencesData, isFetching: isFetchingUserPreferences } =
- useQuery({
- queryFn: () => listUserPreferences(),
- queryKey: ['getAllUserPreferences', 'app-context'],
- enabled: !!isLoggedIn && !!user.email,
- });
+ const {
+ data: userPreferencesData,
+ isFetching: isFetchingUserPreferencesQuery,
+ isIdle: isUserPreferencesQueryIdle,
+ } = useQuery({
+ queryFn: () => listUserPreferences(),
+ queryKey: ['getAllUserPreferences', 'app-context'],
+ enabled: !!isLoggedIn && !!user.email,
+ });
useEffect(() => {
if (
userPreferencesData &&
userPreferencesData.data &&
- !isFetchingUserPreferences
+ !isFetchingUserPreferencesQuery
) {
setUserPreferences(userPreferencesData.data);
}
- }, [userPreferencesData, isFetchingUserPreferences, isLoggedIn]);
+ }, [userPreferencesData, isFetchingUserPreferencesQuery, isLoggedIn]);
+
+ // Idle means waiting for `user.email`, unless `/users/me` failed and it never
+ // arrives.
+ const isFetchingUserPreferences =
+ isFetchingUserPreferencesQuery ||
+ (isUserPreferencesQueryIdle && !userFetchError) ||
+ (!!userPreferencesData?.data && userPreferences === null);
function updateUser(user: IUser): void {
setDefaultUser((prev) => ({
diff --git a/frontend/src/providers/App/__tests__/App.test.tsx b/frontend/src/providers/App/__tests__/App.test.tsx
index de3fcacf85..d68fdb0caa 100644
--- a/frontend/src/providers/App/__tests__/App.test.tsx
+++ b/frontend/src/providers/App/__tests__/App.test.tsx
@@ -297,6 +297,103 @@ describe('AppProvider user and org data from v2 APIs', () => {
});
});
+describe('AppProvider user preferences loading state', () => {
+ beforeEach(() => {
+ queryClient.clear();
+ setLocalStorageApi(LOCALSTORAGE.IS_LOGGED_IN, 'true');
+ });
+
+ it('keeps isFetchingUserPreferences true until the preferences are in context', async () => {
+ server.use(
+ rest.get(MY_USER_URL, (_, res, ctx) =>
+ res(ctx.status(200), ctx.json({ data: { id: 'u-1', email: '[email protected]' } })),
+ ),
+ rest.get(MY_ORG_URL, (_, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({ data: { id: 'org-1', displayName: 'Org' } }),
+ ),
+ ),
+ rest.get('http://localhost/api/v1/user/preferences', (_, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({
+ data: [
+ {
+ name: 'nav_shortcuts',
+ description: '',
+ valueType: 'array',
+ defaultValue: [],
+ allowedValues: [],
+ allowedScopes: ['user'],
+ value: ['alerts'],
+ },
+ ],
+ }),
+ ),
+ ),
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [false, false, false])),
+ );
+ }),
+ );
+
+ const snapshots: { fetching: boolean; loaded: boolean }[] = [];
+ const { result } = renderHook(
+ () => {
+ const ctx = useAppContext();
+ snapshots.push({
+ fetching: ctx.isFetchingUserPreferences,
+ loaded: ctx.userPreferences !== null,
+ });
+ return ctx;
+ },
+ { wrapper: createWrapper() },
+ );
+
+ await waitFor(
+ () => {
+ expect(result.current.isFetchingUserPreferences).toBe(false);
+ },
+ { timeout: 3000 },
+ );
+
+ expect(result.current.userPreferences).toHaveLength(1);
+ expect(snapshots.filter((s) => !s.fetching && !s.loaded)).toHaveLength(0);
+ });
+
+ it('stops waiting for user preferences when /users/me fails', async () => {
+ server.use(
+ rest.get(MY_USER_URL, (_, res, ctx) =>
+ res(ctx.status(500), ctx.json({ error: 'Internal Server Error' })),
+ ),
+ rest.post(AUTHZ_CHECK_URL, async (req, res, ctx) => {
+ const payload = await req.json();
+ return res(
+ ctx.status(200),
+ ctx.json(authzMockResponse(payload, [false, false, false])),
+ );
+ }),
+ );
+
+ const { result } = renderHook(() => useAppContext(), {
+ wrapper: createWrapper(),
+ });
+
+ await waitFor(
+ () => {
+ expect(result.current.userFetchError).toBeTruthy();
+ },
+ { timeout: 3000 },
+ );
+ expect(result.current.isFetchingUserPreferences).toBe(false);
+ expect(result.current.userPreferences).toBeNull();
+ });
+});
+
describe('AppProvider when authz/check fails', () => {
beforeEach(() => {
queryClient.clear();
diff --git a/tests/e2e/AGENTS.md b/tests/e2e/AGENTS.md
new file mode 100644
index 0000000000..640a31f075
--- /dev/null
+++ b/tests/e2e/AGENTS.md
@@ -0,0 +1,171 @@
+# Working in `tests/e2e`
+
+Read this before adding or changing a spec.
+
+## The five standards
+
+| # | Standard |
+|---|---|
+| S1 | **Prose lives in docs.** A comment states a non-obvious constraint in a line or two. Measurements, incident history and "why this timeout" go to [`docs/flake-notes.md`](docs/flake-notes.md). |
+| S2 | **Generated code is marked generated.** Transcribed data lives under a `__generated__/` path, carries a header saying how to regenerate it, and has something that re-derives it at runtime. |
+| S3 | **One driver per feature.** A spec imports exactly one module: its feature's `test`. No feature helper takes a `page`. |
+| S4 | **Cheapest layer that can catch it.** Four layers, in cost order: jest → Storybook + msw → pytest integration → Playwright. |
+| S5 | **The API contract comes from the spec.** No hand-written response type for an endpoint `docs/api/openapi.yml` already describes. |
+
+## S4, in practice — check before you write
+
+Before writing a scenario, work out which layer already covers it. In order:
+
+1. **Is it a pure function, a reducer, a config literal or a component's own
+ behaviour?** Then it is jest. Grep `frontend/src/**/__tests__/` for the
+ container first — most of them are covered far better than a browser could.
+2. **Is it a rendered state that needs no backend** (empty, error, loading)?
+ Storybook with msw, or jest with a fixed mock.
+3. **Is it something the API does** — ordering, pagination, filter semantics,
+ validation, roll-ups, "does this endpoint 500"? **Grep `tests/integration/`.**
+ For infra monitoring and for alert evaluation the answer is almost always
+ that it is already covered, per entity, headless.
+4. **Only then**: does a real response have to reach a real DOM? That is an E2E.
+
+Two directions worth knowing:
+
+- **Infra monitoring**: `tests/integration/tests/inframonitoring/` is 123 test
+ functions over 101 fixtures, driving the same list endpoints the UI calls. The
+ E2E suite drives **one** entity; the other nine are covered by that suite plus
+ `frontend/src/container/InfraMonitoringK8sV2/__tests__/entityConfig.test.ts`.
+- **Alerts**: the integration suite owns **evaluation and delivery** — it seeds
+ metrics, loads a rule, waits for the ruler and checks the webhook. Never
+ assert firing behaviour in Playwright. The E2E suite asserts what the form
+ offers and what a save persists.
+
+## Layout
+
+```
+tests/e2e/
+├── drivers/ # the kit and one module per feature
+│ ├── kit.ts # driver(), seeded(), allowFor(), the root `test`
+│ ├── auth.ts # login, per-worker storageState
+│ ├── api.ts # the authed HTTP client, seeder URL
+│ ├── console.ts # console/network watch
+│ ├── storage.ts # localStorage helpers
+│ ├── tanstack.ts # the shared table driver
+│ ├── querysearch.ts # the expression editor and its URL param
+│ ├── antd.ts # antd select primitives
+│ ├── alerts/ # feature driver + seeds + generated payloads
+│ └── infra/ # feature driver + seeds + __generated__/datasets.ts
+├── tests/<feature>/ # specs, one directory per feature
+├── testdata/ # static fixtures (marked generated)
+├── bootstrap/ # pytest lifecycle, global setup and teardown
+└── docs/flake-notes.md
+```
+
+## Writing a spec
+
+```ts
+import { expect, test } from '../../drivers/alerts';
+
+test('TC-01 …', async ({ alerts, alertList }) => {
+ await alerts.list.goto({ search: alertList.namePrefix });
+ await expect(alerts.list.rows()).toHaveCount(10);
+});
+```
+
+- One import. Take `authedPage` only for navigation, `goBack`,
+ `waitForResponse` or a second tab. A `page.locator(...)` in a spec body is a
+ driver method that is missing.
+- Titles are `TC-NN <description>`.
+- Each spec seeds its own data and cleans up. The bootstrap stack starts empty.
+- Never assert "the table has exactly N rows" on an unscoped list: seeding is
+ additive and six workers share one stack. Scope by a name you seeded.
+- Names carry the worker index (`e2e-alert-list-w${workerIndex}-${Date.now()}`),
+ so workers and repeat runs never collide.
+- A write path attaches `waitForResponse` before the click, then reloads and
+ re-reads from the server instead of trusting the optimistic update.
+- A failing assertion gets a verdict with evidence: product bug or test bug.
+ Never weaken it. A spec that cannot be made deterministic moves down a layer,
+ or becomes `test.fixme` with the diagnosis in it.
+- Green locally, red on CI? Run `STRESS=1 CI=1 pnpm test <path>` before filing
+ a product bug.
+
+## Seeding
+
+| Scope | For | How |
+|---|---|---|
+| test | anything the test mutates | a test-scoped layer (`ownedRules`), or `try / finally` through the driver |
+| worker | read-only data | `seeded()` |
+| suite | a dataset only one file uses | `test.beforeAll` with `onAdminPage(browser, …)`, since `authedPage` is test-scoped |
+
+Seeding reaches the backend one way: `apiDriver(page)` for control-plane
+objects, the seeder for telemetry. The JWT lives in `localStorage`, so never
+improvise with `page.request.*`.
+
+| Data | Source |
+|---|---|
+| Alerts, dashboards, channels, views | created through the API by the spec, which picks the names |
+| Traces, logs | a payload under `testdata/`, POSTed to the seeder |
+| Infra monitoring metrics | the integration suite's fixtures, read by `seedDataset` (`drivers/infra/seed.ts`), never copied |
+
+Assert on what `seedDataset` returned, never on names you typed.
+
+## Adding a driver
+
+A driver is a function that closes over the page and returns an object of
+methods. Bind it into a layer with `driver()`, and compose the layers into the
+feature's `test`:
+
+```ts
+export const withThing = driver('thing', ({ page }) => thingDriver(page));
+export const test = withThing(withTanstack(kit));
+```
+
+Worker-scoped seeds use `seeded()`, which runs on a throwaway admin page and
+tears down after. Drivers reuse each other by calling the factory directly,
+never by reaching for another fixture.
+
+- A method is navigation or a locator, never a scenario. A method that exists
+ for one spec belongs in that spec; a flag that switches behaviour is two
+ methods.
+- Locate by testid. A missing one is added to the product in the same change.
+ Role, label and CSS lookups are converted as you touch them; antd internals
+ (`antd.ts`) are the exception.
+- Never `test.slow()` in a driver: it triples the remaining budget on every
+ call and compounds in loops. Use `allowFor(floor)`. Budgets and their
+ measurements are in [`docs/flake-notes.md`](docs/flake-notes.md).
+
+## Moving a test down a layer
+
+Move it, do not delete it. The PR names the replacement for every browser test
+it removes, by file and title:
+
+```markdown
+Moved to jest:
+- search debounce → ListAlertRules/__tests__/search.test.tsx, "debounces to one request"
+```
+
+"It's covered in jest" names nothing a reviewer can check. If nothing replaces
+it, the PR says so and why.
+
+## Commits
+
+Keep driver changes apart from everything else, so the history reads one
+concern per commit:
+
+1. `drivers/**` on its own. `.gitattributes` marks it generated, so it
+ collapses in review and is read once.
+2. Product changes the suite needs (testids) in their own commit.
+3. Tests moved down a layer, per area.
+4. Specs, one commit per area.
+
+A new driver method goes in the driver commit even when one spec prompted it.
+Every commit passes `pnpm typecheck` on its own, and the tip passes
+`pnpm fmt:check` and `pnpm lint`.
+
+## AI-maintained paths
+
+- `drivers/infra/__generated__/datasets.ts` — transcribed facts about the
+ integration suite's `.jsonl` fixtures. `assertDatasetFacts` re-derives every
+ value at seed time, so a stale entry fails loudly.
+- `testdata/**` — golden payloads. Marked `linguist-generated` in
+ `.gitattributes`; review the thing that produces them, not the diff.
+
+Do not hand-edit either without also updating what re-derives it.
diff --git a/tests/e2e/bootstrap/conftest.py b/tests/e2e/bootstrap/conftest.py
index ce361b222d..8759a3108b 100644
--- a/tests/e2e/bootstrap/conftest.py
+++ b/tests/e2e/bootstrap/conftest.py
@@ -16,8 +16,12 @@ def base_path() -> str:
def e2e_env() -> dict:
"""Environment every e2e SigNoz gets. Each Playwright worker logs in once,
and the default cap of 5 sessions per user evicts the oldest, which turns a
- worker's requests into 401s mid-run."""
- return {"SIGNOZ_TOKENIZER_OPAQUE_TOKEN_MAX__PER__USER": 100}
+ worker's requests into 401s mid-run. Metrics reduction is off by default in
+ pkg/flagger/registry.go and the Volume Control specs need it."""
+ return {
+ "SIGNOZ_TOKENIZER_OPAQUE_TOKEN_MAX__PER__USER": 100,
+ "SIGNOZ_FLAGGER_CONFIG_BOOLEAN_ENABLE__METRICS__REDUCTION": True,
+ }
@pytest.fixture(name="signoz", scope="package")
diff --git a/tests/e2e/bootstrap/global.setup.ts b/tests/e2e/bootstrap/global.setup.ts
index 6bcf9d903e..e9176ae9f3 100644
--- a/tests/e2e/bootstrap/global.setup.ts
+++ b/tests/e2e/bootstrap/global.setup.ts
@@ -3,6 +3,7 @@ import { expect, test as setup } from '@playwright/test';
const seederUrl = process.env.SIGNOZ_E2E_SEEDER_URL ?? '';
setup('refresh golden dataset', async ({ request }) => {
+ setup.setTimeout(150_000);
expect(seederUrl, 'SIGNOZ_E2E_SEEDER_URL not set').not.toBe('');
const response = await request.post(`${seederUrl}/seed/golden`, {
timeout: 120_000,
diff --git a/tests/e2e/docs/flake-notes.md b/tests/e2e/docs/flake-notes.md
new file mode 100644
index 0000000000..d142230255
--- /dev/null
+++ b/tests/e2e/docs/flake-notes.md
@@ -0,0 +1,261 @@
+# Flake notes
+
+Measurements and budgets that would otherwise live as essays in the code. Add to
+this file rather than to a comment.
+
+## Workers are capped at 6
+
+Playwright's local default is `cpus / 2`, which on a 32-core box is 16 — and 16
+is strictly worse than 6 here, because every worker's browser shares one SigNoz
+container.
+
+Measured on `tests/alerts/{create,edit}` at `--repeat-each=3` (224 tests):
+
+| Workers | Wall clock | Failures |
+|---|---|---|
+| 16 | 128 s | 3 |
+| 6 | 119 s | 0 |
+
+Past about six, the extra workers only add queueing, which shows up as 4-6 s app
+mounts and save requests that outlive the test timeout — i.e. as flakes that look
+like product bugs. The config caps rather than fixes the number, so a four-core
+laptop still gets `cpus / 2`.
+
+## `toPass` needs its own budget
+
+`expect(...).toPass()` reads `expect.toPass.timeout`, **not** `expect.timeout`.
+Without one it defaults to 0, which means "run to the test deadline" — and a
+retry budget equal to the test timeout reports as a bare "Test timeout exceeded"
+with no failing assertion and no steps, which is the least debuggable failure
+Playwright can emit. Keep it strictly under `timeout`.
+
+## Never `test.slow()` inside a helper
+
+`test.slow()` multiplies the remaining budget by three on *every* call, so a
+driver method that carries it and is called in a loop compounds: ten columns at
+30 s × 3¹⁰ is about seven days. A test that never times out is strictly worse
+than one that fails fast, because it wedges a worker until the whole run is
+killed.
+
+`allowFor(floor)` in `drivers/kit.ts` is absolute and monotonic instead: it
+raises the budget to `floor` and never lowers it, so repeated calls and a spec's
+own `setTimeout` settle on the largest value.
+
+## Seeded data needs 30 s, not 15
+
+A row appearing is not a render race but an *ingestion* one: the seeder's insert
+has to become queryable in ClickHouse, and with six workers seeding at once that
+regularly takes longer than the 15 s default expect budget. Failing at 15 s
+produces "row not visible" on data that arrives a second later, which reads as
+product flake and is not. `SEEDED_DATA_TIMEOUT` is 30 s and
+`SEEDED_TEST_BUDGET` is 90 s.
+
+## The seeder collides under parallel load
+
+The seeder container shares one ClickHouse client, so concurrent POSTs from
+parallel workers return a transient `500 concurrent queries within the same
+session`. Both seeders retry that specific error with backoff and fail on
+anything else.
+
+With four workers seeding at once, `postToSeeder`'s old budget (6 attempts,
+150 ms linear backoff, about 2 s in total) ran out on the traces explorer,
+funnels and messaging-queue seeds. It is now 8 attempts at 500 ms (about 14 s).
+The real fix is a lock or a client per request in `tests/seeder/server.py`.
+
+## antd virtualises long dropdowns
+
+A select over a global list — notification channels, for one — renders about ten
+options into the DOM regardless of how many exist. Clicking an option by name
+without typing a filter first is not a slow path, it is a missing element, and it
+fails as a plain click timeout that reads like a renamed testid. Every driver
+that picks from one of these searches first; see `antd.pickByName`.
+
+## The `STRESS` throttle
+
+`STRESS=1` enables 4× CPU throttling on the authenticated page, which reproduces
+GitHub-runner conditions on a developer machine. Pair it with `CI=1` for the
+two-worker, two-retry configuration. `STRESS_CPU_RATE` overrides the multiplier.
+
+## Volume control needs a stack flag
+
+`enable_metrics_reduction` is off by default, and without it the Volume Control
+tab renders its "unavailable" state. `e2e_env` in `bootstrap/conftest.py` sets
+`SIGNOZ_FLAGGER_CONFIG_BOOLEAN_ENABLE__METRICS__REDUCTION`, the same override
+`tests/integration/tests/metricreduction/conftest.py` uses. A stack started
+before the flag needs `--reuse --rebuild` to pick it up. `volume-control.spec.ts` still reads `/api/v1/features` and skips
+when the flag is off, so an older stack skips instead of failing.
+
+## Live tail pause needs a fixed wait
+
+`tests/logs-explorer/live-tail.spec.ts` TC-02 proves a paused stream delivers
+nothing, and absence has no DOM signal. The backend polls ClickHouse every 5 s
+(`liveDataRefresh`), so the spec holds for 7 s (one tick plus slack) through
+`live.expectAbsentFor` before resuming.
+
+Resume opens a new stream whose window starts at the moment it connects, so a
+row seeded while paused is stamped 60 s ahead. Stamped at "now" it would sit
+before the new window and never arrive.
+
+## The golden seed outlives the default test budget
+
+`/seed/golden` took 27 s on the TrueNAS VM, against a 30 s local test timeout.
+The setup test's budget sits above its own 120 s request timeout, so a slow seed
+fails on the request and says so.
+
+## The alert history editor can rotate typed text
+
+`alerts.history.typeFilter` types into the CodeMirror editor right after the
+page mounts. A keystroke that lands while the editor is still syncing its
+initial value moves the cursor, so `nonexistent.key = 'x'` came out as
+`onexistent.key = 'x'n` and the filter request never matched. The driver now
+retypes until the editor holds the exact expression.
+
+## Manage Shortcuts rows move while the modal zooms in
+
+The antd modal is visible before its zoom-in ends. `shell.nav.dragShortcut`
+measured the rows mid animation, so the drop missed and the saved order came
+back unchanged. `openManageShortcuts` now waits for the zoom classes to clear,
+and the drag nudges the pointer first so dnd-kit activates on the source row.
+
+## The traces explorer editor moves once after mount
+
+`QuickFiltersLayout` wraps the explorer in an `OverlayScrollbar` with `defer`,
+so it initialises on idle and re-parents the content pane, query editor
+included. Focus is restored but the caret lands at 0, so a key typed before
+that moment ends up last: `service.name = 'x'` became `ervice.name = 'x's`.
+`tracesExplorerDriver.goto` waits for `[data-overlayscrollbars-viewport]` in
+the content pane before returning. The caret jump also hits a real user who
+types within the first second; it came with #12915, not PR #12971.
+
+The logs explorer, which `query-builder/token-highlight.spec.ts` types into,
+uses the same layout: `k8s.namespace.name` came out as `8s.namespace.namek`.
+`querySearch.apply` and `editor.type` retype until the editor holds exactly
+the expression, and the colour checks use `toHaveCSS`, which retries, instead
+of a fixed wait for the highlighter.
+
+## Typing an expression logs parser errors
+
+`parser/analyzeQuery.ts` builds an ANTLR parser without removing the default
+console listener, so every incomplete prefix of a typed expression logs
+`line 1:N missing ...` as a console error. Specs that type and then assert a
+clean console filter those lines (`withoutParserNoise`).
+
+## Seeded spans fill the APM materialized views
+
+On the bootstrap stack, `top_level_operations` (services detail TC-05) and
+`dependency_graph_minutes_v2` (service map TC-01) fill from spans the seeder
+inserts into `signoz_index_v3`, within the 90 s seeded budget. Both specs
+passed in the full run and in isolation; no seeder route is needed.
+
+## Celery state tabs read one minute bucket
+
+The celery state tabs reduce a 60 s series to its last point, so a count only
+matches the seed when every task span lands in the same minute. The seed puts
+all four in the last complete minute.
+
+## Home checklist steps complete without a loading marker
+
+Logs, traces, alerts, dashboards and saved-views steps flip to completed as
+their widget queries resolve, and the checklist has no loading state for that.
+`home.skippableSteps` polls until the list is unchanged for one second before
+choosing a step. On a fully seeded stack every step completes and TC-03 skips.
+
+## The explorer's floating view bar sits under the filters pane
+
+At the 1280px viewport the bottom view bar (`explorer-views-select`, update and clear buttons) is centred on the page and partly covered by the 280px `z-index: 2` filters aside, which is also on main. Playwright's hit test fails, so the saved-views driver clicks the select near its right edge and uses `dispatchEvent('click')` for update and clear.
+
+## The AWS account settings drawer footer sits below the viewport
+
+At 1280x720 the region grid pushes the "Update Changes" footer to y=746, and the drawer content does not scroll, so Playwright reports "element is outside of the viewport". `aws.updateRegions` uses `dispatchEvent('click')` on `aws-update-account-btn`. The dialog CSS is identical in `@signozhq/ui` 0.1.0 and 0.2.0-rc.1.
+
+## The alert history filter editor auto-closes quotes and shows its placeholder as text
+
+`typeFilter` accepts one trailing auto-closed quote or bracket, and checks `.cm-placeholder` instead of empty text when clearing, because the placeholder is part of the editor's `textContent`.
+
+## The funnel save request carries 200ms-old steps
+
+The Save button enables on live `steps`, but the PUT body is built from `useDebounce(steps, 200)`. Saving right after the last select sends the previous value (an empty span name, a 400). The driver waits for the `FUNNEL_STEPS_<id>` draft, which the app writes from the same debounced value, to hold complete steps before clicking.
+
+## The home checklist background covers the skip button
+
+At 1280px the decorative `checklist-img-bg` sits over "Skip for now" and
+intercepts pointer events, so a coordinate click never reaches the button. The
+driver dispatches the click on the node instead.
+
+## Home checklist skip, sidebar pin reload, volume-control label picker
+
+`home.skip` does not hover: the item re-renders as sibling specs churn the data, so hover never saw it stable. The skip button is always in the DOM and disabled while the widget refetches, so the click retries until the item shows `skipped`. `nav.toggleWithShortcut` waits for the `sidenav_pinned` PUT and `nav.reloadSettled` for the preferences list, because the list overrides the cached pin and a toggle pressed before it lands is reverted. The volume-control label picker waits out `ant-select-loading` before typing, because the options arrive after the attribute keys query.
+
+## Sign-out races requests still in flight
+
+`DeleteToken` in `pkg/tokenizer/opaquetokenizer/provider.go` drops the cache entry
+before the database row, and `getOrGetSetToken` re-caches whatever it read for
+`Lifetime.Max`, 30 days. A request on the token that looks it up between the two
+writes puts it back, and the revoked token keeps answering 200. That is a product
+bug, and a browser cannot keep the page's own requests out of the window: with a
+`networkidle` wait before the click (which resolves at once on a page that was
+already idle), `auth/login` TC-05 still failed one full pass in two. TC-05 now
+asserts the UI side, and `passwordauthn/09_tokenizer.py::test_logout_revokes_token`
+checks revocation with nothing else in flight.
+
+## Viewer specs and long forms get 60 s
+
+`test.use({ as: 'viewer' })` provisions the user through the admin API and logs
+it in on the first test of each worker, on top of the admin login that seeds.
+Measured on a loaded shared stack, `dashboards/permissions` ran 41-47 s and the
+planned-downtime and routing-policy forms 27-34 s, against the 30 s default.
+Those describes set `timeout: 60_000`; the list suite does too, since its
+create-through-the-modal case measured 29-33 s.
+
+## A run with the setup project wipes everyone's telemetry
+
+`bootstrap/global.teardown.ts` deletes every seeded trace, log and metric. Two
+runs against one stack, one with deps and one with `--no-deps`, therefore race:
+the second run's seeded traces vanish mid-test and the trace page lands on
+NoData. When several people share a stack, run with `--no-deps`.
+
+## querysearch.apply retypes, volume-control reseeds
+
+`apply` retypes inside `toPass` until the editor text equals the expression, because the caret can jump after mount and rotate typed characters (`8s.pod.name...k`). The Volume Control tab ignores the URL range and uses 15m, so the label-picker spec reseeds the gauge right before opening the tab; the worker seed can be older than 15m under load.
+
+## The Apdex panel's metadata 500 lands after the panels render
+
+The service Overview's Apdex card mounts once its settings load, and only then
+asks `/metric/metric_metadata` for `signoz_latency.bucket`. The stack never
+ingests that metric and the endpoint answers 500 rather than 404, so whether a
+spec saw the error depended on whether the response beat its last assertion. In
+three full passes at four workers, `services/list` TC-02 failed all three and
+`app-shell/routes` TC-03 two. They now drop that one URL (`withoutMissingMetadata`,
+`allowFailures`), which the console watcher can match because a failed load's
+entry ends with its URL. The axios error the DB Call and External tabs log for it
+names no URL, so `withoutMissingMetadata` drops it only once the 500 was seen.
+
+`app-shell/routes` TC-19 has the same shape: the AI observability overview's
+dashboard toolbar asks for the public meta and an authz check under the
+synthetic id `useSystemDashboard` assigns, both answer 400, and the probe failed
+one pass in three.
+
+## Traces never finish writing under Node 26
+
+With Playwright 1.57 on Node 26, a failing test with tracing on also reports
+"Test timeout exceeded" and leaves a truncated `trace.zip`; the same probe on
+Node 24 writes the trace in a second. CI runs `lts/*`. Run the suite locally on
+Node 24 (`mise exec node@24 -- …`) when you need traces.
+
+## A lost click never opens its tab
+
+`infra-monitoring/drawer` TC-07 ctrl-clicks a pod row and waits for the new tab.
+In one full pass the click landed on the row and no tab opened, and the bare
+`waitForEvent('page')` held the test to its 90 s budget. `clickForNewTab` in the
+infra driver bounds the click and the wait, and clicks again only while no tab
+has arrived, the same way `drawer.open` retries a swallowed click.
+
+## The evaluation window popover ignores Escape
+
+`alerts/create` TC-08 timed out in one full pass and in two of five repeats. The
+evaluation settings popover is an antd `Popover` with `trigger="click"`, and
+neither antd 5.11 nor `@rc-component/trigger` closes it on Escape, so
+`selectEvaluationTimeframe` left it open. The next click outside usually closed
+it, but when the popover covered the Advanced Options header, that click waited
+on "intercepts pointer events" for the rest of the budget. The driver now closes
+the popover through its trigger and waits for it to go.
diff --git a/tests/e2e/drivers/alerts/configuration.ts b/tests/e2e/drivers/alerts/configuration.ts
new file mode 100644
index 0000000000..da1f8b81af
--- /dev/null
+++ b/tests/e2e/drivers/alerts/configuration.ts
@@ -0,0 +1,300 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { apiDriver } from '../api';
+
+import { ALERTS_LIST_PATH } from './constants';
+
+/**
+ * The Alerts page's Configuration tab: planned downtime and routing policies.
+ * Both lists are TanStack tables filtered by a client-side search; both forms
+ * are antd modals with almost no testids, so their locators go through a role,
+ * a placeholder or the modal's own class.
+ */
+
+/** The slice of `GET /api/v1/downtime_schedules` the specs assert on. */
+export interface StoredDowntime {
+ id: string;
+ name: string;
+ alertIds: string[] | null;
+ scope?: string;
+ schedule: { timezone: string; startTime: string; endTime?: string };
+}
+
+export interface StoredRoutingPolicy {
+ id: string;
+ name: string;
+ expression: string;
+ channels: string[];
+ description?: string;
+}
+
+export interface PlannedDowntime {
+ goto(): Promise<void>;
+ newButton(): Locator;
+ form(): Locator;
+ fillName(name: string): Promise<void>;
+ /** Pick a day in the Starts from / Ends on picker, at the picker's default time. */
+ pickDate(field: 'Starts from' | 'Ends on', day: Date): Promise<void>;
+ pickTimezone(timezone: string): Promise<void>;
+ scope(value: 'All alert rules' | 'Specific alert rules'): Locator;
+ rulePicker(): Locator;
+ pickRule(name: string): Promise<void>;
+ /** The chip for a picked rule. Labels past 20 characters are truncated. */
+ pickedRule(name: string): Locator;
+ save(): Promise<void>;
+ /** Filter the table by name, so the row is on the first page whatever else is stored. */
+ search(name: string): Promise<void>;
+ row(name: string): Locator;
+ remove(name: string): Promise<void>;
+ list(): Promise<StoredDowntime[]>;
+ byName(name: string): Promise<StoredDowntime | undefined>;
+ tryDelete(name: string): Promise<void>;
+}
+
+export interface RoutingPolicies {
+ goto(): Promise<void>;
+ newButton(): Locator;
+ /** Hover the create button and return the tooltip it shows. */
+ newButtonTooltip(): Promise<Locator>;
+ fill(policy: {
+ name?: string;
+ description?: string;
+ expression?: string;
+ channel?: string;
+ }): Promise<void>;
+ save(): Promise<void>;
+ /** Filter the table by name, so the row is on the first page whatever else is stored. */
+ search(name: string): Promise<void>;
+ row(name: string): Locator;
+ edit(name: string): Promise<void>;
+ remove(name: string): Promise<void>;
+ byName(name: string): Promise<StoredRoutingPolicy | undefined>;
+ tryDelete(name: string): Promise<void>;
+}
+
+const dayTitle = (day: Date): string =>
+ [
+ day.getFullYear(),
+ String(day.getMonth() + 1).padStart(2, '0'),
+ String(day.getDate()).padStart(2, '0'),
+ ].join('-');
+
+export function plannedDowntimeDriver(page: Page): PlannedDowntime {
+ const api = apiDriver(page);
+ const form = (): Locator => page.locator('.createDowntimeModal');
+ const openPicker = (): Locator =>
+ page.locator('.datePicker:not(.ant-picker-dropdown-hidden)');
+
+ const downtime: PlannedDowntime = {
+ goto: async () => {
+ await page.goto(
+ `${ALERTS_LIST_PATH}?tab=Configuration&subTab=planned-downtime`,
+ );
+ await expect(downtime.newButton()).toBeVisible();
+ },
+
+ newButton: () => page.getByTestId('planned-downtime-create'),
+ form,
+
+ fillName: async (name) => {
+ await form().getByRole('textbox', { name: 'Name' }).fill(name);
+ },
+
+ pickDate: async (field, day) => {
+ await form().getByRole('textbox', { name: field }).click();
+ const picker = openPicker();
+ await picker.locator(`td[title="${dayTitle(day)}"]`).click();
+ await picker.getByRole('button', { name: 'OK' }).click();
+ await expect(picker).toHaveCount(0);
+ },
+
+ pickTimezone: async (timezone) => {
+ const select = form().getByRole('combobox', { name: 'Timezone' });
+ await select.fill(timezone);
+ await page
+ .locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden)')
+ .locator('.ant-select-item-option')
+ .filter({ hasText: new RegExp(`^${timezone}$`) })
+ .first()
+ .click();
+ },
+
+ scope: (value) => form().getByRole('radio', { name: value }),
+
+ rulePicker: () =>
+ form().locator('.ant-select').filter({ hasText: 'Search for alert rules' }),
+
+ pickRule: async (name) => {
+ const select = downtime.rulePicker();
+ await select.click();
+ await select.locator('input[role="combobox"]').fill(name);
+ await page
+ .locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden)')
+ .locator('.ant-select-item-option')
+ .filter({ hasText: name })
+ .first()
+ .click();
+ await page.keyboard.press('Escape');
+ },
+
+ pickedRule: (name) =>
+ form().locator('.alert-rule-tags').getByText(name, { exact: true }),
+
+ save: async () => {
+ await form().getByRole('button', { name: 'Add downtime schedule' }).click();
+ await expect(form()).toHaveCount(0);
+ },
+
+ search: async (name) => {
+ await page.getByTestId('planned-downtime-search').fill(name);
+ },
+
+ row: (name) => page.locator('tbody tr').filter({ hasText: name }),
+
+ remove: async (name) => {
+ await downtime.search(name);
+ await downtime
+ .row(name)
+ .getByRole('button', { name: `Actions for ${name}` })
+ .click();
+ await page.getByRole('menuitem', { name: 'Delete' }).click();
+ await page.getByRole('button', { name: 'Delete Schedule' }).click();
+ await expect(downtime.row(name)).toHaveCount(0);
+ },
+
+ list: async () =>
+ (
+ await api.get<{ data: StoredDowntime[] | null }>(
+ '/api/v1/downtime_schedules',
+ )
+ ).data ?? [],
+
+ byName: async (name) =>
+ (await downtime.list()).find((entry) => entry.name === name),
+
+ // A schedule still naming rules refuses deletion with a 409, and those
+ // rules refuse it in turn, so detach them first.
+ tryDelete: async (name) => {
+ const found = await downtime.byName(name).catch(() => undefined);
+ if (!found) {
+ return;
+ }
+ if ((found.alertIds ?? []).length > 0) {
+ await api
+ .put(`/api/v1/downtime_schedules/${found.id}`, {
+ name: found.name,
+ alertIds: [],
+ schedule: found.schedule,
+ scope: found.scope ?? '',
+ })
+ .catch(() => undefined);
+ }
+ await api.tryDel(`/api/v1/downtime_schedules/${found.id}`);
+ },
+ };
+
+ return downtime;
+}
+
+export function routingPoliciesDriver(page: Page): RoutingPolicies {
+ const api = apiDriver(page);
+ const modal = (): Locator => page.locator('.create-policy-modal');
+
+ const byName = async (
+ name: string,
+ ): Promise<StoredRoutingPolicy | undefined> =>
+ (
+ (
+ await api.get<{ data: StoredRoutingPolicy[] | null }>(
+ '/api/v1/route_policies',
+ )
+ ).data ?? []
+ ).find((entry) => entry.name === name);
+
+ const routing: RoutingPolicies = {
+ goto: async () => {
+ await page.goto(
+ `${ALERTS_LIST_PATH}?tab=Configuration&subTab=routing-policies`,
+ );
+ await expect(routing.newButton()).toBeVisible();
+ },
+
+ newButton: () => page.getByTestId('routing-policies-create'),
+
+ newButtonTooltip: async () => {
+ await routing.newButton().hover();
+ return page.getByRole('tooltip');
+ },
+
+ fill: async ({ name, description, expression, channel }) => {
+ if (name !== undefined) {
+ await modal().getByPlaceholder('e.g. Base routing policy...').fill(name);
+ }
+ if (description !== undefined) {
+ await modal()
+ .getByPlaceholder('e.g. This is a routing policy that...')
+ .fill(description);
+ }
+ if (expression !== undefined) {
+ await modal()
+ .getByPlaceholder(/^e\.g\. service\.name ==/)
+ .fill(expression);
+ }
+ if (channel !== undefined) {
+ const select = modal().locator('.ant-select');
+ await select.click();
+ await select.locator('input[role="combobox"]').fill(channel);
+ await page
+ .locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden)')
+ .locator('.ant-select-item-option')
+ .filter({ hasText: channel })
+ .first()
+ .click();
+ await page.keyboard.press('Escape');
+ }
+ },
+
+ save: async () => {
+ await modal().getByRole('button', { name: 'Save Routing Policy' }).click();
+ await expect(modal()).toHaveCount(0);
+ },
+
+ search: async (name) => {
+ await page.getByTestId('routing-policies-search').fill(name);
+ },
+
+ row: (name) => page.locator('tbody tr').filter({ hasText: name }),
+
+ edit: async (name) => {
+ await routing.search(name);
+ await routing
+ .row(name)
+ .getByRole('button', { name: `Actions for ${name}` })
+ .click();
+ await page.getByRole('menuitem', { name: 'Edit' }).click();
+ await expect(modal()).toBeVisible();
+ },
+
+ remove: async (name) => {
+ await routing.search(name);
+ await routing
+ .row(name)
+ .getByRole('button', { name: `Actions for ${name}` })
+ .click();
+ await page.getByRole('menuitem', { name: 'Delete' }).click();
+ await page.getByRole('button', { name: 'Delete Routing Policy' }).click();
+ await expect(routing.row(name)).toHaveCount(0);
+ },
+
+ byName,
+
+ tryDelete: async (name) => {
+ const found = await byName(name).catch(() => undefined);
+ if (found) {
+ await api.tryDel(`/api/v1/route_policies/${found.id}`);
+ }
+ },
+ };
+
+ return routing;
+}
diff --git a/tests/e2e/helpers/alert-forms/constants.ts b/tests/e2e/drivers/alerts/constants.ts
similarity index 65%
rename from tests/e2e/helpers/alert-forms/constants.ts
rename to tests/e2e/drivers/alerts/constants.ts
index 645b62ce6b..82b9836639 100644
--- a/tests/e2e/helpers/alert-forms/constants.ts
+++ b/tests/e2e/drivers/alerts/constants.ts
@@ -1,3 +1,48 @@
+// ─── Constants ───────────────────────────────────────────────────────────
+
+export const ALERTS_LIST_PATH = '/alerts';
+export const ALERT_OVERVIEW_PATH = '/alerts/overview';
+export const ALERT_HISTORY_PATH = '/alerts/history';
+
+/**
+ * Mirrors `TIMELINE_TABLE_PAGE_SIZE` in
+ * `frontend/src/container/AlertHistory/constants.ts`. This 20 is what makes the
+ * page-2 cursor `base64url({"offset":20,"limit":20})`, so the two must not drift.
+ */
+export const TIMELINE_PAGE_SIZE = 20;
+
+/** The `relativeTime` the history page falls back to (`DEFAULT_TIME_RANGE`). */
+export const DEFAULT_RELATIVE_TIME = '30m';
+
+/**
+ * Page size the list specs pin in the URL, so the number of rendered rows never
+ * depends on the viewport height.
+ */
+export const ALERT_LIST_PAGE_SIZE = 10;
+
+/** Severities the list seed cycles through, so search/sort tests have more than one value. */
+export const SEED_B_SEVERITIES = ['critical', 'warning', 'info'] as const;
+
+// ─── Wait timeouts (ms) ──────────────────────────────────────────────────
+// These timeouts gate on the "ruler" — SigNoz's alert evaluation engine that
+// runs on ~15s cycles and writes history rows to ClickHouse. No way to force
+// evaluation or seed history directly, so we poll until rows appear.
+
+/**
+ * Default timeout for waitForTimelineEntries.
+ *
+ * Logs rules need 2+ ruler cycles (~15s each) to see 25 services fire.
+ * 90s = 6 cycles worst-case. Actual time: 20-35s for logs, ~10s for metrics.
+ */
+export const WAIT_TIMELINE_ENTRIES_DEFAULT = 90_000;
+
+/**
+ * Default timeout for waitForTimelineStates (firing + resolved).
+ *
+ * Resolved state appears after evalWindow expires with no matching data.
+ * 1m window + 2 ruler cycles = ~105s observed. 180s = safe margin.
+ */
+export const WAIT_TIMELINE_STATES_DEFAULT = 180_000;
// ─── Routes ────────────────────────────────────────────────────────────────
export const ALERTS_NEW_PATH = '/alerts/new';
@@ -81,8 +126,8 @@ export const AlertListTab = {
/**
* The four cards a stock stack shows, in render order
* (`CreateAlertRule/SelectAlertType/config.ts:10-31`). Anomaly is `unshift`ed to
- * the **front** of this list when the `ANOMALY_DETECTION` feature flag is active,
- * so both the count and the order change when it is enabled.
+ * the **front** of this list when anomaly detection is available (cloud or enterprise license),
+ * so both the count and the order change when it is.
*/
export const STOCK_ALERT_TYPE_CARDS: AlertTypeValue[] = [
AlertType.METRICS,
diff --git a/tests/e2e/drivers/alerts/driver.ts b/tests/e2e/drivers/alerts/driver.ts
new file mode 100644
index 0000000000..8f6c0a0a16
--- /dev/null
+++ b/tests/e2e/drivers/alerts/driver.ts
@@ -0,0 +1,1054 @@
+import {
+ expect,
+ type Locator,
+ type Page,
+ type Request,
+ type Response,
+ type Route,
+} from '@playwright/test';
+
+import { antdDriver, type Antd } from '../antd';
+import { apiDriver } from '../api';
+import { collectRequests } from '../console';
+import { driver, type Layer } from '../kit';
+import { tanstackDriver, type Tanstack } from '../tanstack';
+
+import {
+ ALERT_EDIT_PATH,
+ ALERT_HISTORY_PATH,
+ ALERT_LIST_PAGE_SIZE,
+ ALERT_OVERVIEW_PATH,
+ ALERTS_LIST_PATH,
+ ALERTS_NEW_PATH,
+ AlertType,
+ type AlertTypeValue,
+ DEFAULT_RELATIVE_TIME,
+ EVALUATION_WINDOW_PRESETS,
+ RuleType,
+ STOCK_ALERT_TYPE_CARDS,
+ TIMELINE_PAGE_SIZE,
+ WAIT_TIMELINE_ENTRIES_DEFAULT,
+ WAIT_TIMELINE_STATES_DEFAULT,
+} from './constants';
+import {
+ plannedDowntimeDriver,
+ routingPoliciesDriver,
+ type PlannedDowntime,
+ type RoutingPolicies,
+} from './configuration';
+import { alertSeeder, type AlertSeeder } from './seed';
+import type { TimelineItem, TimelineResponse } from './types';
+
+/**
+ * The alerts driver: one object per surface, all bound to one page.
+ *
+ * Everything a spec needs to reach the alerts UI is here — the list, the create
+ * builder, the details shell and the history tab — plus `seed` for the API side
+ * and `antd` for the widget primitives underneath.
+ */
+
+// ─── Page shell ──────────────────────────────────────────────────────────────
+
+export type ConfigSection =
+ | 'channels'
+ | 'routing-policies'
+ | 'planned-downtime';
+
+export interface AlertsShell {
+ /** Open `/alerts` with exactly `params` and wait for nothing: which pane
+ * renders, the table or the empty state, is what the caller asserts. */
+ goto(params?: Record<string, string>): Promise<void>;
+ tab(name: string | RegExp): Locator;
+ /** The Configuration sidebar, whose items are buttons rather than tabs. */
+ configSidebar(): Locator;
+ configSidebarItem(key: ConfigSection): Locator;
+ rulesHeading(): Locator;
+ triggeredSearch(): Locator;
+ breadcrumb(): Locator;
+ crumb(text: string): Locator;
+ crumbButton(name: string): Locator;
+ /** A toast or notification, by its text. */
+ message(text: string | RegExp): Locator;
+ /** Every request the page makes from this call on. */
+ recordRequests(): Request[];
+}
+
+// ─── Channels ────────────────────────────────────────────────────────────────
+
+/** Only what the page shell asserts; the channel screens have their own driver in `drivers/channels.ts`. */
+export interface AlertChannels {
+ /** Filter the table by name, so the row is on the first page whatever else is stored. */
+ search(name: string): Promise<void>;
+ /** A channel in the table, by name. */
+ entry(name: string): Locator;
+ newButton(): Locator;
+}
+
+// ─── List ────────────────────────────────────────────────────────────────────
+
+export interface AlertList {
+ table: Tanstack;
+ /**
+ * Open the rules list. `limit` defaults to a fixed page size so row counts
+ * never depend on viewport height. Pass `expectRows: false` for filters that
+ * are *meant* to match nothing.
+ */
+ goto(
+ params?: Record<string, string>,
+ options?: { expectRows?: boolean },
+ ): Promise<void>;
+ rows(): Locator;
+ rowFor(name: string): Locator;
+ /** The STATE cell of `ruleId`'s row — `OK`, `Disabled`, `Firing`. */
+ stateCell(ruleId: string): Locator;
+ search(): Locator;
+ searchFor(text: string): Promise<void>;
+ openRowActions(name: string): Promise<void>;
+ openFirstRowActions(): Promise<void>;
+ menuItem(label: string | RegExp): Locator;
+ newAlertButton(): Locator;
+ /** A header cell, by its rendered text. */
+ columnHeader(name: string): Locator;
+ /** A header's sort control, by its rendered text. */
+ sortButton(name: string): Locator;
+ nextPageButton(): Locator;
+ pageSizeSelect(): Locator;
+ pageSizeOption(size: number): Locator;
+ /** A rule's name anywhere on the page, such as a clone's `<name> - Copy`. */
+ ruleName(name: string, options?: { exact?: boolean }): Locator;
+}
+
+// ─── Create / edit form ──────────────────────────────────────────────────────
+
+export interface AlertForm {
+ gotoTypeSelection(): Promise<void>;
+ typeCard(type: AlertTypeValue): Locator;
+ typeCards(): Locator;
+ /** Whether the anomaly card is present, i.e. whether anomaly detection is available on this
+ * stack. Card-count assertions branch on it rather than hard-coding four. */
+ hasAnomalyCard(): Promise<boolean>;
+ expectTypeCardSet(): Promise<void>;
+ url(options?: CreateAlertUrlOptions): string;
+ gotoV2(options?: Omit<CreateAlertUrlOptions, 'classic'>): Promise<void>;
+ gotoV1(options?: Omit<CreateAlertUrlOptions, 'classic'>): Promise<void>;
+
+ name(): Locator;
+ saveButton(): Locator;
+ testButton(): Locator;
+ discardButton(): Locator;
+ /** Hover the disabled Save and read the validator's message — the only way to
+ * see it, since the button cannot be clicked while a message exists. */
+ saveTooltip(): Promise<string>;
+ /** Click Discard through `dispatchEvent`; see the note in the implementation. */
+ discard(): Promise<void>;
+
+ thresholdRows(): Locator;
+ thresholdRow(index: number): Locator;
+ thresholdValue(index?: number): Locator;
+ selectThresholdChannel(index: number, channelName: string): Promise<void>;
+ addLabel(key: string, value: string): Promise<void>;
+ labelPill(key: string, value: string): Locator;
+ v1SaveButton(): Locator;
+
+ advancedOptionToggle(containerTestId: string): Locator;
+ expandAdvancedOptions(): Promise<void>;
+ evaluationSettingsButton(): Locator;
+ openEvaluationSettings(): Promise<void>;
+ evaluationWindowOption(
+ section: 'window-type' | 'timeframe',
+ value: string,
+ ): Locator;
+ selectEvaluationTimeframe(
+ value: keyof typeof EVALUATION_WINDOW_PRESETS,
+ ): Promise<void>;
+ evaluationCadenceInput(): Locator;
+ evaluationCadenceUnitSelect(): Locator;
+ /** Serve both channel lists empty (the pickers read v2, older screens v1) — the one stub in the alerts suite. */
+ stubNoChannels(): Promise<void>;
+ /** The class name of whatever is on top at a point, for the covered-Discard
+ * defect: the side navigation, not the footer, receives the click. */
+ elementAtPointClassName(x: number, y: number): Promise<string>;
+
+ typeSelectionTitle(): Locator;
+ switchToClassicButton(): Locator;
+ /** The "New Alert Rule" chip, which the create header shows and edit hides. */
+ newRuleChip(): Locator;
+ addThresholdButton(): Locator;
+ thresholdName(index?: number): Locator;
+ thresholdOperatorSelect(): Locator;
+ thresholdMatchTypeSelect(): Locator;
+ recoveryThresholdValue(): Locator;
+ thresholdChannelSelects(): Locator;
+ /** Open a threshold's channel select and return its own dropdown. */
+ openChannelDropdown(index?: number): Promise<ChannelDropdown>;
+ routingPoliciesSwitch(): Locator;
+ viewRoutingPoliciesButton(): Locator;
+ repeatNotificationsInterval(): Locator;
+ repeatNotificationsUnitSelect(): Locator;
+ repeatNotificationsConditionsSelect(): Locator;
+ missingDataToleranceInput(): Locator;
+ minimumDatapointsInput(): Locator;
+ customScheduleEditor(): Locator;
+ /** The shared modal every save error lands in, for both forms. */
+ errorModal(): Locator;
+ errorModalCloseButton(): Locator;
+}
+
+/** `NotificationChannelsNotFoundContent`, rendered inside a channel dropdown. */
+export interface ChannelDropdown {
+ emptyMessage(): Locator;
+ createHereButton(): Locator;
+ refreshButton(): Locator;
+ askAdminMessage(): Locator;
+}
+
+export interface CreateAlertUrlOptions {
+ alertType?: AlertTypeValue;
+ ruleType?: string;
+ /** Sets `showClassicCreateAlertsPage=true` ⇒ the v1 classic form. */
+ classic?: boolean;
+ /** Merged in last, so it can override anything above. */
+ params?: Record<string, string>;
+}
+
+// ─── Details shell ───────────────────────────────────────────────────────────
+
+export interface AlertDetails {
+ /** The details shell (Overview tab), waiting only for the shell to mount. */
+ goto(ruleId: string, params?: Record<string, string>): Promise<void>;
+ /** The overview editor, waiting for the condition editor *and* the serialised
+ * query — without the second half an assertion races the builder's rewrite. */
+ gotoOverview(ruleId: string): Promise<void>;
+ /** `/alerts/edit`, the legacy alias; omit `ruleId` to send none. */
+ gotoEdit(ruleId?: string): Promise<void>;
+ /** Navigate only, for ids that never resolve; omit `ruleId` to send none. */
+ open(ruleId?: string): Promise<void>;
+ root(): Locator;
+ tab(name: string | RegExp): Locator;
+ openActions(): Promise<void>;
+ menuItem(label: string | RegExp): Locator;
+ nameInput(): Locator;
+ /** The Overview and History tabs, by their testids. */
+ sectionTab(key: 'overview' | 'history'): Locator;
+ historyBetaBadge(): Locator;
+ enableToggle(): Locator;
+ copyLinkButton(): Locator;
+ /** The static v1 header; v2 renders `nameInput()` instead. */
+ headerField(field: 'title' | 'state' | 'severity' | 'labels'): Locator;
+ renameInput(): Locator;
+ renameConfirmButton(): Locator;
+ /** Found by label, so it also proves the History tab renders none. */
+ footerSaveButton(): Locator;
+ notFound(): Locator;
+ notFoundMessage(): Locator;
+ editRulesError(): Locator;
+}
+
+// ─── History ─────────────────────────────────────────────────────────────────
+
+export interface AlertHistory {
+ goto(ruleId: string, params?: Record<string, string>): Promise<void>;
+ /** Navigate only, for rule ids that never reach the table. */
+ open(ruleId: string): Promise<void>;
+ table(): Locator;
+ timelineTitle(): Locator;
+ timelineTab(key: 'overall-status' | 'top-contributors'): Locator;
+ stateFilter(key: 'all' | 'fired' | 'resolved'): Locator;
+ prevPageButton(): Locator;
+ nextPageButton(): Locator;
+ /** A cell of `row`; pass `rows()` for that cell in every row. */
+ rowCell(
+ row: Locator,
+ cell: 'state' | 'labels' | 'created-at' | 'actions',
+ ): Locator;
+ viewLogsLink(): Locator;
+ viewTracesLink(): Locator;
+ error(): Locator;
+ filterSearch(): Locator;
+ filterSkeleton(): Locator;
+ filterEditor(): Locator;
+ suggestions(): Locator;
+ runQueryButton(): Locator;
+ cancelQueryButton(): Locator;
+ timeRangeInput(): Locator;
+ timeRangeOption(label: string): Locator;
+ statsCardValue(title: string): Locator;
+ statsCardChange(title: string): Locator;
+ statsCardSparkline(title: string): Locator;
+ graph(): Locator;
+ graphCanvas(): Locator;
+ graphTitle(): Locator;
+ contributorsCard(): Locator;
+ contributorsViewAll(): Locator;
+ contributorsDrawer(): Locator;
+ contributorsDrawerTitle(): Locator;
+ contributorsDrawerTotal(): Locator;
+ /** Contributor rows inside `scope`, or anywhere on the page. */
+ contributorRows(scope?: Locator): Locator;
+ contributorCount(row: Locator): Locator;
+ contributorBar(row: Locator): Locator;
+ rows(): Locator;
+ rowLabels(): Promise<string[]>;
+ firstRowCreatedAt(): Promise<string>;
+ footerRange(): Locator;
+ statsCard(title: string): Locator;
+ openRowActions(index: number): Promise<void>;
+ expectFirstPage(): Promise<void>;
+
+ /** Read the timeline straight from the API, to gate on the ruler having
+ * produced rows before the UI is opened. */
+ fetchTimeline(
+ ruleId: string,
+ params?: Record<string, string | number>,
+ ): Promise<TimelineResponse>;
+ readTotal(ruleId: string): Promise<number>;
+ waitForEntries(
+ ruleId: string,
+ options: { min: number; state?: string; timeoutMs?: number },
+ ): Promise<TimelineResponse>;
+ waitForStates(
+ ruleId: string,
+ options: { states: Record<string, number>; timeoutMs?: number },
+ ): Promise<TimelineResponse>;
+
+ isRequest(request: Request, endpoint: HistoryEndpoint): boolean;
+ waitForResponse(
+ endpoint: HistoryEndpoint,
+ options?: { status?: number; filterExpression?: string },
+ ): Promise<Response>;
+ /** Type into the expression editor without running it — for suggestions. */
+ typeFilter(expression: string): Promise<void>;
+ runFilter(expression: string): Promise<void>;
+ sortDescending(): Promise<void>;
+ /** The exact cursor the UI sends for `page`, byte-identical to the server's. */
+ cursorFor(page: number, limit?: number): string | undefined;
+ labelsOf(item: TimelineItem): Record<string, string>;
+}
+
+/** The four v2 endpoints one history page load hits. */
+export const HISTORY_ENDPOINTS = [
+ 'stats',
+ 'timeline',
+ 'top_contributors',
+ 'overall_status',
+] as const;
+
+export type HistoryEndpoint = (typeof HISTORY_ENDPOINTS)[number];
+
+export interface Alerts {
+ seed: AlertSeeder;
+ antd: Antd;
+ shell: AlertsShell;
+ channels: AlertChannels;
+ list: AlertList;
+ form: AlertForm;
+ details: AlertDetails;
+ history: AlertHistory;
+ downtime: PlannedDowntime;
+ routing: RoutingPolicies;
+}
+
+export function alertsDriver(page: Page): Alerts {
+ const antd = antdDriver(page);
+ const seed = alertSeeder(page);
+
+ const table = tanstackDriver(page, { tableKey: 'alert-rules' });
+
+ const shell: AlertsShell = {
+ goto: async (params = {}) => {
+ const query = new URLSearchParams(params).toString();
+ await page.goto(query ? `${ALERTS_LIST_PATH}?${query}` : ALERTS_LIST_PATH);
+ },
+
+ tab: (name) => page.getByRole('tab', { name }),
+ configSidebar: () => page.getByTestId('alert-configuration-sidebar'),
+ configSidebarItem: (key) => page.getByTestId(`configuration-sidebar-${key}`),
+ rulesHeading: () => page.getByRole('heading', { name: 'Alert Rules' }),
+ triggeredSearch: () => page.getByTestId('triggered-alerts-search-input'),
+ breadcrumb: () => page.locator('.ant-breadcrumb'),
+ crumb: (text) => shell.breadcrumb().getByText(text),
+ crumbButton: (name) => shell.breadcrumb().getByRole('button', { name }),
+ message: (text) => page.getByText(text),
+ recordRequests: () => collectRequests(page),
+ };
+
+ const channels: AlertChannels = {
+ search: async (name) => {
+ await page.getByTestId('channels-search').fill(name);
+ },
+ entry: (name) => page.locator('tbody tr').filter({ hasText: name }),
+ newButton: () => page.getByTestId('channels-create'),
+ };
+
+ const list: AlertList = {
+ table,
+
+ goto: async (params = {}, { expectRows = true } = {}) => {
+ const query = new URLSearchParams({
+ limit: String(ALERT_LIST_PAGE_SIZE),
+ ...params,
+ });
+ await page.goto(`${ALERTS_LIST_PATH}?${query.toString()}`);
+ await expect(list.search()).toBeVisible();
+ if (expectRows) {
+ // Skeleton rows are empty and ignore clicks; wait for a loaded one.
+ await expect(list.rows().first()).toHaveText(/\S/);
+ }
+ },
+
+ rows: () => page.locator('tbody tr'),
+ rowFor: (name) => page.locator('tbody tr', { hasText: name }).first(),
+ stateCell: (ruleId) => page.getByTestId(`alert-row-${ruleId}-state`),
+ search: () => page.getByTestId('list-alerts-search-input'),
+
+ searchFor: async (text) => {
+ await list.search().fill(text);
+ await expect(page).toHaveURL(new RegExp(`search=${text}`));
+ },
+
+ openRowActions: async (name) => {
+ await list.rowFor(name).getByTestId('alert-actions').click();
+ },
+
+ openFirstRowActions: async () => {
+ await list.rows().first().getByTestId('alert-actions').click();
+ },
+
+ menuItem: (label) => page.getByRole('menuitem').filter({ hasText: label }),
+ newAlertButton: () => page.getByTestId('list-alerts-new-alert-button'),
+ columnHeader: (name) => page.getByRole('columnheader', { name }),
+ sortButton: (name) => page.getByRole('button', { name }),
+ nextPageButton: () => page.getByLabel('Go to next page'),
+ pageSizeSelect: () => page.getByTestId('pagination-page-size'),
+ pageSizeOption: (size) =>
+ page.getByRole('option', { name: String(size), exact: true }),
+ ruleName: (name, options) => page.getByText(name, options),
+ };
+
+ const form: AlertForm = {
+ gotoTypeSelection: async () => {
+ // `isTypeSelectionMode` is `!alertType && !ruleType && !compositeQuery`,
+ // so *any* of those three params skips this page — including a stale
+ // `compositeQuery` left over in the URL.
+ await page.goto(ALERTS_NEW_PATH);
+ await expect(form.typeCard(AlertType.METRICS)).toBeVisible();
+ },
+
+ typeCard: (type) => page.getByTestId(`alert-type-card-${type}`),
+ typeCards: () => page.locator('[data-testid^="alert-type-card-"]'),
+
+ hasAnomalyCard: async () =>
+ (await form.typeCard(AlertType.ANOMALY).count()) > 0,
+
+ /**
+ * Exactly the expected set, in order: the four stock cards, plus anomaly
+ * *first* when anomaly is available, because `getOptionList` unshifts it. Written
+ * as an exact set so a fifth signal still fails here.
+ */
+ expectTypeCardSet: async () => {
+ const expected = (await form.hasAnomalyCard())
+ ? [AlertType.ANOMALY, ...STOCK_ALERT_TYPE_CARDS]
+ : STOCK_ALERT_TYPE_CARDS;
+ const cards = form.typeCards();
+ await expect(cards).toHaveCount(expected.length);
+ const rendered = await cards.evaluateAll((nodes) =>
+ nodes.map((node) => node.getAttribute('data-testid')),
+ );
+ expect(rendered).toEqual(expected.map((type) => `alert-type-card-${type}`));
+ },
+
+ url: ({
+ alertType = AlertType.LOGS,
+ ruleType = RuleType.THRESHOLD,
+ classic = false,
+ params = {},
+ }: CreateAlertUrlOptions = {}) => {
+ const search = new URLSearchParams({ alertType, ruleType });
+ if (classic) {
+ search.set('showClassicCreateAlertsPage', 'true');
+ }
+ for (const [key, value] of Object.entries(params)) {
+ search.set(key, value);
+ }
+ return `${ALERTS_NEW_PATH}?${search.toString()}`;
+ },
+
+ gotoV2: async (options = {}) => {
+ await page.goto(form.url({ ...options, classic: false }));
+ await expect(form.name()).toBeVisible();
+ // `useShareBuilderUrl` serialises the default query shortly after mount;
+ // asserting on the URL before that races its rewrite.
+ await page.waitForURL(/compositeQuery=/, { timeout: 15_000 });
+ },
+
+ gotoV1: async (options = {}) => {
+ await page.goto(form.url({ ...options, classic: true }));
+ await expect(form.v1SaveButton()).toBeVisible();
+ },
+
+ name: () => page.getByTestId('alert-name-input'),
+ saveButton: () => page.getByTestId('save-alert-rule-button'),
+ testButton: () => page.getByTestId('test-notification-button'),
+ discardButton: () => page.getByTestId('discard-alert-rule-button'),
+ v1SaveButton: () => page.getByTestId('alert-save-button'),
+
+ saveTooltip: async () => {
+ await form.saveButton().hover();
+ const tooltip = page.locator('[data-slot="tooltip-content"]').first();
+ await expect(tooltip).toBeVisible();
+ return (await tooltip.innerText()).trim();
+ },
+
+ /**
+ * The footer is `position: fixed; left: 63px` — the *collapsed* rail width —
+ * so Discard sits under the 240px side navigation, which swallows the click.
+ * `{ force: true }` does not help: it skips the actionability wait but still
+ * delivers a real mouse event at those coordinates. `dispatchEvent` bypasses
+ * hit-testing and React's delegated handler fires normally.
+ *
+ * This is a workaround for a **product** bug, not for a flaky test.
+ */
+ discard: async () => {
+ await form.discardButton().dispatchEvent('click');
+ },
+
+ // There is no `threshold-item-<id>` testid: the row is a bare
+ // `className="threshold-item"`, so rows are addressed positionally.
+ thresholdRows: () => page.locator('.threshold-item'),
+ thresholdRow: (index) => form.thresholdRows().nth(index),
+ thresholdValue: (index = 0) =>
+ page.getByTestId('threshold-value-input').nth(index),
+
+ selectThresholdChannel: async (index, channelName) => {
+ await antd.pickByName(
+ form.thresholdChannelSelects().nth(index),
+ channelName,
+ );
+ },
+
+ /**
+ * The label editor is one field with two phases, key then value, each
+ * committed with Enter. Committing does *not* close it — `isAdding` stays
+ * true so a user can type several in a row — so Escape is what closes it,
+ * and without that a second call waits forever for the add button.
+ */
+ addLabel: async (key, value) => {
+ await page.getByTestId('alert-add-label-button').click();
+ const input = page.getByTestId('alert-add-label-input');
+ await input.fill(key);
+ await input.press('Enter');
+ await input.fill(value);
+ await input.press('Enter');
+ await input.press('Escape');
+ await expect(page.getByTestId('alert-add-label-button')).toBeVisible();
+ },
+
+ labelPill: (key, value) => page.getByTestId(`label-pill-${key}-${value}`),
+
+ // The `Switch` inside an `AdvancedOptionItem` carries no testid of its own,
+ // so it is reached through its container's.
+ advancedOptionToggle: (containerTestId) =>
+ page.getByTestId(containerTestId).locator('[role="switch"]'),
+
+ /**
+ * antd's `Collapse` renders panel children lazily, so the cadence inputs and
+ * the advanced-option containers do not exist in the DOM until this runs.
+ */
+ expandAdvancedOptions: async () => {
+ const header = page.getByRole('button', { name: /ADVANCED OPTIONS/i });
+ if ((await header.getAttribute('aria-expanded')) !== 'true') {
+ await header.click();
+ }
+ await expect(
+ page.getByTestId('evaluation-cadence-input-group'),
+ ).toBeVisible();
+ },
+
+ evaluationSettingsButton: () =>
+ page.getByTestId('evaluation-settings-button'),
+
+ // The popover's content is only in the DOM while open, so every option
+ // lookup has to come after this.
+ openEvaluationSettings: async () => {
+ await form.evaluationSettingsButton().click();
+ await expect(page.locator('.evaluation-window-popover')).toBeVisible();
+ },
+
+ // One component renders both lists, keyed by `data-section-id`, and the
+ // testid carries the section so a timeframe cannot collide with a type.
+ evaluationWindowOption: (section, value) =>
+ page.getByTestId(`${section}-option-${value}`),
+
+ // Waiting for the trigger to reflect the pick matters: a spec that saves
+ // immediately posts the old window. The popover ignores Escape and can sit
+ // over the controls below it, so its trigger closes it.
+ selectEvaluationTimeframe: async (value) => {
+ await form.openEvaluationSettings();
+ await form.evaluationWindowOption('timeframe', value).click();
+ await expect(form.evaluationSettingsButton()).toContainText(
+ EVALUATION_WINDOW_PRESETS[value],
+ );
+ await form.evaluationSettingsButton().click();
+ await expect(page.locator('.evaluation-window-popover')).toBeHidden();
+ },
+
+ evaluationCadenceInput: () =>
+ page.getByTestId('evaluation-cadence-duration-input'),
+ evaluationCadenceUnitSelect: () =>
+ page.getByTestId('evaluation-cadence-unit-select'),
+
+ /**
+ * The **one** place the alerts suite mocks the network, deliberately: zero
+ * channels is a real product state that every fresh install has, it is the
+ * only state that reaches the disabled broadcast switch, and it cannot be
+ * produced server-side because the channel fixture is worker-scoped and
+ * parallel workers share one stack.
+ */
+ elementAtPointClassName: (x, y) =>
+ page.evaluate(
+ ([px, py]) => {
+ const element = document.elementFromPoint(px, py);
+ return element ? String(element.className) : '';
+ },
+ [x, y],
+ ),
+
+ stubNoChannels: async () => {
+ const emptyList = async (
+ route: Route,
+ body: Record<string, unknown>,
+ ): Promise<void> => {
+ if (route.request().method() !== 'GET') {
+ await route.fallback();
+ return;
+ }
+ await route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify(body),
+ });
+ };
+
+ await page.route('**/api/v1/channels', (route) =>
+ emptyList(route, { status: 'success', data: [] }),
+ );
+ // the v2 list is paginated, so the empty page has to carry its total
+ await page.route('**/api/v2/notification_channels*', (route) =>
+ emptyList(route, {
+ status: 'success',
+ data: { channels: [], total: 0 },
+ }),
+ );
+ },
+
+ typeSelectionTitle: () => page.getByText('Choose a type for the alert'),
+ switchToClassicButton: () =>
+ page.getByRole('button', { name: 'Switch to Classic Experience' }),
+ newRuleChip: () => page.getByText('New Alert Rule'),
+ addThresholdButton: () => page.getByTestId('add-threshold-button'),
+ thresholdName: (index = 0) =>
+ page.getByTestId('threshold-name-input').nth(index),
+ thresholdOperatorSelect: () =>
+ page.getByTestId('alert-threshold-operator-select'),
+ thresholdMatchTypeSelect: () =>
+ page.getByTestId('alert-threshold-match-type-select'),
+ recoveryThresholdValue: () =>
+ page.getByTestId('recovery-threshold-value-input'),
+ thresholdChannelSelects: () =>
+ page.getByTestId('threshold-notification-channel-select'),
+
+ openChannelDropdown: async (index = 0) => {
+ const select = form.thresholdChannelSelects().nth(index);
+ await select.click();
+ const dropdown = await antd.ownDropdown(select);
+ return {
+ emptyMessage: () => dropdown.getByText('No channels yet.'),
+ createHereButton: () => dropdown.getByRole('button', { name: 'here.' }),
+ refreshButton: () => dropdown.getByRole('button', { name: 'Refresh' }),
+ askAdminMessage: () =>
+ dropdown.getByText('Please ask your admin to create one.'),
+ };
+ },
+
+ routingPoliciesSwitch: () => page.getByTestId('routing-policies-switch'),
+ viewRoutingPoliciesButton: () =>
+ page.getByTestId('view-routing-policies-button'),
+ repeatNotificationsInterval: () =>
+ page.getByTestId('repeat-notifications-time-input'),
+ repeatNotificationsUnitSelect: () =>
+ page.getByTestId('repeat-notifications-unit-select'),
+ repeatNotificationsConditionsSelect: () =>
+ page.getByTestId('repeat-notifications-conditions-select'),
+ missingDataToleranceInput: () =>
+ page.getByTestId('send-notification-if-data-is-missing-input'),
+ minimumDatapointsInput: () =>
+ page.getByTestId('enforce-minimum-datapoints-input'),
+ customScheduleEditor: () => page.locator('.edit-custom-schedule'),
+ errorModal: () => page.locator('.error-modal__wrap'),
+ errorModalCloseButton: () => page.getByTestId('close-button'),
+ };
+
+ const details: AlertDetails = {
+ goto: async (ruleId, params = {}) => {
+ const query = new URLSearchParams({
+ ruleId,
+ relativeTime: DEFAULT_RELATIVE_TIME,
+ ...params,
+ });
+ await page.goto(`${ALERT_OVERVIEW_PATH}?${query.toString()}`);
+ await expect(details.root()).toBeVisible();
+ },
+
+ gotoOverview: async (ruleId) => {
+ await page.goto(`${ALERT_OVERVIEW_PATH}?ruleId=${ruleId}`);
+ // `.first()`: a rule may have several thresholds and the editor renders
+ // one input per threshold, so an unscoped locator is a strict-mode
+ // violation that only appears once the second row has rendered.
+ await expect(form.thresholdValue()).toBeVisible();
+ await page.waitForURL(/compositeQuery=/, { timeout: 15_000 });
+ },
+
+ gotoEdit: async (ruleId) => {
+ await page.goto(
+ ruleId === undefined
+ ? ALERT_EDIT_PATH
+ : `${ALERT_EDIT_PATH}?ruleId=${ruleId}`,
+ );
+ },
+
+ open: async (ruleId) => {
+ await page.goto(
+ ruleId === undefined
+ ? ALERT_OVERVIEW_PATH
+ : `${ALERT_OVERVIEW_PATH}?ruleId=${ruleId}`,
+ );
+ },
+
+ root: () => page.getByTestId('alert-details-root'),
+ tab: (name) => page.getByRole('tab', { name }),
+ menuItem: (label) => page.getByRole('menuitem').filter({ hasText: label }),
+ nameInput: () => page.getByTestId('alert-name-input'),
+
+ openActions: async () => {
+ await page.getByTestId('alert-actions-menu').click();
+ },
+
+ sectionTab: (key) => page.getByTestId(`alert-details-tab-${key}`),
+ historyBetaBadge: () => details.sectionTab('history').getByText('Beta'),
+ enableToggle: () => page.getByTestId('alert-actions-toggle'),
+ copyLinkButton: () => page.getByRole('button', { name: 'Copy link' }),
+ headerField: (field) => page.getByTestId(`alert-header-${field}`),
+ renameInput: () => page.getByTestId('alert-name'),
+ renameConfirmButton: () => page.getByRole('button', { name: 'Rename Alert' }),
+ footerSaveButton: () => page.getByRole('button', { name: 'Save Alert Rule' }),
+ notFound: () => page.locator('.alert-not-found'),
+ notFoundMessage: () =>
+ page.getByText("Uh-oh! We couldn't find the given alert rule."),
+ editRulesError: () => page.locator('.edit-rules-container--error'),
+ };
+
+ const historyApi = (
+ ruleId: string,
+ params: Record<string, string | number> = {},
+ ): Promise<TimelineResponse> => {
+ const now = Date.now();
+ const query = new URLSearchParams({
+ start: String(now - 30 * 60 * 1000),
+ end: String(now),
+ limit: '100',
+ order: 'asc',
+ ...Object.fromEntries(
+ Object.entries(params).map(([key, value]) => [key, String(value)]),
+ ),
+ });
+ return apiDriver(page)
+ .get<{ data: TimelineResponse | null }>(
+ `/api/v2/rules/${ruleId}/history/timeline?${query.toString()}`,
+ )
+ .then((body) => ({
+ items: body.data?.items ?? [],
+ total: body.data?.total ?? 0,
+ nextCursor: body.data?.nextCursor,
+ }));
+ };
+
+ const countStates = (items: TimelineItem[]): Record<string, number> =>
+ items.reduce<Record<string, number>>((acc, item) => {
+ acc[item.state] = (acc[item.state] ?? 0) + 1;
+ return acc;
+ }, {});
+
+ const history: AlertHistory = {
+ goto: async (ruleId, params = {}) => {
+ // An absolute window and `relativeTime` are mutually exclusive in
+ // practice: with both present the time picker normalises back to the
+ // relative range and drops `startTime`/`endTime`, so the absolute window
+ // never takes effect.
+ const hasAbsoluteRange = !!params.startTime && !!params.endTime;
+ const query = new URLSearchParams({
+ ruleId,
+ ...(hasAbsoluteRange ? {} : { relativeTime: DEFAULT_RELATIVE_TIME }),
+ ...params,
+ });
+ await page.goto(`${ALERT_HISTORY_PATH}?${query.toString()}`);
+
+ // Race the table against the app's error boundary: the history page has
+ // been seen crashing into it on load, and without this the failure reads
+ // as "timeline-table not found", which says nothing about why.
+ const table_ = history.table();
+ const crashed = page.getByText('Something went wrong :/');
+ await expect(table_.or(crashed)).toBeVisible();
+ if (await crashed.isVisible()) {
+ throw new Error(
+ `alert history crashed into the app error boundary at ${page.url()} — ` +
+ 'a component threw during render; check the captured console output',
+ );
+ }
+ await expect(table_).toBeVisible();
+ // The node is rendered by the first paint, *before* the timeline request
+ // settles — antd only overlays a spinner. Returning here would leave that
+ // request in flight and the spec's next `waitForResponse` would resolve
+ // with the page load instead of its own interaction.
+ await expect(page.locator('.timeline-table .ant-spin-spinning')).toHaveCount(
+ 0,
+ );
+ },
+
+ open: async (ruleId) => {
+ await page.goto(`${ALERT_HISTORY_PATH}?ruleId=${ruleId}`);
+ },
+
+ table: () => page.getByTestId('timeline-table'),
+ timelineTitle: () => page.locator('.timeline__title'),
+ timelineTab: (key) => page.getByTestId(`timeline-tab-${key}`),
+ stateFilter: (key) => page.getByTestId(`timeline-filter-${key}`),
+ prevPageButton: () => page.getByTestId('timeline-prev-page'),
+ nextPageButton: () => page.getByTestId('timeline-next-page'),
+ rowCell: (row, cell) => row.getByTestId(`timeline-row-${cell}`),
+ viewLogsLink: () => page.getByTestId('alert-popover-view-logs'),
+ viewTracesLink: () => page.getByTestId('alert-popover-view-traces'),
+ error: () => page.getByTestId('timeline-error'),
+ filterSearch: () => page.getByTestId('timeline-filter-search'),
+ filterSkeleton: () => page.getByTestId('timeline-filter-skeleton'),
+ filterEditor: () => page.locator('.query-where-clause-editor .cm-content'),
+ suggestions: () => page.locator('.cm-tooltip-autocomplete li'),
+ runQueryButton: () => page.getByRole('button', { name: /run query/i }),
+ cancelQueryButton: () => page.getByRole('button', { name: 'Cancel' }),
+ timeRangeInput: () => page.locator('.filters input').first(),
+ timeRangeOption: (label) => page.getByText(label, { exact: true }),
+ statsCardValue: (title) =>
+ history.statsCard(title).getByTestId('stats-card-value'),
+ statsCardChange: (title) =>
+ history.statsCard(title).getByTestId('stats-card-change'),
+ statsCardSparkline: (title) =>
+ history.statsCard(title).getByTestId('stats-card-sparkline'),
+ graph: () => page.getByTestId('timeline-graph'),
+ graphCanvas: () => history.graph().locator('canvas'),
+ graphTitle: () => page.getByTestId('timeline-graph-title'),
+ contributorsCard: () => page.getByTestId('top-contributors-card'),
+ contributorsViewAll: () => page.getByTestId('top-contributors-view-all'),
+ contributorsDrawer: () => page.getByTestId('top-contributors-drawer'),
+ contributorsDrawerTitle: () => page.getByText('Viewing All Contributors'),
+ contributorsDrawerTotal: () => history.contributorsDrawer().locator('.total'),
+ contributorRows: (scope) =>
+ (scope ?? page).getByTestId('top-contributors-row'),
+ contributorCount: (row) => row.getByTestId('top-contributors-row-count'),
+ contributorBar: (row) => row.getByRole('progressbar'),
+
+ rows: () => page.getByTestId('timeline-row'),
+ footerRange: () => page.getByTestId('timeline-footer-range'),
+ statsCard: (title) =>
+ page.locator(`[data-testid="stats-card"][data-stats-title="${title}"]`),
+
+ rowLabels: () => history.rowCell(history.rows(), 'labels').allInnerTexts(),
+
+ firstRowCreatedAt: () =>
+ history.rowCell(history.rows().first(), 'created-at').innerText(),
+
+ openRowActions: async (index) => {
+ await history.rowCell(history.rows().nth(index), 'actions').click();
+ },
+
+ /**
+ * Both the list and the timeline use nuqs with
+ * `parseAsInteger.withDefault(1)`, which **removes** the param on reset
+ * rather than writing `page=1`, so "absent" and "1" are the same state and a
+ * naive `?page=1` regex never matches.
+ */
+ expectFirstPage: async () => {
+ await expect
+ .poll(() => new URL(page.url()).searchParams.get('page') ?? '1')
+ .toBe('1');
+ },
+
+ fetchTimeline: historyApi,
+
+ readTotal: async (ruleId) => (await historyApi(ruleId, { limit: 1 })).total,
+
+ /**
+ * Poll until `min` rows in `state` exist. ~20-35 s for the logs seed and
+ * ~10 s for metrics, so budget generously: a timeout here means the marker
+ * aged out of the eval window, not that the assertion is wrong.
+ */
+ waitForEntries: async (
+ ruleId,
+ { min, state = 'firing', timeoutMs = WAIT_TIMELINE_ENTRIES_DEFAULT },
+ ) => {
+ const deadline = Date.now() + timeoutMs;
+ let last: TimelineResponse = { items: [], total: 0 };
+ while (Date.now() < deadline) {
+ // eslint-disable-next-line no-await-in-loop
+ last = await historyApi(ruleId);
+ if (last.items.filter((item) => item.state === state).length >= min) {
+ return last;
+ }
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, 2_000);
+ });
+ }
+ throw new Error(
+ `timeline for rule ${ruleId} never reached ${min} '${state}' rows within ${timeoutMs}ms ` +
+ `(last: total=${last.total}, states=${JSON.stringify(countStates(last.items))})`,
+ );
+ },
+
+ waitForStates: async (
+ ruleId,
+ { states, timeoutMs = WAIT_TIMELINE_STATES_DEFAULT },
+ ) => {
+ const deadline = Date.now() + timeoutMs;
+ let last: TimelineResponse = { items: [], total: 0 };
+ while (Date.now() < deadline) {
+ // eslint-disable-next-line no-await-in-loop
+ last = await historyApi(ruleId);
+ const seen = countStates(last.items);
+ if (
+ Object.entries(states).every(([state, min]) => (seen[state] ?? 0) >= min)
+ ) {
+ return last;
+ }
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, 3_000);
+ });
+ }
+ throw new Error(
+ `timeline for rule ${ruleId} never reached ${JSON.stringify(states)} within ${timeoutMs}ms ` +
+ `(last states: ${JSON.stringify(countStates(last.items))})`,
+ );
+ },
+
+ isRequest: (request, endpoint) =>
+ new RegExp(`/api/v2/rules/[^/]+/history/${endpoint}`).test(request.url()),
+
+ /**
+ * `filterExpression` matters whenever a scenario reacts to *its own*
+ * request: the page's own load is still in flight when the spec starts
+ * typing, so an unqualified matcher resolves with that earlier response.
+ */
+ waitForResponse: (endpoint, options) =>
+ page.waitForResponse((res) => {
+ if (!history.isRequest(res.request(), endpoint)) {
+ return false;
+ }
+ if (options?.status !== undefined && res.status() !== options.status) {
+ return false;
+ }
+ if (options?.filterExpression !== undefined) {
+ const sent =
+ new URL(res.request().url()).searchParams.get('filterExpression') ?? '';
+ return sent === options.filterExpression;
+ }
+ return true;
+ }),
+
+ typeFilter: async (expression) => {
+ const editor = history.filterEditor().first();
+ await editor.waitFor({ state: 'visible', timeout: 15_000 });
+ // Retried: a keystroke landing while the editor is still syncing its
+ // initial value moves the cursor, so the text comes out rotated. An
+ // unterminated quote or bracket is auto-closed by the editor.
+ await expect(async () => {
+ await editor.click();
+ await page.keyboard.press('ControlOrMeta+a');
+ await page.keyboard.press('Delete');
+ await page.keyboard.type(expression);
+ if (expression === '') {
+ await expect(editor.locator('.cm-placeholder')).toBeVisible({
+ timeout: 2_000,
+ });
+ } else {
+ const escaped = expression.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ await expect(editor).toHaveText(new RegExp(`^${escaped}['")\\]]?$`), {
+ timeout: 2_000,
+ });
+ }
+ }).toPass({ timeout: 15_000 });
+ },
+
+ runFilter: async (expression) => {
+ await history.typeFilter(expression);
+ await history.runQueryButton().click();
+ },
+
+ /**
+ * The antd table is *uncontrolled* — `sorter: true` with no `sortOrder` — so
+ * its cycle is none → ascend → descend regardless of the order the hook
+ * already sends. Reaching `desc` takes two clicks, and the first only resets
+ * the page, because asc is nuqs's default and writes no param.
+ */
+ sortDescending: async () => {
+ const header = page.getByRole('columnheader', { name: 'STATE' });
+ const descRequest = page.waitForRequest(
+ (req) =>
+ history.isRequest(req, 'timeline') &&
+ new URL(req.url()).searchParams.get('order') === 'desc',
+ );
+ await header.click();
+ await header.click();
+ await descRequest;
+ },
+
+ /** Mirror of `encodeCursor` in `useTimelineTableCursor.ts`. */
+ cursorFor: (pageNumber, limit = TIMELINE_PAGE_SIZE) => {
+ if (pageNumber <= 1) {
+ return undefined;
+ }
+ return Buffer.from(
+ JSON.stringify({ offset: (pageNumber - 1) * limit, limit }),
+ )
+ .toString('base64')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ .replace(/=+$/, '');
+ },
+
+ labelsOf: (item) =>
+ (item.labels ?? []).reduce<Record<string, string>>((acc, label) => {
+ const name = label.key?.name;
+ if (name) {
+ acc[name] = String(label.value ?? '');
+ }
+ return acc;
+ }, {}),
+ };
+
+ return {
+ seed,
+ antd,
+ shell,
+ channels,
+ list,
+ form,
+ details,
+ history,
+ downtime: plannedDowntimeDriver(page),
+ routing: routingPoliciesDriver(page),
+ };
+}
+
+export const withAlerts: Layer<{ alerts: Alerts }> = driver(
+ 'alerts',
+ ({ page }) => alertsDriver(page),
+);
diff --git a/tests/e2e/drivers/alerts/index.ts b/tests/e2e/drivers/alerts/index.ts
new file mode 100644
index 0000000000..5637717739
--- /dev/null
+++ b/tests/e2e/drivers/alerts/index.ts
@@ -0,0 +1,44 @@
+import { kit } from '../kit';
+
+import { withAlerts } from './driver';
+import {
+ withAlertChannel,
+ withAlertHistory,
+ withAlertList,
+ withEmptyHistory,
+ withMetricsHistory,
+ withNoDataHistory,
+ withOwnedRules,
+ withResolvedHistory,
+ withTracesHistory,
+} from './seeds';
+
+/**
+ * The alerts `test`: the driver plus every alerts seed.
+ *
+ * Carrying all the seeds costs nothing a spec does not use — Playwright builds
+ * fixtures lazily, so a spec that never destructures `resolvedHistory` never
+ * pays its 105 s ruler wait. One import per spec is the point.
+ */
+export const test = withAlerts(
+ withOwnedRules(
+ withAlertChannel(
+ withAlertList(
+ withAlertHistory(
+ withMetricsHistory(
+ withTracesHistory(
+ withResolvedHistory(withNoDataHistory(withEmptyHistory(kit))),
+ ),
+ ),
+ ),
+ ),
+ ),
+ ),
+);
+
+export { expect } from '../kit';
+export { alertsDriver, HISTORY_ENDPOINTS, withAlerts } from './driver';
+export type { Alerts, HistoryEndpoint } from './driver';
+export * from './constants';
+export type { TimelineItem, TimelineResponse } from './types';
+export { V1_RULE_TEAM_LABEL } from './seeds';
diff --git a/tests/e2e/helpers/alerts/payloads.ts b/tests/e2e/drivers/alerts/payloads.ts
similarity index 100%
rename from tests/e2e/helpers/alerts/payloads.ts
rename to tests/e2e/drivers/alerts/payloads.ts
diff --git a/tests/e2e/drivers/alerts/seed.ts b/tests/e2e/drivers/alerts/seed.ts
new file mode 100644
index 0000000000..68f4000d1a
--- /dev/null
+++ b/tests/e2e/drivers/alerts/seed.ts
@@ -0,0 +1,340 @@
+import { randomBytes } from 'crypto';
+
+import type { Page } from '@playwright/test';
+
+import { apiDriver } from '../api';
+import { postToSeeder, type TelemetryPath } from '../telemetry';
+
+import { SEED_B_SEVERITIES } from './constants';
+import {
+ buildThresholdRulePayload,
+ logsCompositeQuery,
+ metricsCompositeQuery,
+ tracesCompositeQuery,
+ v1RulePayload,
+ v2RulePayload,
+} from './payloads';
+import type {
+ AlertRulesSeedOptions,
+ AlertSchema,
+ LogsAlertSeed,
+ LogsSeedOptions,
+ MetricAlertSeed,
+ MetricsSeedOptions,
+ ThresholdAlertSeed,
+ TracesAlertSeed,
+ TracesSeedOptions,
+} from './types';
+
+/**
+ * Seeding alerts: rules through the API, telemetry through the seeder container.
+ *
+ * Page-bound rather than layered on `test`, because worker fixtures run outside
+ * a test and still need all of it. {@link alertSeeder} is what the worker seeds
+ * and the `seed` driver both call.
+ */
+
+export interface AlertSeeder {
+ channel(name: string): Promise<{ id: string; name: string }>;
+ deleteChannel(id: string): Promise<void>;
+ threshold(seed: ThresholdAlertSeed): Promise<string>;
+ logsRule(seed: LogsAlertSeed): Promise<string>;
+ tracesRule(seed: TracesAlertSeed): Promise<string>;
+ metricRule(seed: MetricAlertSeed): Promise<string>;
+ /** A logs rule whose filter matches nothing, with `alertOnAbsent` set — the
+ * only cheap way to get a `nodata` history row. Seed no telemetry for it. */
+ noDataRule(options: {
+ name: string;
+ marker: string;
+ channels: string[];
+ }): Promise<string>;
+ rules(options: AlertRulesSeedOptions): Promise<string[]>;
+ deleteRule(id: string): Promise<void>;
+ deleteRules(ids: string[]): Promise<void>;
+ /**
+ * Freeze a rule's history. Rows are written on *state change* only, so the
+ * firing wave lands once — but once the eval window rolls past the seeded
+ * records the rule resolves and writes a second row per fingerprint, doubling
+ * `total` mid-suite. Disable as soon as the firing wave is confirmed.
+ */
+ setDisabled(id: string, disabled: boolean): Promise<void>;
+ logs(options: LogsSeedOptions): Promise<string[]>;
+ traces(options: TracesSeedOptions): Promise<string[]>;
+ metrics(options: MetricsSeedOptions): Promise<void>;
+}
+
+export function alertSeeder(page: Page): AlertSeeder {
+ const api = apiDriver(page);
+
+ const postRule = (
+ schema: AlertSchema,
+ payload: Record<string, unknown>,
+ ): Promise<string> =>
+ api.create(schema === 'v1' ? '/api/v1/rules' : '/api/v2/rules', payload);
+
+ const postTelemetry = (path: TelemetryPath, data: unknown[]): Promise<void> =>
+ postToSeeder(page.request, path, data);
+
+ const seeder: AlertSeeder = {
+ channel: async (name) => {
+ // `to` is never delivered; the channel only has to exist for rule
+ // validation, which references channels by name.
+ const id = await api.create('/api/v1/channels', {
+ name,
+ email_configs: [
+ { send_resolved: true, to: '[email protected]', html: '', headers: {} },
+ ],
+ });
+ return { id, name };
+ },
+
+ deleteChannel: (id) => api.tryDel(`/api/v1/channels/${id}`),
+
+ threshold: (seed) =>
+ api.create('/api/v2/rules', buildThresholdRulePayload(seed)),
+
+ logsRule: ({
+ name,
+ marker,
+ channels,
+ schema = 'v2',
+ evalWindow = '5m0s',
+ frequency = '15s',
+ severity = schema === 'v1' ? 'warning' : 'critical',
+ extraLabels,
+ alertOnAbsent,
+ absentFor,
+ target,
+ op,
+ matchType,
+ }) => {
+ const args = {
+ name,
+ alertType: 'LOGS_BASED_ALERT',
+ compositeQuery: logsCompositeQuery(marker),
+ channels,
+ severity,
+ extraLabels,
+ evalWindow,
+ frequency,
+ extraCondition:
+ alertOnAbsent === undefined
+ ? undefined
+ : { alertOnAbsent, absentFor: absentFor ?? 1 },
+ target,
+ op,
+ matchType,
+ };
+ return postRule(
+ schema,
+ schema === 'v1' ? v1RulePayload(args) : v2RulePayload(args),
+ );
+ },
+
+ tracesRule: ({
+ name,
+ marker,
+ channels,
+ evalWindow = '5m0s',
+ frequency = '15s',
+ }) =>
+ postRule(
+ 'v2',
+ v2RulePayload({
+ name,
+ alertType: 'TRACES_BASED_ALERT',
+ compositeQuery: tracesCompositeQuery(marker),
+ channels,
+ severity: 'critical',
+ evalWindow,
+ frequency,
+ }),
+ ),
+
+ metricRule: ({
+ name,
+ metricName,
+ channels,
+ groupByKey = 'host',
+ evalWindow = '5m0s',
+ frequency = '15s',
+ }) =>
+ postRule(
+ 'v2',
+ v2RulePayload({
+ name,
+ alertType: 'METRIC_BASED_ALERT',
+ compositeQuery: metricsCompositeQuery(metricName, groupByKey),
+ channels,
+ severity: 'critical',
+ evalWindow,
+ frequency,
+ }),
+ ),
+
+ noDataRule: ({ name, marker, channels }) =>
+ seeder.logsRule({
+ name,
+ marker,
+ channels,
+ evalWindow: '5m0s',
+ frequency: '15s',
+ alertOnAbsent: true,
+ absentFor: 1,
+ }),
+
+ /**
+ * `count` metric threshold rules sharing one channel. Severities cycle so
+ * the list's search has hits *and* misses for all three, and every rule
+ * carries a `team` label: even-indexed `platform`, odd `payments`, i.e.
+ * half the batch each.
+ */
+ rules: async ({
+ count,
+ channelName,
+ namePrefix = 'e2e-alert-list',
+ teamSuffix = '',
+ }) => {
+ const ids: string[] = [];
+ for (let i = 0; i < count; i += 1) {
+ // Sequential on purpose: the rules API is not the thing under test and
+ // parallel POSTs make failures harder to attribute.
+ // eslint-disable-next-line no-await-in-loop
+ const id = await seeder.threshold({
+ name: `${namePrefix}-${String(i).padStart(2, '0')}`,
+ target: 100 + i,
+ channels: [channelName],
+ labels: {
+ severity: SEED_B_SEVERITIES[i % SEED_B_SEVERITIES.length],
+ team: `${i % 2 === 0 ? 'platform' : 'payments'}${teamSuffix}`,
+ },
+ });
+ ids.push(id);
+ }
+ return ids;
+ },
+
+ deleteRule: (id) => api.tryDel(`/api/v2/rules/${id}`),
+
+ deleteRules: async (ids) => {
+ for (const id of ids) {
+ // eslint-disable-next-line no-await-in-loop
+ await seeder.deleteRule(id);
+ }
+ },
+
+ setDisabled: async (id, disabled) => {
+ await api.patch(`/api/v2/rules/${id}`, { disabled });
+ },
+
+ /**
+ * Log records the history rules match on. Returns the generated
+ * `service.name` values, which become the timeline rows' `groupBy` labels
+ * (N services ⇒ N fingerprints ⇒ N timeline rows).
+ *
+ * Seed **immediately** before creating the rule: the rule only fires while
+ * the records are inside its eval window, and a stale marker silently never
+ * fires.
+ */
+ logs: async ({
+ marker,
+ services,
+ recordsPerService = 2,
+ ageSeconds = 150,
+ minAgeSeconds = 30,
+ servicePrefix = 'e2e-ah-svc',
+ }) => {
+ const now = Date.now();
+ const span = Math.max(ageSeconds - minAgeSeconds, 1);
+ const serviceNames: string[] = [];
+ const records: Record<string, unknown>[] = [];
+
+ for (let i = 0; i < services; i += 1) {
+ const service = `${servicePrefix}-${i}`;
+ serviceNames.push(service);
+ for (let r = 0; r < recordsPerService; r += 1) {
+ const fraction =
+ (i * recordsPerService + r) / (services * recordsPerService);
+ records.push({
+ timestamp: new Date(
+ now - (ageSeconds - Math.floor(fraction * span)) * 1000,
+ ).toISOString(),
+ body: marker,
+ resources: { 'service.name': service },
+ });
+ }
+ }
+
+ await postTelemetry('/telemetry/logs', records);
+ return serviceNames;
+ },
+
+ /** One root span per service, all sharing the span `name` marker. */
+ traces: async ({
+ marker,
+ services,
+ spansPerService = 2,
+ ageSeconds = 150,
+ minAgeSeconds = 30,
+ servicePrefix = 'e2e-aht-svc',
+ }) => {
+ const now = Date.now();
+ const span = Math.max(ageSeconds - minAgeSeconds, 1);
+ const serviceNames: string[] = [];
+ const spans: Record<string, unknown>[] = [];
+
+ for (let i = 0; i < services; i += 1) {
+ const service = `${servicePrefix}-${i}`;
+ serviceNames.push(service);
+ for (let s = 0; s < spansPerService; s += 1) {
+ const fraction = (i * spansPerService + s) / (services * spansPerService);
+ spans.push({
+ timestamp: new Date(
+ now - (ageSeconds - Math.floor(fraction * span)) * 1000,
+ ).toISOString(),
+ trace_id: randomBytes(16).toString('hex'),
+ span_id: randomBytes(8).toString('hex'),
+ name: marker,
+ kind: 2,
+ duration: 'PT0.05S',
+ resources: { 'service.name': service },
+ });
+ }
+ }
+
+ await postTelemetry('/telemetry/traces', spans);
+ return serviceNames;
+ },
+
+ /**
+ * A throwaway gauge the metrics rule alerts on. Cheaper than the logs seed
+ * (~10 s to fire) and its history rows carry neither related link — the "no
+ * links available" case.
+ */
+ metrics: async ({
+ metricName,
+ hosts,
+ pointsPerHost = 3,
+ groupByKey = 'host',
+ }) => {
+ const now = Date.now();
+ const points: Record<string, unknown>[] = [];
+ for (const host of hosts) {
+ for (let p = 0; p < pointsPerHost; p += 1) {
+ points.push({
+ metric_name: metricName,
+ labels: { [groupByKey]: host },
+ timestamp: new Date(now - (pointsPerHost - p) * 20 * 1000).toISOString(),
+ value: 10 + p,
+ type_: 'Gauge',
+ temporality: 'Unspecified',
+ is_monotonic: false,
+ });
+ }
+ }
+ await postTelemetry('/telemetry/metrics', points);
+ },
+ };
+
+ return seeder;
+}
diff --git a/tests/e2e/drivers/alerts/seeds.ts b/tests/e2e/drivers/alerts/seeds.ts
new file mode 100644
index 0000000000..7961aeb5cf
--- /dev/null
+++ b/tests/e2e/drivers/alerts/seeds.ts
@@ -0,0 +1,491 @@
+import type { Browser, Page, TestType } from '@playwright/test';
+
+import { onAdminPage, seeded, type Layer, type WorkerLayer } from '../kit';
+
+type Fixtures = Record<string, unknown>;
+
+import {
+ FIXTURE_ALERT_HISTORY_TIMEOUT,
+ FIXTURE_ALERT_LIST_TIMEOUT,
+ FIXTURE_EMPTY_HISTORY_TIMEOUT,
+ FIXTURE_METRICS_HISTORY_TIMEOUT,
+ FIXTURE_NODATA_HISTORY_TIMEOUT,
+ FIXTURE_RESOLVED_HISTORY_TIMEOUT,
+ FIXTURE_TRACES_HISTORY_TIMEOUT,
+ WAIT_METRICS_TIMELINE_TIMEOUT,
+ WAIT_NODATA_TIMELINE_TIMEOUT,
+} from './timeouts';
+import { alertsDriver } from './driver';
+
+/**
+ * Worker-scoped alert seeds.
+ *
+ * Every history row has to come from the ruler actually evaluating a rule —
+ * there is no seeder endpoint for `rule_state_history_v0` — so each history seed
+ * pays a real wait: ~20-35 s for logs, ~10 s for metrics, ~105 s for
+ * firing→resolved. Worker scope means one wait per worker rather than one per
+ * test, and Playwright builds fixtures lazily, so a spec that never asks for
+ * `resolvedHistory` never pays its 105 s.
+ *
+ * Rules seeded here are **frozen** (disabled) as soon as their firing wave
+ * lands. Rows are written on state change, so an active rule resolves once the
+ * eval window rolls past the seeded records and doubles `total` mid-suite.
+ */
+
+/** Anything a seed teardown has to remove. */
+interface Owned {
+ ruleIds: string[];
+ channelId: string;
+}
+
+async function drop(page: Page, { ruleIds, channelId }: Owned): Promise<void> {
+ const { seed } = alertsDriver(page);
+ await seed.deleteRules(ruleIds);
+ await seed.deleteChannel(channelId);
+}
+
+// ─── Rules ───────────────────────────────────────────────────────────────────
+
+export interface AlertChannelSeed {
+ id: string;
+ name: string;
+}
+
+/** Every rule payload references a channel by name; one serves the whole worker. */
+export const withAlertChannel: WorkerLayer<{ alertChannel: AlertChannelSeed }> =
+ seeded(
+ 'alertChannel',
+ async ({ page, workerIndex }) =>
+ alertsDriver(page).seed.channel(
+ `e2e-alerts-ch-w${workerIndex}-${Date.now()}`,
+ ),
+ async ({ page, value }) => alertsDriver(page).seed.deleteChannel(value.id),
+ );
+
+export interface AlertListSeed extends Owned {
+ channelName: string;
+ /** Rules are named `<namePrefix>-NN`, unique to this worker's batch. */
+ namePrefix: string;
+ /** Rules seeded ⇒ the `of N` total once the list is scoped to the prefix. */
+ count: number;
+ /** `team` label on the odd-indexed half of the batch, i.e. `count / 2` rules. */
+ paymentsLabel: string;
+}
+
+/** 12 rules over page size 10 leaves a short second page for pagination. */
+const LIST_SEED_COUNT = 12;
+
+/**
+ * A read-only batch of rules the list specs page, search and sort through. Names
+ * and label values are stamped per worker so parallel batches never count each
+ * other's rules.
+ */
+export const withAlertList: WorkerLayer<{ alertList: AlertListSeed }> = seeded(
+ 'alertList',
+ async ({ page, workerIndex }) => {
+ const { seed } = alertsDriver(page);
+ const stamp = `w${workerIndex}-${Date.now()}`;
+ const namePrefix = `e2e-alert-list-${stamp}`;
+ const channel = await seed.channel(`e2e-alerts-ch-${stamp}`);
+ const ruleIds = await seed.rules({
+ count: LIST_SEED_COUNT,
+ channelName: channel.name,
+ namePrefix,
+ teamSuffix: `-${stamp}`,
+ });
+ return {
+ channelName: channel.name,
+ namePrefix,
+ count: LIST_SEED_COUNT,
+ paymentsLabel: `payments-${stamp}`,
+ ruleIds,
+ channelId: channel.id,
+ };
+ },
+ async ({ page, value }) => drop(page, value),
+ { timeout: FIXTURE_ALERT_LIST_TIMEOUT },
+);
+
+// ─── History ─────────────────────────────────────────────────────────────────
+
+export interface AlertHistorySeed extends Owned {
+ /** v2 (`schemaVersion: v2alpha1`) rule — the default history subject. */
+ ruleId: string;
+ /** Legacy v1 rule over the same logs. Its `threshold.name` is `warning`. */
+ ruleIdV1: string;
+ channelName: string;
+ /** The `body CONTAINS` marker both rules match. */
+ marker: string;
+ services: string[];
+ total: number;
+ totalV1: number;
+}
+
+/** 25 services yields a multi-page timeline, which is what pagination needs. */
+const LOGS_HISTORY_SERVICES = 25;
+/** 3 services with a 1m window resolve in ~105 s. */
+const RESOLVED_HISTORY_SERVICES = 3;
+/** 2 hosts fit one page and carry no related-logs links. */
+const METRICS_HISTORY_HOSTS = ['host-0', 'host-1'];
+const TRACES_HISTORY_SERVICES = 3;
+
+/** Team label for the v1 rule, so its header labels row is non-empty. */
+export const V1_RULE_TEAM_LABEL = 'e2e-platform';
+
+export const withAlertHistory: WorkerLayer<{ alertHistory: AlertHistorySeed }> =
+ seeded(
+ 'alertHistory',
+ async ({ page }) => {
+ const { seed, history } = alertsDriver(page);
+ const stamp = Date.now();
+ const marker = `e2e alert history ${stamp}`;
+ const channel = await seed.channel(`e2e-ah-ch-${stamp}`);
+
+ const services = await seed.logs({
+ marker,
+ services: LOGS_HISTORY_SERVICES,
+ servicePrefix: 'e2e-ah-svc',
+ });
+
+ const ruleId = await seed.logsRule({
+ name: `e2e-ah-rule-v2-${stamp}`,
+ marker,
+ channels: [channel.name],
+ schema: 'v2',
+ });
+ const ruleIdV1 = await seed.logsRule({
+ name: `e2e-ah-rule-v1-${stamp}`,
+ marker,
+ channels: [channel.name],
+ schema: 'v1',
+ extraLabels: { team: V1_RULE_TEAM_LABEL },
+ });
+
+ await history.waitForEntries(ruleId, { min: LOGS_HISTORY_SERVICES });
+ await history.waitForEntries(ruleIdV1, { min: LOGS_HISTORY_SERVICES });
+ await seed.setDisabled(ruleId, true);
+ await seed.setDisabled(ruleIdV1, true);
+
+ const total = await history.readTotal(ruleId);
+ if (total !== LOGS_HISTORY_SERVICES) {
+ throw new Error(
+ `alertHistory expected ${LOGS_HISTORY_SERVICES} timeline rows, got ${total}`,
+ );
+ }
+
+ return {
+ ruleId,
+ ruleIdV1,
+ channelName: channel.name,
+ marker,
+ services,
+ total,
+ totalV1: await history.readTotal(ruleIdV1),
+ ruleIds: [ruleId, ruleIdV1],
+ channelId: channel.id,
+ };
+ },
+ async ({ page, value }) => drop(page, value),
+ { timeout: FIXTURE_ALERT_HISTORY_TIMEOUT },
+ );
+
+export interface MetricsHistorySeed extends Owned {
+ ruleId: string;
+ channelName: string;
+ metricName: string;
+ hosts: string[];
+ total: number;
+}
+
+export const withMetricsHistory: WorkerLayer<{
+ metricsHistory: MetricsHistorySeed;
+}> = seeded(
+ 'metricsHistory',
+ async ({ page }) => {
+ const { seed, history } = alertsDriver(page);
+ const stamp = Date.now();
+ const metricName = `e2e_ah_probe_metric_${stamp}`;
+ const channel = await seed.channel(`e2e-ah-metrics-ch-${stamp}`);
+
+ await seed.metrics({ metricName, hosts: METRICS_HISTORY_HOSTS });
+ const ruleId = await seed.metricRule({
+ name: `e2e-ah-metrics-rule-${stamp}`,
+ metricName,
+ channels: [channel.name],
+ });
+
+ await history.waitForEntries(ruleId, {
+ min: METRICS_HISTORY_HOSTS.length,
+ timeoutMs: WAIT_METRICS_TIMELINE_TIMEOUT,
+ });
+ await seed.setDisabled(ruleId, true);
+
+ return {
+ ruleId,
+ channelName: channel.name,
+ metricName,
+ hosts: METRICS_HISTORY_HOSTS,
+ total: await history.readTotal(ruleId),
+ ruleIds: [ruleId],
+ channelId: channel.id,
+ };
+ },
+ async ({ page, value }) => drop(page, value),
+ { timeout: FIXTURE_METRICS_HISTORY_TIMEOUT },
+);
+
+export interface TracesHistorySeed extends Owned {
+ ruleId: string;
+ channelName: string;
+ /** The span `name` the rule matches (`name = '<marker>'`). */
+ marker: string;
+ services: string[];
+ total: number;
+}
+
+export const withTracesHistory: WorkerLayer<{
+ tracesHistory: TracesHistorySeed;
+}> = seeded(
+ 'tracesHistory',
+ async ({ page }) => {
+ const { seed, history } = alertsDriver(page);
+ const stamp = Date.now();
+ const marker = `e2e-aht-span-${stamp}`;
+ const channel = await seed.channel(`e2e-ah-traces-ch-${stamp}`);
+
+ const services = await seed.traces({
+ marker,
+ services: TRACES_HISTORY_SERVICES,
+ servicePrefix: 'e2e-aht-svc',
+ });
+ const ruleId = await seed.tracesRule({
+ name: `e2e-ah-traces-rule-${stamp}`,
+ marker,
+ channels: [channel.name],
+ });
+
+ await history.waitForEntries(ruleId, { min: TRACES_HISTORY_SERVICES });
+ await seed.setDisabled(ruleId, true);
+
+ return {
+ ruleId,
+ channelName: channel.name,
+ marker,
+ services,
+ total: await history.readTotal(ruleId),
+ ruleIds: [ruleId],
+ channelId: channel.id,
+ };
+ },
+ async ({ page, value }) => drop(page, value),
+ { timeout: FIXTURE_TRACES_HISTORY_TIMEOUT },
+);
+
+export interface ResolvedHistorySeed extends Owned {
+ ruleId: string;
+ channelName: string;
+ marker: string;
+ services: string[];
+ /** Rows in `firing` — equals `stats.totalCurrentTriggers`. */
+ firingCount: number;
+ /** Rows in `inactive`, i.e. what the Resolved filter shows. */
+ resolvedCount: number;
+}
+
+export const withResolvedHistory: WorkerLayer<{
+ resolvedHistory: ResolvedHistorySeed;
+}> = seeded(
+ 'resolvedHistory',
+ async ({ page }) => {
+ const { seed, history } = alertsDriver(page);
+ const stamp = Date.now();
+ const marker = `e2e alert resolved ${stamp}`;
+ const channel = await seed.channel(`e2e-ah-resolved-ch-${stamp}`);
+
+ const services = await seed.logs({
+ marker,
+ services: RESOLVED_HISTORY_SERVICES,
+ ageSeconds: 40,
+ minAgeSeconds: 28,
+ servicePrefix: 'e2e-ahr-svc',
+ });
+ const ruleId = await seed.logsRule({
+ name: `e2e-ah-resolved-rule-${stamp}`,
+ marker,
+ channels: [channel.name],
+ evalWindow: '1m0s',
+ });
+
+ const timeline = await history.waitForStates(ruleId, {
+ states: {
+ firing: RESOLVED_HISTORY_SERVICES,
+ inactive: RESOLVED_HISTORY_SERVICES,
+ },
+ });
+ await seed.setDisabled(ruleId, true);
+
+ return {
+ ruleId,
+ channelName: channel.name,
+ marker,
+ services,
+ firingCount: timeline.items.filter((item) => item.state === 'firing').length,
+ resolvedCount: timeline.items.filter((item) => item.state === 'inactive')
+ .length,
+ ruleIds: [ruleId],
+ channelId: channel.id,
+ };
+ },
+ async ({ page, value }) => drop(page, value),
+ { timeout: FIXTURE_RESOLVED_HISTORY_TIMEOUT },
+);
+
+export interface RuleSeed extends Owned {
+ ruleId: string;
+ channelName: string;
+}
+
+export const withNoDataHistory: WorkerLayer<{ noDataHistory: RuleSeed }> =
+ seeded(
+ 'noDataHistory',
+ async ({ page }) => {
+ const { seed, history } = alertsDriver(page);
+ const stamp = Date.now();
+ const channel = await seed.channel(`e2e-ah-nodata-ch-${stamp}`);
+ const ruleId = await seed.noDataRule({
+ name: `e2e-ah-nodata-rule-${stamp}`,
+ marker: `e2e alert nodata ${stamp}`,
+ channels: [channel.name],
+ });
+
+ await history.waitForEntries(ruleId, {
+ min: 1,
+ state: 'nodata',
+ timeoutMs: WAIT_NODATA_TIMELINE_TIMEOUT,
+ });
+ await seed.setDisabled(ruleId, true);
+
+ return {
+ ruleId,
+ channelName: channel.name,
+ ruleIds: [ruleId],
+ channelId: channel.id,
+ };
+ },
+ async ({ page, value }) => drop(page, value),
+ { timeout: FIXTURE_NODATA_HISTORY_TIMEOUT },
+ );
+
+/** A rule that never fires, for the "no history yet" empty state. */
+export const withEmptyHistory: WorkerLayer<{ emptyHistory: RuleSeed }> = seeded(
+ 'emptyHistory',
+ async ({ page }) => {
+ const { seed } = alertsDriver(page);
+ const stamp = Date.now();
+ const channel = await seed.channel(`e2e-ah-empty-ch-${stamp}`);
+ const ruleId = await seed.logsRule({
+ name: `e2e-ah-empty-rule-${stamp}`,
+ marker: `e2e alert never seeded ${stamp}`,
+ channels: [channel.name],
+ });
+ await seed.setDisabled(ruleId, true);
+
+ return {
+ ruleId,
+ channelName: channel.name,
+ ruleIds: [ruleId],
+ channelId: channel.id,
+ };
+ },
+ async ({ page, value }) => drop(page, value),
+ { timeout: FIXTURE_EMPTY_HISTORY_TIMEOUT },
+);
+
+// ─── Rules a single test owns ────────────────────────────────────────────────
+
+export interface OwnedRules {
+ /** Seed a metric threshold rule this test owns. */
+ threshold(name: string, overrides?: Record<string, unknown>): Promise<string>;
+ /**
+ * Seed a logs rule this test owns. No telemetry is seeded for its marker, so
+ * it never fires — enough for anything about the details shell.
+ */
+ logs(options: {
+ name: string;
+ schema?: 'v1' | 'v2';
+ marker?: string;
+ severity?: string;
+ extraLabels?: Record<string, string>;
+ evalWindow?: string;
+ target?: number;
+ op?: string;
+ matchType?: string;
+ }): Promise<string>;
+ /**
+ * Track a rule the *app* created (Clone) so teardown removes it
+ * too. Lives here because the id may legitimately be missing, and a
+ * conditional inside a test body is a lint error.
+ */
+ register(response: { json: () => Promise<unknown> }): Promise<void>;
+}
+
+/**
+ * Test-scoped, because a scenario that renames, toggles, clones or deletes a
+ * rule must not mutate a shared seed: everything scheduled after it would break.
+ */
+export const withOwnedRules: Layer<{ ownedRules: OwnedRules }> = ((
+ test: TestType<Fixtures, Fixtures>,
+) =>
+ test.extend({
+ ownedRules: async (
+ {
+ browser,
+ alertChannel,
+ }: { browser: Browser; alertChannel: AlertChannelSeed },
+ use: (value: OwnedRules) => Promise<void>,
+ ) => {
+ const ids = new Set<string>();
+ const create = async (
+ body: (page: Page) => Promise<string>,
+ ): Promise<string> => {
+ const id = await onAdminPage(browser, body);
+ ids.add(id);
+ return id;
+ };
+
+ await use({
+ threshold: (name, overrides = {}) =>
+ create((page) =>
+ alertsDriver(page).seed.threshold({
+ name,
+ target: 42,
+ channels: [alertChannel.name],
+ labels: { severity: 'critical' },
+ ...overrides,
+ }),
+ ),
+
+ logs: ({ name, schema = 'v2', marker, ...overrides }) =>
+ create((page) =>
+ alertsDriver(page).seed.logsRule({
+ name,
+ marker: marker ?? `e2e alert never seeded ${name}`,
+ channels: [alertChannel.name],
+ schema,
+ ...overrides,
+ }),
+ ),
+
+ register: async (response) => {
+ const body = (await response.json()) as { data?: { id?: string } };
+ if (body.data?.id) {
+ ids.add(String(body.data.id));
+ }
+ },
+ });
+
+ await onAdminPage(browser, (page) =>
+ alertsDriver(page).seed.deleteRules([...ids]),
+ );
+ },
+ }) as never) as Layer<{ ownedRules: OwnedRules }>;
diff --git a/tests/e2e/fixtures/alerts/timeouts.ts b/tests/e2e/drivers/alerts/timeouts.ts
similarity index 100%
rename from tests/e2e/fixtures/alerts/timeouts.ts
rename to tests/e2e/drivers/alerts/timeouts.ts
diff --git a/tests/e2e/helpers/alerts/types.ts b/tests/e2e/drivers/alerts/types.ts
similarity index 100%
rename from tests/e2e/helpers/alerts/types.ts
rename to tests/e2e/drivers/alerts/types.ts
diff --git a/tests/e2e/drivers/antd.ts b/tests/e2e/drivers/antd.ts
new file mode 100644
index 0000000000..afe225ee90
--- /dev/null
+++ b/tests/e2e/drivers/antd.ts
@@ -0,0 +1,96 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+/**
+ * antd select primitives, shared by every feature that drives one.
+ *
+ * antd keeps previously-opened dropdowns in the DOM under
+ * `.ant-select-dropdown-hidden`, and applies that class only *after* the close
+ * transition — so "the open dropdown" is ambiguous whenever two selects of the
+ * same kind sit next to each other. {@link Antd.ownDropdown} resolves the one a
+ * specific select owns, through the combobox's `aria-controls`.
+ */
+
+export interface Antd {
+ /** An antd multi-select's chosen values. */
+ selectedTags(scope: Locator): Locator;
+ openDropdown(): Locator;
+ ownDropdown(select: Locator): Promise<Locator>;
+ /** An option in the open dropdown, matched on its **exact** label —
+ * substring matching would make `EQUAL TO` also match `NOT EQUAL TO`. */
+ option(label: string): Locator;
+ optionLabels(): Promise<string[]>;
+ /** Open `select`, search for `name`, pick it, and close. */
+ pickByName(select: Locator, name: string): Promise<void>;
+}
+
+export function antdDriver(page: Page): Antd {
+ const antd: Antd = {
+ selectedTags: (scope) => scope.locator('.ant-select-selection-item-content'),
+
+ openDropdown: () =>
+ page.locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden)'),
+
+ ownDropdown: async (select) => {
+ const listId = await select
+ .locator('input[role="combobox"]')
+ .getAttribute('aria-controls');
+ if (!listId) {
+ throw new Error(
+ 'select has no aria-controls — not an antd combobox, or not yet opened',
+ );
+ }
+ return page
+ .locator('.ant-select-dropdown')
+ .filter({ has: page.locator(`[id="${listId}"]`) });
+ },
+
+ option: (label) =>
+ antd
+ .openDropdown()
+ .locator('.ant-select-item-option')
+ .filter({ has: page.getByText(label, { exact: true }) }),
+
+ optionLabels: async () =>
+ antd.openDropdown().locator('.ant-select-item-option').allInnerTexts(),
+
+ /**
+ * The list must be **searched**, not scrolled. Channel-style lists are
+ * global while their fixtures are worker-scoped, so a shared stack
+ * accumulates one entry per worker and antd virtualises the dropdown:
+ * measured at 31 channels, only 10 options exist in the DOM and the wanted
+ * one is simply not there. Clicking by name without filtering first is not
+ * a slow path, it is a missing element, and it was the single biggest
+ * source of flake in this suite.
+ */
+ pickByName: async (select, name) => {
+ const before = await antd.selectedTags(select).count();
+ await select.click();
+ await expect(select).toHaveClass(/ant-select-open/);
+
+ // `fill` rather than `keyboard.type`: every keystroke re-runs antd's
+ // filter, so typing a ~30 character name costs seconds per pick, while
+ // one input event is all rc-select's search needs.
+ await select.locator('input[role="combobox"]').fill(name);
+ const dropdown = await antd.ownDropdown(select);
+ await dropdown
+ .locator('.ant-select-item-option')
+ .filter({ hasText: name })
+ .first()
+ .click();
+
+ // A multi-select stays open after a pick and overlays the controls below.
+ await page.keyboard.press('Escape');
+ // Wait for *this* select to report itself closed: a caller that opens the
+ // next one immediately would otherwise race a still-visible stale list.
+ await expect(select).not.toHaveClass(/ant-select-open/);
+
+ // Fail here rather than three assertions later: a silently-missed pick
+ // surfaces as "Save is still disabled", which points at the validator.
+ // Counted, not name-matched — the tags are truncated or empty by design,
+ // so the name is verified in the request body where it matters.
+ await expect(antd.selectedTags(select)).toHaveCount(before + 1);
+ },
+ };
+
+ return antd;
+}
diff --git a/tests/e2e/drivers/api-monitoring.ts b/tests/e2e/drivers/api-monitoring.ts
new file mode 100644
index 0000000000..8c5cc66934
--- /dev/null
+++ b/tests/e2e/drivers/api-monitoring.ts
@@ -0,0 +1,274 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import {
+ allowFor,
+ driver,
+ kit,
+ seeded,
+ SEEDED_TEST_BUDGET,
+ type Layer,
+ type WorkerLayer,
+} from './kit';
+import { querySearchDriver, type QuerySearch } from './querysearch';
+import { clientCall, STATUS, stamp as stampFor } from './spans';
+import { seedTracesViaSeeder } from './traces';
+
+/**
+ * External API monitoring: the domain list and the domain drawer. A domain is a
+ * CLIENT span's `http.host`; an endpoint is its full `http.url`.
+ */
+
+const PATH = '/api-monitoring/explorer';
+const PARAM = 'apiMonitoringParams';
+
+export type DomainView = 'all_endpoints' | 'endpoint_stats' | 'top_errors';
+
+export interface ApiSeed {
+ stamp: string;
+ host: string;
+ /** Full URLs, as the drawer lists them. */
+ endpoints: { items: string; pay: string };
+ callers: { orders: string; billing: string };
+ errorMessage: string;
+ errorStatus: number;
+ /** Seeded CLIENT spans; the drawer's "External API" metric counts them. */
+ callCount: number;
+}
+
+/** Shape of the `apiMonitoringParams` URL param (`ApiMonitoring/queryParams.ts`). */
+interface ApiMonitoringParams {
+ showIP?: boolean;
+ selectedDomain?: string;
+ selectedView?: string;
+ selectedEndPointName?: string;
+ /** Epoch seconds. */
+ modalTimeRange?: { startTime: number; endTime: number };
+}
+
+export interface DomainDrawer {
+ root(): Locator;
+ title(): Locator;
+ metrics(): Locator;
+ /** The four metric values, in label order. */
+ metricValues(): Promise<string[]>;
+ view(view: DomainView): Promise<void>;
+ viewButton(view: DomainView): Locator;
+ endpointsTable(): Locator;
+ topErrorsTable(): Locator;
+ topErrorRow(endpoint: string): Locator;
+ /** The row's last column, its error count. */
+ topErrorCount(endpoint: string): Locator;
+ statusMessageToggle(): Locator;
+ dependentServices(): Locator;
+ statusCodeTable(): Locator;
+ statusCodeCell(code: string): Locator;
+ next(): Promise<void>;
+ prev(): Promise<void>;
+}
+
+export interface ApiMonitoring {
+ goto(params?: Record<string, string>): Promise<void>;
+ search: QuerySearch;
+ domainTable(): Locator;
+ emptyState(): Locator;
+ headers(): Promise<string[]>;
+ domainRow(host: string): Locator;
+ domainCell(host: string, header: string): Promise<Locator>;
+ /** Reload until `host` is listed: the list fetches once per load. */
+ waitForDomain(host: string): Promise<void>;
+ openDomain(host: string): Promise<void>;
+ /** Deep-link the drawer on `view`, with a modal range covering the last 15 m. */
+ gotoDomain(
+ host: string,
+ view: DomainView,
+ extra?: { endpoint?: string },
+ ): Promise<void>;
+ params(): ApiMonitoringParams;
+ drawer: DomainDrawer;
+}
+
+const normalise = (text: string): string => text.replace(/\s+/g, ' ').trim();
+
+export function apiMonitoringDriver(page: Page): ApiMonitoring {
+ const domainTable = (): Locator =>
+ page.getByTestId('api-monitoring-domain-table');
+ const emptyState = (): Locator =>
+ page.getByTestId('api-monitoring-empty-state');
+ const root = (): Locator => page.getByTestId('domain-details-drawer');
+
+ const headers = async (): Promise<string[]> =>
+ // Text content, not inner text: the headers are uppercased in CSS.
+ (await domainTable().getByRole('columnheader').allTextContents())
+ .map(normalise)
+ .filter(Boolean);
+
+ const readyList = async (): Promise<void> => {
+ await expect(domainTable().or(emptyState()).first()).toBeVisible();
+ };
+
+ const api: ApiMonitoring = {
+ search: querySearchDriver(page, { runTestId: 'explorer-run-query-btn' }),
+ domainTable,
+ emptyState,
+ headers,
+
+ goto: async (params = {}) => {
+ const query = new URLSearchParams({ relativeTime: '15m', ...params });
+ await page.goto(`${PATH}?${query.toString()}`);
+ await readyList();
+ },
+
+ domainRow: (host) => page.getByTestId(`domain-row-${host}`),
+
+ domainCell: async (host, header) => {
+ const index = (await headers()).indexOf(header);
+ if (index === -1) {
+ throw new Error(`domain table has no "${header}" column`);
+ }
+ return api.domainRow(host).getByRole('cell').nth(index);
+ },
+
+ waitForDomain: async (host) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(async () => {
+ await page.reload();
+ await expect(api.domainRow(host)).toBeVisible({ timeout: 5_000 });
+ }).toPass({ timeout: SEEDED_TEST_BUDGET - 15_000 });
+ },
+
+ openDomain: async (host) => {
+ await api.domainRow(host).click();
+ await expect(root()).toBeVisible();
+ await expect(api.drawer.title()).toHaveText(host);
+ },
+
+ gotoDomain: async (host, view, extra = {}) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ const nowS = Math.floor(Date.now() / 1000);
+ const params: ApiMonitoringParams = {
+ showIP: true,
+ selectedDomain: host,
+ selectedView: view,
+ selectedEndPointName: extra.endpoint ?? '',
+ modalTimeRange: { startTime: nowS - 15 * 60, endTime: nowS },
+ };
+ const query = new URLSearchParams({
+ relativeTime: '15m',
+ [PARAM]: encodeURIComponent(JSON.stringify(params)),
+ });
+ // The drawer opens only once the list response contains the domain, so
+ // a seed that is not queryable yet leaves it closed.
+ await expect(async () => {
+ await page.goto(`${PATH}?${query.toString()}`);
+ await expect(root()).toBeVisible({ timeout: 8_000 });
+ }).toPass({ timeout: SEEDED_TEST_BUDGET - 15_000 });
+ await expect(api.drawer.title()).toHaveText(host);
+ },
+
+ params: () => {
+ const raw = new URL(page.url()).searchParams.get(PARAM);
+ if (!raw) {
+ return {};
+ }
+ return JSON.parse(decodeURIComponent(raw)) as ApiMonitoringParams;
+ },
+
+ drawer: {
+ root,
+ title: () => page.getByTestId('domain-details-title'),
+ metrics: () => page.getByTestId('domain-metrics'),
+ metricValues: async () => {
+ const values = page.getByTestId('domain-metrics-values');
+ await expect(values.locator('.ant-skeleton')).toHaveCount(0);
+ return (await values.locator('> *').allInnerTexts()).map(normalise);
+ },
+ viewButton: (view) => page.getByTestId(`domain-view-${view}`),
+ view: async (view) => {
+ await api.drawer.viewButton(view).click();
+ await expect(async () => {
+ expect(api.params().selectedView).toBe(view);
+ }).toPass();
+ },
+ endpointsTable: () => root().getByRole('table').first(),
+ topErrorsTable: () => page.getByTestId('top-errors-table'),
+ // The table prints the endpoint's path, not its full URL.
+ topErrorRow: (endpoint) =>
+ api.drawer
+ .topErrorsTable()
+ .getByRole('row')
+ .filter({ hasText: new URL(endpoint).pathname }),
+ topErrorCount: (endpoint) =>
+ api.drawer.topErrorRow(endpoint).getByRole('cell').last(),
+ statusMessageToggle: () =>
+ page.getByTestId('top-errors-status-message-toggle'),
+ dependentServices: () => page.getByTestId('dependent-services-table'),
+ statusCodeTable: () => page.getByTestId('endpoint-status-code-table'),
+ statusCodeCell: (code) =>
+ api.drawer.statusCodeTable().getByRole('cell', { name: code, exact: true }),
+ next: async () => {
+ await root().getByRole('button', { name: 'Next domain' }).click();
+ },
+ prev: async () => {
+ await root().getByRole('button', { name: 'Previous domain' }).click();
+ },
+ },
+ };
+
+ return api;
+}
+
+export const withApiMonitoring: Layer<{ apiMonitoring: ApiMonitoring }> =
+ driver('apiMonitoring', ({ page }) => apiMonitoringDriver(page));
+
+/**
+ * Six CLIENT spans to one stamped host: four OK and one 503 on `/v1/items` from
+ * the orders service, one `POST /v1/pay` from billing. No teardown: telemetry
+ * has no scoped delete, and the host is unique to the worker.
+ */
+export const withApiSeed: WorkerLayer<{ apiSeed: ApiSeed }> = seeded(
+ 'apiSeed',
+ async ({ page, workerIndex }) => {
+ const stamp = stampFor('api', workerIndex);
+ const host = `${stamp}.example.com`;
+ const endpoints = {
+ items: `https://${host}/v1/items`,
+ pay: `https://${host}/v1/pay`,
+ };
+ const callers = { orders: `${stamp}-orders`, billing: `${stamp}-billing` };
+ const errorMessage = 'upstream 503';
+ const errorStatus = 503;
+ const spans = [
+ ...[50_000, 40_000, 30_000, 20_000].map((agoMs) =>
+ clientCall({ service: callers.orders, url: endpoints.items, agoMs }),
+ ),
+ clientCall({
+ service: callers.orders,
+ url: endpoints.items,
+ httpStatus: errorStatus,
+ status: STATUS.error,
+ statusMessage: errorMessage,
+ agoMs: 25_000,
+ }),
+ clientCall({
+ service: callers.billing,
+ url: endpoints.pay,
+ method: 'POST',
+ agoMs: 35_000,
+ }),
+ ];
+ await seedTracesViaSeeder(page.request, spans);
+ return {
+ stamp,
+ host,
+ endpoints,
+ callers,
+ errorMessage,
+ errorStatus,
+ callCount: spans.length,
+ };
+ },
+);
+
+/** The API monitoring `test`. */
+export const test = withApiSeed(withApiMonitoring(kit));
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/api.ts b/tests/e2e/drivers/api.ts
new file mode 100644
index 0000000000..2150fa9d2a
--- /dev/null
+++ b/tests/e2e/drivers/api.ts
@@ -0,0 +1,130 @@
+import type { APIResponse, Page } from '@playwright/test';
+
+import { storageKey } from './base-path';
+
+/**
+ * The authenticated HTTP client every seed and API assertion goes through.
+ *
+ * Auth is a JWT in localStorage, not a cookie, so `page.request.*` does not
+ * carry it on its own and every call needs the header attached by hand. One
+ * place to do that, and one place that turns a non-2xx into a message naming the
+ * method, the path and the body — a bare `res.json()` on a 400 reports as
+ * "Unexpected end of JSON input", which names nothing.
+ */
+
+/** The `{ data, status }` envelope every v1/v2 JSON endpoint here returns. */
+export interface Envelope<T> {
+ data: T;
+ status: string;
+}
+
+export interface Api {
+ get<T>(path: string): Promise<T>;
+ post<T>(path: string, data: unknown): Promise<T>;
+ patch<T>(path: string, data: unknown): Promise<T>;
+ put<T>(path: string, data: unknown): Promise<T>;
+ del(path: string): Promise<void>;
+ /** POST that returns `data.id` — the shape every create endpoint here uses. */
+ create(path: string, data: unknown): Promise<string>;
+ /** DELETE that tolerates a 404, for best-effort teardown. */
+ tryDel(path: string): Promise<void>;
+ token(): Promise<string>;
+}
+
+/**
+ * Read the app JWT from the context's stored auth state. No navigation needed:
+ * the storage state carries `AUTH_TOKEN` from the moment the context is created,
+ * so this works regardless of where the page currently is.
+ */
+export async function authToken(page: Page): Promise<string> {
+ const state = await page.context().storageState();
+ for (const origin of state.origins) {
+ const entry = origin.localStorage.find(
+ (item) => item.name === storageKey('AUTH_TOKEN'),
+ );
+ if (entry) {
+ return entry.value;
+ }
+ }
+ throw new Error('AUTH_TOKEN not found in storage state — is the page authed?');
+}
+
+async function unwrap<T>(
+ method: string,
+ path: string,
+ response: Promise<APIResponse>,
+): Promise<T> {
+ const res = await response;
+ if (!res.ok()) {
+ throw new Error(`${method} ${path} ${res.status()}: ${await res.text()}`);
+ }
+ const text = await res.text();
+ return (text ? JSON.parse(text) : undefined) as T;
+}
+
+export function apiDriver(page: Page): Api {
+ const headers = async (): Promise<Record<string, string>> => ({
+ Authorization: `Bearer ${await authToken(page)}`,
+ });
+
+ const api: Api = {
+ token: () => authToken(page),
+
+ get: async <T>(path: string) =>
+ unwrap<T>('GET', path, page.request.get(path, { headers: await headers() })),
+
+ post: async <T>(path: string, data: unknown) =>
+ unwrap<T>(
+ 'POST',
+ path,
+ page.request.post(path, { data, headers: await headers() }),
+ ),
+
+ patch: async <T>(path: string, data: unknown) =>
+ unwrap<T>(
+ 'PATCH',
+ path,
+ page.request.patch(path, { data, headers: await headers() }),
+ ),
+
+ put: async <T>(path: string, data: unknown) =>
+ unwrap<T>(
+ 'PUT',
+ path,
+ page.request.put(path, { data, headers: await headers() }),
+ ),
+
+ del: async (path: string) => {
+ await unwrap<unknown>(
+ 'DELETE',
+ path,
+ page.request.delete(path, { headers: await headers() }),
+ );
+ },
+
+ tryDel: async (path: string) => {
+ await page.request.delete(path, { headers: await headers() });
+ },
+
+ create: async (path: string, data: unknown) => {
+ const body = await api.post<{ data: { id: string | number } }>(path, data);
+ return String(body.data.id);
+ },
+ };
+
+ return api;
+}
+
+/**
+ * Base URL of the HTTP seeder container the pytest harness brings up. Written to
+ * `.env.local` by `bootstrap/setup.py`.
+ */
+export function seederUrl(): string {
+ const url = process.env.SIGNOZ_E2E_SEEDER_URL;
+ if (!url) {
+ throw new Error(
+ 'SIGNOZ_E2E_SEEDER_URL not set — pytest test_setup must be running.',
+ );
+ }
+ return url;
+}
diff --git a/tests/e2e/drivers/apm.ts b/tests/e2e/drivers/apm.ts
new file mode 100644
index 0000000000..d89019123f
--- /dev/null
+++ b/tests/e2e/drivers/apm.ts
@@ -0,0 +1,395 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import {
+ allowFor,
+ driver,
+ kit,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ seeded,
+ type ConsoleWatch,
+ type Layer,
+ type WorkerLayer,
+} from './kit';
+import { childSpan, rootSpan, SPAN_KIND, stamp, STATUS } from './spans';
+import { seedTracesViaSeeder, type SeederSpan } from './traces';
+
+/**
+ * APM: the services list, a service's detail tabs, its top-level operations
+ * page and the service map.
+ *
+ * `use_span_metrics` is off by default, so every page here reads spans: the
+ * services list and Key Operations come from `/api/v2/services` and
+ * `/api/v2/service/{top,entry_point}_operations`, scoped to root spans. The
+ * Rate, Error % and Apdex panels query span metrics that nothing seeds, so
+ * specs assert they render, not their values.
+ */
+
+export const SERVICE_TAB = {
+ Overview: 'OVER_METRICS',
+ 'DB Call Metrics': 'DB_CALL_METRICS',
+ 'External Metrics': 'EXTERNAL_METRICS',
+} as const;
+
+export type ServiceTab = keyof typeof SERVICE_TAB;
+
+/**
+ * Known application defect: `/metric/metric_metadata` answers 500, not 404, for
+ * a metric the stack never ingested. The Overview's Apdex panel asks for
+ * `signoz_latency.bucket`, which the seeder does not emit.
+ */
+export const MISSING_METADATA = '/metric/metric_metadata';
+
+/**
+ * `noise` without the {@link MISSING_METADATA} 500: the failed response, its
+ * failed load, and the axios error the DB Call and External tabs log for it,
+ * which names no URL. The response always arrives before axios rejects.
+ */
+export function withoutMissingMetadata(noise: ConsoleWatch): ConsoleWatch {
+ const known = (entry: string): boolean => entry.includes(MISSING_METADATA);
+ const failedResponses = noise.failedResponses.filter((entry) => !known(entry));
+ const seen = failedResponses.length < noise.failedResponses.length;
+ return {
+ failedResponses,
+ errors: noise.errors.filter(
+ (entry) =>
+ !known(entry) &&
+ !(seen && entry.includes('Request failed with status code 500')),
+ ),
+ };
+}
+
+export const OVERVIEW_PANELS = [
+ 'service_latency',
+ 'operations_per_sec',
+ 'error_percentage_%',
+ 'apdex',
+] as const;
+
+export const DB_PANELS = [
+ 'database_call_rps',
+ 'database_call_avg_duration',
+] as const;
+
+export const EXTERNAL_PANELS = [
+ 'external_call_error_percentage',
+ 'external_call_duration',
+ 'external_call_rps_by_address',
+ 'external_call_duration_by_address',
+] as const;
+
+const RELATIVE_TIME = '15m';
+const PANEL_ERROR_TEXT = 'Something went wrong';
+
+// ─── Seed ────────────────────────────────────────────────────────────────────
+
+export interface ApmSeed {
+ stamp: string;
+ /** Six root spans, one of them an error. */
+ service: string;
+ /** Called once by `service`, in the same insert, so the MVs can join them. */
+ downstream: string;
+ entryOp: 'POST /checkout';
+ ops: {
+ checkout: { name: 'POST /checkout'; calls: 4; errors: 1 };
+ cart: { name: 'GET /cart'; calls: 2; errors: 0 };
+ };
+ /** `numErrors * 100 / numCalls` over the root spans, as the list renders it. */
+ errorRate: string;
+}
+
+export function buildApmSpans(prefix: string): {
+ seed: ApmSeed;
+ spans: SeederSpan[];
+} {
+ const service = `${prefix}-checkout`;
+ const downstream = `${prefix}-payment`;
+ const checkouts = [50_000, 40_000, 30_000, 20_000].map((agoMs, index) =>
+ rootSpan({
+ service,
+ name: 'POST /checkout',
+ status: index === 0 ? STATUS.error : STATUS.ok,
+ durationMs: 120,
+ agoMs,
+ }),
+ );
+ const carts = [45_000, 15_000].map((agoMs) =>
+ rootSpan({ service, name: 'GET /cart', durationMs: 80, agoMs }),
+ );
+ const charge = childSpan(checkouts[1], {
+ service: downstream,
+ name: 'charge',
+ kind: SPAN_KIND.server,
+ durationMs: 40,
+ offsetMs: 20,
+ });
+
+ return {
+ spans: [...checkouts, ...carts, charge],
+ seed: {
+ stamp: prefix,
+ service,
+ downstream,
+ entryOp: 'POST /checkout',
+ ops: {
+ checkout: { name: 'POST /checkout', calls: 4, errors: 1 },
+ cart: { name: 'GET /cart', calls: 2, errors: 0 },
+ },
+ errorRate: ((1 * 100) / 6).toFixed(2),
+ },
+ };
+}
+
+export const withApmSeed: WorkerLayer<{ apmSeed: ApmSeed }> = seeded(
+ 'apmSeed',
+ async ({ page, workerIndex }) => {
+ const { seed, spans } = buildApmSpans(stamp('apm', workerIndex));
+ await seedTracesViaSeeder(page.request, spans);
+ return seed;
+ },
+);
+
+// ─── Driver ──────────────────────────────────────────────────────────────────
+
+export interface ServiceMapEdge {
+ parent: string;
+ child: string;
+ callCount: number;
+}
+
+export interface KeyOperations {
+ root(): Locator;
+ /** "Key Operations" or "Key Entrypoint Operations". */
+ title(): Locator;
+ rows(): Locator;
+ row(opName: string): Locator;
+ cell(opName: string, header: string): Promise<string>;
+ /** Flip the Entrypoint Spans switch and resolve with the response rows. */
+ toggleEntrypoint(): Promise<unknown[]>;
+}
+
+export interface Apm {
+ gotoServices(): Promise<void>;
+ servicesTable(): Locator;
+ serviceRow(name: string): Locator;
+ /** Narrow the list with the Application column's search box. */
+ searchService(name: string): Promise<void>;
+ /** Reload and search until the row renders: the list fetches once. */
+ waitForService(name: string): Promise<void>;
+ headers(): Promise<string[]>;
+ /** A row's cell texts keyed by header text. */
+ rowCells(name: string): Promise<Record<string, string>>;
+ openService(name: string): Promise<void>;
+ gotoService(name: string, tab?: ServiceTab): Promise<void>;
+ tab(name: ServiceTab): Locator;
+ openTab(name: ServiceTab): Promise<void>;
+ panel(testId: string): Locator;
+ /** Visible, and not showing the panel's error text. */
+ expectPanelRendered(testId: string): Promise<void>;
+ keyOps: KeyOperations;
+ /** Click an operation name; resolves once the traces explorer has loaded. */
+ openKeyOp(opName: string): Promise<void>;
+ /** Traces explorer list rows, after `openKeyOp`. */
+ explorerRows(): Locator;
+ /** The span-name cell of every explorer row. */
+ explorerRowNames(): Locator;
+ gotoTopLevelOps(name: string): Promise<void>;
+ topLevelOpsTable(): Locator;
+ servicesBreadcrumb(): Locator;
+ /** Open the map and resolve with the dependency graph the page received. */
+ gotoServiceMap(): Promise<ServiceMapEdge[]>;
+ /** Reopen the map until its dependency graph has the `parent -> child` edge. */
+ waitForServiceMapEdge(parent: string, child: string): Promise<void>;
+ serviceMap: { root(): Locator; canvas(): Locator; empty(): Locator };
+}
+
+async function cellsByHeader(
+ scope: Locator,
+ row: Locator,
+): Promise<Record<string, string>> {
+ const headers = (await scope.locator('thead th').allInnerTexts()).map((text) =>
+ text.trim(),
+ );
+ const cells = (await row.locator('td').allInnerTexts()).map((text) =>
+ text.trim(),
+ );
+ return Object.fromEntries(
+ headers.map((header, i) => [header, cells[i] ?? '']),
+ );
+}
+
+export function apmDriver(page: Page): Apm {
+ const servicesTable = (): Locator => page.getByTestId('services-table');
+ const serviceRow = (name: string): Locator =>
+ servicesTable().locator(`tbody tr[data-row-key="${name}"]`);
+ const keyOpsRoot = (): Locator => page.getByTestId('top-operations');
+ const keyOpRow = (opName: string): Locator =>
+ keyOpsRoot().locator(`tbody tr[data-row-key="${opName}"]`);
+
+ const keyOps: KeyOperations = {
+ root: keyOpsRoot,
+ title: () => keyOpsRoot().locator('.ant-table-title'),
+ rows: () => keyOpsRoot().locator('tbody tr[data-row-key]'),
+ row: keyOpRow,
+ cell: async (opName, header) => {
+ await expect(keyOpRow(opName)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ const cells = await cellsByHeader(keyOpsRoot(), keyOpRow(opName));
+ if (!(header in cells)) {
+ throw new Error(
+ `Key Operations has no "${header}" column: ${Object.keys(cells).join(', ')}`,
+ );
+ }
+ return cells[header];
+ },
+ toggleEntrypoint: async () => {
+ const response = page.waitForResponse(
+ (res) =>
+ res.url().includes('/service/entry_point_operations') &&
+ res.request().method() === 'POST',
+ );
+ await page.getByTestId('top-operations-entrypoint-toggle').click();
+ const res = await response;
+ expect(res.ok()).toBe(true);
+ const body = (await res.json()) as { data?: unknown[] | null };
+ return body.data ?? [];
+ },
+ };
+
+ const apm: Apm = {
+ servicesTable,
+ serviceRow,
+ keyOps,
+
+ gotoServices: async () => {
+ await page.goto(`/services?relativeTime=${RELATIVE_TIME}`);
+ await expect(servicesTable()).toBeVisible();
+ },
+
+ searchService: async (name) => {
+ const header = servicesTable().locator('thead th').first();
+ await header.locator('.ant-table-filter-trigger').click();
+ const input = page.getByPlaceholder('Search by service');
+ await input.fill(name);
+ await input.press('Enter');
+ await expect(input).toBeHidden();
+ },
+
+ waitForService: async (name) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(async () => {
+ await apm.gotoServices();
+ await expect(servicesTable().locator('.ant-spin-spinning')).toHaveCount(0);
+ await apm.searchService(name);
+ await expect(serviceRow(name)).toBeVisible({ timeout: 5_000 });
+ }).toPass({ timeout: SEEDED_TEST_BUDGET - 10_000 });
+ },
+
+ headers: async () =>
+ (await servicesTable().locator('thead th').allInnerTexts())
+ .map((text) => text.trim())
+ .filter(Boolean),
+
+ rowCells: (name) => cellsByHeader(servicesTable(), serviceRow(name)),
+
+ openService: async (name) => {
+ await page.getByTestId(`service-link-${name}`).click();
+ await expect(page).toHaveURL(
+ new RegExp(`/services/${encodeURIComponent(name)}(\\?|$)`),
+ );
+ },
+
+ gotoService: async (name, tab) => {
+ const params = new URLSearchParams({ relativeTime: RELATIVE_TIME });
+ if (tab) {
+ params.set('tab', SERVICE_TAB[tab]);
+ }
+ await page.goto(`/services/${encodeURIComponent(name)}?${params}`);
+ await expect(apm.tab(tab ?? 'Overview')).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ },
+
+ tab: (name) => page.getByRole('tab', { name, exact: true }),
+
+ openTab: async (name) => {
+ await apm.tab(name).click();
+ await expect(page).toHaveURL(new RegExp(`tab=${SERVICE_TAB[name]}`));
+ await expect(apm.tab(name)).toHaveAttribute('aria-selected', 'true');
+ },
+
+ panel: (testId) => page.getByTestId(testId),
+
+ expectPanelRendered: async (testId) => {
+ const panel = apm.panel(testId);
+ await expect(panel).toBeVisible();
+ await expect(panel).not.toContainText(PANEL_ERROR_TEXT);
+ },
+
+ openKeyOp: async (opName) => {
+ await keyOpRow(opName).getByTestId('top-operation-link').click();
+ await expect(page).toHaveURL(/\/traces-explorer/);
+ },
+
+ explorerRows: () => page.locator('[data-testid^="traces-table-row-"]'),
+ explorerRowNames: () => apm.explorerRows().getByTestId('name'),
+
+ gotoTopLevelOps: async (name) => {
+ await page.goto(
+ `/services/${encodeURIComponent(name)}/top-level-operations?relativeTime=${RELATIVE_TIME}`,
+ );
+ },
+
+ topLevelOpsTable: () => page.getByTestId('top-level-operations-table'),
+
+ servicesBreadcrumb: () =>
+ page.locator('.top-level-operations-header').getByRole('link', {
+ name: 'services',
+ }),
+
+ gotoServiceMap: async () => {
+ const response = page.waitForResponse(
+ (res) =>
+ res.url().includes('/api/v1/dependency_graph') &&
+ res.request().method() === 'POST',
+ );
+ await page.goto(`/service-map?relativeTime=${RELATIVE_TIME}`);
+ const res = await response;
+ expect(res.ok()).toBe(true);
+ const body = (await res.json()) as
+ | ServiceMapEdge[]
+ | { data?: ServiceMapEdge[] | null }
+ | null;
+ if (Array.isArray(body)) {
+ return body;
+ }
+ return body?.data ?? [];
+ },
+
+ waitForServiceMapEdge: async (parent, child) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(async () => {
+ const edges = await apm.gotoServiceMap();
+ expect(edges).toContainEqual(expect.objectContaining({ parent, child }));
+ }).toPass({ timeout: SEEDED_TEST_BUDGET - 10_000 });
+ },
+
+ serviceMap: {
+ root: () => page.getByTestId('service-map'),
+ canvas: () => page.getByTestId('service-map').locator('canvas'),
+ empty: () => page.getByTestId('service-map-empty'),
+ },
+ };
+
+ return apm;
+}
+
+export const withApm: Layer<{ apm: Apm }> = driver('apm', ({ page }) =>
+ apmDriver(page),
+);
+
+/** The APM `test`: services, service detail, top-level operations, service map. */
+export const test = withApmSeed(withApm(kit));
+export { expect, SEEDED_DATA_TIMEOUT } from './kit';
diff --git a/tests/e2e/drivers/auth-flows.ts b/tests/e2e/drivers/auth-flows.ts
new file mode 100644
index 0000000000..069703443b
--- /dev/null
+++ b/tests/e2e/drivers/auth-flows.ts
@@ -0,0 +1,173 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import type { User } from './auth';
+import { storageKey } from './base-path';
+import { dashboardListDriver } from './dashboard-list';
+import { guestDriver, kit, type Layer } from './kit';
+import { withSettings } from './settings/driver';
+
+/**
+ * The logged-out flows: sign in, forgot password, set a password from a reset
+ * or invite link, sign out. Bound to `guestPage`, a context with no session, so
+ * signing in here never touches the worker's cached admin session.
+ */
+
+export interface AuthFlows {
+ goto(pathOrUrl: string): Promise<void>;
+ pathname(): string;
+ url(): URL;
+ reload(): Promise<void>;
+
+ gotoLogin(query?: string): Promise<void>;
+ expectOnLogin(): Promise<void>;
+ enterEmail(email: string): Promise<void>;
+ emailInput(): Locator;
+ enterPassword(password: string): Promise<void>;
+ submitPassword(): Promise<void>;
+ /** Sign in and wait for the app to leave `/login`. */
+ login(user: User): Promise<void>;
+ authError(): Locator;
+
+ forgotPasswordLink(): Locator;
+ /** Submit the forgot-password form; resolves with the POST's status. */
+ submitForgot(): Promise<number>;
+ forgotSuccess(): Locator;
+ backToLogin(): Promise<void>;
+
+ /** Fill both password fields on a reset/invite link and submit. */
+ setNewPassword(password: string): Promise<void>;
+ tokenError(): Locator;
+
+ /** The signed-in shell's user entry, which only renders once logged in. */
+ settingsNavItem(): Locator;
+ openUserMenu(): Promise<void>;
+ loggedInAs(): Locator;
+ signOut(): Promise<void>;
+ storedToken(): Promise<string | null>;
+ newDashboardButton(): Locator;
+ /** Open the dashboards list, search it for `title` and return the row. */
+ findDashboard(title: string): Promise<Locator>;
+}
+
+export function authFlowsDriver(page: Page): AuthFlows {
+ const flows: AuthFlows = {
+ goto: async (pathOrUrl) => {
+ await page.goto(pathOrUrl);
+ },
+ pathname: () => new URL(page.url()).pathname,
+ url: () => new URL(page.url()),
+ reload: async () => {
+ await page.reload();
+ },
+
+ gotoLogin: async (query) => {
+ await page.goto(query ? `/login?${query}` : '/login');
+ await expect(flows.emailInput()).toBeVisible();
+ },
+
+ expectOnLogin: async () => {
+ await page.waitForURL((url) => url.pathname === '/login');
+ await expect(flows.emailInput()).toBeVisible();
+ },
+
+ emailInput: () => page.getByTestId('email'),
+
+ enterEmail: async (email) => {
+ await flows.emailInput().fill(email);
+ await page.getByTestId('initiate_login').click();
+ await expect(page.getByTestId('password')).toBeVisible();
+ },
+
+ enterPassword: async (password) => {
+ await page.getByTestId('password').fill(password);
+ },
+
+ submitPassword: async () => {
+ await page.getByTestId('password_authn_submit').click();
+ },
+
+ login: async (user) => {
+ await flows.gotoLogin();
+ await flows.enterEmail(user.email);
+ await flows.enterPassword(user.password);
+ await flows.submitPassword();
+ await page.waitForURL((url) => !url.pathname.startsWith('/login'));
+ await expect(flows.settingsNavItem()).toBeVisible();
+ },
+
+ authError: () => page.getByTestId('auth-error'),
+
+ forgotPasswordLink: () => page.getByText('Forgot password?', { exact: true }),
+
+ submitForgot: async () => {
+ const sent = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/v2/factor_password/forgot',
+ );
+ await page.getByTestId('forgot-password-submit').click();
+ return (await sent).status();
+ },
+
+ forgotSuccess: () => page.getByRole('heading', { name: 'Check your email' }),
+
+ backToLogin: async () => {
+ await page.getByTestId('back-to-login').click();
+ await flows.expectOnLogin();
+ },
+
+ setNewPassword: async (password) => {
+ await page.getByTestId('password').fill(password);
+ await page.getByTestId('confirmPassword').fill(password);
+ await page.getByTestId('reset-password-submit').click();
+ await flows.expectOnLogin();
+ },
+
+ tokenError: () =>
+ page.getByRole('heading', {
+ name:
+ /Reset Password token is expired|Invalid Reset Link|Reset Link Unavailable/,
+ }),
+
+ settingsNavItem: () => page.getByTestId('settings-nav-item'),
+
+ openUserMenu: async () => {
+ await flows.settingsNavItem().click();
+ await expect(page.getByTestId('logout-nav-item')).toBeVisible();
+ },
+
+ loggedInAs: () => page.getByTestId('logged-in-as-nav-item'),
+
+ signOut: async () => {
+ await flows.openUserMenu();
+ await page.getByTestId('logout-nav-item').click();
+ await flows.expectOnLogin();
+ },
+
+ storedToken: () =>
+ page.evaluate((key) => localStorage.getItem(key), storageKey('AUTH_TOKEN')),
+
+ newDashboardButton: () => page.getByTestId('new-dashboard-cta'),
+
+ findDashboard: async (title) => {
+ const list = dashboardListDriver(page);
+ await list.open(title);
+ return list.rowTitle(title);
+ },
+ };
+
+ return flows;
+}
+
+export const withAuthFlows: Layer<{ authFlows: AuthFlows }> = guestDriver(
+ 'authFlows',
+ ({ page }) => authFlowsDriver(page),
+);
+
+/**
+ * The auth `test`: the guest flows, plus the settings driver on the admin page
+ * for the half of a flow an admin drives.
+ */
+export const test = withAuthFlows(withSettings(kit));
+export { ADMIN, expect } from './kit';
+export { E2E_PASSWORD } from './users';
diff --git a/tests/e2e/helpers/auth.ts b/tests/e2e/drivers/auth.ts
similarity index 98%
rename from tests/e2e/helpers/auth.ts
rename to tests/e2e/drivers/auth.ts
index b1db6b38a5..3904f1fbeb 100644
--- a/tests/e2e/helpers/auth.ts
+++ b/tests/e2e/drivers/auth.ts
@@ -111,7 +111,7 @@ export function storageStateFor(
/**
* Build an authenticated admin `BrowserContext`. Used by suite hooks
* (`test.beforeAll` / `test.afterAll`) and worker-scoped fixtures, where the
- * test-scoped `authedPage` fixture from `fixtures/auth.ts` is not reachable.
+ * test-scoped `authedPage` fixture the kit provides is not reachable.
*
* Reuses this worker's cached session, so only the first call in a worker pays
* for a login. The caller owns the context and must close it.
diff --git a/tests/e2e/helpers/base-path.ts b/tests/e2e/drivers/base-path.ts
similarity index 100%
rename from tests/e2e/helpers/base-path.ts
rename to tests/e2e/drivers/base-path.ts
diff --git a/tests/e2e/drivers/channels.ts b/tests/e2e/drivers/channels.ts
index d8f1ce3bb6..7e4ad5a64b 100644
--- a/tests/e2e/drivers/channels.ts
+++ b/tests/e2e/drivers/channels.ts
@@ -4,7 +4,7 @@
*/
import { expect, type Locator, type Page } from '@playwright/test';
-import { authToken } from '../helpers/common';
+import { authToken } from './api';
import { driver, kit, seeded } from './kit';
diff --git a/tests/e2e/drivers/console.ts b/tests/e2e/drivers/console.ts
new file mode 100644
index 0000000000..6e9f2726f1
--- /dev/null
+++ b/tests/e2e/drivers/console.ts
@@ -0,0 +1,131 @@
+import type { Page, Request } from '@playwright/test';
+
+/**
+ * Console and network noise, and how to tell it from a real failure.
+ *
+ * Text matching alone is a weak signal: the harness's Zeus 404 reaches the
+ * console three ways, all generic. The failed-response list is the precise half,
+ * which is why the URL deny-list stays strict while the text one stays loose.
+ */
+
+// Requests the bootstrap stack always fails, on every page, for reasons that
+// have nothing to do with the feature under test.
+const HARNESS_FAILING_REQUESTS = [
+ // Zeus is the cloud control plane, not part of the binary this stack runs, so
+ // the app shell's workspace-URL lookup 404s on every page load.
+ '/api/v2/zeus/',
+ // The app shell polls GitHub for the latest release; unauthenticated calls
+ // from CI get rate-limited.
+ 'api.github.com',
+];
+
+const HARNESS_CONSOLE_NOISE = [
+ 'Failed to load resource: the server responded with a status of 404 (Not Found)',
+ 'Failed to load resource: the server responded with a status of 403',
+ 'Request failed with status code 404',
+ // `ErrorResponseHandler` logs these for any axios failure, including the
+ // requests the app cancels itself when a component unmounts.
+ 'client never received a response, or request never left',
+ 'ErrorResponseHandler: unclassified error',
+ // Google Fonts, which the chromium project fails at DNS (playwright.config.ts).
+ 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED',
+];
+
+export interface ConsoleWatch {
+ /**
+ * Console `error` entries and uncaught page errors, harness noise removed.
+ * A failed resource load ends with its URL.
+ */
+ errors: string[];
+ /** `"<status> <method> <url>"` for every same-origin 4xx/5xx. */
+ failedResponses: string[];
+}
+
+function sameOrigin(pageUrl: string, responseUrl: string): boolean {
+ try {
+ return new URL(pageUrl).origin === new URL(responseUrl).origin;
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Watch a page for console errors and failed requests. The `noise` fixture arms
+ * this before the first navigation; both arrays fill as the page runs, so assert
+ * on them at the end of the scenario.
+ *
+ * `ignore` takes extra substrings for a *known application* bug out of the
+ * spec's scope, so the rest of the assertion keeps its value instead of being
+ * deleted. Name the defect when you use it.
+ */
+export function watchConsole(
+ page: Page,
+ options: { ignore?: string[] } = {},
+): ConsoleWatch {
+ const watch: ConsoleWatch = { errors: [], failedResponses: [] };
+ const noise = [...HARNESS_CONSOLE_NOISE, ...(options.ignore ?? [])];
+ const isNoise = (text: string): boolean =>
+ noise.some((entry) => text.includes(entry));
+
+ page.on('console', (message) => {
+ if (message.type() !== 'error') {
+ return;
+ }
+ // Chrome leaves the URL out of a failed load's text; its location has it.
+ const text = message.text().startsWith('Failed to load resource')
+ ? `${message.text()} ${message.location().url}`
+ : message.text();
+ if (!isNoise(text)) {
+ watch.errors.push(text);
+ }
+ });
+ page.on('pageerror', (error) => {
+ if (!isNoise(String(error))) {
+ watch.errors.push(String(error));
+ }
+ });
+ page.on('response', (response) => {
+ const url = response.url();
+ if (response.status() < 400 || !sameOrigin(page.url(), url)) {
+ return;
+ }
+ if (HARNESS_FAILING_REQUESTS.some((entry) => url.includes(entry))) {
+ return;
+ }
+ watch.failedResponses.push(
+ `${response.status()} ${response.request().method()} ${url}`,
+ );
+ });
+ return watch;
+}
+
+/**
+ * Serve the cloud control plane's endpoints so a console assertion reflects the
+ * page under test rather than the deployment shape. Use it in the few specs that
+ * assert a clean console end to end.
+ */
+export async function stubCloudOnlyApis(page: Page): Promise<void> {
+ await page.route('**/api/v2/zeus/**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ data: {} }),
+ }),
+ );
+}
+
+/**
+ * Every request the page issues from now on. Arm before the first navigation;
+ * filter the array at the end of the scenario ("called exactly once", "no legacy
+ * route used").
+ */
+export function collectRequests(page: Page): Request[] {
+ const requests: Request[] = [];
+ page.on('request', (request) => requests.push(request));
+ return requests;
+}
+
+/** A request's URL, parsed — the readable way to reach `searchParams`. */
+export function requestUrl(request: Request): URL {
+ return new URL(request.url());
+}
diff --git a/tests/e2e/drivers/dashboard-list.ts b/tests/e2e/drivers/dashboard-list.ts
index 83355c2161..ecedbfdfac 100644
--- a/tests/e2e/drivers/dashboard-list.ts
+++ b/tests/e2e/drivers/dashboard-list.ts
@@ -6,9 +6,9 @@ import { randomBytes } from 'crypto';
import { expect, type Locator, type Page } from '@playwright/test';
-import { BASE_PATH } from '../helpers/base-path';
-import { buildDashboard } from '../helpers/dashboard-spec';
-import type { PostableDashboard, Tag } from '../helpers/dashboard-spec.types';
+import { BASE_PATH } from './base-path';
+import { buildDashboard } from './dashboard-spec';
+import type { PostableDashboard, Tag } from './dashboard-spec.types';
import {
DASHBOARDS_API,
@@ -136,6 +136,12 @@ export interface DashboardList {
/** Opens the delete confirmation without answering it. */
requestDelete(name: string): Promise<Locator>;
cancelDelete(): Promise<void>;
+ /** Through the row menu's Rename dialog. */
+ renameRow(name: string, to: string): Promise<void>;
+ /** Replaces the row's tags through its Edit tags dialog; `key:value` each. */
+ editRowTags(name: string, tags: string[]): Promise<void>;
+ /** Duplicates through the row menu and returns the copy's id. */
+ duplicateRow(name: string): Promise<string>;
newDashboardDialog(): Locator;
openNewDashboard(tab?: NewDashboardTab): Promise<void>;
@@ -152,7 +158,7 @@ export interface DashboardList {
back(): Promise<void>;
}
-function dashboardListDriver(page: Page): DashboardList {
+export function dashboardListDriver(page: Page): DashboardList {
const rowTitle = (name: string): Locator =>
page
.locator('[data-testid^="dashboard-title-"]')
@@ -342,6 +348,50 @@ function dashboardListDriver(page: Page): DashboardList {
await expect(deleteConfirm()).toContainText(name);
return deleteConfirm();
},
+ async renameRow(name, to) {
+ await list.openRowMenu(name);
+ await list.rowAction('rename').click();
+ const input = page.getByTestId('rename-dashboard-input');
+ await input.fill(to);
+ await page.getByTestId('rename-dashboard-submit').click();
+ await expect(input).toBeHidden();
+ },
+ async editRowTags(name, tags) {
+ await list.openRowMenu(name);
+ await list.rowAction('edit-tags').click();
+ const input = page.getByTestId('edit-dashboard-tags');
+ // Closing a chip removes the tag, and the dialog opens with the current ones.
+ const chips = page.locator(
+ '[data-testid^="edit-dashboard-tags-chip"] button',
+ );
+ while ((await chips.count()) > 0) {
+ await chips.first().click();
+ }
+ for (const tag of tags) {
+ await input.fill(tag);
+ await input.press('Enter');
+ }
+ await page.getByTestId('edit-tags-submit').click();
+ await expect(input).toBeHidden();
+ },
+ async duplicateRow(name) {
+ await list.openRowMenu(name);
+ const [response] = await Promise.all([
+ page.waitForResponse((r) => {
+ const { pathname } = new URL(r.url());
+ return (
+ r.request().method() === 'POST' &&
+ pathname.startsWith(`${BASE_PATH}${DASHBOARDS_API}/`) &&
+ pathname.endsWith('/clone')
+ );
+ }),
+ list.rowAction('duplicate').click(),
+ ]);
+ expect(response.ok(), `POST ${DASHBOARDS_API}/:id/clone failed`).toBe(true);
+ const id = ((await response.json()) as { data: { id: string } }).data.id;
+ trackDashboard(page, id);
+ return id;
+ },
async cancelDelete() {
await deleteConfirm().getByRole('button', { name: 'Cancel' }).click();
await expect(deleteConfirm()).toBeHidden();
diff --git a/tests/e2e/drivers/dashboard-settings.ts b/tests/e2e/drivers/dashboard-settings.ts
index 131be7761d..1329ac9beb 100644
--- a/tests/e2e/drivers/dashboard-settings.ts
+++ b/tests/e2e/drivers/dashboard-settings.ts
@@ -4,12 +4,12 @@
*/
import { expect, type Locator, type Page } from '@playwright/test';
-import { buildDashboard, panel, PanelKind } from '../helpers/dashboard-spec';
+import { buildDashboard, panel, PanelKind } from './dashboard-spec';
import type {
PostableDashboard,
Signal,
Variable,
-} from '../helpers/dashboard-spec.types';
+} from './dashboard-spec.types';
import { toolbarAt } from './dashboard-page';
import { boxOf, dragBy, openSelectOption } from './panels/dom';
diff --git a/tests/e2e/helpers/dashboard-spec.ts b/tests/e2e/drivers/dashboard-spec.ts
similarity index 100%
rename from tests/e2e/helpers/dashboard-spec.ts
rename to tests/e2e/drivers/dashboard-spec.ts
diff --git a/tests/e2e/helpers/dashboard-spec.types.ts b/tests/e2e/drivers/dashboard-spec.types.ts
similarity index 100%
rename from tests/e2e/helpers/dashboard-spec.types.ts
rename to tests/e2e/drivers/dashboard-spec.types.ts
diff --git a/tests/e2e/drivers/dashboards.ts b/tests/e2e/drivers/dashboards.ts
index ec020af6a8..b7eb2abaa8 100644
--- a/tests/e2e/drivers/dashboards.ts
+++ b/tests/e2e/drivers/dashboards.ts
@@ -9,12 +9,13 @@ import {
type Request,
} from '@playwright/test';
-import { BASE_PATH } from '../helpers/base-path';
-import { authToken } from '../helpers/common';
+import { BASE_PATH } from './base-path';
+import { authToken } from './api';
+import { buildDashboard } from './dashboard-spec';
import type {
GettableDashboard,
PostableDashboard,
-} from '../helpers/dashboard-spec.types';
+} from './dashboard-spec.types';
import {
holdQueryRange,
isQueryRange,
@@ -24,9 +25,9 @@ import {
type QueryWindow,
recordQueryWindows,
unmockQueryRange,
-} from '../helpers/query-range-mock';
+} from './query-range-mock';
-import { driver, kit } from './kit';
+import { asAdmin, driver, kit } from './kit';
// `POST /api/v2/dashboards` takes the full perses spec in one call.
@@ -54,6 +55,8 @@ export const EDITOR_ROOT = '[data-testid="panel-editor-v2"]:not([data-group])';
export interface Dashboards {
/** Created for this test and deleted when it ends. */
seed(dashboard: PostableDashboard): Promise<string>;
+ /** For a test running as a lesser identity: created and deleted as admin. */
+ seedAsAdmin(dashboard: PostableDashboard): Promise<string>;
seedAndOpen(dashboard: PostableDashboard): Promise<string>;
seedAndEdit(dashboard: PostableDashboard, panelId: string): Promise<string>;
/** The open dashboard's heading. */
@@ -164,7 +167,22 @@ async function setLockedViaApi(
}
}
+export interface DashboardSeed {
+ id: string;
+ title: string;
+}
+
+/** A bare dashboard for features that only need one to exist. */
+export async function createDashboard(
+ page: Page,
+ title: string,
+): Promise<DashboardSeed> {
+ const id = await createViaApi(page, buildDashboard({ title, sections: [] }));
+ return { id, title };
+}
+
const trackedByPage = new WeakMap<Page, string[]>();
+const trackedAsAdminByPage = new WeakMap<Page, string[]>();
/** Registers a dashboard for deletion when the test owning `page` ends. */
export function trackDashboard(page: Page, id: string): void {
@@ -192,16 +210,29 @@ export async function deleteViaApi(page: Page, id: string): Promise<void> {
export async function removeTrackedDashboards(page: Page): Promise<void> {
const ids = trackedByPage.get(page) ?? [];
trackedByPage.delete(page);
+ const adminIds = trackedAsAdminByPage.get(page) ?? [];
+ trackedAsAdminByPage.delete(page);
try {
for (const id of ids) {
await deleteViaApi(page, id);
}
+ if (adminIds.length > 0) {
+ await asAdmin(
+ page,
+ (admin) => admin,
+ async (admin) => {
+ for (const id of adminIds) {
+ await deleteViaApi(admin, id);
+ }
+ },
+ );
+ }
} catch {
/* the dashboards outlive the run rather than hiding why it failed */
}
}
-function dashboardsDriver(page: Page): Dashboards {
+export function dashboardsDriver(page: Page): Dashboards {
const editorRoot = (): Locator => page.locator(EDITOR_ROOT);
const dashboards: Dashboards = {
@@ -210,6 +241,18 @@ function dashboardsDriver(page: Page): Dashboards {
trackDashboard(page, id);
return id;
},
+ async seedAsAdmin(dashboard) {
+ const id = await asAdmin(
+ page,
+ (admin) => admin,
+ (admin) => createViaApi(admin, dashboard),
+ );
+ trackedAsAdminByPage.set(page, [
+ ...(trackedAsAdminByPage.get(page) ?? []),
+ id,
+ ]);
+ return id;
+ },
title: () => page.getByTestId('dashboard-title'),
async seedAndOpen(dashboard) {
const id = await dashboards.seed(dashboard);
@@ -298,7 +341,7 @@ const withQueryRange = driver('queryRange', ({ page }) =>
export const test = withQueryRange(withDashboards(kit));
export { expect } from './kit';
-export * from '../helpers/dashboard-spec';
-export type * from '../helpers/dashboard-spec.types';
-export { heatmapPoints, QueryRange, ramp } from '../helpers/query-range-mock';
+export * from './dashboard-spec';
+export type * from './dashboard-spec.types';
+export { heatmapPoints, QueryRange, ramp } from './query-range-mock';
export * from '../testdata/dashboards/panels';
diff --git a/tests/e2e/drivers/exceptions.ts b/tests/e2e/drivers/exceptions.ts
new file mode 100644
index 0000000000..6417482f37
--- /dev/null
+++ b/tests/e2e/drivers/exceptions.ts
@@ -0,0 +1,247 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import {
+ allowFor,
+ driver,
+ kit,
+ seeded,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ type Layer,
+ type WorkerLayer,
+} from './kit';
+import { exceptionSpan, stamp as stampFor } from './spans';
+import { seedTracesViaSeeder, type SeederSpan } from './traces';
+
+/**
+ * The exceptions list (`/exceptions`) and the exception detail page
+ * (`/error-detail`). Both read the error index, which the seeder fills from a
+ * span's `exception` event.
+ */
+
+const LIST_PATH = '/exceptions';
+const TABLE = 'exceptions-table';
+const ROW_LINK = 'exception-row-link';
+
+/**
+ * `listErrors` moves `end` back 30 s when it is within 30 s of now, so an event
+ * seeded later than that is invisible. Every event sits past that edge.
+ */
+const TIMEOUT_EVENTS_AGO_MS = [120_000, 60_000];
+const VALUE_EVENT_AGO_MS = 90_000;
+
+export interface ExceptionGroup {
+ type: string;
+ message: string;
+ count: number;
+ /** Oldest first. */
+ spans: SeederSpan[];
+}
+
+export interface ExceptionSeed {
+ stamp: string;
+ service: string;
+ /** A frame every seeded stack trace carries. */
+ frame: string;
+ groups: { timeout: ExceptionGroup; value: ExceptionGroup };
+}
+
+export interface ExceptionDetail {
+ type(): Locator;
+ message(): Locator;
+ eventId(): Locator;
+ olderButton(): Locator;
+ newerButton(): Locator;
+ /** Click Older and wait for `errorId` in the URL to change. */
+ older(): Promise<void>;
+ newer(): Promise<void>;
+ /** Click "See the error in trace graph"; resolves with the trace page URL. */
+ viewTrace(): Promise<URL>;
+ stacktrace(): Locator;
+ attributes(): Locator;
+}
+
+export interface Exceptions {
+ gotoList(params?: Record<string, string>): Promise<void>;
+ table(): Locator;
+ headers(): Promise<string[]>;
+ tab(name: string): Locator;
+ /** The data row whose type link is exactly `type`. */
+ row(type: string): Locator;
+ cell(type: string, header: string): Promise<Locator>;
+ /** Application cell of every data row. */
+ applications(): Promise<string[]>;
+ /** Reload until `type` is listed: the list fetches once per load. */
+ waitForRow(type: string): Promise<void>;
+ /** The Application column's search dropdown. */
+ filterByService(name: string): Promise<void>;
+ openRow(type: string): Promise<void>;
+ detail: ExceptionDetail;
+}
+
+const errorIdOf = (page: Page): string | null =>
+ new URL(page.url()).searchParams.get('errorId');
+
+export function exceptionsDriver(page: Page): Exceptions {
+ const table = (): Locator => page.getByTestId(TABLE);
+
+ const headers = async (): Promise<string[]> =>
+ (await table().getByRole('columnheader').allInnerTexts())
+ .map((text) => text.trim())
+ .filter(Boolean);
+
+ const columnIndex = async (header: string): Promise<number> => {
+ const index = (await headers()).indexOf(header);
+ if (index === -1) {
+ throw new Error(`exceptions table has no "${header}" column`);
+ }
+ return index;
+ };
+
+ const dataRows = (): Locator =>
+ table()
+ .getByRole('row')
+ .filter({ has: page.getByTestId(ROW_LINK) });
+
+ const stepThrough = async (button: Locator): Promise<void> => {
+ const before = errorIdOf(page);
+ await expect(button).toBeEnabled();
+ await button.click();
+ await expect(async () => {
+ expect(errorIdOf(page)).not.toBe(before);
+ }).toPass();
+ };
+
+ const exceptions: Exceptions = {
+ table,
+ headers,
+ tab: (name) => page.getByRole('tab', { name, exact: true }),
+
+ gotoList: async (params = {}) => {
+ const query = new URLSearchParams({ relativeTime: '15m', ...params });
+ await page.goto(`${LIST_PATH}?${query.toString()}`);
+ await expect(table()).toBeVisible();
+ },
+
+ row: (type) =>
+ dataRows().filter({
+ has: page.getByTestId(ROW_LINK).getByText(type, { exact: true }),
+ }),
+
+ cell: async (type, header) =>
+ exceptions
+ .row(type)
+ .getByRole('cell')
+ .nth(await columnIndex(header)),
+
+ applications: async () => {
+ const index = await columnIndex('Application');
+ const rows = await dataRows().all();
+ return Promise.all(
+ rows.map(async (row) =>
+ (await row.getByRole('cell').nth(index).innerText()).trim(),
+ ),
+ );
+ },
+
+ waitForRow: async (type) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(async () => {
+ await page.reload();
+ await expect(exceptions.row(type)).toBeVisible({ timeout: 5_000 });
+ }).toPass({ timeout: SEEDED_TEST_BUDGET - 15_000 });
+ },
+
+ filterByService: async (name) => {
+ await table()
+ .getByRole('columnheader', { name: /Application/ })
+ .getByRole('button')
+ .click();
+ const input = page.getByPlaceholder('Search By Application');
+ await input.fill(name);
+ await input.press('Enter');
+ await expect(page).toHaveURL(
+ new RegExp(`serviceName=${encodeURIComponent(name)}`),
+ );
+ },
+
+ openRow: async (type) => {
+ await exceptions.row(type).getByTestId(ROW_LINK).click();
+ await expect(page).toHaveURL(/\/error-detail\?groupId=/);
+ await expect(exceptions.detail.type()).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ },
+
+ detail: {
+ type: () => page.getByTestId('error-details-type'),
+ message: () => page.getByTestId('error-details-message'),
+ eventId: () => page.getByTestId('error-details-event-id'),
+ olderButton: () => page.getByTestId('error-details-older'),
+ newerButton: () => page.getByTestId('error-details-newer'),
+ older: () => stepThrough(exceptions.detail.olderButton()),
+ newer: () => stepThrough(exceptions.detail.newerButton()),
+ viewTrace: async () => {
+ await page.getByTestId('error-details-view-trace').click();
+ await expect(page).toHaveURL(/\/trace\/[0-9a-f]{32}\?spanId=/);
+ return new URL(page.url());
+ },
+ stacktrace: () => page.getByTestId('error-details-stacktrace'),
+ attributes: () => page.getByTestId('error-details-attributes-table'),
+ },
+ };
+
+ return exceptions;
+}
+
+export const withExceptions: Layer<{ exceptions: Exceptions }> = driver(
+ 'exceptions',
+ ({ page }) => exceptionsDriver(page),
+);
+
+/**
+ * Two groups for one stamped service: `E2eTimeoutError` twice (so Older/Newer
+ * have somewhere to go) and `E2eValueError` once. Telemetry has no scoped
+ * delete, so there is no teardown; the stamp keeps workers apart.
+ */
+export const withExceptionSeed: WorkerLayer<{ exceptionSeed: ExceptionSeed }> =
+ seeded('exceptionSeed', async ({ page, workerIndex }) => {
+ const stamp = stampFor('exc', workerIndex);
+ const service = stamp;
+ const frame = `at ${stamp.replace(/-/g, '_')}.handler (app.js:42:7)`;
+ const group = (
+ type: string,
+ message: string,
+ agos: number[],
+ ): ExceptionGroup => ({
+ type,
+ message,
+ count: agos.length,
+ spans: agos.map((agoMs) =>
+ exceptionSpan({
+ service,
+ type,
+ message,
+ stack: `${type}: ${message}\n ${frame}`,
+ agoMs,
+ }),
+ ),
+ });
+ const groups = {
+ timeout: group(
+ 'E2eTimeoutError',
+ `${stamp} upstream timeout`,
+ TIMEOUT_EVENTS_AGO_MS,
+ ),
+ value: group('E2eValueError', `${stamp} bad value`, [VALUE_EVENT_AGO_MS]),
+ };
+ await seedTracesViaSeeder(page.request, [
+ ...groups.timeout.spans,
+ ...groups.value.spans,
+ ]);
+ return { stamp, service, frame, groups };
+ });
+
+/** The exceptions `test`. */
+export const test = withExceptionSeed(withExceptions(kit));
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/explorers.ts b/tests/e2e/drivers/explorers.ts
new file mode 100644
index 0000000000..6848bbd27d
--- /dev/null
+++ b/tests/e2e/drivers/explorers.ts
@@ -0,0 +1,202 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { apiDriver } from './api';
+import { driver, kit, type Layer } from './kit';
+import {
+ dismissQuickFiltersAnnouncement,
+ LOGS_EXPLORER_PATH,
+ logsExplorerDriver,
+ type LogsExplorer,
+} from './logs/explorer';
+
+/**
+ * The logs explorer, the quick-filters rail and the CodeMirror query editor —
+ * one driver each, composed into the explorer `test`.
+ */
+
+export { LOGS_EXPLORER_PATH };
+
+// ─── Quick filters ───────────────────────────────────────────────────────────
+
+const SETTINGS_PANEL_TITLE = 'Edit quick filters';
+const SETTINGS_ICON = 'settings-icon';
+const SETTINGS_ICON_CONTAINER = 'settings-icon-container';
+/** The panel is 342px wide; 300 leaves slack for sub-pixel rounding. */
+const SETTINGS_PANEL_MIN_WIDTH_PX = 300;
+
+export type QuickFilterSignal = 'logs' | 'traces';
+
+export interface QuickFilterDefinition {
+ key: string;
+ dataType: string;
+ type: string;
+}
+
+/** Minimal set so `isDynamicFilters` is true and the settings gear renders. */
+export const DEFAULT_CUSTOM_FILTERS: QuickFilterDefinition[] = [
+ { key: 'service.name', dataType: 'string', type: 'resource' },
+ { key: 'deployment.environment', dataType: 'string', type: 'resource' },
+];
+
+export interface QuickFilters {
+ seed(
+ signal: QuickFilterSignal,
+ filters?: QuickFilterDefinition[],
+ ): Promise<void>;
+ /** Hide the one-off announcement tooltip so it cannot swallow the gear click. */
+ dismissAnnouncement(): Promise<void>;
+ gotoExplorer(path: string): Promise<void>;
+ openSettings(): Promise<void>;
+ closeSettings(): Promise<void>;
+ expectSettingsOpen(seeded?: QuickFilterDefinition[]): Promise<void>;
+ expectSettingsClosed(): Promise<void>;
+ rail(): Locator;
+ /** The settings drawer, open or not. */
+ settingsPanel(): Locator;
+}
+
+export function quickFiltersDriver(page: Page): QuickFilters {
+ const panel = (): Locator =>
+ page
+ .locator('.quick-filters-settings')
+ .filter({ hasText: SETTINGS_PANEL_TITLE });
+ const gearContainer = (): Locator => page.getByTestId(SETTINGS_ICON_CONTAINER);
+
+ const filters: QuickFilters = {
+ rail: () => page.locator('.quick-filters'),
+ settingsPanel: panel,
+
+ seed: async (signal, definitions = DEFAULT_CUSTOM_FILTERS) => {
+ await apiDriver(page).put('/api/v1/orgs/me/filters', {
+ signal,
+ filters: definitions,
+ });
+ },
+
+ dismissAnnouncement: () => dismissQuickFiltersAnnouncement(page),
+
+ gotoExplorer: async (path) => {
+ await filters.dismissAnnouncement();
+ await page.goto(path);
+ await page.getByTestId(SETTINGS_ICON).waitFor({ state: 'visible' });
+ },
+
+ expectSettingsClosed: async () => {
+ await expect(page.getByText(SETTINGS_PANEL_TITLE)).toBeHidden();
+ await expect(gearContainer()).toHaveAttribute('aria-expanded', 'false');
+ // A collapsed panel keeps the `hidden` class (width: 0), and a zero-width
+ // element is never "visible" to Playwright, so assert the class.
+ await expect(page.locator('.quick-filters-settings')).toHaveClass(/hidden/);
+ },
+
+ openSettings: async () => {
+ await filters.expectSettingsClosed();
+ await page.getByTestId(SETTINGS_ICON).click();
+ },
+
+ closeSettings: async () => {
+ await panel().getByTestId('quick-filters-settings-close').click();
+ await filters.expectSettingsClosed();
+ },
+
+ /** Open, painted on screen and populated — not merely present in the DOM. */
+ expectSettingsOpen: async (seeded = DEFAULT_CUSTOM_FILTERS) => {
+ const settings = panel();
+ await expect(gearContainer()).toHaveAttribute('aria-expanded', 'true');
+ await expect(settings).toBeVisible();
+ await expect(settings).not.toHaveClass(/hidden/);
+ await expect(page.getByText(SETTINGS_PANEL_TITLE)).toBeVisible();
+ await expect(page.getByPlaceholder('Search for a filter...')).toBeVisible();
+ await expect(
+ settings.getByTestId('quick-filters-settings-close'),
+ ).toBeVisible();
+
+ const added = settings.locator('.qf-added-filters-list');
+ await expect(settings.getByText('ADDED FILTERS')).toBeVisible();
+ for (const filter of seeded) {
+ // eslint-disable-next-line no-await-in-loop
+ await expect(added.getByText(filter.key, { exact: true })).toBeVisible();
+ }
+
+ // The footer only mounts after an edit, so it is absent on first open.
+ await expect(settings.getByRole('button', { name: 'Discard' })).toBeHidden();
+ await expect(
+ settings.getByRole('button', { name: 'Save changes' }),
+ ).toBeHidden();
+
+ // OTHER FILTERS loads asynchronously from attribute suggestions.
+ await expect(settings.locator('.qf-other-filters-skeleton')).toHaveCount(0);
+ await expect(settings.getByText('OTHER FILTERS')).toBeVisible();
+ await expect(
+ settings.locator('.qf-other-filters-list .other-filters-item').first(),
+ ).toBeVisible();
+
+ const [panelBox, columnBox] = await Promise.all([
+ settings.boundingBox(),
+ filters.rail().boundingBox(),
+ ]);
+ expect(panelBox?.width ?? 0).toBeGreaterThanOrEqual(
+ SETTINGS_PANEL_MIN_WIDTH_PX,
+ );
+ expect(columnBox).not.toBeNull();
+ expect(panelBox?.x ?? 0).toBeGreaterThanOrEqual(columnBox?.x ?? 0);
+ },
+ };
+
+ return filters;
+}
+
+// ─── Query editor ────────────────────────────────────────────────────────────
+
+const EDITOR_CONTENT = '.query-where-clause-editor .cm-content';
+const EDITOR_LINES = '.query-where-clause-editor .cm-line';
+
+export interface QueryEditor {
+ type(expression: string): Promise<void>;
+ /** The first token whose text is exactly `text`; read its colour with `toHaveCSS`. */
+ token(text: string): Locator;
+ /** Set the app theme. Must run before the first navigation. */
+ setTheme(theme: 'dark' | 'light'): Promise<void>;
+}
+
+export function queryEditorDriver(page: Page): QueryEditor {
+ return {
+ type: async (expression) => {
+ const editor = page.locator(EDITOR_CONTENT).first();
+ await editor.waitFor({ state: 'visible', timeout: 15_000 });
+ // The caret can jump once after mount and rotate typed text, so retype
+ // until the editor holds exactly the expression.
+ await expect(async () => {
+ await editor.click();
+ await page.keyboard.press('ControlOrMeta+a');
+ await page.keyboard.press('Delete');
+ await page.keyboard.type(expression);
+ await expect(editor).toHaveText(expression, { timeout: 1_000 });
+ }).toPass({ timeout: 15_000 });
+ },
+
+ token: (text) =>
+ page.locator(EDITOR_LINES).getByText(text, { exact: true }).first(),
+
+ setTheme: async (theme) => {
+ await page.addInitScript((value) => {
+ localStorage.setItem('THEME', value);
+ }, theme);
+ },
+ };
+}
+
+export const withExplorers: Layer<{
+ logs: LogsExplorer;
+ quickFilters: QuickFilters;
+ editor: QueryEditor;
+}> = (base) =>
+ driver('editor', ({ page }) => queryEditorDriver(page))(
+ driver('quickFilters', ({ page }) => quickFiltersDriver(page))(
+ driver('logs', ({ page }) => logsExplorerDriver(page))(base),
+ ),
+ );
+
+/** The explorers `test`. */
+export const test = withExplorers(kit);
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/funnels.ts b/tests/e2e/drivers/funnels.ts
new file mode 100644
index 0000000000..ff6a7a0150
--- /dev/null
+++ b/tests/e2e/drivers/funnels.ts
@@ -0,0 +1,506 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { antdDriver } from './antd';
+import { apiDriver } from './api';
+import {
+ driver,
+ kit,
+ SEEDED_DATA_TIMEOUT,
+ seeded,
+ type Layer,
+ type WorkerLayer,
+} from './kit';
+import { childSpan, rootSpan, stamp, STATUS } from './spans';
+import {
+ seedTracesViaSeeder,
+ traceDetailsDriver,
+ type SeederSpan,
+ type TraceDetails,
+} from './traces';
+
+/**
+ * Trace funnels: the list page, the detail page, the "add span to funnel" modal
+ * on trace details, and API seeds.
+ *
+ * Funnels are org-wide and their names must be unique, so every name carries the
+ * worker's stamp. The `funnelSpans` seed removes them by prefix on close.
+ */
+
+const FUNNELS_API = '/api/v1/trace-funnels';
+const LIST_PATH = '/traces/funnels';
+const TIME_RANGE = 'relativeTime=15m';
+
+/** `/api/v1/trace-funnels` is not in `docs/api/openapi.yml`, so these are local. */
+export interface FunnelStep {
+ step_order: number;
+ service_name: string;
+ span_name: string;
+ latency_pointer?: 'start' | 'end';
+ latency_type?: string;
+ has_errors: boolean;
+ filters?: { op: string; items: unknown[] };
+}
+
+export interface Funnel {
+ funnel_id: string;
+ funnel_name: string;
+ steps?: FunnelStep[] | null;
+}
+
+export type LatencyPointer = 'Start of span' | 'End of span';
+
+export interface FunnelSeed {
+ create(name: string): Promise<Funnel>;
+ /** Replace the steps; each entry is a complete step. */
+ setSteps(
+ id: string,
+ steps: { service: string; span: string; latencyPointer?: 'start' | 'end' }[],
+ ): Promise<void>;
+ get(id: string): Promise<Funnel>;
+ list(): Promise<Funnel[]>;
+ remove(id: string): Promise<void>;
+ removeByPrefix(prefix: string): Promise<void>;
+}
+
+export interface Funnels {
+ seed: FunnelSeed;
+
+ gotoList(): Promise<void>;
+ newFunnelButton(): Locator;
+ search(text: string): Promise<void>;
+ item(name: string): Locator;
+ /** Fill the create modal and press Create; resolves with the response status. */
+ submitCreate(name: string): Promise<number>;
+ /** Create through the modal and land on the detail page; resolves with the id. */
+ create(name: string): Promise<string>;
+ createModal(): Locator;
+ createError(): Locator;
+ rename(name: string, next: string): Promise<void>;
+ remove(name: string): Promise<void>;
+ /** Delete from the detail page header. */
+ removeFromDetail(): Promise<void>;
+ pathname(): string;
+
+ goto(id: string): Promise<void>;
+ title(): Locator;
+ actionsTrigger(): Locator;
+ step(index: number): Locator;
+ setStep(index: number, service: string, span: string): Promise<void>;
+ stepSelect(index: number, which: 'service' | 'span'): Locator;
+ addStep(): Promise<void>;
+ stepsCount(): Locator;
+ stepActionsTrigger(index: number): Locator;
+ openStepActions(index: number): Promise<void>;
+ stepDeleteAction(): Locator;
+ deleteStep(index: number): Promise<void>;
+ latencyPointer(index: number): Locator;
+ setLatencyPointer(index: number, pointer: LatencyPointer): Promise<void>;
+ saveButton(): Locator;
+ save(): Promise<void>;
+ validStatus(): Locator;
+ results(): Locator;
+ slowTraces(): Locator;
+ errorTraces(): Locator;
+ slowTraceIdCells(): Locator;
+ errorTrace(traceId: string): Locator;
+ traceIdsIn(table: Locator): Promise<string[]>;
+
+ /** Trace details, for the add-span-to-funnel flow. */
+ traces: TraceDetails;
+ addSpanModal: {
+ open(spanId: string): Promise<void>;
+ dialog(): Locator;
+ pickFunnel(id: string): Promise<void>;
+ addForNewStep(): Promise<void>;
+ save(): Promise<void>;
+ };
+}
+
+const isFunnelsCall =
+ (method: string, path: string | RegExp) =>
+ (response: { url(): string; request(): { method(): string } }): boolean => {
+ const url = new URL(response.url()).pathname;
+ const matches =
+ typeof path === 'string'
+ ? url === `${FUNNELS_API}${path}`
+ : path.test(url.replace(FUNNELS_API, ''));
+ return matches && response.request().method() === method;
+ };
+
+export function funnelSeed(page: Page): FunnelSeed {
+ const api = apiDriver(page);
+ const seed: FunnelSeed = {
+ create: async (name) =>
+ (
+ await api.post<{ data: Funnel }>(`${FUNNELS_API}/new`, {
+ funnel_name: name,
+ timestamp: Date.now(),
+ })
+ ).data,
+
+ setSteps: async (id, steps) => {
+ await api.put(`${FUNNELS_API}/steps/update`, {
+ funnel_id: id,
+ timestamp: Date.now(),
+ steps: steps.map((step, index) => ({
+ step_order: index + 1,
+ service_name: step.service,
+ span_name: step.span,
+ latency_pointer: step.latencyPointer ?? (index === 0 ? 'start' : 'end'),
+ has_errors: false,
+ filters: { op: 'AND', items: [] },
+ })),
+ });
+ },
+
+ get: async (id) =>
+ (await api.get<{ data: Funnel }>(`${FUNNELS_API}/${id}`)).data,
+
+ list: async () =>
+ (await api.get<{ data: Funnel[] | null }>(`${FUNNELS_API}/list`)).data ?? [],
+
+ remove: (id) => api.tryDel(`${FUNNELS_API}/${id}`),
+
+ removeByPrefix: async (prefix) => {
+ const all = await seed.list();
+ await Promise.all(
+ all
+ .filter((funnel) => funnel.funnel_name.startsWith(prefix))
+ .map((funnel) => seed.remove(funnel.funnel_id)),
+ );
+ },
+ };
+ return seed;
+}
+
+// `addInitScript` re-runs on every navigation, so each funnel's reset is
+// registered at most once per page.
+const stepResets = new WeakMap<Page, Set<string>>();
+
+export function funnelsDriver(page: Page): Funnels {
+ const antd = antdDriver(page);
+
+ /**
+ * Unsaved steps live in `FUNNEL_STEPS_<id>` and are restored over the saved
+ * ones, so the key is cleared before every navigation, reloads included.
+ */
+ const resetSteps = async (id: string): Promise<void> => {
+ const registered = stepResets.get(page) ?? new Set<string>();
+ stepResets.set(page, registered);
+ if (registered.has(id)) {
+ return;
+ }
+ registered.add(id);
+ await page.addInitScript((key) => {
+ localStorage.removeItem(key);
+ }, `FUNNEL_STEPS_${id}`);
+ };
+
+ const openActions = async (scope: Locator): Promise<void> => {
+ await scope.getByTestId('funnel-actions-trigger').click();
+ };
+
+ const confirmDelete = async (): Promise<void> => {
+ await page.getByTestId('funnel-action-delete').click();
+ const deleted = page.waitForResponse(
+ isFunnelsCall('DELETE', /^\/[0-9a-f-]{36}$/),
+ );
+ await page.getByRole('button', { name: 'Delete Funnel' }).click();
+ expect((await deleted).ok()).toBe(true);
+ };
+
+ const funnels: Funnels = {
+ seed: funnelSeed(page),
+
+ gotoList: async () => {
+ await page.goto(LIST_PATH);
+ await expect(funnels.newFunnelButton()).toBeVisible();
+ },
+
+ newFunnelButton: () => page.getByTestId('traces-funnels-new-btn'),
+
+ search: async (text) => {
+ await page.getByTestId('traces-funnels-search').fill(text);
+ },
+
+ item: (name) =>
+ page.locator('[data-testid^="funnel-item-"]').filter({
+ has: page.getByText(name, { exact: true }),
+ }),
+
+ createModal: () => page.getByTestId('create-funnel-modal'),
+ createError: () => page.getByTestId('create-funnel-error'),
+
+ submitCreate: async (name) => {
+ await funnels.newFunnelButton().click();
+ await page.getByTestId('create-funnel-name-input').fill(name);
+ const created = page.waitForResponse(isFunnelsCall('POST', '/new'));
+ await page.getByRole('button', { name: 'Create Funnel' }).click();
+ return (await created).status();
+ },
+
+ create: async (name) => {
+ expect(await funnels.submitCreate(name)).toBe(200);
+ await expect(page).toHaveURL(/\/traces\/funnels\/[0-9a-f-]{36}/);
+ const id = new URL(page.url()).pathname.split('/').pop();
+ if (!id) {
+ throw new Error(`no funnel id in ${page.url()}`);
+ }
+ return id;
+ },
+
+ rename: async (name, next) => {
+ await openActions(funnels.item(name));
+ await page.getByTestId('funnel-action-rename').click();
+ await page.getByTestId('rename-funnel-name-input').fill(next);
+ const renamed = page.waitForResponse(
+ isFunnelsCall('PUT', /^\/[0-9a-f-]{36}$/),
+ );
+ await page.getByRole('button', { name: 'Rename Funnel' }).click();
+ expect((await renamed).ok()).toBe(true);
+ },
+
+ remove: async (name) => {
+ await openActions(funnels.item(name));
+ await confirmDelete();
+ },
+
+ removeFromDetail: async () => {
+ await funnels.actionsTrigger().click();
+ await confirmDelete();
+ },
+
+ pathname: () => new URL(page.url()).pathname,
+
+ goto: async (id) => {
+ await resetSteps(id);
+ await page.goto(`${LIST_PATH}/${id}?${TIME_RANGE}`);
+ await expect(funnels.title()).toBeVisible();
+ },
+
+ title: () => page.getByTestId('funnel-title'),
+
+ actionsTrigger: () => page.getByTestId('funnel-actions-trigger'),
+
+ step: (index) => page.getByTestId(`funnel-step-${index}`),
+
+ stepSelect: (index, which) =>
+ page
+ .getByTestId(`funnel-step-${which}-select-${index}`)
+ .locator('.ant-select'),
+
+ setStep: async (index, service, span) => {
+ for (const [which, value] of [
+ ['service', service],
+ ['span', span],
+ ] as const) {
+ const select = funnels.stepSelect(index, which);
+ // eslint-disable-next-line no-await-in-loop
+ await select.click();
+ // eslint-disable-next-line no-await-in-loop
+ await select.locator('input[role="combobox"]').fill(value);
+ // eslint-disable-next-line no-await-in-loop
+ const dropdown = await antd.ownDropdown(select);
+ // FilterSelect prepends the typed text as an option, so the exact
+ // title exists even before the options request returns.
+ // eslint-disable-next-line no-await-in-loop
+ await dropdown
+ .locator(`.ant-select-item-option[title="${value}"]`)
+ .first()
+ .click();
+ // eslint-disable-next-line no-await-in-loop
+ await expect(select).toContainText(value);
+ }
+ },
+
+ addStep: async () => {
+ await page.getByTestId('funnel-add-step-btn').click();
+ },
+
+ stepsCount: () => page.getByTestId('funnel-steps-count'),
+
+ stepActionsTrigger: (index) =>
+ funnels.step(index).getByTestId('funnel-step-actions'),
+ openStepActions: async (index) => {
+ await funnels.stepActionsTrigger(index).click();
+ await expect(funnels.stepDeleteAction()).toBeVisible();
+ },
+
+ stepDeleteAction: () => page.getByTestId('funnel-step-action-delete'),
+
+ deleteStep: async (index) => {
+ await funnels.openStepActions(index);
+ await funnels.stepDeleteAction().click();
+ await page.getByRole('button', { name: 'Delete Step' }).click();
+ },
+
+ latencyPointer: (index) =>
+ page.getByTestId(`funnel-step-latency-pointer-${index}`),
+
+ setLatencyPointer: async (index, pointer) => {
+ await funnels.latencyPointer(index).click();
+ await page.getByRole('menuitemradio', { name: pointer }).click();
+ await expect(funnels.latencyPointer(index)).toContainText(pointer);
+ },
+
+ saveButton: () => page.getByTestId('funnel-save-btn'),
+
+ save: async () => {
+ // The PUT body is the 200ms-debounced steps; the draft key is written from the same value.
+ await expect
+ .poll(() =>
+ page.evaluate(() => {
+ const key = Object.keys(localStorage).find((name) =>
+ name.startsWith('FUNNEL_STEPS_'),
+ );
+ const draft = key ? JSON.parse(localStorage.getItem(key) ?? '[]') : [];
+ return (
+ draft.length > 0 &&
+ draft.every(
+ (step: { service_name: string; span_name: string }) =>
+ step.service_name && step.span_name,
+ )
+ );
+ }),
+ )
+ .toBe(true);
+ const saved = page.waitForResponse(isFunnelsCall('PUT', '/steps/update'));
+ await funnels.saveButton().click();
+ expect((await saved).ok()).toBe(true);
+ },
+
+ validStatus: () => page.getByTestId('funnel-valid-traces-status'),
+ results: () => page.getByTestId('funnel-results'),
+ slowTraces: () => page.getByTestId('funnel-slowest-traces'),
+ errorTraces: () => page.getByTestId('funnel-error-traces'),
+ slowTraceIdCells: () =>
+ page.getByTestId('funnel-slowest-traces').locator('a.trace-id-cell'),
+ errorTrace: (traceId) =>
+ page.getByTestId('funnel-error-traces').getByText(traceId, { exact: true }),
+
+ traceIdsIn: async (table) =>
+ (await table.locator('a.trace-id-cell').allInnerTexts()).map((text) =>
+ text.trim(),
+ ),
+
+ traces: traceDetailsDriver(page),
+
+ addSpanModal: {
+ dialog: () => page.getByRole('dialog', { name: 'Add span to funnel' }),
+
+ open: async (spanId) => {
+ const row = page.getByTestId(`cell-0-${spanId}`);
+ // The row's action buttons are only shown on hover.
+ await row.hover();
+ await row.getByTestId('span-add-to-funnel-btn').click();
+ await expect(funnels.addSpanModal.dialog()).toBeVisible();
+ },
+
+ pickFunnel: async (id) => {
+ const dialog = funnels.addSpanModal.dialog();
+ await dialog.getByTestId(`funnel-item-${id}`).click();
+ await expect(dialog.getByTestId('funnel-step-0')).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ },
+
+ addForNewStep: async () => {
+ await funnels.addSpanModal
+ .dialog()
+ .getByTestId('funnel-add-step-btn')
+ .click();
+ },
+
+ save: async () => {
+ const saved = page.waitForResponse(isFunnelsCall('PUT', '/steps/update'));
+ await page.getByTestId('add-span-save-btn').click();
+ expect((await saved).ok()).toBe(true);
+ },
+ },
+ };
+
+ return funnels;
+}
+
+// ─── Seed ────────────────────────────────────────────────────────────────────
+
+export interface FunnelSpans {
+ /** Prefix for every funnel name in this worker; removed on close. */
+ stamp: string;
+ services: { a: string; b: string };
+ spans: { a: string; b: string };
+ /** Traces that complete both steps, the error trace included. */
+ traceIds: string[];
+ errorTraceId: string;
+ /** Root (step 1) span id per trace in `traceIds`. */
+ rootSpanIds: Record<string, string>;
+ /** A trace with only the step 1 span. */
+ dropOffTraceId: string;
+}
+
+const STEP_A = 'GET /checkout';
+const STEP_B = 'POST /charge';
+
+export const withFunnelSpans: WorkerLayer<{ funnelSpans: FunnelSpans }> =
+ seeded(
+ 'funnelSpans',
+ async ({ page, workerIndex }) => {
+ const prefix = stamp('fn', workerIndex);
+ const services = { a: `${prefix}-web`, b: `${prefix}-pay` };
+ const spans: SeederSpan[] = [];
+ const rootSpanIds: Record<string, string> = {};
+ const traceIds: string[] = [];
+
+ for (let i = 0; i < 4; i += 1) {
+ const root = rootSpan({
+ service: services.a,
+ name: STEP_A,
+ agoMs: 60_000 - i * 5_000,
+ });
+ const child = childSpan(root, {
+ service: services.b,
+ name: STEP_B,
+ offsetMs: 50,
+ status: i === 3 ? STATUS.error : STATUS.ok,
+ });
+ spans.push(root, child);
+ traceIds.push(root.trace_id);
+ rootSpanIds[root.trace_id] = root.span_id;
+ }
+ const dropOff = rootSpan({
+ service: services.a,
+ name: STEP_A,
+ agoMs: 20_000,
+ });
+ spans.push(dropOff);
+
+ await seedTracesViaSeeder(page.request, spans);
+
+ return {
+ stamp: prefix,
+ services,
+ spans: { a: STEP_A, b: STEP_B },
+ traceIds,
+ errorTraceId: traceIds[3],
+ rootSpanIds,
+ dropOffTraceId: dropOff.trace_id,
+ };
+ },
+ async ({ page, value }) => {
+ await funnelSeed(page).removeByPrefix(value.stamp);
+ },
+ );
+
+export const withFunnels: Layer<{ funnels: Funnels }> = driver(
+ 'funnels',
+ ({ page }) => funnelsDriver(page),
+);
+
+/** The trace funnels `test`. */
+export const test = withFunnelSpans(withFunnels(kit));
+export {
+ allowFor,
+ expect,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+} from './kit';
diff --git a/tests/e2e/drivers/infra/__generated__/datasets.ts b/tests/e2e/drivers/infra/__generated__/datasets.ts
new file mode 100644
index 0000000000..27e6c969fd
--- /dev/null
+++ b/tests/e2e/drivers/infra/__generated__/datasets.ts
@@ -0,0 +1,951 @@
+/**
+ * AI-maintained. Regenerate with `pnpm exec tsx drivers/infra/derive-datasets.ts`
+ * after the integration fixtures change; `assertDatasetFacts` re-derives every
+ * value here at seed time, so a stale entry fails loudly rather than silently.
+ *
+ * Logical dataset name → the JSONL fixture that backs it, plus the facts a spec
+ * needs to assert against it. Specs never hardcode a filename or a pod name.
+ *
+ * The fixtures live in `tests/integration/testdata/inframonitoring/` and are
+ * owned by the Python integration suite. They are **read, not copied** — one
+ * source of truth instead of a drifting duplicate under `tests/e2e/testdata/`.
+ */
+
+import fs from 'fs';
+import path from 'path';
+
+/** Where the integration suite keeps its inframonitoring fixtures. */
+export const TESTDATA_DIR = path.resolve(
+ __dirname,
+ '../../../../integration/testdata/inframonitoring',
+);
+
+export interface DatasetFacts {
+ /** Fixture basename, without the `.jsonl` extension. */
+ file: string;
+ /** Which entity's list endpoint reports the rows. */
+ entity: string;
+ /** Entity names the dataset seeds, sorted. */
+ names: string[];
+ /** Namespaces present, when the dataset carries `k8s.namespace.name`. */
+ namespaces?: string[];
+ /** Clusters present, when the dataset carries `k8s.cluster.name`. */
+ clusters?: string[];
+ /** Group label → member count, keyed by the attribute the group is on. */
+ groups?: Record<string, Record<string, number>>;
+ /** Notes on what the dataset exists to exercise. */
+ purpose: string;
+}
+
+/**
+ * Every dataset a spec references. `names`/`groups` are transcribed from the
+ * fixtures; {@link assertDatasetFacts} re-derives them at runtime so a fixture
+ * edit fails loudly here instead of silently in an unrelated assertion.
+ */
+export const DATASETS = {
+ // ── hosts ────────────────────────────────────────────────────────────────
+ hosts_value_accuracy: {
+ file: 'hosts_value_accuracy',
+ entity: 'hosts',
+ names: ['acc-h1', 'acc-h2'],
+ purpose: 'happy-path host list; has a *_expected.json assertion source',
+ },
+ hosts_pagination: {
+ file: 'hosts_pagination',
+ entity: 'hosts',
+ names: [
+ 'page-h1',
+ 'page-h2',
+ 'page-h3',
+ 'page-h4',
+ 'page-h5',
+ 'page-h6',
+ 'page-h7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ hosts_orderby: {
+ file: 'hosts_orderby',
+ entity: 'hosts',
+ names: ['order-h1', 'order-h2', 'order-h3', 'order-h4', 'order-h5'],
+ purpose: 'table TC-08',
+ },
+ hosts_filter_dataset: {
+ file: 'hosts_filter_dataset',
+ entity: 'hosts',
+ names: ['dev-linux-1', 'dev-windows-1', 'prod-linux-1', 'prod-windows-1'],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ hosts_missing_metrics: {
+ file: 'hosts_missing_metrics',
+ entity: 'hosts',
+ names: ['miss-h1'],
+ purpose: '`-`/TextNoData rendering',
+ },
+ hosts_status: {
+ file: 'hosts_status',
+ entity: 'hosts',
+ names: ['active-h1', 'inactive-h1'],
+ purpose: 'hosts TC-02/hosts TC-03 — Active/Inactive status filter and badge',
+ },
+ hosts_groupby_os_type: {
+ file: 'hosts_groupby_os_type',
+ entity: 'hosts',
+ names: [],
+ groups: { 'os.type': { linux: 3, windows: 3 } },
+ purpose: 'hosts TC-07 and the hosts arm of group-by TC-*',
+ },
+
+ // ── pods ─────────────────────────────────────────────────────────────────
+ pods_value_accuracy: {
+ file: 'pods_value_accuracy',
+ entity: 'pods',
+ names: ['acc-p1', 'acc-p2'],
+ namespaces: ['ns-a', 'ns-b'],
+ clusters: ['cluster-x'],
+ purpose:
+ 'happy-path pod list; carries `k8s.pod.uid` (acc-p1-uid, acc-p2-uid)',
+ },
+ pods_pagination: {
+ file: 'pods_pagination',
+ entity: 'pods',
+ names: [
+ 'page-p1',
+ 'page-p2',
+ 'page-p3',
+ 'page-p4',
+ 'page-p5',
+ 'page-p6',
+ 'page-p7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ pods_orderby: {
+ file: 'pods_orderby',
+ entity: 'pods',
+ names: ['order-p1', 'order-p2', 'order-p3', 'order-p4', 'order-p5'],
+ purpose: 'table TC-08',
+ },
+ pods_groupby: {
+ file: 'pods_groupby',
+ entity: 'pods',
+ names: [],
+ groups: {
+ 'k8s.namespace.name': { 'gns-a': 2, 'gns-b': 2 },
+ 'k8s.node.name': { 'node-a': 2, 'node-b': 2 },
+ },
+ purpose:
+ 'group-by TC-*, expanded-row TC-* (clone up for the >10 member cases)',
+ },
+ pods_filter_dataset: {
+ file: 'pods_filter_dataset',
+ entity: 'pods',
+ names: [
+ 'api-dev-1',
+ 'api-dev-2',
+ 'api-prod-1',
+ 'api-prod-2',
+ 'web-dev-1',
+ 'web-dev-2',
+ 'web-prod-1',
+ 'web-prod-2',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ pods_missing_metrics: {
+ file: 'pods_missing_metrics',
+ entity: 'pods',
+ names: ['miss-p1'],
+ purpose: 'pods TC-08 — a pod missing a metric renders `-`, not `0`',
+ },
+ pods_phases: {
+ file: 'pods_phases',
+ entity: 'pods',
+ names: ['clbo-a', 'clbo-b', 'fail-p', 'pend-p', 'run-p', 'succ-p', 'unk-p'],
+ purpose: 'pods TC-01 — one pod per status, plus a `no_data` pod',
+ },
+ pods_phases_grouped: {
+ file: 'pods_phases_grouped',
+ entity: 'pods',
+ names: [],
+ groups: { 'k8s.namespace.name': { 'ns-mixed': 6 } },
+ purpose: 'pods TC-02 — podCountsByStatus breakdown in grouped view',
+ },
+ pods_phases_transition: {
+ file: 'pods_phases_transition',
+ entity: 'pods',
+ names: ['trans-p'],
+ purpose: 'a pod whose phase flips mid-window reports the latest state',
+ },
+
+ // ── nodes ────────────────────────────────────────────────────────────────
+ nodes_value_accuracy: {
+ file: 'nodes_value_accuracy',
+ entity: 'nodes',
+ names: ['acc-n1', 'acc-n2'],
+ clusters: ['cluster-x', 'cluster-y'],
+ purpose: 'happy-path node list',
+ },
+ nodes_pagination: {
+ file: 'nodes_pagination',
+ entity: 'nodes',
+ names: [
+ 'carrier-phantom-host',
+ 'page-n1',
+ 'page-n2',
+ 'page-n3',
+ 'page-n4',
+ 'page-n5',
+ 'page-n6',
+ 'page-n7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ nodes_orderby: {
+ file: 'nodes_orderby',
+ entity: 'nodes',
+ names: [
+ 'carrier-phantom-host',
+ 'order-n1',
+ 'order-n2',
+ 'order-n3',
+ 'order-n4',
+ 'order-n5',
+ ],
+ purpose: 'table TC-08',
+ },
+ nodes_groupby: {
+ file: 'nodes_groupby',
+ entity: 'nodes',
+ names: [],
+ groups: {
+ 'k8s.cluster.name': { 'gb-cluster-a': 2, 'gb-cluster-b': 2 },
+ },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ nodes_filter_dataset: {
+ file: 'nodes_filter_dataset',
+ entity: 'nodes',
+ names: [
+ 'api-a-eu-1',
+ 'api-a-us-1',
+ 'api-b-eu-1',
+ 'api-b-us-1',
+ 'web-a-eu-1',
+ 'web-a-us-1',
+ 'web-b-eu-1',
+ 'web-b-us-1',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ nodes_missing_metrics: {
+ file: 'nodes_missing_metrics',
+ entity: 'nodes',
+ names: ['miss-n1'],
+ purpose: '`-`/TextNoData rendering',
+ },
+ nodes_conditions: {
+ file: 'nodes_conditions',
+ entity: 'nodes',
+ names: [
+ 'carrier-phantom-host',
+ 'notready-n',
+ 'ready-n',
+ 'ready-n2',
+ 'ready-n3',
+ 'ready-n4',
+ ],
+ purpose: 'nodes TC-01 — Ready / NotReady / NoData condition badges',
+ },
+ nodes_conditions_transition: {
+ file: 'nodes_conditions_transition',
+ entity: 'nodes',
+ names: ['carrier-phantom-host', 'trans-n'],
+ purpose: 'nodes TC-02 — a node whose condition flips mid-window',
+ },
+ nodes_conditions_grouped: {
+ file: 'nodes_conditions_grouped',
+ entity: 'nodes',
+ names: [],
+ groups: { 'k8s.cluster.name': { 'cluster-mixed': 3 } },
+ purpose: 'nodes TC-03 — Pod Status ready vs not-ready counts',
+ },
+
+ // ── namespaces ───────────────────────────────────────────────────────────
+ namespaces_value_accuracy: {
+ file: 'namespaces_value_accuracy',
+ entity: 'namespaces',
+ names: ['acc-ns-1', 'acc-ns-2'],
+ clusters: ['cluster-x', 'cluster-y'],
+ purpose: 'happy-path namespace list; feeds namespaces TC-01 counts cards',
+ },
+ namespaces_pagination: {
+ file: 'namespaces_pagination',
+ entity: 'namespaces',
+ names: [
+ 'page-ns-1',
+ 'page-ns-2',
+ 'page-ns-3',
+ 'page-ns-4',
+ 'page-ns-5',
+ 'page-ns-6',
+ 'page-ns-7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ namespaces_orderby: {
+ file: 'namespaces_orderby',
+ entity: 'namespaces',
+ names: ['order-ns-1', 'order-ns-2', 'order-ns-3', 'order-ns-4', 'order-ns-5'],
+ purpose: 'table TC-08',
+ },
+ namespaces_groupby: {
+ file: 'namespaces_groupby',
+ entity: 'namespaces',
+ names: [],
+ groups: { 'k8s.cluster.name': { 'gb-cluster-a': 2, 'gb-cluster-b': 2 } },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ namespaces_filter_dataset: {
+ file: 'namespaces_filter_dataset',
+ entity: 'namespaces',
+ names: [
+ 'api-a-dev',
+ 'api-a-prod',
+ 'api-b-dev',
+ 'api-b-prod',
+ 'web-a-dev',
+ 'web-a-prod',
+ 'web-b-dev',
+ 'web-b-prod',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ namespaces_missing_metrics: {
+ file: 'namespaces_missing_metrics',
+ entity: 'namespaces',
+ names: ['miss-ns'],
+ purpose: '`-`/TextNoData rendering',
+ },
+ namespaces_same_name_across_clusters: {
+ file: 'namespaces_same_name_across_clusters',
+ entity: 'namespaces',
+ names: ['dup-ns'],
+ purpose:
+ 'namespaces TC-04 — one namespace name in two clusters stays two rows',
+ },
+
+ // ── clusters ─────────────────────────────────────────────────────────────
+ clusters_value_accuracy: {
+ file: 'clusters_value_accuracy',
+ entity: 'clusters',
+ names: ['acc-cluster-1', 'acc-cluster-2'],
+ purpose: 'happy-path cluster list; feeds clusters TC-01 counts cards',
+ },
+ clusters_pagination: {
+ file: 'clusters_pagination',
+ entity: 'clusters',
+ names: [
+ 'page-c1',
+ 'page-c2',
+ 'page-c3',
+ 'page-c4',
+ 'page-c5',
+ 'page-c6',
+ 'page-c7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ clusters_orderby: {
+ file: 'clusters_orderby',
+ entity: 'clusters',
+ names: ['order-c1', 'order-c2', 'order-c3', 'order-c4', 'order-c5'],
+ purpose: 'table TC-08',
+ },
+ clusters_groupby: {
+ file: 'clusters_groupby',
+ entity: 'clusters',
+ names: [],
+ groups: {
+ 'k8s.cluster.name': {
+ 'gb-gcp-1': 1,
+ 'gb-gcp-2': 1,
+ 'gb-aws-1': 1,
+ 'gb-aws-2': 1,
+ },
+ },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ clusters_filter_dataset: {
+ file: 'clusters_filter_dataset',
+ entity: 'clusters',
+ names: [
+ 'api-aws-dev',
+ 'api-aws-prod',
+ 'api-gcp-dev',
+ 'api-gcp-prod',
+ 'web-aws-dev',
+ 'web-aws-prod',
+ 'web-gcp-dev',
+ 'web-gcp-prod',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ clusters_missing_metrics: {
+ file: 'clusters_missing_metrics',
+ entity: 'clusters',
+ names: ['miss-cluster'],
+ purpose: '`-`/TextNoData rendering',
+ },
+ clusters_node_readiness: {
+ file: 'clusters_node_readiness',
+ entity: 'clusters',
+ names: ['rn-cluster'],
+ purpose: 'clusters TC-02 — Node Readiness column and breakdown tooltip',
+ },
+ clusters_pod_phases: {
+ file: 'clusters_pod_phases',
+ entity: 'clusters',
+ names: ['pp-cluster'],
+ purpose: 'clusters TC-04 — pod-phase roll-up into Pod Status',
+ },
+
+ // ── deployments ──────────────────────────────────────────────────────────
+ deployments_value_accuracy: {
+ file: 'deployments_value_accuracy',
+ entity: 'deployments',
+ names: ['acc-dep-1', 'acc-dep-2'],
+ namespaces: ['ns-acc'],
+ clusters: ['cluster-x'],
+ purpose: 'happy-path deployment list',
+ },
+ deployments_pagination: {
+ file: 'deployments_pagination',
+ entity: 'deployments',
+ names: [
+ 'page-dep-1',
+ 'page-dep-2',
+ 'page-dep-3',
+ 'page-dep-4',
+ 'page-dep-5',
+ 'page-dep-6',
+ 'page-dep-7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ deployments_orderby: {
+ file: 'deployments_orderby',
+ entity: 'deployments',
+ names: [
+ 'order-dep-1',
+ 'order-dep-2',
+ 'order-dep-3',
+ 'order-dep-4',
+ 'order-dep-5',
+ ],
+ purpose: 'table TC-08',
+ },
+ deployments_groupby: {
+ file: 'deployments_groupby',
+ entity: 'deployments',
+ names: [],
+ groups: { 'k8s.namespace.name': { 'gb-ns-a': 2, 'gb-ns-b': 2 } },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ deployments_filter_dataset: {
+ file: 'deployments_filter_dataset',
+ entity: 'deployments',
+ names: [
+ 'api-a-dev',
+ 'api-a-prod',
+ 'api-b-dev',
+ 'api-b-prod',
+ 'web-a-dev',
+ 'web-a-prod',
+ 'web-b-dev',
+ 'web-b-prod',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ deployments_missing_metrics: {
+ file: 'deployments_missing_metrics',
+ entity: 'deployments',
+ names: ['miss-dep'],
+ purpose: '`-`/TextNoData rendering',
+ },
+ deployments_desired_available: {
+ file: 'deployments_desired_available',
+ entity: 'deployments',
+ names: ['da-dep'],
+ purpose:
+ 'deployments TC-01 — Pod Replicas available/desired with the warning colour',
+ },
+ deployments_non_deployment_pods: {
+ file: 'deployments_non_deployment_pods',
+ entity: 'deployments',
+ names: ['nd-dep'],
+ purpose:
+ 'deployments TC-05 — pods not owned by a deployment stay out of the roll-up',
+ },
+ deployments_same_name_across_ns_and_clusters: {
+ file: 'deployments_same_name_across_ns_and_clusters',
+ entity: 'deployments',
+ names: ['dup-dep'],
+ purpose:
+ 'deployments TC-04 — same name across namespaces/clusters stays distinct rows',
+ },
+
+ // ── statefulsets ─────────────────────────────────────────────────────────
+ statefulsets_value_accuracy: {
+ file: 'statefulsets_value_accuracy',
+ entity: 'statefulsets',
+ names: ['acc-ss-1', 'acc-ss-2'],
+ namespaces: ['ns-acc'],
+ clusters: ['cluster-x'],
+ purpose: 'happy-path statefulset list',
+ },
+ statefulsets_pagination: {
+ file: 'statefulsets_pagination',
+ entity: 'statefulsets',
+ names: [
+ 'page-ss-1',
+ 'page-ss-2',
+ 'page-ss-3',
+ 'page-ss-4',
+ 'page-ss-5',
+ 'page-ss-6',
+ 'page-ss-7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ statefulsets_orderby: {
+ file: 'statefulsets_orderby',
+ entity: 'statefulsets',
+ names: ['order-ss-1', 'order-ss-2', 'order-ss-3', 'order-ss-4', 'order-ss-5'],
+ purpose: 'table TC-08',
+ },
+ statefulsets_groupby: {
+ file: 'statefulsets_groupby',
+ entity: 'statefulsets',
+ names: [],
+ groups: { 'k8s.namespace.name': { 'gb-ns-a': 2, 'gb-ns-b': 2 } },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ statefulsets_filter_dataset: {
+ file: 'statefulsets_filter_dataset',
+ entity: 'statefulsets',
+ names: [
+ 'api-a-dev',
+ 'api-a-prod',
+ 'api-b-dev',
+ 'api-b-prod',
+ 'web-a-dev',
+ 'web-a-prod',
+ 'web-b-dev',
+ 'web-b-prod',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ statefulsets_desired_current: {
+ file: 'statefulsets_desired_current',
+ entity: 'statefulsets',
+ names: ['dc-ss'],
+ purpose: 'statefulsets TC-01 — Pod Replicas current/desired',
+ },
+ statefulsets_non_ss_pods: {
+ file: 'statefulsets_non_ss_pods',
+ entity: 'statefulsets',
+ names: ['ns-ss'],
+ purpose: 'statefulsets TC-05 — non-statefulset pods excluded',
+ },
+ statefulsets_same_name_across_ns_and_clusters: {
+ file: 'statefulsets_same_name_across_ns_and_clusters',
+ entity: 'statefulsets',
+ names: ['dup-ss'],
+ purpose: 'identity/dedup',
+ },
+
+ // ── daemonsets ───────────────────────────────────────────────────────────
+ daemonsets_value_accuracy: {
+ file: 'daemonsets_value_accuracy',
+ entity: 'daemonsets',
+ names: ['acc-ds-1', 'acc-ds-2'],
+ namespaces: ['ns-acc'],
+ clusters: ['cluster-x'],
+ purpose: 'happy-path daemonset list',
+ },
+ daemonsets_pagination: {
+ file: 'daemonsets_pagination',
+ entity: 'daemonsets',
+ names: [
+ 'page-ds-1',
+ 'page-ds-2',
+ 'page-ds-3',
+ 'page-ds-4',
+ 'page-ds-5',
+ 'page-ds-6',
+ 'page-ds-7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ daemonsets_orderby: {
+ file: 'daemonsets_orderby',
+ entity: 'daemonsets',
+ names: ['order-ds-1', 'order-ds-2', 'order-ds-3', 'order-ds-4', 'order-ds-5'],
+ purpose: 'table TC-08',
+ },
+ daemonsets_groupby: {
+ file: 'daemonsets_groupby',
+ entity: 'daemonsets',
+ names: [],
+ groups: { 'k8s.namespace.name': { 'gb-ns-a': 2, 'gb-ns-b': 2 } },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ daemonsets_filter_dataset: {
+ file: 'daemonsets_filter_dataset',
+ entity: 'daemonsets',
+ names: [
+ 'logs-a-dev',
+ 'logs-a-prod',
+ 'logs-b-dev',
+ 'logs-b-prod',
+ 'metrics-a-dev',
+ 'metrics-a-prod',
+ 'metrics-b-dev',
+ 'metrics-b-prod',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ daemonsets_desired_current: {
+ file: 'daemonsets_desired_current',
+ entity: 'daemonsets',
+ names: ['dc-ds'],
+ purpose: 'daemonsets TC-01 — Scheduled Nodes',
+ },
+ daemonsets_non_ds_pods: {
+ file: 'daemonsets_non_ds_pods',
+ entity: 'daemonsets',
+ names: ['nd-ds'],
+ purpose: 'non-daemonset pods excluded',
+ },
+ daemonsets_same_name_across_ns_and_clusters: {
+ file: 'daemonsets_same_name_across_ns_and_clusters',
+ entity: 'daemonsets',
+ names: ['dup-ds'],
+ purpose: 'identity/dedup',
+ },
+
+ // ── jobs ─────────────────────────────────────────────────────────────────
+ jobs_value_accuracy: {
+ file: 'jobs_value_accuracy',
+ entity: 'jobs',
+ names: ['acc-job-1', 'acc-job-2'],
+ namespaces: ['ns-acc'],
+ clusters: ['cluster-x'],
+ purpose: 'happy-path job list',
+ },
+ jobs_pagination: {
+ file: 'jobs_pagination',
+ entity: 'jobs',
+ names: [
+ 'page-job-1',
+ 'page-job-2',
+ 'page-job-3',
+ 'page-job-4',
+ 'page-job-5',
+ 'page-job-6',
+ 'page-job-7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ jobs_orderby: {
+ file: 'jobs_orderby',
+ entity: 'jobs',
+ names: [
+ 'order-job-1',
+ 'order-job-2',
+ 'order-job-3',
+ 'order-job-4',
+ 'order-job-5',
+ ],
+ purpose: 'table TC-08',
+ },
+ jobs_groupby: {
+ file: 'jobs_groupby',
+ entity: 'jobs',
+ names: [],
+ groups: { 'k8s.namespace.name': { 'gb-ns-a': 2, 'gb-ns-b': 2 } },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ jobs_filter_dataset: {
+ file: 'jobs_filter_dataset',
+ entity: 'jobs',
+ names: [
+ 'cron-a-dev',
+ 'cron-a-prod',
+ 'cron-b-dev',
+ 'cron-b-prod',
+ 'etl-a-dev',
+ 'etl-a-prod',
+ 'etl-b-dev',
+ 'etl-b-prod',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ jobs_missing_metrics: {
+ file: 'jobs_missing_metrics',
+ entity: 'jobs',
+ names: ['miss-job'],
+ purpose: '`-`/TextNoData rendering',
+ },
+ jobs_lifecycle: {
+ file: 'jobs_lifecycle',
+ entity: 'jobs',
+ names: ['lc-job'],
+ purpose: 'jobs TC-01 — Completions column',
+ },
+ jobs_completed: {
+ file: 'jobs_completed',
+ entity: 'jobs',
+ names: ['done-job'],
+ purpose: 'jobs TC-03 — a completed job still lists with its final counts',
+ },
+ jobs_non_job_pods: {
+ file: 'jobs_non_job_pods',
+ entity: 'jobs',
+ names: ['nj-job'],
+ purpose: 'non-job pods excluded',
+ },
+ jobs_same_name_across_ns_and_clusters: {
+ file: 'jobs_same_name_across_ns_and_clusters',
+ entity: 'jobs',
+ names: ['dup-job'],
+ purpose: 'identity/dedup',
+ },
+
+ // ── volumes ──────────────────────────────────────────────────────────────
+ volumes_value_accuracy: {
+ file: 'volumes_value_accuracy',
+ entity: 'volumes',
+ names: ['acc-pvc-1', 'acc-pvc-2'],
+ namespaces: ['ns-acc'],
+ clusters: ['cluster-x'],
+ purpose: 'happy-path volume list',
+ },
+ volumes_pagination: {
+ file: 'volumes_pagination',
+ entity: 'volumes',
+ names: [
+ 'page-pvc-1',
+ 'page-pvc-2',
+ 'page-pvc-3',
+ 'page-pvc-4',
+ 'page-pvc-5',
+ 'page-pvc-6',
+ 'page-pvc-7',
+ ],
+ purpose: 'table TC-06/07/16',
+ },
+ volumes_orderby: {
+ file: 'volumes_orderby',
+ entity: 'volumes',
+ names: [
+ 'order-pvc-1',
+ 'order-pvc-2',
+ 'order-pvc-3',
+ 'order-pvc-4',
+ 'order-pvc-5',
+ ],
+ purpose: 'table TC-08',
+ },
+ volumes_groupby: {
+ file: 'volumes_groupby',
+ entity: 'volumes',
+ names: [],
+ groups: { 'k8s.namespace.name': { 'gb-ns-a': 2, 'gb-ns-b': 2 } },
+ purpose: 'group-by TC-*, expanded-row TC-*',
+ },
+ volumes_filter_dataset: {
+ file: 'volumes_filter_dataset',
+ entity: 'volumes',
+ names: [
+ 'data-ns-a-dev',
+ 'data-ns-a-prod',
+ 'data-ns-b-dev',
+ 'data-ns-b-prod',
+ 'logs-ns-a-dev',
+ 'logs-ns-a-prod',
+ 'logs-ns-b-dev',
+ 'logs-ns-b-prod',
+ ],
+ purpose: 'filters TC-02/04/07/09',
+ },
+ volumes_usage_formula: {
+ file: 'volumes_usage_formula',
+ entity: 'volumes',
+ names: ['uf-pvc'],
+ purpose: 'volumes TC-01 — Used progress bar computed from the usage formula',
+ },
+ volumes_non_pvc_volume: {
+ file: 'volumes_non_pvc_volume',
+ entity: 'volumes',
+ names: ['np-real-pvc'],
+ purpose: 'volumes TC-05 — non-PVC volumes excluded',
+ },
+ volumes_formula_operand_missing: {
+ file: 'volumes_formula_operand_missing',
+ entity: 'volumes',
+ names: ['fop-pvc'],
+ purpose:
+ 'volumes TC-06 — a formula with a missing operand renders `-`, no crash',
+ },
+ volumes_same_name_across_ns_and_clusters: {
+ file: 'volumes_same_name_across_ns_and_clusters',
+ entity: 'volumes',
+ names: ['dup-pvc'],
+ purpose: 'identity/dedup',
+ },
+} satisfies Record<string, DatasetFacts>;
+
+export type DatasetKey = keyof typeof DATASETS;
+
+/**
+ * A dataset's facts, widened to {@link DatasetFacts}. Reach for this rather than
+ * indexing `DATASETS` directly: the literal type of each entry omits the
+ * optional keys it does not set, so `DATASETS[key].groups` does not type-check
+ * across the union.
+ */
+export function datasetFacts(key: DatasetKey): DatasetFacts {
+ return DATASETS[key];
+}
+
+export function datasetPath(key: DatasetKey): string {
+ return path.join(TESTDATA_DIR, `${DATASETS[key].file}.jsonl`);
+}
+
+/**
+ * One row of a `*_value_accuracy_expected.json`.
+ *
+ * Deliberately open: each entity's file uses its own field names
+ * (`podCPU`, `volumeUsage`, `namespaceCPU` …) and namespaces nests a `counts`
+ * object. Callers reach for the field they are asserting and
+ * {@link expectedRecord} does the "is it actually there" check.
+ */
+export interface ExpectedRecord {
+ [field: string]: string | number | Record<string, number> | undefined;
+}
+
+export interface ExpectedValues {
+ records: ExpectedRecord[];
+}
+
+/**
+ * The integration suite's `*_value_accuracy_expected.json`, when one exists —
+ * the assertion source for value-accuracy scenarios, so expected numbers are
+ * read rather than invented.
+ *
+ * Returns `null` when the dataset has no expectation file; use
+ * {@link expectedRecord} when the scenario requires one.
+ */
+export function expectedValues(key: DatasetKey): ExpectedValues | null {
+ const file = path.join(TESTDATA_DIR, `${DATASETS[key].file}_expected.json`);
+ if (!fs.existsSync(file)) {
+ return null;
+ }
+ return JSON.parse(fs.readFileSync(file, 'utf8')) as ExpectedValues;
+}
+
+/**
+ * One named record from a dataset's expectation file, or a failure that says
+ * which dataset and which record.
+ *
+ * This is the entry point value-accuracy scenarios should use. Reading the
+ * expected number rather than hardcoding it is what keeps a fixture edit from
+ * silently invalidating an assertion — and what stops a scenario settling for
+ * `not.toHaveText('')`, which passes on the `-` that means "no data".
+ */
+export function expectedRecord(
+ key: DatasetKey,
+ nameField: string,
+ name: string,
+): ExpectedRecord {
+ const expected = expectedValues(key);
+ if (!expected) {
+ throw new Error(
+ `dataset ${key} has no *_expected.json — value-accuracy assertions need one`,
+ );
+ }
+ const record = expected.records.find((row) => row[nameField] === name);
+ if (!record) {
+ const found = expected.records.map((row) => String(row[nameField]));
+ throw new Error(
+ `dataset ${key}: no expected record with ${nameField}='${name}' (found ${found.join(', ')})`,
+ );
+ }
+ return record;
+}
+
+/**
+ * A metric's value for one named entity, read straight out of the fixture.
+ *
+ * The companion to {@link expectedRecord}, and needed because the two do not
+ * cover the same ground: `*_expected.json` exists only for the ten
+ * `*_value_accuracy` datasets, while most value-accuracy *scenarios* seed a
+ * different fixture (`deployments_desired_available`, `jobs_lifecycle`,
+ * `volumes_usage_formula`, …) that has no expectation file. Those still must not
+ * hardcode a magic number — §6's rule is "read it, don't invent it", and a
+ * fixture edit should fail the assertion rather than silently invalidate it.
+ *
+ * Also the right source when the expectation file records a *different* quantity
+ * than the column under test: `pods_value_accuracy_expected.json` carries
+ * `podCPULimit` (the limit, in cores) while the `cpu_limit` column renders
+ * `k8s.pod.cpu_limit_utilization` (a ratio).
+ */
+export function fixtureMetric(
+ key: DatasetKey,
+ nameLabel: string,
+ name: string,
+ metricName: string,
+): number {
+ const file = datasetPath(key);
+ const rows = fs
+ .readFileSync(file, 'utf8')
+ .split('\n')
+ .filter((line) => line.trim() !== '')
+ .map(
+ (line) =>
+ JSON.parse(line) as {
+ metric_name?: string;
+ labels?: Record<string, string>;
+ value?: number;
+ },
+ );
+ const match = rows.find(
+ (row) => row.metric_name === metricName && row.labels?.[nameLabel] === name,
+ );
+ if (match?.value === undefined) {
+ const available = [
+ ...new Set(
+ rows
+ .filter((row) => row.labels?.[nameLabel] === name)
+ .map((row) => row.metric_name ?? '?'),
+ ),
+ ];
+ throw new Error(
+ `dataset ${key}: no '${metricName}' for ${nameLabel}='${name}' ` +
+ `(that entity has ${available.join(', ') || 'no rows'})`,
+ );
+ }
+ return match.value;
+}
+
+/** A numeric field from an expected record, checked rather than coerced. */
+export function expectedNumber(record: ExpectedRecord, field: string): number {
+ const value = record[field];
+ if (typeof value !== 'number') {
+ throw new Error(
+ `expected record has no numeric '${field}' (got ${JSON.stringify(value)})`,
+ );
+ }
+ return value;
+}
diff --git a/tests/e2e/drivers/infra/driver.ts b/tests/e2e/drivers/infra/driver.ts
new file mode 100644
index 0000000000..03466f3eb9
--- /dev/null
+++ b/tests/e2e/drivers/infra/driver.ts
@@ -0,0 +1,588 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { driver, SEEDED_DATA_TIMEOUT, type Layer } from '../kit';
+import {
+ expressionParams,
+ querySearchDriver,
+ type QuerySearch,
+} from '../querysearch';
+import { resetKeys } from '../storage';
+import { columnStorageKey } from '../storage';
+import { tanstackDriver, type Tanstack } from '../tanstack';
+
+import { K8S_PATH, type EntityDef, type K8sCategory } from './entities';
+
+/**
+ * Driving infra monitoring: the list, the drawer, and the state they share.
+ *
+ * Two details are load-bearing and were paid for in flake. Locators are
+ * table-scoped, because an entity's name also appears as a quick-filter checkbox
+ * in the left rail and clicking that only applies a filter. And row clicks are
+ * retried, because the list re-renders as the counts and list requests settle,
+ * so a single click can land on a detaching row.
+ */
+
+const TOOLBAR = {
+ groupBySelect: 'k8s-table-group-by-select',
+ optionsButton: 'k8s-table-options-button',
+ runQuery: 'list-run-query-btn',
+} as const;
+
+export const EMPTY_STATE = {
+ empty: 'k8s-empty-state',
+ retention: 'k8s-empty-state-retention',
+ error: 'k8s-error-state',
+} as const;
+
+export const NO_RESULTS_TEXT =
+ 'This query had no results. Edit your query and try again!';
+
+/** Global table preferences: font size and line clamp, shared by every entity. */
+export const TABLE_PREFERENCES_KEY =
+ '@signoz/infra-monitoring-table-preferences';
+
+export const DRAWER = {
+ wrapper: 'drawer-wrapper',
+ close: 'close-drawer-button',
+ copyId: 'copy-id-button',
+ tabBar: 'drawer-tab-bar',
+ timeSelection: 'drawer-time-selection',
+ resetToListTime: 'reset-to-list-time-button',
+} as const;
+
+export const DRAWER_TAB = {
+ overview: 'overview',
+ metrics: 'metrics',
+ logs: 'logs',
+ traces: 'traces',
+ events: 'events',
+ podMetrics: 'pod_metrics',
+} as const;
+
+export type DrawerView = (typeof DRAWER_TAB)[keyof typeof DRAWER_TAB];
+
+export const DRAWER_STATE = {
+ emptyState: 'entity-empty-state',
+ errorState: 'entity-error-state',
+ eventsNotConfigured: 'events-not-configured',
+} as const;
+
+export const METRICS = {
+ chartHeader: 'chart-header',
+ table: 'metrics-table',
+ /** The panel body. Carries `data-has-data`, so an empty panel is observable. */
+ chart: 'entity-metrics-chart',
+} as const;
+
+export const EXPLORER_LINK = {
+ logs: 'open-logs-explorer',
+ traces: 'open-traces-explorer',
+} as const;
+
+/** The tab labels, for reading back which views the bar rendered. */
+const TAB_LABEL: Record<DrawerView, string> = {
+ [DRAWER_TAB.overview]: 'Overview',
+ [DRAWER_TAB.metrics]: 'Metrics',
+ [DRAWER_TAB.logs]: 'Logs',
+ [DRAWER_TAB.traces]: 'Traces',
+ [DRAWER_TAB.events]: 'Events',
+ [DRAWER_TAB.podMetrics]: 'Pod Metrics',
+};
+
+export interface InfraList {
+ url(entity: EntityDef, params?: Record<string, string>): string;
+ goto(entity: EntityDef, params?: Record<string, string>): Promise<void>;
+ /**
+ * Open `entity`'s list showing only `names`.
+ *
+ * Seeding is additive and the stack is shared across workers, so an unscoped
+ * list can push the row under test onto page 3 the moment a sibling spec
+ * seeds the same entity.
+ */
+ gotoScoped(
+ entity: EntityDef,
+ names: string[],
+ params?: Record<string, string>,
+ ): Promise<void>;
+ /**
+ * Open `entity`'s list scoped to one group label. The grouped page size is
+ * viewport-derived, so on an unscoped grouped list the group under test is
+ * regularly not on page one.
+ */
+ gotoGroupScoped(
+ entity: EntityDef,
+ groupLabel: string,
+ params?: Record<string, string>,
+ ): Promise<void>;
+ /**
+ * Load the kubernetes route, or `entity`'s list, without waiting for the list
+ * to answer: for assertions on the shell and the URL.
+ */
+ load(entity?: EntityDef): Promise<void>;
+ switchCategory(category: K8sCategory): Promise<void>;
+ expectCategoryActive(category: K8sCategory): Promise<void>;
+ /** Every category rail button, in render order. */
+ categoryTabs(): Locator;
+ /** A status toggle on the hosts list, e.g. `inactive`. */
+ statusFilter(value: string): Locator;
+ /** A table driver bound to `entity`'s storage keys and row testids. */
+ table(entity: EntityDef): Tanstack;
+ search: QuerySearch;
+ optionsButton(): Locator;
+ emptyState(): Locator;
+ retentionState(): Locator;
+ errorState(): Locator;
+ noResults(): Locator;
+ /** Clear every persisted table key for `entity`, once, before navigating. */
+ resetState(entity: EntityDef): Promise<void>;
+ /** Whether a URL is the entity *list* request, not the instrumentation check. */
+ isListRequest(url: string): boolean;
+ quickFiltersToggle(): Locator;
+ quickFilterSections(): Locator;
+ /** Assert a set of URL params, `null` meaning "absent". */
+ expectUrlParams(expected: Record<string, string | null>): Promise<void>;
+ /** The grouped list's row for `groupLabel`. */
+ groupRow(groupLabel: string): Locator;
+ expandGroup(groupLabel: string): Promise<Locator>;
+ collapseGroup(groupLabel: string): Promise<void>;
+ expandedTable(): Locator;
+ expandedRows(): Locator;
+ expectExpandedVisible(): Promise<void>;
+ /** The expanded group's way past `EXPANDED_ROW_LIMIT`. */
+ viewAllButton(): Locator;
+}
+
+export interface InfraDrawer {
+ panel(): Locator;
+ title(): Locator;
+ open(rowKey: string): Promise<Locator>;
+ openInNewTab(rowKey: string): Promise<Page>;
+ /** Click a compass link; the explorer opens in a new tab, which is returned. */
+ openExplorer(
+ link: (typeof EXPLORER_LINK)[keyof typeof EXPLORER_LINK],
+ ): Promise<Page>;
+ /** Wait for the drawer shell. Proves only that it opened. */
+ expectVisible(): Promise<Locator>;
+ /**
+ * Wait for the body — the part gated behind the entity-details query.
+ * Required before any absence assertion about drawer content, which would
+ * otherwise pass against a still-loading drawer.
+ */
+ expectBodyReady(): Promise<Locator>;
+ close(): Promise<void>;
+ tabBar(): Locator;
+ tab(view: DrawerView): Locator;
+ switchTab(view: DrawerView): Promise<void>;
+ renderedTabs(): Promise<string[]>;
+ renderedViews(): Promise<DrawerView[]>;
+ viewFromUrl(): string | null;
+ /** The `selectedItem*` params `entity` writes for its sample row. */
+ selectedItemParams(entity: EntityDef): Record<string, string>;
+ charts(): Locator;
+ chartHeaders(): Locator;
+ countCard(label: string): Locator;
+ countCardNavLink(label: string): Locator;
+ emptyState(): Locator;
+ errorState(): Locator;
+ eventsNotConfigured(): Locator;
+ timePicker(): Locator;
+ setTime(option: string): Promise<void>;
+ resetTimeToList(): Promise<void>;
+ timeParams(): {
+ relative: string | null;
+ start: string | null;
+ end: string | null;
+ };
+}
+
+export interface Infra {
+ list: InfraList;
+ drawer: InfraDrawer;
+}
+
+/** `EntityCountsSection` derives its testids from the label this way. */
+export function slug(label: string): string {
+ return label.toLowerCase().replace(/\s+/g, '-');
+}
+
+export function infraDriver(page: Page): Infra {
+ const search = querySearchDriver(page, { runTestId: TOOLBAR.runQuery });
+
+ const list: InfraList = {
+ search,
+
+ url: (entity, params = {}) => {
+ const query = new URLSearchParams(params);
+ if (entity.categoryTestId) {
+ query.set('category', entity.key);
+ }
+ const search_ = query.toString();
+ return search_ ? `${entity.route}?${search_}` : entity.route;
+ },
+
+ goto: async (entity, params = {}) => {
+ await page.goto(list.url(entity, params));
+ // The editor mounts with the list's first response, not with the shell,
+ // so the default expect budget is a coin flip under six workers.
+ await expect(search.editor()).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ },
+
+ gotoScoped: async (entity, names, params = {}) => {
+ const values = names.map((name) => `'${name}'`).join(', ');
+ await list.goto(entity, {
+ ...params,
+ ...expressionParams(`${entity.nameColumnId} IN (${values})`),
+ });
+ },
+
+ gotoGroupScoped: async (entity, groupLabel, params = {}) => {
+ await list.goto(entity, {
+ ...params,
+ ...expressionParams(`${entity.groupByAttribute} = '${groupLabel}'`),
+ });
+ await list.table(entity).waitForRows();
+ },
+
+ load: async (entity) => {
+ await page.goto(entity ? list.url(entity) : K8S_PATH);
+ },
+
+ switchCategory: async (category) => {
+ if (!category.categoryTestId) {
+ throw new Error(`${category.key} has no category rail button`);
+ }
+ await page.getByTestId(category.categoryTestId).click();
+ // `clearOnDefault: false`, so even the default category is written.
+ await expect(page).toHaveURL(new RegExp(`category=${category.key}\\b`));
+ await list.expectCategoryActive(category);
+ },
+
+ expectCategoryActive: async (category) => {
+ if (!category.categoryTestId) {
+ throw new Error(`${category.key} has no category rail button`);
+ }
+ // The rail buttons carry no pressed state, only the selected one's
+ // CSS-module class, whose generated name keeps the local name.
+ await expect(page.getByTestId(category.categoryTestId)).toHaveClass(
+ /categoryItemSelected/,
+ );
+ },
+
+ categoryTabs: () => page.locator('[data-testid^="category-"]'),
+
+ statusFilter: (value) => page.getByTestId(`status-filter-${value}`),
+
+ table: (entity) =>
+ tanstackDriver(page, {
+ rowTestIdPrefix: 'row-',
+ tableKey: entity.columnStorageKey,
+ groupBySelectTestId: TOOLBAR.groupBySelect,
+ extraStorageKeys: [
+ columnStorageKey(entity.expandedColumnStorageKey),
+ columnStorageKey(entity.pageSizeStorageKey),
+ TABLE_PREFERENCES_KEY,
+ ],
+ }),
+
+ optionsButton: () => page.getByTestId(TOOLBAR.optionsButton),
+ emptyState: () => page.getByTestId(EMPTY_STATE.empty),
+ retentionState: () => page.getByTestId(EMPTY_STATE.retention),
+ errorState: () => page.getByTestId(EMPTY_STATE.error),
+ noResults: () => page.getByText(NO_RESULTS_TEXT),
+
+ resetState: (entity) =>
+ resetKeys(page, [
+ columnStorageKey(entity.columnStorageKey),
+ columnStorageKey(entity.expandedColumnStorageKey),
+ columnStorageKey(entity.pageSizeStorageKey),
+ TABLE_PREFERENCES_KEY,
+ ]),
+
+ // `/api/v1/infra_monitoring/checks` shares the prefix and fires alongside
+ // every list load, so a bare match counts the instrumentation callout's
+ // request as the list's.
+ isListRequest: (url) =>
+ /\/api\/v\d+\/infra_monitoring\//.test(url) && !url.includes('/checks'),
+
+ quickFiltersToggle: () => page.getByTestId('quick-filters-toggle'),
+ quickFilterSections: () =>
+ page.locator('.quick-filters').getByTestId('checkbox-filter-v2'),
+
+ expectUrlParams: async (expected) => {
+ await expect(async () => {
+ const params = new URL(page.url()).searchParams;
+ for (const [key, value] of Object.entries(expected)) {
+ expect(params.get(key), `param ${key}`).toBe(value);
+ }
+ }).toPass();
+ },
+
+ /**
+ * Exact-matched against the group cell's badge and scoped to the outer
+ * table's own rows: `hasText` is a substring match over every row on the
+ * page, so a loose version also matches the header, any expanded member row
+ * and — for hosts, whose sample group is `linux` — every hostname
+ * containing the label.
+ */
+ groupRow: (groupLabel) =>
+ page
+ .locator('table')
+ .first()
+ .locator('> tbody > tr')
+ .filter({ has: page.getByText(groupLabel, { exact: true }) }),
+
+ /**
+ * Expand a group row, retrying because it can detach while the list
+ * settles. The button is a **toggle**, so an unguarded retry collapses what
+ * the previous attempt opened and the loop never converges.
+ */
+ expandGroup: async (groupLabel) => {
+ const row = list.groupRow(groupLabel);
+ await expect(row).toBeVisible();
+ const container = list.expandedTable();
+
+ await expect(async () => {
+ const button = row.getByTestId('expand-row-button');
+ if ((await button.getAttribute('aria-expanded')) !== 'true') {
+ // Playwright's auto-scroll aligns to the nearest edge, which parks a
+ // low row under the sticky pagination bar; centring clears both
+ // sticky edges, as a user's own scroll would.
+ await button.evaluate((element) =>
+ element.scrollIntoView({ block: 'center', inline: 'nearest' }),
+ );
+ await button.click({ timeout: 5_000 });
+ }
+ await expect(container).toBeVisible({ timeout: 3_000 });
+ }).toPass({ timeout: 15_000 });
+
+ return container;
+ },
+
+ collapseGroup: async (groupLabel) => {
+ const button = list.groupRow(groupLabel).getByTestId('expand-row-button');
+ if ((await button.getAttribute('aria-expanded')) === 'true') {
+ await button.evaluate((element) =>
+ element.scrollIntoView({ block: 'center', inline: 'nearest' }),
+ );
+ await button.click({ timeout: 5_000 });
+ }
+ await expect(button).toHaveAttribute('aria-expanded', 'false');
+ await expect(list.expandedTable()).toHaveCount(0);
+ },
+
+ viewAllButton: () => page.getByRole('button', { name: /view all/i }),
+
+ expandedTable: () => page.getByTestId('expanded-table-container'),
+ expandedRows: () =>
+ list.expandedTable().locator('tbody tr[data-testid^="row-"]'),
+
+ // The container mounts with the expanded fetch, not with the click or with
+ // the reload that restores `expanded` from the URL, so it inherits the same
+ // ingestion-bound budget as the rows themselves.
+ expectExpandedVisible: async () => {
+ await expect(list.expandedTable()).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ },
+ };
+
+ // Under load the list refetches and re-renders a row between mousedown and
+ // mouseup, which loses the click. Click again until a tab arrives, and only
+ // while none has, so a slow tab is not opened twice.
+ const clickForNewTab = async (
+ target: Locator,
+ modifiers: 'ControlOrMeta'[] = [],
+ ): Promise<Page> => {
+ const tabs: Page[] = [];
+ const onPage = (tab: Page): void => {
+ tabs.push(tab);
+ };
+ page.context().on('page', onPage);
+ try {
+ await expect(async () => {
+ if (tabs.length === 0) {
+ await target.click({ modifiers, timeout: 5_000 });
+ }
+ await expect.poll(() => tabs.length, { timeout: 3_000 }).toBeGreaterThan(0);
+ }).toPass({ timeout: 20_000 });
+ } finally {
+ page.context().off('page', onPage);
+ }
+ const [tab] = tabs;
+ await tab.waitForLoadState();
+ return tab;
+ };
+
+ const drawerPanel = (): Locator =>
+ // An exiting drawer keeps its node mounted for the slide-out animation,
+ // marked `aria-hidden`, so during a transition two dialogs are in the DOM
+ // and a bare testid is a strict-mode violation. The hidden node is out of
+ // the accessibility tree, so excluding it is also semantically right.
+ page.locator(`[data-testid="${DRAWER.wrapper}"]:not([aria-hidden="true"])`);
+
+ const drawer: InfraDrawer = {
+ panel: drawerPanel,
+ title: () => drawerPanel().getByRole('heading').first(),
+ tabBar: () => page.getByTestId(DRAWER.tabBar),
+ charts: () => page.getByTestId(METRICS.chart),
+ chartHeaders: () => page.getByTestId(METRICS.chartHeader),
+ countCard: (label) => page.getByTestId(`count-card-${slug(label)}`),
+ countCardNavLink: (label) => page.getByTestId(`navigate-${slug(label)}`),
+ emptyState: () => page.getByTestId(DRAWER_STATE.emptyState),
+ errorState: () => page.getByTestId(DRAWER_STATE.errorState),
+ eventsNotConfigured: () => page.getByTestId(DRAWER_STATE.eventsNotConfigured),
+ timePicker: () => page.getByTestId(DRAWER.timeSelection),
+
+ // The toggle group names each button `<bar testId>-button-<value>`.
+ tab: (view) => page.getByTestId(`${DRAWER.tabBar}-button-${view}`),
+
+ open: async (rowKey) => {
+ const row = page.getByTestId(`row-${rowKey}`);
+ await expect(row).toBeVisible();
+
+ // The click needs its own timeout: `toPass` awaits the callback to
+ // completion before checking its deadline, so an unbounded click cannot
+ // be interrupted — and once the drawer is up, a retried click is behind
+ // its modal mask and blocks on actionability forever.
+ await expect(async () => {
+ if (!(await drawerPanel().isVisible())) {
+ // The header row is `position: sticky`, so a row scrolled "just into
+ // view" lands under it and the click is swallowed by a header cell.
+ await row.evaluate((element) =>
+ element.scrollIntoView({ block: 'center' }),
+ );
+ await row.click({ timeout: 5_000 });
+ }
+ await expect(page.getByTestId(DRAWER.close)).toBeVisible({
+ timeout: 3_000,
+ });
+ }).toPass({ timeout: 20_000 });
+
+ const panel = drawerPanel();
+ await expect(panel).toBeVisible();
+ return panel;
+ },
+
+ openInNewTab: (rowKey) =>
+ clickForNewTab(page.getByTestId(`row-${rowKey}`), ['ControlOrMeta']),
+
+ openExplorer: (link) => clickForNewTab(page.getByTestId(link)),
+
+ expectVisible: async () => {
+ const panel = drawerPanel();
+ await expect(panel).toBeVisible({ timeout: 30_000 });
+ return panel;
+ },
+
+ /**
+ * `drawer-time-selection` is the signal because `EntityDateTimeSelector` is
+ * rendered by all four tab bodies and by nothing in the shell — including on
+ * volumes, which has no tab bar but still renders the Metrics body.
+ */
+ expectBodyReady: async () => {
+ const panel = await drawer.expectVisible();
+ await expect(drawer.timePicker()).toBeVisible({ timeout: 30_000 });
+ return panel;
+ },
+
+ close: async () => {
+ await page.getByTestId(DRAWER.close).click();
+ await expect(async () => {
+ expect(new URL(page.url()).searchParams.get('selectedItem')).toBeNull();
+ }).toPass();
+ },
+
+ renderedTabs: async () => {
+ const labels = await drawer.tabBar().locator('button').allInnerTexts();
+ return labels.map((label) => label.trim()).filter(Boolean);
+ },
+
+ renderedViews: async () => {
+ const byLabel = new Map(
+ Object.entries(TAB_LABEL).map(([view, label]) => [
+ label,
+ view as DrawerView,
+ ]),
+ );
+ const labels = await drawer.renderedTabs();
+ return labels
+ .map((label) => byLabel.get(label))
+ .filter((view): view is DrawerView => Boolean(view));
+ },
+
+ viewFromUrl: () => new URL(page.url()).searchParams.get('view'),
+
+ switchTab: async (view) => {
+ await drawer.tab(view).click();
+ await expect(async () => {
+ expect(drawer.viewFromUrl()).toBe(view);
+ }).toPass();
+ // The tab bar is the authority on what rendered; the URL alone cannot
+ // tell "switched to Metrics" from "never wrote a view".
+ await expect(drawer.tab(view)).toHaveAttribute('aria-pressed', 'true');
+ },
+
+ /**
+ * Throws rather than defaulting a missing registry value to `''`: a deep
+ * link with an empty extra opens a drawer titled `-` with empty panels,
+ * which is indistinguishable from a slow one.
+ */
+ selectedItemParams: (entity) => {
+ const params: Record<string, string> = {
+ selectedItem: entity.seed.sampleItemKey,
+ };
+ const required = (value: string | undefined, field: string): string => {
+ if (!value) {
+ throw new Error(
+ `${entity.key}: seed.${field} is required because selectedItemExtraParams asks for it`,
+ );
+ }
+ return value;
+ };
+ if (entity.selectedItemExtraParams.includes('clusterName')) {
+ params.selectedItemClusterName = required(
+ entity.seed.sampleClusterName,
+ 'sampleClusterName',
+ );
+ }
+ if (entity.selectedItemExtraParams.includes('namespaceName')) {
+ params.selectedItemNamespaceName = required(
+ entity.seed.sampleNamespaceName,
+ 'sampleNamespaceName',
+ );
+ }
+ return params;
+ },
+
+ setTime: async (option) => {
+ await drawer.timePicker().click();
+ await page.getByText(option, { exact: true }).click();
+ await expect(async () => {
+ expect(drawer.timeParams().relative).not.toBeNull();
+ }).toPass();
+ },
+
+ resetTimeToList: async () => {
+ await page.getByTestId(DRAWER.resetToListTime).click();
+ await expect(async () => {
+ expect(drawer.timeParams().relative).toBeNull();
+ }).toPass();
+ },
+
+ timeParams: () => {
+ const params = new URL(page.url()).searchParams;
+ return {
+ relative: params.get('detailRelativeTime'),
+ start: params.get('detailStartTime'),
+ end: params.get('detailEndTime'),
+ };
+ },
+ };
+
+ return { list, drawer };
+}
+
+export const withInfraMonitoring: Layer<{ infra: Infra }> = driver(
+ 'infra',
+ ({ page }) => infraDriver(page),
+);
diff --git a/tests/e2e/drivers/infra/entities.ts b/tests/e2e/drivers/infra/entities.ts
new file mode 100644
index 0000000000..2d33104ba6
--- /dev/null
+++ b/tests/e2e/drivers/infra/entities.ts
@@ -0,0 +1,463 @@
+import type { DatasetKey } from './__generated__/datasets';
+
+/**
+ * The infra-monitoring entity registry: the single place a new entity is added.
+ *
+ * What is **not** here is as deliberate as what is. `K8sBaseList` and
+ * `K8sBaseDetails` are entity-agnostic — the only thing that varies is the
+ * config object handed to them — so the columns, filter placeholders,
+ * quick-filter sections, metadata labels and widget titles are asserted against
+ * the product's own config in jest
+ * (`frontend/src/container/InfraMonitoringK8sV2/__tests__/entityConfig.test.ts`),
+ * not mirrored here and re-checked through a browser ten times over.
+ *
+ * What stays is what an E2E needs to *drive* the page: where an entity lives,
+ * what its rows are keyed by, what it can be grouped or sorted by, and which
+ * dataset seeds each scenario.
+ */
+
+export type EntityCapability =
+ | 'groupBy'
+ | 'statusFilter'
+ | 'countsCards'
+ | 'podMetricsTab'
+ | 'logsTab'
+ | 'tracesTab'
+ | 'eventsTab'
+ | 'tabBar';
+
+/** Extra `selectedItem*` params an entity's `getItemKey` writes to the URL. */
+export type SelectedItemExtra = 'clusterName' | 'namespaceName';
+
+export interface EntitySeedFacts {
+ /** Dataset covering a happy-path list. */
+ primary: DatasetKey;
+ /** Dataset whose group membership the group-by and expanded-row specs use. */
+ grouped: DatasetKey;
+ pagination: DatasetKey;
+ orderBy: DatasetKey;
+ /**
+ * Dataset whose rows differ in the attributes the quick-filter rail and the
+ * expression editor filter on, so a filter can actually narrow the list.
+ * `pagination` cannot: its rows are near-identical by construction.
+ */
+ filter: DatasetKey;
+ /** One row's name, for row-scoped locators. */
+ sampleName: string;
+ /** What `selectedItem` takes for `sampleName` — pods key rows by UID. */
+ sampleItemKey: string;
+ sampleClusterName?: string;
+ sampleNamespaceName?: string;
+ /** One group label from `grouped`, under `groupByAttribute`. */
+ sampleGroup: string;
+}
+
+export interface EntityDef {
+ /** `category` param value, storage-key segment and registry key. */
+ key: string;
+ label: string;
+ route: string;
+ /** `category-<key>` in the left rail; absent for hosts, which has no rail. */
+ categoryTestId?: string;
+ columnStorageKey: string;
+ expandedColumnStorageKey: string;
+ pageSizeStorageKey: string;
+ nameColumnId: string;
+ groupColumnId: string;
+ capabilities: Set<EntityCapability>;
+ selectedItemExtraParams: SelectedItemExtra[];
+ groupByAttribute: string;
+ /**
+ * A second, distinct attribute to group on. Must exist in the entity's own
+ * metric namespace — hosts has only `host.name` / `os.type` / `state`, so it
+ * cannot borrow a `k8s.*` key.
+ */
+ secondGroupByAttribute: string;
+ /**
+ * A sortable, default-visible column whose values vary across the rows of
+ * {@link EntityDef.orderByDataset}.
+ *
+ * Needed twice over: not every sortable column has a backing metric in the
+ * fixture, and sorting by one that does not returns an empty list, which
+ * swaps the table for the empty state and takes the header with it. A
+ * populated column is still useless for an ordering assertion if every row
+ * holds the same value.
+ */
+ orderByColumnId: string;
+ /**
+ * Dataset the row-order assertion seeds. Normally `<entity>_orderby`, but
+ * `hosts_orderby` gives every host identical values for every metric, so
+ * hosts borrows its accuracy fixture instead.
+ */
+ orderByDataset: DatasetKey;
+ seed: EntitySeedFacts;
+}
+
+const K8S_ROUTE = '/infrastructure-monitoring/kubernetes';
+const HOSTS_ROUTE = '/infrastructure-monitoring/hosts';
+
+const NAMESPACE_ATTR = 'k8s.namespace.name';
+const CLUSTER_ATTR = 'k8s.cluster.name';
+const OS_TYPE_ATTR = 'os.type';
+
+const ALL_TABS: EntityCapability[] = [
+ 'tabBar',
+ 'logsTab',
+ 'tracesTab',
+ 'eventsTab',
+];
+
+/** Storage keys follow one scheme, so they are derived rather than repeated. */
+function storageKeys(
+ slug: string,
+): Pick<
+ EntityDef,
+ 'columnStorageKey' | 'expandedColumnStorageKey' | 'pageSizeStorageKey'
+> {
+ return {
+ columnStorageKey: `k8s-${slug}-columns`,
+ expandedColumnStorageKey: `k8s-${slug}-columns-expanded`,
+ pageSizeStorageKey: `k8s-${slug}-preferred-page-size`,
+ };
+}
+
+export const ENTITIES: EntityDef[] = [
+ {
+ key: 'hosts',
+ label: 'Hosts',
+ route: HOSTS_ROUTE,
+ ...storageKeys('hosts'),
+ nameColumnId: 'host.name',
+ groupColumnId: 'hostGroup',
+ capabilities: new Set<EntityCapability>([
+ 'groupBy',
+ 'statusFilter',
+ 'tabBar',
+ 'logsTab',
+ 'tracesTab',
+ ]),
+ selectedItemExtraParams: [],
+ groupByAttribute: OS_TYPE_ATTR,
+ secondGroupByAttribute: 'host.name',
+ orderByColumnId: 'load15',
+ orderByDataset: 'hosts_value_accuracy',
+ seed: {
+ primary: 'hosts_value_accuracy',
+ grouped: 'hosts_groupby_os_type',
+ pagination: 'hosts_pagination',
+ filter: 'hosts_filter_dataset',
+ orderBy: 'hosts_orderby',
+ sampleName: 'acc-h1',
+ sampleItemKey: 'acc-h1',
+ sampleGroup: 'linux',
+ },
+ },
+ {
+ key: 'pods',
+ label: 'Pods',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-pods',
+ ...storageKeys('pods'),
+ nameColumnId: 'k8s.pod.name',
+ groupColumnId: 'podGroup',
+ capabilities: new Set<EntityCapability>(['groupBy', ...ALL_TABS]),
+ selectedItemExtraParams: [],
+ groupByAttribute: NAMESPACE_ATTR,
+ secondGroupByAttribute: CLUSTER_ATTR,
+ orderByColumnId: 'cpu',
+ orderByDataset: 'pods_orderby',
+ seed: {
+ primary: 'pods_value_accuracy',
+ grouped: 'pods_groupby',
+ pagination: 'pods_pagination',
+ filter: 'pods_filter_dataset',
+ orderBy: 'pods_orderby',
+ sampleName: 'acc-p1',
+ sampleItemKey: 'acc-p1-uid',
+ sampleGroup: 'gns-a',
+ },
+ },
+ {
+ key: 'nodes',
+ label: 'Nodes',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-nodes',
+ ...storageKeys('nodes'),
+ nameColumnId: 'k8s.node.name',
+ groupColumnId: 'nodeGroup',
+ capabilities: new Set<EntityCapability>(['groupBy', ...ALL_TABS]),
+ selectedItemExtraParams: [],
+ groupByAttribute: CLUSTER_ATTR,
+ secondGroupByAttribute: 'k8s.node.name',
+ orderByColumnId: 'cpu',
+ orderByDataset: 'nodes_orderby',
+ seed: {
+ primary: 'nodes_value_accuracy',
+ grouped: 'nodes_groupby',
+ pagination: 'nodes_pagination',
+ filter: 'nodes_filter_dataset',
+ orderBy: 'nodes_orderby',
+ sampleName: 'acc-n1',
+ sampleItemKey: 'acc-n1',
+ sampleGroup: 'gb-cluster-a',
+ },
+ },
+ {
+ key: 'namespaces',
+ label: 'Namespaces',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-namespaces',
+ ...storageKeys('namespaces'),
+ nameColumnId: 'k8s.namespace.name',
+ groupColumnId: 'namespaceGroup',
+ capabilities: new Set<EntityCapability>([
+ 'groupBy',
+ 'countsCards',
+ 'podMetricsTab',
+ ...ALL_TABS,
+ ]),
+ selectedItemExtraParams: ['clusterName'],
+ groupByAttribute: CLUSTER_ATTR,
+ secondGroupByAttribute: NAMESPACE_ATTR,
+ orderByColumnId: 'cpu',
+ orderByDataset: 'namespaces_orderby',
+ seed: {
+ primary: 'namespaces_value_accuracy',
+ grouped: 'namespaces_groupby',
+ pagination: 'namespaces_pagination',
+ filter: 'namespaces_filter_dataset',
+ orderBy: 'namespaces_orderby',
+ sampleName: 'acc-ns-1',
+ sampleItemKey: 'acc-ns-1',
+ sampleClusterName: 'cluster-x',
+ sampleGroup: 'gb-cluster-a',
+ },
+ },
+ {
+ key: 'clusters',
+ label: 'Clusters',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-clusters',
+ ...storageKeys('clusters'),
+ nameColumnId: 'k8s.cluster.name',
+ groupColumnId: 'clusterGroup',
+ capabilities: new Set<EntityCapability>([
+ 'groupBy',
+ 'countsCards',
+ ...ALL_TABS,
+ ]),
+ selectedItemExtraParams: [],
+ groupByAttribute: CLUSTER_ATTR,
+ secondGroupByAttribute: NAMESPACE_ATTR,
+ orderByColumnId: 'cpu',
+ orderByDataset: 'clusters_orderby',
+ seed: {
+ primary: 'clusters_value_accuracy',
+ grouped: 'clusters_groupby',
+ pagination: 'clusters_pagination',
+ filter: 'clusters_filter_dataset',
+ orderBy: 'clusters_orderby',
+ sampleName: 'acc-cluster-1',
+ sampleItemKey: 'acc-cluster-1',
+ sampleGroup: 'gb-gcp-1',
+ },
+ },
+ {
+ key: 'deployments',
+ label: 'Deployments',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-deployments',
+ ...storageKeys('deployments'),
+ nameColumnId: 'k8s.deployment.name',
+ groupColumnId: 'deploymentGroup',
+ capabilities: new Set<EntityCapability>([
+ 'groupBy',
+ 'podMetricsTab',
+ ...ALL_TABS,
+ ]),
+ selectedItemExtraParams: ['clusterName', 'namespaceName'],
+ groupByAttribute: NAMESPACE_ATTR,
+ secondGroupByAttribute: CLUSTER_ATTR,
+ orderByColumnId: 'cpu',
+ orderByDataset: 'deployments_orderby',
+ seed: {
+ primary: 'deployments_value_accuracy',
+ grouped: 'deployments_groupby',
+ pagination: 'deployments_pagination',
+ filter: 'deployments_filter_dataset',
+ orderBy: 'deployments_orderby',
+ sampleName: 'acc-dep-1',
+ sampleItemKey: 'acc-dep-1',
+ sampleClusterName: 'cluster-x',
+ sampleNamespaceName: 'ns-acc',
+ sampleGroup: 'gb-ns-a',
+ },
+ },
+ {
+ key: 'statefulsets',
+ label: 'StatefulSets',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-statefulsets',
+ ...storageKeys('statefulsets'),
+ nameColumnId: 'k8s.statefulset.name',
+ groupColumnId: 'statefulSetGroup',
+ capabilities: new Set<EntityCapability>([
+ 'groupBy',
+ 'podMetricsTab',
+ ...ALL_TABS,
+ ]),
+ selectedItemExtraParams: ['clusterName', 'namespaceName'],
+ groupByAttribute: NAMESPACE_ATTR,
+ secondGroupByAttribute: CLUSTER_ATTR,
+ orderByColumnId: 'cpu_limit',
+ orderByDataset: 'statefulsets_orderby',
+ seed: {
+ primary: 'statefulsets_value_accuracy',
+ grouped: 'statefulsets_groupby',
+ pagination: 'statefulsets_pagination',
+ filter: 'statefulsets_filter_dataset',
+ orderBy: 'statefulsets_orderby',
+ sampleName: 'acc-ss-1',
+ sampleItemKey: 'acc-ss-1',
+ sampleClusterName: 'cluster-x',
+ sampleNamespaceName: 'ns-acc',
+ sampleGroup: 'gb-ns-a',
+ },
+ },
+ {
+ key: 'daemonsets',
+ label: 'DaemonSets',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-daemonsets',
+ ...storageKeys('daemonsets'),
+ nameColumnId: 'k8s.daemonset.name',
+ groupColumnId: 'daemonSetGroup',
+ capabilities: new Set<EntityCapability>([
+ 'groupBy',
+ 'podMetricsTab',
+ ...ALL_TABS,
+ ]),
+ selectedItemExtraParams: ['clusterName', 'namespaceName'],
+ groupByAttribute: NAMESPACE_ATTR,
+ secondGroupByAttribute: CLUSTER_ATTR,
+ orderByColumnId: 'cpu_limit',
+ orderByDataset: 'daemonsets_orderby',
+ seed: {
+ primary: 'daemonsets_value_accuracy',
+ grouped: 'daemonsets_groupby',
+ pagination: 'daemonsets_pagination',
+ filter: 'daemonsets_filter_dataset',
+ orderBy: 'daemonsets_orderby',
+ sampleName: 'acc-ds-1',
+ sampleItemKey: 'acc-ds-1',
+ sampleClusterName: 'cluster-x',
+ sampleNamespaceName: 'ns-acc',
+ sampleGroup: 'gb-ns-a',
+ },
+ },
+ {
+ key: 'jobs',
+ label: 'Jobs',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-jobs',
+ ...storageKeys('jobs'),
+ nameColumnId: 'k8s.job.name',
+ groupColumnId: 'jobGroup',
+ capabilities: new Set<EntityCapability>([
+ 'groupBy',
+ 'podMetricsTab',
+ ...ALL_TABS,
+ ]),
+ selectedItemExtraParams: ['clusterName', 'namespaceName'],
+ groupByAttribute: NAMESPACE_ATTR,
+ secondGroupByAttribute: CLUSTER_ATTR,
+ orderByColumnId: 'cpu',
+ orderByDataset: 'jobs_orderby',
+ seed: {
+ primary: 'jobs_value_accuracy',
+ grouped: 'jobs_groupby',
+ pagination: 'jobs_pagination',
+ filter: 'jobs_filter_dataset',
+ orderBy: 'jobs_orderby',
+ sampleName: 'acc-job-1',
+ sampleItemKey: 'acc-job-1',
+ sampleClusterName: 'cluster-x',
+ sampleNamespaceName: 'ns-acc',
+ sampleGroup: 'gb-ns-a',
+ },
+ },
+ {
+ key: 'volumes',
+ label: 'Volumes',
+ route: K8S_ROUTE,
+ categoryTestId: 'category-volumes',
+ ...storageKeys('volumes'),
+ nameColumnId: 'k8s.persistentvolumeclaim.name',
+ groupColumnId: 'volumeGroup',
+ capabilities: new Set<EntityCapability>(['groupBy']),
+ selectedItemExtraParams: ['clusterName', 'namespaceName'],
+ groupByAttribute: NAMESPACE_ATTR,
+ secondGroupByAttribute: CLUSTER_ATTR,
+ orderByColumnId: 'capacity',
+ orderByDataset: 'volumes_orderby',
+ seed: {
+ primary: 'volumes_value_accuracy',
+ grouped: 'volumes_groupby',
+ pagination: 'volumes_pagination',
+ filter: 'volumes_filter_dataset',
+ orderBy: 'volumes_orderby',
+ sampleName: 'acc-pvc-1',
+ sampleItemKey: 'acc-pvc-1',
+ sampleClusterName: 'cluster-x',
+ sampleNamespaceName: 'ns-acc',
+ sampleGroup: 'gb-ns-a',
+ },
+ },
+];
+
+export const K8S_PATH = K8S_ROUTE;
+export const HOSTS_PATH = HOSTS_ROUTE;
+
+/**
+ * Rail order, as `InfraMonitoringK8s` renders it. Hosts has no rail entry.
+ * Containers has a rail entry but no entity here: no spec seeds it.
+ */
+export const K8S_CATEGORY_TAB_ORDER = [
+ 'containers',
+ 'pods',
+ 'nodes',
+ 'namespaces',
+ 'clusters',
+ 'deployments',
+ 'jobs',
+ 'daemonsets',
+ 'statefulsets',
+ 'volumes',
+];
+
+/** A rail button: what category switching needs from an entity. */
+export type K8sCategory = Pick<EntityDef, 'key' | 'categoryTestId'>;
+
+/** `DEFAULT_K8S_CATEGORY`: what a route with no `category` param shows. */
+export const DEFAULT_CATEGORY: K8sCategory = {
+ key: 'containers',
+ categoryTestId: 'category-containers',
+};
+
+/** `ENTITIES` minus hosts: the ones on the kubernetes route. */
+export function k8sEntities(): EntityDef[] {
+ return ENTITIES.filter((entity) => Boolean(entity.categoryTestId));
+}
+
+export function entityByKey(key: string): EntityDef {
+ const entity = ENTITIES.find((candidate) => candidate.key === key);
+ if (!entity) {
+ throw new Error(
+ `unknown infra entity \`${key}\` — known: ${ENTITIES.map((e) => e.key).join(', ')}`,
+ );
+ }
+ return entity;
+}
+
+/** The entity the entity-agnostic specs run on. */
+export const BASE_ENTITY = entityByKey('pods');
diff --git a/tests/e2e/drivers/infra/index.ts b/tests/e2e/drivers/infra/index.ts
new file mode 100644
index 0000000000..cb79bfb5a0
--- /dev/null
+++ b/tests/e2e/drivers/infra/index.ts
@@ -0,0 +1,18 @@
+import { kit } from '../kit';
+
+import { withInfraMonitoring } from './driver';
+
+/**
+ * The infra-monitoring `test`.
+ *
+ * Seeding is explicit rather than a fixture: a dataset belongs to one spec's
+ * `beforeAll`, is additive across the shared stack, and every scenario scopes
+ * its list to the names it seeded. See `seed.ts`.
+ */
+export const test = withInfraMonitoring(kit);
+
+export { expect } from '../kit';
+export * from './driver';
+export * from './entities';
+export * from './seed';
+export { DATASETS, type DatasetKey } from './__generated__/datasets';
diff --git a/tests/e2e/helpers/infra-monitoring.ts b/tests/e2e/drivers/infra/pods.ts
similarity index 98%
rename from tests/e2e/helpers/infra-monitoring.ts
rename to tests/e2e/drivers/infra/pods.ts
index 6b78209152..366730d7d0 100644
--- a/tests/e2e/helpers/infra-monitoring.ts
+++ b/tests/e2e/drivers/infra/pods.ts
@@ -1,6 +1,6 @@
import type { Page } from '@playwright/test';
-import { seederUrl } from './common';
+import { seederUrl } from '../api';
// Seeding for the Kubernetes lists under /infrastructure-monitoring.
diff --git a/tests/e2e/drivers/infra/seed.ts b/tests/e2e/drivers/infra/seed.ts
new file mode 100644
index 0000000000..fc00a9c096
--- /dev/null
+++ b/tests/e2e/drivers/infra/seed.ts
@@ -0,0 +1,412 @@
+/**
+ * Seeding infra-monitoring metrics through the pytest harness's HTTP seeder.
+ *
+ * Reimplements the two behaviours `_load_pods_metrics` in
+ * `tests/integration/tests/inframonitoring/02_pods.py` relies on:
+ *
+ * 1. **rebase** — shift every timestamp so the newest sample sits ~30 s in the
+ * past. The list endpoints only report an entity whose latest sample falls
+ * inside the queried window, and future-stamped samples are dropped outright.
+ * 2. **`__START_TIME__` substitution** — the `k8s.pod.start_time` placeholder
+ * becomes a real ISO string, so `podAge` is deterministic.
+ *
+ * Seeding is **additive** and the stack is shared across workers, so a dataset
+ * must own the names it asserts on (the fixtures already do) and specs must
+ * never assert "the table has exactly N rows".
+ */
+
+import fs from 'fs';
+import type { Page } from '@playwright/test';
+
+import { postToSeeder } from '../telemetry';
+
+import { ENTITIES, entityByKey, type EntityDef } from './entities';
+import {
+ datasetFacts,
+ datasetPath,
+ type DatasetKey,
+} from './__generated__/datasets';
+
+const START_TIME_PLACEHOLDER = '__START_TIME__';
+
+/** `K8sExpandedRow`'s `EXPANDED_ROW_LIMIT` — the expanded table's page size. */
+export const EXPANDED_ROW_LIMIT = 10;
+
+export interface MetricRow {
+ timestamp: string;
+ labels?: Record<string, string>;
+ [key: string]: unknown;
+}
+
+export interface SeededFacts {
+ dataset: DatasetKey;
+ entity: string;
+ /** Entity names actually seeded, sorted. */
+ names: string[];
+ /** Group label → member count, per group attribute. */
+ groups: Record<string, Record<string, number>>;
+ /** Rows POSTed to the seeder. */
+ rowCount: number;
+}
+
+// ─── Fixture reading ─────────────────────────────────────────────────────────
+
+function readRows(dataset: DatasetKey): MetricRow[] {
+ const file = datasetPath(dataset);
+ if (!fs.existsSync(file)) {
+ throw new Error(
+ `dataset fixture missing: ${file}. Datasets come from the integration suite — check tests/integration/testdata/inframonitoring/.`,
+ );
+ }
+ return fs
+ .readFileSync(file, 'utf8')
+ .split('\n')
+ .filter((line) => line.trim() !== '')
+ .map((line) => JSON.parse(line) as MetricRow);
+}
+
+/**
+ * Shift a series so its newest sample lands `LATEST_SAMPLE_LAG_MS` before now,
+ * and resolve the start-time placeholder.
+ */
+const LATEST_SAMPLE_LAG_MS = 30_000;
+const START_TIME_AGE_MS = 10 * 60 * 1000;
+
+function rebaseToNow(rows: MetricRow[]): MetricRow[] {
+ if (rows.length === 0) {
+ // `Math.max()` of nothing is -Infinity, which makes every rebased timestamp
+ // `new Date(NaN).toISOString()` — a RangeError from deep inside the map, with
+ // nothing pointing at the empty fixture that caused it.
+ throw new Error('rebaseToNow: no rows — the fixture is empty or unparsed');
+ }
+ const now = Date.now();
+ const startTime = new Date(now - START_TIME_AGE_MS).toISOString();
+ const timestamps = rows.map((row) => Date.parse(row.timestamp));
+ const unparsed = timestamps.findIndex(Number.isNaN);
+ if (unparsed !== -1) {
+ throw new Error(
+ `rebaseToNow: row ${unparsed} has an unparseable timestamp \`${rows[unparsed].timestamp}\``,
+ );
+ }
+ const latest = Math.max(...timestamps);
+ const offset = now - LATEST_SAMPLE_LAG_MS - latest;
+
+ return rows.map((row) => {
+ const labels = { ...row.labels };
+ if (labels['k8s.pod.start_time'] === START_TIME_PLACEHOLDER) {
+ labels['k8s.pod.start_time'] = startTime;
+ }
+ return {
+ ...row,
+ labels,
+ timestamp: new Date(Date.parse(row.timestamp) + offset).toISOString(),
+ };
+ });
+}
+
+// ─── Facts ───────────────────────────────────────────────────────────────────
+
+/**
+ * Every attribute any entity can group by, derived rather than hand-listed — the
+ * literal version silently omitted `host.name` (hosts' `secondGroupByAttribute`),
+ * so `SeededFacts.groups` had no entry for it and any scenario grouping on it got
+ * `undefined` back.
+ */
+const GROUP_ATTRS = [
+ ...new Set(
+ ENTITIES.flatMap((entity) =>
+ [entity.groupByAttribute, entity.secondGroupByAttribute].filter(
+ (attr): attr is string => Boolean(attr),
+ ),
+ ),
+ ),
+];
+
+function factsFor(dataset: DatasetKey, rows: MetricRow[]): SeededFacts {
+ const { entity } = datasetFacts(dataset);
+ // The registry's `nameColumnId` doubles as the name *label* for all ten
+ // entities, and the drift guard checks it against the product's table config.
+ // `datasets.NAME_LABEL` used to hold a third hand-maintained copy of the same
+ // mapping, which #12402 renamed all ten values of in one commit.
+ const nameLabel = entityByKey(entity).nameColumnId;
+
+ const names = new Set<string>();
+ const groups: Record<string, Record<string, Set<string>>> = {};
+
+ for (const row of rows) {
+ const name = row.labels?.[nameLabel];
+ if (!name) {
+ continue;
+ }
+ names.add(name);
+ for (const attr of GROUP_ATTRS) {
+ const value = row.labels?.[attr];
+ if (!value) {
+ continue;
+ }
+ ((groups[attr] ??= {})[value] ??= new Set()).add(name);
+ }
+ }
+
+ return {
+ dataset,
+ entity,
+ names: [...names].sort(),
+ groups: Object.fromEntries(
+ Object.entries(groups).map(([attr, byLabel]) => [
+ attr,
+ Object.fromEntries(
+ Object.entries(byLabel).map(([label, members]) => [label, members.size]),
+ ),
+ ]),
+ ),
+ rowCount: rows.length,
+ };
+}
+
+/**
+ * Re-derive a dataset's declared facts from the fixture and fail if they drifted.
+ * Cheap enough to run in a `beforeAll`; it turns a fixture edit into an explicit
+ * error here instead of a puzzling assertion failure three specs away.
+ */
+export function assertDatasetFacts(dataset: DatasetKey): SeededFacts {
+ const declared = datasetFacts(dataset);
+ const actual = factsFor(dataset, readRows(dataset));
+
+ // Both loops below are guarded on non-empty input, so a dataset that declares
+ // neither is registered with nothing this function can check.
+ if (
+ declared.names.length === 0 &&
+ Object.keys(declared.groups ?? {}).length === 0
+ ) {
+ throw new Error(
+ `dataset ${dataset} declares no names and no groups, so smoke TC-01 asserts nothing about it`,
+ );
+ }
+
+ if (declared.names.length > 0) {
+ const missing = declared.names.filter((name) => !actual.names.includes(name));
+ if (missing.length > 0) {
+ throw new Error(
+ `dataset ${dataset}: declared names ${missing.join(', ')} are not in the fixture (found ${actual.names.join(', ')})`,
+ );
+ }
+ }
+
+ for (const [attr, expected] of Object.entries(declared.groups ?? {})) {
+ for (const [label, count] of Object.entries(expected)) {
+ const got = actual.groups[attr]?.[label];
+ if (got !== count) {
+ throw new Error(
+ `dataset ${dataset}: group ${attr}=${label} has ${got ?? 0} members, declared ${count}`,
+ );
+ }
+ }
+ }
+
+ return actual;
+}
+
+// ─── Seeder transport ────────────────────────────────────────────────────────
+
+/**
+ * Per-attempt budget, sized so all {@link SEED_ATTEMPTS} fit inside one test.
+ *
+ * Was 60 s, which with three attempts meant a worst case of 180 s against a 30 s
+ * (local) / 60 s (CI) test timeout — so a genuinely dead seeder reported as a
+ * bare "Test timeout exceeded" with no failing assertion, which is the least
+ * debuggable failure the runner can emit.
+ */
+const SEED_TIMEOUT_MS = 15_000;
+
+/**
+ * The seeder rejects very large single POSTs, so chunking keeps each one bounded.
+ * The largest fixture in the corpus is ~430 rows, i.e. always a single chunk —
+ * this is headroom for a future fixture, not something the suite exercises today.
+ */
+const SEED_CHUNK_SIZE = 2_000;
+
+/**
+ * Six workers hammering one uvicorn worker occasionally drops a connection
+ * mid-POST ("socket hang up") — a transport failure, not a rejected payload.
+ * Insertion is additive and idempotent enough to retry that: a duplicated chunk
+ * adds rows the assertions already tolerate (no spec counts absolute rows),
+ * whereas a lost chunk fails the scenario for a reason that has nothing to do
+ * with it.
+ */
+const SEED_ATTEMPTS = 3;
+
+/** Backoff between attempts. Three retries in the same millisecond against a
+ * seeder that just dropped a connection under load all fail the same way. */
+const SEED_BACKOFF_MS = 250;
+
+function postChunk(page: Page, chunk: MetricRow[]): Promise<void> {
+ return postToSeeder(page.request, '/telemetry/metrics', chunk, {
+ timeout: SEED_TIMEOUT_MS,
+ attempts: SEED_ATTEMPTS,
+ backoffMs: SEED_BACKOFF_MS,
+ });
+}
+
+async function postMetrics(page: Page, rows: MetricRow[]): Promise<void> {
+ for (let i = 0; i < rows.length; i += SEED_CHUNK_SIZE) {
+ await postChunk(page, rows.slice(i, i + SEED_CHUNK_SIZE));
+ }
+}
+
+// ─── Public API ──────────────────────────────────────────────────────────────
+
+/**
+ * Seed a dataset with timestamps rebased so its samples land a few seconds
+ * before now — inside every default time window the UI uses. Returns the facts
+ * derived from what was actually seeded, so a spec asserts against the fixture
+ * rather than against a transcription of it.
+ */
+export async function seedDataset(
+ page: Page,
+ dataset: DatasetKey,
+): Promise<SeededFacts> {
+ const rows = rebaseToNow(readRows(dataset));
+ await postMetrics(page, rows);
+ return factsFor(dataset, rows);
+}
+
+export interface SeedGroupedOptions {
+ /**
+ * How many members the cloned group should hold. Defaults to
+ * `EXPANDED_ROW_LIMIT + 2`, so the expanded table is capped *and* offers
+ * "View All" — the two things expanded-row TC-02/06 need.
+ */
+ members?: number;
+ /**
+ * Prefix for the cloned entity names. Defaults to a per-entity value; it must
+ * be unique to the calling scenario family because seeding is additive across
+ * workers.
+ */
+ namePrefix?: string;
+ /** Group label the clones land under. Defaults to `viewall-<entity.key>`. */
+ groupLabel?: string;
+ /**
+ * Attribute the clones are grouped under. Defaults to `entity.groupByAttribute`.
+ *
+ * Needed for clusters, whose group attribute *is* its name attribute — grouping
+ * clusters by cluster name makes every group a singleton, so a >10-member group
+ * is not constructible that way. `clusters_groupby.jsonl` also carries
+ * `cloud.provider`, which is the usable alternative.
+ */
+ groupAttribute?: string;
+}
+
+/**
+ * Seed a group whose member count exceeds `EXPANDED_ROW_LIMIT`.
+ *
+ * No fixture has a group that large — the biggest is 6 — so the rows for one
+ * entity are cloned under fresh names inside a scenario-owned group label, the
+ * same trick the original pods-only helper used for `ns-viewall`.
+ *
+ * Cloning preserves every label the list endpoint needs, so the clones are
+ * indistinguishable from seeded rows apart from their name and group.
+ */
+export async function seedGroupedDataset(
+ page: Page,
+ entity: EntityDef,
+ options: SeedGroupedOptions = {},
+): Promise<SeededFacts> {
+ const dataset = entity.seed.grouped;
+ const { members, namePrefix, groupLabel } = resolveGroupedOptions(
+ entity,
+ options,
+ );
+ const groupAttr = options.groupAttribute ?? entity.groupByAttribute;
+ const nameLabel = entity.nameColumnId;
+
+ // For clusters the name label *is* the group attribute, so the two label writes
+ // below collide: every clone would be renamed to `groupLabel` and the twelve
+ // members would collapse into one row, while `groupedCloneNames` still promised
+ // twelve. That is a real property of the entity, not a fixture gap — grouping
+ // clusters by cluster name makes every group a singleton. Fail loudly rather
+ // than seeding one row and letting the caller time out on "row not visible".
+ if (nameLabel === groupAttr) {
+ throw new Error(
+ `${entity.key}: groupByAttribute '${groupAttr}' is also its name attribute, so ` +
+ `every group holds exactly one member and grouped clones cannot be distinct. ` +
+ `Pass { groupAttribute } explicitly — '${dataset}' carries cloud.provider.`,
+ );
+ }
+
+ const all = readRows(dataset);
+ // Clone one entity's whole series so the clones carry every metric the list
+ // endpoint reads, not just the one the group is keyed on.
+ const templateName = all.find((row) => row.labels?.[nameLabel])?.labels?.[
+ nameLabel
+ ];
+ if (!templateName) {
+ throw new Error(
+ `dataset ${dataset}: no row carries ${nameLabel}, cannot build a grouped clone`,
+ );
+ }
+ const template = all.filter((row) => row.labels?.[nameLabel] === templateName);
+
+ const clones = Array.from({ length: members }, (_, index) => {
+ const name = `${namePrefix}${index + 1}`;
+ return template.map((row) => {
+ const labels = { ...row.labels, [nameLabel]: name, [groupAttr]: groupLabel };
+ // Pods are identified by UID, so a clone needs its own or the list
+ // collapses every clone into one row.
+ if (labels['k8s.pod.uid']) {
+ labels['k8s.pod.uid'] = `${name}-uid`;
+ }
+ return { ...row, labels };
+ });
+ }).flat();
+
+ const rows = rebaseToNow(clones);
+ await postMetrics(page, rows);
+ return factsFor(dataset, rows);
+}
+
+/**
+ * The one place the grouped-clone defaults live.
+ *
+ * {@link seedGroupedDataset} and {@link groupedCloneNames} each used to re-derive
+ * these, so changing a default in one made specs address names that were never
+ * seeded — and the failure would have been a 30 s "row not visible".
+ */
+function resolveGroupedOptions(
+ entity: EntityDef,
+ options: SeedGroupedOptions,
+): { members: number; namePrefix: string; groupLabel: string } {
+ return {
+ members: options.members ?? EXPANDED_ROW_LIMIT + 2,
+ namePrefix: options.namePrefix ?? `viewall-${entity.key}-`,
+ groupLabel: options.groupLabel ?? `viewall-${entity.key}`,
+ };
+}
+
+/**
+ * The row key / `selectedItem` value for a seeded entity called `name`.
+ *
+ * The two differ only for pods, which `getK8sPodRowKey` identifies by UID — and
+ * {@link seedGroupedDataset} mints clone UIDs as `<name>-uid`, the same shape the
+ * `*_value_accuracy` fixtures use (`acc-p1` → `acc-p1-uid`). Addressing a pod row
+ * by its *name* builds `row-acc-p1`, which matches nothing whether the behaviour
+ * under test works or not — a silent pass, not a failure.
+ */
+export function itemKeyFor(entity: EntityDef, name: string): string {
+ return entity.key === 'pods' ? `${name}-uid` : name;
+}
+
+/** Names {@link seedGroupedDataset} produces, without seeding. */
+export function groupedCloneNames(
+ entity: EntityDef,
+ options: SeedGroupedOptions = {},
+): { groupLabel: string; names: string[] } {
+ const { members, namePrefix, groupLabel } = resolveGroupedOptions(
+ entity,
+ options,
+ );
+ return {
+ groupLabel,
+ names: Array.from({ length: members }, (_, i) => `${namePrefix}${i + 1}`),
+ };
+}
diff --git a/tests/e2e/drivers/integrations.ts b/tests/e2e/drivers/integrations.ts
new file mode 100644
index 0000000000..216a4e269f
--- /dev/null
+++ b/tests/e2e/drivers/integrations.ts
@@ -0,0 +1,656 @@
+import {
+ expect,
+ type Locator,
+ type Page,
+ type Response,
+} from '@playwright/test';
+
+import { antdDriver } from './antd';
+import { apiDriver } from './api';
+import type { ConsoleWatch } from './console';
+import { driver, kit, seeded, type Layer, type WorkerLayer } from './kit';
+
+/**
+ * The integrations surface: the list, a built-in integration's detail page, and
+ * the AWS / GCP / Azure one-click pages.
+ *
+ * Built-in installs and cloud accounts are org-global. Specs assert only on
+ * what they seeded; install state of any integration other than the spec's own
+ * is never asserted.
+ */
+
+export const INTEGRATIONS_PATH = '/integrations';
+
+export type CloudProvider = 'aws' | 'gcp' | 'azure';
+export type DetailTab = 'Overview' | 'Configure' | 'Data Collected';
+
+const INTEGRATIONS_API = '/api/v1/integrations';
+const cloudApi = (provider: CloudProvider): string =>
+ `/api/v1/cloud_integrations/${provider}`;
+
+/**
+ * `IntegrationDetailPage` calls `GET /api/v1/integrations/<id>` (and its
+ * connection status) before it branches to the cloud page, so every
+ * `/integrations/{aws,gcp,azure}` load 404s on a result nobody reads.
+ */
+const CLOUD_DETAIL_404 = /\/api\/v1\/integrations\/(aws|gcp|azure)(\/|\?|$)/;
+
+/** Mirrors `CloudintegrationtypesCredentialsDTO`. */
+interface Credentials {
+ ingestionKey: string;
+ ingestionUrl: string;
+ sigNozApiKey: string;
+ sigNozApiUrl: string;
+}
+
+/** Mirrors `CloudintegrationtypesAccountDTO`, trimmed to what specs read. */
+export interface CloudAccountDto {
+ id: string;
+ providerAccountId: string | null;
+ config: { aws?: { regions: string[] } };
+}
+
+/** Mirrors `CloudintegrationtypesServiceConfigDTO` for one provider. */
+export interface ServiceSignals {
+ metrics: boolean;
+ logs: boolean;
+}
+
+export const E2E_CREDENTIALS: Credentials = {
+ ingestionUrl: 'https://ingest.test.signoz.cloud',
+ ingestionKey: 'e2e-ingestion-key',
+ sigNozApiUrl: 'https://e2e.test.signoz.cloud',
+ sigNozApiKey: 'e2e-api-key',
+};
+
+const isCall =
+ (method: string, path: string | RegExp) =>
+ (response: Response): boolean =>
+ response.request().method() === method &&
+ (typeof path === 'string'
+ ? new URL(response.url()).pathname === path
+ : path.test(new URL(response.url()).pathname));
+
+// ─── Built-in integrations ─────────────────────────────────────────────────
+
+export interface Integrations {
+ gotoList(): Promise<void>;
+ searchBox(): Locator;
+ search(text: string): Promise<void>;
+ row(id: string): Locator;
+ rowStatus(id: string): Locator;
+ oneClick(id: CloudProvider): Locator;
+
+ gotoDetail(id: string): Promise<void>;
+ backToList(): Promise<void>;
+ tab(name: DetailTab): Locator;
+ openTab(name: DetailTab): Promise<void>;
+ categories(): Locator;
+ assets(): Locator;
+ configureSteps(): Locator;
+ /** Body rows of the Data Collected metrics table. */
+ metricsRows(): Locator;
+ connectButton(): Locator;
+ /** Connect through the modal. Resolves the install response. */
+ connect(): Promise<Response>;
+ connectionStatus(): Locator;
+ removeButton(): Locator;
+ /** Remove through the confirm modal. Resolves the uninstall response. */
+ remove(): Promise<Response>;
+ uninstallViaApi(id: string): Promise<void>;
+
+ toast(text: string | RegExp): Locator;
+ /** `noise.failedResponses` minus the cloud detail page's known 404. */
+ unexpectedFailures(noise: ConsoleWatch): string[];
+}
+
+export function integrationsDriver(page: Page): Integrations {
+ const api = apiDriver(page);
+
+ const integrations: Integrations = {
+ searchBox: () => page.getByPlaceholder('Search for an integration...'),
+
+ gotoList: async () => {
+ await page.goto(INTEGRATIONS_PATH);
+ await expect(integrations.searchBox()).toBeVisible();
+ },
+
+ search: async (text) => {
+ await integrations.searchBox().fill(text);
+ },
+
+ row: (id) => page.getByTestId(`integration-row-${id}`),
+ rowStatus: (id) => integrations.row(id).getByTestId('integration-row-status'),
+ oneClick: (id) => page.getByTestId(`one-click-integration-${id}`),
+
+ gotoDetail: async (id) => {
+ await page.goto(`${INTEGRATIONS_PATH}/${id}`);
+ await expect(integrations.connectButton()).toBeEnabled();
+ },
+
+ backToList: async () => {
+ await page.getByRole('button', { name: 'All Integrations' }).click();
+ await expect(page).toHaveURL(/\/integrations$/);
+ await expect(integrations.searchBox()).toBeVisible();
+ },
+
+ tab: (name) => page.getByRole('tab', { name }),
+
+ openTab: async (name) => {
+ await integrations.tab(name).click();
+ await expect(integrations.tab(name)).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ },
+
+ categories: () => page.getByTestId('integration-category'),
+ assets: () => page.getByTestId('integration-assets'),
+ configureSteps: () => page.getByTestId('integration-configure-step'),
+ metricsRows: () =>
+ page
+ .getByTestId('integration-metrics-table')
+ .locator('tbody')
+ .getByRole('row'),
+
+ connectButton: () => page.getByTestId('integration-connect-btn'),
+
+ connect: async () => {
+ await integrations.connectButton().click();
+ const installed = page.waitForResponse(
+ isCall('POST', `${INTEGRATIONS_API}/install`),
+ );
+ await page.getByTestId('integration-modal-primary-btn').click();
+ return installed;
+ },
+
+ // The header and the (closed) modal both render one while installed.
+ connectionStatus: () =>
+ page.getByTestId('integration-connection-status').filter({ visible: true }),
+
+ removeButton: () => page.getByTestId('integration-remove-btn'),
+
+ remove: async () => {
+ await integrations.removeButton().click();
+ const removed = page.waitForResponse(
+ isCall('POST', `${INTEGRATIONS_API}/uninstall`),
+ );
+ await page.getByTestId('integration-remove-confirm').click();
+ return removed;
+ },
+
+ uninstallViaApi: async (id) => {
+ await api
+ .post(`${INTEGRATIONS_API}/uninstall`, { integration_id: id })
+ .catch(() => undefined);
+ },
+
+ toast: (text) =>
+ page.locator('[data-sonner-toast]').filter({ hasText: text }),
+
+ unexpectedFailures: (noise) =>
+ noise.failedResponses.filter((entry) => {
+ const url = entry.split(' ').slice(2).join(' ');
+ try {
+ return !CLOUD_DETAIL_404.test(new URL(url).pathname);
+ } catch {
+ return true;
+ }
+ }),
+ };
+
+ return integrations;
+}
+
+// ─── Cloud providers ─────────────────────────────────────────────────────────
+
+export interface AwsFlow {
+ pickDeploymentRegion(label: string): Promise<void>;
+ region(code: string): Locator;
+ toggleRegion(code: string): Promise<void>;
+ /** Fill whichever credential inputs the credentials endpoint left empty. */
+ fillMissingCredentials(): Promise<void>;
+ /**
+ * Submit the add-account drawer. `window.open` is replaced first, so no AWS
+ * console tab opens; the URL it was called with is returned instead.
+ */
+ launch(): Promise<{
+ accountId: string;
+ connectionUrl: string;
+ body: { config?: { aws?: { regions?: string[] } } };
+ }>;
+ /** Set exactly `codes` in the edit drawer and press Update Changes. */
+ updateRegions(codes: string[]): Promise<Response>;
+}
+
+export interface GcpForm {
+ name: string;
+ projectId: string;
+ /** Option text, `<label> (<value>)`. */
+ region: string;
+ projectIds: string[];
+}
+
+export interface GcpFlow {
+ fill(form: GcpForm): Promise<void>;
+ connectButton(): Locator;
+ /** Resolves the create and check-in responses. */
+ connect(): Promise<{ created: Response; checkedIn: Response }>;
+}
+
+export interface Cloud {
+ provider: CloudProvider;
+ seedAccount(providerAccountId: string, regions?: string[]): Promise<string>;
+ createAccount(regions?: string[]): Promise<string>;
+ checkIn(id: string, providerAccountId: string): Promise<void>;
+ /** Best-effort; an empty id (nothing was created) is a no-op. */
+ removeAccount(id: string): Promise<void>;
+ listAccounts(): Promise<CloudAccountDto[]>;
+ setService(
+ id: string,
+ serviceId: string,
+ signals: ServiceSignals,
+ ): Promise<void>;
+
+ goto(accountId?: string): Promise<void>;
+ breadcrumb(): Locator;
+ accountSelector(): Locator;
+ integrateNowButton(): Locator;
+ addAccountButton(): Locator;
+ editAccountButton(): Locator;
+ /** Add New Account when an account exists, Integrate Now otherwise. */
+ addAccount(): Promise<void>;
+ editAccount(): Promise<void>;
+ services(): Locator;
+ service(id: string): Locator;
+ enabledSection(): Locator;
+ notEnabledSection(): Locator;
+ enabledService(id: string): Locator;
+ notEnabledService(id: string): Locator;
+ detailsTab(name: 'Overview' | 'Data Collected'): Locator;
+ metricsSwitch(): Locator;
+ logsSwitch(): Locator;
+ saveButton(): Locator;
+ discardButton(): Locator;
+ /** Press Save. Resolves the service PUT. */
+ saveService(): Promise<Response>;
+ dashboardCards(): Locator;
+ /** Only a provisioned dashboard's card is a button. */
+ provisionedDashboardCards(): Locator;
+ /** The title of the dashboard a card opened. */
+ dashboardTitle(): Locator;
+ waitingCallout(): Locator;
+ /** Disconnect from the edit drawer. Resolves the DELETE. */
+ disconnect(): Promise<Response>;
+
+ aws: AwsFlow;
+ gcp: GcpFlow;
+}
+
+export function cloudDriver(page: Page, provider: CloudProvider): Cloud {
+ const api = apiDriver(page);
+ const antd = antdDriver(page);
+ const base = cloudApi(provider);
+
+ const awsConfig = (regions: string[]): Record<string, unknown> => ({
+ aws: { deploymentRegion: regions[0], regions },
+ });
+ const configFor = (regions: string[]): Record<string, unknown> => {
+ if (provider === 'aws') {
+ return awsConfig(regions);
+ }
+ if (provider === 'gcp') {
+ return {
+ gcp: {
+ deploymentProjectId: 'e2e-deploy',
+ deploymentRegion: 'us-central1',
+ projectIds: ['e2e-deploy'],
+ },
+ };
+ }
+ return { azure: { deploymentRegion: 'eastus', resourceGroups: ['e2e-rg'] } };
+ };
+
+ const cloud: Cloud = {
+ provider,
+
+ createAccount: (regions = ['us-east-1']) =>
+ api.create(`${base}/accounts`, {
+ config: configFor(regions),
+ credentials: E2E_CREDENTIALS,
+ }),
+
+ checkIn: async (id, providerAccountId) => {
+ await api.post(`${base}/accounts/check_in`, {
+ cloudIntegrationId: id,
+ providerAccountId,
+ data: {},
+ });
+ },
+
+ seedAccount: async (providerAccountId, regions) => {
+ const id = await cloud.createAccount(regions);
+ await cloud.checkIn(id, providerAccountId);
+ return id;
+ },
+
+ removeAccount: async (id) => {
+ if (id) {
+ await api.tryDel(`${base}/accounts/${id}`);
+ }
+ },
+
+ listAccounts: async () =>
+ (
+ await api.get<{ data: { accounts: CloudAccountDto[] | null } }>(
+ `${base}/accounts`,
+ )
+ ).data.accounts ?? [],
+
+ setService: async (id, serviceId, { metrics, logs }) => {
+ await api.put(`${base}/accounts/${id}/services/${serviceId}`, {
+ config: {
+ [provider]: {
+ metrics: { enabled: metrics },
+ ...(provider === 'gcp' ? {} : { logs: { enabled: logs } }),
+ },
+ },
+ });
+ },
+
+ // `?cloudAccountId=` does not survive the load: AccountActions strips it
+ // while the account list is still pending, then falls back to the first
+ // account. Accounts are org-global, so pick ours in the selector.
+ goto: async (accountId) => {
+ await page.goto(`${INTEGRATIONS_PATH}/${provider}`);
+ await expect(cloud.breadcrumb()).toBeVisible();
+ if (!accountId) {
+ return;
+ }
+ const account = (await cloud.listAccounts()).find((a) => a.id === accountId);
+ const label = account?.providerAccountId;
+ expect(label, `account ${accountId} is not listed`).toBeTruthy();
+ const select = cloud.accountSelector();
+ await expect(select).toBeVisible();
+ if (!((await select.textContent()) ?? '').includes(label!)) {
+ await select.click();
+ const dropdown = await antd.ownDropdown(select);
+ await dropdown
+ .locator('.ant-select-item-option')
+ .filter({ has: page.getByText(label!, { exact: true }) })
+ .click();
+ }
+ await expect(select).toContainText(label!);
+ await expect(page).toHaveURL(new RegExp(`cloudAccountId=${accountId}`));
+ },
+
+ breadcrumb: () =>
+ page
+ .getByTestId('cloud-header-breadcrumb')
+ .getByRole('link', { name: 'Integrations' }),
+
+ accountSelector: () => page.getByTestId('cloud-account-selector'),
+ integrateNowButton: () => page.getByTestId('cloud-integrate-now-btn'),
+ addAccountButton: () => page.getByTestId('cloud-add-account-btn'),
+ editAccountButton: () => page.getByTestId('cloud-edit-account-btn'),
+
+ // The form hides each credential field the credentials response fills, and
+ // submits without waiting for it, so the fields are only known after it.
+ addAccount: async () => {
+ const credentials = page.waitForResponse(
+ isCall('GET', `${base}/credentials`),
+ );
+ const entry = cloud.addAccountButton().or(cloud.integrateNowButton());
+ await entry.click();
+ await expect(page.getByRole('dialog')).toBeVisible();
+ expect((await credentials).ok()).toBe(true);
+ },
+
+ editAccount: async () => {
+ await cloud.editAccountButton().click();
+ await expect(
+ page.getByRole('dialog').filter({ hasText: 'Account Settings' }),
+ ).toBeVisible();
+ },
+
+ services: () => page.locator('[data-testid^="cloud-service-item-"]'),
+ service: (id) => page.getByTestId(`cloud-service-item-${id}`),
+ enabledSection: () => page.getByTestId('cloud-services-enabled'),
+ notEnabledSection: () => page.getByTestId('cloud-services-not-enabled'),
+ enabledService: (id) =>
+ cloud.enabledSection().getByTestId(`cloud-service-item-${id}`),
+ notEnabledService: (id) =>
+ cloud.notEnabledSection().getByTestId(`cloud-service-item-${id}`),
+ detailsTab: (name) => page.getByRole('tab', { name }),
+ metricsSwitch: () => page.getByTestId('cloud-service-metrics-switch'),
+ logsSwitch: () => page.getByTestId('cloud-service-logs-switch'),
+ saveButton: () => page.getByTestId('cloud-service-save-btn'),
+ discardButton: () => page.getByTestId('cloud-service-discard-btn'),
+
+ saveService: async () => {
+ const saved = page.waitForResponse(
+ isCall('PUT', new RegExp(`^${base}/accounts/[^/]+/services/[^/]+$`)),
+ );
+ await cloud.saveButton().click();
+ return saved;
+ },
+
+ dashboardCards: () =>
+ page.locator('[data-testid^="cloud-service-dashboard-"]'),
+ provisionedDashboardCards: () =>
+ cloud.dashboardCards().and(page.getByRole('button')),
+ dashboardTitle: () => page.getByTestId('dashboard-title'),
+
+ waitingCallout: () => page.getByTestId('cloud-connect-waiting'),
+
+ disconnect: async () => {
+ await page
+ .getByTestId('cloud-disconnect-account-btn')
+ .dispatchEvent('click');
+ const deleted = page.waitForResponse(
+ isCall('DELETE', new RegExp(`^${base}/accounts/[^/]+$`)),
+ );
+ await page.getByTestId('cloud-remove-account-confirm').click();
+ return deleted;
+ },
+
+ aws: {
+ pickDeploymentRegion: async (label) => {
+ const select = page.getByTestId('aws-deployment-region-select');
+ await select.click();
+ const dropdown = await antd.ownDropdown(select);
+ await dropdown
+ .locator('.ant-select-item-option')
+ .filter({ has: page.getByText(label, { exact: true }) })
+ .click();
+ await expect(select).toContainText(label);
+ },
+
+ region: (code) => page.getByTestId(`aws-region-${code}`),
+
+ toggleRegion: async (code) => {
+ const box = cloud.aws.region(code);
+ const before = await box.getAttribute('aria-checked');
+ await box.click();
+ await expect(box).not.toHaveAttribute('aria-checked', before ?? '');
+ },
+
+ fillMissingCredentials: async () => {
+ const fields: [string, string][] = [
+ ['Enter ingestion URL', E2E_CREDENTIALS.ingestionUrl],
+ ['Enter ingestion key', E2E_CREDENTIALS.ingestionKey],
+ ['Enter SigNoz API URL', E2E_CREDENTIALS.sigNozApiUrl],
+ ['Enter SigNoz API Key', E2E_CREDENTIALS.sigNozApiKey],
+ ];
+ for (const [placeholder, value] of fields) {
+ const input = page.getByPlaceholder(placeholder, { exact: true });
+ // eslint-disable-next-line no-await-in-loop
+ if (await input.isVisible()) {
+ // eslint-disable-next-line no-await-in-loop
+ await input.fill(value);
+ }
+ }
+ },
+
+ launch: async () => {
+ await page.evaluate(() => {
+ const w = window as unknown as {
+ open: (url?: string) => null;
+ __e2eOpened?: string;
+ };
+ w.open = (url?: string): null => {
+ w.__e2eOpened = String(url ?? '');
+ return null;
+ };
+ });
+ const created = page.waitForResponse(isCall('POST', `${base}/accounts`));
+ await page.getByTestId('aws-launch-cfn-btn').click();
+ const response = await created;
+ expect(response.status(), await response.text()).toBe(201);
+ const { data } = (await response.json()) as { data: { id: string } };
+ const connectionUrl = await page
+ .waitForFunction(
+ () => (window as unknown as { __e2eOpened?: string }).__e2eOpened,
+ )
+ .then((handle) => handle.jsonValue() as Promise<string>);
+ return {
+ accountId: data.id,
+ connectionUrl,
+ body: response.request().postDataJSON(),
+ };
+ },
+
+ updateRegions: async (codes) => {
+ const boxes = page.locator('[data-testid^="aws-region-"]');
+ await expect(boxes.first()).toBeVisible();
+ for (const box of await boxes.all()) {
+ // eslint-disable-next-line no-await-in-loop
+ const testId = (await box.getAttribute('data-testid')) ?? '';
+ const want = codes.includes(testId.replace('aws-region-', ''));
+ // eslint-disable-next-line no-await-in-loop
+ const checked = (await box.getAttribute('aria-checked')) === 'true';
+ if (want !== checked) {
+ // eslint-disable-next-line no-await-in-loop
+ await box.click();
+ }
+ }
+ // The drawer footer sits below the 720px viewport once the region grid
+ // renders, so a coordinate click never lands.
+ const updated = page.waitForResponse(
+ isCall('PUT', new RegExp(`^${base}/accounts/[^/]+$`)),
+ );
+ await page.getByTestId('aws-update-account-btn').dispatchEvent('click');
+ return updated;
+ },
+ },
+
+ gcp: {
+ fill: async ({ name, projectId, region, projectIds }) => {
+ await page.getByTestId('gcp-account-name-input').fill(name);
+ await page.getByTestId('gcp-deployment-project-id-input').fill(projectId);
+ await page.getByTestId('gcp-deployment-region-select').click();
+ await page.getByText(region, { exact: true }).click();
+ const projects = page.getByTestId('gcp-project-ids-select');
+ await projects.click();
+ const projectInput = page.getByPlaceholder(
+ 'Type a project ID and press Enter',
+ );
+ for (const id of projectIds) {
+ // eslint-disable-next-line no-await-in-loop
+ await projectInput.fill(id);
+ // eslint-disable-next-line no-await-in-loop
+ await projectInput.press('Enter');
+ }
+ // Escape would also close the drawer, so the trigger closes the list.
+ await projects.click();
+ await expect(projectInput).toBeHidden();
+ const secrets: [string, string][] = [
+ ['gcp-signoz-api-url-input', E2E_CREDENTIALS.sigNozApiUrl],
+ ['gcp-signoz-api-key-input', E2E_CREDENTIALS.sigNozApiKey],
+ ['gcp-ingestion-url-input', E2E_CREDENTIALS.ingestionUrl],
+ ['gcp-ingestion-key-input', E2E_CREDENTIALS.ingestionKey],
+ ];
+ for (const [testId, value] of secrets) {
+ // A backend-provided secret renders read-only under the same testid.
+ const input = page.locator(`input[data-testid="${testId}"]`);
+ // eslint-disable-next-line no-await-in-loop
+ if (await input.isVisible()) {
+ // eslint-disable-next-line no-await-in-loop
+ await input.fill(value);
+ }
+ }
+ },
+
+ connectButton: () => page.getByTestId('gcp-connect-account-btn'),
+
+ connect: async () => {
+ const created = page.waitForResponse(isCall('POST', `${base}/accounts`));
+ const checkedIn = page.waitForResponse(
+ isCall('POST', `${base}/accounts/check_in`),
+ );
+ await cloud.gcp.connectButton().click();
+ return { created: await created, checkedIn: await checkedIn };
+ },
+ },
+ };
+
+ return cloud;
+}
+
+// ─── Layers ──────────────────────────────────────────────────────────────────
+
+export const withIntegrations: Layer<{ integrations: Integrations }> = driver(
+ 'integrations',
+ ({ page }) => integrationsDriver(page),
+);
+
+export const withCloud: Layer<{
+ cloud: (provider: CloudProvider) => Cloud;
+}> = driver(
+ 'cloud',
+ ({ page }) =>
+ (provider: CloudProvider) =>
+ cloudDriver(page, provider),
+);
+
+export interface AwsAccountSeed {
+ id: string;
+ providerAccountId: string;
+}
+
+/** One checked-in AWS account per worker, with two regions. */
+export const withAwsAccount: WorkerLayer<{ awsAccount: AwsAccountSeed }> =
+ seeded(
+ 'awsAccount',
+ async ({ page, workerIndex }) => {
+ const providerAccountId = `e2e-aws-w${workerIndex}-${Date.now()}`;
+ const id = await cloudDriver(page, 'aws').seedAccount(providerAccountId, [
+ 'us-east-1',
+ 'us-west-2',
+ ]);
+ return { id, providerAccountId };
+ },
+ async ({ page, value }) => cloudDriver(page, 'aws').removeAccount(value.id),
+ );
+
+/**
+ * The one built-in integration the install spec owns. Uninstalled on open and
+ * on close, so a crashed run cannot leave it installed for the next.
+ */
+export const OWNED_INTEGRATION = 'builtin-nginx';
+
+export const withOwnedIntegration: WorkerLayer<{ ownedIntegration: string }> =
+ seeded(
+ 'ownedIntegration',
+ async ({ page }) => {
+ await integrationsDriver(page).uninstallViaApi(OWNED_INTEGRATION);
+ return OWNED_INTEGRATION;
+ },
+ async ({ page, value }) => integrationsDriver(page).uninstallViaApi(value),
+ );
+
+/** The integrations `test`. */
+export const test = withOwnedIntegration(
+ withAwsAccount(withIntegrations(withCloud(kit))),
+);
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/kit.ts b/tests/e2e/drivers/kit.ts
index 8451dd30d9..3b6d2aa398 100644
--- a/tests/e2e/drivers/kit.ts
+++ b/tests/e2e/drivers/kit.ts
@@ -1,13 +1,45 @@
/**
- * AI-owned. Generated and maintained by coding agents alongside the specs that
- * use it. Do not hand-edit: regenerate it with the spec that needs the change.
+ * The driver kit.
+ *
+ * A spec imports one module: the `test` constant its feature exports. That
+ * constant is built by composing layers, outermost last:
+ *
+ * ```ts
+ * export const test = withInfraMonitoring(withTanstack(kit));
+ * ```
+ *
+ * Each layer adds one named driver to the test arguments, so a spec body never
+ * sees a `Page`:
+ *
+ * ```ts
+ * test('TC-01 …', async ({ infra, table }) => {
+ * await infra.gotoList('pods');
+ * await table.expectColumns(['Pod Name', 'Status']);
+ * });
+ * ```
+ *
+ * A driver is a plain function returning an object of closures over the page.
+ * Drivers reuse each other by calling the factory directly, never by reaching
+ * for another fixture — layer order then carries no meaning beyond reading
+ * order, and a driver stays usable from a worker seed, where test-scoped
+ * fixtures are not reachable.
*/
-import type { Browser, Page, TestType } from '@playwright/test';
-import { newAdminContext } from '../helpers/auth';
+import {
+ expect,
+ test as base,
+ test as playwright,
+ type Browser,
+ type Page,
+ type TestType,
+} from '@playwright/test';
-export { expect, test as kit } from '../fixtures/auth';
+import { ADMIN, newAdminContext, storageStateFor, type User } from './auth';
+import { installBasePathMode } from './base-path';
+import { watchConsole, type ConsoleWatch } from './console';
+import { usersApi, type CreatedUser, type ManagedRole } from './users';
+/** What every driver is built from. */
export interface DriverContext {
page: Page;
}
@@ -15,22 +47,28 @@ export interface DriverContext {
type Fixtures = Record<string, unknown>;
/**
- * Adds test-scoped fixtures to any test carrying `authedPage`. `T` is inferred
- * from the argument: TypeScript cannot invert `T & { authedPage: Page }`, so
- * constraining that way widens every existing fixture to `unknown`.
+ * Adds test-scoped fixtures. Accepts any test that already carries `authedPage`.
+ *
+ * `T` is inferred straight from the argument rather than from an intersection:
+ * TypeScript cannot invert `T & { authedPage: Page }`, so writing the constraint
+ * that way silently widens every existing fixture to `unknown`.
*/
export type Layer<Adds> = <T extends { authedPage: Page }, W extends object>(
base: TestType<T, W>,
) => TestType<T & Adds, W>;
+/** Adds worker-scoped fixtures — seeded data shared by every test in the worker. */
export type WorkerLayer<Adds> = <T extends object, W extends object>(
base: TestType<T, W>,
) => TestType<T, W & Adds>;
/**
- * A `withX` layer binding `build` to the authenticated page. `dispose` runs
- * after the test while the page is still open, so it can clean up over the
- * same session.
+ * Build a `withX` layer that binds `build` to the authenticated page. `dispose`
+ * runs after the test while the page is still open, so it can clean up over
+ * the same session.
+ *
+ * The fixture destructures `authedPage` literally because Playwright derives
+ * fixture dependencies from the function's source text.
*/
export function driver<Name extends string, T>(
name: Name,
@@ -38,8 +76,6 @@ export function driver<Name extends string, T>(
dispose?: (value: T, ctx: DriverContext) => Promise<void>,
): Layer<{ [K in Name]: T }> {
const fixture = {
- // Playwright reads fixture dependencies from the source text, so
- // `authedPage` must stay destructured literally.
[name]: async (
{ authedPage }: { authedPage: Page },
use: (value: T) => Promise<void>,
@@ -51,14 +87,39 @@ export function driver<Name extends string, T>(
}
},
};
+ // The fixture map is keyed at runtime, so its type cannot be expressed
+ // against `extend`'s mapped parameter. The exported `Layer` signature is what
+ // callers see, and it is checked.
return ((test: TestType<Fixtures, Fixtures>) =>
test.extend(fixture as never)) as Layer<{ [K in Name]: T }>;
}
/**
- * A `withX` layer that seeds once per worker and tears down after. `open` and
- * `close` run on a throwaway admin page: worker fixtures cannot reach
- * `authedPage`.
+ * Like {@link driver}, but binds `build` to the logged-out `guestPage`, so a
+ * logged-out feature stays page-free in specs too.
+ */
+export function guestDriver<Name extends string, T>(
+ name: Name,
+ build: (ctx: DriverContext) => T,
+): Layer<{ [K in Name]: T }> {
+ const fixture = {
+ [name]: async (
+ { guestPage }: { guestPage: Page },
+ use: (value: T) => Promise<void>,
+ ) => {
+ await use(build({ page: guestPage }));
+ },
+ };
+ return ((test: TestType<Fixtures, Fixtures>) =>
+ test.extend(fixture as never)) as Layer<{ [K in Name]: T }>;
+}
+
+/**
+ * Build a `withX` layer that seeds data once per worker and tears it down after.
+ *
+ * `open` and `close` run on a throwaway admin page: worker fixtures cannot use
+ * the test-scoped `authedPage`, and every API call needs a context carrying the
+ * admin storage state.
*/
export function seeded<Name extends string, T>(
name: Name,
@@ -88,15 +149,213 @@ export function seeded<Name extends string, T>(
test.extend(fixture as never)) as WorkerLayer<{ [K in Name]: T }>;
}
-/** Run `body` on a throwaway page authenticated as the admin. */
+/**
+ * Run `body` on a throwaway admin page, then close its context. The worker's
+ * cached session is reused, so the cost is a context, not a login.
+ */
export async function onAdminPage<T>(
browser: Browser,
body: (page: Page) => Promise<T>,
): Promise<T> {
const ctx = await newAdminContext(browser);
+ const page = await ctx.newPage();
try {
- return await body(await ctx.newPage());
+ return await body(page);
} finally {
await ctx.close();
}
}
+
+/**
+ * Run `body` on `factory` bound to a throwaway admin page. For seeding and
+ * teardown from a driver whose own page is a less privileged user.
+ */
+export async function asAdmin<D, T>(
+ page: Page,
+ factory: (page: Page) => D,
+ body: (driver: D) => Promise<T>,
+): Promise<T> {
+ const browser = page.context().browser();
+ if (!browser) {
+ throw new Error('asAdmin needs a page launched from a browser');
+ }
+ return onAdminPage(browser, (admin) => body(factory(admin)));
+}
+
+/**
+ * Raise the current test's timeout to `floor`, idempotently.
+ *
+ * **Not `test.slow()`**: that multiplies the budget by three on *every* call, so
+ * a driver method carrying it and called in a loop compounds — ten columns at
+ * 30 s × 3¹⁰ is about seven days, and a test that never times out wedges a
+ * worker until the whole run is killed. Absolute and monotonic instead, so
+ * repeated calls and a spec's own `setTimeout` settle on the largest budget.
+ */
+export function allowFor(floor: number): void {
+ const info = playwright.info();
+ if (info.timeout < floor) {
+ info.setTimeout(floor);
+ }
+}
+
+/**
+ * Seeded data has to be queryable in ClickHouse, not merely rendered, and with
+ * six workers seeding at once that regularly outruns the default expect budget.
+ * Failing at 15 s reports as "row not visible" on data that lands a second
+ * later, which reads as product flake and is not.
+ */
+export const SEEDED_DATA_TIMEOUT = 30_000;
+export const SEEDED_TEST_BUDGET = 90_000;
+
+/**
+ * Who a test runs as. `admin` is the bootstrap admin every existing spec uses;
+ * the others are created once per worker, on first use.
+ */
+export type Identity = 'admin' | 'admin2' | 'editor' | 'viewer';
+
+const MEMBER_ROLES: Record<Exclude<Identity, 'admin'>, ManagedRole> = {
+ admin2: 'signoz-admin',
+ editor: 'signoz-editor',
+ viewer: 'signoz-viewer',
+};
+
+/** The worker's seeded members, created lazily and deleted at worker teardown. */
+export interface Members {
+ get(identity: Exclude<Identity, 'admin'>): Promise<User>;
+}
+
+/**
+ * The root test constant. Everything else is `kit` with layers on top.
+ *
+ * `noise` is a fixture rather than a call in a spec body because the watcher has
+ * to be installed before the first navigation, and a fixture is the only place
+ * that is guaranteed.
+ */
+export const kit = base.extend<
+ {
+ /**
+ * Which identity `user` resolves to. `test.use({ as: 'viewer' })` runs a
+ * describe as a seeded viewer. Anything that logs out, changes a password
+ * or writes a per-user preference must not run as `admin`: every admin
+ * context in the worker shares one session and one preference set.
+ */
+ as: Identity;
+ /**
+ * User identity for this test. Override with `test.use({ user: … })` at the
+ * describe or test level to run as someone else. Defaults to the user `as`
+ * names, which defaults to the pytest-bootstrap-seeded admin.
+ */
+ user: User;
+ /** A page whose context is already authenticated as `user`. */
+ authedPage: Page;
+ /** Console errors and failed responses since before the first navigation. */
+ noise: ConsoleWatch;
+ /** A page in a fresh context with no session, for logged-out flows. */
+ guestPage: Page;
+ /**
+ * An active viewer created for this test alone and deleted after it, for
+ * flows that revoke the session they run in. It has no cached storage
+ * state: log in on `guestPage`.
+ */
+ throwaway: CreatedUser;
+ },
+ {
+ members: Members;
+ /** Applies SIGNOZ_E2E_BASE_PATH before any page or login in the worker. */
+ basePathMode: void;
+ }
+>({
+ basePathMode: [
+ async ({ browser }, use) => {
+ await installBasePathMode(browser);
+ await use();
+ },
+ { scope: 'worker', auto: true },
+ ],
+
+ as: ['admin', { option: true }],
+
+ members: [
+ async ({ browser }, use, workerInfo) => {
+ const stamp = `w${workerInfo.workerIndex}-${Date.now()}`;
+ const created = new Map<string, Promise<CreatedUser>>();
+ await use({
+ get: async (identity) => {
+ let pending = created.get(identity);
+ if (!pending) {
+ pending = onAdminPage(browser, (page) =>
+ usersApi(page).createActive(
+ MEMBER_ROLES[identity],
+ `${identity}-${stamp}`,
+ ),
+ );
+ created.set(identity, pending);
+ }
+ return (await pending).user;
+ },
+ });
+ const settled = await Promise.allSettled(created.values());
+ const ids = settled.flatMap((entry) =>
+ entry.status === 'fulfilled' ? [entry.value.id] : [],
+ );
+ if (ids.length > 0) {
+ await onAdminPage(browser, async (page) => {
+ for (const id of ids) {
+ await usersApi(page).remove(id);
+ }
+ });
+ }
+ },
+ { scope: 'worker' },
+ ],
+
+ user: [
+ async ({ as, members }, use) => {
+ await use(as === 'admin' ? ADMIN : await members.get(as));
+ },
+ { option: true },
+ ],
+
+ guestPage: async ({ browser, baseURL }, use) => {
+ const ctx = await browser.newContext({ baseURL });
+ const page = await ctx.newPage();
+ await use(page);
+ await ctx.close();
+ },
+
+ throwaway: async ({ browser }, use, testInfo) => {
+ const created = await onAdminPage(browser, (page) =>
+ usersApi(page).createActive(
+ 'signoz-viewer',
+ `throwaway-w${testInfo.workerIndex}-${Date.now()}`,
+ ),
+ );
+ await use(created);
+ await onAdminPage(browser, (page) => usersApi(page).remove(created.id));
+ },
+
+ authedPage: async ({ browser, user }, use) => {
+ const ctx = await browser.newContext({
+ storageState: await storageStateFor(browser, user),
+ });
+ const page = await ctx.newPage();
+ // Opt-in CPU throttling reproduces GitHub-runner conditions on developer
+ // machines: `STRESS=1`, typically with `CI=1` for 2 workers and 2 retries.
+ // The rate is the slowdown multiplier; 4× matches the 2 vCPU runner.
+ if (process.env.STRESS === '1') {
+ const client = await ctx.newCDPSession(page);
+ await client.send('Emulation.setCPUThrottlingRate', {
+ rate: Number(process.env.STRESS_CPU_RATE ?? '4'),
+ });
+ }
+ await use(page);
+ await ctx.close();
+ },
+
+ noise: async ({ authedPage }, use) => {
+ await use(watchConsole(authedPage));
+ },
+});
+
+export { ADMIN, expect };
+export type { ConsoleWatch, CreatedUser, Page, User };
diff --git a/tests/e2e/drivers/llm-o11y.ts b/tests/e2e/drivers/llm-o11y.ts
new file mode 100644
index 0000000000..b7eb5c49ce
--- /dev/null
+++ b/tests/e2e/drivers/llm-o11y.ts
@@ -0,0 +1,265 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { apiDriver } from './api';
+import { quickFiltersDriver } from './explorers';
+import {
+ allowFor,
+ driver,
+ kit,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ type Layer,
+} from './kit';
+import { randomSpanId, randomTraceId, seedTracesViaSeeder } from './traces';
+
+/** AI observability: the LLM traces explorer, model pricing and attribute mapping. */
+
+export const LLM_EXPLORER_PATH = '/ai-observability/explorer';
+
+export const LLM_PRICING_PATH = '/ai-observability/configuration';
+export const LLM_PRICING_PAGE_TESTID = 'llm-observability-model-pricing-page';
+export const ATTRIBUTE_MAPPING_PATH = '/ai-observability/attribute-mapping';
+export const ATTRIBUTE_MAPPING_PAGE_TESTID =
+ 'llm-observability-attribute-mapping-page';
+
+/** A seeded two-span trace whose child is an LLM call. */
+export interface LlmTraceSeed {
+ traceId: string;
+ rootSpanId: string;
+ rootName: string;
+}
+
+export interface AttributeMapping {
+ addGroup(): Locator;
+ groupDrawer(): Locator;
+ groupName(): Locator;
+ addGroupAttribute(): Locator;
+ groupAttribute(index: number): Locator;
+ saveGroup(): Locator;
+ /** The expand header of the group named `name`; its testid carries a local id. */
+ groupHeader(name: string): Locator;
+ /** The add-mapper button; its testid carries the group's local id. */
+ addMapper(): Locator;
+ mapperDrawer(): Locator;
+ mapperTarget(): Locator;
+ mapperSource(index: number): Locator;
+ saveMapper(): Locator;
+ unsavedChanges(): Locator;
+ tab(name: string): Locator;
+ testTab(): Locator;
+ runTest(): Locator;
+ testError(): Locator;
+ testResults(): Locator;
+ saveChanges(): Locator;
+}
+
+export interface ModelPricing {
+ addModelCost(): Locator;
+ modelIdInput(): Locator;
+ patternInput(): Locator;
+ addPattern(): Locator;
+ inputCost(): Locator;
+ outputCost(): Locator;
+ save(): Locator;
+ table(): Locator;
+ /** The name cell of the rule for `modelName`; its testid carries the rule id. */
+ modelName(modelName: string): Locator;
+}
+
+export interface LlmO11y {
+ /**
+ * Seed a trace the AI explorer lists: a root span plus one child carrying
+ * `gen_ai.request.model`, one of the keys that gate a trace into it.
+ */
+ seedLlmTrace(): Promise<LlmTraceSeed>;
+ gotoExplorer(): Promise<void>;
+ traceRow(traceId: string): Locator;
+ /** Re-run the query until the seeded row lands; the page fetches only once. */
+ waitForTraceRow(traceId: string): Promise<void>;
+ openTraceRow(seed: LlmTraceSeed): Promise<void>;
+ /** The trace details waterfall row for `spanId`. */
+ waterfallRow(spanId: string): Locator;
+ /** Trace details tabs; LLM traces open on the thread. */
+ traceDetailsTab(tab: 'overview' | 'thread'): Locator;
+ openQuickFilterSettings(): Promise<void>;
+ quickFilterSettings(): Locator;
+ gotoPricing(): Promise<void>;
+ gotoAttributeMapping(): Promise<void>;
+ mapping: AttributeMapping;
+ pricing: ModelPricing;
+ toast(text: string): Locator;
+ /** Best-effort teardown: delete every pricing rule with one of these models. */
+ deletePricingRules(modelNames: string[]): Promise<void>;
+ /** Best-effort teardown: delete every span-mapper group with one of these names. */
+ deleteSpanMapperGroups(names: string[]): Promise<void>;
+}
+
+export function llmO11yDriver(page: Page): LlmO11y {
+ const api = apiDriver(page);
+
+ const deleteAll = async (
+ path: string,
+ listPath: string,
+ matches: (item: Record<string, string>) => boolean,
+ ): Promise<void> => {
+ const body = await api
+ .get<{ data?: { items?: Record<string, string>[] | null } }>(listPath)
+ .catch(() => ({ data: { items: [] } }));
+ await Promise.all(
+ (body.data?.items ?? [])
+ .filter(matches)
+ .map((item) => api.tryDel(`${path}/${item.id}`).catch(() => undefined)),
+ );
+ };
+
+ const llm: LlmO11y = {
+ seedLlmTrace: async () => {
+ const traceId = randomTraceId();
+ const rootSpanId = randomSpanId();
+ const rootName = `e2e-llm-root-${Date.now()}`;
+ const start = Date.now() - 30_000;
+ const resources = { 'service.name': 'e2e-llm-explorer' };
+ await seedTracesViaSeeder(page.request, [
+ {
+ timestamp: new Date(start).toISOString(),
+ trace_id: traceId,
+ span_id: rootSpanId,
+ name: rootName,
+ kind: 2,
+ duration: 'PT0.5S',
+ resources,
+ attributes: {},
+ },
+ {
+ timestamp: new Date(start + 10).toISOString(),
+ trace_id: traceId,
+ span_id: randomSpanId(),
+ parent_span_id: rootSpanId,
+ name: 'chat gpt-4o',
+ kind: 3,
+ duration: 'PT0.3S',
+ resources,
+ attributes: {
+ 'gen_ai.request.model': 'gpt-4o',
+ 'gen_ai.operation.name': 'chat',
+ 'gen_ai.usage.input_tokens': 12,
+ 'gen_ai.usage.output_tokens': 34,
+ },
+ },
+ ]);
+ return { traceId, rootSpanId, rootName };
+ },
+
+ gotoExplorer: async () => {
+ await quickFiltersDriver(page).dismissAnnouncement();
+ await page.goto(LLM_EXPLORER_PATH);
+ await expect(page.getByTestId('llm-observability-explorer')).toBeVisible();
+ },
+
+ traceRow: (traceId) => page.getByTestId(`traces-table-row-${traceId}`),
+
+ waitForTraceRow: async (traceId) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(async () => {
+ await page.getByTestId('explorer-run-query-btn').click();
+ await expect(llm.traceRow(traceId)).toBeVisible({ timeout: 5_000 });
+ }).toPass({ timeout: SEEDED_DATA_TIMEOUT });
+ },
+
+ // The trace id cell is a link that stops propagation, so the row's own
+ // click handler is reached through another cell.
+ openTraceRow: async ({ traceId, rootName }) => {
+ await llm.traceRow(traceId).getByText(rootName, { exact: true }).click();
+ await page.waitForURL(new RegExp(`/trace/${traceId}`));
+ },
+
+ waterfallRow: (spanId) => page.getByTestId(`cell-0-${spanId}`),
+
+ traceDetailsTab: (tab) => page.getByTestId(`trace-details-tab-${tab}`),
+
+ openQuickFilterSettings: () => quickFiltersDriver(page).openSettings(),
+ quickFilterSettings: () => quickFiltersDriver(page).settingsPanel(),
+
+ gotoPricing: async () => {
+ await page.goto(LLM_PRICING_PATH);
+ await page
+ .getByTestId(LLM_PRICING_PAGE_TESTID)
+ .waitFor({ state: 'visible' });
+ },
+
+ gotoAttributeMapping: async () => {
+ await page.goto(ATTRIBUTE_MAPPING_PATH);
+ await page
+ .getByTestId(ATTRIBUTE_MAPPING_PAGE_TESTID)
+ .waitFor({ state: 'visible' });
+ },
+
+ mapping: {
+ addGroup: () => page.getByTestId('add-group-row'),
+ groupDrawer: () => page.getByTestId('group-form-drawer'),
+ groupName: () => page.getByTestId('group-form-name'),
+ addGroupAttribute: () => page.getByTestId('group-form-attribute-add'),
+ groupAttribute: (index) => page.getByTestId(`group-form-attribute-${index}`),
+ saveGroup: () => page.getByTestId('group-form-save'),
+ groupHeader: (name) =>
+ page.locator('[data-testid^="group-expand-"]').filter({ hasText: name }),
+ addMapper: () => page.locator('[data-testid^="add-mapper-"]'),
+ mapperDrawer: () => page.getByTestId('mapper-form-drawer'),
+ mapperTarget: () => page.getByTestId('mapper-form-target'),
+ mapperSource: (index) => page.getByTestId(`mapper-form-source-${index}`),
+ saveMapper: () => page.getByTestId('mapper-form-save'),
+ unsavedChanges: () => page.getByTestId('unsaved-changes'),
+ tab: (name) => page.getByRole('tab', { name }),
+ testTab: () => page.getByTestId('test-tab'),
+ runTest: () => page.getByTestId('run-test-button'),
+ testError: () => page.getByTestId('test-error'),
+ testResults: () => page.getByTestId('test-results'),
+ saveChanges: () => page.getByTestId('save-changes-btn'),
+ },
+
+ pricing: {
+ addModelCost: () => page.getByTestId('add-model-cost-btn'),
+ modelIdInput: () => page.getByTestId('drawer-model-id-input'),
+ patternInput: () => page.getByTestId('drawer-pattern-input'),
+ addPattern: () => page.getByTestId('drawer-pattern-add-btn'),
+ inputCost: () => page.getByTestId('drawer-input-cost'),
+ outputCost: () => page.getByTestId('drawer-output-cost'),
+ save: () => page.getByTestId('drawer-save-btn'),
+ table: () => page.getByTestId('model-costs-table'),
+ modelName: (modelName) =>
+ page
+ .locator('[data-testid^="model-cell-name-"]')
+ .filter({ hasText: modelName }),
+ },
+
+ toast: (text) => page.getByText(text),
+
+ deletePricingRules: (modelNames) => {
+ const wanted = new Set(modelNames);
+ return deleteAll(
+ '/api/v1/llm_pricing_rules',
+ '/api/v1/llm_pricing_rules?offset=0&limit=100',
+ (rule) => wanted.has(rule.modelName),
+ );
+ },
+
+ deleteSpanMapperGroups: (names) => {
+ const wanted = new Set(names);
+ return deleteAll(
+ '/api/v1/span_mapper_groups',
+ '/api/v1/span_mapper_groups',
+ (group) => wanted.has(group.name),
+ );
+ },
+ };
+
+ return llm;
+}
+
+export const withLlmO11y: Layer<{ llm: LlmO11y }> = driver('llm', ({ page }) =>
+ llmO11yDriver(page),
+);
+
+/** The AI-observability `test`. */
+export const test = withLlmO11y(kit);
+export { expect, onAdminPage } from './kit';
diff --git a/tests/e2e/drivers/logs/detail.ts b/tests/e2e/drivers/logs/detail.ts
new file mode 100644
index 0000000000..426a754da7
--- /dev/null
+++ b/tests/e2e/drivers/logs/detail.ts
@@ -0,0 +1,82 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+/** The log detail drawer: body, highlights, Overview/Context tabs, field actions. */
+
+export type DetailTab = 'Overview' | 'Context' | 'Metrics';
+export type FieldAction =
+ | 'Filter for value'
+ | 'Filter out value'
+ | 'Group by field'
+ | 'Replace filters with this value';
+
+export interface LogDetail {
+ drawer(): Locator;
+ /** Click a row (any format) and wait for the drawer. */
+ open(row: Locator): Promise<void>;
+ body(): Locator;
+ highlights(): Locator;
+ tab(name: DetailTab): Promise<void>;
+ viewMode(mode: 'Pretty' | 'JSON'): Promise<void>;
+ /**
+ * The actions trigger of a pretty-view field. `fieldKey` is the dotted path
+ * from the root, e.g. `attributes.e2e.kind`.
+ */
+ fieldActions(fieldKey: string): Locator;
+ fieldAction(fieldKey: string, action: FieldAction): Promise<void>;
+ contextItems(): Locator;
+ close(): Promise<void>;
+}
+
+export function logDetailDriver(page: Page): LogDetail {
+ const drawer = (): Locator => page.getByTestId('log-detail-drawer');
+
+ const detail: LogDetail = {
+ drawer,
+
+ open: async (row) => {
+ // Column rows are table rows whose first cell opens the drawer; Default
+ // and Raw rows are clickable as a whole.
+ const cell = row.locator('td').first();
+ if ((await cell.count()) > 0) {
+ await cell.click();
+ } else {
+ await row.click();
+ }
+ await expect(drawer()).toBeVisible();
+ },
+
+ body: () => page.getByTestId('log-detail-body'),
+ highlights: () => page.getByTestId('log-details-highlights'),
+
+ tab: async (name) => {
+ await page
+ .getByTestId('log-detail-views-tabs')
+ .getByText(name, { exact: true })
+ .click();
+ },
+
+ viewMode: async (mode) => {
+ await page
+ .getByTestId('data-viewer-view-mode')
+ .getByText(mode, { exact: true })
+ .click();
+ },
+
+ fieldActions: (fieldKey) =>
+ drawer().getByTestId(`pretty-view-actions-${fieldKey}`),
+
+ fieldAction: async (fieldKey, action) => {
+ await detail.fieldActions(fieldKey).click();
+ await page.getByRole('menuitem', { name: action }).click();
+ },
+
+ contextItems: () => page.locator('[data-testid^="context-log-item-"]'),
+
+ close: async () => {
+ await page.keyboard.press('Escape');
+ await expect(drawer()).toBeHidden();
+ },
+ };
+
+ return detail;
+}
diff --git a/tests/e2e/drivers/logs/explorer.ts b/tests/e2e/drivers/logs/explorer.ts
new file mode 100644
index 0000000000..5b12a5a377
--- /dev/null
+++ b/tests/e2e/drivers/logs/explorer.ts
@@ -0,0 +1,432 @@
+import fs from 'fs';
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { antdDriver } from '../antd';
+import { allowFor, SEEDED_DATA_TIMEOUT, SEEDED_TEST_BUDGET } from '../kit';
+import {
+ expressionParams,
+ querySearchDriver,
+ type QuerySearch,
+} from '../querysearch';
+import { tanstackDriver, type Tanstack } from '../tanstack';
+import { timePickerDriver, type TimePicker } from '../timepicker';
+
+import { logDetailDriver, type LogDetail } from './detail';
+import { liveTailDriver, type LiveTail } from './liveTail';
+import { ROW_SELECTOR } from './rows';
+import { seedOne } from './seed';
+
+export const LOGS_EXPLORER_PATH = '/logs/logs-explorer';
+export const LINKED_ROW_CLASS = 'logs-linked-row';
+
+const RELATIVE_TIME = '6h';
+const FORMAT_OPTIONS = 'periscope-btn-format-options';
+const ROW_PREFIX = 'logs-table-row-';
+const LOG_DETAIL_DRAWER = 'log-detail-drawer';
+const LIST = 'logs-list-virtuoso';
+const RUN_QUERY = 'explorer-run-query-btn';
+const ANNOUNCEMENT_DISMISSED_KEY = 'QUICK_FILTERS_SETTINGS_ANNOUNCEMENT';
+const RELOAD_BUDGET_MS = 60_000;
+
+// `addInitScript` re-runs on every navigation, so the dismissal is registered at
+// most once per page rather than stacking up across helper calls.
+const announcementDismissed = new WeakSet<Page>();
+
+/**
+ * Hide the quick-filters announcement tooltip so it cannot swallow a click.
+ *
+ * Registered through `addInitScript` rather than `page.evaluate` so it runs
+ * in the app's own origin on every navigation: an `evaluate` before `goto`
+ * writes to the pre-navigation `about:blank` origin, which the app never
+ * reads. Must run before the first navigation.
+ */
+export async function dismissQuickFiltersAnnouncement(
+ page: Page,
+): Promise<void> {
+ if (announcementDismissed.has(page)) {
+ return;
+ }
+ await page.addInitScript((key) => {
+ localStorage.setItem(key, 'false');
+ }, ANNOUNCEMENT_DISMISSED_KEY);
+ announcementDismissed.add(page);
+}
+
+export type LogsFormat = 'Raw' | 'Default' | 'Column';
+export type LogsView = 'List View' | 'Time Series' | 'Table';
+
+const FORMAT_MODES: Record<LogsFormat, string> = {
+ Raw: 'raw',
+ Default: 'list',
+ Column: 'table',
+};
+
+const VIEW_PANEL: Record<LogsView, string> = {
+ 'List View': 'list',
+ 'Time Series': 'graph',
+ Table: 'table',
+};
+
+export interface GotoOptions {
+ expression?: string;
+ relativeTime?: string;
+ pageSize?: number;
+ view?: LogsView;
+}
+
+export interface LogsExplorer {
+ goto(options?: GotoOptions): Promise<void>;
+ /**
+ * `goto`, then reload until `firstBody` renders. The explorer fetches once
+ * and shows its empty state without refetching when ingestion lags.
+ */
+ gotoUntil(firstBody: string, options?: GotoOptions): Promise<void>;
+ setFormat(format: LogsFormat): Promise<void>;
+ search: QuerySearch;
+ table: Tanstack;
+ timePicker: TimePicker;
+ detail: LogDetail;
+ live: LiveTail;
+
+ /** Rows of the explorer list, in any format. */
+ listRows(): Locator;
+ rowByBody(text: string): Locator;
+ /** `line-NN` / `old` / `json` tokens of the rendered rows, in DOM order. */
+ visibleTokens(marker: string): Promise<string[]>;
+ runButton(): Locator;
+
+ switchView(view: LogsView): Promise<void>;
+ timeSeriesGraph(): Locator;
+ timeSeriesCanvas(): Locator;
+ timeSeriesHeader(): Locator;
+ frequencyChart(): Locator;
+ /** Turn the frequency chart on. It is off until a viewer enables it. */
+ showFrequencyChart(): Promise<void>;
+ queryTable(): Locator;
+ queryTableRows(): Locator;
+
+ /** Pick a preset by URL value (`15m`). */
+ setTimeRange(value: string): Promise<void>;
+ /** Pick an order-by option by label, e.g. `timestamp (asc)`. */
+ setOrderBy(label: string): Promise<void>;
+ /**
+ * Scroll the Column table until `expected` distinct rows have rendered. Fails
+ * if one DOM snapshot ever holds the same row twice. Returns every key seen.
+ */
+ collectRowKeys(expected: number): Promise<string[]>;
+ openColumns(): Promise<void>;
+ addColumn(key: string): Promise<void>;
+ /** Export the list and read the file back. */
+ download(format: 'csv' | 'jsonl'): Promise<{ name: string; text: string }>;
+ /** Hover `row`, press its copy-link button, return the clipboard text. */
+ copyRowLink(row: Locator): Promise<string>;
+ /** Seed one row under `service`, `offsetMs` from now. */
+ seedRow(service: string, body: string, offsetMs?: number): Promise<void>;
+ toast(text: string): Locator;
+ reload(): Promise<void>;
+ /** Open `url` in a new tab of the same context. */
+ openInNewTab(url: string): Promise<Page>;
+ /** A row by log id, in any format. */
+ rowById(logId: string, target?: Page): Locator;
+ /** Top-level route tab (Explorer, Pipelines, Views). */
+ openTab(name: string): Promise<void>;
+ gotoIndexFields(): Promise<void>;
+
+ rows(target?: Page): Locator;
+ row(logId: string, target?: Page): Locator;
+ highlightedRows(target?: Page): Locator;
+ unhighlightedRows(target?: Page): Locator;
+ activeLogId(target?: Page): string;
+ detailsDrawer(target?: Page): Locator;
+ clickRowFirstCell(row: Locator): Promise<void>;
+ openDetailsFromRow(row: Locator): Promise<void>;
+ openContextView(): Promise<void>;
+ /** Click the first context log; resolves with the tab it opened. */
+ openFirstContextLogInNewTab(): Promise<Page>;
+}
+
+function explorerUrl(options: GotoOptions): string {
+ const params = new URLSearchParams({
+ relativeTime: options.relativeTime ?? RELATIVE_TIME,
+ });
+ if (options.expression) {
+ for (const [key, value] of Object.entries(
+ expressionParams(options.expression, 'logs'),
+ )) {
+ // `expressionParams` is already URI-encoded; URLSearchParams encodes
+ // again, which is the double encoding the app itself writes.
+ params.set(key, value);
+ }
+ }
+ if (options.pageSize) {
+ params.set('pageSize', String(options.pageSize));
+ }
+ if (options.view) {
+ params.set('panelTypes', JSON.stringify(VIEW_PANEL[options.view]));
+ }
+ return `${LOGS_EXPLORER_PATH}?${params.toString()}`;
+}
+
+export function logsExplorerDriver(page: Page): LogsExplorer {
+ const contextItems = (): Locator =>
+ page.locator('[data-testid^="context-log-item-"]');
+ const listRows = (): Locator => page.getByTestId(LIST).locator(ROW_SELECTOR);
+ const table = tanstackDriver(page, { rowTestIdPrefix: ROW_PREFIX });
+ const timePicker = timePickerDriver(page);
+ const formatOption = (format: LogsFormat): Locator =>
+ page.getByTestId(`format-option-${FORMAT_MODES[format]}`);
+
+ const readyLocator = (view?: LogsView): Locator => {
+ if (view === 'Time Series') {
+ return page.getByTestId('time-series-view-header');
+ }
+ if (view === 'Table') {
+ return page.getByTestId('query-table');
+ }
+ return page.getByTestId(FORMAT_OPTIONS);
+ };
+
+ const logs: LogsExplorer = {
+ search: querySearchDriver(page, { runTestId: RUN_QUERY }),
+ table,
+ timePicker,
+ detail: logDetailDriver(page),
+ live: liveTailDriver(page),
+
+ goto: async (options = {}) => {
+ await dismissQuickFiltersAnnouncement(page);
+ await page.goto(explorerUrl(options));
+ await expect(readyLocator(options.view)).toBeVisible();
+ },
+
+ gotoUntil: async (firstBody, options = {}) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await logs.goto(options);
+ let attempt = 0;
+ await expect(async () => {
+ if (attempt > 0) {
+ await page.reload();
+ }
+ attempt += 1;
+ await expect(logs.rowByBody(firstBody).first()).toBeVisible({
+ timeout: 10_000,
+ });
+ }).toPass({ timeout: RELOAD_BUDGET_MS, intervals: [1_000] });
+ },
+
+ setFormat: async (format) => {
+ const trigger = page.getByTestId(FORMAT_OPTIONS);
+ const option = formatOption(format);
+ const applied = new RegExp(`%22format%22%3A%22${FORMAT_MODES[format]}%22`);
+
+ await expect(async () => {
+ if (!(await option.isVisible())) {
+ await trigger.click();
+ await expect(option).toBeVisible();
+ }
+ await option.click();
+ await expect(page).toHaveURL(applied, { timeout: 3_000 });
+ }).toPass({ timeout: 20_000 });
+
+ await trigger.click();
+ await expect(option).toBeHidden();
+ },
+
+ listRows,
+ rowByBody: (text) => listRows().filter({ hasText: text }),
+
+ visibleTokens: async (marker) => {
+ const texts = await listRows().allInnerTexts();
+ const token = new RegExp(`${marker} (line-\\d{2}|old)|${marker} json`);
+ return texts.flatMap((text) => {
+ const match = token.exec(text);
+ if (!match) {
+ return [];
+ }
+ return [match[1] ?? 'json'];
+ });
+ },
+
+ runButton: () => page.getByTestId(RUN_QUERY),
+
+ switchView: async (view) => {
+ await page.getByRole('button', { name: view, exact: true }).click();
+ await expect(page).toHaveURL(
+ new RegExp(`panelTypes=(%22|")${VIEW_PANEL[view]}(%22|")`),
+ );
+ },
+
+ timeSeriesGraph: () => page.getByTestId('time-series-graph'),
+ timeSeriesCanvas: () =>
+ page.getByTestId('time-series-graph').locator('canvas').first(),
+ timeSeriesHeader: () => page.getByTestId('time-series-view-header'),
+ frequencyChart: () => page.getByTestId('logs-frequency-chart'),
+ showFrequencyChart: async () => {
+ const toggle = page.getByTestId('logs-frequency-chart-toggle');
+ if ((await toggle.getAttribute('aria-checked')) !== 'true') {
+ await toggle.click();
+ }
+ await expect(toggle).toHaveAttribute('aria-checked', 'true');
+ },
+ queryTable: () => page.getByTestId('query-table'),
+ queryTableRows: () =>
+ page.getByTestId('query-table').locator('tbody tr.ant-table-row'),
+
+ setTimeRange: async (value) => {
+ await timePicker.pickPreset(value);
+ },
+
+ setOrderBy: async (label) => {
+ const select = page.getByTestId('list-view-order-by');
+ await select.click();
+ await select
+ .locator('input[role="combobox"]')
+ .fill(label.split(' ')[0] ?? label);
+ const dropdown = await antdDriver(page).ownDropdown(select);
+ await dropdown
+ .locator('.ant-select-item-option')
+ .filter({ has: page.getByText(label, { exact: true }) })
+ .click();
+ await expect(select).toContainText(label);
+ },
+
+ collectRowKeys: async (expected) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ const seen = new Set<string>();
+ await expect(async () => {
+ const keys = (await table.rowKeys()).filter(
+ (key) => key && key !== 'undefined',
+ );
+ expect(new Set(keys).size).toBe(keys.length);
+ keys.forEach((key) => seen.add(key));
+ if (seen.size < expected) {
+ // Virtuoso loads the next page when the last row nears the viewport.
+ await table.rows().last().scrollIntoViewIfNeeded({ timeout: 2_000 });
+ await page.mouse.wheel(0, 4_000);
+ }
+ expect(seen.size).toBeGreaterThanOrEqual(expected);
+ }).toPass({ timeout: SEEDED_DATA_TIMEOUT, intervals: [500] });
+ return [...seen];
+ },
+
+ openColumns: async () => {
+ await page.getByTestId(FORMAT_OPTIONS).click();
+ await page.getByTestId('periscope-btn-edit-columns').click();
+ await expect(page.getByPlaceholder('Search for a field...')).toBeVisible();
+ },
+
+ addColumn: async (key) => {
+ const searchBox = page.getByPlaceholder('Search for a field...');
+ await searchBox.fill(key);
+ // The Add buttons carry no testid, and the search is debounced, so pick
+ // the button inside the row naming `key` (the innermost matching div).
+ const item = page
+ .locator('div')
+ .filter({ has: page.getByText(key, { exact: true }) })
+ .filter({ has: page.getByRole('button', { name: 'Add', exact: true }) })
+ .last();
+ await item.hover();
+ await item.getByRole('button', { name: 'Add', exact: true }).click();
+ await page.getByRole('button', { name: 'Save changes' }).click();
+ await expect(logs.toast('Saved successfully')).toBeVisible();
+ },
+
+ download: async (format) => {
+ await page.getByTestId('periscope-btn-download-logs').click();
+ await page.getByRole('radio', { name: format, exact: true }).click();
+ const [file] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('button', { name: 'Export', exact: true }).click(),
+ ]);
+ return {
+ name: file.suggestedFilename(),
+ text: fs.readFileSync(await file.path(), 'utf8'),
+ };
+ },
+
+ copyRowLink: async (row) => {
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write']);
+ await row.hover();
+ await row.getByTestId('log-line-copy-link').click();
+ await expect(logs.toast('Copied to clipboard')).toBeVisible();
+ return page.evaluate(() => navigator.clipboard.readText());
+ },
+
+ seedRow: (service, body, offsetMs = 0) =>
+ seedOne(page.request, service, body, offsetMs),
+
+ toast: (text) => page.getByText(text, { exact: true }),
+
+ reload: async () => {
+ await page.reload();
+ await expect(page.getByTestId(FORMAT_OPTIONS)).toBeVisible();
+ },
+
+ openInNewTab: async (url) => {
+ const tab = await page.context().newPage();
+ await tab.goto(url);
+ return tab;
+ },
+
+ rowById: (logId, target = page) =>
+ target.getByTestId(LIST).locator(`[data-testid$="-row-${logId}"]`),
+
+ openTab: async (name) => {
+ await page.getByRole('tab', { name }).first().click();
+ },
+
+ gotoIndexFields: async () => {
+ await page.goto('/logs-explorer/index-fields');
+ await expect(page.getByRole('tab', { name: 'Index Fields' })).toBeVisible();
+ },
+
+ // The linked-row scenarios read a second tab, so every locator takes an
+ // optional page and defaults to this driver's own.
+ rows: (target = page) => target.locator(`[data-testid^="${ROW_PREFIX}"]`),
+ row: (logId, target = page) => target.getByTestId(`${ROW_PREFIX}${logId}`),
+
+ highlightedRows: (target = page) =>
+ logs.rows(target).and(target.locator(`.${LINKED_ROW_CLASS}`)),
+
+ unhighlightedRows: (target = page) =>
+ target.locator(`[data-testid^="${ROW_PREFIX}"]:not(.${LINKED_ROW_CLASS})`),
+
+ activeLogId: (target = page) => {
+ const value = new URL(target.url()).searchParams.get('activeLogId');
+ if (!value) {
+ throw new Error(`No activeLogId in URL: ${target.url()}`);
+ }
+ return value.replace(/"/g, '');
+ },
+
+ detailsDrawer: (target = page) => target.getByTestId(LOG_DETAIL_DRAWER),
+
+ clickRowFirstCell: async (row) => {
+ await row.locator('td').first().click();
+ },
+
+ openDetailsFromRow: async (row) => {
+ await logs.clickRowFirstCell(row);
+ await expect(logs.detailsDrawer(row.page())).toBeVisible();
+ },
+
+ openContextView: async () => {
+ await page
+ .getByTestId('log-detail-views-tabs')
+ .getByText('Context', { exact: true })
+ .click();
+ await expect(contextItems().first()).toBeVisible();
+ },
+
+ openFirstContextLogInNewTab: async () => {
+ const [newTab] = await Promise.all([
+ page.context().waitForEvent('page'),
+ contextItems().first().click(),
+ ]);
+ await newTab.waitForLoadState();
+ return newTab;
+ },
+ };
+
+ return logs;
+}
diff --git a/tests/e2e/drivers/logs/index.ts b/tests/e2e/drivers/logs/index.ts
new file mode 100644
index 0000000000..b5ca16ef13
--- /dev/null
+++ b/tests/e2e/drivers/logs/index.ts
@@ -0,0 +1,47 @@
+import { driver, kit, type Layer } from '../kit';
+
+import { logsExplorerDriver, type LogsExplorer } from './explorer';
+import { pipelinesDriver, type Pipelines } from './pipelines';
+import { logsRailDriver, type LogsRail } from './rail';
+import { withLogsSeed } from './seed';
+import { logsViewsDriver, type LogsViews } from './views';
+
+export const withLogs: Layer<{
+ logs: LogsExplorer;
+ views: LogsViews;
+ pipelines: Pipelines;
+ logsRail: LogsRail;
+}> = (base) =>
+ driver('logsRail', ({ page }) => logsRailDriver(page))(
+ driver('pipelines', ({ page }) => pipelinesDriver(page))(
+ driver('views', ({ page }) => logsViewsDriver(page))(
+ driver('logs', ({ page }) => logsExplorerDriver(page))(base),
+ ),
+ ),
+ );
+
+/**
+ * The logs `test`: explorer, detail drawer, live tail, saved views, pipelines
+ * and the quick-filters rail, over one worker-scoped seed (`logsSeed`).
+ */
+export const test = withLogs(withLogsSeed(kit));
+
+export { expect, SEEDED_DATA_TIMEOUT } from '../kit';
+export {
+ LINKED_ROW_CLASS,
+ LOGS_EXPLORER_PATH,
+ logsExplorerDriver,
+ type LogsExplorer,
+ type LogsFormat,
+ type LogsView,
+} from './explorer';
+export type { DetailTab, FieldAction, LogDetail } from './detail';
+export type { LiveTail } from './liveTail';
+export {
+ servicePipeline,
+ type PipelineInput,
+ type Pipelines,
+} from './pipelines';
+export type { LogsRail } from './rail';
+export { lineBody, serviceFilter, sideService, type LogsSeed } from './seed';
+export type { LogsViews } from './views';
diff --git a/tests/e2e/drivers/logs/liveTail.ts b/tests/e2e/drivers/logs/liveTail.ts
new file mode 100644
index 0000000000..1b169eb5d0
--- /dev/null
+++ b/tests/e2e/drivers/logs/liveTail.ts
@@ -0,0 +1,82 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { timePickerDriver } from '../timepicker';
+
+import { ROW_SELECTOR } from './rows';
+
+/**
+ * Live tail on the logs explorer List view. The stream is an SSE request to
+ * `/api/v3/logs/livetail`, and the backend only returns rows stamped after the
+ * moment it connected, so rows a test expects must be seeded after `start`.
+ */
+
+const LIVE_TAIL_PATH = '/logs/livetail';
+const PAUSE_RESUME = 'live-logs-pause-resume';
+
+export interface LiveTail {
+ /** Go live and wait for the stream to connect. */
+ start(): Promise<void>;
+ list(): Locator;
+ rows(): Locator;
+ rowByBody(text: string): Locator;
+ pauseResume(): Locator;
+ pause(): Promise<void>;
+ /** Resume and wait for the new stream to connect. */
+ resume(): Promise<void>;
+ /** Assert `body` stays off the list for `ms`. */
+ expectAbsentFor(body: string, ms: number): Promise<void>;
+ /** Pick the 15 minute preset, which leaves live mode. */
+ exit(): Promise<void>;
+}
+
+export function liveTailDriver(page: Page): LiveTail {
+ const pauseResume = (): Locator => page.getByTestId(PAUSE_RESUME);
+ const connected = (): Promise<unknown> =>
+ page.waitForResponse((response) => response.url().includes(LIVE_TAIL_PATH));
+
+ const live: LiveTail = {
+ list: () => page.getByTestId('live-logs-list'),
+ rows: () => live.list().locator(ROW_SELECTOR),
+ rowByBody: (text) => live.rows().filter({ hasText: text }),
+ pauseResume,
+
+ start: async () => {
+ const stream = connected();
+ await timePickerDriver(page).goLive();
+ await stream;
+ await expect(pauseResume()).toHaveText('Pause');
+ },
+
+ pause: async () => {
+ await pauseResume().click();
+ await expect(pauseResume()).toHaveText('Resume');
+ },
+
+ resume: async () => {
+ const stream = connected();
+ await pauseResume().click();
+ await stream;
+ await expect(pauseResume()).toHaveText('Pause');
+ },
+
+ expectAbsentFor: async (body, ms) => {
+ // Absence has no DOM signal: the only proof that a paused stream
+ // delivered nothing is that the row is still missing after a backend
+ // tick. See docs/flake-notes.md.
+ // eslint-disable-next-line playwright/no-wait-for-timeout
+ await page.waitForTimeout(ms);
+ await expect(live.rowByBody(body)).toHaveCount(0);
+ },
+
+ exit: async () => {
+ // The picker input stays read-only while live, so `pickPreset`, which
+ // waits for it to turn editable, cannot open it here.
+ await timePickerDriver(page).input().click();
+ await page.getByTestId('time-option-15m').click();
+ await expect(page).toHaveURL(/relativeTime=15m(&|$)/);
+ await expect(pauseResume()).toHaveCount(0);
+ },
+ };
+
+ return live;
+}
diff --git a/tests/e2e/drivers/logs/pipelines.ts b/tests/e2e/drivers/logs/pipelines.ts
new file mode 100644
index 0000000000..5bbcc591ea
--- /dev/null
+++ b/tests/e2e/drivers/logs/pipelines.ts
@@ -0,0 +1,330 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { antdDriver } from '../antd';
+import { apiDriver } from '../api';
+import { allowFor, SEEDED_DATA_TIMEOUT, SEEDED_TEST_BUDGET } from '../kit';
+
+/**
+ * Logs pipelines: API seeds and the `/logs/pipelines` page.
+ *
+ * Pipelines are one org-wide list and every save replaces it, so exactly one
+ * spec touches them, serially, and resets the list after each test.
+ */
+
+const PIPELINES_PATH = '/logs/pipelines';
+const PIPELINES_API = '/api/v1/logs/pipelines';
+/** `pipelines.alias` is varchar(20); a longer one fails the insert with a 500. */
+const ALIAS_MAX = 20;
+
+/** `/api/v1/logs/pipelines` is not in `docs/api/openapi.yml`, so these are local. */
+export interface AddProcessor {
+ type: 'add';
+ id: string;
+ orderId: number;
+ enabled: boolean;
+ name: string;
+ field: string;
+ value: string;
+}
+
+export interface PipelineFilterItem {
+ key: { key: string; dataType: string; type: string };
+ op: string;
+ value: string;
+}
+
+export interface PipelineInput {
+ id?: string;
+ orderId: number;
+ name: string;
+ alias: string;
+ description?: string;
+ enabled: boolean;
+ filter: { op: 'AND'; items: PipelineFilterItem[] };
+ config: AddProcessor[];
+}
+
+interface PipelinesResponse {
+ data: { pipelines: PipelineInput[] | null; version: number };
+}
+
+/** A pipeline over one `service.name`, with a single add processor. */
+export function servicePipeline(
+ name: string,
+ service: string,
+ orderId = 1,
+): PipelineInput {
+ return {
+ orderId,
+ name,
+ alias: name.replace(/\s/g, '').slice(0, ALIAS_MAX),
+ description: '',
+ enabled: true,
+ filter: {
+ op: 'AND',
+ items: [
+ {
+ key: { key: 'service.name', dataType: 'string', type: 'resource' },
+ op: '=',
+ value: service,
+ },
+ ],
+ },
+ config: [
+ {
+ type: 'add',
+ id: `${name}-add`,
+ orderId: 1,
+ enabled: true,
+ name: 'tag',
+ field: 'attributes.e2e_pipeline',
+ value: 'yes',
+ },
+ ],
+ };
+}
+
+export interface ProcessorForm {
+ /** Label in the processor type select, e.g. `Add`. */
+ type: string;
+ name: string;
+ field: string;
+ value: string;
+}
+
+export interface Pipelines {
+ seed(list: PipelineInput[]): Promise<void>;
+ reset(): Promise<void>;
+ latest(): Promise<PipelineInput[]>;
+
+ goto(): Promise<void>;
+ emptyState(): Locator;
+ newPipelineButton(): Locator;
+ editModeButton(): Locator;
+ row(name: string): Locator;
+ enterEditMode(): Promise<void>;
+ /** Create a pipeline and its first processor through the forms, then save. */
+ createThroughUi(p: {
+ name: string;
+ filter: string;
+ processor: ProcessorForm;
+ }): Promise<void>;
+ expand(name: string): Promise<void>;
+ rename(from: string, to: string): Promise<void>;
+ remove(name: string): Promise<void>;
+ save(): Promise<void>;
+ openChangeHistory(): Promise<void>;
+ changeHistoryRows(): Locator;
+ openPreview(name: string): Promise<void>;
+ /**
+ * Open the preview until its sample list shows `text`. The sample query runs
+ * once per open, so a row still being ingested needs a reopen.
+ */
+ openPreviewUntil(name: string, text: string): Promise<void>;
+ closePreview(): Promise<void>;
+ previewModal(): Locator;
+ previewSamples(): Locator;
+ simulate(): Promise<void>;
+ previewOutput(): Locator;
+ /** Expand the first simulated log into its detail drawer. */
+ expandFirstOutput(): Promise<void>;
+ outputDetail(): Locator;
+}
+
+export function pipelinesDriver(page: Page): Pipelines {
+ const api = apiDriver(page);
+ const antd = antdDriver(page);
+
+ const dialog = (name: string | RegExp): Locator =>
+ page.getByRole('dialog', { name });
+
+ const pipelines: Pipelines = {
+ seed: async (list) => {
+ await api.post(PIPELINES_API, { pipelines: list });
+ },
+
+ reset: async () => {
+ await api.post(PIPELINES_API, { pipelines: [] });
+ },
+
+ latest: async () =>
+ (await api.get<PipelinesResponse>(`${PIPELINES_API}/latest`)).data
+ .pipelines ?? [],
+
+ goto: async () => {
+ await page.goto(PIPELINES_PATH);
+ await expect(
+ pipelines.newPipelineButton().or(pipelines.editModeButton()),
+ ).toBeVisible();
+ },
+
+ emptyState: () => page.getByTestId('pipelines-empty-state'),
+ newPipelineButton: () => page.getByRole('button', { name: 'New Pipeline' }),
+ editModeButton: () => page.getByRole('button', { name: 'Enter Edit Mode' }),
+
+ row: (name) =>
+ page
+ .locator('tr[data-row-key]')
+ .filter({ has: page.getByText(name, { exact: true }) }),
+
+ enterEditMode: async () => {
+ await pipelines.editModeButton().click();
+ await expect(pipelines.editModeButton()).toBeDisabled();
+ },
+
+ createThroughUi: async ({ name, filter, processor }) => {
+ if (await pipelines.newPipelineButton().isVisible()) {
+ await pipelines.newPipelineButton().click();
+ } else {
+ await pipelines.enterEditMode();
+ await page.getByRole('button', { name: 'Add a New Pipeline' }).click();
+ }
+
+ const form = dialog('Create New Pipeline');
+ await expect(form).toBeVisible();
+ const nameInput = form.getByPlaceholder('Name', { exact: true });
+ await nameInput.fill(name);
+
+ // The filter box commits a typed `key op value` into a chip on blur.
+ const filterBox = form.getByTestId('qb-search-select');
+ await filterBox.locator('input[role="combobox"]').click();
+ await page.keyboard.type(filter);
+ await nameInput.click();
+ await expect(filterBox).toContainText(filter);
+
+ await form.getByRole('button', { name: 'Create', exact: true }).click();
+ await expect(form).toBeHidden();
+
+ await pipelines.expand(name);
+ await page.getByRole('button', { name: 'Add Processor' }).click();
+
+ const processorForm = dialog('Create New Processor');
+ await expect(processorForm).toBeVisible();
+ const typeSelect = processorForm.getByTestId('processor-type-select');
+ await typeSelect.click();
+ const dropdown = await antd.ownDropdown(typeSelect);
+ await dropdown
+ .locator('.ant-select-item-option')
+ .filter({ has: page.getByText(processor.type, { exact: true }) })
+ .click();
+ await processorForm
+ .getByPlaceholder('Name', { exact: true })
+ .fill(processor.name);
+ await processorForm
+ .getByPlaceholder('Field', { exact: true })
+ .fill(processor.field);
+ await processorForm
+ .getByPlaceholder('Value', { exact: true })
+ .fill(processor.value);
+ await processorForm
+ .getByRole('button', { name: 'Create', exact: true })
+ .click();
+ await expect(processorForm).toBeHidden();
+
+ await pipelines.save();
+ },
+
+ expand: async (name) => {
+ await pipelines.row(name).getByTestId('pipeline-row-expand').click();
+ },
+
+ rename: async (from, to) => {
+ await pipelines.enterEditMode();
+ await pipelines.row(from).getByTestId('pipeline-edit-action').click();
+ const form = dialog(new RegExp(`^Edit Pipeline : ${from}`));
+ await expect(form).toBeVisible();
+ await form.getByPlaceholder('Name', { exact: true }).fill(to);
+ await form.getByRole('button', { name: 'Update', exact: true }).click();
+ await expect(form).toBeHidden();
+ await pipelines.save();
+ },
+
+ remove: async (name) => {
+ await pipelines.enterEditMode();
+ await pipelines.row(name).getByTestId('pipeline-delete-action').click();
+ const confirm = page
+ .getByRole('dialog')
+ .filter({ hasText: 'Do you want to delete pipeline' });
+ await confirm.getByRole('button', { name: 'Delete', exact: true }).click();
+ await expect(confirm).toBeHidden();
+ await pipelines.save();
+ },
+
+ save: async () => {
+ const saved = page.waitForResponse(
+ (response) =>
+ response.url().endsWith(PIPELINES_API) &&
+ response.request().method() === 'POST',
+ );
+ const button = page.getByRole('button', { name: 'Save Configuration' });
+ await button.click();
+ expect((await saved).ok()).toBe(true);
+ await expect(button).toBeHidden();
+ },
+
+ openChangeHistory: async () => {
+ await page.getByRole('tab', { name: 'Change History' }).click();
+ },
+
+ changeHistoryRows: () =>
+ page
+ .getByRole('tabpanel', { name: 'Change History' })
+ .locator('tbody tr.ant-table-row'),
+
+ openPreview: async (name) => {
+ await pipelines.row(name).getByTestId('pipeline-preview-action').click();
+ await expect(pipelines.previewModal()).toBeVisible();
+ },
+
+ openPreviewUntil: async (name, text) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(async () => {
+ if (await pipelines.previewModal().isVisible()) {
+ await pipelines.closePreview();
+ }
+ await pipelines.openPreview(name);
+ await expect(
+ pipelines.previewSamples().filter({ hasText: text }).first(),
+ ).toBeVisible({ timeout: 10_000 });
+ }).toPass({ timeout: SEEDED_DATA_TIMEOUT * 2, intervals: [1_000] });
+ },
+
+ closePreview: async () => {
+ await page.keyboard.press('Escape');
+ await expect(pipelines.previewModal()).toBeHidden();
+ },
+
+ previewModal: () =>
+ page.getByRole('dialog').filter({
+ hasText: 'Logs processing preview for',
+ }),
+
+ previewSamples: () =>
+ pipelines
+ .previewModal()
+ .getByTestId('pipeline-preview-samples')
+ .getByTestId('pipeline-preview-log'),
+
+ simulate: async () => {
+ await pipelines
+ .previewModal()
+ .getByRole('button', { name: 'Simulate Processing' })
+ .click();
+ },
+
+ previewOutput: () =>
+ pipelines
+ .previewModal()
+ .getByTestId('pipeline-preview-output')
+ .getByTestId('pipeline-preview-log'),
+
+ expandFirstOutput: async () => {
+ await pipelines.previewOutput().first().getByRole('button').click();
+ await expect(pipelines.outputDetail()).toBeVisible();
+ },
+
+ outputDetail: () => page.getByTestId('log-detail-drawer'),
+ };
+
+ return pipelines;
+}
diff --git a/tests/e2e/drivers/logs/rail.ts b/tests/e2e/drivers/logs/rail.ts
new file mode 100644
index 0000000000..f168166134
--- /dev/null
+++ b/tests/e2e/drivers/logs/rail.ts
@@ -0,0 +1,49 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { DEFAULT_CUSTOM_FILTERS, quickFiltersDriver } from '../explorers';
+import { SEEDED_DATA_TIMEOUT } from '../kit';
+
+/** The quick-filters rail on the logs explorer. */
+
+export interface LogsRail {
+ /** The same payload the settings spec seeds, so parallel seeding agrees. */
+ ensureSeeded(): Promise<void>;
+ section(key: string): Locator;
+ /** Filter the list to `value` only, through the value row's Only action. */
+ only(key: string, value: string): Promise<void>;
+}
+
+export function logsRailDriver(page: Page): LogsRail {
+ const rail: LogsRail = {
+ ensureSeeded: () =>
+ quickFiltersDriver(page).seed('logs', DEFAULT_CUSTOM_FILTERS),
+
+ section: (key) => page.locator(`[data-filter-key="${key}"]`),
+
+ only: async (key, value) => {
+ const section = rail.section(key);
+ const header = section.getByTestId('checkbox-filter-header');
+ await expect(header).toBeVisible();
+ if ((await header.getAttribute('data-state')) !== 'open') {
+ await header.click();
+ }
+ await expect(header).toHaveAttribute('data-state', 'open');
+
+ // The service list is global and grows with every worker, so search it
+ // rather than scroll it. The search box renders only once the section
+ // holds more values than it shows.
+ const searchBox = section.getByTestId('checkbox-filter-search');
+ const row = section.getByTestId(`checkbox-value-row-${value}`);
+ await expect(searchBox.or(row).first()).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ if (await searchBox.isVisible()) {
+ await searchBox.fill(value);
+ }
+ await expect(row).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ await row.getByText(value, { exact: true }).click();
+ },
+ };
+
+ return rail;
+}
diff --git a/tests/e2e/drivers/logs/rows.ts b/tests/e2e/drivers/logs/rows.ts
new file mode 100644
index 0000000000..90b9b7939b
--- /dev/null
+++ b/tests/e2e/drivers/logs/rows.ts
@@ -0,0 +1,6 @@
+/** A log row in any list format: Default, Raw or Column. */
+export const ROW_SELECTOR = [
+ '[data-testid^="logs-list-row-"]',
+ '[data-testid^="logs-raw-row-"]',
+ '[data-testid^="logs-table-row-"]',
+].join(', ');
diff --git a/tests/e2e/drivers/logs/seed.ts b/tests/e2e/drivers/logs/seed.ts
new file mode 100644
index 0000000000..3de4a358ea
--- /dev/null
+++ b/tests/e2e/drivers/logs/seed.ts
@@ -0,0 +1,124 @@
+import type { APIRequestContext } from '@playwright/test';
+
+import { seeded, type WorkerLayer } from '../kit';
+import { seedLogs, type SeederLog } from '../telemetry';
+
+/**
+ * The worker's logs, all under one `service.name` the worker owns.
+ *
+ * No teardown: the seeder cannot delete by marker, and additive rows under a
+ * unique service are invisible to every spec that scopes by its own service.
+ */
+
+export const RECENT_COUNT = 25;
+const RECENT_START_AGO_MS = 150_000;
+const RECENT_STEP_MS = 4_000;
+const OLD_AGO_MS = 60 * 60_000;
+const JSON_AGO_MS = 30_000;
+const SEVERITIES = ['INFO', 'WARN', 'ERROR'] as const;
+
+export type LogKind = 'even' | 'odd' | 'old';
+
+export interface LogsSeed {
+ service: string;
+ /** Every body starts with it. Equal to `service`. */
+ marker: string;
+ /** `line-NN` bodies, newest first. */
+ recent: string[];
+ old: string;
+ json: string;
+ total: number;
+ kinds: Record<'even' | 'odd', number>;
+}
+
+export const lineBody = (marker: string, index: number): string =>
+ `${marker} line-${String(index).padStart(2, '0')}`;
+
+export const serviceFilter = (service: string): string =>
+ `service.name = '${service}'`;
+
+const resources = (service: string): Record<string, string> => ({
+ 'service.name': service,
+ 'deployment.environment': 'e2e-logs',
+});
+
+const iso = (ms: number): string => new Date(ms).toISOString();
+
+export function buildWorkerLogs(
+ service: string,
+ now = Date.now(),
+): SeederLog[] {
+ const recent: SeederLog[] = Array.from({ length: RECENT_COUNT }, (_, i) => ({
+ timestamp: iso(now - RECENT_START_AGO_MS + i * RECENT_STEP_MS),
+ body: lineBody(service, i),
+ severity_text: SEVERITIES[i % SEVERITIES.length],
+ resources: resources(service),
+ attributes: { 'e2e.index': i, 'e2e.kind': i % 2 ? 'odd' : 'even' },
+ }));
+ return [
+ ...recent,
+ {
+ timestamp: iso(now - OLD_AGO_MS),
+ body: `${service} old`,
+ resources: resources(service),
+ attributes: { 'e2e.kind': 'old' },
+ },
+ {
+ timestamp: iso(now - JSON_AGO_MS),
+ body: JSON.stringify({ message: `${service} json`, user: { id: 42 } }),
+ resources: resources(service),
+ attributes: { 'e2e.kind': 'json' },
+ },
+ ];
+}
+
+export async function seedWorkerLogs(
+ request: APIRequestContext,
+ service: string,
+): Promise<LogsSeed> {
+ await seedLogs(request, buildWorkerLogs(service));
+ const recent = Array.from({ length: RECENT_COUNT }, (_, i) =>
+ lineBody(service, i),
+ ).reverse();
+ return {
+ service,
+ marker: service,
+ recent,
+ old: `${service} old`,
+ json: `${service} json`,
+ total: RECENT_COUNT + 2,
+ kinds: {
+ even: Math.ceil(RECENT_COUNT / 2),
+ odd: Math.floor(RECENT_COUNT / 2),
+ },
+ };
+}
+
+/**
+ * A service of its own for rows a single test adds (live tail, time window), so
+ * the worker's counts stay fixed for every other spec in the worker.
+ */
+export const sideService = (seed: LogsSeed, suffix: string): string =>
+ `${seed.service}-${suffix}`;
+
+/** One row under `service`, `offsetMs` from now. */
+export async function seedOne(
+ request: APIRequestContext,
+ service: string,
+ body: string,
+ offsetMs = 0,
+): Promise<void> {
+ await seedLogs(request, [
+ {
+ timestamp: iso(Date.now() + offsetMs),
+ body,
+ resources: resources(service),
+ },
+ ]);
+}
+
+export const withLogsSeed: WorkerLayer<{ logsSeed: LogsSeed }> = seeded(
+ 'logsSeed',
+ async ({ page, workerIndex }) =>
+ seedWorkerLogs(page.request, `e2e-logs-w${workerIndex}-${Date.now()}`),
+);
diff --git a/tests/e2e/drivers/logs/views.ts b/tests/e2e/drivers/logs/views.ts
new file mode 100644
index 0000000000..7dc702a958
--- /dev/null
+++ b/tests/e2e/drivers/logs/views.ts
@@ -0,0 +1,25 @@
+import { test as playwright, type Page } from '@playwright/test';
+
+import { savedViewsDriver, type SavedViews } from '../savedviews';
+
+/** Saved views for the logs explorer, on the shared saved-views driver. */
+
+export interface LogsViews extends SavedViews {
+ /** Stamp shared by every view this test creates; `removeByPrefix` takes it. */
+ prefix: string;
+ /** A fresh view name under {@link LogsViews.prefix}. */
+ name(tag: string): string;
+ names(): Promise<string[]>;
+}
+
+export function logsViewsDriver(page: Page): LogsViews {
+ const shared = savedViewsDriver(page, 'logs');
+ const prefix = `e2e-logs-view-w${playwright.info().workerIndex}-${Date.now()}`;
+
+ return {
+ ...shared,
+ prefix,
+ name: (tag) => `${prefix}-${tag}`,
+ names: async () => (await shared.list()).map((view) => view.spec.displayName),
+ };
+}
diff --git a/tests/e2e/drivers/messaging-queues.ts b/tests/e2e/drivers/messaging-queues.ts
new file mode 100644
index 0000000000..4c2355fded
--- /dev/null
+++ b/tests/e2e/drivers/messaging-queues.ts
@@ -0,0 +1,379 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { antdDriver } from './antd';
+import {
+ allowFor,
+ driver,
+ kit,
+ seeded,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ type Layer,
+ type WorkerLayer,
+} from './kit';
+import { celeryTask, kafkaPair, stamp, STATUS } from './spans';
+import { postToSeeder } from './telemetry';
+import { seedTracesViaSeeder } from './traces';
+
+/**
+ * Messaging queues: the overview (`/messaging-queues/overview`), the kafka page
+ * and its detail views, and the celery task page.
+ *
+ * Every table on these pages fetches once on mount, so a seed that is not yet
+ * queryable never shows up without a reload: {@link reloadUntilVisible}.
+ */
+
+const RELATIVE_TIME = '15m';
+const LAG_METRIC = 'kafka.consumer_group.lag';
+
+export type KafkaView =
+ | 'consumerLag'
+ | 'producerLatency'
+ | 'partitionLatency'
+ | 'dropRate'
+ | 'metricPage';
+
+export const KAFKA_VIEWS: KafkaView[] = [
+ 'consumerLag',
+ 'producerLatency',
+ 'partitionLatency',
+ 'dropRate',
+ 'metricPage',
+];
+
+export type DetailType = 'producer-details' | 'consumer-details';
+export type CeleryState = 'all' | 'failed' | 'retry' | 'successful';
+
+// ─── Seed ────────────────────────────────────────────────────────────────────
+
+export interface MqSeed {
+ stamp: string;
+ topic: string;
+ partition: string;
+ group: string;
+ producer: string;
+ consumer: string;
+ /** Kafka pairs seeded; one consumer span of them has status 2. */
+ pairs: number;
+ celeryService: string;
+ task: string;
+ /** The celery overview row's span name. */
+ taskSpan: string;
+ worker: string;
+ /** Celery spans per state tab. */
+ states: Record<CeleryState, number>;
+}
+
+const PAIRS = 3;
+
+async function seedMessagingQueues(
+ page: Page,
+ workerIndex: number,
+): Promise<MqSeed> {
+ const prefix = stamp('mq', workerIndex);
+ const seed: MqSeed = {
+ stamp: prefix,
+ topic: `${prefix}-orders`,
+ partition: '0',
+ group: `${prefix}-grp`,
+ producer: `${prefix}-producer`,
+ consumer: `${prefix}-consumer`,
+ pairs: PAIRS,
+ celeryService: `${prefix}-celery`,
+ task: `${prefix}.send_email`,
+ taskSpan: `run/${prefix}.send_email`,
+ worker: `${prefix}-worker`,
+ states: { all: 4, successful: 2, failed: 1, retry: 1 },
+ };
+
+ const kafka = Array.from({ length: PAIRS }, (_, i) =>
+ kafkaPair({
+ topic: seed.topic,
+ partition: seed.partition,
+ group: seed.group,
+ producer: seed.producer,
+ consumer: seed.consumer,
+ consumerStatus: i === 0 ? STATUS.error : STATUS.ok,
+ agoMs: 60_000 - i * 10_000,
+ }),
+ ).flat();
+
+ const now = Date.now();
+ // The state tabs reduce a 60 s series to its last point, so every task has
+ // to land in one minute bucket: the last complete one.
+ const bucketStart = Math.floor(now / 60_000) * 60_000 - 60_000;
+ const celery = (['SUCCESS', 'SUCCESS', 'FAILURE', 'RETRY'] as const).map(
+ (state, i) =>
+ celeryTask({
+ service: seed.celeryService,
+ task: seed.task,
+ state,
+ hostname: seed.worker,
+ agoMs: now - (bucketStart + 5_000 + i * 1_000),
+ }),
+ );
+
+ const lag = Array.from({ length: 10 }, (_, i) => ({
+ metric_name: LAG_METRIC,
+ labels: { group: seed.group, topic: seed.topic, partition: seed.partition },
+ timestamp: new Date(now - 10 * 60_000 + i * 60_000 + 30_000).toISOString(),
+ value: 5 + i,
+ type_: 'Gauge',
+ temporality: 'Unspecified',
+ is_monotonic: false,
+ }));
+
+ await seedTracesViaSeeder(page.request, [...kafka, ...celery]);
+ await postToSeeder(page.request, '/telemetry/metrics', lag);
+ return seed;
+}
+
+/** Telemetry cannot be deleted per worker, so there is no teardown. */
+export const withMqSeed: WorkerLayer<{ mqSeed: MqSeed }> = seeded(
+ 'mqSeed',
+ ({ page, workerIndex }) => seedMessagingQueues(page, workerIndex),
+);
+
+// ─── Driver ──────────────────────────────────────────────────────────────────
+
+export interface MessagingQueues {
+ gotoOverview(): Promise<void>;
+ overviewTable(): Locator;
+ overviewRow(service: string, span: string): Locator;
+ /** Reload the overview until the row for `service` / `span` renders. */
+ waitForOverviewRow(service: string, span: string): Promise<void>;
+ openOverviewRow(service: string, span: string): Promise<void>;
+ overviewDrawer(): Locator;
+ overviewDrawerMetric(title: string): Locator;
+
+ gotoKafka(): Promise<void>;
+ viewDetailsButtons(): Locator;
+ viewDetails(view: KafkaView): Promise<void>;
+ openHealthCheck(): Promise<Locator>;
+ healthCheckSection(name: 'Consumers' | 'Producers'): Locator;
+
+ /** Deep link a detail view. `params` are extra query params. */
+ gotoKafkaDetail(
+ view: KafkaView,
+ params?: Record<string, string>,
+ ): Promise<void>;
+ /** Consumer-lag view scoped to one group/topic/partition, as a graph click leaves it. */
+ gotoConsumerLagPoint(seed: MqSeed): Promise<void>;
+ viewSelect(): Locator;
+ table(type: 'overview' | 'detail'): Locator;
+ dropRateTable(): Locator;
+ /** Reload the current detail URL until `table` has a row containing `text`. */
+ waitForTableRow(table: Locator, text: string): Promise<void>;
+ /** A row of `table` containing `text`. */
+ tableRow(table: Locator, text: string): Locator;
+ tableHeader(table: Locator, name: string): Locator;
+ producerLatencyToggle(): Locator;
+ producerLatencyOption(option: 'Producers' | 'Consumers'): Locator;
+ detailType(type: DetailType): Locator;
+ consumerLagGraph(): Locator;
+ consumerLagChart(): Locator;
+ consumerLagNoData(): Locator;
+ metricPage(): Locator;
+ metricPageSection(title: string): Locator;
+
+ gotoCelery(): Promise<void>;
+ celeryGrid(): Locator;
+ celeryGridSection(title: string): Locator;
+ /** The first chart the grid draws. */
+ celeryGridChart(): Locator;
+ pickTask(name: string): Promise<void>;
+ /** Deep link the page filtered to `task`, reloading until `state` reads `count`. */
+ gotoCeleryTask(task: string, state: CeleryState, count: number): Promise<void>;
+ celeryStateTab(state: CeleryState): Locator;
+ selectCeleryState(state: CeleryState): Promise<void>;
+}
+
+export function messagingQueuesDriver(page: Page): MessagingQueues {
+ const antd = antdDriver(page);
+
+ /**
+ * `goto` and wait for `target`, reloading on a miss. Budgeted for ingestion,
+ * not render: the page fetches once, so a late row needs a new mount.
+ */
+ const reloadUntilVisible = async (
+ goto: () => Promise<void>,
+ target: () => Locator,
+ attempts = 5,
+ ): Promise<void> => {
+ allowFor(SEEDED_TEST_BUDGET);
+ for (let i = 0; i < attempts; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ await goto();
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ await target().first().waitFor({ state: 'visible', timeout: 8_000 });
+ return;
+ } catch {
+ // not ingested yet; remount
+ }
+ }
+ await expect(target().first()).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ };
+
+ const rowOf = (table: Locator, text: string): Locator =>
+ table.locator('tbody tr').filter({ hasText: text });
+
+ const mq: MessagingQueues = {
+ gotoOverview: async () => {
+ await page.goto(`/messaging-queues/overview?relativeTime=${RELATIVE_TIME}`);
+ await expect(mq.overviewTable()).toBeVisible();
+ },
+
+ overviewTable: () => page.getByTestId('mq-overview-table'),
+
+ overviewRow: (service, span) =>
+ rowOf(mq.overviewTable(), service).filter({ hasText: span }),
+
+ waitForOverviewRow: (service, span) =>
+ reloadUntilVisible(
+ () => mq.gotoOverview(),
+ () => mq.overviewRow(service, span),
+ ),
+
+ openOverviewRow: async (service, span) => {
+ await mq.overviewRow(service, span).first().click();
+ await expect(mq.overviewDrawer()).toBeVisible();
+ },
+
+ overviewDrawer: () => page.getByTestId('mq-overview-details-drawer'),
+ overviewDrawerMetric: (title) =>
+ mq.overviewDrawer().getByText(title, { exact: true }),
+
+ gotoKafka: async () => {
+ await page.goto(`/messaging-queues/kafka?relativeTime=${RELATIVE_TIME}`);
+ await expect(page.getByTestId('mq-view-details-consumerLag')).toBeVisible();
+ },
+
+ viewDetailsButtons: () => page.locator('[data-testid^="mq-view-details-"]'),
+
+ viewDetails: async (view) => {
+ await page.getByTestId(`mq-view-details-${view}`).click();
+ await expect(page).toHaveURL(new RegExp(`mqServiceView=${view}`));
+ },
+
+ openHealthCheck: async () => {
+ // "Configuration", or "Missing Configuration (N)" when checks fail.
+ await page.getByRole('button', { name: /Configuration/ }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toBeVisible();
+ return dialog;
+ },
+
+ healthCheckSection: (name) =>
+ page.getByRole('dialog').getByText(name, { exact: true }),
+
+ gotoKafkaDetail: async (view, params = {}) => {
+ const query = new URLSearchParams({
+ mqServiceView: view,
+ relativeTime: RELATIVE_TIME,
+ ...params,
+ });
+ await page.goto(`/messaging-queues/kafka/detail?${query.toString()}`);
+ await expect(mq.viewSelect()).toBeVisible();
+ },
+
+ gotoConsumerLagPoint: async (seed) => {
+ const now = Date.now();
+ const timeline = {
+ group: seed.group,
+ topic: seed.topic,
+ partition: seed.partition,
+ start: now - 10 * 60_000,
+ end: now,
+ };
+ // The app writes `encodeURIComponent(JSON)` into the param, so the value
+ // carries one encoding beyond URLSearchParams' own.
+ await mq.gotoKafkaDetail('consumerLag', {
+ consumerGrp: seed.group,
+ topic: seed.topic,
+ selectedTimelineQuery: encodeURIComponent(JSON.stringify(timeline)),
+ });
+ },
+
+ viewSelect: () => page.getByTestId('mq-view-select'),
+ table: (type) => page.getByTestId(`mq-table-${type}`),
+ dropRateTable: () => page.getByTestId('mq-drop-rate-table'),
+ tableRow: rowOf,
+ tableHeader: (table, name) => table.getByRole('columnheader', { name }),
+
+ waitForTableRow: async (table, text) => {
+ const url = page.url();
+ await reloadUntilVisible(
+ async () => {
+ await page.goto(url);
+ },
+ () => rowOf(table, text),
+ );
+ },
+
+ producerLatencyToggle: () => page.getByTestId('mq-producer-latency-toggle'),
+ producerLatencyOption: (option) =>
+ page.getByTestId(`mq-producer-latency-toggle-button-${option}`),
+ detailType: (type) =>
+ page.getByTestId(`mq-detail-type-toggle-button-${type}`),
+ consumerLagGraph: () => page.getByTestId('mq-consumer-lag-graph'),
+ consumerLagChart: () => mq.consumerLagGraph().locator('canvas').first(),
+ consumerLagNoData: () =>
+ mq.consumerLagGraph().getByText('No Data', { exact: true }),
+ metricPage: () => page.getByTestId('mq-metric-page'),
+ metricPageSection: (title) => mq.metricPage().getByText(title),
+
+ gotoCelery: async () => {
+ await page.goto(
+ `/messaging-queues/celery-task?relativeTime=${RELATIVE_TIME}`,
+ );
+ await expect(mq.celeryGrid()).toBeVisible();
+ },
+
+ celeryGrid: () => page.getByTestId('celery-graph-grid'),
+ celeryGridSection: (title) => mq.celeryGrid().getByText(title),
+ celeryGridChart: () => mq.celeryGrid().locator('canvas').first(),
+
+ pickTask: async (name) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await antd.pickByName(page.getByTestId('celery-task-name-select'), name);
+ await expect(page).toHaveURL(/taskName=/);
+ },
+
+ gotoCeleryTask: async (task, state, count) => {
+ const query = new URLSearchParams({
+ taskName: task,
+ relativeTime: RELATIVE_TIME,
+ });
+ // The tab's text is its label then its value, e.g. "Failed1".
+ const reads = new RegExp(`\\D${count}$`);
+ await reloadUntilVisible(
+ async () => {
+ await page.goto(`/messaging-queues/celery-task?${query.toString()}`);
+ },
+ () => mq.celeryStateTab(state).filter({ hasText: reads }),
+ );
+ },
+
+ celeryStateTab: (state) => page.getByTestId(`celery-state-tab-${state}`),
+
+ selectCeleryState: async (state) => {
+ await mq.celeryStateTab(state).click();
+ // The tab exposes its selection only through this BEM modifier.
+ await expect(mq.celeryStateTab(state)).toHaveClass(
+ /celery-task-states__tab--selected/,
+ );
+ },
+ };
+
+ return mq;
+}
+
+export const withMessagingQueues: Layer<{ mq: MessagingQueues }> = driver(
+ 'mq',
+ ({ page }) => messagingQueuesDriver(page),
+);
+
+/** The messaging-queues `test`. */
+export const test = withMessagingQueues(withMqSeed(kit));
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/meter.ts b/tests/e2e/drivers/meter.ts
new file mode 100644
index 0000000000..1caf5c51d7
--- /dev/null
+++ b/tests/e2e/drivers/meter.ts
@@ -0,0 +1,86 @@
+import {
+ expect,
+ type Locator,
+ type Page,
+ type Response,
+} from '@playwright/test';
+
+import { driver, kit, SEEDED_DATA_TIMEOUT, type Layer } from './kit';
+import {
+ isQueryRange,
+ metricsExplorerDriver,
+ type MetricsExplorer,
+} from './metrics/driver';
+import { savedViewsDriver, type SavedViews } from './savedviews';
+
+/**
+ * The cost meter: the `/meter` breakdown, the meter explorer and its views.
+ *
+ * Nothing writes `signoz_meter.*` on the e2e stack (the seeder has no meter
+ * endpoint), so the breakdown and explorer are exercised on their empty state.
+ * Meter query semantics are tests/integration/tests/queriermetrics/09_cost_meter.py.
+ */
+
+export const METER_PATH = '/meter';
+export const METER_EXPLORER_PATH = '/meter/explorer';
+
+export type MeterSection = 'total' | 'logs' | 'traces' | 'metrics';
+
+export interface MeterBreakdown {
+ /** Open `/meter` and return the `query_range` responses its widgets fire. */
+ goto(): Promise<Response[]>;
+ section(name: MeterSection): Locator;
+}
+
+export interface Meter {
+ breakdown: MeterBreakdown;
+ explorer: MetricsExplorer;
+ /** Resolve the meter metric-name list the explorer's selector requests. */
+ nextMetricList(): Promise<Response>;
+ views: SavedViews;
+}
+
+export function meterDriver(page: Page): Meter {
+ const breakdown: MeterBreakdown = {
+ goto: async () => {
+ const responses: Response[] = [];
+ const collect = (res: Response): void => {
+ if (isQueryRange(res.request())) {
+ responses.push(res);
+ }
+ };
+ page.on('response', collect);
+ await page.goto(METER_PATH);
+ await expect(breakdown.section('metrics')).toBeVisible();
+ await expect
+ .poll(() => responses.length, { timeout: SEEDED_DATA_TIMEOUT })
+ .toBeGreaterThan(0);
+ page.off('response', collect);
+ return responses;
+ },
+ section: (name) => page.getByTestId(`meter-breakdown-section-${name}`),
+ };
+
+ return {
+ breakdown,
+ explorer: metricsExplorerDriver(page, { path: METER_EXPLORER_PATH }),
+ nextMetricList: () =>
+ page.waitForResponse((res) => {
+ const url = new URL(res.url());
+ return (
+ url.pathname === '/api/v2/metrics' &&
+ res.request().method() === 'GET' &&
+ url.searchParams.get('source') === 'meter'
+ );
+ }),
+ views: savedViewsDriver(page, 'meter'),
+ };
+}
+
+export const withMeter: Layer<{ meter: Meter }> = driver('meter', ({ page }) =>
+ meterDriver(page),
+);
+
+/** The meter `test`. */
+export const test = withMeter(kit);
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/metrics/driver.ts b/tests/e2e/drivers/metrics/driver.ts
new file mode 100644
index 0000000000..97e190a89f
--- /dev/null
+++ b/tests/e2e/drivers/metrics/driver.ts
@@ -0,0 +1,836 @@
+import {
+ expect,
+ type Locator,
+ type Page,
+ type Request,
+ type Response,
+} from '@playwright/test';
+
+import { antdDriver } from '../antd';
+import { apiDriver } from '../api';
+import {
+ createDashboard,
+ dashboardsDriver,
+ deleteViaApi,
+ type DashboardSeed,
+ type Dashboards,
+} from '../dashboards';
+import { editorDriver, type PanelEditor } from '../panel-editor';
+import { driver, SEEDED_DATA_TIMEOUT, type Layer } from '../kit';
+import { querySearchDriver, type QuerySearch } from '../querysearch';
+import { savedViewsDriver, type SavedViews } from '../savedviews';
+import type {
+ MetricreductionruletypesGettableReductionRuleDTO,
+ MetricsexplorertypesMetricMetadataDTO,
+ MetricsexplorertypesStatsRequestDTO,
+ MetricsexplorertypesTreemapRequestDTO,
+ MetricsexplorertypesUpdateMetricMetadataRequestDTO,
+} from '../schemas';
+import { readJson } from '../storage';
+
+import {
+ scopeExpression,
+ seedMetric,
+ type MetricSpec,
+ type MetricsCatalogSeed,
+} from './seeds';
+
+/**
+ * The metrics explorer: the summary list and treemap, the metric details drawer,
+ * inspect, the query explorer and the volume-control tab.
+ */
+
+export const SUMMARY_PATH = '/metrics-explorer/summary';
+export const EXPLORER_PATH = '/metrics-explorer/explorer';
+export const VOLUME_CONTROL_PATH = '/metrics-explorer/volume-control';
+
+const STATS_API = '/api/v2/metrics/stats';
+const TREEMAP_API = '/api/v2/metrics/treemap';
+const METADATA_API = '/api/v2/metrics/metadata';
+const RULES_API = '/api/v2/metric_reduction_rules';
+const QUERY_RANGE_API = '/api/v5/query_range';
+/** `usePageSize('metricsExplorer')`. */
+const PAGE_SIZE_KEY = 'k8s-metricsExplorer-page-size';
+
+export type StatsRequest = MetricsexplorertypesStatsRequestDTO;
+export type TreemapRequest = MetricsexplorertypesTreemapRequestDTO;
+export type MetadataUpdate = MetricsexplorertypesUpdateMetricMetadataRequestDTO;
+export type MetricMetadata = MetricsexplorertypesMetricMetadataDTO;
+export type ReductionRule = MetricreductionruletypesGettableReductionRuleDTO;
+
+export type SummaryTab = 'Summary' | 'Explorer' | 'Volume Control';
+export type SummaryColumn =
+ | 'METRIC'
+ | 'DESCRIPTION'
+ | 'TYPE'
+ | 'UNIT'
+ | 'SAMPLES'
+ | 'TIME SERIES';
+export type MetadataField =
+ | 'description'
+ | 'unit'
+ | 'type'
+ | 'temporality'
+ | 'isMonotonic';
+
+const COLUMN_INDEX: Record<SummaryColumn, number> = {
+ METRIC: 0,
+ DESCRIPTION: 1,
+ TYPE: 2,
+ UNIT: 3,
+ SAMPLES: 4,
+ 'TIME SERIES': 5,
+};
+
+const isPost =
+ (path: string) =>
+ (request: Request): boolean =>
+ request.method() === 'POST' && new URL(request.url()).pathname === path;
+
+function body<T>(request: Request): T {
+ return request.postDataJSON() as T;
+}
+
+/** An antd single select: open, optionally search, pick the exact label. */
+async function pickSingle(
+ page: Page,
+ select: Locator,
+ label: string,
+ search?: string,
+): Promise<void> {
+ const antd = antdDriver(page);
+ await select.click();
+ if (search !== undefined) {
+ await select.locator('input[role="combobox"]').fill(search);
+ }
+ const dropdown = await antd.ownDropdown(select);
+ await dropdown
+ .locator('.ant-select-item-option')
+ .filter({ has: page.getByText(label, { exact: true }) })
+ .first()
+ .click();
+ await expect(select).not.toHaveClass(/ant-select-open/);
+}
+
+export function toast(page: Page, text: string | RegExp): Locator {
+ return page.locator('.ant-notification-notice').filter({ hasText: text });
+}
+
+// ─── Summary, details, inspect ───────────────────────────────────────────────
+
+export interface MetricDetails {
+ drawer(): Locator;
+ title(): Locator;
+ samples(): Locator;
+ timeSeries(): Locator;
+ lastReceived(): Locator;
+ openInExplorer(): Promise<void>;
+ inspectButton(): Locator;
+ inspect(): Promise<void>;
+ attributeKey(key: string): Locator;
+ attributeValue(key: string, value: string): Locator;
+ attributesSearch(text: string): Promise<void>;
+}
+
+export interface MetadataEditor {
+ editButton(): Locator;
+ saveButton(): Locator;
+ edit(): Promise<void>;
+ cancel(): Promise<void>;
+ /** Save and resolve the POST, whatever its status. */
+ save(): Promise<{ body: MetadataUpdate; response: Response }>;
+ setType(label: string): Promise<void>;
+ setTemporality(label: string): Promise<void>;
+ /** `label` is the unit's display name, e.g. "Bytes (B)". */
+ setUnit(label: string): Promise<void>;
+ setDescription(text: string): Promise<void>;
+ value(field: MetadataField): Locator;
+}
+
+export interface InspectDrawer {
+ root(): Locator;
+ seriesCount(): Locator;
+ empty(): Locator;
+ toggleView(): Promise<void>;
+ viewLabel(label: 'Graph View' | 'Table View'): Locator;
+ runButton(): Locator;
+}
+
+export interface Metrics {
+ /** Seed a one-off metric with its own run stamp. Returns its name and scope. */
+ seedMetric(
+ spec: Omit<MetricSpec, 'name' | 'series'> & { prefix: string },
+ ): Promise<{ name: string; scope: string }>;
+ gotoSummary(params?: Record<string, string>): Promise<void>;
+ tab(name: SummaryTab): Locator;
+ search(): QuerySearch;
+ /** Apply `expression` and wait for the stats response that carries it. */
+ scopeTo(expression: string): Promise<void>;
+ /** Arm before acting: the next stats request whose body passes `match`. */
+ nextStatsRequest(
+ match?: (body: StatsRequest) => boolean,
+ ): Promise<StatsRequest>;
+ nextTreemapRequest(
+ match?: (body: TreemapRequest) => boolean,
+ ): Promise<TreemapRequest>;
+ /** Re-run the scoped query until every row in `names` is listed. */
+ waitForRows(names: string[]): Promise<void>;
+ table(): Locator;
+ row(name: string): Locator;
+ cell(name: string, column: SummaryColumn): Locator;
+ rowOrder(names: string[]): Promise<string[]>;
+ sortBy(column: 'SAMPLES' | 'TIME SERIES'): Promise<void>;
+ setPageSize(size: number): Promise<void>;
+ storedPageSize(): Promise<number | null>;
+ treemap(): Locator;
+ setTreemapMode(label: 'Time Series' | 'Samples'): Promise<void>;
+ tile(name: string): Locator;
+ /** The METRIC column's search popover: type, then pick `name`. */
+ searchMetricName(name: string): Promise<void>;
+ openDetails(name: string): Promise<void>;
+ closeDetails(): Promise<void>;
+ details: MetricDetails;
+ metadata: MetadataEditor;
+ inspectDrawer: InspectDrawer;
+ metadataFromApi(name: string): Promise<MetricMetadata>;
+ toast(text: string | RegExp): Locator;
+}
+
+export function metricsDriver(page: Page): Metrics {
+ const api = apiDriver(page);
+ const search = querySearchDriver(page, {
+ runTestId: 'metrics-summary-run-query',
+ });
+ const table = (): Locator => page.getByTestId('metrics-table');
+ const drawer = (): Locator =>
+ page
+ .getByRole('dialog')
+ .filter({ has: page.getByTestId('metric-details-title') });
+
+ const nextRequest = <T>(path: string, match: (b: T) => boolean): Promise<T> =>
+ page
+ .waitForRequest(
+ (request) => isPost(path)(request) && match(body<T>(request)),
+ )
+ .then((request) => body<T>(request));
+
+ const details: MetricDetails = {
+ drawer,
+ title: () => page.getByTestId('metric-details-title'),
+ samples: () => page.getByTestId('metric-highlights-data-points'),
+ timeSeries: () => page.getByTestId('metric-highlights-time-series-total'),
+ lastReceived: () => page.getByTestId('metric-highlights-last-received'),
+
+ openInExplorer: async () => {
+ const button = page.getByTestId('open-in-explorer-button');
+ await expect(button).toBeEnabled();
+ // The button opens the explorer in a new tab; replay its URL here so
+ // the explorer driver stays on this page.
+ const [popup] = await Promise.all([
+ page.context().waitForEvent('page'),
+ button.click(),
+ ]);
+ await popup.waitForURL(new RegExp(EXPLORER_PATH));
+ const url = popup.url();
+ await popup.close();
+ await page.goto(url);
+ },
+
+ inspectButton: () => page.getByTestId('inspect-metric-button'),
+
+ inspect: async () => {
+ await expect(details.inspectButton()).toBeEnabled();
+ await details.inspectButton().click();
+ await expect(page.getByTestId('inspect-metrics-content')).toBeVisible();
+ },
+
+ attributeKey: (key) => page.getByTestId(`attribute-key-${key}`),
+
+ attributeValue: (key, value) =>
+ page
+ .getByTestId('all-attributes-table')
+ .locator('tr')
+ .filter({ has: details.attributeKey(key) })
+ .getByRole('button', { name: value, exact: true }),
+
+ attributesSearch: async (text) => {
+ await page.getByTestId('all-attributes-search').fill(text);
+ },
+ };
+
+ const metadata: MetadataEditor = {
+ editButton: () => page.getByTestId('metadata-edit-button'),
+ saveButton: () => page.getByTestId('metadata-save-button'),
+
+ edit: async () => {
+ await expect(metadata.editButton()).toBeEnabled({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await metadata.editButton().click();
+ await expect(metadata.saveButton()).toBeVisible();
+ },
+
+ cancel: async () => {
+ await page.getByTestId('metadata-cancel-button').click();
+ await expect(metadata.editButton()).toBeVisible();
+ },
+
+ save: async () => {
+ const response = page.waitForResponse((res) =>
+ isPost(METADATA_API)(res.request()),
+ );
+ await metadata.saveButton().click();
+ const res = await response;
+ return { body: body<MetadataUpdate>(res.request()), response: res };
+ },
+
+ setType: (label) =>
+ pickSingle(page, page.getByTestId('metric-type-select'), label),
+ setTemporality: (label) =>
+ pickSingle(page, page.getByTestId('temporality-select'), label),
+ setUnit: (label) =>
+ pickSingle(
+ page,
+ page.getByTestId('unit-select'),
+ label,
+ label.split(' ')[0],
+ ),
+ setDescription: async (text) => {
+ await page.getByTestId('description-input').fill(text);
+ },
+
+ value: (field) =>
+ page
+ .getByTestId('metric-metadata-table')
+ .locator(`tr[data-row-key="${field}"] td`)
+ .nth(1),
+ };
+
+ const inspectDrawer: InspectDrawer = {
+ root: () => page.getByTestId('inspect-metrics-content'),
+ seriesCount: () => page.getByTestId('inspect-time-series-count'),
+ empty: () => page.getByTestId('inspect-metrics-empty'),
+ toggleView: async () => {
+ await page.getByTestId('inspect-view-toggle').click();
+ },
+ viewLabel: (label) => inspectDrawer.root().getByText(label, { exact: true }),
+ runButton: () => page.getByTestId('inspect-run-query'),
+ };
+
+ const metrics: Metrics = {
+ seedMetric: async ({ prefix, ...spec }) => {
+ const run = `t${Date.now()}_${Math.floor(Math.random() * 1e6)}`;
+ const name = `${prefix}_${run}`;
+ await seedMetric(page.request, {
+ ...spec,
+ name,
+ series: [{ resource: { 'e2e.run': run, 'service.name': `e2e-mx-${run}` } }],
+ });
+ return { name, scope: scopeExpression(run) };
+ },
+
+ gotoSummary: async (params = {}) => {
+ const query = new URLSearchParams({ relativeTime: '1h', ...params });
+ await page.goto(`${SUMMARY_PATH}?${query.toString()}`);
+ await expect(page.getByTestId('metrics-table-title')).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ },
+
+ tab: (name) => page.getByRole('tab', { name }),
+ search: () => search,
+
+ scopeTo: async (expression) => {
+ const stats = page.waitForResponse(
+ (res) =>
+ isPost(STATS_API)(res.request()) &&
+ body<StatsRequest>(res.request()).filter?.expression === expression,
+ );
+ await search.apply(expression);
+ expect((await stats).ok()).toBe(true);
+ },
+
+ nextStatsRequest: (match = () => true) => nextRequest(STATS_API, match),
+ nextTreemapRequest: (match = () => true) => nextRequest(TREEMAP_API, match),
+
+ // Seeded rows can land in ClickHouse after the first stats response, and
+ // the summary never re-polls on its own.
+ waitForRows: async (names) => {
+ await expect(async () => {
+ const missing = [];
+ for (const name of names) {
+ // eslint-disable-next-line no-await-in-loop
+ if (!(await metrics.row(name).isVisible())) {
+ missing.push(name);
+ }
+ }
+ if (missing.length > 0) {
+ await search.run();
+ }
+ for (const name of names) {
+ // eslint-disable-next-line no-await-in-loop
+ await expect(metrics.row(name)).toBeVisible({ timeout: 3_000 });
+ }
+ }).toPass({ timeout: SEEDED_DATA_TIMEOUT });
+ },
+
+ table,
+ row: (name) => table().locator(`tr[data-row-key="${name}"]`),
+ cell: (name, column) =>
+ metrics.row(name).locator('td').nth(COLUMN_INDEX[column]),
+
+ rowOrder: async (names) => {
+ const keys = await table()
+ .locator('tr[data-row-key]')
+ .evaluateAll((rows) => rows.map((row) => row.getAttribute('data-row-key')));
+ return keys.filter((key): key is string => !!key && names.includes(key));
+ },
+
+ sortBy: async (column) => {
+ await table().locator('th').filter({ hasText: column }).click();
+ },
+
+ setPageSize: async (size) => {
+ const changer = page
+ .locator('.ant-pagination-options')
+ .locator('.ant-select')
+ .first();
+ await changer.click();
+ await page
+ .locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden)')
+ .locator('.ant-select-item-option')
+ .filter({ hasText: `${size} / page` })
+ .click();
+ },
+
+ storedPageSize: () => readJson<number>(page, PAGE_SIZE_KEY),
+
+ treemap: () =>
+ page.getByTestId('metrics-treemap-container').locator('svg').first(),
+
+ setTreemapMode: (label) =>
+ pickSingle(page, page.getByTestId('metrics-treemap-view-select'), label),
+
+ tile: (name) => page.getByTestId(`metrics-treemap-tile-${name}`),
+
+ searchMetricName: async (name) => {
+ await page.getByTestId('metric-name-search-button').click();
+ await page.getByTestId('metric-name-search-input').fill(name);
+ await page.getByRole('menuitem', { name, exact: true }).first().click();
+ },
+
+ // A row click can land while the list re-renders from a second stats
+ // response, which drops the click; retry until the drawer shows the name.
+ openDetails: async (name) => {
+ await expect(metrics.row(name)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(async () => {
+ if (!(await details.title().isVisible())) {
+ await metrics.row(name).click();
+ }
+ await expect(details.title()).toHaveText(name, { timeout: 2_000 });
+ }).toPass({ timeout: 15_000 });
+ },
+
+ closeDetails: async () => {
+ await drawer().getByRole('button', { name: 'Close' }).click();
+ await expect(details.title()).toHaveCount(0);
+ await expect(page).toHaveURL(/isMetricDetailsOpen=false/);
+ },
+
+ details,
+ metadata,
+ inspectDrawer,
+
+ metadataFromApi: async (name) =>
+ (
+ await api.get<{ data: MetricMetadata }>(
+ `${METADATA_API}?metricName=${encodeURIComponent(name)}`,
+ )
+ ).data,
+
+ toast: (text) => toast(page, text),
+ };
+
+ return metrics;
+}
+
+// ─── Query explorer ──────────────────────────────────────────────────────────
+
+export interface MetricsExplorer {
+ goto(params?: Record<string, string>): Promise<void>;
+ metricSelector(index?: number): Locator;
+ metricInput(index?: number): Locator;
+ pickMetric(name: string, index?: number): Promise<void>;
+ /** Open the metric dropdown and return its options. */
+ openMetricOptions(index?: number): Promise<Locator>;
+ groupBy(attribute: string): Promise<void>;
+ /** Press Run and resolve the first `query_range` response it sends. */
+ run(): Promise<Response>;
+ /** Arm before acting: the next `query_range` response whose body names `metric`. */
+ nextQueryFor(metric: string): Promise<Response>;
+ charts(): Locator;
+ firstChartCanvas(): Locator;
+ emptyState(): Locator;
+ noData(): Locator;
+ legendLabels(): Promise<string[]>;
+ createAlertButton(): Locator;
+ addToDashboardButton(): Locator;
+ /** Add the current query to `title` through the export dialog. */
+ addToDashboard(title: string): Promise<void>;
+ createAlert(): Promise<void>;
+ /** The `compositeQuery` URL param, fully decoded. */
+ compositeQueryFromUrl(): string;
+ /** Dashboards and the panel editor, for the add-to-dashboard round trip. */
+ dashboards: Dashboards;
+ panelEditor: PanelEditor;
+ /** An empty dashboard for the export dialog to target. */
+ seedDashboard(title: string): Promise<DashboardSeed>;
+ removeDashboard(id: string): Promise<void>;
+}
+
+export function isQueryRange(request: Request): boolean {
+ return isPost(QUERY_RANGE_API)(request);
+}
+
+export function metricsExplorerDriver(
+ page: Page,
+ { path = EXPLORER_PATH }: { path?: string } = {},
+): MetricsExplorer {
+ const antd = antdDriver(page);
+ const selector = (index = 0): Locator =>
+ page.getByTestId(`metric-name-selector-${index}`);
+
+ const explorer: MetricsExplorer = {
+ goto: async (params = {}) => {
+ const query = new URLSearchParams({ relativeTime: '1h', ...params });
+ await page.goto(`${path}?${query.toString()}`);
+ await expect(selector()).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ },
+
+ metricSelector: selector,
+ metricInput: (index = 0) => selector(index).locator('input'),
+
+ openMetricOptions: async (index = 0) => {
+ await selector(index).click();
+ return (await antd.ownDropdown(selector(index))).locator(
+ '.ant-select-item-option',
+ );
+ },
+
+ pickMetric: async (name, index = 0) => {
+ await selector(index).click();
+ await explorer.metricInput(index).fill(name);
+ const option = (await antd.ownDropdown(selector(index)))
+ .locator('.ant-select-item-option')
+ .filter({ hasText: name })
+ .first();
+ await option.click({ timeout: SEEDED_DATA_TIMEOUT });
+ await expect(explorer.metricInput(index)).toHaveValue(name);
+ },
+
+ groupBy: (attribute) =>
+ antd.pickByName(page.getByTestId('group-by').first(), attribute),
+
+ run: async () => {
+ const response = page.waitForResponse((res) => isQueryRange(res.request()));
+ await page.getByTestId('explorer-run-query-btn').click();
+ return response;
+ },
+
+ nextQueryFor: (metric) =>
+ page.waitForResponse(
+ (res) =>
+ isQueryRange(res.request()) &&
+ (res.request().postData() ?? '').includes(metric),
+ ),
+
+ charts: () => page.getByTestId('time-series-graph'),
+ firstChartCanvas: () =>
+ page.getByTestId('time-series-graph').first().locator('canvas').first(),
+ emptyState: () =>
+ page.getByText('Select a metric and run a query to see the results', {
+ exact: true,
+ }),
+ noData: () => page.getByText('No data', { exact: true }),
+
+ // The explorer's chart is the v1 Uplot, whose legend is uPlot's own table.
+ legendLabels: () =>
+ page
+ .locator('.u-legend tr.u-series th')
+ .evaluateAll((items) => items.map((item) => item.textContent ?? '')),
+
+ createAlertButton: () => page.getByTestId('explorer-create-alert'),
+ addToDashboardButton: () => page.getByTestId('explorer-add-to-dashboard'),
+
+ addToDashboard: async (title) => {
+ await explorer.addToDashboardButton().click();
+ const dialog = page.getByTestId('export-panel-dialog');
+ await expect(dialog).toBeVisible();
+ const select = page.getByTestId('export-dashboard-select');
+ await select.click();
+ await select.locator('input[role="combobox"]').fill(title);
+ await (
+ await antd.ownDropdown(select)
+ )
+ .locator('.ant-select-item-option')
+ .filter({ hasText: title })
+ .first()
+ .click();
+ await page.getByTestId('export-panel-export').click();
+ await expect(page).toHaveURL(/\/dashboard\/[^/]+\/panel\//);
+ },
+
+ createAlert: async () => {
+ await explorer.createAlertButton().click();
+ await expect(page).toHaveURL(/\/alerts\/new\?compositeQuery=/);
+ },
+
+ compositeQueryFromUrl: () => {
+ const raw = new URL(page.url()).searchParams.get('compositeQuery') ?? '';
+ try {
+ return decodeURIComponent(raw);
+ } catch {
+ return raw;
+ }
+ },
+
+ dashboards: dashboardsDriver(page),
+ panelEditor: editorDriver(page),
+ seedDashboard: (title) => createDashboard(page, title),
+ removeDashboard: (id) => deleteViaApi(page, id),
+ };
+
+ return explorer;
+}
+
+// ─── Volume control ──────────────────────────────────────────────────────────
+
+export type RuleMode = 'all' | 'include' | 'exclude';
+
+export interface VolumeControl {
+ /** Whether `enable_metrics_reduction` is active on this stack. */
+ available(): Promise<boolean>;
+ seedRule(
+ metricName: string,
+ matchType: 'keep' | 'drop',
+ labels: string[],
+ ): Promise<string>;
+ /** Re-post the catalog gauge so its newest sample is inside the tab's 15m window. */
+ reseedGauge(seed: MetricsCatalogSeed): Promise<void>;
+ rulesFor(metricName: string): Promise<ReductionRule[]>;
+ removeRulesFor(metricName: string): Promise<void>;
+ gotoTab(): Promise<void>;
+ /** Type into the search box and wait for the debounced list response. */
+ search(text: string): Promise<void>;
+ tab(): Locator;
+ stats(): Locator;
+ chart(): Locator;
+ empty(): Locator;
+ row(metric: string): Locator;
+ mode(metric: string): Locator;
+ badge(metric: string, state: 'active' | 'pending'): Locator;
+ /** Open the config drawer for `metric` from the tab. */
+ manage(metric: string): Promise<void>;
+ drawer: {
+ root(): Locator;
+ mode(mode: RuleMode): Promise<void>;
+ pickLabels(labels: string[]): Promise<void>;
+ impact(): Locator;
+ /** Save and resolve the rule write (POST, or PUT for an existing rule). */
+ save(): Promise<Response>;
+ /** Remove and resolve the DELETE. */
+ remove(): Promise<Response>;
+ cancel(): Promise<void>;
+ };
+ section: {
+ root(): Locator;
+ setup(): Promise<void>;
+ edit(): Promise<void>;
+ pendingBanner(): Locator;
+ active(): Locator;
+ };
+ toast(text: string | RegExp): Locator;
+}
+
+const isRuleWrite = (response: Response): boolean => {
+ const { pathname } = new URL(response.url());
+ return (
+ pathname.startsWith(RULES_API) &&
+ !pathname.endsWith('/preview') &&
+ ['POST', 'PUT', 'DELETE'].includes(response.request().method())
+ );
+};
+
+export function volumeControlDriver(page: Page): VolumeControl {
+ const api = apiDriver(page);
+ const antd = antdDriver(page);
+ const tab = (): Locator => page.getByTestId('volume-control-tab');
+ const drawerRoot = (): Locator =>
+ page.getByTestId('volume-control-config-drawer');
+
+ const vc: VolumeControl = {
+ available: async () => {
+ const flags = await api.get<{ data: { name: string; active: boolean }[] }>(
+ '/api/v1/features',
+ );
+ return flags.data.some(
+ (flag) => flag.name === 'enable_metrics_reduction' && flag.active,
+ );
+ },
+
+ seedRule: (metricName, matchType, labels) =>
+ api.create(RULES_API, { metricName, matchType, labels }),
+
+ reseedGauge: async (seed) => {
+ await seedMetric(page.request, {
+ name: seed.gauge,
+ type: 'Gauge',
+ unit: 'By',
+ description: 'e2e gauge',
+ points: 5,
+ series: seed.services.map((service, i) => ({
+ labels: { host: `h${i + 1}` },
+ resource: { 'e2e.run': seed.run, 'service.name': service },
+ })),
+ });
+ },
+
+ rulesFor: async (metricName) =>
+ (
+ await api.get<{ data: { rules: ReductionRule[] | null } }>(
+ `${RULES_API}?metricName=${encodeURIComponent(metricName)}`,
+ )
+ ).data.rules ?? [],
+
+ removeRulesFor: async (metricName) => {
+ const rules = await vc.rulesFor(metricName);
+ await Promise.all(
+ rules.map((rule) => api.tryDel(`${RULES_API}/${rule.id}`)),
+ );
+ },
+
+ gotoTab: async () => {
+ // The tab has no time picker and ignores the URL range, and seeded
+ // series fall outside the default 15m window, so the drawer's attribute
+ // list would come back empty. Widen the range on the summary and arrive
+ // through the tab.
+ await page.goto(`${SUMMARY_PATH}?relativeTime=30m`);
+ await page.getByRole('tab', { name: 'Volume Control' }).click();
+ await expect(tab()).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ },
+
+ search: async (text) => {
+ const listed = page.waitForResponse((res) => {
+ const url = new URL(res.url());
+ return (
+ url.pathname === RULES_API &&
+ res.request().method() === 'GET' &&
+ url.searchParams.get('search') === text
+ );
+ });
+ await page.getByTestId('volume-control-search').fill(text);
+ expect((await listed).ok()).toBe(true);
+ },
+
+ tab,
+ stats: () => page.getByTestId('volume-control-stats'),
+ chart: () => page.getByTestId('volume-control-chart'),
+ empty: () => page.getByTestId('volume-control-tab-empty'),
+ row: (metric) => tab().locator(`tr[data-row-key="${metric}"]`),
+ // METRIC, STATUS, MODE: the table's column order.
+ mode: (metric) => vc.row(metric).locator('td').nth(2),
+ badge: (metric, state) => vc.row(metric).getByTestId(`vc-badge-${state}`),
+
+ manage: async (metric) => {
+ await page.getByTestId(`volume-control-manage-${metric}`).click();
+ await expect(drawerRoot()).toBeVisible();
+ },
+
+ drawer: {
+ root: drawerRoot,
+ mode: async (mode) => {
+ await page.getByTestId(`volume-control-mode-${mode}`).click();
+ },
+ pickLabels: async (labels) => {
+ const select = page.getByTestId('volume-control-label-select');
+ for (const label of labels) {
+ // Escape would close the drawer along with the dropdown, so close
+ // the dropdown by clicking the field's label instead.
+ // eslint-disable-next-line no-await-in-loop
+ await expect(select).not.toHaveClass(/ant-select-loading/);
+ const before = await antd.selectedTags(select).count();
+ await select.click();
+ await select.locator('input[role="combobox"]').fill(label);
+ const dropdown = await antd.ownDropdown(select);
+ const option = dropdown
+ .locator('.ant-select-item-option')
+ .filter({ hasText: label })
+ .first();
+ await expect(
+ option,
+ `attribute key "${label}" never listed: the metric has no sample in the tab's 15m window`,
+ ).toBeVisible({ timeout: 20_000 });
+ await option.click();
+ await drawerRoot().getByText('Attributes', { exact: true }).click();
+ await expect(select).not.toHaveClass(/ant-select-open/);
+ await expect(antd.selectedTags(select)).toHaveCount(before + 1);
+ }
+ },
+ impact: () => page.getByTestId('volume-control-impact'),
+ save: async () => {
+ const written = page.waitForResponse(isRuleWrite);
+ await page.getByTestId('volume-control-save').click();
+ return written;
+ },
+ remove: async () => {
+ const removed = page.waitForResponse(
+ (res) => isRuleWrite(res) && res.request().method() === 'DELETE',
+ );
+ await page.getByTestId('volume-control-remove').click();
+ return removed;
+ },
+ cancel: async () => {
+ await page.getByTestId('volume-control-cancel').click();
+ await expect(drawerRoot()).toHaveCount(0);
+ },
+ },
+
+ section: {
+ root: () => page.getByTestId('volume-control-section'),
+ setup: async () => {
+ await page.getByTestId('volume-control-setup').click();
+ await expect(drawerRoot()).toBeVisible();
+ },
+ edit: async () => {
+ await page.getByTestId('volume-control-edit').click();
+ await expect(drawerRoot()).toBeVisible();
+ },
+ pendingBanner: () => page.getByTestId('volume-control-pending-banner'),
+ active: () => page.getByTestId('volume-control-active'),
+ },
+
+ toast: (text) => toast(page, text),
+ };
+
+ return vc;
+}
+
+// ─── Layers ──────────────────────────────────────────────────────────────────
+
+export const withMetrics: Layer<{ metrics: Metrics }> = driver(
+ 'metrics',
+ ({ page }) => metricsDriver(page),
+);
+
+export const withMetricsExplorer: Layer<{ metricsExplorer: MetricsExplorer }> =
+ driver('metricsExplorer', ({ page }) => metricsExplorerDriver(page));
+
+export const withSavedViews: Layer<{ savedViews: SavedViews }> = driver(
+ 'savedViews',
+ ({ page }) => savedViewsDriver(page, 'metrics'),
+);
+
+export const withVolumeControl: Layer<{ volumeControl: VolumeControl }> =
+ driver('volumeControl', ({ page }) => volumeControlDriver(page));
diff --git a/tests/e2e/drivers/metrics/index.ts b/tests/e2e/drivers/metrics/index.ts
new file mode 100644
index 0000000000..95155827ec
--- /dev/null
+++ b/tests/e2e/drivers/metrics/index.ts
@@ -0,0 +1,30 @@
+import { kit } from '../kit';
+
+import {
+ withMetrics,
+ withMetricsExplorer,
+ withSavedViews,
+ withVolumeControl,
+} from './driver';
+import { withMetricsCatalog } from './seeds';
+
+/** The metrics-explorer `test`: summary, explorer, views and volume control. */
+export const test = withMetricsCatalog(
+ withMetrics(withMetricsExplorer(withSavedViews(withVolumeControl(kit)))),
+);
+
+export {
+ allowFor,
+ expect,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+} from '../kit';
+export { isQueryRange, metricsExplorerDriver, toast } from './driver';
+export type {
+ MetricMetadata,
+ MetricsExplorer,
+ ReductionRule,
+ StatsRequest,
+ TreemapRequest,
+} from './driver';
+export type { MetricsCatalogSeed } from './seeds';
diff --git a/tests/e2e/drivers/metrics/seeds.ts b/tests/e2e/drivers/metrics/seeds.ts
new file mode 100644
index 0000000000..8b0a52e560
--- /dev/null
+++ b/tests/e2e/drivers/metrics/seeds.ts
@@ -0,0 +1,133 @@
+import type { APIRequestContext } from '@playwright/test';
+
+import { seeded, type WorkerLayer } from '../kit';
+import { postToSeeder } from '../telemetry';
+
+/**
+ * Metrics seeded through `POST /telemetry/metrics`.
+ *
+ * The seeder has no scoped delete and `test_teardown` truncates, so nothing here
+ * is removed per spec. Every series carries the resource attribute `e2e.run`,
+ * and every read scopes by it.
+ */
+
+/** Shape of `Metrics.from_dict` in `tests/fixtures/metrics.py`. */
+export interface SeederMetric {
+ metric_name: string;
+ labels: Record<string, string>;
+ resource_attrs: Record<string, string>;
+ timestamp: string;
+ value: number;
+ type_: 'Gauge' | 'Sum' | 'Histogram';
+ temporality: 'Cumulative' | 'Delta' | 'Unspecified';
+ is_monotonic: boolean;
+ unit: string;
+ description: string;
+}
+
+export interface SeriesSpec {
+ labels?: Record<string, string>;
+ /**
+ * Also copied into `labels`: the query builder reads every filter key from
+ * the labels JSON, as the collector's exporter writes it.
+ */
+ resource?: Record<string, string>;
+}
+
+export interface MetricSpec {
+ name: string;
+ type: SeederMetric['type_'];
+ temporality?: SeederMetric['temporality'];
+ unit?: string;
+ description?: string;
+ series: SeriesSpec[];
+ /** Points per series, one per `stepSec`. Defaults to 30. */
+ points?: number;
+ stepSec?: number;
+}
+
+/**
+ * Newest point this far before now. The summary and explorer only report a
+ * series whose latest sample falls inside the window, and the seeder drops
+ * future-stamped samples.
+ */
+const LATEST_SAMPLE_LAG_MS = 30_000;
+
+export function metricRows(spec: MetricSpec): SeederMetric[] {
+ const points = spec.points ?? 30;
+ const stepMs = (spec.stepSec ?? 60) * 1000;
+ const newest = Date.now() - LATEST_SAMPLE_LAG_MS;
+ const monotonic = spec.type === 'Sum';
+ return spec.series.flatMap((series, seriesIndex) =>
+ Array.from({ length: points }, (_, i) => ({
+ metric_name: spec.name,
+ labels: { ...series.resource, ...series.labels },
+ resource_attrs: series.resource ?? {},
+ timestamp: new Date(newest - (points - 1 - i) * stepMs).toISOString(),
+ value: monotonic ? (i + 1) * 10 : 10 + seriesIndex * 5 + (i % 5),
+ type_: spec.type,
+ temporality:
+ spec.temporality ?? (spec.type === 'Gauge' ? 'Unspecified' : 'Cumulative'),
+ is_monotonic: monotonic,
+ unit: spec.unit ?? '',
+ description: spec.description ?? '',
+ })),
+ );
+}
+
+export function seedMetric(
+ request: APIRequestContext,
+ spec: MetricSpec,
+): Promise<void> {
+ return postToSeeder(request, '/telemetry/metrics', metricRows(spec));
+}
+
+/** Metric names allow `[a-zA-Z0-9_]` only, so the stamp uses underscores. */
+export function runStamp(workerIndex: number): string {
+ return `w${workerIndex}_${Date.now()}`;
+}
+
+export function scopeExpression(run: string): string {
+ return `e2e.run = '${run}'`;
+}
+
+export interface MetricsCatalogSeed {
+ run: string;
+ /** Gauge, unit `By`, description `e2e gauge`, three series. */
+ gauge: string;
+ /** Cumulative monotonic Sum, one series on its own service, no unit or description. */
+ sum: string;
+ /** `service.name` of the gauge's three series, in `host` order h1..h3. */
+ services: string[];
+ /** The filter expression that scopes a list to this worker's metrics. */
+ scope: string;
+}
+
+export const withMetricsCatalog: WorkerLayer<{
+ metricsCatalog: MetricsCatalogSeed;
+}> = seeded('metricsCatalog', async ({ page, workerIndex }) => {
+ const run = runStamp(workerIndex);
+ const gauge = `e2e_mx_gauge_${run}`;
+ const sum = `e2e_mx_sum_${run}`;
+ const services = ['a', 'b', 'c'].map((s) => `e2e-mx-${s}-${run}`);
+ const resource = { 'e2e.run': run };
+
+ await seedMetric(page.request, {
+ name: gauge,
+ type: 'Gauge',
+ unit: 'By',
+ description: 'e2e gauge',
+ series: services.map((service, i) => ({
+ labels: { host: `h${i + 1}` },
+ resource: { ...resource, 'service.name': service },
+ })),
+ });
+ await seedMetric(page.request, {
+ name: sum,
+ type: 'Sum',
+ temporality: 'Cumulative',
+ series: [{ resource: { ...resource, 'service.name': `e2e-mx-sum-${run}` } }],
+ });
+
+ return { run, gauge, sum, services, scope: scopeExpression(run) };
+});
diff --git a/tests/e2e/drivers/onboarding.ts b/tests/e2e/drivers/onboarding.ts
new file mode 100644
index 0000000000..59ca36544c
--- /dev/null
+++ b/tests/e2e/drivers/onboarding.ts
@@ -0,0 +1,421 @@
+import {
+ expect,
+ type Locator,
+ type Page,
+ type Request,
+ type Route,
+} from '@playwright/test';
+
+import { antdDriver } from './antd';
+import { apiDriver } from './api';
+import { ADMIN } from './auth';
+import { driver, kit, type Layer } from './kit';
+
+/**
+ * Org onboarding: the four-step questionnaire at `/onboarding` and the
+ * data-source wizard at `/get-started-with-signoz-cloud`.
+ *
+ * The redirect to `/onboarding` needs `org_onboarding` unset and exactly one
+ * user in the org. Bootstrap sets the preference org-wide and other specs add
+ * users, so both are faked per context with `page.route` and the real org is
+ * never written. Invites in the questionnaire are the exception: they go to the
+ * real API and the spec removes them.
+ */
+
+export const ONBOARDING_PATH = '/onboarding';
+export const GET_STARTED_PATH = '/get-started-with-signoz-cloud';
+
+const ORG_ONBOARDING = 'org_onboarding';
+
+export type ObservabilityTool =
+ | 'AWS Cloudwatch'
+ | 'DataDog'
+ | 'New Relic'
+ | 'Grafana / Prometheus'
+ | 'None/Starting fresh';
+
+export type MigrationTimeline =
+ | 'Less than a month'
+ | '1-3 months'
+ | 'Greater than 3 months'
+ | 'Just exploring';
+
+export interface OrgAnswers {
+ tool: ObservabilityTool;
+ timeline?: MigrationTimeline;
+ usesOtel: boolean;
+}
+
+export interface SignozAnswers {
+ discovery: string;
+ interests: string[];
+}
+
+export interface FirstRunOptions {
+ /** `several` returns the admin plus a second member, which suppresses the redirect. */
+ users?: 'single' | 'several';
+ /** How `PUT /api/v2/zeus/profiles` answers. */
+ profiles?: 'ok' | 'error';
+ /**
+ * Hold the profiles response until {@link FirstRun.releaseProfiles}, to see
+ * the step-3 buttons while the request is in flight.
+ */
+ holdProfiles?: boolean;
+}
+
+export interface FirstRun {
+ /** Bodies the app sent to `PUT /api/v2/zeus/profiles`. */
+ profileBodies: unknown[];
+ /** Bodies the app sent to `PUT /api/v1/org/preferences/org_onboarding`. */
+ onboardingWrites: unknown[];
+ releaseProfiles(): void;
+}
+
+export interface InvitedUser {
+ id: string;
+ email: string;
+ status?: string;
+}
+
+export interface Onboarding {
+ /**
+ * Make this context look like a fresh cloud org: `org_onboarding` reads
+ * false until the app writes it, and the users list holds only the admin.
+ */
+ stubFirstRun(options?: FirstRunOptions): Promise<FirstRun>;
+ /** Navigate to `path` and wait for the app to settle on a route. */
+ visit(path: string): Promise<void>;
+ expectPath(path: string): Promise<void>;
+ pathname(): string;
+ /**
+ * Wait for the network to go quiet. The redirect decision waits on the users
+ * and preferences queries, so a page can paint before it is redirected.
+ */
+ settle(): Promise<void>;
+
+ questionnaire: {
+ root(): Locator;
+ heading(name: string): Locator;
+ next(): Locator;
+ doLater(): Locator;
+ /** Assert `button` is disabled and its hover tooltip reads `reason`. */
+ expectDisabledBecause(button: Locator, reason: string): Promise<void>;
+ pickTool(tool: ObservabilityTool): Promise<void>;
+ pickTimeline(timeline: MigrationTimeline): Promise<void>;
+ pickOtel(uses: boolean): Promise<void>;
+ answerOrg(answers: OrgAnswers): Promise<void>;
+ discovery(): Locator;
+ interest(label: string): Locator;
+ answerSignoz(answers: SignozAnswers): Promise<void>;
+ /** Drag the Logs / Day slider to its maximum. */
+ maxLogsSlider(): Promise<void>;
+ invite(rows: { email: string; role: string }[]): Promise<void>;
+ sendInvites(): Locator;
+ };
+
+ wizard: {
+ root(): Locator;
+ search(text: string): Promise<void>;
+ source(label: string): Locator;
+ option(label: string): Locator;
+ configure(): Locator;
+ docsFrame(): Locator;
+ back(): Locator;
+ continue(): Locator;
+ inviteButton(): Locator;
+ inviteModal(): Locator;
+ invite(rows: { email: string; role: string }[]): Promise<void>;
+ noResults(): Locator;
+ };
+
+ homePage(): Locator;
+ servicesPage(): Locator;
+ toast(text: string | RegExp): Locator;
+
+ users: {
+ byEmail(email: string): Promise<InvitedUser | undefined>;
+ remove(email: string): Promise<void>;
+ };
+}
+
+interface OrgPreferenceRow {
+ name: string;
+ value: unknown;
+}
+
+interface UserRow {
+ id: string;
+ email: string;
+ status?: string;
+}
+
+const exactText = (text: string): RegExp =>
+ new RegExp(`^${text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}$`);
+
+const pathIs =
+ (path: string) =>
+ (url: URL): boolean =>
+ url.pathname === path;
+
+async function fulfillWith<T>(
+ route: Route,
+ edit: (body: { data: T }) => void,
+): Promise<void> {
+ const response = await route.fetch();
+ const body = (await response.json()) as { data: T };
+ edit(body);
+ await route.fulfill({ response, json: body });
+}
+
+async function stubFirstRun(
+ page: Page,
+ { users = 'single', profiles = 'ok', holdProfiles = false }: FirstRunOptions,
+): Promise<FirstRun> {
+ let completed = false;
+ let release: () => void = () => undefined;
+ const released = holdProfiles
+ ? new Promise<void>((resolve) => {
+ release = resolve;
+ })
+ : Promise.resolve();
+ const run: FirstRun = {
+ profileBodies: [],
+ onboardingWrites: [],
+ releaseProfiles: () => release(),
+ };
+ const isGet = (request: Request): boolean => request.method() === 'GET';
+
+ await page.route(pathIs('/api/v1/org/preferences'), async (route) => {
+ if (!isGet(route.request())) {
+ await route.fallback();
+ return;
+ }
+ await fulfillWith<OrgPreferenceRow[]>(route, (body) => {
+ const rows = body.data ?? [];
+ const row = rows.find((entry) => entry.name === ORG_ONBOARDING);
+ if (row) {
+ row.value = completed;
+ } else {
+ rows.push({ name: ORG_ONBOARDING, value: completed });
+ }
+ body.data = rows;
+ });
+ });
+
+ await page.route(
+ pathIs(`/api/v1/org/preferences/${ORG_ONBOARDING}`),
+ async (route) => {
+ if (route.request().method() !== 'PUT') {
+ await route.fallback();
+ return;
+ }
+ run.onboardingWrites.push(route.request().postDataJSON());
+ completed = true;
+ await route.fulfill({ json: { status: 'success', data: null } });
+ },
+ );
+
+ await page.route(pathIs('/api/v2/users'), async (route) => {
+ if (!isGet(route.request())) {
+ await route.fallback();
+ return;
+ }
+ await fulfillWith<UserRow[]>(route, (body) => {
+ const admin = (body.data ?? []).filter((row) => row.email === ADMIN.email);
+ body.data =
+ users === 'single'
+ ? admin
+ : [
+ ...admin,
+ ...admin.map((row) => ({
+ ...row,
+ id: `${row.id}-colleague`,
+ email: '[email protected]',
+ })),
+ ];
+ });
+ });
+
+ await page.route(pathIs('/api/v2/zeus/profiles'), async (route) => {
+ run.profileBodies.push(route.request().postDataJSON());
+ await released;
+ if (profiles === 'ok') {
+ await route.fulfill({ status: 204 });
+ } else {
+ await route.fulfill({ status: 500, json: { status: 'error' } });
+ }
+ });
+
+ return run;
+}
+
+export function onboardingDriver(page: Page): Onboarding {
+ const antd = antdDriver(page);
+ const api = apiDriver(page);
+ const questionnaireRoot = (): Locator =>
+ page.locator('.onboarding-questionaire-container');
+ const wizardRoot = (): Locator => page.locator('.onboarding-v2');
+
+ const fillInviteRows = async (
+ scope: Locator,
+ rows: { email: string; role: string }[],
+ ): Promise<void> => {
+ for (const [index, { email, role }] of rows.entries()) {
+ const emails = scope.locator('[data-testid^="invite-email-"]');
+ if (index >= (await emails.count())) {
+ await scope.getByTestId('invite-add-row').click();
+ }
+ await emails.nth(index).fill(email);
+ const select = scope
+ .locator('.ant-select')
+ .filter({ has: page.locator('input[id^="invite-role-"]') })
+ .nth(index);
+ await antd.pickByName(select, role);
+ }
+ };
+
+ const onboarding: Onboarding = {
+ stubFirstRun: (options = {}) => stubFirstRun(page, options),
+
+ visit: async (path) => {
+ // The wizard frames the public docs site; keep the run off the network.
+ await page.route('https://signoz.io/**', (route) =>
+ route.fulfill({ contentType: 'text/html', body: '<html></html>' }),
+ );
+ await page.goto(path);
+ },
+
+ expectPath: async (path) => {
+ await expect(page).toHaveURL((url) => url.pathname === path);
+ },
+
+ pathname: () => new URL(page.url()).pathname,
+
+ settle: async () => {
+ await page.waitForLoadState('networkidle');
+ },
+
+ questionnaire: {
+ root: questionnaireRoot,
+ heading: (name) =>
+ questionnaireRoot().getByRole('heading', { name, exact: true }),
+ next: () =>
+ questionnaireRoot().getByRole('button', { name: 'Next', exact: true }),
+ doLater: () =>
+ questionnaireRoot().getByRole('button', { name: "I'll do this later" }),
+
+ expectDisabledBecause: async (button, reason) => {
+ await expect(button).toHaveAttribute('aria-disabled', 'true');
+ await button.hover();
+ await expect(page.getByRole('tooltip')).toHaveText(reason);
+ await page.mouse.move(0, 0);
+ await expect(page.getByRole('tooltip')).toHaveCount(0);
+ },
+
+ pickTool: async (tool) => {
+ await questionnaireRoot()
+ .getByRole('radio', { name: tool, exact: true })
+ .click();
+ },
+ pickTimeline: async (timeline) => {
+ await questionnaireRoot()
+ .getByRole('radio', { name: timeline, exact: true })
+ .click();
+ },
+ pickOtel: async (uses) => {
+ await questionnaireRoot()
+ .getByRole('radio', { name: uses ? 'Yes' : 'No', exact: true })
+ .click();
+ },
+
+ answerOrg: async ({ tool, timeline, usesOtel }) => {
+ await onboarding.questionnaire.pickTool(tool);
+ if (timeline) {
+ await onboarding.questionnaire.pickTimeline(timeline);
+ }
+ await onboarding.questionnaire.pickOtel(usesOtel);
+ },
+
+ discovery: () =>
+ questionnaireRoot().getByPlaceholder(/^e\.g\., I asked ChatGPT/),
+ interest: (label) =>
+ questionnaireRoot().getByRole('checkbox', { name: label, exact: true }),
+
+ answerSignoz: async ({ discovery, interests }) => {
+ await onboarding.questionnaire.discovery().fill(discovery);
+ for (const label of interests) {
+ await onboarding.questionnaire.interest(label).click();
+ }
+ },
+
+ maxLogsSlider: async () => {
+ const slider = questionnaireRoot().getByRole('slider').first();
+ await slider.focus();
+ await slider.press('End');
+ await expect(slider).toHaveAttribute('aria-valuenow', '100');
+ },
+
+ invite: (rows) => fillInviteRows(questionnaireRoot(), rows),
+ sendInvites: () => page.getByTestId('send-invites-button'),
+ },
+
+ wizard: {
+ root: wizardRoot,
+ search: async (text) => {
+ await wizardRoot().getByPlaceholder('Search', { exact: true }).fill(text);
+ },
+ // The logo's alt repeats the label, so the accessible name is doubled.
+ source: (label) =>
+ wizardRoot()
+ .locator('.onboarding-data-source-list .onboarding-data-source-button')
+ .filter({ hasText: exactText(label) }),
+ option: (label) =>
+ wizardRoot()
+ .locator('.onboarding-data-source-options .onboarding-data-source-button')
+ .filter({ hasText: exactText(label) }),
+ configure: () =>
+ wizardRoot().getByRole('button', { name: 'Next: Configure your product' }),
+ docsFrame: () => wizardRoot().locator('iframe[title="docs"]'),
+ back: () => wizardRoot().getByRole('button', { name: 'Back', exact: true }),
+ continue: () =>
+ wizardRoot().getByRole('button', { name: 'Continue', exact: true }),
+ inviteButton: () =>
+ wizardRoot().getByRole('button', { name: 'Invite a teammate' }),
+ inviteModal: () => page.locator('.invite-team-member-modal'),
+ invite: async (rows) => {
+ const modal = onboarding.wizard.inviteModal();
+ await fillInviteRows(modal, rows);
+ await modal.getByRole('button', { name: 'Send Invites' }).click();
+ },
+ noResults: () => wizardRoot().locator('.no-results-found-container'),
+ },
+
+ homePage: () => page.locator('.home-container'),
+ servicesPage: () => page.getByRole('columnheader', { name: 'Application' }),
+ toast: (text) =>
+ page.locator('[data-sonner-toast]').filter({ hasText: text }),
+
+ users: {
+ byEmail: async (email) => {
+ const body = await api.get<{ data: UserRow[] | null }>('/api/v2/users');
+ return (body.data ?? []).find((row) => row.email === email);
+ },
+ remove: async (email) => {
+ const match = await onboarding.users.byEmail(email);
+ if (match) {
+ await api.tryDel(`/api/v2/users/${match.id}`);
+ }
+ },
+ },
+ };
+
+ return onboarding;
+}
+
+export const withOnboarding: Layer<{ onboarding: Onboarding }> = driver(
+ 'onboarding',
+ ({ page }) => onboardingDriver(page),
+);
+
+export const test = withOnboarding(kit);
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/panel-config.ts b/tests/e2e/drivers/panel-config.ts
index 66c3689e4c..44ffb15f32 100644
--- a/tests/e2e/drivers/panel-config.ts
+++ b/tests/e2e/drivers/panel-config.ts
@@ -4,10 +4,7 @@
*/
import { type Locator, type Page } from '@playwright/test';
-import type {
- ContextLink,
- PanelPluginSpec,
-} from '../helpers/dashboard-spec.types';
+import type { ContextLink, PanelPluginSpec } from './dashboard-spec.types';
import { SINGLE_PANEL_ID } from '../testdata/dashboards/panels';
import { getViaApi } from './dashboards';
diff --git a/tests/e2e/drivers/panel-editor.ts b/tests/e2e/drivers/panel-editor.ts
index 858f419c79..db0227a1fd 100644
--- a/tests/e2e/drivers/panel-editor.ts
+++ b/tests/e2e/drivers/panel-editor.ts
@@ -4,7 +4,7 @@
*/
import { expect, type Locator, type Page } from '@playwright/test';
-import { PanelKind } from '../helpers/dashboard-spec';
+import { PanelKind } from './dashboard-spec';
import { EDITOR_ROOT } from './dashboards';
import { driver } from './kit';
@@ -56,7 +56,9 @@ export type EditorControl =
| 'soft-min'
| 'soft-max'
| 'decimals'
- | 'legend-position';
+ | 'legend-position'
+ | 'stack-mode'
+ | 'stacked-bar-chart';
export interface PatchOperation {
op: string;
@@ -124,7 +126,7 @@ function isDashboardPatch(method: string, url: string): boolean {
return method === 'PATCH' && /\/api\/v2\/dashboards\//.test(url);
}
-function editorDriver(page: Page): PanelEditor {
+export function editorDriver(page: Page): PanelEditor {
const byTestId = (suffix: string): Locator =>
page.getByTestId(`panel-editor-v2-${suffix}`);
const preview = (): Locator => page.getByTestId('preview-pane');
diff --git a/tests/e2e/drivers/panel-editor/picker.ts b/tests/e2e/drivers/panel-editor/picker.ts
index c359c23ee4..a5f39e56e9 100644
--- a/tests/e2e/drivers/panel-editor/picker.ts
+++ b/tests/e2e/drivers/panel-editor/picker.ts
@@ -4,7 +4,7 @@
*/
import { expect, type Locator, type Page } from '@playwright/test';
-import { PanelKind } from '../../helpers/dashboard-spec';
+import { PanelKind } from '../dashboard-spec';
import { PATH } from '../dashboards';
const NEW_PANEL_DRAWER = 'panel-type-drawer';
diff --git a/tests/e2e/drivers/panel-editor/select.ts b/tests/e2e/drivers/panel-editor/select.ts
index d816262822..0c023edf3c 100644
--- a/tests/e2e/drivers/panel-editor/select.ts
+++ b/tests/e2e/drivers/panel-editor/select.ts
@@ -4,7 +4,7 @@
*/
import { expect, type Page } from '@playwright/test';
-import { ownDropdown } from '../../helpers/alert-forms/shared';
+import { antdDriver } from '../antd';
export interface EditorSelects {
/** Picks the panel's own time window, by its exact label. */
@@ -18,7 +18,7 @@ async function select(
): Promise<void> {
const trigger = page.getByTestId(triggerTestId);
await trigger.click();
- const dropdown = await ownDropdown(page, trigger);
+ const dropdown = await antdDriver(page).ownDropdown(trigger);
await expect(dropdown).toBeVisible();
await dropdown
.locator('.ant-select-item-option')
diff --git a/tests/e2e/drivers/panel-editor/type-switcher.ts b/tests/e2e/drivers/panel-editor/type-switcher.ts
index 4c696b4275..b520ba3435 100644
--- a/tests/e2e/drivers/panel-editor/type-switcher.ts
+++ b/tests/e2e/drivers/panel-editor/type-switcher.ts
@@ -4,7 +4,7 @@
*/
import { expect, type Locator, type Page } from '@playwright/test';
-import { PanelKind } from '../../helpers/dashboard-spec';
+import { PanelKind } from '../dashboard-spec';
const TYPE_SWITCHER_DRAWER = 'panel-type-switcher-drawer';
diff --git a/tests/e2e/drivers/panels.ts b/tests/e2e/drivers/panels.ts
index d4215ecf6c..845b4607b8 100644
--- a/tests/e2e/drivers/panels.ts
+++ b/tests/e2e/drivers/panels.ts
@@ -4,8 +4,8 @@
*/
import { expect, type Locator, type Page } from '@playwright/test';
-import { PanelKind } from '../helpers/dashboard-spec';
-import { logDetailsDrawer } from '../helpers/logs-explorer';
+import { PanelKind } from './dashboard-spec';
+import { logDetailDriver } from './logs/detail';
import { test as dashboardsTest } from './dashboards';
import { driver } from './kit';
@@ -85,6 +85,8 @@ export interface Panels {
statusContent(): Locator;
/** Free text inside any open tooltip. */
text(text: string): Locator;
+ /** Hovers `target` and returns the newest tooltip, since an earlier one may still be fading out. */
+ reasonFor(target: Locator): Promise<Locator>;
heatmap: HeatmapTooltip;
};
/** The log detail drawer a List row of logs opens. */
@@ -173,9 +175,13 @@ function panelsDriver(page: Page): Panels {
statusContent: () =>
page.getByRole('tooltip').getByTestId('panel-status-content'),
text: (text) => page.getByText(text),
+ async reasonFor(target) {
+ await target.hover();
+ return page.getByRole('tooltip').last();
+ },
heatmap: heatmapTooltipAt(page),
},
- logDetail: () => logDetailsDrawer(page),
+ logDetail: () => logDetailDriver(page).drawer(),
drilldown: {
menu,
item: (testId) =>
diff --git a/tests/e2e/drivers/public-dashboard.ts b/tests/e2e/drivers/public-dashboard.ts
new file mode 100644
index 0000000000..eb0bfcb7a9
--- /dev/null
+++ b/tests/e2e/drivers/public-dashboard.ts
@@ -0,0 +1,160 @@
+import {
+ expect,
+ type Locator,
+ type Page,
+ type Response,
+} from '@playwright/test';
+
+import type { DashboardtypesGettablePublicDasbhboardDTO } from './schemas';
+import { apiDriver } from './api';
+import {
+ createDashboard,
+ deleteViaApi,
+ PATH,
+ type DashboardSeed,
+} from './dashboards';
+import { driver, guestDriver, kit, type Layer } from './kit';
+
+/**
+ * Public dashboards: publishing from the dashboard's settings drawer, and the
+ * logged-out page the public link opens.
+ *
+ * The API contract (anonymous role, filter redaction, authz) is covered by
+ * `tests/integration/tests/dashboard/02_public_dashboard.py` and
+ * `05_v2_public_dashboard.py`. What is left for a browser is a link published
+ * in the UI rendering for a visitor with no session.
+ */
+
+export interface PublicDashboards {
+ create(title: string): Promise<DashboardSeed>;
+ remove(id: string): Promise<void>;
+ /** Publish through the API. Resolves with the `/public/dashboard/<id>` path. */
+ publish(
+ id: string,
+ options?: { timeRangeEnabled?: boolean; defaultTimeRange?: string },
+ ): Promise<string>;
+ unpublish(id: string): Promise<void>;
+ /** Resolves with the public path, or undefined while the dashboard is private. */
+ publicPath(id: string): Promise<string | undefined>;
+
+ /** Open the dashboard and its settings drawer on the Publish tab. */
+ openPublishTab(id: string): Promise<void>;
+ publishButton(): Locator;
+ unpublishButton(): Locator;
+ /** Click Publish and wait for the POST to land. */
+ publishInUi(): Promise<void>;
+ unpublishInUi(): Promise<void>;
+ liveStatus(): Locator;
+ privateStatus(): Locator;
+ publicUrl(): Locator;
+}
+
+export function publicDashboardsDriver(page: Page): PublicDashboards {
+ const api = apiDriver(page);
+ const publicEndpoint = (id: string): string =>
+ `/api/v1/dashboards/${id}/public`;
+
+ const isPublicCall =
+ (method: string) =>
+ (response: Response): boolean =>
+ response.request().method() === method &&
+ /^\/api\/v1\/dashboards\/[^/]+\/public$/.test(
+ new URL(response.url()).pathname,
+ );
+
+ const publicDashboards: PublicDashboards = {
+ create: (title) => createDashboard(page, title),
+ remove: (id) => deleteViaApi(page, id),
+
+ publish: async (id, options = {}) => {
+ await api.post(publicEndpoint(id), {
+ timeRangeEnabled: options.timeRangeEnabled ?? true,
+ defaultTimeRange: options.defaultTimeRange ?? '1h',
+ });
+ const path = await publicDashboards.publicPath(id);
+ if (!path) {
+ throw new Error(`dashboard ${id} has no publicPath after publishing`);
+ }
+ return path;
+ },
+
+ unpublish: (id) => api.tryDel(publicEndpoint(id)),
+
+ publicPath: async (id) => {
+ const res = await page.request.get(publicEndpoint(id), {
+ headers: { Authorization: `Bearer ${await api.token()}` },
+ });
+ if (!res.ok()) {
+ return undefined;
+ }
+ return (
+ (await res.json()) as { data?: DashboardtypesGettablePublicDasbhboardDTO }
+ ).data?.publicPath;
+ },
+
+ openPublishTab: async (id) => {
+ await page.goto(PATH.dashboard(id));
+ await expect(page.getByTestId('dashboard-title')).toBeVisible();
+ await page.getByTestId('show-drawer').click();
+ await page.getByRole('tab', { name: 'Publish' }).click();
+ await expect(
+ publicDashboards.publishButton().or(publicDashboards.unpublishButton()),
+ ).toBeVisible();
+ },
+
+ publishButton: () => page.getByTestId('public-dashboard-publish'),
+ unpublishButton: () => page.getByTestId('public-dashboard-unpublish'),
+
+ publishInUi: async () => {
+ const saved = page.waitForResponse(isPublicCall('POST'));
+ await publicDashboards.publishButton().click();
+ expect((await saved).ok()).toBe(true);
+ },
+
+ unpublishInUi: async () => {
+ const removed = page.waitForResponse(isPublicCall('DELETE'));
+ await publicDashboards.unpublishButton().click();
+ expect((await removed).ok()).toBe(true);
+ },
+
+ liveStatus: () => page.getByText('This dashboard is live'),
+ privateStatus: () => page.getByText('This dashboard is private'),
+ publicUrl: () => page.getByText(/\/public\/dashboard\//),
+ };
+
+ return publicDashboards;
+}
+
+/** The page a public link opens, seen by a visitor with no session. */
+export interface PublicView {
+ goto(publicPath: string): Promise<void>;
+ title(text: string): Locator;
+ unavailable(): Locator;
+ sidenav(): Locator;
+ settingsNavItem(): Locator;
+}
+
+export function publicViewDriver(page: Page): PublicView {
+ return {
+ goto: async (publicPath) => {
+ await page.goto(publicPath);
+ },
+ title: (text) => page.getByText(text, { exact: true }),
+ unavailable: () => page.getByTestId('public-dashboard-unavailable'),
+ sidenav: () => page.getByTestId('sidenav'),
+ settingsNavItem: () => page.getByTestId('settings-nav-item'),
+ };
+}
+
+export const withPublicDashboards: Layer<{
+ publicDashboards: PublicDashboards;
+}> = driver('publicDashboards', ({ page }) => publicDashboardsDriver(page));
+
+export const withPublicView: Layer<{ publicView: PublicView }> = guestDriver(
+ 'publicView',
+ ({ page }) => publicViewDriver(page),
+);
+
+/** The public-dashboard `test`. */
+export const test = withPublicView(withPublicDashboards(kit));
+export { expect } from './kit';
diff --git a/tests/e2e/helpers/query-range-mock.ts b/tests/e2e/drivers/query-range-mock.ts
similarity index 100%
rename from tests/e2e/helpers/query-range-mock.ts
rename to tests/e2e/drivers/query-range-mock.ts
diff --git a/tests/e2e/drivers/querysearch.ts b/tests/e2e/drivers/querysearch.ts
new file mode 100644
index 0000000000..4794a1e3c5
--- /dev/null
+++ b/tests/e2e/drivers/querysearch.ts
@@ -0,0 +1,176 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { SEEDED_DATA_TIMEOUT } from './kit';
+
+/**
+ * The query-search box: the CodeMirror expression editor, its Run button, and
+ * the URL param the expression is encoded into.
+ *
+ * `compositeQuery` is on the way out — the query-URL serializer work replaces it
+ * with flat leaf params. Every read and write of an expression in the suite goes
+ * through this module, so that migration lands in one file rather than in forty
+ * specs. Spread {@link expressionParams} at call sites rather than spelling the
+ * key out.
+ */
+
+const EXPRESSION_PARAM = 'compositeQuery';
+const EDITOR = '.query-where-clause-editor .cm-content';
+
+interface CompositeQuery {
+ builder?: { queryData?: { filter?: { expression?: string } }[] };
+}
+
+/**
+ * Three outcomes, kept distinct. Collapsing `malformed` into `''` would make
+ * "the filter was cleared" pass against a URL carrying garbage.
+ */
+export type ExpressionState =
+ | { kind: 'absent'; expression: '' }
+ | { kind: 'ok'; expression: string }
+ | { kind: 'malformed'; expression: ''; raw: string };
+
+/**
+ * `dataSource` is required on an explorer: a query without one is filled from
+ * the metrics defaults, and the logs or traces list never runs.
+ */
+export function expressionParam(
+ expression: string,
+ dataSource?: 'logs' | 'traces',
+): string {
+ return encodeURIComponent(
+ JSON.stringify({
+ queryType: 'builder',
+ builder: {
+ queryData: [
+ {
+ ...(dataSource ? { dataSource } : {}),
+ filter: { expression },
+ filters: { items: [], op: 'AND' },
+ },
+ ],
+ },
+ }),
+ );
+}
+
+export function expressionParams(
+ expression: string,
+ dataSource?: 'logs' | 'traces',
+): Record<string, string> {
+ return { [EXPRESSION_PARAM]: expressionParam(expression, dataSource) };
+}
+
+export interface QuerySearch {
+ editor(): Locator;
+ runButton(): Locator;
+ cancelButton(): Locator;
+ /** Type an expression into the box and press Run, then wait for the URL. */
+ apply(expression: string): Promise<void>;
+ /** Press Run without touching the box — the staged-expression path. */
+ run(): Promise<void>;
+ /** The expression encoded in the URL, or `''` when unset. Throws if corrupt. */
+ read(): string;
+ readState(): ExpressionState;
+ expectExpression(expression: string): Promise<void>;
+ expectContains(fragment: string): Promise<void>;
+}
+
+/**
+ * `runTestId` names the Run button. `.run-query-btn` is shared with every
+ * drawer tab that has its own query, so the bare class resolves to several
+ * elements and each click fails on strict mode.
+ */
+export function querySearchDriver(
+ page: Page,
+ { runTestId }: { runTestId: string },
+): QuerySearch {
+ const readState = (): ExpressionState => {
+ const raw = new URL(page.url()).searchParams.get(EXPRESSION_PARAM);
+ if (!raw) {
+ return { kind: 'absent', expression: '' };
+ }
+ // The app writes `encodeURIComponent(JSON.stringify(query))` into a
+ // URLSearchParams value, so one decode remains after `searchParams.get`.
+ let json = raw;
+ try {
+ json = decodeURIComponent(raw);
+ } catch {
+ // A hand-written deep link arrives already decoded.
+ }
+ try {
+ const parsed = JSON.parse(json) as CompositeQuery;
+ return {
+ kind: 'ok',
+ expression: parsed.builder?.queryData?.[0]?.filter?.expression ?? '',
+ };
+ } catch {
+ return { kind: 'malformed', expression: '', raw };
+ }
+ };
+
+ const read = (): string => {
+ const state = readState();
+ if (state.kind === 'malformed') {
+ throw new Error(
+ `${EXPRESSION_PARAM} is not decodable JSON — got \`${state.raw.slice(0, 200)}\``,
+ );
+ }
+ return state.expression;
+ };
+
+ const search: QuerySearch = {
+ editor: () => page.locator(EDITOR).first(),
+ runButton: () => page.getByTestId(runTestId),
+ cancelButton: () => page.getByTestId(`${runTestId}-cancel`),
+ readState,
+ read,
+
+ run: async () => {
+ await search.runButton().click();
+ },
+
+ apply: async (expression) => {
+ const editor = search.editor();
+ // The editor mounts with the list's first response, not with the shell.
+ await expect(editor).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ // The caret can jump once after mount and rotate typed text, so retype
+ // until the editor holds exactly the expression.
+ await expect(async () => {
+ await editor.click();
+ await page.keyboard.press('ControlOrMeta+a');
+ await page.keyboard.press('Delete');
+ if (expression) {
+ await page.keyboard.insertText(expression);
+ }
+ // An empty editor renders its placeholder as text.
+ if (expression) {
+ await expect(editor).toHaveText(expression, { timeout: 1_000 });
+ } else {
+ await expect(editor.locator('.cm-placeholder')).toHaveCount(1, {
+ timeout: 1_000,
+ });
+ }
+ }).toPass({ timeout: 15_000 });
+ // Typing opens the suggestion popover, which covers the Run button.
+ await page.keyboard.press('Escape');
+ await search.run();
+ await expect(async () => {
+ expect(read()).toBe(expression);
+ }).toPass({ timeout: 15_000 });
+ },
+
+ expectExpression: async (expression) => {
+ await expect(async () => {
+ expect(read()).toBe(expression);
+ }).toPass();
+ },
+
+ expectContains: async (fragment) => {
+ await expect(async () => {
+ expect(read()).toContain(fragment);
+ }).toPass();
+ },
+ };
+
+ return search;
+}
diff --git a/tests/e2e/drivers/routing.ts b/tests/e2e/drivers/routing.ts
index a9a91cad69..60c5c889bb 100644
--- a/tests/e2e/drivers/routing.ts
+++ b/tests/e2e/drivers/routing.ts
@@ -6,20 +6,18 @@ import { randomBytes } from 'crypto';
import { expect, type Locator, type Page } from '@playwright/test';
-import { ADMIN } from '../helpers/auth';
-import { authToken } from '../helpers/common';
-import { buildDashboard } from '../helpers/dashboard-spec';
-import { seedPodMetricsViaSeeder } from '../helpers/infra-monitoring';
-import { gotoLogsExplorer } from '../helpers/logs-explorer';
+import { authToken } from './api';
+import { ADMIN } from './auth';
+import { buildDashboard, createViaApi, deleteViaApi } from './dashboards';
+import { seedPodMetricsViaSeeder } from './infra/pods';
+import { driver, kit, seeded } from './kit';
+import { logsExplorerDriver } from './logs/explorer';
import {
gotoTraceUntilLoaded,
type LargeTrace,
loadLargeTrace,
seedTracesViaSeeder,
-} from '../helpers/trace-details';
-
-import { createViaApi, deleteViaApi } from './dashboards';
-import { driver, kit, seeded } from './kit';
+} from './traces';
// The react-router v5 -> v7 regression net. Router-sensitive mechanics (history
// depth, POP, same-url suppression, the `newTab` branch) live here so the specs
@@ -101,7 +99,22 @@ export interface Routing {
): Promise<void>;
/** Hold every script requested during `body`, so lazy route chunks suspend. */
whileScriptsHeld(body: () => Promise<void>): Promise<void>;
+ /** The `Spinner` a route's Suspense fallback renders. */
+ suspenseFallback(): Locator;
+ /** Every console message and page error from now on; fills as the page runs. */
+ recordMessages(): string[];
+ /** `NotFound`, the catch-all route's screen. */
+ notFound(): Locator;
gotoLogsExplorer(): Promise<void>;
+ alerts: {
+ /** The rules table, or its empty state when nothing is seeded. */
+ landmark(): Locator;
+ };
+ settings: {
+ sidenav(): Locator;
+ /** An entry's testid is its `itemKey`. */
+ navItem(itemKey: string): Locator;
+ };
dashboards: {
gotoList(title?: string): Promise<void>;
/** Not `dashboard-title-0`: the search tokenises on hyphens and matches leftovers. */
@@ -130,6 +143,7 @@ export interface Routing {
cancel(): Promise<void>;
save(): Promise<void>;
discardDialog(): Locator;
+ discardDialogButton(name: 'Keep editing' | 'Discard'): Locator;
settings(): Locator;
removeByName(names: string[]): Promise<void>;
};
@@ -234,7 +248,30 @@ export function routingDriver(page: Page): Routing {
}
},
- gotoLogsExplorer: () => gotoLogsExplorer(page),
+ suspenseFallback: () => page.getByRole('img', { name: 'loading' }).first(),
+
+ recordMessages: () => {
+ const messages: string[] = [];
+ page.on('pageerror', (error) => messages.push(error.message));
+ page.on('console', (message) => messages.push(message.text()));
+ return messages;
+ },
+
+ notFound: () => page.getByTestId('not-found'),
+
+ gotoLogsExplorer: () => logsExplorerDriver(page).goto(),
+
+ alerts: {
+ landmark: () =>
+ page
+ .getByRole('heading', { name: 'Alert Rules' })
+ .or(page.getByTestId('list-alerts-search-input')),
+ },
+
+ settings: {
+ sidenav: () => page.getByTestId('settings-page-sidenav'),
+ navItem: (itemKey) => page.getByTestId(itemKey),
+ },
dashboards: {
gotoList: async (title) => {
@@ -305,6 +342,8 @@ export function routingDriver(page: Page): Routing {
await page.getByTestId('save-button').click();
},
discardDialog: () => page.getByTestId('discard-changes-dialog'),
+ discardDialogButton: (name) =>
+ page.getByTestId('discard-changes-dialog').getByRole('button', { name }),
settings: () => page.getByTestId('roles-settings'),
removeByName: async (names) => {
const headers = { Authorization: `Bearer ${await authToken(page)}` };
diff --git a/tests/e2e/drivers/savedviews.ts b/tests/e2e/drivers/savedviews.ts
new file mode 100644
index 0000000000..60eea87f2a
--- /dev/null
+++ b/tests/e2e/drivers/savedviews.ts
@@ -0,0 +1,215 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import type {
+ Querybuildertypesv5RequestTypeDTO,
+ SavedviewtypesPanelTypeDTO,
+ SavedviewtypesPostableSavedViewDTO,
+ SavedviewtypesSavedViewDTO,
+ SavedviewtypesSchemaVersionDTO,
+ SavedviewtypesSourceDTO,
+} from './schemas';
+import { apiDriver, type Envelope } from './api';
+
+/**
+ * Saved views, shared by every explorer that has them (logs, traces, metrics,
+ * meter): the header and views list in the explorer's sidebar, and API seeds.
+ * Feature drivers call {@link savedViewsDriver} with their source.
+ *
+ * Views are org-wide, so every name a spec creates carries its own stamp and is
+ * removed by prefix.
+ */
+
+export type ViewSource = 'logs' | 'traces' | 'metrics' | 'meter';
+
+const VIEWS_API = '/api/v2/saved_views';
+
+type PanelType = `${SavedviewtypesPanelTypeDTO}`;
+
+const REQUEST_TYPE: Record<PanelType, `${Querybuildertypesv5RequestTypeDTO}`> =
+ {
+ list: 'raw',
+ trace: 'trace',
+ table: 'scalar',
+ value: 'scalar',
+ graph: 'time_series',
+ };
+
+export interface ViewSeed {
+ expression: string;
+ panelType?: 'list' | 'trace' | 'table' | 'graph';
+ /** Defaults to the view's source (`meter` views query `metrics`). */
+ dataSource?: 'logs' | 'traces' | 'metrics';
+ /** Merged into the v5 query spec, e.g. `aggregations` for a metrics view. */
+ spec?: Record<string, unknown>;
+}
+
+export interface SavedViews {
+ /** The header's view name, "My view" while none is selected. */
+ current(): Locator;
+ /** Open the views list. The metrics explorer keeps it pinned. */
+ openList(): Promise<void>;
+ search(text: string): Promise<void>;
+ /** The list row for `name`. Search first. */
+ row(name: string): Locator;
+ /** Select `name` from the list and wait for its `viewKey` in the URL. */
+ pick(name: string): Promise<void>;
+ /** Save the current query as a new view, with no view selected. */
+ saveAs(name: string): Promise<void>;
+ /** "Update selected view", only rendered once the query differs from the view. */
+ update(): Promise<void>;
+ clear(): Promise<void>;
+ rename(name: string, next: string): Promise<void>;
+ remove(name: string): Promise<void>;
+
+ create(name: string, seed: ViewSeed): Promise<string>;
+ list(): Promise<SavedviewtypesSavedViewDTO[]>;
+ removeByPrefix(prefix: string): Promise<void>;
+}
+
+const isViewsCall =
+ (method: string) =>
+ (response: { url(): string; request(): { method(): string } }): boolean =>
+ response.url().includes(VIEWS_API) && response.request().method() === method;
+
+/** List and trace panels return rows; every other panel needs an aggregation. */
+const isRawPanel = (seed: ViewSeed): boolean =>
+ (seed.panelType ?? 'list') === 'list' || seed.panelType === 'trace';
+
+export function savedViewsDriver(page: Page, source: ViewSource): SavedViews {
+ const api = apiDriver(page);
+ const dataSource = (seed: ViewSeed): string =>
+ seed.dataSource ?? (source === 'meter' ? 'metrics' : source);
+
+ const header = (): Locator => page.getByTestId('saved-views-header');
+ const panel = (): Locator => page.getByTestId('saved-views-panel');
+
+ // The row menu has no width until its row is hovered.
+ const openRowMenu = async (name: string): Promise<void> => {
+ const row = views.row(name);
+ await row.hover();
+ await row.getByTestId('saved-views-row-menu').click();
+ };
+
+ const views: SavedViews = {
+ current: () => header().getByTestId('saved-views-name'),
+
+ openList: async () => {
+ await expect(header()).toBeVisible();
+ const open = header().getByTestId('saved-views-open');
+ if (await open.isVisible()) {
+ await open.click();
+ }
+ await expect(panel().getByTestId('saved-views-search')).toBeVisible();
+ },
+
+ search: async (text) => {
+ await views.openList();
+ await panel().getByTestId('saved-views-search').fill(text);
+ },
+
+ row: (name) =>
+ panel()
+ .getByTestId('saved-views-row')
+ .filter({
+ has: page.getByTestId('saved-views-row-name').getByText(name, {
+ exact: true,
+ }),
+ }),
+
+ pick: async (name) => {
+ await views.search(name);
+ await views.row(name).getByTestId('saved-views-row-name').click();
+ await expect(page).toHaveURL(/viewKey=/);
+ await expect(views.current()).toContainText(name);
+ },
+
+ saveAs: async (name) => {
+ await header().getByTestId('saved-views-create').click();
+ await page.getByTestId('save-view-name').fill(name);
+ const saved = page.waitForResponse(isViewsCall('POST'));
+ await page.getByTestId('save-view-submit').click();
+ expect((await saved).ok()).toBe(true);
+ await expect(page).toHaveURL(/viewKey=/);
+ await expect(views.current()).toContainText(name);
+ },
+
+ update: async () => {
+ await header().getByTestId('saved-views-save-changes').click();
+ const updated = page.waitForResponse(isViewsCall('PUT'));
+ await page.getByTestId('saved-views-save-changes-item-update').click();
+ expect((await updated).ok()).toBe(true);
+ },
+
+ clear: async () => {
+ await header().getByTestId('saved-views-clear').click();
+ await expect(page).not.toHaveURL(/viewKey=/);
+ },
+
+ rename: async (name, next) => {
+ await openRowMenu(name);
+ await page.getByTestId('saved-views-row-menu-item-editDetails').click();
+ await page.getByTestId('save-view-name').fill(next);
+ const updated = page.waitForResponse(isViewsCall('PUT'));
+ await page.getByTestId('save-view-submit').click();
+ expect((await updated).ok()).toBe(true);
+ },
+
+ remove: async (name) => {
+ await openRowMenu(name);
+ await page.getByTestId('saved-views-row-menu-item-delete').click();
+ const deleted = page.waitForResponse(isViewsCall('DELETE'));
+ await page.getByTestId('delete-saved-view-confirm').click();
+ expect((await deleted).ok()).toBe(true);
+ await expect(views.row(name)).toHaveCount(0);
+ },
+
+ create: async (name, seed) => {
+ const panelType = seed.panelType ?? 'list';
+ const view = {
+ generateName: true,
+ source: source as SavedviewtypesSourceDTO,
+ schemaVersion: 'v2' as SavedviewtypesSchemaVersionDTO,
+ spec: {
+ displayName: name,
+ panelType: panelType as SavedviewtypesPanelTypeDTO,
+ requestType: REQUEST_TYPE[panelType] as Querybuildertypesv5RequestTypeDTO,
+ queries: [
+ {
+ type: 'builder_query',
+ spec: {
+ name: 'A',
+ signal: dataSource(seed),
+ disabled: false,
+ stepInterval: 60,
+ filter: { expression: seed.expression },
+ ...(isRawPanel(seed)
+ ? { order: [{ key: { name: 'timestamp' }, direction: 'desc' }] }
+ : { aggregations: [{ expression: 'count()' }] }),
+ ...seed.spec,
+ },
+ },
+ ],
+ },
+ } as SavedviewtypesPostableSavedViewDTO;
+ return api.create(VIEWS_API, view);
+ },
+
+ list: async () =>
+ (
+ await api.get<Envelope<SavedviewtypesSavedViewDTO[] | null>>(
+ `${VIEWS_API}?source=${source}`,
+ )
+ ).data ?? [],
+
+ removeByPrefix: async (prefix) => {
+ const all = await views.list();
+ await Promise.all(
+ all
+ .filter((view) => view.spec.displayName.startsWith(prefix))
+ .map((view) => api.tryDel(`${VIEWS_API}/${view.id}`)),
+ );
+ },
+ };
+
+ return views;
+}
diff --git a/tests/e2e/drivers/schemas.ts b/tests/e2e/drivers/schemas.ts
new file mode 100644
index 0000000000..e9ff203562
--- /dev/null
+++ b/tests/e2e/drivers/schemas.ts
@@ -0,0 +1,5 @@
+/**
+ * The API contract, generated by orval from `docs/api/openapi.yml`. Import
+ * request and response types from here rather than writing them by hand (S5).
+ */
+export type * from '../../../frontend/src/api/generated/services/sigNoz.schemas';
diff --git a/tests/e2e/drivers/settings/driver.ts b/tests/e2e/drivers/settings/driver.ts
new file mode 100644
index 0000000000..5ed2f68acc
--- /dev/null
+++ b/tests/e2e/drivers/settings/driver.ts
@@ -0,0 +1,753 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import type {
+ AuthtypesRelationDTO,
+ AuthtypesRoleDTO,
+ AuthtypesTransactionGroupDTO,
+ CoretypesKindDTO,
+ CoretypesTypeDTO,
+ ServiceaccounttypesGettableFactorAPIKeyWithKeyDTO,
+ ServiceaccounttypesServiceAccountDTO,
+ ServiceaccounttypesServiceAccountWithRolesDTO,
+ TypesOrganizationDTO,
+} from '../schemas';
+import { antdDriver } from '../antd';
+import { apiDriver, type Envelope } from '../api';
+import {
+ createDashboard,
+ deleteViaApi,
+ type DashboardSeed,
+} from '../dashboards';
+import { driver, type Layer } from '../kit';
+import { usersApi, type UsersApi } from '../users';
+
+/**
+ * The `/settings/*` pages: workspace, org, account, members, roles, service
+ * accounts, ingestion keys, shortcuts, MCP and billing.
+ *
+ * Members, roles and service accounts are org-wide lists that every worker
+ * adds to, so every read here is scoped by a name or email the caller stamped.
+ */
+
+export type Theme = 'dark' | 'light' | 'auto';
+export type Scope = 'all' | 'none';
+
+const toastText = (page: Page, text: string): Locator =>
+ page.locator('[data-sonner-toast]').filter({ hasText: text });
+
+/** `n` in base 26, spelled with `a-z` only. */
+const letters = (n: number): string =>
+ n
+ .toString(26)
+ .replace(/[0-9a-p]/g, (char) =>
+ String.fromCharCode(97 + Number.parseInt(char, 26)),
+ );
+
+/**
+ * A unique custom role name. The server accepts only `a-z` and `-`, at most 50
+ * characters, so the worker index and timestamp are spelled in letters.
+ */
+export function roleName(kind: string, workerIndex: number): string {
+ return `e-role-${kind}-w${letters(workerIndex)}-${letters(Date.now())}`;
+}
+
+/** A `transactionGroups` entry granting `relation` on every `kind` object. */
+export function grantAll(
+ relation: `${AuthtypesRelationDTO}`,
+ kind: `${CoretypesKindDTO}`,
+ type: `${CoretypesTypeDTO}` = 'metaresource',
+): AuthtypesTransactionGroupDTO {
+ return {
+ relation: relation as AuthtypesRelationDTO,
+ objectGroup: {
+ resource: {
+ kind: kind as CoretypesKindDTO,
+ type: type as CoretypesTypeDTO,
+ },
+ selectors: ['*'],
+ },
+ };
+}
+
+export interface Settings {
+ users: UsersApi;
+ toast(text: string): Locator;
+ pathname(): string;
+ reload(): Promise<void>;
+ errorBoundary(): Locator;
+ goto(path: string): Promise<void>;
+ seedDashboard(title: string): Promise<DashboardSeed>;
+ removeDashboard(id: string): Promise<void>;
+
+ /** The app side nav, as far as the account preferences drive it. */
+ sidenav: {
+ isCollapsed(): Promise<boolean>;
+ hover(): Promise<void>;
+ /** Move the pointer away: an unpinned nav expands on hover. */
+ parkPointer(): Promise<void>;
+ };
+
+ shell: {
+ goto(path: string): Promise<void>;
+ title(): Locator;
+ navItem(key: string): Locator;
+ navKeys(): Promise<string[]>;
+ };
+
+ general: {
+ retentionTitle(): Locator;
+ licenseCopyButton(): Locator;
+ };
+
+ org: {
+ goto(): Promise<void>;
+ nameInput(): Locator;
+ rename(name: string): Promise<void>;
+ apiName(): Promise<string>;
+ setApiName(name: string): Promise<void>;
+ authDomainTitle(): Locator;
+ };
+
+ account: {
+ goto(): Promise<void>;
+ userName(): Locator;
+ rename(name: string): Promise<void>;
+ changePassword(current: string, next: string): Promise<void>;
+ theme(value: Theme): Promise<void>;
+ /** `lightMode` on `<body>` and the persisted `THEME`. */
+ appliedTheme(): Promise<{ light: boolean; stored: string | null }>;
+ themeSelector(): Locator;
+ sidebarPinnedSwitch(): Locator;
+ /** Flip the pinned switch; resolves with the value the PUT sent. */
+ toggleSidebarPinned(): Promise<boolean>;
+ timezoneAdaptationSwitch(): Locator;
+ email(address: string): Locator;
+ };
+
+ members: {
+ goto(params?: string): Promise<void>;
+ heading(): Locator;
+ search(text: string): Promise<void>;
+ /** The member's table row. Search for the email first: the list pages at 20. */
+ row(email: string): Locator;
+ openInvite(): Promise<void>;
+ inviteDialog(): Locator;
+ invite(rows: { email: string; role: string }[]): Promise<void>;
+ openMember(email: string): Promise<void>;
+ drawer(): Locator;
+ roleSelect(): Locator;
+ deleteButton(): Locator;
+ setRoles(roles: string[]): Promise<void>;
+ saveMember(): Promise<void>;
+ /** Mint a reset or invite link from the drawer and return it. */
+ generateLink(): Promise<string>;
+ deleteMember(): Promise<void>;
+ filter(label: 'All members' | 'Pending invites' | 'Deleted'): Promise<void>;
+ };
+
+ roles: {
+ goto(): Promise<void>;
+ page(): Locator;
+ search(text: string): Promise<void>;
+ row(name: string): Locator;
+ section(label: string): Locator;
+ openCreate(): Promise<void>;
+ fillName(name: string): Promise<void>;
+ fillDescription(text: string): Promise<void>;
+ grant(resource: string, verb: string, scope: Scope): Promise<void>;
+ /** The view page's Update button, disabled for managed roles. */
+ updateButton(): Locator;
+ deleteButton(): Locator;
+ save(): Promise<void>;
+ view(id: string, name: string): Promise<void>;
+ openEdit(): Promise<void>;
+ viewPage(): Locator;
+ /** The create and edit page. */
+ editor(): Locator;
+ grantedCount(kind: string): Locator;
+ delete(): Promise<void>;
+ apiRole(id: string): Promise<AuthtypesRoleDTO>;
+ createApi(input: {
+ name: string;
+ description?: string;
+ transactionGroups?: AuthtypesTransactionGroupDTO[];
+ }): Promise<string>;
+ removeApi(id: string): Promise<void>;
+ removeByName(name: string): Promise<void>;
+ idByName(name: string): Promise<string | undefined>;
+ };
+
+ serviceAccounts: {
+ goto(params?: string): Promise<void>;
+ heading(): Locator;
+ newButton(): Locator;
+ search(text: string): Promise<void>;
+ row(name: string): Locator;
+ /** Create through the UI. Returns the new account's id. */
+ create(name: string): Promise<string>;
+ drawer(): Locator;
+ closeDrawer(): Promise<void>;
+ openAccount(id: string): Promise<void>;
+ openKeys(id: string): Promise<void>;
+ /** Add a key through the UI and return the secret it shows once. */
+ addKey(name: string): Promise<string>;
+ keyCreatedCallout(): Locator;
+ closeKeyModal(): Promise<void>;
+ revokeKey(name: string): Promise<void>;
+ roleSelect(): Locator;
+ setRoles(roles: string[]): Promise<void>;
+ save(): Promise<void>;
+ delete(): Promise<void>;
+ filter(label: 'All accounts' | 'Active' | 'Deleted'): Promise<void>;
+ callWithKey(key: string, path: string): Promise<number>;
+ createApi(name: string, role?: string): Promise<string>;
+ removeApi(id: string): Promise<void>;
+ removeByName(name: string): Promise<void>;
+ apiAccount(
+ id: string,
+ ): Promise<ServiceaccounttypesServiceAccountWithRolesDTO>;
+ addKeyApi(id: string, name: string): Promise<string>;
+ };
+
+ ingestion: {
+ goto(): Promise<void>;
+ /** The gateway WireMock has no mappings; serve an empty key list instead. */
+ stubGateway(): Promise<void>;
+ title(): Locator;
+ addButton(): Locator;
+ };
+
+ mcp: {
+ goto(): Promise<void>;
+ fallbackTitle(): Locator;
+ };
+
+ billing: {
+ goto(): Promise<void>;
+ subtitle(): Locator;
+ };
+
+ shortcutsPage: {
+ goto(): Promise<void>;
+ root(): Locator;
+ section(name: string): Locator;
+ };
+}
+
+export function settingsDriver(page: Page): Settings {
+ const api = apiDriver(page);
+ const antd = antdDriver(page);
+ const users = usersApi(page);
+
+ const clearSelect = async (select: Locator): Promise<void> => {
+ const removers = select.locator('.ant-select-selection-item-remove');
+ while ((await removers.count()) > 0) {
+ await removers.first().click();
+ }
+ };
+
+ /**
+ * `antd.pickByName` closes the list with Escape, which also closes the
+ * enclosing dialog or drawer. Close it by clicking the dialog's title.
+ */
+ const pickInDialog = async (
+ dialog: Locator,
+ select: Locator,
+ name: string,
+ ): Promise<void> => {
+ const before = await antd.selectedTags(select).count();
+ await select.click();
+ await expect(select).toHaveClass(/ant-select-open/);
+ await select.locator('input[role="combobox"]').fill(name);
+ const dropdown = await antd.ownDropdown(select);
+ await dropdown
+ .locator('.ant-select-item-option')
+ .filter({ hasText: name })
+ .first()
+ .click();
+ await dialog.getByRole('heading').first().click();
+ await expect(select).not.toHaveClass(/ant-select-open/);
+ await expect(antd.selectedTags(select)).toHaveCount(before + 1);
+ };
+
+ /** antd renders the select root around the input that carries the id. */
+ const selectById = (id: string): Locator =>
+ page.locator('.ant-select').filter({ has: page.locator(`input#${id}`) });
+
+ const settings: Settings = {
+ users,
+ toast: (text) => toastText(page, text),
+ pathname: () => new URL(page.url()).pathname,
+ reload: async () => {
+ await page.reload();
+ },
+ errorBoundary: () => page.getByTestId('error-boundary-fallback'),
+ goto: async (path) => {
+ await page.goto(path);
+ },
+ seedDashboard: (title) => createDashboard(page, title),
+ removeDashboard: (id) => deleteViaApi(page, id),
+
+ sidenav: {
+ isCollapsed: async () =>
+ (await page.getByTestId('sidenav').getAttribute('data-collapsed')) ===
+ 'true',
+ hover: async () => {
+ await page.getByTestId('sidenav').hover();
+ await expect(page.getByTestId('sidenav')).toHaveAttribute(
+ 'data-collapsed',
+ 'false',
+ );
+ },
+ parkPointer: async () => {
+ const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
+ await page.mouse.move(viewport.width - 10, viewport.height - 10);
+ },
+ },
+
+ shell: {
+ goto: async (path) => {
+ await page.goto(path);
+ await expect(settings.shell.title()).toBeVisible();
+ },
+ title: () => page.getByTestId('settings-page-title'),
+ navItem: (key) => page.getByTestId('settings-page-sidenav').getByTestId(key),
+ navKeys: () =>
+ page
+ .getByTestId('settings-page-sidenav')
+ .locator('[data-testid]')
+ .evaluateAll((nodes) =>
+ nodes.map((node) => node.getAttribute('data-testid') ?? ''),
+ ),
+ },
+
+ general: {
+ retentionTitle: () => page.getByText('Retention Controls'),
+ licenseCopyButton: () => page.getByTestId('license-key-row-copy-btn'),
+ },
+
+ org: {
+ goto: () => settings.shell.goto('/settings/org-settings'),
+ nameInput: () => page.getByTestId('org-display-name-input'),
+ rename: async (name) => {
+ await settings.org.nameInput().fill(name);
+ const saved = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'PUT' &&
+ new URL(response.url()).pathname === '/api/v2/orgs/me',
+ );
+ await page.getByTestId('org-display-name-submit').click();
+ expect((await saved).ok()).toBe(true);
+ },
+ apiName: async () =>
+ (await api.get<Envelope<TypesOrganizationDTO>>('/api/v2/orgs/me')).data
+ .displayName ?? '',
+ setApiName: async (name) => {
+ const org = (
+ await api.get<Envelope<TypesOrganizationDTO>>('/api/v2/orgs/me')
+ ).data;
+ await api.put('/api/v2/orgs/me', { id: org.id, displayName: name });
+ },
+ authDomainTitle: () => page.getByTestId('auth-domain-title'),
+ },
+
+ account: {
+ goto: () => settings.shell.goto('/settings/my-settings'),
+ userName: () => page.getByTestId('user-info-name'),
+ rename: async (name) => {
+ await page.getByTestId('update-name-open-btn').click();
+ await page.getByTestId('update-name-input').fill(name);
+ const saved = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'PUT' &&
+ new URL(response.url()).pathname === '/api/v2/users/me',
+ );
+ await page.getByTestId('update-name-btn').click();
+ expect((await saved).ok()).toBe(true);
+ await expect(settings.toast('Name updated successfully')).toBeVisible();
+ },
+ changePassword: async (current, next) => {
+ await page.getByTestId('reset-password-open-btn').click();
+ await page.getByTestId('current-password-textbox').fill(current);
+ await page.getByTestId('new-password-textbox').fill(next);
+ await page.getByTestId('reset-password-btn').click();
+ await expect(settings.toast('Password updated successfully')).toBeVisible();
+ },
+ themeSelector: () => page.getByTestId('theme-selector'),
+ theme: async (value) => {
+ await page.getByTestId(`theme-selector-button-${value}`).click();
+ },
+ appliedTheme: () =>
+ page.evaluate(() => ({
+ light: document.body.classList.contains('lightMode'),
+ stored: localStorage.getItem('THEME'),
+ })),
+ sidebarPinnedSwitch: () => page.getByTestId('side-nav-pinned-switch'),
+ toggleSidebarPinned: async () => {
+ const saved = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'PUT' &&
+ response.url().includes('/api/v1/user/preferences/sidenav_pinned'),
+ );
+ await settings.account.sidebarPinnedSwitch().click();
+ const response = await saved;
+ expect(response.ok()).toBe(true);
+ return (response.request().postDataJSON() as { value: boolean }).value;
+ },
+ timezoneAdaptationSwitch: () =>
+ page.getByTestId('timezone-adaptation-switch'),
+ email: (address) => page.getByText(address, { exact: true }),
+ },
+
+ members: {
+ goto: async (params) => {
+ await settings.shell.goto(
+ params ? `/settings/members?${params}` : '/settings/members',
+ );
+ await expect(settings.members.heading()).toBeVisible();
+ },
+ heading: () => page.getByRole('heading', { name: 'Members', exact: true }),
+ search: async (text) => {
+ await page.getByTestId('members-search-input').fill(text);
+ },
+ // antd keys each row by the member id; the email is what callers hold.
+ row: (email) => page.locator('tr[data-row-key]').filter({ hasText: email }),
+ openInvite: async () => {
+ await page.getByTestId('invite-member-btn').click();
+ await expect(settings.members.inviteDialog()).toBeVisible();
+ },
+ inviteDialog: () =>
+ page.getByRole('dialog', { name: 'Invite Team Members' }),
+ invite: async (rows) => {
+ const dialog = settings.members.inviteDialog();
+ for (const [index, { email, role }] of rows.entries()) {
+ if (
+ index >= (await dialog.locator('[data-testid^="invite-email-"]').count())
+ ) {
+ await dialog.getByTestId('invite-add-row').click();
+ }
+ await dialog
+ .locator('[data-testid^="invite-email-"]')
+ .nth(index)
+ .fill(email);
+ const select = dialog
+ .locator('.ant-select')
+ .filter({ has: page.locator('input[id^="invite-role-"]') })
+ .nth(index);
+ await pickInDialog(dialog, select, role);
+ }
+ await page.getByTestId('invite-submit-btn').click();
+ await expect(settings.toast('Invites sent successfully')).toBeVisible();
+ await expect(dialog).toHaveCount(0);
+ },
+ openMember: async (email) => {
+ await settings.members.search(email);
+ await settings.members.row(email).click();
+ await expect(settings.members.drawer()).toBeVisible();
+ await expect(settings.members.drawer().getByText(email)).toBeVisible();
+ },
+ drawer: () => page.getByRole('dialog', { name: 'Member Details' }),
+ roleSelect: () => selectById('member-role'),
+ deleteButton: () => page.getByTestId('member-delete-btn'),
+ setRoles: async (roles) => {
+ const select = settings.members.roleSelect();
+ await clearSelect(select);
+ for (const role of roles) {
+ await pickInDialog(settings.members.drawer(), select, role);
+ }
+ },
+ saveMember: async () => {
+ await page.getByTestId('member-save-btn').click();
+ await expect(
+ settings.toast('Member details updated successfully'),
+ ).toBeVisible();
+ },
+ generateLink: async () => {
+ await page.getByTestId('member-reset-link-btn').click();
+ const link = page.getByTestId('reset-link-text');
+ await expect(link).toContainText('/password-reset?token=');
+ return (await link.innerText()).trim();
+ },
+ deleteMember: async () => {
+ await settings.members.deleteButton().click();
+ await page.getByTestId('member-delete-confirm-btn').click();
+ },
+ filter: async (label) => {
+ await page.getByTestId('members-filter-trigger').click();
+ await page.getByRole('menuitem', { name: new RegExp(`^${label}`) }).click();
+ },
+ },
+
+ roles: {
+ goto: async () => {
+ await settings.shell.goto('/settings/roles');
+ await expect(settings.roles.page()).toBeVisible();
+ },
+ page: () => page.getByTestId('roles-settings'),
+ search: async (text) => {
+ await page.getByTestId('roles-search-input').fill(text);
+ },
+ row: (name) => page.getByTestId(`role-row-${name}`),
+ section: (label) =>
+ page.getByRole('heading', { name: new RegExp(`^${label}`) }),
+ openCreate: async () => {
+ await page.getByTestId('create-custom-role-btn').click();
+ await expect(settings.roles.editor()).toBeVisible();
+ },
+ fillName: async (name) => {
+ await page.getByTestId('role-name-input').fill(name);
+ },
+ fillDescription: async (text) => {
+ await page.getByTestId('role-description-input').fill(text);
+ },
+ grant: async (resource, verb, scope) => {
+ // The view page shares the header testid and can still be mounted.
+ const editor = settings.roles.editor();
+ const header = editor.getByTestId(`resource-card-header-${resource}`);
+ if ((await header.getAttribute('aria-expanded')) !== 'true') {
+ await header.click();
+ }
+ await editor
+ .getByTestId(`action-toggle-scope-${resource}-${verb}-button-${scope}`)
+ .click();
+ },
+ // The view and edit pages share testids, and the route tab that is
+ // leaving stays mounted until its animation ends.
+ updateButton: () => settings.roles.viewPage().getByTestId('save-button'),
+ deleteButton: () => settings.roles.viewPage().getByTestId('delete-button'),
+ save: async () => {
+ await settings.roles.editor().getByTestId('save-button').click();
+ },
+ view: async (id, name) => {
+ await page.goto(`/settings/roles/${id}?name=${encodeURIComponent(name)}`);
+ await expect(settings.roles.viewPage()).toBeVisible();
+ },
+ openEdit: async () => {
+ await settings.roles.updateButton().click();
+ await expect(settings.roles.editor()).toBeVisible();
+ },
+ viewPage: () => page.getByTestId('view-role-page'),
+ editor: () => page.getByTestId('create-edit-role-page'),
+ grantedCount: (kind) =>
+ settings.roles.viewPage().getByTestId(`granted-count-${kind}`),
+ delete: async () => {
+ await settings.roles.deleteButton().click();
+ await page
+ .getByTestId('delete-role-modal')
+ .getByRole('button', { name: 'Delete Role' })
+ .click();
+ },
+ apiRole: async (id) =>
+ (await api.get<Envelope<AuthtypesRoleDTO>>(`/api/v1/roles/${id}`)).data,
+ createApi: ({ name, description = '', transactionGroups = [] }) =>
+ api.create('/api/v1/roles', { name, description, transactionGroups }),
+ removeApi: (id) => api.tryDel(`/api/v1/roles/${id}`),
+ idByName: async (name) =>
+ (await users.roles()).find((role) => role.name === name)?.id,
+ removeByName: async (name) => {
+ const id = await settings.roles.idByName(name);
+ if (id) {
+ await settings.roles.removeApi(id);
+ }
+ },
+ },
+
+ serviceAccounts: {
+ goto: async (params) => {
+ await settings.shell.goto(
+ params
+ ? `/settings/service-accounts?${params}`
+ : '/settings/service-accounts',
+ );
+ await expect(settings.serviceAccounts.heading()).toBeVisible();
+ },
+ heading: () =>
+ page.getByRole('heading', { name: 'Service Accounts', exact: true }),
+ newButton: () => page.getByTestId('new-sa-btn'),
+ search: async (text) => {
+ await page.getByTestId('sa-search-input').fill(text);
+ },
+ row: (name) =>
+ page.getByRole('button', { name: `View service account ${name}` }),
+ create: async (name) => {
+ await settings.serviceAccounts.newButton().click();
+ await page.getByTestId('create-sa-name-input').fill(name);
+ const created = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'POST' &&
+ new URL(response.url()).pathname === '/api/v1/service_accounts',
+ );
+ await page.getByTestId('create-sa-submit-btn').click();
+ const response = await created;
+ expect(response.ok()).toBe(true);
+ const body = (await response.json()) as Envelope<{ id: string }>;
+ return body.data.id;
+ },
+ drawer: () => page.getByRole('dialog', { name: 'Service Account Details' }),
+ closeDrawer: async () => {
+ await settings.serviceAccounts
+ .drawer()
+ .getByRole('button', { name: 'Cancel' })
+ .click();
+ await expect(settings.serviceAccounts.drawer()).toHaveCount(0);
+ },
+ // The drawer is modal and hides the page heading from the a11y tree.
+ openAccount: async (id) => {
+ await settings.shell.goto(
+ `/settings/service-accounts?account=${encodeURIComponent(id)}`,
+ );
+ await expect(settings.serviceAccounts.drawer()).toBeVisible();
+ // The select renders empty until the account loads, and a clear
+ // that runs first is overwritten by the late roles.
+ const { serviceAccountRoles } =
+ await settings.serviceAccounts.apiAccount(id);
+ await expect(
+ antd.selectedTags(settings.serviceAccounts.roleSelect()),
+ ).toHaveCount((serviceAccountRoles ?? []).length);
+ },
+ openKeys: async (id) => {
+ await settings.shell.goto(
+ `/settings/service-accounts?account=${encodeURIComponent(id)}&tab=keys`,
+ );
+ await expect(settings.serviceAccounts.drawer()).toBeVisible();
+ },
+ addKey: async (name) => {
+ await page.getByTestId('sa-add-key-btn').click();
+ await page.getByTestId('add-key-name-input').fill(name);
+ await page.getByTestId('add-key-submit-btn').click();
+ const value = page.getByTestId('created-key-value');
+ await expect(value).not.toBeEmpty();
+ return (await value.innerText()).trim();
+ },
+ keyCreatedCallout: () =>
+ page.getByText(
+ 'Store the key securely. This is the only time it will be displayed.',
+ ),
+ closeKeyModal: async () => {
+ await page.keyboard.press('Escape');
+ await expect(page.getByTestId('add-key-modal')).toHaveCount(0);
+ },
+ revokeKey: async (name) => {
+ await settings.serviceAccounts
+ .drawer()
+ .locator('tr')
+ .filter({ hasText: name })
+ .getByTestId('keys-tab-revoke-btn')
+ .click();
+ await page.getByTestId('revoke-key-confirm-btn').click();
+ await expect(settings.toast('Key revoked successfully')).toBeVisible();
+ },
+ roleSelect: () => selectById('sa-roles'),
+ setRoles: async (roles) => {
+ const select = settings.serviceAccounts.roleSelect();
+ await clearSelect(select);
+ for (const role of roles) {
+ await pickInDialog(settings.serviceAccounts.drawer(), select, role);
+ }
+ },
+ save: async () => {
+ await page.getByTestId('sa-save-btn').click();
+ await expect(
+ settings.toast('Service account updated successfully'),
+ ).toBeVisible();
+ },
+ delete: async () => {
+ await page.getByTestId('sa-delete-btn').click();
+ await page.getByTestId('confirm-delete-btn').click();
+ await expect(settings.toast('Service account deleted')).toBeVisible();
+ },
+ filter: async (label) => {
+ await page.getByTestId('sa-filter-trigger').click();
+ await page.getByRole('menuitem', { name: new RegExp(`^${label}`) }).click();
+ },
+ callWithKey: async (key, path) =>
+ (
+ await page.request.get(path, { headers: { 'SIGNOZ-API-KEY': key } })
+ ).status(),
+ createApi: async (name, role) => {
+ const id = await api.create('/api/v1/service_accounts', { name });
+ if (role) {
+ await api.post('/api/v1/service_account_roles', {
+ serviceAccountId: id,
+ roleId: await users.roleId(role),
+ });
+ }
+ return id;
+ },
+ removeApi: (id) => api.tryDel(`/api/v1/service_accounts/${id}`),
+ removeByName: async (name) => {
+ const list = await api.get<
+ Envelope<ServiceaccounttypesServiceAccountDTO[]>
+ >('/api/v1/service_accounts');
+ await Promise.all(
+ list.data
+ .filter((account) => account.name === name)
+ .map((account) => settings.serviceAccounts.removeApi(account.id)),
+ );
+ },
+ apiAccount: async (id) =>
+ (
+ await api.get<Envelope<ServiceaccounttypesServiceAccountWithRolesDTO>>(
+ `/api/v1/service_accounts/${id}`,
+ )
+ ).data,
+ addKeyApi: async (id, name) =>
+ (
+ await api.post<
+ Envelope<ServiceaccounttypesGettableFactorAPIKeyWithKeyDTO>
+ >(`/api/v1/service_accounts/${id}/keys`, { name, expiresAt: 0 })
+ ).data.key,
+ },
+
+ ingestion: {
+ goto: () => settings.shell.goto('/settings/ingestion-settings'),
+ stubGateway: async () => {
+ await page.route('**/api/v2/gateway/**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ status: 'success',
+ data: {
+ keys: [],
+ _pagination: { page: 1, per_page: 10, pages: 0, total: 0 },
+ },
+ }),
+ }),
+ );
+ },
+ title: () => page.getByRole('heading', { name: 'Ingestion Keys' }),
+ addButton: () => page.getByTestId('ingestion-key-add-btn'),
+ },
+
+ mcp: {
+ goto: () => settings.shell.goto('/settings/mcp-server'),
+ fallbackTitle: () =>
+ page.getByRole('heading', { name: 'MCP Server is available on SigNoz' }),
+ },
+
+ billing: {
+ goto: () => settings.shell.goto('/settings/billing'),
+ subtitle: () =>
+ page.getByText(
+ 'Manage your billing information, invoices, and monitor costs.',
+ ),
+ },
+
+ shortcutsPage: {
+ goto: async () => {
+ await settings.shell.goto('/settings/shortcuts');
+ await expect(settings.shortcutsPage.root()).toBeVisible();
+ },
+ root: () => page.getByTestId('keyboard-shortcuts-page'),
+ section: (name) => page.getByTestId(`shortcut-section-${name}`),
+ },
+ };
+
+ return settings;
+}
+
+export const withSettings: Layer<{ settings: Settings }> = driver(
+ 'settings',
+ ({ page }) => settingsDriver(page),
+);
diff --git a/tests/e2e/drivers/settings/index.ts b/tests/e2e/drivers/settings/index.ts
new file mode 100644
index 0000000000..b12e03ae3d
--- /dev/null
+++ b/tests/e2e/drivers/settings/index.ts
@@ -0,0 +1,28 @@
+import { withAuthFlows } from '../auth-flows';
+import { kit } from '../kit';
+
+import { withSettings } from './driver';
+import {
+ withActiveEditor,
+ withCustomRoleSeed,
+ withPendingMember,
+ withServiceAccountSeed,
+} from './seeds';
+
+/**
+ * The settings `test`. Seeds are test-scoped and lazy: a spec pays only for the
+ * ones it destructures. `authFlows` drives a guest context, for the flows that
+ * end in signing in as someone else.
+ */
+export const test = withAuthFlows(
+ withSettings(
+ withActiveEditor(
+ withPendingMember(withServiceAccountSeed(withCustomRoleSeed(kit))),
+ ),
+ ),
+);
+
+export { ADMIN, expect } from '../kit';
+export { E2E_PASSWORD } from '../users';
+export * from './driver';
+export * from './seeds';
diff --git a/tests/e2e/drivers/settings/seeds.ts b/tests/e2e/drivers/settings/seeds.ts
new file mode 100644
index 0000000000..b6b5a1aeaa
--- /dev/null
+++ b/tests/e2e/drivers/settings/seeds.ts
@@ -0,0 +1,125 @@
+import type { Browser, TestType } from '@playwright/test';
+
+import { onAdminPage, type Layer } from '../kit';
+import { usersApi, type CreatedUser } from '../users';
+
+import { grantAll, roleName, settingsDriver } from './driver';
+
+/**
+ * Test-scoped seeds. Each test that asks for one gets its own copy, created on
+ * an admin page and deleted after the test: every spec here mutates what it
+ * seeds (roles, keys, deletion), so a worker-shared copy would make the tests
+ * order-dependent.
+ */
+
+type Fixtures = Record<string, unknown>;
+
+function perTest<Name extends string, T>(
+ name: Name,
+ open: (ctx: {
+ browser: Browser;
+ stamp: string;
+ workerIndex: number;
+ }) => Promise<T>,
+ close: (ctx: { browser: Browser; value: T }) => Promise<void>,
+): Layer<{ [K in Name]: T }> {
+ const fixture = {
+ [name]: async (
+ { browser }: { browser: Browser },
+ use: (value: T) => Promise<void>,
+ testInfo: { workerIndex: number },
+ ) => {
+ const stamp = `w${testInfo.workerIndex}-${Date.now()}`;
+ const value = await open({
+ browser,
+ stamp,
+ workerIndex: testInfo.workerIndex,
+ });
+ await use(value);
+ await close({ browser, value });
+ },
+ };
+ return ((test: TestType<Fixtures, Fixtures>) =>
+ test.extend(fixture as never)) as Layer<{ [K in Name]: T }>;
+}
+
+export interface ServiceAccountSeed {
+ id: string;
+ name: string;
+}
+
+/** A service account holding `signoz-viewer`. */
+export const withServiceAccountSeed = perTest(
+ 'serviceAccount',
+ ({ browser, stamp }): Promise<ServiceAccountSeed> =>
+ onAdminPage(browser, async (page) => {
+ const name = `e2e-sa-${stamp}`;
+ const id = await settingsDriver(page).serviceAccounts.createApi(
+ name,
+ 'signoz-viewer',
+ );
+ return { id, name };
+ }),
+ ({ browser, value }) =>
+ onAdminPage(browser, (page) =>
+ settingsDriver(page).serviceAccounts.removeApi(value.id),
+ ),
+);
+
+export interface CustomRoleSeed {
+ id: string;
+ name: string;
+ description: string;
+}
+
+/** A custom role granting dashboard read and list. */
+export const withCustomRoleSeed = perTest(
+ 'customRole',
+ ({ browser, workerIndex }): Promise<CustomRoleSeed> =>
+ onAdminPage(browser, async (page) => {
+ const name = roleName('seed', workerIndex);
+ const description = 'e2e seeded role';
+ const id = await settingsDriver(page).roles.createApi({
+ name,
+ description,
+ transactionGroups: [
+ grantAll('read', 'dashboard'),
+ grantAll('list', 'dashboard'),
+ ],
+ });
+ return { id, name, description };
+ }),
+ ({ browser, value }) =>
+ onAdminPage(browser, (page) =>
+ settingsDriver(page).roles.removeApi(value.id),
+ ),
+);
+
+export interface PendingMemberSeed {
+ id: string;
+ email: string;
+}
+
+/** An invited, never-activated `signoz-viewer`. */
+export const withPendingMember = perTest(
+ 'pendingMember',
+ ({ browser, stamp }): Promise<PendingMemberSeed> =>
+ onAdminPage(browser, async (page) => {
+ const email = `e2e-pending-${stamp}@signoz.test`;
+ const id = await usersApi(page).create({ email, role: 'signoz-viewer' });
+ return { id, email };
+ }),
+ ({ browser, value }) =>
+ onAdminPage(browser, (page) => usersApi(page).remove(value.id)),
+);
+
+/** An active `signoz-editor`, for flows that delete a member. */
+export const withActiveEditor = perTest(
+ 'activeEditor',
+ ({ browser, stamp }): Promise<CreatedUser> =>
+ onAdminPage(browser, (page) =>
+ usersApi(page).createActive('signoz-editor', `editor-${stamp}`),
+ ),
+ ({ browser, value }) =>
+ onAdminPage(browser, (page) => usersApi(page).remove(value.id)),
+);
diff --git a/tests/e2e/drivers/shell.ts b/tests/e2e/drivers/shell.ts
new file mode 100644
index 0000000000..e1a2b2d37e
--- /dev/null
+++ b/tests/e2e/drivers/shell.ts
@@ -0,0 +1,920 @@
+import {
+ expect,
+ type Locator,
+ type Page,
+ type Request,
+ type Response,
+} from '@playwright/test';
+
+import { alertSeeder } from './alerts/seed';
+import { MISSING_METADATA } from './apm';
+import { stubCloudOnlyApis, type ConsoleWatch } from './console';
+import {
+ createDashboard,
+ deleteViaApi,
+ type DashboardSeed,
+} from './dashboards';
+import { driver, guestDriver, kit, type Layer } from './kit';
+import { randomSpanId, randomTraceId, seedTracesViaSeeder } from './traces';
+import { timePickerDriver, type TimePicker } from './timepicker';
+import { usersApi, type UsersApi } from './users';
+
+/**
+ * The app shell: every top-level route, the side nav, its menus, the global
+ * keyboard shortcuts, the top-nav time picker and Home.
+ *
+ * Per-user preferences (`sidenav_pinned`, `nav_shortcuts`, the
+ * `welcome_checklist_*` flags) are server-side, so a spec that writes one runs
+ * `as: 'admin2'`: the bootstrap admin's preferences are shared by every worker.
+ */
+
+/** A service the golden dataset always carries. */
+export const GOLDEN_SERVICE = 'frontend';
+
+export interface RouteProbe {
+ /** Test title, `TC-NN <what>`. */
+ title: string;
+ path: string;
+ /** Pathname the app must settle on. Defaults to `path` without its query. */
+ expectPath?: string;
+ /** Proof the route's own component rendered, read from its source. */
+ marker(page: Page): Locator;
+ /**
+ * Substrings of failed responses and console errors the route is known to
+ * produce. Each entry names the defect where the probe is declared.
+ */
+ allowFailures?: string[];
+ /** Console errors the route is known to log that carry no URL, such as axios's. */
+ allowErrors?: string[];
+ /** The route *is* the error fallback, so the boundary must be present. */
+ expectBoundary?: boolean;
+}
+
+const byTestId =
+ (id: string) =>
+ (page: Page): Locator =>
+ page.getByTestId(id);
+
+const selectedTab =
+ (name: string | RegExp) =>
+ (page: Page): Locator =>
+ page.getByRole('tab', { name, selected: true });
+
+/**
+ * One row per registered top-level route. Markers come from the component the
+ * route mounts, so a row fails when that component stops rendering rather than
+ * when some shared chrome does.
+ */
+export const ROUTES: RouteProbe[] = [
+ {
+ title: 'TC-01 /home renders the welcome view',
+ path: '/home',
+ marker: byTestId('home-page'),
+ },
+ {
+ title: 'TC-02 /services renders the services table',
+ path: '/services',
+ marker: (page) => page.getByRole('columnheader', { name: 'Application' }),
+ },
+ {
+ title: 'TC-03 /services/<service> renders the service overview',
+ path: `/services/${GOLDEN_SERVICE}`,
+ marker: selectedTab('Overview'),
+ // The Apdex panel's metadata request, see `MISSING_METADATA`.
+ allowFailures: [MISSING_METADATA],
+ },
+ {
+ title: 'TC-04 /service-map renders the map container',
+ path: '/service-map',
+ // `modules/Servicemap` carries no testid; the container class is the
+ // component's own root.
+ marker: (page) => page.locator('.service-map-container'),
+ },
+ {
+ title: 'TC-05 /logs/logs-explorer renders the explorer toolbar',
+ path: '/logs/logs-explorer',
+ marker: byTestId('search-view'),
+ },
+ {
+ title: 'TC-06 /logs/pipelines renders the pipelines tab',
+ path: '/logs/pipelines',
+ // The route tab and the page's own inner tab are both "Pipelines".
+ marker: (page) => selectedTab('Pipelines')(page).first(),
+ },
+ {
+ title: 'TC-07 /logs/saved-views redirects to the logs explorer',
+ path: '/logs/saved-views',
+ expectPath: '/logs/logs-explorer',
+ marker: byTestId('search-view'),
+ },
+ {
+ title: 'TC-08 /traces-explorer renders the explorer toolbar',
+ path: '/traces-explorer',
+ marker: byTestId('trace-view'),
+ },
+ {
+ title: 'TC-09 /traces/saved-views redirects to the traces explorer',
+ path: '/traces/saved-views',
+ expectPath: '/traces-explorer',
+ marker: byTestId('trace-view'),
+ },
+ {
+ title: 'TC-10 /traces/funnels renders the funnels header',
+ path: '/traces/funnels',
+ marker: (page) => page.getByText('Create and manage tracing funnels.'),
+ },
+ {
+ title: 'TC-11 /metrics-explorer/summary renders the metrics search',
+ path: '/metrics-explorer/summary',
+ marker: byTestId('qb-search-container'),
+ },
+ {
+ title: 'TC-12 /metrics-explorer/explorer renders the explorer header',
+ path: '/metrics-explorer/explorer',
+ marker: (page) => page.getByText('1 chart/query', { exact: true }),
+ },
+ {
+ title: 'TC-13 /metrics-explorer/views redirects to the metrics explorer',
+ path: '/metrics-explorer/views',
+ expectPath: '/metrics-explorer/explorer',
+ marker: (page) => page.getByText('1 chart/query', { exact: true }),
+ },
+ {
+ title: 'TC-14 /infrastructure-monitoring/hosts renders the hosts list',
+ path: '/infrastructure-monitoring/hosts',
+ marker: (page) => page.getByTestId('quick-filters-toggle').first(),
+ },
+ {
+ title: 'TC-15 /infrastructure-monitoring/kubernetes renders the entity rail',
+ path: '/infrastructure-monitoring/kubernetes',
+ marker: byTestId('category-pods'),
+ },
+ {
+ title: 'TC-16 /integrations renders the integrations header',
+ path: '/integrations',
+ marker: (page) =>
+ page.getByRole('heading', { name: 'Integrations', exact: true }),
+ },
+ {
+ title: 'TC-17 /exceptions renders the exceptions table',
+ path: '/exceptions',
+ marker: (page) => page.getByRole('columnheader', { name: /Exception Type/ }),
+ },
+ {
+ title: 'TC-18 /api-monitoring/explorer renders the domain list',
+ path: '/api-monitoring/explorer',
+ marker: (page) =>
+ page
+ .getByTestId('quick-filters-layout-content')
+ .getByTestId('explorer-run-query-btn'),
+ },
+ {
+ title: 'TC-19 /ai-observability/overview renders the overview',
+ path: '/ai-observability/overview',
+ marker: byTestId('llm-observability-overview'),
+ // The dashboard toolbar asks for the public meta and an authz check under
+ // the synthetic id `useSystemDashboard` assigns, and both answer 400.
+ allowFailures: [
+ '/api/v1/dashboards/llm-observability-overview/public',
+ '/api/v1/authz/check',
+ ],
+ allowErrors: ['Request failed with status code 400'],
+ },
+ {
+ title: 'TC-20 /meter renders the meter tab',
+ path: '/meter',
+ marker: selectedTab(/Meter/),
+ },
+ {
+ title: 'TC-21 /messaging-queues/overview renders the overview',
+ path: '/messaging-queues/overview',
+ marker: (page) => page.getByText('Messaging Queue Overview', { exact: true }),
+ },
+ {
+ title: 'TC-22 /dashboard renders the dashboards list',
+ path: '/dashboard',
+ marker: byTestId('new-dashboard-cta'),
+ },
+ {
+ title: 'TC-23 /alerts renders the alert rules tab',
+ path: '/alerts',
+ marker: selectedTab(/Alert Rules/),
+ },
+ {
+ title: 'TC-24 /alerts?tab=Channels renders the channels list',
+ path: '/alerts?tab=Channels',
+ marker: (page) => page.getByTestId('channels-create'),
+ },
+ {
+ title: 'TC-25 /status shows the running version',
+ path: '/status',
+ marker: (page) => page.getByPlaceholder('Current version'),
+ },
+ {
+ title: 'TC-26 /support renders the support page',
+ path: '/support',
+ marker: byTestId('support-page-title'),
+ },
+ {
+ title: 'TC-27 /onboarding renders the questionnaire',
+ path: '/onboarding',
+ marker: (page) =>
+ page.getByRole('heading', { name: 'Welcome to SigNoz Cloud' }),
+ },
+ {
+ title: 'TC-28 /get-started-with-signoz-cloud renders the data sources',
+ path: '/get-started-with-signoz-cloud',
+ marker: (page) => page.getByText('Select your data source').first(),
+ },
+ {
+ title: 'TC-29 /un-authorized renders the restricted page',
+ path: '/un-authorized',
+ marker: (page) => page.getByRole('heading', { name: 'Access Restricted' }),
+ },
+ {
+ title: 'TC-30 /something-went-wrong renders the error fallback',
+ path: '/something-went-wrong',
+ marker: byTestId('error-boundary-fallback'),
+ expectBoundary: true,
+ },
+];
+
+const homeMarker = byTestId('home-page');
+
+export const HOME_PROBE: RouteProbe = {
+ title: 'home',
+ path: '/home',
+ marker: homeMarker,
+};
+
+/** Routes the shell must send elsewhere on this stack. */
+export const REDIRECTS: RouteProbe[] = [
+ ...[
+ '/workspace-locked',
+ '/workspace-suspended',
+ '/workspace-access-restricted',
+ ].map((path): RouteProbe => ({
+ title: `TC-31 ${path} with a healthy license lands on /home`,
+ path,
+ expectPath: '/home',
+ marker: homeMarker,
+ })),
+ ...['/ai-assistant', '/ai-assistant/00000000-0000-0000-0000-000000000000'].map(
+ (path): RouteProbe => ({
+ title: `TC-32 ${path} without an assistant URL lands on /home`,
+ path,
+ expectPath: '/home',
+ marker: homeMarker,
+ }),
+ ),
+ {
+ // `/licenses` is known to the route guard on every platform but only
+ // mounted for self-hosted, so a cloud license falls through to NotFound.
+ title: 'TC-33 /licenses on a cloud license renders not-found',
+ path: '/licenses',
+ marker: (page) => page.getByText('Page Not Found', { exact: true }),
+ },
+ {
+ title: 'TC-34 an unknown path lands on /home',
+ path: '/definitely-not-a-route',
+ expectPath: '/home',
+ marker: homeMarker,
+ },
+];
+
+export interface NavShortcut {
+ combo: string;
+ /** Where the chord is pressed. Home, unless the chord itself goes there. */
+ from: string;
+ path: string;
+ /** Expected `tab` query param, `null` for none. */
+ tab: string | null;
+}
+
+const shortcut = (
+ combo: string,
+ path: string,
+ tab: string | null = null,
+): NavShortcut => ({
+ combo,
+ from: path === '/home' ? '/dashboard' : '/home',
+ path,
+ tab,
+});
+
+/** Global navigation shortcuts and where each one lands. */
+export const NAV_SHORTCUTS: NavShortcut[] = [
+ shortcut('shift+h', '/home'),
+ shortcut('shift+s', '/services'),
+ shortcut('shift+t', '/traces-explorer'),
+ shortcut('shift+t+f', '/traces/funnels'),
+ shortcut('shift+l', '/logs/logs-explorer'),
+ shortcut('shift+l+p', '/logs/pipelines'),
+ shortcut('shift+d', '/dashboard'),
+ shortcut('shift+a', '/alerts'),
+ shortcut('shift+e', '/exceptions'),
+ shortcut('shift+q', '/messaging-queues/overview'),
+ shortcut('shift+m', '/metrics-explorer/summary'),
+ shortcut('shift+m+e', '/metrics-explorer/explorer'),
+ shortcut('shift+g', '/settings'),
+ shortcut('shift+g+i', '/settings/ingestion-settings'),
+ shortcut('shift+g+b', '/settings/billing'),
+ shortcut('shift+g+n', '/alerts', 'Channels'),
+ shortcut('shift+g+k', '/settings/service-accounts'),
+ shortcut('shift+g+r', '/settings/roles'),
+ shortcut('shift+g+m', '/settings/members'),
+];
+
+/** Side-nav items and the pathname each one opens. */
+export const NAV_ITEMS: { key: string; path: string }[] = [
+ { key: 'home', path: '/home' },
+ { key: 'alerts', path: '/alerts' },
+ { key: 'dashboards', path: '/dashboard' },
+ { key: 'services', path: '/services' },
+ { key: 'logs', path: '/logs/logs-explorer' },
+ { key: 'traces', path: '/traces-explorer' },
+ { key: 'metrics', path: '/metrics-explorer/summary' },
+ { key: 'infrastructure', path: '/infrastructure-monitoring/hosts' },
+ { key: 'integrations', path: '/integrations' },
+ { key: 'exceptions', path: '/exceptions' },
+ { key: 'external-apis', path: '/api-monitoring/explorer' },
+ { key: 'ai-observability', path: '/ai-observability/overview' },
+ { key: 'meter-explorer', path: '/meter' },
+ { key: 'messaging-queues', path: '/messaging-queues/overview' },
+ { key: 'service-map', path: '/service-map' },
+];
+
+export type HomeSection = 'alerts' | 'dashboards' | 'services' | 'saved-views';
+
+/** Home checklist step ids, as `container/Home/constants.ts` names them. */
+export type ChecklistStep =
+ | 'SEND_LOGS'
+ | 'SEND_TRACES'
+ | 'SEND_METRICS'
+ | 'SETUP_ALERTS'
+ | 'SETUP_SAVED_VIEWS'
+ | 'SETUP_DASHBOARDS';
+
+/** `checkListStepToPreferenceKeyMap` in `container/Home/constants.ts`. */
+const SKIP_PREFERENCE: Record<ChecklistStep, string> = {
+ SEND_LOGS: 'welcome_checklist_send_logs_skipped',
+ SEND_TRACES: 'welcome_checklist_send_traces_skipped',
+ SEND_METRICS: 'welcome_checklist_send_metrics_skipped',
+ SETUP_ALERTS: 'welcome_checklist_setup_alerts_skipped',
+ SETUP_SAVED_VIEWS: 'welcome_checklist_setup_saved_view_skipped',
+ SETUP_DASHBOARDS: 'welcome_checklist_setup_dashboards_skipped',
+};
+
+// The server registers `welcome_checklist_send_infra_metrics_skipped`, so it
+// rejects this step's name with a 400 and the skip never persists.
+const UNREGISTERED_STEPS: readonly ChecklistStep[] = ['SEND_METRICS'];
+
+const DO_LATER_PREFERENCE = 'welcome_checklist_do_later';
+
+const isPreferencePut =
+ (name: string) =>
+ (response: Response): boolean =>
+ response.request().method() === 'PUT' &&
+ response.url().includes(`/api/v1/user/preferences/${name}`);
+
+export interface Shell {
+ timePicker: TimePicker;
+ users: UsersApi;
+
+ goto(path: string): Promise<void>;
+ reload(): Promise<void>;
+ url(): URL;
+ /** Move the pointer off the side nav, which expands on hover. */
+ parkPointer(): Promise<void>;
+ /** Stub the cloud control plane, open `probe.path` and wait for its marker. */
+ visit(probe: RouteProbe): Promise<void>;
+ pathname(): string;
+ errorBoundary(): Locator;
+ /** Console errors the probe does not name as known. */
+ unexpectedErrors(noise: ConsoleWatch, probe: RouteProbe): string[];
+ /** Failed responses the probe does not name as known. */
+ unexpectedFailures(noise: ConsoleWatch, probe: RouteProbe): string[];
+
+ nav: {
+ root(): Locator;
+ item(key: string): Locator;
+ click(key: string): Promise<void>;
+ pin(key: string): Promise<void>;
+ unpin(key: string): Promise<void>;
+ shortcutKeys(): Promise<string[]>;
+ moreKeys(): Promise<string[]>;
+ toggleMore(): Promise<void>;
+ openManageShortcuts(): Promise<void>;
+ /** The Manage Shortcuts rows, in their current order. */
+ reorderRows(): Locator;
+ reorderRow(key: string): Locator;
+ /** Drag one Manage Shortcuts row onto another (dnd-kit pointer sensor). */
+ dragShortcut(from: string, onto: string): Promise<void>;
+ /** Save the modal. Returns the `nav_shortcuts` value the PUT sent. */
+ saveShortcuts(): Promise<string[]>;
+ isCollapsed(): Promise<boolean>;
+ hover(): Promise<void>;
+ /** Press `shift+b` and wait for the pin to be saved. */
+ toggleWithShortcut(): Promise<void>;
+ /** Reload and wait for the preferences list that overrides the cached pin. */
+ reloadSettled(): Promise<void>;
+ };
+
+ helpMenu: {
+ open(): Promise<void>;
+ item(key: string): Locator;
+ /** Click an external entry and return the URL of the tab it opens. */
+ openExternal(key: string): Promise<string>;
+ };
+
+ userMenu: {
+ open(): Promise<void>;
+ item(testId: string): Locator;
+ signOut(): Promise<void>;
+ };
+
+ keys: {
+ /** Press a `+`-joined chord the way the hotkey hook reads it: on keyup. */
+ press(combo: string): Promise<void>;
+ };
+
+ /** The `UTC …` offset badge in the time picker input. */
+ timezoneBadge(): Locator;
+ /** `PREFERRED_TIMEZONE` from localStorage. */
+ storedTimezone(): Promise<string | null>;
+ /** The My Settings note naming an overridden timezone. */
+ timezoneOverrideNote(): Locator;
+ clearTimezoneOverride(): Promise<void>;
+ /**
+ * Resolves with the next `POST /api/v2/services` whose window is
+ * `minutes` wide, within a minute. Arm before the action that triggers it.
+ */
+ nextServicesWindow(minutes: number): Promise<Request>;
+
+ inviteDialog(): Locator;
+ /** The dashboards list search: a CodeMirror editor, so assert its text. */
+ dashboardsSearch(): Locator;
+ /** Type one letter with Shift held, as a user typing a capital would. */
+ typeShifted(letter: string): Promise<void>;
+
+ home: {
+ goto(): Promise<void>;
+ checklist(): Locator;
+ checklistItem(step: ChecklistStep): Locator;
+ skipButton(step: ChecklistStep): Locator;
+ /** Ids of the steps that still offer a "Skip for now" the server persists. */
+ skippableSteps(): Promise<ChecklistStep[]>;
+ skip(step: ChecklistStep): Promise<void>;
+ doLater(): Promise<void>;
+ checklistButton(): Locator;
+ reopenChecklist(): Promise<void>;
+ section(name: HomeSection): Locator;
+ sectionEntry(name: HomeSection, text: string): Locator;
+ explorerCard(label: string): Locator;
+ /** Clear every `welcome_checklist_*` flag for the current user. */
+ resetChecklistPrefs(): Promise<void>;
+ };
+
+ seedDashboard(title: string): Promise<DashboardSeed>;
+ removeDashboard(id: string): Promise<void>;
+ /**
+ * One alert rule and its channel. Test-scoped on purpose: Home lists the
+ * five most recently updated rules, and sibling workers keep adding more.
+ */
+ seedAlertRule(name: string): Promise<AlertRuleSeed>;
+ /**
+ * A root span just now, slow enough to lead Home's services widget, which
+ * ranks by p99 over the last 30 minutes and so cannot rely on the golden seed.
+ */
+ seedSlowService(service: string): Promise<void>;
+ removeAlertRule(seed: AlertRuleSeed): Promise<void>;
+}
+
+export interface AlertRuleSeed {
+ channelId: string;
+ ruleId: string;
+ ruleName: string;
+}
+
+export function shellDriver(page: Page): Shell {
+ const users = usersApi(page);
+ const timePicker = timePickerDriver(page);
+
+ const keyName = (part: string): string => {
+ const lower = part.toLowerCase();
+ if (lower === 'shift') {
+ return 'Shift';
+ }
+ if (lower.length === 1 && /[a-z]/.test(lower)) {
+ return `Key${lower.toUpperCase()}`;
+ }
+ return part;
+ };
+
+ const navKeysIn = async (section: string): Promise<string[]> => {
+ const ids = await page
+ .getByTestId(section)
+ .locator('[data-testid^="nav-item-"]:not([data-testid^="nav-item-pin-"])')
+ .evaluateAll((nodes) =>
+ nodes.map((node) => node.getAttribute('data-testid') ?? ''),
+ );
+ return ids.map((id) => id.replace(/^nav-item-/, ''));
+ };
+
+ const togglePin = async (key: string): Promise<void> => {
+ const item = shell.nav.item(key);
+ const saved = page.waitForResponse(isPreferencePut('nav_shortcuts'));
+ await item.hover();
+ await item.getByTestId(`nav-item-pin-${key}`).click();
+ expect((await saved).ok()).toBe(true);
+ };
+
+ const shell: Shell = {
+ timePicker,
+ users,
+
+ goto: async (path) => {
+ await page.goto(path);
+ },
+
+ reload: async () => {
+ await page.reload();
+ },
+
+ url: () => new URL(page.url()),
+
+ parkPointer: async () => {
+ const viewport = page.viewportSize() ?? { width: 1280, height: 720 };
+ await page.mouse.move(viewport.width - 10, viewport.height - 10);
+ },
+
+ visit: async (probe) => {
+ await stubCloudOnlyApis(page);
+ await page.goto(probe.path);
+ await expect(probe.marker(page)).toBeVisible();
+ },
+
+ pathname: () => new URL(page.url()).pathname,
+
+ errorBoundary: () => page.getByTestId('error-boundary-fallback'),
+
+ unexpectedErrors: (noise, probe) =>
+ noise.errors.filter(
+ (entry) =>
+ ![...(probe.allowFailures ?? []), ...(probe.allowErrors ?? [])].some(
+ (known) => entry.includes(known),
+ ),
+ ),
+
+ unexpectedFailures: (noise, probe) =>
+ noise.failedResponses.filter(
+ (entry) =>
+ !(probe.allowFailures ?? []).some((known) => entry.includes(known)),
+ ),
+
+ nav: {
+ root: () => page.getByTestId('sidenav'),
+ item: (key) => page.getByTestId(`nav-item-${key}`),
+
+ click: async (key) => {
+ await shell.nav.item(key).click();
+ },
+
+ pin: (key) => togglePin(key),
+ unpin: (key) => togglePin(key),
+
+ shortcutKeys: () => navKeysIn('sidenav-shortcuts'),
+ moreKeys: () => navKeysIn('sidenav-more'),
+
+ toggleMore: async () => {
+ const toggle = page.getByTestId('more-nav-toggle');
+ const before = await toggle.getAttribute('aria-expanded');
+ await toggle.click();
+ await expect(toggle).not.toHaveAttribute('aria-expanded', before ?? '');
+ },
+
+ openManageShortcuts: async () => {
+ await page.getByTestId('manage-shortcuts-btn').click();
+ await expect(
+ page.getByRole('dialog').filter({ hasText: 'Manage Shortcuts' }),
+ ).toBeVisible();
+ // Rows measured mid zoom-in land the drag off target.
+ await expect(
+ page.locator('.ant-modal.ant-zoom-appear, .ant-modal.ant-zoom-enter'),
+ ).toHaveCount(0);
+ },
+
+ reorderRows: () => page.locator('[data-testid^="reorder-item-"]'),
+ reorderRow: (key) => page.getByTestId(`reorder-item-${key}`),
+
+ dragShortcut: async (from, onto) => {
+ const source = await shell.nav.reorderRow(from).boundingBox();
+ const target = await shell.nav.reorderRow(onto).boundingBox();
+ if (!source || !target) {
+ throw new Error(`reorder rows ${from} / ${onto} are not laid out`);
+ }
+ await page.mouse.move(
+ source.x + source.width / 2,
+ source.y + source.height / 2,
+ );
+ await page.mouse.down();
+ // dnd-kit only starts a drag after the pointer has moved, and resolves
+ // the drop target from intermediate positions.
+ await page.mouse.move(
+ source.x + source.width / 2,
+ source.y + source.height / 2 - 5,
+ { steps: 3 },
+ );
+ await page.mouse.move(
+ target.x + target.width / 2,
+ target.y + target.height / 4,
+ { steps: 12 },
+ );
+ await page.mouse.up();
+ },
+
+ saveShortcuts: async () => {
+ const saved = page.waitForResponse(isPreferencePut('nav_shortcuts'));
+ await page.getByTestId('save-changes-btn').click();
+ const response = await saved;
+ expect(response.ok()).toBe(true);
+ return (response.request().postDataJSON() as { value: string[] }).value;
+ },
+
+ toggleWithShortcut: async () => {
+ const saved = page.waitForResponse(isPreferencePut('sidenav_pinned'));
+ await shell.keys.press('shift+b');
+ expect((await saved).ok()).toBe(true);
+ },
+
+ reloadSettled: async () => {
+ const loaded = page.waitForResponse(
+ (response) =>
+ response.request().method() === 'GET' &&
+ /\/api\/v1\/user\/preferences\/?(\?.*)?$/.test(response.url()),
+ );
+ await page.reload();
+ await loaded;
+ },
+
+ isCollapsed: async () =>
+ (await shell.nav.root().getAttribute('data-collapsed')) === 'true',
+
+ hover: async () => {
+ await shell.nav.root().hover();
+ await expect(shell.nav.root()).toHaveAttribute('data-collapsed', 'false');
+ },
+ },
+
+ helpMenu: {
+ open: async () => {
+ await page.getByTestId('help-support-nav-item').click();
+ },
+ item: (key) => page.getByTestId(`help-menu-${key}`),
+ openExternal: async (key) => {
+ // Served empty so the assertion does not depend on the internet.
+ await page
+ .context()
+ .route(/^https:\/\/(signoz\.io|github\.com)\//, (route) =>
+ route.fulfill({ status: 200, contentType: 'text/html', body: '' }),
+ );
+ const opened = page.context().waitForEvent('page');
+ await shell.helpMenu.item(key).click();
+ const tab = await opened;
+ await tab.waitForURL((url) => url.protocol === 'https:');
+ const url = tab.url();
+ await tab.close();
+ return url;
+ },
+ },
+
+ userMenu: {
+ open: async () => {
+ await page.getByTestId('settings-nav-item').click();
+ await expect(page.getByTestId('logout-nav-item')).toBeVisible();
+ },
+ item: (testId) => page.getByTestId(testId),
+ signOut: async () => {
+ await shell.userMenu.open();
+ await page.getByTestId('logout-nav-item').click();
+ await page.waitForURL((url) => url.pathname.startsWith('/login'));
+ },
+ },
+
+ keys: {
+ press: async (combo) => {
+ // Hotkeys are ignored while an input or editor has focus, and several
+ // pages focus one on mount.
+ await page.evaluate(() => {
+ (document.activeElement as HTMLElement | null)?.blur();
+ });
+ const parts = combo.split('+').map(keyName);
+ for (const part of parts) {
+ await page.keyboard.down(part);
+ }
+ for (const part of [...parts].reverse()) {
+ await page.keyboard.up(part);
+ }
+ },
+ },
+
+ // The badge sits in the antd input's suffix, a sibling of the input that
+ // carries the testid, and has no testid of its own.
+ timezoneBadge: () =>
+ page
+ .locator('.ant-input-affix-wrapper', { has: timePicker.input() })
+ .locator('.timezone-badge'),
+
+ storedTimezone: () =>
+ page.evaluate(() => localStorage.getItem('PREFERRED_TIMEZONE')),
+
+ timezoneOverrideNote: () =>
+ page.getByText('Your current timezone is overridden to'),
+
+ clearTimezoneOverride: async () => {
+ await page.getByTestId('timezone-clear-override').click();
+ await expect(shell.timezoneOverrideNote()).toHaveCount(0);
+ },
+
+ nextServicesWindow: (minutes) =>
+ page.waitForRequest((request) => {
+ if (
+ request.method() !== 'POST' ||
+ new URL(request.url()).pathname !== '/api/v2/services'
+ ) {
+ return false;
+ }
+ // `start` and `end` are nanosecond strings.
+ const body = request.postDataJSON() as { start: string; end: string };
+ const spanMinutes = (Number(body.end) - Number(body.start)) / 6e10;
+ return Math.abs(spanMinutes - minutes) <= 1;
+ }),
+
+ inviteDialog: () => page.getByRole('dialog', { name: 'Invite Team Members' }),
+
+ dashboardsSearch: () => page.getByPlaceholder('Filter views by name'),
+
+ typeShifted: async (letter) => {
+ await page.keyboard.down('Shift');
+ await page.keyboard.press(`Key${letter.toUpperCase()}`);
+ await page.keyboard.up('Shift');
+ },
+
+ home: {
+ goto: async () => {
+ await page.goto('/home');
+ await expect(page.getByTestId('home-page')).toBeVisible();
+ },
+
+ checklist: () => page.getByTestId('home-checklist-card'),
+ checklistItem: (step) =>
+ shell.home.checklist().getByTestId(`checklist-item-${step}`),
+ skipButton: (step) =>
+ shell.home.checklist().getByTestId(`checklist-skip-${step}`),
+
+ skippableSteps: async () => {
+ const read = async (): Promise<ChecklistStep[]> => {
+ const ids = await shell.home
+ .checklist()
+ .locator('[data-testid^="checklist-skip-"]')
+ .evaluateAll((nodes) =>
+ nodes.map((node) => node.getAttribute('data-testid') ?? ''),
+ );
+ return ids
+ .map((id) => id.replace(/^checklist-skip-/, '') as ChecklistStep)
+ .filter((step) => !UNREGISTERED_STEPS.includes(step));
+ };
+ // Steps complete one by one as the widget queries resolve, with no
+ // loading marker, so the list is read once it stops changing. The poll
+ // runs its first read at once, so that read only sets the baseline.
+ let previous: string | undefined;
+ await expect
+ .poll(
+ async () => {
+ const current = (await read()).join();
+ const settled = current === previous;
+ previous = current;
+ return settled;
+ },
+ { intervals: [1_000], timeout: 15_000 },
+ )
+ .toBe(true);
+ return read();
+ },
+
+ skip: async (step) => {
+ const saved = page.waitForResponse(isPreferencePut(SKIP_PREFERENCE[step]));
+ // A step's actions render only while it is hovered.
+ await shell.home.checklistItem(step).hover();
+ // The decorative checklist background covers the button at 1280px.
+ await shell.home.skipButton(step).dispatchEvent('click');
+ expect((await saved).ok()).toBe(true);
+ },
+
+ doLater: async () => {
+ const saved = page.waitForResponse(isPreferencePut(DO_LATER_PREFERENCE));
+ await page.getByTestId('checklist-do-later-btn').click();
+ expect((await saved).ok()).toBe(true);
+ },
+
+ checklistButton: () => page.getByTestId('welcome-checklist-btn'),
+
+ reopenChecklist: async () => {
+ await shell.home.checklistButton().click();
+ await expect(
+ page.locator('.welcome-checklist-popover').getByText('Completed'),
+ ).toBeVisible();
+ },
+
+ // The widget cards are `periscope/components/Card`, which forwards no
+ // testid, so the card is reached from the testid on its header.
+ section: (name) =>
+ page
+ .locator('.home-data-card')
+ .filter({ has: page.getByTestId(`home-section-${name}`) }),
+ sectionEntry: (name, text) =>
+ page
+ .locator('.home-data-card')
+ .filter({ has: page.getByTestId(`home-section-${name}`) })
+ .getByText(text, { exact: true }),
+
+ explorerCard: (label) => page.getByRole('button', { name: label }),
+
+ resetChecklistPrefs: async () => {
+ for (const name of [
+ DO_LATER_PREFERENCE,
+ ...(Object.keys(SKIP_PREFERENCE) as ChecklistStep[])
+ .filter((step) => !UNREGISTERED_STEPS.includes(step))
+ .map((step) => SKIP_PREFERENCE[step]),
+ ]) {
+ await users.setPreference(name, false);
+ }
+ },
+ },
+
+ seedDashboard: (title) => createDashboard(page, title),
+ removeDashboard: (id) => deleteViaApi(page, id),
+
+ seedAlertRule: async (name) => {
+ const seed = alertSeeder(page);
+ const channel = await seed.channel(`${name}-ch`);
+ const [ruleId] = await seed.rules({
+ count: 1,
+ channelName: channel.name,
+ namePrefix: name,
+ });
+ return { channelId: channel.id, ruleId, ruleName: `${name}-00` };
+ },
+
+ seedSlowService: (service) =>
+ seedTracesViaSeeder(page.request, [
+ {
+ timestamp: new Date(Date.now() - 5_000).toISOString(),
+ trace_id: randomTraceId(),
+ span_id: randomSpanId(),
+ name: 'GET /home',
+ kind: 2,
+ duration: 'PT60S',
+ resources: { 'service.name': service },
+ },
+ ]),
+
+ removeAlertRule: async ({ channelId, ruleId }) => {
+ const seed = alertSeeder(page);
+ await seed.deleteRules([ruleId]);
+ await seed.deleteChannel(channelId);
+ },
+ };
+
+ return shell;
+}
+
+/** A logged-out visitor, for the redirects only a guest sees. */
+export interface ShellGuest {
+ goto(path: string): Promise<void>;
+ pathname(): string;
+ emailInput(): Locator;
+}
+
+export function shellGuestDriver(page: Page): ShellGuest {
+ return {
+ goto: async (path) => {
+ await page.goto(path);
+ },
+ pathname: () => new URL(page.url()).pathname,
+ emailInput: () => page.getByTestId('email'),
+ };
+}
+
+export const withShell: Layer<{ shell: Shell }> = driver('shell', ({ page }) =>
+ shellDriver(page),
+);
+
+export const withShellGuest: Layer<{ guest: ShellGuest }> = guestDriver(
+ 'guest',
+ ({ page }) => shellGuestDriver(page),
+);
+
+/** The app-shell `test`. */
+export const test = withShellGuest(withShell(kit));
+export { ADMIN, expect } from './kit';
diff --git a/tests/e2e/drivers/spans.ts b/tests/e2e/drivers/spans.ts
new file mode 100644
index 0000000000..fab042f394
--- /dev/null
+++ b/tests/e2e/drivers/spans.ts
@@ -0,0 +1,244 @@
+import { randomSpanId, randomTraceId, type SeederSpan } from './traces';
+
+/**
+ * Pure span builders for the seeder. No page, no request: a feature seed builds
+ * its spans here and posts them with `seedTracesViaSeeder`.
+ *
+ * Timestamps are relative to now (`agoMs`), because every page in scope opens on
+ * a 15-30 minute window and the golden dataset sits at its edge.
+ */
+
+export const SPAN_KIND = {
+ internal: 1,
+ server: 2,
+ client: 3,
+ producer: 4,
+ consumer: 5,
+} as const;
+
+export const STATUS = { unset: 0, ok: 1, error: 2 } as const;
+
+/** `e2e-<feature>-w<worker>-<ms>`: the prefix every seeded name carries. */
+export function stamp(feature: string, workerIndex: number): string {
+ return `e2e-${feature}-w${workerIndex}-${Date.now()}`;
+}
+
+export interface SpanOptions {
+ service: string;
+ name: string;
+ kind?: number;
+ status?: number;
+ statusMessage?: string;
+ durationMs?: number;
+ /** Start time, in ms before now. */
+ agoMs?: number;
+ attrs?: Record<string, unknown>;
+ /** Extra resource attributes; `service.name` is set from `service`. */
+ resources?: Record<string, string>;
+ events?: SeederSpan['events'];
+}
+
+const DEFAULT_AGO_MS = 30_000;
+
+function isoDuration(ms: number): string {
+ return `PT${(ms / 1000).toFixed(6)}S`;
+}
+
+function build(
+ opts: SpanOptions,
+ traceId: string,
+ parentSpanId: string | undefined,
+ startMs: number,
+): SeederSpan {
+ const span: SeederSpan = {
+ timestamp: new Date(startMs).toISOString(),
+ trace_id: traceId,
+ span_id: randomSpanId(),
+ name: opts.name,
+ kind: opts.kind ?? SPAN_KIND.server,
+ status_code: opts.status ?? STATUS.ok,
+ duration: isoDuration(opts.durationMs ?? 100),
+ resources: { ...opts.resources, 'service.name': opts.service },
+ attributes: opts.attrs ?? {},
+ };
+ if (opts.statusMessage) {
+ span.status_message = opts.statusMessage;
+ }
+ if (parentSpanId) {
+ span.parent_span_id = parentSpanId;
+ }
+ if (opts.events) {
+ span.events = opts.events;
+ }
+ return span;
+}
+
+/** A root span in a fresh trace. Defaults to a SERVER span, OK, 100 ms. */
+export function rootSpan(opts: SpanOptions): SeederSpan {
+ return build(
+ opts,
+ randomTraceId(),
+ undefined,
+ Date.now() - (opts.agoMs ?? DEFAULT_AGO_MS),
+ );
+}
+
+/**
+ * A child of `parent` in the same trace. `offsetMs` is its start after the
+ * parent's start; `agoMs` is ignored.
+ */
+export function childSpan(
+ parent: SeederSpan,
+ opts: SpanOptions & { offsetMs?: number },
+): SeederSpan {
+ return build(
+ { kind: SPAN_KIND.internal, ...opts },
+ parent.trace_id,
+ parent.span_id,
+ Date.parse(parent.timestamp) + (opts.offsetMs ?? 10),
+ );
+}
+
+export interface ClientCallOptions {
+ service: string;
+ /** Full URL, e.g. `https://api.example.com/v1/items`. */
+ url: string;
+ method?: string;
+ /** HTTP status code attribute. */
+ httpStatus?: number;
+ status?: number;
+ statusMessage?: string;
+ durationMs?: number;
+ agoMs?: number;
+}
+
+/**
+ * A CLIENT span to an external host, the shape API monitoring reads. The fixture
+ * derives `external_http_url` from `http.url`; `net.peer.name` is not mapped.
+ */
+export function clientCall(opts: ClientCallOptions): SeederSpan {
+ const url = new URL(opts.url);
+ const method = opts.method ?? 'GET';
+ return rootSpan({
+ service: opts.service,
+ name: `${method} ${url.pathname}`,
+ kind: SPAN_KIND.client,
+ status: opts.status,
+ statusMessage: opts.statusMessage,
+ durationMs: opts.durationMs,
+ agoMs: opts.agoMs,
+ attrs: {
+ 'http.url': opts.url,
+ 'http.method': method,
+ 'http.host': url.host,
+ 'http.status_code': opts.httpStatus ?? 200,
+ },
+ });
+}
+
+export interface KafkaPairOptions {
+ topic: string;
+ partition: string;
+ group: string;
+ producer: string;
+ consumer: string;
+ consumerStatus?: number;
+ bodySize?: number;
+ agoMs?: number;
+}
+
+/** A kafka PRODUCER span and its CONSUMER child, in one trace. */
+export function kafkaPair(opts: KafkaPairOptions): SeederSpan[] {
+ const messaging = {
+ 'messaging.system': 'kafka',
+ 'messaging.destination.name': opts.topic,
+ 'messaging.destination.partition.id': opts.partition,
+ 'messaging.message.body.size': opts.bodySize ?? 512,
+ };
+ const producer = rootSpan({
+ service: opts.producer,
+ name: `${opts.topic} publish`,
+ kind: SPAN_KIND.producer,
+ durationMs: 20,
+ agoMs: opts.agoMs,
+ attrs: { ...messaging, 'messaging.client_id': `${opts.producer}-client` },
+ resources: { 'service.instance.id': `${opts.producer}-0` },
+ });
+ const consumer = childSpan(producer, {
+ service: opts.consumer,
+ name: `${opts.topic} process`,
+ kind: SPAN_KIND.consumer,
+ status: opts.consumerStatus,
+ durationMs: 40,
+ offsetMs: 50,
+ attrs: {
+ ...messaging,
+ 'messaging.kafka.consumer.group': opts.group,
+ 'messaging.client_id': `${opts.consumer}-client`,
+ },
+ resources: { 'service.instance.id': `${opts.consumer}-0` },
+ });
+ return [producer, consumer];
+}
+
+export interface CeleryTaskOptions {
+ service: string;
+ task: string;
+ state: 'SUCCESS' | 'FAILURE' | 'RETRY';
+ hostname: string;
+ agoMs?: number;
+}
+
+/** A celery worker span (`run/<task>`), status 2 when the state is FAILURE. */
+export function celeryTask(opts: CeleryTaskOptions): SeederSpan {
+ return rootSpan({
+ service: opts.service,
+ name: `run/${opts.task}`,
+ kind: SPAN_KIND.consumer,
+ status: opts.state === 'FAILURE' ? STATUS.error : STATUS.ok,
+ durationMs: 200,
+ agoMs: opts.agoMs,
+ attrs: {
+ 'messaging.destination': 'celery',
+ 'celery.task_name': opts.task,
+ 'celery.state': opts.state,
+ 'celery.hostname': opts.hostname,
+ 'celery.action': 'run',
+ },
+ });
+}
+
+export interface ExceptionSpanOptions {
+ service: string;
+ type: string;
+ message: string;
+ stack: string;
+ name?: string;
+ agoMs?: number;
+}
+
+/**
+ * A SERVER span with status 2 and an `exception` event. The seeder writes the
+ * event to the error index, which the exceptions pages read.
+ */
+export function exceptionSpan(opts: ExceptionSpanOptions): SeederSpan {
+ const startMs = Date.now() - (opts.agoMs ?? DEFAULT_AGO_MS);
+ return rootSpan({
+ service: opts.service,
+ name: opts.name ?? 'GET /fail',
+ status: STATUS.error,
+ agoMs: opts.agoMs,
+ events: [
+ {
+ name: 'exception',
+ timestamp: new Date(startMs + 10).toISOString(),
+ attributes: {
+ 'exception.type': opts.type,
+ 'exception.message': opts.message,
+ 'exception.stacktrace': opts.stack,
+ 'exception.escaped': 'false',
+ },
+ },
+ ],
+ });
+}
diff --git a/tests/e2e/drivers/sso.ts b/tests/e2e/drivers/sso.ts
new file mode 100644
index 0000000000..590c306162
--- /dev/null
+++ b/tests/e2e/drivers/sso.ts
@@ -0,0 +1,215 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { apiDriver } from './api';
+import { driver, kit, type Layer } from './kit';
+
+// ─── Constants ───────────────────────────────────────────────────────────
+
+export const ORG_SETTINGS_PATH = '/settings/org-settings';
+
+// ─── Types ─────────────────────────────────────────────────────────────────
+
+export interface GoogleAuthDomainSeed {
+ /** Domain name (e.g. `sso-edit.example.com`). Keep unique per test. */
+ name: string;
+ /** Enforce-SSO flag. Defaults to false. */
+ enabled?: boolean;
+ clientId?: string;
+ clientSecret?: string;
+ /**
+ * Enables Google Workspace group fetching. The backend then requires
+ * `serviceAccountJson` and `domainToAdminEmail`, and only with it may
+ * `allowedGroups` be set.
+ */
+ fetchGroups?: boolean;
+ serviceAccountJson?: string;
+ domainToAdminEmail?: Record<string, string>;
+ allowedGroups?: string[];
+ roleMapping?: {
+ defaultRole?: string;
+ groupMappings?: Record<string, string>;
+ useRoleAttribute?: boolean;
+ };
+}
+
+// ─── API helpers ─────────────────────────────────────────────────────────
+
+/**
+ * Seed a Google auth domain via POST /api/v2/auth_domains. Returns the new
+ * domain ID. Pair with {@link deleteAuthDomainByNameViaApi} for cleanup.
+ */
+async function createGoogleAuthDomainViaApi(
+ page: Page,
+ seed: GoogleAuthDomainSeed,
+): Promise<string> {
+ const spec: Record<string, unknown> = {
+ clientId: seed.clientId ?? 'e2e-client-id.apps.googleusercontent.com',
+ clientSecret: seed.clientSecret ?? 'e2e-client-secret',
+ fetchGroups: seed.fetchGroups ?? false,
+ insecureSkipEmailVerified: false,
+ };
+ if (seed.serviceAccountJson) {
+ spec.serviceAccountJson = seed.serviceAccountJson;
+ }
+ if (seed.domainToAdminEmail) {
+ spec.domainToAdminEmail = seed.domainToAdminEmail;
+ }
+ if (seed.allowedGroups) {
+ spec.allowedGroups = seed.allowedGroups;
+ }
+
+ return apiDriver(page).create('/api/v2/auth_domains', {
+ name: seed.name,
+ enabled: seed.enabled ?? false,
+ config: { kind: 'google', spec },
+ roleMapping: seed.roleMapping,
+ });
+}
+
+/**
+ * Delete any auth domain named `name`; a no-op when absent. Doubles as the
+ * leftover guard before seeding (domain names are unique per org, so a
+ * crashed earlier run would otherwise make the seed conflict).
+ */
+async function deleteAuthDomainByNameViaApi(
+ page: Page,
+ name: string,
+): Promise<void> {
+ const api = apiDriver(page);
+ const body = await api.get<{ data: { id: string; name: string }[] | null }>(
+ '/api/v2/auth_domains',
+ );
+ const match = (body.data ?? []).find((domain) => domain.name === name);
+ if (match) {
+ await api.tryDel(`/api/v2/auth_domains/${match.id}`);
+ }
+}
+
+// ─── Navigation ────────────────────────────────────────────────────────────
+
+/** Open org settings and wait for the Authenticated Domains section. */
+async function gotoAuthDomains(page: Page): Promise<void> {
+ await page.goto(ORG_SETTINGS_PATH);
+ await expect(page.getByTestId('auth-domain-title')).toBeVisible();
+}
+
+/** Locate the list row for the domain named `name`. */
+async function findAuthDomainRow(page: Page, name: string): Promise<Locator> {
+ const row = page.getByTestId(`auth-domain-row-${name}`);
+ await row.waitFor({ state: 'attached' });
+ return row;
+}
+
+/** Open the Configure (edit) modal for the domain row named `name`. */
+async function openConfigureAuthDomain(
+ page: Page,
+ name: string,
+): Promise<void> {
+ const row = await findAuthDomainRow(page, name);
+ await row.getByTestId('auth-domain-configure').click();
+ await expect(page.getByTestId('auth-domain-form')).toBeVisible();
+}
+
+// ─── The driver ──────────────────────────────────────────────────────────────
+
+export interface SsoForm {
+ root(): Locator;
+ googleDomain(): Locator;
+ googleClientId(): Locator;
+ googleClientSecret(): Locator;
+ save(): Locator;
+}
+
+export interface SsoRoleMapping {
+ header(): Locator;
+ rows(): Locator;
+ groupName(index: number): Locator;
+ remove(index: number): Locator;
+}
+
+export interface SsoWorkspaceGroups {
+ header(): Locator;
+ fetchGroups(): Locator;
+ /** The chosen allowed groups, one per antd select item. */
+ allowedGroups(): Locator;
+}
+
+export interface Sso {
+ /** Seed a Google auth domain. Returns its id. */
+ createGoogleDomain(seed: GoogleAuthDomainSeed): Promise<string>;
+ /**
+ * Delete any auth domain named `name`; a no-op when absent. Doubles as the
+ * leftover guard before seeding, since domain names are unique per org and a
+ * crashed earlier run would otherwise make the seed conflict.
+ */
+ deleteDomainByName(name: string): Promise<void>;
+ goto(): Promise<void>;
+ title(): Locator;
+ addButton(): Locator;
+ /** The provider card's Configure button in the add-domain modal. */
+ configureProvider(provider: string): Locator;
+ row(name: string): Locator;
+ configureButton(name: string): Locator;
+ enforceSsoToggle(name: string): Locator;
+ deleteButton(name: string): Locator;
+ deleteConfirmButton(): Locator;
+ openConfigure(name: string): Promise<void>;
+ form: SsoForm;
+ roleMapping: SsoRoleMapping;
+ workspaceGroups: SsoWorkspaceGroups;
+ toast(text: string): Locator;
+}
+
+export function ssoDriver(page: Page): Sso {
+ const row = (name: string): Locator =>
+ page.getByTestId(`auth-domain-row-${name}`);
+ const roleMappingRows = (): Locator => page.getByTestId('role-mapping-row');
+
+ return {
+ createGoogleDomain: (seed) => createGoogleAuthDomainViaApi(page, seed),
+ deleteDomainByName: (name) => deleteAuthDomainByNameViaApi(page, name),
+ goto: () => gotoAuthDomains(page),
+ title: () => page.getByTestId('auth-domain-title'),
+ addButton: () => page.getByTestId('auth-domain-add'),
+ configureProvider: (provider) =>
+ page.getByTestId(`authn-provider-configure-${provider}`),
+ row,
+ configureButton: (name) => row(name).getByTestId('auth-domain-configure'),
+ enforceSsoToggle: (name) => row(name).getByTestId('auth-domain-enforce-sso'),
+ deleteButton: (name) => row(name).getByTestId('auth-domain-delete'),
+ deleteConfirmButton: () => page.getByTestId('auth-domain-delete-confirm'),
+ openConfigure: (name) => openConfigureAuthDomain(page, name),
+ form: {
+ root: () => page.getByTestId('auth-domain-form'),
+ googleDomain: () => page.getByTestId('google-auth-domain'),
+ googleClientId: () => page.getByTestId('google-auth-client-id'),
+ googleClientSecret: () => page.getByTestId('google-auth-client-secret'),
+ save: () => page.getByTestId('auth-domain-save'),
+ },
+ roleMapping: {
+ header: () => page.getByTestId('role-mapping-header'),
+ rows: roleMappingRows,
+ groupName: (index) =>
+ roleMappingRows().nth(index).getByTestId('role-mapping-group-name'),
+ remove: (index) =>
+ roleMappingRows().nth(index).getByTestId('role-mapping-remove'),
+ },
+ workspaceGroups: {
+ header: () => page.getByTestId('google-auth-workspace-groups-header'),
+ fetchGroups: () => page.getByRole('checkbox', { name: 'Fetch Groups' }),
+ allowedGroups: () =>
+ page
+ .getByTestId('google-auth-allowed-groups')
+ .locator('.ant-select-selection-item'),
+ },
+ toast: (text) => page.getByText(text),
+ };
+}
+
+export const withSso: Layer<{ sso: Sso }> = driver('sso', ({ page }) =>
+ ssoDriver(page),
+);
+
+/** The SSO `test`. */
+export const test = withSso(kit);
+export { expect } from './kit';
diff --git a/tests/e2e/drivers/storage.ts b/tests/e2e/drivers/storage.ts
new file mode 100644
index 0000000000..bb191f6731
--- /dev/null
+++ b/tests/e2e/drivers/storage.ts
@@ -0,0 +1,84 @@
+import type { Page } from '@playwright/test';
+
+/** The app's persisted table state, and the one-shot reset specs need. */
+
+const COLUMN_STORAGE_PREFIX = '@signoz/table-columns/';
+
+export interface ColumnState {
+ hiddenColumnIds?: string[];
+ columnOrder?: string[];
+ columnSizing?: Record<string, number>;
+}
+
+export function columnStorageKey(tableKey: string): string {
+ return `${COLUMN_STORAGE_PREFIX}${tableKey}`;
+}
+
+export async function readJson<T>(page: Page, key: string): Promise<T | null> {
+ const raw = await page.evaluate((k) => localStorage.getItem(k), key);
+ return raw ? (JSON.parse(raw) as T) : null;
+}
+
+export async function writeJson(
+ page: Page,
+ key: string,
+ value: unknown,
+): Promise<void> {
+ await page.evaluate(({ k, v }) => localStorage.setItem(k, JSON.stringify(v)), {
+ k: key,
+ v: value,
+ });
+}
+
+export async function writeRaw(
+ page: Page,
+ key: string,
+ raw: string,
+): Promise<void> {
+ await page.evaluate(({ k, v }) => localStorage.setItem(k, v), {
+ k: key,
+ v: raw,
+ });
+}
+
+/**
+ * Read a zustand-persisted store.
+ *
+ * The `persist` middleware writes a `{ state, version }` envelope, so reading
+ * the keys off the top level silently yields `undefined` for all of them.
+ * `useColumnStore` writes its own JSON directly, which is why
+ * {@link ColumnState} needs no unwrapping.
+ */
+export async function readPersisted<T>(
+ page: Page,
+ key: string,
+): Promise<Partial<T>> {
+ const parsed = await readJson<{ state?: T } & T>(page, key);
+ return parsed ? (parsed.state ?? parsed) : {};
+}
+
+/** Marker that makes {@link resetKeys} clear exactly once. */
+const RESET_MARKER = '__e2e_storage_reset';
+
+/**
+ * Clear `keys` once, before the first navigation.
+ *
+ * The "once" is load-bearing: `addInitScript` re-runs before app code on
+ * **every** navigation, so an unguarded version also wipes state on
+ * `page.reload()` — which silently breaks exactly the scenarios that assert
+ * persistence survives a reload.
+ */
+export async function resetKeys(page: Page, keys: string[]): Promise<void> {
+ await page.addInitScript(
+ ({ marker, items }) => {
+ if (sessionStorage.getItem(marker)) {
+ return;
+ }
+ sessionStorage.setItem(marker, '1');
+ for (const key of items) {
+ localStorage.removeItem(key);
+ }
+ },
+ { marker: RESET_MARKER, items: keys },
+ );
+}
diff --git a/tests/e2e/drivers/tanstack.ts b/tests/e2e/drivers/tanstack.ts
new file mode 100644
index 0000000000..ae948ee38d
--- /dev/null
+++ b/tests/e2e/drivers/tanstack.ts
@@ -0,0 +1,376 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { allowFor, SEEDED_DATA_TIMEOUT, SEEDED_TEST_BUDGET } from './kit';
+import {
+ columnStorageKey,
+ readJson,
+ resetKeys,
+ writeJson,
+ writeRaw,
+ type ColumnState,
+} from './storage';
+
+/**
+ * The TanStack table, driven the same way everywhere it is used: the alert-rules
+ * list, the infra-monitoring lists and their expanded rows.
+ *
+ * Two details are load-bearing and were paid for in flake:
+ *
+ * - Locators are table-scoped. A row's name also appears in the quick-filter
+ * rail, and an unscoped text locator clicks the filter instead of the row.
+ * - Skeleton rows carry the same testids as real ones, so waiting only for "a
+ * row exists" samples the placeholder and reads its key back as `unknown`.
+ */
+
+export interface SortState {
+ columnName: string;
+ order: string;
+}
+
+export interface TanstackOptions {
+ /**
+ * Row testid prefix, when the table passes `getRowTestId`. Rows are matched
+ * on it so an expanded group's nested rows, which repeat the pattern, stay
+ * out of the outer row set. Omit for tables that render plain rows.
+ */
+ rowTestIdPrefix?: string;
+ /** `useColumnStore` table key, unprefixed. Enables the column-state methods. */
+ tableKey?: string;
+ /** Extra localStorage keys {@link Tanstack.reset} clears alongside it. */
+ extraStorageKeys?: string[];
+ /** Toolbar "Group by" select, when the feature has one. */
+ groupBySelectTestId?: string;
+}
+
+export interface Tanstack {
+ table(): Locator;
+ rows(): Locator;
+ row(key: string): Locator;
+ rowKeys(): Promise<string[]>;
+ headers(): Promise<string[]>;
+ headerCell(columnId: string): Locator;
+ sortButton(columnId: string): Locator;
+ columnActions(columnId: string): Locator;
+
+ waitForRows(): Promise<void>;
+ waitForRow(key: string): Promise<void>;
+ expectColumns(headers: string[]): Promise<void>;
+ expectRowCount(count: number): Promise<void>;
+ expectFirstPage(): Promise<void>;
+
+ sortBy(columnId: string): Promise<void>;
+ sortState(): SortState | null;
+ rawOrderBy(): string | null;
+ dragColumn(columnId: string, ontoColumnId: string): Promise<void>;
+ resizeColumn(columnId: string, deltaX: number): Promise<number>;
+
+ totalCount(): Locator;
+ pageSize(size: number): Promise<void>;
+ gotoPage(pageNumber: number): Promise<void>;
+ paginationBar(): Locator;
+
+ groupBy(attribute: string): Promise<void>;
+ clearGrouping(): Promise<void>;
+ groupByFromUrl(): string[];
+
+ columnState(): Promise<ColumnState>;
+ setColumnState(state: ColumnState): Promise<void>;
+ setRawColumnState(raw: string): Promise<void>;
+ /** Clear persisted table state once, before the first navigation. */
+ reset(): Promise<void>;
+}
+
+const PAGINATION = {
+ totalCount: 'pagination-total-count',
+ pageSize: 'pagination-page-size',
+} as const;
+
+/**
+ * `TanStackHeaderRow` builds these labels and the header `title` attribute from
+ * the column **id**, capitalised — not from the visible header text, whose
+ * string branch never applies when `column.header` is a render function.
+ */
+export function headerTitleAttr(columnId: string): string {
+ return columnId.replace(/^\w/, (character) => character.toUpperCase());
+}
+
+export function dragHandleLabel(columnId: string): string {
+ return `Drag ${columnId} column`;
+}
+
+export function columnActionsLabel(columnId: string): string {
+ return `Column actions for ${headerTitleAttr(columnId)}`;
+}
+
+/** A bounding box, or a failure naming what never rendered. */
+async function boxOf(
+ locator: Locator,
+ what: string,
+): Promise<{ x: number; y: number; width: number; height: number }> {
+ const box = await locator.boundingBox();
+ if (!box) {
+ throw new Error(`${what} has no bounding box — it is not rendered`);
+ }
+ return box;
+}
+
+export function tanstackDriver(
+ page: Page,
+ options: TanstackOptions = {},
+): Tanstack {
+ const table = (): Locator => page.locator('table').first();
+ const headerCells = (): Locator => table().locator('thead th');
+ const rows = (): Locator =>
+ options.rowTestIdPrefix
+ ? table().locator(`> tbody > tr[data-testid^="${options.rowTestIdPrefix}"]`)
+ : table().locator('> tbody > tr');
+
+ const headerCell = (columnId: string): Locator =>
+ headerCells()
+ .filter({ has: page.locator(`[title="${headerTitleAttr(columnId)}"]`) })
+ .first();
+
+ const storageKey = options.tableKey
+ ? columnStorageKey(options.tableKey)
+ : null;
+
+ const requireStorage = (): string => {
+ if (!storageKey) {
+ throw new Error('tanstackDriver needs a tableKey for column state');
+ }
+ return storageKey;
+ };
+
+ const driver: Tanstack = {
+ table,
+ rows,
+ row: (key) => page.getByTestId(`${options.rowTestIdPrefix ?? ''}${key}`),
+ headerCell,
+ totalCount: () => page.getByTestId(PAGINATION.totalCount),
+ paginationBar: () => page.locator('[class*="paginationContainer"]').first(),
+
+ sortButton: (columnId) =>
+ headerCell(columnId).locator('button.tanstack-header-title'),
+
+ columnActions: (columnId) =>
+ page.getByRole('button', { name: columnActionsLabel(columnId) }),
+
+ headers: async () => {
+ const titles = await headerCells()
+ .locator('.tanstack-header-title')
+ .allInnerTexts();
+ return titles.map((title) => title.trim()).filter(Boolean);
+ },
+
+ rowKeys: async () => {
+ const ids = await rows().evaluateAll((elements) =>
+ elements.map((element) => element.getAttribute('data-testid') ?? ''),
+ );
+ const prefix = options.rowTestIdPrefix ?? '';
+ return ids.map((id) => (prefix ? id.replace(prefix, '') : id));
+ },
+
+ waitForRows: async () => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(rows().first()).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ // Skeletons carry the same testids as real rows, so row keys read back
+ // as placeholders while they are up. Short budget: the data has arrived
+ // by now and the skeletons are one render away.
+ await expect(table().locator('.ant-skeleton')).toHaveCount(0, {
+ timeout: 10_000,
+ });
+ },
+
+ waitForRow: async (key) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ await expect(driver.row(key)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ },
+
+ expectColumns: async (headers) => {
+ await expect(async () => {
+ expect(await driver.headers()).toEqual(headers);
+ }).toPass();
+ },
+
+ expectRowCount: async (count) => {
+ await expect(rows()).toHaveCount(count);
+ },
+
+ expectFirstPage: async () => {
+ await expect(async () => {
+ const value = new URL(page.url()).searchParams.get('page');
+ expect(value === null || value === '1').toBe(true);
+ }).toPass();
+ },
+
+ sortBy: async (columnId) => {
+ // Resolve on the URL, not on a re-render: sorting by a column the data
+ // has no value for empties the list, which swaps the table for the empty
+ // state and takes the header with it. `orderBy` is written either way.
+ const before = new URL(page.url()).searchParams.get('orderBy');
+ await driver.sortButton(columnId).click();
+ await expect(async () => {
+ expect(new URL(page.url()).searchParams.get('orderBy')).not.toBe(before);
+ }).toPass();
+ },
+
+ rawOrderBy: () => new URL(page.url()).searchParams.get('orderBy'),
+
+ sortState: () => {
+ const raw = driver.rawOrderBy();
+ if (!raw) {
+ return null;
+ }
+ try {
+ return JSON.parse(raw) as SortState;
+ } catch {
+ // "unsorted" and "the app wrote something unparseable" are different
+ // outcomes, and one scenario deep-links a malformed value on purpose.
+ throw new Error(
+ `orderBy is not decodable JSON — got \`${raw.slice(0, 200)}\``,
+ );
+ }
+ },
+
+ dragColumn: async (columnId, ontoColumnId) => {
+ const grip = page.getByRole('button', { name: dragHandleLabel(columnId) });
+ await grip.scrollIntoViewIfNeeded();
+ const from = await boxOf(grip, `${columnId} drag grip`);
+ const to = await boxOf(headerCell(ontoColumnId), `${ontoColumnId} header`);
+
+ await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);
+ await page.mouse.down();
+ // dnd-kit only starts a drag past its activation distance, so a single
+ // jump from grip to target is swallowed.
+ await page.mouse.move(
+ from.x + from.width / 2 + 12,
+ from.y + from.height / 2,
+ { steps: 4 },
+ );
+ await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, {
+ steps: 20,
+ });
+ await page.mouse.move(to.x + to.width / 2 + 2, to.y + to.height / 2, {
+ steps: 2,
+ });
+ await page.mouse.up();
+ },
+
+ resizeColumn: async (columnId, deltaX) => {
+ const cell = headerCell(columnId);
+ const before = await boxOf(cell, `${columnId} header`);
+ await cell.locator('[title="Drag to resize column"]').hover();
+ await page.mouse.down();
+ await page.mouse.move(
+ before.x + before.width + deltaX,
+ before.y + before.height / 2,
+ { steps: 12 },
+ );
+ await page.mouse.up();
+
+ // A quarter of the requested travel, in the requested direction: the
+ // table clamps to a min width and rounds, so demanding the full delta is
+ // flaky, while an unsigned comparison would pass on a no-op shrink.
+ await expect(async () => {
+ const after = await boxOf(cell, `${columnId} header`);
+ if (deltaX >= 0) {
+ expect(after.width).toBeGreaterThan(before.width + deltaX / 4);
+ } else {
+ expect(after.width).toBeLessThan(before.width + deltaX / 4);
+ }
+ }).toPass();
+ return (await boxOf(cell, `${columnId} header`)).width;
+ },
+
+ pageSize: async (size) => {
+ await page.getByTestId(PAGINATION.pageSize).click();
+ // The viewport-derived size is labelled `Auto (N)` instead of `N`.
+ await page
+ .getByRole('option', { name: new RegExp(`^(Auto \\()?${size}\\)?$`) })
+ .click();
+ await expect(page).toHaveURL(new RegExp(`pageSize=${size}\\b`));
+ },
+
+ gotoPage: async (pageNumber) => {
+ // The pagination component exposes no testids; its buttons are reachable
+ // by accessible name. Scoped to the bar so a number elsewhere on the page
+ // cannot resolve into a strict-mode violation.
+ await driver
+ .paginationBar()
+ .getByRole('button', { name: String(pageNumber), exact: true })
+ .click();
+ await expect(page).toHaveURL(new RegExp(`page=${pageNumber}\\b`));
+ },
+
+ groupBy: async (attribute) => {
+ if (!options.groupBySelectTestId) {
+ throw new Error('tanstackDriver needs a groupBySelectTestId to group');
+ }
+ const select = page.getByTestId(options.groupBySelectTestId);
+ await expect(select).toBeVisible();
+ // antd Select: the search input is readonly until the dropdown opens, so
+ // click first and type through the keyboard. Pick by exact title —
+ // `hasText` would also match a longer key containing this one.
+ await select.click();
+ await page.keyboard.type(attribute);
+ await page.locator(`.ant-select-item-option[title="${attribute}"]`).click();
+ await expect(page).toHaveURL(
+ new RegExp(`groupBy=[^&]*${attribute.replace(/\./g, '\\.')}`),
+ );
+ // Close the dropdown so it stops covering the rows.
+ await page.keyboard.press('Escape');
+ },
+
+ clearGrouping: async () => {
+ if (!options.groupBySelectTestId) {
+ throw new Error('tanstackDriver needs a groupBySelectTestId to group');
+ }
+ const select = page.getByTestId(options.groupBySelectTestId);
+ await select.hover();
+ await select.locator('.ant-select-clear').click();
+ await expect(async () => {
+ expect(new URL(page.url()).searchParams.get('groupBy')).toBeNull();
+ }).toPass();
+ },
+
+ groupByFromUrl: () => {
+ const raw = new URL(page.url()).searchParams.get('groupBy');
+ if (!raw) {
+ return [];
+ }
+ const parsed = JSON.parse(raw) as (string | { key: string })[];
+ return parsed.map((entry) =>
+ typeof entry === 'string' ? entry : entry.key,
+ );
+ },
+
+ columnState: async () =>
+ (await readJson<ColumnState>(page, requireStorage())) ?? {},
+
+ setColumnState: async (state) => {
+ // `useColumnStore` always writes all three keys, so seeding one of them
+ // tests a shape the product never produces. A partial value is worth a
+ // scenario of its own, not the accidental setup of every other one.
+ await writeJson(page, requireStorage(), {
+ hiddenColumnIds: state.hiddenColumnIds ?? [],
+ columnOrder: state.columnOrder ?? [],
+ columnSizing: state.columnSizing ?? {},
+ });
+ },
+
+ setRawColumnState: async (raw) => {
+ await writeRaw(page, requireStorage(), raw);
+ },
+
+ reset: async () => {
+ await resetKeys(page, [
+ ...(storageKey ? [storageKey] : []),
+ ...(options.extraStorageKeys ?? []),
+ ]);
+ },
+ };
+
+ return driver;
+}
diff --git a/tests/e2e/drivers/telemetry.ts b/tests/e2e/drivers/telemetry.ts
new file mode 100644
index 0000000000..444931cec7
--- /dev/null
+++ b/tests/e2e/drivers/telemetry.ts
@@ -0,0 +1,86 @@
+import type { APIRequestContext } from '@playwright/test';
+
+import { seederUrl } from './api';
+
+/**
+ * The seeder's telemetry endpoints. No auth: the seeder is a harness container,
+ * so any request context works, including a standalone `request.newContext()`.
+ *
+ * The seeder has no scoped delete (`DELETE /telemetry/*` truncates everything and
+ * belongs to teardown), so seeded rows are never removed per spec. Scope every
+ * read by a name the spec stamped.
+ */
+
+export type TelemetryPath =
+ | '/telemetry/logs'
+ | '/telemetry/traces'
+ | '/telemetry/metrics';
+
+/** Shape of `Logs.from_dict` in `tests/fixtures/logs.py`. */
+export interface SeederLog {
+ timestamp: string;
+ body: string;
+ severity_text?: string;
+ resources?: Record<string, string>;
+ attributes?: Record<string, unknown>;
+}
+
+const ATTEMPTS = 8;
+const BACKOFF_MS = 500;
+const TIMEOUT_MS = 15_000;
+
+/**
+ * POST rows to the seeder. Retries 5xx and transport faults (the seeder's one
+ * ClickHouse client returns `500 concurrent queries within the same session`
+ * under parallel workers); a 4xx is a wrong payload and fails at once.
+ */
+export async function postToSeeder(
+ request: APIRequestContext,
+ path: TelemetryPath,
+ rows: unknown[],
+ options: { timeout?: number; attempts?: number; backoffMs?: number } = {},
+): Promise<void> {
+ const attempts = options.attempts ?? ATTEMPTS;
+ const backoffMs = options.backoffMs ?? BACKOFF_MS;
+ let lastError = '';
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
+ let status = 0;
+ let body = '';
+ try {
+ // eslint-disable-next-line no-await-in-loop
+ const res = await request.post(`${seederUrl()}${path}`, {
+ data: rows,
+ headers: { 'Content-Type': 'application/json' },
+ timeout: options.timeout ?? TIMEOUT_MS,
+ });
+ if (res.ok()) {
+ return;
+ }
+ status = res.status();
+ // eslint-disable-next-line no-await-in-loop
+ body = await res.text();
+ } catch (error) {
+ body = String(error);
+ }
+ if (status >= 400 && status < 500) {
+ throw new Error(
+ `seeder POST ${path} rejected the payload, ${status}: ${body}`,
+ );
+ }
+ lastError = status ? `${status}: ${body}` : body;
+ if (attempt < attempts) {
+ // eslint-disable-next-line no-await-in-loop
+ await new Promise((resolve) => {
+ setTimeout(resolve, backoffMs * attempt + Math.floor(Math.random() * 100));
+ });
+ }
+ }
+ throw new Error(
+ `seeder POST ${path} failed after ${attempts} attempts, ${lastError}`,
+ );
+}
+
+export const seedLogs = (
+ request: APIRequestContext,
+ logs: SeederLog[],
+): Promise<void> => postToSeeder(request, '/telemetry/logs', logs);
diff --git a/tests/e2e/drivers/timepicker.ts b/tests/e2e/drivers/timepicker.ts
new file mode 100644
index 0000000000..e67fdbbd86
--- /dev/null
+++ b/tests/e2e/drivers/timepicker.ts
@@ -0,0 +1,67 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+/**
+ * The top-nav time range picker (`CustomTimePicker`), shared by every page that
+ * shows one. Presets are addressed by their URL value (`15m`, `1h`, `6h`, `1d`).
+ */
+
+export interface TimePicker {
+ input(): Locator;
+ open(): Promise<void>;
+ /** Pick a preset and wait for `relativeTime=<value>` in the URL. */
+ pickPreset(value: string): Promise<void>;
+ /** Type shorthand such as `2h` and press Enter. */
+ typeRange(text: string): Promise<void>;
+ /** Logs explorer list view only. */
+ goLive(): Promise<void>;
+ /** Open the timezone list, search it, and pick the row with `value`. */
+ pickTimezone(search: string, value: string): Promise<void>;
+ urlParams(): { relativeTime?: string; startTime?: string; endTime?: string };
+}
+
+export function timePickerDriver(page: Page): TimePicker {
+ const picker: TimePicker = {
+ input: () => page.getByTestId('dropDown'),
+
+ open: async () => {
+ const input = picker.input();
+ await input.click();
+ await expect(input).not.toHaveAttribute('readonly');
+ },
+
+ pickPreset: async (value) => {
+ await picker.open();
+ await page.getByTestId(`time-option-${value}`).click();
+ await expect(page).toHaveURL(new RegExp(`relativeTime=${value}(&|$)`));
+ },
+
+ typeRange: async (text) => {
+ await picker.open();
+ await picker.input().fill(text);
+ await page.keyboard.press('Enter');
+ },
+
+ goLive: async () => {
+ await picker.open();
+ await page.getByTestId('time-picker-live').click();
+ },
+
+ pickTimezone: async (search, value) => {
+ await picker.open();
+ await page.getByRole('button', { name: 'Change Timezone' }).click();
+ await page.getByPlaceholder('Search timezones...').fill(search);
+ await page.getByTestId(`timezone-item-${value}`).click();
+ },
+
+ urlParams: () => {
+ const params = new URL(page.url()).searchParams;
+ return {
+ relativeTime: params.get('relativeTime') ?? undefined,
+ startTime: params.get('startTime') ?? undefined,
+ endTime: params.get('endTime') ?? undefined,
+ };
+ },
+ };
+
+ return picker;
+}
diff --git a/tests/e2e/drivers/traces-explorer.ts b/tests/e2e/drivers/traces-explorer.ts
new file mode 100644
index 0000000000..406090bac5
--- /dev/null
+++ b/tests/e2e/drivers/traces-explorer.ts
@@ -0,0 +1,340 @@
+import { expect, type Locator, type Page } from '@playwright/test';
+
+import { quickFiltersDriver } from './explorers';
+import {
+ allowFor,
+ driver,
+ kit,
+ seeded,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ type Layer,
+ type WorkerLayer,
+} from './kit';
+import { querySearchDriver, type QuerySearch } from './querysearch';
+import { savedViewsDriver, type SavedViews } from './savedviews';
+import { childSpan, rootSpan, SPAN_KIND, stamp, STATUS } from './spans';
+import { seedTracesViaSeeder, type SeederSpan } from './traces';
+
+/**
+ * The traces explorer: its four views, the traces quick-filter rail and the
+ * saved views built on `savedViewsDriver(page, 'traces')`.
+ */
+
+export const TRACES_EXPLORER_PATH = '/traces-explorer';
+const RELATIVE_TIME = '15m';
+const RUN_TEST_ID = 'explorer-run-query-btn';
+const ROW_PREFIX = 'traces-table-row-';
+
+/**
+ * A saved view auto-restores from `LAST_USED_SAVED_VIEWS`, and the column and
+ * toolbar keys leak one test's layout into the next.
+ */
+const STORAGE_KEYS = [
+ 'LAST_USED_SAVED_VIEWS',
+ 'TRACES_LIST_OPTIONS',
+ 'TRACES_LIST_COLUMNS',
+ 'TRACES_VIEW_COLUMNS',
+ 'SHOW_EXPLORER_TOOLBAR',
+];
+
+/**
+ * `parser/analyzeQuery.ts` keeps ANTLR's console listener, so an expression typed
+ * one key at a time logs a syntax error for every incomplete prefix.
+ */
+const PARSER_NOISE = /^line \d+:\d+ /;
+export const withoutParserNoise = (errors: string[]): string[] =>
+ errors.filter((line) => !PARSER_NOISE.test(line));
+
+export type ExplorerView = 'list' | 'trace' | 'timeseries' | 'table';
+
+/** The `panelTypes` value each view writes. */
+const PANEL_TYPE: Record<ExplorerView, string> = {
+ list: 'list',
+ trace: 'trace',
+ timeseries: 'graph',
+ table: 'table',
+};
+
+export interface TracesExplorer {
+ goto(params?: Record<string, string>): Promise<void>;
+ reload(): Promise<void>;
+ /** A URL search param, or null. */
+ urlParam(name: string): string | null;
+ search: QuerySearch;
+ filterService(name: string): Promise<void>;
+ switchView(view: ExplorerView): Promise<void>;
+ viewButton(view: ExplorerView): Locator;
+ /** `panelTypes` from the URL, JSON-decoded, or null. */
+ panelType(): string | null;
+ /** The TanStack table of the list (`list`) or trace (`trace`) view. */
+ table(view?: 'list' | 'trace'): Locator;
+ row(key: string): Locator;
+ rows(): Locator;
+ /** Re-run the query until `key`'s row renders: the list fetches once. */
+ waitForRow(key: string): Promise<void>;
+ cell(rowKey: string, field: string): Locator;
+ /** Click a list row and wait for its trace-details URL. */
+ openRow(rowKey: string, traceId: string): Promise<void>;
+ /** A waterfall row on the trace-details page. */
+ traceDetailsRow(spanId: string): Locator;
+ timeSeriesGraph(): Locator;
+ timeSeriesCanvas(): Locator;
+ tableView(): Locator;
+ tableCell(text: string): Locator;
+ /** The `service.name` cell of every list row. */
+ rowServices(): Locator;
+ toast(text: string): Locator;
+ /** Click "Only" for `value` in the rail section for attribute `key`. */
+ pickOnly(key: string, value: string): Promise<void>;
+ quickFilterValue(key: string, value: string): Locator;
+ views: SavedViews;
+}
+
+const storageReset = new WeakSet<Page>();
+
+export function tracesExplorerDriver(page: Page): TracesExplorer {
+ const search = querySearchDriver(page, { runTestId: RUN_TEST_ID });
+ const quickFilters = quickFiltersDriver(page);
+
+ const resetStorage = async (): Promise<void> => {
+ if (storageReset.has(page)) {
+ return;
+ }
+ // Once per page, so a reload keeps what the scenario wrote.
+ await page.addInitScript(
+ ({ keys, marker }) => {
+ if (sessionStorage.getItem(marker)) {
+ return;
+ }
+ sessionStorage.setItem(marker, '1');
+ keys.forEach((key) => localStorage.removeItem(key));
+ },
+ { keys: STORAGE_KEYS, marker: '__e2e_traces_explorer_reset' },
+ );
+ storageReset.add(page);
+ };
+
+ /**
+ * The content pane's scrollbar initialises on idle and re-parents the query
+ * editor, which drops a caret mid-typing to position 0.
+ */
+ const settled = async (): Promise<void> => {
+ await expect(search.runButton()).toBeVisible();
+ await expect(
+ page
+ .getByTestId('quick-filters-layout-content')
+ .locator('[data-overlayscrollbars-viewport]'),
+ ).toBeAttached();
+ };
+
+ const filterSection = (key: string): Locator =>
+ page.locator(`[data-filter-key="${key}"]`);
+
+ const explorer: TracesExplorer = {
+ search,
+ views: savedViewsDriver(page, 'traces'),
+
+ goto: async (params = {}) => {
+ await quickFilters.dismissAnnouncement();
+ await resetStorage();
+ const query = new URLSearchParams({
+ relativeTime: RELATIVE_TIME,
+ ...params,
+ });
+ await page.goto(`${TRACES_EXPLORER_PATH}?${query.toString()}`);
+ await settled();
+ },
+
+ reload: async () => {
+ await page.reload();
+ await settled();
+ },
+
+ urlParam: (name) => new URL(page.url()).searchParams.get(name),
+
+ filterService: (name) => search.apply(`service.name = '${name}'`),
+
+ viewButton: (view) => page.getByTestId(`explorer-view-${view}`),
+
+ panelType: () => {
+ const raw = new URL(page.url()).searchParams.get('panelTypes');
+ if (!raw) {
+ return null;
+ }
+ try {
+ return JSON.parse(raw) as string;
+ } catch {
+ return raw;
+ }
+ },
+
+ switchView: async (view) => {
+ await explorer.viewButton(view).click();
+ await expect(explorer.viewButton(view)).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(async () => {
+ expect(explorer.panelType()).toBe(PANEL_TYPE[view]);
+ }).toPass();
+ },
+
+ table: (view = 'list') => page.getByTestId(`traces-table-${view}`),
+ rows: () => page.locator(`[data-testid^="${ROW_PREFIX}"]`),
+ row: (key) => page.getByTestId(`${ROW_PREFIX}${key}`),
+
+ waitForRow: async (key) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ const row = explorer.row(key);
+ await expect(async () => {
+ if (!(await row.isVisible())) {
+ await search.run();
+ }
+ await expect(row).toBeVisible({ timeout: 5_000 });
+ }).toPass({ timeout: SEEDED_DATA_TIMEOUT });
+ },
+
+ cell: (rowKey, field) => explorer.row(rowKey).getByTestId(field).first(),
+
+ openRow: async (rowKey, traceId) => {
+ await explorer.cell(rowKey, 'name').click();
+ await expect(page).toHaveURL(
+ new RegExp(`/trace/${traceId}\\?.*spanId=${rowKey}`),
+ );
+ },
+
+ traceDetailsRow: (spanId) => page.getByTestId(`cell-0-${spanId}`),
+
+ timeSeriesGraph: () => page.getByTestId('time-series-graph'),
+ timeSeriesCanvas: () =>
+ page.getByTestId('time-series-graph').locator('canvas').first(),
+
+ tableView: () => page.getByTestId('query-table'),
+ tableCell: (text) =>
+ page
+ .getByTestId('query-table')
+ .locator('tbody td')
+ .getByText(text, { exact: true }),
+ rowServices: () =>
+ page.locator(`[data-testid^="${ROW_PREFIX}"]`).getByTestId('service.name'),
+
+ toast: (text) => page.getByText(text, { exact: true }),
+
+ quickFilterValue: (key, value) =>
+ filterSection(key).getByTestId(`checkbox-value-row-${value}`),
+
+ pickOnly: async (key, value) => {
+ const section = filterSection(key);
+ const header = section.getByTestId('checkbox-filter-header');
+ await expect(header).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ if ((await header.getAttribute('data-state')) !== 'open') {
+ await header.click();
+ }
+ await expect(header).toHaveAttribute('data-state', 'open');
+ // The rail shows ten values, so the seeded one has to be searched for. The
+ // search box renders only once the section holds more than that.
+ const searchBox = section.getByTestId('checkbox-filter-search');
+ const row = explorer.quickFilterValue(key, value);
+ await expect(searchBox.or(row).first()).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ if (await searchBox.isVisible()) {
+ await searchBox.fill(value);
+ }
+ await expect(row).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ await row.getByText(value, { exact: true }).click();
+ await search.expectContains(value);
+ },
+ };
+
+ return explorer;
+}
+
+// ─── Seed ────────────────────────────────────────────────────────────────────
+
+export interface TracesExplorerSeed {
+ stamp: string;
+ service: string;
+ traceId: string;
+ rootSpanId: string;
+ dbSpanId: string;
+ errorSpanId: string;
+ /** Root span ids of the five single-span traces. */
+ extraRootIds: string[];
+ spanCount: number;
+ traceSpanCount: number;
+}
+
+const EXTRA_ROOT_AGO_MS = [540_000, 420_000, 300_000, 180_000, 90_000];
+
+export const withTracesExplorerSeed: WorkerLayer<{
+ tracesExplorerSeed: TracesExplorerSeed;
+}> = seeded(
+ 'tracesExplorerSeed',
+ async ({ page, workerIndex }) => {
+ const prefix = stamp('tx', workerIndex);
+ const service = `${prefix}-orders`;
+
+ const root = rootSpan({
+ service,
+ name: 'GET /orders',
+ durationMs: 300,
+ agoMs: 60_000,
+ attrs: { 'http.method': 'GET', 'http.status_code': 200 },
+ });
+ const db = childSpan(root, {
+ service,
+ name: 'SELECT orders',
+ kind: SPAN_KIND.client,
+ durationMs: 40,
+ offsetMs: 20,
+ attrs: { 'db.system': 'postgresql', 'db.name': 'orders' },
+ });
+ const pay = childSpan(root, {
+ service,
+ name: 'POST /pay',
+ kind: SPAN_KIND.client,
+ status: STATUS.error,
+ durationMs: 120,
+ offsetMs: 80,
+ attrs: { 'http.method': 'POST', 'http.status_code': 500 },
+ });
+ const extras = EXTRA_ROOT_AGO_MS.map((agoMs) =>
+ rootSpan({
+ service,
+ name: 'GET /orders',
+ durationMs: 150,
+ agoMs,
+ attrs: { 'http.method': 'GET', 'http.status_code': 200 },
+ }),
+ );
+ const spans: SeederSpan[] = [root, db, pay, ...extras];
+ await seedTracesViaSeeder(page.request, spans);
+
+ return {
+ stamp: prefix,
+ service,
+ traceId: root.trace_id,
+ rootSpanId: root.span_id,
+ dbSpanId: db.span_id,
+ errorSpanId: pay.span_id,
+ extraRootIds: extras.map((span) => span.span_id),
+ spanCount: spans.length,
+ traceSpanCount: 3,
+ };
+ },
+ // Views are org-wide; every name a spec saves starts with the stamp.
+ async ({ page, value }) => {
+ await savedViewsDriver(page, 'traces').removeByPrefix(value.stamp);
+ },
+);
+
+export const withTracesExplorer: Layer<{ traces: TracesExplorer }> = driver(
+ 'traces',
+ ({ page }) => tracesExplorerDriver(page),
+);
+
+/** The traces explorer `test`. */
+export const test = withTracesExplorer(withTracesExplorerSeed(kit));
+export { expect } from './kit';
diff --git a/tests/e2e/helpers/trace-details.ts b/tests/e2e/drivers/traces.ts
similarity index 53%
rename from tests/e2e/helpers/trace-details.ts
rename to tests/e2e/drivers/traces.ts
index 6787410da6..8158c94b0b 100644
--- a/tests/e2e/helpers/trace-details.ts
+++ b/tests/e2e/drivers/traces.ts
@@ -1,16 +1,31 @@
import { randomBytes } from 'crypto';
-import { expect, type APIRequestContext, type Page } from '@playwright/test';
+import {
+ expect,
+ type APIRequestContext,
+ type Locator,
+ type Page,
+} from '@playwright/test';
import largeTraceRecords from '../testdata/traces/large-trace.json';
-import { authToken, seederUrl } from './common';
+
+import { apiDriver } from './api';
+import { driver, kit, type Layer } from './kit';
+import { postToSeeder } from './telemetry';
// ── Seeder: insert traces via POST /telemetry/traces ─────────────────────────
// Shape accepted by the seeder's POST /telemetry/traces endpoint
// (mirrors `Traces.from_dict` in tests/fixtures/traces.py). One object per span;
// spans sharing a `trace_id` form one trace, linked into a tree via
-// `parent_span_id`. NOTE: the endpoint does NOT ingest span events/links.
+// `parent_span_id`. Links are not ingested; an `exception` event also lands in
+// the error index.
+export interface SeederSpanEvent {
+ name: string;
+ timestamp: string;
+ attributes?: Record<string, string | number | boolean>;
+}
+
export interface SeederSpan {
timestamp: string; // ISO-8601, e.g. new Date().toISOString()
trace_id: string; // 32 hex chars
@@ -23,49 +38,19 @@ export interface SeederSpan {
duration?: string; // ISO-8601 duration, e.g. "PT0.12S" (default PT1S)
resources?: Record<string, string>; // include 'service.name'
attributes?: Record<string, unknown>;
+ events?: SeederSpanEvent[];
}
// 16-byte trace id / 8-byte span id, matching tests/fixtures/traces.py.
export const randomTraceId = (): string => randomBytes(16).toString('hex');
export const randomSpanId = (): string => randomBytes(8).toString('hex');
-// Insert spans into the backend via the seeder. No auth needed (direct seeder
-// call), so any APIRequestContext works — `page.request` or a standalone
-// `playwright.request.newContext()` (cheaper than a full browser page for a
-// pure API call).
-//
-// The seeder shares a single ClickHouse client, so concurrent POSTs from
-// parallel workers collide with a 500 "concurrent queries within the same
-// session". That's transient, so retry with backoff; any other error is real.
-export async function seedTracesViaSeeder(
+// Insert spans into the backend via the seeder. See `postToSeeder`.
+export function seedTracesViaSeeder(
request: APIRequestContext,
spans: SeederSpan[],
): Promise<void> {
- const url = `${seederUrl()}/telemetry/traces`;
- const maxAttempts = 6;
- let lastStatus = 0;
- let lastText = '';
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
- // eslint-disable-next-line no-await-in-loop
- const res = await request.post(url, {
- data: spans,
- headers: { 'Content-Type': 'application/json' },
- });
- if (res.ok()) {
- return;
- }
- lastStatus = res.status();
- // eslint-disable-next-line no-await-in-loop
- lastText = await res.text();
- if (!(lastStatus === 500 && lastText.includes('concurrent'))) {
- break;
- }
- // eslint-disable-next-line no-await-in-loop
- await new Promise((resolve) => {
- setTimeout(resolve, 150 * (attempt + 1) + Math.floor(Math.random() * 100));
- });
- }
- throw new Error(`seeder POST /telemetry/traces ${lastStatus}: ${lastText}`);
+ return postToSeeder(request, '/telemetry/traces', spans);
}
// ── Navigation ───────────────────────────────────────────────────────────────
@@ -127,7 +112,7 @@ export async function gotoTraceUntilLoaded(
// COLOR_BY_OPTIONS label (service.name | service.namespace | host.name |
// k8s.node.name | k8s.container.name); exact match avoids service.name matching
// service.namespace.
-export async function changeColourByViaMenu(
+async function changeColourByViaMenu(
page: Page,
fieldName: string,
): Promise<void> {
@@ -287,26 +272,20 @@ async function spanPoint(
}
// Hover the flamegraph bar for `spanId` (opens its SpanHoverCard).
-export async function hoverFlamegraphSpan(
- page: Page,
- spanId: string,
-): Promise<void> {
+async function hoverFlamegraphSpan(page: Page, spanId: string): Promise<void> {
const { x, y } = await spanPoint(page, spanId);
await page.mouse.move(x, y);
}
// Click the flamegraph bar for `spanId` (selects the span / opens the drawer).
-export async function clickFlamegraphSpan(
- page: Page,
- spanId: string,
-): Promise<void> {
+async function clickFlamegraphSpan(page: Page, spanId: string): Promise<void> {
const { x, y } = await spanPoint(page, spanId);
await page.mouse.move(x, y);
await page.mouse.click(x, y);
}
// Whether `spanId`'s bar is currently drawn AND inside the viewport container.
-export async function isFlamegraphSpanInView(
+async function isFlamegraphSpanInView(
page: Page,
spanId: string,
): Promise<boolean> {
@@ -319,7 +298,7 @@ export async function isFlamegraphSpanInView(
}
// Resting group color of a span's bar — used to assert colour-by recolor.
-export async function getFlamegraphSpanColor(
+async function getFlamegraphSpanColor(
page: Page,
spanId: string,
): Promise<string | null> {
@@ -358,27 +337,18 @@ export interface PreviewFieldKey {
// NOTE: user preferences are GLOBAL PER USER, not per-test — they persist on the
// server for the admin user. Reset them (resetTracePreferences) in afterAll, and
// be aware other specs run by the same user in parallel share this state.
-export async function setUserPreference(
+async function setUserPreference(
page: Page,
name: string,
value: unknown,
): Promise<void> {
- const token = await authToken(page);
- const res = await page.request.put(`/api/v1/user/preferences/${name}`, {
- data: { value },
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(
- `PUT /api/v1/user/preferences/${name} ${res.status()}: ${await res.text()}`,
- );
- }
+ await apiDriver(page).put(`/api/v1/user/preferences/${name}`, { value });
}
// Persist the flamegraph color-by field. `fieldName` must be one of
// COLOR_BY_OPTIONS (service.name | service.namespace | host.name |
// k8s.node.name | k8s.container.name); '' falls back to the default.
-export async function setColorByPreference(
+async function setColorByPreference(
page: Page,
fieldName: string,
): Promise<void> {
@@ -386,7 +356,7 @@ export async function setColorByPreference(
}
// Persist the span-details preview fields (shown as rows in the hover card).
-export async function setPreviewFieldsPreference(
+async function setPreviewFieldsPreference(
page: Page,
fields: PreviewFieldKey[],
): Promise<void> {
@@ -395,7 +365,7 @@ export async function setPreviewFieldsPreference(
// Reset trace-detail prefs to defaults. Run in afterAll so a prefs spec doesn't
// leak color-by / preview-field state into other specs for the same user.
-export async function resetTracePreferences(page: Page): Promise<void> {
+async function resetTracePreferences(page: Page): Promise<void> {
await setColorByPreference(page, '');
await setPreviewFieldsPreference(page, []);
}
@@ -406,6 +376,287 @@ export async function resetTracePreferences(page: Page): Promise<void> {
// bars) lands on the sidebar instead. Pinned, it's a flex child that reserves
// layout space, so nothing is occluded. Set before navigating: the server pref
// wins over localStorage once preferences load.
-export async function pinSidenav(page: Page): Promise<void> {
+async function pinSidenav(page: Page): Promise<void> {
await setUserPreference(page, SIDENAV_PINNED, true);
}
+
+// ── Waterfall filter ─────────────────────────────────────────────────────────
+
+/** `data-span-state` on a waterfall row, set by `SpanOverview`. */
+export type SpanRowState =
+ | 'default'
+ | 'highlighted'
+ | 'dimmed'
+ | 'selected'
+ | 'selected-non-matching';
+
+export interface WaterfallFilter {
+ root(): Locator;
+ expand(): Promise<void>;
+ /** Type an expression, run it with Mod+Enter, and wait for its query. */
+ apply(expression: string): Promise<void>;
+ highlightErrors(on: boolean): Promise<void>;
+ count(): Locator;
+ /** `{ current, total }` read from "n / N". */
+ resultCount(): Promise<{ current: number; total: number }>;
+ noResults(): Locator;
+ next(): Promise<void>;
+ prev(): Promise<void>;
+ clear(): Promise<void>;
+ /**
+ * The state of every row currently rendered, keyed by span id. The waterfall
+ * is virtualised, so a span scrolled out of view is absent rather than
+ * `default`.
+ */
+ rowStates(): Promise<Record<string, SpanRowState>>;
+ selectedSpanId(): string | null;
+}
+
+const isTraceFilterQuery = (response: {
+ url(): string;
+ request(): { method(): string; postData(): string | null };
+}): boolean =>
+ response.url().includes('/query_range') &&
+ response.request().method() === 'POST' &&
+ (response.request().postData() ?? '').includes('trace_id');
+
+function waterfallFilterDriver(page: Page): WaterfallFilter {
+ const root = (): Locator => page.getByTestId('waterfall-filters');
+ const count = (): Locator => page.getByTestId('waterfall-filter-count');
+
+ const filter: WaterfallFilter = {
+ root,
+ count,
+ noResults: () => page.getByTestId('waterfall-filter-no-results'),
+
+ expand: async () => {
+ const editor = root().locator('.query-where-clause-editor .cm-content');
+ if (await editor.isVisible()) {
+ return;
+ }
+ await page.getByTestId('waterfall-filter-pill').click();
+ await expect(editor).toBeVisible();
+ },
+
+ apply: async (expression) => {
+ await filter.expand();
+ const editor = root().locator('.query-where-clause-editor .cm-content');
+ await editor.click();
+ await page.keyboard.press('ControlOrMeta+a');
+ await page.keyboard.press('Delete');
+ await page.keyboard.type(expression);
+ // The suggestion popover would otherwise take the Mod+Enter.
+ await page.keyboard.press('Escape');
+ const ran = page.waitForResponse(isTraceFilterQuery);
+ await page.keyboard.press('ControlOrMeta+Enter');
+ expect((await ran).ok()).toBe(true);
+ },
+
+ highlightErrors: async (on) => {
+ const toggle = page
+ .getByTestId('highlight-errors-toggle')
+ .getByRole('switch');
+ if ((await toggle.getAttribute('aria-checked')) === String(on)) {
+ return;
+ }
+ const ran = on ? page.waitForResponse(isTraceFilterQuery) : null;
+ await toggle.click();
+ await expect(toggle).toHaveAttribute('aria-checked', String(on));
+ if (ran) {
+ expect((await ran).ok()).toBe(true);
+ }
+ },
+
+ resultCount: async () => {
+ await expect(count()).toHaveText(/^\s*\d+ \/ \d+\s*$/);
+ const [current, total] = (await count().innerText())
+ .split('/')
+ .map((part) => Number(part.trim()));
+ return { current, total };
+ },
+
+ next: async () => {
+ await page.getByTestId('waterfall-filter-next').click();
+ },
+
+ prev: async () => {
+ await page.getByTestId('waterfall-filter-prev').click();
+ },
+
+ clear: async () => {
+ await page.getByTestId('clear-filter').click();
+ await expect(count()).toHaveCount(0);
+ },
+
+ rowStates: async () =>
+ page
+ .locator('[data-testid^="cell-0-"]')
+ .evaluateAll((rows) =>
+ Object.fromEntries(
+ rows.map((row) => [
+ row.getAttribute('data-span-id') ?? '',
+ row
+ .querySelector('[data-span-state]')
+ ?.getAttribute('data-span-state') ?? 'default',
+ ]),
+ ),
+ ) as Promise<Record<string, SpanRowState>>,
+
+ selectedSpanId: () => new URL(page.url()).searchParams.get('spanId'),
+ };
+
+ return filter;
+}
+
+// ── The driver ───────────────────────────────────────────────────────────────
+
+export interface TraceDetails {
+ /** Open a seeded trace, reloading until `readyTestId` renders. */
+ goto(
+ url: string,
+ readyTestId: string,
+ options?: { attempts?: number; perAttemptTimeoutMs?: number },
+ ): Promise<void>;
+ changeColourBy(fieldName: string): Promise<void>;
+ /** The header's Analytics floating panel. */
+ analytics: {
+ open(): Promise<void>;
+ panel(): Locator;
+ dragHandle(): Locator;
+ };
+ /** The span hover card, shared by the waterfall and the flamegraph. */
+ hoverCard: {
+ field(name: 'status' | 'start' | 'duration'): Locator;
+ /** The row a configured preview field renders, e.g. `db.system`. */
+ preview(key: string): Locator;
+ };
+ /** The canvas flamegraph, through the frontend's read-only test hook. */
+ flame: {
+ hover(spanId: string): Promise<void>;
+ click(spanId: string): Promise<void>;
+ isInView(spanId: string): Promise<boolean>;
+ color(spanId: string): Promise<string | null>;
+ };
+ /** Server-side, per-user preferences. Set them before navigating. */
+ prefs: {
+ set(name: string, value: unknown): Promise<void>;
+ colorBy(fieldName: string): Promise<void>;
+ previewFields(fields: PreviewFieldKey[]): Promise<void>;
+ reset(): Promise<void>;
+ pinSidenav(): Promise<void>;
+ };
+ waterfallFilter: WaterfallFilter;
+
+ /** The span details panel and the PrettyView tree inside it. */
+ span: {
+ /** The span's waterfall row. */
+ row(spanId: string): Locator;
+ open(spanId: string): Promise<void>;
+ /** The Overview tab, which only the details panel renders. */
+ overviewTab(): Locator;
+ /** The header a floating (`dialog`) panel is dragged by. */
+ dragHandle(): Locator;
+ /** `dialog` floats, `docked` sits under the waterfall, `right` beside it. */
+ dock(mode: 'dialog' | 'docked' | 'right'): Promise<void>;
+ dockOption(mode: 'dialog' | 'docked' | 'right'): Locator;
+ panelTitle(): Locator;
+ /** Open the actions menu of a leaf row in the main tree, e.g. `db.system`. */
+ openFieldMenu(key: string): Promise<void>;
+ /** Open the actions menu of a row in the pinned section. */
+ openPinnedFieldMenu(key: string): Promise<void>;
+ menuItem(label: string): Locator;
+ pinnedSection(): Locator;
+ pinnedField(path: string): Locator;
+ };
+}
+
+// A PrettyView row, matched on its label exactly so `db.system` does not also
+// match `db.system.name`.
+function prettyRow(scope: Locator, key: string): Locator {
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
+ return scope.locator('li.pretty-view__row').filter({
+ has: scope.page().locator('label', { hasText: new RegExp(`^${escaped}:$`) }),
+ });
+}
+
+// The row's actions trigger is focused and opened from the keyboard: docked
+// under the waterfall at the default 720 px viewport, the panel clips its rows
+// at the bottom edge and a pointer click lands on the waterfall instead.
+// Retried because the tree re-renders once the span's fields load, which can
+// drop a menu opened a moment earlier.
+async function openRowMenu(row: Locator): Promise<void> {
+ const trigger = row.locator('.pretty-view__actions').first();
+ await expect(async () => {
+ await trigger.focus();
+ await trigger.press('Enter');
+ await expect(row.page().getByRole('menu')).toBeVisible({ timeout: 2_000 });
+ }).toPass();
+}
+
+export function traceDetailsDriver(page: Page): TraceDetails {
+ return {
+ goto: (url, readyTestId, options = {}) =>
+ gotoTraceUntilLoaded(page, url, readyTestId, options),
+ changeColourBy: (fieldName) => changeColourByViaMenu(page, fieldName),
+ analytics: {
+ open: async () => {
+ await page.getByRole('button', { name: 'Analytics' }).click();
+ },
+ panel: () => page.getByTestId('trace-analytics-panel'),
+ dragHandle: () => page.locator('.floating-panel__drag-handle'),
+ },
+ hoverCard: {
+ field: (name) => page.getByTestId(`span-hover-card-${name}`),
+ preview: (key) => page.getByTestId(`span-hover-card-preview-${key}`),
+ },
+ flame: {
+ hover: (spanId) => hoverFlamegraphSpan(page, spanId),
+ click: (spanId) => clickFlamegraphSpan(page, spanId),
+ isInView: (spanId) => isFlamegraphSpanInView(page, spanId),
+ color: (spanId) => getFlamegraphSpanColor(page, spanId),
+ },
+ prefs: {
+ set: (name, value) => setUserPreference(page, name, value),
+ colorBy: (fieldName) => setColorByPreference(page, fieldName),
+ previewFields: (fields) => setPreviewFieldsPreference(page, fields),
+ reset: () => resetTracePreferences(page),
+ pinSidenav: () => pinSidenav(page),
+ },
+ waterfallFilter: waterfallFilterDriver(page),
+
+ span: {
+ row: (spanId) => page.getByTestId(`cell-0-${spanId}`),
+ open: async (spanId) => {
+ await page.getByTestId(`cell-0-${spanId}`).click();
+ },
+ overviewTab: () => page.getByRole('tab', { name: /overview/i }),
+ dragHandle: () => page.locator('.floating-panel__drag-handle'),
+ dockOption: (mode) => page.getByTestId(`dock-mode-${mode}`),
+ dock: async (mode) => {
+ await page.getByTestId(`dock-mode-${mode}`).click();
+ },
+ panelTitle: () => page.getByText('Span details', { exact: true }),
+ openFieldMenu: (key) =>
+ openRowMenu(prettyRow(page.locator('.pretty-view > ul'), key)),
+ openPinnedFieldMenu: (key) =>
+ openRowMenu(
+ page
+ .locator('.pretty-view__pinned li.pretty-view__row')
+ .filter({ hasText: key }),
+ ),
+ menuItem: (label) => page.getByRole('menuitem', { name: label }),
+ pinnedSection: () => page.locator('.pretty-view__pinned'),
+ pinnedField: (path) =>
+ page.locator('.pretty-view__pinned-label').filter({ hasText: path }),
+ },
+ };
+}
+
+export const withTraceDetails: Layer<{ traces: TraceDetails }> = driver(
+ 'traces',
+ ({ page }) => traceDetailsDriver(page),
+);
+
+/** The trace-details `test`. */
+export const test = withTraceDetails(kit);
+export { expect, onAdminPage } from './kit';
diff --git a/tests/e2e/drivers/users.ts b/tests/e2e/drivers/users.ts
new file mode 100644
index 0000000000..16a87ebefa
--- /dev/null
+++ b/tests/e2e/drivers/users.ts
@@ -0,0 +1,133 @@
+import type { Page } from '@playwright/test';
+
+import type {
+ AuthtypesPostableUserDTO,
+ AuthtypesRoleDTO,
+ AuthtypesUserWithRolesDTO,
+ TypesResetPasswordTokenDTO,
+ TypesUserDTO,
+} from './schemas';
+import { apiDriver, type Envelope } from './api';
+import type { User } from './auth';
+
+/**
+ * Users and roles over HTTP: the only place user API calls live.
+ *
+ * There is no invite endpoint that yields a password, so an active user is
+ * created in three steps, mirroring `create_active_user` in
+ * `tests/fixtures/auth.py`: create a pending user, mint a reset token, and
+ * redeem it with a password. Deleting a user revokes their sessions.
+ */
+
+export type ManagedRole = 'signoz-admin' | 'signoz-editor' | 'signoz-viewer';
+
+/** Password for every user the suite creates. Meets the backend policy. */
+export const E2E_PASSWORD = 'password123Z$';
+
+export interface CreatedUser {
+ id: string;
+ user: User;
+}
+
+export interface UsersApi {
+ roleId(name: string): Promise<string>;
+ roles(): Promise<AuthtypesRoleDTO[]>;
+ /** A pending (invited) user. Returns its id. */
+ create(input: {
+ email: string;
+ displayName?: string;
+ role: string;
+ }): Promise<string>;
+ resetToken(id: string): Promise<string>;
+ activate(id: string, password?: string): Promise<void>;
+ /** Pending user plus activation, named `e2e-<label>@signoz.test`. */
+ createActive(role: string, label: string): Promise<CreatedUser>;
+ remove(id: string): Promise<void>;
+ /** Best-effort teardown for a user the UI created, whose id the test never saw. */
+ removeByEmail(email: string): Promise<void>;
+ byEmail(email: string): Promise<AuthtypesUserWithRolesDTO | undefined>;
+ me(): Promise<AuthtypesUserWithRolesDTO>;
+ /** Write a preference for the user this page is authenticated as. */
+ setPreference(name: string, value: unknown): Promise<void>;
+}
+
+export function usersApi(page: Page): UsersApi {
+ const api = apiDriver(page);
+
+ const users: UsersApi = {
+ roles: async () =>
+ (await api.get<Envelope<AuthtypesRoleDTO[]>>('/api/v1/roles')).data,
+
+ roleId: async (name) => {
+ const role = (await users.roles()).find((entry) => entry.name === name);
+ if (!role) {
+ throw new Error(`role ${name} not found in GET /api/v1/roles`);
+ }
+ return role.id;
+ },
+
+ create: async ({ email, displayName = '', role }) => {
+ const body: AuthtypesPostableUserDTO = {
+ email,
+ displayName,
+ userRoles: [{ id: await users.roleId(role) }],
+ };
+ return api.create('/api/v2/users', body);
+ },
+
+ resetToken: async (id) => {
+ const body = await api.put<Envelope<TypesResetPasswordTokenDTO>>(
+ `/api/v2/users/${id}/reset_password_tokens`,
+ {},
+ );
+ if (!body.data.token) {
+ throw new Error(`reset token for user ${id} came back empty`);
+ }
+ return body.data.token;
+ },
+
+ activate: async (id, password = E2E_PASSWORD) => {
+ const token = await users.resetToken(id);
+ await api.post('/api/v2/factor_password/reset', { password, token });
+ },
+
+ createActive: async (role, label) => {
+ const email = `e2e-${label}@signoz.test`;
+ const id = await users.create({ email, displayName: `e2e ${label}`, role });
+ await users.activate(id);
+ return { id, user: { email, password: E2E_PASSWORD } };
+ },
+
+ remove: (id) => api.tryDel(`/api/v2/users/${id}`),
+
+ removeByEmail: async (email) => {
+ const match = await users.byEmail(email);
+ if (match) {
+ await users.remove(match.id);
+ }
+ },
+
+ byEmail: async (email) => {
+ const list = await api.get<Envelope<TypesUserDTO[]>>('/api/v2/users');
+ const match = list.data.find((entry) => entry.email === email);
+ if (!match) {
+ return undefined;
+ }
+ return (
+ await api.get<Envelope<AuthtypesUserWithRolesDTO>>(
+ `/api/v2/users/${match.id}`,
+ )
+ ).data;
+ },
+
+ me: async () =>
+ (await api.get<Envelope<AuthtypesUserWithRolesDTO>>('/api/v2/users/me'))
+ .data,
+
+ setPreference: async (name, value) => {
+ await api.put(`/api/v1/user/preferences/${name}`, { value });
+ },
+ };
+
+ return users;
+}
diff --git a/tests/e2e/fixtures/alerts/alert-history.ts b/tests/e2e/fixtures/alerts/alert-history.ts
deleted file mode 100644
index dc28cd4f49..0000000000
--- a/tests/e2e/fixtures/alerts/alert-history.ts
+++ /dev/null
@@ -1,459 +0,0 @@
-import type { Browser } from '@playwright/test';
-
-import {
- createEmailChannelViaApi,
- createLogsAlertViaApi,
- createMetricAlertViaApi,
- createNoDataAlertViaApi,
- createTracesAlertViaApi,
- deleteAlertViaApi,
- deleteChannelViaApi,
- setRuleDisabledViaApi,
-} from '../../helpers/alerts/api';
-import {
- readTimelineTotal,
- waitForTimelineEntries,
- waitForTimelineStates,
-} from '../../helpers/alerts/history';
-import {
- seedAlertHistoryLogs,
- seedAlertHistoryMetrics,
- seedAlertHistoryTraces,
-} from '../../helpers/alerts/seeding';
-import { expect, test as base, withAdminPage } from './alert-rules';
-import {
- FIXTURE_ALERT_HISTORY_TIMEOUT,
- FIXTURE_EMPTY_HISTORY_TIMEOUT,
- FIXTURE_METRICS_HISTORY_TIMEOUT,
- FIXTURE_NODATA_HISTORY_TIMEOUT,
- FIXTURE_RESOLVED_HISTORY_TIMEOUT,
- FIXTURE_TRACES_HISTORY_TIMEOUT,
- WAIT_METRICS_TIMELINE_TIMEOUT,
- WAIT_NODATA_TIMELINE_TIMEOUT,
-} from './timeouts';
-
-// Worker-scoped alert-history fixtures. Extends `alert-rules`, so a spec that
-// imports `test` from here also gets `alertChannel` / `alertList` / `ownedRules`
-// — the details specs need a history seed *and* their own throwaway rules.
-//
-// Every history row has to come from the ruler actually evaluating a rule (there
-// is no seeder endpoint for `rule_state_history_v0`), so each fixture pays a
-// real ruler wait: ~20-35s for logs, ~10s for metrics, ~105s for firing→resolved.
-// Worker scope means one wait per worker instead of one per test, and Playwright
-// creates each fixture lazily — a spec that never asks for `resolvedHistory`
-// never pays its 105s.
-
-/** Service count for `alertHistory`. 25 yields multi-page timeline + pagination tests. */
-const LOGS_HISTORY_SERVICES = 25;
-
-/** Service count for `resolvedHistory`. 3 services + 1m window = resolves in ~105s. */
-const RESOLVED_HISTORY_SERVICES = 3;
-
-/** Hosts for `metricsHistory`. 2 rows fit one page, no related-logs links. */
-const METRICS_HISTORY_HOSTS = ['host-0', 'host-1'];
-
-/** Service count for `tracesHistory`. 3 keeps wait short while proving traces link. */
-const TRACES_HISTORY_SERVICES = 3;
-
-/** Team label for the v1 rule in `alertHistory`, so its header labels row is non-empty. */
-export const V1_RULE_TEAM_LABEL = 'e2e-platform';
-
-export interface AlertHistorySeed {
- /** v2 (`schemaVersion: v2alpha1`) rule — the default history subject. */
- ruleId: string;
- /** Legacy v1 rule over the same logs. Its `threshold.name` is `warning`. */
- ruleIdV1: string;
- channelName: string;
- /** The `body CONTAINS` marker both rules match. */
- marker: string;
- /** The seeded `service.name` values, in creation order. */
- services: string[];
- /** Baseline `total` for {@link ruleId}, read after the rule was frozen. */
- total: number;
- /** Baseline `total` for {@link ruleIdV1}. */
- totalV1: number;
-}
-
-export interface MetricsHistorySeed {
- ruleId: string;
- channelName: string;
- metricName: string;
- hosts: string[];
- total: number;
-}
-
-export interface TracesHistorySeed {
- ruleId: string;
- channelName: string;
- /** The span `name` the rule matches (`name = '<marker>'`). */
- marker: string;
- services: string[];
- total: number;
-}
-
-export interface ResolvedHistorySeed {
- ruleId: string;
- channelName: string;
- marker: string;
- services: string[];
- /** Rows in the `firing` state — equals `stats.totalCurrentTriggers`. */
- firingCount: number;
- /** Rows in the `inactive` state, i.e. what the `Resolved` filter shows. */
- resolvedCount: number;
-}
-
-export interface NoDataHistorySeed {
- ruleId: string;
- channelName: string;
-}
-
-export interface EmptyHistorySeed {
- ruleId: string;
- channelName: string;
-}
-
-async function cleanup(
- browser: Browser,
- { ruleIds, channelId }: { ruleIds: string[]; channelId?: string },
-): Promise<void> {
- await withAdminPage(browser, async (page) => {
- for (const id of ruleIds) {
- // eslint-disable-next-line no-await-in-loop
- await deleteAlertViaApi(page, id);
- }
- if (channelId) {
- await deleteChannelViaApi(page, channelId);
- }
- });
-}
-
-// --- Fixture setup functions ---
-
-interface HistoryFixtureResult<T> {
- seed: T;
- ruleIds: string[];
- channelId: string;
-}
-
-async function createAlertHistorySeed(
- browser: Browser,
-): Promise<HistoryFixtureResult<AlertHistorySeed>> {
- const stamp = Date.now();
- const marker = `e2e alert history ${stamp}`;
-
- const result = await withAdminPage(browser, async (page) => {
- const channel = await createEmailChannelViaApi(page, `e2e-ah-ch-${stamp}`);
-
- const services = await seedAlertHistoryLogs(page, {
- marker,
- services: LOGS_HISTORY_SERVICES,
- servicePrefix: `e2e-ah-svc`,
- });
-
- const ruleId = await createLogsAlertViaApi(page, {
- name: `e2e-ah-rule-v2-${stamp}`,
- marker,
- channels: [channel.name],
- schema: 'v2',
- });
- const ruleIdV1 = await createLogsAlertViaApi(page, {
- name: `e2e-ah-rule-v1-${stamp}`,
- marker,
- channels: [channel.name],
- schema: 'v1',
- extraLabels: { team: V1_RULE_TEAM_LABEL },
- });
-
- await waitForTimelineEntries(page, ruleId, { min: LOGS_HISTORY_SERVICES });
- await waitForTimelineEntries(page, ruleIdV1, { min: LOGS_HISTORY_SERVICES });
-
- await setRuleDisabledViaApi(page, ruleId, true);
- await setRuleDisabledViaApi(page, ruleIdV1, true);
-
- return {
- seed: {
- ruleId,
- ruleIdV1,
- channelName: channel.name,
- marker,
- services,
- total: await readTimelineTotal(page, ruleId),
- totalV1: await readTimelineTotal(page, ruleIdV1),
- },
- ruleIds: [ruleId, ruleIdV1],
- channelId: channel.id,
- };
- });
-
- if (result.seed.total !== LOGS_HISTORY_SERVICES) {
- throw new Error(
- `alertHistory expected ${LOGS_HISTORY_SERVICES} timeline rows, got ${result.seed.total}`,
- );
- }
-
- return result;
-}
-
-async function createMetricsHistorySeed(
- browser: Browser,
-): Promise<HistoryFixtureResult<MetricsHistorySeed>> {
- const stamp = Date.now();
- const metricName = `e2e_ah_probe_metric_${stamp}`;
-
- return withAdminPage(browser, async (page) => {
- const channel = await createEmailChannelViaApi(
- page,
- `e2e-ah-metrics-ch-${stamp}`,
- );
-
- await seedAlertHistoryMetrics(page, {
- metricName,
- hosts: METRICS_HISTORY_HOSTS,
- });
-
- const ruleId = await createMetricAlertViaApi(page, {
- name: `e2e-ah-metrics-rule-${stamp}`,
- metricName,
- channels: [channel.name],
- });
-
- await waitForTimelineEntries(page, ruleId, {
- min: METRICS_HISTORY_HOSTS.length,
- timeoutMs: WAIT_METRICS_TIMELINE_TIMEOUT,
- });
- await setRuleDisabledViaApi(page, ruleId, true);
-
- return {
- seed: {
- ruleId,
- channelName: channel.name,
- metricName,
- hosts: METRICS_HISTORY_HOSTS,
- total: await readTimelineTotal(page, ruleId),
- },
- ruleIds: [ruleId],
- channelId: channel.id,
- };
- });
-}
-
-async function createTracesHistorySeed(
- browser: Browser,
-): Promise<HistoryFixtureResult<TracesHistorySeed>> {
- const stamp = Date.now();
- const marker = `e2e-aht-span-${stamp}`;
-
- return withAdminPage(browser, async (page) => {
- const channel = await createEmailChannelViaApi(
- page,
- `e2e-ah-traces-ch-${stamp}`,
- );
-
- const services = await seedAlertHistoryTraces(page, {
- marker,
- services: TRACES_HISTORY_SERVICES,
- servicePrefix: 'e2e-aht-svc',
- });
-
- const ruleId = await createTracesAlertViaApi(page, {
- name: `e2e-ah-traces-rule-${stamp}`,
- marker,
- channels: [channel.name],
- });
-
- await waitForTimelineEntries(page, ruleId, { min: TRACES_HISTORY_SERVICES });
- await setRuleDisabledViaApi(page, ruleId, true);
-
- return {
- seed: {
- ruleId,
- channelName: channel.name,
- marker,
- services,
- total: await readTimelineTotal(page, ruleId),
- },
- ruleIds: [ruleId],
- channelId: channel.id,
- };
- });
-}
-
-async function createResolvedHistorySeed(
- browser: Browser,
-): Promise<HistoryFixtureResult<ResolvedHistorySeed>> {
- const stamp = Date.now();
- const marker = `e2e alert resolved ${stamp}`;
-
- return withAdminPage(browser, async (page) => {
- const channel = await createEmailChannelViaApi(
- page,
- `e2e-ah-resolved-ch-${stamp}`,
- );
-
- const services = await seedAlertHistoryLogs(page, {
- marker,
- services: RESOLVED_HISTORY_SERVICES,
- ageSeconds: 40,
- minAgeSeconds: 28,
- servicePrefix: 'e2e-ahr-svc',
- });
-
- const ruleId = await createLogsAlertViaApi(page, {
- name: `e2e-ah-resolved-rule-${stamp}`,
- marker,
- channels: [channel.name],
- evalWindow: '1m0s',
- });
-
- const timeline = await waitForTimelineStates(page, ruleId, {
- states: {
- firing: RESOLVED_HISTORY_SERVICES,
- inactive: RESOLVED_HISTORY_SERVICES,
- },
- });
- await setRuleDisabledViaApi(page, ruleId, true);
-
- return {
- seed: {
- ruleId,
- channelName: channel.name,
- marker,
- services,
- firingCount: timeline.items.filter((i) => i.state === 'firing').length,
- resolvedCount: timeline.items.filter((i) => i.state === 'inactive').length,
- },
- ruleIds: [ruleId],
- channelId: channel.id,
- };
- });
-}
-
-async function createNoDataHistorySeed(
- browser: Browser,
-): Promise<HistoryFixtureResult<NoDataHistorySeed>> {
- const stamp = Date.now();
-
- return withAdminPage(browser, async (page) => {
- const channel = await createEmailChannelViaApi(
- page,
- `e2e-ah-nodata-ch-${stamp}`,
- );
-
- const ruleId = await createNoDataAlertViaApi(page, {
- name: `e2e-ah-nodata-rule-${stamp}`,
- marker: `e2e alert nodata ${stamp}`,
- channels: [channel.name],
- });
-
- await waitForTimelineEntries(page, ruleId, {
- min: 1,
- state: 'nodata',
- timeoutMs: WAIT_NODATA_TIMELINE_TIMEOUT,
- });
- await setRuleDisabledViaApi(page, ruleId, true);
-
- return {
- seed: { ruleId, channelName: channel.name },
- ruleIds: [ruleId],
- channelId: channel.id,
- };
- });
-}
-
-async function createEmptyHistorySeed(
- browser: Browser,
-): Promise<HistoryFixtureResult<EmptyHistorySeed>> {
- const stamp = Date.now();
-
- return withAdminPage(browser, async (page) => {
- const channel = await createEmailChannelViaApi(
- page,
- `e2e-ah-empty-ch-${stamp}`,
- );
-
- const ruleId = await createLogsAlertViaApi(page, {
- name: `e2e-ah-empty-rule-${stamp}`,
- marker: `e2e alert never seeded ${stamp}`,
- channels: [channel.name],
- });
- await setRuleDisabledViaApi(page, ruleId, true);
-
- return {
- seed: { ruleId, channelName: channel.name },
- ruleIds: [ruleId],
- channelId: channel.id,
- };
- });
-}
-
-// --- Fixture definitions ---
-
-export const test = base.extend<
- // eslint-disable-next-line @typescript-eslint/ban-types
- {},
- {
- alertHistory: AlertHistorySeed;
- metricsHistory: MetricsHistorySeed;
- tracesHistory: TracesHistorySeed;
- resolvedHistory: ResolvedHistorySeed;
- noDataHistory: NoDataHistorySeed;
- emptyHistory: EmptyHistorySeed;
- }
->({
- alertHistory: [
- async ({ browser }, use) => {
- const { seed, ruleIds, channelId } = await createAlertHistorySeed(browser);
- await use(seed);
- await cleanup(browser, { ruleIds, channelId });
- },
- { scope: 'worker', timeout: FIXTURE_ALERT_HISTORY_TIMEOUT },
- ],
-
- metricsHistory: [
- async ({ browser }, use) => {
- const { seed, ruleIds, channelId } = await createMetricsHistorySeed(browser);
- await use(seed);
- await cleanup(browser, { ruleIds, channelId });
- },
- { scope: 'worker', timeout: FIXTURE_METRICS_HISTORY_TIMEOUT },
- ],
-
- tracesHistory: [
- async ({ browser }, use) => {
- const { seed, ruleIds, channelId } = await createTracesHistorySeed(browser);
- await use(seed);
- await cleanup(browser, { ruleIds, channelId });
- },
- { scope: 'worker', timeout: FIXTURE_TRACES_HISTORY_TIMEOUT },
- ],
-
- resolvedHistory: [
- async ({ browser }, use) => {
- const { seed, ruleIds, channelId } =
- await createResolvedHistorySeed(browser);
- await use(seed);
- await cleanup(browser, { ruleIds, channelId });
- },
- { scope: 'worker', timeout: FIXTURE_RESOLVED_HISTORY_TIMEOUT },
- ],
-
- noDataHistory: [
- async ({ browser }, use) => {
- const { seed, ruleIds, channelId } = await createNoDataHistorySeed(browser);
- await use(seed);
- await cleanup(browser, { ruleIds, channelId });
- },
- { scope: 'worker', timeout: FIXTURE_NODATA_HISTORY_TIMEOUT },
- ],
-
- emptyHistory: [
- async ({ browser }, use) => {
- const { seed, ruleIds, channelId } = await createEmptyHistorySeed(browser);
- await use(seed);
- await cleanup(browser, { ruleIds, channelId });
- },
- { scope: 'worker', timeout: FIXTURE_EMPTY_HISTORY_TIMEOUT },
- ],
-});
-
-export { expect };
diff --git a/tests/e2e/fixtures/alerts/alert-rules.ts b/tests/e2e/fixtures/alerts/alert-rules.ts
deleted file mode 100644
index 26a796a7c5..0000000000
--- a/tests/e2e/fixtures/alerts/alert-rules.ts
+++ /dev/null
@@ -1,245 +0,0 @@
-import type { Browser, Page } from '@playwright/test';
-
-import {
- createEmailChannelViaApi,
- createLogsAlertViaApi,
- createThresholdAlertViaApi,
- deleteAlertViaApi,
- deleteChannelViaApi,
-} from '../../helpers/alerts/api';
-import { seedAlertRules } from '../../helpers/alerts/seeding';
-import type {
- AlertSchema,
- LogsAlertSeed,
- ThresholdAlertSeed,
-} from '../../helpers/alerts/types';
-import { newAdminContext } from '../../helpers/auth';
-import { expect, test as base } from '../auth';
-import { FIXTURE_ALERT_LIST_TIMEOUT } from './timeouts';
-
-// Alert *rule* fixtures — the API-only half of the alerts suite. Nothing here
-// waits on the ruler: a rule is created and that's it. History rows need real
-// evaluations, so those fixtures live in `alert-history.ts`, which
-// extends this module — a spec importing from there gets both sets.
-//
-// Scopes, and why:
-// `alertChannel` — worker. Every rule payload has to reference a channel by
-// name, and one channel serves the whole worker.
-// `alertList` — worker. Read-only rule list the `tests/alerts/list` specs
-// page, search and sort through. Names and label values are stamped per
-// worker so parallel batches never count each other's rules.
-// `ownedRules` — test. Scenarios that rename/toggle/clone/delete a rule seed
-// their own and have it removed when they finish; mutating a shared seed
-// would break every scenario scheduled after it.
-
-export interface AlertChannel {
- id: string;
- name: string;
-}
-
-export interface AlertListSeed {
- channelName: string;
- /** Rules are named `<namePrefix>-NN` — unique to this worker's batch. */
- namePrefix: string;
- /** Rules seeded ⇒ the `of N` total once the list is scoped to the prefix. */
- count: number;
- /** `team` label on the odd-indexed half of the batch, i.e. `count / 2` rules. */
- paymentsLabel: string;
- ruleIds: string[];
-}
-
-export interface OwnedRules {
- /** Seed a metric threshold rule this test owns. */
- threshold(
- name: string,
- overrides?: Partial<Omit<ThresholdAlertSeed, 'name'>>,
- ): Promise<string>;
- /**
- * Seed a logs rule this test owns. No telemetry is seeded for its marker, so
- * it never fires — enough for anything about the details shell.
- *
- * `schema: 'v1'` posts the legacy payload; the condition overrides exist so
- * a v1 *prefill* assertion can be made against values the create form would
- * not have produced by itself.
- */
- logs(
- options: {
- name: string;
- schema?: AlertSchema;
- marker?: string;
- } & Partial<
- Pick<
- LogsAlertSeed,
- 'severity' | 'extraLabels' | 'evalWindow' | 'target' | 'op' | 'matchType'
- >
- >,
- ): Promise<string>;
- /**
- * Track a rule the *app* created (Clone / Duplicate) so teardown removes it
- * too. Lives here because the id may legitimately be missing and a
- * conditional inside a test body is a lint error.
- */
- register(response: { json: () => Promise<unknown> }): Promise<void>;
-}
-
-/** alertList size. 12 over page size 10 = short second page for pagination tests. */
-const LIST_SEED_COUNT = 12;
-
-/**
- * Run `body` on a throwaway admin page. Worker hooks can't use the test-scoped
- * `authedPage`, and every API helper needs a page whose context carries the
- * admin storage state.
- */
-export async function withAdminPage<T>(
- browser: Browser,
- body: (page: Page) => Promise<T>,
-): Promise<T> {
- const ctx = await newAdminContext(browser);
- const page = await ctx.newPage();
- try {
- return await body(page);
- } finally {
- await ctx.close();
- }
-}
-
-async function deleteRules(browser: Browser, ids: string[]): Promise<void> {
- if (ids.length === 0) {
- return;
- }
- await withAdminPage(browser, async (page) => {
- for (const id of ids) {
- // eslint-disable-next-line no-await-in-loop
- await deleteAlertViaApi(page, id);
- }
- });
-}
-
-// --- Fixture setup/teardown functions ---
-
-async function createAlertChannel(
- browser: Browser,
- workerIndex: number,
-): Promise<AlertChannel> {
- return withAdminPage(browser, (page) =>
- createEmailChannelViaApi(page, `e2e-alerts-ch-w${workerIndex}-${Date.now()}`),
- );
-}
-
-async function deleteAlertChannel(
- browser: Browser,
- channelId: string,
-): Promise<void> {
- await withAdminPage(browser, (page) => deleteChannelViaApi(page, channelId));
-}
-
-async function createAlertList(
- browser: Browser,
- channelName: string,
- workerIndex: number,
-): Promise<AlertListSeed> {
- const stamp = `w${workerIndex}-${Date.now()}`;
- const namePrefix = `e2e-alert-list-${stamp}`;
- const teamSuffix = `-${stamp}`;
-
- const ruleIds = await withAdminPage(browser, (page) =>
- seedAlertRules(page, {
- count: LIST_SEED_COUNT,
- channelName,
- namePrefix,
- teamSuffix,
- }),
- );
-
- return {
- channelName,
- namePrefix,
- count: LIST_SEED_COUNT,
- paymentsLabel: `payments${teamSuffix}`,
- ruleIds,
- };
-}
-
-function createOwnedRulesFactory(
- browser: Browser,
- channelName: string,
- ids: Set<string>,
-): OwnedRules {
- const seed = async (
- create: (page: Page) => Promise<string>,
- ): Promise<string> => {
- const id = await withAdminPage(browser, create);
- ids.add(id);
- return id;
- };
-
- return {
- threshold: (name, overrides = {}) =>
- seed((page) =>
- createThresholdAlertViaApi(page, {
- name,
- target: 42,
- channels: [channelName],
- labels: { severity: 'critical' },
- ...overrides,
- }),
- ),
-
- logs: ({ name, schema = 'v2', marker, ...overrides }) =>
- seed((page) =>
- createLogsAlertViaApi(page, {
- name,
- marker: marker ?? `e2e alert never seeded ${name}`,
- channels: [channelName],
- schema,
- ...overrides,
- }),
- ),
-
- register: async (response) => {
- const body = (await response.json()) as { data?: { id?: string } };
- const id = body.data?.id;
- if (id) {
- ids.add(String(id));
- }
- },
- };
-}
-
-// --- Fixture definitions ---
-
-export const test = base.extend<
- { ownedRules: OwnedRules },
- { alertChannel: AlertChannel; alertList: AlertListSeed }
->({
- alertChannel: [
- async ({ browser }, use, workerInfo) => {
- const channel = await createAlertChannel(browser, workerInfo.workerIndex);
- await use(channel);
- await deleteAlertChannel(browser, channel.id);
- },
- { scope: 'worker' },
- ],
-
- alertList: [
- async ({ browser, alertChannel }, use, workerInfo) => {
- const seed = await createAlertList(
- browser,
- alertChannel.name,
- workerInfo.workerIndex,
- );
- await use(seed);
- await deleteRules(browser, seed.ruleIds);
- },
- { scope: 'worker', timeout: FIXTURE_ALERT_LIST_TIMEOUT },
- ],
-
- ownedRules: async ({ browser, alertChannel }, use) => {
- const ids = new Set<string>();
- const factory = createOwnedRulesFactory(browser, alertChannel.name, ids);
- await use(factory);
- await deleteRules(browser, [...ids]);
- },
-});
-
-export { expect };
diff --git a/tests/e2e/fixtures/auth.ts b/tests/e2e/fixtures/auth.ts
deleted file mode 100644
index 6649b4b7af..0000000000
--- a/tests/e2e/fixtures/auth.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { test as base, expect, type Page } from '@playwright/test';
-
-import { ADMIN, storageStateFor, type User } from '../helpers/auth';
-import { installBasePathMode } from '../helpers/base-path';
-
-// The login flow and the per-worker session cache live in `helpers/auth.ts` so
-// worker-scoped fixtures and suite hooks share one login with this fixture.
-export { ADMIN };
-export type { User };
-
-export const test = base.extend<
- {
- /**
- * User identity for this test. Override with `test.use({ user: ... })` at
- * the describe or test level to run the suite as a different user.
- * Defaults to ADMIN (the pytest-bootstrap-seeded admin).
- */
- user: User;
-
- /**
- * A Page whose context is already authenticated as `user`. First request
- * for a given user triggers one login per worker; the resulting
- * storageState is held in memory and reused for all later requests.
- */
- authedPage: Page;
- },
- {
- /** Applies SIGNOZ_E2E_BASE_PATH before any page or login in the worker. */
- basePathMode: void;
- }
->({
- basePathMode: [
- async ({ browser }, use) => {
- await installBasePathMode(browser);
- await use();
- },
- { scope: 'worker', auto: true },
- ],
-
- user: [ADMIN, { option: true }],
-
- authedPage: async ({ browser, user }, use) => {
- const storageState = await storageStateFor(browser, user);
- const ctx = await browser.newContext({ storageState });
- const page = await ctx.newPage();
- // Opt-in CPU throttling to reproduce GitHub-Linux-runner conditions on
- // developer machines. Set `STRESS=1` (typically with `CI=1` to also get
- // 2 workers + 2 retries) before running the suite — see CI-HARDENING.md.
- // The rate is the CPU slowdown multiplier; 4× matches the 2 vCPU runner.
- const throttleRate = Number(process.env.STRESS_CPU_RATE ?? '4');
- if (process.env.STRESS === '1') {
- const client = await ctx.newCDPSession(page);
- await client.send('Emulation.setCPUThrottlingRate', {
- rate: throttleRate,
- });
- }
- await use(page);
- await ctx.close();
- },
-});
-
-export { expect };
diff --git a/tests/e2e/helpers/alert-forms/navigation.ts b/tests/e2e/helpers/alert-forms/navigation.ts
deleted file mode 100644
index 5ea2491442..0000000000
--- a/tests/e2e/helpers/alert-forms/navigation.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { expect, type Locator, type Page } from '@playwright/test';
-
-import {
- ALERTS_NEW_PATH,
- AlertType,
- type AlertTypeValue,
- RuleType,
- STOCK_ALERT_TYPE_CARDS,
-} from './constants';
-import { v1SaveButton } from './v1';
-
-// ─── Navigation ────────────────────────────────────────────────────────────
-
-/**
- * Open the bare type-selection page. `isTypeSelectionMode` is
- * `!alertType && !ruleType && !compositeQuery`
- * (`container/CreateAlertRule/index.tsx:39-41`), so *any* of those three params
- * skips this page — including a stale `compositeQuery` left in the URL.
- */
-export async function gotoAlertTypeSelection(page: Page): Promise<void> {
- await page.goto(ALERTS_NEW_PATH);
- await expect(alertTypeCard(page, AlertType.METRICS)).toBeVisible();
-}
-
-export function alertTypeCard(page: Page, type: AlertTypeValue): Locator {
- return page.getByTestId(`alert-type-card-${type}`);
-}
-
-function alertTypeCards(page: Page): Locator {
- return page.locator('[data-testid^="alert-type-card-"]');
-}
-
-/**
- * Whether the anomaly card is on the page, i.e. whether `ANOMALY_DETECTION` is
- * active for this stack. It **is** active on the pytest-bootstrapped integration
- * stack, so every card-count assertion has to branch on it rather than hard-code
- * 4.
- */
-export async function hasAnomalyAlertTypeCard(page: Page): Promise<boolean> {
- return (await alertTypeCard(page, AlertType.ANOMALY).count()) > 0;
-}
-
-/**
- * Assert the type-selection page shows exactly the expected set of cards: the
- * four stock ones, plus anomaly *first* when the flag is on (`getOptionList`
- * `unshift`s it, `SelectAlertType/config.ts:33-40`).
- *
- * Written as an exact set rather than "at least four" so that adding a fifth
- * signal still fails this assertion — the flag branch is the only slack.
- */
-export async function expectAlertTypeCardSet(page: Page): Promise<void> {
- const anomaly = await hasAnomalyAlertTypeCard(page);
- const expected = anomaly
- ? [AlertType.ANOMALY, ...STOCK_ALERT_TYPE_CARDS]
- : STOCK_ALERT_TYPE_CARDS;
-
- const cards = alertTypeCards(page);
- await expect(cards).toHaveCount(expected.length);
-
- // Read the testids positionally so order is asserted too — anomaly being
- // unshifted rather than appended is the behaviour worth pinning.
- const rendered: (string | null)[] = [];
- for (let i = 0; i < expected.length; i += 1) {
- // eslint-disable-next-line no-await-in-loop
- rendered.push(await cards.nth(i).getAttribute('data-testid'));
- }
- expect(rendered).toEqual(expected.map((type) => `alert-type-card-${type}`));
-}
-
-export interface CreateAlertUrlOptions {
- alertType?: AlertTypeValue;
- ruleType?: string;
- /** Sets `showClassicCreateAlertsPage=true` ⇒ the v1 classic form. */
- classic?: boolean;
- /** Merged in last, so it can override anything above. */
- params?: Record<string, string>;
-}
-
-export function createAlertUrl({
- alertType = AlertType.LOGS,
- ruleType = RuleType.THRESHOLD,
- classic = false,
- params = {},
-}: CreateAlertUrlOptions = {}): string {
- const search = new URLSearchParams({ alertType, ruleType });
- if (classic) {
- search.set('showClassicCreateAlertsPage', 'true');
- }
- for (const [key, value] of Object.entries(params)) {
- search.set(key, value);
- }
- return `${ALERTS_NEW_PATH}?${search.toString()}`;
-}
-
-/**
- * Open the **v2** builder and wait until it has settled. The wait is two-part on
- * purpose: the header proves the builder mounted, and the `compositeQuery` in the
- * URL proves `useShareBuilderUrl` has finished serialising the default query —
- * without the second half, an assertion on the URL races the builder's own
- * rewrite (the same trap `gotoAlertOverview` documents).
- */
-export async function gotoCreateAlertV2(
- page: Page,
- options: Omit<CreateAlertUrlOptions, 'classic'> = {},
-): Promise<void> {
- await page.goto(createAlertUrl({ ...options, classic: false }));
- await expect(page.getByTestId('alert-name-input')).toBeVisible();
- await page.waitForURL(/compositeQuery=/, { timeout: 15_000 });
-}
-
-/** Open the **v1** classic create form and wait for its primary action. */
-export async function gotoCreateAlertV1(
- page: Page,
- options: Omit<CreateAlertUrlOptions, 'classic'> = {},
-): Promise<void> {
- await page.goto(createAlertUrl({ ...options, classic: true }));
- await expect(v1SaveButton(page)).toBeVisible();
-}
diff --git a/tests/e2e/helpers/alert-forms/shared.ts b/tests/e2e/helpers/alert-forms/shared.ts
deleted file mode 100644
index 9c9f4a22b9..0000000000
--- a/tests/e2e/helpers/alert-forms/shared.ts
+++ /dev/null
@@ -1,165 +0,0 @@
-import { expect, type Locator, type Page, type Route } from '@playwright/test';
-
-// ─── Antd select helpers ───────────────────────────────────────────────────
-
-/**
- * Read an antd multi-select's chosen values, for asserting what a threshold row
- * ended up pointing at.
- */
-export function selectedTags(scope: Locator): Locator {
- return scope.locator('.ant-select-selection-item-content');
-}
-
-/**
- * The currently-open antd dropdown. Scoping option lookups to it matters because
- * antd keeps previously-opened dropdowns in the DOM with
- * `.ant-select-dropdown-hidden`, so an unscoped `.ant-select-item-option` can
- * resolve into a stale list.
- *
- * Adequate when only one select is ever open on the page. When several selects of
- * the *same kind* exist — the per-threshold channel selects — use
- * {@link ownDropdown} instead: `-hidden` is applied only after the close
- * transition, so "the open dropdown" is briefly ambiguous.
- */
-export function openDropdown(page: Page): Locator {
- return page.locator('.ant-select-dropdown:not(.ant-select-dropdown-hidden)');
-}
-
-/**
- * The dropdown belonging to one specific antd select, resolved through the
- * combobox's `aria-controls` → the listbox id it owns.
- *
- * This is the only unambiguous way to address one of several sibling selects'
- * option lists. Filtering on "the visible dropdown" is not enough: with four
- * threshold rows, row N's list is still mid-close while row N+1's opens, so the
- * option lookup lands in the wrong list and the click fails with "element is not
- * stable" and then "element is not visible".
- */
-export async function ownDropdown(
- page: Page,
- select: Locator,
-): Promise<Locator> {
- const listId = await select
- .locator('input[role="combobox"]')
- .getAttribute('aria-controls');
- if (!listId) {
- throw new Error(
- 'select has no aria-controls — not an antd combobox, or not yet opened',
- );
- }
- return page
- .locator('.ant-select-dropdown')
- .filter({ has: page.locator(`[id="${listId}"]`) });
-}
-
-/**
- * An option in the open dropdown, matched on its **exact** label. Substring
- * matching is wrong here: `hasText: 'EQUAL TO'` also matches `NOT EQUAL TO`.
- */
-export function dropdownOption(page: Page, label: string): Locator {
- return openDropdown(page)
- .locator('.ant-select-item-option')
- .filter({ has: page.getByText(label, { exact: true }) });
-}
-
-/**
- * Pick a notification channel by exact name in one of the two channel selects —
- * v2's per-threshold one and v1's single `alert-channel-select`. Both are
- * `mode="multiple"` antd selects over the *same* global channel list, so both need
- * exactly this sequence; the shared body is why this is one function rather than
- * two near-copies.
- *
- * The list must be **searched**, not scrolled. Channels are global while the
- * `alertChannel` fixture is worker-scoped, so a shared stack accumulates one
- * channel per worker (plus anything a killed run leaked) and antd virtualises the
- * dropdown: measured on this stack, 31 channels render **10** options into the DOM,
- * and the wanted one is simply not there. Clicking by name without filtering first
- * is therefore not a slow path, it is a missing element — and it was the single
- * biggest source of flake in this suite. It fails as a plain click timeout
- * ("waiting for locator … .ant-select-item-option …"), which reads like a renamed
- * testid rather than a virtualised list.
- */
-export async function pickChannelByName(
- page: Page,
- select: Locator,
- channelName: string,
-): Promise<void> {
- const tagsBefore = await selectedTags(select).count();
- await select.click();
- await expect(select).toHaveClass(/ant-select-open/);
-
- // `fill` on the combobox input rather than `keyboard.type`: the query is a ~30
- // character channel name and every keystroke re-runs antd's filter, so typing it
- // costs ~2.5 s per pick — CV2-09 makes four of them, which was a quarter of that
- // test's 30 s budget. `fill` sets the value in one input event, which is all
- // rc-select's search needs.
- await select.locator('input[role="combobox"]').fill(channelName);
- const dropdown = await ownDropdown(page, select);
- await dropdown
- .locator('.ant-select-item-option')
- .filter({ hasText: channelName })
- .first()
- .click();
-
- // A multi-select stays open after a pick and its dropdown overlays the controls
- // below, which the next interaction would otherwise hit instead.
- await page.keyboard.press('Escape');
-
- // Wait for *this* select to report itself closed before returning. antd removes
- // `.ant-select-dropdown-hidden` only after the close transition, so a caller that
- // immediately opens the next row's select races a still-visible stale list: the
- // option lookup then resolves inside the previous row's dropdown and the click
- // fails with "element is not stable" followed by "element is not visible".
- await expect(select).not.toHaveClass(/ant-select-open/);
-
- // Fail here rather than three assertions later: a silently-missed pick shows up
- // as "Save is still disabled", which points at the validator instead of at this.
- //
- // Counted, not name-matched: v2's select sets `maxTagTextLength={10}`
- // (`ThresholdItem.tsx:140`) so its tag reads `e2e-alerts…`, and v1's passes
- // `optionLabelProp="label"` to options that carry no `label` prop, so its tag
- // renders empty. Neither can ever contain the full channel name. The name itself
- // is verified where it actually matters — in the request body (CV2-20, CV1-08).
- await expect(selectedTags(select)).toHaveCount(tagsBefore + 1);
-}
-
-// ─── SEED-CH1: a stack with no notification channels ───────────────────────
-
-/**
- * Route-stub the channel list to an empty one for this page only.
- *
- * This is the **one** place the alerts suite mocks the network, and it is a
- * deliberate exception to the standing no-stubbing rule. The justification: zero
- * channels is a real product state — every fresh install has it — and it is the
- * only state that reaches the `disabled` broadcast switch and
- * the empty-channel dropdown content. It cannot be produced server-side, because
- * `alertChannel` is worker-scoped and parallel workers share one stack, so
- * deleting the channel would break every other scenario running at that moment.
- *
- * Both list endpoints are stubbed: the pickers read v2, while screens still on
- * the v1 client read v1, and a scenario may cross both.
- */
-export async function stubNoChannels(page: Page): Promise<void> {
- const emptyList = async (
- route: Route,
- body: Record<string, unknown>,
- ): Promise<void> => {
- if (route.request().method() !== 'GET') {
- await route.fallback();
- return;
- }
- await route.fulfill({
- status: 200,
- contentType: 'application/json',
- body: JSON.stringify(body),
- });
- };
-
- await page.route('**/api/v1/channels', (route) =>
- emptyList(route, { status: 'success', data: [] }),
- );
- // the v2 list is paginated, so the empty page has to carry its total
- await page.route('**/api/v2/notification_channels*', (route) =>
- emptyList(route, { status: 'success', data: { channels: [], total: 0 } }),
- );
-}
diff --git a/tests/e2e/helpers/alert-forms/v1.ts b/tests/e2e/helpers/alert-forms/v1.ts
deleted file mode 100644
index 28e79d06d3..0000000000
--- a/tests/e2e/helpers/alert-forms/v1.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { type Locator, type Page } from '@playwright/test';
-
-/**
- * The v1 primary action. Its *label* is mode-dependent — *Create Rule* when
- * `isNewRule`, *Save Rule* when editing (`FormAlertRules/index.tsx:970`) — so
- * scenarios that care about the mode assert the text; the locator itself does not.
- */
-export function v1SaveButton(page: Page): Locator {
- return page.getByTestId('alert-save-button');
-}
diff --git a/tests/e2e/helpers/alert-forms/v2.ts b/tests/e2e/helpers/alert-forms/v2.ts
deleted file mode 100644
index 3c6f39a61a..0000000000
--- a/tests/e2e/helpers/alert-forms/v2.ts
+++ /dev/null
@@ -1,224 +0,0 @@
-import { expect, type Locator, type Page } from '@playwright/test';
-
-import { EVALUATION_WINDOW_PRESETS } from './constants';
-import { pickChannelByName } from './shared';
-
-// ─── v2 builder ────────────────────────────────────────────────────────────
-
-/**
- * Footer buttons. The disabled Save/Test buttons are wrapped in a `<span>` inside
- * an antd `Tooltip` (`CreateAlertV2/Footer/Footer.tsx:198-204`) — the wrapper is
- * why {@link v2SaveTooltip} exists instead of reading a `title` attribute, and
- * why these are testids rather than accessible names: the name lookup also
- * matched the wrapper in some states.
- */
-export function v2SaveButton(page: Page): Locator {
- return page.getByTestId('save-alert-rule-button');
-}
-
-export function v2TestButton(page: Page): Locator {
- return page.getByTestId('test-notification-button');
-}
-
-export function v2DiscardButton(page: Page): Locator {
- return page.getByTestId('discard-alert-rule-button');
-}
-
-/**
- * Click the v2 Discard button — via `dispatchEvent`, because a real click cannot
- * reach it.
- *
- * The footer is `position: fixed; left: 63px` (the *collapsed* nav rail width) and
- * Discard is its left-most control, so the button occupies roughly x 75-170 at the
- * bottom of the viewport. The side navigation occupies x 0-240 whenever it is
- * 240px wide, which is: always when pinned — the default — and transiently when
- * not pinned, because a mouse travelling toward the button crosses the rail and
- * triggers `:not(.pinned).is-hovered`. Either way `document.elementFromPoint` at
- * the button's centre returns the nav's `.nav-item-data`, so the nav swallows the
- * click.
- *
- * `{ force: true }` does **not** help: it skips Playwright's actionability wait
- * but still delivers a real mouse event at those coordinates, which the nav
- * receives. `dispatchEvent('click')` bypasses hit-testing entirely and React's
- * delegated handler fires normally — verified: the page navigates to `/alerts`.
- *
- * This is a workaround for a **product** bug, not for a flaky test.
- * `create/edge.spec.ts` CE-09 is the skipped scenario that asserts the fixed
- * behaviour; unskipping it and reverting this helper to `.click()` belong in the
- * same commit as the fix.
- */
-export async function v2ClickDiscard(page: Page): Promise<void> {
- await v2DiscardButton(page).dispatchEvent('click');
-}
-
-/**
- * Whether the side navigation currently overlaps a point — the mechanism behind
- * {@link v2ClickDiscard}. Used by CE-09, which asserts the *absence* of that
- * overlap and is skipped until the footer is fixed.
- */
-export async function elementAtPointClassName(
- page: Page,
- x: number,
- y: number,
-): Promise<string> {
- return page.evaluate(
- ([px, py]) => {
- const el = document.elementFromPoint(px as number, py as number);
- return el ? String(el.className) : '';
- },
- [x, y],
- );
-}
-
-/**
- * Hover the (disabled) Save button and return the tooltip's text — this is
- * the only way to read `validateCreateAlertState`'s message, since the button
- * cannot be clicked while a message exists.
- */
-export async function v2SaveTooltip(page: Page): Promise<string> {
- await v2SaveButton(page).hover();
- const tooltip = page.locator('[data-slot="tooltip-content"]').first();
- await expect(tooltip).toBeVisible();
- return (await tooltip.innerText()).trim();
-}
-
-/**
- * Threshold rows. There is **no** `threshold-item-<id>` testid — the row is a bare
- * `className="threshold-item"` (`AlertCondition/ThresholdItem.tsx`), so rows are
- * addressed positionally.
- */
-export function thresholdRows(page: Page): Locator {
- return page.locator('.threshold-item');
-}
-
-export function thresholdRow(page: Page, index: number): Locator {
- return thresholdRows(page).nth(index);
-}
-
-/** Assign a notification channel to the Nth v2 threshold. */
-export async function selectThresholdChannel(
- page: Page,
- index: number,
- channelName: string,
-): Promise<void> {
- await pickChannelByName(
- page,
- page.getByTestId('threshold-notification-channel-select').nth(index),
- channelName,
- );
-}
-
-/**
- * Add a label through the v2 header editor. The input is a single field with two
- * phases — key, then value, each committed with Enter
- * (`CreateAlertHeader/LabelsInput.tsx:25-93`) — and a `key:value` string in the
- * first phase is accepted as a shortcut. This helper drives the two-phase path
- * because that is what a user does.
- */
-export async function addAlertLabel(
- page: Page,
- key: string,
- value: string,
-): Promise<void> {
- await page.getByTestId('alert-add-label-button').click();
- const input = page.getByTestId('alert-add-label-input');
- await input.fill(key);
- await input.press('Enter');
- await input.fill(value);
- await input.press('Enter');
-
- // Committing a label does *not* close the editor — `isAdding` stays true so a
- // user can type several in a row, which means `alert-add-label-button` is still
- // unmounted. Escape (with both fields empty) is what closes it, and without this
- // a second call to this helper waits forever for the add button.
- await input.press('Escape');
- await expect(page.getByTestId('alert-add-label-button')).toBeVisible();
-}
-
-/**
- * The toggle inside an `AdvancedOptionItem` (repeat notifications, send-if-missing,
- * enforce-minimum-datapoints). The `Switch` there carries no testid of its own, so
- * it is reached through the container's — hence the container testid being the
- * documented handle rather than the switch.
- */
-export function advancedOptionToggle(
- page: Page,
- containerTestId: string,
-): Locator {
- return page.getByTestId(containerTestId).locator('[role="switch"]');
-}
-
-// ─── Evaluation window + cadence ───────────────────────────────────────────
-
-export function evaluationSettingsButton(page: Page): Locator {
- return page.getByTestId('evaluation-settings-button');
-}
-
-/**
- * Open the evaluation-window popover. It is an antd `Popover`, so its content is
- * only in the DOM while open — every option lookup has to come after this.
- */
-export async function openEvaluationSettings(page: Page): Promise<void> {
- await evaluationSettingsButton(page).click();
- await expect(page.locator('.evaluation-window-popover')).toBeVisible();
-}
-
-/**
- * A popover option. The popover renders two lists from one component, keyed by
- * `data-section-id` — `window-type` (Rolling / Cumulative) and `timeframe` — and
- * the testid carries both, so `timeframe-option-10m0s` cannot collide with a
- * window-type value.
- */
-export function evaluationWindowOption(
- page: Page,
- section: 'window-type' | 'timeframe',
- value: string,
-): Locator {
- return page.getByTestId(`${section}-option-${value}`);
-}
-
-/**
- * Pick a rolling timeframe and wait for the trigger button to reflect it. The wait
- * matters: the popover closes on its own animation, and a spec that immediately
- * clicks Save can otherwise post the previous window.
- */
-export async function selectEvaluationTimeframe(
- page: Page,
- value: keyof typeof EVALUATION_WINDOW_PRESETS,
-): Promise<void> {
- await openEvaluationSettings(page);
- await evaluationWindowOption(page, 'timeframe', value).click();
- await expect(evaluationSettingsButton(page)).toContainText(
- EVALUATION_WINDOW_PRESETS[value],
- );
- await page.keyboard.press('Escape');
-}
-
-/**
- * Expand the ADVANCED OPTIONS panel inside the alert-condition section.
- *
- * antd's `Collapse` renders its panel children lazily, so `evaluation-cadence-*`
- * and the two `AdvancedOptionItem` containers do not exist in the DOM at all until
- * this runs — an assertion on them without it fails as "not found" rather than as
- * "not visible", which reads like a missing testid.
- */
-export async function expandAdvancedOptions(page: Page): Promise<void> {
- const header = page.getByRole('button', { name: /ADVANCED OPTIONS/i });
- if ((await header.getAttribute('aria-expanded')) !== 'true') {
- await header.click();
- }
- await expect(page.getByTestId('evaluation-cadence-input-group')).toBeVisible();
-}
-
-/** The cadence duration field — `evaluation.spec.frequency`'s UI half. */
-export function evaluationCadenceInput(page: Page): Locator {
- return page.getByTestId('evaluation-cadence-duration-input');
-}
-
-export function evaluationCadenceUnitSelect(page: Page): Locator {
- return page.getByTestId('evaluation-cadence-unit-select');
-}
-
-export function labelPill(page: Page, key: string, value: string): Locator {
- return page.getByTestId(`label-pill-${key}-${value}`);
-}
diff --git a/tests/e2e/helpers/alerts/api.ts b/tests/e2e/helpers/alerts/api.ts
deleted file mode 100644
index 2ed407cd1d..0000000000
--- a/tests/e2e/helpers/alerts/api.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import type { Page } from '@playwright/test';
-
-import { authToken } from '../common';
-
-import {
- buildThresholdRulePayload,
- logsCompositeQuery,
- metricsCompositeQuery,
- tracesCompositeQuery,
- v1RulePayload,
- v2RulePayload,
-} from './payloads';
-import type {
- AlertSchema,
- LogsAlertSeed,
- MetricAlertSeed,
- ThresholdAlertSeed,
- TracesAlertSeed,
-} from './types';
-
-// ─── API helpers ─────────────────────────────────────────────────────────
-
-/**
- * Seed an email notification channel via API. Returns its `{ id, name }`;
- * thresholds reference channels by name, cleanup deletes by id. `to` is never
- * delivered — the channel only needs to exist to satisfy rule validation.
- */
-export async function createEmailChannelViaApi(
- page: Page,
- name: string,
-): Promise<{ id: string; name: string }> {
- const token = await authToken(page);
- const res = await page.request.post('/api/v1/channels', {
- data: {
- name,
- email_configs: [
- { send_resolved: true, to: '[email protected]', html: '', headers: {} },
- ],
- },
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(`POST /api/v1/channels ${res.status()}: ${await res.text()}`);
- }
- const json = (await res.json()) as { data: { id: string } };
- return { id: String(json.data.id), name };
-}
-
-/** Delete a notification channel by ID (best-effort cleanup). */
-export async function deleteChannelViaApi(
- page: Page,
- id: string,
-): Promise<void> {
- const token = await authToken(page);
- await page.request.delete(`/api/v1/channels/${id}`, {
- headers: { Authorization: `Bearer ${token}` },
- });
-}
-
-/**
- * Seed a v2 threshold alert via API. Returns the new rule ID. Pair with
- * {@link deleteAlertViaApi} in an `afterAll`/`afterEach` for cleanup.
- */
-export async function createThresholdAlertViaApi(
- page: Page,
- seed: ThresholdAlertSeed,
-): Promise<string> {
- const token = await authToken(page);
- const res = await page.request.post('/api/v2/rules', {
- data: buildThresholdRulePayload(seed),
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(`POST /api/v2/rules ${res.status()}: ${await res.text()}`);
- }
- const json = (await res.json()) as { data: { id: string } };
- return json.data.id;
-}
-
-/** Delete a rule by ID. Tolerates an already-deleted rule (best-effort cleanup). */
-export async function deleteAlertViaApi(page: Page, id: string): Promise<void> {
- const token = await authToken(page);
- await page.request.delete(`/api/v2/rules/${id}`, {
- headers: { Authorization: `Bearer ${token}` },
- });
-}
-
-async function postRule(
- page: Page,
- schema: AlertSchema,
- payload: Record<string, unknown>,
-): Promise<string> {
- const token = await authToken(page);
- const path = schema === 'v1' ? '/api/v1/rules' : '/api/v2/rules';
- const res = await page.request.post(path, {
- data: payload,
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(`POST ${path} ${res.status()}: ${await res.text()}`);
- }
- const json = (await res.json()) as { data: { id: string } };
- return String(json.data.id);
-}
-
-/**
- * Create a logs threshold rule grouped by `service.name`. `schema: 'v1'` posts
- * the legacy payload to `/api/v1/rules`, which the UI then renders through the
- * v1 branch of `AlertHeader` / `ActionButtons` — both schemas serve the *same*
- * history APIs, so history scenarios can be parameterised over them.
- */
-export async function createLogsAlertViaApi(
- page: Page,
- {
- name,
- marker,
- channels,
- schema = 'v2',
- evalWindow = '5m0s',
- frequency = '15s',
- severity = schema === 'v1' ? 'warning' : 'critical',
- extraLabels,
- alertOnAbsent,
- absentFor,
- target,
- op,
- matchType,
- }: LogsAlertSeed,
-): Promise<string> {
- const extraCondition =
- alertOnAbsent === undefined
- ? undefined
- : { alertOnAbsent, absentFor: absentFor ?? 1 };
- const args = {
- name,
- alertType: 'LOGS_BASED_ALERT',
- compositeQuery: logsCompositeQuery(marker),
- channels,
- severity,
- extraLabels,
- evalWindow,
- frequency,
- extraCondition,
- target,
- op,
- matchType,
- };
- return postRule(
- page,
- schema,
- schema === 'v1' ? v1RulePayload(args) : v2RulePayload(args),
- );
-}
-
-/**
- * SEED-H's rule: traces-based over the seeded spans, grouped by `service.name`.
- * Its history rows carry `relatedTracesLink` and an empty `relatedLogsLink`, so
- * the popover offers "View Traces" only.
- */
-export async function createTracesAlertViaApi(
- page: Page,
- {
- name,
- marker,
- channels,
- evalWindow = '5m0s',
- frequency = '15s',
- }: TracesAlertSeed,
-): Promise<string> {
- return postRule(
- page,
- 'v2',
- v2RulePayload({
- name,
- alertType: 'TRACES_BASED_ALERT',
- compositeQuery: tracesCompositeQuery(marker),
- channels,
- severity: 'critical',
- evalWindow,
- frequency,
- }),
- );
-}
-
-/** SEED-E's rule: metrics-based, so its history rows carry no related links. */
-export async function createMetricAlertViaApi(
- page: Page,
- {
- name,
- metricName,
- channels,
- groupByKey = 'host',
- evalWindow = '5m0s',
- frequency = '15s',
- }: MetricAlertSeed,
-): Promise<string> {
- return postRule(
- page,
- 'v2',
- v2RulePayload({
- name,
- alertType: 'METRIC_BASED_ALERT',
- compositeQuery: metricsCompositeQuery(metricName, groupByKey),
- channels,
- severity: 'critical',
- evalWindow,
- frequency,
- }),
- );
-}
-
-/**
- * SEED-G's rule: a logs rule whose filter matches nothing, with
- * `alertOnAbsent` set — the only cheap way to get a `nodata` history row.
- * Seed no telemetry for its marker.
- */
-export async function createNoDataAlertViaApi(
- page: Page,
- {
- name,
- marker,
- channels,
- }: { name: string; marker: string; channels: string[] },
-): Promise<string> {
- return createLogsAlertViaApi(page, {
- name,
- marker,
- channels,
- evalWindow: '5m0s',
- frequency: '15s',
- alertOnAbsent: true,
- absentFor: 1,
- });
-}
-
-/**
- * Freeze a rule's history. Rows are written on *state change* only, so the
- * firing wave lands once — but once the eval window rolls past the seeded
- * records the rule resolves and writes a second row per fingerprint, doubling
- * `total` mid-suite. Disable the rule as soon as the firing wave is confirmed.
- */
-export async function setRuleDisabledViaApi(
- page: Page,
- id: string,
- disabled: boolean,
-): Promise<void> {
- const token = await authToken(page);
- const res = await page.request.patch(`/api/v2/rules/${id}`, {
- data: { disabled },
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(
- `PATCH /api/v2/rules/${id} ${res.status()}: ${await res.text()}`,
- );
- }
-}
diff --git a/tests/e2e/helpers/alerts/constants.ts b/tests/e2e/helpers/alerts/constants.ts
deleted file mode 100644
index 1def03f68a..0000000000
--- a/tests/e2e/helpers/alerts/constants.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-// ─── Constants ───────────────────────────────────────────────────────────
-
-export const ALERTS_LIST_PATH = '/alerts';
-export const ALERT_OVERVIEW_PATH = '/alerts/overview';
-export const ALERT_HISTORY_PATH = '/alerts/history';
-
-/**
- * Mirrors `TIMELINE_TABLE_PAGE_SIZE` in
- * `frontend/src/container/AlertHistory/constants.ts`. This 20 is what makes the
- * page-2 cursor `base64url({"offset":20,"limit":20})`, so the two must not drift.
- */
-export const TIMELINE_PAGE_SIZE = 20;
-
-/** The `relativeTime` the history page falls back to (`DEFAULT_TIME_RANGE`). */
-export const DEFAULT_RELATIVE_TIME = '30m';
-
-/**
- * Page size the list specs pin in the URL, so the number of rendered rows never
- * depends on the viewport height.
- */
-export const ALERT_LIST_PAGE_SIZE = 10;
-
-/** Severities the list seed cycles through, so search/sort tests have more than one value. */
-export const SEED_B_SEVERITIES = ['critical', 'warning', 'info'] as const;
-
-// ─── Wait timeouts (ms) ──────────────────────────────────────────────────
-// These timeouts gate on the "ruler" — SigNoz's alert evaluation engine that
-// runs on ~15s cycles and writes history rows to ClickHouse. No way to force
-// evaluation or seed history directly, so we poll until rows appear.
-
-/**
- * Default timeout for waitForTimelineEntries.
- *
- * Logs rules need 2+ ruler cycles (~15s each) to see 25 services fire.
- * 90s = 6 cycles worst-case. Actual time: 20-35s for logs, ~10s for metrics.
- */
-export const WAIT_TIMELINE_ENTRIES_DEFAULT = 90_000;
-
-/**
- * Default timeout for waitForTimelineStates (firing + resolved).
- *
- * Resolved state appears after evalWindow expires with no matching data.
- * 1m window + 2 ruler cycles = ~105s observed. 180s = safe margin.
- */
-export const WAIT_TIMELINE_STATES_DEFAULT = 180_000;
diff --git a/tests/e2e/helpers/alerts/history.ts b/tests/e2e/helpers/alerts/history.ts
deleted file mode 100644
index 782a1eebd2..0000000000
--- a/tests/e2e/helpers/alerts/history.ts
+++ /dev/null
@@ -1,359 +0,0 @@
-import {
- expect,
- type Locator,
- type Page,
- type Request,
- type Response,
-} from '@playwright/test';
-
-import { authToken, requestUrl } from '../common';
-import { typeExpression } from '../query-builder';
-
-import {
- ALERT_HISTORY_PATH,
- DEFAULT_RELATIVE_TIME,
- TIMELINE_PAGE_SIZE,
- WAIT_TIMELINE_ENTRIES_DEFAULT,
- WAIT_TIMELINE_STATES_DEFAULT,
-} from './constants';
-import type { TimelineItem, TimelineResponse } from './types';
-
-// ─── History API probes ──────────────────────────────────────────────────
-
-/**
- * Read the timeline straight from the API. Used to gate on the ruler having
- * produced rows *before* a spec opens the UI — polling through the browser
- * would conflate "no rows yet" with "the table failed to render".
- */
-export async function fetchTimeline(
- page: Page,
- ruleId: string,
- params: Record<string, string | number> = {},
-): Promise<TimelineResponse> {
- const token = await authToken(page);
- const now = Date.now();
- const query = new URLSearchParams({
- start: String(now - 30 * 60 * 1000),
- end: String(now),
- limit: '100',
- order: 'asc',
- ...Object.fromEntries(Object.entries(params).map(([k, v]) => [k, String(v)])),
- });
- const res = await page.request.get(
- `/api/v2/rules/${ruleId}/history/timeline?${query.toString()}`,
- { headers: { Authorization: `Bearer ${token}` } },
- );
- if (!res.ok()) {
- throw new Error(
- `GET /api/v2/rules/${ruleId}/history/timeline ${res.status()}: ${await res.text()}`,
- );
- }
- const json = (await res.json()) as { data: TimelineResponse | null };
- return {
- items: json.data?.items ?? [],
- total: json.data?.total ?? 0,
- nextCursor: json.data?.nextCursor,
- };
-}
-
-function countStates(items: TimelineItem[]): Record<string, number> {
- return items.reduce<Record<string, number>>((acc, item) => {
- acc[item.state] = (acc[item.state] ?? 0) + 1;
- return acc;
- }, {});
-}
-
-/**
- * Poll until at least `min` rows in state `state` exist. Takes ~20-35s for the
- * logs fixture (the rule fires on the first evaluation that sees the data) and
- * ~10s for the metrics one, so budget generously — a timeout here means the
- * marker aged out of the eval window, not that the assertion is wrong.
- */
-export async function waitForTimelineEntries(
- page: Page,
- ruleId: string,
- {
- min,
- state = 'firing',
- timeoutMs = WAIT_TIMELINE_ENTRIES_DEFAULT,
- }: { min: number; state?: string; timeoutMs?: number },
-): Promise<TimelineResponse> {
- const deadline = Date.now() + timeoutMs;
- let last: TimelineResponse = { items: [], total: 0 };
- while (Date.now() < deadline) {
- // eslint-disable-next-line no-await-in-loop
- last = await fetchTimeline(page, ruleId);
- if (last.items.filter((item) => item.state === state).length >= min) {
- return last;
- }
- // eslint-disable-next-line no-await-in-loop
- await new Promise((resolve) => {
- setTimeout(resolve, 2_000);
- });
- }
- throw new Error(
- `timeline for rule ${ruleId} never reached ${min} '${state}' rows within ${timeoutMs}ms ` +
- `(last: total=${last.total}, states=${JSON.stringify(countStates(last.items))})`,
- );
-}
-
-/**
- * Poll until every requested state has at least the requested row count.
- * SEED-F's firing→resolved wave and SEED-G's `nodata` row both gate on this.
- */
-export async function waitForTimelineStates(
- page: Page,
- ruleId: string,
- {
- states,
- timeoutMs = WAIT_TIMELINE_STATES_DEFAULT,
- }: { states: Record<string, number>; timeoutMs?: number },
-): Promise<TimelineResponse> {
- const deadline = Date.now() + timeoutMs;
- let last: TimelineResponse = { items: [], total: 0 };
- while (Date.now() < deadline) {
- // eslint-disable-next-line no-await-in-loop
- last = await fetchTimeline(page, ruleId);
- const seen = countStates(last.items);
- if (
- Object.entries(states).every(([state, min]) => (seen[state] ?? 0) >= min)
- ) {
- return last;
- }
- // eslint-disable-next-line no-await-in-loop
- await new Promise((resolve) => {
- setTimeout(resolve, 3_000);
- });
- }
- throw new Error(
- `timeline for rule ${ruleId} never reached ${JSON.stringify(states)} within ${timeoutMs}ms ` +
- `(last states: ${JSON.stringify(countStates(last.items))})`,
- );
-}
-
-/** The filtered row count the timeline reports. Ignores `limit`. */
-export async function readTimelineTotal(
- page: Page,
- ruleId: string,
-): Promise<number> {
- return (await fetchTimeline(page, ruleId, { limit: 1 })).total;
-}
-
-/**
- * Mirror of `encodeCursor` in
- * `container/AlertHistory/Timeline/Table/useTimelineTableCursor.ts`, so specs
- * can assert the *exact* cursor the UI sends. Verified byte-identical to the
- * server's `nextCursor`.
- */
-export function encodeTimelineCursor(
- page_: number,
- limit = TIMELINE_PAGE_SIZE,
-): string | undefined {
- if (page_ <= 1) {
- return undefined;
- }
- const offset = (page_ - 1) * limit;
- return Buffer.from(JSON.stringify({ offset, limit }))
- .toString('base64')
- .replace(/\+/g, '-')
- .replace(/\//g, '_')
- .replace(/=+$/, '');
-}
-
-/** Labels on a timeline row, flattened to a plain object. */
-export function timelineLabelsToObject(
- item: TimelineItem,
-): Record<string, string> {
- return (item.labels ?? []).reduce<Record<string, string>>((acc, label) => {
- const name = label.key?.name;
- if (name) {
- acc[name] = String(label.value ?? '');
- }
- return acc;
- }, {});
-}
-
-// ─── Navigation ────────────────────────────────────────────────────────────
-
-/**
- * Open the history tab for `ruleId` and wait until the timeline table has
- * mounted. `params` is merged into the query string, so scenarios can deep-link
- * `page`, `order`, `timelineFilter`, … in one call.
- */
-export async function gotoAlertHistory(
- page: Page,
- ruleId: string,
- params: Record<string, string> = {},
-): Promise<void> {
- // An absolute window and `relativeTime` are mutually exclusive in practice:
- // with both present the time picker normalises back to the relative range and
- // **drops** `startTime`/`endTime` from the URL, so the absolute window never
- // takes effect. Only send the default relative range when no absolute one was
- // asked for.
- const hasAbsoluteRange = !!params.startTime && !!params.endTime;
- const query = new URLSearchParams({
- ruleId,
- ...(hasAbsoluteRange ? {} : { relativeTime: DEFAULT_RELATIVE_TIME }),
- ...params,
- });
- await page.goto(`${ALERT_HISTORY_PATH}?${query.toString()}`);
-
- // Race the table against the app's error boundary. The history page has been
- // observed crashing into it intermittently on load; without this the failure
- // reads as a 15s "timeline-table not found", which says nothing about why.
- const table = page.getByTestId('timeline-table');
- const crashed = page.getByText('Something went wrong :/');
- await expect(table.or(crashed)).toBeVisible();
- if (await crashed.isVisible()) {
- throw new Error(
- `alert history crashed into the app error boundary at ${page.url()} — ` +
- 'a component threw during render; check the captured console output',
- );
- }
- await expect(table).toBeVisible();
-
- // The `timeline-table` node is rendered by the first paint, *before* the
- // timeline request settles — antd only overlays a spinner on it. Returning
- // here would leave that request in flight, and the next
- // `waitForHistoryResponse` in the spec would resolve with the page's own
- // load instead of the response its interaction produced. Wait the spinner
- // out so every caller starts from a quiet page.
- await expect(page.locator('.timeline-table .ant-spin-spinning')).toHaveCount(
- 0,
- );
-}
-
-// ─── Locators ──────────────────────────────────────────────────────────────
-
-/**
- * Assert the table is back on page 1. Both the list and the timeline use nuqs
- * with `parseAsInteger.withDefault(1)`, which **removes** the `page` param when
- * it is reset rather than writing `page=1` — so "absent" and "1" are the same
- * state and a naive `?page=1` regex never matches.
- */
-export async function expectFirstPage(page: Page): Promise<void> {
- await expect
- .poll(() => new URL(page.url()).searchParams.get('page') ?? '1')
- .toBe('1');
-}
-
-export function timelineRows(page: Page): Locator {
- return page.getByTestId('timeline-row');
-}
-
-export function timelineFooterRange(page: Page): Locator {
- return page.getByTestId('timeline-footer-range');
-}
-
-export function statsCard(page: Page, title: string): Locator {
- return page.locator(`[data-testid="stats-card"][data-stats-title="${title}"]`);
-}
-
-/** Open the ACTIONS popover on timeline row `index` (0-based). */
-export async function openTimelineRowActions(
- page: Page,
- index: number,
-): Promise<void> {
- await timelineRows(page)
- .nth(index)
- .getByTestId('timeline-row-actions')
- .click();
-}
-
-// ─── History request matchers ──────────────────────────────────────────────
-
-/** The four v2 endpoints one history page load hits. */
-export const HISTORY_ENDPOINTS = [
- 'stats',
- 'timeline',
- 'top_contributors',
- 'overall_status',
-] as const;
-
-export type HistoryEndpoint = (typeof HISTORY_ENDPOINTS)[number];
-
-/** Match a request against one history endpoint, whatever the rule id. */
-export function isHistoryRequest(
- request: Request,
- endpoint: HistoryEndpoint,
-): boolean {
- return new RegExp(`/api/v2/rules/[^/]+/history/${endpoint}`).test(
- request.url(),
- );
-}
-
-/**
- * Wait for a history API response. Common pattern across history specs.
- *
- * Optionally narrow by HTTP status code or by the `filterExpression` the
- * request carried. The latter matters whenever a scenario reacts to *its own*
- * request: the page's own load is still in flight when the spec starts typing,
- * so an unqualified matcher happily resolves with that earlier response.
- */
-export function waitForHistoryResponse(
- page: Page,
- endpoint: HistoryEndpoint,
- options?: { status?: number; filterExpression?: string },
-): Promise<Response> {
- return page.waitForResponse((res) => {
- if (!isHistoryRequest(res.request(), endpoint)) return false;
- if (options?.status !== undefined && res.status() !== options.status)
- return false;
- if (
- options?.filterExpression !== undefined &&
- (requestUrl(res.request()).searchParams.get('filterExpression') ?? '') !==
- options.filterExpression
- )
- return false;
- return true;
- });
-}
-
-// ─── History interactions ──────────────────────────────────────────────────
-
-/** Apply a filter expression through the real editor + Run button. */
-export async function runFilterExpression(
- page: Page,
- expression: string,
-): Promise<void> {
- await typeExpression(page, expression);
- await page.getByRole('button', { name: /run query/i }).click();
-}
-
-/**
- * Sort the timeline descending through the STATE header.
- *
- * The antd table is *uncontrolled* — it has `sorter: true` but no `sortOrder`,
- * so its internal cycle is none → ascend → descend regardless of the `order`
- * the hook already sends. Reaching `desc` therefore takes two clicks, and the
- * first one only resets the page (asc is nuqs's default, so it writes no param).
- */
-export async function sortTimelineDescending(page: Page): Promise<void> {
- const header = page.getByRole('columnheader', { name: 'STATE' });
- const descRequest = page.waitForRequest(
- (req) =>
- isHistoryRequest(req, 'timeline') &&
- requestUrl(req).searchParams.get('order') === 'desc',
- );
- await header.click();
- await header.click();
- await descRequest;
-}
-
-/**
- * Snapshot the LABELS cell of every rendered row. Scenarios that compare two
- * snapshots taken at different times (page 1 vs page 2, one timezone vs
- * another) cannot express that as a web-first assertion, so the read lives in a
- * helper rather than inline in the test.
- */
-export async function timelineRowLabels(page: Page): Promise<string[]> {
- return timelineRows(page).getByTestId('timeline-row-labels').allInnerTexts();
-}
-
-/** Snapshot the first row's CREATED AT cell. See {@link timelineRowLabels}. */
-export async function firstTimelineRowCreatedAt(page: Page): Promise<string> {
- return timelineRows(page)
- .first()
- .getByTestId('timeline-row-created-at')
- .innerText();
-}
diff --git a/tests/e2e/helpers/alerts/navigation.ts b/tests/e2e/helpers/alerts/navigation.ts
deleted file mode 100644
index 2b4ce9b0b6..0000000000
--- a/tests/e2e/helpers/alerts/navigation.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-import { expect, type Locator, type Page } from '@playwright/test';
-
-import {
- ALERT_LIST_PAGE_SIZE,
- ALERT_OVERVIEW_PATH,
- ALERTS_LIST_PATH,
- DEFAULT_RELATIVE_TIME,
-} from './constants';
-
-// ─── Navigation ────────────────────────────────────────────────────────────
-
-/**
- * Open the alert overview (edit) page for `ruleId` and wait until it has fully
- * settled: the condition editor is visible and the query builder has finished
- * serializing the loaded query into the URL.
- */
-export async function gotoAlertOverview(
- page: Page,
- ruleId: string,
-): Promise<void> {
- await page.goto(`${ALERT_OVERVIEW_PATH}?ruleId=${ruleId}`);
- // `.first()` because a rule may have several thresholds, and the editor renders
- // one input per threshold. Without it this is a strict-mode violation that only
- // appears once the *second* row has rendered — i.e. a timing-dependent failure
- // for multi-threshold rules.
- await expect(page.getByTestId('threshold-value-input').first()).toBeVisible();
- // The builder rewrites location.search shortly after load (adds compositeQuery).
- await page.waitForURL(/compositeQuery=/, { timeout: 15_000 });
- // Let post-load state updates flush so callers read the settled value.
- // eslint-disable-next-line playwright/no-wait-for-timeout -- no DOM signal for the async settle
- await page.waitForTimeout(500);
-}
-
-/**
- * Open the alert details shell (Overview tab) for `ruleId` and wait until it has
- * mounted. Unlike {@link gotoAlertOverview} this does **not** wait for the
- * condition editor or the serialised query — use it for scenarios about the
- * shell itself (header, tabs, actions menu) rather than the rule's contents.
- */
-export async function gotoAlertDetails(
- page: Page,
- ruleId: string,
-): Promise<void> {
- await page.goto(
- `${ALERT_OVERVIEW_PATH}?ruleId=${ruleId}&relativeTime=${DEFAULT_RELATIVE_TIME}`,
- );
- await expect(page.getByTestId('alert-details-root')).toBeVisible();
-}
-
-/** Rows currently rendered in the alert-rules table body. */
-export function alertRuleRows(page: Page): Locator {
- return page.locator('tbody tr');
-}
-
-/**
- * Open the alert-rules list and wait until it has rows. `params` is merged into
- * the query string (`search`, `page`, `orderBy`, …); `limit` defaults to
- * {@link ALERT_LIST_PAGE_SIZE} so row counts are viewport-independent.
- *
- * Pass `expectRows: false` for scenarios whose filters are *meant* to match
- * nothing — the row wait would otherwise fail before the assertion runs.
- */
-export async function gotoAlertList(
- page: Page,
- params: Record<string, string> = {},
- { expectRows = true }: { expectRows?: boolean } = {},
-): Promise<void> {
- const query = new URLSearchParams({
- limit: String(ALERT_LIST_PAGE_SIZE),
- ...params,
- });
- await page.goto(`${ALERTS_LIST_PATH}?${query.toString()}`);
- await expect(page.getByTestId('list-alerts-search-input')).toBeVisible();
- if (expectRows) {
- // Skeleton rows are empty and ignore clicks; wait for a loaded one.
- await expect(alertRuleRows(page).first()).toHaveText(/\S/);
- }
-}
diff --git a/tests/e2e/helpers/alerts/seeding.ts b/tests/e2e/helpers/alerts/seeding.ts
deleted file mode 100644
index 0958b3b457..0000000000
--- a/tests/e2e/helpers/alerts/seeding.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-import { randomBytes } from 'crypto';
-
-import type { Page } from '@playwright/test';
-
-import { seederUrl } from '../common';
-
-import { createThresholdAlertViaApi } from './api';
-import { SEED_B_SEVERITIES } from './constants';
-import type {
- AlertRulesSeedOptions,
- LogsSeedOptions,
- MetricsSeedOptions,
- TracesSeedOptions,
-} from './types';
-
-// ─── Seeding telemetry ───────────────────────────────────────────────────
-
-async function postToSeeder(
- page: Page,
- path: string,
- data: unknown,
-): Promise<void> {
- const url = `${seederUrl()}${path}`;
- // The seeder shares one ClickHouse client, so concurrent POSTs from parallel
- // workers collide with a transient 500 "concurrent queries within the same
- // session". Retry those; anything else is real.
- const maxAttempts = 6;
- let lastStatus = 0;
- let lastText = '';
- for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
- // eslint-disable-next-line no-await-in-loop
- const res = await page.request.post(url, {
- data,
- headers: { 'Content-Type': 'application/json' },
- });
- if (res.ok()) {
- return;
- }
- lastStatus = res.status();
- // eslint-disable-next-line no-await-in-loop
- lastText = await res.text();
- if (!(lastStatus === 500 && lastText.includes('concurrent'))) {
- break;
- }
- // eslint-disable-next-line no-await-in-loop
- await new Promise((resolve) => {
- setTimeout(resolve, 150 * (attempt + 1) + Math.floor(Math.random() * 100));
- });
- }
- throw new Error(`seeder POST ${path} ${lastStatus}: ${lastText}`);
-}
-
-/**
- * Seed log records the history rules match on. Returns the generated
- * `service.name` values, which become the timeline rows' `groupBy` labels
- * (N distinct services ⇒ N distinct fingerprints ⇒ N timeline rows).
- *
- * Seed these **immediately** before creating the rule: the rule only fires
- * while the records are still inside its eval window, and a stale marker
- * silently never fires.
- */
-export async function seedAlertHistoryLogs(
- page: Page,
- {
- marker,
- services,
- recordsPerService = 2,
- ageSeconds = 150,
- minAgeSeconds = 30,
- servicePrefix = 'e2e-ah-svc',
- }: LogsSeedOptions,
-): Promise<string[]> {
- const now = Date.now();
- const span = Math.max(ageSeconds - minAgeSeconds, 1);
- const serviceNames: string[] = [];
- const records: Record<string, unknown>[] = [];
-
- for (let i = 0; i < services; i += 1) {
- const service = `${servicePrefix}-${i}`;
- serviceNames.push(service);
- for (let r = 0; r < recordsPerService; r += 1) {
- const fraction =
- (i * recordsPerService + r) / (services * recordsPerService);
- const offset = ageSeconds - Math.floor(fraction * span);
- records.push({
- timestamp: new Date(now - offset * 1000).toISOString(),
- body: marker,
- resources: { 'service.name': service },
- });
- }
- }
-
- await postToSeeder(page, '/telemetry/logs', records);
- return serviceNames;
-}
-
-/**
- * Seed spans the traces history rule matches on — one root span per
- * `service.name`, all sharing the span `name` marker. Returns the generated
- * service names (⇒ one timeline row each), same contract as
- * {@link seedAlertHistoryLogs}, and the same "seed immediately before creating
- * the rule" rule applies.
- */
-export async function seedAlertHistoryTraces(
- page: Page,
- {
- marker,
- services,
- spansPerService = 2,
- ageSeconds = 150,
- minAgeSeconds = 30,
- servicePrefix = 'e2e-aht-svc',
- }: TracesSeedOptions,
-): Promise<string[]> {
- const now = Date.now();
- const span = Math.max(ageSeconds - minAgeSeconds, 1);
- const serviceNames: string[] = [];
- const spans: Record<string, unknown>[] = [];
-
- for (let i = 0; i < services; i += 1) {
- const service = `${servicePrefix}-${i}`;
- serviceNames.push(service);
- for (let s = 0; s < spansPerService; s += 1) {
- const fraction = (i * spansPerService + s) / (services * spansPerService);
- const offset = ageSeconds - Math.floor(fraction * span);
- spans.push({
- timestamp: new Date(now - offset * 1000).toISOString(),
- trace_id: randomBytes(16).toString('hex'),
- span_id: randomBytes(8).toString('hex'),
- name: marker,
- kind: 2,
- duration: 'PT0.05S',
- resources: { 'service.name': service },
- });
- }
- }
-
- await postToSeeder(page, '/telemetry/traces', spans);
- return serviceNames;
-}
-
-/**
- * Seed a throwaway gauge the metrics rule alerts on. Cheaper than the logs
- * fixture (~10s to fire) and its history rows carry neither `relatedLogsLink`
- * nor `relatedTracesLink` — the "no links available" case.
- */
-export async function seedAlertHistoryMetrics(
- page: Page,
- {
- metricName,
- hosts,
- pointsPerHost = 3,
- groupByKey = 'host',
- }: MetricsSeedOptions,
-): Promise<void> {
- const now = Date.now();
- const points: Record<string, unknown>[] = [];
- for (const host of hosts) {
- for (let p = 0; p < pointsPerHost; p += 1) {
- points.push({
- metric_name: metricName,
- labels: { [groupByKey]: host },
- timestamp: new Date(now - (pointsPerHost - p) * 20 * 1000).toISOString(),
- value: 10 + p,
- type_: 'Gauge',
- temporality: 'Unspecified',
- is_monotonic: false,
- });
- }
- }
- await postToSeeder(page, '/telemetry/metrics', points);
-}
-
-/**
- * SEED-B: `count` metric threshold rules sharing one channel. Severities cycle
- * through {@link SEED_B_SEVERITIES} and every rule carries a `team` label, so
- * the list's "Alert Name, Severity and Labels" search has hits *and* misses for
- * all three. Even-indexed rules are `platform`, odd ones `payments` — i.e. half
- * the batch each. Returns the ids in creation order.
- */
-export async function seedAlertRules(
- page: Page,
- {
- count,
- channelName,
- namePrefix = 'e2e-alert-list',
- teamSuffix = '',
- }: AlertRulesSeedOptions,
-): Promise<string[]> {
- const ids: string[] = [];
- for (let i = 0; i < count; i += 1) {
- // Sequential on purpose: the rules API is not the thing under test and
- // parallel POSTs make failures harder to attribute.
- // eslint-disable-next-line no-await-in-loop
- const id = await createThresholdAlertViaApi(page, {
- name: `${namePrefix}-${String(i).padStart(2, '0')}`,
- target: 100 + i,
- channels: [channelName],
- labels: {
- severity: SEED_B_SEVERITIES[i % SEED_B_SEVERITIES.length],
- team: `${i % 2 === 0 ? 'platform' : 'payments'}${teamSuffix}`,
- },
- });
- ids.push(id);
- }
- return ids;
-}
diff --git a/tests/e2e/helpers/common.ts b/tests/e2e/helpers/common.ts
deleted file mode 100644
index df18f66678..0000000000
--- a/tests/e2e/helpers/common.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-import type { Page, Request } from '@playwright/test';
-
-import { storageKey } from './base-path';
-
-// Shared helpers used across feature-specific helper modules (dashboards,
-// trace-details, …). Keep this to genuinely cross-feature utilities.
-
-// ─── Seeder ────────────────────────────────────────────────────────────────
-
-// Base URL of the HTTP seeder container the pytest harness brings up (exposes
-// POST/DELETE on /telemetry/{traces,logs,metrics}). Written to
-// `tests/e2e/.env.local` as `SIGNOZ_E2E_SEEDER_URL` and read here from the env.
-export function seederUrl(): string {
- const url = process.env.SIGNOZ_E2E_SEEDER_URL;
- if (!url) {
- throw new Error(
- 'SIGNOZ_E2E_SEEDER_URL not set — pytest test_setup must be running.',
- );
- }
- return url;
-}
-
-// ─── Console / network noise ──────────────────────────────────────────────
-
-// Requests the bootstrap stack always fails, on every page, for reasons that
-// have nothing to do with the feature under test. Keep this list tiny and give
-// every entry a reason — it is a deny-list of *environment* noise, never of real
-// application errors.
-const HARNESS_FAILING_REQUESTS = [
- // Zeus is a WireMock stub with no /api/v2/zeus/hosts mapping, so the app
- // shell's workspace-URL lookup 404s on every page load. It reaches the console
- // three ways: the resource-load error, the AxiosError, and the literal `any`
- // that `api/ErrorResponseHandler.ts`'s fallback branch logs.
- '/api/v2/zeus/hosts',
- // The app shell polls GitHub for the latest release. Unauthenticated calls
- // from CI/dev machines get rate-limited (403), which has nothing to do with
- // the page under test.
- 'api.github.com',
-];
-
-// The console side of {@link HARNESS_FAILING_REQUESTS}. Browsers log a
-// resource-load error without the URL, so these have to be matched on text —
-// which is why the URL list above is the precise half of the check.
-const HARNESS_CONSOLE_NOISE = [
- 'Failed to load resource: the server responded with a status of 404 (Not Found)',
- 'Failed to load resource: the server responded with a status of 403',
- 'Request failed with status code 404',
- 'client never received a response, or request never left',
- 'ErrorResponseHandler: unclassified error',
- // Google Fonts, which the chromium project fails at DNS (playwright.config.ts).
- 'Failed to load resource: net::ERR_NAME_NOT_RESOLVED',
-];
-
-export interface ConsoleWatch {
- /** Console `error` entries and uncaught page errors, harness noise removed. */
- errors: string[];
- /** `"<status> <method> <url>"` for every 4xx/5xx, harness noise removed. */
- failedResponses: string[];
-}
-
-/**
- * Watch a page for console errors and failed requests. Call **before** the first
- * navigation; the returned object fills in as the page runs, so assert on it at
- * the end of the scenario.
- *
- * Console text alone is a weak signal (the harness's Zeus 404 produces three
- * generic-looking entries), so the failed-response list is the precise half:
- * text matching is deliberately loose while the URL check stays strict.
- */
-export function watchConsole(
- page: Page,
- /**
- * Extra substrings to ignore. Use this — with a comment naming the defect —
- * for a *known application* bug that is out of the spec's scope, so the rest
- * of the console assertion keeps its value instead of being deleted.
- */
- options: { ignore?: string[] } = {},
-): ConsoleWatch {
- const watch: ConsoleWatch = { errors: [], failedResponses: [] };
- const noise = [...HARNESS_CONSOLE_NOISE, ...(options.ignore ?? [])];
- const isNoise = (text: string): boolean =>
- noise.some((entry) => text.includes(entry));
-
- page.on('console', (msg) => {
- if (msg.type() === 'error' && !isNoise(msg.text())) {
- watch.errors.push(msg.text());
- }
- });
- page.on('pageerror', (err) => {
- if (!isNoise(String(err))) {
- watch.errors.push(String(err));
- }
- });
- page.on('response', (res) => {
- if (res.status() < 400) {
- return;
- }
- const url = res.url();
- if (HARNESS_FAILING_REQUESTS.some((entry) => url.includes(entry))) {
- return;
- }
- watch.failedResponses.push(
- `${res.status()} ${res.request().method()} ${url}`,
- );
- });
- return watch;
-}
-
-// ─── Network capture ──────────────────────────────────────────────────────
-
-/**
- * Every request the page issues from now on. Call **before** the first
- * navigation — the returned array fills in as the page runs, so filter it at the
- * end of the scenario ("endpoint called exactly once", "no legacy route used").
- */
-export function collectRequests(page: Page): Request[] {
- const requests: Request[] = [];
- page.on('request', (request) => requests.push(request));
- return requests;
-}
-
-/** A request's URL, parsed — the readable way to reach `searchParams`. */
-export function requestUrl(request: Request): URL {
- return new URL(request.url());
-}
-
-// ─── Auth ────────────────────────────────────────────────────────────────
-
-// Read the app JWT from the context's stored auth state. No navigation needed:
-// the auth fixture loads the admin storageState (localStorage AUTH_TOKEN) into
-// the context at creation, so storageState() returns it regardless of the page's
-// current URL. Server-side APIs need this as a Bearer token (auth is
-// JWT-in-localStorage, not cookies, so request.* doesn't carry it automatically).
-export async function authToken(page: Page): Promise<string> {
- const state = await page.context().storageState();
- for (const origin of state.origins) {
- const entry = origin.localStorage.find(
- (e) => e.name === storageKey('AUTH_TOKEN'),
- );
- if (entry) {
- return entry.value;
- }
- }
- throw new Error('AUTH_TOKEN not found in storage state — is the page authed?');
-}
diff --git a/tests/e2e/helpers/llm-o11y/attribute-mapping.ts b/tests/e2e/helpers/llm-o11y/attribute-mapping.ts
deleted file mode 100644
index e91c07f716..0000000000
--- a/tests/e2e/helpers/llm-o11y/attribute-mapping.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import type { APIRequestContext, Page } from '@playwright/test';
-
-export const ATTRIBUTE_MAPPING_PATH = '/ai-observability/attribute-mapping';
-export const ATTRIBUTE_MAPPING_PAGE_TESTID =
- 'llm-observability-attribute-mapping-page';
-
-/** Navigate to the Attribute Mapping page and wait for its root container. */
-export async function gotoAttributeMapping(page: Page): Promise<void> {
- await page.goto(ATTRIBUTE_MAPPING_PATH);
- await page
- .getByTestId(ATTRIBUTE_MAPPING_PAGE_TESTID)
- .waitFor({ state: 'visible' });
-}
-
-interface SpanMapperGroup {
- id: string;
- name: string;
-}
-
-/** List span-mapper groups via API (`GET /api/v1/span_mapper_groups`). */
-async function listSpanMapperGroups(
- request: APIRequestContext,
- token: string,
-): Promise<SpanMapperGroup[]> {
- const res = await request.get('/api/v1/span_mapper_groups', {
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- return [];
- }
- const body = (await res.json()) as { data?: { items?: SpanMapperGroup[] } };
- return body.data?.items ?? [];
-}
-
-export async function deleteSpanMapperGroupsByName(
- request: APIRequestContext,
- token: string,
- names: string[],
-): Promise<void> {
- const wanted = new Set(names);
- const groups = await listSpanMapperGroups(request, token).catch(() => []);
- await Promise.all(
- groups
- .filter((group) => wanted.has(group.name))
- .map((group) =>
- request
- .delete(`/api/v1/span_mapper_groups/${group.id}`, {
- headers: { Authorization: `Bearer ${token}` },
- })
- .catch(() => undefined),
- ),
- );
-}
diff --git a/tests/e2e/helpers/llm-o11y/llm-pricing.ts b/tests/e2e/helpers/llm-o11y/llm-pricing.ts
deleted file mode 100644
index 961d79eca8..0000000000
--- a/tests/e2e/helpers/llm-o11y/llm-pricing.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import type { APIRequestContext, Page } from '@playwright/test';
-
-export const LLM_PRICING_PATH = '/ai-observability/configuration';
-export const LLM_PRICING_PAGE_TESTID = 'llm-observability-model-pricing-page';
-
-export async function gotoLlmPricing(page: Page): Promise<void> {
- await page.goto(LLM_PRICING_PATH);
- await page.getByTestId(LLM_PRICING_PAGE_TESTID).waitFor({ state: 'visible' });
-}
-
-interface PricingRule {
- id: string;
- modelName: string;
-}
-
-/** List pricing rules via API (`GET /api/v1/llm_pricing_rules`). */
-async function listPricingRules(
- request: APIRequestContext,
- token: string,
-): Promise<PricingRule[]> {
- const res = await request.get('/api/v1/llm_pricing_rules', {
- params: { offset: 0, limit: 100 },
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- return [];
- }
- const body = (await res.json()) as {
- data?: { items?: PricingRule[] | null };
- };
- return body.data?.items ?? [];
-}
-
-export async function deletePricingRulesByModelName(
- request: APIRequestContext,
- token: string,
- modelNames: string[],
-): Promise<void> {
- const wanted = new Set(modelNames);
- const rules = await listPricingRules(request, token).catch(() => []);
- await Promise.all(
- rules
- .filter((rule) => wanted.has(rule.modelName))
- .map((rule) =>
- request
- .delete(`/api/v1/llm_pricing_rules/${rule.id}`, {
- headers: { Authorization: `Bearer ${token}` },
- })
- .catch(() => undefined),
- ),
- );
-}
diff --git a/tests/e2e/helpers/logs-explorer.ts b/tests/e2e/helpers/logs-explorer.ts
deleted file mode 100644
index f5653b416c..0000000000
--- a/tests/e2e/helpers/logs-explorer.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { expect, type Locator, type Page } from '@playwright/test';
-
-import { dismissQuickFiltersAnnouncement } from './quick-filters';
-
-const LOGS_EXPLORER_PATH = '/logs/logs-explorer';
-
-const RELATIVE_TIME = '6h';
-
-const FORMAT_OPTIONS_TEST_ID = 'periscope-btn-format-options';
-
-const ROW_TEST_ID_PREFIX = 'logs-table-row-';
-
-const LOG_DETAIL_DRAWER_TEST_ID = 'log-detail-drawer';
-export const LINKED_ROW_CLASS = 'logs-linked-row';
-
-type LogsFormat = 'Raw' | 'Default' | 'Column';
-
-const FORMAT_MODES: Record<LogsFormat, string> = {
- Raw: 'raw',
- Default: 'list',
- Column: 'table',
-};
-
-export async function gotoLogsExplorer(page: Page): Promise<void> {
- await dismissQuickFiltersAnnouncement(page);
- await page.goto(`${LOGS_EXPLORER_PATH}?relativeTime=${RELATIVE_TIME}`);
- await expect(page.getByTestId(FORMAT_OPTIONS_TEST_ID)).toBeVisible();
-}
-
-export async function setLogsFormat(
- page: Page,
- format: LogsFormat,
-): Promise<void> {
- const trigger = page.getByTestId(FORMAT_OPTIONS_TEST_ID);
- const popover = page.locator('.format-options-popover');
- const appliedMode = new RegExp(`%22format%22%3A%22${FORMAT_MODES[format]}%22`);
-
- await expect(async () => {
- if (!(await popover.isVisible())) {
- await trigger.click();
- await expect(popover).toBeVisible();
- }
- await popover
- .locator('.menu-items .item')
- .filter({ hasText: format })
- .click();
- await expect(page).toHaveURL(appliedMode, { timeout: 3_000 });
- }).toPass({ timeout: 20_000 });
-
- await trigger.click();
- await expect(popover).toBeHidden();
-}
-
-export function logsTableRows(page: Page): Locator {
- return page.locator(`[data-testid^="${ROW_TEST_ID_PREFIX}"]`);
-}
-
-export function logsTableRow(page: Page, logId: string): Locator {
- return page.getByTestId(`${ROW_TEST_ID_PREFIX}${logId}`);
-}
-
-export function highlightedLogsTableRows(page: Page): Locator {
- return logsTableRows(page).and(page.locator(`.${LINKED_ROW_CLASS}`));
-}
-
-export function unhighlightedLogsTableRows(page: Page): Locator {
- return page.locator(
- `[data-testid^="${ROW_TEST_ID_PREFIX}"]:not(.${LINKED_ROW_CLASS})`,
- );
-}
-
-export function activeLogIdFromUrl(page: Page): string {
- const value = new URL(page.url()).searchParams.get('activeLogId');
- if (!value) {
- throw new Error(`No activeLogId in URL: ${page.url()}`);
- }
- return value.replace(/"/g, '');
-}
-
-export function logDetailsDrawer(page: Page): Locator {
- return page.getByTestId(LOG_DETAIL_DRAWER_TEST_ID);
-}
-
-export async function clickRowFirstCell(row: Locator): Promise<void> {
- await row.locator('td').first().click();
-}
-
-export async function openLogDetailsFromRow(row: Locator): Promise<void> {
- await clickRowFirstCell(row);
- await expect(logDetailsDrawer(row.page())).toBeVisible();
-}
-
-export async function openContextView(page: Page): Promise<void> {
- await page
- .getByTestId('log-detail-views-tabs')
- .getByText('Context', { exact: true })
- .click();
- await expect(contextLogItems(page).first()).toBeVisible();
-}
-
-function contextLogItems(page: Page): Locator {
- return page.locator('.context-log-renderer__item');
-}
-
-export async function openFirstContextLogInNewTab(page: Page): Promise<Page> {
- const [newPage] = await Promise.all([
- page.context().waitForEvent('page'),
- contextLogItems(page).first().click(),
- ]);
- await newPage.waitForLoadState();
- return newPage;
-}
diff --git a/tests/e2e/helpers/query-builder.ts b/tests/e2e/helpers/query-builder.ts
deleted file mode 100644
index 2b8d420ad2..0000000000
--- a/tests/e2e/helpers/query-builder.ts
+++ /dev/null
@@ -1,36 +0,0 @@
-import { Page } from '@playwright/test';
-
-const EDITOR_CONTENT = '.query-where-clause-editor .cm-content';
-const SPANS = '.query-where-clause-editor .cm-line span';
-
-export async function typeExpression(page: Page, expr: string): Promise<void> {
- const editor = page.locator(EDITOR_CONTENT).first();
- await editor.waitFor({ state: 'visible', timeout: 15_000 });
- await editor.click();
- await page.keyboard.press('ControlOrMeta+a');
- await page.keyboard.press('Delete');
- await page.keyboard.type(expr);
- await page.waitForTimeout(300);
-}
-
-export async function tokenColor(
- page: Page,
- text: string,
-): Promise<string | null> {
- return page.evaluate(
- ({ selector, target }) => {
- const el = Array.from(
- document.querySelectorAll<HTMLSpanElement>(selector),
- ).find((s) => s.textContent === target);
- return el ? window.getComputedStyle(el).color : null;
- },
- { selector: SPANS, target: text },
- );
-}
-
-export async function setupTheme(
- page: Page,
- theme: 'dark' | 'light',
-): Promise<void> {
- await page.addInitScript((t) => localStorage.setItem('THEME', t), theme);
-}
diff --git a/tests/e2e/helpers/quick-filters.ts b/tests/e2e/helpers/quick-filters.ts
deleted file mode 100644
index d8da4cb5dc..0000000000
--- a/tests/e2e/helpers/quick-filters.ts
+++ /dev/null
@@ -1,167 +0,0 @@
-import { expect, type Locator, type Page } from '@playwright/test';
-
-import { authToken } from './common';
-
-export const LOGS_EXPLORER_PATH = '/logs/logs-explorer';
-
-const SETTINGS_PANEL_TITLE = 'Edit quick filters';
-const SETTINGS_ICON_TEST_ID = 'settings-icon';
-const SETTINGS_CLOSE_TEST_ID = 'quick-filters-settings-close';
-const ANNOUNCEMENT_DISMISSED_KEY = 'QUICK_FILTERS_SETTINGS_ANNOUNCEMENT';
-/**
- * Conservative lower bound for the open panel width. The panel is 342px in
- * QuickFiltersSettings.styles.scss; 300 leaves slack for sub-pixel rounding.
- */
-const SETTINGS_PANEL_MIN_WIDTH_PX = 300;
-
-// Pages that already had the announcement-dismissal init script registered.
-// addInitScript re-runs on every navigation, so registering once per Page keeps
-// the callback from stacking up across repeated helper calls.
-const announcementDismissed = new WeakSet<Page>();
-
-export type QuickFilterSignal = 'logs' | 'traces';
-
-export interface QuickFilterDefinition {
- key: string;
- dataType: string;
- type: string;
-}
-
-export const DEFAULT_CUSTOM_FILTERS: QuickFilterDefinition[] = [
- {
- key: 'service.name',
- dataType: 'string',
- type: 'resource',
- },
- {
- key: 'deployment.environment',
- dataType: 'string',
- type: 'resource',
- },
-];
-
-function settingsPanel(page: Page): Locator {
- return page
- .locator('.quick-filters-settings')
- .filter({ hasText: SETTINGS_PANEL_TITLE });
-}
-
-/** Minimal filter set so `isDynamicFilters` is true and the settings gear renders. */
-export async function seedCustomFiltersViaApi(
- page: Page,
- signal: QuickFilterSignal,
- filters: QuickFilterDefinition[] = DEFAULT_CUSTOM_FILTERS,
-): Promise<void> {
- const token = await authToken(page);
- const res = await page.request.put('/api/v1/orgs/me/filters', {
- data: { signal, filters },
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(
- `PUT /api/v1/orgs/me/filters ${res.status()}: ${await res.text()}`,
- );
- }
-}
-
-/**
- * Hide the one-off announcement tooltip so it cannot intercept the gear click.
- * Registered via addInitScript (not page.evaluate) so it runs in the app's own
- * origin on every navigation — evaluate() before goto() would set localStorage
- * on the pre-navigation about:blank origin, which the app never reads. Must be
- * called before the first goto(). Guarded to once per Page to avoid stacking.
- */
-export async function dismissQuickFiltersAnnouncement(
- page: Page,
-): Promise<void> {
- if (announcementDismissed.has(page)) {
- return;
- }
- await page.addInitScript((key) => {
- // Runs in the browser; Node's tsc has no DOM globals on this callback.
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- (globalThis as any).localStorage.setItem(key, 'false');
- }, ANNOUNCEMENT_DISMISSED_KEY);
- announcementDismissed.add(page);
-}
-
-export async function gotoExplorerWithQuickFilters(
- page: Page,
- path: string,
-): Promise<void> {
- await dismissQuickFiltersAnnouncement(page);
- await page.goto(path);
- await page.getByTestId(SETTINGS_ICON_TEST_ID).waitFor({ state: 'visible' });
-}
-
-/** Settings drawer is closed — content unmounted and gear not active. */
-export async function assertQuickFiltersSettingsDrawerClosed(
- page: Page,
-): Promise<void> {
- await expect(page.getByText(SETTINGS_PANEL_TITLE)).toBeHidden();
- // Collapsed panel keeps the `hidden` class (width: 0). Assert the class, not
- // toBeVisible() — a zero-width element is never "visible" to Playwright.
- await expect(page.locator('.quick-filters-settings')).toHaveClass(/hidden/);
-}
-
-/**
- * Click the settings gear. Pair with `assertQuickFiltersSettingsDrawerOpen` for
- * visibility/layout checks that guard overflow clipping regressions.
- */
-export async function openQuickFiltersSettingsPanel(page: Page): Promise<void> {
- await assertQuickFiltersSettingsDrawerClosed(page);
- await page.getByTestId(SETTINGS_ICON_TEST_ID).click();
-}
-
-/**
- * Assert the customization drawer is open, painted on screen, and populated with
- * the seeded filters — not merely present in the DOM.
- */
-export async function assertQuickFiltersSettingsDrawerOpen(
- page: Page,
- seededFilters: QuickFilterDefinition[] = DEFAULT_CUSTOM_FILTERS,
-): Promise<void> {
- const panel = settingsPanel(page);
- const filtersColumn = page.locator('.quick-filters');
-
- await expect(panel).toBeVisible();
- await expect(panel).not.toHaveClass(/hidden/);
- await expect(page.getByText(SETTINGS_PANEL_TITLE)).toBeVisible();
- await expect(page.getByPlaceholder('Search for a filter...')).toBeVisible();
- await expect(panel.getByTestId(SETTINGS_CLOSE_TEST_ID)).toBeVisible();
-
- const addedList = panel.locator('.qf-added-filters-list');
- await expect(panel.getByText('ADDED FILTERS')).toBeVisible();
- for (const filter of seededFilters) {
- await expect(addedList.getByText(filter.key, { exact: true })).toBeVisible();
- }
-
- // Footer only mounts after edits — absent on first open.
- await expect(panel.getByRole('button', { name: 'Discard' })).toBeHidden();
- await expect(panel.getByRole('button', { name: 'Save changes' })).toBeHidden();
-
- // OTHER FILTERS loads asynchronously from attribute/aggregate suggestions.
- await expect(panel.locator('.qf-other-filters-skeleton')).toHaveCount(0);
- await expect(panel.getByText('OTHER FILTERS')).toBeVisible();
- await expect(
- panel.locator('.qf-other-filters-list .other-filters-item').first(),
- ).toBeVisible();
-
- const [panelBox, columnBox] = await Promise.all([
- panel.boundingBox(),
- filtersColumn.boundingBox(),
- ]);
- expect(panelBox?.width ?? 0).toBeGreaterThanOrEqual(
- SETTINGS_PANEL_MIN_WIDTH_PX,
- );
- expect(columnBox).not.toBeNull();
- expect(panelBox!.x).toBeGreaterThanOrEqual(columnBox!.x);
-}
-
-/** Close via the drawer header X and confirm state resets. */
-export async function closeQuickFiltersSettingsPanel(
- page: Page,
-): Promise<void> {
- await settingsPanel(page).getByTestId(SETTINGS_CLOSE_TEST_ID).click();
- await assertQuickFiltersSettingsDrawerClosed(page);
-}
diff --git a/tests/e2e/helpers/sso.ts b/tests/e2e/helpers/sso.ts
deleted file mode 100644
index 68ba6b78b0..0000000000
--- a/tests/e2e/helpers/sso.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import { expect, type Locator, type Page } from '@playwright/test';
-
-import { authToken } from './common';
-
-// ─── Constants ───────────────────────────────────────────────────────────
-
-export const ORG_SETTINGS_PATH = '/settings/org-settings';
-
-// ─── Types ─────────────────────────────────────────────────────────────────
-
-export interface GoogleAuthDomainSeed {
- /** Domain name (e.g. `sso-edit.example.com`). Keep unique per test. */
- name: string;
- /** Enforce-SSO flag. Defaults to false. */
- enabled?: boolean;
- clientId?: string;
- clientSecret?: string;
- /**
- * Enables Google Workspace group fetching. The backend then requires
- * `serviceAccountJson` and `domainToAdminEmail`, and only with it may
- * `allowedGroups` be set.
- */
- fetchGroups?: boolean;
- serviceAccountJson?: string;
- domainToAdminEmail?: Record<string, string>;
- allowedGroups?: string[];
- roleMapping?: {
- defaultRole?: string;
- groupMappings?: Record<string, string>;
- useRoleAttribute?: boolean;
- };
-}
-
-// ─── API helpers ─────────────────────────────────────────────────────────
-
-/**
- * Seed a Google auth domain via POST /api/v2/auth_domains. Returns the new
- * domain ID. Pair with {@link deleteAuthDomainByNameViaApi} for cleanup.
- */
-export async function createGoogleAuthDomainViaApi(
- page: Page,
- seed: GoogleAuthDomainSeed,
-): Promise<string> {
- const token = await authToken(page);
-
- const spec: Record<string, unknown> = {
- clientId: seed.clientId ?? 'e2e-client-id.apps.googleusercontent.com',
- clientSecret: seed.clientSecret ?? 'e2e-client-secret',
- fetchGroups: seed.fetchGroups ?? false,
- insecureSkipEmailVerified: false,
- };
- if (seed.serviceAccountJson) {
- spec.serviceAccountJson = seed.serviceAccountJson;
- }
- if (seed.domainToAdminEmail) {
- spec.domainToAdminEmail = seed.domainToAdminEmail;
- }
- if (seed.allowedGroups) {
- spec.allowedGroups = seed.allowedGroups;
- }
-
- const res = await page.request.post('/api/v2/auth_domains', {
- data: {
- name: seed.name,
- enabled: seed.enabled ?? false,
- config: { kind: 'google', spec },
- roleMapping: seed.roleMapping,
- },
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(
- `POST /api/v2/auth_domains ${res.status()}: ${await res.text()}`,
- );
- }
- const json = (await res.json()) as { data: { id: string } };
- return json.data.id;
-}
-
-/** Delete an auth domain by ID (best-effort cleanup). */
-async function deleteAuthDomainViaApi(page: Page, id: string): Promise<void> {
- const token = await authToken(page);
- await page.request.delete(`/api/v2/auth_domains/${id}`, {
- headers: { Authorization: `Bearer ${token}` },
- });
-}
-
-/**
- * Delete any auth domain named `name`; a no-op when absent. Doubles as the
- * leftover guard before seeding (domain names are unique per org, so a
- * crashed earlier run would otherwise make the seed conflict).
- */
-export async function deleteAuthDomainByNameViaApi(
- page: Page,
- name: string,
-): Promise<void> {
- const token = await authToken(page);
- const res = await page.request.get('/api/v2/auth_domains', {
- headers: { Authorization: `Bearer ${token}` },
- });
- if (!res.ok()) {
- throw new Error(
- `GET /api/v2/auth_domains ${res.status()}: ${await res.text()}`,
- );
- }
- const json = (await res.json()) as {
- data: Array<{ id: string; name: string }> | null;
- };
- const match = (json.data ?? []).find((domain) => domain.name === name);
- if (match) {
- await deleteAuthDomainViaApi(page, match.id);
- }
-}
-
-// ─── Navigation ────────────────────────────────────────────────────────────
-
-/** Open org settings and wait for the Authenticated Domains section. */
-export async function gotoAuthDomains(page: Page): Promise<void> {
- await page.goto(ORG_SETTINGS_PATH);
- await expect(page.getByTestId('auth-domain-title')).toBeVisible();
-}
-
-/** Locate the list row for the domain named `name`. */
-export async function findAuthDomainRow(
- page: Page,
- name: string,
-): Promise<Locator> {
- const row = page.getByTestId(`auth-domain-row-${name}`);
- await row.waitFor({ state: 'attached' });
- return row;
-}
-
-/** Open the Configure (edit) modal for the domain row named `name`. */
-export async function openConfigureAuthDomain(
- page: Page,
- name: string,
-): Promise<void> {
- const row = await findAuthDomainRow(page, name);
- await row.getByTestId('auth-domain-configure').click();
- await expect(page.getByTestId('auth-domain-form')).toBeVisible();
-}
diff --git a/tests/e2e/playwright.config.ts b/tests/e2e/playwright.config.ts
index e3d75567d4..f544c54d11 100644
--- a/tests/e2e/playwright.config.ts
+++ b/tests/e2e/playwright.config.ts
@@ -50,20 +50,17 @@ export default defineConfig({
// Retry on CI only
retries: process.env.CI ? 2 : 0,
- // Workers. Playwright's local default is `cpus / 2`, which on a 32-core box is
- // 16 — and 16 is strictly worse than 6 here, because every worker's browser
- // shares one SigNoz container: measured on `tests/alerts/{create,edit}` at
- // `--repeat-each=3` (224 tests), 16 workers took 128 s with 3 failures while 6
- // took 119 s with none. Past ~6 the extra workers only add queueing, which shows
- // up as 4-6 s app mounts and save requests that outlive the test timeout — i.e.
- // as flakes that look like product bugs. Capped rather than fixed at 6 so a
- // 4-core laptop still gets `cpus / 2`.
+ // Capped at 6 rather than fixed, so a four-core laptop still gets `cpus / 2`.
+ // Past six, extra workers only queue behind the one shared SigNoz container —
+ // measured in `docs/flake-notes.md`.
workers: process.env.CI
? 2
: Math.max(1, Math.min(6, Math.floor(os.cpus().length / 2))),
- // The SPA hydrates slowly on CI, so the 5s expect default fires mid-load.
- expect: { timeout: 15_000 },
+ // The SPA hydrates slowly on CI, so the 5s expect default fires mid-load, and
+ // `toPass` needs its own budget because it reads `expect.toPass.timeout`
+ // rather than `expect.timeout` — see `docs/flake-notes.md`.
+ expect: { timeout: 15_000, toPass: { timeout: 20_000 } },
timeout: process.env.CI ? 60_000 : 30_000,
// Reporter
diff --git a/tests/e2e/testdata/dashboards/panels.ts b/tests/e2e/testdata/dashboards/panels.ts
index e8a02e3e0e..c51633b0dc 100644
--- a/tests/e2e/testdata/dashboards/panels.ts
+++ b/tests/e2e/testdata/dashboards/panels.ts
@@ -7,14 +7,14 @@ import {
panel,
promqlQuery,
rawQuery,
-} from '../../helpers/dashboard-spec';
+} from '../../drivers/dashboard-spec';
import type {
ContextLink,
PanelPluginSpec,
PostableDashboard,
Query,
Variable,
-} from '../../helpers/dashboard-spec.types';
+} from '../../drivers/dashboard-spec.types';
// Dashboard fixtures for the dashboard suites. TypeScript rather than frozen JSON so
// a contract change is a compile error, and panel ids stay visible to the specs
diff --git a/tests/e2e/tests/alerts/channels/edit.spec.ts b/tests/e2e/tests/alerts/channels/edit.spec.ts
deleted file mode 100644
index bec11a3d1f..0000000000
--- a/tests/e2e/tests/alerts/channels/edit.spec.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { expect, test } from '../../../fixtures/auth';
-import {
- createEmailChannelViaApi,
- deleteChannelViaApi,
-} from '../../../helpers/alerts/api';
-
-test.describe('Notification channels — edit', () => {
- // Regression guard for engineering-pod#5509: after channels moved from
- // /settings/channels to /alerts/channels, the edit container still parsed the
- // channel id out of the old pathname, so every save PUT went to an empty id
- // and no edit ever persisted. Nothing in the suite navigated into the edit
- // page, so the whole class of "edits silently do nothing" was invisible.
- //
- // The screen now reads and writes through /api/v2/notification_channels; the
- // seed helper still posts the v1 shape, which the same store backs.
- test('TC-01 an edited recipient persists after reload', async ({
- authedPage: page,
- }) => {
- // The channel *name* is read-only on the edit page, so the editable field
- // this exercises is the email recipient.
- const name = `e2e-nc-${Date.now()}`;
- const updatedTo = '[email protected]';
- const { id } = await createEmailChannelViaApi(page, name);
-
- try {
- await page.goto(`/alerts/channels/edit/${id}`);
-
- const toBox = page.getByRole('textbox', { name: 'To' });
- await expect(toBox).toHaveValue('[email protected]');
- await toBox.fill(updatedTo);
-
- await Promise.all([
- page.waitForResponse(
- (r) =>
- r.url().includes('/api/v2/notification_channels') &&
- r.request().method() === 'PUT',
- ),
- page.getByTestId('save-channel-button').click(),
- ]);
-
- await page.goto(`/alerts/channels/edit/${id}`);
- await expect(page.getByRole('textbox', { name: 'To' })).toHaveValue(
- updatedTo,
- );
- } finally {
- await deleteChannelViaApi(page, id);
- }
- });
-});
diff --git a/tests/e2e/tests/alerts/create.spec.ts b/tests/e2e/tests/alerts/create.spec.ts
new file mode 100644
index 0000000000..1ef485331f
--- /dev/null
+++ b/tests/e2e/tests/alerts/create.spec.ts
@@ -0,0 +1,431 @@
+import {
+ AlertListTab,
+ AlertType,
+ expect,
+ RuleType,
+ STOCK_ALERT_TYPE_CARDS,
+ test,
+ ThresholdMatchType,
+ ThresholdOperator,
+} from '../../drivers/alerts';
+
+// The create shell and the v2 builder, kept to what needs a real backend or a
+// real browser: type selection and its URL contract, the save round-trip, and
+// the error paths. The builder's own validation, threshold tiers, option lists
+// and payload shaping are asserted against the components in jest — see
+// `frontend/src/container/CreateAlertV2/**/__tests__/`.
+
+test.describe('Alert create', () => {
+ test('TC-01 the type cards render and picking one mounts the builder', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.form.gotoTypeSelection();
+
+ await expect(alerts.form.typeSelectionTitle()).toBeVisible();
+ for (const type of STOCK_ALERT_TYPE_CARDS) {
+ await expect(alerts.form.typeCard(type)).toBeVisible();
+ }
+ // Pins the exact set *and* order for whichever branch applies, so
+ // adding a sixth signal still fails here.
+ await alerts.form.expectTypeCardSet();
+
+ await alerts.form.typeCard(AlertType.METRICS).click();
+ await expect(alerts.form.name()).toBeVisible();
+
+ const params = new URL(page.url()).searchParams;
+ expect(params.get('ruleType')).toBe(RuleType.THRESHOLD);
+ expect(params.get('alertType')).toBe(AlertType.METRICS);
+ });
+
+ test('TC-02 the anomaly card rewrites the rule type, not the alert type', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.form.gotoTypeSelection();
+ test.skip(
+ !(await alerts.form.hasAnomalyCard()),
+ 'anomaly detection is unavailable on this stack',
+ );
+
+ await alerts.form.typeCard(AlertType.ANOMALY).click();
+
+ const params = new URL(page.url()).searchParams;
+ expect(params.get('ruleType')).toBe(RuleType.ANOMALY);
+ // The card's own value is deliberately *not* written: `handleSelectType`
+ // forces the metrics alert type for anomaly rules, and the form resolves
+ // back to anomaly from `ruleType` alone.
+ expect(params.get('alertType')).toBe(AlertType.METRICS);
+ });
+
+ test('TC-03 modifier-clicking a card opens the builder in a new tab', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.form.gotoTypeSelection();
+
+ const [newTab] = await Promise.all([
+ page.context().waitForEvent('page'),
+ alerts.form
+ .typeCard(AlertType.METRICS)
+ .click({ modifiers: ['ControlOrMeta'] }),
+ ]);
+
+ await newTab.waitForLoadState();
+ const params = new URL(newTab.url()).searchParams;
+ expect(params.get('ruleType')).toBe(RuleType.THRESHOLD);
+ expect(params.get('alertType')).toBe(AlertType.METRICS);
+ // A modifier click that *also* navigates in place is the regression.
+ await expect(alerts.form.typeCard(AlertType.METRICS)).toBeVisible();
+
+ await newTab.close();
+ });
+
+ test('TC-04 the breadcrumb gains a third crumb and navigates back', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.form.gotoTypeSelection();
+
+ await expect(alerts.shell.crumb('Alert Rules')).toBeVisible();
+ await expect(alerts.shell.crumb('Select Alert Type')).toBeVisible();
+
+ await alerts.form.typeCard(AlertType.METRICS).click();
+ await expect(alerts.form.name()).toBeVisible();
+ await expect(alerts.shell.crumb('Metric-Based Alert')).toBeVisible();
+
+ await alerts.shell.crumbButton('Select Alert Type').click();
+ await expect(alerts.form.typeCard(AlertType.METRICS)).toBeVisible();
+ expect(new URL(page.url()).searchParams.get('alertType')).toBeNull();
+ });
+
+ test('TC-05 create renders inside the Alert Rules tab and leaving drops subTab', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ // `subTab` and `search` are seeded so their removal is observable —
+ // `handleTabChange` deletes them while keeping everything else.
+ await alerts.form.gotoV2({
+ alertType: AlertType.LOGS,
+ params: { subTab: 'Alert Rules', search: 'stale' },
+ });
+ await expect(alerts.form.name()).toBeVisible();
+
+ await expect(alerts.shell.tab(/Alert Rules/)).toBeVisible();
+ await alerts.shell.tab(/Triggered Alerts/).click();
+
+ await page.waitForURL(/\/alerts\?/);
+ const params = new URL(page.url()).searchParams;
+ // The param carries the space-less enum value, not the visible label.
+ expect(params.get('tab')).toBe(AlertListTab.TRIGGERED_ALERTS);
+ expect(params.get('subTab')).toBeNull();
+ expect(params.get('search')).toBeNull();
+ });
+
+ test('TC-06 the classic experience replaces history rather than stacking it', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.form.gotoV1({ alertType: AlertType.METRICS });
+ await expect(alerts.form.v1SaveButton()).toBeVisible();
+ // The clearest v1/v2 discriminator: the v2 header input is not there.
+ await expect(alerts.form.name()).toBeHidden();
+
+ await alerts.form.gotoV2({ alertType: AlertType.METRICS });
+ await alerts.form.switchToClassicButton().click();
+
+ await expect(alerts.form.v1SaveButton()).toBeVisible();
+ expect(
+ new URL(page.url()).searchParams.get('showClassicCreateAlertsPage'),
+ ).toBe('true');
+
+ // `safeNavigate(url, { replace: true })` — going back must skip the v2 entry
+ // rather than bouncing between the two experiences.
+ await page.goBack();
+ await expect(alerts.form.name()).toBeHidden();
+ });
+
+ test('TC-07 a save posts the v2 shape, keeps its labels and lands on the list', async ({
+ authedPage: page,
+ alerts,
+ alertChannel,
+ ownedRules,
+ }) => {
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ const name = `e2e-create-${Date.now()}`;
+ await alerts.form.name().fill(name);
+
+ // Two thresholds, because the UI models one operator per rule while the
+ // schema stores one per threshold: a single change has to fan out.
+ await alerts.form.addThresholdButton().click();
+ await expect(alerts.form.thresholdRows()).toHaveCount(2);
+ await alerts.form.selectThresholdChannel(0, alertChannel.name);
+ await alerts.form.selectThresholdChannel(1, alertChannel.name);
+
+ await alerts.form.thresholdOperatorSelect().click();
+ await alerts.antd.option(ThresholdOperator.BELOW.label).click();
+
+ await alerts.form.addLabel('team', 'payments');
+ await expect(alerts.form.labelPill('team', 'payments')).toBeVisible();
+
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes('/api/v2/rules') && res.request().method() === 'POST',
+ ),
+ alerts.form.saveButton().click(),
+ ]);
+ await ownedRules.register(response);
+
+ expect(response.status()).toBe(201);
+ expect(new URL(response.url()).pathname).toBe('/api/v2/rules');
+
+ const body = response.request().postDataJSON();
+ expect(body.schemaVersion).toBe('v2alpha1');
+ expect(body.version).toBe('v5');
+ expect(body.alert).toBe(name);
+ // The label is asserted on the request rather than on the pill: the pill
+ // only proves local state, and the defect worth guarding is a label that
+ // renders but is never posted.
+ expect(body.labels).toMatchObject({ team: 'payments' });
+ expect(body.condition.thresholds.kind).toBe('basic');
+ expect(body.condition.thresholds.spec).toHaveLength(2);
+ expect(
+ body.condition.thresholds.spec.map((entry: { op: string }) => entry.op),
+ ).toEqual([ThresholdOperator.BELOW.value, ThresholdOperator.BELOW.value]);
+ expect(body.condition.thresholds.spec[0]).toMatchObject({
+ name: 'critical',
+ target: 0,
+ matchType: ThresholdMatchType.AT_LEAST_ONCE.value,
+ channels: [alertChannel.name],
+ targetUnit: '',
+ });
+ // The payload carries no recovery field at all.
+ expect(body.condition.thresholds.spec[0]).not.toHaveProperty(
+ 'recoveryTarget',
+ );
+
+ await expect(
+ alerts.shell.message('Alert rule created successfully'),
+ ).toBeVisible();
+ // `safeNavigate('/alerts')`; the list appends its own defaults afterwards.
+ await page.waitForURL(/\/alerts(\?|$)/);
+ expect(new URL(page.url()).pathname).toBe('/alerts');
+ });
+
+ test('TC-08 the evaluation window and cadence reach the payload', async ({
+ authedPage: page,
+ alerts,
+ alertChannel,
+ ownedRules,
+ }) => {
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ await alerts.form.name().fill(`e2e-create-eval-${Date.now()}`);
+ await alerts.form.selectThresholdChannel(0, alertChannel.name);
+
+ // One test because the two share a payload branch: `getEvaluationProps`
+ // emits `evalWindow` and `frequency` together, so a scenario changing only
+ // one would still pass with the other hardcoded.
+ await alerts.form.selectEvaluationTimeframe('30m0s');
+ await alerts.form.expandAdvancedOptions();
+ await alerts.form.evaluationCadenceInput().fill('5');
+
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes('/api/v2/rules') && res.request().method() === 'POST',
+ ),
+ alerts.form.saveButton().click(),
+ ]);
+ await ownedRules.register(response);
+
+ const { evaluation } = response.request().postDataJSON();
+ expect(evaluation.kind).toBe('rolling');
+ expect(evaluation.spec.evalWindow).toBe('30m0s');
+ // `getFormattedTimeValue` maps value + unit onto a Go duration; the unit
+ // stays at its default Minutes, which is what makes `5m` expected.
+ expect(evaluation.spec.frequency).toBe('5m');
+ });
+
+ test('TC-09 a test notification reports that a non-firing rule matched nothing', async ({
+ authedPage: page,
+ alerts,
+ alertChannel,
+ }) => {
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ await alerts.form.name().fill(`e2e-create-test-${Date.now()}`);
+ await alerts.form.selectThresholdChannel(0, alertChannel.name);
+
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes('/api/v2/rules/test') &&
+ res.request().method() === 'POST',
+ ),
+ alerts.form.testButton().click(),
+ ]);
+ expect(response.ok()).toBe(true);
+
+ // `alertCount === 0` is an *error* toast, not a success one: the rule
+ // evaluated fine, it just did not fire. Asserted permissively so a stack
+ // that happens to have matching data does not flip it.
+ await expect(
+ alerts.shell.message(
+ /No alerts found during the evaluation|sent successfully/,
+ ),
+ ).toBeVisible();
+ });
+
+ test('TC-10 with no channels, routing policies are the only way to save', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.form.stubNoChannels();
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ await alerts.form.name().fill(`e2e-create-nochan-${Date.now()}`);
+
+ const dropdown = await alerts.form.openChannelDropdown();
+
+ // `NotificationChannelsNotFoundContent` branches on role; the harness user
+ // is an admin, so this is the "create one here" half.
+ await expect(dropdown.emptyMessage()).toBeVisible();
+ await expect(dropdown.createHereButton()).toBeVisible();
+ await expect(dropdown.refreshButton()).toBeVisible();
+ await expect(dropdown.askAdminMessage()).toBeHidden();
+ await page.keyboard.press('Escape');
+ await expect(alerts.form.saveButton()).toBeDisabled();
+
+ await alerts.form.routingPoliciesSwitch().click();
+
+ // The threshold row *removes* its channel select rather than disabling it.
+ await expect(alerts.form.thresholdChannelSelects()).toHaveCount(0);
+ await expect(alerts.form.saveButton()).toBeEnabled();
+
+ await alerts.form.viewRoutingPoliciesButton().click();
+ await page.waitForURL(/subTab=routing-policies/);
+ const url = new URL(page.url());
+ expect(url.pathname).toBe('/alerts');
+ expect(url.searchParams.get('tab')).toBe('Configuration');
+ expect(url.searchParams.get('subTab')).toBe('routing-policies');
+ });
+
+ test('TC-11 Discard leaves without posting and resets the form', async ({
+ authedPage: page,
+ alerts,
+ alertChannel,
+ }) => {
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ await alerts.form.name().fill(`e2e-create-discard-${Date.now()}`);
+ await alerts.form.selectThresholdChannel(0, alertChannel.name);
+
+ let sawPost = false;
+ page.on('request', (request) => {
+ if (request.method() === 'POST' && request.url().includes('/api/v2/rules')) {
+ sawPost = true;
+ }
+ });
+
+ await alerts.form.discard();
+ await page.waitForURL(/\/alerts(\?|$)/);
+ expect(sawPost).toBe(false);
+
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ await expect(alerts.form.name()).toHaveValue('');
+ await expect(alerts.form.thresholdRows()).toHaveCount(1);
+ });
+
+ test('TC-12 a rejected save opens the error modal and keeps the draft', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ // The 4xx comes from a real race rather than a stub: a duplicate name is
+ // accepted by the API, a missing channel is not, so the form is filled with
+ // a channel that exists and the channel is deleted behind its back.
+ const channel = await alerts.seed.channel(`e2e-create-err-${Date.now()}`);
+
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ const name = `e2e-create-err-${Date.now()}`;
+ await alerts.form.name().fill(name);
+ await alerts.form.selectThresholdChannel(0, channel.name);
+
+ await alerts.seed.deleteChannel(channel.id);
+
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes('/api/v2/rules') && res.request().method() === 'POST',
+ ),
+ alerts.form.saveButton().click(),
+ ]);
+ expect(response.status()).toBe(400);
+
+ // Both forms funnel every save error into the shared error modal.
+ await expect(alerts.form.errorModal()).toBeVisible();
+ await expect(alerts.shell.message(/do not exist/)).toBeVisible();
+
+ // A rejected save must not navigate, and must not lose what was typed.
+ expect(new URL(page.url()).pathname).toBe('/alerts/new');
+ await alerts.form.errorModalCloseButton().click();
+ await expect(alerts.form.errorModal()).toBeHidden();
+ await expect(alerts.form.name()).toHaveValue(name);
+ });
+
+ test('TC-13 none of the four builder mounts logs a console error', async ({
+ alerts,
+ noise,
+ ownedRules,
+ }) => {
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+ // Metrics-based v1 on purpose: the only alert type whose classic form
+ // renders the detection-method step and the PromQL tab, i.e. the most code.
+ await alerts.form.gotoV1({ alertType: AlertType.METRICS });
+
+ await alerts.details.gotoOverview(
+ await ownedRules.threshold(`e2e-create-mount-v2-${Date.now()}`),
+ );
+
+ // The v1 edit form renders no `threshold-value-input`, so the shell-level
+ // wait is used and the classic form is asserted directly.
+ await alerts.details.goto(
+ await ownedRules.logs({
+ name: `e2e-create-mount-v1-${Date.now()}`,
+ schema: 'v1',
+ }),
+ );
+ await expect(alerts.form.v1SaveButton()).toBeVisible();
+
+ expect(noise.errors).toEqual([]);
+ });
+
+ // TODO: enable once the covered-Discard defect is fixed, and revert
+ // `alerts.form.discard()` to a plain `.click()` in the same commit.
+ //
+ // 🐞 **A user cannot discard an alert draft.** The footer is
+ // `position: fixed; left: 63px` — the *collapsed* nav rail width — while the
+ // side navigation is 240px wide whenever expanded, which is the default.
+ // Discard is the footer's left-most control, so the nav sits on top of it and
+ // wins the stacking contest despite the footer's `z-index: 1000`.
+ //
+ // Observed live: `elementFromPoint` at the button's centre returns the nav's
+ // `.nav-item-data`, and a real click fails with "intercepts pointer events".
+ // `{ force: true }` does not help. Only `dispatchEvent` gets through, which
+ // proves the handler is fine and the defect is pointer delivery.
+ test.skip('TC-14 the v2 Discard button is clickable', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.form.gotoV2({ alertType: AlertType.LOGS });
+
+ const box = await alerts.form.discardButton().boundingBox();
+ expect(box).not.toBeNull();
+ const covering = await alerts.form.elementAtPointClassName(
+ (box?.x ?? 0) + (box?.width ?? 0) / 2,
+ (box?.y ?? 0) + (box?.height ?? 0) / 2,
+ );
+ expect(covering).not.toMatch(/nav-item/);
+
+ await alerts.form.discardButton().click({ timeout: 3_000 });
+ await page.waitForURL(/\/alerts(\?|$)/);
+ expect(new URL(page.url()).pathname).toBe('/alerts');
+ });
+});
diff --git a/tests/e2e/tests/alerts/create/edge.spec.ts b/tests/e2e/tests/alerts/create/edge.spec.ts
deleted file mode 100644
index 54e7ba2073..0000000000
--- a/tests/e2e/tests/alerts/create/edge.spec.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import { AlertType } from '../../../helpers/alert-forms/constants';
-import {
- gotoCreateAlertV1,
- gotoCreateAlertV2,
-} from '../../../helpers/alert-forms/navigation';
-import { v1SaveButton } from '../../../helpers/alert-forms/v1';
-import {
- elementAtPointClassName,
- selectThresholdChannel,
- v2DiscardButton,
- v2SaveButton,
-} from '../../../helpers/alert-forms/v2';
-import {
- createEmailChannelViaApi,
- deleteChannelViaApi,
-} from '../../../helpers/alerts/api';
-import {
- gotoAlertDetails,
- gotoAlertOverview,
-} from '../../../helpers/alerts/navigation';
-import { watchConsole } from '../../../helpers/common';
-
-// TC-* — errors and edges that are not specific to one form.
-
-test.describe('Alert create — errors and edges', () => {
- test('TC-01 a server-side rejection opens the error modal and keeps the draft', async ({
- authedPage: page,
- }) => {
- // A duplicate rule name is *not* rejected — the API happily creates two rules
- // with the same `alert`. A missing channel is, with
- // `400 invalid_input: channels: the following channels do not exist`.
- //
- // So the 4xx comes from a real race rather than a stub: the form is filled with
- // a channel that exists, and the channel is deleted behind its back before the
- // save. Nothing about the response is faked.
- const channel = await createEmailChannelViaApi(
- page,
- `e2e-ce04-ch-${Date.now()}`,
- );
-
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- const name = `e2e-ce04-${Date.now()}`;
- await page.getByTestId('alert-name-input').fill(name);
- await selectThresholdChannel(page, 0, channel.name);
-
- await deleteChannelViaApi(page, channel.id);
-
- const [response] = await Promise.all([
- page.waitForResponse(
- (r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
- ),
- v2SaveButton(page).click(),
- ]);
- expect(response.status()).toBe(400);
-
- // Both forms funnel every save error into the shared error modal, which is
- // antd's wrapped in `.error-modal__wrap`.
- await expect(page.locator('.error-modal__wrap')).toBeVisible();
- await expect(page.getByText(/do not exist/)).toBeVisible();
-
- // A rejected save must not navigate, and must not lose what the user typed.
- expect(new URL(page.url()).pathname).toBe('/alerts/new');
- await page.getByTestId('close-button').click();
- await expect(page.locator('.error-modal__wrap')).toBeHidden();
- await expect(page.getByTestId('alert-name-input')).toHaveValue(name);
- });
-
- test('TC-02 none of the four builder mounts logs a console error', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const watch = watchConsole(page);
-
- // v2 create.
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- // v1 create. Metrics-based on purpose: it is the only alert type whose classic
- // form renders the detection-method step and the PromQL tab, i.e. the most code.
- await gotoCreateAlertV1(page, { alertType: AlertType.METRICS });
-
- // v2 edit.
- const v2Rule = await ownedRules.threshold(`e2e-ce07-v2-${Date.now()}`);
- await gotoAlertOverview(page, v2Rule);
-
- // v1 edit. `gotoAlertOverview` is wrong here — it waits for
- // `threshold-value-input`, which only the v2 builder renders — so the shell-level
- // wait is used and the classic form is asserted directly.
- const v1Rule = await ownedRules.logs({
- name: `e2e-ce07-v1-${Date.now()}`,
- schema: 'v1',
- });
- await gotoAlertDetails(page, v1Rule);
- await expect(v1SaveButton(page)).toBeVisible();
-
- expect(watch.errors).toEqual([]);
- });
-
- // TODO: enable once the covered-Discard bug is fixed, and revert
- // `v2ClickDiscard` (`helpers/alert-forms.ts`) to a plain `.click()` in the same
- // commit — CV2-22 and EV2-11 both go through it.
- //
- // 🐞 **A user cannot discard an alert draft.** The footer is
- // `position: fixed; left: 63px` — the *collapsed* nav rail width — while the side
- // navigation is 240px wide whenever expanded, which is the default (pinned for a
- // fresh admin) and also happens transiently on hover when unpinned. Discard is the
- // footer's left-most control, so the nav sits on top of it and wins the stacking
- // contest despite the footer's `z-index: 1000`.
- //
- // Observed live: `document.elementFromPoint` at the button's centre returns the
- // nav's `.nav-item-data`, and `page.click()` fails with
- // *"div.nav-item-data … intercepts pointer events"*. `{ force: true }` does not
- // help — it skips the actionability wait but still delivers a real mouse event at
- // those coordinates. Only `dispatchEvent('click')` gets through, which proves the
- // handler is fine and the defect is purely pointer delivery.
- //
- // Fix is one of: make the footer's `left` follow the nav's actual width, move
- // Discard to the right-hand group, or lift the footer out of the nav's stacking
- // context.
- test.skip('TC-03 the v2 Discard button is clickable', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- // Nothing from the side navigation may sit over the button's centre.
- const box = await v2DiscardButton(page).boundingBox();
- expect(box).not.toBeNull();
- const covering = await elementAtPointClassName(
- page,
- box!.x + box!.width / 2,
- box!.y + box!.height / 2,
- );
- expect(covering).not.toMatch(/nav-item/);
-
- // And the consequence that matters: a real click lands and leaves the form.
- await v2DiscardButton(page).click({ timeout: 3_000 });
- await page.waitForURL(/\/alerts(\?|$)/);
- expect(new URL(page.url()).pathname).toBe('/alerts');
- });
-});
diff --git a/tests/e2e/tests/alerts/create/prefill.spec.ts b/tests/e2e/tests/alerts/create/prefill.spec.ts
deleted file mode 100644
index 19385ad20d..0000000000
--- a/tests/e2e/tests/alerts/create/prefill.spec.ts
+++ /dev/null
@@ -1,266 +0,0 @@
-import type { Page } from '@playwright/test';
-
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- ALERTS_NEW_PATH,
- AlertType,
- type AlertTypeValue,
- RuleType,
- ThresholdMatchType,
- ThresholdOperator,
-} from '../../../helpers/alert-forms/constants';
-import { gotoCreateAlertV2 } from '../../../helpers/alert-forms/navigation';
-import {
- evaluationSettingsButton,
- thresholdRows,
-} from '../../../helpers/alert-forms/v2';
-import { gotoAlertOverview } from '../../../helpers/alerts/navigation';
-
-// TC-* — deep-link prefill.
-//
-// The contract is producer-agnostic (`context/resolveUrlAlertPrefill.ts`), but the
-// three producers do **not** write the same params: dashboards
-// (`buildAlertUrl`) and the explorer only ever emit query/panel params, while
-// metering (`MultiIngestionSettings`) is the sole producer of `ruleName`,
-// `yAxisUnit` and `evaluationWindowPreset`. CD-04 and CD-05 therefore drive the
-// *metering* URL shape — aiming them at a dashboard URL would test a link nobody
-// generates.
-
-/**
- * A `compositeQuery` param harvested from the app itself.
- *
- * Hand-writing the v5 envelope would be a second, drifting copy of the query
- * builder's serialiser — the thing these scenarios are *reading*, not testing. So
- * the builder is opened once, allowed to serialise its own default query into the
- * URL, and that exact value is reused as the deep link.
- */
-async function harvestCompositeQuery(
- page: Page,
- alertType: AlertTypeValue,
-): Promise<string> {
- await gotoCreateAlertV2(page, { alertType });
- const value = new URL(page.url()).searchParams.get('compositeQuery');
- if (!value) {
- throw new Error(
- 'the builder did not serialise a compositeQuery into the URL',
- );
- }
- return value;
-}
-
-/** `Threshold` as `context/types.ts` declares it — the shape the URL param carries. */
-function urlThreshold(
- overrides: Record<string, unknown>,
-): Record<string, unknown> {
- return {
- id: 'e2e-url-threshold',
- label: 'from-url',
- thresholdValue: 0,
- recoveryThresholdValue: null,
- unit: '',
- channels: [],
- color: '#e5484d',
- ...overrides,
- };
-}
-
-function prefillUrl(params: Record<string, string>): string {
- return `${ALERTS_NEW_PATH}?${new URLSearchParams(params).toString()}`;
-}
-
-test.describe('Alert create — deep-link prefill', () => {
- test('TC-01 a compositeQuery alone selects the alert type', async ({
- authedPage: page,
- }) => {
- const compositeQuery = await harvestCompositeQuery(page, AlertType.LOGS);
-
- // No `alertType` and no `ruleType` in this URL: both come from the query's data
- // source through `ALERT_TYPE_VS_SOURCE_MAPPING`. The presence of
- // `compositeQuery` is also what skips the type-selection page, so this one
- // param decides two things at once.
- await page.goto(prefillUrl({ compositeQuery }));
-
- await expect(page.getByTestId('alert-name-input')).toBeVisible();
-
- // Asserted on the *rendered* signal tab, not on the URL: the mapping only feeds
- // the memo that picks the form — it does **not** write `alertType` back into the
- // query string. So a spec waiting for `alertType=LOGS_BASED_ALERT` in the URL
- // waits forever.
- await expect(
- page.locator('.list-view-tab.active-tab', {
- has: page.getByTestId('logs-view'),
- }),
- ).toHaveCount(1);
- expect(new URL(page.url()).searchParams.get('alertType')).toBeNull();
-
- // A stale `compositeQuery` silently bypasses card selection, so the cards must
- // not be on screen.
- await expect(page.locator('[data-testid^="alert-type-card-"]')).toHaveCount(
- 0,
- );
- });
-
- test('TC-02 thresholds prefill from JSON, and a malformed value falls back', async ({
- authedPage: page,
- }) => {
- const base = {
- alertType: AlertType.LOGS,
- ruleType: RuleType.THRESHOLD,
- };
-
- await page.goto(
- prefillUrl({
- ...base,
- thresholds: JSON.stringify([
- urlThreshold({ label: 'page-me', thresholdValue: 42 }),
- urlThreshold({
- id: 'e2e-url-threshold-2',
- label: 'warn-me',
- thresholdValue: 7,
- }),
- ]),
- }),
- );
-
- await expect(thresholdRows(page)).toHaveCount(2);
- const names = page.getByTestId('threshold-name-input');
- await expect(names.nth(0)).toHaveValue('page-me');
- await expect(names.nth(1)).toHaveValue('warn-me');
- await expect(page.getByTestId('threshold-value-input').nth(0)).toHaveValue(
- '42',
- );
-
- // A malformed value is swallowed by `parseThresholds` and the form falls back to
- // its own single `critical` row. That path also writes
- // `console.error('Error parsing thresholds from URL:', …)`, which is why this
- // scenario must never be paired with CE-07's clean-console assertion.
- await page.goto(prefillUrl({ ...base, thresholds: 'not-json-at-all' }));
- await expect(thresholdRows(page)).toHaveCount(1);
- await expect(page.getByTestId('threshold-name-input')).toHaveValue(
- 'critical',
- );
- });
-
- test('TC-03 matchType and compareOp aliases normalise to the enum', async ({
- authedPage: page,
- }) => {
- // `avg` and `<` are aliases the *backend* accepts (`normalizeMatchType` /
- // `normalizeOperator` mirror `pkg/types/ruletypes/{match,compare}.go`), not values
- // the UI ever writes — so a producer or a hand-edited link can carry them.
- await page.goto(
- prefillUrl({
- alertType: AlertType.LOGS,
- ruleType: RuleType.THRESHOLD,
- matchType: 'avg',
- compareOp: '<',
- }),
- );
-
- await expect(
- page.getByTestId('alert-threshold-match-type-select'),
- ).toContainText(ThresholdMatchType.ON_AVERAGE.label);
- await expect(
- page.getByTestId('alert-threshold-operator-select'),
- ).toContainText(ThresholdOperator.BELOW.label);
- });
-
- test('TC-04 ruleName and yAxisUnit apply once and never stomp an edit', async ({
- authedPage: page,
- }) => {
- const compositeQuery = await harvestCompositeQuery(page, AlertType.METRICS);
- const ruleName =
- '[ingestion][logs] e2e key has exceeded daily ingestion limit';
-
- // The metering URL shape, verbatim from `MultiIngestionSettings.tsx`.
- await page.goto(
- prefillUrl({
- compositeQuery,
- thresholds: JSON.stringify([
- urlThreshold({ label: 'critical', thresholdValue: 100, unit: 'bytes' }),
- ]),
- ruleName,
- yAxisUnit: 'bytes',
- matchType: ThresholdMatchType.IN_TOTAL.value,
- evaluationWindowPreset: 'meter',
- }),
- );
-
- await expect(page.getByTestId('alert-name-input')).toHaveValue(ruleName);
- // `yAxisUnit` is what makes the per-threshold unit select usable at all — with no
- // unit the control is permanently disabled (CV2-12).
- await expect(
- page.getByTestId('threshold-unit-select').first(),
- ).not.toHaveClass(/ant-select-disabled/);
-
- // Now the half the `ruleNameAppliedRef` / `yAxisUnitAppliedRef` guards exist for.
- // The prefill effect re-runs on *every* change to location.search, and the query
- // builder rewrites it constantly — without the refs, a hand-edited name would be
- // silently reverted to the URL's the next time that happened.
- const edited = 'e2e-cd-04-renamed-by-hand';
- await page.getByTestId('alert-name-input').fill(edited);
-
- // Switching the signal tab is a real user action that rewrites the URL *and*
- // changes `alertType`, which is also in the effect's dependency list.
- await page.getByTestId('logs-view').click();
- await page.waitForURL(/alertType=LOGS_BASED_ALERT/);
-
- await expect(page.getByTestId('alert-name-input')).toHaveValue(edited);
- });
-
- test('TC-05 evaluationWindowPreset=meter switches to the cumulative daily window', async ({
- authedPage: page,
- }) => {
- const compositeQuery = await harvestCompositeQuery(page, AlertType.METRICS);
-
- await page.goto(
- prefillUrl({
- compositeQuery,
- matchType: ThresholdMatchType.IN_TOTAL.value,
- evaluationWindowPreset: 'meter',
- }),
- );
-
- // `SET_INITIAL_STATE_FOR_METER` is a *cumulative* window starting at midnight
- // UTC — not one of the rolling presets — so the trigger button's whole text
- // changes shape, type included.
- await expect(evaluationSettingsButton(page)).toContainText('Cumulative');
- await expect(evaluationSettingsButton(page)).toContainText(
- 'Current day, starting from 00:00:00 (UTC)',
- );
- });
-
- test('TC-06 URL prefill is ignored in edit mode', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(`e2e-cd-06-${Date.now()}`, {
- target: 42,
- });
-
- await gotoAlertOverview(page, ruleId);
- // Append a prefill param to the *edit* URL, which is what a stale link or a copied
- // query string produces in practice.
- await page.goto(
- `${new URL(page.url()).pathname}?${new URLSearchParams({
- ruleId,
- thresholds: JSON.stringify([
- urlThreshold({ label: 'from-url', thresholdValue: 999 }),
- ]),
- }).toString()}`,
- );
-
- await expect(page.getByTestId('threshold-value-input').first()).toBeVisible();
-
- // The effect early-returns in edit mode. Without that return the `RESET` at the
- // top of the block would wipe the loaded rule's thresholds every time the query
- // builder rewrote location.search.
- await expect(thresholdRows(page)).toHaveCount(1);
- await expect(page.getByTestId('threshold-name-input')).toHaveValue(
- 'critical',
- );
- await expect(page.getByTestId('threshold-value-input')).toHaveValue('42');
- await expect(page.getByTestId('alert-name-input')).not.toHaveValue(
- 'from-url',
- );
- });
-});
diff --git a/tests/e2e/tests/alerts/create/shell.spec.ts b/tests/e2e/tests/alerts/create/shell.spec.ts
deleted file mode 100644
index e001eebf1f..0000000000
--- a/tests/e2e/tests/alerts/create/shell.spec.ts
+++ /dev/null
@@ -1,170 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- AlertListTab,
- AlertType,
- RuleType,
- STOCK_ALERT_TYPE_CARDS,
-} from '../../../helpers/alert-forms/constants';
-import {
- alertTypeCard,
- createAlertUrl,
- expectAlertTypeCardSet,
- gotoAlertTypeSelection,
- gotoCreateAlertV1,
- gotoCreateAlertV2,
- hasAnomalyAlertTypeCard,
-} from '../../../helpers/alert-forms/navigation';
-import { v1SaveButton } from '../../../helpers/alert-forms/v1';
-
-// TC-* — the create *shell*: type selection, how a card click writes the
-// URL, the breadcrumb, the surrounding alerts tab bar, and the two ways to reach
-// the classic form. Nothing here saves a rule, so no scenario needs a channel.
-
-test.describe('Alert create — shell & type selection', () => {
- test('TC-01 bare /alerts/new lists exactly the expected alert-type cards', async ({
- authedPage: page,
- }) => {
- await gotoAlertTypeSelection(page);
-
- await expect(page.getByText('Choose a type for the alert')).toBeVisible();
-
- // The four stock signals are unconditional; anomaly is added only when
- // ANOMALY_DETECTION is active. `expectAlertTypeCardSet` pins the exact set *and
- // order* for whichever branch applies, so adding a sixth signal still fails.
- for (const type of STOCK_ALERT_TYPE_CARDS) {
- await expect(alertTypeCard(page, type)).toBeVisible();
- }
- await expectAlertTypeCardSet(page);
- });
-
- test('TC-02 picking a card writes both params and mounts the v2 builder', async ({
- authedPage: page,
- }) => {
- await gotoAlertTypeSelection(page);
- await alertTypeCard(page, AlertType.METRICS).click();
-
- await expect(page.getByTestId('alert-name-input')).toBeVisible();
-
- const params = new URL(page.url()).searchParams;
- expect(params.get('ruleType')).toBe(RuleType.THRESHOLD);
- expect(params.get('alertType')).toBe(AlertType.METRICS);
- });
-
- test('TC-03 the anomaly card rewrites the rule type, not the alert type', async ({
- authedPage: page,
- }) => {
- await gotoAlertTypeSelection(page);
-
- test.skip(
- !(await hasAnomalyAlertTypeCard(page)),
- 'ANOMALY_DETECTION feature flag is inactive on this stack (see CS-01)',
- );
-
- await alertTypeCard(page, AlertType.ANOMALY).click();
-
- const params = new URL(page.url()).searchParams;
- expect(params.get('ruleType')).toBe(RuleType.ANOMALY);
- // The card's own value is deliberately *not* written: `handleSelectType`
- // forces the metrics alert type for anomaly rules, and the rendered form
- // resolves back to anomaly from `ruleType` alone.
- expect(params.get('alertType')).toBe(AlertType.METRICS);
- });
-
- test('TC-04 modifier-clicking a card opens the builder in a new tab', async ({
- authedPage: page,
- }) => {
- await gotoAlertTypeSelection(page);
-
- const [newTab] = await Promise.all([
- page.context().waitForEvent('page'),
- alertTypeCard(page, AlertType.METRICS).click({
- modifiers: ['ControlOrMeta'],
- }),
- ]);
-
- await newTab.waitForLoadState();
- const params = new URL(newTab.url()).searchParams;
- expect(params.get('ruleType')).toBe(RuleType.THRESHOLD);
- expect(params.get('alertType')).toBe(AlertType.METRICS);
-
- // A modifier click that *also* navigates in place is the regression this half
- // guards.
- await expect(alertTypeCard(page, AlertType.METRICS)).toBeVisible();
-
- await newTab.close();
- });
-
- test('TC-05 breadcrumb gains a third crumb after a type is picked', async ({
- authedPage: page,
- }) => {
- await gotoAlertTypeSelection(page);
-
- const breadcrumb = page.locator('.ant-breadcrumb');
- await expect(breadcrumb.getByText('Alert Rules')).toBeVisible();
- await expect(breadcrumb.getByText('Select Alert Type')).toBeVisible();
-
- await alertTypeCard(page, AlertType.METRICS).click();
- await expect(page.getByTestId('alert-name-input')).toBeVisible();
-
- await expect(breadcrumb.getByText('Metric-Based Alert')).toBeVisible();
-
- // The middle crumb is now navigable and goes back to bare /alerts/new.
- await breadcrumb.getByRole('button', { name: 'Select Alert Type' }).click();
- await expect(alertTypeCard(page, AlertType.METRICS)).toBeVisible();
- expect(new URL(page.url()).searchParams.get('alertType')).toBeNull();
- });
-
- test('TC-06 create renders inside the Alert Rules tab and leaving drops subTab/search', async ({
- authedPage: page,
- }) => {
- // `subTab` and `search` are seeded here precisely so their removal is
- // observable — `handleTabChange` deletes them while keeping everything else.
- await page.goto(
- createAlertUrl({
- alertType: AlertType.LOGS,
- params: { subTab: 'Alert Rules', search: 'stale' },
- }),
- );
- await expect(page.getByTestId('alert-name-input')).toBeVisible();
-
- await expect(page.getByRole('tab', { name: /Alert Rules/ })).toBeVisible();
- await page.getByRole('tab', { name: /Triggered Alerts/ }).click();
-
- await page.waitForURL(/\/alerts\?/);
- const params = new URL(page.url()).searchParams;
- // The param carries the space-less enum value, not the tab's visible label.
- expect(params.get('tab')).toBe(AlertListTab.TRIGGERED_ALERTS);
- expect(params.get('subTab')).toBeNull();
- expect(params.get('search')).toBeNull();
- });
-
- test('TC-07 showClassicCreateAlertsPage=true renders the v1 form instead', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV1(page, { alertType: AlertType.METRICS });
-
- await expect(v1SaveButton(page)).toBeVisible();
- // The clearest v1/v2 discriminator: the v2 header input simply is not there.
- await expect(page.getByTestId('alert-name-input')).toBeHidden();
- });
-
- test('TC-08 Switch to Classic Experience replaces history, so Back does not return to v2', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.METRICS });
-
- await page
- .getByRole('button', { name: 'Switch to Classic Experience' })
- .click();
-
- await expect(v1SaveButton(page)).toBeVisible();
- expect(
- new URL(page.url()).searchParams.get('showClassicCreateAlertsPage'),
- ).toBe('true');
-
- // `safeNavigate(url, { replace: true })` — going back must skip the v2 entry
- // entirely rather than bouncing between the two experiences.
- await page.goBack();
- await expect(page.getByTestId('alert-name-input')).toBeHidden();
- });
-});
diff --git a/tests/e2e/tests/alerts/create/v2.spec.ts b/tests/e2e/tests/alerts/create/v2.spec.ts
deleted file mode 100644
index 7077e05dbd..0000000000
--- a/tests/e2e/tests/alerts/create/v2.spec.ts
+++ /dev/null
@@ -1,569 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- AlertType,
- ThresholdMatchType,
- ThresholdOperator,
-} from '../../../helpers/alert-forms/constants';
-import { gotoCreateAlertV2 } from '../../../helpers/alert-forms/navigation';
-import {
- dropdownOption,
- openDropdown,
- ownDropdown,
- stubNoChannels,
-} from '../../../helpers/alert-forms/shared';
-import {
- addAlertLabel,
- advancedOptionToggle,
- evaluationCadenceInput,
- expandAdvancedOptions,
- labelPill,
- selectEvaluationTimeframe,
- selectThresholdChannel,
- thresholdRows,
- v2ClickDiscard,
- v2DiscardButton,
- v2SaveButton,
- v2SaveTooltip,
- v2TestButton,
-} from '../../../helpers/alert-forms/v2';
-import { BASE_PATH } from '../../../helpers/base-path';
-
-// CV2-* — the v2 create builder.
-//
-// Every scenario uses a **logs**-based alert unless it says otherwise: its default
-// query is valid with no seeded metrics. CV2-12 (unit select) and CV2-16 (group-by
-// select) are about what that choice costs — both are gated on query state a
-// default logs query does not provide, and both assert the gate.
-
-const VALIDATION = {
- name: 'Please enter an alert name',
- thresholdLabel: 'Please enter a label for each threshold',
- channels:
- 'Please select at least one channel for each threshold or enable routing policies',
-} as const;
-
-test.describe('Alert create — v2 builder', () => {
- test('CV2-01 initial state: one critical threshold, both actions gated', async ({
- authedPage: page,
- alertChannel,
- }) => {
- expect(alertChannel.name).toBeTruthy();
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- await expect(page.getByTestId('alert-name-input')).toHaveValue('');
- await expect(page.getByTestId('alert-name-input')).toHaveAttribute(
- 'placeholder',
- 'Enter alert rule name',
- );
-
- // `INITIAL_CRITICAL_THRESHOLD` — label `critical`, value 0, `channels: []`.
- // The empty channel list is what makes the save gate reachable at all.
- await expect(thresholdRows(page)).toHaveCount(1);
- await expect(page.getByTestId('threshold-name-input')).toHaveValue(
- 'critical',
- );
- await expect(page.getByTestId('threshold-value-input')).toHaveValue('0');
-
- await expect(v2SaveButton(page)).toBeDisabled();
- await expect(v2TestButton(page)).toBeDisabled();
- });
-
- test('CV2-02 the save tooltip walks from the name gate to the channel gate', async ({
- authedPage: page,
- alertChannel,
- }) => {
- expect(alertChannel.name).toBeTruthy();
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- // `validateCreateAlertState` returns the *first* failure, so the message order
- // encodes the validation order: name, then per-threshold label, then channels.
- expect(await v2SaveTooltip(page)).toBe(VALIDATION.name);
-
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-02-${Date.now()}`);
- expect(await v2SaveTooltip(page)).toBe(VALIDATION.channels);
- });
-
- test('CV2-03 clearing a threshold label re-gates the save', async ({
- authedPage: page,
- alertChannel,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-03-${Date.now()}`);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- // With a name and a channel the only remaining gate is the label.
- await expect(v2SaveButton(page)).toBeEnabled();
-
- await page.getByTestId('threshold-name-input').fill('');
- expect(await v2SaveTooltip(page)).toBe(VALIDATION.thresholdLabel);
- });
-
- test('CV2-04 a label added in the header survives the save round-trip', async ({
- authedPage: page,
- alertChannel,
- ownedRules,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- const name = `e2e-cv2-04-${Date.now()}`;
- await page.getByTestId('alert-name-input').fill(name);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- await addAlertLabel(page, 'team', 'payments');
- await expect(labelPill(page, 'team', 'payments')).toBeVisible();
-
- const [response] = await Promise.all([
- page.waitForResponse(
- (r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
- ),
- v2SaveButton(page).click(),
- ]);
- await ownedRules.register(response);
-
- // Asserted on the request body rather than on the pill: the pill only proves
- // local state, and the defect worth guarding is a label that renders but is
- // never posted.
- const body = response.request().postDataJSON();
- expect(body.labels).toMatchObject({ team: 'payments' });
- });
-
- test('CV2-05 a rejected label key surfaces as a notification, not an inline message', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- // Both rejection branches in `LabelsInput` — duplicate key and group-by key —
- // raise an antd **notification**, so a spec looking for inline text fails. Only
- // the duplicate branch is reachable here: the group-by branch needs a query that
- // already groups by something, which the default logs query does not.
- await addAlertLabel(page, 'team', 'payments');
- await expect(labelPill(page, 'team', 'payments')).toBeVisible();
-
- await page.getByTestId('alert-add-label-button').click();
- const input = page.getByTestId('alert-add-label-input');
- await input.fill('team');
- await input.press('Enter');
-
- await expect(
- page.getByText('Label with this key already exists'),
- ).toBeVisible();
- // Rejected, so no second pill appeared.
- await expect(page.locator('[data-testid^="label-pill-team-"]')).toHaveCount(
- 1,
- );
- });
-
- test('CV2-06 CV2-07 the operator and match-type selects offer the documented options', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- await page.getByTestId('alert-threshold-operator-select').click();
- // Exact-text matching, because `hasText: 'EQUAL TO'` also matches the
- // `NOT EQUAL TO` option and the count assertion then reads 2.
- for (const operator of Object.values(ThresholdOperator)) {
- await expect(dropdownOption(page, operator.label)).toHaveCount(1);
- }
- await expect(
- openDropdown(page).locator('.ant-select-item-option'),
- ).toHaveCount(Object.keys(ThresholdOperator).length);
- await page.keyboard.press('Escape');
-
- await page.getByTestId('alert-threshold-match-type-select').click();
- for (const matchType of Object.values(ThresholdMatchType)) {
- await expect(dropdownOption(page, matchType.label)).toHaveCount(1);
- }
- await expect(
- openDropdown(page).locator('.ant-select-item-option'),
- ).toHaveCount(Object.keys(ThresholdMatchType).length);
- });
-
- test('CV2-08 the operator is rule-wide: one change reaches every threshold', async ({
- authedPage: page,
- alertChannel,
- ownedRules,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-08-${Date.now()}`);
-
- await page.getByTestId('add-threshold-button').click();
- await expect(thresholdRows(page)).toHaveCount(2);
- await selectThresholdChannel(page, 0, alertChannel.name);
- await selectThresholdChannel(page, 1, alertChannel.name);
-
- await page.getByTestId('alert-threshold-operator-select').click();
- await dropdownOption(page, ThresholdOperator.BELOW.label).click();
-
- const [response] = await Promise.all([
- page.waitForResponse(
- (r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
- ),
- v2SaveButton(page).click(),
- ]);
- await ownedRules.register(response);
-
- // The UI models one operator per rule while the schema stores one per
- // threshold, so a single change is fanned out across `spec[]`.
- const spec = response.request().postDataJSON().condition.thresholds.spec;
- expect(spec).toHaveLength(2);
- expect(spec.map((entry: { op: string }) => entry.op)).toEqual([
- ThresholdOperator.BELOW.value,
- ThresholdOperator.BELOW.value,
- ]);
- });
-
- test('CV2-09 CV2-10 added thresholds take preset tiers, and the first cannot be removed', async ({
- authedPage: page,
- alertChannel,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- // `addThreshold` branches on the current count: 2nd ⇒ warning, 3rd ⇒ info,
- // 4th and beyond ⇒ an unnamed row with a random colour.
- await page.getByTestId('add-threshold-button').click();
- await page.getByTestId('add-threshold-button').click();
- await page.getByTestId('add-threshold-button').click();
- await expect(thresholdRows(page)).toHaveCount(4);
-
- const names = page.getByTestId('threshold-name-input');
- await expect(names.nth(0)).toHaveValue('critical');
- await expect(names.nth(1)).toHaveValue('warning');
- await expect(names.nth(2)).toHaveValue('info');
- await expect(names.nth(3)).toHaveValue('');
-
- // `showRemoveButton` is `index !== 0 && length > 1`, so there are three remove
- // buttons for four rows and the first row can never be removed.
- await expect(page.getByTestId('remove-threshold-button')).toHaveCount(3);
-
- // To see the unnamed row's own gate, the earlier gates have to be satisfied
- // first: `validateCreateAlertState` loops thresholds and returns on the first
- // failure, checking label *then* channels **per threshold** — so with row 0
- // lacking a channel the channel message wins before row 3 is ever examined.
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-09-${Date.now()}`);
- for (const index of [0, 1, 2, 3]) {
- // eslint-disable-next-line no-await-in-loop
- await selectThresholdChannel(page, index, alertChannel.name);
- }
- expect(await v2SaveTooltip(page)).toBe(VALIDATION.thresholdLabel);
-
- await names.nth(3).fill('page-me');
- await expect(v2SaveButton(page)).toBeEnabled();
- });
-
- test('CV2-11 a channel on one threshold is not enough — the validator loops all of them', async ({
- authedPage: page,
- alertChannel,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-11-${Date.now()}`);
- await page.getByTestId('add-threshold-button').click();
-
- await selectThresholdChannel(page, 0, alertChannel.name);
- expect(await v2SaveTooltip(page)).toBe(VALIDATION.channels);
-
- await selectThresholdChannel(page, 1, alertChannel.name);
- await expect(v2SaveButton(page)).toBeEnabled();
- });
-
- test('CV2-12 the unit select is disabled while the query has no y-axis unit', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- // `disabled={units.length === 0}`, and `units` is derived from
- // `alertState.yAxisUnit`. A logs alert carries no unit, so the control is dead on
- // this path — CD-04 covers a URL that does supply one.
- const unitSelect = page.getByTestId('threshold-unit-select').first();
- await expect(unitSelect).toHaveClass(/ant-select-disabled/);
- });
-
- test('CV2-13 the recovery threshold control is never rendered', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- // `showRecoveryThreshold` starts false and the only setter is commented out, so
- // neither the input nor its remove button can appear.
- await expect(page.getByTestId('recovery-threshold-value-input')).toHaveCount(
- 0,
- );
- await expect(
- page.getByTestId('remove-recovery-threshold-button'),
- ).toHaveCount(0);
- });
-
- test('CV2-14 CV2-15 the evaluation window and cadence reach the payload', async ({
- authedPage: page,
- alertChannel,
- ownedRules,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-14-${Date.now()}`);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- // Written as one test because the two settings share a payload branch:
- // `getEvaluationProps` emits `evalWindow` and `frequency` together, and a
- // scenario that changed only one would still pass with the other hardcoded.
- await selectEvaluationTimeframe(page, '30m0s');
-
- await expandAdvancedOptions(page);
- await evaluationCadenceInput(page).fill('5');
-
- const [response] = await Promise.all([
- page.waitForResponse(
- (r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
- ),
- v2SaveButton(page).click(),
- ]);
- await ownedRules.register(response);
-
- const { evaluation } = response.request().postDataJSON();
- expect(evaluation.kind).toBe('rolling');
- expect(evaluation.spec.evalWindow).toBe('30m0s');
- // `getFormattedTimeValue` maps value + unit onto a Go duration; the unit is
- // left at its default Minutes, which is what makes `5m` the expected string.
- expect(evaluation.spec.frequency).toBe('5m');
- });
-
- test('CV2-18 with no channels the dropdown offers only a way to create one', async ({
- authedPage: page,
- }) => {
- // The single deliberate network stub in the alerts suite — its justification is
- // in `stubNoChannels`, and the state it produces is the one every fresh install
- // starts in.
- await stubNoChannels(page);
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-18-${Date.now()}`);
-
- const select = page
- .getByTestId('threshold-notification-channel-select')
- .first();
- await select.click();
- const dropdown = await ownDropdown(page, select);
-
- // `NotificationChannelsNotFoundContent` branches on the user's role. The harness
- // user is an admin, so this is the "create one here" half — asserting the
- // non-admin string instead would fail for the wrong reason.
- await expect(dropdown.getByText('No channels yet.')).toBeVisible();
- await expect(dropdown.getByRole('button', { name: 'here.' })).toBeVisible();
- await expect(dropdown.getByRole('button', { name: 'Refresh' })).toBeVisible();
- await expect(
- dropdown.getByText('Please ask your admin to create one.'),
- ).toBeHidden();
-
- await page.keyboard.press('Escape');
-
- // With a name filled and no channel selectable, the channel gate is the only
- // thing left — and there is no way to satisfy it from this page.
- expect(await v2SaveTooltip(page)).toBe(VALIDATION.channels);
- await expect(v2SaveButton(page)).toBeDisabled();
- });
-
- test('CV2-19 routing policies unlock the save with zero channels', async ({
- authedPage: page,
- }) => {
- await stubNoChannels(page);
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-19-${Date.now()}`);
- await expect(v2SaveButton(page)).toBeDisabled();
-
- await page.getByTestId('routing-policies-switch').click();
-
- // The validator skips the channel check when `routingPolicies` is on, and the
- // threshold row *removes* its channel select rather than disabling it — so this
- // is the one route to a saveable rule on a stack with no channels at all.
- await expect(
- page.getByTestId('threshold-notification-channel-select'),
- ).toHaveCount(0);
- await expect(v2SaveButton(page)).toBeEnabled();
-
- await page.getByTestId('view-routing-policies-button').click();
- await page.waitForURL(/subTab=routing-policies/);
- const url = new URL(page.url());
- expect(url.pathname).toBe('/alerts');
- expect(url.searchParams.get('tab')).toBe('Configuration');
- expect(url.searchParams.get('subTab')).toBe('routing-policies');
- });
-
- test('CV2-16 the group-by select is disabled until the query groups by something', async ({
- authedPage: page,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
-
- // `isMultipleNotificationsEnabled` is `spaceAggregationOptions.length > 0`, and
- // the options come from the query's `groupBy` keys. The default logs query has
- // none, so notification grouping is unreachable without editing the query first.
- const groupBy = page.getByTestId('multiple-notifications-select');
- await expect(groupBy).toHaveAttribute('aria-disabled', 'true');
- await expect(page.getByText('No grouping fields available')).toBeVisible();
- });
-
- test('CV2-17 repeat notifications enable their inputs and reach the payload', async ({
- authedPage: page,
- alertChannel,
- ownedRules,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-17-${Date.now()}`);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- const interval = page.getByTestId('repeat-notifications-time-input');
- await expect(interval).toBeDisabled();
-
- await advancedOptionToggle(page, 'repeat-notifications-container').click();
- await expect(interval).toBeEnabled();
- await interval.fill('45');
-
- const [response] = await Promise.all([
- page.waitForResponse(
- (r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
- ),
- v2SaveButton(page).click(),
- ]);
- await ownedRules.register(response);
-
- // `getFormattedTimeValue` turns value+unit into a Go duration.
- const renotify = response.request().postDataJSON()
- .notificationSettings.renotify;
- expect(renotify.enabled).toBe(true);
- expect(renotify.interval).toBe('45m');
- });
-
- test('CV2-20 happy-path save posts the v2 shape and lands on the list', async ({
- authedPage: page,
- alertChannel,
- ownedRules,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- const name = `e2e-cv2-20-${Date.now()}`;
- await page.getByTestId('alert-name-input').fill(name);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- // One click — v2 has no confirm dialog, unlike v1.
- const [response] = await Promise.all([
- page.waitForResponse(
- (r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
- ),
- v2SaveButton(page).click(),
- ]);
- await ownedRules.register(response);
-
- expect(response.status()).toBe(201);
- expect(new URL(response.url()).pathname).toBe(`${BASE_PATH}/api/v2/rules`);
-
- const body = response.request().postDataJSON();
- expect(body.schemaVersion).toBe('v2alpha1');
- expect(body.version).toBe('v5');
- expect(body.alert).toBe(name);
- expect(body.condition.thresholds.kind).toBe('basic');
- expect(body.condition.thresholds.spec[0]).toMatchObject({
- name: 'critical',
- target: 0,
- matchType: ThresholdMatchType.AT_LEAST_ONCE.value,
- op: ThresholdOperator.ABOVE.value,
- channels: [alertChannel.name],
- targetUnit: '',
- });
- // The payload carries no recovery field at all — see CV2-13.
- expect(body.condition.thresholds.spec[0]).not.toHaveProperty(
- 'recoveryTarget',
- );
-
- await expect(page.getByText('Alert rule created successfully')).toBeVisible();
- // `safeNavigate('/alerts')`; the list page then appends its own defaults, so
- // only the pathname is asserted.
- await page.waitForURL(/\/alerts(\?|$)/);
- expect(new URL(page.url()).pathname).toBe('/alerts');
- });
-
- test('CV2-21 test notification reports that a non-firing rule matched nothing', async ({
- authedPage: page,
- alertChannel,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-21-${Date.now()}`);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- const [response] = await Promise.all([
- page.waitForResponse(
- (r) =>
- r.url().includes('/api/v2/rules/test') && r.request().method() === 'POST',
- ),
- v2TestButton(page).click(),
- ]);
- expect(response.ok()).toBe(true);
-
- // `alertCount === 0` is an *error* toast, not a success one — the rule evaluated
- // fine, it just did not fire. Asserted permissively so a stack that happens to
- // have matching data does not flip it.
- await expect(
- page.getByText(/No alerts found during the evaluation|sent successfully/),
- ).toBeVisible();
- });
-
- test('CV2-22 discard leaves without posting and resets the form', async ({
- authedPage: page,
- alertChannel,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-22-${Date.now()}`);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- let sawPost = false;
- page.on('request', (request) => {
- if (request.method() === 'POST' && request.url().includes('/api/v2/rules')) {
- sawPost = true;
- }
- });
-
- // dispatchEvent, not click — the side navigation covers the button (CE-09).
- await v2ClickDiscard(page);
- await page.waitForURL(/\/alerts(\?|$)/);
- expect(sawPost).toBe(false);
-
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await expect(page.getByTestId('alert-name-input')).toHaveValue('');
- await expect(thresholdRows(page)).toHaveCount(1);
- });
-
- test('CV2-23 every footer button is disabled while the save is in flight', async ({
- authedPage: page,
- alertChannel,
- ownedRules,
- }) => {
- await gotoCreateAlertV2(page, { alertType: AlertType.LOGS });
- await page.getByTestId('alert-name-input').fill(`e2e-cv2-23-${Date.now()}`);
- await selectThresholdChannel(page, 0, alertChannel.name);
-
- // The in-flight window is a few milliseconds against a local stack, so it is
- // widened by *delaying* the request — `route.continue()` still sends it to the
- // real backend and the real 201 comes back, so nothing about the response is
- // faked.
- await page.route('**/api/v2/rules', async (route) => {
- if (route.request().method() !== 'POST') {
- await route.fallback();
- return;
- }
- await new Promise((resolve) => {
- setTimeout(resolve, 2_000);
- });
- await route.continue();
- });
-
- const responsePromise = page.waitForResponse(
- (r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
- );
- await v2SaveButton(page).click();
-
- // `disableButtons` is one flag shared by all three, so Discard going disabled is
- // what proves a user cannot abandon a half-created rule mid-request.
- await expect(v2SaveButton(page)).toHaveAttribute('aria-busy', 'true');
- await expect(v2SaveButton(page)).toBeDisabled();
- await expect(v2TestButton(page)).toBeDisabled();
- await expect(v2DiscardButton(page)).toBeDisabled();
-
- const response = await responsePromise;
- await ownedRules.register(response);
- expect(response.status()).toBe(201);
- await expect(page.getByText('Alert rule created successfully')).toBeVisible();
- });
-});
diff --git a/tests/e2e/tests/alerts/details.spec.ts b/tests/e2e/tests/alerts/details.spec.ts
new file mode 100644
index 0000000000..347a07d556
--- /dev/null
+++ b/tests/e2e/tests/alerts/details.spec.ts
@@ -0,0 +1,316 @@
+import {
+ ALERT_HISTORY_PATH,
+ ALERT_OVERVIEW_PATH,
+ ALERTS_LIST_PATH,
+ DEFAULT_RELATIVE_TIME,
+ expect,
+ test,
+ V1_RULE_TEAM_LABEL,
+} from '../../drivers/alerts';
+
+test.describe('Alert details', () => {
+ test('TC-01 the enable/disable toggle round-trips through the API', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const ruleId = await ownedRules.logs({
+ name: `e2e-ad-toggle-${Date.now()}`,
+ });
+ await alerts.details.goto(ruleId);
+
+ const toggle = alerts.details.enableToggle();
+ const patched = (): Promise<unknown> =>
+ page.waitForResponse(
+ (res) =>
+ res.url().includes(`/api/v2/rules/${ruleId}`) &&
+ res.request().method() === 'PATCH',
+ );
+
+ await Promise.all([patched(), toggle.click()]);
+ await expect(alerts.shell.message('Alert has been disabled.')).toBeVisible();
+
+ await Promise.all([patched(), toggle.click()]);
+ await expect(alerts.shell.message('Alert has been enabled.')).toBeVisible();
+ });
+
+ test('TC-02 Clone creates a copy and lands on its overview', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const name = `e2e-ad-clone-${Date.now()}`;
+ const ruleId = await ownedRules.logs({ name });
+
+ await alerts.details.goto(ruleId);
+ await alerts.details.openActions();
+
+ const [created] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ /\/api\/v\d\/rules\/[^/]+\/clone$/.test(new URL(res.url()).pathname) &&
+ res.request().method() === 'POST',
+ ),
+ alerts.details.menuItem('Clone').click(),
+ ]);
+ await ownedRules.register(created);
+
+ await expect(page).toHaveURL(new RegExp(ALERT_OVERVIEW_PATH));
+ await expect(page).toHaveURL(/[?&]ruleId=/);
+
+ await alerts.shell.goto({ search: name });
+ await expect(alerts.list.ruleName(`${name} - Copy`)).toBeVisible();
+ });
+
+ test('TC-03 Delete removes the rule and returns to the list', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const name = `e2e-ad-delete-${Date.now()}`;
+ const ruleId = await ownedRules.logs({ name });
+
+ await alerts.details.goto(ruleId);
+ await alerts.details.openActions();
+
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes(`/api/v2/rules/${ruleId}`) &&
+ res.request().method() === 'DELETE',
+ ),
+ alerts.details.menuItem('Delete').click(),
+ ]);
+
+ await expect(page).toHaveURL(new RegExp(`${ALERTS_LIST_PATH}$`));
+ await alerts.shell.goto({ search: name });
+ await expect(alerts.list.ruleName(name, { exact: true })).toHaveCount(0);
+ });
+
+ test('TC-04 the breadcrumb and document title name the rule', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ await expect
+ .poll(() => page.title(), { timeout: 15_000 })
+ .toContain('e2e-ah-rule-v2');
+
+ const breadcrumb = alerts.shell.breadcrumb();
+ await expect(breadcrumb).toContainText('Alert Rules');
+ await expect(breadcrumb).toContainText(alertHistory.ruleId);
+
+ await alerts.shell.crumb('Alert Rules').click();
+ await expect(page).toHaveURL(new RegExp(`${ALERTS_LIST_PATH}$`));
+ });
+
+ test('TC-05 the copy-link button copies the current URL', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ browserName,
+ }) => {
+ test.skip(
+ browserName !== 'chromium',
+ 'clipboard-read permission is Chromium-only in Playwright',
+ );
+ await page.context().grantPermissions(['clipboard-read', 'clipboard-write']);
+
+ await alerts.history.goto(alertHistory.ruleId);
+ const expected = page.url();
+
+ await alerts.details.copyLinkButton().click();
+ await expect(alerts.shell.message('Copied')).toBeVisible();
+
+ expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(
+ expected,
+ );
+ });
+
+ test('TC-06 the v2 header renames inline and offers no Rename item', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.details.goto(alertHistory.ruleId);
+
+ await expect(alerts.details.root()).toHaveAttribute(
+ 'data-schema-version',
+ 'v2alpha1',
+ );
+ const nameInput = alerts.details.nameInput();
+ await expect(nameInput).toBeVisible();
+ await expect(nameInput).not.toHaveValue('');
+ await expect(nameInput).toBeEditable();
+
+ await alerts.details.openActions();
+ await expect(alerts.details.menuItem('Clone')).toBeVisible();
+ await expect(alerts.details.menuItem('Delete')).toBeVisible();
+ await expect(alerts.details.menuItem('Rename')).toHaveCount(0);
+ });
+
+ test('TC-07 the v1 header is static and keeps the Rename item', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.details.goto(alertHistory.ruleIdV1);
+
+ await expect(alerts.details.root()).toHaveAttribute(
+ 'data-schema-version',
+ 'v1',
+ );
+ await expect(alerts.details.headerField('title')).toBeVisible();
+ await expect(alerts.details.headerField('state')).toBeVisible();
+ await expect(alerts.details.headerField('severity')).toContainText('Warning');
+ await expect(alerts.details.headerField('labels')).toContainText(
+ V1_RULE_TEAM_LABEL,
+ );
+ await expect(alerts.details.nameInput()).toHaveCount(0);
+
+ await alerts.details.openActions();
+ await expect(alerts.details.menuItem('Rename')).toBeVisible();
+ });
+
+ test('TC-08 a v1 rename through the modal persists', async ({
+ alerts,
+ ownedRules,
+ }) => {
+ const original = `e2e-ad-rename-v1-${Date.now()}`;
+ const renamed = `${original}-renamed`;
+ const ruleId = await ownedRules.logs({ name: original, schema: 'v1' });
+
+ await alerts.details.goto(ruleId);
+ await expect(alerts.details.headerField('title')).toContainText(original);
+
+ await alerts.details.openActions();
+ await alerts.details.menuItem('Rename').click();
+
+ const modalInput = alerts.details.renameInput();
+ await expect(modalInput).toBeVisible();
+ await modalInput.fill(renamed);
+ await alerts.details.renameConfirmButton().click();
+
+ await expect(
+ alerts.shell.message('Alert renamed successfully'),
+ ).toBeVisible();
+ await expect(alerts.details.headerField('title')).toContainText(renamed);
+
+ await alerts.shell.goto({ search: renamed });
+ await expect(alerts.list.ruleName(renamed)).toBeVisible();
+ });
+
+ test('TC-09 a v2 rename persists only through the Overview footer', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const original = `e2e-ad-rename-v2-${Date.now()}`;
+ const renamed = `${original}-renamed`;
+ const ruleId = await ownedRules.logs({ name: original });
+
+ await alerts.details.goto(ruleId);
+
+ const nameInput = alerts.details.nameInput();
+ await expect(nameInput).toHaveValue(original);
+ await nameInput.fill(renamed);
+
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.url().includes(`/api/v2/rules/${ruleId}`) &&
+ ['PUT', 'POST', 'PATCH'].includes(res.request().method()),
+ ),
+ alerts.details.footerSaveButton().click(),
+ ]);
+
+ await alerts.shell.goto({ search: renamed });
+ await expect(alerts.list.ruleName(renamed)).toBeVisible();
+
+ // The History tab renders the same name input with no save button, so an
+ // edit made there is discarded rather than persisted.
+ await alerts.history.goto(ruleId);
+ await alerts.details.nameInput().fill(`${renamed}-unsaved`);
+ await expect(alerts.details.footerSaveButton()).toHaveCount(0);
+
+ await alerts.shell.goto({ search: renamed });
+ await expect(alerts.list.ruleName(renamed)).toBeVisible();
+ await expect(alerts.list.ruleName(`${renamed}-unsaved`)).toHaveCount(0);
+ });
+
+ test('TC-10 the tabs preserve ruleId and relativeTime', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.details.goto(alertHistory.ruleId);
+
+ await alerts.details.sectionTab('history').click();
+
+ await expect(page).toHaveURL(new RegExp(ALERT_HISTORY_PATH));
+ await expect(page).toHaveURL(new RegExp(`ruleId=${alertHistory.ruleId}`));
+ await expect(page).toHaveURL(
+ new RegExp(`relativeTime=${DEFAULT_RELATIVE_TIME}`),
+ );
+ await expect(alerts.details.historyBetaBadge()).toBeVisible();
+
+ await alerts.details.sectionTab('overview').click();
+
+ await expect(page).toHaveURL(new RegExp(ALERT_OVERVIEW_PATH));
+ await expect(page).toHaveURL(new RegExp(`ruleId=${alertHistory.ruleId}`));
+ });
+
+ test('TC-11 switching back to History discards the other history params', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId, {
+ page: '2',
+ order: 'desc',
+ timelineFilter: 'FIRED',
+ });
+
+ await alerts.details.sectionTab('overview').click();
+ await expect(page).toHaveURL(new RegExp(ALERT_OVERVIEW_PATH));
+ await expect(page).toHaveURL(/[?&]timelineFilter=FIRED/);
+
+ await alerts.details.sectionTab('history').click();
+
+ await expect(page).toHaveURL(new RegExp(ALERT_HISTORY_PATH));
+ const search = new URL(page.url()).searchParams;
+ expect([...search.keys()].sort()).toEqual(['relativeTime', 'ruleId']);
+ expect(search.get('ruleId')).toBe(alertHistory.ruleId);
+ });
+
+ test('TC-12 the overview shows the saved threshold value', async ({
+ alerts,
+ ownedRules,
+ }) => {
+ const target = 245;
+ const ruleId = await ownedRules.threshold(
+ `e2e-threshold-persistence-${Date.now()}`,
+ { target },
+ );
+
+ await alerts.details.gotoOverview(ruleId);
+
+ await expect(alerts.form.thresholdValue()).toHaveValue(String(target));
+ });
+
+ test('TC-13 an unknown or missing ruleId lands on AlertNotFound', async ({
+ alerts,
+ }) => {
+ for (const open of [
+ () => alerts.history.open('not-a-real-rule-id'),
+ () => alerts.history.open('01920000-0000-7000-8000-000000000000'),
+ () => alerts.details.open(),
+ () => alerts.details.open('not-a-real-rule-id'),
+ ]) {
+ // eslint-disable-next-line no-await-in-loop
+ await open();
+ // eslint-disable-next-line no-await-in-loop
+ await expect(alerts.details.notFoundMessage()).toBeVisible();
+ }
+ });
+});
diff --git a/tests/e2e/tests/alerts/details/actions.spec.ts b/tests/e2e/tests/alerts/details/actions.spec.ts
deleted file mode 100644
index 670e268b3a..0000000000
--- a/tests/e2e/tests/alerts/details/actions.spec.ts
+++ /dev/null
@@ -1,96 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import {
- ALERT_OVERVIEW_PATH,
- ALERTS_LIST_PATH,
-} from '../../../helpers/alerts/constants';
-import { gotoAlertDetails } from '../../../helpers/alerts/navigation';
-
-test.describe('Alert details — actions', () => {
- test('TC-01 enable/disable toggle changes the rule state', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.logs({
- name: `e2e-ad-toggle-${Date.now()}`,
- schema: 'v2',
- });
-
- await gotoAlertDetails(page, ruleId);
-
- const toggle = page.getByTestId('alert-actions-toggle');
- await expect(toggle).toBeVisible();
-
- await Promise.all([
- page.waitForResponse(
- (res) =>
- res.url().includes(`/api/v2/rules/${ruleId}`) &&
- res.request().method() === 'PATCH',
- ),
- toggle.click(),
- ]);
-
- await expect(page.getByText('Alert has been disabled.')).toBeVisible();
-
- await Promise.all([
- page.waitForResponse(
- (res) =>
- res.url().includes(`/api/v2/rules/${ruleId}`) &&
- res.request().method() === 'PATCH',
- ),
- toggle.click(),
- ]);
-
- await expect(page.getByText('Alert has been enabled.')).toBeVisible();
- });
-
- test('TC-02 Clone creates a copy and navigates to overview', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-ad-clone-${Date.now()}`;
- const ruleId = await ownedRules.logs({ name, schema: 'v2' });
-
- await gotoAlertDetails(page, ruleId);
- await page.getByTestId('alert-actions-menu').click();
-
- const [createResponse] = await Promise.all([
- page.waitForResponse(
- (res) =>
- /\/api\/v\d\/rules\/[^/]+\/clone$/.test(new URL(res.url()).pathname) &&
- res.request().method() === 'POST',
- ),
- page.getByRole('menuitem', { name: 'Clone' }).click(),
- ]);
- await ownedRules.register(createResponse);
-
- await expect(page).toHaveURL(new RegExp(ALERT_OVERVIEW_PATH));
- await expect(page).toHaveURL(/[?&]ruleId=/);
-
- await page.goto(`${ALERTS_LIST_PATH}?search=${name}`);
- await expect(page.getByText(`${name} - Copy`)).toBeVisible();
- });
-
- test('TC-03 Delete removes the rule and returns to the list', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-ad-delete-${Date.now()}`;
- const ruleId = await ownedRules.logs({ name, schema: 'v2' });
-
- await gotoAlertDetails(page, ruleId);
- await page.getByTestId('alert-actions-menu').click();
-
- await Promise.all([
- page.waitForResponse(
- (res) =>
- res.url().includes(`/api/v2/rules/${ruleId}`) &&
- res.request().method() === 'DELETE',
- ),
- page.getByRole('menuitem', { name: 'Delete' }).click(),
- ]);
-
- await expect(page).toHaveURL(new RegExp(`${ALERTS_LIST_PATH}$`));
- await page.goto(`${ALERTS_LIST_PATH}?search=${name}`);
- await expect(page.getByText(name, { exact: true })).toHaveCount(0);
- });
-});
diff --git a/tests/e2e/tests/alerts/details/chrome.spec.ts b/tests/e2e/tests/alerts/details/chrome.spec.ts
deleted file mode 100644
index 02c838cc86..0000000000
--- a/tests/e2e/tests/alerts/details/chrome.spec.ts
+++ /dev/null
@@ -1,53 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import { ALERTS_LIST_PATH } from '../../../helpers/alerts/constants';
-import { gotoAlertHistory } from '../../../helpers/alerts/history';
-
-test.describe('Alert details — page chrome', () => {
- test('TC-01 copy-link button copies the current URL to clipboard', async ({
- authedPage: page,
- alertHistory,
- browserName,
- }) => {
- test.skip(
- browserName !== 'chromium',
- 'clipboard-read permission is Chromium-only in Playwright',
- );
- await page.context().grantPermissions(['clipboard-read', 'clipboard-write']);
-
- await gotoAlertHistory(page, alertHistory.ruleId);
- // The served URL: base path mode strips the prefix from `page.url()`.
- const expected = page.mainFrame().url();
-
- await page.getByRole('button', { name: 'Copy link' }).click();
- await expect(page.getByText('Copied')).toBeVisible();
-
- const copied = await page.evaluate(() => navigator.clipboard.readText());
- expect(copied).toBe(expected);
- });
-
- test('TC-02 breadcrumb navigates back to the alert list', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const breadcrumb = page.locator('.ant-breadcrumb');
- await expect(breadcrumb).toContainText('Alert Rules');
- await expect(breadcrumb).toContainText(alertHistory.ruleId);
-
- await breadcrumb.getByText('Alert Rules').click();
-
- await expect(page).toHaveURL(new RegExp(`${ALERTS_LIST_PATH}$`));
- });
-
- test('TC-03 document title updates to show the rule name', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await expect
- .poll(() => page.title(), { timeout: 15_000 })
- .toContain('e2e-ah-rule-v2');
- });
-});
diff --git a/tests/e2e/tests/alerts/details/header.spec.ts b/tests/e2e/tests/alerts/details/header.spec.ts
deleted file mode 100644
index 46b742c1eb..0000000000
--- a/tests/e2e/tests/alerts/details/header.spec.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import {
- expect,
- V1_RULE_TEAM_LABEL,
- test,
-} from '../../../fixtures/alerts/alert-history';
-import { gotoAlertDetails } from '../../../helpers/alerts/navigation';
-
-test.describe('Alert details — header', () => {
- test('TC-01 v2 header shows editable name input without Rename menu item', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertDetails(page, alertHistory.ruleId);
-
- await expect(page.getByTestId('alert-details-root')).toHaveAttribute(
- 'data-schema-version',
- 'v2alpha1',
- );
-
- const nameInput = page.getByTestId('alert-name-input');
- await expect(nameInput).toBeVisible();
- await expect(nameInput).not.toHaveValue('');
- await expect(nameInput).toBeEditable();
-
- await page.getByTestId('alert-actions-menu').click();
- await expect(page.getByRole('menuitem', { name: 'Clone' })).toBeVisible();
- await expect(page.getByRole('menuitem', { name: 'Delete' })).toBeVisible();
- await expect(page.getByRole('menuitem', { name: 'Rename' })).toHaveCount(0);
- });
-
- test('TC-02 v1 header shows static title with state, severity and labels', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertDetails(page, alertHistory.ruleIdV1);
-
- await expect(page.getByTestId('alert-details-root')).toHaveAttribute(
- 'data-schema-version',
- 'v1',
- );
-
- await expect(page.getByTestId('alert-header-title')).toBeVisible();
- await expect(page.getByTestId('alert-header-state')).toBeVisible();
- await expect(page.getByTestId('alert-header-severity')).toContainText(
- 'Warning',
- );
- await expect(page.getByTestId('alert-header-labels')).toContainText(
- V1_RULE_TEAM_LABEL,
- );
- await expect(page.getByTestId('alert-name-input')).toHaveCount(0);
-
- await page.getByTestId('alert-actions-menu').click();
- await expect(page.getByRole('menuitem', { name: 'Rename' })).toBeVisible();
- });
-});
diff --git a/tests/e2e/tests/alerts/details/not-found.spec.ts b/tests/e2e/tests/alerts/details/not-found.spec.ts
deleted file mode 100644
index d3f7682882..0000000000
--- a/tests/e2e/tests/alerts/details/not-found.spec.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- ALERT_HISTORY_PATH,
- ALERT_OVERVIEW_PATH,
-} from '../../../helpers/alerts/constants';
-
-test.describe('Alert details — not found', () => {
- test('TC-01 invalid ruleId shows AlertNotFound page', async ({
- authedPage: page,
- }) => {
- await page.goto(`${ALERT_HISTORY_PATH}?ruleId=not-a-real-rule-id`);
- await expect(
- page.getByText("Uh-oh! We couldn't find the given alert rule."),
- ).toBeVisible();
-
- await page.goto(
- `${ALERT_HISTORY_PATH}?ruleId=01920000-0000-7000-8000-000000000000`,
- );
- await expect(
- page.getByText("Uh-oh! We couldn't find the given alert rule."),
- ).toBeVisible();
- });
-
- test('TC-02 missing ruleId on overview shows AlertNotFound page', async ({
- authedPage: page,
- }) => {
- await page.goto(ALERT_OVERVIEW_PATH);
-
- await expect(
- page.getByText("Uh-oh! We couldn't find the given alert rule."),
- ).toBeVisible();
- });
-});
diff --git a/tests/e2e/tests/alerts/details/rename.spec.ts b/tests/e2e/tests/alerts/details/rename.spec.ts
deleted file mode 100644
index 6eae1664bb..0000000000
--- a/tests/e2e/tests/alerts/details/rename.spec.ts
+++ /dev/null
@@ -1,72 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import { ALERTS_LIST_PATH } from '../../../helpers/alerts/constants';
-import { gotoAlertHistory } from '../../../helpers/alerts/history';
-import { gotoAlertDetails } from '../../../helpers/alerts/navigation';
-
-test.describe('Alert details — rename', () => {
- test('TC-01 v1 rename via modal updates the rule name', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const stamp = Date.now();
- const original = `e2e-ad-rename-v1-${stamp}`;
- const renamed = `${original}-renamed`;
- const ruleId = await ownedRules.logs({ name: original, schema: 'v1' });
-
- await gotoAlertDetails(page, ruleId);
- await expect(page.getByTestId('alert-header-title')).toContainText(original);
-
- await page.getByTestId('alert-actions-menu').click();
- await page.getByRole('menuitem', { name: 'Rename' }).click();
-
- const modalInput = page.getByTestId('alert-name');
- await expect(modalInput).toBeVisible();
- await modalInput.fill(renamed);
- await page.getByRole('button', { name: 'Rename Alert' }).click();
-
- await expect(page.getByText('Alert renamed successfully')).toBeVisible();
- await expect(page.getByTestId('alert-header-title')).toContainText(renamed);
-
- await page.goto(`${ALERTS_LIST_PATH}?search=${renamed}`);
- await expect(page.getByText(renamed)).toBeVisible();
- });
-
- test('TC-02 v2 inline rename saves via Overview footer button', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const stamp = Date.now();
- const original = `e2e-ad-rename-v2-${stamp}`;
- const renamed = `${original}-renamed`;
- const ruleId = await ownedRules.logs({ name: original, schema: 'v2' });
-
- await gotoAlertDetails(page, ruleId);
-
- const nameInput = page.getByTestId('alert-name-input');
- await expect(nameInput).toHaveValue(original);
- await nameInput.fill(renamed);
-
- await Promise.all([
- page.waitForResponse(
- (res) =>
- res.url().includes(`/api/v2/rules/${ruleId}`) &&
- ['PUT', 'POST', 'PATCH'].includes(res.request().method()),
- ),
- page.getByRole('button', { name: 'Save Alert Rule' }).click(),
- ]);
-
- await page.goto(`${ALERTS_LIST_PATH}?search=${renamed}`);
- await expect(page.getByText(renamed)).toBeVisible();
-
- await gotoAlertHistory(page, ruleId);
- const historyInput = page.getByTestId('alert-name-input');
- await historyInput.fill(`${renamed}-unsaved`);
- await expect(
- page.getByRole('button', { name: 'Save Alert Rule' }),
- ).toHaveCount(0);
-
- await page.goto(`${ALERTS_LIST_PATH}?search=${renamed}`);
- await expect(page.getByText(renamed)).toBeVisible();
- await expect(page.getByText(`${renamed}-unsaved`)).toHaveCount(0);
- });
-});
diff --git a/tests/e2e/tests/alerts/details/tabs.spec.ts b/tests/e2e/tests/alerts/details/tabs.spec.ts
deleted file mode 100644
index 7a59092c23..0000000000
--- a/tests/e2e/tests/alerts/details/tabs.spec.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import {
- ALERT_HISTORY_PATH,
- ALERT_OVERVIEW_PATH,
- DEFAULT_RELATIVE_TIME,
-} from '../../../helpers/alerts/constants';
-import { gotoAlertHistory } from '../../../helpers/alerts/history';
-import { gotoAlertDetails } from '../../../helpers/alerts/navigation';
-
-test.describe('Alert details — tabs', () => {
- test('TC-01 Overview/History tabs preserve ruleId and relativeTime', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertDetails(page, alertHistory.ruleId);
-
- await page.getByTestId('alert-details-tab-history').click();
-
- await expect(page).toHaveURL(new RegExp(ALERT_HISTORY_PATH));
- await expect(page).toHaveURL(new RegExp(`ruleId=${alertHistory.ruleId}`));
- await expect(page).toHaveURL(
- new RegExp(`relativeTime=${DEFAULT_RELATIVE_TIME}`),
- );
- await expect(
- page.getByTestId('alert-details-tab-history').getByText('Beta'),
- ).toBeVisible();
-
- await page.getByTestId('alert-details-tab-overview').click();
-
- await expect(page).toHaveURL(new RegExp(ALERT_OVERVIEW_PATH));
- await expect(page).toHaveURL(new RegExp(`ruleId=${alertHistory.ruleId}`));
- });
-
- test('TC-02 switching to History tab discards other history params', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, {
- page: '2',
- order: 'desc',
- timelineFilter: 'FIRED',
- });
-
- await page.getByTestId('alert-details-tab-overview').click();
- await expect(page).toHaveURL(new RegExp(ALERT_OVERVIEW_PATH));
- await expect(page).toHaveURL(/[?&]timelineFilter=FIRED/);
-
- await page.getByTestId('alert-details-tab-history').click();
-
- await expect(page).toHaveURL(new RegExp(ALERT_HISTORY_PATH));
- const search = new URL(page.url()).searchParams;
- expect([...search.keys()].sort()).toEqual(['relativeTime', 'ruleId']);
- expect(search.get('ruleId')).toBe(alertHistory.ruleId);
- });
-});
diff --git a/tests/e2e/tests/alerts/details/threshold-persistence.spec.ts b/tests/e2e/tests/alerts/details/threshold-persistence.spec.ts
deleted file mode 100644
index 5b28ce4834..0000000000
--- a/tests/e2e/tests/alerts/details/threshold-persistence.spec.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import { gotoAlertOverview } from '../../../helpers/alerts/navigation';
-
-const TARGET = 245;
-
-test.describe('Alert overview — threshold persistence', () => {
- test('TC-01 edit page displays the saved threshold value', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(
- `e2e-threshold-persistence-${Date.now()}`,
- { target: TARGET },
- );
-
- await gotoAlertOverview(page, ruleId);
-
- await expect(page.getByTestId('threshold-value-input')).toHaveValue(
- String(TARGET),
- );
- });
-});
diff --git a/tests/e2e/tests/alerts/edit.spec.ts b/tests/e2e/tests/alerts/edit.spec.ts
new file mode 100644
index 0000000000..2bbf25b83b
--- /dev/null
+++ b/tests/e2e/tests/alerts/edit.spec.ts
@@ -0,0 +1,335 @@
+import {
+ EVALUATION_WINDOW_PRESETS,
+ expect,
+ test,
+ ThresholdMatchType,
+ ThresholdOperator,
+} from '../../drivers/alerts';
+
+// Editing a rule whose `schemaVersion` is `v2alpha1`.
+//
+// These run through `/alerts/overview?ruleId=`, the route the list's Edit action
+// uses. TC-07 is the exception and the reason the distinction matters: the same
+// editor reached through `/alerts/edit` has no `CreateAlertProvider` above it.
+//
+// The rule-definition-to-form mapping itself is asserted in jest against
+// `CreateAlertV2/context/utils`; what stays here is the round trip — that a rule
+// the API created renders back through that mapper, and that a save persists.
+
+/** Every asserted field differs from the create-form default, so a passing
+ * prefill assertion cannot be satisfied by the defaults. */
+const SEED = {
+ target: 42,
+ warningTarget: 21,
+ evalWindow: '10m0s',
+ /** Deliberately *not* one of the rolling presets. */
+ customEvalWindow: '7m0s',
+ frequency: '5m',
+ renotifyInterval: '2h',
+ absentFor: 7,
+} as const;
+
+test.describe('Alert edit', () => {
+ test('TC-01 the v2 editor renders inside the details shell', async ({
+ alerts,
+ ownedRules,
+ }) => {
+ const ruleId = await ownedRules.threshold(`e2e-ev2-shell-${Date.now()}`, {
+ target: SEED.target,
+ });
+
+ await alerts.details.gotoOverview(ruleId);
+
+ const root = alerts.details.root();
+ await expect(root).toHaveClass(/alert-details-v2/);
+ await expect(root).toHaveAttribute('data-schema-version', 'v2alpha1');
+
+ // `CreateAlertHeader` hides the whole tab bar in edit mode, which removes
+ // the "New Alert Rule" chip and the classic-experience escape hatch.
+ // Switching experiences mid-edit would silently drop the loaded rule.
+ await expect(alerts.form.name()).toBeVisible();
+ await expect(alerts.form.newRuleChip()).toBeHidden();
+ await expect(alerts.form.switchToClassicButton()).toBeHidden();
+ });
+
+ test('TC-02 a seeded rule prefills every field it set', async ({
+ alerts,
+ alertChannel,
+ ownedRules,
+ }) => {
+ const name = `e2e-ev2-prefill-${Date.now()}`;
+ const ruleId = await ownedRules.threshold(name, {
+ labels: { severity: 'critical', team: 'payments' },
+ evalWindow: SEED.evalWindow,
+ frequency: SEED.frequency,
+ renotify: {
+ enabled: true,
+ interval: SEED.renotifyInterval,
+ alertStates: ['firing'],
+ },
+ alertOnAbsent: { absentFor: SEED.absentFor },
+ recoveryTarget: 10,
+ thresholds: [
+ {
+ name: 'critical',
+ target: SEED.target,
+ op: ThresholdOperator.BELOW.value,
+ matchType: ThresholdMatchType.ALL_THE_TIME.value,
+ channels: [alertChannel.name],
+ },
+ {
+ name: 'warning',
+ target: SEED.warningTarget,
+ op: ThresholdOperator.BELOW.value,
+ matchType: ThresholdMatchType.ALL_THE_TIME.value,
+ channels: [alertChannel.name],
+ },
+ ],
+ });
+
+ await alerts.details.gotoOverview(ruleId);
+
+ await expect(alerts.form.name()).toHaveValue(name);
+ await expect(alerts.form.labelPill('severity', 'critical')).toBeVisible();
+ await expect(alerts.form.labelPill('team', 'payments')).toBeVisible();
+
+ await expect(alerts.form.thresholdRows()).toHaveCount(2);
+ await expect(alerts.form.thresholdName(0)).toHaveValue('critical');
+ await expect(alerts.form.thresholdName(1)).toHaveValue('warning');
+ await expect(alerts.form.thresholdValue(0)).toHaveValue(String(SEED.target));
+ await expect(alerts.form.thresholdValue(1)).toHaveValue(
+ String(SEED.warningTarget),
+ );
+
+ // The condition sentence is rule-wide in the UI but per-threshold in the
+ // schema, and the mapper reads it back from `spec[0]` only.
+ await expect(alerts.form.thresholdOperatorSelect()).toContainText(
+ ThresholdOperator.BELOW.label,
+ );
+ await expect(alerts.form.thresholdMatchTypeSelect()).toContainText(
+ ThresholdMatchType.ALL_THE_TIME.label,
+ );
+
+ // `showRecoveryThreshold` starts false and its only setter is commented out,
+ // so a seeded `recoveryTarget` has nowhere to land. If this ever appears the
+ // feature was finished and the assertion needs rewriting, not deleting.
+ await expect(alerts.form.recoveryThresholdValue()).toHaveCount(0);
+
+ // The trigger carries both halves of the window: the timeframe label and the
+ // window *type*, which comes from the seeded `evaluation.kind`.
+ await expect(alerts.form.evaluationSettingsButton()).toContainText(
+ EVALUATION_WINDOW_PRESETS[SEED.evalWindow],
+ );
+ await expect(alerts.form.evaluationSettingsButton()).toContainText('Rolling');
+
+ // Every repeat-notification control is `disabled={!reNotification.enabled}`,
+ // so "is it enabled" reads the toggle more strongly than the Switch itself.
+ const interval = alerts.form.repeatNotificationsInterval();
+ await expect(interval).toBeEnabled();
+ // `parseGoTime` splits the Go duration into value + unit.
+ await expect(interval).toHaveValue('2');
+ await expect(alerts.form.repeatNotificationsUnitSelect()).toContainText(
+ 'Hours',
+ );
+ await expect(alerts.form.repeatNotificationsConditionsSelect()).toContainText(
+ 'Firing',
+ );
+
+ await alerts.form.expandAdvancedOptions();
+ const tolerance = alerts.form.missingDataToleranceInput();
+ await expect(tolerance).toHaveValue(String(SEED.absentFor));
+ // The sibling option was not seeded, so it stays behind the `display: none`
+ // its container applies — asserted so a prefill that turned *every* advanced
+ // option on would still fail here.
+ await expect(alerts.form.minimumDatapointsInput()).toBeHidden();
+
+ await expect(alerts.form.evaluationCadenceInput()).toHaveValue('5');
+ await expect(alerts.form.evaluationCadenceUnitSelect()).toContainText(
+ 'Minutes',
+ );
+ // `getAdvancedOptionsStateFromAlertDef` hardcodes `mode: 'default'`, and
+ // `EditCustomSchedule` mounts only when the mode is not default — so a
+ // schedule saved by another client reopens as a plain interval and the next
+ // save persists the flattened value. The day the custom editor can mount,
+ // this fails.
+ await expect(alerts.form.customScheduleEditor()).toHaveCount(0);
+ });
+
+ test('TC-03 a non-preset evaluation window collapses to custom', async ({
+ alerts,
+ ownedRules,
+ }) => {
+ const ruleId = await ownedRules.threshold(
+ `e2e-ev2-window-custom-${Date.now()}`,
+ { target: SEED.target, evalWindow: SEED.customEvalWindow },
+ );
+
+ await alerts.details.gotoOverview(ruleId);
+
+ // `getRollingWindowTimeframe` only recognises the seven presets; anything
+ // else becomes `custom` and the label is built from the parsed number and
+ // unit, so a rule created outside the UI keeps its value.
+ await expect(alerts.form.evaluationSettingsButton()).toContainText(
+ 'Last 7 Minutes',
+ );
+ await alerts.form.openEvaluationSettings();
+ await expect(
+ alerts.form.evaluationWindowOption('timeframe', 'custom'),
+ ).toHaveClass(/active/);
+ });
+
+ test('TC-04 changing a threshold PUTs the rule and survives a reload', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const name = `e2e-ev2-update-${Date.now()}`;
+ const ruleId = await ownedRules.threshold(name, { target: SEED.target });
+
+ await alerts.details.gotoOverview(ruleId);
+ await alerts.form.thresholdValue().fill('99');
+
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.request().method() === 'PUT' &&
+ res.url().includes(`/api/v2/rules/${ruleId}`),
+ ),
+ alerts.form.saveButton().click(),
+ ]);
+
+ expect(response.ok()).toBe(true);
+ const body = response.request().postDataJSON();
+ expect(body.condition.thresholds.spec[0].target).toBe(99);
+ // The mapper hardcodes the schema version on every save, so editing a v2
+ // rule keeps it v2.
+ expect(body.schemaVersion).toBe('v2alpha1');
+ expect(body.alert).toBe(name);
+
+ await expect(
+ alerts.shell.message('Alert rule updated successfully'),
+ ).toBeVisible();
+ await page.waitForURL(/\/alerts(\?|$)/);
+ expect(new URL(page.url()).pathname).toBe('/alerts');
+
+ // Re-read rather than trust the toast: the footer invalidates the rule and
+ // list caches, and a stale cache would show the old value.
+ await alerts.details.gotoOverview(ruleId);
+ await expect(alerts.form.thresholdValue()).toHaveValue('99');
+ });
+
+ test('TC-05 the footer save is what persists a rename on the Overview tab', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const name = `e2e-ev2-rename-${Date.now()}`;
+ const renamed = `${name}-renamed`;
+ const ruleId = await ownedRules.threshold(name, { target: SEED.target });
+
+ await alerts.details.gotoOverview(ruleId);
+ await alerts.form.name().fill(renamed);
+
+ // The details header's RenameModal PATCHes on its own; this is the other
+ // path, where the editable header field is local state until the footer
+ // saves it.
+ const [response] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ res.request().method() === 'PUT' &&
+ res.url().includes(`/api/v2/rules/${ruleId}`),
+ ),
+ alerts.form.saveButton().click(),
+ ]);
+
+ expect(response.request().postDataJSON().alert).toBe(renamed);
+
+ await alerts.details.gotoOverview(ruleId);
+ await expect(alerts.form.name()).toHaveValue(renamed);
+ });
+
+ test('TC-06 Discard leaves without a PUT and without touching the rule', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const name = `e2e-ev2-discard-${Date.now()}`;
+ const ruleId = await ownedRules.threshold(name, { target: SEED.target });
+
+ await alerts.details.gotoOverview(ruleId);
+
+ let sawPut = false;
+ page.on('request', (request) => {
+ if (request.method() === 'PUT' && request.url().includes('/rules/')) {
+ sawPut = true;
+ }
+ });
+
+ await alerts.form.thresholdValue().fill('999');
+ await alerts.form.discard();
+ await page.waitForURL(/\/alerts(\?|$)/);
+
+ expect(sawPut).toBe(false);
+
+ // `discardAlertRule` also forces the context's alertType back to metrics,
+ // which is harmless on the way out only if the stored rule is untouched.
+ await alerts.details.gotoOverview(ruleId);
+ await expect(alerts.form.thresholdValue()).toHaveValue(String(SEED.target));
+ await expect(alerts.form.name()).toHaveValue(name);
+ });
+
+ test('TC-07 /alerts/edit is a legacy alias that redirects into the shell', async ({
+ authedPage: page,
+ alerts,
+ noise,
+ ownedRules,
+ }) => {
+ const ruleId = await ownedRules.threshold(
+ `e2e-ev2-standalone-${Date.now()}`,
+ { target: SEED.target },
+ );
+
+ // Reading the components suggests this route should crash: `EditAlertV2`
+ // renders Footer/AlertCondition/NotificationSettings, all of which call
+ // `useCreateAlertState()`, and the only provider lives in `AlertDetails`. It
+ // does not crash, because `/alerts/edit` never renders `pages/EditRules` at
+ // all — `AppRoutes/Private.tsx` redirects the legacy alias, merging the
+ // search params, before route matching.
+ //
+ // Worth keeping despite being a redirect: the alias is linked from the AI
+ // assistant and Metrics Explorer, so a regression in `oldNewRoutesMapping`
+ // would break real product links.
+ await alerts.details.gotoEdit(ruleId);
+
+ await page.waitForURL(/\/alerts\/overview/);
+ expect(new URL(page.url()).pathname).toBe('/alerts/overview');
+ expect(new URL(page.url()).searchParams.get('ruleId')).toBe(ruleId);
+
+ await expect(alerts.form.thresholdRows()).toHaveCount(1);
+ // If someone removes the redirect entry, this is the message that appears.
+ expect(
+ noise.errors.filter((message) =>
+ message.includes('useCreateAlertState must be used within'),
+ ),
+ ).toEqual([]);
+ });
+
+ test('TC-08 an unknown or missing ruleId on /alerts/edit lands on AlertNotFound', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ // `pages/EditRules`'s own error branches are unreachable: the alias redirect
+ // fires before any route matches, and the details shell validates the id
+ // before rendering. So neither the "Rule Id is required" notification nor
+ // the `edit-rules-container--error` card can render.
+ await alerts.details.gotoEdit('999999999');
+ await expect(alerts.details.notFound()).toBeVisible();
+ await expect(alerts.details.root()).toBeHidden();
+ await expect(alerts.details.editRulesError()).toBeHidden();
+
+ await alerts.details.gotoEdit();
+ await page.waitForURL(/\/alerts\/overview/);
+ await expect(alerts.details.notFound()).toBeVisible();
+ await expect(alerts.shell.message('Rule Id is required')).toBeHidden();
+ });
+});
diff --git a/tests/e2e/tests/alerts/edit/edge.spec.ts b/tests/e2e/tests/alerts/edit/edge.spec.ts
deleted file mode 100644
index 3c2a72fa2a..0000000000
--- a/tests/e2e/tests/alerts/edit/edge.spec.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import { ALERT_EDIT_PATH } from '../../../helpers/alert-forms/constants';
-import { ALERT_OVERVIEW_PATH } from '../../../helpers/alerts/constants';
-
-// TC-* — what the edit routes do with an unknown ruleId.
-//
-// `pages/EditRules`'s own error branches are unreachable: `/alerts/edit` is a
-// legacy alias redirected to `/alerts/overview` before any route matches
-// (`AppRoutes/Private.tsx`), and the details shell validates the id before
-// rendering the Overview tab. So neither the "Rule Id is required" notification nor
-// the `edit-rules-container--error` card can ever render — this file asserts the
-// behaviour that replaces them.
-
-const UNKNOWN_RULE_ID = '999999999';
-
-test.describe('Alert edit — routing edges', () => {
- test('TC-01 an unknown ruleId shows AlertNotFound on both entry URLs', async ({
- authedPage: page,
- }) => {
- for (const entry of [
- `${ALERT_OVERVIEW_PATH}?ruleId=${UNKNOWN_RULE_ID}`,
- `${ALERT_EDIT_PATH}?ruleId=${UNKNOWN_RULE_ID}`,
- ]) {
- // eslint-disable-next-line no-await-in-loop
- await page.goto(entry);
-
- // `AlertDetails.tsx` returns AlertNotFound before the provider or the editor
- // mount, so neither the details root nor the standalone route's error card may
- // appear.
- // eslint-disable-next-line no-await-in-loop
- await expect(page.locator('.alert-not-found')).toBeVisible();
- // eslint-disable-next-line no-await-in-loop
- await expect(
- page.getByText("Uh-oh! We couldn't find the given alert rule."),
- ).toBeVisible();
- // eslint-disable-next-line no-await-in-loop
- await expect(page.getByTestId('alert-details-root')).toBeHidden();
- // eslint-disable-next-line no-await-in-loop
- await expect(page.locator('.edit-rules-container--error')).toBeHidden();
- }
- });
-
- test('TC-02 /alerts/edit with no ruleId also lands on AlertNotFound', async ({
- authedPage: page,
- }) => {
- await page.goto(ALERT_EDIT_PATH);
-
- // The alias redirect fires first, so `pages/EditRules`'s missing-id branch — an
- // error notification plus a navigation to `/alerts` — never runs.
- await page.waitForURL(/\/alerts\/overview/);
- await expect(page.locator('.alert-not-found')).toBeVisible();
- await expect(page.getByText('Rule Id is required')).toBeHidden();
- });
-});
diff --git a/tests/e2e/tests/alerts/edit/v2.spec.ts b/tests/e2e/tests/alerts/edit/v2.spec.ts
deleted file mode 100644
index df06d29fe9..0000000000
--- a/tests/e2e/tests/alerts/edit/v2.spec.ts
+++ /dev/null
@@ -1,422 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- ALERT_EDIT_PATH,
- EVALUATION_WINDOW_PRESETS,
- ThresholdMatchType,
- ThresholdOperator,
-} from '../../../helpers/alert-forms/constants';
-import {
- evaluationCadenceInput,
- evaluationCadenceUnitSelect,
- evaluationSettingsButton,
- evaluationWindowOption,
- expandAdvancedOptions,
- openEvaluationSettings,
- thresholdRows,
- v2ClickDiscard,
- v2SaveButton,
-} from '../../../helpers/alert-forms/v2';
-import { gotoAlertOverview } from '../../../helpers/alerts/navigation';
-import { watchConsole } from '../../../helpers/common';
-
-// TC-* — editing a rule whose `schemaVersion` is `v2alpha1`.
-//
-// Unless a scenario says otherwise these run through `/alerts/overview?ruleId=`,
-// which is the route the rules list's Edit action actually uses. EV2-12 is the
-// exception and the reason the distinction matters: the same editor reached
-// through `/alerts/edit` has no `CreateAlertProvider` above it.
-
-/**
- * SEED-RV2 — a v2 rule whose every asserted field differs from the create-form
- * default, so a passing prefill assertion cannot be satisfied by the defaults.
- */
-const SEED_RV2 = {
- target: 42,
- warningTarget: 21,
- evalWindow: '10m0s',
- /** Deliberately *not* one of the rolling presets — see EV2-05. */
- customEvalWindow: '7m0s',
- frequency: '5m',
- renotifyInterval: '2h',
- absentFor: 7,
-} as const;
-
-/** PUT for one specific rule. v1 and v2 share this endpoint. */
-function isRuleUpdate(url: string, method: string, ruleId: string): boolean {
- return method === 'PUT' && url.includes(`/api/v2/rules/${ruleId}`);
-}
-
-test.describe('Alert edit — v2 rule', () => {
- test('TC-01 the v2 editor renders inside the details shell', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(`e2e-ev2-shell-${Date.now()}`, {
- target: SEED_RV2.target,
- });
-
- await gotoAlertOverview(page, ruleId);
-
- const root = page.getByTestId('alert-details-root');
- await expect(root).toHaveClass(/alert-details-v2/);
- await expect(root).toHaveAttribute('data-schema-version', 'v2alpha1');
-
- // `CreateAlertHeader` hides the whole tab bar in edit mode, which removes both
- // the "New Alert Rule" chip and the classic-experience escape hatch. The escape
- // hatch matters: switching experiences mid-edit would silently drop the loaded
- // rule.
- await expect(page.getByTestId('alert-name-input')).toBeVisible();
- await expect(page.getByText('New Alert Rule')).toBeHidden();
- await expect(
- page.getByRole('button', { name: 'Switch to Classic Experience' }),
- ).toBeHidden();
- });
-
- test('TC-02 name and labels prefill from the rule', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-ev2-prefill-${Date.now()}`;
- const ruleId = await ownedRules.threshold(name, {
- target: SEED_RV2.target,
- labels: { severity: 'critical', team: 'payments' },
- });
-
- await gotoAlertOverview(page, ruleId);
-
- await expect(page.getByTestId('alert-name-input')).toHaveValue(name);
- await expect(page.getByTestId('label-pill-severity-critical')).toBeVisible();
- await expect(page.getByTestId('label-pill-team-payments')).toBeVisible();
- });
-
- test('TC-03 both thresholds prefill, and the sentence reads spec[0]', async ({
- authedPage: page,
- ownedRules,
- alertChannel,
- }) => {
- const ruleId = await ownedRules.threshold(
- `e2e-ev2-thresholds-${Date.now()}`,
- {
- thresholds: [
- {
- name: 'critical',
- target: SEED_RV2.target,
- op: ThresholdOperator.BELOW.value,
- matchType: ThresholdMatchType.ALL_THE_TIME.value,
- channels: [alertChannel.name],
- },
- {
- name: 'warning',
- target: SEED_RV2.warningTarget,
- op: ThresholdOperator.BELOW.value,
- matchType: ThresholdMatchType.ALL_THE_TIME.value,
- channels: [alertChannel.name],
- },
- ],
- },
- );
-
- await gotoAlertOverview(page, ruleId);
-
- await expect(thresholdRows(page)).toHaveCount(2);
- await expect(page.getByTestId('threshold-name-input').nth(0)).toHaveValue(
- 'critical',
- );
- await expect(page.getByTestId('threshold-name-input').nth(1)).toHaveValue(
- 'warning',
- );
- await expect(page.getByTestId('threshold-value-input').nth(0)).toHaveValue(
- String(SEED_RV2.target),
- );
- await expect(page.getByTestId('threshold-value-input').nth(1)).toHaveValue(
- String(SEED_RV2.warningTarget),
- );
-
- // The condition sentence is rule-wide in the UI but per-threshold in the schema,
- // and the mapper reads it back from `spec[0]` only. Both seeded thresholds share
- // op/matchType so this row stays about prefill.
- await expect(
- page.getByTestId('alert-threshold-operator-select'),
- ).toContainText(ThresholdOperator.BELOW.label);
- await expect(
- page.getByTestId('alert-threshold-match-type-select'),
- ).toContainText(ThresholdMatchType.ALL_THE_TIME.label);
- });
-
- test('TC-04 the recovery threshold control never renders', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(`e2e-ev2-recovery-${Date.now()}`, {
- target: SEED_RV2.target,
- recoveryTarget: 10,
- });
-
- await gotoAlertOverview(page, ruleId);
-
- // `showRecoveryThreshold` starts false and its only setter is commented out, so a
- // seeded `recoveryTarget` has nowhere to land. If either locator ever appears the
- // feature was finished, and CV2-13/EV2-04 need rewriting rather than deleting.
- await expect(page.getByTestId('recovery-threshold-value-input')).toHaveCount(
- 0,
- );
- await expect(
- page.getByTestId('remove-recovery-threshold-button'),
- ).toHaveCount(0);
- });
-
- test('TC-05 the evaluation window prefills, and a non-preset value collapses to custom', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const presetRule = await ownedRules.threshold(
- `e2e-ev2-window-${Date.now()}`,
- { target: SEED_RV2.target, evalWindow: SEED_RV2.evalWindow },
- );
-
- await gotoAlertOverview(page, presetRule);
-
- // The trigger button carries both halves of the window: the timeframe label and
- // the window *type*, which comes from the seeded `evaluation.kind`.
- await expect(evaluationSettingsButton(page)).toContainText(
- EVALUATION_WINDOW_PRESETS[SEED_RV2.evalWindow],
- );
- await expect(evaluationSettingsButton(page)).toContainText('Rolling');
-
- const customRule = await ownedRules.threshold(
- `e2e-ev2-window-custom-${Date.now()}`,
- { target: SEED_RV2.target, evalWindow: SEED_RV2.customEvalWindow },
- );
-
- await gotoAlertOverview(page, customRule);
-
- // `getRollingWindowTimeframe` only recognises the seven presets; anything else
- // becomes `custom`, and the label is then built from the parsed number + unit. So
- // a rule created outside the UI with an odd window keeps its value — it just
- // renders through the custom branch.
- await expect(evaluationSettingsButton(page)).toContainText('Last 7 Minutes');
- await openEvaluationSettings(page);
- await expect(evaluationWindowOption(page, 'timeframe', 'custom')).toHaveClass(
- /active/,
- );
- });
-
- test('TC-06 repeat notifications prefill from the seeded renotify block', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(`e2e-ev2-renotify-${Date.now()}`, {
- target: SEED_RV2.target,
- renotify: {
- enabled: true,
- interval: SEED_RV2.renotifyInterval,
- alertStates: ['firing'],
- },
- });
-
- await gotoAlertOverview(page, ruleId);
-
- // Every control in the block is `disabled={!reNotification.enabled}`, so "is it
- // enabled" is a stronger read of the toggle than the Switch's own state.
- const interval = page.getByTestId('repeat-notifications-time-input');
- await expect(interval).toBeEnabled();
- // `parseGoTime` splits the Go duration into value + unit.
- await expect(interval).toHaveValue('2');
- await expect(
- page.getByTestId('repeat-notifications-unit-select'),
- ).toContainText('Hours');
- await expect(
- page.getByTestId('repeat-notifications-conditions-select'),
- ).toContainText('Firing');
- });
-
- test('TC-07 alertOnAbsent prefills the advanced options', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(`e2e-ev2-absent-${Date.now()}`, {
- target: SEED_RV2.target,
- alertOnAbsent: { absentFor: SEED_RV2.absentFor },
- });
-
- await gotoAlertOverview(page, ruleId);
- await expandAdvancedOptions(page);
-
- const tolerance = page.getByTestId(
- 'send-notification-if-data-is-missing-input',
- );
- await expect(tolerance).toBeVisible();
- await expect(tolerance).toHaveValue(String(SEED_RV2.absentFor));
-
- // The sibling option was not seeded, so its input stays behind the
- // `display: none` its container applies when the toggle is off — asserted so a
- // prefill that turned *every* advanced option on would still fail this row.
- await expect(
- page.getByTestId('enforce-minimum-datapoints-input'),
- ).toBeHidden();
- });
-
- test('TC-08 the evaluation cadence always reads back in default mode', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(`e2e-ev2-cadence-${Date.now()}`, {
- target: SEED_RV2.target,
- frequency: SEED_RV2.frequency,
- });
-
- await gotoAlertOverview(page, ruleId);
- await expandAdvancedOptions(page);
-
- await expect(evaluationCadenceInput(page)).toHaveValue('5');
- await expect(evaluationCadenceUnitSelect(page)).toContainText('Minutes');
-
- // `getAdvancedOptionsStateFromAlertDef` hardcodes `mode: 'default'`, and
- // `EditCustomSchedule` mounts only when the mode is *not* default — so a schedule
- // saved by any other client reopens as a plain interval and the next save
- // persists the flattened value. The custom and rrule modes are unreachable from
- // the UI (the "Add custom schedule" button is commented out) and unrepresentable
- // in the payload, so the flattening itself is what this row asserts; the day the
- // custom editor can mount, it fails.
- await expect(page.locator('.edit-custom-schedule')).toHaveCount(0);
- });
-
- test('TC-09 changing a threshold PUTs the rule and the change survives a reload', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-ev2-update-${Date.now()}`;
- const ruleId = await ownedRules.threshold(name, {
- target: SEED_RV2.target,
- });
-
- await gotoAlertOverview(page, ruleId);
- await page.getByTestId('threshold-value-input').first().fill('99');
-
- const [response] = await Promise.all([
- page.waitForResponse((r) =>
- isRuleUpdate(r.url(), r.request().method(), ruleId),
- ),
- v2SaveButton(page).click(),
- ]);
-
- expect(response.ok()).toBe(true);
- const body = response.request().postDataJSON();
- expect(body.condition.thresholds.spec[0].target).toBe(99);
- // The mapper hardcodes the schema version on every save, so an edit of a v2 rule
- // stays v2.
- expect(body.schemaVersion).toBe('v2alpha1');
- expect(body.alert).toBe(name);
-
- await expect(page.getByText('Alert rule updated successfully')).toBeVisible();
- await page.waitForURL(/\/alerts(\?|$)/);
- expect(new URL(page.url()).pathname).toBe('/alerts');
-
- // Re-read rather than trust the toast: the footer invalidates the rule and list
- // caches, and a stale cache would show the old value here.
- await gotoAlertOverview(page, ruleId);
- await expect(page.getByTestId('threshold-value-input').first()).toHaveValue(
- '99',
- );
- });
-
- test('TC-10 the footer save is what persists a rename made on the Overview tab', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-ev2-rename-${Date.now()}`;
- const renamed = `${name}-renamed`;
- const ruleId = await ownedRules.threshold(name, {
- target: SEED_RV2.target,
- });
-
- await gotoAlertOverview(page, ruleId);
- await page.getByTestId('alert-name-input').fill(renamed);
-
- // AD-03/AD-04 cover renaming through the details header's RenameModal, which
- // PATCHes on its own. This row is the other path: the editable header field is
- // local state until the *Footer* saves it, so the assertion is on the PUT body.
- const [response] = await Promise.all([
- page.waitForResponse((r) =>
- isRuleUpdate(r.url(), r.request().method(), ruleId),
- ),
- v2SaveButton(page).click(),
- ]);
-
- expect(response.request().postDataJSON().alert).toBe(renamed);
-
- await gotoAlertOverview(page, ruleId);
- await expect(page.getByTestId('alert-name-input')).toHaveValue(renamed);
- });
-
- test('TC-11 Discard leaves without a PUT and without touching the rule', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-ev2-discard-${Date.now()}`;
- const ruleId = await ownedRules.threshold(name, {
- target: SEED_RV2.target,
- });
-
- await gotoAlertOverview(page, ruleId);
-
- let sawPut = false;
- page.on('request', (request) => {
- if (request.method() === 'PUT' && request.url().includes('/rules/')) {
- sawPut = true;
- }
- });
-
- await page.getByTestId('threshold-value-input').first().fill('999');
- // dispatchEvent, not click — the side navigation covers the button (CE-09).
- await v2ClickDiscard(page);
- await page.waitForURL(/\/alerts(\?|$)/);
-
- expect(sawPut).toBe(false);
-
- // `discardAlertRule` also forces the *context's* alertType back to metrics, which
- // is harmless on the way out only if the stored rule is untouched.
- await gotoAlertOverview(page, ruleId);
- await expect(page.getByTestId('threshold-value-input').first()).toHaveValue(
- String(SEED_RV2.target),
- );
- await expect(page.getByTestId('alert-name-input')).toHaveValue(name);
- });
-
- test('TC-12 /alerts/edit is a legacy alias that redirects into the details shell', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const ruleId = await ownedRules.threshold(
- `e2e-ev2-standalone-${Date.now()}`,
- { target: SEED_RV2.target },
- );
-
- // Reading the components suggests this route should crash: `EditAlertV2` renders
- // Footer/AlertCondition/NotificationSettings, all of which call
- // `useCreateAlertState()`, and the only provider lives in `AlertDetails.tsx`. It
- // does not crash, because `/alerts/edit` never renders `pages/EditRules` at all —
- // `AppRoutes/Private.tsx` redirects the legacy alias to `/alerts/overview`,
- // merging the search params, before route matching.
- //
- // Worth keeping despite being a redirect: the alias is linked from the AI
- // assistant and Metrics Explorer, so a regression in `oldNewRoutesMapping` would
- // break real product links.
- const watch = watchConsole(page);
- await page.goto(`${ALERT_EDIT_PATH}?ruleId=${ruleId}`);
-
- await page.waitForURL(/\/alerts\/overview/);
- expect(new URL(page.url()).pathname).toBe('/alerts/overview');
- expect(new URL(page.url()).searchParams.get('ruleId')).toBe(ruleId);
-
- // The editor mounted under the shell's provider, so the missing-provider error
- // never fires. Asserted explicitly: if someone removes the redirect entry, this
- // is the message that would appear.
- await expect(thresholdRows(page)).toHaveCount(1);
- expect(
- watch.errors.filter((message) =>
- message.includes('useCreateAlertState must be used within'),
- ),
- ).toEqual([]);
- });
-});
diff --git a/tests/e2e/tests/alerts/history/cross-cutting.spec.ts b/tests/e2e/tests/alerts/history/cross-cutting.spec.ts
deleted file mode 100644
index 5aafe65f3c..0000000000
--- a/tests/e2e/tests/alerts/history/cross-cutting.spec.ts
+++ /dev/null
@@ -1,225 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import {
- ALERT_HISTORY_PATH,
- DEFAULT_RELATIVE_TIME,
- TIMELINE_PAGE_SIZE,
-} from '../../../helpers/alerts/constants';
-import {
- encodeTimelineCursor,
- gotoAlertHistory,
- HISTORY_ENDPOINTS,
- isHistoryRequest,
- sortTimelineDescending,
- statsCard,
- timelineFooterRange,
- timelineRows,
-} from '../../../helpers/alerts/history';
-import {
- collectRequests,
- requestUrl,
- watchConsole,
-} from '../../../helpers/common';
-
-test.describe('Alert history — cross-cutting', () => {
- test('TC-01 full deep-link with all params is honoured in one load', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const service = alertHistory.services[8];
- await page.goto(
- `${ALERT_HISTORY_PATH}?ruleId=${alertHistory.ruleId}` +
- `&relativeTime=${DEFAULT_RELATIVE_TIME}` +
- `&timelineFilter=FIRED&page=1&order=desc` +
- `&alertHistoryExpression=${encodeURIComponent(`service.name = '${service}'`)}` +
- `&viewAllTopContributors=true`,
- );
-
- await expect(page.getByTestId('timeline-table')).toBeVisible();
- await expect(page.getByTestId('top-contributors-drawer')).toBeVisible();
- await expect(page.getByTestId('timeline-filter-fired')).toHaveClass(
- /selected/,
- );
- await expect(timelineRows(page)).toHaveCount(1);
- });
-
- test('TC-02 page reload preserves all history params', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, {
- timelineFilter: 'FIRED',
- page: '2',
- order: 'desc',
- });
- const before = new URL(page.url()).searchParams;
-
- await page.reload();
- await expect(page.getByTestId('timeline-table')).toBeVisible();
-
- const after = new URL(page.url()).searchParams;
- for (const [key, value] of before) {
- expect(after.get(key), `param ${key} survived the reload`).toBe(value);
- }
- });
-
- test('TC-03 browser back/forward restores correct table state', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(timelineRows(page)).toHaveCount(TIMELINE_PAGE_SIZE);
-
- await page.getByTestId('timeline-filter-fired').click();
- await expect(page).toHaveURL(/[?&]timelineFilter=FIRED/);
-
- await page.getByTestId('timeline-next-page').click();
- await expect(page).toHaveURL(/[?&]page=2/);
- await expect(timelineRows(page)).toHaveCount(
- alertHistory.total - TIMELINE_PAGE_SIZE,
- );
-
- await page.goBack();
- await expect(page).not.toHaveURL(/[?&]page=2/);
- await expect(timelineRows(page)).toHaveCount(TIMELINE_PAGE_SIZE);
-
- await page.goForward();
- await expect(page).toHaveURL(/[?&]page=2/);
- await expect(timelineRows(page)).toHaveCount(
- alertHistory.total - TIMELINE_PAGE_SIZE,
- );
- });
-
- test('TC-04 no unhandled console errors across full history session', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const watch = watchConsole(page);
-
- await gotoAlertHistory(page, alertHistory.ruleId);
- await page.getByTestId('timeline-filter-fired').click();
- await page.getByTestId('timeline-next-page').click();
- await expect(page).toHaveURL(/[?&]page=2/);
- await sortTimelineDescending(page);
- await expect(page).toHaveURL(/[?&]order=desc/);
- await page.getByTestId('top-contributors-view-all').click();
- await expect(page.getByTestId('top-contributors-drawer')).toBeVisible();
-
- expect(watch.errors).toEqual([]);
- expect(watch.failedResponses).toEqual([]);
- });
-
- test('TC-05 no request storm on mount (exactly one call per endpoint)', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const requests = collectRequests(page);
-
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(timelineRows(page)).toHaveCount(TIMELINE_PAGE_SIZE);
- await expect(
- statsCard(page, 'Total Triggered').getByTestId('stats-card-value'),
- ).toBeVisible();
-
- for (const endpoint of HISTORY_ENDPOINTS) {
- const calls = requests.filter((req) => isHistoryRequest(req, endpoint));
- expect(calls, `${endpoint} called exactly once on mount`).toHaveLength(1);
- }
- });
-
- test('TC-06 v1 and v2 schema rules both render history correctly', async ({
- authedPage: page,
- alertHistory,
- }) => {
- for (const [variant, ruleId, total] of [
- ['v2', alertHistory.ruleId, alertHistory.total],
- ['v1', alertHistory.ruleIdV1, alertHistory.totalV1],
- ] as const) {
- await gotoAlertHistory(page, ruleId);
- await expect(
- page.getByTestId('alert-details-root'),
- `${variant} rule renders the details shell`,
- ).toHaveAttribute(
- 'data-schema-version',
- variant === 'v2' ? 'v2alpha1' : 'v1',
- );
- await expect(timelineFooterRange(page)).toContainText(`of ${total}`);
- }
- });
-
- test('TC-07 no legacy v1 history API calls during full session', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const requests = collectRequests(page);
-
- await gotoAlertHistory(page, alertHistory.ruleId);
- await page.getByTestId('timeline-filter-fired').click();
- await page.getByTestId('timeline-next-page').click();
- await expect(page).toHaveURL(/[?&]page=2/);
- await sortTimelineDescending(page);
- await expect(page).toHaveURL(/[?&]order=desc/);
- await gotoAlertHistory(page, alertHistory.ruleId, { relativeTime: '6h' });
-
- const legacy = requests.filter((req) =>
- /\/api\/v1\/rules\/[^/]+\/history\//.test(req.url()),
- );
- expect(
- legacy.map((req) => req.url()),
- 'no legacy POST /api/v1/rules/*/history/* calls',
- ).toEqual([]);
-
- for (const endpoint of HISTORY_ENDPOINTS) {
- expect(
- requests.filter((req) => isHistoryRequest(req, endpoint)).length,
- `v2 ${endpoint} endpoint was used`,
- ).toBeGreaterThan(0);
- }
- });
-
- test('TC-08 history API endpoints carry expected params', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const requests = collectRequests(page);
-
- await gotoAlertHistory(page, alertHistory.ruleId, {
- timelineFilter: 'FIRED',
- page: '2',
- });
- await expect(page.getByTestId('timeline-table')).toBeVisible();
-
- const timeline = requests
- .filter((req) => isHistoryRequest(req, 'timeline'))
- .pop();
- expect(timeline).toBeDefined();
- const timelineParams = requestUrl(timeline!).searchParams;
- for (const key of ['start', 'end', 'limit', 'order', 'cursor', 'state']) {
- expect(timelineParams.get(key), `timeline carries ${key}`).toBeTruthy();
- }
- expect(timelineParams.get('limit')).toBe(String(TIMELINE_PAGE_SIZE));
- expect(timelineParams.get('cursor')).toBe(encodeTimelineCursor(2));
-
- for (const endpoint of [
- 'stats',
- 'overall_status',
- 'top_contributors',
- ] as const) {
- const request = requests
- .filter((req) => isHistoryRequest(req, endpoint))
- .pop();
- expect(request, `${endpoint} was requested`).toBeDefined();
- const params = requestUrl(request!).searchParams;
- expect(params.get('start'), `${endpoint} carries start`).toBeTruthy();
- expect(params.get('end'), `${endpoint} carries end`).toBeTruthy();
- }
-
- const keys = requests
- .filter((req) => /\/history\/filter_keys/.test(req.url()))
- .pop();
- expect(keys, 'filter_keys was requested').toBeDefined();
- const keyParams = requestUrl(keys!).searchParams;
- expect(keyParams.get('startUnixMilli')).toBeTruthy();
- expect(keyParams.get('endUnixMilli')).toBeTruthy();
- expect(keyParams.get('start')).toBeNull();
- });
-});
diff --git a/tests/e2e/tests/alerts/history/empty-and-errors.spec.ts b/tests/e2e/tests/alerts/history/empty-and-errors.spec.ts
deleted file mode 100644
index cf6903604a..0000000000
--- a/tests/e2e/tests/alerts/history/empty-and-errors.spec.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import {
- createLogsAlertViaApi,
- deleteAlertViaApi,
- setRuleDisabledViaApi,
-} from '../../../helpers/alerts/api';
-import {
- ALERT_HISTORY_PATH,
- TIMELINE_PAGE_SIZE,
-} from '../../../helpers/alerts/constants';
-import {
- expectFirstPage,
- gotoAlertHistory,
- runFilterExpression,
- statsCard,
- timelineFooterRange,
- timelineRows,
- waitForHistoryResponse,
-} from '../../../helpers/alerts/history';
-import { collectRequests } from '../../../helpers/common';
-import { typeExpression } from '../../../helpers/query-builder';
-
-test.describe('Alert history — error and empty states', () => {
- test('TC-01 invalid filter expression shows syntax error and recovers on fix', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const responsePromise = waitForHistoryResponse(page, 'timeline', {
- filterExpression: 'service.name =',
- });
- await runFilterExpression(page, 'service.name =');
- const response = await responsePromise;
- expect(response.status()).toBe(400);
-
- const error = page.getByTestId('timeline-error');
- await expect(error).toBeVisible();
- await expect(error).toContainText(/syntax error/i);
-
- const fixed = `service.name = '${alertHistory.services[7]}'`;
- const fixResponsePromise = waitForHistoryResponse(page, 'timeline', {
- status: 200,
- filterExpression: fixed,
- });
- await runFilterExpression(page, fixed);
- await fixResponsePromise;
- await expect(page.getByTestId('timeline-error')).toHaveCount(0);
- await expect(timelineRows(page)).toHaveCount(1);
- });
-
- test('TC-02 empty filter_keys response still mounts editor (no suggestions)', async ({
- authedPage: page,
- emptyHistory,
- }) => {
- const keysPromise = page.waitForResponse((res) =>
- /\/history\/filter_keys/.test(res.url()),
- );
- await gotoAlertHistory(page, emptyHistory.ruleId);
- const keysResponse = await keysPromise;
-
- const body = (await keysResponse.json()) as {
- data: { keys?: Record<string, unknown> } | null;
- };
- expect(Object.keys(body.data?.keys ?? {})).toHaveLength(0);
-
- await expect(page.getByTestId('timeline-filter-skeleton')).toHaveCount(0);
- await expect(page.getByTestId('timeline-filter-search')).toBeVisible();
- await typeExpression(page, 'anything.at.all');
- await expect(
- page.locator('.query-where-clause-editor .cm-content'),
- ).toContainText('anything.at.all');
- });
-
- test('TC-03 bogus ruleId never reaches history APIs (shows AlertNotFound)', async ({
- authedPage: page,
- }) => {
- const requests = collectRequests(page);
-
- await page.goto(`${ALERT_HISTORY_PATH}?ruleId=not-a-real-rule-id`);
- await expect(
- page.getByText("Uh-oh! We couldn't find the given alert rule."),
- ).toBeVisible();
-
- expect(requests.filter((req) => /\/history\//.test(req.url()))).toHaveLength(
- 0,
- );
- });
-
- test('TC-04 rule with no history renders empty state (not error)', async ({
- authedPage: page,
- emptyHistory,
- }) => {
- await gotoAlertHistory(page, emptyHistory.ruleId);
-
- await expect(timelineRows(page)).toHaveCount(0);
- await expect(
- statsCard(page, 'Total Triggered').getByTestId('stats-card-value'),
- ).toHaveText('None Triggered.');
- await expect(
- statsCard(page, 'Avg. Resolution Time').getByTestId('stats-card-value'),
- ).toHaveText('No Resolutions.');
- await expect(page.getByTestId('top-contributors-row')).toHaveCount(0);
- await expect(page.getByTestId('timeline-error')).toHaveCount(0);
- });
-
- test('TC-05 time range with no data renders empty state', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const end = Date.now() - 24 * 60 * 60 * 1000;
- const start = end - 30 * 60 * 1000;
- await gotoAlertHistory(page, alertHistory.ruleId, {
- startTime: String(start),
- endTime: String(end),
- });
-
- await expect(timelineRows(page)).toHaveCount(0);
- await expect(
- statsCard(page, 'Total Triggered').getByTestId('stats-card-value'),
- ).toHaveText('None Triggered.');
- await expect(page.getByTestId('timeline-error')).toHaveCount(0);
- });
-
- test('TC-06 time-range change resets pagination to first page', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, { page: '2' });
- await expect(page).toHaveURL(/[?&]page=2/);
-
- await page.locator('.filters input').first().click();
- await page.getByText('Last 6 hours', { exact: true }).click();
-
- await expectFirstPage(page);
- });
-
- test('TC-07 absurd time range (90d) still renders', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, { relativeTime: '90d' });
-
- await expect(page.getByTestId('timeline-table')).toBeVisible();
- await expect(timelineRows(page).first()).toBeVisible();
- await expect(page.getByTestId('timeline-graph-title')).toContainText(
- `${alertHistory.total} triggers in`,
- );
- });
-
- test('TC-08 disabled rule history is still readable', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await expect(timelineRows(page)).toHaveCount(TIMELINE_PAGE_SIZE);
- await expect(timelineFooterRange(page)).toContainText(
- `of ${alertHistory.total}`,
- );
- });
-
- test('TC-09 deleted rule shows AlertNotFound on revisit', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const doomedId = await createLogsAlertViaApi(page, {
- name: `e2e-ah-doomed-${Date.now()}`,
- marker: alertHistory.marker,
- channels: [alertHistory.channelName],
- });
- await setRuleDisabledViaApi(page, doomedId, true);
-
- await gotoAlertHistory(page, doomedId);
- await expect(page.getByTestId('timeline-table')).toBeVisible();
-
- await deleteAlertViaApi(page, doomedId);
-
- await page.goto(`${ALERT_HISTORY_PATH}?ruleId=${doomedId}`);
- await expect(
- page.getByText("Uh-oh! We couldn't find the given alert rule."),
- ).toBeVisible();
- });
-});
diff --git a/tests/e2e/tests/alerts/history/expression-filter.spec.ts b/tests/e2e/tests/alerts/history/expression-filter.spec.ts
deleted file mode 100644
index 498b09eac8..0000000000
--- a/tests/e2e/tests/alerts/history/expression-filter.spec.ts
+++ /dev/null
@@ -1,286 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import { TIMELINE_PAGE_SIZE } from '../../../helpers/alerts/constants';
-import {
- expectFirstPage,
- gotoAlertHistory,
- isHistoryRequest,
- runFilterExpression,
- timelineFooterRange,
- timelineRows,
- waitForHistoryResponse,
-} from '../../../helpers/alerts/history';
-import { requestUrl } from '../../../helpers/common';
-import { typeExpression } from '../../../helpers/query-builder';
-
-test.describe('Alert history — expression filter', () => {
- test('TC-01 key suggestions load on page load', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const keysPromise = page.waitForResponse((res) =>
- /\/history\/filter_keys/.test(res.url()),
- );
- await gotoAlertHistory(page, alertHistory.ruleId);
- const keysResponse = await keysPromise;
-
- const body = (await keysResponse.json()) as {
- data: { keys: Record<string, { name: string }[]> } | null;
- };
- expect(Object.keys(body.data?.keys ?? {}).sort()).toEqual([
- 'service.name',
- 'severity',
- 'threshold.name',
- ]);
- const params = new URL(keysResponse.url()).searchParams;
- expect(params.get('startUnixMilli')).toBeTruthy();
- expect(params.get('endUnixMilli')).toBeTruthy();
-
- await expect(page.getByTestId('timeline-filter-search')).toBeVisible();
- await expect(page.getByTestId('timeline-filter-skeleton')).toHaveCount(0);
- });
-
- test('TC-02 value suggestions fetch from filter_values endpoint', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const valuesPromise = page.waitForResponse((res) =>
- /\/history\/filter_values/.test(res.url()),
- );
- await typeExpression(page, "service.name = '");
- const valuesResponse = await valuesPromise;
-
- const params = new URL(valuesResponse.url()).searchParams;
- expect(params.get('name')).toBe('service.name');
-
- const body = (await valuesResponse.json()) as {
- data: { values?: { stringValues?: string[] }; complete?: boolean } | null;
- };
- expect(body.data?.values?.stringValues).toEqual(
- [...alertHistory.services].sort(),
- );
- expect(body.data?.complete).toBe(true);
- });
-
- test('TC-03 value suggestions filter client-side as user types', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await typeExpression(page, "service.name = 'svc-1");
-
- const options = page.locator('.cm-tooltip-autocomplete li');
- await expect(options.first()).toBeVisible();
- const texts = await options.allInnerTexts();
- expect(texts.length).toBeGreaterThan(0);
- expect(texts.length).toBeLessThan(alertHistory.services.length);
- for (const text of texts) {
- expect(text).toContain('svc-1');
- }
- });
-
- test('TC-04 running equality expression filters the table', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- const service = alertHistory.services[3];
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await runFilterExpression(page, `service.name = '${service}'`);
- const request = await requestPromise;
-
- expect(requestUrl(request).searchParams.get('filterExpression')).toBe(
- `service.name = '${service}'`,
- );
- await expect(timelineRows(page)).toHaveCount(1);
- await expect(page).toHaveURL(/[?&]alertHistoryExpression=/);
- });
-
- test('TC-05 running expression resets pagination to first page', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, { page: '2' });
-
- const responsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(
- page,
- `service.name = '${alertHistory.services[0]}'`,
- );
- await responsePromise;
-
- await expect(page).not.toHaveURL(/[?&]page=2/);
- await expectFirstPage(page);
- });
-
- test('TC-06 Run button re-fetches unchanged expression', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- const expression = `service.name = '${alertHistory.services[1]}'`;
- const firstResponsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(page, expression);
- await firstResponsePromise;
- await expect(timelineRows(page)).toHaveCount(1);
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await page.getByRole('button', { name: /run query/i }).click();
- await requestPromise;
-
- await expect(timelineRows(page)).toHaveCount(1);
- });
-
- test('TC-07 in-flight query can be cancelled', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await page.route(
- (url) => /\/history\/timeline/.test(url.pathname),
- async (route) => {
- await new Promise((resolve) => {
- setTimeout(resolve, 3_000);
- });
- await route.continue();
- },
- );
-
- await typeExpression(page, `service.name = '${alertHistory.services[2]}'`);
- await page.getByRole('button', { name: /run query/i }).click();
-
- const cancel = page.getByRole('button', { name: 'Cancel' });
- await expect(cancel).toBeVisible();
- await cancel.click();
-
- await page.unrouteAll({ behavior: 'ignoreErrors' });
- await expect(page.getByRole('button', { name: 'Cancel' })).toHaveCount(0);
- await expect(page.getByRole('button', { name: /run query/i })).toBeVisible();
- });
-
- test('TC-08 threshold.name and severity keys filter correctly', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- let responsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(page, `threshold.name = 'critical'`);
- await responsePromise;
- await expect(timelineRows(page)).toHaveCount(TIMELINE_PAGE_SIZE);
- await expect(timelineFooterRange(page)).toContainText(
- `of ${alertHistory.total}`,
- );
-
- responsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(page, `severity = 'critical'`);
- await responsePromise;
- await expect(timelineFooterRange(page)).toContainText(
- `of ${alertHistory.total}`,
- );
-
- await gotoAlertHistory(page, alertHistory.ruleIdV1);
- responsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(page, `threshold.name = 'warning'`);
- await responsePromise;
- await expect(timelineFooterRange(page)).toContainText(
- `of ${alertHistory.totalV1}`,
- );
-
- responsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(page, `threshold.name = 'critical'`);
- await responsePromise;
- await expect(timelineRows(page)).toHaveCount(0);
- });
-
- test('TC-09 unknown key returns 200 with zero rows (not 500)', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const responsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(page, `nonexistent.key = 'x'`);
- const response = await responsePromise;
-
- expect(response.status()).toBe(200);
- await expect(timelineRows(page)).toHaveCount(0);
- await expect(page.getByTestId('timeline-error')).toHaveCount(0);
- });
-
- test('TC-10 expression is lost on Overview→History round-trip (known bug)', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- const expression = `service.name = '${alertHistory.services[4]}'`;
- const responsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(page, expression);
- await responsePromise;
- await expect(timelineRows(page)).toHaveCount(1);
- await expect(page).toHaveURL(/[?&]alertHistoryExpression=/);
-
- await page.getByTestId('alert-details-tab-overview').click();
- await page.getByTestId('alert-details-tab-history').click();
-
- await expect(page.getByTestId('timeline-table')).toBeVisible();
- expect(new URL(page.url()).searchParams.has('alertHistoryExpression')).toBe(
- false,
- );
- await expect(timelineRows(page)).toHaveCount(TIMELINE_PAGE_SIZE);
- });
-
- test('TC-11 expression and state filter compose in request', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, {
- timelineFilter: 'FIRED',
- });
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- const service = alertHistory.services[5];
- await runFilterExpression(page, `service.name = '${service}'`);
- const request = await requestPromise;
-
- const params = requestUrl(request).searchParams;
- expect(params.get('state')).toBe('firing');
- expect(params.get('filterExpression')).toBe(`service.name = '${service}'`);
- await expect(timelineRows(page)).toHaveCount(1);
- });
-
- test('TC-12 clearing expression restores full unfiltered list', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- const firstResponsePromise = waitForHistoryResponse(page, 'timeline');
- await runFilterExpression(
- page,
- `service.name = '${alertHistory.services[6]}'`,
- );
- await firstResponsePromise;
- await expect(timelineRows(page)).toHaveCount(1);
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await runFilterExpression(page, '');
- const request = await requestPromise;
-
- expect(requestUrl(request).searchParams.get('filterExpression')).toBeNull();
- await expect(timelineFooterRange(page)).toContainText(
- `of ${alertHistory.total}`,
- );
- });
-});
diff --git a/tests/e2e/tests/alerts/history/filters.spec.ts b/tests/e2e/tests/alerts/history/filters.spec.ts
new file mode 100644
index 0000000000..e6bb22feef
--- /dev/null
+++ b/tests/e2e/tests/alerts/history/filters.spec.ts
@@ -0,0 +1,358 @@
+import { expect, test, TIMELINE_PAGE_SIZE } from '../../../drivers/alerts';
+
+// The two filters over the timeline: the expression editor and the state tabs.
+
+test.describe('Alert history — filters', () => {
+ test('TC-01 key suggestions load with the page', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ const keys = page.waitForResponse((res) =>
+ /\/history\/filter_keys/.test(res.url()),
+ );
+ await alerts.history.goto(alertHistory.ruleId);
+ const response = await keys;
+
+ const body = (await response.json()) as {
+ data: { keys: Record<string, { name: string }[]> } | null;
+ };
+ expect(Object.keys(body.data?.keys ?? {}).sort()).toEqual([
+ 'service.name',
+ 'severity',
+ 'threshold.name',
+ ]);
+ const params = new URL(response.url()).searchParams;
+ expect(params.get('startUnixMilli')).toBeTruthy();
+ expect(params.get('endUnixMilli')).toBeTruthy();
+
+ await expect(alerts.history.filterSearch()).toBeVisible();
+ await expect(alerts.history.filterSkeleton()).toHaveCount(0);
+ });
+
+ test('TC-02 value suggestions come from the API and narrow as you type', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ const values = page.waitForResponse((res) =>
+ /\/history\/filter_values/.test(res.url()),
+ );
+ await alerts.history.typeFilter("service.name = '");
+ const response = await values;
+
+ expect(new URL(response.url()).searchParams.get('name')).toBe('service.name');
+ const body = (await response.json()) as {
+ data: { values?: { stringValues?: string[] }; complete?: boolean } | null;
+ };
+ expect(body.data?.values?.stringValues).toEqual(
+ [...alertHistory.services].sort(),
+ );
+ expect(body.data?.complete).toBe(true);
+
+ // Narrowing is client-side over the same fetched list.
+ await page.keyboard.type('svc-1');
+ const options = alerts.history.suggestions();
+ // The list shows a "Loading suggestions..." row until the values land.
+ await expect(options.first()).toBeVisible();
+ await expect(options.filter({ hasText: 'Loading suggestions' })).toHaveCount(
+ 0,
+ );
+ const texts = await options.allInnerTexts();
+ expect(texts.length).toBeGreaterThan(0);
+ expect(texts.length).toBeLessThan(alertHistory.services.length);
+ for (const text of texts) {
+ expect(text).toContain('svc-1');
+ }
+ });
+
+ test('TC-03 an expression filters the table, resets the page and composes with the state tab', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId, {
+ page: '2',
+ timelineFilter: 'FIRED',
+ });
+
+ const service = alertHistory.services[3];
+ const request = page.waitForRequest((req) =>
+ alerts.history.isRequest(req, 'timeline'),
+ );
+ await alerts.history.runFilter(`service.name = '${service}'`);
+
+ const params = new URL((await request).url()).searchParams;
+ expect(params.get('filterExpression')).toBe(`service.name = '${service}'`);
+ // Both filters reach the same request rather than replacing each other.
+ expect(params.get('state')).toBe('firing');
+
+ await expect(alerts.history.rows()).toHaveCount(1);
+ await expect(page).toHaveURL(/[?&]alertHistoryExpression=/);
+ await alerts.history.expectFirstPage();
+ });
+
+ test('TC-04 Run re-fetches an unchanged expression', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ const expression = `service.name = '${alertHistory.services[1]}'`;
+
+ const first = alerts.history.waitForResponse('timeline', {
+ filterExpression: expression,
+ });
+ await alerts.history.runFilter(expression);
+ await first;
+ await expect(alerts.history.rows()).toHaveCount(1);
+
+ const again = page.waitForRequest((req) =>
+ alerts.history.isRequest(req, 'timeline'),
+ );
+ await alerts.history.runQueryButton().click();
+ await again;
+
+ await expect(alerts.history.rows()).toHaveCount(1);
+ });
+
+ test('TC-05 an in-flight query can be cancelled', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ // Delay the real request rather than faking it: `route.continue()` still
+ // reaches the backend, so only the timing is changed.
+ await page.route(
+ (url) => /\/history\/timeline/.test(url.pathname),
+ async (route) => {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 3_000);
+ });
+ await route.continue();
+ },
+ );
+
+ await alerts.history.runFilter(
+ `service.name = '${alertHistory.services[2]}'`,
+ );
+
+ const cancel = alerts.history.cancelQueryButton();
+ await expect(cancel).toBeVisible();
+ await cancel.click();
+
+ await page.unrouteAll({ behavior: 'ignoreErrors' });
+ await expect(alerts.history.cancelQueryButton()).toHaveCount(0);
+ await expect(alerts.history.runQueryButton()).toBeVisible();
+ });
+
+ test('TC-06 threshold.name and severity filter per the rule schema', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ // The v2 rule's single threshold is `critical`, so both keys match every row.
+ let response = alerts.history.waitForResponse('timeline', {
+ filterExpression: `threshold.name = 'critical'`,
+ });
+ await alerts.history.runFilter(`threshold.name = 'critical'`);
+ await response;
+ await expect(alerts.history.rows()).toHaveCount(TIMELINE_PAGE_SIZE);
+ await expect(alerts.history.footerRange()).toContainText(
+ `of ${alertHistory.total}`,
+ );
+
+ response = alerts.history.waitForResponse('timeline', {
+ filterExpression: `severity = 'critical'`,
+ });
+ await alerts.history.runFilter(`severity = 'critical'`);
+ await response;
+ await expect(alerts.history.footerRange()).toContainText(
+ `of ${alertHistory.total}`,
+ );
+
+ // The v1 rule's threshold is named `warning`, so the same keys select the
+ // opposite way round.
+ await alerts.history.goto(alertHistory.ruleIdV1);
+ response = alerts.history.waitForResponse('timeline', {
+ filterExpression: `threshold.name = 'warning'`,
+ });
+ await alerts.history.runFilter(`threshold.name = 'warning'`);
+ await response;
+ await expect(alerts.history.footerRange()).toContainText(
+ `of ${alertHistory.totalV1}`,
+ );
+
+ response = alerts.history.waitForResponse('timeline', {
+ filterExpression: `threshold.name = 'critical'`,
+ });
+ await alerts.history.runFilter(`threshold.name = 'critical'`);
+ await response;
+ await expect(alerts.history.rows()).toHaveCount(0);
+ });
+
+ test('TC-07 an unknown key returns zero rows rather than an error', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ const response = alerts.history.waitForResponse('timeline', {
+ filterExpression: `nonexistent.key = 'x'`,
+ });
+ await alerts.history.runFilter(`nonexistent.key = 'x'`);
+
+ expect((await response).status()).toBe(200);
+ await expect(alerts.history.rows()).toHaveCount(0);
+ await expect(alerts.history.error()).toHaveCount(0);
+ });
+
+ test('TC-08 an invalid expression shows the syntax error and recovers on a fix', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ const rejected = alerts.history.waitForResponse('timeline', {
+ filterExpression: 'service.name =',
+ });
+ await alerts.history.runFilter('service.name =');
+ expect((await rejected).status()).toBe(400);
+
+ const error = alerts.history.error();
+ await expect(error).toBeVisible();
+ await expect(error).toContainText(/syntax error/i);
+
+ const fixed = `service.name = '${alertHistory.services[7]}'`;
+ const accepted = alerts.history.waitForResponse('timeline', {
+ status: 200,
+ filterExpression: fixed,
+ });
+ await alerts.history.runFilter(fixed);
+ await accepted;
+
+ await expect(alerts.history.error()).toHaveCount(0);
+ await expect(alerts.history.rows()).toHaveCount(1);
+ });
+
+ test('TC-09 clearing the expression restores the unfiltered list', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ const first = alerts.history.waitForResponse('timeline');
+ await alerts.history.runFilter(
+ `service.name = '${alertHistory.services[6]}'`,
+ );
+ await first;
+ await expect(alerts.history.rows()).toHaveCount(1);
+
+ const cleared = page.waitForRequest((req) =>
+ alerts.history.isRequest(req, 'timeline'),
+ );
+ await alerts.history.runFilter('');
+
+ expect(
+ new URL((await cleared).url()).searchParams.get('filterExpression'),
+ ).toBeNull();
+ await expect(alerts.history.footerRange()).toContainText(
+ `of ${alertHistory.total}`,
+ );
+ });
+
+ test('TC-10 the expression is lost on an Overview round-trip (known bug)', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ const applied = alerts.history.waitForResponse('timeline');
+ await alerts.history.runFilter(
+ `service.name = '${alertHistory.services[4]}'`,
+ );
+ await applied;
+ await expect(alerts.history.rows()).toHaveCount(1);
+ await expect(page).toHaveURL(/[?&]alertHistoryExpression=/);
+
+ await alerts.details.sectionTab('overview').click();
+ await alerts.details.sectionTab('history').click();
+
+ await expect(alerts.history.table()).toBeVisible();
+ expect(new URL(page.url()).searchParams.has('alertHistoryExpression')).toBe(
+ false,
+ );
+ await expect(alerts.history.rows()).toHaveCount(TIMELINE_PAGE_SIZE);
+ });
+
+ test('TC-11 the state tabs send the right param and reset the page', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId, {
+ timelineFilter: 'FIRED',
+ page: '2',
+ });
+ // A deep-linked filter starts on its own tab.
+ await expect(alerts.history.stateFilter('fired')).toHaveClass(/selected/);
+
+ // A tab switch can be followed by a late refetch for the previous tab, so
+ // each wait names the state it expects rather than taking the next request.
+ const timelineWithState = (state: string | null): Promise<unknown> =>
+ page.waitForRequest(
+ (req) =>
+ alerts.history.isRequest(req, 'timeline') &&
+ new URL(req.url()).searchParams.get('state') === state,
+ { timeout: 15_000 },
+ );
+
+ // "All" is the absence of a state param, not a state of its own.
+ let request = timelineWithState(null);
+ await alerts.history.stateFilter('all').click();
+ await expect(page).toHaveURL(/[?&]timelineFilter=ALL/);
+ await request;
+ await alerts.history.expectFirstPage();
+
+ request = timelineWithState('firing');
+ await alerts.history.stateFilter('fired').click();
+ await expect(page).toHaveURL(/[?&]timelineFilter=FIRED/);
+ await request;
+ await expect(alerts.history.rows().first()).toBeVisible();
+
+ request = timelineWithState('inactive');
+ await alerts.history.stateFilter('resolved').click();
+ await expect(page).toHaveURL(/[?&]timelineFilter=RESOLVED/);
+ await request;
+ // This rule never resolved, so Resolved is empty.
+ await expect(alerts.history.rows()).toHaveCount(0);
+ });
+
+ test('TC-12 a rule with resolutions splits between the Resolved and Fired tabs', async ({
+ alerts,
+ resolvedHistory,
+ }) => {
+ await alerts.history.goto(resolvedHistory.ruleId, {
+ timelineFilter: 'RESOLVED',
+ });
+
+ await expect(alerts.history.rows()).toHaveCount(
+ resolvedHistory.resolvedCount,
+ );
+ for (const text of await alerts.history
+ .rowCell(alerts.history.rows(), 'state')
+ .allInnerTexts()) {
+ expect(text).toBe('Resolved');
+ }
+
+ const fired = alerts.history.waitForResponse('timeline');
+ await alerts.history.stateFilter('fired').click();
+ await fired;
+ await expect(alerts.history.rows()).toHaveCount(resolvedHistory.firingCount);
+ });
+});
diff --git a/tests/e2e/tests/alerts/history/insights.spec.ts b/tests/e2e/tests/alerts/history/insights.spec.ts
new file mode 100644
index 0000000000..30b9d9f1da
--- /dev/null
+++ b/tests/e2e/tests/alerts/history/insights.spec.ts
@@ -0,0 +1,224 @@
+import { DEFAULT_RELATIVE_TIME, expect, test } from '../../../drivers/alerts';
+
+// The three read-only panels above the timeline: the stats cards, the top
+// contributors card and the overall-status graph.
+//
+// The sparkline's populated branch has no scenario: whether the seed's ~2 minute
+// firing wave lands in one stats bucket or two depends on where it falls
+// relative to the bucket boundary, and the `timeSeries.length > 1` gate flips
+// between runs. It needs a fixture that guarantees two points.
+
+test.describe('Alert history — insights', () => {
+ test('TC-01 the stats cards report the firing count and the empty resolution', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ const triggered = alerts.history.statsCard('Total Triggered');
+ await expect(triggered).toHaveAttribute('data-empty', 'false');
+ await expect(alerts.history.statsCardValue('Total Triggered')).toHaveText(
+ String(alertHistory.total),
+ );
+ // No earlier window to compare against, and that has to read as words
+ // rather than as a number.
+ await expect(alerts.history.statsCardChange('Total Triggered')).toHaveText(
+ 'no previous data',
+ );
+
+ const resolution = alerts.history.statsCard('Avg. Resolution Time');
+ await expect(resolution).toHaveAttribute('data-empty', 'true');
+ const value = alerts.history.statsCardValue('Avg. Resolution Time');
+ await expect(value).toHaveText('No Resolutions.');
+ await expect(value).not.toHaveText(/NaN/);
+ // An empty card never draws a sparkline.
+ await expect(
+ alerts.history.statsCardSparkline('Avg. Resolution Time'),
+ ).toHaveCount(0);
+ });
+
+ test('TC-02 the stats follow the time range', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ const end = Date.now() - 24 * 60 * 60 * 1000;
+ await alerts.history.goto(alertHistory.ruleId, {
+ startTime: String(end - 30 * 60 * 1000),
+ endTime: String(end),
+ });
+
+ await expect(alerts.history.statsCardValue('Total Triggered')).toHaveText(
+ 'None Triggered.',
+ );
+ await expect(
+ alerts.history.statsCardValue('Avg. Resolution Time'),
+ ).toHaveText('No Resolutions.');
+
+ await alerts.history.goto(alertHistory.ruleId);
+ await expect(alerts.history.statsCardValue('Total Triggered')).toHaveText(
+ String(alertHistory.total),
+ );
+ });
+
+ test('TC-03 a resolved rule gets a formatted average and a firing-only count', async ({
+ alerts,
+ resolvedHistory,
+ }) => {
+ await alerts.history.goto(resolvedHistory.ruleId);
+
+ const resolution = alerts.history.statsCard('Avg. Resolution Time');
+ await expect(resolution).toHaveAttribute('data-empty', 'false');
+ const value = alerts.history.statsCardValue('Avg. Resolution Time');
+ await expect(value).not.toHaveText('No Resolutions.');
+ await expect(value).not.toHaveText('');
+
+ // Total Triggered counts firing rows only, while the table shows both.
+ await expect(alerts.history.statsCardValue('Total Triggered')).toHaveText(
+ String(resolvedHistory.firingCount),
+ );
+ await expect(alerts.history.rows()).toHaveCount(
+ resolvedHistory.firingCount + resolvedHistory.resolvedCount,
+ );
+ });
+
+ test('TC-04 top contributors shows three rows with their ratio and bar', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ const card = alerts.history.contributorsCard();
+ await expect(card).toBeVisible();
+ await expect(card).toContainText('top contributors');
+
+ const rows = alerts.history.contributorRows(card);
+ await expect(rows).toHaveCount(3);
+ // The ratio text and the bar are rendered by different columns, so dropping
+ // the bar's `/ total * 100` scaling would leave the text intact. Radix
+ // surfaces the clamped percent as `aria-valuenow`.
+ const percent = String((1 / alertHistory.total) * 100);
+ for (let i = 0; i < 3; i += 1) {
+ // eslint-disable-next-line no-await-in-loop
+ await expect(alerts.history.contributorCount(rows.nth(i))).toHaveText(
+ `1/${alertHistory.total}`,
+ );
+ // eslint-disable-next-line no-await-in-loop
+ await expect(rows.nth(i)).toContainText('service.name');
+ // eslint-disable-next-line no-await-in-loop
+ await expect(alerts.history.contributorBar(rows.nth(i))).toHaveAttribute(
+ 'aria-valuenow',
+ percent,
+ );
+ }
+
+ // A logs rule's contributors carry a logs link and no traces link.
+ await alerts.history.contributorCount(rows.first()).click();
+ await expect(alerts.history.viewLogsLink()).toBeVisible();
+ await expect(alerts.history.viewTracesLink()).toHaveCount(0);
+ });
+
+ test('TC-05 View all opens a paginated drawer and deep-links to it', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ metricsHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ await alerts.history.contributorsViewAll().click();
+
+ await expect(page).toHaveURL(/[?&]viewAllTopContributors=true/);
+ const drawer = alerts.history.contributorsDrawer();
+ await expect(drawer).toBeVisible();
+ await expect(alerts.history.contributorsDrawerTitle()).toBeVisible();
+ await expect(alerts.history.contributorRows(drawer)).toHaveCount(10);
+ await expect(alerts.history.contributorsDrawerTotal()).toHaveText(
+ ` of ${alertHistory.total}`,
+ );
+
+ await alerts.history.goto(alertHistory.ruleId, {
+ viewAllTopContributors: 'true',
+ });
+ await expect(alerts.history.contributorsDrawer()).toBeVisible();
+
+ // Three contributors or fewer and there is nothing to view all of.
+ await alerts.history.goto(metricsHistory.ruleId);
+ await expect(alerts.history.contributorsCard()).toBeVisible();
+ await expect(alerts.history.contributorsViewAll()).toHaveCount(0);
+ });
+
+ test('TC-06 the graph draws the segments the status endpoint returns', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ noise,
+ }) => {
+ const status = page.waitForResponse((res) =>
+ alerts.history.isRequest(res.request(), 'overall_status'),
+ );
+ await alerts.history.goto(alertHistory.ruleId);
+
+ const body = (await (await status).json()) as {
+ data: { state: string }[] | null;
+ };
+ // The rule was inactive until the seeded records arrived, then fired.
+ expect((body.data ?? []).map((segment) => segment.state)).toEqual([
+ 'inactive',
+ 'firing',
+ ]);
+
+ await expect(alerts.history.graph()).toBeVisible();
+ await expect(alerts.history.graphCanvas()).toBeVisible();
+ await expect(alerts.history.graphTitle()).toHaveText(
+ `${alertHistory.total} triggers in ${DEFAULT_RELATIVE_TIME}`,
+ );
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-07 a resolved and a nodata rule both draw without errors', async ({
+ authedPage: page,
+ alerts,
+ noDataHistory,
+ noise,
+ resolvedHistory,
+ }) => {
+ const resolved = page.waitForResponse((res) =>
+ alerts.history.isRequest(res.request(), 'overall_status'),
+ );
+ await alerts.history.goto(resolvedHistory.ruleId);
+ const resolvedBody = (await (await resolved).json()) as {
+ data: { state: string }[] | null;
+ };
+ expect((resolvedBody.data ?? []).map((segment) => segment.state)).toEqual([
+ 'inactive',
+ 'firing',
+ 'inactive',
+ ]);
+ await expect(alerts.history.graphCanvas()).toBeVisible();
+
+ const nodata = page.waitForResponse((res) =>
+ alerts.history.isRequest(res.request(), 'overall_status'),
+ );
+ await alerts.history.goto(noDataHistory.ruleId);
+ const nodataBody = (await (await nodata).json()) as {
+ data: { state: string }[] | null;
+ };
+ const states = (nodataBody.data ?? []).map((segment) => segment.state);
+ expect(states.length).toBeGreaterThan(0);
+ for (const state of states) {
+ expect([
+ 'firing',
+ 'inactive',
+ 'pending',
+ 'nodata',
+ 'recovering',
+ 'disabled',
+ ]).toContain(state);
+ }
+ await expect(alerts.history.graphCanvas()).toBeVisible();
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+});
diff --git a/tests/e2e/tests/alerts/history/session.spec.ts b/tests/e2e/tests/alerts/history/session.spec.ts
new file mode 100644
index 0000000000..f94c674297
--- /dev/null
+++ b/tests/e2e/tests/alerts/history/session.spec.ts
@@ -0,0 +1,286 @@
+import {
+ DEFAULT_RELATIVE_TIME,
+ expect,
+ HISTORY_ENDPOINTS,
+ test,
+ TIMELINE_PAGE_SIZE,
+} from '../../../drivers/alerts';
+
+// Whole-page behaviour: deep links, history navigation, what one mount costs,
+// and the states where there is nothing to show.
+
+test.describe('Alert history — session', () => {
+ test('TC-01 a full deep-link is honoured in one load', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ const service = alertHistory.services[8];
+ await alerts.history.goto(alertHistory.ruleId, {
+ relativeTime: DEFAULT_RELATIVE_TIME,
+ timelineFilter: 'FIRED',
+ page: '1',
+ order: 'desc',
+ alertHistoryExpression: `service.name = '${service}'`,
+ viewAllTopContributors: 'true',
+ });
+
+ await expect(alerts.history.table()).toBeVisible();
+ await expect(alerts.history.contributorsDrawer()).toBeVisible();
+ await expect(alerts.history.stateFilter('fired')).toHaveClass(/selected/);
+ await expect(alerts.history.rows()).toHaveCount(1);
+ });
+
+ test('TC-02 a reload preserves every history param', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId, {
+ timelineFilter: 'FIRED',
+ page: '2',
+ order: 'desc',
+ });
+ const before = new URL(page.url()).searchParams;
+
+ await page.reload();
+ await expect(alerts.history.table()).toBeVisible();
+
+ const after = new URL(page.url()).searchParams;
+ for (const [key, value] of before) {
+ expect(after.get(key), `param ${key} survived the reload`).toBe(value);
+ }
+ });
+
+ test('TC-03 back and forward restore the table state', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ await expect(alerts.history.rows()).toHaveCount(TIMELINE_PAGE_SIZE);
+
+ await alerts.history.stateFilter('fired').click();
+ await expect(page).toHaveURL(/[?&]timelineFilter=FIRED/);
+
+ await alerts.history.nextPageButton().click();
+ await expect(page).toHaveURL(/[?&]page=2/);
+ await expect(alerts.history.rows()).toHaveCount(
+ alertHistory.total - TIMELINE_PAGE_SIZE,
+ );
+
+ await page.goBack();
+ await expect(page).not.toHaveURL(/[?&]page=2/);
+ await expect(alerts.history.rows()).toHaveCount(TIMELINE_PAGE_SIZE);
+
+ await page.goForward();
+ await expect(page).toHaveURL(/[?&]page=2/);
+ await expect(alerts.history.rows()).toHaveCount(
+ alertHistory.total - TIMELINE_PAGE_SIZE,
+ );
+ });
+
+ test('TC-04 a full session stays clean and uses no legacy endpoint', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ noise,
+ }) => {
+ const requests = alerts.shell.recordRequests();
+
+ await alerts.history.goto(alertHistory.ruleId);
+ await alerts.history.stateFilter('fired').click();
+ await alerts.history.nextPageButton().click();
+ await expect(page).toHaveURL(/[?&]page=2/);
+ await alerts.history.sortDescending();
+ await expect(page).toHaveURL(/[?&]order=desc/);
+ await alerts.history.contributorsViewAll().click();
+ await expect(alerts.history.contributorsDrawer()).toBeVisible();
+ await alerts.history.goto(alertHistory.ruleId, { relativeTime: '6h' });
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+
+ expect(
+ requests
+ .filter((req) => /\/api\/v1\/rules\/[^/]+\/history\//.test(req.url()))
+ .map((req) => req.url()),
+ 'no legacy v1 history calls',
+ ).toEqual([]);
+ for (const endpoint of HISTORY_ENDPOINTS) {
+ expect(
+ requests.filter((req) => alerts.history.isRequest(req, endpoint)).length,
+ `v2 ${endpoint} endpoint was used`,
+ ).toBeGreaterThan(0);
+ }
+ });
+
+ test('TC-05 one mount calls each endpoint once, with the expected params', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ const requests = alerts.shell.recordRequests();
+
+ await alerts.history.goto(alertHistory.ruleId, {
+ timelineFilter: 'FIRED',
+ page: '2',
+ });
+ await expect(alerts.history.table()).toBeVisible();
+ await expect(alerts.history.statsCardValue('Total Triggered')).toBeVisible();
+
+ for (const endpoint of HISTORY_ENDPOINTS) {
+ expect(
+ requests.filter((req) => alerts.history.isRequest(req, endpoint)),
+ `${endpoint} called exactly once on mount`,
+ ).toHaveLength(1);
+ }
+
+ const timeline = requests
+ .filter((req) => alerts.history.isRequest(req, 'timeline'))
+ .pop();
+ expect(timeline).toBeDefined();
+ const timelineParams = new URL(timeline?.url() ?? '').searchParams;
+ for (const key of ['start', 'end', 'limit', 'order', 'cursor', 'state']) {
+ expect(timelineParams.get(key), `timeline carries ${key}`).toBeTruthy();
+ }
+ expect(timelineParams.get('limit')).toBe(String(TIMELINE_PAGE_SIZE));
+ expect(timelineParams.get('cursor')).toBe(alerts.history.cursorFor(2));
+
+ for (const endpoint of [
+ 'stats',
+ 'overall_status',
+ 'top_contributors',
+ ] as const) {
+ const request = requests
+ .filter((req) => alerts.history.isRequest(req, endpoint))
+ .pop();
+ const params = new URL(request?.url() ?? '').searchParams;
+ expect(params.get('start'), `${endpoint} carries start`).toBeTruthy();
+ expect(params.get('end'), `${endpoint} carries end`).toBeTruthy();
+ }
+
+ // filter_keys takes its window in different params from the rest.
+ const keys = requests
+ .filter((req) => /\/history\/filter_keys/.test(req.url()))
+ .pop();
+ expect(keys, 'filter_keys was requested').toBeDefined();
+ const keyParams = new URL(keys?.url() ?? '').searchParams;
+ expect(keyParams.get('startUnixMilli')).toBeTruthy();
+ expect(keyParams.get('endUnixMilli')).toBeTruthy();
+ expect(keyParams.get('start')).toBeNull();
+ });
+
+ test('TC-06 v1 and v2 rules both render their history', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ for (const [variant, ruleId, total] of [
+ ['v2alpha1', alertHistory.ruleId, alertHistory.total],
+ ['v1', alertHistory.ruleIdV1, alertHistory.totalV1],
+ ] as const) {
+ // eslint-disable-next-line no-await-in-loop
+ await alerts.history.goto(ruleId);
+ // eslint-disable-next-line no-await-in-loop
+ await expect(
+ alerts.details.root(),
+ `${variant} rule renders the details shell`,
+ ).toHaveAttribute('data-schema-version', variant);
+ // eslint-disable-next-line no-await-in-loop
+ await expect(alerts.history.footerRange()).toContainText(`of ${total}`);
+ }
+ });
+
+ test('TC-07 a rule with no history renders the empty state, not an error', async ({
+ authedPage: page,
+ alerts,
+ emptyHistory,
+ }) => {
+ const keys = page.waitForResponse((res) =>
+ /\/history\/filter_keys/.test(res.url()),
+ );
+ await alerts.history.goto(emptyHistory.ruleId);
+
+ // No rows means no filter keys, and the editor still has to mount.
+ const body = (await (await keys).json()) as {
+ data: { keys?: Record<string, unknown> } | null;
+ };
+ expect(Object.keys(body.data?.keys ?? {})).toHaveLength(0);
+ await expect(alerts.history.filterSkeleton()).toHaveCount(0);
+ await expect(alerts.history.filterSearch()).toBeVisible();
+ await alerts.history.typeFilter('anything.at.all');
+ await expect(alerts.history.filterEditor()).toContainText('anything.at.all');
+
+ await expect(alerts.history.rows()).toHaveCount(0);
+ await expect(alerts.history.statsCardValue('Total Triggered')).toHaveText(
+ 'None Triggered.',
+ );
+ await expect(
+ alerts.history.statsCardValue('Avg. Resolution Time'),
+ ).toHaveText('No Resolutions.');
+ await expect(alerts.history.contributorRows()).toHaveCount(0);
+ await expect(alerts.history.error()).toHaveCount(0);
+ });
+
+ test('TC-08 an empty time range empties the page and resets pagination', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ const end = Date.now() - 24 * 60 * 60 * 1000;
+ await alerts.history.goto(alertHistory.ruleId, {
+ startTime: String(end - 30 * 60 * 1000),
+ endTime: String(end),
+ });
+
+ await expect(alerts.history.rows()).toHaveCount(0);
+ await expect(alerts.history.statsCardValue('Total Triggered')).toHaveText(
+ 'None Triggered.',
+ );
+ await expect(alerts.history.error()).toHaveCount(0);
+
+ await alerts.history.goto(alertHistory.ruleId, { page: '2' });
+ await expect(page).toHaveURL(/[?&]page=2/);
+ await alerts.history.timeRangeInput().click();
+ await alerts.history.timeRangeOption('Last 6 hours').click();
+ await alerts.history.expectFirstPage();
+ });
+
+ test('TC-09 a 90 day range still renders', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId, { relativeTime: '90d' });
+
+ await expect(alerts.history.table()).toBeVisible();
+ await expect(alerts.history.rows().first()).toBeVisible();
+ await expect(alerts.history.graphTitle()).toContainText(
+ `${alertHistory.total} triggers in`,
+ );
+ });
+
+ test('TC-10 an unknown rule never reaches the history APIs', async ({
+ alerts,
+ alertHistory,
+ }) => {
+ const requests = alerts.shell.recordRequests();
+
+ await alerts.history.open('not-a-real-rule-id');
+ await expect(alerts.details.notFoundMessage()).toBeVisible();
+ expect(requests.filter((req) => /\/history\//.test(req.url()))).toHaveLength(
+ 0,
+ );
+
+ // And a rule that existed a moment ago behaves the same once deleted.
+ const doomed = await alerts.seed.logsRule({
+ name: `e2e-ah-doomed-${Date.now()}`,
+ marker: alertHistory.marker,
+ channels: [alertHistory.channelName],
+ });
+ await alerts.seed.setDisabled(doomed, true);
+ await alerts.history.goto(doomed);
+ await expect(alerts.history.table()).toBeVisible();
+
+ await alerts.seed.deleteRule(doomed);
+ await alerts.history.open(doomed);
+ await expect(alerts.details.notFoundMessage()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/alerts/history/state-filter.spec.ts b/tests/e2e/tests/alerts/history/state-filter.spec.ts
deleted file mode 100644
index 1eb0c80713..0000000000
--- a/tests/e2e/tests/alerts/history/state-filter.spec.ts
+++ /dev/null
@@ -1,112 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import {
- expectFirstPage,
- gotoAlertHistory,
- isHistoryRequest,
- timelineRows,
- waitForHistoryResponse,
-} from '../../../helpers/alerts/history';
-import { requestUrl } from '../../../helpers/common';
-
-test.describe('Alert history — state filter', () => {
- test('TC-01 All filter sends no state param in request', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, {
- timelineFilter: 'FIRED',
- });
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await page.getByTestId('timeline-filter-all').click();
- const request = await requestPromise;
-
- await expect(page).toHaveURL(/[?&]timelineFilter=ALL/);
- expect(requestUrl(request).searchParams.get('state')).toBeNull();
- });
-
- test('TC-02 Fired filter sends state=firing in request', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await page.getByTestId('timeline-filter-fired').click();
- const request = await requestPromise;
-
- await expect(page).toHaveURL(/[?&]timelineFilter=FIRED/);
- expect(requestUrl(request).searchParams.get('state')).toBe('firing');
- await expect(timelineRows(page).first()).toBeVisible();
- });
-
- test('TC-03 Resolved filter shows empty for rule with no resolutions', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await page.getByTestId('timeline-filter-resolved').click();
- const request = await requestPromise;
-
- await expect(page).toHaveURL(/[?&]timelineFilter=RESOLVED/);
- expect(requestUrl(request).searchParams.get('state')).toBe('inactive');
- await expect(timelineRows(page)).toHaveCount(0);
- });
-
- test('TC-04 Resolved filter shows rows for rule with resolutions', async ({
- authedPage: page,
- resolvedHistory,
- }) => {
- await gotoAlertHistory(page, resolvedHistory.ruleId, {
- timelineFilter: 'RESOLVED',
- });
-
- await expect(timelineRows(page)).toHaveCount(resolvedHistory.resolvedCount);
- for (const text of await timelineRows(page)
- .getByTestId('timeline-row-state')
- .allInnerTexts()) {
- expect(text).toBe('Resolved');
- }
-
- const responsePromise = waitForHistoryResponse(page, 'timeline');
- await page.getByTestId('timeline-filter-fired').click();
- await responsePromise;
- await expect(timelineRows(page)).toHaveCount(resolvedHistory.firingCount);
- });
-
- test('TC-05 deep-link ?timelineFilter=FIRED starts on Fired tab', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, {
- timelineFilter: 'FIRED',
- });
-
- await expect(page.getByTestId('timeline-filter-fired')).toHaveClass(
- /selected/,
- );
- await expect(timelineRows(page).first()).toBeVisible();
- });
-
- test('TC-06 changing state filter resets pagination to first page', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, { page: '2' });
-
- const responsePromise = waitForHistoryResponse(page, 'timeline');
- await page.getByTestId('timeline-filter-fired').click();
- await responsePromise;
-
- await expect(page).not.toHaveURL(/[?&]page=2/);
- await expectFirstPage(page);
- });
-});
diff --git a/tests/e2e/tests/alerts/history/statistics.spec.ts b/tests/e2e/tests/alerts/history/statistics.spec.ts
deleted file mode 100644
index 90d6363461..0000000000
--- a/tests/e2e/tests/alerts/history/statistics.spec.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import {
- gotoAlertHistory,
- statsCard,
- timelineRows,
-} from '../../../helpers/alerts/history';
-
-test.describe('Alert history — statistics', () => {
- test('TC-01 Total Triggered card shows the firing count', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const card = statsCard(page, 'Total Triggered');
- await expect(card).toBeVisible();
- await expect(card).toHaveAttribute('data-empty', 'false');
- await expect(card.getByTestId('stats-card-value')).toHaveText(
- String(alertHistory.total),
- );
- });
-
- test('TC-02 Avg. Resolution Time card shows "No Resolutions." when none exist', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const card = statsCard(page, 'Avg. Resolution Time');
- await expect(card).toBeVisible();
- await expect(card).toHaveAttribute('data-empty', 'true');
- const value = card.getByTestId('stats-card-value');
- await expect(value).toHaveText('No Resolutions.');
- await expect(value).not.toHaveText(/NaN/);
- await expect(card.getByTestId('stats-card-sparkline')).toHaveCount(0);
- });
-
- test('TC-03 empty stats card never renders a sparkline', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const empty = statsCard(page, 'Avg. Resolution Time');
- await expect(empty).toHaveAttribute('data-empty', 'true');
- await expect(empty.getByTestId('stats-card-sparkline')).toHaveCount(0);
- });
-
- // eslint-disable-next-line playwright/expect-expect -- documented coverage gap
- test('TC-04 sparkline present with a multi-point series', async () => {
- test.skip(
- true,
- 'Not deterministic on SEED-A: whether `currentTriggersSeries` lands in ' +
- 'one stats bucket or two depends on where the ~2-minute seed falls ' +
- 'relative to the bucket boundary, so the `timeSeries.length > 1` gate ' +
- 'flips between runs (observed both ways). Needs a fixture that ' +
- 'guarantees ≥2 points — see coverage doc §3.5.',
- );
- });
-
- test('TC-05 change-vs-past indicator shows "no previous data" when unavailable', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const card = statsCard(page, 'Total Triggered');
- await expect(card.getByTestId('stats-card-change')).toHaveText(
- 'no previous data',
- );
- });
-
- test('TC-06 stats update when time range changes', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const end = Date.now() - 24 * 60 * 60 * 1000;
- const start = end - 30 * 60 * 1000;
- await gotoAlertHistory(page, alertHistory.ruleId, {
- startTime: String(start),
- endTime: String(end),
- });
-
- await expect(
- statsCard(page, 'Total Triggered').getByTestId('stats-card-value'),
- ).toHaveText('None Triggered.');
- await expect(
- statsCard(page, 'Avg. Resolution Time').getByTestId('stats-card-value'),
- ).toHaveText('No Resolutions.');
-
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(
- statsCard(page, 'Total Triggered').getByTestId('stats-card-value'),
- ).toHaveText(String(alertHistory.total));
- });
-
- test('TC-07 Avg. Resolution Time shows formatted duration when resolutions exist', async ({
- authedPage: page,
- resolvedHistory,
- }) => {
- await gotoAlertHistory(page, resolvedHistory.ruleId);
-
- const card = statsCard(page, 'Avg. Resolution Time');
- await expect(card).toHaveAttribute('data-empty', 'false');
- await expect(card.getByTestId('stats-card-value')).not.toHaveText(
- 'No Resolutions.',
- );
- await expect(card.getByTestId('stats-card-value')).not.toHaveText('');
- await expect(card.getByTestId('stats-card-sparkline')).toHaveCount(0);
- });
-
- test('TC-08 Total Triggered counts only firing rows (not resolved)', async ({
- authedPage: page,
- resolvedHistory,
- }) => {
- await gotoAlertHistory(page, resolvedHistory.ruleId);
-
- await expect(
- statsCard(page, 'Total Triggered').getByTestId('stats-card-value'),
- ).toHaveText(String(resolvedHistory.firingCount));
- await expect(timelineRows(page)).toHaveCount(
- resolvedHistory.firingCount + resolvedHistory.resolvedCount,
- );
- });
-});
diff --git a/tests/e2e/tests/alerts/history/timeline-graph.spec.ts b/tests/e2e/tests/alerts/history/timeline-graph.spec.ts
deleted file mode 100644
index 8b3d8f2ea8..0000000000
--- a/tests/e2e/tests/alerts/history/timeline-graph.spec.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import { DEFAULT_RELATIVE_TIME } from '../../../helpers/alerts/constants';
-import {
- gotoAlertHistory,
- isHistoryRequest,
-} from '../../../helpers/alerts/history';
-import { watchConsole } from '../../../helpers/common';
-
-test.describe('Alert history — timeline graph', () => {
- test('TC-01 renders canvas with two segments (inactive→firing)', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const watch = watchConsole(page);
-
- const statusPromise = page.waitForResponse((res) =>
- isHistoryRequest(res.request(), 'overall_status'),
- );
- await gotoAlertHistory(page, alertHistory.ruleId);
- const status = await statusPromise;
-
- const body = (await status.json()) as {
- data: { state: string }[] | null;
- };
- const states = (body.data ?? []).map((segment) => segment.state);
- expect(states).toEqual(['inactive', 'firing']);
-
- await expect(page.getByTestId('timeline-graph')).toBeVisible();
- await expect(
- page.getByTestId('timeline-graph').locator('canvas'),
- ).toBeVisible();
-
- await expect(page.getByTestId('timeline-graph-title')).toHaveText(
- `${alertHistory.total} triggers in ${DEFAULT_RELATIVE_TIME}`,
- );
-
- expect(watch.errors).toEqual([]);
- expect(watch.failedResponses).toEqual([]);
- });
-
- test('TC-02 renders canvas with three segments (inactive→firing→inactive)', async ({
- authedPage: page,
- resolvedHistory,
- }) => {
- const watch = watchConsole(page);
-
- const statusPromise = page.waitForResponse((res) =>
- isHistoryRequest(res.request(), 'overall_status'),
- );
- await gotoAlertHistory(page, resolvedHistory.ruleId);
- const status = await statusPromise;
-
- const body = (await status.json()) as { data: { state: string }[] | null };
- expect((body.data ?? []).map((s) => s.state)).toEqual([
- 'inactive',
- 'firing',
- 'inactive',
- ]);
- await expect(
- page.getByTestId('timeline-graph').locator('canvas'),
- ).toBeVisible();
- expect(watch.errors).toEqual([]);
- expect(watch.failedResponses).toEqual([]);
- });
-
- test('TC-03 handles nodata state without console errors', async ({
- authedPage: page,
- noDataHistory,
- }) => {
- const watch = watchConsole(page);
-
- const statusPromise = page.waitForResponse((res) =>
- isHistoryRequest(res.request(), 'overall_status'),
- );
- await gotoAlertHistory(page, noDataHistory.ruleId);
- const status = await statusPromise;
-
- const body = (await status.json()) as { data: { state: string }[] | null };
- const KNOWN_STATES = [
- 'firing',
- 'inactive',
- 'pending',
- 'nodata',
- 'recovering',
- 'disabled',
- ];
- const states = (body.data ?? []).map((segment) => segment.state);
- expect(states.length).toBeGreaterThan(0);
- for (const state of states) {
- expect(KNOWN_STATES).toContain(state);
- }
-
- await expect(
- page.getByTestId('timeline-graph').locator('canvas'),
- ).toBeVisible();
- expect(watch.errors).toEqual([]);
- expect(watch.failedResponses).toEqual([]);
- });
-});
diff --git a/tests/e2e/tests/alerts/history/timeline-pagination.spec.ts b/tests/e2e/tests/alerts/history/timeline-pagination.spec.ts
deleted file mode 100644
index f834e64345..0000000000
--- a/tests/e2e/tests/alerts/history/timeline-pagination.spec.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import { TIMELINE_PAGE_SIZE } from '../../../helpers/alerts/constants';
-import {
- encodeTimelineCursor,
- expectFirstPage,
- gotoAlertHistory,
- isHistoryRequest,
- sortTimelineDescending,
- timelineFooterRange,
- timelineRowLabels,
- timelineRows,
-} from '../../../helpers/alerts/history';
-import { requestUrl } from '../../../helpers/common';
-
-test.describe('Alert history — timeline pagination', () => {
- test('TC-01 next page sends cursor and shows different rows', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(timelineRows(page).first()).toBeVisible();
- const firstPageLabels = await timelineRowLabels(page);
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await page.getByTestId('timeline-next-page').click();
- const request = await requestPromise;
-
- expect(requestUrl(request).searchParams.get('cursor')).toBe(
- encodeTimelineCursor(2),
- );
- await expect(page).toHaveURL(/[?&]page=2/);
- await expect(timelineRows(page)).toHaveCount(
- alertHistory.total - TIMELINE_PAGE_SIZE,
- );
- await expect(timelineFooterRange(page)).toHaveText(
- `${TIMELINE_PAGE_SIZE + 1} — ${alertHistory.total} of ${alertHistory.total}`,
- );
- await expect(page.getByTestId('timeline-prev-page')).toBeEnabled();
-
- expect(await timelineRowLabels(page)).not.toEqual(firstPageLabels);
- });
-
- test('TC-02 prev page drops the cursor from request', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, { page: '2' });
-
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await page.getByTestId('timeline-prev-page').click();
- const request = await requestPromise;
-
- expect(requestUrl(request).searchParams.get('cursor')).toBeNull();
- await expect(timelineFooterRange(page)).toHaveText(
- `1 — ${TIMELINE_PAGE_SIZE} of ${alertHistory.total}`,
- );
- });
-
- test('TC-03 pagination buttons disable at first and last page', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(page.getByTestId('timeline-prev-page')).toBeDisabled();
- await expect(page.getByTestId('timeline-next-page')).toBeEnabled();
-
- await page.getByTestId('timeline-next-page').click();
-
- await expect(page.getByTestId('timeline-next-page')).toBeDisabled();
- await expect(page.getByTestId('timeline-prev-page')).toBeEnabled();
- });
-
- test('TC-04 browser back after paging returns to previous page', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await page.getByTestId('timeline-next-page').click();
- await expect(page).toHaveURL(/[?&]page=2/);
-
- await page.goBack();
-
- await expect(page).not.toHaveURL(/[?&]page=2/);
- await expect(timelineFooterRange(page)).toHaveText(
- `1 — ${TIMELINE_PAGE_SIZE} of ${alertHistory.total}`,
- );
- });
-
- test('TC-05 deep-link ?page=2 loads second page directly', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const requestPromise = page.waitForRequest(
- (req) =>
- isHistoryRequest(req, 'timeline') &&
- requestUrl(req).searchParams.get('cursor') === encodeTimelineCursor(2),
- );
- await gotoAlertHistory(page, alertHistory.ruleId, { page: '2' });
- await requestPromise;
-
- await expect(timelineRows(page)).toHaveCount(
- alertHistory.total - TIMELINE_PAGE_SIZE,
- );
- });
-
- test('TC-06 default sort order is ascending', async ({
- authedPage: page,
- alertHistory,
- }) => {
- const requestPromise = page.waitForRequest((req) =>
- isHistoryRequest(req, 'timeline'),
- );
- await gotoAlertHistory(page, alertHistory.ruleId);
- const request = await requestPromise;
-
- expect(new URL(page.url()).searchParams.get('order')).toBeNull();
- expect(requestUrl(request).searchParams.get('order')).toBe('asc');
- });
-
- test('TC-07 sorting toggles order and resets to first page', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, { page: '2' });
-
- await sortTimelineDescending(page);
-
- await expect(page).toHaveURL(/[?&]order=desc/);
- await expectFirstPage(page);
- });
-
- test('TC-08 single page disables both pagination buttons', async ({
- authedPage: page,
- metricsHistory,
- }) => {
- await gotoAlertHistory(page, metricsHistory.ruleId);
-
- await expect(timelineRows(page)).toHaveCount(metricsHistory.total);
- await expect(page.getByTestId('timeline-prev-page')).toBeDisabled();
- await expect(page.getByTestId('timeline-next-page')).toBeDisabled();
- await expect(timelineFooterRange(page)).toHaveText(
- `1 — ${metricsHistory.total} of ${metricsHistory.total}`,
- );
- });
-
- test('TC-09 all pages together cover the complete row set', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(timelineRows(page).first()).toBeVisible();
- const pageOne = await timelineRowLabels(page);
-
- await page.getByTestId('timeline-next-page').click();
- await expect(timelineRows(page)).toHaveCount(
- alertHistory.total - TIMELINE_PAGE_SIZE,
- );
- await expect(timelineFooterRange(page)).toHaveText(
- `${TIMELINE_PAGE_SIZE + 1} — ${alertHistory.total} of ${alertHistory.total}`,
- );
- const pageTwo = await timelineRowLabels(page);
-
- const union = new Set([...pageOne, ...pageTwo]);
- expect(pageOne.length + pageTwo.length).toBe(alertHistory.total);
- expect(union.size).toBe(alertHistory.total);
- });
-});
diff --git a/tests/e2e/tests/alerts/history/timeline-table.spec.ts b/tests/e2e/tests/alerts/history/timeline-table.spec.ts
deleted file mode 100644
index 8a94573ad7..0000000000
--- a/tests/e2e/tests/alerts/history/timeline-table.spec.ts
+++ /dev/null
@@ -1,198 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import { TIMELINE_PAGE_SIZE } from '../../../helpers/alerts/constants';
-import {
- firstTimelineRowCreatedAt,
- gotoAlertHistory,
- timelineFooterRange,
- timelineRows,
-} from '../../../helpers/alerts/history';
-
-test.describe('Alert history — timeline table', () => {
- test('TC-01 timeline section renders all chrome elements', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await expect(page.locator('.timeline__title')).toHaveText('Timeline');
- await expect(page.getByTestId('timeline-tab-overall-status')).toBeVisible();
- await expect(page.getByTestId('timeline-filter-all')).toBeVisible();
- await expect(page.getByTestId('timeline-filter-fired')).toBeVisible();
- await expect(page.getByTestId('timeline-filter-resolved')).toBeVisible();
- await expect(page.getByTestId('timeline-graph')).toBeVisible();
- await expect(page.getByTestId('timeline-table')).toBeVisible();
- });
-
- test('TC-02 Top 5 Contributors tab is disabled with Coming Soon indicator', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const tab = page.getByTestId('timeline-tab-top-contributors');
- await expect(tab).toBeDisabled();
- await expect(tab).toContainText('Coming Soon');
- });
-
- test('TC-03 table rows display state, labels and formatted timestamp', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await expect(timelineRows(page)).toHaveCount(TIMELINE_PAGE_SIZE);
-
- const first = timelineRows(page).first();
- await expect(first.getByTestId('timeline-row-state')).toHaveText('Firing');
- await expect(first.getByTestId('timeline-row-labels')).toContainText(
- 'service.name',
- );
- await expect(first.getByTestId('timeline-row-created-at')).toHaveText(
- /^[A-Z][a-z]{2} \d{1,2}, \d{4} ⎯ \d{2}:\d{2}:\d{2}$/,
- );
- });
-
- test('TC-04 footer shows correct row range', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await expect(timelineFooterRange(page)).toHaveText(
- `1 — ${TIMELINE_PAGE_SIZE} of ${alertHistory.total}`,
- );
- });
-
- test('TC-05 row click does not navigate away', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- const before = page.url();
-
- await timelineRows(page).first().click();
-
- expect(page.url()).toBe(before);
- await expect(page.getByTestId('timeline-table')).toBeVisible();
- });
-
- test('TC-06 row actions link navigates to logs explorer', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await timelineRows(page).first().getByTestId('timeline-row-actions').click();
-
- const viewLogs = page.getByTestId('alert-popover-view-logs');
- await expect(viewLogs).toBeVisible();
- await viewLogs.click();
-
- await expect(page).toHaveURL(/\/logs\/logs-explorer/);
- const search = new URL(page.url()).searchParams;
- expect(search.get('startTime')).toBeTruthy();
- expect(search.get('endTime')).toBeTruthy();
- expect(page.url()).toContain('compositeQuery');
- });
-
- test('TC-07 row actions link navigates to traces explorer', async ({
- authedPage: page,
- tracesHistory,
- }) => {
- await gotoAlertHistory(page, tracesHistory.ruleId);
-
- await timelineRows(page).first().getByTestId('timeline-row-actions').click();
-
- // A traces rule yields a traces link only — the backend returns one or the
- // other, never both, so "View Logs" must be absent.
- const viewTraces = page.getByTestId('alert-popover-view-traces');
- await expect(viewTraces).toBeVisible();
- await expect(page.getByTestId('alert-popover-view-logs')).toHaveCount(0);
- await viewTraces.click();
-
- await expect(page).toHaveURL(/\/traces-explorer/);
- const search = new URL(page.url()).searchParams;
- expect(search.get('startTime')).toBeTruthy();
- expect(search.get('endTime')).toBeTruthy();
- expect(page.url()).toContain('compositeQuery');
- });
-
- test('TC-08 metrics rule rows show disabled action (no related links)', async ({
- authedPage: page,
- metricsHistory,
- }) => {
- await gotoAlertHistory(page, metricsHistory.ruleId);
-
- const action = timelineRows(page).first().getByTestId('timeline-row-actions');
- await expect(action).toBeDisabled();
-
- await expect(page.getByTestId('alert-popover-view-logs')).toHaveCount(0);
- await expect(page.getByTestId('alert-popover-view-traces')).toHaveCount(0);
- });
-
- test('TC-09 CREATED AT column respects app timezone setting', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(timelineRows(page).first()).toBeVisible();
- const utcCell = await firstTimelineRowCreatedAt(page);
-
- await page.addInitScript(() =>
- localStorage.setItem('PREFERRED_TIMEZONE', 'Asia/Kolkata'),
- );
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(timelineRows(page).first()).toBeVisible();
-
- expect(await firstTimelineRowCreatedAt(page)).not.toBe(utcCell);
- });
-
- test('TC-10 state cell renders Firing, Resolved, and No Data correctly', async ({
- authedPage: page,
- resolvedHistory,
- noDataHistory,
- }) => {
- await gotoAlertHistory(page, resolvedHistory.ruleId);
- await expect(timelineRows(page).first()).toBeVisible();
- const stateCells = timelineRows(page).getByTestId('timeline-row-state');
- const labels = [...new Set(await stateCells.allInnerTexts())];
- expect(labels).toContain('Firing');
- expect(labels).toContain('Resolved');
-
- await gotoAlertHistory(page, noDataHistory.ruleId);
- await expect(
- timelineRows(page).getByTestId('timeline-row-state').first(),
- ).toHaveText('No Data');
- });
-
- // eslint-disable-next-line playwright/expect-expect -- documented coverage gap
- test('TC-11 pending/recovering states render blank (coverage gap)', async () => {
- test.skip(
- true,
- 'Needs SEED-D (coverage doc §3.5): `pending` and `recovering` are ' +
- 'transient states no cheap fixture produces. AlertState.tsx has no ' +
- '`case` for either, so both hit `default` and the STATE cell renders ' +
- 'empty — write this as a bug-catch once the seeder endpoint exists.',
- );
- });
-
- // eslint-disable-next-line playwright/expect-expect -- documented coverage gap
- test('TC-12 disabled state renders as "Muted" (coverage gap)', async () => {
- test.skip(
- true,
- 'Needs SEED-D (coverage doc §3.5): a `disabled` history row is ' +
- 'policy-driven and the ruler never writes one for a rule we disable ' +
- '(verified: disabling appends no row).',
- );
- });
-
- // eslint-disable-next-line playwright/expect-expect -- documented coverage gap
- test('TC-13 time-range boundaries inclusive/exclusive (coverage gap)', async () => {
- test.skip(
- true,
- 'Needs SEED-D (coverage doc §3.5): asserting a row exactly at `start` ' +
- 'and one at `start-1ms` requires controlling the row timestamps, and ' +
- 'evaluation times are whatever the ruler chose.',
- );
- });
-});
diff --git a/tests/e2e/tests/alerts/history/timeline.spec.ts b/tests/e2e/tests/alerts/history/timeline.spec.ts
new file mode 100644
index 0000000000..3bd40d1308
--- /dev/null
+++ b/tests/e2e/tests/alerts/history/timeline.spec.ts
@@ -0,0 +1,260 @@
+import { expect, test, TIMELINE_PAGE_SIZE } from '../../../drivers/alerts';
+
+// The timeline table and its pagination, against history rows the ruler really
+// produced.
+//
+// Three states have no cheap fixture and are deliberately uncovered: `pending`
+// and `recovering` are transient and nothing can hold them still; a `disabled`
+// row is policy-driven and the ruler writes none when a rule is disabled
+// (verified); and asserting a row exactly at `start` versus `start-1ms` needs
+// control over evaluation timestamps the ruler chooses for itself.
+
+test.describe('Alert history — timeline', () => {
+ test('TC-01 the timeline renders its chrome, rows and footer range', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+
+ await expect(alerts.history.timelineTitle()).toHaveText('Timeline');
+ await expect(alerts.history.timelineTab('overall-status')).toBeVisible();
+ await expect(alerts.history.stateFilter('all')).toBeVisible();
+ await expect(alerts.history.stateFilter('fired')).toBeVisible();
+ await expect(alerts.history.stateFilter('resolved')).toBeVisible();
+ await expect(alerts.history.graph()).toBeVisible();
+ await expect(alerts.history.table()).toBeVisible();
+
+ const contributorsTab = alerts.history.timelineTab('top-contributors');
+ await expect(contributorsTab).toBeDisabled();
+ await expect(contributorsTab).toContainText('Coming Soon');
+
+ await expect(alerts.history.rows()).toHaveCount(TIMELINE_PAGE_SIZE);
+ const first = alerts.history.rows().first();
+ await expect(alerts.history.rowCell(first, 'state')).toHaveText('Firing');
+ await expect(alerts.history.rowCell(first, 'labels')).toContainText(
+ 'service.name',
+ );
+ await expect(alerts.history.rowCell(first, 'created-at')).toHaveText(
+ /^[A-Z][a-z]{2} \d{1,2}, \d{4} ⎯ \d{2}:\d{2}:\d{2}$/,
+ );
+ await expect(alerts.history.footerRange()).toHaveText(
+ `1 — ${TIMELINE_PAGE_SIZE} of ${alertHistory.total}`,
+ );
+
+ // A row is not a link: clicking one must not navigate.
+ const before = page.url();
+ await first.click();
+ expect(page.url()).toBe(before);
+ await expect(alerts.history.table()).toBeVisible();
+ });
+
+ test('TC-02 paging forward sends the cursor and covers the rest of the rows', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ await expect(alerts.history.rows().first()).toBeVisible();
+ const pageOne = await alerts.history.rowLabels();
+ await expect(alerts.history.prevPageButton()).toBeDisabled();
+
+ const request = page.waitForRequest((req) =>
+ alerts.history.isRequest(req, 'timeline'),
+ );
+ await alerts.history.nextPageButton().click();
+
+ expect(new URL((await request).url()).searchParams.get('cursor')).toBe(
+ alerts.history.cursorFor(2),
+ );
+ await expect(page).toHaveURL(/[?&]page=2/);
+ await expect(alerts.history.rows()).toHaveCount(
+ alertHistory.total - TIMELINE_PAGE_SIZE,
+ );
+ await expect(alerts.history.footerRange()).toHaveText(
+ `${TIMELINE_PAGE_SIZE + 1} — ${alertHistory.total} of ${alertHistory.total}`,
+ );
+ await expect(alerts.history.nextPageButton()).toBeDisabled();
+ await expect(alerts.history.prevPageButton()).toBeEnabled();
+
+ // Together the two pages are the whole set, with nothing repeated.
+ const pageTwo = await alerts.history.rowLabels();
+ expect(pageTwo).not.toEqual(pageOne);
+ expect(pageOne.length + pageTwo.length).toBe(alertHistory.total);
+ expect(new Set([...pageOne, ...pageTwo]).size).toBe(alertHistory.total);
+ });
+
+ test('TC-03 paging back drops the cursor, and so does the browser Back button', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId, { page: '2' });
+
+ const request = page.waitForRequest((req) =>
+ alerts.history.isRequest(req, 'timeline'),
+ );
+ await alerts.history.prevPageButton().click();
+
+ expect(new URL((await request).url()).searchParams.get('cursor')).toBeNull();
+ await expect(alerts.history.footerRange()).toHaveText(
+ `1 — ${TIMELINE_PAGE_SIZE} of ${alertHistory.total}`,
+ );
+
+ await alerts.history.nextPageButton().click();
+ await expect(page).toHaveURL(/[?&]page=2/);
+ await page.goBack();
+ await expect(page).not.toHaveURL(/[?&]page=2/);
+ await expect(alerts.history.footerRange()).toHaveText(
+ `1 — ${TIMELINE_PAGE_SIZE} of ${alertHistory.total}`,
+ );
+ });
+
+ test('TC-04 ?page=2 deep-links straight to the second page', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ const request = page.waitForRequest(
+ (req) =>
+ alerts.history.isRequest(req, 'timeline') &&
+ new URL(req.url()).searchParams.get('cursor') ===
+ alerts.history.cursorFor(2),
+ );
+ await alerts.history.goto(alertHistory.ruleId, { page: '2' });
+ await request;
+
+ await expect(alerts.history.rows()).toHaveCount(
+ alertHistory.total - TIMELINE_PAGE_SIZE,
+ );
+ });
+
+ test('TC-05 the default order is ascending and sorting resets the page', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ const request = page.waitForRequest((req) =>
+ alerts.history.isRequest(req, 'timeline'),
+ );
+ await alerts.history.goto(alertHistory.ruleId, { page: '2' });
+
+ // Ascending is the default, so the URL carries no `order` while the request
+ // spells it out.
+ expect(new URL(page.url()).searchParams.get('order')).toBeNull();
+ expect(new URL((await request).url()).searchParams.get('order')).toBe('asc');
+
+ await alerts.history.sortDescending();
+
+ await expect(page).toHaveURL(/[?&]order=desc/);
+ await alerts.history.expectFirstPage();
+ });
+
+ test('TC-06 a single-page rule disables both pagination buttons', async ({
+ alerts,
+ metricsHistory,
+ }) => {
+ await alerts.history.goto(metricsHistory.ruleId);
+
+ await expect(alerts.history.rows()).toHaveCount(metricsHistory.total);
+ await expect(alerts.history.prevPageButton()).toBeDisabled();
+ await expect(alerts.history.nextPageButton()).toBeDisabled();
+ await expect(alerts.history.footerRange()).toHaveText(
+ `1 — ${metricsHistory.total} of ${metricsHistory.total}`,
+ );
+ });
+
+ test('TC-07 a logs rule links its rows to the logs explorer', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ await alerts.history.openRowActions(0);
+
+ const viewLogs = alerts.history.viewLogsLink();
+ await expect(viewLogs).toBeVisible();
+ await viewLogs.click();
+
+ await expect(page).toHaveURL(/\/logs\/logs-explorer/);
+ const search = new URL(page.url()).searchParams;
+ expect(search.get('startTime')).toBeTruthy();
+ expect(search.get('endTime')).toBeTruthy();
+ expect(page.url()).toContain('compositeQuery');
+ });
+
+ test('TC-08 a traces rule links its rows to the traces explorer only', async ({
+ authedPage: page,
+ alerts,
+ tracesHistory,
+ }) => {
+ await alerts.history.goto(tracesHistory.ruleId);
+ await alerts.history.openRowActions(0);
+
+ // The backend returns one related link or the other, never both.
+ const viewTraces = alerts.history.viewTracesLink();
+ await expect(viewTraces).toBeVisible();
+ await expect(alerts.history.viewLogsLink()).toHaveCount(0);
+ await viewTraces.click();
+
+ await expect(page).toHaveURL(/\/traces-explorer/);
+ const search = new URL(page.url()).searchParams;
+ expect(search.get('startTime')).toBeTruthy();
+ expect(search.get('endTime')).toBeTruthy();
+ expect(page.url()).toContain('compositeQuery');
+ });
+
+ test('TC-09 a metrics rule has no related links at all', async ({
+ alerts,
+ metricsHistory,
+ }) => {
+ await alerts.history.goto(metricsHistory.ruleId);
+
+ await expect(
+ alerts.history.rowCell(alerts.history.rows().first(), 'actions'),
+ ).toBeDisabled();
+ await expect(alerts.history.viewLogsLink()).toHaveCount(0);
+ await expect(alerts.history.viewTracesLink()).toHaveCount(0);
+ });
+
+ test('TC-10 CREATED AT follows the app timezone setting', async ({
+ authedPage: page,
+ alerts,
+ alertHistory,
+ }) => {
+ await alerts.history.goto(alertHistory.ruleId);
+ await expect(alerts.history.rows().first()).toBeVisible();
+ const utcCell = await alerts.history.firstRowCreatedAt();
+
+ await page.addInitScript(() =>
+ localStorage.setItem('PREFERRED_TIMEZONE', 'Asia/Kolkata'),
+ );
+ await alerts.history.goto(alertHistory.ruleId);
+ await expect(alerts.history.rows().first()).toBeVisible();
+
+ expect(await alerts.history.firstRowCreatedAt()).not.toBe(utcCell);
+ });
+
+ test('TC-11 the state cell renders Firing, Resolved and No Data', async ({
+ alerts,
+ noDataHistory,
+ resolvedHistory,
+ }) => {
+ await alerts.history.goto(resolvedHistory.ruleId);
+ await expect(alerts.history.rows().first()).toBeVisible();
+ const labels = [
+ ...new Set(
+ await alerts.history
+ .rowCell(alerts.history.rows(), 'state')
+ .allInnerTexts(),
+ ),
+ ];
+ expect(labels).toContain('Firing');
+ expect(labels).toContain('Resolved');
+
+ await alerts.history.goto(noDataHistory.ruleId);
+ await expect(
+ alerts.history.rowCell(alerts.history.rows(), 'state').first(),
+ ).toHaveText('No Data');
+ });
+});
diff --git a/tests/e2e/tests/alerts/history/top-contributors.spec.ts b/tests/e2e/tests/alerts/history/top-contributors.spec.ts
deleted file mode 100644
index bd667f4da1..0000000000
--- a/tests/e2e/tests/alerts/history/top-contributors.spec.ts
+++ /dev/null
@@ -1,118 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-history';
-import { gotoAlertHistory } from '../../../helpers/alerts/history';
-
-test.describe('Alert history — top contributors', () => {
- test('TC-01 card displays max 3 rows with count ratios', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const card = page.getByTestId('top-contributors-card');
- await expect(card).toBeVisible();
- await expect(card).toContainText('top contributors');
-
- const rows = card.getByTestId('top-contributors-row');
- await expect(rows).toHaveCount(3);
- for (let i = 0; i < 3; i += 1) {
- await expect(
- rows.nth(i).getByTestId('top-contributors-row-count'),
- ).toHaveText(`1/${alertHistory.total}`);
- await expect(rows.nth(i)).toContainText('service.name');
- }
- });
-
- // AS-05 reads the `count/total` text, which a *different* column renders than
- // the bar does. Dropping the `/ total * 100` scaling from the bar leaves that
- // text untouched, so the width needs its own assertion. Radix surfaces the
- // clamped percent as `aria-valuenow`.
- test('TC-02 contributor bar width is the count as a percentage of the total', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- const rows = page
- .getByTestId('top-contributors-card')
- .getByTestId('top-contributors-row');
- await expect(rows).toHaveCount(3);
-
- // Every SEED-A contributor fired exactly once out of `total`.
- const percent = String((1 / alertHistory.total) * 100);
- for (let i = 0; i < 3; i += 1) {
- await expect(rows.nth(i).getByRole('progressbar')).toHaveAttribute(
- 'aria-valuenow',
- percent,
- );
- }
- });
-
- test('TC-03 "View all" button only appears when more than 3 contributors', async ({
- authedPage: page,
- alertHistory,
- metricsHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- await expect(page.getByTestId('top-contributors-view-all')).toBeVisible();
-
- await gotoAlertHistory(page, metricsHistory.ruleId);
- await expect(page.getByTestId('top-contributors-card')).toBeVisible();
- await expect(page.getByTestId('top-contributors-view-all')).toHaveCount(0);
- });
-
- test('TC-04 View-all drawer shows paginated list of all contributors', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await page.getByTestId('top-contributors-view-all').click();
-
- const drawer = page.getByTestId('top-contributors-drawer');
- await expect(drawer).toBeVisible();
- await expect(page.getByText('Viewing All Contributors')).toBeVisible();
- await expect(drawer.getByTestId('top-contributors-row')).toHaveCount(10);
- await expect(drawer.locator('.total')).toHaveText(
- ` of ${alertHistory.total}`,
- );
- });
-
- test('TC-05 drawer opens from deep link with ?viewAllTopContributors=true', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId, {
- viewAllTopContributors: 'true',
- });
-
- await expect(page.getByTestId('top-contributors-drawer')).toBeVisible();
- });
-
- test('TC-06 View-all click adds ?viewAllTopContributors=true to URL', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
- await page.getByTestId('top-contributors-view-all').click();
-
- await expect(page).toHaveURL(/[?&]viewAllTopContributors=true/);
- await expect(page.getByTestId('top-contributors-drawer')).toBeVisible();
- });
-
- test('TC-07 contributor rows show related-logs link for logs-based rules', async ({
- authedPage: page,
- alertHistory,
- }) => {
- await gotoAlertHistory(page, alertHistory.ruleId);
-
- await page
- .getByTestId('top-contributors-card')
- .getByTestId('top-contributors-row')
- .first()
- .getByTestId('top-contributors-row-count')
- .click();
-
- await expect(page.getByTestId('alert-popover-view-logs')).toBeVisible();
- await expect(page.getByTestId('alert-popover-view-traces')).toHaveCount(0);
- });
-});
diff --git a/tests/e2e/tests/alerts/list.spec.ts b/tests/e2e/tests/alerts/list.spec.ts
new file mode 100644
index 0000000000..eb7d63a96a
--- /dev/null
+++ b/tests/e2e/tests/alerts/list.spec.ts
@@ -0,0 +1,170 @@
+import { ALERT_LIST_PAGE_SIZE, expect, test } from '../../drivers/alerts';
+
+// What stays here is what needs a real backend behind a real table: the seeded
+// rules rendering, the server-side filter semantics, and the write paths that
+// have to survive a reload. Column visibility, search debounce, client-side
+// pagination, the row-action *requests* and the empty states are asserted
+// against `ListAlertRules` in jest — see
+// `frontend/src/container/ListAlertRules/__tests__/`.
+
+test.describe('Alert rules list', () => {
+ test('TC-01 seeded rules render with their columns, total and second page', async ({
+ authedPage: page,
+ alerts,
+ alertList,
+ }) => {
+ await alerts.list.goto({ search: alertList.namePrefix });
+
+ for (const header of ['Status', 'Alert Name', 'Severity', 'Labels']) {
+ await expect(alerts.list.columnHeader(header)).toBeVisible();
+ }
+ await expect(alerts.list.rows()).toHaveCount(ALERT_LIST_PAGE_SIZE);
+ await expect(alerts.list.table.totalCount()).toContainText(
+ `of ${alertList.count}`,
+ );
+
+ await alerts.list.nextPageButton().click();
+
+ await expect(page).toHaveURL(/[?&]page=2/);
+ await expect(alerts.list.rows()).toHaveCount(
+ alertList.count - ALERT_LIST_PAGE_SIZE,
+ );
+ await expect(alerts.list.table.totalCount()).toContainText(
+ `${ALERT_LIST_PAGE_SIZE + 1} - ${alertList.count}`,
+ );
+ });
+
+ test('TC-02 state and severity filters intersect, they do not union', async ({
+ alerts,
+ alertList,
+ }) => {
+ const perSeverity = alertList.count / 3;
+ const scoped = { search: alertList.namePrefix };
+
+ // One filter kind: a third of the batch.
+ await alerts.list.goto({
+ ...scoped,
+ alertRulesFilters: JSON.stringify(['severity:warning']),
+ });
+ await expect(alerts.list.rows()).toHaveCount(perSeverity);
+
+ // Both kinds, both satisfied — seeded rules never fire, so they sit in
+ // `inactive` and the intersection is unchanged.
+ await alerts.list.goto({
+ ...scoped,
+ alertRulesFilters: JSON.stringify(['severity:warning', 'state:inactive']),
+ });
+ await expect(alerts.list.rows()).toHaveCount(perSeverity);
+
+ // Both kinds, only one satisfied. Under AND this is empty; under OR the
+ // severity match alone would still surface all `perSeverity` rules.
+ await alerts.list.goto(
+ {
+ ...scoped,
+ alertRulesFilters: JSON.stringify(['severity:warning', 'state:firing']),
+ },
+ { expectRows: false },
+ );
+ await expect(alerts.list.rows()).toHaveCount(0);
+ });
+
+ test('TC-03 row actions persist: disable, clone, delete', async ({
+ authedPage: page,
+ alerts,
+ ownedRules,
+ }) => {
+ const name = `e2e-alert-row-${Date.now()}`;
+ const ruleId = await ownedRules.threshold(name);
+
+ await alerts.list.goto({ search: name });
+ await expect(alerts.list.stateCell(ruleId)).toHaveText('OK');
+
+ const patched = (): Promise<unknown> =>
+ page.waitForResponse(
+ (res) =>
+ res.url().includes(`/api/v2/rules/${ruleId}`) &&
+ res.request().method() === 'PATCH',
+ );
+
+ await alerts.list.openFirstRowActions();
+ await Promise.all([patched(), alerts.list.menuItem('Disable').click()]);
+ await expect(alerts.list.stateCell(ruleId)).toHaveText('Disabled');
+
+ // The state has to come back from the server, not from optimistic UI.
+ await page.reload();
+ await expect(alerts.list.stateCell(ruleId)).toHaveText('Disabled');
+
+ await alerts.list.openFirstRowActions();
+ await Promise.all([patched(), alerts.list.menuItem('Enable').click()]);
+ await expect(alerts.list.stateCell(ruleId)).toHaveText('OK');
+
+ await alerts.list.openFirstRowActions();
+ const [cloned] = await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ /\/api\/v\d\/rules\/[^/]+\/clone$/.test(new URL(res.url()).pathname) &&
+ res.request().method() === 'POST',
+ ),
+ alerts.list.menuItem('Clone').click(),
+ ]);
+ await ownedRules.register(cloned);
+ await expect(alerts.shell.message('Alert cloned successfully')).toBeVisible();
+
+ await alerts.list.goto({ search: name });
+ await expect(alerts.list.ruleName(`${name} - Copy`)).toBeVisible();
+
+ await alerts.list.openRowActions(`${name} - Copy`);
+ await Promise.all([
+ page.waitForResponse(
+ (res) =>
+ /\/api\/v\d\/rules\//.test(new URL(res.url()).pathname) &&
+ res.request().method() === 'DELETE',
+ ),
+ alerts.list.menuItem('Delete').click(),
+ ]);
+ await expect(
+ alerts.shell.message('Alert deleted successfully'),
+ ).toBeVisible();
+ await expect(alerts.list.ruleName(`${name} - Copy`)).toHaveCount(0);
+ });
+
+ test('TC-04 sorting and page size reach the URL and the request', async ({
+ authedPage: page,
+ alerts,
+ alertList,
+ }) => {
+ await alerts.list.goto({ search: alertList.namePrefix });
+ const firstAscending = await alerts.list.rows().first().textContent();
+
+ await alerts.list.sortButton('Alert Name').click();
+ await expect(page).toHaveURL(/[?&]orderBy=/);
+ await alerts.list.sortButton('Alert Name').click();
+ await expect(alerts.list.rows().first()).not.toHaveText(firstAscending ?? '');
+
+ await alerts.list.goto({ search: alertList.namePrefix });
+ await alerts.list.pageSizeSelect().click();
+ await alerts.list.pageSizeOption(20).click();
+
+ await expect(page).toHaveURL(/[?&]limit=20/);
+ await expect(alerts.list.rows()).toHaveCount(alertList.count);
+ });
+
+ test('TC-05 Edit in New Tab opens the rule in a second tab', async ({
+ authedPage: page,
+ alerts,
+ alertList,
+ }) => {
+ await alerts.list.goto({ search: alertList.namePrefix });
+
+ await alerts.list.openFirstRowActions();
+ await alerts.list.menuItem('Edit in New Tab').first().waitFor();
+
+ const [newTab] = await Promise.all([
+ page.context().waitForEvent('page'),
+ alerts.list.menuItem('Edit in New Tab').first().click(),
+ ]);
+ await newTab.waitForLoadState();
+ expect(newTab.url()).toContain('/alerts/overview');
+ await newTab.close();
+ });
+});
diff --git a/tests/e2e/tests/alerts/list/columns.spec.ts b/tests/e2e/tests/alerts/list/columns.spec.ts
deleted file mode 100644
index 40ec312fac..0000000000
--- a/tests/e2e/tests/alerts/list/columns.spec.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import { ALERT_LIST_PAGE_SIZE } from '../../../helpers/alerts/constants';
-import {
- alertRuleRows,
- gotoAlertList,
-} from '../../../helpers/alerts/navigation';
-
-test.describe('Alert rules list — columns', () => {
- test('TC-01 renders all default columns (Status, Alert Name, Severity, Labels, Actions)', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
-
- for (const header of ['Status', 'Alert Name', 'Severity', 'Labels']) {
- await expect(page.getByRole('columnheader', { name: header })).toBeVisible();
- }
- await expect(
- page.getByRole('columnheader', { name: 'Actions' }),
- ).toBeVisible();
- for (const hidden of [
- 'Created At',
- 'Created By',
- 'Updated At',
- 'Updated By',
- ]) {
- await expect(page.getByRole('columnheader', { name: hidden })).toHaveCount(
- 0,
- );
- }
-
- await expect(alertRuleRows(page)).toHaveCount(ALERT_LIST_PAGE_SIZE);
- await expect(page.getByTestId('alert-columns-button')).toBeVisible();
- });
-
- test('TC-02 column selector hides and shows a column', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
- await expect(
- page.getByRole('columnheader', { name: 'Severity' }),
- ).toBeVisible();
-
- await page.getByTestId('alert-columns-button').click();
- await page.getByText('Toggle Columns').waitFor();
- const severityToggle = page.locator('label', { hasText: 'Severity' });
- await severityToggle.click();
-
- await expect(
- page.getByRole('columnheader', { name: 'Severity' }),
- ).toHaveCount(0);
-
- await page.reload();
- await expect(
- page.getByRole('columnheader', { name: 'Severity' }),
- ).toHaveCount(0);
-
- await page.getByTestId('alert-columns-button').click();
- await page.locator('label', { hasText: 'Severity' }).click();
- await expect(
- page.getByRole('columnheader', { name: 'Severity' }),
- ).toBeVisible();
- });
-
- test('TC-03 sorts by column header click', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
-
- const firstCell = alertRuleRows(page).first();
- const ascFirst = await firstCell.textContent();
-
- await page.getByRole('button', { name: 'Alert Name' }).click();
- await expect(page).toHaveURL(/[?&]orderBy=/);
-
- await page.getByRole('button', { name: 'Alert Name' }).click();
- await expect(page).toHaveURL(/[?&]orderBy=/);
- await expect(alertRuleRows(page).first()).not.toHaveText(ascFirst ?? '');
- });
-});
diff --git a/tests/e2e/tests/alerts/list/navigation.spec.ts b/tests/e2e/tests/alerts/list/navigation.spec.ts
deleted file mode 100644
index 27c62989a7..0000000000
--- a/tests/e2e/tests/alerts/list/navigation.spec.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- alertRuleRows,
- gotoAlertList,
-} from '../../../helpers/alerts/navigation';
-
-test.describe('Alert rules list — navigation', () => {
- test('TC-01 row click opens the overview page', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
-
- await alertRuleRows(page).first().click();
-
- await expect(page).toHaveURL(/\/alerts\/overview\?/);
- await expect(page).toHaveURL(/[?&]ruleId=/);
- await expect(page).toHaveURL(/[?&]compositeQuery=/);
- await expect(page).toHaveURL(/[?&]panelTypes=/);
- });
-
- test('TC-02 actions menu Edit and Edit in New Tab navigate correctly', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
-
- await alertRuleRows(page).first().getByTestId('alert-actions').click();
- await page.getByRole('menuitem', { name: 'Edit in New Tab' }).waitFor();
-
- const [newPage] = await Promise.all([
- page.context().waitForEvent('page'),
- page.getByRole('menuitem', { name: 'Edit in New Tab' }).click(),
- ]);
- await newPage.waitForLoadState();
- expect(newPage.url()).toContain('/alerts/overview');
- await newPage.close();
-
- await alertRuleRows(page).first().getByTestId('alert-actions').click();
- await page.getByRole('menuitem', { name: 'Edit', exact: true }).click();
-
- await expect(page).toHaveURL(/\/alerts\/overview\?/);
- await expect(page).toHaveURL(/[?&]ruleId=/);
- });
-
- test('TC-03 New Alert button navigates to alert creation', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
-
- await page.getByTestId('list-alerts-new-alert-button').click();
-
- await expect(page).toHaveURL(/\/alerts\/new/);
- });
-});
diff --git a/tests/e2e/tests/alerts/list/pagination-sort.spec.ts b/tests/e2e/tests/alerts/list/pagination-sort.spec.ts
deleted file mode 100644
index ea0eba77fc..0000000000
--- a/tests/e2e/tests/alerts/list/pagination-sort.spec.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import { ALERT_LIST_PAGE_SIZE } from '../../../helpers/alerts/constants';
-import {
- alertRuleRows,
- gotoAlertList,
-} from '../../../helpers/alerts/navigation';
-
-test.describe('Alert rules list — pagination and sorting', () => {
- test('TC-01 navigates between pages', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
-
- await expect(page.getByTestId('pagination-total-count')).toContainText(
- `of ${alertList.count}`,
- );
- await expect(alertRuleRows(page)).toHaveCount(ALERT_LIST_PAGE_SIZE);
-
- await page.getByLabel('Go to next page').click();
-
- await expect(page).toHaveURL(/[?&]page=2/);
- await expect(alertRuleRows(page)).toHaveCount(
- alertList.count - ALERT_LIST_PAGE_SIZE,
- );
- await expect(page.getByTestId('pagination-total-count')).toContainText(
- `${ALERT_LIST_PAGE_SIZE + 1} - ${alertList.count}`,
- );
- });
-
- test('TC-02 changes page size', async ({ authedPage: page, alertList }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
- await expect(alertRuleRows(page)).toHaveCount(ALERT_LIST_PAGE_SIZE);
-
- await page.getByTestId('pagination-page-size').click();
- await page.getByRole('option', { name: '20', exact: true }).click();
-
- await expect(page).toHaveURL(/[?&]limit=20/);
- await expect(alertRuleRows(page)).toHaveCount(alertList.count);
- });
-});
diff --git a/tests/e2e/tests/alerts/list/row-actions.spec.ts b/tests/e2e/tests/alerts/list/row-actions.spec.ts
deleted file mode 100644
index f62b605fc8..0000000000
--- a/tests/e2e/tests/alerts/list/row-actions.spec.ts
+++ /dev/null
@@ -1,95 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- alertRuleRows,
- gotoAlertList,
-} from '../../../helpers/alerts/navigation';
-
-test.describe('Alert rules list — row actions', () => {
- test('TC-01 Disable then Enable toggles the rule state', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-alert-row-toggle-${Date.now()}`;
- const ruleId = await ownedRules.threshold(name);
-
- await gotoAlertList(page, { search: name });
- const row = alertRuleRows(page).first();
- await expect(row.getByTestId(`alert-row-${ruleId}-state`)).toHaveText('OK');
-
- await row.getByTestId('alert-actions').click();
- await Promise.all([
- page.waitForResponse(
- (res) =>
- res.url().includes(`/api/v2/rules/${ruleId}`) &&
- res.request().method() === 'PATCH',
- ),
- page.getByRole('menuitem', { name: 'Disable' }).click(),
- ]);
-
- await expect(row.getByTestId(`alert-row-${ruleId}-state`)).toHaveText(
- 'Disabled',
- );
-
- await row.getByTestId('alert-actions').click();
- await Promise.all([
- page.waitForResponse(
- (res) =>
- res.url().includes(`/api/v2/rules/${ruleId}`) &&
- res.request().method() === 'PATCH',
- ),
- page.getByRole('menuitem', { name: 'Enable' }).click(),
- ]);
-
- await expect(row.getByTestId(`alert-row-${ruleId}-state`)).toHaveText('OK');
- });
-
- test('TC-02 Clone creates a copy and shows success toast', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-alert-row-clone-${Date.now()}`;
- await ownedRules.threshold(name);
-
- await gotoAlertList(page, { search: name });
- await alertRuleRows(page).first().getByTestId('alert-actions').click();
-
- const [createResponse] = await Promise.all([
- page.waitForResponse(
- (res) =>
- /\/api\/v\d\/rules\/[^/]+\/clone$/.test(new URL(res.url()).pathname) &&
- res.request().method() === 'POST',
- ),
- page.getByRole('menuitem', { name: 'Clone' }).click(),
- ]);
-
- await ownedRules.register(createResponse);
-
- await expect(page.getByText('Alert cloned successfully')).toBeVisible();
-
- await gotoAlertList(page, { search: name });
- await expect(page.getByText(`${name} - Copy`)).toBeVisible();
- });
-
- test('TC-03 Delete removes the rule and shows success toast', async ({
- authedPage: page,
- ownedRules,
- }) => {
- const name = `e2e-alert-row-delete-${Date.now()}`;
- const ruleId = await ownedRules.threshold(name);
-
- await gotoAlertList(page, { search: name });
- await alertRuleRows(page).first().getByTestId('alert-actions').click();
-
- await Promise.all([
- page.waitForResponse(
- (res) =>
- res.url().includes(`/api/v2/rules/${ruleId}`) &&
- res.request().method() === 'DELETE',
- ),
- page.getByRole('menuitem', { name: 'Delete' }).click(),
- ]);
-
- await expect(page.getByText('Alert deleted successfully')).toBeVisible();
- await expect(page.getByText(name, { exact: true })).toHaveCount(0);
- });
-});
diff --git a/tests/e2e/tests/alerts/list/search.spec.ts b/tests/e2e/tests/alerts/list/search.spec.ts
deleted file mode 100644
index 36cf9bda5d..0000000000
--- a/tests/e2e/tests/alerts/list/search.spec.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { expect, test } from '../../../fixtures/alerts/alert-rules';
-import {
- ALERT_LIST_PAGE_SIZE,
- SEED_B_SEVERITIES,
-} from '../../../helpers/alerts/constants';
-import { expectFirstPage } from '../../../helpers/alerts/history';
-import {
- alertRuleRows,
- gotoAlertList,
-} from '../../../helpers/alerts/navigation';
-
-test.describe('Alert rules list — search', () => {
- test('TC-01 filters by name', async ({ authedPage: page, alertList }) => {
- await gotoAlertList(page);
-
- await page
- .getByTestId('list-alerts-search-input')
- .fill(`${alertList.namePrefix}-03`);
-
- await expect(page).toHaveURL(new RegExp(`search=${alertList.namePrefix}-03`));
- await expect(alertRuleRows(page)).toHaveCount(1);
- await expect(page.getByText(`${alertList.namePrefix}-03`)).toBeVisible();
- });
-
- test('TC-02 filters by severity and by label', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page);
- const search = page.getByTestId('list-alerts-search-input');
-
- const perSeverity = Math.floor(alertList.count / SEED_B_SEVERITIES.length);
-
- await search.fill('warning');
- await expect(page).toHaveURL(/search=warning/);
- await expect(alertRuleRows(page)).not.toHaveCount(0);
- for (const row of await alertRuleRows(page).all()) {
- await expect(row).toContainText('warning');
- }
- expect(await alertRuleRows(page).count()).toBeGreaterThanOrEqual(perSeverity);
-
- await search.fill(alertList.paymentsLabel);
- await expect(page).toHaveURL(new RegExp(`search=${alertList.paymentsLabel}`));
- await expect(alertRuleRows(page)).toHaveCount(alertList.count / 2);
- });
-
- test('TC-03 shows no-results state with clear button', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { search: alertList.namePrefix });
-
- await page
- .getByTestId('list-alerts-search-input')
- .fill('no-such-alert-anywhere');
-
- await expect(page.getByText('No matching alert rules')).toBeVisible();
-
- await page.getByRole('button', { name: 'Clear Search' }).click();
-
- await expect(page).not.toHaveURL(/search=/);
- await expect(alertRuleRows(page)).toHaveCount(ALERT_LIST_PAGE_SIZE);
- });
-
- test('TC-04 resets pagination when searching', async ({
- authedPage: page,
- alertList,
- }) => {
- await gotoAlertList(page, { page: '2' });
- await expect(page).toHaveURL(/[?&]page=2/);
-
- await page.getByTestId('list-alerts-search-input').fill(alertList.namePrefix);
-
- await expectFirstPage(page);
- });
-
- test('TC-05 state and severity filters intersect, they do not union', async ({
- authedPage: page,
- alertList,
- }) => {
- const perSeverity = alertList.count / SEED_B_SEVERITIES.length;
- const scoped = { search: alertList.namePrefix };
-
- // One filter kind: a third of the batch.
- await gotoAlertList(page, {
- ...scoped,
- alertRulesFilters: JSON.stringify(['severity:warning']),
- });
- await expect(alertRuleRows(page)).toHaveCount(perSeverity);
- for (const row of await alertRuleRows(page).all()) {
- await expect(row).toContainText('warning');
- }
-
- // Both kinds, both satisfied — seeded rules never fire, so they sit in
- // `inactive`. The intersection is unchanged.
- await gotoAlertList(page, {
- ...scoped,
- alertRulesFilters: JSON.stringify(['severity:warning', 'state:inactive']),
- });
- await expect(alertRuleRows(page)).toHaveCount(perSeverity);
-
- // Both kinds, only one satisfied. Under AND this is empty; under OR the
- // severity match alone would still surface all `perSeverity` rules.
- await gotoAlertList(
- page,
- {
- ...scoped,
- alertRulesFilters: JSON.stringify(['severity:warning', 'state:firing']),
- },
- { expectRows: false },
- );
- await expect(alertRuleRows(page)).toHaveCount(0);
- await expect(page.getByText('No matching alert rules')).toBeVisible();
- });
-});
diff --git a/tests/e2e/tests/alerts/page.spec.ts b/tests/e2e/tests/alerts/page.spec.ts
index 31291162d0..993d8edeff 100644
--- a/tests/e2e/tests/alerts/page.spec.ts
+++ b/tests/e2e/tests/alerts/page.spec.ts
@@ -1,144 +1,157 @@
-import { expect, test } from '../../fixtures/alerts/alert-rules';
-import { ALERTS_LIST_PATH } from '../../helpers/alerts/constants';
-import { watchConsole } from '../../helpers/common';
+import { ALERTS_LIST_PATH, expect, test } from '../../drivers/alerts';
-// TC-* — the Alerts page shell: the top-level tabs, how they map to
-// `?tab=`, and a navigation smoke check per tab. Tab *internals* (channel CRUD,
-// planned downtime, routing policies) are deliberately out of scope — each
-// deserves its own spec file.
+// The Alerts page shell: the three top-level tabs, how they map to `?tab=`, and
+// the Configuration sidebar. Sidebar internals (channel CRUD, planned downtime,
+// routing policies) each deserve their own spec.
-const TAB_NAMES = {
+const TAB = {
triggered: /triggered alerts/i,
rules: /alert rules/i,
configuration: /configuration/i,
};
+// The sidebar marks its current item with a plain `active` class.
+const ACTIVE = /(^|\s)active(\s|$)/;
+
test.describe('Alerts page shell', () => {
- test('TC-01 all top-level tabs render', async ({ authedPage: page }) => {
- await page.goto(ALERTS_LIST_PATH);
+ test('TC-01 the three tabs render and Alert Rules is the default', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.shell.goto();
- for (const name of Object.values(TAB_NAMES)) {
- await expect(page.getByRole('tab', { name })).toBeVisible();
+ for (const name of Object.values(TAB)) {
+ await expect(alerts.shell.tab(name)).toBeVisible();
}
- });
-
- test('TC-02 default tab is Alert Rules', async ({ authedPage: page }) => {
- await page.goto(ALERTS_LIST_PATH);
-
- // No `tab` param at all — `getActiveKey()` falls back to AlertRules.
- await expect(page).toHaveURL(new RegExp(`${ALERTS_LIST_PATH}(\\?|$)`));
- await expect(page).not.toHaveURL(/[?&]tab=/);
- await expect(
- page.getByRole('tab', { name: TAB_NAMES.rules }),
- ).toHaveAttribute('aria-selected', 'true');
- // This spec seeds no rules, so the pane may render either the table (with
- // its search input) or `AlertsEmptyState` depending on what neighbouring
- // specs have in flight. Assert the pane itself, not one of its variants —
- // `ListAlertRules` hides the search input entirely in the empty state.
+ // No `tab` param at all — `getActiveKey()` falls back to AlertRules. The
+ // rules table writes its own `limit`, so the URL is not bare.
+ await expect(page).toHaveURL(
+ (url) => url.pathname === ALERTS_LIST_PATH && !url.searchParams.has('tab'),
+ );
+ await expect(alerts.shell.tab(TAB.rules)).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ // This spec seeds no rules, so the pane may render either the table or the
+ // empty state depending on what neighbouring specs have in flight.
await expect(
- page
- .getByRole('heading', { name: 'Alert Rules' })
- .or(page.getByTestId('list-alerts-search-input')),
+ alerts.shell.rulesHeading().or(alerts.list.search()),
).toBeVisible();
});
- test('TC-03 tab switch writes ?tab=', async ({ authedPage: page }) => {
- await page.goto(ALERTS_LIST_PATH);
+ test('TC-02 tab switch writes ?tab= and clears subTab', async ({
+ authedPage: page,
+ alerts,
+ }) => {
+ await alerts.shell.goto();
- await page.getByRole('tab', { name: TAB_NAMES.triggered }).click();
+ await alerts.shell.tab(TAB.triggered).click();
await expect(page).toHaveURL(/[?&]tab=TriggeredAlerts/);
- await page.getByRole('tab', { name: TAB_NAMES.configuration }).click();
+ // Entering Configuration adds the current sub-tab, channels by default…
+ await alerts.shell.tab(TAB.configuration).click();
await expect(page).toHaveURL(/[?&]tab=Configuration/);
await expect(page).toHaveURL(/[?&]subTab=channels/);
- await page.getByRole('tab', { name: TAB_NAMES.rules }).click();
+ // …and leaving it drops subTab entirely, because `onChange` rebuilds the
+ // search from scratch rather than mutating the existing params.
+ await alerts.shell.tab(TAB.rules).click();
await expect(page).toHaveURL(/[?&]tab=AlertRules/);
+ await expect(page).not.toHaveURL(/subTab=/);
});
- test('TC-04 Configuration sub-tab deep-links and sidebar navigation', async ({
+ test('TC-03 Configuration deep-links to its sidebar sections', async ({
authedPage: page,
+ alerts,
}) => {
- await page.goto(
- `${ALERTS_LIST_PATH}?tab=Configuration&subTab=routing-policies`,
+ // Without subTab the sidebar falls back to channels without writing it to
+ // the URL, so assert the rendered item, not the param.
+ await alerts.shell.goto({ tab: 'Configuration' });
+ await expect(alerts.shell.tab(TAB.configuration)).toHaveAttribute(
+ 'aria-selected',
+ 'true',
);
- await expect(
- page.getByRole('tab', { name: TAB_NAMES.configuration }),
- ).toHaveAttribute('aria-selected', 'true');
- await expect(page.getByTestId('alert-configuration-sidebar')).toBeVisible();
- await expect(
- page.getByTestId('configuration-sidebar-routing-policies'),
- ).toBeVisible();
+ await expect(alerts.shell.configSidebarItem('channels')).toHaveClass(ACTIVE);
- await page.goto(
- `${ALERTS_LIST_PATH}?tab=Configuration&subTab=planned-downtime`,
+ await alerts.shell.goto({
+ tab: 'Configuration',
+ subTab: 'routing-policies',
+ });
+ await expect(alerts.shell.configSidebarItem('routing-policies')).toHaveClass(
+ ACTIVE,
);
- await expect(
- page.getByRole('tab', { name: TAB_NAMES.configuration }),
- ).toHaveAttribute('aria-selected', 'true');
- await expect(
- page.getByTestId('configuration-sidebar-planned-downtime'),
- ).toBeVisible();
- // Backwards-compatible legacy deep links
- await page.goto(`${ALERTS_LIST_PATH}?tab=RoutingPolicies`);
- await expect(
- page.getByRole('tab', { name: TAB_NAMES.configuration }),
- ).toHaveAttribute('aria-selected', 'true');
+ await alerts.shell.goto({
+ tab: 'Configuration',
+ subTab: 'planned-downtime',
+ });
+ await expect(alerts.shell.configSidebarItem('planned-downtime')).toHaveClass(
+ ACTIVE,
+ );
- await page.goto(`${ALERTS_LIST_PATH}?tab=PlannedDowntime`);
- await expect(
- page.getByRole('tab', { name: TAB_NAMES.configuration }),
- ).toHaveAttribute('aria-selected', 'true');
- });
+ await alerts.shell.configSidebarItem('routing-policies').click();
+ await expect(page).toHaveURL(/[?&]tab=Configuration/);
+ await expect(page).toHaveURL(/[?&]subTab=routing-policies/);
+ await expect(alerts.shell.configSidebarItem('routing-policies')).toHaveClass(
+ ACTIVE,
+ );
- test('TC-05 Triggered Alerts tab smoke', async ({ authedPage: page }) => {
- // Known application defect, out of scope here: an icon on this tab renders
- // with a NaN dimension ("<svg> attribute viewBox: Expected number, \"0 0 32
- // NaN\""). Ignore that one string so the rest of the console guard still
- // has teeth.
- const watch = watchConsole(page, {
- ignore: ['attribute viewBox: Expected number'],
- });
+ // Links from before the sidebar, when these were top-level tabs.
+ const legacy = [
+ ['Channels', 'channels'],
+ ['RoutingPolicies', 'routing-policies'],
+ ['PlannedDowntime', 'planned-downtime'],
+ ] as const;
+
+ for (const [tab, section] of legacy) {
+ await alerts.shell.goto({ tab });
+ await expect(alerts.shell.tab(TAB.configuration)).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await expect(alerts.shell.configSidebarItem(section)).toHaveClass(ACTIVE);
+ }
+ });
- await page.goto(`${ALERTS_LIST_PATH}?tab=TriggeredAlerts`);
+ test('TC-04 the Triggered Alerts tab mounts clean', async ({
+ alerts,
+ noise,
+ }) => {
+ await alerts.shell.goto({ tab: 'TriggeredAlerts' });
// A fresh stack has no firing instances, so either the table or the empty
- // state is correct — what matters is that the tab mounts and its controls
- // render.
- await expect(page.getByTestId('triggered-alerts-search-input')).toBeVisible();
- expect(watch.errors).toEqual([]);
- expect(watch.failedResponses).toEqual([]);
+ // state is correct; what matters is that the tab mounts.
+ await expect(alerts.shell.triggeredSearch()).toBeVisible();
+ // Known application defect, out of scope here: an icon on this tab renders
+ // with a NaN dimension.
+ expect(
+ noise.errors.filter(
+ (error) => !error.includes('attribute viewBox: Expected number'),
+ ),
+ ).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
});
- test('TC-06 Notification Channels smoke under Configuration', async ({
+ test('TC-05 the Channels section lists channels and survives a reload', async ({
authedPage: page,
+ alerts,
alertChannel,
}) => {
- // The worker's channel gives this tab a row to render.
- await page.goto(`${ALERTS_LIST_PATH}?tab=Configuration&subTab=channels`);
-
- await expect(
- page.getByTestId('configuration-sidebar-channels'),
- ).toBeVisible();
- await expect(page.getByText(alertChannel.name)).toBeVisible();
- await expect(
- page.getByRole('button', { name: /new channel/i }),
- ).toBeVisible();
- });
+ await alerts.shell.goto({ tab: 'Configuration', subTab: 'channels' });
- test('TC-07 tab state survives reload', async ({ authedPage: page }) => {
- await page.goto(`${ALERTS_LIST_PATH}?tab=Configuration&subTab=channels`);
- await expect(
- page.getByRole('tab', { name: TAB_NAMES.configuration }),
- ).toHaveAttribute('aria-selected', 'true');
+ await expect(alerts.shell.configSidebar()).toBeVisible();
+ await expect(alerts.channels.newButton()).toBeVisible();
+ await alerts.channels.search(alertChannel.name);
+ await expect(alerts.channels.entry(alertChannel.name)).toBeVisible();
await page.reload();
await expect(page).toHaveURL(/[?&]tab=Configuration/);
await expect(page).toHaveURL(/[?&]subTab=channels/);
- await expect(
- page.getByRole('tab', { name: TAB_NAMES.configuration }),
- ).toHaveAttribute('aria-selected', 'true');
+ await expect(alerts.shell.tab(TAB.configuration)).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await expect(alerts.shell.configSidebarItem('channels')).toHaveClass(ACTIVE);
});
});
diff --git a/tests/e2e/tests/alerts/planned-downtime.spec.ts b/tests/e2e/tests/alerts/planned-downtime.spec.ts
new file mode 100644
index 0000000000..d1c08fc0b1
--- /dev/null
+++ b/tests/e2e/tests/alerts/planned-downtime.spec.ts
@@ -0,0 +1,59 @@
+import { expect, test } from '../../drivers/alerts';
+
+// Planned downtime under Configuration. The form's scope switch and payload
+// mapping are covered by jest in `container/PlannedDowntime/__test__/`; here
+// the save has to reach the real API.
+
+const inDays = (days: number): Date => {
+ const day = new Date();
+ day.setDate(day.getDate() + days);
+ return day;
+};
+
+test.describe('Planned downtime', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test('TC-01 a schedule started on specific rules and switched to All saves with no rule ids', async ({
+ alerts,
+ alertChannel,
+ }) => {
+ const stamp = Date.now();
+ const name = `e2e-downtime-${stamp}`;
+ const ruleName = `e2e-dt-${String(stamp).slice(-8)}`;
+ const ruleId = await alerts.seed.threshold({
+ name: ruleName,
+ target: 1,
+ channels: [alertChannel.name],
+ });
+
+ try {
+ await alerts.downtime.goto();
+ await alerts.downtime.newButton().click();
+ await alerts.downtime.fillName(name);
+ await alerts.downtime.pickDate('Starts from', inDays(1));
+ await alerts.downtime.pickTimezone('UTC');
+ await alerts.downtime.pickDate('Ends on', inDays(2));
+
+ await expect(alerts.downtime.scope('Specific alert rules')).toBeChecked();
+ await expect(alerts.downtime.rulePicker()).toBeVisible();
+ await alerts.downtime.pickRule(ruleName);
+ await expect(alerts.downtime.pickedRule(ruleName)).toBeVisible();
+
+ await alerts.downtime.scope('All alert rules').click();
+ await expect(alerts.downtime.rulePicker()).toHaveCount(0);
+ await alerts.downtime.save();
+
+ await alerts.downtime.search(name);
+ await expect(alerts.downtime.row(name)).toBeVisible();
+ const stored = await alerts.downtime.byName(name);
+ expect(stored?.alertIds ?? []).toEqual([]);
+ expect(stored?.schedule.timezone).toBe('UTC');
+
+ await alerts.downtime.remove(name);
+ await expect.poll(() => alerts.downtime.byName(name)).toBeUndefined();
+ } finally {
+ await alerts.downtime.tryDelete(name);
+ await alerts.seed.deleteRule(ruleId);
+ }
+ });
+});
diff --git a/tests/e2e/tests/alerts/routing-policies.spec.ts b/tests/e2e/tests/alerts/routing-policies.spec.ts
new file mode 100644
index 0000000000..b96499a0dc
--- /dev/null
+++ b/tests/e2e/tests/alerts/routing-policies.spec.ts
@@ -0,0 +1,66 @@
+import { expect, test } from '../../drivers/alerts';
+
+// Routing policies under Configuration. List rendering, search and the modal's
+// validation are covered by jest in `container/RoutingPolicies/__tests__/`;
+// here each write has to reach the real API.
+
+test.describe('Routing policies', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test('TC-01 a policy created, edited and deleted through the UI round-trips the API', async ({
+ alerts,
+ alertChannel,
+ }) => {
+ const name = `e2e-route-${Date.now()}`;
+ const expression = 'service.name == "checkout"';
+ const edited = 'service.name == "payment"';
+
+ try {
+ await alerts.routing.goto();
+ await alerts.routing.newButton().click();
+ await alerts.routing.fill({
+ name,
+ description: 'created by the e2e suite',
+ expression,
+ channel: alertChannel.name,
+ });
+ await alerts.routing.save();
+
+ await alerts.routing.search(name);
+ await expect(alerts.routing.row(name)).toBeVisible();
+ await expect
+ .poll(() => alerts.routing.byName(name))
+ .toMatchObject({ name, expression, channels: [alertChannel.name] });
+
+ await alerts.routing.edit(name);
+ await alerts.routing.fill({ expression: edited });
+ await alerts.routing.save();
+
+ await expect
+ .poll(async () => (await alerts.routing.byName(name))?.expression)
+ .toBe(edited);
+
+ await alerts.routing.remove(name);
+ await expect.poll(() => alerts.routing.byName(name)).toBeUndefined();
+ } finally {
+ await alerts.routing.tryDelete(name);
+ }
+ });
+});
+
+test.describe('Routing policies as a viewer', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test.use({ as: 'viewer' });
+
+ test('TC-02 the create button is disabled with its reason', async ({
+ alerts,
+ }) => {
+ await alerts.routing.goto();
+
+ await expect(alerts.routing.newButton()).toBeDisabled();
+ await expect(await alerts.routing.newButtonTooltip()).toHaveText(
+ 'You need edit permissions to create a routing policy',
+ );
+ });
+});
diff --git a/tests/e2e/tests/api-monitoring/explorer.spec.ts b/tests/e2e/tests/api-monitoring/explorer.spec.ts
new file mode 100644
index 0000000000..4dfeac6ccb
--- /dev/null
+++ b/tests/e2e/tests/api-monitoring/explorer.spec.ts
@@ -0,0 +1,97 @@
+import { expect, test } from '../../drivers/api-monitoring';
+
+const DOMAIN_HEADERS = [
+ 'Domain',
+ 'Endpoints in use',
+ 'Last used',
+ 'Rate ops/s',
+ 'Error %',
+ 'Avg. Latency ms',
+];
+
+const METRIC_LABELS = [
+ 'EXTERNAL API',
+ 'AVERAGE LATENCY',
+ 'ERROR %',
+ 'LAST USED',
+];
+
+test.describe('API monitoring, explorer', () => {
+ test('TC-01 domain list shows the seeded external host', async ({
+ apiMonitoring,
+ apiSeed,
+ noise,
+ }) => {
+ await apiMonitoring.goto();
+ await apiMonitoring.waitForDomain(apiSeed.host);
+
+ expect(await apiMonitoring.headers()).toEqual(DOMAIN_HEADERS);
+ await expect(
+ await apiMonitoring.domainCell(apiSeed.host, 'Endpoints in use'),
+ ).toHaveText('2');
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 the domain drawer opens with metrics and all three views render', async ({
+ apiMonitoring,
+ apiSeed,
+ }) => {
+ await apiMonitoring.goto();
+ await apiMonitoring.waitForDomain(apiSeed.host);
+ await apiMonitoring.openDomain(apiSeed.host);
+
+ const { drawer } = apiMonitoring;
+ for (const label of METRIC_LABELS) {
+ await expect(drawer.metrics()).toContainText(label);
+ }
+ await expect(async () => {
+ const values = await drawer.metricValues();
+ expect(values).toHaveLength(METRIC_LABELS.length);
+ expect(values[0]).toBe(String(apiSeed.callCount));
+ expect(values).not.toContain('-');
+ }).toPass();
+
+ await drawer.view('all_endpoints');
+ await expect(drawer.root()).toContainText('/v1/items');
+ await drawer.view('endpoint_stats');
+ await expect(drawer.statusCodeTable()).toBeVisible();
+ await drawer.view('top_errors');
+ await expect(drawer.topErrorsTable()).toBeVisible();
+ });
+
+ test('TC-03 top errors lists the seeded failing endpoint', async ({
+ apiMonitoring,
+ apiSeed,
+ }) => {
+ await apiMonitoring.gotoDomain(apiSeed.host, 'top_errors');
+
+ const row = apiMonitoring.drawer.topErrorRow(apiSeed.endpoints.items);
+ await expect(row).toHaveCount(1);
+ await expect(row).toContainText(String(apiSeed.errorStatus));
+ await expect(row).toContainText(apiSeed.errorMessage);
+ await expect(
+ apiMonitoring.drawer.topErrorCount(apiSeed.endpoints.items),
+ ).toHaveText('1');
+ });
+
+ test('TC-04 endpoint stats shows dependent caller services', async ({
+ apiMonitoring,
+ apiSeed,
+ }) => {
+ await apiMonitoring.gotoDomain(apiSeed.host, 'endpoint_stats', {
+ endpoint: apiSeed.endpoints.items,
+ });
+
+ const { drawer } = apiMonitoring;
+ await expect(drawer.dependentServices()).toContainText(
+ apiSeed.callers.orders,
+ );
+ await expect(drawer.dependentServices()).not.toContainText(
+ apiSeed.callers.billing,
+ );
+ for (const code of ['200', String(apiSeed.errorStatus)]) {
+ await expect(drawer.statusCodeCell(code)).toHaveCount(1);
+ }
+ });
+});
diff --git a/tests/e2e/tests/app-shell/routes.spec.ts b/tests/e2e/tests/app-shell/routes.spec.ts
new file mode 100644
index 0000000000..9242a9c2c2
--- /dev/null
+++ b/tests/e2e/tests/app-shell/routes.spec.ts
@@ -0,0 +1,35 @@
+import { expect, REDIRECTS, ROUTES, test } from '../../drivers/shell';
+
+// The broad regression net: every top-level route mounts its own component
+// without tripping an error boundary, a console error or a failed request.
+
+test.describe('app shell — routes', () => {
+ for (const probe of [...ROUTES, ...REDIRECTS]) {
+ test(probe.title, async ({ shell, noise }) => {
+ await shell.visit(probe);
+
+ await expect(shell.errorBoundary()).toHaveCount(
+ probe.expectBoundary ? 1 : 0,
+ );
+ expect(shell.pathname()).toBe(probe.expectPath ?? probe.path.split('?')[0]);
+ expect(shell.unexpectedErrors(noise, probe)).toEqual([]);
+ expect(shell.unexpectedFailures(noise, probe)).toEqual([]);
+ });
+ }
+
+ test('TC-32 the side nav offers no assistant entry without an assistant URL', async ({
+ shell,
+ }) => {
+ await shell.home.goto();
+ await expect(shell.nav.item('home')).toBeVisible();
+ await expect(shell.nav.item('ai-assistant')).toHaveCount(0);
+ });
+
+ test('TC-35 a logged-out visitor to /dashboard lands on /login', async ({
+ guest,
+ }) => {
+ await guest.goto('/dashboard');
+ await expect.poll(() => guest.pathname()).toBe('/login');
+ await expect(guest.emailInput()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/app-shell/shortcuts.spec.ts b/tests/e2e/tests/app-shell/shortcuts.spec.ts
new file mode 100644
index 0000000000..af1cbdb119
--- /dev/null
+++ b/tests/e2e/tests/app-shell/shortcuts.spec.ts
@@ -0,0 +1,55 @@
+import { expect, NAV_SHORTCUTS, test } from '../../drivers/shell';
+
+test.describe('app shell — keyboard shortcuts', () => {
+ for (const { combo, from, path, tab } of NAV_SHORTCUTS) {
+ test(`TC-01 ${combo} opens ${path}`, async ({ shell }) => {
+ await shell.goto(from);
+ await expect(shell.nav.item('home')).toBeVisible();
+
+ await shell.keys.press(combo);
+
+ await expect.poll(() => shell.pathname()).toBe(path);
+ expect(shell.url().searchParams.get('tab')).toBe(tab);
+ });
+ }
+
+ test('TC-02 shortcuts are ignored while typing', async ({ shell }) => {
+ await shell.goto('/dashboard');
+ const search = shell.dashboardsSearch();
+ await search.click();
+ await shell.typeShifted('a');
+
+ await expect(search).toHaveValue('A');
+ expect(shell.pathname()).toBe('/dashboard');
+ });
+});
+
+test.describe('app shell — sidebar toggle shortcut', () => {
+ // `sidenav_pinned` is per user and settings/account.spec.ts toggles it on
+ // admin2 in parallel, so this runs as the editor, which nothing else pins.
+ test.use({ as: 'editor' });
+
+ test.afterEach(async ({ shell }) => {
+ await shell.users.setPreference('sidenav_pinned', true);
+ });
+
+ test('TC-03 shift+b toggles the sidebar pin and persists it', async ({
+ shell,
+ }) => {
+ await shell.home.goto();
+ // An unpinned nav expands on hover, which would mask the collapse.
+ await shell.parkPointer();
+ expect(await shell.nav.isCollapsed()).toBe(false);
+
+ await shell.nav.toggleWithShortcut();
+ await expect.poll(() => shell.nav.isCollapsed()).toBe(true);
+
+ await shell.nav.reloadSettled();
+ await expect(shell.nav.root()).toBeVisible();
+ await shell.parkPointer();
+ await expect.poll(() => shell.nav.isCollapsed()).toBe(true);
+
+ await shell.nav.toggleWithShortcut();
+ await expect.poll(() => shell.nav.isCollapsed()).toBe(false);
+ });
+});
diff --git a/tests/e2e/tests/app-shell/sidenav.spec.ts b/tests/e2e/tests/app-shell/sidenav.spec.ts
new file mode 100644
index 0000000000..e9aa540edb
--- /dev/null
+++ b/tests/e2e/tests/app-shell/sidenav.spec.ts
@@ -0,0 +1,107 @@
+import { ADMIN, expect, NAV_ITEMS, test } from '../../drivers/shell';
+
+test.describe('app shell — side nav', () => {
+ for (const { key, path } of NAV_ITEMS) {
+ test(`TC-01 the ${key} nav item opens ${path}`, async ({ shell }) => {
+ await shell.home.goto();
+ await shell.nav.click(key);
+ await expect.poll(() => shell.pathname()).toBe(path);
+ });
+ }
+
+ test('TC-04 the help menu invite entry opens the invite dialog', async ({
+ shell,
+ }) => {
+ await shell.home.goto();
+ await shell.helpMenu.open();
+ await shell.helpMenu.item('invite-collaborators').click();
+
+ await expect.poll(() => shell.pathname()).toBe('/settings/members');
+ expect(shell.url().searchParams.get('invite')).toBe('true');
+ await expect(shell.inviteDialog()).toBeVisible();
+ });
+
+ test('TC-05 the help menu documentation entry opens the docs', async ({
+ shell,
+ }) => {
+ await shell.home.goto();
+ await shell.helpMenu.open();
+ expect(await shell.helpMenu.openExternal('documentation')).toBe(
+ 'https://signoz.io/docs',
+ );
+ });
+
+ test('TC-06 the user menu names the user and routes to each settings page', async ({
+ shell,
+ }) => {
+ const destinations = [
+ { item: 'workspace-settings-nav-item', path: '/settings' },
+ { item: 'account-settings-nav-item', path: '/settings/my-settings' },
+ { item: 'keyboard-shortcuts-nav-item', path: '/settings/shortcuts' },
+ ];
+
+ await shell.home.goto();
+ await shell.userMenu.open();
+ await expect(shell.userMenu.item('logged-in-as-nav-item')).toContainText(
+ ADMIN.email,
+ );
+ // A cloud license manages billing, not a license key.
+ await expect(shell.userMenu.item('manage-license-nav-item')).toHaveCount(0);
+
+ for (const { item, path } of destinations) {
+ await shell.home.goto();
+ await shell.userMenu.open();
+ await shell.userMenu.item(item).click();
+ await expect.poll(() => shell.pathname()).toBe(path);
+ }
+ });
+});
+
+test.describe('app shell — side nav shortcuts', () => {
+ // `nav_shortcuts` is a per-user preference.
+ test.use({ as: 'admin2' });
+
+ test.afterEach(async ({ shell }) => {
+ await shell.users.setPreference('nav_shortcuts', []);
+ });
+
+ test('TC-02 pinning a More item moves it to Shortcuts and persists', async ({
+ shell,
+ }) => {
+ await shell.home.goto();
+ await expect(shell.nav.item('exceptions')).toBeVisible();
+ expect(await shell.nav.moreKeys()).toContain('exceptions');
+
+ await shell.nav.pin('exceptions');
+ await expect.poll(() => shell.nav.shortcutKeys()).toContain('exceptions');
+ expect(await shell.nav.moreKeys()).not.toContain('exceptions');
+
+ await shell.reload();
+ await expect(shell.nav.item('exceptions')).toBeVisible();
+ await expect.poll(() => shell.nav.shortcutKeys()).toContain('exceptions');
+ expect(await shell.nav.moreKeys()).not.toContain('exceptions');
+
+ await shell.nav.unpin('exceptions');
+ await expect.poll(() => shell.nav.moreKeys()).toContain('exceptions');
+ expect(await shell.nav.shortcutKeys()).not.toContain('exceptions');
+ });
+
+ test('TC-03 Manage Shortcuts saves a new order', async ({ shell }) => {
+ await shell.home.goto();
+ await expect(shell.nav.item('services')).toBeVisible();
+ const before = await shell.nav.shortcutKeys();
+ expect(before.length).toBeGreaterThan(1);
+ const [first, second] = before;
+
+ await shell.nav.openManageShortcuts();
+ await shell.nav.dragShortcut(second, first);
+ const sent = await shell.nav.saveShortcuts();
+
+ const expected = [second, first, ...before.slice(2)];
+ expect(sent).toEqual(expected);
+
+ await shell.reload();
+ await expect(shell.nav.item(second)).toBeVisible();
+ await expect.poll(() => shell.nav.shortcutKeys()).toEqual(expected);
+ });
+});
diff --git a/tests/e2e/tests/app-shell/time-picker.spec.ts b/tests/e2e/tests/app-shell/time-picker.spec.ts
new file mode 100644
index 0000000000..00404357ec
--- /dev/null
+++ b/tests/e2e/tests/app-shell/time-picker.spec.ts
@@ -0,0 +1,57 @@
+import { expect, test } from '../../drivers/shell';
+
+test.describe('app shell — time picker', () => {
+ // A fixed zone makes the displayed offset deterministic.
+ test.use({ timezoneId: 'Asia/Kolkata' });
+
+ test('TC-01 a preset rewrites the URL and the services query window', async ({
+ shell,
+ }) => {
+ await shell.goto('/services');
+ await expect(shell.timePicker.input()).toBeVisible();
+
+ const servicesCall = shell.nextServicesWindow(15);
+ await shell.timePicker.pickPreset('15m');
+ await servicesCall;
+
+ expect(shell.timePicker.urlParams()).toEqual({
+ relativeTime: '15m',
+ startTime: undefined,
+ endTime: undefined,
+ });
+ await expect(shell.timePicker.input()).toHaveValue('Last 15 minutes');
+ });
+
+ test('TC-02 a typed shorthand range applies', async ({ shell }) => {
+ await shell.goto('/services');
+ await expect(shell.timePicker.input()).toBeVisible();
+
+ const servicesCall = shell.nextServicesWindow(120);
+ await shell.timePicker.typeRange('2h');
+ await servicesCall;
+
+ await expect.poll(() => shell.timePicker.urlParams().relativeTime).toBe('2h');
+ await expect(shell.timePicker.input()).toHaveValue('Last 2 hours');
+ });
+
+ test('TC-03 a timezone picked in the picker changes the offset and persists', async ({
+ shell,
+ }) => {
+ await shell.goto('/services');
+ await expect(shell.timezoneBadge()).toHaveText('UTC + 5:30');
+
+ await shell.timePicker.pickTimezone('UTC', 'UTC');
+ await expect(shell.timezoneBadge()).toHaveText('UTC');
+ expect(await shell.storedTimezone()).not.toBeNull();
+
+ await shell.reload();
+ await expect(shell.timezoneBadge()).toHaveText('UTC');
+
+ await shell.goto('/settings/my-settings');
+ await expect(shell.timezoneOverrideNote()).toBeVisible();
+ await shell.clearTimezoneOverride();
+
+ await shell.goto('/services');
+ await expect(shell.timezoneBadge()).toHaveText('UTC + 5:30');
+ });
+});
diff --git a/tests/e2e/tests/auth/invite.spec.ts b/tests/e2e/tests/auth/invite.spec.ts
new file mode 100644
index 0000000000..75f629ae70
--- /dev/null
+++ b/tests/e2e/tests/auth/invite.spec.ts
@@ -0,0 +1,50 @@
+import { E2E_PASSWORD, expect, test } from '../../drivers/auth-flows';
+
+// The admin half runs on the kit's admin page through `settings`; the invitee
+// half runs on a guest context through `authFlows`.
+
+test.describe('auth — invite', () => {
+ test('TC-01 an invited viewer sets a password, signs in, sees the viewer UI and cannot reuse the link', async ({
+ settings,
+ authFlows,
+ }, testInfo) => {
+ const email = `e2e-invite-w${testInfo.workerIndex}-${Date.now()}@signoz.test`;
+ try {
+ await settings.members.goto();
+ await settings.members.openInvite();
+ await settings.members.invite([{ email, role: 'signoz-viewer' }]);
+
+ await settings.members.search(email);
+ await expect(settings.members.row(email)).toContainText('INVITED');
+
+ await settings.members.openMember(email);
+ const link = await settings.members.generateLink();
+ expect(link).toMatch(/\/password-reset\?token=/);
+
+ await authFlows.goto(link);
+ await authFlows.setNewPassword(E2E_PASSWORD);
+
+ await authFlows.login({ email, password: E2E_PASSWORD });
+ await authFlows.openUserMenu();
+ await expect(authFlows.loggedInAs()).toContainText(email);
+
+ await authFlows.goto('/dashboard');
+ await expect(authFlows.newDashboardButton()).toHaveAttribute(
+ 'data-denied-permissions',
+ /.+/,
+ );
+
+ await settings.members.goto();
+ await settings.members.search(email);
+ await expect(settings.members.row(email)).toContainText('ACTIVE');
+
+ // The link is single use. A signed-in visitor is bounced off
+ // /password-reset, so sign the invitee out first.
+ await authFlows.signOut();
+ await authFlows.goto(link);
+ await expect(authFlows.tokenError()).toBeVisible();
+ } finally {
+ await settings.users.removeByEmail(email);
+ }
+ });
+});
diff --git a/tests/e2e/tests/auth/login.spec.ts b/tests/e2e/tests/auth/login.spec.ts
new file mode 100644
index 0000000000..5f12f4aa02
--- /dev/null
+++ b/tests/e2e/tests/auth/login.spec.ts
@@ -0,0 +1,79 @@
+import { ADMIN, expect, test } from '../../drivers/auth-flows';
+
+// Every test here signs in on a fresh guest context, which mints a new session
+// and leaves the worker's cached admin session alone.
+
+test.describe('auth — login', () => {
+ test('TC-01 the admin signs in with email and password', async ({
+ authFlows,
+ }) => {
+ // No `?password=Y`: the password step has to be offered on its own.
+ await authFlows.gotoLogin();
+ await authFlows.enterEmail(ADMIN.email);
+ await authFlows.enterPassword(ADMIN.password);
+ await authFlows.submitPassword();
+
+ await expect.poll(() => authFlows.pathname()).not.toMatch(/^\/login/);
+ await expect(authFlows.settingsNavItem()).toBeVisible();
+ });
+
+ test('TC-02 a wrong password shows the error and stays on /login', async ({
+ authFlows,
+ }) => {
+ await authFlows.gotoLogin();
+ await authFlows.enterEmail(ADMIN.email);
+ await authFlows.enterPassword(`${ADMIN.password}-wrong`);
+ await authFlows.submitPassword();
+
+ await expect(authFlows.authError()).toBeVisible();
+ expect(authFlows.pathname()).toBe('/login');
+ });
+
+ test('TC-03 a deep link survives the login round trip', async ({
+ authFlows,
+ }) => {
+ await authFlows.goto('/alerts?tab=Channels');
+ await authFlows.expectOnLogin();
+
+ await authFlows.login(ADMIN);
+
+ // The guard saves the pathname only, so the query does not survive.
+ await expect.poll(() => authFlows.pathname()).toBe('/alerts');
+ });
+
+ test('TC-04 "Forgot password?" carries the email to the reset request', async ({
+ authFlows,
+ throwaway,
+ }) => {
+ // The bootstrap admin is the root user, which cannot reset its password.
+ const { email } = throwaway.user;
+ await authFlows.gotoLogin();
+ await authFlows.enterEmail(email);
+ await authFlows.forgotPasswordLink().click();
+
+ await expect.poll(() => authFlows.pathname()).toBe('/forgot-password');
+ await expect(authFlows.emailInput()).toBeDisabled();
+ await expect(authFlows.emailInput()).toHaveValue(email);
+
+ expect(await authFlows.submitForgot()).toBe(204);
+ await expect(authFlows.forgotSuccess()).toBeVisible();
+
+ await authFlows.backToLogin();
+ });
+
+ // Revocation is checked headless, in `passwordauthn/09_tokenizer.py`: here a
+ // request the logout fires alongside it can re-cache the token.
+ test('TC-05 signing out clears the session and returns to login', async ({
+ authFlows,
+ throwaway,
+ }) => {
+ await authFlows.login(throwaway.user);
+ expect(await authFlows.storedToken()).not.toBeNull();
+
+ await authFlows.signOut();
+ expect(await authFlows.storedToken()).toBeNull();
+
+ await authFlows.goto('/home');
+ await authFlows.expectOnLogin();
+ });
+});
diff --git a/tests/e2e/tests/dashboards/editor/visualization.spec.ts b/tests/e2e/tests/dashboards/editor/visualization.spec.ts
new file mode 100644
index 0000000000..91f0b1108b
--- /dev/null
+++ b/tests/e2e/tests/dashboards/editor/visualization.spec.ts
@@ -0,0 +1,53 @@
+import {
+ expect,
+ PanelKind,
+ Section,
+ SINGLE_PANEL_ID,
+ singlePanelDashboard,
+ test,
+} from '../../../drivers/panel-config';
+
+// Scope: visualization settings that only some kinds declare, saved from the
+// editor and read back from the stored spec.
+
+test.describe('Dashboards — editor visualization settings', () => {
+ test('TC-01 percent stacking on an Area panel persists', async ({
+ dashboards,
+ editor,
+ config,
+ }) => {
+ const id = await dashboards.seedAndEdit(
+ singlePanelDashboard({ kind: PanelKind.AreaChart }),
+ SINGLE_PANEL_ID,
+ );
+
+ await editor.section.expand(Section.visualization);
+ await editor.setTile('stack-mode', 'percent');
+ await expect(editor.tileInput('stack-mode', 'percent')).toBeChecked();
+ await editor.save();
+
+ expect((await config.saved(id)).plugin).toMatchObject({
+ visualization: { stack: 'percent' },
+ });
+ });
+
+ test('TC-02 stacked series on a Bar panel persist', async ({
+ dashboards,
+ editor,
+ config,
+ }) => {
+ const id = await dashboards.seedAndEdit(
+ singlePanelDashboard({ kind: PanelKind.BarChart }),
+ SINGLE_PANEL_ID,
+ );
+
+ await editor.section.expand(Section.visualization);
+ await editor.setTile('stacked-bar-chart', 'stacked');
+ await expect(editor.tileInput('stacked-bar-chart', 'stacked')).toBeChecked();
+ await editor.save();
+
+ expect((await config.saved(id)).plugin).toMatchObject({
+ visualization: { stackedBarChart: true },
+ });
+ });
+});
diff --git a/tests/e2e/tests/dashboards/list/row-actions.spec.ts b/tests/e2e/tests/dashboards/list/row-actions.spec.ts
index df653efc76..0249263cbc 100644
--- a/tests/e2e/tests/dashboards/list/row-actions.spec.ts
+++ b/tests/e2e/tests/dashboards/list/row-actions.spec.ts
@@ -110,4 +110,63 @@ test.describe('Dashboards — list row actions', () => {
await expect(dashboardList.rowTitle(name)).toBeVisible();
expect((await dashboards.get(id)).id).toBe(id);
});
+
+ test('TC-07 Rename from the row menu persists and stays on the list', async ({
+ authedPage: page,
+ dashboards,
+ dashboardList,
+ }) => {
+ const name = uniqueName('row-rename');
+ const renamed = uniqueName('row-renamed');
+ const id = await dashboards.seed(listDashboard(name));
+ await dashboardList.open(name);
+
+ await dashboardList.renameRow(name, renamed);
+
+ await expect(page).toHaveURL(LIST_URL);
+ await expect
+ .poll(async () => (await dashboards.get(id)).spec.display.name)
+ .toBe(renamed);
+ await dashboardList.open(renamed);
+ await expect(dashboardList.rowTitle(renamed)).toBeVisible();
+ });
+
+ test('TC-08 Edit tags from the row menu persists and stays on the list', async ({
+ authedPage: page,
+ dashboards,
+ dashboardList,
+ }) => {
+ const name = uniqueName('row-tags');
+ const id = await dashboards.seed(listDashboard(name));
+ await dashboardList.open(name);
+
+ await dashboardList.editRowTags(name, ['team:e2e', 'env:test']);
+
+ await expect(page).toHaveURL(LIST_URL);
+ await expect
+ .poll(async () => (await dashboards.get(id)).tags)
+ .toEqual(
+ expect.arrayContaining([
+ { key: 'team', value: 'e2e' },
+ { key: 'env', value: 'test' },
+ ]),
+ );
+ });
+
+ test('TC-09 Duplicate clones the dashboard and opens the copy', async ({
+ authedPage: page,
+ dashboards,
+ dashboardList,
+ }) => {
+ const name = uniqueName('row-duplicate');
+ await dashboards.seed(listDashboard(name));
+ await dashboardList.open(name);
+
+ const copyId = await dashboardList.duplicateRow(name);
+
+ await expect(page).toHaveURL(PATH.onDashboard(copyId));
+ expect((await dashboards.get(copyId)).spec.display.name).toContain(name);
+ await dashboardList.open(name);
+ await expect(dashboardList.rows()).toHaveCount(2);
+ });
});
diff --git a/tests/e2e/tests/dashboards/page/permissions.spec.ts b/tests/e2e/tests/dashboards/page/permissions.spec.ts
new file mode 100644
index 0000000000..766831f6f4
--- /dev/null
+++ b/tests/e2e/tests/dashboards/page/permissions.spec.ts
@@ -0,0 +1,68 @@
+import {
+ COMPACT_PANELS,
+ compactDashboard,
+ DashboardAction,
+ expect,
+ PanelAction,
+ test,
+} from '../../../drivers/dashboard-page';
+
+// What a viewer is offered on a dashboard someone else can edit. The gating
+// logic is jest (`*.authz.test.tsx`); this checks the real authz endpoint
+// denies a real viewer and the menus carry its reason.
+
+const DENIED = /is not authorized to perform/;
+
+test.describe('Dashboards — viewer permissions', () => {
+ test.describe.configure({ timeout: 60_000 });
+
+ test.use({ as: 'viewer' });
+
+ test('TC-01 the Actions rows that write are disabled with a reason', async ({
+ dashboards,
+ dashboardPage,
+ panels,
+ }) => {
+ const id = await dashboards.seedAsAdmin(compactDashboard());
+ await dashboards.open(id);
+
+ await dashboardPage.actions.open();
+
+ // A row still checking its permission is disabled too, so the reason is
+ // what proves the denial.
+ for (const action of [
+ DashboardAction.rename,
+ DashboardAction.clone,
+ DashboardAction.lock,
+ DashboardAction.newSection,
+ DashboardAction.delete,
+ ]) {
+ const row = dashboardPage.actions.item(action);
+ await expect(row).toBeDisabled();
+ await expect(await panels.tooltip.reasonFor(row)).toHaveText(DENIED);
+ }
+ await expect(
+ dashboardPage.actions.item(DashboardAction.fullScreen),
+ ).toBeEnabled();
+ });
+
+ test('TC-02 the panel menu disables Edit and Delete with a reason, and View still opens', async ({
+ dashboards,
+ panels,
+ }) => {
+ const id = await dashboards.seedAsAdmin(compactDashboard());
+ await dashboards.open(id);
+ const { actions } = panels.panel(COMPACT_PANELS.timeseries);
+
+ await actions.open();
+
+ for (const label of [PanelAction.edit, PanelAction.delete]) {
+ const item = actions.item(label);
+ await expect(item).toBeDisabled();
+ await expect(await panels.tooltip.reasonFor(item)).toHaveText(DENIED);
+ }
+
+ await actions.item(PanelAction.view).click();
+ await expect(panels.view.content()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/dashboards/page/sections.spec.ts b/tests/e2e/tests/dashboards/page/sections.spec.ts
index 22514ad069..7a362ab85e 100644
--- a/tests/e2e/tests/dashboards/page/sections.spec.ts
+++ b/tests/e2e/tests/dashboards/page/sections.spec.ts
@@ -102,4 +102,45 @@ test.describe('Dashboards — sections', () => {
.poll(async () => (await dashboards.get(id)).spec.layouts.length)
.toBe(2);
});
+
+ test('TC-06 cloning a section adds a copy with its own panels', async ({
+ dashboards,
+ dashboardPage,
+ }) => {
+ const id = await dashboards.seedAndOpen(compactDashboard());
+ const charts = dashboardPage.section('Charts');
+
+ await charts.openMenu();
+ await charts.menuItem(SectionAction.clone).click();
+
+ await expect(dashboardPage.section('Charts (Copy)').toggle()).toBeVisible();
+ await expect
+ .poll(async () => {
+ const { spec } = await dashboards.get(id);
+ return {
+ titles: spec.layouts.map((layout) => layout.spec.display.title).sort(),
+ panels: Object.keys(spec.panels).length,
+ };
+ })
+ .toEqual({ titles: ['Charts', 'Charts (Copy)', 'Tabular'], panels: 4 });
+ });
+
+ test('TC-07 deleting a section removes its panels from the spec', async ({
+ dashboards,
+ dashboardPage,
+ }) => {
+ const id = await dashboards.seedAndOpen(compactDashboard());
+
+ await dashboardPage.section('Tabular').delete();
+
+ await expect
+ .poll(async () => {
+ const { spec } = await dashboards.get(id);
+ return {
+ titles: spec.layouts.map((layout) => layout.spec.display.title),
+ panels: Object.keys(spec.panels),
+ };
+ })
+ .toEqual({ titles: ['Charts'], panels: [COMPACT_PANELS.timeseries] });
+ });
});
diff --git a/tests/e2e/tests/exceptions/list.spec.ts b/tests/e2e/tests/exceptions/list.spec.ts
new file mode 100644
index 0000000000..2fd9c2ef6b
--- /dev/null
+++ b/tests/e2e/tests/exceptions/list.spec.ts
@@ -0,0 +1,92 @@
+import { expect, test } from '../../drivers/exceptions';
+
+const HEADERS = [
+ 'Exception Type',
+ 'Error Message',
+ 'Count',
+ 'Last Seen',
+ 'First Seen',
+ 'Application',
+];
+
+test.describe('Exceptions, list and detail', () => {
+ test('TC-01 exceptions page renders with no console errors', async ({
+ exceptions,
+ noise,
+ }) => {
+ await exceptions.gotoList();
+
+ await expect(exceptions.tab('All Exceptions')).toBeVisible();
+ await expect(async () => {
+ expect(await exceptions.headers()).toEqual(HEADERS);
+ }).toPass();
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a seeded exception group is listed with its count', async ({
+ exceptions,
+ exceptionSeed,
+ }) => {
+ const { timeout } = exceptionSeed.groups;
+ await exceptions.gotoList({ serviceName: exceptionSeed.service });
+ await exceptions.waitForRow(timeout.type);
+
+ await expect(await exceptions.cell(timeout.type, 'Count')).toHaveText(
+ String(timeout.count),
+ );
+ await expect(await exceptions.cell(timeout.type, 'Application')).toHaveText(
+ exceptionSeed.service,
+ );
+ await expect(
+ await exceptions.cell(timeout.type, 'Error Message'),
+ ).toContainText(exceptionSeed.stamp);
+ });
+
+ test('TC-03 application column search narrows to the seeded service', async ({
+ exceptions,
+ exceptionSeed,
+ }) => {
+ const { timeout, value } = exceptionSeed.groups;
+ await exceptions.gotoList({ serviceName: exceptionSeed.service });
+ await exceptions.waitForRow(timeout.type);
+ await exceptions.gotoList();
+
+ await exceptions.filterByService(exceptionSeed.service);
+
+ await expect(exceptions.row(timeout.type)).toBeVisible();
+ await expect(exceptions.row(value.type)).toBeVisible();
+ expect(new Set(await exceptions.applications())).toEqual(
+ new Set([exceptionSeed.service]),
+ );
+ });
+
+ test('TC-04 exception detail shows the event, stack and trace link', async ({
+ exceptions,
+ exceptionSeed,
+ }) => {
+ const { timeout } = exceptionSeed.groups;
+ const latest = timeout.spans[timeout.spans.length - 1];
+ await exceptions.gotoList({ serviceName: exceptionSeed.service });
+ await exceptions.waitForRow(timeout.type);
+
+ await exceptions.openRow(timeout.type);
+ const { detail } = exceptions;
+ await expect(detail.type()).toHaveText(timeout.type);
+ await expect(detail.message()).toHaveText(timeout.message);
+ await expect(detail.stacktrace()).toContainText(exceptionSeed.frame);
+ await expect(detail.attributes()).toContainText(exceptionSeed.service);
+
+ const latestEvent = (await detail.eventId().innerText()).trim();
+ await expect(detail.newerButton()).toBeDisabled();
+ await detail.older();
+ await expect(detail.eventId()).not.toHaveText(latestEvent);
+ await expect(detail.olderButton()).toBeDisabled();
+ await detail.newer();
+ await expect(detail.eventId()).toHaveText(latestEvent);
+
+ const trace = await detail.viewTrace();
+ expect(trace.pathname).toBe(`/trace/${latest.trace_id}`);
+ expect(trace.searchParams.get('spanId')).toBe(latest.span_id);
+ });
+});
diff --git a/tests/e2e/tests/home/home.spec.ts b/tests/e2e/tests/home/home.spec.ts
new file mode 100644
index 0000000000..2badea99c5
--- /dev/null
+++ b/tests/e2e/tests/home/home.spec.ts
@@ -0,0 +1,94 @@
+import { expect, HOME_PROBE, test } from '../../drivers/shell';
+
+// The checklist flags are per-user preferences, so none of this runs as the
+// shared bootstrap admin.
+test.use({ as: 'admin2' });
+
+test.describe('home', () => {
+ test.beforeEach(async ({ shell }) => {
+ await shell.home.resetChecklistPrefs();
+ });
+
+ test('TC-01 the data-received home renders its widgets against the real backend', async ({
+ shell,
+ noise,
+ }, testInfo) => {
+ const service = `e2e-home-svc-w${testInfo.workerIndex}-${Date.now()}`;
+ await shell.seedSlowService(service);
+ await shell.visit(HOME_PROBE);
+
+ await expect(shell.home.sectionEntry('services', service)).toBeVisible();
+ await expect(shell.home.checklist()).toBeVisible();
+ await expect(shell.errorBoundary()).toHaveCount(0);
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a seeded alert rule and dashboard appear in their widgets', async ({
+ shell,
+ }, testInfo) => {
+ const stamp = `w${testInfo.workerIndex}-${Date.now()}`;
+ const title = `e2e-home-dash-${stamp}`;
+ const rule = await shell.seedAlertRule(`e2e-home-rule-${stamp}`);
+ const dashboard = await shell.seedDashboard(title);
+ try {
+ await shell.home.goto();
+
+ // Both widgets show the five most recently updated entries, and sibling
+ // workers keep creating more, so the fresh seeds are only guaranteed to
+ // be listed right after they are made.
+ await expect(shell.home.section('dashboards')).toContainText(title);
+ await expect(shell.home.section('alerts')).toContainText(rule.ruleName);
+ } finally {
+ await shell.removeDashboard(dashboard.id);
+ await shell.removeAlertRule(rule);
+ }
+ });
+
+ test('TC-03 skipping a checklist step persists across a reload', async ({
+ shell,
+ }) => {
+ await shell.home.goto();
+ await expect(shell.home.checklist()).toBeVisible();
+ const steps = await shell.home.skippableSteps();
+ // Alerts, views and dashboards appear and vanish as sibling specs create
+ // and delete them, so only ingestion steps are safe to pick.
+ const step = steps.find((id) =>
+ id.startsWith('SEND_'),
+ ) as (typeof steps)[number];
+ // An ingestion step completes itself once its data exists, and the
+ // shared stack may already hold all of it.
+ test.skip(!step, 'every ingestion checklist step is already complete');
+
+ await shell.home.skip(step);
+ await expect(shell.home.checklistItem(step)).toHaveClass(/skipped/);
+ await expect(shell.home.skipButton(step)).toHaveCount(0);
+
+ await shell.reload();
+ await expect(shell.home.checklistItem(step)).toHaveClass(/skipped/);
+ await expect(shell.home.skipButton(step)).toHaveCount(0);
+ });
+
+ test('TC-04 "I\'ll do this later" hides the checklist until reopened', async ({
+ shell,
+ }) => {
+ await shell.home.goto();
+ await expect(shell.home.checklist()).toBeVisible();
+
+ await shell.home.doLater();
+ await expect(shell.home.checklist()).toHaveCount(0);
+ await expect(shell.home.checklistButton()).toBeVisible();
+
+ await shell.reload();
+ await expect(shell.home.checklistButton()).toBeVisible();
+ await expect(shell.home.checklist()).toHaveCount(0);
+
+ await shell.home.reopenChecklist();
+ });
+
+ test('TC-05 an explorer card opens its explorer', async ({ shell }) => {
+ await shell.home.goto();
+ await shell.home.explorerCard('Open Logs Explorer').click();
+ await expect.poll(() => shell.pathname()).toBe('/logs/logs-explorer');
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/drawer.spec.ts b/tests/e2e/tests/infra-monitoring/drawer.spec.ts
new file mode 100644
index 0000000000..1dba466df1
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/drawer.spec.ts
@@ -0,0 +1,154 @@
+import {
+ BASE_ENTITY,
+ DRAWER_TAB,
+ entityByKey,
+ EXPLORER_LINK,
+ expect,
+ seedDataset,
+ test,
+} from '../../drivers/infra';
+
+// The entity-details drawer: how it opens, what the URL says about it, and the
+// two things only a browser can show — its own time range, and the cross-page
+// links out of it.
+
+const VOLUMES = entityByKey('volumes');
+
+test.describe('infra monitoring — drawer', () => {
+ test('TC-01 a row click opens the drawer and writes selectedItem', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ await infra.list.table(BASE_ENTITY).waitForRows();
+
+ await infra.drawer.open(BASE_ENTITY.seed.sampleItemKey);
+ await infra.drawer.expectBodyReady();
+
+ await infra.list.expectUrlParams({
+ selectedItem: BASE_ENTITY.seed.sampleItemKey,
+ });
+ await expect(infra.drawer.title()).toContainText(BASE_ENTITY.seed.sampleName);
+
+ await infra.drawer.close();
+ await infra.list.expectUrlParams({ selectedItem: null });
+ });
+
+ test('TC-02 a deep link opens the drawer without the list being touched', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.goto(
+ BASE_ENTITY,
+ infra.drawer.selectedItemParams(BASE_ENTITY),
+ );
+
+ await infra.drawer.expectBodyReady();
+ await expect(infra.drawer.title()).toContainText(BASE_ENTITY.seed.sampleName);
+ });
+
+ test('TC-03 the drawer opens on Overview and the tab bar writes view', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.goto(
+ BASE_ENTITY,
+ infra.drawer.selectedItemParams(BASE_ENTITY),
+ );
+ await infra.drawer.expectBodyReady();
+
+ // The bar is the authority on what an entity offers; the registry only
+ // records whether it has one at all.
+ const views = await infra.drawer.renderedViews();
+ expect(views[0]).toBe(DRAWER_TAB.overview);
+ expect(views).toContain(DRAWER_TAB.metrics);
+ expect(infra.drawer.viewFromUrl()).toBeNull();
+
+ await infra.drawer.switchTab(DRAWER_TAB.logs);
+ await infra.list.expectUrlParams({ view: DRAWER_TAB.logs });
+
+ await infra.drawer.switchTab(DRAWER_TAB.metrics);
+ await infra.list.expectUrlParams({ view: DRAWER_TAB.metrics });
+ });
+
+ test('TC-04 volumes has no tab bar but still renders the metrics body', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, VOLUMES.seed.primary);
+ await infra.list.goto(VOLUMES, infra.drawer.selectedItemParams(VOLUMES));
+
+ // The body wait is what makes this absence assertion mean anything: before
+ // it, the tab bar has simply not mounted yet and the check passes for the
+ // wrong reason.
+ await infra.drawer.expectBodyReady();
+ await expect(infra.drawer.tabBar()).toHaveCount(0);
+ await expect(infra.drawer.timePicker()).toBeVisible();
+ });
+
+ test('TC-05 the drawer keeps its own time range and can reset to the list', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.goto(
+ BASE_ENTITY,
+ infra.drawer.selectedItemParams(BASE_ENTITY),
+ );
+ await infra.drawer.expectBodyReady();
+
+ expect(infra.drawer.timeParams().relative).toBeNull();
+ const listRange = new URL(page.url()).searchParams.get('relativeTime');
+
+ await infra.drawer.setTime('Last 1 hour');
+ expect(infra.drawer.timeParams().relative).not.toBeNull();
+ // The list's own range is a different set of params and must not move.
+ await infra.list.expectUrlParams({ relativeTime: listRange });
+
+ await infra.drawer.resetTimeToList();
+ expect(infra.drawer.timeParams().relative).toBeNull();
+ });
+
+ test('TC-06 the compass opens the logs explorer in a new tab and keeps the drawer', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.goto(
+ BASE_ENTITY,
+ infra.drawer.selectedItemParams(BASE_ENTITY),
+ );
+ await infra.drawer.expectBodyReady();
+ await infra.drawer.switchTab(DRAWER_TAB.logs);
+
+ const explorer = await infra.drawer.openExplorer(EXPLORER_LINK.logs);
+ expect(new URL(explorer.url()).pathname).toMatch(/logs-explorer/);
+ expect(
+ new URL(explorer.url()).searchParams.get('compositeQuery'),
+ ).toBeTruthy();
+ await explorer.close();
+
+ await expect(infra.drawer.panel()).toBeVisible();
+ });
+
+ test('TC-07 a drawer opened in a new tab carries its identity', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ await infra.list.table(BASE_ENTITY).waitForRows();
+
+ const opened = await infra.drawer.openInNewTab(
+ BASE_ENTITY.seed.sampleItemKey,
+ );
+
+ expect(new URL(opened.url()).searchParams.get('selectedItem')).toBe(
+ BASE_ENTITY.seed.sampleItemKey,
+ );
+ await opened.close();
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/entities.spec.ts b/tests/e2e/tests/infra-monitoring/entities.spec.ts
new file mode 100644
index 0000000000..19e2c9cec1
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/entities.spec.ts
@@ -0,0 +1,91 @@
+import {
+ DRAWER_TAB,
+ entityByKey,
+ expect,
+ seedDataset,
+ test,
+} from '../../drivers/infra';
+
+// What is genuinely per-entity and genuinely needs a browser.
+//
+// Value accuracy, ownership roll-ups, name distinctness across namespaces and
+// latest-wins state are asserted per entity, headless, by the integration suite
+// — `test_<entity>_accuracy`, `test_<entity>_base_filter_drops_non_<entity>_pods`,
+// `same_name_across_ns_and_clusters`, `test_pods_status_latest_wins`. Repeating
+// them through a rendered table adds a ClickHouse round trip and no signal.
+//
+// What is left is the handful of surfaces that exist on some entities and not
+// others: the hosts route and its status filter, the counts cards that navigate,
+// and the Pod Metrics tab.
+
+const HOSTS = entityByKey('hosts');
+const CLUSTERS = entityByKey('clusters');
+const DEPLOYMENTS = entityByKey('deployments');
+
+test.describe('infra monitoring — per-entity surfaces', () => {
+ test('TC-01 hosts renders on its own route, with no category rail', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, HOSTS.seed.primary);
+ await infra.list.gotoScoped(HOSTS, facts.names);
+ const table = infra.list.table(HOSTS);
+ await table.waitForRows();
+
+ expect(new URL(page.url()).pathname).toBe(HOSTS.route);
+ await expect(infra.list.categoryTabs()).toHaveCount(0);
+ expect(await table.rowKeys()).toEqual(
+ expect.arrayContaining([HOSTS.seed.sampleItemKey]),
+ );
+ });
+
+ test('TC-02 the hosts status filter narrows the list', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, HOSTS.seed.primary);
+ await infra.list.gotoScoped(HOSTS, facts.names);
+ await infra.list.table(HOSTS).waitForRows();
+
+ // The toggle group is hosts-only; every other entity filters through the
+ // expression editor alone.
+ await infra.list.statusFilter('inactive').click();
+
+ await expect(async () => {
+ expect(new URL(page.url()).search).toContain('inactive');
+ }).toPass();
+ });
+
+ test('TC-03 a counts card navigates to the entity it counts', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, CLUSTERS.seed.primary);
+ await infra.list.goto(CLUSTERS, infra.drawer.selectedItemParams(CLUSTERS));
+ await infra.drawer.expectBodyReady();
+
+ const card = infra.drawer.countCard('Nodes');
+ await expect(card).toBeVisible();
+ await infra.drawer.countCardNavLink('Nodes').click();
+
+ // The card is a link into the nodes list, scoped to this cluster.
+ await expect(page).toHaveURL(/category=nodes/);
+ });
+
+ test('TC-04 the Pod Metrics tab renders for the entities that have it', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, DEPLOYMENTS.seed.primary);
+ await infra.list.goto(
+ DEPLOYMENTS,
+ infra.drawer.selectedItemParams(DEPLOYMENTS),
+ );
+ await infra.drawer.expectBodyReady();
+
+ expect(await infra.drawer.renderedViews()).toContain(DRAWER_TAB.podMetrics);
+
+ await infra.drawer.switchTab(DRAWER_TAB.podMetrics);
+ await expect(infra.drawer.charts().first()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/filters.spec.ts b/tests/e2e/tests/infra-monitoring/filters.spec.ts
new file mode 100644
index 0000000000..e60f1fda05
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/filters.spec.ts
@@ -0,0 +1,112 @@
+import { BASE_ENTITY, expect, seedDataset, test } from '../../drivers/infra';
+
+// The expression editor over the list.
+//
+// Filter *semantics* — what an expression selects, what an invalid one returns,
+// how an attribute narrows the set — are asserted per entity and headless by
+// `test_<entity>_filter` and `test_<entity>_filter_invalid` in the integration
+// suite. What a browser adds is that the editor produces the expression, the
+// Run button sends it, and the response reaches the table.
+
+test.describe('infra monitoring — filters', () => {
+ test('TC-01 an applied expression narrows the table and reaches the URL', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.filter);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ const [first] = facts.names;
+ await infra.list.search.apply(`${BASE_ENTITY.nameColumnId} = '${first}'`);
+ await table.waitForRows();
+
+ // Asserted by name: this fixture's pod UIDs do not follow `<name>-uid`.
+ await expect(table.rows()).toHaveCount(1);
+ await expect(table.rows().first()).toContainText(first);
+ expect(infra.list.search.read()).toBe(
+ `${BASE_ENTITY.nameColumnId} = '${first}'`,
+ );
+ });
+
+ test('TC-02 clearing the expression restores the full list', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.filter);
+ await infra.list.goto(BASE_ENTITY);
+ const table = infra.list.table(BASE_ENTITY);
+
+ const [first] = facts.names;
+ await infra.list.search.apply(`${BASE_ENTITY.nameColumnId} = '${first}'`);
+ await table.waitForRows();
+ expect(await table.rowKeys()).toHaveLength(1);
+
+ await infra.list.search.apply('');
+ await table.waitForRows();
+
+ expect((await table.rowKeys()).length).toBeGreaterThan(1);
+ });
+
+ test('TC-03 an expression that matches nothing shows the no-results state', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.goto(BASE_ENTITY);
+
+ await infra.list.search.apply(
+ `${BASE_ENTITY.nameColumnId} = 'no-such-row-anywhere'`,
+ );
+
+ await expect(infra.list.noResults()).toBeVisible();
+ });
+
+ test('TC-04 an in-flight query can be cancelled', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.goto(BASE_ENTITY);
+
+ // Delay the real request rather than faking it: `route.continue()` still
+ // reaches the backend, so only the timing changes.
+ await page.route(
+ (url) => infra.list.isListRequest(url.toString()),
+ async (route) => {
+ await new Promise((resolve) => {
+ setTimeout(resolve, 3_000);
+ });
+ await route.continue();
+ },
+ );
+
+ await infra.list.search.editor().click();
+ await page.keyboard.type(`${BASE_ENTITY.nameColumnId} = 'anything'`);
+ await page.keyboard.press('Escape');
+ await infra.list.search.run();
+
+ await expect(infra.list.search.cancelButton()).toBeVisible();
+ await infra.list.search.cancelButton().click();
+
+ await page.unrouteAll({ behavior: 'ignoreErrors' });
+ await expect(infra.list.search.cancelButton()).toHaveCount(0);
+ await expect(infra.list.search.runButton()).toBeVisible();
+ });
+
+ test('TC-05 a deep-linked expression is honoured on the first load', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.filter);
+ const [first] = facts.names;
+
+ await infra.list.gotoScoped(BASE_ENTITY, [first]);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ await expect(table.rows()).toHaveCount(1);
+ await expect(table.rows().first()).toContainText(first);
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/group-by.spec.ts b/tests/e2e/tests/infra-monitoring/group-by.spec.ts
new file mode 100644
index 0000000000..1063dc87c6
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/group-by.spec.ts
@@ -0,0 +1,75 @@
+import {
+ BASE_ENTITY,
+ EXPANDED_ROW_LIMIT,
+ expect,
+ groupedCloneNames,
+ seedGroupedDataset,
+ test,
+} from '../../drivers/infra';
+
+// Grouping and the expanded row.
+//
+// Which rows belong to which group is a backend concern the integration suite
+// already covers per entity. What is here is the UI contract: grouping writes
+// the param, the group row expands, and the expanded table is capped with a way
+// out.
+
+test.describe('infra monitoring — group by', () => {
+ test('TC-01 grouping writes the param and renders group rows', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedGroupedDataset(page, BASE_ENTITY);
+ expect(facts.rowCount).toBeGreaterThan(0);
+
+ const { groupLabel } = groupedCloneNames(BASE_ENTITY);
+ await infra.list.gotoGroupScoped(BASE_ENTITY, groupLabel);
+ const table = infra.list.table(BASE_ENTITY);
+
+ await table.groupBy(BASE_ENTITY.groupByAttribute);
+ expect(table.groupByFromUrl()).toContain(BASE_ENTITY.groupByAttribute);
+ await table.waitForRows();
+ });
+
+ test('TC-02 clearing the grouping drops the param', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedGroupedDataset(page, BASE_ENTITY);
+ const { groupLabel } = groupedCloneNames(BASE_ENTITY);
+ await infra.list.gotoGroupScoped(BASE_ENTITY, groupLabel);
+ const table = infra.list.table(BASE_ENTITY);
+
+ await table.groupBy(BASE_ENTITY.groupByAttribute);
+ await table.clearGrouping();
+
+ expect(table.groupByFromUrl()).toEqual([]);
+ });
+
+ test('TC-03 an expanded group is capped and offers View All', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ // The clone group holds more members than the expanded table's page size,
+ // which is what makes both the cap and the escape hatch observable.
+ await seedGroupedDataset(page, BASE_ENTITY);
+ const { groupLabel, names } = groupedCloneNames(BASE_ENTITY);
+ expect(names.length).toBeGreaterThan(EXPANDED_ROW_LIMIT);
+
+ await infra.list.gotoGroupScoped(BASE_ENTITY, groupLabel);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.groupBy(BASE_ENTITY.groupByAttribute);
+ await table.waitForRows();
+
+ await infra.list.expandGroup(groupLabel);
+ await infra.list.expectExpandedVisible();
+
+ // The expanded table pages at `EXPANDED_ROW_LIMIT`, and the way past that
+ // cap is View All rather than a second page inside the row.
+ await expect(infra.list.expandedRows()).toHaveCount(EXPANDED_ROW_LIMIT);
+ await expect(infra.list.viewAllButton()).toBeVisible();
+
+ await infra.list.collapseGroup(groupLabel);
+ await expect(infra.list.expandedTable()).toHaveCount(0);
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/navigation.spec.ts b/tests/e2e/tests/infra-monitoring/navigation.spec.ts
new file mode 100644
index 0000000000..a44947aac9
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/navigation.spec.ts
@@ -0,0 +1,116 @@
+import {
+ BASE_ENTITY,
+ DEFAULT_CATEGORY,
+ entityByKey,
+ expect,
+ K8S_CATEGORY_TAB_ORDER,
+ seedDataset,
+ test,
+} from '../../drivers/infra';
+
+// The kubernetes route's left rail: category switching and what it does to the
+// URL. Hosts lives on its own route with no rail.
+//
+// These run on pods and nodes only. `K8sBaseList` does not branch on entity —
+// the only thing that varies is the config object it is handed — so running the
+// same navigation nine more times proves nothing the source does not already
+// say. The per-entity config is asserted in jest.
+
+const NODES = entityByKey('nodes');
+
+test.describe('infra monitoring — navigation', () => {
+ test('TC-01 a fresh kubernetes route lands on containers with no category param', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await infra.list.load();
+
+ // "containers active", which `toBeVisible` cannot say: the rail renders
+ // every button on every category, so the selected class is the evidence.
+ await infra.list.expectCategoryActive(DEFAULT_CATEGORY);
+ expect(new URL(page.url()).searchParams.get('category')).toBeNull();
+ });
+
+ test(`TC-02 the rail renders ${K8S_CATEGORY_TAB_ORDER.length} categories in order`, async ({
+ infra,
+ }) => {
+ await infra.list.load();
+
+ // The rail mounts a tab at a time, so counting first catches a partial list.
+ const tabs = infra.list.categoryTabs();
+ await expect(tabs).toHaveCount(K8S_CATEGORY_TAB_ORDER.length);
+
+ expect(
+ await tabs.evaluateAll((buttons) =>
+ buttons.map(
+ (button) =>
+ button.getAttribute('data-testid')?.replace('category-', '') ?? '',
+ ),
+ ),
+ ).toEqual(K8S_CATEGORY_TAB_ORDER);
+ });
+
+ test('TC-03 switching to the default category writes its param', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await infra.list.load(NODES);
+ await expect(page).toHaveURL(/category=nodes/);
+
+ await infra.list.switchCategory(DEFAULT_CATEGORY);
+ });
+
+ test('TC-04 a category switch clears orderBy, groupBy and the expression', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ await table.sortBy(BASE_ENTITY.orderByColumnId);
+ await table.groupBy(BASE_ENTITY.groupByAttribute);
+
+ await infra.list.switchCategory(NODES);
+
+ await expect(page).not.toHaveURL(/orderBy=|groupBy=/);
+ await infra.list.search.expectExpression('');
+ });
+
+ test('TC-05 a deep-linked category and filter survive a reload', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, NODES.seed.primary);
+ await infra.list.gotoScoped(NODES, facts.names);
+ await infra.list.table(NODES).waitForRows();
+ const before = new URL(page.url()).searchParams;
+
+ await page.reload();
+ await infra.list.table(NODES).waitForRows();
+
+ const after = new URL(page.url()).searchParams;
+ for (const [key, value] of before) {
+ expect(after.get(key), `param ${key} survived the reload`).toBe(value);
+ }
+ await infra.list.expectCategoryActive(NODES);
+ });
+
+ test('TC-06 the quick-filter rail collapses and restores', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.goto(BASE_ENTITY);
+
+ const sections = infra.list.quickFilterSections();
+ await expect(sections.first()).toBeVisible();
+
+ await infra.list.quickFiltersToggle().first().click();
+ await expect(sections).toHaveCount(0);
+
+ await infra.list.quickFiltersToggle().first().click();
+ await expect(sections.first()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/smoke.spec.ts b/tests/e2e/tests/infra-monitoring/smoke.spec.ts
new file mode 100644
index 0000000000..f7c105c128
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/smoke.spec.ts
@@ -0,0 +1,66 @@
+import {
+ assertDatasetFacts,
+ BASE_ENTITY,
+ entityByKey,
+ expect,
+ seedDataset,
+ test,
+} from '../../drivers/infra';
+
+// The harness proving the data it claims. Every other spec in this directory
+// scopes its list to names it seeded, so if the dataset facts are wrong those
+// specs fail somewhere unrelated — this is where that failure belongs.
+
+const ENTITIES_WITH_FIXTURES = [
+ 'hosts',
+ 'pods',
+ 'nodes',
+ 'namespaces',
+ 'clusters',
+ 'deployments',
+ 'statefulsets',
+ 'daemonsets',
+ 'jobs',
+ 'volumes',
+];
+
+test.describe('infra monitoring — harness', () => {
+ test('TC-01 every dataset re-derives the facts the registry records', () => {
+ for (const key of ENTITIES_WITH_FIXTURES) {
+ const entity = entityByKey(key);
+ for (const dataset of [
+ entity.seed.primary,
+ entity.seed.grouped,
+ entity.seed.pagination,
+ entity.seed.filter,
+ entity.seed.orderBy,
+ ]) {
+ // Throws, naming the dataset and the mismatch, if the fixture and the
+ // transcribed facts have drifted.
+ const facts = assertDatasetFacts(dataset);
+ expect(facts.names.length, `${dataset} seeds names`).toBeGreaterThan(0);
+ }
+ }
+ });
+
+ test('TC-02 a seeded list renders its rows against the real backend', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.primary);
+
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ // The one thing no cheaper layer sees: the real response reaching the real
+ // table. Scoped by name, so a sibling worker's seed cannot change the count.
+ expect(await table.rowKeys()).toEqual(
+ expect.arrayContaining(
+ facts.names.map((name) =>
+ BASE_ENTITY.key === 'pods' ? `${name}-uid` : name,
+ ),
+ ),
+ );
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/states.spec.ts b/tests/e2e/tests/infra-monitoring/states.spec.ts
new file mode 100644
index 0000000000..59930301de
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/states.spec.ts
@@ -0,0 +1,66 @@
+import { BASE_ENTITY, expect, test } from '../../drivers/infra';
+
+// The three states the seeder cannot produce: a failing list request, a window
+// before retention, and a window with nothing in it. All three are reached by
+// intercepting the list request, which is the only way to make the backend fail
+// on demand — nothing else in this directory stubs the network.
+
+test.describe('infra monitoring — empty and error states', () => {
+ test('TC-01 a failed list request renders the error state', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await page.route(
+ (url) => infra.list.isListRequest(url.toString()),
+ (route) =>
+ route.fulfill({
+ status: 500,
+ contentType: 'application/json',
+ body: JSON.stringify({ status: 'error', error: 'boom' }),
+ }),
+ );
+
+ await infra.list.goto(BASE_ENTITY);
+
+ await expect(infra.list.errorState()).toBeVisible();
+ await expect(infra.list.table(BASE_ENTITY).rows()).toHaveCount(0);
+ });
+
+ test('TC-02 an empty list response renders the empty state', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await page.route(
+ (url) => infra.list.isListRequest(url.toString()),
+ (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({
+ status: 'success',
+ data: { records: [], total: 0 },
+ }),
+ }),
+ );
+
+ await infra.list.goto(BASE_ENTITY);
+
+ await expect(infra.list.emptyState()).toBeVisible();
+ });
+
+ test('TC-03 a window before retention says so rather than showing nothing', async ({
+ infra,
+ }) => {
+ // The retention branch keys off the *requested* window, so a deep link far
+ // enough back reaches it without any stubbing.
+ const end = Date.now() - 400 * 24 * 60 * 60 * 1000;
+ await infra.list.goto(BASE_ENTITY, {
+ startTime: String(end - 60 * 60 * 1000),
+ endTime: String(end),
+ });
+
+ await expect(
+ infra.list.retentionState().or(infra.list.emptyState()),
+ ).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/infra-monitoring/table.spec.ts b/tests/e2e/tests/infra-monitoring/table.spec.ts
new file mode 100644
index 0000000000..cae8ccb19b
--- /dev/null
+++ b/tests/e2e/tests/infra-monitoring/table.spec.ts
@@ -0,0 +1,139 @@
+import { BASE_ENTITY, expect, seedDataset, test } from '../../drivers/infra';
+
+// The list table: what a real response does to it, and what the user can do to
+// it that persists.
+//
+// Ordering and pagination *correctness* are not here. `test_<entity>_orderby`
+// and `test_<entity>_pagination` in `tests/integration/tests/inframonitoring/`
+// already assert, per entity and headless, that the API returns the right rows
+// in the right order for every column and direction. What a browser adds is that
+// the click writes the param and the response reaches the table.
+
+test.describe('infra monitoring — table', () => {
+ test('TC-01 sorting writes orderBy and re-renders from the response', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await infra.list.resetState(BASE_ENTITY);
+ const facts = await seedDataset(page, BASE_ENTITY.orderByDataset);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ const ascending = await table.rowKeys();
+ await table.sortBy(BASE_ENTITY.orderByColumnId);
+
+ const sorted = table.sortState();
+ expect(sorted?.columnName).toBe(BASE_ENTITY.orderByColumnId);
+ await expect(async () => {
+ expect(await table.rowKeys()).not.toEqual(ascending);
+ }).toPass();
+ });
+
+ test('TC-02 paging moves through the seeded rows', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.pagination);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names, { pageSize: '5' });
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ const pageOne = await table.rowKeys();
+ expect(pageOne.length).toBeGreaterThan(0);
+
+ await table.gotoPage(2);
+ await table.waitForRows();
+
+ const pageTwo = await table.rowKeys();
+ expect(pageTwo).not.toEqual(pageOne);
+ // No row appears twice across the two pages.
+ expect(new Set([...pageOne, ...pageTwo]).size).toBe(
+ pageOne.length + pageTwo.length,
+ );
+ });
+
+ test('TC-03 a page size change reaches the URL and the table', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ const facts = await seedDataset(page, BASE_ENTITY.seed.pagination);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ await table.pageSize(10);
+ await table.waitForRows();
+
+ expect((await table.rowKeys()).length).toBeLessThanOrEqual(10);
+ });
+
+ test('TC-04 hiding a column persists across a reload', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await infra.list.resetState(BASE_ENTITY);
+ const facts = await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ const before = await table.headers();
+ expect(before.length).toBeGreaterThan(1);
+
+ // The store is what persistence hangs on, and `useColumnStore`'s own
+ // behaviour is covered in jest — what a browser adds is that the table
+ // reads it back on a cold load.
+ await table.setColumnState({
+ hiddenColumnIds: [BASE_ENTITY.orderByColumnId],
+ });
+ await page.reload();
+ await table.waitForRows();
+
+ expect(await table.headers()).not.toEqual(before);
+ expect((await table.columnState()).hiddenColumnIds).toEqual([
+ BASE_ENTITY.orderByColumnId,
+ ]);
+ });
+
+ test('TC-05 a resize survives a reload', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await infra.list.resetState(BASE_ENTITY);
+ const facts = await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ const widened = await table.resizeColumn(BASE_ENTITY.nameColumnId, 120);
+
+ await page.reload();
+ await table.waitForRows();
+
+ const restored = (await table.columnState()).columnSizing ?? {};
+ expect(Object.keys(restored).length).toBeGreaterThan(0);
+ expect(
+ await table.headerCell(BASE_ENTITY.nameColumnId).boundingBox(),
+ ).toMatchObject({ width: expect.closeTo(widened, -1) });
+ });
+
+ test('TC-06 a malformed persisted column state does not break the table', async ({
+ authedPage: page,
+ infra,
+ }) => {
+ await infra.list.resetState(BASE_ENTITY);
+ const facts = await seedDataset(page, BASE_ENTITY.seed.primary);
+ await infra.list.gotoScoped(BASE_ENTITY, facts.names);
+ const table = infra.list.table(BASE_ENTITY);
+ await table.waitForRows();
+
+ // A value persisted under an older schema. The store fills the gaps rather
+ // than handing `undefined` to its selectors.
+ await table.setRawColumnState('{"hiddenColumnIds":"nope"}');
+ await page.reload();
+
+ await table.waitForRows();
+ expect((await table.headers()).length).toBeGreaterThan(1);
+ });
+});
diff --git a/tests/e2e/tests/integrations/cloud.spec.ts b/tests/e2e/tests/integrations/cloud.spec.ts
new file mode 100644
index 0000000000..4ce95e8ac8
--- /dev/null
+++ b/tests/e2e/tests/integrations/cloud.spec.ts
@@ -0,0 +1,198 @@
+import { expect, test } from '../../drivers/integrations';
+
+// The one-click cloud pages against the real cloud-integrations API. The account
+// and service contract (create, check-in, update, dashboard provisioning) is
+// covered headless by tests/integration/tests/cloudintegrations/. Accounts are
+// org-global: every assertion names an account this worker created, and
+// "Integrate Now" is never asserted.
+
+const SMOKE = [
+ { provider: 'aws', service: 'ec2' },
+ { provider: 'gcp', service: 'computeengine' },
+ { provider: 'azure', service: 'aks' },
+] as const;
+
+/** The AWS agent polls every 10 s, so one missed poll still lands. */
+const AWS_POLL_BUDGET = 25_000;
+
+test.describe('Cloud integrations', () => {
+ for (const { provider, service } of SMOKE) {
+ test(`TC-01 the ${provider} page renders its services`, async ({
+ cloud,
+ integrations,
+ noise,
+ }) => {
+ const page = cloud(provider);
+ await page.goto();
+
+ await expect(page.service(service)).toBeVisible();
+ await expect(page.detailsTab('Overview')).toBeVisible();
+
+ expect(noise.errors).toEqual([]);
+ expect(integrations.unexpectedFailures(noise)).toEqual([]);
+ });
+ }
+
+ test('TC-02 a checked-in AWS account is selectable and lists its services by state', async ({
+ authedPage,
+ awsAccount,
+ cloud,
+ }) => {
+ const aws = cloud('aws');
+ await aws.goto(awsAccount.id);
+
+ await expect(aws.accountSelector()).toContainText(
+ awsAccount.providerAccountId,
+ );
+ await expect(aws.notEnabledService('rds')).toBeVisible();
+
+ await aws.service('rds').click();
+ await expect(authedPage).toHaveURL(/[?&]service=rds(&|$)/);
+ await expect(aws.metricsSwitch()).toBeEnabled();
+ });
+
+ test('TC-03 enabling metrics for a service saves, moves it to Enabled, and exposes its dashboards', async ({
+ authedPage,
+ awsAccount,
+ cloud,
+ }) => {
+ const aws = cloud('aws');
+ try {
+ await aws.goto(awsAccount.id);
+ await aws.service('rds').click();
+ await expect(aws.metricsSwitch()).toBeEnabled();
+
+ await aws.metricsSwitch().click();
+ const saved = await aws.saveService();
+ expect(saved.ok()).toBe(true);
+ expect(saved.request().postDataJSON()).toMatchObject({
+ config: { aws: { metrics: { enabled: true } } },
+ });
+
+ await expect(aws.saveButton()).toHaveCount(0);
+ await expect(aws.discardButton()).toHaveCount(0);
+ await expect(aws.enabledService('rds')).toBeVisible();
+
+ // Provisioned dashboards arrive with the service refetch.
+ const card = aws.provisionedDashboardCards().first();
+ await expect(card).toBeVisible();
+ await card.click();
+ await expect(authedPage).toHaveURL(/\/dashboard\/[^/?]+/);
+ await expect(aws.dashboardTitle()).toBeVisible();
+ } finally {
+ await aws.setService(awsAccount.id, 'rds', { metrics: false, logs: false });
+ }
+ });
+
+ test('TC-04 adding an AWS account reaches the waiting state and completes on agent check-in', async ({
+ cloud,
+ integrations,
+ }) => {
+ const aws = cloud('aws');
+ const providerAccountId = `e2e-aws-ui-${Date.now()}`;
+ let accountId = '';
+ try {
+ await aws.goto();
+ await aws.addAccount();
+ await aws.aws.pickDeploymentRegion('US East (N. Virginia)');
+ await aws.aws.toggleRegion('us-east-1');
+ await aws.aws.fillMissingCredentials();
+
+ const launched = await aws.aws.launch();
+ accountId = launched.accountId;
+ expect(launched.body.config?.aws?.regions).toEqual(['us-east-1']);
+ expect(launched.connectionUrl).toContain(
+ 'console.aws.amazon.com/cloudformation',
+ );
+ expect(launched.connectionUrl).toContain(
+ `param_SigNozAccountId=${accountId}`,
+ );
+ await expect(aws.waitingCallout()).toBeVisible();
+
+ await aws.checkIn(accountId, providerAccountId);
+ await expect(
+ integrations.toast('AWS account connected successfully'),
+ ).toBeVisible({ timeout: AWS_POLL_BUDGET });
+
+ await aws.goto(accountId);
+ await expect(aws.accountSelector()).toContainText(providerAccountId);
+ } finally {
+ await aws.removeAccount(accountId);
+ }
+ });
+
+ test('TC-05 editing regions and disconnecting an AWS account', async ({
+ cloud,
+ integrations,
+ }) => {
+ const aws = cloud('aws');
+ const providerAccountId = `e2e-aws-edit-${Date.now()}`;
+ const id = await aws.seedAccount(providerAccountId, [
+ 'us-east-1',
+ 'us-west-2',
+ ]);
+ try {
+ await aws.goto(id);
+ await expect(aws.accountSelector()).toContainText(providerAccountId);
+
+ await aws.editAccount();
+ const updated = await aws.aws.updateRegions(['us-east-1', 'eu-west-1']);
+ expect(updated.ok()).toBe(true);
+ expect(
+ [
+ ...(updated.request().postDataJSON().config.aws.regions as string[]),
+ ].sort(),
+ ).toEqual(['eu-west-1', 'us-east-1']);
+ await expect(
+ integrations.toast('Account settings updated successfully'),
+ ).toBeVisible();
+
+ await aws.editAccount();
+ await expect(aws.aws.region('eu-west-1')).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+
+ const deleted = await aws.disconnect();
+ expect(deleted.status()).toBe(204);
+ await expect(aws.accountSelector()).not.toContainText(providerAccountId);
+ expect((await aws.listAccounts()).map((a) => a.id)).not.toContain(id);
+ } finally {
+ await aws.removeAccount(id);
+ }
+ });
+
+ test('TC-06 GCP connect completes in the UI against the real backend', async ({
+ cloud,
+ integrations,
+ }) => {
+ const gcp = cloud('gcp');
+ const name = `e2e-gcp-${Date.now()}`;
+ let id = '';
+ try {
+ await gcp.goto();
+ await gcp.addAccount();
+ await gcp.gcp.fill({
+ name,
+ projectId: 'e2e-deploy-project',
+ region: 'Council Bluffs (us-central1)',
+ projectIds: ['e2e-monitored-project'],
+ });
+
+ const { created, checkedIn } = await gcp.gcp.connect();
+ expect(created.status()).toBe(201);
+ id = ((await created.json()) as { data: { id: string } }).data.id;
+ expect(checkedIn.status()).toBe(200);
+
+ await expect(
+ integrations.toast('GCP account connected successfully'),
+ ).toBeVisible();
+ await expect(gcp.gcp.connectButton()).toHaveCount(0);
+
+ await gcp.goto(id);
+ await expect(gcp.accountSelector()).toContainText(name);
+ } finally {
+ await gcp.removeAccount(id);
+ }
+ });
+});
diff --git a/tests/e2e/tests/integrations/install.spec.ts b/tests/e2e/tests/integrations/install.spec.ts
new file mode 100644
index 0000000000..dc2925237a
--- /dev/null
+++ b/tests/e2e/tests/integrations/install.spec.ts
@@ -0,0 +1,60 @@
+import { expect, test } from '../../drivers/integrations';
+
+// Owns `builtin-nginx`: no other spec installs it or asserts its badge. The two
+// scenarios are one lifecycle, so they run in order on one worker.
+
+test.describe.configure({ mode: 'serial' });
+
+test.describe('Integration install', () => {
+ // known: POST /api/v1/integrations/install returns 500 on sqlite, the config
+ // column is written through InstalledIntegrationConfig.Value() as []byte and
+ // Scan then fails with "invalid character '\\'"
+ test.fixme('TC-01 connecting installs the integration and shows it listening', async ({
+ integrations,
+ ownedIntegration,
+ }) => {
+ await integrations.gotoDetail(ownedIntegration);
+ await expect(integrations.connectButton()).toHaveText(/^Connect /);
+
+ const installed = await integrations.connect();
+ expect(installed.status(), await installed.text()).toBe(200);
+ expect(installed.request().postDataJSON()).toMatchObject({
+ integration_id: ownedIntegration,
+ });
+
+ await expect(integrations.connectionStatus()).toHaveText(
+ 'Listening for data...',
+ );
+ await expect(integrations.connectionStatus()).toHaveAttribute(
+ 'data-state',
+ 'testingConnection',
+ );
+ await expect(integrations.removeButton()).toBeVisible();
+ await expect(integrations.connectButton()).toHaveText('Test Connection');
+
+ await integrations.gotoList();
+ await expect(integrations.rowStatus(ownedIntegration)).toHaveText(
+ /^Installed$/i,
+ );
+ });
+
+ // known: needs TC-01's install, see above
+ test.fixme('TC-02 removing uninstalls it', async ({
+ integrations,
+ ownedIntegration,
+ }) => {
+ await integrations.gotoDetail(ownedIntegration);
+ await expect(integrations.removeButton()).toBeVisible();
+
+ const removed = await integrations.remove();
+ expect(removed.status()).toBe(200);
+
+ await expect(integrations.removeButton()).toHaveCount(0);
+ await expect(integrations.connectButton()).toHaveText('Connect Nginx');
+
+ await integrations.gotoList();
+ await expect(integrations.rowStatus(ownedIntegration)).toHaveText(
+ /^Not Installed$/i,
+ );
+ });
+});
diff --git a/tests/e2e/tests/integrations/list.spec.ts b/tests/e2e/tests/integrations/list.spec.ts
new file mode 100644
index 0000000000..7c1477cadc
--- /dev/null
+++ b/tests/e2e/tests/integrations/list.spec.ts
@@ -0,0 +1,64 @@
+import { expect, test } from '../../drivers/integrations';
+
+// The built-in list and its detail page against the real integrations API.
+// Client-side search, connection-state derivation and the modal labels are
+// jest territory (see the plan's jest list); install state is org-global, so
+// badges are asserted for presence only.
+
+const BUILT_INS = ['builtin-redis', 'builtin-postgres', 'builtin-clickhouse'];
+const ONE_CLICK = ['aws', 'gcp', 'azure'] as const;
+
+test.describe('Integrations list', () => {
+ test('TC-01 the list renders built-in and one-click integrations from the API', async ({
+ integrations,
+ noise,
+ }) => {
+ await integrations.gotoList();
+
+ for (const id of BUILT_INS) {
+ await expect(integrations.row(id)).toBeVisible();
+ await expect(integrations.rowStatus(id)).toHaveText(
+ /^(Installed|Not Installed)$/i,
+ );
+ }
+ for (const id of ONE_CLICK) {
+ await expect(integrations.oneClick(id)).toBeVisible();
+ }
+
+ await integrations.search('redis');
+ await expect(integrations.row('builtin-redis')).toBeVisible();
+ await expect(integrations.row('builtin-nginx')).toHaveCount(0);
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a row opens its detail page, and the tabs render real content', async ({
+ authedPage: page,
+ integrations,
+ }) => {
+ await integrations.gotoList();
+ await integrations.row('builtin-clickhouse').click();
+ await expect(page).toHaveURL(/\/integrations\/builtin-clickhouse$/);
+ await expect(integrations.connectButton()).toBeEnabled();
+
+ await expect(integrations.tab('Overview')).toHaveAttribute(
+ 'aria-selected',
+ 'true',
+ );
+ await expect(integrations.categories().first()).toBeVisible();
+ await expect(integrations.assets()).toContainText('Dashboards');
+
+ await integrations.openTab('Configure');
+ // Clickhouse ships several steps; the first is selected on mount.
+ const target = integrations.configureSteps().nth(1);
+ await expect(target).not.toHaveClass(/\bactive\b/);
+ await target.click();
+ await expect(target).toHaveClass(/\bactive\b/);
+
+ await integrations.openTab('Data Collected');
+ await expect(integrations.metricsRows().first()).toBeVisible();
+
+ await integrations.backToList();
+ });
+});
diff --git a/tests/e2e/tests/llm-o11y/attribute-mapping.spec.ts b/tests/e2e/tests/llm-o11y/attribute-mapping.spec.ts
index 49fad8d6bf..e07a2057ca 100644
--- a/tests/e2e/tests/llm-o11y/attribute-mapping.spec.ts
+++ b/tests/e2e/tests/llm-o11y/attribute-mapping.spec.ts
@@ -1,11 +1,9 @@
-import { expect, test } from '../../fixtures/auth';
-import { newAdminContext } from '../../helpers/auth';
import {
- deleteSpanMapperGroupsByName,
- gotoAttributeMapping,
-} from '../../helpers/llm-o11y/attribute-mapping';
-import { authToken } from '../../helpers/common';
-
+ expect,
+ llmO11yDriver,
+ onAdminPage,
+ test,
+} from '../../drivers/llm-o11y';
test.describe.configure({ mode: 'serial' });
const GROUP_NAME = 'e2e-attr-mapping-happy';
@@ -15,64 +13,58 @@ const TARGET_ATTR = 'gen_ai.content.prompt';
const SOURCE_ATTR = 'my_company.llm.input';
test.afterAll(async ({ browser }) => {
- const ctx = await newAdminContext(browser);
- const page = await ctx.newPage();
- try {
- const token = await authToken(page);
- await deleteSpanMapperGroupsByName(ctx.request, token, [GROUP_NAME]);
- } finally {
- await ctx.close();
- }
+ await onAdminPage(browser, (page) =>
+ llmO11yDriver(page).deleteSpanMapperGroups([GROUP_NAME]),
+ );
});
test.describe('LLM Observability — Attribute Mapping', () => {
test('basic flow: add a mapping, test it, then save it to the backend', async ({
authedPage: page,
+ llm,
}) => {
- await gotoAttributeMapping(page);
+ await llm.gotoAttributeMapping();
- await page.getByTestId('add-group-row').click();
- const groupDrawer = page.getByTestId('group-form-drawer');
+ await llm.mapping.addGroup().click();
+ const groupDrawer = llm.mapping.groupDrawer();
await expect(groupDrawer).toBeVisible();
- await page.getByTestId('group-form-name').fill(GROUP_NAME);
- await page.getByTestId('group-form-attribute-add').click();
- await page.getByTestId('group-form-attribute-0').fill(GROUP_CONDITION);
- await page.getByTestId('group-form-save').click();
+ await llm.mapping.groupName().fill(GROUP_NAME);
+ await llm.mapping.addGroupAttribute().click();
+ await llm.mapping.groupAttribute(0).fill(GROUP_CONDITION);
+ await llm.mapping.saveGroup().click();
await expect(groupDrawer).toBeHidden();
- const groupHeader = page
- .locator('[data-testid^="group-expand-"]')
- .filter({ hasText: GROUP_NAME });
+ const groupHeader = llm.mapping.groupHeader(GROUP_NAME);
await expect(groupHeader).toBeVisible();
await groupHeader.click();
- await page.locator('[data-testid^="add-mapper-"]').click();
- const mapperDrawer = page.getByTestId('mapper-form-drawer');
+ await llm.mapping.addMapper().click();
+ const mapperDrawer = llm.mapping.mapperDrawer();
await expect(mapperDrawer).toBeVisible();
- await page.getByTestId('mapper-form-target').fill(TARGET_ATTR);
- await page.getByTestId('mapper-form-source-0').fill(SOURCE_ATTR);
+ await llm.mapping.mapperTarget().fill(TARGET_ATTR);
+ await llm.mapping.mapperSource(0).fill(SOURCE_ATTR);
- const mapperSave = page.getByTestId('mapper-form-save');
+ const mapperSave = llm.mapping.saveMapper();
await expect(mapperSave).toBeEnabled();
await mapperSave.click();
await expect(mapperDrawer).toBeHidden();
- await expect(page.getByTestId('unsaved-changes')).toBeVisible();
+ await expect(llm.mapping.unsavedChanges()).toBeVisible();
- await page.getByRole('tab', { name: 'Test' }).click();
- await expect(page.getByTestId('test-tab')).toBeVisible();
+ await llm.mapping.tab('Test').click();
+ await expect(llm.mapping.testTab()).toBeVisible();
const testResponse = page.waitForResponse(
(r) =>
new URL(r.url()).pathname.endsWith('/span_mapper_groups/test') &&
r.request().method() === 'POST',
);
- await page.getByTestId('run-test-button').click();
+ await llm.mapping.runTest().click();
expect((await testResponse).ok()).toBeTruthy();
- await expect(page.getByTestId('test-error')).toHaveCount(0);
- await expect(page.getByTestId('test-results')).toBeVisible();
+ await expect(llm.mapping.testError()).toHaveCount(0);
+ await expect(llm.mapping.testResults()).toBeVisible();
const createGroup = page.waitForResponse(
(r) =>
@@ -86,12 +78,12 @@ test.describe('LLM Observability — Attribute Mapping', () => {
) && r.request().method() === 'POST',
);
- await page.getByTestId('save-changes-btn').click();
+ await llm.mapping.saveChanges().click();
expect((await createGroup).ok()).toBeTruthy();
expect((await createMapper).ok()).toBeTruthy();
- await expect(page.getByText('Attribute mapping changes saved')).toBeVisible();
- await expect(page.getByTestId('unsaved-changes')).toHaveCount(0);
+ await expect(llm.toast('Attribute mapping changes saved')).toBeVisible();
+ await expect(llm.mapping.unsavedChanges()).toHaveCount(0);
});
});
diff --git a/tests/e2e/tests/llm-o11y/explorer.spec.ts b/tests/e2e/tests/llm-o11y/explorer.spec.ts
new file mode 100644
index 0000000000..49f2d07508
--- /dev/null
+++ b/tests/e2e/tests/llm-o11y/explorer.spec.ts
@@ -0,0 +1,43 @@
+import { expect, test } from '../../drivers/llm-o11y';
+
+// The AI observability explorer: the traces explorer scoped to gen_ai spans.
+// Column config, the view switcher and the empty state are covered by jest
+// under `container/LLMObservability/Explorer/` and by its Storybook story; here
+// a real gen_ai trace has to come back through `builder_ai_query`.
+
+test.describe('LLM traces explorer', () => {
+ test('TC-01 the page loads clean and lists a seeded LLM trace', async ({
+ llm,
+ noise,
+ }) => {
+ const seed = await llm.seedLlmTrace();
+
+ await llm.gotoExplorer();
+ await llm.waitForTraceRow(seed.traceId);
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 opening a trace row reaches trace details', async ({ llm }) => {
+ const seed = await llm.seedLlmTrace();
+
+ await llm.gotoExplorer();
+ await llm.waitForTraceRow(seed.traceId);
+ await llm.openTraceRow(seed);
+
+ await expect(llm.traceDetailsTab('thread')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await llm.traceDetailsTab('overview').click();
+ await expect(llm.waterfallRow(seed.rootSpanId)).toBeVisible();
+ });
+
+ test('TC-03 the quick-filter settings open', async ({ llm }) => {
+ await llm.gotoExplorer();
+ await llm.openQuickFilterSettings();
+
+ await expect(llm.quickFilterSettings()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/llm-o11y/llm-pricing.spec.ts b/tests/e2e/tests/llm-o11y/llm-pricing.spec.ts
index 3ad5840df5..0cac88d679 100644
--- a/tests/e2e/tests/llm-o11y/llm-pricing.spec.ts
+++ b/tests/e2e/tests/llm-o11y/llm-pricing.spec.ts
@@ -1,11 +1,9 @@
-import { expect, test } from '../../fixtures/auth';
-import { newAdminContext } from '../../helpers/auth';
-import { authToken } from '../../helpers/common';
import {
- deletePricingRulesByModelName,
- gotoLlmPricing,
-} from '../../helpers/llm-o11y/llm-pricing';
-
+ expect,
+ llmO11yDriver,
+ onAdminPage,
+ test,
+} from '../../drivers/llm-o11y';
test.describe.configure({ mode: 'serial' });
const MODEL_NAME = 'e2e-pricing-happy-model';
@@ -13,30 +11,26 @@ const INPUT_COST = '5.50';
const OUTPUT_COST = '17.00';
test.afterAll(async ({ browser }) => {
- const ctx = await newAdminContext(browser);
- const page = await ctx.newPage();
- try {
- const token = await authToken(page);
- await deletePricingRulesByModelName(ctx.request, token, [MODEL_NAME]);
- } finally {
- await ctx.close();
- }
+ await onAdminPage(browser, (page) =>
+ llmO11yDriver(page).deletePricingRules([MODEL_NAME]),
+ );
});
test.describe('LLM Observability — Model Pricing', () => {
test('basic flow: add a user-override model cost and save it to the backend', async ({
authedPage: page,
+ llm,
}) => {
- await gotoLlmPricing(page);
+ await llm.gotoPricing();
- await page.getByTestId('add-model-cost-btn').click();
- await expect(page.getByTestId('drawer-model-id-input')).toBeVisible();
+ await llm.pricing.addModelCost().click();
+ await expect(llm.pricing.modelIdInput()).toBeVisible();
- await page.getByTestId('drawer-model-id-input').fill(MODEL_NAME);
- await page.getByTestId('drawer-pattern-input').fill(MODEL_NAME);
- await page.getByTestId('drawer-pattern-add-btn').click();
- await page.getByTestId('drawer-input-cost').fill(INPUT_COST);
- await page.getByTestId('drawer-output-cost').fill(OUTPUT_COST);
+ await llm.pricing.modelIdInput().fill(MODEL_NAME);
+ await llm.pricing.patternInput().fill(MODEL_NAME);
+ await llm.pricing.addPattern().click();
+ await llm.pricing.inputCost().fill(INPUT_COST);
+ await llm.pricing.outputCost().fill(OUTPUT_COST);
const putResponse = page.waitForResponse(
(r) =>
@@ -44,17 +38,13 @@ test.describe('LLM Observability — Model Pricing', () => {
r.request().method() === 'PUT',
);
- const saveBtn = page.getByTestId('drawer-save-btn');
+ const saveBtn = llm.pricing.save();
await expect(saveBtn).toBeEnabled();
await saveBtn.click();
expect((await putResponse).ok()).toBeTruthy();
- await expect(page.getByTestId('drawer-model-id-input')).toHaveCount(0);
- await expect(page.getByTestId('model-costs-table')).toBeVisible();
- await expect(
- page
- .locator('[data-testid^="model-cell-name-"]')
- .filter({ hasText: MODEL_NAME }),
- ).toBeVisible();
+ await expect(llm.pricing.modelIdInput()).toHaveCount(0);
+ await expect(llm.pricing.table()).toBeVisible();
+ await expect(llm.pricing.modelName(MODEL_NAME)).toBeVisible();
});
});
diff --git a/tests/e2e/tests/logs-explorer/detail.spec.ts b/tests/e2e/tests/logs-explorer/detail.spec.ts
new file mode 100644
index 0000000000..4457465dff
--- /dev/null
+++ b/tests/e2e/tests/logs-explorer/detail.spec.ts
@@ -0,0 +1,99 @@
+import { expect, lineBody, serviceFilter, test } from '../../drivers/logs';
+
+const KIND_FIELD = 'attributes.e2e.kind';
+
+test.describe('Logs Explorer — detail drawer', () => {
+ test('TC-01 the drawer shows the log body and its fields in pretty and JSON views', async ({
+ logs,
+ logsSeed,
+ noise,
+ }) => {
+ await logs.gotoUntil(logsSeed.json, {
+ expression: serviceFilter(logsSeed.service),
+ });
+ await logs.detail.open(logs.rowByBody(logsSeed.json).first());
+
+ await expect(logs.detail.body()).toContainText(logsSeed.json);
+ await expect(logs.detail.highlights()).toContainText(logsSeed.service);
+ await expect(logs.detail.fieldActions(KIND_FIELD)).toBeVisible();
+ // The JSON body is parsed into its own fields in the pretty view.
+ await expect(logs.detail.fieldActions('body.user.id')).toBeVisible();
+
+ await logs.detail.viewMode('JSON');
+ await expect(logs.detail.drawer()).toContainText('e2e.kind');
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 Filter for value from the drawer narrows the list', async ({
+ logs,
+ logsSeed,
+ }) => {
+ const odd = lineBody(logsSeed.marker, 23);
+ await logs.gotoUntil(odd, { expression: serviceFilter(logsSeed.service) });
+ await logs.detail.open(logs.rowByBody(odd));
+
+ await logs.detail.fieldAction(KIND_FIELD, 'Filter for value');
+
+ // The drawer action appends to `filters.items`; the URL expression keeps
+ // its old text, so the editor is what shows the merged query.
+ await expect(logs.search.editor()).toContainText("e2e.kind = 'odd'");
+ await expect(logs.rowByBody(odd)).toBeVisible();
+ await expect(logs.rowByBody(logsSeed.recent[0])).toHaveCount(0);
+ });
+
+ test('TC-03 Filter out value excludes it', async ({ logs, logsSeed }) => {
+ const odd = lineBody(logsSeed.marker, 23);
+ await logs.gotoUntil(odd, { expression: serviceFilter(logsSeed.service) });
+ await logs.detail.open(logs.rowByBody(odd));
+
+ await logs.detail.fieldAction(KIND_FIELD, 'Filter out value');
+
+ await expect(logs.search.editor()).toContainText("e2e.kind != 'odd'");
+ await expect(logs.rowByBody(odd)).toHaveCount(0);
+ await expect(logs.rowByBody(logsSeed.recent[0])).toBeVisible();
+ });
+
+ test('TC-04 the context tab lists the neighbours of the selected log', async ({
+ logs,
+ logsSeed,
+ }) => {
+ const [before, selected, after] = [11, 12, 13].map((index) =>
+ lineBody(logsSeed.marker, index),
+ );
+ await logs.gotoUntil(selected, {
+ expression: serviceFilter(logsSeed.service),
+ });
+ await logs.detail.open(logs.rowByBody(selected));
+
+ await logs.detail.tab('Context');
+
+ const items = logs.detail.contextItems();
+ await expect(items.filter({ hasText: before })).toBeVisible();
+ await expect(items.filter({ hasText: after })).toBeVisible();
+ const order = (await items.allInnerTexts()).flatMap((text) =>
+ [before, selected, after].filter((body) => text.includes(body)),
+ );
+ expect(order).toHaveLength(3);
+ expect(order[1]).toBe(selected);
+ expect([order[0], order[2]].sort()).toEqual([after, before].sort());
+ });
+
+ test('TC-05 a copied row link reopens the same log', async ({
+ logs,
+ logsSeed,
+ }) => {
+ // Near the top: the Default list is virtualised and renders about a dozen rows.
+ const target = lineBody(logsSeed.marker, 22);
+ await logs.gotoUntil(target, { expression: serviceFilter(logsSeed.service) });
+ await logs.setFormat('Default');
+
+ const link = await logs.copyRowLink(logs.rowByBody(target));
+
+ expect(new URL(link).searchParams.get('activeLogId')).toBeTruthy();
+ const linked = await logs.openInNewTab(link);
+ const row = logs.rowById(logs.activeLogId(linked), linked);
+ await expect(row).toBeVisible();
+ await expect(row).toContainText(target);
+ });
+});
diff --git a/tests/e2e/tests/logs-explorer/linked-row-click.spec.ts b/tests/e2e/tests/logs-explorer/linked-row-click.spec.ts
index b0da65096b..617b9fec52 100644
--- a/tests/e2e/tests/logs-explorer/linked-row-click.spec.ts
+++ b/tests/e2e/tests/logs-explorer/linked-row-click.spec.ts
@@ -1,49 +1,33 @@
-import { expect, test } from '../../fixtures/auth';
-import {
- activeLogIdFromUrl,
- clickRowFirstCell,
- gotoLogsExplorer,
- highlightedLogsTableRows,
- LINKED_ROW_CLASS,
- logDetailsDrawer,
- logsTableRow,
- logsTableRows,
- openFirstContextLogInNewTab,
- openContextView,
- openLogDetailsFromRow,
- setLogsFormat,
- unhighlightedLogsTableRows,
-} from '../../helpers/logs-explorer';
+import { expect, test } from '../../drivers/logs';
test.describe('Logs Explorer — linked row in Column format', () => {
test('TC-01 the linked row in a newly opened tab is highlighted and toggles the details drawer on click', async ({
- authedPage: page,
+ logs,
}) => {
- await gotoLogsExplorer(page);
- await setLogsFormat(page, 'Column');
+ await logs.goto();
+ await logs.setFormat('Column');
- const rows = logsTableRows(page);
+ const rows = logs.rows();
await expect(rows.first()).toBeVisible();
- await expect(highlightedLogsTableRows(page)).toHaveCount(0);
+ await expect(logs.highlightedRows()).toHaveCount(0);
- await openLogDetailsFromRow(rows.first());
- await openContextView(page);
+ await logs.openDetailsFromRow(rows.first());
+ await logs.openContextView();
- const linkedTab = await openFirstContextLogInNewTab(page);
+ const linkedTab = await logs.openFirstContextLogInNewTab();
await expect(linkedTab).toHaveURL(/activeLogId=/);
- const linkedLogId = activeLogIdFromUrl(linkedTab);
- const linkedRow = logsTableRow(linkedTab, linkedLogId);
+ const linkedRow = logs.row(logs.activeLogId(linkedTab), linkedTab);
await expect(linkedRow).toBeVisible();
- await expect(linkedRow).toHaveClass(new RegExp(LINKED_ROW_CLASS));
+ await expect(linkedRow).toHaveClass(/logs-linked-row/);
- await expect(highlightedLogsTableRows(linkedTab)).toHaveCount(1);
- await expect(unhighlightedLogsTableRows(linkedTab).first()).toBeVisible();
+ await expect(logs.highlightedRows(linkedTab)).toHaveCount(1);
+ await expect(logs.unhighlightedRows(linkedTab).first()).toBeVisible();
- await expect(logDetailsDrawer(linkedTab)).toBeHidden();
- await openLogDetailsFromRow(linkedRow);
+ await expect(logs.detailsDrawer(linkedTab)).toBeHidden();
+ await logs.openDetailsFromRow(linkedRow);
- await clickRowFirstCell(linkedRow);
- await expect(logDetailsDrawer(linkedTab)).toBeHidden();
+ await logs.clickRowFirstCell(linkedRow);
+ await expect(logs.detailsDrawer(linkedTab)).toBeHidden();
});
});
diff --git a/tests/e2e/tests/logs-explorer/list-options.spec.ts b/tests/e2e/tests/logs-explorer/list-options.spec.ts
new file mode 100644
index 0000000000..b1b72693a6
--- /dev/null
+++ b/tests/e2e/tests/logs-explorer/list-options.spec.ts
@@ -0,0 +1,48 @@
+import { expect, lineBody, serviceFilter, test } from '../../drivers/logs';
+
+test.describe('Logs Explorer — list options', () => {
+ test('TC-01 an added column shows seeded values and survives a reload', async ({
+ logs,
+ logsSeed,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+ await logs.setFormat('Column');
+
+ await logs.openColumns();
+ await logs.addColumn('e2e.kind');
+
+ await expect
+ .poll(() => logs.table.headers())
+ .toEqual(expect.arrayContaining(['e2e.kind']));
+ await expect(logs.rowByBody(lineBody(logsSeed.marker, 23))).toContainText(
+ 'odd',
+ );
+
+ await logs.reload();
+ await expect
+ .poll(() => logs.table.headers())
+ .toEqual(expect.arrayContaining(['e2e.kind']));
+ });
+
+ test('TC-02 Download exports the filtered rows as CSV', async ({
+ logs,
+ logsSeed,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+
+ const file = await logs.download('csv');
+
+ expect(file.name).toMatch(/\.csv$/);
+ expect(file.text).toContain(logsSeed.recent[0]);
+ const rows = file.text
+ .split('\n')
+ .slice(1)
+ .filter((line) => line.trim() !== '');
+ expect(rows).toHaveLength(logsSeed.total);
+ expect(rows.filter((line) => !line.includes(logsSeed.marker))).toEqual([]);
+ });
+});
diff --git a/tests/e2e/tests/logs-explorer/live-tail.spec.ts b/tests/e2e/tests/logs-explorer/live-tail.spec.ts
new file mode 100644
index 0000000000..7d2a07768e
--- /dev/null
+++ b/tests/e2e/tests/logs-explorer/live-tail.spec.ts
@@ -0,0 +1,76 @@
+import {
+ expect,
+ SEEDED_DATA_TIMEOUT,
+ serviceFilter,
+ sideService,
+ test,
+ type LogsSeed,
+} from '../../drivers/logs';
+
+/** One backend refresh (5 s) plus slack. See docs/flake-notes.md. */
+const PAUSED_HOLD_MS = 7_000;
+const LIVE_OFFSET_MS = 5_000;
+/** Far enough ahead that the row is still newer than a stream reopened later. */
+const PAUSED_OFFSET_MS = 60_000;
+
+// Live rows go to a service of their own so the worker's counts stay fixed.
+const liveService = (seed: LogsSeed): string => sideService(seed, 'live');
+
+test.describe('Logs Explorer — live tail', () => {
+ test('TC-01 going live streams a log seeded after the connection opens', async ({
+ logs,
+ logsSeed,
+ }) => {
+ const service = liveService(logsSeed);
+ await logs.goto({ expression: serviceFilter(service) });
+
+ await logs.live.start();
+ const body = `${service} live-${Date.now()}`;
+ await logs.seedRow(service, body, LIVE_OFFSET_MS);
+
+ await expect(logs.live.rowByBody(body)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(logs.runButton()).toBeDisabled();
+ });
+
+ test('TC-02 pause holds new rows back and resume delivers them', async ({
+ logs,
+ logsSeed,
+ }) => {
+ const service = liveService(logsSeed);
+ await logs.goto({ expression: serviceFilter(service) });
+ await logs.live.start();
+
+ await logs.live.pause();
+ const body = `${service} paused-${Date.now()}`;
+ await logs.seedRow(service, body, PAUSED_OFFSET_MS);
+ await logs.live.expectAbsentFor(body, PAUSED_HOLD_MS);
+
+ await logs.live.resume();
+
+ await expect(logs.live.rowByBody(body)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(logs.live.pauseResume()).toHaveText('Pause');
+ });
+
+ test('TC-03 leaving live mode returns to the list with the query enabled', async ({
+ logs,
+ logsSeed,
+ noise,
+ }) => {
+ const service = sideService(logsSeed, `exit-${Date.now()}`);
+ const fresh = `${service} fresh`;
+ await logs.seedRow(service, fresh, -60_000);
+ await logs.gotoUntil(fresh, { expression: serviceFilter(service) });
+
+ await logs.live.start();
+ await logs.live.exit();
+
+ await expect(logs.runButton()).toBeEnabled();
+ await expect(logs.rowByBody(fresh)).toBeVisible();
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+});
diff --git a/tests/e2e/tests/logs-explorer/quick-filters.spec.ts b/tests/e2e/tests/logs-explorer/quick-filters.spec.ts
new file mode 100644
index 0000000000..91783e6106
--- /dev/null
+++ b/tests/e2e/tests/logs-explorer/quick-filters.spec.ts
@@ -0,0 +1,22 @@
+import { expect, SEEDED_DATA_TIMEOUT, test } from '../../drivers/logs';
+
+test.describe('Logs Explorer — quick filters rail', () => {
+ test('TC-01 picking a service in the rail narrows the list and writes the expression', async ({
+ logs,
+ logsRail,
+ logsSeed,
+ }) => {
+ await logsRail.ensureSeeded();
+ await logs.goto();
+
+ await logsRail.only('service.name', logsSeed.service);
+
+ await logs.search.expectContains(logsSeed.service);
+ await expect(logs.rowByBody(logsSeed.recent[0])).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(
+ logs.listRows().filter({ hasNotText: logsSeed.marker }),
+ ).toHaveCount(0);
+ });
+});
diff --git a/tests/e2e/tests/logs-explorer/saved-views.spec.ts b/tests/e2e/tests/logs-explorer/saved-views.spec.ts
new file mode 100644
index 0000000000..1e18bc6318
--- /dev/null
+++ b/tests/e2e/tests/logs-explorer/saved-views.spec.ts
@@ -0,0 +1,108 @@
+import { expect, serviceFilter, test } from '../../drivers/logs';
+
+test.describe('Logs Explorer — saved views', () => {
+ test.afterEach(async ({ views }) => {
+ await views.removeByPrefix(views.prefix);
+ });
+
+ test('TC-01 the views list shows a seeded view and selecting it loads the view', async ({
+ logs,
+ logsSeed,
+ views,
+ }) => {
+ const name = views.name('tc01');
+ await views.create(name, { expression: serviceFilter(logsSeed.service) });
+ await logs.goto();
+
+ await views.search(name);
+ await expect(views.row(name)).toBeVisible();
+ await views.pick(name);
+
+ await logs.search.expectContains(logsSeed.service);
+ await expect(logs.rowByBody(logsSeed.recent[0])).toBeVisible();
+ });
+
+ test('TC-02 a view saved from the explorer appears in the views list', async ({
+ logs,
+ logsSeed,
+ views,
+ }) => {
+ const name = views.name('tc02');
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+ await logs.search.apply(
+ `${serviceFilter(logsSeed.service)} AND e2e.kind = 'even'`,
+ );
+
+ await views.saveAs(name);
+
+ expect(await views.names()).toContain(name);
+ await views.clear();
+ await views.pick(name);
+ await logs.search.expectContains("e2e.kind = 'even'");
+ });
+
+ test('TC-03 selecting a view in the explorer loads its query', async ({
+ logs,
+ logsSeed,
+ views,
+ }) => {
+ const odd = views.name('tc03-odd');
+ const even = views.name('tc03-even');
+ const base = serviceFilter(logsSeed.service);
+ await views.create(odd, { expression: `${base} AND e2e.kind = 'odd'` });
+ await views.create(even, { expression: `${base} AND e2e.kind = 'even'` });
+ await logs.gotoUntil(logsSeed.recent[0], { expression: base });
+
+ await views.pick(odd);
+ await logs.search.expectContains("e2e.kind = 'odd'");
+ await expect(logs.rowByBody(logsSeed.recent[1])).toBeVisible();
+ await expect(logs.rowByBody(logsSeed.recent[0])).toHaveCount(0);
+
+ await views.pick(even);
+ await logs.search.expectContains("e2e.kind = 'even'");
+ await expect(logs.rowByBody(logsSeed.recent[0])).toBeVisible();
+ await expect(logs.rowByBody(logsSeed.recent[1])).toHaveCount(0);
+ });
+
+ test('TC-04 renaming a view in the views list persists after a reload', async ({
+ logs,
+ logsSeed,
+ views,
+ }) => {
+ const name = views.name('tc04');
+ const renamed = `${name}-renamed`;
+ await views.create(name, { expression: serviceFilter(logsSeed.service) });
+ await logs.goto();
+ await views.search(name);
+
+ await views.rename(name, renamed);
+
+ await logs.goto();
+ await views.search(name);
+ await expect(views.row(renamed)).toBeVisible();
+ await expect(views.row(name)).toHaveCount(0);
+ const names = await views.names();
+ expect(names).toContain(renamed);
+ expect(names).not.toContain(name);
+ });
+
+ test('TC-05 deleting a view removes it from the views list', async ({
+ logs,
+ logsSeed,
+ views,
+ }) => {
+ const name = views.name('tc05');
+ await views.create(name, { expression: serviceFilter(logsSeed.service) });
+ await logs.goto();
+ await views.search(name);
+
+ await views.remove(name);
+
+ expect(await views.names()).not.toContain(name);
+ await logs.goto();
+ await views.search(name);
+ await expect(views.row(name)).toHaveCount(0);
+ });
+});
diff --git a/tests/e2e/tests/logs-explorer/smoke.spec.ts b/tests/e2e/tests/logs-explorer/smoke.spec.ts
new file mode 100644
index 0000000000..f2c1d676c3
--- /dev/null
+++ b/tests/e2e/tests/logs-explorer/smoke.spec.ts
@@ -0,0 +1,97 @@
+import { expect, serviceFilter, test } from '../../drivers/logs';
+
+test.describe('Logs Explorer — smoke', () => {
+ test('TC-01 the explorer lists the seeded logs', async ({
+ logs,
+ logsSeed,
+ noise,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+
+ await logs.showFrequencyChart();
+ await expect(logs.frequencyChart()).toBeVisible();
+ await expect(
+ logs.listRows().filter({ hasNotText: logsSeed.marker }),
+ ).toHaveCount(0);
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 every list format renders the seeded rows', async ({
+ logs,
+ logsSeed,
+ noise,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+
+ for (const format of ['Raw', 'Default', 'Column'] as const) {
+ // eslint-disable-next-line no-await-in-loop
+ await logs.setFormat(format);
+ // eslint-disable-next-line no-await-in-loop
+ await expect(logs.rowByBody(logsSeed.recent[0])).toBeVisible();
+ }
+ await expect
+ .poll(() => logs.table.headers())
+ .toEqual(expect.arrayContaining(['Timestamp', 'Body']));
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-03 the table view counts the seeded rows', async ({
+ logs,
+ logsSeed,
+ noise,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+ await logs.switchView('Table');
+
+ await expect(logs.queryTableRows()).toHaveCount(1);
+ await expect(logs.queryTableRows().first()).toContainText(
+ String(logsSeed.total),
+ );
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-04 the time series view draws the seeded series', async ({
+ logs,
+ logsSeed,
+ noise,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+ await logs.switchView('Time Series');
+
+ await expect(logs.timeSeriesHeader()).toBeVisible();
+ await expect(logs.timeSeriesGraph()).toBeVisible();
+ await expect(logs.timeSeriesCanvas()).toBeVisible();
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-05 the views list, the pipelines tab and the index-fields page load', async ({
+ logs,
+ pipelines,
+ views,
+ noise,
+ }) => {
+ await logs.goto();
+ await views.openList();
+
+ await logs.openTab('Pipelines');
+ await expect(
+ pipelines.newPipelineButton().or(pipelines.editModeButton()),
+ ).toBeVisible();
+
+ await logs.gotoIndexFields();
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+});
diff --git a/tests/e2e/tests/logs-explorer/toolbar.spec.ts b/tests/e2e/tests/logs-explorer/toolbar.spec.ts
new file mode 100644
index 0000000000..ae5cbb668f
--- /dev/null
+++ b/tests/e2e/tests/logs-explorer/toolbar.spec.ts
@@ -0,0 +1,90 @@
+import {
+ expect,
+ lineBody,
+ serviceFilter,
+ sideService,
+ test,
+} from '../../drivers/logs';
+
+const OLD_OFFSET_MS = -60 * 60_000;
+const FRESH_OFFSET_MS = -60_000;
+
+test.describe('Logs Explorer — toolbar', () => {
+ test('TC-01 Run query applies a typed expression and narrows the list', async ({
+ logs,
+ logsSeed,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+
+ const expression = `${serviceFilter(logsSeed.service)} AND e2e.kind = 'odd'`;
+ await logs.search.apply(expression);
+
+ expect(logs.search.read()).toBe(expression);
+ await expect(logs.rowByBody(lineBody(logsSeed.marker, 23))).toBeVisible();
+ await expect(logs.rowByBody(logsSeed.recent[0])).toHaveCount(0);
+ await expect(logs.rowByBody(logsSeed.old)).toHaveCount(0);
+ await expect
+ .poll(() => logs.visibleTokens(logsSeed.marker))
+ .not.toContainEqual(expect.stringMatching(/line-\d[02468]$/));
+ });
+
+ test('TC-02 the time picker window reaches the query', async ({
+ logs,
+ logsSeed,
+ }) => {
+ // A service of its own: the worker's rows age with the worker, and a
+ // 15 minute window needs rows stamped now.
+ const service = sideService(logsSeed, `tp-${Date.now()}`);
+ const fresh = `${service} fresh`;
+ const old = `${service} old`;
+ await logs.seedRow(service, fresh, FRESH_OFFSET_MS);
+ await logs.seedRow(service, old, OLD_OFFSET_MS);
+
+ await logs.gotoUntil(fresh, {
+ expression: serviceFilter(service),
+ relativeTime: '6h',
+ });
+ await expect(logs.rowByBody(old)).toBeVisible();
+
+ await logs.setTimeRange('15m');
+
+ await expect(logs.rowByBody(old)).toHaveCount(0);
+ await expect(logs.rowByBody(fresh)).toBeVisible();
+ });
+
+ test('TC-03 order by timestamp ascending reverses the rows', async ({
+ logs,
+ logsSeed,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ });
+ await logs.setFormat('Column');
+ await expect
+ .poll(async () => (await logs.visibleTokens(logsSeed.marker))[0])
+ .toBe('json');
+
+ await logs.setOrderBy('timestamp (asc)');
+
+ await expect
+ .poll(async () => (await logs.visibleTokens(logsSeed.marker)).slice(0, 2))
+ .toEqual(['old', 'line-00']);
+ });
+
+ test('TC-04 scrolling past a page loads the next one without duplicates', async ({
+ logs,
+ logsSeed,
+ }) => {
+ await logs.gotoUntil(logsSeed.recent[0], {
+ expression: serviceFilter(logsSeed.service),
+ pageSize: 10,
+ });
+ await logs.setFormat('Column');
+
+ const keys = await logs.collectRowKeys(logsSeed.total);
+
+ expect(keys).toHaveLength(logsSeed.total);
+ });
+});
diff --git a/tests/e2e/tests/logs-pipelines/pipelines.spec.ts b/tests/e2e/tests/logs-pipelines/pipelines.spec.ts
new file mode 100644
index 0000000000..c79f4b9507
--- /dev/null
+++ b/tests/e2e/tests/logs-pipelines/pipelines.spec.ts
@@ -0,0 +1,135 @@
+import {
+ expect,
+ servicePipeline,
+ sideService,
+ test,
+ type LogsSeed,
+} from '../../drivers/logs';
+
+// Pipelines are one org-wide list that every save replaces, so this is the only
+// spec that touches them, and it runs serially.
+test.describe.configure({ mode: 'serial' });
+
+// The backend stores the alias (the name without spaces) as varchar(20).
+const pipelineName = (seed: LogsSeed, tag: string): string =>
+ `pl-${tag}-${seed.service.slice(-6)}`;
+
+test.describe('Logs Pipelines', () => {
+ test.afterEach(async ({ pipelines }) => {
+ await pipelines.reset();
+ });
+
+ test('TC-01 the pipelines page loads empty, then lists a seeded pipeline', async ({
+ logsSeed,
+ pipelines,
+ noise,
+ }) => {
+ await pipelines.reset();
+ await pipelines.goto();
+ await expect(pipelines.emptyState()).toBeVisible();
+ await expect(pipelines.newPipelineButton()).toBeVisible();
+
+ const pipeline = servicePipeline(
+ pipelineName(logsSeed, 'tc01'),
+ logsSeed.service,
+ );
+ await pipelines.seed([pipeline]);
+ await pipelines.goto();
+
+ await expect(pipelines.row(pipeline.name)).toBeVisible();
+ await expect(pipelines.row(pipeline.name)).toContainText(logsSeed.service);
+ await expect(pipelines.editModeButton()).toBeVisible();
+ await pipelines.openChangeHistory();
+ await expect(pipelines.changeHistoryRows().first()).toBeVisible();
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a pipeline built in the UI persists after a reload', async ({
+ logsSeed,
+ pipelines,
+ }) => {
+ const name = pipelineName(logsSeed, 'tc02');
+ await pipelines.reset();
+ await pipelines.goto();
+
+ await pipelines.createThroughUi({
+ name,
+ filter: `service.name = ${logsSeed.service}`,
+ processor: {
+ type: 'Add',
+ name: 'tag',
+ field: 'attributes.e2e_pipeline',
+ value: 'yes',
+ },
+ });
+
+ await pipelines.goto();
+ await expect(pipelines.row(name)).toBeVisible();
+ await pipelines.expand(name);
+ await expect(pipelines.row('tag')).toBeVisible();
+ const saved = await pipelines.latest();
+ expect(saved.map((p) => p.name)).toEqual([name]);
+ expect(saved[0]?.config[0]?.type).toBe('add');
+ });
+
+ test('TC-03 renaming a pipeline persists', async ({ logsSeed, pipelines }) => {
+ const pipeline = servicePipeline(
+ pipelineName(logsSeed, 'tc03'),
+ logsSeed.service,
+ );
+ const renamed = `${pipeline.name}-v2`;
+ await pipelines.seed([pipeline]);
+ await pipelines.goto();
+
+ await pipelines.rename(pipeline.name, renamed);
+
+ await pipelines.goto();
+ await expect(pipelines.row(renamed)).toBeVisible();
+ await expect(pipelines.row(pipeline.name)).toHaveCount(0);
+ expect((await pipelines.latest()).map((p) => p.name)).toEqual([renamed]);
+ });
+
+ test('TC-04 deleting a pipeline persists', async ({ logsSeed, pipelines }) => {
+ const first = servicePipeline(
+ pipelineName(logsSeed, 'tc04-a'),
+ logsSeed.service,
+ 1,
+ );
+ const second = servicePipeline(
+ pipelineName(logsSeed, 'tc04-b'),
+ logsSeed.service,
+ 2,
+ );
+ await pipelines.seed([first, second]);
+ await pipelines.goto();
+
+ await pipelines.remove(first.name);
+
+ await pipelines.goto();
+ await expect(pipelines.row(first.name)).toHaveCount(0);
+ await expect(pipelines.row(second.name)).toBeVisible();
+ expect((await pipelines.latest()).map((p) => p.name)).toEqual([second.name]);
+ });
+
+ test('TC-05 the preview simulates the pipeline against seeded logs', async ({
+ logs,
+ logsSeed,
+ pipelines,
+ }) => {
+ // Fresh rows of their own: the preview samples the last hour only.
+ const service = sideService(logsSeed, `pl-${Date.now()}`);
+ const sample = `${service} sample`;
+ await logs.seedRow(service, sample, -30_000);
+ const pipeline = servicePipeline(pipelineName(logsSeed, 'tc05'), service);
+ await pipelines.seed([pipeline]);
+ await pipelines.goto();
+
+ await pipelines.openPreviewUntil(pipeline.name, sample);
+ await pipelines.simulate();
+
+ await expect(pipelines.previewOutput().first()).toContainText(sample);
+ await pipelines.expandFirstOutput();
+ await expect(pipelines.outputDetail()).toContainText('e2e_pipeline');
+ });
+});
diff --git a/tests/e2e/tests/messaging-queues/celery.spec.ts b/tests/e2e/tests/messaging-queues/celery.spec.ts
new file mode 100644
index 0000000000..80ccbc4cc3
--- /dev/null
+++ b/tests/e2e/tests/messaging-queues/celery.spec.ts
@@ -0,0 +1,39 @@
+import { expect, test } from '../../drivers/messaging-queues';
+
+test.describe('Messaging queues, celery', () => {
+ test('TC-01 celery page draws span-based stats for the seeded task', async ({
+ mq,
+ mqSeed,
+ noise,
+ }) => {
+ await mq.gotoCelery();
+ await mq.pickTask(mqSeed.task);
+
+ await expect(mq.celeryGridSection('Span Based Stats')).toBeVisible();
+ await expect(mq.celeryGridSection('Flower Metrics')).toBeVisible();
+ await expect(mq.celeryGridChart()).toBeVisible();
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 state tabs count the seeded task by state', async ({
+ mq,
+ mqSeed,
+ }) => {
+ await mq.gotoCeleryTask(mqSeed.task, 'failed', mqSeed.states.failed);
+
+ await expect(mq.celeryStateTab('all')).toHaveText(
+ new RegExp(`\\D${mqSeed.states.all}$`),
+ );
+ await expect(mq.celeryStateTab('successful')).toHaveText(
+ new RegExp(`\\D${mqSeed.states.successful}$`),
+ );
+ await expect(mq.celeryStateTab('retry')).toHaveText(
+ new RegExp(`\\D${mqSeed.states.retry}$`),
+ );
+
+ await mq.selectCeleryState('failed');
+ await expect(mq.celeryGridChart()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/messaging-queues/kafka.spec.ts b/tests/e2e/tests/messaging-queues/kafka.spec.ts
new file mode 100644
index 0000000000..776da58a3c
--- /dev/null
+++ b/tests/e2e/tests/messaging-queues/kafka.spec.ts
@@ -0,0 +1,121 @@
+import { expect, KAFKA_VIEWS, test } from '../../drivers/messaging-queues';
+
+test.describe('Messaging queues, kafka', () => {
+ test('TC-01 kafka page renders its view cards and the health check', async ({
+ mq,
+ noise,
+ }) => {
+ await mq.gotoKafka();
+
+ await expect(mq.viewDetailsButtons()).toHaveCount(KAFKA_VIEWS.length);
+ await mq.openHealthCheck();
+ await expect(mq.healthCheckSection('Consumers')).toBeVisible();
+ await expect(mq.healthCheckSection('Producers')).toBeVisible();
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a view card opens its detail view', async ({ mq }) => {
+ await mq.gotoKafka();
+ await mq.viewDetails('producerLatency');
+
+ await expect(mq.viewSelect()).toContainText('Producer Latency view');
+ await expect(mq.producerLatencyToggle()).toBeVisible();
+ });
+
+ test('TC-03 producer latency lists the seeded topic and switches to consumers', async ({
+ mq,
+ mqSeed,
+ }) => {
+ await mq.gotoKafkaDetail('producerLatency');
+ await mq.waitForTableRow(mq.table('overview'), mqSeed.topic);
+
+ await expect(mq.producerLatencyOption('Producers')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(mq.tableRow(mq.table('overview'), mqSeed.topic)).toContainText(
+ mqSeed.producer,
+ );
+
+ await mq.producerLatencyOption('Consumers').click();
+ await expect(mq.producerLatencyOption('Consumers')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ const consumerRow = mq.tableRow(mq.table('overview'), mqSeed.topic);
+ await expect(consumerRow).toContainText(mqSeed.consumer);
+ // `ingestion_rate` is the consumer query's own column.
+ await expect(
+ mq.tableHeader(mq.table('overview'), 'Ingestion Rate'),
+ ).toBeVisible();
+ });
+
+ test('TC-04 partition latency lists partition 0 and its consumer group', async ({
+ mq,
+ mqSeed,
+ }) => {
+ await mq.gotoKafkaDetail('partitionLatency');
+ await mq.waitForTableRow(mq.table('overview'), mqSeed.topic);
+
+ const row = mq.tableRow(mq.table('overview'), mqSeed.topic);
+ await expect(row).toContainText(mqSeed.partition);
+ await row.click();
+ await expect(mq.table('detail')).toBeVisible();
+
+ await mq.detailType('consumer-details').click();
+ await expect(mq.tableRow(mq.table('detail'), mqSeed.group)).toContainText(
+ mqSeed.consumer,
+ );
+ });
+
+ test('TC-05 drop rate evaluates the seeded producer to consumer pair', async ({
+ mq,
+ mqSeed,
+ }) => {
+ test.skip(
+ true,
+ 'stack limitation: /kafka/span/evaluation answers 400 "span evaluation feature is disabled" until the stack starts with SIGNOZ_FLAGGER_CONFIG_BOOLEAN_KAFKA__SPAN__EVAL=true',
+ );
+ await mq.gotoKafkaDetail('dropRate');
+ await mq.waitForTableRow(mq.dropRateTable(), mqSeed.producer);
+
+ await expect(mq.tableRow(mq.dropRateTable(), mqSeed.producer)).toContainText(
+ mqSeed.consumer,
+ );
+ });
+
+ test('TC-06 consumer lag draws the seeded gauge and its point details', async ({
+ mq,
+ mqSeed,
+ }) => {
+ test.skip(
+ true,
+ 'stack limitation: the graph runs the legacy metrics query (__normalized = false) and the seeder writes __normalized = true series, so the result is empty',
+ );
+ await mq.gotoConsumerLagPoint(mqSeed);
+
+ await expect(mq.consumerLagChart()).toBeVisible();
+ await expect(mq.consumerLagNoData()).toBeHidden();
+
+ // The deep-linked timeline point stands in for a canvas click.
+ await mq.waitForTableRow(mq.table('detail'), mqSeed.producer);
+ await mq.detailType('consumer-details').click();
+ await expect(mq.detailType('consumer-details')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(mq.tableRow(mq.table('detail'), mqSeed.consumer)).toBeVisible();
+ });
+
+ test('TC-07 metric view renders its sections', async ({ mq, noise }) => {
+ await mq.gotoKafkaDetail('metricPage');
+
+ await expect(mq.metricPageSection('Broker JVM Metrics')).toBeVisible();
+ await expect(mq.metricPageSection('Partition Metrics')).toBeVisible();
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+});
diff --git a/tests/e2e/tests/messaging-queues/overview.spec.ts b/tests/e2e/tests/messaging-queues/overview.spec.ts
new file mode 100644
index 0000000000..ae693b4d7f
--- /dev/null
+++ b/tests/e2e/tests/messaging-queues/overview.spec.ts
@@ -0,0 +1,41 @@
+import { expect, test } from '../../drivers/messaging-queues';
+
+test.describe('Messaging queues, overview', () => {
+ test('TC-01 overview lists the seeded kafka and celery spans', async ({
+ mq,
+ mqSeed,
+ noise,
+ }) => {
+ await mq.waitForOverviewRow(mqSeed.producer, `${mqSeed.topic} publish`);
+
+ const producer = mq.overviewRow(mqSeed.producer, `${mqSeed.topic} publish`);
+ await expect(producer).toHaveCount(1);
+ await expect(producer).toContainText('kafka');
+ await expect(producer).toContainText(mqSeed.topic);
+ await expect(producer).toContainText('Producer');
+
+ const consumer = mq.overviewRow(mqSeed.consumer, `${mqSeed.topic} process`);
+ await expect(consumer).toContainText('Consumer');
+
+ const celery = mq.overviewRow(mqSeed.celeryService, mqSeed.taskSpan);
+ await expect(celery).toHaveCount(1);
+ await expect(celery).toContainText('celery');
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 an overview row opens its details drawer', async ({
+ mq,
+ mqSeed,
+ }) => {
+ const span = `${mqSeed.topic} publish`;
+ await mq.waitForOverviewRow(mqSeed.producer, span);
+ await mq.openOverviewRow(mqSeed.producer, span);
+
+ const drawer = mq.overviewDrawer();
+ await expect(drawer).toContainText(mqSeed.producer);
+ await expect(drawer).toContainText(span);
+ await expect(mq.overviewDrawerMetric('Request Rate')).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/meter/meter.spec.ts b/tests/e2e/tests/meter/meter.spec.ts
new file mode 100644
index 0000000000..3c67352770
--- /dev/null
+++ b/tests/e2e/tests/meter/meter.spec.ts
@@ -0,0 +1,72 @@
+import { expect, test } from '../../drivers/meter';
+
+// The cost meter on a stack with no meter data: nothing writes
+// `signoz_meter.*` here, so these are empty-state smokes. The short-window
+// notice, the billing notice and the hidden Create Alert / Add to Dashboard
+// buttons are jest candidates.
+
+test.describe('Meter', () => {
+ test('TC-01 the breakdown page renders its sections with no data (smoke)', async ({
+ meter,
+ noise,
+ }) => {
+ const responses = await meter.breakdown.goto();
+
+ for (const section of ['total', 'logs', 'traces', 'metrics'] as const) {
+ await expect(meter.breakdown.section(section)).toBeVisible();
+ }
+ expect(responses.filter((res) => !res.ok()).map((res) => res.url())).toEqual(
+ [],
+ );
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 the meter explorer shows the pre-query empty state and an empty metric list', async ({
+ meter,
+ }) => {
+ const { explorer } = meter;
+ const listed = meter.nextMetricList();
+ await explorer.goto();
+
+ expect((await listed).ok()).toBe(true);
+ await expect(explorer.emptyState()).toBeVisible();
+ await expect(await explorer.openMetricOptions()).toHaveCount(0);
+ await expect(explorer.createAlertButton()).toHaveCount(0);
+ await expect(explorer.addToDashboardButton()).toHaveCount(0);
+ });
+
+ test('TC-03 a seeded meter view is listed and opens in the meter explorer', async ({
+ authedPage: page,
+ meter,
+ }) => {
+ const { explorer, views } = meter;
+ const prefix = `e2e-meter-view-${Date.now()}`;
+ const name = `${prefix}-a`;
+ await views.create(name, {
+ expression: '',
+ panelType: 'graph',
+ spec: {
+ aggregations: [
+ {
+ metricName: 'signoz.meter.log.size',
+ timeAggregation: 'increase',
+ spaceAggregation: 'sum',
+ },
+ ],
+ },
+ });
+
+ try {
+ await explorer.goto();
+ await views.search(name);
+ await expect(views.row(name)).toBeVisible();
+
+ await views.pick(name);
+ await expect(page).toHaveURL(/\/meter\/explorer\?/);
+ } finally {
+ await views.removeByPrefix(prefix);
+ }
+ });
+});
diff --git a/tests/e2e/tests/metrics-explorer/explorer.spec.ts b/tests/e2e/tests/metrics-explorer/explorer.spec.ts
new file mode 100644
index 0000000000..af46736980
--- /dev/null
+++ b/tests/e2e/tests/metrics-explorer/explorer.spec.ts
@@ -0,0 +1,153 @@
+import {
+ allowFor,
+ expect,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ test,
+} from '../../drivers/metrics';
+
+// The metrics query explorer against metrics this worker seeded. Switch, unit
+// and empty-state logic are jest (Explorer/__tests__); the add-to-dashboard
+// dialog wiring is ExplorerActions/__tests__. This spec keeps the round trips.
+
+test.describe('Metrics explorer', () => {
+ test.beforeEach(() => {
+ allowFor(SEEDED_TEST_BUDGET);
+ });
+
+ test('TC-01 picking a metric and running plots real data (smoke)', async ({
+ metricsExplorer: explorer,
+ metricsCatalog: seed,
+ noise,
+ }) => {
+ await explorer.goto();
+ await explorer.pickMetric(seed.gauge);
+ const response = await explorer.run();
+
+ expect(response.ok()).toBe(true);
+ expect(response.request().postData() ?? '').toContain(seed.gauge);
+ await expect(explorer.firstChartCanvas()).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(explorer.noData()).toHaveCount(0);
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 group by splits the legend into the seeded services', async ({
+ metricsExplorer: explorer,
+ metricsCatalog: seed,
+ }) => {
+ await explorer.goto();
+ await explorer.pickMetric(seed.gauge);
+ await explorer.groupBy('service.name');
+ await explorer.run();
+
+ await expect(async () => {
+ const labels = await explorer.legendLabels();
+ for (const service of seed.services) {
+ expect(labels.some((label) => label.includes(service))).toBe(true);
+ }
+ }).toPass({ timeout: SEEDED_DATA_TIMEOUT });
+ });
+
+ test('TC-03 Add to Dashboard lands in the panel editor with the query, and saving puts the panel on the dashboard', async ({
+ authedPage: page,
+ metricsExplorer: explorer,
+ metricsCatalog: seed,
+ }) => {
+ const { dashboards, panelEditor } = explorer;
+ const dashboard = await explorer.seedDashboard(
+ `e2e-mx-export-${seed.run}-${Date.now()}`,
+ );
+
+ try {
+ await explorer.goto();
+ await explorer.pickMetric(seed.gauge);
+ await explorer.run();
+ await explorer.addToDashboard(dashboard.title);
+
+ await expect(page).toHaveURL(
+ new RegExp(`/dashboard/${dashboard.id}/panel/`),
+ );
+ await expect(panelEditor.query.metricInput()).toHaveValue(seed.gauge);
+ await expect(panelEditor.preview.chart.plotArea()).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+
+ const patches = panelEditor.capturePatches();
+ await panelEditor.save();
+ expect(
+ patches
+ .flat()
+ .some((op) => op.op === 'add' && /^\/spec\/panels\/[^/]+$/.test(op.path)),
+ ).toBe(true);
+
+ await expect
+ .poll(async () =>
+ Object.keys((await dashboards.get(dashboard.id)).spec.panels),
+ )
+ .toHaveLength(1);
+ const panels = Object.values(
+ (await dashboards.get(dashboard.id)).spec.panels,
+ );
+ expect(panels[0].spec.queries?.[0]).toMatchObject({
+ spec: {
+ plugin: {
+ kind: 'signoz/CompositeQuery',
+ spec: {
+ queries: [
+ {
+ type: 'builder_query',
+ spec: { aggregations: [{ metricName: seed.gauge }] },
+ },
+ ],
+ },
+ },
+ },
+ });
+ } finally {
+ await explorer.removeDashboard(dashboard.id);
+ }
+ });
+
+ test('TC-04 Save view round trips through the views list', async ({
+ metricsExplorer: explorer,
+ metricsCatalog: seed,
+ savedViews,
+ }) => {
+ const prefix = `e2e-mx-view-${seed.run}`;
+ const name = `${prefix}-${Date.now()}`;
+
+ try {
+ await explorer.goto();
+ await explorer.pickMetric(seed.gauge);
+ await explorer.run();
+ await savedViews.saveAs(name);
+
+ await savedViews.clear();
+ await expect(explorer.metricInput()).not.toHaveValue(seed.gauge);
+
+ await savedViews.pick(name);
+ await expect(explorer.metricInput()).toHaveValue(seed.gauge);
+ } finally {
+ await savedViews.removeByPrefix(prefix);
+ }
+ });
+
+ test('TC-05 Create an Alert hands the query to the alert form', async ({
+ metricsExplorer: explorer,
+ metricsCatalog: seed,
+ }) => {
+ await explorer.goto();
+ await explorer.pickMetric(seed.gauge);
+ await explorer.run();
+ await explorer.createAlert();
+
+ expect(explorer.compositeQueryFromUrl()).toContain(seed.gauge);
+ await expect(explorer.metricInput()).toHaveValue(seed.gauge, {
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ });
+});
diff --git a/tests/e2e/tests/metrics-explorer/summary.spec.ts b/tests/e2e/tests/metrics-explorer/summary.spec.ts
new file mode 100644
index 0000000000..c969f8f2c4
--- /dev/null
+++ b/tests/e2e/tests/metrics-explorer/summary.spec.ts
@@ -0,0 +1,286 @@
+import {
+ allowFor,
+ expect,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ test,
+} from '../../drivers/metrics';
+
+// The summary tab against metrics this worker seeded. Loading, error and empty
+// states, and the table's own callbacks, are jest (Summary/__tests__); what is
+// left is a real stats/treemap/metadata response reaching the DOM.
+
+test.describe('Metrics explorer summary', () => {
+ test.beforeEach(() => {
+ allowFor(SEEDED_TEST_BUDGET);
+ });
+
+ test('TC-01 summary loads seeded metrics in the list and treemap, with no console noise', async ({
+ metrics,
+ metricsCatalog: seed,
+ noise,
+ }) => {
+ await metrics.gotoSummary();
+ const stats = metrics.nextStatsRequest(
+ (body) => body.filter?.expression === seed.scope,
+ );
+ await metrics.scopeTo(seed.scope);
+ expect((await stats).filter?.expression).toBe(seed.scope);
+ await metrics.waitForRows([seed.gauge, seed.sum]);
+
+ await expect(metrics.cell(seed.gauge, 'TYPE')).toHaveText('Gauge');
+ await expect(metrics.cell(seed.gauge, 'UNIT')).toHaveText('Bytes (B)');
+ await expect(metrics.cell(seed.gauge, 'DESCRIPTION')).toHaveText('e2e gauge');
+ await expect(metrics.cell(seed.gauge, 'TIME SERIES')).toHaveText('3');
+ await expect(metrics.cell(seed.sum, 'TYPE')).toHaveText('Sum');
+ await expect(metrics.cell(seed.sum, 'DESCRIPTION')).toHaveText('-');
+
+ await expect(metrics.treemap()).toBeVisible();
+ for (const tab of ['Summary', 'Explorer'] as const) {
+ await expect(metrics.tab(tab)).toBeVisible();
+ }
+
+ // Known defect: parser/analyzeQuery.ts keeps antlr's default console
+ // listener, so each half-typed expression logs `line 1:N ...`.
+ expect(noise.errors.filter((e) => !/^line \d+:\d+ /.test(e))).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a resource-attribute filter narrows the list through the API', async ({
+ metrics,
+ metricsCatalog: seed,
+ }) => {
+ const expression = `service.name = '${seed.services[0]}'`;
+ await metrics.gotoSummary();
+ const stats = metrics.nextStatsRequest(
+ (body) => body.filter?.expression === expression,
+ );
+ await metrics.scopeTo(expression);
+
+ expect((await stats).filter?.expression).toBe(expression);
+ await metrics.waitForRows([seed.gauge]);
+ await expect(metrics.row(seed.sum)).toHaveCount(0);
+ await metrics.search().expectExpression(expression);
+ });
+
+ test('TC-03 sort and page size reach the stats request', async ({
+ authedPage: page,
+ metrics,
+ metricsCatalog: seed,
+ }) => {
+ const names = [seed.gauge, seed.sum];
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seed.scope);
+ await metrics.waitForRows(names);
+
+ // antd cycles an unsorted column to ascend first, then descend.
+ const ascending = metrics.nextStatsRequest(
+ (body) =>
+ body.orderBy?.key?.name === 'timeseries' &&
+ body.orderBy.direction === 'asc',
+ );
+ await metrics.sortBy('TIME SERIES');
+ await ascending;
+ await expect
+ .poll(() => metrics.rowOrder(names))
+ .toEqual([seed.sum, seed.gauge]);
+
+ const descending = metrics.nextStatsRequest(
+ (body) =>
+ body.orderBy?.key?.name === 'timeseries' &&
+ body.orderBy.direction === 'desc',
+ );
+ await metrics.sortBy('TIME SERIES');
+ await descending;
+ await expect
+ .poll(() => metrics.rowOrder(names))
+ .toEqual([seed.gauge, seed.sum]);
+
+ const resized = metrics.nextStatsRequest((body) => body.limit === 20);
+ await metrics.setPageSize(20);
+ expect((await resized).offset).toBe(0);
+
+ await page.reload();
+ expect(await metrics.storedPageSize()).toBe(20);
+ });
+
+ test('TC-04 a row opens the details drawer with real highlights and attributes, and a deep link restores it', async ({
+ authedPage: page,
+ metrics,
+ metricsCatalog: seed,
+ }) => {
+ const { details } = metrics;
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seed.scope);
+ await metrics.openDetails(seed.gauge);
+
+ await expect(details.timeSeries()).toContainText('3 total');
+ await expect(details.lastReceived()).not.toHaveText('-');
+ await expect(details.attributeKey('host')).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(details.attributeKey('service.name')).toBeVisible();
+ await expect(details.attributeValue('host', 'h1')).toBeVisible();
+
+ await details.attributesSearch('host');
+ await expect(details.attributeKey('service.name')).toHaveCount(0);
+ await expect(details.attributeKey('host')).toBeVisible();
+
+ await expect(page).toHaveURL(/isMetricDetailsOpen=true/);
+ expect(new URL(page.url()).searchParams.get('selectedMetricName')).toBe(
+ seed.gauge,
+ );
+
+ await page.reload();
+ await expect(details.title()).toHaveText(seed.gauge);
+
+ await metrics.closeDetails();
+ });
+
+ test('TC-05 editing metadata persists across a reload', async ({
+ authedPage: page,
+ metrics,
+ }) => {
+ const { metadata } = metrics;
+ const seeded = await metrics.seedMetric({
+ prefix: 'e2e_mx_meta',
+ type: 'Sum',
+ temporality: 'Cumulative',
+ });
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seeded.scope);
+ await metrics.waitForRows([seeded.name]);
+ await metrics.openDetails(seeded.name);
+
+ await metadata.edit();
+ await metadata.setDescription('e2e edited');
+ await metadata.setUnit('Bytes (B)');
+ await metadata.setTemporality('Delta');
+ const saved = await metadata.save();
+
+ expect(saved.response.ok()).toBe(true);
+ expect(saved.body).toMatchObject({
+ metricName: seeded.name,
+ description: 'e2e edited',
+ unit: 'By',
+ temporality: 'delta',
+ });
+ await expect(metrics.toast('Metadata updated successfully')).toBeVisible();
+
+ await page.reload();
+ await expect(metadata.value('description')).toHaveText('e2e edited');
+ expect((await metrics.metadataFromApi(seeded.name)).description).toBe(
+ 'e2e edited',
+ );
+
+ await metrics.closeDetails();
+ await metrics.search().run();
+ await expect(metrics.cell(seeded.name, 'DESCRIPTION')).toHaveText(
+ 'e2e edited',
+ );
+ });
+
+ test('TC-06 a backend validation error surfaces in the toast and keeps edit mode', async ({
+ metrics,
+ }) => {
+ const { metadata } = metrics;
+ const seeded = await metrics.seedMetric({
+ prefix: 'e2e_mx_invalid',
+ type: 'Sum',
+ temporality: 'Unspecified',
+ });
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seeded.scope);
+ await metrics.waitForRows([seeded.name]);
+ await metrics.openDetails(seeded.name);
+
+ await metadata.edit();
+ await metadata.setDescription('e2e rejected');
+ const saved = await metadata.save();
+
+ expect(saved.response.status()).toBe(400);
+ await expect(metrics.toast(/temporality/)).toBeVisible();
+ await expect(metadata.saveButton()).toBeVisible();
+ expect((await metrics.metadataFromApi(seeded.name)).description).not.toBe(
+ 'e2e rejected',
+ );
+ });
+
+ test('TC-07 Open in Explorer carries the metric into the explorer and plots it', async ({
+ metrics,
+ metricsExplorer,
+ metricsCatalog: seed,
+ }) => {
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seed.scope);
+ await metrics.openDetails(seed.gauge);
+
+ const plotted = metricsExplorer.nextQueryFor(seed.gauge);
+ await metrics.details.openInExplorer();
+
+ expect((await plotted).ok()).toBe(true);
+ await expect(metricsExplorer.metricInput()).toHaveValue(seed.gauge);
+ await expect(metricsExplorer.firstChartCanvas()).toBeVisible();
+ });
+
+ test('TC-08 Inspect a gauge shows its real series', async ({
+ authedPage: page,
+ metrics,
+ metricsCatalog: seed,
+ }) => {
+ const inspect = metrics.inspectDrawer;
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seed.scope);
+ await metrics.openDetails(seed.gauge);
+ await metrics.details.inspect();
+
+ await expect(inspect.seriesCount()).toHaveText('3 time series', {
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(inspect.empty()).toHaveCount(0);
+ await expect(page).toHaveURL(/isInspectModalOpen=true/);
+
+ await inspect.toggleView();
+ await expect(inspect.viewLabel('Table View')).toBeVisible();
+ });
+
+ // The stats and treemap APIs drop every `signoz*` metric, so the golden
+ // dataset never reaches the treemap; the scoped seed does.
+ test('TC-09 treemap mode switch and tile click', async ({
+ metrics,
+ metricsCatalog: seed,
+ }) => {
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seed.scope);
+ await metrics.waitForRows([seed.gauge]);
+
+ const treemap = metrics.nextTreemapRequest(
+ (body) =>
+ body.mode === 'timeseries' && body.filter?.expression === seed.scope,
+ );
+ await metrics.setTreemapMode('Time Series');
+ expect((await treemap).mode).toBe('timeseries');
+
+ await expect(metrics.tile(seed.gauge)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await metrics.tile(seed.gauge).click();
+ await expect(metrics.details.title()).toHaveText(seed.gauge);
+ });
+
+ test('TC-10 the METRIC column search adds a CONTAINS filter', async ({
+ metrics,
+ metricsCatalog: seed,
+ }) => {
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seed.scope);
+ await metrics.waitForRows([seed.gauge, seed.sum]);
+
+ await metrics.searchMetricName(seed.gauge);
+
+ await metrics.search().expectContains('metric_name contains');
+ await metrics.search().expectContains(seed.gauge);
+ await expect(metrics.row(seed.gauge)).toBeVisible();
+ await expect(metrics.row(seed.sum)).toHaveCount(0);
+ });
+});
diff --git a/tests/e2e/tests/metrics-explorer/views.spec.ts b/tests/e2e/tests/metrics-explorer/views.spec.ts
new file mode 100644
index 0000000000..e78bed608a
--- /dev/null
+++ b/tests/e2e/tests/metrics-explorer/views.spec.ts
@@ -0,0 +1,74 @@
+import { expect, test } from '../../drivers/metrics';
+
+// The metrics explorer's views list over views seeded through the API. Search,
+// edit and delete component behaviour is jest (container/SavedViews/__tests__);
+// the API lifecycle is tests/integration/tests/savedview. This spec keeps one
+// real round trip.
+
+const gaugeAverage = (metricName: string): Record<string, unknown> => ({
+ aggregations: [
+ { metricName, timeAggregation: 'avg', spaceAggregation: 'avg' },
+ ],
+});
+
+test.describe('Metrics explorer views', () => {
+ test('TC-01 the views list shows a seeded view (smoke)', async ({
+ metricsExplorer: explorer,
+ metricsCatalog: seed,
+ savedViews,
+ noise,
+ }) => {
+ const prefix = `e2e-mx-views-${seed.run}-list`;
+ const name = `${prefix}-${Date.now()}`;
+ await savedViews.create(name, {
+ expression: seed.scope,
+ panelType: 'graph',
+ spec: gaugeAverage(seed.gauge),
+ });
+
+ try {
+ await explorer.goto();
+ await savedViews.search(name);
+ await expect(savedViews.row(name)).toBeVisible();
+
+ await savedViews.search(`${name}-no-such-view`);
+ await expect(savedViews.row(name)).toHaveCount(0);
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ } finally {
+ await savedViews.removeByPrefix(prefix);
+ }
+ });
+
+ test('TC-02 rename and delete persist through the API', async ({
+ authedPage: page,
+ metricsExplorer: explorer,
+ metricsCatalog: seed,
+ savedViews,
+ }) => {
+ const prefix = `e2e-mx-views-${seed.run}-edit`;
+ const name = `${prefix}-${Date.now()}`;
+ const renamed = `${name}-renamed`;
+ const id = await savedViews.create(name, {
+ expression: seed.scope,
+ panelType: 'graph',
+ spec: gaugeAverage(seed.gauge),
+ });
+
+ try {
+ await explorer.goto();
+ await savedViews.search(name);
+ await savedViews.rename(name, renamed);
+
+ await page.reload();
+ await savedViews.search(renamed);
+ await expect(savedViews.row(renamed)).toBeVisible();
+
+ await savedViews.remove(renamed);
+ expect((await savedViews.list()).map((view) => view.id)).not.toContain(id);
+ } finally {
+ await savedViews.removeByPrefix(prefix);
+ }
+ });
+});
diff --git a/tests/e2e/tests/metrics-explorer/volume-control.spec.ts b/tests/e2e/tests/metrics-explorer/volume-control.spec.ts
new file mode 100644
index 0000000000..b0a712d8aa
--- /dev/null
+++ b/tests/e2e/tests/metrics-explorer/volume-control.spec.ts
@@ -0,0 +1,94 @@
+import { expect, SEEDED_DATA_TIMEOUT, test } from '../../drivers/metrics';
+
+// Volume control needs `enable_metrics_reduction`, which `e2e_env` in
+// bootstrap/conftest.py turns on. A stack started without it skips rather than fails. Reduction
+// semantics are tests/integration/tests/metricreduction; this spec keeps what
+// the tab and the details drawer write and read back.
+
+test.describe('Metrics explorer volume control', () => {
+ test.beforeEach(async ({ volumeControl }) => {
+ test.skip(
+ !(await volumeControl.available()),
+ 'enable_metrics_reduction is off on this stack',
+ );
+ });
+
+ test.afterEach(async ({ volumeControl, metricsCatalog: seed }) => {
+ await volumeControl.removeRulesFor(seed.gauge);
+ });
+
+ test('TC-01 the tab lists a seeded rule as pending (smoke)', async ({
+ volumeControl: vc,
+ metricsCatalog: seed,
+ noise,
+ }) => {
+ await vc.seedRule(seed.gauge, 'keep', ['service.name']);
+
+ await vc.gotoTab();
+ await vc.search(seed.gauge);
+
+ await expect(vc.stats()).toBeVisible();
+ await expect(vc.mode(seed.gauge)).toHaveText('Include');
+ await expect(vc.badge(seed.gauge, 'pending')).toBeVisible();
+ await expect(vc.chart()).toBeVisible();
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a rule created from the details drawer shows as pending in both places', async ({
+ metrics,
+ volumeControl: vc,
+ metricsCatalog: seed,
+ }) => {
+ await metrics.gotoSummary();
+ await metrics.scopeTo(seed.scope);
+ await metrics.openDetails(seed.gauge);
+
+ await vc.section.setup();
+ await vc.drawer.mode('include');
+ await vc.drawer.pickLabels(['service.name']);
+ await expect(vc.drawer.impact()).toContainText('Potential retained', {
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+
+ const saved = await vc.drawer.save();
+ expect(saved.request().method()).toBe('POST');
+ expect(saved.ok()).toBe(true);
+ expect(saved.request().postDataJSON()).toEqual({
+ metricName: seed.gauge,
+ matchType: 'keep',
+ labels: ['service.name'],
+ });
+ await expect(vc.toast('Volume control rule saved')).toBeVisible();
+ await expect(vc.section.pendingBanner()).toBeVisible();
+
+ await vc.gotoTab();
+ await vc.search(seed.gauge);
+ await expect(vc.badge(seed.gauge, 'pending')).toBeVisible();
+ });
+
+ test('TC-03 managing from the tab updates and removes the rule', async ({
+ volumeControl: vc,
+ metricsCatalog: seed,
+ }) => {
+ await vc.reseedGauge(seed);
+ await vc.seedRule(seed.gauge, 'keep', ['service.name']);
+ await vc.gotoTab();
+ await vc.search(seed.gauge);
+
+ await vc.manage(seed.gauge);
+ await vc.drawer.mode('exclude');
+ await vc.drawer.pickLabels(['host']);
+ const updated = await vc.drawer.save();
+ expect(updated.request().method()).toBe('PUT');
+ expect(updated.ok()).toBe(true);
+ await expect(vc.mode(seed.gauge)).toHaveText('Exclude');
+
+ await vc.manage(seed.gauge);
+ const removed = await vc.drawer.remove();
+ expect(removed.ok()).toBe(true);
+ await expect(vc.toast('Volume control rule removed')).toBeVisible();
+ await expect(vc.empty()).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/onboarding/get-started.spec.ts b/tests/e2e/tests/onboarding/get-started.spec.ts
new file mode 100644
index 0000000000..f7112bb87d
--- /dev/null
+++ b/tests/e2e/tests/onboarding/get-started.spec.ts
@@ -0,0 +1,56 @@
+import { expect, GET_STARTED_PATH, test } from '../../drivers/onboarding';
+
+test.describe('get started wizard', () => {
+ // The wizard renders every source logo on load, which is slow on a shared stack.
+ test.describe.configure({ timeout: 60_000 });
+
+ test('TC-05 a searched source walks to its docs and Continue opens its module', async ({
+ onboarding,
+ }) => {
+ const { wizard } = onboarding;
+ await onboarding.visit(GET_STARTED_PATH);
+
+ await wizard.search('python');
+ await expect(wizard.source('Syslogs')).toHaveCount(0);
+ await wizard.source('Python').click();
+ await wizard.option('VM').click();
+ await wizard.configure().click();
+
+ await expect(wizard.docsFrame()).toHaveAttribute(
+ 'src',
+ /\/docs\/instrumentation\/opentelemetry-python\/\?.*source=onboarding.*environment=vm/,
+ );
+ await wizard.continue().click();
+ await onboarding.expectPath('/services');
+ });
+
+ test('TC-08 a search with no match offers to raise a request', async ({
+ onboarding,
+ }) => {
+ const { wizard } = onboarding;
+ await onboarding.visit(GET_STARTED_PATH);
+
+ await wizard.search('zzzz');
+ await expect(wizard.noResults()).toHaveText('No results for zzzz :/');
+ });
+
+ test('TC-09 the invite modal sends an invite and closes', async ({
+ onboarding,
+ }) => {
+ const { wizard } = onboarding;
+ const email = `e2e-onboarding-modal-${Date.now()}@signoz.test`;
+ await onboarding.visit(GET_STARTED_PATH);
+
+ try {
+ await wizard.inviteButton().click();
+ await expect(wizard.inviteModal()).toBeVisible();
+ await wizard.invite([{ email, role: 'signoz-viewer' }]);
+
+ await expect(onboarding.toast('Invites sent successfully')).toBeVisible();
+ await expect(wizard.inviteModal()).toBeHidden();
+ expect(await onboarding.users.byEmail(email)).toBeDefined();
+ } finally {
+ await onboarding.users.remove(email);
+ }
+ });
+});
diff --git a/tests/e2e/tests/onboarding/questionnaire.spec.ts b/tests/e2e/tests/onboarding/questionnaire.spec.ts
new file mode 100644
index 0000000000..ca03e88e5e
--- /dev/null
+++ b/tests/e2e/tests/onboarding/questionnaire.spec.ts
@@ -0,0 +1,167 @@
+import {
+ expect,
+ GET_STARTED_PATH,
+ ONBOARDING_PATH,
+ test,
+} from '../../drivers/onboarding';
+
+const DISCOVERY = 'A colleague recommended it';
+
+test.describe('onboarding questionnaire', () => {
+ // Each test walks up to four steps and two full page loads.
+ test.describe.configure({ timeout: 90_000 });
+
+ test('TC-01 a first-run admin is sent to /onboarding, finishes all four steps and is not sent back', async ({
+ onboarding,
+ }) => {
+ const run = await onboarding.stubFirstRun();
+ const { questionnaire: q } = onboarding;
+
+ await onboarding.visit('/home');
+ await onboarding.expectPath(ONBOARDING_PATH);
+
+ await expect(q.heading('Welcome to SigNoz Cloud')).toBeVisible();
+ await q.answerOrg({
+ tool: 'DataDog',
+ timeline: 'Less than a month',
+ usesOtel: true,
+ });
+ await q.next().click();
+
+ await expect(q.discovery()).toBeVisible();
+ await q.answerSignoz({
+ discovery: DISCOVERY,
+ interests: ['Prefer open-source tooling'],
+ });
+ await q.next().click();
+
+ await q.maxLogsSlider();
+ await q.next().click();
+
+ await expect(q.heading('Invite your team')).toBeVisible();
+ expect(run.profileBodies).toEqual([
+ {
+ uses_otel: true,
+ has_existing_observability_tool: true,
+ existing_observability_tool: 'DataDog',
+ where_did_you_discover_signoz: DISCOVERY,
+ timeline_for_migrating_to_signoz: 'lessThanMonth',
+ reasons_for_interest_in_signoz: ['openSourceTooling'],
+ logs_scale_per_day_in_gb: 10000,
+ number_of_hosts: 0,
+ number_of_services: 0,
+ },
+ ]);
+
+ await q.doLater().click();
+ await onboarding.expectPath(GET_STARTED_PATH);
+ expect(run.onboardingWrites).toEqual([{ value: true }]);
+
+ await onboarding.visit('/home');
+ await expect(onboarding.homePage()).toBeVisible();
+ await onboarding.settle();
+ expect(onboarding.pathname()).toBe('/home');
+ });
+
+ test('TC-02 each step keeps Next disabled and says why until it is answered', async ({
+ onboarding,
+ }) => {
+ await onboarding.stubFirstRun();
+ const { questionnaire: q } = onboarding;
+ await onboarding.visit(ONBOARDING_PATH);
+
+ await q.expectDisabledBecause(
+ q.next(),
+ 'Select the observability tool you use',
+ );
+ await q.pickTool('DataDog');
+ await q.expectDisabledBecause(q.next(), 'Select your migration timeline');
+ await q.pickTimeline('Just exploring');
+ await q.expectDisabledBecause(
+ q.next(),
+ 'Tell us if you already use OpenTelemetry',
+ );
+ await q.pickOtel(false);
+ await expect(q.next()).not.toHaveAttribute('aria-disabled', 'true');
+ await q.next().click();
+
+ await q.expectDisabledBecause(
+ q.next(),
+ 'Tell us how you first came across SigNoz',
+ );
+ await q.discovery().fill(DISCOVERY);
+ await q.expectDisabledBecause(
+ q.next(),
+ 'Select what got you interested in SigNoz',
+ );
+ await q.interest('Prefer open-source tooling').click();
+ await expect(q.next()).not.toHaveAttribute('aria-disabled', 'true');
+ await q.next().click();
+
+ await q.expectDisabledBecause(
+ q.next(),
+ 'Set at least one of the values above',
+ );
+ await q.maxLogsSlider();
+ await expect(q.next()).not.toHaveAttribute('aria-disabled', 'true');
+ await q.next().click();
+
+ await q.expectDisabledBecause(
+ q.sendInvites(),
+ 'Add at least one team member to invite',
+ );
+ });
+
+ test('TC-03 a failed profile save shows a toast and still reaches the invite step', async ({
+ onboarding,
+ }) => {
+ const run = await onboarding.stubFirstRun({ profiles: 'error' });
+ const { questionnaire: q } = onboarding;
+ await onboarding.visit(ONBOARDING_PATH);
+
+ await q.answerOrg({ tool: 'None/Starting fresh', usesOtel: false });
+ await q.next().click();
+ await q.answerSignoz({
+ discovery: DISCOVERY,
+ interests: ['Prefer open-source tooling'],
+ });
+ await q.next().click();
+ await q.doLater().click();
+
+ await expect(
+ onboarding.toast('Request failed with status code 500'),
+ ).toBeVisible();
+ await expect(q.heading('Invite your team')).toBeVisible();
+ expect(run.profileBodies).toHaveLength(1);
+ expect(run.onboardingWrites).toEqual([]);
+ });
+
+ test('TC-04 Send invites creates the invited user and finishes onboarding', async ({
+ onboarding,
+ }) => {
+ const run = await onboarding.stubFirstRun();
+ const { questionnaire: q } = onboarding;
+ const email = `e2e-onboarding-invite-${Date.now()}@signoz.test`;
+
+ try {
+ await onboarding.visit(ONBOARDING_PATH);
+ await q.answerOrg({ tool: 'None/Starting fresh', usesOtel: true });
+ await q.next().click();
+ await q.answerSignoz({
+ discovery: DISCOVERY,
+ interests: ['Prefer open-source tooling'],
+ });
+ await q.next().click();
+ await q.doLater().click();
+
+ await q.invite([{ email, role: 'signoz-viewer' }]);
+ await q.sendInvites().click();
+
+ await onboarding.expectPath(GET_STARTED_PATH);
+ expect(run.onboardingWrites).toEqual([{ value: true }]);
+ expect(await onboarding.users.byEmail(email)).toBeDefined();
+ } finally {
+ await onboarding.users.remove(email);
+ }
+ });
+});
diff --git a/tests/e2e/tests/onboarding/redirect.spec.ts b/tests/e2e/tests/onboarding/redirect.spec.ts
new file mode 100644
index 0000000000..b9bce51bce
--- /dev/null
+++ b/tests/e2e/tests/onboarding/redirect.spec.ts
@@ -0,0 +1,30 @@
+import { expect, test } from '../../drivers/onboarding';
+
+test.describe('onboarding redirect', () => {
+ // The viewer logs in through the UI on first use, and settle() waits for idle.
+ test.describe.configure({ timeout: 60_000 });
+
+ test('TC-06 an admin in an org with several users stays on /home', async ({
+ onboarding,
+ }) => {
+ await onboarding.stubFirstRun({ users: 'several' });
+ await onboarding.visit('/home');
+ await expect(onboarding.homePage()).toBeVisible();
+ await onboarding.settle();
+ expect(onboarding.pathname()).toBe('/home');
+ });
+
+ test.describe('as a viewer', () => {
+ test.use({ as: 'viewer' });
+
+ test('TC-07 a viewer in a first-run org stays on /home', async ({
+ onboarding,
+ }) => {
+ await onboarding.stubFirstRun();
+ await onboarding.visit('/home');
+ await expect(onboarding.homePage()).toBeVisible();
+ await onboarding.settle();
+ expect(onboarding.pathname()).toBe('/home');
+ });
+ });
+});
diff --git a/tests/e2e/tests/public-dashboard/public.spec.ts b/tests/e2e/tests/public-dashboard/public.spec.ts
new file mode 100644
index 0000000000..843bf1fce9
--- /dev/null
+++ b/tests/e2e/tests/public-dashboard/public.spec.ts
@@ -0,0 +1,52 @@
+import { expect, test } from '../../drivers/public-dashboard';
+
+test.describe('public dashboards', () => {
+ test('TC-01 a dashboard published in the UI renders for a logged-out visitor', async ({
+ publicDashboards,
+ publicView,
+ }, testInfo) => {
+ const title = `e2e-public-w${testInfo.workerIndex}-${Date.now()}`;
+ const dashboard = await publicDashboards.create(title);
+ try {
+ await publicDashboards.openPublishTab(dashboard.id);
+ await expect(publicDashboards.privateStatus()).toBeVisible();
+
+ await publicDashboards.publishInUi();
+ await expect(publicDashboards.liveStatus()).toBeVisible();
+ await expect(publicDashboards.publicUrl()).toBeVisible();
+
+ const path = await publicDashboards.publicPath(dashboard.id);
+ expect(path).toMatch(/^\/public\/dashboard\//);
+
+ await publicView.goto(path ?? '');
+ await expect(publicView.title(title)).toBeVisible();
+ await expect(publicView.sidenav()).toHaveCount(0);
+ await expect(publicView.settingsNavItem()).toHaveCount(0);
+ } finally {
+ await publicDashboards.unpublish(dashboard.id);
+ await publicDashboards.remove(dashboard.id);
+ }
+ });
+
+ test('TC-02 unpublishing makes the public link unavailable', async ({
+ publicDashboards,
+ publicView,
+ }, testInfo) => {
+ const title = `e2e-unpublish-w${testInfo.workerIndex}-${Date.now()}`;
+ const dashboard = await publicDashboards.create(title);
+ try {
+ const path = await publicDashboards.publish(dashboard.id);
+
+ await publicDashboards.openPublishTab(dashboard.id);
+ await expect(publicDashboards.liveStatus()).toBeVisible();
+ await publicDashboards.unpublishInUi();
+ await expect(publicDashboards.privateStatus()).toBeVisible();
+
+ await publicView.goto(path);
+ await expect(publicView.unavailable()).toBeVisible();
+ } finally {
+ await publicDashboards.unpublish(dashboard.id);
+ await publicDashboards.remove(dashboard.id);
+ }
+ });
+});
diff --git a/tests/e2e/tests/query-builder/token-highlight.spec.ts b/tests/e2e/tests/query-builder/token-highlight.spec.ts
index 5766b4dc05..5aef9415a0 100644
--- a/tests/e2e/tests/query-builder/token-highlight.spec.ts
+++ b/tests/e2e/tests/query-builder/token-highlight.spec.ts
@@ -1,9 +1,9 @@
-import { expect, test } from '../../fixtures/auth';
-import { setupTheme, tokenColor, typeExpression } from '@helpers/query-builder';
+import { expect, LOGS_EXPLORER_PATH, test } from '../../drivers/explorers';
-const LOGS_EXPLORER = '/logs/logs-explorer';
+// The editor's highlight colours come from two CodeMirror themes, and the only
+// way to read them back is the computed style of a rendered token.
-type ThemeConfig = {
+interface ThemeConfig {
name: string;
theme: 'dark' | 'light';
colors: {
@@ -12,7 +12,7 @@ type ThemeConfig = {
property: string;
string: string;
};
-};
+}
const THEMES: ThemeConfig[] = [
{
@@ -39,28 +39,30 @@ const THEMES: ThemeConfig[] = [
for (const { name, theme, colors } of THEMES) {
test.describe(`QueryBuilder token highlighting — ${name}`, () => {
- test(`k8s.namespace.name — each segment gets its own color`, async ({
+ test('TC-01 each segment of a dotted key gets its own colour', async ({
authedPage: page,
+ editor,
}) => {
- await setupTheme(page, theme);
- await page.goto(LOGS_EXPLORER);
- await typeExpression(page, 'k8s.namespace.name');
+ await editor.setTheme(theme);
+ await page.goto(LOGS_EXPLORER_PATH);
+ await editor.type('k8s.namespace.name');
- expect(await tokenColor(page, 'k8s')).toBe(colors.identifier);
- expect(await tokenColor(page, '.')).toBe(colors.operator);
- expect(await tokenColor(page, 'namespace')).toBe(colors.property);
- expect(await tokenColor(page, 'name')).toBe(colors.property);
+ await expect(editor.token('k8s')).toHaveCSS('color', colors.identifier);
+ await expect(editor.token('.')).toHaveCSS('color', colors.operator);
+ await expect(editor.token('namespace')).toHaveCSS('color', colors.property);
+ await expect(editor.token('name')).toHaveCSS('color', colors.property);
});
- test(`['value', 'value2'] — string tokens have native theme color`, async ({
+ test('TC-02 string tokens take the native theme colour', async ({
authedPage: page,
+ editor,
}) => {
- await setupTheme(page, theme);
- await page.goto(LOGS_EXPLORER);
- await typeExpression(page, "['value', 'value2']");
+ await editor.setTheme(theme);
+ await page.goto(LOGS_EXPLORER_PATH);
+ await editor.type("['value', 'value2']");
- expect(await tokenColor(page, "'value'")).toBe(colors.string);
- expect(await tokenColor(page, "'value2'")).toBe(colors.string);
+ await expect(editor.token("'value'")).toHaveCSS('color', colors.string);
+ await expect(editor.token("'value2'")).toHaveCSS('color', colors.string);
});
});
}
diff --git a/tests/e2e/tests/quick-filters/settings.spec.ts b/tests/e2e/tests/quick-filters/settings.spec.ts
index 78b0aa822c..944ae2e0fd 100644
--- a/tests/e2e/tests/quick-filters/settings.spec.ts
+++ b/tests/e2e/tests/quick-filters/settings.spec.ts
@@ -1,24 +1,21 @@
-import { test, expect } from '../../fixtures/auth';
import {
- assertQuickFiltersSettingsDrawerOpen,
- closeQuickFiltersSettingsPanel,
DEFAULT_CUSTOM_FILTERS,
- gotoExplorerWithQuickFilters,
+ expect,
LOGS_EXPLORER_PATH,
- openQuickFiltersSettingsPanel,
- seedCustomFiltersViaApi,
-} from '../../helpers/quick-filters';
+ test,
+} from '../../drivers/explorers';
-// smoke tests for settings drawer in quick filters
test.describe('Quick Filters — settings drawer', () => {
- test('TC-01 logs explorer — settings gear opens a visible, populated drawer', async ({
- authedPage: page,
+ test('TC-01 the settings gear opens a visible, populated drawer', async ({
+ quickFilters,
}) => {
- await seedCustomFiltersViaApi(page, 'logs', DEFAULT_CUSTOM_FILTERS);
- await gotoExplorerWithQuickFilters(page, LOGS_EXPLORER_PATH);
- await openQuickFiltersSettingsPanel(page);
- await assertQuickFiltersSettingsDrawerOpen(page, DEFAULT_CUSTOM_FILTERS);
- await closeQuickFiltersSettingsPanel(page);
- await expect(page.locator('.quick-filters')).toBeVisible();
+ await quickFilters.seed('logs', DEFAULT_CUSTOM_FILTERS);
+ await quickFilters.gotoExplorer(LOGS_EXPLORER_PATH);
+
+ await quickFilters.openSettings();
+ await quickFilters.expectSettingsOpen(DEFAULT_CUSTOM_FILTERS);
+ await quickFilters.closeSettings();
+
+ await expect(quickFilters.rail()).toBeVisible();
});
});
diff --git a/tests/e2e/tests/routing/mount.spec.ts b/tests/e2e/tests/routing/mount.spec.ts
index 6145fa209c..f8180977cb 100644
--- a/tests/e2e/tests/routing/mount.spec.ts
+++ b/tests/e2e/tests/routing/mount.spec.ts
@@ -6,7 +6,6 @@ test.describe('Routing: router mount', () => {
// Under a React transition the previous screen stays up instead of the
// Suspense fallback, so an uncached route renders no loader at all.
test('TC-18 an in-app navigation to an uncached route commits the Suspense fallback', async ({
- authedPage: page,
routing,
}) => {
await routing.dashboards.gotoList();
@@ -16,27 +15,18 @@ test.describe('Routing: router mount', () => {
await routing.waitForPath(PATH.alerts);
await expect(routing.dashboards.landmark()).toBeHidden();
- await expect(
- page.getByRole('img', { name: 'loading' }).first(),
- ).toBeVisible();
+ await expect(routing.suspenseFallback()).toBeVisible();
});
- await expect(
- page
- .getByRole('heading', { name: 'Alert Rules' })
- .or(page.getByTestId('list-alerts-search-input')),
- ).toBeVisible();
+ await expect(routing.alerts.landmark()).toBeVisible();
});
// nuqs' react-router adapter needs a router above it; the wrong order throws
// on the first page that reads a nuqs param.
test('TC-19 a page with nuqs params mounts with no router-context error', async ({
- authedPage: page,
routing,
}) => {
- const reported: string[] = [];
- page.on('pageerror', (error) => reported.push(error.message));
- page.on('console', (message) => reported.push(message.text()));
+ const reported = routing.recordMessages();
await routing.k8s.goto({ relativeTime: '30m' });
diff --git a/tests/e2e/tests/routing/nav-blocker.spec.ts b/tests/e2e/tests/routing/nav-blocker.spec.ts
index 27de8a2c32..b066d7919e 100644
--- a/tests/e2e/tests/routing/nav-blocker.spec.ts
+++ b/tests/e2e/tests/routing/nav-blocker.spec.ts
@@ -33,16 +33,13 @@ test.describe('Routing — unsaved-changes navigation blocker', () => {
await expect(roles.discardDialog()).toBeVisible();
// Cancel drops the blocked transition rather than retrying it.
- await roles
- .discardDialog()
- .getByRole('button', { name: 'Keep editing' })
- .click();
+ await roles.discardDialogButton('Keep editing').click();
await expect(roles.discardDialog()).toBeHidden();
expect(routing.url().pathname).toBe(PATH.roleCreate);
await expect(roles.nameInput()).toHaveValue(BLOCKED_ROLE_NAME);
await roles.cancel();
- await roles.discardDialog().getByRole('button', { name: 'Discard' }).click();
+ await roles.discardDialogButton('Discard').click();
await routing.waitForPath(PATH.roles);
});
diff --git a/tests/e2e/tests/routing/navigation.spec.ts b/tests/e2e/tests/routing/navigation.spec.ts
index d01e5faa7b..a8d228a393 100644
--- a/tests/e2e/tests/routing/navigation.spec.ts
+++ b/tests/e2e/tests/routing/navigation.spec.ts
@@ -4,19 +4,6 @@ import { dashboardListParams, expect, PATH, test } from '../../drivers/routing';
// `useSafeNavigate`'s same-url suppression, and its `newTab` branch.
test.describe('Routing — imperative navigation', () => {
- test('TC-05 Back from a detail page restores the list with its params', async ({
- routing,
- dashboard,
- }) => {
- await routing.dashboards.gotoList(dashboard.title);
- await routing.dashboards.row(dashboard.title).click();
- await routing.waitForPath(dashboard.path);
-
- await routing.goBackTo(PATH.dashboards);
-
- expect(routing.params()).toMatchObject(dashboardListParams(dashboard.title));
- });
-
// Both branches of the trace header's Back button in one document:
// `hasInAppHistory() ? goBack() : push(TRACES_EXPLORER)`.
test('TC-06 the trace-details previous button pushes when deep-linked and pops once in-app', async ({
diff --git a/tests/e2e/tests/routing/route-matching.spec.ts b/tests/e2e/tests/routing/route-matching.spec.ts
index 94b771bb10..1810334bc5 100644
--- a/tests/e2e/tests/routing/route-matching.spec.ts
+++ b/tests/e2e/tests/routing/route-matching.spec.ts
@@ -21,14 +21,13 @@ test.describe('Routing — route matching', () => {
});
test('TC-10 a prefix-route deep link loads with the right tab selected', async ({
- authedPage: page,
routing,
}) => {
await routing.goto(PATH.roles);
expect(routing.url().pathname).toBe(PATH.roles);
- await expect(page.getByTestId('settings-page-sidenav')).toBeVisible();
- await expect(page.getByTestId('roles')).toHaveClass(/active/);
+ await expect(routing.settings.sidenav()).toBeVisible();
+ await expect(routing.settings.navItem('roles')).toHaveClass(/active/);
await expect(routing.roles.settings()).toBeVisible();
});
@@ -67,7 +66,6 @@ test.describe('Routing — route matching', () => {
// `PrivateRoute` redirects a logged-in user on an unknown path to HOME before
// the catch-all runs, so `NotFound` is unreachable while authenticated.
test('TC-13 an unknown path redirects home and replaces its history entry', async ({
- authedPage: page,
routing,
}) => {
await routing.dashboards.gotoList();
@@ -75,7 +73,7 @@ test.describe('Routing — route matching', () => {
await routing.goto(PATH.unknown);
await routing.waitForPath(PATH.home);
- await expect(page.getByTestId('not-found')).toHaveCount(0);
+ await expect(routing.notFound()).toHaveCount(0);
// The redirect replaced the entry, so one Back reaches the list.
expect(await routing.historyDepth()).toBe(depthBefore + 1);
diff --git a/tests/e2e/tests/service-map/service-map.spec.ts b/tests/e2e/tests/service-map/service-map.spec.ts
new file mode 100644
index 0000000000..ed347b917a
--- /dev/null
+++ b/tests/e2e/tests/service-map/service-map.spec.ts
@@ -0,0 +1,19 @@
+import { expect, test } from '../../drivers/apm';
+
+test.describe('Service map', () => {
+ // Needs the migrator's `dependency_graph_minutes_v2` materialized view to
+ // join the seeded parent and child spans; the seeder has no route for it.
+ test('TC-01 service map draws the seeded caller to callee edge', async ({
+ apm,
+ apmSeed,
+ noise,
+ }) => {
+ await apm.waitForServiceMapEdge(apmSeed.service, apmSeed.downstream);
+
+ await expect(apm.serviceMap.root()).toBeVisible();
+ await expect(apm.serviceMap.canvas()).toBeVisible();
+ await expect(apm.serviceMap.empty()).toHaveCount(0);
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+});
diff --git a/tests/e2e/tests/services/detail.spec.ts b/tests/e2e/tests/services/detail.spec.ts
new file mode 100644
index 0000000000..baa78f293f
--- /dev/null
+++ b/tests/e2e/tests/services/detail.spec.ts
@@ -0,0 +1,107 @@
+import {
+ DB_PANELS,
+ expect,
+ EXTERNAL_PANELS,
+ SEEDED_DATA_TIMEOUT,
+ test,
+ withoutMissingMetadata,
+} from '../../drivers/apm';
+
+test.describe('Services, detail', () => {
+ test('TC-01 key operations lists seeded operations with real call counts', async ({
+ apm,
+ apmSeed,
+ }) => {
+ const { checkout, cart } = apmSeed.ops;
+ await apm.gotoService(apmSeed.service);
+
+ await expect(apm.keyOps.title()).toHaveText('Key Operations');
+ await expect(apm.keyOps.row(checkout.name)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ expect(await apm.keyOps.cell(checkout.name, 'Number of Calls')).toBe(
+ String(checkout.calls),
+ );
+ expect(await apm.keyOps.cell(checkout.name, 'Error Rate')).toBe(
+ `${((checkout.errors * 100) / checkout.calls).toFixed(2)} %`,
+ );
+ expect(await apm.keyOps.cell(cart.name, 'Number of Calls')).toBe(
+ String(cart.calls),
+ );
+ });
+
+ test('TC-02 the entrypoint toggle switches to entry-point operations from the backend', async ({
+ apm,
+ apmSeed,
+ }) => {
+ await apm.gotoService(apmSeed.service);
+ await expect(apm.keyOps.row(apmSeed.ops.checkout.name)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+
+ const operations = await apm.keyOps.toggleEntrypoint();
+
+ await expect(apm.keyOps.title()).toHaveText('Key Entrypoint Operations');
+ await expect(apm.keyOps.row(apmSeed.ops.checkout.name)).toBeVisible();
+ await expect(apm.keyOps.row(apmSeed.ops.cart.name)).toBeVisible();
+ await expect(apm.keyOps.rows()).toHaveCount(operations.length);
+ });
+
+ test('TC-03 a key operation opens the traces explorer filtered to it', async ({
+ apm,
+ apmSeed,
+ }) => {
+ const { checkout } = apmSeed.ops;
+ await apm.gotoService(apmSeed.service);
+ await expect(apm.keyOps.row(checkout.name)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+
+ await apm.openKeyOp(checkout.name);
+
+ const rows = apm.explorerRows();
+ await expect(rows.first()).toBeVisible({ timeout: SEEDED_DATA_TIMEOUT });
+ await expect(rows).toHaveCount(checkout.calls);
+ await expect(apm.explorerRowNames()).toHaveText(
+ Array.from({ length: checkout.calls }, () => checkout.name),
+ );
+ });
+
+ test('TC-04 DB Call and External tabs render their panels', async ({
+ apm,
+ apmSeed,
+ noise,
+ }) => {
+ await apm.gotoService(apmSeed.service);
+
+ await apm.openTab('DB Call Metrics');
+ for (const panel of DB_PANELS) {
+ // eslint-disable-next-line no-await-in-loop
+ await apm.expectPanelRendered(panel);
+ }
+
+ await apm.openTab('External Metrics');
+ for (const panel of EXTERNAL_PANELS) {
+ // eslint-disable-next-line no-await-in-loop
+ await apm.expectPanelRendered(panel);
+ }
+
+ const { errors, failedResponses } = withoutMissingMetadata(noise);
+ expect(failedResponses).toEqual([]);
+ expect(errors).toEqual([]);
+ });
+
+ // Needs the migrator's `top_level_operations` materialized view to fill from
+ // `signoz_index_v3`; the seeder has no route for it.
+ test('TC-05 top-level operations page lists the seeded root operation', async ({
+ apm,
+ apmSeed,
+ }) => {
+ await apm.gotoTopLevelOps(apmSeed.service);
+
+ await expect(apm.servicesBreadcrumb()).toHaveAttribute('href', '/services');
+ await expect(apm.topLevelOpsTable()).toContainText(apmSeed.entryOp, {
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ });
+});
diff --git a/tests/e2e/tests/services/list.spec.ts b/tests/e2e/tests/services/list.spec.ts
new file mode 100644
index 0000000000..72ef600a0d
--- /dev/null
+++ b/tests/e2e/tests/services/list.spec.ts
@@ -0,0 +1,50 @@
+import {
+ expect,
+ OVERVIEW_PANELS,
+ test,
+ withoutMissingMetadata,
+} from '../../drivers/apm';
+
+test.describe('Services, list', () => {
+ test('TC-01 services list shows a seeded service with trace-derived stats', async ({
+ apm,
+ apmSeed,
+ noise,
+ }) => {
+ await apm.waitForService(apmSeed.service);
+
+ expect(await apm.headers()).toEqual([
+ 'Application',
+ 'P99 latency (in ms)',
+ 'Error Rate (% of total)',
+ 'Operations Per Second',
+ ]);
+ const cells = await apm.rowCells(apmSeed.service);
+ expect(cells['Application']).toBe(apmSeed.service);
+ expect(cells['Error Rate (% of total)']).toBe(apmSeed.errorRate);
+ expect(Number(cells['P99 latency (in ms)'])).toBeGreaterThan(0);
+ expect(Number(cells['Operations Per Second'])).toBeGreaterThan(0);
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 service name opens the service overview', async ({
+ apm,
+ apmSeed,
+ noise,
+ }) => {
+ await apm.waitForService(apmSeed.service);
+
+ await apm.openService(apmSeed.service);
+
+ await expect(apm.tab('Overview')).toHaveAttribute('aria-selected', 'true');
+ for (const panel of OVERVIEW_PANELS) {
+ // eslint-disable-next-line no-await-in-loop
+ await apm.expectPanelRendered(panel);
+ }
+ const { errors, failedResponses } = withoutMissingMetadata(noise);
+ expect(errors).toEqual([]);
+ expect(failedResponses).toEqual([]);
+ });
+});
diff --git a/tests/e2e/tests/settings/account.spec.ts b/tests/e2e/tests/settings/account.spec.ts
new file mode 100644
index 0000000000..f7ce72b49f
--- /dev/null
+++ b/tests/e2e/tests/settings/account.spec.ts
@@ -0,0 +1,98 @@
+import { E2E_PASSWORD, expect, test } from '../../drivers/settings';
+
+test.describe('settings — account as a seeded admin', () => {
+ // Display name and `sidenav_pinned` belong to the user.
+ test.use({ as: 'admin2' });
+
+ test.afterEach(async ({ settings }) => {
+ await settings.users.setPreference('sidenav_pinned', true);
+ });
+
+ test('TC-01 an updated name persists', async ({ settings }, testInfo) => {
+ const name = `e2e admin2 w${testInfo.workerIndex} ${Date.now()}`;
+ await settings.account.goto();
+
+ await settings.account.rename(name);
+ await expect(settings.account.userName()).toHaveText(name);
+
+ await settings.reload();
+ await expect(settings.account.userName()).toHaveText(name);
+ expect((await settings.users.me()).displayName).toBe(name);
+ });
+
+ test('TC-04 the sidebar-pinned switch collapses the nav and persists', async ({
+ settings,
+ }) => {
+ await settings.account.goto();
+ await expect(settings.account.sidebarPinnedSwitch()).toHaveAttribute(
+ 'aria-checked',
+ 'true',
+ );
+
+ expect(await settings.account.toggleSidebarPinned()).toBe(false);
+ await settings.sidenav.parkPointer();
+ await expect.poll(() => settings.sidenav.isCollapsed()).toBe(true);
+
+ await settings.reload();
+ await expect(settings.account.sidebarPinnedSwitch()).toHaveAttribute(
+ 'aria-checked',
+ 'false',
+ );
+ await settings.sidenav.parkPointer();
+ await expect.poll(() => settings.sidenav.isCollapsed()).toBe(true);
+
+ await settings.sidenav.hover();
+
+ expect(await settings.account.toggleSidebarPinned()).toBe(true);
+ });
+});
+
+test.describe('settings — account password', () => {
+ // A password change revokes the sessions of the user it runs as.
+ test.use({
+ user: async ({ throwaway }, use) => {
+ await use(throwaway.user);
+ },
+ });
+
+ test('TC-02 a changed password is the only one that works', async ({
+ settings,
+ authFlows,
+ throwaway,
+ }) => {
+ const next = `${E2E_PASSWORD}-next`;
+ await settings.account.goto();
+ await settings.account.changePassword(E2E_PASSWORD, next);
+
+ await authFlows.gotoLogin();
+ await authFlows.enterEmail(throwaway.user.email);
+ await authFlows.enterPassword(E2E_PASSWORD);
+ await authFlows.submitPassword();
+ await expect(authFlows.authError()).toBeVisible();
+
+ await authFlows.login({ email: throwaway.user.email, password: next });
+ });
+});
+
+test.describe('settings — account theme', () => {
+ // The theme lives in localStorage, so it is scoped to this test's context.
+ test('TC-03 the theme choice applies app-wide and survives a reload', async ({
+ settings,
+ }) => {
+ await settings.account.goto();
+ await settings.account.theme('light');
+ await expect
+ .poll(() => settings.account.appliedTheme())
+ .toEqual({ light: true, stored: 'light' });
+
+ await settings.goto('/dashboard');
+ await expect
+ .poll(() => settings.account.appliedTheme())
+ .toEqual({ light: true, stored: 'light' });
+
+ await settings.reload();
+ await expect
+ .poll(() => settings.account.appliedTheme())
+ .toEqual({ light: true, stored: 'light' });
+ });
+});
diff --git a/tests/e2e/tests/settings/members.spec.ts b/tests/e2e/tests/settings/members.spec.ts
new file mode 100644
index 0000000000..71a0a482d2
--- /dev/null
+++ b/tests/e2e/tests/settings/members.spec.ts
@@ -0,0 +1,65 @@
+import { expect, test } from '../../drivers/settings';
+
+test.describe('settings — members', () => {
+ test('TC-01 an invite of two rows creates two pending members', async ({
+ settings,
+ }, testInfo) => {
+ const stamp = `e2e-inv2-w${testInfo.workerIndex}-${Date.now()}`;
+ const rows = [
+ { email: `${stamp}[email protected]`, role: 'signoz-viewer' },
+ { email: `${stamp}[email protected]`, role: 'signoz-editor' },
+ ];
+ try {
+ await settings.members.goto();
+ await settings.members.openInvite();
+ await settings.members.invite(rows);
+
+ await settings.members.search(stamp);
+ await expect(settings.members.row(stamp)).toHaveCount(2);
+ for (const { email } of rows) {
+ await expect(settings.members.row(email)).toContainText('INVITED');
+ }
+ } finally {
+ for (const { email } of rows) {
+ await settings.users.removeByEmail(email);
+ }
+ }
+ });
+
+ test('TC-02 a role change on a pending member persists', async ({
+ settings,
+ pendingMember,
+ }) => {
+ await settings.members.goto();
+ await settings.members.openMember(pendingMember.email);
+ await settings.members.setRoles(['signoz-editor']);
+ await settings.members.saveMember();
+
+ await settings.reload();
+ await settings.members.openMember(pendingMember.email);
+ await expect(settings.members.roleSelect()).toContainText('signoz-editor');
+ await expect(settings.members.roleSelect()).not.toContainText(
+ 'signoz-viewer',
+ );
+
+ const member = await settings.users.byEmail(pendingMember.email);
+ expect((member?.userRoles ?? []).map((entry) => entry.role.name)).toEqual([
+ 'signoz-editor',
+ ]);
+ });
+
+ test('TC-03 deleting an active member moves them to Deleted', async ({
+ settings,
+ activeEditor,
+ }) => {
+ const { email } = activeEditor.user;
+ await settings.members.goto();
+ await settings.members.openMember(email);
+ await settings.members.deleteMember();
+ await expect(settings.toast('Member deleted successfully')).toBeVisible();
+
+ await settings.members.filter('Deleted');
+ await settings.members.search(email);
+ await expect(settings.members.row(email)).toContainText('DELETED');
+ });
+});
diff --git a/tests/e2e/tests/settings/org.spec.ts b/tests/e2e/tests/settings/org.spec.ts
new file mode 100644
index 0000000000..ff32cec05c
--- /dev/null
+++ b/tests/e2e/tests/settings/org.spec.ts
@@ -0,0 +1,23 @@
+import { expect, test } from '../../drivers/settings';
+
+test.describe('settings — organization', () => {
+ test('TC-01 an org display-name edit persists', async ({
+ settings,
+ }, testInfo) => {
+ const original = await settings.org.apiName();
+ const name = `e2e-org-w${testInfo.workerIndex}-${Date.now()}`;
+ try {
+ await settings.org.goto();
+ await expect(settings.org.nameInput()).toHaveValue(original);
+
+ await settings.org.rename(name);
+ await expect(settings.toast('Success')).toBeVisible();
+
+ await settings.reload();
+ await expect(settings.org.nameInput()).toHaveValue(name);
+ expect(await settings.org.apiName()).toBe(name);
+ } finally {
+ await settings.org.setApiName(original);
+ }
+ });
+});
diff --git a/tests/e2e/tests/settings/roles.spec.ts b/tests/e2e/tests/settings/roles.spec.ts
new file mode 100644
index 0000000000..7ac35a144d
--- /dev/null
+++ b/tests/e2e/tests/settings/roles.spec.ts
@@ -0,0 +1,126 @@
+import { expect, grantAll, roleName, test } from '../../drivers/settings';
+
+test.describe('settings — roles', () => {
+ test('TC-01 managed roles are listed and read-only', async ({ settings }) => {
+ await settings.roles.goto();
+ await settings.roles.search('signoz-');
+ for (const role of ['signoz-admin', 'signoz-editor', 'signoz-viewer']) {
+ await expect(settings.roles.row(role)).toBeVisible();
+ }
+
+ await settings.roles.row('signoz-viewer').click();
+ await expect(settings.roles.viewPage()).toBeVisible();
+ await expect(settings.roles.deleteButton()).toBeDisabled();
+ await expect(settings.roles.updateButton()).toBeDisabled();
+ });
+
+ test('TC-02 a custom role created in the editor is persisted with its grants', async ({
+ settings,
+ }, testInfo) => {
+ const name = roleName('ui', testInfo.workerIndex);
+ try {
+ await settings.roles.goto();
+ await settings.roles.openCreate();
+ await settings.roles.fillName(name);
+ await settings.roles.fillDescription('created by the e2e suite');
+ await settings.roles.grant('dashboard', 'read', 'all');
+ await settings.roles.save();
+
+ await expect(settings.toast('Role created successfully')).toBeVisible();
+ await expect.poll(() => settings.pathname()).toBe('/settings/roles');
+ await settings.roles.search(name);
+ await expect(settings.roles.row(name)).toBeVisible();
+
+ const id = await settings.roles.idByName(name);
+ expect(id).toBeDefined();
+ const role = await settings.roles.apiRole(id ?? '');
+ expect(role.transactionGroups).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ relation: 'read',
+ objectGroup: expect.objectContaining({
+ resource: expect.objectContaining({ kind: 'dashboard' }),
+ }),
+ }),
+ ]),
+ );
+
+ await settings.roles.view(id ?? '', name);
+ await expect(settings.roles.grantedCount('dashboard')).not.toHaveText(/^0 /);
+ } finally {
+ await settings.roles.removeByName(name);
+ }
+ });
+
+ test('TC-03 editing a custom role updates the view page', async ({
+ settings,
+ customRole,
+ }) => {
+ const description = `edited ${Date.now()}`;
+ await settings.roles.view(customRole.id, customRole.name);
+ await expect(settings.roles.grantedCount('serviceaccount')).toHaveText(/^0 /);
+
+ await settings.roles.openEdit();
+ await settings.roles.fillDescription(description);
+ await settings.roles.grant('serviceaccount', 'read', 'all');
+ await settings.roles.save();
+
+ await expect(settings.toast('Role updated successfully')).toBeVisible();
+ await expect(settings.roles.viewPage()).toBeVisible();
+ await expect(settings.roles.viewPage()).toContainText(description);
+ await expect(settings.roles.grantedCount('serviceaccount')).not.toHaveText(
+ /^0 /,
+ );
+
+ await settings.reload();
+ await expect(settings.roles.viewPage()).toContainText(description);
+ await expect(settings.roles.grantedCount('serviceaccount')).not.toHaveText(
+ /^0 /,
+ );
+ });
+
+ test('TC-04 deleting a custom role removes it from the list', async ({
+ settings,
+ }, testInfo) => {
+ const name = roleName('del', testInfo.workerIndex);
+ const id = await settings.roles.createApi({
+ name,
+ transactionGroups: [grantAll('read', 'dashboard')],
+ });
+ try {
+ await settings.roles.view(id, name);
+ await settings.roles.delete();
+
+ await expect.poll(() => settings.pathname()).toBe('/settings/roles');
+ await settings.roles.search(name);
+ await expect(settings.roles.row(name)).toHaveCount(0);
+ } finally {
+ await settings.roles.removeApi(id);
+ }
+ });
+
+ test('TC-05 a user with a custom role sees only what it grants', async ({
+ settings,
+ customRole,
+ authFlows,
+ }, testInfo) => {
+ const title = `e2e-role-dash-w${testInfo.workerIndex}-${Date.now()}`;
+ const dashboard = await settings.seedDashboard(title);
+ const member = await settings.users.createActive(
+ customRole.name,
+ `custom-w${testInfo.workerIndex}-${Date.now()}`,
+ );
+ try {
+ await authFlows.login(member.user);
+
+ await expect(await authFlows.findDashboard(title)).toBeVisible();
+ await expect(authFlows.newDashboardButton()).toHaveAttribute(
+ 'data-denied-permissions',
+ /.+/,
+ );
+ } finally {
+ await settings.users.remove(member.id);
+ await settings.removeDashboard(dashboard.id);
+ }
+ });
+});
diff --git a/tests/e2e/tests/settings/service-accounts.spec.ts b/tests/e2e/tests/settings/service-accounts.spec.ts
new file mode 100644
index 0000000000..06df66645d
--- /dev/null
+++ b/tests/e2e/tests/settings/service-accounts.spec.ts
@@ -0,0 +1,73 @@
+import { expect, test } from '../../drivers/settings';
+
+test.describe('settings — service accounts', () => {
+ test('TC-01 a service account created in the UI opens its drawer and lists', async ({
+ settings,
+ }, testInfo) => {
+ const name = `e2e-sa-ui-w${testInfo.workerIndex}-${Date.now()}`;
+ try {
+ await settings.serviceAccounts.goto();
+ await settings.serviceAccounts.create(name);
+
+ await expect(
+ settings.toast('Service account created successfully'),
+ ).toBeVisible();
+ await expect(settings.serviceAccounts.drawer()).toBeVisible();
+
+ await settings.serviceAccounts.closeDrawer();
+ await settings.serviceAccounts.search(name);
+ await expect(settings.serviceAccounts.row(name)).toBeVisible();
+ } finally {
+ await settings.serviceAccounts.removeByName(name);
+ }
+ });
+
+ test('TC-02 a key shown once authenticates, and revoking it stops it working', async ({
+ settings,
+ serviceAccount,
+ }) => {
+ await settings.serviceAccounts.openKeys(serviceAccount.id);
+ const key = await settings.serviceAccounts.addKey('k1');
+
+ await expect(settings.serviceAccounts.keyCreatedCallout()).toBeVisible();
+ expect(
+ await settings.serviceAccounts.callWithKey(key, '/api/v2/dashboards'),
+ ).toBe(200);
+
+ await settings.serviceAccounts.closeKeyModal();
+ await settings.serviceAccounts.revokeKey('k1');
+ await expect
+ .poll(() => settings.serviceAccounts.callWithKey(key, '/api/v2/dashboards'))
+ .toBe(401);
+ });
+
+ test('TC-03 a role assigned in the drawer persists', async ({
+ settings,
+ serviceAccount,
+ }) => {
+ await settings.serviceAccounts.openAccount(serviceAccount.id);
+ await settings.serviceAccounts.setRoles(['signoz-editor']);
+ await settings.serviceAccounts.save();
+
+ await settings.reload();
+ await expect(settings.serviceAccounts.roleSelect()).toContainText(
+ 'signoz-editor',
+ );
+ const account = await settings.serviceAccounts.apiAccount(serviceAccount.id);
+ expect(
+ (account.serviceAccountRoles ?? []).map((entry) => entry.role.name),
+ ).toEqual(['signoz-editor']);
+ });
+
+ test('TC-04 deleting an account moves it to Deleted', async ({
+ settings,
+ serviceAccount,
+ }) => {
+ await settings.serviceAccounts.openAccount(serviceAccount.id);
+ await settings.serviceAccounts.delete();
+
+ await settings.serviceAccounts.filter('Deleted');
+ await settings.serviceAccounts.search(serviceAccount.name);
+ await expect(settings.serviceAccounts.row(serviceAccount.name)).toBeVisible();
+ });
+});
diff --git a/tests/e2e/tests/settings/smoke.spec.ts b/tests/e2e/tests/settings/smoke.spec.ts
new file mode 100644
index 0000000000..32b62c2f0e
--- /dev/null
+++ b/tests/e2e/tests/settings/smoke.spec.ts
@@ -0,0 +1,155 @@
+import { ADMIN, expect, test, type Settings } from '../../drivers/settings';
+
+interface SettingsProbe {
+ title: string;
+ open(settings: Settings): Promise<void>;
+ markers(settings: Settings): Promise<void>;
+ /** Substrings of failed responses the page is known to produce. */
+ allowFailures?: string[];
+}
+
+const PROBES: SettingsProbe[] = [
+ {
+ title: 'TC-01 /settings renders the workspace page',
+ open: (settings) => settings.shell.goto('/settings'),
+ markers: async (settings) => {
+ await expect(settings.general.retentionTitle()).toBeVisible();
+ await expect(settings.general.licenseCopyButton()).toBeVisible();
+ },
+ },
+ {
+ title: 'TC-02 /settings/org-settings shows the org name the API holds',
+ open: (settings) => settings.org.goto(),
+ markers: async (settings) => {
+ await expect(settings.org.nameInput()).toHaveValue(
+ await settings.org.apiName(),
+ );
+ await expect(settings.org.authDomainTitle()).toBeVisible();
+ },
+ },
+ {
+ title: 'TC-03 /settings/my-settings renders the preferences',
+ open: (settings) => settings.account.goto(),
+ markers: async (settings) => {
+ await expect(settings.account.themeSelector()).toBeVisible();
+ await expect(settings.account.timezoneAdaptationSwitch()).toBeVisible();
+ await expect(settings.account.sidebarPinnedSwitch()).toBeVisible();
+ await expect(settings.account.email(ADMIN.email)).toBeVisible();
+ },
+ },
+ {
+ title: 'TC-04 /settings/members lists the admin as active',
+ open: (settings) => settings.members.goto(),
+ markers: async (settings) => {
+ await settings.members.search(ADMIN.email);
+ await expect(settings.members.row(ADMIN.email)).toContainText('ACTIVE');
+ },
+ },
+ {
+ title: 'TC-05 /settings/roles lists the managed roles',
+ open: (settings) => settings.roles.goto(),
+ markers: async (settings) => {
+ await settings.roles.search('signoz-');
+ for (const role of ['signoz-admin', 'signoz-editor', 'signoz-viewer']) {
+ await expect(settings.roles.row(role)).toBeVisible();
+ }
+ },
+ },
+ {
+ title: 'TC-06 /settings/service-accounts renders the list',
+ open: (settings) => settings.serviceAccounts.goto(),
+ markers: async (settings) => {
+ await expect(settings.serviceAccounts.newButton()).toBeVisible();
+ },
+ },
+ {
+ title: 'TC-07 /settings/ingestion-settings renders the keys page',
+ open: async (settings) => {
+ await settings.ingestion.stubGateway();
+ await settings.ingestion.goto();
+ },
+ markers: async (settings) => {
+ await expect(settings.ingestion.title()).toBeVisible();
+ await expect(settings.ingestion.addButton()).toBeVisible();
+ },
+ },
+ {
+ title: 'TC-08 /settings/shortcuts lists every shortcut section',
+ open: (settings) => settings.shortcutsPage.goto(),
+ markers: async (settings) => {
+ for (const section of [
+ 'Global Shortcuts',
+ 'Logs Explorer Shortcuts',
+ 'Query Builder Shortcuts',
+ 'Dashboard Shortcuts',
+ ]) {
+ await expect(settings.shortcutsPage.section(section)).toBeVisible();
+ }
+ },
+ },
+ {
+ title: 'TC-09 /settings/mcp-server shows the fallback without an MCP URL',
+ open: (settings) => settings.mcp.goto(),
+ markers: async (settings) => {
+ await expect(settings.mcp.fallbackTitle()).toBeVisible();
+ },
+ },
+ {
+ title: 'TC-10 /settings/billing renders the billing page',
+ open: (settings) => settings.billing.goto(),
+ markers: async (settings) => {
+ await expect(settings.billing.subtitle()).toBeVisible();
+ },
+ // The zeus mock stubs only `/v2/licenses/me`, so the usage request behind
+ // the subscription answers 404 on this stack. It lands after the subtitle.
+ allowFailures: ['/api/v1/subscriptions'],
+ },
+];
+
+test.describe('settings — smoke', () => {
+ for (const probe of PROBES) {
+ test(probe.title, async ({ settings, noise }) => {
+ await probe.open(settings);
+ await probe.markers(settings);
+
+ await expect(settings.errorBoundary()).toHaveCount(0);
+ expect(noise.errors).toEqual([]);
+ expect(
+ noise.failedResponses.filter(
+ (entry) =>
+ !(probe.allowFailures ?? []).some((known) => entry.includes(known)),
+ ),
+ ).toEqual([]);
+ });
+ }
+});
+
+test.describe('settings — smoke as a viewer', () => {
+ test.use({ as: 'viewer' });
+
+ test('TC-11 the settings nav shows a viewer only what the backend grants', async ({
+ settings,
+ }) => {
+ await settings.shell.goto('/settings');
+ await expect(settings.shell.navItem('workspace')).toBeVisible();
+
+ const keys = await settings.shell.navKeys();
+ expect(keys).toEqual(
+ expect.arrayContaining(['roles', 'service-accounts', 'keyboard-shortcuts']),
+ );
+ expect(keys).not.toContain('members');
+ expect(keys).not.toContain('sso');
+ });
+
+ test('TC-12 a viewer on /settings/members gets no members page', async ({
+ settings,
+ }) => {
+ // The members route sits inside the settings route, which every role may
+ // open, so the guard does not redirect: the settings page simply mounts
+ // no members tab for a viewer.
+ await settings.shell.goto('/settings/members');
+ await expect(settings.members.heading()).toHaveCount(0);
+ expect(settings.pathname()).toBe('/settings/members');
+ await expect(settings.errorBoundary()).toHaveCount(0);
+ });
+});
diff --git a/tests/e2e/tests/sso/auth-domains.spec.ts b/tests/e2e/tests/sso/auth-domains.spec.ts
index 404e56369c..390b131160 100644
--- a/tests/e2e/tests/sso/auth-domains.spec.ts
+++ b/tests/e2e/tests/sso/auth-domains.spec.ts
@@ -1,87 +1,70 @@
-import { expect, test } from '../../fixtures/auth';
-import {
- createGoogleAuthDomainViaApi,
- deleteAuthDomainByNameViaApi,
- findAuthDomainRow,
- gotoAuthDomains,
- openConfigureAuthDomain,
- ORG_SETTINGS_PATH,
-} from '../../helpers/sso';
+import { expect, test } from '../../drivers/sso';
test.describe('SSO auth domains', () => {
// Every test seeds its own uniquely-named domain so the file can run fully
// parallel. Names are registered here and removed by the afterEach guard.
const cleanupNames: string[] = [];
- test.afterEach(async ({ authedPage: page }) => {
+ test.afterEach(async ({ sso }) => {
for (const name of cleanupNames.splice(0)) {
- await deleteAuthDomainByNameViaApi(page, name);
+ await sso.deleteDomainByName(name);
}
});
test('TC-01 org settings shows the authenticated domains section', async ({
- authedPage: page,
+ sso,
}) => {
- await page.goto(ORG_SETTINGS_PATH);
- await expect(page.getByTestId('auth-domain-title')).toBeVisible();
- await expect(page.getByTestId('auth-domain-add')).toBeVisible();
+ await sso.goto();
+ await expect(sso.title()).toBeVisible();
+ await expect(sso.addButton()).toBeVisible();
});
- test('TC-02 create a google auth domain via the UI', async ({
- authedPage: page,
- }) => {
+ test('TC-02 create a google auth domain via the UI', async ({ sso }) => {
const domain = 'sso-create.example.com';
cleanupNames.push(domain);
- await gotoAuthDomains(page);
- await page.getByTestId('auth-domain-add').click();
- await page.getByTestId('authn-provider-configure-google').click();
+ await sso.goto();
+ await sso.addButton().click();
+ await sso.configureProvider('google').click();
- await page.getByTestId('google-auth-domain').fill(domain);
- await page
- .getByTestId('google-auth-client-id')
+ await sso.form.googleDomain().fill(domain);
+ await sso.form
+ .googleClientId()
.fill('e2e-client-id.apps.googleusercontent.com');
- await page.getByTestId('google-auth-client-secret').fill('e2e-client-secret');
- await page.getByTestId('auth-domain-save').click();
+ await sso.form.googleClientSecret().fill('e2e-client-secret');
+ await sso.form.save().click();
- await expect(page.getByText('Domain created successfully')).toBeVisible();
- const row = await findAuthDomainRow(page, domain);
- await expect(row.getByTestId('auth-domain-configure')).toHaveText(
- 'Configure Google Auth',
- );
+ await expect(sso.toast('Domain created successfully')).toBeVisible();
+ await expect(sso.configureButton(domain)).toHaveText('Configure Google Auth');
});
- test('TC-03 editing the client id persists across reopen', async ({
- authedPage: page,
- }) => {
+ test('TC-03 editing the client id persists across reopen', async ({ sso }) => {
const domain = 'sso-edit.example.com';
cleanupNames.push(domain);
- await createGoogleAuthDomainViaApi(page, { name: domain });
+ await sso.createGoogleDomain({ name: domain });
- await gotoAuthDomains(page);
- await openConfigureAuthDomain(page, domain);
- await expect(page.getByTestId('google-auth-client-id')).toHaveValue(
+ await sso.goto();
+ await sso.openConfigure(domain);
+ await expect(sso.form.googleClientId()).toHaveValue(
'e2e-client-id.apps.googleusercontent.com',
);
- await page
- .getByTestId('google-auth-client-id')
+ await sso.form
+ .googleClientId()
.fill('rotated-client-id.apps.googleusercontent.com');
- await page.getByTestId('auth-domain-save').click();
- await expect(page.getByText('Domain updated successfully')).toBeVisible();
- await expect(page.getByTestId('auth-domain-form')).toBeHidden();
+ await sso.form.save().click();
+ await expect(sso.toast('Domain updated successfully')).toBeVisible();
+ await expect(sso.form.root()).toBeHidden();
- await openConfigureAuthDomain(page, domain);
- await expect(page.getByTestId('google-auth-client-id')).toHaveValue(
+ await sso.openConfigure(domain);
+ await expect(sso.form.googleClientId()).toHaveValue(
'rotated-client-id.apps.googleusercontent.com',
);
});
- test('TC-04 removing a group mapping persists after save', async ({
- authedPage: page,
- }) => {
+ test('TC-04 removing a group mapping persists after save', async ({ sso }) => {
const domain = 'sso-rolemap.example.com';
cleanupNames.push(domain);
- await createGoogleAuthDomainViaApi(page, {
+ await sso.createGoogleDomain({
name: domain,
roleMapping: {
defaultRole: 'signoz-viewer',
@@ -92,37 +75,33 @@ test.describe('SSO auth domains', () => {
},
});
- await gotoAuthDomains(page);
- await openConfigureAuthDomain(page, domain);
- await page.getByTestId('role-mapping-header').click();
+ await sso.goto();
+ await sso.openConfigure(domain);
+ await sso.roleMapping.header().click();
- const rows = page.getByTestId('role-mapping-row');
+ const rows = sso.roleMapping.rows();
await expect(rows).toHaveCount(2);
// Go marshals map keys sorted, so "engineers" is always the first row.
- await expect(rows.nth(0).getByTestId('role-mapping-group-name')).toHaveValue(
- 'engineers',
- );
- await rows.nth(0).getByTestId('role-mapping-remove').click();
+ await expect(sso.roleMapping.groupName(0)).toHaveValue('engineers');
+ await sso.roleMapping.remove(0).click();
await expect(rows).toHaveCount(1);
- await page.getByTestId('auth-domain-save').click();
- await expect(page.getByText('Domain updated successfully')).toBeVisible();
- await expect(page.getByTestId('auth-domain-form')).toBeHidden();
+ await sso.form.save().click();
+ await expect(sso.toast('Domain updated successfully')).toBeVisible();
+ await expect(sso.form.root()).toBeHidden();
- await openConfigureAuthDomain(page, domain);
- await page.getByTestId('role-mapping-header').click();
+ await sso.openConfigure(domain);
+ await sso.roleMapping.header().click();
await expect(rows).toHaveCount(1);
- await expect(rows.getByTestId('role-mapping-group-name')).toHaveValue(
- 'support',
- );
+ await expect(sso.roleMapping.groupName(0)).toHaveValue('support');
});
test('TC-05 disabling fetch groups clears the allowed groups', async ({
- authedPage: page,
+ sso,
}) => {
const domain = 'sso-groups.example.com';
cleanupNames.push(domain);
- await createGoogleAuthDomainViaApi(page, {
+ await sso.createGoogleDomain({
name: domain,
fetchGroups: true,
serviceAccountJson: '{"type":"service_account","project_id":"e2e"}',
@@ -130,48 +109,39 @@ test.describe('SSO auth domains', () => {
allowedGroups: ['[email protected]'],
});
- await gotoAuthDomains(page);
- await openConfigureAuthDomain(page, domain);
- await page.getByTestId('google-auth-workspace-groups-header').click();
+ await sso.goto();
+ await sso.openConfigure(domain);
+ await sso.workspaceGroups.header().click();
- const fetchGroups = page.getByRole('checkbox', { name: 'Fetch Groups' });
+ const fetchGroups = sso.workspaceGroups.fetchGroups();
await expect(fetchGroups).toBeChecked();
- await expect(
- page
- .getByTestId('google-auth-allowed-groups')
- .locator('.ant-select-selection-item'),
- ).toHaveCount(1);
+ await expect(sso.workspaceGroups.allowedGroups()).toHaveCount(1);
await fetchGroups.click();
await expect(fetchGroups).not.toBeChecked();
- await page.getByTestId('auth-domain-save').click();
- await expect(page.getByText('Domain updated successfully')).toBeVisible();
- await expect(page.getByTestId('auth-domain-form')).toBeHidden();
+ await sso.form.save().click();
+ await expect(sso.toast('Domain updated successfully')).toBeVisible();
+ await expect(sso.form.root()).toBeHidden();
- await openConfigureAuthDomain(page, domain);
- await page.getByTestId('google-auth-workspace-groups-header').click();
+ await sso.openConfigure(domain);
+ await sso.workspaceGroups.header().click();
await expect(fetchGroups).not.toBeChecked();
// Re-enable to reveal the group fields: the allowed-groups list must be
// empty, not repopulated from the pre-disable state.
await fetchGroups.click();
- await expect(
- page
- .getByTestId('google-auth-allowed-groups')
- .locator('.ant-select-selection-item'),
- ).toHaveCount(0);
+ await expect(sso.workspaceGroups.allowedGroups()).toHaveCount(0);
});
test('TC-06 enforce sso toggle persists across reload', async ({
authedPage: page,
+ sso,
}) => {
const domain = 'sso-toggle.example.com';
cleanupNames.push(domain);
- await createGoogleAuthDomainViaApi(page, { name: domain, enabled: false });
+ await sso.createGoogleDomain({ name: domain, enabled: false });
- await gotoAuthDomains(page);
- const toggle = (await findAuthDomainRow(page, domain)).getByTestId(
- 'auth-domain-enforce-sso',
- );
+ await sso.goto();
+ const toggle = sso.enforceSsoToggle(domain);
await expect(toggle).not.toBeChecked();
await toggle.click();
@@ -181,35 +151,32 @@ test.describe('SSO auth domains', () => {
await expect(toggle).toBeEnabled();
await page.reload();
- const reloadedRow = await findAuthDomainRow(page, domain);
- await expect(
- reloadedRow.getByTestId('auth-domain-enforce-sso'),
- ).toBeChecked();
+ await expect(sso.enforceSsoToggle(domain)).toBeChecked();
});
- test('TC-07 delete a domain via the UI', async ({ authedPage: page }) => {
+ test('TC-07 delete a domain via the UI', async ({ sso }) => {
const removed = 'sso-delete.example.com';
const kept = 'sso-delete-keep.example.com';
cleanupNames.push(removed, kept);
- await createGoogleAuthDomainViaApi(page, { name: removed });
- await createGoogleAuthDomainViaApi(page, { name: kept });
+ await sso.createGoogleDomain({ name: removed });
+ await sso.createGoogleDomain({ name: kept });
- await gotoAuthDomains(page);
- const row = await findAuthDomainRow(page, removed);
- await row.getByTestId('auth-domain-delete').click();
- await page.getByTestId('auth-domain-delete-confirm').click();
+ await sso.goto();
+ await sso.deleteButton(removed).click();
+ await sso.deleteConfirmButton().click();
- await expect(page.getByText('Domain deleted successfully')).toBeVisible();
- await expect(page.getByTestId(`auth-domain-row-${removed}`)).toHaveCount(0);
- await expect(page.getByTestId(`auth-domain-row-${kept}`)).toHaveCount(1);
+ await expect(sso.toast('Domain deleted successfully')).toBeVisible();
+ await expect(sso.row(removed)).toHaveCount(0);
+ await expect(sso.row(kept)).toHaveCount(1);
});
test('TC-08 enforce sso toggle preserves the role mapping', async ({
authedPage: page,
+ sso,
}) => {
const domain = 'sso-toggle-rolemap.example.com';
cleanupNames.push(domain);
- await createGoogleAuthDomainViaApi(page, {
+ await sso.createGoogleDomain({
name: domain,
enabled: false,
roleMapping: {
@@ -218,25 +185,18 @@ test.describe('SSO auth domains', () => {
},
});
- await gotoAuthDomains(page);
- const toggle = (await findAuthDomainRow(page, domain)).getByTestId(
- 'auth-domain-enforce-sso',
- );
+ await sso.goto();
+ const toggle = sso.enforceSsoToggle(domain);
await toggle.click();
await expect(toggle).toBeChecked();
await expect(toggle).toBeEnabled();
await page.reload();
- await openConfigureAuthDomain(page, domain);
- await page.getByTestId('role-mapping-header').click();
+ await sso.openConfigure(domain);
+ await sso.roleMapping.header().click();
- const rows = page.getByTestId('role-mapping-row');
- await expect(rows).toHaveCount(2);
- await expect(rows.nth(0).getByTestId('role-mapping-group-name')).toHaveValue(
- 'engineers',
- );
- await expect(rows.nth(1).getByTestId('role-mapping-group-name')).toHaveValue(
- 'support',
- );
+ await expect(sso.roleMapping.rows()).toHaveCount(2);
+ await expect(sso.roleMapping.groupName(0)).toHaveValue('engineers');
+ await expect(sso.roleMapping.groupName(1)).toHaveValue('support');
});
});
diff --git a/tests/e2e/tests/trace-details/drawer.spec.ts b/tests/e2e/tests/trace-details/drawer.spec.ts
index f92e93dc5c..a6084f35eb 100644
--- a/tests/e2e/tests/trace-details/drawer.spec.ts
+++ b/tests/e2e/tests/trace-details/drawer.spec.ts
@@ -1,9 +1,10 @@
-import { test, expect } from '../../fixtures/auth';
import {
- gotoTraceUntilLoaded,
+ expect,
loadLargeTrace,
seedTracesViaSeeder,
-} from '../../helpers/trace-details';
+ test,
+ TRACE_PREFERENCE,
+} from '../../drivers/traces';
// One shared trace for the whole file, seeded once. Unique ids per run keep this
// isolated from other parallel specs; the global teardown clears the traces signal.
@@ -18,10 +19,9 @@ test.describe('Trace details — span details drawer', () => {
await request.dispose();
});
- test.beforeEach(async ({ authedPage: page }) => {
+ test.beforeEach(async ({ traces }) => {
// open the trace, reloading until the waterfall renders (seed→query lag)
- await gotoTraceUntilLoaded(
- page,
+ await traces.goto(
`/trace/${trace.traceId}`,
`cell-0-${trace.landmarks.root}`,
);
@@ -29,11 +29,12 @@ test.describe('Trace details — span details drawer', () => {
test('TC-01 the floating drawer can be dragged', async ({
authedPage: page,
+ traces,
}) => {
- await page.getByTestId(`cell-0-${trace.landmarks.root}`).click();
- await page.getByTestId('dock-mode-dialog').click();
+ await traces.span.open(trace.landmarks.root);
+ await traces.span.dock('dialog');
- const handle = page.locator('.floating-panel__drag-handle');
+ const handle = traces.span.dragHandle();
await expect(handle).toBeVisible();
const zero = { x: 0, y: 0, width: 0, height: 0 };
@@ -53,17 +54,49 @@ test.describe('Trace details — span details drawer', () => {
test('TC-02 a dock-mode change persists and is restored on reload', async ({
authedPage: page,
+ traces,
}) => {
// §0 prefs-boot, UI-first: switch to floating via the dock-mode UI (which
// persists the variant), then reload and confirm it's restored — the drawer
// boots floating, not the docked-right default.
- await page.getByTestId(`cell-0-${trace.landmarks.root}`).click();
- await page.getByTestId('dock-mode-dialog').click();
- await expect(page.locator('.floating-panel__drag-handle')).toBeVisible();
+ await traces.span.open(trace.landmarks.root);
+ await traces.span.dock('dialog');
+ await expect(traces.span.dragHandle()).toBeVisible();
await page.reload();
- await page.getByTestId(`cell-0-${trace.landmarks.root}`).click();
+ await traces.span.open(trace.landmarks.root);
- await expect(page.locator('.floating-panel__drag-handle')).toBeVisible();
+ await expect(traces.span.dragHandle()).toBeVisible();
+ });
+
+ // Pins a leaf value: pinning an object node is a known, separately tracked
+ // regression in the PrettyView nested-node menu.
+ test('TC-03 a leaf attribute pinned from the docked panel moves into a pinned section', async ({
+ traces,
+ }) => {
+ test.setTimeout(60_000);
+ try {
+ await traces.span.open(trace.landmarks.db);
+ await traces.span.dock('docked');
+ await expect(traces.span.dockOption('docked')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+
+ await traces.span.openFieldMenu('db.system');
+ await traces.span.menuItem('Pin field').click();
+
+ await expect(traces.span.panelTitle()).toBeVisible();
+ await expect(traces.span.pinnedSection()).toBeVisible();
+ await expect(traces.span.pinnedField('attributes.db.system')).toBeVisible();
+
+ await traces.span.openPinnedFieldMenu('attributes.db.system');
+ await traces.span.menuItem('Unpin field').click();
+
+ await expect(traces.span.pinnedSection()).toHaveCount(0);
+ await expect(traces.span.panelTitle()).toBeVisible();
+ } finally {
+ await traces.prefs.set(TRACE_PREFERENCE.PINNED_ATTRIBUTES, []);
+ }
});
});
diff --git a/tests/e2e/tests/trace-details/flamegraph.spec.ts b/tests/e2e/tests/trace-details/flamegraph.spec.ts
index c8f74c885b..8fa7c2ee68 100644
--- a/tests/e2e/tests/trace-details/flamegraph.spec.ts
+++ b/tests/e2e/tests/trace-details/flamegraph.spec.ts
@@ -1,20 +1,15 @@
-import { test, expect } from '../../fixtures/auth';
-import { newAdminContext } from '../../helpers/auth';
import {
- changeColourByViaMenu,
- clickFlamegraphSpan,
- getFlamegraphSpanColor,
- gotoTraceUntilLoaded,
- hoverFlamegraphSpan,
- isFlamegraphSpanInView,
+ expect,
loadLargeTrace,
+ onAdminPage,
seedTracesViaSeeder,
- setColorByPreference,
-} from '../../helpers/trace-details';
+ test,
+ traceDetailsDriver,
+} from '../../drivers/traces';
// The flamegraph is canvas-rendered, so individual bars have no DOM nodes. These
// specs drive it through the window.__sigTraceFlame__ test hook (enabled by
-// gotoTraceUntilLoaded) — see helpers/trace-details.ts — which resolves a span's
+// gotoTraceUntilLoaded) — see drivers/traces.ts — which resolves a span's
// on-canvas point from the live span→rect map and dispatches real mouse events.
//
// One shared trace for the file, seeded once. Random ids per run isolate it from
@@ -35,86 +30,77 @@ test.describe('Trace details — flamegraph', () => {
});
test.afterAll(async ({ browser }) => {
- // TC-04 changes colour-by — a per-user pref. Reset it so it doesn't leak to
- // other specs (afterAll can't use the test-scoped authedPage fixture).
- const ctx = await newAdminContext(browser);
- const page = await ctx.newPage();
- await setColorByPreference(page, '');
- await ctx.close();
+ // TC-04 changes colour-by — a per-user pref. Reset it so it does not leak
+ // into other specs; `afterAll` cannot use the test-scoped `authedPage`.
+ await onAdminPage(browser, (page) =>
+ traceDetailsDriver(page).prefs.colorBy(''),
+ );
});
- test.beforeEach(async ({ authedPage: page }) => {
- await gotoTraceUntilLoaded(
- page,
+ test.beforeEach(async ({ traces }) => {
+ await traces.goto(
`/trace/${trace.traceId}`,
`cell-0-${trace.landmarks.root}`,
);
});
test('TC-01 hovering an error bar opens its hover card with status/start/duration', async ({
- authedPage: page,
+ traces,
}) => {
- await hoverFlamegraphSpan(page, trace.landmarks.errors[0]);
+ await traces.flame.hover(trace.landmarks.errors[0]);
// The status row only renders in the hover card (not in waterfall rows),
// so it proves both that the card opened and that we hovered the right
// (error) span — the bar was targeted by id via the span→rect map.
- await expect(page.getByTestId('span-hover-card-status')).toHaveText(
- /status\s*error/,
- );
- await expect(page.getByTestId('span-hover-card-start')).toHaveText(
- /start\s*[\d.]+ ms/,
- );
- await expect(page.getByTestId('span-hover-card-duration')).toHaveText(
+ await expect(traces.hoverCard.field('status')).toHaveText(/status\s*error/);
+ await expect(traces.hoverCard.field('start')).toHaveText(/start\s*[\d.]+ ms/);
+ await expect(traces.hoverCard.field('duration')).toHaveText(
/duration\s*[\d.]+/,
);
});
test('TC-02 clicking a bar selects the span, opens the drawer, and syncs the waterfall row', async ({
authedPage: page,
+ traces,
}) => {
- await clickFlamegraphSpan(page, trace.landmarks.db);
+ await traces.flame.click(trace.landmarks.db);
// selection is reflected in the shared URL state...
await expect(page).toHaveURL(new RegExp(`spanId=${trace.landmarks.db}`));
// ...the drawer opens (Overview tab is drawer-only)...
- await expect(page.getByRole('tab', { name: /overview/i })).toBeVisible();
+ await expect(traces.span.overviewTab()).toBeVisible();
// ...and the same span's waterfall row is present (views share selection).
- await expect(page.getByTestId(`cell-0-${trace.landmarks.db}`)).toBeVisible();
+ await expect(traces.span.row(trace.landmarks.db)).toBeVisible();
});
test('TC-03 deep-linking a deeply-nested span scrolls it into view on the flamegraph', async ({
- authedPage: page,
+ traces,
}) => {
// Open pre-pointed at a deep (level ~34) span; useScrollToSpan should
// center it, so its bar becomes drawn and inside the viewport container.
- await gotoTraceUntilLoaded(
- page,
+ await traces.goto(
`/trace/${trace.traceId}?spanId=${trace.landmarks.deepLeaf}`,
`cell-0-${trace.landmarks.deepLeaf}`,
);
await expect
- .poll(() => isFlamegraphSpanInView(page, trace.landmarks.deepLeaf))
+ .poll(() => traces.flame.isInView(trace.landmarks.deepLeaf))
.toBe(true);
});
test('TC-04 changing colour-by recolors the flamegraph bars', async ({
- authedPage: page,
+ traces,
}) => {
// colour-by persists per-user, so set an explicit baseline rather than
// assuming the default. Root's color under service.name:
- await changeColourByViaMenu(page, 'service.name');
- const colorByService = await getFlamegraphSpanColor(
- page,
- trace.landmarks.root,
- );
+ await traces.changeColourBy('service.name');
+ const colorByService = await traces.flame.color(trace.landmarks.root);
expect(colorByService).not.toBeNull();
// Switch to host.name → root groups by a different value → new color.
- await changeColourByViaMenu(page, 'host.name');
+ await traces.changeColourBy('host.name');
await expect
- .poll(() => getFlamegraphSpanColor(page, trace.landmarks.root))
+ .poll(() => traces.flame.color(trace.landmarks.root))
.not.toBe(colorByService);
});
});
diff --git a/tests/e2e/tests/trace-details/header.spec.ts b/tests/e2e/tests/trace-details/header.spec.ts
index 3b1d67d707..7046c73179 100644
--- a/tests/e2e/tests/trace-details/header.spec.ts
+++ b/tests/e2e/tests/trace-details/header.spec.ts
@@ -1,9 +1,9 @@
-import { test, expect } from '../../fixtures/auth';
import {
- gotoTraceUntilLoaded,
+ expect,
loadLargeTrace,
seedTracesViaSeeder,
-} from '../../helpers/trace-details';
+ test,
+} from '../../drivers/traces';
// §1 header — the Analytics FloatingPanel. The action cluster (Analytics button
// + options menu) only renders once trace data is loaded, which gotoTraceUntilLoaded
@@ -21,9 +21,8 @@ test.describe('Trace details — header analytics panel', () => {
await request.dispose();
});
- test.beforeEach(async ({ authedPage: page }) => {
- await gotoTraceUntilLoaded(
- page,
+ test.beforeEach(async ({ traces }) => {
+ await traces.goto(
`/trace/${trace.traceId}`,
`cell-0-${trace.landmarks.root}`,
);
@@ -31,15 +30,15 @@ test.describe('Trace details — header analytics panel', () => {
test('TC-01 the analytics panel can be dragged by its header', async ({
authedPage: page,
+ traces,
}) => {
- await page.getByRole('button', { name: 'Analytics' }).click();
- const panel = page.getByTestId('trace-analytics-panel');
+ await traces.analytics.open();
+ const panel = traces.analytics.panel();
await expect(panel).toBeVisible();
const zero = { x: 0, y: 0, width: 0, height: 0 };
const before = (await panel.boundingBox()) ?? zero;
- const hb =
- (await page.locator('.floating-panel__drag-handle').boundingBox()) ?? zero;
+ const hb = (await traces.analytics.dragHandle().boundingBox()) ?? zero;
// Drag the header left + down.
await page.mouse.move(hb.x + hb.width / 2, hb.y + hb.height / 2);
diff --git a/tests/e2e/tests/trace-details/preview-fields.spec.ts b/tests/e2e/tests/trace-details/preview-fields.spec.ts
index da7d582766..f0b4d67db3 100644
--- a/tests/e2e/tests/trace-details/preview-fields.spec.ts
+++ b/tests/e2e/tests/trace-details/preview-fields.spec.ts
@@ -1,13 +1,11 @@
-import { test, expect } from '../../fixtures/auth';
-import { newAdminContext } from '../../helpers/auth';
import {
- gotoTraceUntilLoaded,
- hoverFlamegraphSpan,
+ expect,
loadLargeTrace,
- resetTracePreferences,
+ onAdminPage,
seedTracesViaSeeder,
- setPreviewFieldsPreference,
-} from '../../helpers/trace-details';
+ test,
+ traceDetailsDriver,
+} from '../../drivers/traces';
// §6 — preview fields. A configured preview field appears as a row in the span
// hover card (SpanTooltipContent, testid span-hover-card-preview-<key>). The
@@ -23,7 +21,6 @@ const trace = loadLargeTrace();
// field so its value renders in the hover card.
const PREVIEW_FIELD = 'db.system';
const PREVIEW_VALUE = 'redis';
-const PREVIEW_TESTID = `span-hover-card-preview-${PREVIEW_FIELD}`;
// Skipped wholesale until the flamegraph preview-fields fetch race (FE bug, see
// the TC-01 FIXME + sprint task) is fixed — the only case here is that flamegraph
@@ -44,23 +41,19 @@ test.describe.skip('Trace details — preview fields in the hover card', () => {
test.afterAll(async ({ browser }) => {
// Reset prefs to defaults (afterAll can't use the authedPage fixture).
- const ctx = await newAdminContext(browser);
- const page = await ctx.newPage();
- await resetTracePreferences(page);
- await ctx.close();
+ await onAdminPage(browser, (page) => traceDetailsDriver(page).prefs.reset());
});
- test.beforeEach(async ({ authedPage: page }) => {
+ test.beforeEach(async ({ traces }) => {
// Seed the preview field BEFORE navigating so the on-mount prefs fetch
// returns it and the hover card renders the row.
// db.system is a span ATTRIBUTE (fieldContext 'attribute', not 'span') —
// the flamegraph fetches fields selectively, so the wrong context means
// the bar's span wouldn't carry the value and the hover row wouldn't render.
- await setPreviewFieldsPreference(page, [
+ await traces.prefs.previewFields([
{ name: PREVIEW_FIELD, fieldContext: 'attribute', fieldDataType: 'string' },
]);
- await gotoTraceUntilLoaded(
- page,
+ await traces.goto(
`/trace/${trace.traceId}`,
`cell-0-${trace.landmarks.root}`,
);
@@ -75,11 +68,12 @@ test.describe.skip('Trace details — preview fields in the hover card', () => {
// gates/refetches on previewFields. See sprint task.
test.fixme('TC-01 flamegraph hover card shows the configured preview field', async ({
authedPage: page,
+ traces,
}) => {
- const previewRow = page.getByTestId(PREVIEW_TESTID).first();
+ const previewRow = traces.hoverCard.preview(PREVIEW_FIELD).first();
await expect(async () => {
await page.mouse.move(0, 0);
- await hoverFlamegraphSpan(page, trace.landmarks.db);
+ await traces.flame.hover(trace.landmarks.db);
await expect(previewRow).toBeVisible({ timeout: 1500 });
}).toPass({ timeout: 15_000 });
diff --git a/tests/e2e/tests/trace-details/waterfall-filter.spec.ts b/tests/e2e/tests/trace-details/waterfall-filter.spec.ts
new file mode 100644
index 0000000000..3f2218c3a7
--- /dev/null
+++ b/tests/e2e/tests/trace-details/waterfall-filter.spec.ts
@@ -0,0 +1,90 @@
+import {
+ expect,
+ loadLargeTrace,
+ seedTracesViaSeeder,
+ test,
+} from '../../drivers/traces';
+
+const trace = loadLargeTrace();
+const rootRow = `cell-0-${trace.landmarks.root}`;
+const errorIds = new Set(trace.landmarks.errors);
+
+// The filter lists matches in timestamp order.
+const authSpans = trace.spans
+ .filter((span) => span.resources?.['service.name'] === 'auth-service')
+ .sort((a, b) => Date.parse(a.timestamp) - Date.parse(b.timestamp))
+ .map((span) => span.span_id);
+
+test.describe('Trace details, waterfall filter', () => {
+ test.beforeAll(async ({ playwright }) => {
+ const request = await playwright.request.newContext();
+ await seedTracesViaSeeder(request, trace.spans);
+ await request.dispose();
+ });
+
+ test('TC-01 highlight errors marks exactly the error spans', async ({
+ traces,
+ }) => {
+ const filter = traces.waterfallFilter;
+ await traces.goto(`/trace/${trace.traceId}`, rootRow);
+
+ await filter.highlightErrors(true);
+
+ await expect
+ .poll(async () => (await filter.resultCount()).total)
+ .toBe(errorIds.size);
+ // The first match is selected, so it reads `selected` rather than
+ // `highlighted`.
+ expect(errorIds.has(filter.selectedSpanId() ?? '')).toBe(true);
+
+ const states = await filter.rowStates();
+ const selected = filter.selectedSpanId();
+ const expected = Object.fromEntries(
+ Object.keys(states).map((spanId) => [
+ spanId,
+ spanId === selected
+ ? 'selected'
+ : errorIds.has(spanId)
+ ? 'highlighted'
+ : 'dimmed',
+ ]),
+ );
+ expect(states).toEqual(expected);
+ });
+
+ test('TC-02 a typed filter navigates matches with next and prev', async ({
+ traces,
+ }) => {
+ expect(authSpans).toHaveLength(2);
+ const filter = traces.waterfallFilter;
+ await traces.goto(`/trace/${trace.traceId}`, rootRow);
+
+ await filter.apply("service.name = 'auth-service'");
+ await expect(filter.count()).toHaveText('1 / 2');
+ await expect.poll(() => filter.selectedSpanId()).toBe(authSpans[0]);
+
+ await filter.next();
+ await expect(filter.count()).toHaveText('2 / 2');
+ await expect.poll(() => filter.selectedSpanId()).toBe(authSpans[1]);
+
+ await filter.prev();
+ await expect(filter.count()).toHaveText('1 / 2');
+ await expect.poll(() => filter.selectedSpanId()).toBe(authSpans[0]);
+ });
+
+ test('TC-03 a filter with no match says so and clearing restores the rows', async ({
+ traces,
+ }) => {
+ const filter = traces.waterfallFilter;
+ await traces.goto(`/trace/${trace.traceId}`, rootRow);
+
+ await filter.apply("name = 'does-not-exist'");
+ await expect(filter.noResults()).toHaveText('No results found');
+
+ await filter.clear();
+ await expect(filter.noResults()).toHaveCount(0);
+ const states = Object.values(await filter.rowStates());
+ expect(states.length).toBeGreaterThan(0);
+ expect(states).not.toContain('dimmed');
+ });
+});
diff --git a/tests/e2e/tests/trace-details/waterfall.spec.ts b/tests/e2e/tests/trace-details/waterfall.spec.ts
index 9c65f9e461..f5d0ff430c 100644
--- a/tests/e2e/tests/trace-details/waterfall.spec.ts
+++ b/tests/e2e/tests/trace-details/waterfall.spec.ts
@@ -1,9 +1,9 @@
-import { test, expect } from '../../fixtures/auth';
import {
- gotoTraceUntilLoaded,
+ expect,
loadLargeTrace,
seedTracesViaSeeder,
-} from '../../helpers/trace-details';
+ test,
+} from '../../drivers/traces';
const trace = loadLargeTrace();
@@ -15,36 +15,32 @@ test.describe('Trace details — waterfall', () => {
});
test('TC-01 deep-link ?spanId auto-selects the span and opens the drawer', async ({
- authedPage: page,
+ traces,
}) => {
// Open the trace pre-pointed at a specific span via the URL, reloading
// until the waterfall renders (seed→query lag).
const errorSpan = trace.landmarks.errors[0];
- await gotoTraceUntilLoaded(
- page,
+ await traces.goto(
`/trace/${trace.traceId}?spanId=${errorSpan}`,
`cell-0-${errorSpan}`,
);
// the deep-linked span's row renders...
- await expect(page.getByTestId(`cell-0-${errorSpan}`)).toBeVisible();
+ await expect(traces.span.row(errorSpan)).toBeVisible();
// ...and it auto-selects → the drawer is open (Overview tab is drawer-only)
- await expect(page.getByRole('tab', { name: /overview/i })).toBeVisible();
+ await expect(traces.span.overviewTab()).toBeVisible();
});
test('TC-02 deep-linking a deeply-nested span auto-expands ancestors and scrolls it into view', async ({
+ traces,
authedPage: page,
}) => {
// deepLeaf sits ~34 levels down; rendering its row at all proves every
// ancestor auto-expanded and the waterfall scrolled it into view.
const deep = trace.landmarks.deepLeaf;
- await gotoTraceUntilLoaded(
- page,
- `/trace/${trace.traceId}?spanId=${deep}`,
- `cell-0-${deep}`,
- );
+ await traces.goto(`/trace/${trace.traceId}?spanId=${deep}`, `cell-0-${deep}`);
- await expect(page.getByTestId(`cell-0-${deep}`)).toBeVisible();
+ await expect(traces.span.row(deep)).toBeVisible();
await expect(page).toHaveURL(new RegExp(`spanId=${deep}`));
});
});
diff --git a/tests/e2e/tests/traces-explorer/saved-views.spec.ts b/tests/e2e/tests/traces-explorer/saved-views.spec.ts
new file mode 100644
index 0000000000..4c2cde0671
--- /dev/null
+++ b/tests/e2e/tests/traces-explorer/saved-views.spec.ts
@@ -0,0 +1,122 @@
+import { expect, test } from '../../drivers/traces-explorer';
+
+test.describe('Traces explorer, saved views', () => {
+ test('TC-01 a view saved from the explorer appears in the views list', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ const name = `${seed.stamp}-tbl`;
+ await traces.goto();
+ await traces.filterService(seed.service);
+ await traces.switchView('table');
+ await traces.views.saveAs(name);
+
+ await expect(traces.toast('View created')).toBeVisible();
+ expect(traces.urlParam('viewKey')).toBeTruthy();
+
+ await traces.views.search(name);
+ await expect(traces.views.row(name)).toBeVisible();
+ });
+
+ test('TC-02 opening a saved view restores its query and panel', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ const name = `${seed.stamp}-open`;
+ await traces.views.create(name, {
+ expression: `service.name = '${seed.service}'`,
+ panelType: 'trace',
+ });
+
+ await traces.goto();
+ await traces.views.pick(name);
+
+ await expect(async () => {
+ expect(traces.panelType()).toBe('trace');
+ }).toPass();
+ await traces.search.expectContains(seed.service);
+ await traces.waitForRow(seed.traceId);
+ });
+
+ test('TC-03 updating a loaded view persists the new query', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ const name = `${seed.stamp}-upd`;
+ const next = `service.name = '${seed.service}' AND name = 'GET /orders'`;
+ await traces.views.create(name, {
+ expression: `service.name = '${seed.service}'`,
+ });
+
+ await traces.goto();
+ await traces.views.pick(name);
+ await traces.search.apply(next);
+ await traces.views.update();
+
+ await expect(traces.toast('View updated')).toBeVisible();
+ const stored = (await traces.views.list()).find(
+ (view) => view.spec.displayName === name,
+ );
+ expect(JSON.stringify(stored?.spec.queries)).toContain(
+ "name = 'GET /orders'",
+ );
+
+ await traces.reload();
+ await traces.search.expectContains("name = 'GET /orders'");
+ });
+
+ test('TC-04 rename and delete in the views list persist through the API', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ const before = `${seed.stamp}-ren-a`;
+ const after = `${seed.stamp}-ren-b`;
+ await traces.views.create(before, {
+ expression: `service.name = '${seed.service}'`,
+ });
+
+ await traces.goto();
+ await traces.views.search(seed.stamp);
+ await traces.views.rename(before, after);
+
+ await traces.reload();
+ await traces.views.search(seed.stamp);
+ await expect(traces.views.row(after)).toBeVisible();
+ await expect(traces.views.row(before)).toHaveCount(0);
+
+ await traces.views.pick(after);
+ await traces.search.expectContains(seed.service);
+
+ await traces.views.search(after);
+ await traces.views.remove(after);
+
+ await traces.reload();
+ await traces.views.search(after);
+ await expect(traces.views.row(after)).toHaveCount(0);
+ expect(
+ (await traces.views.list()).map((view) => view.spec.displayName),
+ ).not.toContain(after);
+ });
+
+ test('TC-05 clearing a loaded view resets the explorer', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ const name = `${seed.stamp}-clr`;
+ await traces.views.create(name, {
+ expression: `service.name = '${seed.service}'`,
+ panelType: 'table',
+ });
+
+ await traces.goto();
+ await traces.views.pick(name);
+ await traces.views.clear();
+
+ expect(traces.urlParam('viewKey')).toBeNull();
+ await expect(traces.viewButton('list')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await traces.search.expectExpression('');
+ });
+});
diff --git a/tests/e2e/tests/traces-explorer/views.spec.ts b/tests/e2e/tests/traces-explorer/views.spec.ts
new file mode 100644
index 0000000000..0a8de2458c
--- /dev/null
+++ b/tests/e2e/tests/traces-explorer/views.spec.ts
@@ -0,0 +1,136 @@
+import {
+ expect,
+ test,
+ withoutParserNoise,
+} from '../../drivers/traces-explorer';
+
+test.describe('Traces explorer, views', () => {
+ test('TC-01 list view renders seeded spans from the real backend', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ noise,
+ }) => {
+ await traces.goto();
+ await traces.filterService(seed.service);
+ await traces.waitForRow(seed.rootSpanId);
+
+ await expect(traces.cell(seed.rootSpanId, 'service.name')).toHaveText(
+ seed.service,
+ );
+ await expect(traces.cell(seed.rootSpanId, 'name')).toHaveText('GET /orders');
+ await expect(traces.cell(seed.rootSpanId, 'duration_nano')).toHaveText(/ms$/);
+ await expect(
+ traces.cell(seed.errorSpanId, 'response_status_code'),
+ ).toHaveText('500');
+
+ expect(withoutParserNoise(noise.errors)).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 clicking a list row opens that span in trace details', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ await traces.goto();
+ await traces.filterService(seed.service);
+ await traces.waitForRow(seed.errorSpanId);
+
+ await traces.openRow(seed.errorSpanId, seed.traceId);
+
+ await expect(traces.traceDetailsRow(seed.errorSpanId)).toBeVisible();
+ });
+
+ test('TC-03 trace view lists the seeded trace with its span count', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ await traces.goto();
+ await traces.filterService(seed.service);
+ await traces.switchView('trace');
+
+ await traces.waitForRow(seed.traceId);
+ await expect(traces.table('trace')).toBeVisible();
+ await expect(traces.cell(seed.traceId, 'span_count')).toHaveText(
+ String(seed.traceSpanCount),
+ );
+ await expect(traces.cell(seed.traceId, 'service.name')).toHaveText(
+ seed.service,
+ );
+ });
+
+ test('TC-04 time series view draws a chart for the filter', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ await traces.goto();
+ await traces.filterService(seed.service);
+ await traces.switchView('timeseries');
+
+ await expect(traces.timeSeriesGraph()).toBeVisible();
+ await expect(traces.timeSeriesCanvas()).toBeVisible({
+ timeout: 30_000,
+ });
+ });
+
+ test('TC-05 table view shows the aggregated count', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ await traces.goto();
+ await traces.filterService(seed.service);
+ await traces.switchView('table');
+
+ await expect(traces.tableCell(String(seed.spanCount))).toBeVisible({
+ timeout: 30_000,
+ });
+ });
+
+ test('TC-06 the chosen view survives a reload', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ await traces.goto();
+ await traces.filterService(seed.service);
+ await traces.switchView('table');
+ await traces.reload();
+
+ await expect(traces.viewButton('table')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ await expect(traces.tableView()).toBeVisible();
+ });
+
+ test('TC-07 a deep-linked selectedExplorerView does not override a later view switch', async ({
+ traces,
+ }) => {
+ // `getExplorerViewFromUrl` (utils/explorerUtils.ts) prefers
+ // `selectedExplorerView` over `panelTypes`, and a view switch rewrites only
+ // `panelTypes`, so the stale param wins on reload.
+ test.fail(true, 'selectedExplorerView outranks panelTypes after a switch');
+
+ await traces.goto({ selectedExplorerView: 'list' });
+ await traces.switchView('table');
+ await traces.reload();
+
+ await expect(traces.viewButton('table')).toHaveAttribute(
+ 'aria-pressed',
+ 'true',
+ );
+ });
+
+ test('TC-08 the traces quick-filter rail offers the seeded service and narrows the list', async ({
+ traces,
+ tracesExplorerSeed: seed,
+ }) => {
+ await traces.goto();
+ await traces.pickOnly('service.name', seed.service);
+
+ await traces.waitForRow(seed.rootSpanId);
+ await expect(async () => {
+ const services = await traces.rowServices().allInnerTexts();
+ expect(services.length).toBeGreaterThan(0);
+ expect(new Set(services)).toEqual(new Set([seed.service]));
+ }).toPass();
+ });
+});
diff --git a/tests/e2e/tests/traces-funnels/list.spec.ts b/tests/e2e/tests/traces-funnels/list.spec.ts
new file mode 100644
index 0000000000..398fecca95
--- /dev/null
+++ b/tests/e2e/tests/traces-funnels/list.spec.ts
@@ -0,0 +1,80 @@
+import { expect, test } from '../../drivers/funnels';
+
+test.describe('Trace funnels, list', () => {
+ test('TC-01 funnels list renders and a funnel is created through the modal', async ({
+ funnels,
+ funnelSpans,
+ noise,
+ }) => {
+ const name = `${funnelSpans.stamp}-new`;
+ await funnels.gotoList();
+ const id = await funnels.create(name);
+
+ await expect(funnels.title()).toHaveText(name);
+
+ await funnels.gotoList();
+ await funnels.search(funnelSpans.stamp);
+ await expect(funnels.item(name)).toBeVisible();
+ await expect(funnels.item(name)).toHaveAttribute(
+ 'data-testid',
+ `funnel-item-${id}`,
+ );
+
+ expect(noise.errors).toEqual([]);
+ expect(noise.failedResponses).toEqual([]);
+ });
+
+ test('TC-02 a duplicate name is rejected inline', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ const name = `${funnelSpans.stamp}-dup`;
+ await funnels.seed.create(name);
+
+ await funnels.gotoList();
+ expect(await funnels.submitCreate(name)).toBe(400);
+
+ await expect(funnels.createError()).toBeVisible();
+ await expect(funnels.createModal()).toBeVisible();
+ await expect(funnels.title()).toHaveCount(0);
+ await expect(funnels.newFunnelButton()).toBeVisible();
+ });
+
+ test('TC-03 rename from the list persists', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ const from = `${funnelSpans.stamp}-rename-a`;
+ const to = `${funnelSpans.stamp}-rename-b`;
+ const { funnel_id: id } = await funnels.seed.create(from);
+
+ await funnels.gotoList();
+ await funnels.search(funnelSpans.stamp);
+ await funnels.rename(from, to);
+
+ await funnels.gotoList();
+ await funnels.search(funnelSpans.stamp);
+ await expect(funnels.item(to)).toBeVisible();
+ await expect(funnels.item(from)).toHaveCount(0);
+ expect((await funnels.seed.get(id)).funnel_name).toBe(to);
+ });
+
+ test('TC-04 delete from the detail page returns to the list', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ const name = `${funnelSpans.stamp}-delete`;
+ const { funnel_id: id } = await funnels.seed.create(name);
+
+ await funnels.goto(id);
+ await funnels.removeFromDetail();
+
+ await expect(funnels.newFunnelButton()).toBeVisible();
+ expect(funnels.pathname()).toBe('/traces/funnels');
+ await funnels.gotoList();
+ await funnels.search(funnelSpans.stamp);
+ await expect(funnels.item(name)).toHaveCount(0);
+ const remaining = await funnels.seed.list();
+ expect(remaining.map((funnel) => funnel.funnel_id)).not.toContain(id);
+ });
+});
diff --git a/tests/e2e/tests/traces-funnels/steps.spec.ts b/tests/e2e/tests/traces-funnels/steps.spec.ts
new file mode 100644
index 0000000000..8cdebfafad
--- /dev/null
+++ b/tests/e2e/tests/traces-funnels/steps.spec.ts
@@ -0,0 +1,159 @@
+import {
+ allowFor,
+ expect,
+ SEEDED_DATA_TIMEOUT,
+ SEEDED_TEST_BUDGET,
+ test,
+} from '../../drivers/funnels';
+
+test.describe('Trace funnels, steps', () => {
+ test('TC-01 configuring two steps validates against seeded traces and shows results', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ const { funnel_id: id } = await funnels.seed.create(
+ `${funnelSpans.stamp}-config`,
+ );
+ const { services, spans } = funnelSpans;
+
+ await funnels.goto(id);
+ await funnels.setStep(0, services.a, spans.a);
+ await funnels.setStep(1, services.b, spans.b);
+
+ await expect(funnels.validStatus()).toHaveText('Valid traces found', {
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ await expect(funnels.results()).toContainText('Overall Funnel Metrics', {
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+
+ await expect(funnels.slowTraceIdCells().first()).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ const slow = await funnels.traceIdsIn(funnels.slowTraces());
+ expect(slow.length).toBeGreaterThanOrEqual(1);
+ for (const traceId of slow) {
+ expect(funnelSpans.traceIds).toContain(traceId);
+ }
+ await expect(funnels.errorTrace(funnelSpans.errorTraceId)).toBeVisible({
+ timeout: SEEDED_DATA_TIMEOUT,
+ });
+ });
+
+ test('TC-02 saving steps persists across reload', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ const { funnel_id: id } = await funnels.seed.create(
+ `${funnelSpans.stamp}-save`,
+ );
+ const { services, spans } = funnelSpans;
+
+ await funnels.goto(id);
+ await funnels.setStep(0, services.a, spans.a);
+ await funnels.setStep(1, services.b, spans.b);
+ await funnels.save();
+
+ const saved = await funnels.seed.get(id);
+ expect(
+ saved.steps?.map((step) => [step.service_name, step.span_name]),
+ ).toEqual([
+ [services.a, spans.a],
+ [services.b, spans.b],
+ ]);
+
+ // `goto` clears the unsaved-steps key, so the reload reads the server copy.
+ await funnels.goto(id);
+ await expect(funnels.stepSelect(0, 'service')).toContainText(services.a);
+ await expect(funnels.stepSelect(0, 'span')).toContainText(spans.a);
+ await expect(funnels.stepSelect(1, 'service')).toContainText(services.b);
+ await expect(funnels.stepSelect(1, 'span')).toContainText(spans.b);
+ await expect(funnels.saveButton()).toBeDisabled();
+ });
+
+ test('TC-03 latency pointer choice persists', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ const { services, spans } = funnelSpans;
+ const { funnel_id: id } = await funnels.seed.create(
+ `${funnelSpans.stamp}-pointer`,
+ );
+ await funnels.seed.setSteps(id, [
+ { service: services.a, span: spans.a },
+ { service: services.b, span: spans.b },
+ ]);
+
+ await funnels.goto(id);
+ await expect(funnels.latencyPointer(1)).toContainText('End of span');
+ await funnels.setLatencyPointer(1, 'Start of span');
+ await funnels.save();
+
+ await funnels.goto(id);
+ await expect(funnels.latencyPointer(1)).toContainText('Start of span');
+ expect((await funnels.seed.get(id)).steps?.[1].latency_pointer).toBe('start');
+ });
+
+ test('TC-04 add a third step and delete it', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ const { services, spans } = funnelSpans;
+ const { funnel_id: id } = await funnels.seed.create(
+ `${funnelSpans.stamp}-add-step`,
+ );
+ await funnels.seed.setSteps(id, [
+ { service: services.a, span: spans.a },
+ { service: services.b, span: spans.b },
+ ]);
+
+ await funnels.goto(id);
+ await expect(funnels.stepsCount()).toHaveText('2 steps');
+ await funnels.openStepActions(0);
+ await expect(funnels.stepDeleteAction()).toBeDisabled();
+ // The trigger toggles the popover closed again.
+ await funnels.stepActionsTrigger(0).click();
+
+ await funnels.addStep();
+ await expect(funnels.stepsCount()).toHaveText('3 steps');
+ await expect(funnels.step(2)).toBeVisible();
+
+ await funnels.deleteStep(2);
+ await expect(funnels.stepsCount()).toHaveText('2 steps');
+ await expect(funnels.step(2)).toHaveCount(0);
+ });
+
+ test('TC-05 adding a span to a funnel from trace details', async ({
+ funnels,
+ funnelSpans,
+ }) => {
+ allowFor(SEEDED_TEST_BUDGET);
+ const { services, spans } = funnelSpans;
+ const { funnel_id: id } = await funnels.seed.create(
+ `${funnelSpans.stamp}-from-trace`,
+ );
+ await funnels.seed.setSteps(id, [
+ { service: services.a, span: spans.a },
+ { service: services.b, span: spans.b },
+ ]);
+
+ const traceId = funnelSpans.traceIds[0];
+ const spanId = funnelSpans.rootSpanIds[traceId];
+ await funnels.traces.goto(
+ `/trace/${traceId}?spanId=${spanId}`,
+ `cell-0-${spanId}`,
+ );
+ await funnels.addSpanModal.open(spanId);
+ await funnels.addSpanModal.pickFunnel(id);
+ await funnels.addSpanModal.addForNewStep();
+ await funnels.addSpanModal.save();
+
+ const steps = (await funnels.seed.get(id)).steps ?? [];
+ expect(steps).toHaveLength(3);
+ expect([steps[2].service_name, steps[2].span_name]).toEqual([
+ services.a,
+ spans.a,
+ ]);
+ });
+});
diff --git a/tests/e2e/tsconfig.json b/tests/e2e/tsconfig.json
index d0ed1b7612..62ef59ff61 100644
--- a/tests/e2e/tsconfig.json
+++ b/tests/e2e/tsconfig.json
@@ -1,9 +1,13 @@
{
"compilerOptions": {
"target": "ES2020",
- "module": "commonjs",
+ // `moduleResolution: bundler` requires `module` at es2015+. Playwright
+ // transpiles with its own loader and this config only runs with `--noEmit`.
+ "module": "esnext",
"moduleResolution": "bundler",
- "lib": ["ES2020"],
+ // `DOM` is needed because drivers run browser code inside `page.evaluate`
+ // callbacks (localStorage, window, document).
+ "lib": ["ES2020", "DOM"],
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
@@ -12,12 +16,9 @@
"types": ["node", "@playwright/test"],
"paths": {
"@tests/*": ["./tests/*"],
- "@helpers/*": ["./helpers/*"],
"@specs/*": ["./specs/*"]
- },
- "outDir": "./dist",
- "rootDir": "."
+ }
},
- "include": ["tests/**/*.ts", "drivers/**/*.ts", "helpers/**/*.ts", "fixtures/**/*.ts", "bootstrap/**/*.ts", "playwright.config.ts"],
+ "include": ["tests/**/*.ts", "drivers/**/*.ts", "bootstrap/**/*.ts", "playwright.config.ts"],
"exclude": ["node_modules", "dist"]
}
diff --git a/tests/fixtures/traces.py b/tests/fixtures/traces.py
index 9c40536fb2..730b301980 100644
--- a/tests/fixtures/traces.py
+++ b/tests/fixtures/traces.py
@@ -203,29 +203,65 @@ class TracesErrorEvent(ABC):
event: TracesEvent
error_id: str
error_group_id: str
+ trace_id: str
+ span_id: str
+ service_name: str
+ resources: dict[str, str]
def __init__(
self,
event: TracesEvent,
error_id: str = "",
error_group_id: str = "",
+ trace_id: str = "",
+ span_id: str = "",
+ service_name: str = "",
+ resources: dict[str, str] | None = None,
) -> None:
self.event = event
self.error_id = error_id
self.error_group_id = error_group_id
+ self.trace_id = trace_id
+ self.span_id = span_id
+ self.service_name = service_name
+ self.resources = resources or {}
def np_arr(self) -> np.array:
+ attrs = self.event.attribute_map
return np.array(
[
- self.event.time_unix_nano,
+ datetime.datetime.fromtimestamp(int(self.event.time_unix_nano) / 1e9, tz=datetime.UTC),
self.error_id,
self.error_group_id,
- self.event.name,
- json.dumps(self.event.attribute_map),
- ]
+ self.trace_id,
+ self.span_id,
+ self.service_name,
+ attrs.get("exception.type", ""),
+ attrs.get("exception.message", ""),
+ attrs.get("exception.stacktrace", ""),
+ str(attrs.get("exception.escaped", "")).lower() == "true",
+ dict(self.resources),
+ ],
+ dtype=object,
)
+# Column order of TracesErrorEvent.np_arr.
+ERROR_INDEX_COLUMNS = [
+ "timestamp",
+ "errorID",
+ "groupID",
+ "traceID",
+ "spanID",
+ "serviceName",
+ "exceptionType",
+ "exceptionMessage",
+ "exceptionStacktrace",
+ "exceptionEscaped",
+ "resourceTagsMap",
+]
+
+
class TracesSpanAttribute(ABC):
key: str
tag_type: str
@@ -600,6 +636,10 @@ class Traces(ABC):
event=event,
error_id=error_id,
error_group_id=error_group_id,
+ trace_id=self.trace_id,
+ span_id=self.span_id,
+ service_name=self.service_name,
+ resources=self.resources_string,
)
def _determine_is_remote(self, flags: np.uint32) -> str:
@@ -732,6 +772,14 @@ class Traces(ABC):
trace_state=data.get("trace_state", ""),
flags=data.get("flags", 0),
scope=data.get("scope", {}),
+ events=[
+ TracesEvent(
+ name=event["name"],
+ timestamp=parse_timestamp(event["timestamp"]),
+ attribute_map={k: str(v) for k, v in (event.get("attributes") or {}).items()},
+ )
+ for event in data.get("events") or []
+ ],
)
@classmethod
@@ -885,6 +933,7 @@ def insert_traces_to_clickhouse(conn, traces: list[Traces]) -> None:
conn.insert(
database="signoz_traces",
table="distributed_signoz_error_index_v2",
+ column_names=ERROR_INDEX_COLUMNS,
data=[error_event.np_arr() for error_event in error_events],
)