Compare commits

...

14 Commits

Author SHA1 Message Date
Manika Malhotra
5f240876fe test(alerts): drop a mock of a helper AlertThreshold does not use 2026-11-30 14:49:01 +05:30
Manika Malhotra
8b3ea4bd89 chore(dashboard): keep PANEL_ACTION_META and drop a link to the deleted isResolved 2026-11-30 14:44:37 +05:30
Manika Malhotra
8f4d724ca6 fix(alerts): keep the check that SPEC_FIELDS lists every channel field 2026-11-30 14:44:16 +05:30
Manika Malhotra
08e7ad7609 refactor(frontend): keep the exports of code that stays 2026-11-30 13:56:37 +05:30
Manika Malhotra
85939b183c chore(frontend): remove dead global styles 2026-11-30 13:28:37 +05:30
Manika Malhotra
f23907d430 chore(frontend): remove unused CSS module classes 2026-11-30 13:28:34 +05:30
Manika Malhotra
05e394f633 refactor(dashboard): remove unused exports 2026-11-30 13:28:23 +05:30
Manika Malhotra
3f34166c43 refactor(alerts): remove unused exports 2026-11-30 13:28:17 +05:30
Manika Malhotra
8d48af6722 refactor(infra-monitoring): remove unused exports 2026-11-30 13:28:11 +05:30
Manika Malhotra
d9c4cf3df4 chore(dashboard): remove the unused first-section migration flow 2026-11-30 13:28:04 +05:30
Manika Malhotra
e792c299af test(dashboard): remove the test of the unused histogram chart options 2026-11-30 13:28:03 +05:30
Manika Malhotra
2be92484b5 chore(frontend): remove unused files 2026-11-30 13:28:02 +05:30
Vinicius Lourenço
c65a73001d test: fix flaky jest, storybook and e2e tests (#13773)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
#### Description

Fixes the jest, storybook and e2e flakes that keep failing CI on busy
runners. I found them by rerunning each suite on fewer CPUs, close to
what a GitHub runner has.

In jest, two tests failed on slow role queries or counted a row the form
no longer adds. The slowest suites (LLM settings, quick filters, cloud
account setup, planned downtime, panel menu) now skip user-event's
per-key delay and render fewer rows. That delay option is one shared
`NO_DELAY_USER_EVENT` constant now, and the test rules say when to keep
the delay.

In storybook, the cloud account stories wait for the setup command
before pressing Cancel. Each story gets 60 s instead of 30 s, because
the first story of a heavy page can spend most of 30 s compiling.

In e2e, browser contexts drop their route handlers before closing, quick
filter seeds add the fields a test needs instead of replacing the org's
filters, multiple-select dropdowns close from their trigger (Escape also
closed the dialog around them), and a dropped wheel event is sent again.
Google Fonts and the changelog CMS are blocked so their failures stay
out of the console checks. The stack fixtures give WireMock and the
SigNoz container 60 tries to come up instead of 10.

The HAVING and aggregation editors in the query builder dropped keys and
jumped the caret to the start when the page was busy, which failed the
query builder e2e specs. `@uiw/react-codemirror` wrote an older `value`
over keys typed since, so the editors now own their text and only a
change from outside, such as a saved view, is written into them.

The lessons also go into the page-story skill and the Playwright
generator and healer agents, since they regenerate those files and would
bring the flakes back.

With the e2e stack on fewer CPUs, a full run passed 788 tests with none
flaky.

#### Screenshots / Screen Recordings

Typing into the aggregation and HAVING editors with the page under
simulated CPU load (the banner is a test overlay, not app UI).

Before, on `main`, the text gets scrambled:


https://github.com/user-attachments/assets/665aad3e-c036-4e00-923c-5707a380a441

After, under the same load:


https://github.com/user-attachments/assets/2213a260-0e19-47ab-904d-501dea86db95
2026-11-30 05:11:23 +00:00
Gaurav Tewari
a6be4d894c feat(ai-observability): create alert and add to dashboard in the AI explorer views (#13445)
Some checks failed
cacheci / tests (push) Has been cancelled
build-staging / prepare (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
#### Description

- Adds Create an alert and Add to dashboard to the AI explorer's List,
Trace, Time Series and Table views through the shared `ExplorerActions`.
The query stays in the AI slot, so the alert opens as an AI Trace-based
Alert and the panel on the AI Query Builder tab.
- List and Trace show only the first query's filter, so their alert and
panel keep only that query, use `count()` and drop the group by, having,
order by, formulas, step interval, limit and legend another view set.
List exports a List panel with the columns the List view shows; Trace
exports a Time Series.
- `ExplorerActions` takes the explorer page (`ExplorerActionsSource`)
instead of a `DataSource`, so the AI explorer, which queries traces,
logs its own `AI Observability Explorer: …` events with `sourcepage:
ai_observability`. Logs, Traces and Metrics send the same events and
payloads as before.
- Create an alert encodes the query twice, like Add to dashboard,
because the alert page decodes it twice. Filters with `%` or `+` used to
open the type picker or lose the `+`, in the Logs and Traces explorers
too.
- Stories: `AddToDashboardDialog` on the AI explorer page;
`AITracesAlertFromExplorer` on Create alert and `AIExplorerExport` on
the panel editor, each opened through the explorer's own link. The
explorer page's plays moved to `__story_mockdata__/explorer.play.ts`.

#### Issues closed by this PR

Closes SigNoz/nerve-pod#274

#### Screenshots / Screen Recordings



https://github.com/user-attachments/assets/a3855187-447a-45bc-b86a-7a185e9929f5



#### Additional Information

- The AI table header renders whenever there is no error, as in traces,
so the actions show while data loads.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-27 09:26:17 +00:00
196 changed files with 1888 additions and 2880 deletions

View File

@@ -20,12 +20,16 @@ You are the Playwright Test Generator for the SigNoz frontend. You take a plan w
await expect(routing.activeRouteTab(PATH.metricsSummary)).toBeVisible();
});
```
- 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.
- 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. A wait for "the request the action fired" skips aborted requests, which have no response: Run after a cancel re-sends the cancelled query and aborts it, and `query-builder/run` TC-34 read that one.
- A page action that opens an explorer waits for the content pane's scrollbar viewport (`quick-filters-layout-content [data-overlayscrollbars-viewport]`) before anything types. The scrollbar starts on idle and re-parents the editors, so keys typed across it land at the start of the text. Typing into a CodeMirror editor retypes until the editor holds exactly the text, as `editorAt(...).type` and `querySearch.apply` do: `query-builder/aggregation` TC-17 sent `c()` for `count()`.
- `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.
- 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.
- **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 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.
- **A seed adds to org-wide settings, never replaces them.** Quick filters, org preferences and similar settings are shared by every spec on the stack, and `fullyParallel` runs those specs at once. Read the stored value and write a superset with only the missing entries, as `quickFilters.seed` does. A seed that replaced the logs filters made `query-builder/filter` TC-16 fail later on the same stack, and a restore in teardown races a parallel spec that seeded the same setting.
- **Close a multiple combobox from its trigger, never with Escape.** A multi-select stays open after a pick, and Escape also closes the dialog or page around it; `onboarding/get-started` TC-09 landed on `/home`. `comboboxAt(...).pick` already does this.
- **A context you open yourself drops its routes before closing.** Call `page.unrouteAll({ behavior: 'ignoreErrors' })` before `ctx.close()`, as `authedPage` does; a handler still inside `route.fetch` otherwise fails a test that already passed.
- **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.

View File

@@ -50,6 +50,9 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
- **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`.
- **A failure that shows only late in a long local run.** Run that spec's shard alone on a freshly seeded stack before fixing it, as CI does. A setting another spec changed and never restored, or golden telemetry aging past a query window, fails it only after the rest of the suite.
- **`route.fetch: Target page, context or browser has been closed` after the test passed.** A route handler was still fetching when the context closed. Unroute with `page.unrouteAll({ behavior: 'ignoreErrors' })` before `ctx.close()` in the fixture that opened the context.
- **Escape after a multi-select pick lands on another page.** Escape closed the dialog around the combobox too. Close it from its trigger (`comboboxAt(...).pick` does), never with another Escape.
- **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.

View File

@@ -11,6 +11,7 @@ Examples and the harness API live in [`frontend/src/tests/README.md`](../../fron
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Drop user-event's pause: `userEvent.setup(NO_DELAY_USER_EVENT)`** from `tests/test-utils`; spread it when the test needs other options. The default `delay: 0` waits a `setTimeout` after every key and click, so typing 40 characters waits 40 timer turns, each slower on a busy CI runner. With `delay: null` the actions run back to back. For a long value, click the field and `user.paste(text)` instead of typing it. Keep the default when the test checks what happens between two actions, such as a debounce per key or an update on a timer or `requestAnimationFrame` between steps: with `null` that code runs only after the whole action. Under `null` the Jest timeout can't fire mid-action, so judge a slow test by its `--verbose` time, not by whether it fails.
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.

View File

@@ -123,10 +123,11 @@ Before writing the clicks, list what has to be on screen for the play's target t
Make those checks with the page's own code instead of restating a condition. Build the rows with the builder the handler uses and the view's own filter, and check a permission with the page's own check through `accessFor(...).allows(...)`, or the role against the constant the page gates on, such as `componentPermission.action`. Export the checks from the mocks module, next to the handlers, so a handler change moves them too. The alert rules page has `listedRules`, `hasRowMenu`, `showsNoRulesPage` and `listsSavedViews`; the dashboards list has `listedDashboards`, `canList`, `canCreate` and `canUpdate`.
Two habits cover the rest:
Three habits cover the rest:
- Use `findAllBy*` and take the first whenever the text can appear twice, such as in a tooltip or a popover title.
- Wrap `toBeVisible` in `waitFor` for anything that fades in. A tooltip or toast found the moment it mounts is not visible yet.
- Wait for what a click depends on before clicking. A control can do something else until a request answers: in the cloud account setup, Cancel closes the drawer outright until the agent command exists, and asks to confirm only after. Clicking Cancel straight after Generate raced the account POST on CI; find `<provider>-agent-command` first.
## Rules

View File

@@ -28,4 +28,6 @@ until curl -sf http://127.0.0.1:6006/index.json >/dev/null 2>&1; do
sleep 1
done
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 30000 "$@"
# The first story of a heavy page compiles it on the cold dev server inside its
# own test, which outlasts 30s on a loaded runner.
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 60000 "$@"

View File

@@ -29,33 +29,6 @@
min-width: 0;
}
.overflowTrigger {
all: unset;
cursor: pointer;
}
.labelPopover {
display: flex;
flex-direction: column;
gap: 6px;
padding: 8px;
max-height: 300px;
overflow-y: auto;
}
.labelTooltip {
display: flex;
flex-direction: column;
gap: 6px;
max-height: 300px;
overflow-y: auto;
}
.labelValue {
text-overflow: ellipsis;
overflow: hidden;
}
.tooltipContent {
display: flex;
align-items: center;

View File

@@ -1,29 +1,5 @@
import type { BadgeColorType } from '@signozhq/ui/badge';
export const STATE_ORDER = ['firing', 'pending', 'inactive', 'disabled'];
export const SEVERITY_ORDER = ['critical', 'error', 'warning', 'info'];
export const STATE_LABELS: Record<string, string> = {
firing: 'Firing',
pending: 'Pending',
inactive: 'OK',
disabled: 'Disabled',
};
export const STATE_COLORS: Record<string, string> = {
firing: 'var(--bg-cherry-500)',
pending: 'var(--bg-amber-500)',
inactive: 'var(--bg-forest-500)',
disabled: 'var(--l2-foreground)',
};
export const SEVERITY_COLORS: Record<string, string> = {
critical: 'var(--bg-cherry-500)',
error: 'var(--bg-cherry-400)',
warning: 'var(--bg-amber-500)',
info: 'var(--bg-robin-500)',
};
export const SEVERITY_BADGE_COLORS: Record<string, BadgeColorType> = {
critical: 'danger',
error: 'danger',

View File

@@ -64,7 +64,7 @@ describe('InviteMembers - Submission', () => {
render(
<InviteMembers
initialRowCount={3}
initialRowCount={2}
renderFooter={({ submit }): JSX.Element => (
<button data-testid="submit-btn" onClick={submit}>
Submit
@@ -77,13 +77,11 @@ describe('InviteMembers - Submission', () => {
await pickRole(user, 0, 'role-viewer');
await enterInviteEmail(user, 1, 'bob@signoz.io');
await pickRole(user, 1, 'role-editor');
await enterInviteEmail(user, 2, 'charlie@signoz.io');
await pickRole(user, 2, 'role-admin');
await user.click(screen.getByTestId('submit-btn'));
await waitFor(() => {
expect(calls).toHaveLength(3);
expect(calls).toHaveLength(2);
});
expect(calls[0]).toMatchObject({
@@ -94,10 +92,6 @@ describe('InviteMembers - Submission', () => {
email: 'bob@signoz.io',
userRoles: [{ id: 'role-editor' }],
});
expect(calls[2]).toMatchObject({
email: 'charlie@signoz.io',
userRoles: [{ id: 'role-admin' }],
});
});
});

View File

@@ -24,11 +24,6 @@
flex-wrap: wrap;
}
.filtersLabel {
color: var(--l2-foreground);
margin-right: 2px;
}
.filterControls {
display: flex;
align-items: center;

View File

@@ -8,8 +8,3 @@
border-top: 1px solid var(--l2-border);
background: var(--l1-background);
}
.count {
font-size: var(--label-small-400-font-size);
color: var(--l3-foreground);
}

View File

@@ -74,10 +74,6 @@
padding: 1px 6px;
}
.deleteName {
color: var(--danger-background);
}
.row {
position: relative;
display: flex;

View File

@@ -62,16 +62,6 @@ $custom-border-color: #2c3044;
}
}
.all-selected-text {
position: absolute;
left: 12px;
top: 50%;
transform: translateY(-50%);
color: var(--l2-foreground);
z-index: 1;
pointer-events: none;
}
.ant-select-selector {
max-height: 200px;
overflow: auto;
@@ -450,8 +440,7 @@ $custom-border-color: #2c3044;
width: 100%;
background-color: var(--l2-background);
.select-all-option,
.custom-value-option {
.select-all-option {
padding: 8px 12px;
border-bottom: 1px solid $custom-border-color;
margin-bottom: 8px;
@@ -461,16 +450,6 @@ $custom-border-color: #2c3044;
z-index: 1;
}
.selected-values-section {
padding: 0 0 8px 0;
border-bottom: 1px solid $custom-border-color;
margin-bottom: 8px;
.selected-option {
padding: 4px 12px;
}
}
.select-group {
margin-bottom: 12px;
overflow: hidden;
@@ -656,14 +635,6 @@ $custom-border-color: #2c3044;
font-weight: 500;
}
// Custom option styles for keyboard navigation
.custom-option {
&.focused,
&.ant-select-item-option-active {
background-color: var(--l1-border) !important;
}
}
// Improve the sticky headers appearance
.custom-select-dropdown-container {
.group-label,
@@ -744,12 +715,6 @@ $custom-border-color: #2c3044;
.custom-multiselect-dropdown {
@include custom-scrollbar;
// Main content area
.options-container {
@include custom-scrollbar;
padding-right: 2px; // Add slight padding to prevent content touching scrollbar
}
// Non-sectioned options
.no-section-options {
@include nested-scrollbar;
@@ -762,11 +727,6 @@ $custom-border-color: #2c3044;
.custom-select-dropdown-container,
.custom-multiselect-dropdown-container {
@include custom-scrollbar;
// Add subtle shadow inside to indicate scrollable area
&.has-overflow {
box-shadow: inset 0 -10px 10px -10px rgba(0, 0, 0, 0.2);
}
}
// Light Mode Overrides
@@ -958,16 +918,11 @@ $custom-border-color: #2c3044;
}
.custom-multiselect-dropdown {
.select-all-option,
.custom-value-option {
.select-all-option {
border-bottom: 1px solid #f0f0f0;
background-color: #fafafa;
}
.selected-values-section {
border-bottom: 1px solid #f0f0f0;
}
.status-message {
color: rgba(0, 0, 0, 0.65);
border-top: 1px dashed #f0f0f0;
@@ -984,13 +939,6 @@ $custom-border-color: #2c3044;
background-color: rgba(24, 144, 255, 0.2);
}
.custom-option {
&.focused,
&.ant-select-item-option-active {
background-color: #f5f5f5 !important;
}
}
.custom-select-dropdown-container {
.group-label,
.ant-select-item-group {

View File

@@ -1,5 +1,5 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { useEffect, useMemo, useRef, useState } from 'react';
import { useEffect, useMemo, useState } from 'react';
import {
autocompletion,
closeCompletion,
@@ -16,6 +16,7 @@ import CodeMirror, { EditorView, keymap } from '@uiw/react-codemirror';
import { Button } from 'antd';
import { Having } from 'api/v5/v5';
import { useQueryBuilderV2Context } from 'components/QueryBuilderV2/QueryBuilderV2Context';
import { useEditorDraft } from 'components/QueryBuilderV2/QueryV2/useEditorDraft';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { ChevronUp } from '@signozhq/icons';
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
@@ -99,28 +100,20 @@ function HavingFilter({
const { getAggregationOptions } = useQueryBuilderV2Context();
const aggregationOptions = getAggregationOptions(queryData.queryName);
const having = queryData?.having as Having;
const [input, setInput] = useState(having?.expression || '');
useEffect(() => {
setInput(having?.expression || '');
}, [having?.expression]);
const { editorRef, editorProps } = useEditorDraft(
having?.expression || '',
onChange,
);
const [isFocused, setIsFocused] = useState(false);
const editorRef = useRef<EditorView | null>(null);
const [options, setOptions] = useState<{ label: string; value: string }[]>([]);
const handleChange = (value: string): void => {
setInput(value);
onChange(value);
};
useEffect(() => {
if (isFocused && editorRef.current && options.length > 0) {
startCompletion(editorRef.current);
}
}, [isFocused, options]);
}, [editorRef, isFocused, options]);
// Update options when aggregation options change
useEffect(() => {
@@ -329,8 +322,7 @@ function HavingFilter({
<div className="having-filter-container">
<div className="having-filter-select-container">
<CodeMirror
value={input}
onChange={handleChange}
{...editorProps}
theme={isDarkMode ? copilot : githubLight}
data-testid="having-editor"
className="having-filter-select-editor"
@@ -354,9 +346,6 @@ function HavingFilter({
autocompletion: true,
completionKeymap: true,
}}
onCreateEditor={(view: EditorView): void => {
editorRef.current = view;
}}
onFocus={(): void => {
setIsFocused(true);
if (editorRef.current) {

View File

@@ -1,6 +1,6 @@
/* eslint-disable import/no-extraneous-dependencies */
/* eslint-disable sonarjs/cognitive-complexity */
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
autocompletion,
closeCompletion,
@@ -36,6 +36,7 @@ import {
} from 'types/common/queryBuilder';
import { useQueryBuilderV2Context } from '../../QueryBuilderV2Context';
import { useEditorDraft } from '../useEditorDraft';
import './QueryAggregation.styles.scss';
@@ -175,20 +176,17 @@ function QueryAggregationSelect({
[],
);
const [input, setInput] = useState(
formatAggregations(queryData?.aggregations),
);
useEffect(() => {
setInput(formatAggregations(queryData?.aggregations));
}, [queryData?.aggregations, formatAggregations]);
const {
draft: input,
editorRef,
editorProps,
} = useEditorDraft(formatAggregations(queryData?.aggregations), onChange);
const [cursorPos, setCursorPos] = useState(0);
const [functionArgPairs, setFunctionArgPairs] = useState<
{ func: string; arg: string }[]
>([]);
const [validationError, setValidationError] = useState<string | null>(null);
const editorRef = useRef<EditorView | null>(null);
const [isFocused, setIsFocused] = useState(false);
// Get valid function names (lowercase)
@@ -204,7 +202,7 @@ function QueryAggregationSelect({
startCompletion(editorRef.current);
}
});
}, []);
}, [editorRef]);
// Update cursor position on every editor update
const handleUpdate = (update: { view: EditorView }): void => {
@@ -601,11 +599,7 @@ function QueryAggregationSelect({
return (
<div className="query-aggregation-select-container">
<CodeMirror
value={input}
onChange={(value): void => {
setInput(value);
onChange?.(value);
}}
{...editorProps}
data-testid="query-aggregation-editor"
className={`query-aggregation-select-editor ${
validationError ? 'error' : ''
@@ -637,9 +631,6 @@ function QueryAggregationSelect({
completionKeymap: true,
}}
onUpdate={handleUpdate}
onCreateEditor={(view: EditorView): void => {
editorRef.current = view;
}}
onFocus={(): void => {
setIsFocused(true);
safeStartCompletion();

View File

@@ -8,7 +8,14 @@ import { ENVIRONMENT } from 'constants/env';
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
import { initialQueriesMap } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import {
act,
render,
screen,
userEvent,
waitFor,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
import DistributionFieldSelect from '../DistributionFieldSelect';
@@ -74,7 +81,7 @@ describe('DistributionFieldSelect', () => {
});
it('picks a numeric field, keeping its context', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
@@ -97,7 +104,7 @@ describe('DistributionFieldSelect', () => {
});
it('replaces the saved field with the newly picked one', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
render(
<DistributionFieldSelect
@@ -119,7 +126,7 @@ describe('DistributionFieldSelect', () => {
});
it('only offers listed fields: typed text is a filter, not a value', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
);

View File

@@ -0,0 +1,115 @@
import { EditorView } from '@uiw/react-codemirror';
import { act, renderHook } from 'tests/test-utils';
import { useEditorDraft } from '../useEditorDraft';
function setup(
external = '',
onEdit?: (value: string) => void,
): {
result: { current: ReturnType<typeof useEditorDraft> };
rerender: (props: { external: string }) => void;
} {
return renderHook(
({ external: value }: { external: string }) => useEditorDraft(value, onEdit),
{ initialProps: { external } },
);
}
// Reports document changes to `onChange` the way `@uiw/react-codemirror` does.
function attachEditor(
result: { current: ReturnType<typeof useEditorDraft> },
doc: string,
): EditorView {
const view = new EditorView({
doc,
extensions: EditorView.updateListener.of((update) => {
if (update.docChanged) {
result.current.editorProps.onChange(update.state.doc.toString());
}
}),
});
act(() => result.current.editorProps.onCreateEditor(view));
return view;
}
function type(view: EditorView, text: string): void {
act(() => {
view.dispatch({ changes: { from: view.state.doc.length, insert: text } });
});
}
describe('useEditorDraft', () => {
it('keeps newer typing when an older edit comes back', () => {
const { result, rerender } = setup();
act(() => result.current.editorProps.onChange('count() > 1'));
act(() => result.current.editorProps.onChange('count() > 10'));
rerender({ external: 'count() > 1' });
expect(result.current.draft).toBe('count() > 10');
});
it('takes a value set outside the editor', () => {
const { result, rerender } = setup('count() > 1');
act(() => result.current.editorProps.onChange('count() > 10'));
rerender({ external: 'count() > 10' });
rerender({ external: 'count() < 5' });
expect(result.current.draft).toBe('count() < 5');
});
it('takes an outside value equal to an edit older than the last echo', () => {
const { result, rerender } = setup();
act(() => result.current.editorProps.onChange('a'));
act(() => result.current.editorProps.onChange('ab'));
rerender({ external: 'ab' });
rerender({ external: 'a' });
expect(result.current.draft).toBe('a');
});
it('keeps the editor value at the first text while the user types', () => {
const { result, rerender } = setup('count()');
act(() => result.current.editorProps.onChange('count() >'));
rerender({ external: 'count() >' });
act(() => result.current.editorProps.onChange('count() > 1'));
expect(result.current.editorProps.value).toBe('count()');
});
it('passes each edit on', () => {
const onEdit = jest.fn();
const { result } = setup('', onEdit);
act(() => result.current.editorProps.onChange('count()'));
expect(onEdit).toHaveBeenCalledWith('count()');
});
it('writes an outside change into the editor without passing it on', () => {
const onEdit = jest.fn();
const { result, rerender } = setup('count() > 1', onEdit);
const view = attachEditor(result, 'count() > 1');
rerender({ external: 'count() < 5' });
expect(view.state.doc.toString()).toBe('count() < 5');
expect(view.state.selection.main.head).toBe('count() < 5'.length);
expect(onEdit).not.toHaveBeenCalled();
});
it('leaves the editor alone when an older edit comes back', () => {
const { result, rerender } = setup();
const view = attachEditor(result, '');
type(view, 'count_');
type(view, 'di');
rerender({ external: 'count_' });
expect(view.state.doc.toString()).toBe('count_di');
});
});

View File

@@ -0,0 +1,109 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import type { MutableRefObject } from 'react';
import type { EditorView } from '@uiw/react-codemirror';
// Bounds the history when no parent ever echoes the edits back.
const MAX_PENDING_ECHOES = 200;
interface EditorDraft {
/** The editor's current text. */
draft: string;
editorRef: MutableRefObject<EditorView | null>;
/** Spread on `CodeMirror`. */
editorProps: {
value: string;
onChange: (value: string) => void;
onCreateEditor: (view: EditorView) => void;
};
}
/**
* Text of a query editor whose edits round-trip through query state. Each
* edit comes back as `external` one or more renders later; writing an older
* copy into the editor would drop the keys typed since and move the caret to
* the start. Values the editor sent are ignored when they come back, and any
* other `external` value replaces the text.
*
* The editor owns its text, so `editorProps.value` never changes after the
* first render: `@uiw/react-codemirror` writes a changed `value` over the
* document in a passive effect, which on a busy page runs after newer keys and
* drops them. Outside changes are written through the view instead.
*/
export function useEditorDraft(
external: string,
onEdit?: (value: string) => void,
): EditorDraft {
const [draft, setDraft] = useState(external);
const [initialValue] = useState(external);
const editorRef = useRef<EditorView | null>(null);
const pendingEchoes = useRef<string[]>([]);
const writingOutsideChange = useRef(false);
const writeIntoEditor = useCallback((view: EditorView, text: string): void => {
if (view.state.doc.toString() === text) {
return;
}
writingOutsideChange.current = true;
try {
view.dispatch({
changes: { from: 0, to: view.state.doc.length, insert: text },
selection: { anchor: text.length },
});
} finally {
writingOutsideChange.current = false;
}
}, []);
// Echoes arrive in order, and a batched render can skip some, so a match
// also drops every older entry: they can no longer come back.
//
// type "c", "co", "cou" pending [c, co, cou] draft "cou"
// echo "c" pending [co, cou] ignored, draft stays "cou"
// echo "cou" (skipped co) pending [] ignored
// "count() > 5" from a saved view, never sent: applied
//
// Keeping the older entries would also swallow an outside change that
// happens to equal one of them: after typing "a", "ab", a saved view with
// "a" would be taken for an echo.
useEffect(() => {
const index = pendingEchoes.current.indexOf(external);
if (index === -1) {
pendingEchoes.current = [];
setDraft(external);
if (editorRef.current) {
writeIntoEditor(editorRef.current, external);
}
return;
}
pendingEchoes.current = pendingEchoes.current.slice(index + 1);
}, [external, writeIntoEditor]);
const onChange = useCallback(
(value: string): void => {
if (writingOutsideChange.current) {
return;
}
pendingEchoes.current.push(value);
if (pendingEchoes.current.length > MAX_PENDING_ECHOES) {
pendingEchoes.current.shift();
}
setDraft(value);
onEdit?.(value);
},
[onEdit],
);
const onCreateEditor = useCallback(
(view: EditorView): void => {
editorRef.current = view;
writeIntoEditor(view, draft);
},
[draft, writeIntoEditor],
);
return {
draft,
editorRef,
editorProps: { value: initialValue, onChange, onCreateEditor },
};
}

View File

@@ -10,6 +10,8 @@ import {
import { getHostsQuickFiltersConfig } from 'container/InfraMonitoringHostsV2/utils';
import { INFRA_MONITORING_ATTR_KEYS } from 'container/InfraMonitoringK8sV2/constants';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { mockUseAuthZGrantAll } from 'lib/authz/utils/authz-test-utils';
import {
otherFiltersResponse,
quickFiltersFieldValuesResponse,
@@ -17,7 +19,14 @@ import {
} from 'mocks-server/__mockdata__/customQuickFilters';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
render,
screen,
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { QueryBuilderContextType } from 'types/common/queryBuilder';
@@ -32,6 +41,7 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: jest.fn(),
}));
jest.mock('container/ApiMonitoring/queryParams');
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
jest.mock(
'components/OverlayScrollbar/OverlayScrollbar',
() =>
@@ -55,6 +65,7 @@ const mockSetApiMonitoringParams = jest.fn() as jest.MockedFunction<
(newParams: Partial<ApiMonitoringParams>, replace?: boolean) => void
>;
const mockUseApiMonitoringParams = jest.mocked(useApiMonitoringParams);
const mockedUseAuthZ = jest.mocked(useAuthZ);
const BASE_URL = ENVIRONMENT.baseURL;
const quickFiltersListURL = `${BASE_URL}/api/v2/quick_filters/logs`;
@@ -78,11 +89,12 @@ const QUERY_NAME = 'Test Query';
const savedFilters = quickFiltersListResponse.data
.filters as TelemetryFieldKey[];
const smallSavedFilters = savedFilters.slice(0, 2);
const smallFiltersListResponse = {
...quickFiltersListResponse,
data: {
...quickFiltersListResponse.data,
filters: savedFilters.slice(0, 2),
filters: smallSavedFilters,
},
};
@@ -134,7 +146,7 @@ function renderSettings(): void {
<QuickFiltersSettings
savedFiltersSource={QuickfiltertypesSourceDTO.logs}
setIsSettingsOpen={jest.fn()}
customFilters={savedFilters}
customFilters={smallSavedFilters}
refetchCustomFilters={jest.fn()}
/>,
);
@@ -180,12 +192,13 @@ beforeEach(() => {
{ showIP: true } as ApiMonitoringParams,
mockSetApiMonitoringParams,
]);
mockedUseAuthZ.mockImplementation(mockUseAuthZGrantAll);
setupServer();
});
describe('Quick Filters', () => {
it('displays the correct query name in the header', () => {
render(<TestQuickFilters />);
render(<TestQuickFilters config={[]} />);
expect(screen.getByText('Filters for')).toBeInTheDocument();
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
});
@@ -194,7 +207,7 @@ describe('Quick Filters', () => {
const setLastUsedQuery = jest.fn() as jest.MockedFunction<
QueryBuilderContextType['setLastUsedQuery']
>;
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
(useQueryBuilder as jest.Mock).mockReturnValue({
currentQuery: {
@@ -221,7 +234,7 @@ describe('Quick Filters', () => {
panelType: 'graph', // not LIST view
});
render(<TestQuickFilters />);
render(<TestQuickFilters config={[]} />);
// The dropdown trigger should show the first query name
const trigger = screen.getByTestId('quick-filters-query-select');
@@ -243,12 +256,10 @@ describe('Quick Filters', () => {
// jsdom cannot deliver the pointer click Base UI expects on an option,
// so pick Query B with the arrow keys and Enter
await waitFor(() =>
expect(
screen.getByTestId('quick-filters-query-select-search'),
).toHaveFocus(),
await user.type(
screen.getByTestId('quick-filters-query-select-search'),
'{ArrowDown}{Enter}',
);
await user.keyboard('{ArrowDown}{Enter}');
// Verify setLastUsedQuery was called with index 1
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
@@ -275,7 +286,7 @@ describe('Quick Filters', () => {
panelType: 'list', // ListView
});
render(<TestQuickFilters />);
render(<TestQuickFilters config={[]} />);
// Should show static query name without dropdown
expect(screen.getByText('Query A')).toBeInTheDocument();
@@ -286,7 +297,7 @@ describe('Quick Filters', () => {
});
it('should display static query name when only one query exists', () => {
render(<TestQuickFilters />);
render(<TestQuickFilters config={[]} />);
// Should show static query name
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
@@ -298,7 +309,7 @@ describe('Quick Filters', () => {
});
it('should add filter data to query when checkbox is clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<TestQuickFilters />);
@@ -330,7 +341,7 @@ describe('Quick Filters', () => {
});
});
it('toggles Show IP addresses and updates API Monitoring params', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.API_MONITORING} />,
@@ -364,7 +375,7 @@ describe('Quick Filters with custom filters', () => {
});
it('opens the settings with the saved filters added and the rest under other filters', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
server.use(
rest.get(quickFiltersListURL, (_, res, ctx) =>
res(ctx.status(200), ctx.json(smallFiltersListResponse)),
@@ -386,7 +397,7 @@ describe('Quick Filters with custom filters', () => {
});
it('keeps same-name fields with different context as distinct entries', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
server.use(
rest.get(quickFiltersSuggestionsURL, (_req, res, ctx) =>
res(
@@ -438,7 +449,7 @@ describe('Quick Filters with custom filters', () => {
});
it('adds a filter from OTHER FILTERS to ADDED FILTERS when clicked', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderSettings();
@@ -450,7 +461,7 @@ describe('Quick Filters with custom filters', () => {
});
it('removes a filter from ADDED FILTERS and moves it to OTHER FILTERS', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderSettings();
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
@@ -468,7 +479,7 @@ describe('Quick Filters with custom filters', () => {
});
it('restores original filter state on Discard', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderSettings();
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
@@ -491,7 +502,7 @@ describe('Quick Filters with custom filters', () => {
});
it('saves the updated filters by calling PUT with correct payload', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderSettings();
@@ -506,7 +517,7 @@ describe('Quick Filters with custom filters', () => {
expect(requestBody.filters).not.toContainEqual(
expect.objectContaining({ name: FILTER_OS_DESCRIPTION }),
);
expect(requestBody.filters).toHaveLength(10);
expect(requestBody.filters).toHaveLength(smallSavedFilters.length - 1);
});
it('should render duration slider for duration_nono filter', async () => {
@@ -548,10 +559,10 @@ describe('Quick Filters with custom filters', () => {
expect(maxDuration).toHaveProperty('placeholder', '100000000');
// Type values and advance debounce
await user.clear(minDuration);
await user.type(minDuration, '10000');
await user.clear(maxDuration);
await user.type(maxDuration, '20000');
await user.click(minDuration);
await user.paste('10000');
await user.click(maxDuration);
await user.paste('20000');
jest.advanceTimersByTime(2000);
await waitFor(() => {
@@ -650,7 +661,7 @@ describe('Quick Filters refetch behavior', () => {
}),
);
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);
@@ -692,7 +703,7 @@ describe('Quick Filters refetch behavior', () => {
),
);
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
);

View File

@@ -94,21 +94,9 @@
&__text {
color: var(--l2-foreground);
line-height: 18px;
.bold-text {
color: var(--l1-foreground);
}
}
&__button-wrapper {
margin-top: 12px;
.configure-alert-rule-button {
padding: 8px 16px;
border-radius: 2px;
background: var(--l3-background);
border-width: 0;
color: var(--l1-foreground);
display: flex;
align-items: center;
}
}
}
}

View File

@@ -19,14 +19,4 @@
line-height: 18px;
letter-spacing: -0.06px;
}
&__chart {
.chart-placeholder {
width: 100%;
height: 52px;
background: color-mix(in srgb, var(--l1-foreground) 12%, transparent);
display: flex;
align-items: center;
justify-content: center;
}
}
}

View File

@@ -2,7 +2,13 @@ import {
GetMetricQueryRange,
GetQueryResultsProps,
} from 'lib/dashboard/getQueryResults';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import {
render,
screen,
userEvent,
waitFor,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
import EndPointPicker from '../Explorer/Domains/DomainDetails/components/EndPointPicker';
@@ -65,7 +71,7 @@ describe('EndPointPicker', () => {
});
it('reports the picked endpoint', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onChange = jest.fn() as jest.MockedFunction<
(endPointName: string) => void
>;
@@ -83,7 +89,7 @@ describe('EndPointPicker', () => {
});
it('shows All endpoints when none is picked and clears through it', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onChange = jest.fn() as jest.MockedFunction<
(endPointName: string) => void
>;

View File

@@ -8,6 +8,7 @@ import {
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
@@ -209,7 +210,7 @@ describe('TopErrors', () => {
});
it('scopes the query to the endpoint picked in the picker', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const expressions: string[] = [];
server.use(
rest.post(V5_QUERY_RANGE_API_PATH, async (req) => {

View File

@@ -104,7 +104,6 @@ jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
// Mock alert format categories
jest.mock('constants/formats/alertFormatCategories', () => ({
getCategoryByOptionId: jest.fn(() => ({ name: 'bytes' })),
getCategorySelectOptionByName: jest.fn(() => [
{ label: 'Bytes', value: 'bytes' },
{ label: 'KB', value: 'kb' },

View File

@@ -205,46 +205,6 @@
}
}
}
.recovery-threshold-input-group {
display: flex;
align-items: center;
gap: 0;
margin-left: 28px;
.recovery-threshold-label {
pointer-events: none;
cursor: default;
}
.recovery-threshold-btn {
pointer-events: none;
cursor: default;
color: var(--muted-foreground);
background-color: var(--surface-2) !important;
border: 1px solid var(--l1-border);
border-radius: 4px;
display: flex;
align-items: center;
justify-content: center;
}
.ant-input {
background-color: var(--surface-2);
border: 1px solid var(--l1-border);
color: var(--l1-foreground);
height: 32px;
&:hover {
border-color: var(--l1-border);
}
&:focus {
border-color: var(--l1-border);
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}
}
}
}
}
@@ -275,15 +235,10 @@
gap: 4px;
}
}
.ant-typography {
color: var(--accent-primary);
}
}
}
.condensed-alert-threshold-container,
.condensed-anomaly-threshold-container {
.condensed-alert-threshold-container {
width: 100%;
}

View File

@@ -11,11 +11,6 @@
gap: 16px;
padding: 16px;
.ant-typography {
color: var(--l1-foreground);
font-size: 13px;
}
.ant-btn-group {
.ant-btn {
border: 1px solid var(--l1-border);
@@ -133,12 +128,6 @@
flex-direction: column;
gap: 4px;
.ant-typography {
color: var(--l1-foreground);
font-size: 13px;
font-weight: 500;
}
.ant-select {
border: 1px solid var(--l1-border);

View File

@@ -1,53 +1,3 @@
.evaluation-settings-container {
margin: 16px;
.evaluate-alert-conditions-container {
display: flex;
align-items: center;
gap: 16px;
background-color: var(--l2-background);
padding: 16px;
border-radius: 4px;
border: 1px solid var(--l1-border);
margin-bottom: 16px;
.ant-typography {
color: var(--l2-foreground);
}
.evaluate-alert-conditions-separator {
flex: 1;
height: 1px;
border-top: 1px dashed var(--l1-border);
}
.ant-btn {
display: flex;
align-items: center;
justify-content: space-between;
background-color: var(--l2-background);
border: 1px solid var(--l1-border);
.evaluate-alert-conditions-button-left {
color: var(--l2-foreground);
padding-right: 16px;
}
.evaluate-alert-conditions-button-right {
display: flex;
align-items: center;
color: var(--muted-foreground);
gap: 8px;
.evaluate-alert-conditions-button-right-text {
background-color: var(--l2-background);
padding: 1px 4px;
}
}
}
}
}
.advanced-options-container {
.ant-collapse {
.ant-collapse-item {
@@ -118,18 +68,9 @@
margin: 0 -16px;
padding: 4px 16px;
.ant-typography {
color: var(--muted-foreground);
font-weight: 400;
}
&.active {
background-color: var(--l1-background);
border-left: 2px solid var(--bg-robin-500);
.ant-typography {
font-weight: 500;
color: var(--l1-foreground);
}
}
&:hover {
@@ -147,25 +88,12 @@
gap: 16px;
width: 400px;
.ant-typography {
color: var(--muted-foreground);
}
.ant-btn {
width: fit-content;
}
}
}
.evaluation-window-footer {
display: flex;
justify-content: flex-end;
gap: 8px;
background-color: var(--l2-background);
border-top: 1px solid var(--l1-border);
padding: 16px;
}
.ant-btn {
background-color: var(--l3-background);
border: 1px solid var(--l1-border);
@@ -188,13 +116,6 @@
display: flex;
flex-direction: column;
gap: 2px;
.ant-typography {
color: var(--l3-foreground);
font-size: 11px;
line-height: 18px;
font-weight: 500;
}
}
.time-select-group {
@@ -218,12 +139,6 @@
}
}
.ant-typography {
color: var(--l2-foreground);
font-size: 13px;
font-weight: 500;
}
.ant-select {
width: 60%;
background-color: var(--l2-background);

View File

@@ -57,14 +57,6 @@ export interface IEvaluationCadencePreviewProps {
setIsOpen: Dispatch<SetStateAction<boolean>>;
}
export interface TimeInputProps {
value?: string; // Format: "HH:MM:SS"
onChange?: (value: string) => void;
placeholder?: string;
disabled?: boolean;
className?: string;
}
export interface IEditCustomScheduleProps {
setIsEvaluationCadenceDetailsVisible: (isOpen: boolean) => void;
setIsPreviewVisible: (isOpen: boolean) => void;

View File

@@ -101,84 +101,12 @@
display: flex;
flex-direction: column;
gap: 8px;
.ant-typography {
display: flex;
gap: 4px;
align-items: center;
}
}
.ant-select {
width: 300px;
}
}
.re-notification-container {
display: flex;
flex-direction: column;
gap: 16px;
background-color: var(--l2-background);
border: 1px solid var(--l1-border);
padding: 16px;
margin-top: 16px;
.advanced-option-item {
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 16px;
.advanced-option-item-left-content {
display: flex;
flex-direction: column;
gap: 6px;
}
}
.border-bottom {
border-bottom: 1px solid var(--l1-border);
width: 100%;
margin-left: -16px;
margin-right: -32px;
}
.re-notification-condition {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: nowrap;
.ant-typography {
color: var(--l2-foreground);
white-space: nowrap;
}
.ant-select {
width: 200px;
height: 32px;
flex-shrink: 0;
.ant-select-selector {
border: 1px solid var(--l1-border);
&:hover {
border-color: var(--l1-border);
}
&:focus {
border-color: var(--l1-border);
box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.1);
}
}
}
.ant-input {
width: 200px;
flex-shrink: 0;
border: 1px solid var(--l1-border);
}
}
}
}
}

View File

@@ -15,11 +15,6 @@
border-bottom: none;
margin-bottom: -1px;
.prom-ql-icon {
height: 13px;
width: 13px;
}
.explorer-view-option {
display: flex;
align-items: center;

View File

@@ -64,13 +64,6 @@ export interface ICreateAlertProviderProps {
ruleId?: string;
}
export enum AlertCreationStep {
ALERT_DEFINITION = 0,
ALERT_CONDITION = 1,
EVALUATION_SETTINGS = 2,
NOTIFICATION_SETTINGS = 3,
}
export interface AlertState {
name: string;
labels: Labels;

View File

@@ -1,21 +1,5 @@
import { AlertTypes } from 'types/api/alerts/alertTypes';
import {
AdvancedOptionsState,
AlertState,
AlertThresholdState,
EvaluationWindowState,
NotificationSettingsState,
} from './context/types';
export interface CreateAlertProps {
alertType: AlertTypes;
}
export interface GetCreateAlertLocalStateFromAlertDefReturn {
basicAlertState: AlertState;
thresholdState: AlertThresholdState;
advancedOptionsState: AdvancedOptionsState;
evaluationWindowState: EvaluationWindowState;
notificationSettingsState: NotificationSettingsState;
}

View File

@@ -13,10 +13,6 @@
border-color: var(--l1-border);
margin: 16px 0;
}
.breadcrumb-divider {
margin-top: 10px;
}
}
.create-alert__breadcrumb {
@@ -26,16 +22,7 @@
align-items: center;
}
.breadcrumb-item {
color: var(--l2-foreground);
font-size: 14px;
line-height: 20px;
letter-spacing: 0.25px;
padding: 0;
}
.ant-breadcrumb-separator,
.breadcrumb-item--last {
.ant-breadcrumb-separator {
color: var(--muted-foreground);
font-family: var(--code-base-400-font-family);
}

View File

@@ -10,23 +10,23 @@ import { useGetExportToDashboardLink } from 'hooks/dashboard/useGetExportToDashb
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import { v4 } from 'uuid';
import {
EXPLORER_ACTION_EVENTS,
ExplorerActionsSource,
getExplorerActionEventPayload,
getExportPanelType,
} from './utils';
function AddToDashboardButton({
query,
sourcepage,
sourcePage,
panelType,
isOneChartPerQuery = false,
}: {
query: Query | null;
sourcepage: DataSource;
sourcePage: ExplorerActionsSource;
panelType?: PANEL_TYPES;
isOneChartPerQuery?: boolean;
}): JSX.Element {
@@ -40,9 +40,9 @@ function AddToDashboardButton({
return;
}
void logEvent(
EXPLORER_ACTION_EVENTS[sourcepage].addToDashboard,
EXPLORER_ACTION_EVENTS[sourcePage].addToDashboard,
getExplorerActionEventPayload({
sourcepage,
sourcePage,
panelType: contextPanelType,
isOneChartPerQuery,
}),
@@ -59,9 +59,9 @@ function AddToDashboardButton({
}
const exportPanelType = panelType ?? getExportPanelType(contextPanelType);
void logEvent(EXPLORER_ACTION_EVENTS[sourcepage].exported, {
void logEvent(EXPLORER_ACTION_EVENTS[sourcePage].exported, {
...getExplorerActionEventPayload({
sourcepage,
sourcePage,
panelType: contextPanelType,
isOneChartPerQuery,
}),

View File

@@ -5,21 +5,21 @@ import logEvent from 'api/common/logEvent';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useAppNavigate } from 'lib/router/useAppNavigate';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import {
EXPLORER_ACTION_EVENTS,
ExplorerActionsSource,
getCreateAlertLink,
getExplorerActionEventPayload,
} from './utils';
function CreateAlertButton({
query,
sourcepage,
sourcePage,
isOneChartPerQuery = false,
}: {
query: Query | null;
sourcepage: DataSource;
sourcePage: ExplorerActionsSource;
isOneChartPerQuery?: boolean;
}): JSX.Element {
const navigate = useAppNavigate();
@@ -30,8 +30,8 @@ function CreateAlertButton({
return;
}
void logEvent(
EXPLORER_ACTION_EVENTS[sourcepage].createAlert,
getExplorerActionEventPayload({ sourcepage, panelType, isOneChartPerQuery }),
EXPLORER_ACTION_EVENTS[sourcePage].createAlert,
getExplorerActionEventPayload({ sourcePage, panelType, isOneChartPerQuery }),
);
navigate(getCreateAlertLink({ query, panelType }));
};

View File

@@ -1,21 +1,21 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import AddToDashboardButton from './AddToDashboardButton';
import CreateAlertButton from './CreateAlertButton';
import { ExplorerActionsSource } from './utils';
function ExplorerActions({
query,
dashboardQuery = query,
sourcepage,
sourcePage,
panelType,
isOneChartPerQuery,
}: {
query: Query | null;
// When the dashboard export differs from the alert one (traces list injects columns).
dashboardQuery?: Query | null;
sourcepage: DataSource;
sourcePage: ExplorerActionsSource;
panelType?: PANEL_TYPES;
isOneChartPerQuery?: boolean;
}): JSX.Element {
@@ -23,12 +23,12 @@ function ExplorerActions({
<>
<CreateAlertButton
query={query}
sourcepage={sourcepage}
sourcePage={sourcePage}
isOneChartPerQuery={isOneChartPerQuery}
/>
<AddToDashboardButton
query={dashboardQuery}
sourcepage={sourcepage}
sourcePage={sourcePage}
panelType={panelType}
isOneChartPerQuery={isOneChartPerQuery}
/>

View File

@@ -17,7 +17,7 @@ import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import AddToDashboardButton from '../AddToDashboardButton';
import { getExportPanelType } from '../utils';
import { ExplorerActionsSource, getExportPanelType } from '../utils';
const DASHBOARD = { id: 'dash-1', title: 'Dash 1' };
@@ -94,7 +94,7 @@ function setPanelType(panelType: PANEL_TYPES): void {
async function exportTo(
query: Query | null,
sourcepage: DataSource,
sourcePage: ExplorerActionsSource,
panelType: PANEL_TYPES,
panelTypeProp?: PANEL_TYPES,
): Promise<void> {
@@ -102,7 +102,7 @@ async function exportTo(
render(
<AddToDashboardButton
query={query}
sourcepage={sourcepage}
sourcePage={sourcePage}
panelType={panelTypeProp}
/>,
);
@@ -128,7 +128,12 @@ describe('AddToDashboardButton', () => {
it('is disabled without a query and the picker stays closed', () => {
setPanelType(PANEL_TYPES.LIST);
render(<AddToDashboardButton query={null} sourcepage={DataSource.LOGS} />);
render(
<AddToDashboardButton
query={null}
sourcePage={ExplorerActionsSource.LOGS_EXPLORER}
/>,
);
expect(screen.getByTestId('explorer-add-to-dashboard')).toHaveAttribute(
'aria-disabled',
@@ -140,7 +145,12 @@ describe('AddToDashboardButton', () => {
it('hands the picker the same query it will export', async () => {
const query = stagedQuery(DataSource.LOGS);
setPanelType(PANEL_TYPES.TIME_SERIES);
render(<AddToDashboardButton query={query} sourcepage={DataSource.LOGS} />);
render(
<AddToDashboardButton
query={query}
sourcePage={ExplorerActionsSource.LOGS_EXPLORER}
/>,
);
await userEvent
.setup()
@@ -155,19 +165,23 @@ describe('AddToDashboardButton', () => {
it("logs the explorer's own open and success events", async () => {
const query = stagedQuery(DataSource.TRACES);
await exportTo(query, DataSource.TRACES, PANEL_TYPES.TABLE);
await exportTo(
query,
ExplorerActionsSource.TRACES_EXPLORER,
PANEL_TYPES.TABLE,
);
expect(mockedLogEvent).toHaveBeenCalledWith(
'Traces Explorer: Add to dashboard clicked',
{
sourcepage: DataSource.TRACES,
sourcepage: ExplorerActionsSource.TRACES_EXPLORER,
panelType: PANEL_TYPES.TABLE,
},
);
expect(mockedLogEvent).toHaveBeenCalledWith(
'Traces Explorer: Add to dashboard successful',
{
sourcepage: DataSource.TRACES,
sourcepage: ExplorerActionsSource.TRACES_EXPLORER,
panelType: PANEL_TYPES.TABLE,
isNewDashboard: undefined,
dashboardName: DASHBOARD.title,
@@ -181,7 +195,7 @@ describe('AddToDashboardButton', () => {
// context says list, the page says time series
await exportTo(
query,
DataSource.METRICS,
ExplorerActionsSource.METRICS_EXPLORER,
PANEL_TYPES.LIST,
PANEL_TYPES.TIME_SERIES,
);
@@ -206,7 +220,11 @@ describe('AddToDashboardButton', () => {
PANEL_TYPES.LIST,
) as Query;
await exportTo(exportQuery, DataSource.LOGS, PANEL_TYPES.LIST);
await exportTo(
exportQuery,
ExplorerActionsSource.LOGS_EXPLORER,
PANEL_TYPES.LIST,
);
expect(exportQuery.builder.queryData[0].orderBy).toStrictEqual([
{ columnName: 'timestamp', order: 'desc' },
@@ -221,7 +239,7 @@ describe('AddToDashboardButton', () => {
async (panelType) => {
const exportQuery = getLogsExportQuery(staged, panelType) as Query;
await exportTo(exportQuery, DataSource.LOGS, panelType);
await exportTo(exportQuery, ExplorerActionsSource.LOGS_EXPLORER, panelType);
expect(exportQuery).toBe(staged);
expect(mockSafeNavigate).toHaveBeenCalledWith(
@@ -241,7 +259,11 @@ describe('AddToDashboardButton', () => {
options,
);
await exportTo(exportQuery, DataSource.TRACES, PANEL_TYPES.LIST);
await exportTo(
exportQuery,
ExplorerActionsSource.TRACES_EXPLORER,
PANEL_TYPES.LIST,
);
const [queryData] = exportQuery.builder.queryData;
expect(queryData.selectColumns).toStrictEqual(COLUMNS);
@@ -258,7 +280,11 @@ describe('AddToDashboardButton', () => {
options,
);
await exportTo(exportQuery, DataSource.TRACES, PANEL_TYPES.TRACE);
await exportTo(
exportQuery,
ExplorerActionsSource.TRACES_EXPLORER,
PANEL_TYPES.TRACE,
);
expect(exportQuery.builder.queryData[0].selectColumns).toBeUndefined();
expect(mockSafeNavigate).toHaveBeenCalledWith(
@@ -278,7 +304,11 @@ describe('AddToDashboardButton', () => {
options,
);
await exportTo(exportQuery, DataSource.TRACES, panelType);
await exportTo(
exportQuery,
ExplorerActionsSource.TRACES_EXPLORER,
panelType,
);
expect(exportQuery.builder.queryData[0].orderBy).toStrictEqual([]);
expect(mockSafeNavigate).toHaveBeenCalledWith(
@@ -296,7 +326,11 @@ describe('AddToDashboardButton', () => {
options,
);
await exportTo(exportQuery, DataSource.TRACES, panelType);
await exportTo(
exportQuery,
ExplorerActionsSource.TRACES_EXPLORER,
panelType,
);
expect(exportQuery).toBe(staged);
expect(mockSafeNavigate).toHaveBeenCalledWith(
@@ -311,7 +345,7 @@ describe('AddToDashboardButton', () => {
await exportTo(
query,
DataSource.METRICS,
ExplorerActionsSource.METRICS_EXPLORER,
PANEL_TYPES.TIME_SERIES,
PANEL_TYPES.TIME_SERIES,
);

View File

@@ -14,6 +14,7 @@ import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import CreateAlertButton from '../CreateAlertButton';
import { ExplorerActionsSource } from '../utils';
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: jest.fn(),
@@ -60,7 +61,7 @@ function pushedQuery(): Query {
const [path, search] = (mockedNavigate.mock.calls[0][0] as string).split('?');
expect(path).toBe(ROUTES.ALERTS_NEW);
const raw = new URLSearchParams(search).get(QueryParams.compositeQuery);
return JSON.parse(raw as string);
return JSON.parse(decodeURIComponent(raw as string));
}
function setPanelType(panelType: PANEL_TYPES): void {
@@ -71,11 +72,11 @@ function setPanelType(panelType: PANEL_TYPES): void {
async function clickCreateAlert(
query: Query | null,
sourcepage: DataSource,
sourcePage: ExplorerActionsSource,
panelType: PANEL_TYPES,
): Promise<void> {
setPanelType(panelType);
render(<CreateAlertButton query={query} sourcepage={sourcepage} />);
render(<CreateAlertButton query={query} sourcePage={sourcePage} />);
await userEvent.setup().click(screen.getByTestId('explorer-create-alert'));
}
@@ -86,7 +87,11 @@ describe('CreateAlertButton', () => {
});
it('is disabled and does nothing without a query', async () => {
await clickCreateAlert(null, DataSource.LOGS, PANEL_TYPES.LIST);
await clickCreateAlert(
null,
ExplorerActionsSource.LOGS_EXPLORER,
PANEL_TYPES.LIST,
);
expect(screen.getByTestId('explorer-create-alert')).toHaveAttribute(
'aria-disabled',
@@ -98,10 +103,14 @@ describe('CreateAlertButton', () => {
it("logs the explorer's own create alert event", async () => {
const query = stagedQuery(DataSource.TRACES, StringOperators.COUNT);
await clickCreateAlert(query, DataSource.TRACES, PANEL_TYPES.TIME_SERIES);
await clickCreateAlert(
query,
ExplorerActionsSource.TRACES_EXPLORER,
PANEL_TYPES.TIME_SERIES,
);
expect(mockedLogEvent).toHaveBeenCalledWith('Traces Explorer: Create alert', {
sourcepage: DataSource.TRACES,
sourcepage: ExplorerActionsSource.TRACES_EXPLORER,
panelType: PANEL_TYPES.TIME_SERIES,
});
});
@@ -111,7 +120,7 @@ describe('CreateAlertButton', () => {
render(
<CreateAlertButton
query={stagedQuery(DataSource.METRICS, StringOperators.COUNT)}
sourcepage={DataSource.METRICS}
sourcePage={ExplorerActionsSource.METRICS_EXPLORER}
isOneChartPerQuery
/>,
);
@@ -123,7 +132,7 @@ describe('CreateAlertButton', () => {
expect(mockedLogEvent).toHaveBeenCalledWith(
'Metrics Explorer: Add to alert clicked',
{
sourcepage: DataSource.METRICS,
sourcepage: ExplorerActionsSource.METRICS_EXPLORER,
panelType: PANEL_TYPES.TIME_SERIES,
tab: 'explorer',
oneChartPerQueryEnabled: true,
@@ -146,7 +155,11 @@ describe('CreateAlertButton', () => {
PANEL_TYPES.LIST,
) as Query;
await clickCreateAlert(exportQuery, DataSource.LOGS, PANEL_TYPES.LIST);
await clickCreateAlert(
exportQuery,
ExplorerActionsSource.LOGS_EXPLORER,
PANEL_TYPES.LIST,
);
const [queryData] = pushedQuery().builder.queryData;
expect(queryData.aggregateOperator).toBe(StringOperators.COUNT);
@@ -165,7 +178,7 @@ describe('CreateAlertButton', () => {
await clickCreateAlert(
exportQuery,
DataSource.LOGS,
ExplorerActionsSource.LOGS_EXPLORER,
PANEL_TYPES.TIME_SERIES,
);
@@ -180,7 +193,11 @@ describe('CreateAlertButton', () => {
PANEL_TYPES.TABLE,
) as Query;
await clickCreateAlert(exportQuery, DataSource.LOGS, PANEL_TYPES.TABLE);
await clickCreateAlert(
exportQuery,
ExplorerActionsSource.LOGS_EXPLORER,
PANEL_TYPES.TABLE,
);
expect(pushedQuery().builder).toStrictEqual(tableStaged.builder);
});
@@ -194,7 +211,11 @@ describe('CreateAlertButton', () => {
async (panelType) => {
const exportQuery = getTracesQueryByPanelType(staged, panelType);
await clickCreateAlert(exportQuery, DataSource.TRACES, panelType);
await clickCreateAlert(
exportQuery,
ExplorerActionsSource.TRACES_EXPLORER,
panelType,
);
const [queryData] = pushedQuery().builder.queryData;
expect(queryData.aggregateOperator).toBe(StringOperators.COUNT);
@@ -211,7 +232,11 @@ describe('CreateAlertButton', () => {
expect(staged.builder.queryData[0].orderBy).toStrictEqual(ORDER_BY);
const exportQuery = getTracesQueryByPanelType(staged, panelType);
await clickCreateAlert(exportQuery, DataSource.TRACES, panelType);
await clickCreateAlert(
exportQuery,
ExplorerActionsSource.TRACES_EXPLORER,
panelType,
);
expect(pushedQuery().builder.queryData[0].orderBy).toStrictEqual([]);
},
@@ -223,7 +248,11 @@ describe('CreateAlertButton', () => {
const aggStaged = stagedQuery(DataSource.TRACES, StringOperators.COUNT);
const exportQuery = getTracesQueryByPanelType(aggStaged, panelType);
await clickCreateAlert(exportQuery, DataSource.TRACES, panelType);
await clickCreateAlert(
exportQuery,
ExplorerActionsSource.TRACES_EXPLORER,
panelType,
);
expect(pushedQuery().builder).toStrictEqual(aggStaged.builder);
},
@@ -233,7 +262,11 @@ describe('CreateAlertButton', () => {
it('metrics: the chart query as is', async () => {
const query = stagedQuery(DataSource.METRICS, StringOperators.COUNT);
await clickCreateAlert(query, DataSource.METRICS, PANEL_TYPES.TIME_SERIES);
await clickCreateAlert(
query,
ExplorerActionsSource.METRICS_EXPLORER,
PANEL_TYPES.TIME_SERIES,
);
expect(pushedQuery().builder).toStrictEqual(query.builder);
});

View File

@@ -1,6 +1,8 @@
import { QueryParams } from 'constants/query';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { StringOperators } from 'types/common/queryBuilder';
@@ -22,7 +24,7 @@ function withFirstQuery(
function decodeQuery(link: string): Query {
const search = link.split('?')[1];
const raw = new URLSearchParams(search).get(QueryParams.compositeQuery);
return JSON.parse(raw as string);
return JSON.parse(decodeURIComponent(raw as string));
}
describe('getExportPanelType', () => {
@@ -55,6 +57,26 @@ describe('getCreateAlertLink', () => {
expect(decodeQuery(link)).toStrictEqual(query);
});
it.each(["service.name ILIKE 'api%'", "http.route = '/a+b'"])(
'the alert page reads back the filter %s unchanged',
(expression) => {
const link = getCreateAlertLink({
query: withFirstQuery(initialQueriesMap.logs, { filter: { expression } }),
panelType: PANEL_TYPES.TIME_SERIES,
});
const { result } = renderHook(() => useGetCompositeQueryParam(), {
wrapper: ({ children }): JSX.Element => (
<AllTheProviders initialRoute={link}>{children}</AllTheProviders>
),
});
expect(result.current?.builder.queryData[0].filter?.expression).toBe(
expression,
);
},
);
it('logs list: noop becomes count and order by is dropped', () => {
const query = withFirstQuery(initialQueriesMap.logs, {
aggregateOperator: StringOperators.NOOP,

View File

@@ -10,41 +10,57 @@ import { cloneDeep } from 'lodash-es';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
// The explorer page, not its DataSource: the AI explorer queries traces but logs its own events.
export const ExplorerActionsSource = {
LOGS_EXPLORER: DataSource.LOGS,
TRACES_EXPLORER: DataSource.TRACES,
METRICS_EXPLORER: DataSource.METRICS,
AI_OBSERVABILITY_EXPLORER: 'ai_observability',
} as const;
export type ExplorerActionsSource =
(typeof ExplorerActionsSource)[keyof typeof ExplorerActionsSource];
export const EXPLORER_ACTION_EVENTS: Record<
DataSource,
ExplorerActionsSource,
{ createAlert: string; addToDashboard: string; exported: string }
> = {
[DataSource.LOGS]: {
[ExplorerActionsSource.LOGS_EXPLORER]: {
createAlert: 'Logs Explorer: Create alert',
addToDashboard: 'Logs Explorer: Add to dashboard clicked',
exported: 'Logs Explorer: Add to dashboard successful',
},
[DataSource.TRACES]: {
[ExplorerActionsSource.TRACES_EXPLORER]: {
createAlert: 'Traces Explorer: Create alert',
addToDashboard: 'Traces Explorer: Add to dashboard clicked',
exported: 'Traces Explorer: Add to dashboard successful',
},
[DataSource.METRICS]: {
[ExplorerActionsSource.METRICS_EXPLORER]: {
createAlert: MetricsExplorerEvents.AddToAlertClicked,
addToDashboard: MetricsExplorerEvents.AddToDashboardClicked,
exported: MetricsExplorerEvents.AddToDashboardSuccessful,
},
[ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER]: {
createAlert: 'AI Observability Explorer: Create alert',
addToDashboard: 'AI Observability Explorer: Add to dashboard clicked',
exported: 'AI Observability Explorer: Add to dashboard successful',
},
};
export function getExplorerActionEventPayload({
sourcepage,
sourcePage,
panelType,
isOneChartPerQuery,
}: {
sourcepage: DataSource;
sourcePage: ExplorerActionsSource;
panelType: PANEL_TYPES | null;
isOneChartPerQuery: boolean;
}): Record<string, unknown> {
if (sourcepage !== DataSource.METRICS) {
return { sourcepage, panelType };
if (sourcePage !== ExplorerActionsSource.METRICS_EXPLORER) {
return { sourcepage: sourcePage, panelType };
}
return {
sourcepage,
sourcepage: sourcePage,
panelType,
[MetricsExplorerEventKeys.Tab]: 'explorer',
[MetricsExplorerEventKeys.OneChartPerQueryEnabled]: isOneChartPerQuery,
@@ -79,7 +95,8 @@ export function getCreateAlertLink({
orderBy: isListStyle ? [] : item.orderBy,
}));
// Encoded twice: the alert page decodes it again after the URL does.
return `${ROUTES.ALERTS_NEW}?${QueryParams.compositeQuery}=${encodeURIComponent(
JSON.stringify(alertQuery),
encodeURIComponent(JSON.stringify(alertQuery)),
)}`;
}

View File

@@ -11,10 +11,6 @@
padding: var(--spacing-4) var(--spacing-5) 0;
}
.title {
font-weight: var(--label-base-500-font-weight);
}
.body {
display: flex;
flex-direction: column;

View File

@@ -5,46 +5,12 @@
--row-control-height: 28px;
}
.row {
display: flex;
align-items: center;
gap: var(--spacing-2);
margin-bottom: var(--spacing-2);
}
.field {
flex: 1 1 0;
min-width: 0;
max-width: 300px;
}
.row > :not(.field) {
flex: 0 0 auto;
}
.heading {
font-size: 11px;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--muted-foreground);
}
.add {
/* Sits with the blocks it adds to, not against the next field's label. */
margin-top: var(--spacing-2);
--button-height: var(--row-control-height);
}
@media (max-width: 720px) {
.row {
flex-wrap: wrap;
}
.field {
max-width: none;
}
}
/* One entry per block, every input labelled. A row of bare boxes gave no way to
tell which column was which once a value was typed. The block keeps a readable
width while the rest of the form fills the page, so its two columns do not
@@ -70,12 +36,6 @@
--button-icon-size: 14px;
}
.entryIndex {
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--muted-foreground);
}
.entryGrid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));

View File

@@ -1,8 +0,0 @@
import { Button as ButtonComponent } from 'antd';
import styled from 'styled-components';
export const Button = styled(ButtonComponent)`
&&& {
margin-right: 1rem;
}
`;

View File

@@ -11,18 +11,4 @@
.threshold-alert-uplot-chart-container {
height: calc(100% - 24px);
}
.anomaly-alert-evaluation-view-loading-container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
.anomaly-alert-evaluation-view-error-container {
height: 100%;
display: flex;
justify-content: center;
align-items: center;
}
}

View File

@@ -11,11 +11,6 @@
align-items: center;
justify-content: center;
gap: 8px;
.prom-ql-icon {
height: 14px;
width: 14px;
}
}
.ant-btn-default {
border-color: transparent;

View File

@@ -12,19 +12,6 @@
position: relative;
overflow-y: auto;
:global(.periscope-btn) {
&.ghost:not(:disabled) {
border: none;
background: transparent;
&:hover {
background: transparent;
color: var(--bg-robin-500) !important;
font-weight: 500;
}
}
}
&::-webkit-scrollbar {
width: 8px;
height: 8px;

View File

@@ -24,10 +24,6 @@
gap: var(--spacing-2);
}
.statusToggleItem {
flex: unset;
}
.statusDot {
width: 8px;
height: 8px;

View File

@@ -1,14 +1,3 @@
.entityGroupHeader {
padding-left: var(--spacing-5);
gap: var(--spacing-5);
display: flex;
align-items: center;
}
.hostnameColumnHeader {
display: block;
}
.progressContainer {
display: flex;
align-items: center;
@@ -17,8 +6,3 @@
width: 100%;
}
}
.progressBar {
flex: 1;
margin-right: 8px;
}

View File

@@ -30,7 +30,6 @@ import { INFRA_MONITORING_DETAILS_CACHE_TIME } from 'constants/queryCacheTime';
export type {
CustomTab,
CustomTabRenderProps,
K8sBaseDetailsProps,
K8sDetailsCountConfig,
K8sDetailsFilters,

View File

@@ -19,10 +19,6 @@
width: 100%;
}
.k8SFiltersButton {
flex: 0 0 auto;
}
.k8SDateTimeSelection {
margin-left: auto;
display: flex;

View File

@@ -36,26 +36,6 @@ export type K8sBaseFilters = {
};
};
export type K8sListResponse<T> = {
type: 'list' | 'grouped_list';
records: T[];
total: number;
endTimeBeforeRetention?: boolean;
error?: string | null;
};
/**
* Type for table row data with required key fields.
* Used when rendering raw data in the table.
*/
export type K8sTableRowData<T> = T & {
key: string;
id: string;
itemKey: string;
/** Metadata about which attributes were used for grouping */
groupedByMeta?: Record<string, string>;
};
export interface K8sDetailsMetadataConfig<T> {
label: string;
getValue: (entity: T) => string | number;
@@ -156,4 +136,3 @@ export interface K8sBaseDetailsContentProps<T> {
// Aliases for backward compatibility
export type CustomTab<T> = K8sDetailsCustomTab<T>;
export type CustomTabRenderProps<T> = K8sDetailsCustomTabRenderProps<T>;

View File

@@ -41,9 +41,3 @@ export const useDrawerHistoryStore = create<IDrawerHistoryStore>()(
export const resetDrawerHistory = (): void =>
useDrawerHistoryStore.getState().reset();
export const pushDrawerHistory = (entry: DrawerHistoryEntry): void =>
useDrawerHistoryStore.getState().push(entry);
export const getDrawerHistoryDepth = (): number =>
useDrawerHistoryStore.getState().entries.length;

View File

@@ -1,114 +0,0 @@
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
export interface IEntityColumn {
label: string;
value: string;
id: string;
defaultVisibility: boolean;
canBeHidden: boolean;
behavior: 'hidden-on-expand' | 'hidden-on-collapse' | 'always-visible';
}
export interface IInfraMonitoringTableColumnsStore {
columns: Record<string, IEntityColumn[]>;
columnsHidden: Record<string, string[]>;
addColumn: (page: string, columnId: string) => void;
removeColumn: (page: string, columnId: string) => void;
initializePageColumns: (page: string, columns: IEntityColumn[]) => void;
}
export const useInfraMonitoringTableColumnsStore =
create<IInfraMonitoringTableColumnsStore>()(
persist(
(set, get) => ({
columns: {},
columnsHidden: {},
addColumn: (page, columnId): void => {
const state = get();
const columnDefinition = state.columns[page]?.find(
(c) => c.id === columnId,
);
if (!columnDefinition) {
return;
}
if (!columnDefinition.canBeHidden) {
return;
}
const columnsHidden = state.columnsHidden[page];
if (columnsHidden.includes(columnId)) {
set({
columnsHidden: {
...state.columnsHidden,
[page]: columnsHidden.filter((id) => id !== columnId),
},
});
}
},
removeColumn: (page, columnId): void => {
const state = get();
const columnDefinition = state.columns[page]?.find(
(c) => c.id === columnId,
);
if (!columnDefinition) {
return;
}
if (!columnDefinition.canBeHidden) {
return;
}
const columnsHidden = state.columnsHidden[page];
if (!columnsHidden.includes(columnId)) {
set({
columnsHidden: {
...state.columnsHidden,
[page]: [...columnsHidden, columnId],
},
});
}
},
initializePageColumns: (page, columns): void => {
const state = get();
set({
columns: {
...state.columns,
[page]: columns,
},
});
if (state.columnsHidden[page] === undefined) {
set({
columnsHidden: {
...state.columnsHidden,
[page]: columns
.filter((c) => c.defaultVisibility === false)
.map((c) => c.id),
},
});
}
},
}),
{
name: '@signoz/infra-monitoring-columns',
},
),
);
export const useInfraMonitoringTableColumnsForPage = (
page: string,
): [columns: IEntityColumn[], columnsHidden: string[]] => {
const state = useInfraMonitoringTableColumnsStore((s) => s.columns);
const columnsHidden = useInfraMonitoringTableColumnsStore(
(s) => s.columnsHidden,
);
return [state[page] ?? [], columnsHidden[page] ?? []];
};

View File

@@ -25,8 +25,3 @@
.title {
font-weight: 600;
}
.subtitle {
font-weight: 400;
color: var(--muted-foreground);
}

View File

@@ -64,11 +64,6 @@
width: fit-content;
}
}
.skeletonContainer {
height: 100%;
padding: 16px;
}
}
.listContainer {

View File

@@ -12,19 +12,6 @@
position: relative;
overflow-y: auto;
:global(.periscope-btn) {
&.ghost:not(:disabled) {
border: none;
background: transparent;
&:hover {
background: transparent;
color: var(--bg-robin-500) !important;
font-weight: 500;
}
}
}
&::-webkit-scrollbar {
width: 8px;
height: 8px;
@@ -50,14 +37,6 @@
border-right: 1px solid var(--l1-border);
}
.quickFiltersContainerHeader {
padding: 8px;
border-bottom: 1px solid var(--l1-border);
display: flex;
align-items: center;
justify-content: space-between;
}
.listContainer {
flex: 1;
max-width: 100%;

View File

@@ -247,13 +247,6 @@ export function getStrokeColorForPercent(
return (match ?? thresholds[thresholds.length - 1]).color;
}
export function getStrokeColor(
type: EntityProgressBarType,
value: number,
): string {
return getStrokeColorForPercent(type, Number((value * 100).toFixed(1)));
}
const PROGRESS_COLOR_BY_STROKE: Record<string, ProgressColorType> = {
[Color.BG_FOREST_500]: 'success',
[Color.BG_AMBER_200]: 'warning',

View File

@@ -32,8 +32,3 @@
align-items: baseline;
gap: var(--spacing-2);
}
.range {
white-space: nowrap;
font-variant-numeric: tabular-nums;
}

View File

@@ -186,35 +186,6 @@ export const K8sCategories = {
/** The section the Kubernetes view opens on when a link names none. */
export const DEFAULT_K8S_CATEGORY = K8sCategories.CONTAINERS;
const dotMap = {
[InfraMonitoringEntity.HOSTS]:
INFRA_MONITORING_ATTR_KEYS.SYSTEM_CPU_LOAD_AVERAGE_15M,
[InfraMonitoringEntity.PODS]: INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_USAGE,
[InfraMonitoringEntity.NODES]: INFRA_MONITORING_ATTR_KEYS.K8S_NODE_CPU_USAGE,
[InfraMonitoringEntity.NAMESPACES]:
INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_USAGE,
[InfraMonitoringEntity.CLUSTERS]:
INFRA_MONITORING_ATTR_KEYS.K8S_NODE_CPU_USAGE,
[InfraMonitoringEntity.DEPLOYMENTS]:
INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_USAGE,
[InfraMonitoringEntity.STATEFULSETS]:
INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_USAGE,
[InfraMonitoringEntity.DAEMONSETS]:
INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_USAGE,
[InfraMonitoringEntity.CONTAINERS]:
INFRA_MONITORING_ATTR_KEYS.CONTAINER_CPU_USAGE,
[InfraMonitoringEntity.JOBS]:
INFRA_MONITORING_ATTR_KEYS.K8S_JOB_DESIRED_SUCCESSFUL_PODS,
[InfraMonitoringEntity.VOLUMES]:
INFRA_MONITORING_ATTR_KEYS.K8S_VOLUME_CAPACITY,
};
export function GetK8sEntityToAggregateAttribute(
category: InfraMonitoringEntity,
): string {
return dotMap[category];
}
export function GetPodsQuickFiltersConfig(): IQuickFiltersConfig[] {
return [
{

View File

@@ -1,7 +1,15 @@
import { ComponentProps } from 'react';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
render,
screen,
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { rest, server } from 'mocks-server/server';
import { RestRequest } from 'msw';
import type { Region } from 'utils/regions';
import type logEvent from '../../../../../api/common/logEvent';
import CloudAccountSetupModal from '../AddNewAccount/CloudAccountSetupModal';
@@ -14,6 +22,24 @@ jest.mock('../../../../../api/common/logEvent', () => ({
default: jest.fn() as jest.MockedFunction<typeof logEvent>,
}));
jest.mock('utils/regions', () => {
const regions: Region[] = [
{
id: 'north-america',
name: 'North America',
subRegions: [
{
id: 'us-east-1',
name: 'us-east-1',
displayName: 'US East (N. Virginia)',
},
{ id: 'us-east-2', name: 'us-east-2', displayName: 'US East (Ohio)' },
],
},
];
return { regions };
});
type OnClose = ComponentProps<typeof CloudAccountSetupModal>['onClose'];
const mockOnClose = (): jest.MockedFunction<OnClose> =>
@@ -96,7 +122,7 @@ describe('AWS CloudAccountSetupModal', () => {
it('creates the account and shows its setup command', async () => {
const api = mockApi();
const openSpy = jest.spyOn(window, 'open').mockImplementation(() => null);
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<CloudAccountSetupModal onClose={mockOnClose()} />);
@@ -123,7 +149,7 @@ describe('AWS CloudAccountSetupModal', () => {
it('asks before closing once a setup command exists', async () => {
mockApi();
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onClose = mockOnClose();
render(<CloudAccountSetupModal onClose={onClose} />);
@@ -146,7 +172,7 @@ describe('AWS CloudAccountSetupModal', () => {
it('closes without asking before a setup command exists', async () => {
mockApi();
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onClose = mockOnClose();
render(<CloudAccountSetupModal onClose={onClose} />);
@@ -159,7 +185,7 @@ describe('AWS CloudAccountSetupModal', () => {
it('resumes polling with Check Again after the connection check fails', async () => {
const api = mockApi({ failFirstPoll: true });
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<CloudAccountSetupModal onClose={mockOnClose()} />);

View File

@@ -1,10 +1,18 @@
import {
SpantypesFieldContextDTO as FieldContext,
SpantypesSpanMapperDTO as Mapper,
SpantypesSpanMapperOperationDTO as MapperOperation,
} from 'api/generated/services/sigNoz.schemas';
import { toast } from '@signozhq/ui/toast';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
render,
screen,
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
jest.mock('@signozhq/ui/toast', () => ({
...jest.requireActual('@signozhq/ui/toast'),
@@ -40,7 +48,9 @@ import { DraftGroup } from 'container/LLMObservability/AttributeMapping/types';
import AttributeMappingsTab from '../AttributeMappingsTab';
import { useAttributeMappingEditor } from '../../hooks/useAttributeMappingEditor';
function setupGroups(groups = mockGroups): void {
const [FIRST_GROUP] = mockGroups;
function setupGroups(groups = [FIRST_GROUP]): void {
server.use(
rest.get(GROUPS_ENDPOINT, (_req, res, ctx) =>
res(ctx.status(200), ctx.json(makeGroupsResponse(groups))),
@@ -155,7 +165,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('renders each group header row with its name, condition count and status', async () => {
setupGroups();
setupGroups(mockGroups);
render(<AttributeMappingsTabWithStore />);
// Condition filters are no longer shown inline as clauses — the header
@@ -179,7 +189,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it("stages a toggle of the group's enabled state via the header switch", async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
render(<AttributeMappingsTabWithStore />);
@@ -191,7 +201,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('invokes onAddGroup from the toolbar button', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onAddGroup = jest.fn() as jest.MockedFunction<() => void>;
setupGroups();
render(<AttributeMappingsTabWithStore onAddGroup={onAddGroup} />);
@@ -203,7 +213,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('invokes onEditGroup with the group when Edit is chosen from the actions menu', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onEditGroup = jest.fn() as jest.MockedFunction<
(group: DraftGroup) => void
>;
@@ -224,8 +234,8 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('stages a group removal when Delete is chosen from the actions menu', async () => {
const user = userEvent.setup();
setupGroups();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups(mockGroups);
render(<AttributeMappingsTabWithStore />);
await screen.findByTestId('group-name-group-1');
@@ -241,7 +251,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it("reveals a group's mappers on expand and hides them on collapse", async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
setupMappers([makeMapper({ id: 'mapper-1' })]);
render(<AttributeMappingsTabWithStore />);
@@ -271,7 +281,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it("lazily fetches and renders a group's mappers on first expand", async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
setupMappers([
makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model', enabled: true }),
@@ -300,7 +310,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('shows the mappers error state when the mappers request fails', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
server.use(
rest.get(mappersEndpoint('group-1'), (_req, res, ctx) =>
@@ -318,7 +328,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('shows the mappers empty state when a group has no mappers', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
setupMappers([]);
render(<AttributeMappingsTabWithStore />);
@@ -332,7 +342,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('collapses extra mapper sources into a "+N more" label beyond the visible cap', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
setupMappers([
makeMapper({
@@ -357,7 +367,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('shows a muted placeholder when a mapper has no sources', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
setupMappers([makeMapper({ id: 'mapper-1', config: { sources: [] } })]);
render(<AttributeMappingsTabWithStore />);
@@ -371,7 +381,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it("re-fetches an open group's mappers on save instead of showing stale rows", async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
let mappers = mockMappers;
@@ -404,7 +414,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('warns and keeps the working copy when the post-save refresh fails', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
jest.mocked(toast.success).mockClear();
jest.mocked(toast.warning).mockClear();
@@ -413,7 +423,7 @@ describe('AttributeMappingsTab (integration)', () => {
rest.get(GROUPS_ENDPOINT, (_req, res, ctx) =>
failRefresh
? res(ctx.status(500), ctx.json({ status: 'error' }))
: res(ctx.status(200), ctx.json(makeGroupsResponse(mockGroups))),
: res(ctx.status(200), ctx.json(makeGroupsResponse([FIRST_GROUP]))),
),
rest.patch(`${GROUPS_ENDPOINT}/:groupId`, (_req, res, ctx) =>
res(ctx.status(200), ctx.json({ status: 'ok' })),
@@ -435,21 +445,37 @@ describe('AttributeMappingsTab (integration)', () => {
});
describe('mapper drawer', () => {
async function openGroupWithMapper(
async function openGroup(
user: ReturnType<typeof userEvent.setup>,
mappers: Mapper[],
): Promise<void> {
setupGroups();
setupMappers([makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' })]);
setupMappers(mappers);
render(<AttributeMappingsTabWithStore />);
await screen.findByTestId('group-name-group-1');
await expandGroup(user);
}
async function openGroupWithMapper(
user: ReturnType<typeof userEvent.setup>,
): Promise<void> {
await openGroup(user, [
makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' }),
]);
await screen.findByTestId('mapper-target-mapper-1');
}
async function openEmptyGroup(
user: ReturnType<typeof userEvent.setup>,
): Promise<void> {
await openGroup(user, []);
await screen.findByTestId('mappers-empty-group-1');
}
it('opens the add-mapping drawer from a group\'s "Add mapping" button', async () => {
const user = userEvent.setup();
await openGroupWithMapper(user);
const user = userEvent.setup(NO_DELAY_USER_EVENT);
await openEmptyGroup(user);
expect(screen.queryByTestId('mapper-form-drawer')).not.toBeInTheDocument();
await user.click(screen.getByTestId('add-mapper-group-1'));
@@ -461,7 +487,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('opens the edit drawer prefilled and locks the target attribute', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
await openGroupWithMapper(user);
await user.click(screen.getByTestId('mapper-actions-mapper-1'));
@@ -479,7 +505,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it("toggles a mapper's enabled state through the store", async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
await openGroupWithMapper(user);
const toggle = screen.getByTestId('mapper-enabled-mapper-1');
@@ -493,7 +519,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('removes a mapper via the row action menu', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
await openGroupWithMapper(user);
await user.click(screen.getByTestId('mapper-actions-mapper-1'));
@@ -510,8 +536,8 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('creates a new mapping through the drawer and appends it to the group', async () => {
const user = userEvent.setup();
await openGroupWithMapper(user);
const user = userEvent.setup(NO_DELAY_USER_EVENT);
await openEmptyGroup(user);
await user.click(screen.getByTestId('add-mapper-group-1'));
await screen.findByTestId('mapper-form-drawer');
@@ -571,7 +597,7 @@ describe('AttributeMappingsTab (integration)', () => {
});
it('renders mappers read-only: no "Add mapping" button or row actions', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
setupGroups();
setupMappers([makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' })]);
render(<AttributeMappingsTabWithStore />);

View File

@@ -0,0 +1,41 @@
import { useMemo } from 'react';
import { TelemetryFieldKey } from 'api/v5/v5';
import { PANEL_TYPES } from 'constants/queryBuilder';
import ExplorerActions from 'container/ExplorerActions/ExplorerActions';
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getAlertQuery, getExportQuery } from '../explorerUtils';
interface AIExplorerActionsProps {
panelType: PANEL_TYPES;
selectColumns?: TelemetryFieldKey[];
}
function AIExplorerActions({
panelType,
selectColumns,
}: AIExplorerActionsProps): JSX.Element {
const { stagedQuery } = useQueryBuilder();
const alertQuery = useMemo(
() => (stagedQuery ? getAlertQuery(stagedQuery, panelType) : null),
[stagedQuery, panelType],
);
const dashboardQuery = useMemo(
() =>
stagedQuery ? getExportQuery(stagedQuery, panelType, selectColumns) : null,
[stagedQuery, panelType, selectColumns],
);
return (
<ExplorerActions
query={alertQuery}
dashboardQuery={dashboardQuery}
sourcePage={ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER}
/>
);
}
export default AIExplorerActions;

View File

@@ -0,0 +1,301 @@
import { logEventMock } from '__tests__/logEventMock';
import { safeNavigateMock } from '__tests__/safeNavigateMock';
import { TelemetryFieldKey } from 'api/v5/v5';
import { QueryParams } from 'constants/query';
import {
initialFormulaBuilderFormValues,
initialQueryAIWithType,
PANEL_TYPES,
} from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { rest, server } from 'mocks-server/server';
import { mockAppNavigate } from 'tests/router-mocks';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import AIExplorerActions from '../AIExplorerActions';
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: jest.fn(),
}));
const mockedUseQueryBuilder = jest.mocked(useQueryBuilder);
const FILTER = "gen_ai.request.model = 'gpt-4o'";
const USER_COLUMNS: TelemetryFieldKey[] = [
{ name: 'gen_ai.request.model', fieldContext: 'attribute' },
{ name: 'duration_nano' },
];
function aiStagedQuery(aggregations?: IBuilderQuery['aggregations']): Query {
const aiBuilder = getActiveBuilder(initialQueryAIWithType);
return {
...initialQueryAIWithType,
builder_ai_query: {
...aiBuilder,
queryData: [
{
...aiBuilder.queryData[0],
...(aggregations && { aggregations }),
filter: { expression: FILTER },
groupBy: [
{ key: 'service.name', dataType: DataTypes.String, type: 'resource' },
],
having: { expression: 'count() > 5' },
orderBy: [{ columnName: 'timestamp', order: 'asc' }],
},
],
},
};
}
async function exportFrom(
panelType: PANEL_TYPES,
stagedQuery: Query = aiStagedQuery(),
selectColumns?: TelemetryFieldKey[],
): Promise<void> {
mockedUseQueryBuilder.mockReturnValue({
stagedQuery,
panelType,
} as ReturnType<typeof useQueryBuilder>);
server.use(
rest.get('*/api/v2/users/me/dashboards', (_req, res, ctx) =>
res(
ctx.status(200),
ctx.json({ status: 'success', data: { dashboards: [] } }),
),
),
rest.post('*/api/v2/dashboards', (_req, res, ctx) =>
res(
ctx.status(200),
ctx.json({ status: 'success', data: { id: 'dash-1' } }),
),
),
);
const user = userEvent.setup();
render(
<AIExplorerActions panelType={panelType} selectColumns={selectColumns} />,
);
await user.click(screen.getByTestId('explorer-add-to-dashboard'));
await user.click(await screen.findByTestId('export-panel-new-dashboard'));
await waitFor(() => expect(safeNavigateMock).toHaveBeenCalledTimes(1));
}
async function createAlertFrom(
panelType: PANEL_TYPES,
stagedQuery: Query = aiStagedQuery(),
): Promise<Query> {
const navigate = mockAppNavigate();
mockedUseQueryBuilder.mockReturnValue({
stagedQuery,
panelType,
} as ReturnType<typeof useQueryBuilder>);
render(<AIExplorerActions panelType={panelType} />);
await userEvent.setup().click(screen.getByTestId('explorer-create-alert'));
expect(navigate).toHaveBeenCalledTimes(1);
const [path, search] = (navigate.mock.calls[0][0] as string).split('?');
expect(path).toBe(ROUTES.ALERTS_NEW);
return JSON.parse(
decodeURIComponent(
new URLSearchParams(search).get(QueryParams.compositeQuery) ?? '',
),
) as Query;
}
function exportedPanel(): { panelKind: string | null; query: Query } {
const link = safeNavigateMock.mock.calls[0][0] as string;
const params = new URLSearchParams(link.split('?')[1]);
return {
panelKind: params.get('panelKind'),
query: JSON.parse(
decodeURIComponent(params.get(QueryParams.compositeQuery) ?? ''),
) as Query,
};
}
describe('AIExplorerActions', () => {
it('logs the AI explorer events, not the traces ones', async () => {
await exportFrom(PANEL_TYPES.TABLE);
expect(logEventMock).toHaveBeenCalledWith(
'AI Observability Explorer: Add to dashboard clicked',
{
sourcepage: ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER,
panelType: PANEL_TYPES.TABLE,
},
);
expect(logEventMock).toHaveBeenCalledWith(
'AI Observability Explorer: Add to dashboard successful',
{
sourcepage: ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER,
panelType: PANEL_TYPES.TABLE,
isNewDashboard: true,
dashboardName: expect.any(String),
},
);
});
it('list: exports an AI List panel with the user picked columns and no group by, having or order by', async () => {
await exportFrom(PANEL_TYPES.LIST, aiStagedQuery(), USER_COLUMNS);
const { panelKind, query } = exportedPanel();
expect(panelKind).toBe('signoz/ListPanel');
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
expect(getActiveBuilder(query).queryData[0]).toMatchObject({
filter: { expression: FILTER },
groupBy: [],
having: { expression: '' },
orderBy: [],
selectColumns: USER_COLUMNS,
});
});
it('trace: exports an AI Time Series panel with no group by, having or order by', async () => {
await exportFrom(PANEL_TYPES.TRACE);
const { panelKind, query } = exportedPanel();
expect(panelKind).toBe('signoz/TimeSeriesPanel');
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
const [queryData] = getActiveBuilder(query).queryData;
expect(queryData).toMatchObject({
filter: { expression: FILTER },
groupBy: [],
having: { expression: '' },
orderBy: [],
});
expect(queryData.selectColumns).toBeUndefined();
});
it('trace: exports without the formulas, step, limit and legend Timeseries set', async () => {
const stagedQuery = aiStagedQuery();
const aiBuilder = getActiveBuilder(stagedQuery);
await exportFrom(PANEL_TYPES.TRACE, {
...stagedQuery,
builder_ai_query: {
...aiBuilder,
queryData: [
{
...aiBuilder.queryData[0],
stepInterval: 300,
limit: 10,
legend: '{{service.name}}',
},
],
queryFormulas: [
{ ...initialFormulaBuilderFormValues, expression: 'A*100' },
],
},
});
const exported = getActiveBuilder(exportedPanel().query);
expect(exported.queryFormulas).toStrictEqual([]);
expect(exported.queryData[0]).toMatchObject({
stepInterval: null,
limit: null,
legend: '',
});
});
it('create alert: logs the AI explorer event, not the traces one', async () => {
await createAlertFrom(PANEL_TYPES.TIME_SERIES);
expect(logEventMock).toHaveBeenCalledWith(
'AI Observability Explorer: Create alert',
{
sourcepage: ExplorerActionsSource.AI_OBSERVABILITY_EXPLORER,
panelType: PANEL_TYPES.TIME_SERIES,
},
);
});
it('without a staged query: both actions are disabled and create alert goes nowhere', async () => {
const navigate = mockAppNavigate();
mockedUseQueryBuilder.mockReturnValue({
stagedQuery: null,
panelType: PANEL_TYPES.LIST,
} as ReturnType<typeof useQueryBuilder>);
render(<AIExplorerActions panelType={PANEL_TYPES.LIST} />);
const createAlert = screen.getByTestId('explorer-create-alert');
await userEvent.setup().click(createAlert);
expect(createAlert).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByTestId('explorer-add-to-dashboard')).toHaveAttribute(
'aria-disabled',
'true',
);
expect(navigate).not.toHaveBeenCalled();
});
it.each([PANEL_TYPES.TIME_SERIES, PANEL_TYPES.TABLE])(
'create alert from %s: keeps the aggregation, group by, having and order by',
async (panelType) => {
const query = await createAlertFrom(
panelType,
aiStagedQuery([{ expression: 'avg(duration_nano)' }]),
);
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
expect(getActiveBuilder(query).queryData[0]).toMatchObject({
aggregations: [{ expression: 'avg(duration_nano)' }],
filter: { expression: FILTER },
groupBy: [
{ key: 'service.name', dataType: DataTypes.String, type: 'resource' },
],
having: { expression: 'count() > 5' },
orderBy: [{ columnName: 'timestamp', order: 'asc' }],
});
},
);
it.each([PANEL_TYPES.LIST, PANEL_TYPES.TRACE])(
'create alert from %s: a count with no group by, having or order by',
async (panelType) => {
const query = await createAlertFrom(
panelType,
aiStagedQuery([{ expression: 'avg(duration_nano)' }]),
);
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
const [queryData] = getActiveBuilder(query).queryData;
expect(queryData).toMatchObject({
aggregations: [{ expression: 'count()' }],
filter: { expression: FILTER },
groupBy: [],
having: { expression: '' },
orderBy: [],
});
expect(queryData.selectColumns).toBeUndefined();
},
);
it.each([PANEL_TYPES.LIST, PANEL_TYPES.TRACE])(
'create alert from %s: only the first query, the one the view shows',
async (panelType) => {
const stagedQuery = aiStagedQuery();
const aiBuilder = getActiveBuilder(stagedQuery);
const [first] = aiBuilder.queryData;
const query = await createAlertFrom(panelType, {
...stagedQuery,
builder_ai_query: {
...aiBuilder,
queryData: [first, { ...first, queryName: 'B', expression: 'B' }],
},
});
expect(
getActiveBuilder(query).queryData.map(({ queryName }) => queryName),
).toStrictEqual([first.queryName]);
},
);
});

View File

@@ -38,6 +38,7 @@ import { GlobalReducer } from 'types/reducer/globalTime';
import { getListOrderBy, setListOrderBy } from 'utils/explorerUtils';
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
import TraceExplorerControls from '../Controls';
import { getListViewQuery } from '../explorerUtils';
import { PER_PAGE_OPTIONS, TIMESTAMP_FIELD } from './configs';
@@ -213,6 +214,10 @@ function ListView({
return (
<div className={styles.container}>
<div className="trace-explorer-controls">
<AIExplorerActions
panelType={PANEL_TYPES.LIST}
selectColumns={selectColumns}
/>
<div className="order-by-container">
<div className="order-by-label">
Order by <Minus size={14} /> <ArrowUp10 size={14} />

View File

@@ -2,6 +2,7 @@
display: flex;
justify-content: flex-end;
align-items: center;
gap: 8px;
padding: 12px;
flex-shrink: 0;
}

View File

@@ -6,6 +6,7 @@ import {
useEffect,
useMemo,
} from 'react';
import { QueryKey } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import Space from 'periscope/components/Space/Space';
@@ -24,6 +25,8 @@ import { QueryDataV3 } from 'types/api/widgets/getQuery';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
import './TableView.styles.scss';
function TableView({
@@ -33,7 +36,7 @@ function TableView({
}: {
setWarning: Dispatch<SetStateAction<Warning | undefined>>;
setIsLoadingQueries: Dispatch<SetStateAction<boolean>>;
queryKeyRef?: MutableRefObject<any>;
queryKeyRef?: MutableRefObject<QueryKey | undefined>;
}): JSX.Element {
const { stagedQuery, panelType } = useQueryBuilder();
@@ -101,14 +104,17 @@ function TableView({
return (
<Space.Compact block direction="vertical">
{isError && error && <ErrorInPlace error={error as APIError} />}
{!isError && data && (
{!isError && (
<div className="traces-table-view-header">
<ExportMenu
dataSource={DataSource.TRACES}
data={data}
query={stagedQuery || initialQueriesMap.traces}
fileName="ai-traces-table"
/>
<AIExplorerActions panelType={PANEL_TYPES.TABLE} />
{data && (
<ExportMenu
dataSource={DataSource.TRACES}
data={data}
query={stagedQuery || initialQueriesMap.traces}
fileName="ai-traces-table"
/>
)}
</div>
)}
{!isError && (

View File

@@ -5,6 +5,7 @@ import {
useEffect,
useMemo,
} from 'react';
import { QueryKey } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { ENTITY_VERSION_V5 } from 'constants/app';
@@ -22,6 +23,8 @@ import APIError from 'types/api/error';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
import './TimeSeriesView.styles.scss';
function TimeSeriesViewContainer({
@@ -128,6 +131,7 @@ function TimeSeriesViewContainer({
setWarning={setWarning}
allowExport
exportFileName="ai-traces-timeseries"
headerActions={<AIExplorerActions panelType={PANEL_TYPES.TIME_SERIES} />}
/>
</div>
);
@@ -138,7 +142,7 @@ interface TimeSeriesViewProps {
isFilterApplied: boolean;
setWarning: Dispatch<SetStateAction<Warning | undefined>>;
setIsLoadingQueries: Dispatch<SetStateAction<boolean>>;
queryKeyRef?: MutableRefObject<any>;
queryKeyRef?: MutableRefObject<QueryKey | undefined>;
}
TimeSeriesViewContainer.defaultProps = {

View File

@@ -34,6 +34,7 @@ import { Warning } from 'types/api';
import { DataSource } from 'types/common/queryBuilder';
import { GlobalReducer } from 'types/reducer/globalTime';
import AIExplorerActions from '../AIExplorerActions/AIExplorerActions';
import TraceExplorerControls from '../Controls';
import {
TRACE_VIEW_BUILDER_QUERY_TYPE,
@@ -191,6 +192,7 @@ function TracesView({
<div className={styles.container}>
<div className={styles.actionsContainer}>
<div className="trace-explorer-controls">
<AIExplorerActions panelType={PANEL_TYPES.TRACE} />
<div className={styles.orderByContainer}>
<div className={styles.orderByLabel}>
Order by <Minus size={14} /> <ArrowUp10 size={14} />

View File

@@ -0,0 +1,88 @@
import { ENVIRONMENT } from 'constants/env';
import { initialQueryAIWithType, PANEL_TYPES } from 'constants/queryBuilder';
import { rest, server } from 'mocks-server/server';
import { render, screen } from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import ListView from '../ListView/ListView';
import TableView from '../TableView/TableView';
import TimeSeriesView from '../TimeSeriesView/TimeSeriesView';
import TracesView from '../TracesView/TracesView';
const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
const VIEWS: [PANEL_TYPES, () => JSX.Element][] = [
[
PANEL_TYPES.LIST,
(): JSX.Element => (
<ListView
isFilterApplied={false}
setWarning={jest.fn()}
setIsLoadingQueries={jest.fn()}
/>
),
],
[
PANEL_TYPES.TRACE,
(): JSX.Element => (
<TracesView
isFilterApplied={false}
setWarning={jest.fn()}
setIsLoadingQueries={jest.fn()}
/>
),
],
[
PANEL_TYPES.TIME_SERIES,
(): JSX.Element => (
<TimeSeriesView
dataSource={DataSource.TRACES}
isFilterApplied={false}
setWarning={jest.fn()}
setIsLoadingQueries={jest.fn()}
/>
),
],
[
PANEL_TYPES.TABLE,
(): JSX.Element => (
<TableView setWarning={jest.fn()} setIsLoadingQueries={jest.fn()} />
),
],
];
describe('AI explorer views', () => {
beforeEach(() => {
server.use(
rest.post(QUERY_RANGE_URL, (_req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: { data: { results: [] } } })),
),
);
});
it.each(VIEWS)(
'%s: offers Create an alert and Add to dashboard for the staged query, before data arrives',
(panelType, renderView) => {
render(
renderView(),
{},
{
queryBuilderOverrides: {
panelType,
stagedQuery: initialQueryAIWithType,
currentQuery: initialQueryAIWithType,
},
},
);
expect(screen.getByTestId('explorer-create-alert')).not.toHaveAttribute(
'aria-disabled',
'true',
);
expect(screen.getByTestId('explorer-add-to-dashboard')).not.toHaveAttribute(
'aria-disabled',
'true',
);
},
);
});

View File

@@ -1,9 +1,16 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import { getActiveBuilder } from 'lib/query/builderSlot';
import { TelemetryFieldKey } from 'api/v5/v5';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import {
getActiveBuilder,
getBuilderSlotKeyForQueryType,
replaceBuilderBySlotKey,
} from 'lib/query/builderSlot';
import { cloneDeep } from 'lodash-es';
import { OrderByPayload, Query } from 'types/api/queryBuilder/queryBuilderData';
import { parseListOrderBy } from 'utils/explorerUtils';
import { defaultSelectedColumns } from './ListView/configs';
export const getListViewQuery = (
stagedQuery: Query,
orderBy?: string,
@@ -28,3 +35,43 @@ export const getListViewQuery = (
return query;
};
export const getAlertQuery = (
stagedQuery: Query,
panelType: PANEL_TYPES,
): Query => {
if (panelType !== PANEL_TYPES.LIST && panelType !== PANEL_TYPES.TRACE) {
return stagedQuery;
}
const query = getListViewQuery(stagedQuery);
const builder = getActiveBuilder(query);
// List and Trace show only the first query's filter, so nothing another view set may reach the alert or chart.
return replaceBuilderBySlotKey(
query,
getBuilderSlotKeyForQueryType(query.queryType),
{
...builder,
queryData: builder.queryData.slice(0, 1).map((item) => ({
...item,
aggregations: [{ expression: 'count()' }],
stepInterval: null,
limit: null,
legend: '',
})),
queryFormulas: [],
},
);
};
export const getExportQuery = (
stagedQuery: Query,
panelType: PANEL_TYPES,
selectColumns: TelemetryFieldKey[] = defaultSelectedColumns,
): Query => {
const query = getAlertQuery(stagedQuery, panelType);
const [queryData] = getActiveBuilder(query).queryData;
if (panelType === PANEL_TYPES.LIST && queryData) {
queryData.selectColumns = selectColumns;
}
return query;
};

View File

@@ -5,11 +5,30 @@ import {
makeListResponse,
makeUnmappedResponse,
mockRules,
mockUnpricedModels,
} from 'container/LLMObservability/Settings/ModelPricing/__tests__/fixtures';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
render,
screen,
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import UnpricedModelsTab from '../UnpricedModelsTab';
import { usePendingMappingStore } from '../usePendingMappingStore';
// One antd skeleton renders per placeholder row and per dropdown option on every
// load, so fewer of them keep each test's first paint cheap.
jest.mock('container/LLMObservability/Settings/ModelPricing/constants', () => ({
...jest.requireActual(
'container/LLMObservability/Settings/ModelPricing/constants',
),
SKELETON_ROW_COUNT: 1,
RULE_OPTIONS_LIMIT: 2,
}));
const toastSuccess = jest.fn();
const toastError = jest.fn();
@@ -21,12 +40,20 @@ jest.mock('@signozhq/ui/toast', () => ({
},
}));
const MODEL = 'gpt-4o-mini-2024-07-18';
const [UNPRICED_MODEL] = mockUnpricedModels;
const MODEL = UNPRICED_MODEL.modelName;
const [TARGET_RULE] = mockRules;
function stageMapping(): void {
usePendingMappingStore.setState({
pending: { model: UNPRICED_MODEL, rule: TARGET_RULE },
});
}
function setup(): void {
server.use(
rest.get(LLM_UNMAPPED_ENDPOINT, (_req, res, ctx) =>
res(ctx.status(200), ctx.json(makeUnmappedResponse())),
res(ctx.status(200), ctx.json(makeUnmappedResponse([UNPRICED_MODEL]))),
),
rest.get(LLM_PRICING_ENDPOINT, (_req, res, ctx) =>
res(ctx.status(200), ctx.json(makeListResponse(mockRules))),
@@ -36,8 +63,8 @@ function setup(): void {
// Picks a billing model in a row's dropdown: open the combobox, wait for the
// options (fetched from the rules list mocked above), then arrow down to the
// option and press Enter. jsdom cannot deliver the pointer click Base UI
// expects on an option.
// option and press Enter in its search box. jsdom cannot deliver the pointer
// click Base UI expects on an option.
async function selectRule(
user: ReturnType<typeof userEvent.setup>,
modelName: string,
@@ -50,10 +77,10 @@ async function selectRule(
.findIndex(
(option) => option.getAttribute('data-testid') === `map-to-option-${ruleId}`,
);
await waitFor(() =>
expect(screen.getByTestId(`map-to-select-${modelName}-search`)).toHaveFocus(),
await user.type(
screen.getByTestId(`map-to-select-${modelName}-search`),
`${'{ArrowDown}'.repeat(index + 1)}{Enter}`,
);
await user.keyboard(`${'{ArrowDown}'.repeat(index + 1)}{Enter}`);
}
describe('UnpricedModelsTab (integration)', () => {
@@ -64,12 +91,36 @@ describe('UnpricedModelsTab (integration)', () => {
afterEach(() => {
server.resetHandlers();
usePendingMappingStore.getState().clearPending();
toastSuccess.mockClear();
toastError.mockClear();
});
it('cancels the mapping without committing', async () => {
const sent: LlmpricingruletypesUpdatableLLMPricingRulesDTO[] = [];
server.use(
rest.put(LLM_PRICING_ENDPOINT, async (req, res, ctx) => {
sent.push(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
stageMapping();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<UnpricedModelsTab />);
await user.click(await screen.findByTestId('unpriced-map-cancel-btn'));
await waitFor(() =>
expect(
screen.queryByTestId(`unpriced-map-confirm-item-${MODEL}`),
).not.toBeInTheDocument(),
);
expect(sent).toHaveLength(0);
});
it('opens the confirm dialog with the target rule pricing when a model is picked', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<UnpricedModelsTab />);
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
@@ -94,26 +145,20 @@ describe('UnpricedModelsTab (integration)', () => {
});
it('reverts the row trigger to the placeholder when the mapping is cancelled', async () => {
const user = userEvent.setup();
stageMapping();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<UnpricedModelsTab />);
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
await selectRule(user, MODEL, 'rule-openai');
const trigger = await screen.findByTestId(`map-to-select-${MODEL}`);
expect(
within(screen.getByTestId(`map-to-select-${MODEL}`)).getByText(
'openai:gpt-4o ($3.00/$9.00)',
),
within(trigger).getByText('openai:gpt-4o ($3.00/$9.00)'),
).toBeInTheDocument();
await user.click(await screen.findByTestId('unpriced-map-cancel-btn'));
await user.click(screen.getByTestId('unpriced-map-cancel-btn'));
await waitFor(() => {
const trigger = screen.getByTestId(`map-to-select-${MODEL}`);
expect(
within(trigger).getByText('Select / Create a pricing model'),
).toBeInTheDocument();
});
expect(
within(trigger).getByText('Select / Create a pricing model'),
).toBeInTheDocument();
});
it('commits the mapping in one request when confirmed', async () => {
@@ -125,12 +170,10 @@ describe('UnpricedModelsTab (integration)', () => {
}),
);
const user = userEvent.setup();
stageMapping();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<UnpricedModelsTab />);
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
await selectRule(user, MODEL, 'rule-openai');
await user.click(await screen.findByTestId('unpriced-map-confirm-btn'));
await waitFor(() => expect(sent).toHaveLength(1));
@@ -147,33 +190,8 @@ describe('UnpricedModelsTab (integration)', () => {
);
});
it('cancels the mapping without committing', async () => {
const sent: LlmpricingruletypesUpdatableLLMPricingRulesDTO[] = [];
server.use(
rest.put(LLM_PRICING_ENDPOINT, async (req, res, ctx) => {
sent.push(await req.json());
return res(ctx.status(200), ctx.json({ status: 'success' }));
}),
);
const user = userEvent.setup();
render(<UnpricedModelsTab />);
await screen.findByTestId(`unpriced-model-name-${MODEL}`);
await selectRule(user, MODEL, 'rule-openai');
await user.click(await screen.findByTestId('unpriced-map-cancel-btn'));
await waitFor(() =>
expect(
screen.queryByTestId(`unpriced-map-confirm-item-${MODEL}`),
).not.toBeInTheDocument(),
);
expect(sent).toHaveLength(0);
});
it('opens the add-cost drawer prefilled when creating pricing for a model', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
render(<UnpricedModelsTab />);
await screen.findByTestId(`unpriced-model-name-${MODEL}`);

View File

@@ -36,10 +36,6 @@
gap: 4px;
}
.icons {
color: white;
}
.actionContainer {
display: flex;
gap: 24px;

View File

@@ -1,4 +1,9 @@
import { screen, userEvent, waitFor } from 'tests/test-utils';
import {
screen,
userEvent,
waitFor,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { renderListAlertRules } from './_helpers';
@@ -16,7 +21,7 @@ describe('ListAlertRules — columns selector', () => {
});
it('opens columns popover and lists toggleable columns', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
await screen.findByText('High CPU Alert');
@@ -44,7 +49,7 @@ describe('ListAlertRules — columns selector', () => {
});
it('toggling Created At on writes to localStorage and adds the header', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
await screen.findByText('High CPU Alert');

View File

@@ -8,7 +8,7 @@ import {
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { getCurrentNuqsSearchParams } from 'tests/nuqs-helpers';
import { screen, waitFor } from 'tests/test-utils';
import { screen, waitFor, NO_DELAY_USER_EVENT } from 'tests/test-utils';
import { renderListAlertRules } from './_helpers';
@@ -18,7 +18,7 @@ describe('ListAlertRules — empty states', () => {
});
it('renders AlertsEmptyState when API returns no rules', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
server.use(
rest.get('http://localhost/api/v3/rules', (req, res, ctx) =>
@@ -49,7 +49,7 @@ describe('ListAlertRules — empty states', () => {
});
it('renders ErrorEmptyState when API returns 500; refresh triggers a refetch', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
let callCount = 0;
server.use(
@@ -76,7 +76,7 @@ describe('ListAlertRules — empty states', () => {
});
it('renders NoResultsEmptyState when the query matches nothing; Clear Search resets it', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
server.use(
rest.get('http://localhost/api/v3/rules', (req, res, ctx) =>
@@ -116,7 +116,7 @@ describe('ListAlertRules — empty states', () => {
});
it('renders NoResultsEmptyState when the states filter matches nothing; Clear Search resets it', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules({ initialRoute: '/?states=nodata' });

View File

@@ -5,7 +5,7 @@ import {
} from 'mocks-server/__mockdata__/alert_rules';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { screen, waitFor } from 'tests/test-utils';
import { screen, waitFor, NO_DELAY_USER_EVENT } from 'tests/test-utils';
import { getCurrentNuqsQueryString } from 'tests/nuqs-helpers';
import { renderListAlertRules } from './_helpers';
@@ -53,7 +53,7 @@ describe('ListAlertRules — pagination', () => {
});
it('navigates to page 2 by requesting the next offset', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
await screen.findByText('Pag Rule 0');

View File

@@ -1,6 +1,11 @@
import { safeNavigateMock } from '__tests__/safeNavigateMock';
import { useAlertRuleViewsStore } from 'container/ListAlertRules/useAlertRuleViewsStore';
import { screen, userEvent, waitFor } from 'tests/test-utils';
import {
screen,
userEvent,
waitFor,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { renderListAlertRules } from './_helpers';
@@ -13,7 +18,7 @@ describe('ListAlertRules — row click navigation', () => {
});
it('clicking a row calls safeNavigate to alerts/overview with ruleId', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
await user.click(await screen.findByTestId(RULE_NAME_CELL_TEST_ID));
@@ -29,7 +34,7 @@ describe('ListAlertRules — row click navigation', () => {
});
it('records an opened rule as recently viewed, most recent first', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
useAlertRuleViewsStore.setState({ recent: ['rule-2', 'rule-1'] });
renderListAlertRules();
@@ -44,7 +49,7 @@ describe('ListAlertRules — row click navigation', () => {
});
it('ctrl+click on a row navigates with newTab option', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
const ruleCell = await screen.findByTestId(RULE_NAME_CELL_TEST_ID);

View File

@@ -4,7 +4,13 @@ import {
} from 'mocks-server/__mockdata__/alert_rules';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
screen,
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import {
getCurrentNuqsQueryString,
getCurrentNuqsSearchParams,
@@ -134,7 +140,7 @@ describe('ListAlertRules — search', () => {
});
it('runs the draft when the search box loses focus', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
// jsdom reports no focus once it lands on <body>; a focused browser window does.
jest.spyOn(document, 'hasFocus').mockReturnValue(true);
renderListAlertRules();
@@ -154,7 +160,7 @@ describe('ListAlertRules — search', () => {
});
it('keeps the draft unrun when focus leaves the window', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
await screen.findByText('High CPU Alert');

View File

@@ -15,6 +15,7 @@ import {
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { renderListAlertRules, runSearchQuery } from './_helpers';
@@ -172,7 +173,7 @@ describe('ListAlertRules — saved views rail', () => {
});
it('Enabled sends every state except disabled', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const requests = captureRulesRequests();
renderListAlertRules();
await screen.findByTestId('alert-row-rule-1-name');
@@ -188,7 +189,7 @@ describe('ListAlertRules — saved views rail', () => {
});
it('Recently viewed lists the opened rules in visit order from one large page', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const requests = captureRulesRequests();
useAlertRuleViewsStore.setState({ recent: ['rule-3', 'rule-1'] });
renderListAlertRules();
@@ -213,7 +214,7 @@ describe('ListAlertRules — saved views rail', () => {
});
it('an empty Recently viewed keeps the search and says how it fills', async () => {
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
await screen.findByTestId('alert-row-rule-1-name');
@@ -564,7 +565,7 @@ describe('ListAlertRules — saved views rail', () => {
),
),
);
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderListAlertRules();
await selectView(user, 'view-1');
await waitFor(() => expect(urlParam('orderBy')).toBe(VIEW_1_ORDER_BY));

View File

@@ -9,8 +9,6 @@ import { dataSourceForAlertType } from 'constants/alerts';
import type { AlertRule, RuleListFilter } from './types';
export const ALERT_RULES_REFRESH_INTERVAL = 30_000;
export const ALERT_ACTIONS = {
TOGGLE: 'toggle',
EDIT: 'edit',

View File

@@ -36,6 +36,7 @@ import {
getQueryByPanelType,
} from 'container/LogsExplorerViews/explorerUtils';
import ExplorerActions from 'container/ExplorerActions/ExplorerActions';
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQueryRange';
@@ -136,7 +137,10 @@ function LogsExplorerViewsContainer({
const explorerActions = useMemo(
() => (
<ExplorerActions query={exportDefaultQuery} sourcepage={DataSource.LOGS} />
<ExplorerActions
query={exportDefaultQuery}
sourcePage={ExplorerActionsSource.LOGS_EXPLORER}
/>
),
[exportDefaultQuery],
);

View File

@@ -21,6 +21,7 @@ import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { MAX_QUERY_RETRIES } from 'constants/reactQuery';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import ExplorerActions from 'container/ExplorerActions/ExplorerActions';
import { ExplorerActionsSource } from 'container/ExplorerActions/utils';
import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
@@ -347,7 +348,7 @@ function TimeSeries({
headerActions={
<ExplorerActions
query={stagedQuery ? exportQuery : null}
sourcepage={DataSource.METRICS}
sourcePage={ExplorerActionsSource.METRICS_EXPLORER}
panelType={PANEL_TYPES.TIME_SERIES}
isOneChartPerQuery={changeLayoutForOneChartPerQuery}
/>

View File

@@ -94,11 +94,6 @@
height: 62px;
}
.expression {
font-family: var(--code-base-400-font-family);
font-size: 13px;
}
.timeText {
display: inline-block;
white-space: nowrap;
@@ -121,20 +116,6 @@
color: var(--l2-foreground);
}
.emptyTitle {
color: var(--l1-foreground);
font-size: 16px;
font-weight: 500;
line-height: 24px;
}
.emptySubtitle {
color: var(--l2-foreground);
font-size: 14px;
line-height: 20px;
max-width: 420px;
}
.docsLink {
color: var(--l2-foreground);
font-size: 13px;

View File

@@ -8,15 +8,6 @@
.ant-modal-header {
background-color: var(--l2-background);
.ant-typography {
margin: 0;
color: var(--l1-foreground);
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
.downtime-schedule-btn {
@@ -55,16 +46,6 @@
}
}
.alert-rule-form {
display: flex;
gap: 8px;
align-items: end;
.alert-rule-info {
color: var(--l2-foreground);
}
}
.alert-rule-scope {
margin-bottom: 12px;
margin-top: 8px;
@@ -78,10 +59,6 @@
}
}
.alert-rule-all-warning {
color: var(--l2-foreground);
}
.formItemWithBullet {
margin-bottom: 0;
}
@@ -119,42 +96,11 @@
.ant-modal-body {
padding: 0px 16px 28px 16px;
.ant-typography {
color: var(--l2-foreground);
font-size: var(--paragraph-base-400-font-size);
font-style: normal;
font-weight: var(--paragraph-base-400-font-weight);
line-height: 20px;
letter-spacing: -0.07px;
}
.save-view-input {
margin-top: 8px;
display: flex;
gap: 8px;
}
.ant-color-picker-trigger {
padding: 6px;
border-radius: 2px;
border: 1px solid var(--l1-border);
background: var(--l3-background);
width: 32px;
height: 32px;
.ant-color-picker-color-block {
border-radius: 50px;
width: 16px;
height: 16px;
flex-shrink: 0;
.ant-color-picker-color-block-inner {
display: flex;
justify-content: center;
align-items: center;
}
}
}
}
.ant-modal-footer {

View File

@@ -66,31 +66,6 @@ export const getAlertOptionsFromIds = (
alertIds?.includes(alert.value as string),
);
export const recurrenceInfo = (
schedule?: AlertmanagertypesScheduleDTO | null,
): string => {
if (!schedule) {
return 'No';
}
const { startTime, endTime, timezone, recurrence } = schedule;
if (!recurrence) {
return 'No';
}
const { duration, repeatOn, repeatType } = recurrence;
const formattedStartTime = startTime
? formatDateTime(startTime, timezone)
: '';
const formattedEndTime = endTime
? `to ${formatDateTime(endTime, timezone)}`
: '';
const weeklyRepeatString = repeatOn ? `on ${repeatOn.join(', ')}` : '';
const durationString = duration ? `- Duration: ${duration}` : '';
return `Repeats - ${repeatType} ${weeklyRepeatString} from ${formattedStartTime} ${formattedEndTime} ${durationString}`;
};
export const defaultInitialValues: Partial<AlertmanagertypesPlannedMaintenanceDTO> =
{
name: '',

View File

@@ -11,7 +11,13 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import type { ErrorType } from 'api/generatedAPIInstance';
import { mockAppLocation, mockNavigate } from 'tests/router-mocks';
import { render, screen, userEvent, within } from 'tests/test-utils';
import {
render,
screen,
userEvent,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { USER_ROLES } from 'types/roles';
import { PlannedDowntime } from '../PlannedDowntime';
@@ -240,14 +246,15 @@ describe('PlannedDowntime Component', () => {
});
it('should filter downtime schedules by name when searching', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderPage();
await expect(
screen.findByText(MOCK_DOWNTIME_1_NAME),
).resolves.toBeInTheDocument();
await user.type(screen.getByTestId(SEARCH_TEST_ID), MOCK_DOWNTIME_1_NAME);
await user.click(screen.getByTestId(SEARCH_TEST_ID));
await user.paste(MOCK_DOWNTIME_1_NAME);
await expect(
screen.findByText(MOCK_DOWNTIME_1_NAME),
@@ -257,7 +264,7 @@ describe('PlannedDowntime Component', () => {
});
it('should filter downtime schedules with partial name match', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderPage();
await expect(
@@ -274,10 +281,11 @@ describe('PlannedDowntime Component', () => {
});
it('should show no results when search term matches nothing', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderPage();
await user.type(screen.getByTestId(SEARCH_TEST_ID), 'NonExistentDowntime');
await user.click(screen.getByTestId(SEARCH_TEST_ID));
await user.paste('NonExistentDowntime');
await expect(
screen.findByTestId('no-results-empty-state'),
@@ -286,7 +294,7 @@ describe('PlannedDowntime Component', () => {
});
it('opens the delete confirmation from the row actions', async () => {
const user = userEvent.setup();
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderPage();
await user.click(await screen.findByTestId('downtime-actions-1'));

View File

@@ -19,6 +19,7 @@ import { QueryBuilderContext } from 'providers/QueryBuilder';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { FieldDataType, TelemetryFieldKey } from 'types/api/v5/queryRange';
import { DataSource } from 'types/common/queryBuilder';
import { NO_DELAY_USER_EVENT } from 'tests/test-utils';
import QueryBuilderSearchV2 from '../QueryBuilderSearchV2';
@@ -148,7 +149,7 @@ jest.mock('hooks/dashboard/useDynamicVariableSuggestions', () => ({
describe('Suggestion Key -> Operator -> Value Flow', () => {
it('should complete full flow from key selection to value', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderWithContext();
const combobox = getSearchCombobox();
@@ -199,7 +200,7 @@ describe('Suggestion Key -> Operator -> Value Flow', () => {
describe('Operator suggestions for data types missing from the operators map', () => {
it('should fall back to universal operators for a non-canonical data type', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderWithContext();
const combobox = getSearchCombobox();
@@ -226,7 +227,7 @@ describe('Operator suggestions for data types missing from the operators map', (
describe('Dynamic Variable Suggestions', () => {
it('should suggest dynamic variable when key matches a variable attribute', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderWithContext();
const combobox = getSearchCombobox();
@@ -298,7 +299,7 @@ describe('Filter chips', () => {
});
it('removes the filter once when the chip close button is clicked', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderWithContext({ query: queryWithFilter });
await user.click(
@@ -312,7 +313,7 @@ describe('Filter chips', () => {
});
it('moves the filter into the search input when the chip body is clicked', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderWithContext({ query: queryWithFilter });
await user.click(screen.getByText(CHIP_LABEL));
@@ -356,7 +357,7 @@ describe('Key fetch context', () => {
describe('Keys the legacy filter builders cannot read', () => {
it('does not suggest body JSON keys or span search scope selectors', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderWithContext();
const combobox = getSearchCombobox();
@@ -372,7 +373,7 @@ describe('Keys the legacy filter builders cannot read', () => {
describe('Span field keys', () => {
it('marks span fields as columns and looks up their values in the span context', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderWithContext();
const combobox = getSearchCombobox();

View File

@@ -121,20 +121,6 @@
color: var(--l2-foreground);
}
.emptyTitle {
color: var(--l1-foreground);
font-size: 16px;
font-weight: 500;
line-height: 24px;
}
.emptySubtitle {
color: var(--l2-foreground);
font-size: 14px;
line-height: 20px;
max-width: 420px;
}
.docsLink {
color: var(--l2-foreground);
font-size: 13px;

View File

@@ -120,28 +120,6 @@ export function getAppContextMockState(
};
}
export function mockLocation(pathname: string): jest.Mock {
return jest.fn().mockReturnValue({
pathname,
});
}
export function mockQueryParams(
params: Record<string, string | null>,
): URLSearchParams {
const realUrlQuery = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value !== null) {
realUrlQuery.set(key, value);
}
});
return Object.create(URLSearchParams.prototype, {
toString: { value: (): string => realUrlQuery.toString() },
get: { value: (key: string): string | null => realUrlQuery.get(key) },
});
}
export function convertRoutingPolicyToApiResponse(
routingPolicy: RoutingPolicy,
): ApiRoutingPolicy {

View File

@@ -8,15 +8,6 @@
.ant-modal-header {
background-color: var(--l2-background);
.ant-typography {
margin: 0;
color: var(--l1-foreground);
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
}
@@ -30,15 +21,6 @@
flex-direction: column;
gap: 4px;
.ant-typography {
color: var(--muted-foreground);
font-size: 14px;
font-style: normal;
font-weight: 500;
line-height: 20px;
padding-bottom: 6px;
}
.ant-input {
width: 100%;
border-radius: 2px;
@@ -98,42 +80,11 @@
.ant-modal-body {
padding: 0px 16px 28px 16px;
.ant-typography {
color: var(--l2-foreground);
font-size: var(--paragraph-base-400-font-size);
font-style: normal;
font-weight: var(--paragraph-base-400-font-weight);
line-height: 20px;
letter-spacing: -0.07px;
}
.save-view-input {
margin-top: 8px;
display: flex;
gap: 8px;
}
.ant-color-picker-trigger {
padding: 6px;
border-radius: 2px;
border: 1px solid var(--l1-border);
background: var(--l3-background);
width: 32px;
height: 32px;
.ant-color-picker-color-block {
border-radius: 50px;
width: 16px;
height: 16px;
flex-shrink: 0;
.ant-color-picker-color-block-inner {
display: flex;
justify-content: center;
align-items: center;
}
}
}
}
.ant-modal-footer {

View File

@@ -135,9 +135,10 @@ describe('ServiceAccountsSettings — FGA', () => {
renderPage();
await waitFor(() => {
expect(
screen.getByRole('button', { name: /New Service Account/i }),
).toHaveAttribute('aria-disabled', 'true');
expect(screen.getByTestId('new-sa-btn')).toHaveAttribute(
'aria-disabled',
'true',
);
});
});
@@ -160,9 +161,10 @@ describe('ServiceAccountsSettings — FGA', () => {
renderPage();
await waitFor(() => {
expect(
screen.getByRole('button', { name: /New Service Account/i }),
).not.toHaveAttribute('aria-disabled', 'true');
expect(screen.getByTestId('new-sa-btn')).not.toHaveAttribute(
'aria-disabled',
'true',
);
});
});
});

View File

@@ -7,17 +7,6 @@
padding-top: var(--spacing-8);
}
.header {
position: relative;
z-index: 10;
display: flex;
justify-content: space-between;
align-items: flex-start;
gap: 1rem;
flex-shrink: 0;
padding: 0 var(--spacing-8);
}
.filtersRow {
position: relative;
z-index: 10;
@@ -98,23 +87,6 @@
color: var(--l2-foreground);
}
.filterBadge {
display: inline-flex;
align-items: center;
gap: 4px;
margin-right: 3px;
}
.filterBadgeClose {
cursor: pointer;
opacity: 0.7;
transition: opacity 0.15s ease;
&:hover {
opacity: 1;
}
}
.paginationContainer {
padding-right: var(--spacing-12);
height: 62px;

View File

@@ -1,11 +1,11 @@
import userEvent from '@testing-library/user-event';
import { screen, waitFor } from 'tests/test-utils';
import { screen, waitFor, NO_DELAY_USER_EVENT } from 'tests/test-utils';
import { renderTriggeredAlerts } from './_helpers';
describe('TriggeredAlerts — severity filter', () => {
it('filters to only critical-severity rows when "Critical" is selected', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>
@@ -30,7 +30,7 @@ describe('TriggeredAlerts — severity filter', () => {
});
it('shows union when multiple severities are selected', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>
@@ -55,7 +55,7 @@ describe('TriggeredAlerts — severity filter', () => {
});
it('clearing the filter shows all rows again', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>

View File

@@ -1,4 +1,10 @@
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
screen,
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { renderTriggeredAlerts } from './_helpers';
@@ -13,7 +19,7 @@ describe('TriggeredAlerts — group by', () => {
});
it('groups by service when "service" is selected', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>
@@ -38,7 +44,7 @@ describe('TriggeredAlerts — group by', () => {
});
it('expands and collapses a group row to reveal nested alerts', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>

View File

@@ -1,7 +1,13 @@
import { triggeredAlertsPaginationFixture } from 'mocks-server/__mockdata__/triggered_alerts';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
import {
screen,
userEvent,
waitFor,
within,
NO_DELAY_USER_EVENT,
} from 'tests/test-utils';
import { getCurrentNuqsQueryString } from 'tests/nuqs-helpers';
import { renderTriggeredAlerts } from './_helpers';
@@ -50,7 +56,7 @@ describe('TriggeredAlerts — pagination', () => {
it('navigates to page 2 and shows the next batch of alerts', async () => {
usePaginationHandler();
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await screen.findByText('Pag Alert 14');

View File

@@ -3,13 +3,13 @@ import { logEventMock } from '__tests__/logEventMock';
import { safeNavigateMock } from '__tests__/safeNavigateMock';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { screen, waitFor } from 'tests/test-utils';
import { screen, waitFor, NO_DELAY_USER_EVENT } from 'tests/test-utils';
import { getTriggeredAlertRowTestId, renderTriggeredAlerts } from './_helpers';
describe('TriggeredAlerts — row click', () => {
it('navigates to the alert overview with the rule id from labels on row click', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>
@@ -35,7 +35,7 @@ describe('TriggeredAlerts — row click', () => {
});
it('opens in a new tab when ctrl+clicked', async () => {
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>
@@ -83,7 +83,7 @@ describe('TriggeredAlerts — row click', () => {
),
);
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>
@@ -125,7 +125,7 @@ describe('TriggeredAlerts — row click', () => {
),
);
const user = userEvent.setup({ delay: null });
const user = userEvent.setup(NO_DELAY_USER_EVENT);
renderTriggeredAlerts();
await waitFor(() =>

View File

@@ -12,10 +12,6 @@
color: var(--bg-forest-500);
}
.emptyStateIconMuted {
color: var(--l2-foreground);
}
.emptyStateTitle {
font-size: 18px;
font-weight: 600;

View File

@@ -69,12 +69,6 @@
margin-bottom: 16px;
}
.legends-list-container {
width: 100%;
overflow: hidden;
overflow-y: auto;
}
.save-cancel-container {
flex-basis: 20%;
display: flex;

View File

@@ -1,24 +1,5 @@
import { PanelTypeAndGraphManagerVisibilityProps } from 'container/WidgetCard/Card/FullView/types';
export enum ColumnsKeyAndDataIndex {
Index = 'index',
Legend = 'legend',
Label = 'label',
Avg = 'avg',
Sum = 'sum',
Max = 'max',
Min = 'min',
}
export const ColumnsTitle = {
[ColumnsKeyAndDataIndex.Index]: 'Index',
[ColumnsKeyAndDataIndex.Label]: 'Label',
[ColumnsKeyAndDataIndex.Avg]: 'Avg',
[ColumnsKeyAndDataIndex.Sum]: 'Sum',
[ColumnsKeyAndDataIndex.Max]: 'Max',
[ColumnsKeyAndDataIndex.Min]: 'Min',
};
export const PANEL_TYPES_VS_FULL_VIEW_TABLE: PanelTypeAndGraphManagerVisibilityProps =
{
TIME_SERIES: true,

View File

@@ -1,5 +1,4 @@
import { PANEL_TYPES } from 'constants/queryBuilder';
import { themeColors } from 'constants/theme';
import styled, { css, FlattenSimpleInterpolation } from 'styled-components';
import { GraphContainerProps } from 'container/WidgetCard/Card/FullView/types';
@@ -40,15 +39,3 @@ export const GraphContainer = styled.div<GraphContainerProps>`
height: ${({ isGraphLegendToggleAvailable }): string =>
isGraphLegendToggleAvailable ? '50%' : '100%'};
`;
export const LabelContainer = styled.button<{
isDarkMode?: boolean;
disabled?: boolean;
}>`
max-width: 18.75rem;
cursor: ${(props): string => (props.disabled ? 'no-drop' : 'pointer')};
border: none;
background-color: transparent;
color: ${(props): string =>
props.isDarkMode ? themeColors.white : themeColors.black};
`;

View File

@@ -7,18 +7,6 @@ import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
import { Widgets } from 'types/api/widgets/widget';
import uPlot from 'uplot';
export interface DataSetProps {
index: number;
data: number | null;
label: string;
borderWidth: number;
spanGaps: boolean;
animations: boolean;
borderColor: string;
showLine: boolean;
pointRadius: number;
}
export interface LegendEntryProps {
label: string;
show: boolean;
@@ -29,13 +17,6 @@ export type PanelTypeAndGraphManagerVisibilityProps = Record<
boolean
>;
export interface LabelProps {
labelClickedHandler: (labelIndex: number) => void;
labelIndex: number;
label: string;
disabled?: boolean;
}
export interface FullViewProps {
widget: Widgets;
fullViewOptions?: boolean;

View File

@@ -3,61 +3,11 @@ import setLocalStorageKey from 'api/browser/localstorage/set';
import { LOCALSTORAGE } from 'constants/localStorage';
import getLabelName from 'lib/getLabelName';
import { QueryData } from 'types/api/widgets/getQuery';
import uPlot from 'uplot';
import {
LegendEntryProps,
SaveLegendEntriesToLocalStoreProps,
} from 'container/WidgetCard/Card/FullView/types';
import { ExtendedChartDataset } from 'lib/visualization/charts/types';
function convertToTwoDecimalsOrZero(value: number): number {
if (
typeof value === 'number' &&
!Number.isNaN(value) &&
value !== Infinity &&
value !== -Infinity
) {
const result = value ? value.toFixed(20).match(/^-?\d*\.?0*\d{0,2}/) : null;
return result ? parseFloat(result[0]) : 0;
}
return 0;
}
export const getDefaultTableDataSet = (
options: uPlot.Options,
data: uPlot.AlignedData,
): ExtendedChartDataset[] =>
options.series.map(
(item: uPlot.Series, index: number): ExtendedChartDataset => {
let arr: number[];
if (data[index]) {
arr = data[index] as number[];
} else {
arr = [];
}
return {
...item,
index,
show: true,
sum: convertToTwoDecimalsOrZero(arr.reduce((a, b) => a + b, 0) || 0),
avg: convertToTwoDecimalsOrZero(
(arr.reduce((a, b) => a + b, 0) || 0) / (arr.length || 1),
),
max: convertToTwoDecimalsOrZero(Math.max(...arr)),
min: convertToTwoDecimalsOrZero(Math.min(...arr)),
};
},
);
export const getAbbreviatedLabel = (label: string): string => {
let newLabel = label;
if (label.length > 30) {
newLabel = `${label.substring(0, 30)}...`;
}
return newLabel;
};
export const showAllDataSetFromApiResponse = (
apiResponse: QueryData[],
@@ -71,14 +21,6 @@ export const showAllDataSetFromApiResponse = (
show: true,
}));
export const showAllDataSet = (options: uPlot.Options): LegendEntryProps[] =>
options.series
.map((item): LegendEntryProps => ({
label: item.label || '',
show: true,
}))
.filter((_, index) => index !== 0);
export const saveLegendEntriesToLocalStorage = ({
options,
graphVisibilityState,
@@ -119,11 +61,3 @@ export const saveLegendEntriesToLocalStorage = ({
console.error('Error setting LEGEND_GRAPH to local storage', error);
}
};
export const getGraphManagerTableHeaderTitle = (
title: string,
yAxisUnit?: string,
): string => {
const yAxisUnitText = yAxisUnit ? `(in ${yAxisUnit})` : '';
return `${title} ${yAxisUnitText}`;
};

Some files were not shown because too many files have changed in this diff Show More