mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-19 14:51:11 +00:00
Compare commits
13 Commits
v0.151.0
...
test/jest-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aad689acd2 | ||
|
|
77ebf4dca9 | ||
|
|
c4ac1929fa | ||
|
|
df0f26b5fb | ||
|
|
3843ac4eeb | ||
|
|
0add9cce0d | ||
|
|
4ffa6ac5da | ||
|
|
824315b093 | ||
|
|
1ee097b60a | ||
|
|
f0370c6cc1 | ||
|
|
b106d86bef | ||
|
|
d8c00a34b9 | ||
|
|
0d3eee5c78 |
@@ -9,12 +9,14 @@ paths:
|
||||
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
|
||||
|
||||
- **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` computes the accessibility tree on every call and is the slowest query.
|
||||
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **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` computes the accessibility tree on every call and is the slowest query. 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, which walks `getComputedStyle` up the tree on every action; never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **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`.
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
|
||||
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
|
||||
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
|
||||
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
|
||||
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
|
||||
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.
|
||||
|
||||
@@ -4420,7 +4420,8 @@ components:
|
||||
description: The dashboard title and description.
|
||||
duration:
|
||||
description: The default time range, as a Prometheus duration such as 1h
|
||||
or 7d. Stored, but not applied by the UI.
|
||||
or 7d. The UI opens the dashboard on it, rounded up to whole minutes,
|
||||
when neither the URL nor the viewer's last pick sets a time range.
|
||||
type: string
|
||||
layouts:
|
||||
description: The Grid layouts that place panels, at most 500. Each panel
|
||||
|
||||
@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
|
||||
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
|
||||
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
|
||||
every interactive element.
|
||||
5. **Verify** before reporting done:
|
||||
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
|
||||
```bash
|
||||
pnpm tsgo --noEmit
|
||||
pnpm oxlint src/pages/<Feature>
|
||||
|
||||
@@ -34,14 +34,18 @@ You are operating within a constrained context window and strict system prompts.
|
||||
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
|
||||
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
|
||||
|
||||
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
|
||||
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
|
||||
- Between gates, after an edit, run at most the one test file that covers it.
|
||||
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
|
||||
|
||||
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
|
||||
- Run `pnpm tsgo --noEmit`
|
||||
- Run `pnpm lint:js --quiet` to find critical errors
|
||||
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
|
||||
- Run `pnpm build`
|
||||
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
|
||||
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails
|
||||
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
|
||||
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
|
||||
- Fixed ALL resulting errors
|
||||
|
||||
|
||||
@@ -65,6 +65,8 @@ const config: Config.InitialOptions = {
|
||||
testPathIgnorePatterns: ['/node_modules/', '/public/'],
|
||||
moduleDirectories: ['node_modules', 'src'],
|
||||
testEnvironment: '<rootDir>/jest.environment.cjs',
|
||||
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
|
||||
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
|
||||
coverageThreshold: {
|
||||
global: {
|
||||
statements: 80,
|
||||
|
||||
@@ -144,6 +144,39 @@ window.getComputedStyle = function (
|
||||
}
|
||||
};
|
||||
|
||||
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
|
||||
// popover ancestor costs up to ~1 s per open.
|
||||
jest.mock('@floating-ui/dom', () => ({
|
||||
...jest.requireActual('@floating-ui/dom'),
|
||||
autoUpdate: (): (() => void) => (): void => {},
|
||||
computePosition: (
|
||||
_reference: unknown,
|
||||
_floating: unknown,
|
||||
{ placement = 'bottom', strategy = 'absolute' } = {},
|
||||
): Promise<unknown> =>
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
jest.mock('@testing-library/user-event', () =>
|
||||
jest.requireActual('tests/userEventWithDefaults'),
|
||||
);
|
||||
|
||||
// antd popups walk getComputedStyle up every ancestor to find scroll
|
||||
// containers on each open. pnpm keeps the package under antd, not at the root.
|
||||
jest.mock(
|
||||
require.resolve('@rc-component/trigger/lib/util', {
|
||||
paths: [require.resolve('antd')],
|
||||
}),
|
||||
() => ({
|
||||
...jest.requireActual(
|
||||
require.resolve('@rc-component/trigger/lib/util', {
|
||||
paths: [require.resolve('antd')],
|
||||
}),
|
||||
),
|
||||
collectScroller: (): HTMLElement[] => [],
|
||||
}),
|
||||
);
|
||||
|
||||
beforeAll(() => server.listen());
|
||||
|
||||
afterEach(() => server.resetHandlers());
|
||||
|
||||
@@ -8042,7 +8042,7 @@ export interface DashboardtypesDashboardSpecDTO {
|
||||
display: DashboardtypesDisplayDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
|
||||
* @description The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range.
|
||||
*/
|
||||
duration?: string;
|
||||
/**
|
||||
|
||||
@@ -903,6 +903,40 @@ describe('prepareQueryRangePayloadV5', () => {
|
||||
const logSpec = builderQuery.spec as LogBuilderQuery;
|
||||
expect(logSpec.filter).toStrictEqual({ expression: '' });
|
||||
});
|
||||
|
||||
it('sends the AI slot as builder_ai_query envelopes, ignoring builder', () => {
|
||||
const props: GetQueryResultsProps = {
|
||||
query: {
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
id: 'q-ai',
|
||||
unit: undefined,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
builder: {
|
||||
queryData: [baseBuilderQuery({ queryName: 'M' })],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
builder_ai_query: {
|
||||
queryData: [
|
||||
baseBuilderQuery({ queryName: 'A', dataSource: DataSource.TRACES }),
|
||||
],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
},
|
||||
graphType: PANEL_TYPES.TIME_SERIES,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
start,
|
||||
end,
|
||||
};
|
||||
|
||||
const { queries } =
|
||||
prepareQueryRangePayloadV5(props).queryPayload.compositeQuery;
|
||||
expect(
|
||||
queries.map((q) => [q.type, (q.spec as { name: string }).name]),
|
||||
).toStrictEqual([['builder_ai_query', 'A']]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mapPanelTypeToRequestType', () => {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { foldAISlot } from 'lib/query/builderSlot';
|
||||
import getStartEndRangeTime from 'lib/getStartEndRangeTime';
|
||||
import { mapQueryDataToApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataToApi';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
@@ -563,9 +564,15 @@ export const prepareQueryRangePayloadV5 = (
|
||||
const requestType = mapPanelTypeToRequestType(graphType);
|
||||
let queries: QueryEnvelope[] = [];
|
||||
|
||||
switch (query.queryType) {
|
||||
const foldedQuery = foldAISlot(query);
|
||||
|
||||
switch (foldedQuery.queryType) {
|
||||
case EQueryType.QUERY_BUILDER: {
|
||||
const { queryData: data, queryFormulas, queryTraceOperator } = query.builder;
|
||||
const {
|
||||
queryData: data,
|
||||
queryFormulas,
|
||||
queryTraceOperator,
|
||||
} = foldedQuery.builder;
|
||||
const currentQueryData = mapQueryDataToApi(data, 'queryName', tableParams);
|
||||
const currentFormulas = mapQueryDataToApi(queryFormulas, 'queryName');
|
||||
|
||||
@@ -627,13 +634,15 @@ export const prepareQueryRangePayloadV5 = (
|
||||
break;
|
||||
}
|
||||
case EQueryType.PROM: {
|
||||
const promQueries = reduceQueriesToObject(query[query.queryType]);
|
||||
const promQueries = reduceQueriesToObject(
|
||||
foldedQuery[foldedQuery.queryType],
|
||||
);
|
||||
queries = convertPromQueriesToV5(promQueries.queries);
|
||||
legendMap = promQueries.legends;
|
||||
break;
|
||||
}
|
||||
case EQueryType.CLICKHOUSE: {
|
||||
const chQueries = reduceQueriesToObject(query[query.queryType]);
|
||||
const chQueries = reduceQueriesToObject(foldedQuery[foldedQuery.queryType]);
|
||||
queries = convertClickHouseQueriesToV5(chQueries.queries);
|
||||
legendMap = chQueries.legends;
|
||||
break;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { memo, useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { Formula } from 'container/QueryBuilder/components/Formula';
|
||||
import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interfaces';
|
||||
@@ -49,6 +50,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
initialDataSource,
|
||||
handleRunQuery,
|
||||
} = useQueryBuilder();
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
|
||||
const containerRef = useRef(null);
|
||||
|
||||
@@ -129,28 +131,28 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
const renderedQueries = useMemo(
|
||||
() =>
|
||||
isMultiQueryAllowed
|
||||
? currentQuery.builder.queryData
|
||||
: currentQuery.builder.queryData.slice(0, 1),
|
||||
[isMultiQueryAllowed, currentQuery.builder.queryData],
|
||||
? activeBuilder.queryData
|
||||
: activeBuilder.queryData.slice(0, 1),
|
||||
[isMultiQueryAllowed, activeBuilder.queryData],
|
||||
);
|
||||
|
||||
const traceOperator = useMemo((): IBuilderTraceOperator | undefined => {
|
||||
if (
|
||||
currentQuery.builder.queryTraceOperator &&
|
||||
currentQuery.builder.queryTraceOperator.length > 0
|
||||
activeBuilder.queryTraceOperator &&
|
||||
activeBuilder.queryTraceOperator.length > 0
|
||||
) {
|
||||
return currentQuery.builder.queryTraceOperator[0];
|
||||
return activeBuilder.queryTraceOperator[0];
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [currentQuery.builder.queryTraceOperator]);
|
||||
}, [activeBuilder.queryTraceOperator]);
|
||||
|
||||
const hasAtLeastOneTraceQuery = useMemo(
|
||||
() =>
|
||||
currentQuery.builder.queryData.some(
|
||||
activeBuilder.queryData.some(
|
||||
(query) => query.dataSource === DataSource.TRACES,
|
||||
),
|
||||
[currentQuery.builder.queryData],
|
||||
[activeBuilder.queryData],
|
||||
);
|
||||
|
||||
const hasTraceOperator = useMemo(
|
||||
@@ -225,9 +227,9 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
{!isMultiQueryAllowed ? (
|
||||
<QueryV2
|
||||
ref={containerRef}
|
||||
key={currentQuery.builder.queryData[0].queryName}
|
||||
key={activeBuilder.queryData[0].queryName}
|
||||
index={0}
|
||||
query={currentQuery.builder.queryData[0]}
|
||||
query={activeBuilder.queryData[0]}
|
||||
fieldsConfig={fieldsConfig}
|
||||
allowedDataSources={queryDataSources}
|
||||
isMultiQueryAllowed={isMultiQueryAllowed}
|
||||
@@ -238,7 +240,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
queryVariant={config?.queryVariant || 'dropdown'}
|
||||
showOnlyWhereClause={showOnlyWhereClause}
|
||||
isRawQuery={isRawQuery}
|
||||
signalSource={currentQuery.builder.queryData[0].source as 'meter' | ''}
|
||||
signalSource={activeBuilder.queryData[0].source as 'meter' | ''}
|
||||
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
|
||||
signalSourceChangeEnabled={signalSourceChangeEnabled}
|
||||
queriesCount={1}
|
||||
@@ -264,28 +266,26 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
signalSource={query.source as 'meter' | ''}
|
||||
onSignalSourceChange={onSignalSourceChange || ((): void => {})}
|
||||
signalSourceChangeEnabled={signalSourceChangeEnabled}
|
||||
queriesCount={currentQuery.builder.queryData.length}
|
||||
queriesCount={activeBuilder.queryData.length}
|
||||
savePreviousQuery={savePreviousQuery}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
|
||||
{!showOnlyWhereClause &&
|
||||
currentQuery.builder.queryFormulas?.length > 0 && (
|
||||
<div className="qb-formulas-container">
|
||||
{currentQuery.builder.queryFormulas.map((formula, index) => {
|
||||
const query =
|
||||
currentQuery.builder.queryData[index] ||
|
||||
currentQuery.builder.queryData[0];
|
||||
{!showOnlyWhereClause && activeBuilder.queryFormulas?.length > 0 && (
|
||||
<div className="qb-formulas-container">
|
||||
{activeBuilder.queryFormulas.map((formula, index) => {
|
||||
const query =
|
||||
activeBuilder.queryData[index] || activeBuilder.queryData[0];
|
||||
|
||||
return (
|
||||
<div key={formula.queryName} className="qb-formula">
|
||||
<Formula query={query} formula={formula} index={index} isQBV2 />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
return (
|
||||
<div key={formula.queryName} className="qb-formula">
|
||||
<Formula query={query} formula={formula} index={index} isQBV2 />
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{shouldShowFooter && (
|
||||
<QueryFooter
|
||||
@@ -319,7 +319,7 @@ export const QueryBuilderV2 = memo(function QueryBuilderV2({
|
||||
</div>
|
||||
))}
|
||||
|
||||
{currentQuery.builder.queryFormulas?.map((formula) => (
|
||||
{activeBuilder.queryFormulas?.map((formula) => (
|
||||
<div key={formula.queryName} className="formula-name">
|
||||
{formula.queryName}
|
||||
</div>
|
||||
|
||||
@@ -88,6 +88,9 @@ export function QueryBuilderV2Provider({
|
||||
);
|
||||
}
|
||||
|
||||
export const useIsInQueryBuilderV2 = (): boolean =>
|
||||
useContext(QueryBuilderV2Context) !== undefined;
|
||||
|
||||
export const useQueryBuilderV2Context = (): QueryBuilderV2ContextType => {
|
||||
const context = useContext(QueryBuilderV2Context);
|
||||
if (!context) {
|
||||
|
||||
@@ -25,6 +25,7 @@ import CodeMirror, {
|
||||
import { Button, Popover, Tooltip } from 'antd';
|
||||
import { TelemetrytypesFieldDataTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { tracesAggregateOperatorOptions } from 'constants/queryBuilderOperators';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
import { useFieldKeysSuggestion } from 'hooks/querySuggestions/useFieldKeysSuggestion';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { Info, TriangleAlert } from '@signozhq/icons';
|
||||
@@ -321,6 +322,7 @@ function QueryAggregationSelect({
|
||||
functionContextForFetch &&
|
||||
OPERATORS_WITHOUT_DATA_TYPE.includes(functionContextForFetch)
|
||||
);
|
||||
const builderQueryType = useBuilderQueryType(queryData);
|
||||
const { data: fieldKeys, isLoading: isLoadingFields } = useFieldKeysSuggestion(
|
||||
{
|
||||
signal: DATA_SOURCE_TO_SIGNAL[queryData.dataSource],
|
||||
@@ -329,7 +331,7 @@ function QueryAggregationSelect({
|
||||
? TelemetrytypesFieldDataTypeDTO.number
|
||||
: undefined,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
{
|
||||
enabled:
|
||||
!!functionContextForFetch &&
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useMemo } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { Button, Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import WarningPopover from 'components/WarningPopover/WarningPopover';
|
||||
@@ -15,28 +16,25 @@ function TraceOperatorSection({
|
||||
addTraceOperator?: () => void;
|
||||
}): JSX.Element {
|
||||
const { currentQuery, panelType } = useQueryBuilder();
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
|
||||
const showTraceOperatorWarning = useMemo(() => {
|
||||
const isRawQueryPanel =
|
||||
panelType === PANEL_TYPES.LIST || panelType === PANEL_TYPES.TRACE;
|
||||
const hasMultipleQueries = currentQuery.builder.queryData.length > 1;
|
||||
const hasMultipleQueries = activeBuilder.queryData.length > 1;
|
||||
const hasTraceOperator =
|
||||
currentQuery.builder.queryTraceOperator &&
|
||||
currentQuery.builder.queryTraceOperator.length > 0;
|
||||
activeBuilder.queryTraceOperator &&
|
||||
activeBuilder.queryTraceOperator.length > 0;
|
||||
return isRawQueryPanel && hasMultipleQueries && !hasTraceOperator;
|
||||
}, [
|
||||
currentQuery?.builder?.queryData,
|
||||
currentQuery?.builder?.queryTraceOperator,
|
||||
panelType,
|
||||
]);
|
||||
}, [activeBuilder.queryData, activeBuilder.queryTraceOperator, panelType]);
|
||||
|
||||
const traceOperatorWarning = useMemo(() => {
|
||||
if (currentQuery.builder.queryData.length === 0) {
|
||||
if (activeBuilder.queryData.length === 0) {
|
||||
return '';
|
||||
}
|
||||
const firstQuery = currentQuery.builder.queryData[0];
|
||||
const firstQuery = activeBuilder.queryData[0];
|
||||
return `Currently, you are only seeing results from query ${firstQuery.queryName}. Add a trace operator to combine results of multiple queries.`;
|
||||
}, [currentQuery]);
|
||||
}, [activeBuilder.queryData]);
|
||||
return (
|
||||
<div className="qb-trace-operator-button-container">
|
||||
<Tooltip
|
||||
|
||||
@@ -33,6 +33,7 @@ import {
|
||||
queryOperatorSuggestions,
|
||||
} from 'constants/antlrQueryConstants';
|
||||
import { useDynamicVariableSuggestions } from 'hooks/dashboard/useDynamicVariableSuggestions';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import useDebounce from 'hooks/useDebounce';
|
||||
import { debounce, isNull } from 'lodash-es';
|
||||
@@ -148,6 +149,7 @@ function QuerySearch({
|
||||
metricNamespace,
|
||||
valueSuggestionsOverride,
|
||||
}: QuerySearchProps): JSX.Element {
|
||||
const builderQueryType = useBuilderQueryType(queryData);
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const [valueSuggestions, setValueSuggestions] = useState<any[]>([]);
|
||||
const [activeKey, setActiveKey] = useState<string>('');
|
||||
@@ -359,7 +361,7 @@ function QuerySearch({
|
||||
source: signalSource as TelemetrytypesSourceDTO,
|
||||
metricNamespace,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
);
|
||||
|
||||
if (response.data.keys) {
|
||||
@@ -397,7 +399,7 @@ function QuerySearch({
|
||||
hardcodedAttributeKeys,
|
||||
showFilterSuggestionsWithoutMetric,
|
||||
metricNamespace,
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -539,7 +541,7 @@ function QuerySearch({
|
||||
source: signalSource as TelemetrytypesSourceDTO,
|
||||
metricName: debouncedMetricName ?? undefined,
|
||||
},
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
).then((response) => {
|
||||
const responseData = response.data;
|
||||
const responseDataValues = responseData.values;
|
||||
@@ -642,7 +644,7 @@ function QuerySearch({
|
||||
signalSource,
|
||||
toggleSuggestions,
|
||||
valueSuggestionsOverride,
|
||||
queryData.builderQueryType,
|
||||
builderQueryType,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import QBEntityOptions from 'container/QueryBuilder/components/QBEntityOptions/QBEntityOptions';
|
||||
import { QueryProps } from 'container/QueryBuilder/type';
|
||||
import SpanScopeSelector from 'container/QueryBuilder/filters/QueryBuilderSearchV2/SpanScopeSelector';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useQueryOperations } from 'hooks/queryBuilder/useQueryBuilderOperations';
|
||||
import { Copy, Ellipsis, Trash } from '@signozhq/icons';
|
||||
@@ -62,7 +63,8 @@ export const QueryV2 = forwardRef(function QueryV2(
|
||||
const { cloneQuery, panelType } = useQueryBuilder();
|
||||
|
||||
const hasQueryFunctions = query?.functions?.length > 0;
|
||||
const { dataSource, builderQueryType } = query;
|
||||
const { dataSource } = query;
|
||||
const builderQueryType = useBuilderQueryType(query);
|
||||
|
||||
const [isCollapsed, setIsCollapsed] = useState(false);
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
/* eslint-disable sonarjs/no-identical-functions */
|
||||
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -87,17 +88,18 @@ function TraceOperatorEditor({
|
||||
const [isExternalQueryChange, setIsExternalQueryChange] = useState(false);
|
||||
const [lastExternalValue, setLastExternalValue] = useState<string>('');
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
|
||||
const queryOptions = useMemo(
|
||||
() =>
|
||||
currentQuery.builder.queryData
|
||||
activeBuilder.queryData
|
||||
.filter((query) => query.dataSource === DataSource.TRACES) // Only show trace queries
|
||||
.map((query) => ({
|
||||
label: query.queryName,
|
||||
type: 'atom',
|
||||
apply: query.queryName,
|
||||
})),
|
||||
[currentQuery.builder.queryData],
|
||||
[activeBuilder.queryData],
|
||||
);
|
||||
|
||||
const toggleSuggestions = useCallback(
|
||||
|
||||
@@ -10,7 +10,11 @@ import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { QueryBuilderV2Provider } from '../../QueryBuilderV2Context';
|
||||
import QueryAggregationSelect from '../QueryAggregation/QueryAggregationSelect';
|
||||
@@ -107,12 +111,18 @@ beforeEach(() => {
|
||||
);
|
||||
});
|
||||
|
||||
async function enterAggregation(text: string): Promise<void> {
|
||||
async function enterAggregation(
|
||||
text: string,
|
||||
queryData: IBuilderQuery = aiQuery,
|
||||
currentQuery?: Query,
|
||||
): Promise<void> {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<QueryBuilderV2Provider>
|
||||
<QueryAggregationSelect queryData={aiQuery} />
|
||||
<QueryAggregationSelect queryData={queryData} />
|
||||
</QueryBuilderV2Provider>,
|
||||
undefined,
|
||||
{ queryBuilderOverrides: currentQuery && { currentQuery } },
|
||||
);
|
||||
|
||||
const content = (
|
||||
@@ -165,4 +175,26 @@ describe('QueryAggregationSelect field suggestions for an AI query', () => {
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
);
|
||||
|
||||
it(
|
||||
'uses the AI keys endpoint for an untagged query on the AI query type',
|
||||
async () => {
|
||||
await enterAggregation(
|
||||
'avg(',
|
||||
{ ...aiQuery, builderQueryType: undefined },
|
||||
{ ...initialQueriesMap.traces, queryType: EQueryType.AI_QUERY_BUILDER },
|
||||
);
|
||||
|
||||
await waitFor(
|
||||
() =>
|
||||
expect(suggestionLabels()).toStrictEqual([
|
||||
'duration_nano',
|
||||
'trace.total_tokens',
|
||||
]),
|
||||
{ timeout: SUGGESTIONS_TIMEOUT_MS },
|
||||
);
|
||||
expect(keysRequests).toHaveLength(0);
|
||||
},
|
||||
TEST_TIMEOUT_MS,
|
||||
);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import type {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { QueryBuilderV2 } from '../QueryBuilderV2';
|
||||
|
||||
jest.mock('../QueryV2/QueryV2', () => ({
|
||||
QueryV2: ({ query }: { query: IBuilderQuery }): JSX.Element => (
|
||||
<div data-testid="query-v2">{query.queryName}</div>
|
||||
),
|
||||
}));
|
||||
jest.mock('../QueryV2/QueryFooter/QueryFooter', () => (): null => null);
|
||||
|
||||
function renderWith(currentQuery: Query): void {
|
||||
render(
|
||||
<QueryBuilderV2 panelType={PANEL_TYPES.TIME_SERIES} version="v3" />,
|
||||
undefined,
|
||||
{
|
||||
queryBuilderOverrides: {
|
||||
currentQuery,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
initialDataSource: null,
|
||||
handleSetConfig: jest.fn(),
|
||||
addNewBuilderQuery: jest.fn(),
|
||||
addNewFormula: jest.fn(),
|
||||
addTraceOperator: jest.fn(),
|
||||
handleRunQuery: jest.fn(),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
const builderWithQuery = (
|
||||
builder: Query['builder'],
|
||||
queryName: string,
|
||||
): Query['builder'] => ({
|
||||
...builder,
|
||||
queryData: [{ ...builder.queryData[0], queryName }],
|
||||
});
|
||||
|
||||
const query: Query = {
|
||||
...initialQueriesMap.metrics,
|
||||
builder: builderWithQuery(initialQueriesMap.metrics.builder, 'MAIN'),
|
||||
builder_ai_query: builderWithQuery(
|
||||
getActiveBuilder(initialQueryAIWithType),
|
||||
'AI',
|
||||
),
|
||||
};
|
||||
|
||||
describe('QueryBuilderV2 builder slot', () => {
|
||||
it('renders the AI slot when AI is the query type', () => {
|
||||
renderWith({ ...query, queryType: EQueryType.AI_QUERY_BUILDER });
|
||||
|
||||
expect(screen.getByTestId('query-v2')).toHaveTextContent('AI');
|
||||
});
|
||||
|
||||
it('renders builder when Query Builder is the query type', () => {
|
||||
renderWith(query);
|
||||
|
||||
expect(screen.getByTestId('query-v2')).toHaveTextContent('MAIN');
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,8 @@
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { QueryMode } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { QueryBuilderV2 } from '../QueryBuilderV2';
|
||||
@@ -19,7 +19,7 @@ const aiQuery: Query = {
|
||||
...initialQueriesMap.traces.builder,
|
||||
queryData: initialQueriesMap.traces.builder.queryData.map((query) => ({
|
||||
...query,
|
||||
builderQueryType: QueryMode.AI_QUERY_BUILDER,
|
||||
builderQueryType: EQueryType.AI_QUERY_BUILDER,
|
||||
})),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
import { negateOperator, OPERATORS } from 'constants/antlrQueryConstants';
|
||||
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { extractQueryPairs } from 'utils/queryContextUtils';
|
||||
|
||||
import {
|
||||
adjustQueryForV5,
|
||||
convertAggregationToExpression,
|
||||
convertExpressionToFilters,
|
||||
convertFiltersToExpression,
|
||||
@@ -1684,3 +1687,31 @@ describe('formatValueForExpression', () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('adjustQueryForV5', () => {
|
||||
it('adjusts the AI builder slot for AI query builder queries', () => {
|
||||
const emptyBuilder = {
|
||||
queryData: [],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
};
|
||||
const query: Query = {
|
||||
id: 'q',
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
builder: emptyBuilder,
|
||||
builder_ai_query: {
|
||||
...emptyBuilder,
|
||||
queryData: [initialQueryBuilderFormValuesMap.logs],
|
||||
},
|
||||
};
|
||||
|
||||
const result = adjustQueryForV5(query);
|
||||
|
||||
expect(result.builder).toBe(emptyBuilder);
|
||||
expect(result.builder_ai_query?.queryData[0]).not.toHaveProperty(
|
||||
'aggregateOperator',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
@@ -20,7 +21,8 @@ export function useSyncQueryBuilderFields(
|
||||
fields: SyncedQueryBuilderField[] = NO_FIELDS,
|
||||
): void {
|
||||
const { currentQuery, handleSetQueryData } = useQueryBuilder();
|
||||
const queries = currentQuery.builder.queryData;
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
const queries = activeBuilder.queryData;
|
||||
const previousRef = useRef<Map<string, IBuilderQuery>>();
|
||||
const enabled = fields.length > 0;
|
||||
|
||||
|
||||
@@ -9,6 +9,11 @@ import {
|
||||
QUERY_BUILDER_FUNCTIONS,
|
||||
} from 'constants/antlrQueryConstants';
|
||||
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
isBuilderQueryType,
|
||||
} from 'lib/query/builderSlot';
|
||||
import FilterQueryLexer from 'parser/FilterQueryLexer';
|
||||
import FilterQueryParser, {
|
||||
AndExpressionContext,
|
||||
@@ -33,7 +38,6 @@ import {
|
||||
MetricAggregation,
|
||||
TraceAggregation,
|
||||
} from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
|
||||
import { extractQueryPairs } from 'utils/queryContextUtils';
|
||||
import { isQuoted, unquote } from 'utils/stringUtils';
|
||||
@@ -1030,8 +1034,9 @@ export function getQueryLabelWithAggregation(
|
||||
}
|
||||
|
||||
export const adjustQueryForV5 = (currentQuery: Query): Query => {
|
||||
if (currentQuery.queryType === EQueryType.QUERY_BUILDER) {
|
||||
const newQueryData = currentQuery.builder.queryData.map((query) => {
|
||||
if (isBuilderQueryType(currentQuery.queryType)) {
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
const newQueryData = activeBuilder.queryData.map((query) => {
|
||||
const aggregations = query.aggregations?.map((aggregation) => {
|
||||
if (query.dataSource === DataSource.METRICS) {
|
||||
const metricAggregation = aggregation as MetricAggregation;
|
||||
@@ -1072,8 +1077,8 @@ export const adjustQueryForV5 = (currentQuery: Query): Query => {
|
||||
|
||||
return {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
[getBuilderSlotKeyForQueryType(currentQuery.queryType)]: {
|
||||
...activeBuilder,
|
||||
queryData: newQueryData,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,6 +4,8 @@ function QueryTypeTag({ queryType }: IQueryTypeTagProps): JSX.Element {
|
||||
switch (queryType) {
|
||||
case EQueryType.QUERY_BUILDER:
|
||||
return <span>Query Builder</span>;
|
||||
case EQueryType.AI_QUERY_BUILDER:
|
||||
return <span>AI Query Builder</span>;
|
||||
|
||||
case EQueryType.CLICKHOUSE:
|
||||
return <span>ClickHouse Query</span>;
|
||||
|
||||
@@ -3,6 +3,8 @@ import {
|
||||
convertFiltersToExpressionWithExistingQuery,
|
||||
} from 'components/QueryBuilderV2/utils';
|
||||
import { QuickFiltersSource } from 'components/QuickFilters/types';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import {
|
||||
Query,
|
||||
TagFilter,
|
||||
@@ -556,3 +558,50 @@ describe('clearFilterFromQuery', () => {
|
||||
expect(active.filter?.expression).toBe(`http.method = 'GET'`);
|
||||
});
|
||||
});
|
||||
|
||||
describe('quick filters on an AI query', () => {
|
||||
const builderQuery = buildQuery([], '').builder;
|
||||
const aiQuery: Query = {
|
||||
...initialQueriesMap.traces,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: builderQuery,
|
||||
builder_ai_query: buildQuery(
|
||||
[{ key: KEY, op: 'in', value: ['a'] }],
|
||||
`${KEY} IN ['a']`,
|
||||
).builder,
|
||||
};
|
||||
|
||||
it('a checkbox toggle writes into the AI slot and leaves builder alone', () => {
|
||||
const result = applyCheckboxToggle({
|
||||
currentQuery: aiQuery,
|
||||
activeQueryIndex: 0,
|
||||
filter: { attributeKey: { key: KEY, type: 'tag' } } as never,
|
||||
quickFilterSource: QuickFiltersSource.AI_OBSERVABILITY,
|
||||
attributeValues: ['a', 'b', 'c'],
|
||||
value: 'b',
|
||||
checked: true,
|
||||
isOnlyOrAllClicked: false,
|
||||
});
|
||||
|
||||
expect(result.builder).toBe(builderQuery);
|
||||
expect(
|
||||
result.builder_ai_query?.queryData[0].filters?.items.map(
|
||||
(item) => item.value,
|
||||
),
|
||||
).toStrictEqual([['a', 'b']]);
|
||||
});
|
||||
|
||||
it('clearing a filter clears it from the AI slot', () => {
|
||||
const result = clearFilterFromQuery({
|
||||
currentQuery: aiQuery,
|
||||
filterKey: KEY,
|
||||
activeQueryIndex: 0,
|
||||
});
|
||||
|
||||
expect(result.builder).toBe(builderQuery);
|
||||
expect(result.builder_ai_query?.queryData[0].filters?.items).toStrictEqual(
|
||||
[],
|
||||
);
|
||||
expect(result.builder_ai_query?.queryData[0].filter?.expression).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,6 +10,11 @@ import {
|
||||
import { OPERATORS } from 'constants/antlrQueryConstants';
|
||||
import { getOperatorValue } from 'container/QueryBuilder/filters/QueryBuilderSearchV2/utils';
|
||||
import { cloneDeep, isArray } from 'lodash-es';
|
||||
import {
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { Query, TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
|
||||
@@ -157,8 +162,10 @@ export function applyCheckboxToggle({
|
||||
previousState?: CheckedState;
|
||||
sectionType?: SectionType;
|
||||
}): Query {
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
|
||||
const activeItems =
|
||||
currentQuery.builder.queryData?.[activeQueryIndex]?.filters?.items;
|
||||
activeBuilder.queryData?.[activeQueryIndex]?.filters?.items;
|
||||
|
||||
const isSomeFilterPresentForCurrentAttribute = !!activeItems?.some((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
@@ -173,7 +180,7 @@ export function applyCheckboxToggle({
|
||||
const isMultipleValuesTrueForTheKey =
|
||||
Object.values(currentFilterState).filter((val) => val).length > 1;
|
||||
|
||||
const query = cloneDeep(currentQuery.builder.queryData?.[activeQueryIndex]);
|
||||
const query = cloneDeep(activeBuilder.queryData?.[activeQueryIndex]);
|
||||
|
||||
// if only or all are clicked we do not need to worry about anything just override whatever we have
|
||||
// by either adding a new IN operator value clause in case of ONLY or remove everything we have for ALL.
|
||||
@@ -430,18 +437,15 @@ export function applyCheckboxToggle({
|
||||
query.filters = synced.filters;
|
||||
}
|
||||
|
||||
return {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: [
|
||||
...currentQuery.builder.queryData.map((q, idx) => {
|
||||
if (idx === activeQueryIndex) {
|
||||
return query;
|
||||
}
|
||||
return q;
|
||||
}),
|
||||
],
|
||||
},
|
||||
};
|
||||
return replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: [
|
||||
...activeBuilder.queryData.map((q, idx) => {
|
||||
if (idx === activeQueryIndex) {
|
||||
return query;
|
||||
}
|
||||
return q;
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import { IQuickFiltersConfig } from 'components/QuickFilters/types';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
|
||||
import { DEFAULT_VISIBLE_ITEMS_COUNT } from './constants';
|
||||
import { isKeyMatch } from './utils';
|
||||
@@ -37,12 +38,13 @@ function useCheckboxDisclosure({
|
||||
DEFAULT_VISIBLE_ITEMS_COUNT,
|
||||
);
|
||||
|
||||
const { queryData } = getActiveBuilder(currentQuery);
|
||||
const isSomeFilterPresentForCurrentAttribute = useMemo(
|
||||
() =>
|
||||
!!currentQuery.builder.queryData?.[activeQueryIndex]?.filters?.items?.some(
|
||||
(item) => isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
!!queryData?.[activeQueryIndex]?.filters?.items?.some((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
),
|
||||
[currentQuery.builder.queryData, activeQueryIndex, filter.attributeKey.key],
|
||||
[queryData, activeQueryIndex, filter.attributeKey.key],
|
||||
);
|
||||
|
||||
const isOpen = useMemo(() => {
|
||||
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
QuickFiltersSource,
|
||||
} from 'components/QuickFilters/types';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { isEqual, isFunction } from 'lodash-es';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
@@ -77,7 +78,7 @@ function useCheckboxFilterActions({
|
||||
dispatch(updatedQuery);
|
||||
|
||||
if (onQuickFilterChange) {
|
||||
const queryData = updatedQuery.builder.queryData[activeQueryIndex];
|
||||
const queryData = getActiveBuilder(updatedQuery).queryData[activeQueryIndex];
|
||||
const expression = queryData?.filter?.expression || '';
|
||||
const filterItemKeys = (queryData?.filters?.items || [])
|
||||
.map((item) => item.key?.key)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useMemo } from 'react';
|
||||
import { IQuickFiltersConfig } from 'components/QuickFilters/types';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
|
||||
import { deriveCheckboxState } from './checkboxFilterQuery';
|
||||
import { isKeyMatch } from './utils';
|
||||
@@ -31,33 +32,28 @@ function useCheckboxFilterState({
|
||||
activeQueryIndex,
|
||||
}: UseCheckboxFilterStateProps): UseCheckboxFilterStateReturn {
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const activeQueryData = currentQuery
|
||||
? getActiveBuilder(currentQuery).queryData
|
||||
: undefined;
|
||||
|
||||
// derive the state of each filter key here and keep it in sync with current query
|
||||
const currentFilterState = useMemo(
|
||||
() =>
|
||||
deriveCheckboxState({
|
||||
attributeValues,
|
||||
filterItems:
|
||||
currentQuery?.builder.queryData?.[activeQueryIndex]?.filters?.items,
|
||||
filterItems: activeQueryData?.[activeQueryIndex]?.filters?.items,
|
||||
filterKey: filter.attributeKey.key,
|
||||
}),
|
||||
[
|
||||
attributeValues,
|
||||
currentQuery?.builder.queryData,
|
||||
filter.attributeKey,
|
||||
activeQueryIndex,
|
||||
],
|
||||
[attributeValues, activeQueryData, filter.attributeKey, activeQueryIndex],
|
||||
);
|
||||
|
||||
// disable the filter when there are multiple entries of the same attribute key present in the filter bar
|
||||
const isFilterDisabled = useMemo(
|
||||
() =>
|
||||
(currentQuery?.builder?.queryData?.[
|
||||
activeQueryIndex
|
||||
]?.filters?.items?.filter((item) =>
|
||||
(activeQueryData?.[activeQueryIndex]?.filters?.items?.filter((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
)?.length || 0) > 1,
|
||||
[currentQuery?.builder?.queryData, activeQueryIndex, filter.attributeKey],
|
||||
[activeQueryData, activeQueryIndex, filter.attributeKey],
|
||||
);
|
||||
|
||||
// whether the current filter has multiple values to its name in the key op value section
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from 'components/QuickFilters/types';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import useDebouncedFn from 'hooks/useDebouncedFunction';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
@@ -128,18 +129,15 @@ export default function CheckboxFilterV2(
|
||||
onToggleOpen();
|
||||
};
|
||||
|
||||
const activeQueryData = currentQuery
|
||||
? getActiveBuilder(currentQuery).queryData
|
||||
: undefined;
|
||||
const currentFilterOp = useMemo(() => {
|
||||
const filterSync = currentQuery?.builder.queryData?.[
|
||||
activeQueryIndex
|
||||
]?.filters?.items.find((item) =>
|
||||
isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
const filterSync = activeQueryData?.[activeQueryIndex]?.filters?.items.find(
|
||||
(item) => isKeyMatch(item.key?.key, filter.attributeKey.key),
|
||||
);
|
||||
return filterSync?.op;
|
||||
}, [
|
||||
currentQuery?.builder.queryData,
|
||||
activeQueryIndex,
|
||||
filter.attributeKey.key,
|
||||
]);
|
||||
}, [activeQueryData, activeQueryIndex, filter.attributeKey.key]);
|
||||
|
||||
const isNotInOperator = NON_SELECTED_OPERATORS.includes(currentFilterOp || '');
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
|
||||
import { QuickFilterCheckboxUseFieldApis } from 'components/QuickFilters/types';
|
||||
|
||||
@@ -18,6 +19,9 @@ export function useExistingQuery({
|
||||
activeQueryIndex,
|
||||
}: UseExistingQueryParams): UseExistingQueryResult {
|
||||
const { stagedQuery } = useQueryBuilder();
|
||||
const stagedQueryData = stagedQuery
|
||||
? getActiveBuilder(stagedQuery).queryData
|
||||
: undefined;
|
||||
|
||||
const existingQuery = useMemo(() => {
|
||||
if (useFieldApis.existingQuery === null) {
|
||||
@@ -28,7 +32,7 @@ export function useExistingQuery({
|
||||
return useFieldApis.existingQuery;
|
||||
}
|
||||
|
||||
const queryData = stagedQuery?.builder.queryData?.[activeQueryIndex];
|
||||
const queryData = stagedQueryData?.[activeQueryIndex];
|
||||
|
||||
// Prefer V5 filter.expression
|
||||
if (queryData?.filter?.expression) {
|
||||
@@ -41,21 +45,17 @@ export function useExistingQuery({
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}, [
|
||||
useFieldApis.existingQuery,
|
||||
stagedQuery?.builder.queryData,
|
||||
activeQueryIndex,
|
||||
]);
|
||||
}, [useFieldApis.existingQuery, stagedQueryData, activeQueryIndex]);
|
||||
|
||||
// Check if ANY filters exist in query (V3 items or V5 expression)
|
||||
// This is separate from existingQuery because existingQuery can be explicitly
|
||||
// disabled (null) while filters still exist in the query for UI purposes
|
||||
const hasExistingQuery = useMemo(() => {
|
||||
const queryData = stagedQuery?.builder.queryData?.[activeQueryIndex];
|
||||
const queryData = stagedQueryData?.[activeQueryIndex];
|
||||
const hasV3Items = (queryData?.filters?.items?.length ?? 0) > 0;
|
||||
const hasV5Expression = !!queryData?.filter?.expression;
|
||||
return hasV3Items || hasV5Expression || !!existingQuery;
|
||||
}, [stagedQuery?.builder.queryData, activeQueryIndex, existingQuery]);
|
||||
}, [stagedQueryData, activeQueryIndex, existingQuery]);
|
||||
|
||||
return { existingQuery, hasExistingQuery };
|
||||
}
|
||||
|
||||
@@ -9,6 +9,12 @@ import {
|
||||
import { getMs } from 'utils/timeUtils';
|
||||
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { cloneDeep, isArray, isEqual, isFunction } from 'lodash-es';
|
||||
import {
|
||||
AllTraceFilterKeys,
|
||||
@@ -57,7 +63,8 @@ function Duration({
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
const syncSelectedFilters = useMemo((): FilterType => {
|
||||
const filters =
|
||||
compositeQuery?.builder.queryData?.[activeQueryIndex]?.filters;
|
||||
compositeQuery &&
|
||||
getActiveBuilder(compositeQuery).queryData?.[activeQueryIndex]?.filters;
|
||||
if (!filters) {
|
||||
return {} as FilterType;
|
||||
}
|
||||
@@ -183,49 +190,51 @@ function Duration({
|
||||
};
|
||||
|
||||
const removeFilterItemIds = (query: Query): Query => {
|
||||
const clonedQuery = cloneDeep(query);
|
||||
clonedQuery.builder.queryData = clonedQuery.builder.queryData.map((data) => ({
|
||||
...data,
|
||||
filters: {
|
||||
...data.filters,
|
||||
items:
|
||||
data.filters?.items?.map((item) => ({
|
||||
...item,
|
||||
id: '',
|
||||
})) || [],
|
||||
op: data.filters?.op || 'AND',
|
||||
},
|
||||
}));
|
||||
return clonedQuery;
|
||||
const slotKey = getBuilderSlotKeyForQueryType(query.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(query, slotKey);
|
||||
return replaceBuilderBySlotKey(cloneDeep(query), slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((data) => ({
|
||||
...data,
|
||||
filters: {
|
||||
...data.filters,
|
||||
items:
|
||||
data.filters?.items?.map((item) => ({
|
||||
...item,
|
||||
id: '',
|
||||
})) || [],
|
||||
op: data.filters?.op || 'AND',
|
||||
},
|
||||
})),
|
||||
});
|
||||
};
|
||||
|
||||
const handleRun = useCallback(
|
||||
(props?: HandleRunProps): void => {
|
||||
const preparedQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: props?.resetAll
|
||||
? []
|
||||
: (unionTagFilterItems(item.filters?.items || [], preparePostData())
|
||||
.map((item) =>
|
||||
item.key?.key === props?.clearByType ? undefined : item,
|
||||
)
|
||||
.filter((i) => i) as TagFilterItem[]),
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
|
||||
const preparedQuery: Query = replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: props?.resetAll
|
||||
? []
|
||||
: (unionTagFilterItems(item.filters?.items || [], preparePostData())
|
||||
.map((item) =>
|
||||
item.key?.key === props?.clearByType ? undefined : item,
|
||||
)
|
||||
.filter((i) => i) as TagFilterItem[]),
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
const currentQueryWithoutIds = removeFilterItemIds(currentQuery);
|
||||
const preparedQueryWithoutIds = removeFilterItemIds(preparedQuery);
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { removeKeysFromExpression } from 'components/QueryBuilderV2/utils';
|
||||
import {
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { getKeySpellings, isKeyMatch } from '../Checkbox/utils';
|
||||
@@ -20,34 +25,33 @@ export function clearFilterFromQuery({
|
||||
activeQueryIndex: number;
|
||||
operators?: string[];
|
||||
}): Query {
|
||||
return {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
expression: removeKeysFromExpression(
|
||||
item.filter?.expression ?? '',
|
||||
getKeySpellings(filterKey),
|
||||
false,
|
||||
operators,
|
||||
),
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items:
|
||||
item.filters?.items?.filter(
|
||||
(fil) => !isKeyMatch(fil.key?.key, filterKey),
|
||||
) || [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(currentQuery, slotKey);
|
||||
return replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
expression: removeKeysFromExpression(
|
||||
item.filter?.expression ?? '',
|
||||
getKeySpellings(filterKey),
|
||||
false,
|
||||
operators,
|
||||
),
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items:
|
||||
item.filters?.items?.filter(
|
||||
(fil) => !isKeyMatch(fil.key?.key, filterKey),
|
||||
) || [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -32,6 +32,11 @@ import {
|
||||
QuickFilterReadPermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
|
||||
import { isFunction } from 'lodash-es';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import useActiveQueryIndex from './hooks/useActiveQueryIndex';
|
||||
@@ -87,15 +92,15 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
panelType,
|
||||
} = useQueryBuilder();
|
||||
const [open, setOpen] = useState(false);
|
||||
const activeBuilder = currentQuery
|
||||
? getActiveBuilder(currentQuery)
|
||||
: undefined;
|
||||
|
||||
// Sync lastUsedQuery when queries change (e.g., after deletion)
|
||||
const validQueryIndex = useMemo(
|
||||
() =>
|
||||
Math.min(
|
||||
lastUsedQuery || 0,
|
||||
(currentQuery?.builder?.queryData?.length || 1) - 1,
|
||||
),
|
||||
[lastUsedQuery, currentQuery?.builder?.queryData?.length],
|
||||
Math.min(lastUsedQuery || 0, (activeBuilder?.queryData?.length || 1) - 1),
|
||||
[lastUsedQuery, activeBuilder?.queryData?.length],
|
||||
);
|
||||
|
||||
// Determine if we're in ListView mode
|
||||
@@ -103,15 +108,15 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
|
||||
// Generate query options based on available queries
|
||||
const queryOptions = useMemo(() => {
|
||||
if (!currentQuery?.builder?.queryData) {
|
||||
if (!activeBuilder?.queryData) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return currentQuery.builder.queryData.map((query, index) => ({
|
||||
return activeBuilder.queryData.map((query, index) => ({
|
||||
label: query.queryName || String.fromCharCode(65 + index),
|
||||
value: index,
|
||||
}));
|
||||
}, [currentQuery?.builder?.queryData]);
|
||||
}, [activeBuilder?.queryData]);
|
||||
|
||||
// Show dropdown in ListView only for TRACES_EXPLORER source
|
||||
const shouldShowDropdownInListView =
|
||||
@@ -127,36 +132,34 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
|
||||
// clear all the filters for the query which is in sync with filters
|
||||
const handleReset = (): void => {
|
||||
const activeQuery = currentQuery?.builder.queryData?.[activeQueryIndex];
|
||||
const activeQuery = activeBuilder?.queryData?.[activeQueryIndex];
|
||||
|
||||
if (!activeQuery) {
|
||||
if (!activeBuilder || !activeQuery) {
|
||||
return;
|
||||
}
|
||||
|
||||
const preparedQuery: Query = {
|
||||
...currentQuery,
|
||||
builder: {
|
||||
...currentQuery.builder,
|
||||
queryData: currentQuery.builder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
const slotKey = getBuilderSlotKeyForQueryType(currentQuery.queryType);
|
||||
const preparedQuery: Query = replaceBuilderBySlotKey(currentQuery, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData: activeBuilder.queryData.map((item, idx) => {
|
||||
if (idx !== activeQueryIndex) {
|
||||
return item;
|
||||
}
|
||||
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
...item.filter,
|
||||
expression: '',
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
},
|
||||
};
|
||||
return {
|
||||
...item,
|
||||
filter: {
|
||||
...item.filter,
|
||||
expression: '',
|
||||
},
|
||||
filters: {
|
||||
...item.filters,
|
||||
items: [],
|
||||
op: item.filters?.op || 'AND',
|
||||
},
|
||||
};
|
||||
}),
|
||||
});
|
||||
|
||||
if (onFilterChange && isFunction(onFilterChange)) {
|
||||
onFilterChange(preparedQuery);
|
||||
@@ -166,13 +169,12 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
};
|
||||
|
||||
const lastQueryName =
|
||||
showQueryName &&
|
||||
currentQuery.builder.queryData?.[lastUsedQuery || 0]?.queryName;
|
||||
showQueryName && activeBuilder?.queryData?.[lastUsedQuery || 0]?.queryName;
|
||||
|
||||
// In ListView, always show the 0th query's name; otherwise use the active query's name
|
||||
const displayedQueryName =
|
||||
isListView || isAIObservabilityRowView
|
||||
? showQueryName && currentQuery.builder.queryData?.[0]?.queryName
|
||||
? showQueryName && activeBuilder?.queryData?.[0]?.queryName
|
||||
: lastQueryName;
|
||||
|
||||
const handleQueryChange = (value: number): void => {
|
||||
|
||||
@@ -311,14 +311,10 @@ export const initialQueryMeterWithType: Query = {
|
||||
|
||||
export const initialQueryAIWithType: Query = {
|
||||
...initialQueryWithType,
|
||||
builder: {
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: {
|
||||
...initialQueryWithType.builder,
|
||||
queryData: [
|
||||
{
|
||||
...initialQueryBuilderFormValuesMap.traces,
|
||||
builderQueryType: 'builder_ai_query',
|
||||
},
|
||||
],
|
||||
queryData: [initialQueryBuilderFormValuesMap.traces],
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
@@ -56,6 +56,8 @@
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
gap: 7px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -63,6 +65,7 @@
|
||||
}
|
||||
|
||||
.shortcut {
|
||||
flex-shrink: 0;
|
||||
font-size: 10px;
|
||||
font-family: var(--font-mono, monospace);
|
||||
font-weight: 500;
|
||||
@@ -81,6 +84,7 @@
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
normalizePage,
|
||||
useAIAssistantAnalyticsContext,
|
||||
} from '../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
import { VariantContext } from '../VariantContext';
|
||||
|
||||
@@ -39,6 +41,7 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
const activeConversationId = useAIAssistantStore(
|
||||
(s) => s.activeConversationId,
|
||||
);
|
||||
const chatTitle = useActiveChatTitle();
|
||||
const openModal = useAIAssistantStore((s) => s.openModal);
|
||||
const closeModal = useAIAssistantStore((s) => s.closeModal);
|
||||
const minimizeModal = useAIAssistantStore((s) => s.minimizeModal);
|
||||
@@ -151,7 +154,7 @@ export default function AIAssistantModal(): JSX.Element | null {
|
||||
<div className={styles.header}>
|
||||
<div className={`${styles.title} noz-wave`}>
|
||||
<Noz size={16} />
|
||||
<span>Noz</span>
|
||||
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
|
||||
<kbd className={styles.shortcut}>
|
||||
<span>⌘</span>
|
||||
<span>J</span>
|
||||
|
||||
@@ -1,39 +1,3 @@
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex-shrink: 0;
|
||||
height: 100%;
|
||||
border-left: 1px solid var(--l1-border);
|
||||
background: var(--l1-background);
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.resizeHandle {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 4px;
|
||||
height: 100%;
|
||||
cursor: col-resize;
|
||||
z-index: 10;
|
||||
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 1px;
|
||||
width: 2px;
|
||||
height: 100%;
|
||||
background: transparent;
|
||||
transition: background 0.15s ease;
|
||||
}
|
||||
|
||||
&:hover::after {
|
||||
background: var(--accent-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -47,6 +11,8 @@
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
gap: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
@@ -55,6 +21,7 @@
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { TextEllipsis } from '@signozhq/ui/text-ellipsis';
|
||||
import { matchRoute } from 'lib/router/matchRoute';
|
||||
import { navigate } from 'lib/router/navigation';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
@@ -7,6 +8,9 @@ import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { History, Maximize2, Plus, X } from '@signozhq/icons';
|
||||
import Noz from 'components/Noz/Noz';
|
||||
import { BOTTOM_STRIP_HEIGHT } from 'container/BottomStrip';
|
||||
import { supportChatObstacle } from 'container/BottomStrip/SupportButton/supportChatObstacle';
|
||||
import { FloatingPanel } from 'periscope/components/FloatingPanel';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
@@ -14,13 +18,28 @@ import ConversationsList from '../components/ConversationsList';
|
||||
import ConversationView from '../ConversationView';
|
||||
import { AIAssistantEvents } from '../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
import { VariantContext } from '../VariantContext';
|
||||
|
||||
import styles from './AIAssistantPanel.module.scss';
|
||||
|
||||
const AI_ASSISTANT_PANEL_OPEN_CLASS = 'ai-assistant-panel-open';
|
||||
const AI_ASSISTANT_PANEL_WIDTH_VAR = '--ai-assistant-panel-width';
|
||||
const PANEL_WIDTH = 420;
|
||||
const PANEL_HEIGHT = 601;
|
||||
const PANEL_MIN_WIDTH = 380;
|
||||
const PANEL_MIN_HEIGHT = 500;
|
||||
const PANEL_MARGIN = 8;
|
||||
const PANEL_RESIZE_EDGES = {
|
||||
top: true,
|
||||
right: true,
|
||||
bottom: true,
|
||||
left: true,
|
||||
topRight: false,
|
||||
bottomRight: false,
|
||||
bottomLeft: false,
|
||||
topLeft: false,
|
||||
};
|
||||
const PANEL_AVOID = [supportChatObstacle];
|
||||
|
||||
export default function AIAssistantPanel(): JSX.Element | null {
|
||||
const { pathname } = useAppLocation();
|
||||
@@ -38,6 +57,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
(s) => s.startNewConversation,
|
||||
);
|
||||
const analyticsCtx = useAIAssistantAnalyticsContext();
|
||||
const chatTitle = useActiveChatTitle();
|
||||
|
||||
const handleExpand = useCallback(() => {
|
||||
if (!activeConversationId) {
|
||||
@@ -72,75 +92,36 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
setShowHistory(false);
|
||||
}, []);
|
||||
|
||||
// ── Resize logic ──────────────────────────────────────────────────────────
|
||||
const [panelWidth, setPanelWidth] = useState(380);
|
||||
const dragStartX = useRef(0);
|
||||
const dragStartWidth = useRef(0);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const shouldOffsetChatSupport = isOpen && !isFullScreenPage;
|
||||
|
||||
document.body.classList.toggle(
|
||||
AI_ASSISTANT_PANEL_OPEN_CLASS,
|
||||
shouldOffsetChatSupport,
|
||||
);
|
||||
|
||||
if (shouldOffsetChatSupport) {
|
||||
document.body.style.setProperty(
|
||||
AI_ASSISTANT_PANEL_WIDTH_VAR,
|
||||
`${panelWidth}px`,
|
||||
);
|
||||
} else {
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
}
|
||||
|
||||
return (): void => {
|
||||
document.body.classList.remove(AI_ASSISTANT_PANEL_OPEN_CLASS);
|
||||
document.body.style.removeProperty(AI_ASSISTANT_PANEL_WIDTH_VAR);
|
||||
};
|
||||
}, [isFullScreenPage, isOpen, panelWidth]);
|
||||
|
||||
const handleResizeMouseDown = useCallback(
|
||||
(e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
dragStartX.current = e.clientX;
|
||||
dragStartWidth.current = panelWidth;
|
||||
|
||||
const onMouseMove = (ev: MouseEvent): void => {
|
||||
// Panel is on the right; dragging left (lower clientX) increases width
|
||||
const delta = dragStartX.current - ev.clientX;
|
||||
const next = Math.min(Math.max(dragStartWidth.current + delta, 380), 800);
|
||||
setPanelWidth(next);
|
||||
};
|
||||
|
||||
const onMouseUp = (): void => {
|
||||
document.removeEventListener('mousemove', onMouseMove);
|
||||
document.removeEventListener('mouseup', onMouseUp);
|
||||
document.body.style.cursor = '';
|
||||
document.body.style.userSelect = '';
|
||||
};
|
||||
|
||||
document.body.style.cursor = 'col-resize';
|
||||
document.body.style.userSelect = 'none';
|
||||
document.addEventListener('mousemove', onMouseMove);
|
||||
document.addEventListener('mouseup', onMouseUp);
|
||||
},
|
||||
[panelWidth],
|
||||
);
|
||||
|
||||
if (!isOpen || isFullScreenPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const availableHeight = Math.max(
|
||||
0,
|
||||
window.innerHeight - BOTTOM_STRIP_HEIGHT - 2 * PANEL_MARGIN,
|
||||
);
|
||||
const panelHeight = Math.min(PANEL_HEIGHT, availableHeight);
|
||||
|
||||
return (
|
||||
<VariantContext.Provider value="panel">
|
||||
<div className={styles.panel} style={{ width: panelWidth }}>
|
||||
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
|
||||
<div className={styles.resizeHandle} onMouseDown={handleResizeMouseDown} />
|
||||
<div className={styles.header}>
|
||||
<FloatingPanel
|
||||
isOpen
|
||||
width={PANEL_WIDTH}
|
||||
height={panelHeight}
|
||||
minWidth={PANEL_MIN_WIDTH}
|
||||
minHeight={Math.min(PANEL_MIN_HEIGHT, availableHeight)}
|
||||
enableResizing={PANEL_RESIZE_EDGES}
|
||||
keepInViewport
|
||||
avoid={PANEL_AVOID}
|
||||
defaultPosition={{
|
||||
x: window.innerWidth - PANEL_WIDTH - PANEL_MARGIN,
|
||||
y: PANEL_MARGIN + availableHeight - panelHeight,
|
||||
}}
|
||||
>
|
||||
<div className={`${styles.header} floating-panel__drag-handle`}>
|
||||
<div className={`${styles.title} noz-wave`}>
|
||||
<Noz size={18} />
|
||||
<span>Noz</span>
|
||||
{chatTitle && <TextEllipsis position="end">{chatTitle}</TextEllipsis>}
|
||||
</div>
|
||||
|
||||
<div className={styles.actions}>
|
||||
@@ -191,6 +172,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
size="sm"
|
||||
icon
|
||||
color="secondary"
|
||||
testId="ai-assistant-panel-close"
|
||||
onClick={closeDrawer}
|
||||
aria-label="Close panel"
|
||||
>
|
||||
@@ -207,7 +189,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
|
||||
<ConversationView conversationId={activeConversationId} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</FloatingPanel>
|
||||
</VariantContext.Provider>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,13 +17,17 @@
|
||||
|
||||
.empty {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
// `safe` falls back to the top once the content overflows, so it stays scrollable.
|
||||
justify-content: safe center;
|
||||
padding: 32px 24px;
|
||||
gap: 8px;
|
||||
text-align: center;
|
||||
@include scrollbar;
|
||||
}
|
||||
|
||||
.emptyIcon {
|
||||
@@ -54,6 +58,7 @@
|
||||
}
|
||||
|
||||
.suggestion {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--l2-border);
|
||||
|
||||
@@ -0,0 +1,44 @@
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
import type { Conversation } from '../../types';
|
||||
import { NEW_CHAT_TITLE, useActiveChatTitle } from '../useActiveChatTitle';
|
||||
|
||||
const initialState = useAIAssistantStore.getState();
|
||||
|
||||
const open = (conversation: Conversation): void => {
|
||||
useAIAssistantStore.setState({
|
||||
conversations: { [conversation.id]: conversation },
|
||||
activeConversationId: conversation.id,
|
||||
});
|
||||
};
|
||||
|
||||
describe('useActiveChatTitle', () => {
|
||||
afterEach(() => {
|
||||
useAIAssistantStore.setState(initialState, true);
|
||||
});
|
||||
|
||||
it('is the open chat’s title', () => {
|
||||
open({ id: 'a', title: 'Checkout p99', messages: [], createdAt: 0 });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBe('Checkout p99');
|
||||
});
|
||||
|
||||
it('is "New chat" until the chat has a title', () => {
|
||||
open({ id: 'a', messages: [], createdAt: 0 });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBe(NEW_CHAT_TITLE);
|
||||
});
|
||||
|
||||
it('is empty while a restored chat loads, rather than flashing "New chat"', () => {
|
||||
open({ id: 'a', messages: [], createdAt: 0, isHydrating: true });
|
||||
|
||||
const { result } = renderHook(() => useActiveChatTitle());
|
||||
|
||||
expect(result.current).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { useAIAssistantStore } from '../store/useAIAssistantStore';
|
||||
|
||||
export const NEW_CHAT_TITLE = 'New chat';
|
||||
|
||||
/** The open chat's title for a header: "New chat" until it has one, null while a restored chat loads. */
|
||||
export function useActiveChatTitle(): string | null {
|
||||
return useAIAssistantStore((s) => {
|
||||
const conversation = s.activeConversationId
|
||||
? s.conversations[s.activeConversationId]
|
||||
: undefined;
|
||||
if (conversation?.title) {
|
||||
return conversation.title;
|
||||
}
|
||||
return conversation?.isHydrating ? null : NEW_CHAT_TITLE;
|
||||
});
|
||||
}
|
||||
@@ -13,6 +13,11 @@ import {
|
||||
Query,
|
||||
TagFilterItem,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
getBuilderBySlotKey,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
replaceBuilderBySlotKey,
|
||||
} from 'lib/query/builderSlot';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
|
||||
/** Param shape emitted by the AI for every filter-touching action. */
|
||||
@@ -56,12 +61,14 @@ export function replaceFirstQueryData(
|
||||
query: Query,
|
||||
updated: IBuilderQuery,
|
||||
): Query {
|
||||
const queryData = [...query.builder.queryData];
|
||||
const slotKey = getBuilderSlotKeyForQueryType(query.queryType);
|
||||
const activeBuilder = getBuilderBySlotKey(query, slotKey);
|
||||
const queryData = [...activeBuilder.queryData];
|
||||
queryData[0] = updated;
|
||||
return {
|
||||
...query,
|
||||
builder: { ...query.builder, queryData },
|
||||
};
|
||||
return replaceBuilderBySlotKey(query, slotKey, {
|
||||
...activeBuilder,
|
||||
queryData,
|
||||
});
|
||||
}
|
||||
|
||||
/** Page-state deps required by the runQuery / addFilter actions. */
|
||||
|
||||
@@ -23,7 +23,8 @@ import styles from './AskNoz.module.scss';
|
||||
|
||||
/**
|
||||
* Opens the Noz drawer, matching the header entry it replaces. Cmd+K opens the
|
||||
* modal instead; this is deliberately the drawer.
|
||||
* modal instead; this is deliberately the drawer. It stays while the drawer is
|
||||
* open, where it closes the drawer and keeps the chat for the next open.
|
||||
*
|
||||
* Carries the header's pending badge: when Noz is blocked on the user
|
||||
* (`awaiting_approval` / `awaiting_clarification`) a dot pulses. Without it,
|
||||
@@ -38,21 +39,28 @@ function AskNoz(): JSX.Element | null {
|
||||
selectPendingUserInputStreamCount,
|
||||
);
|
||||
|
||||
// Noz is already on screen in the modal, so the "needs you" dot would be noise.
|
||||
const showPendingBadge = pendingUserInputCount > 0 && !isModalOpen;
|
||||
const closeDrawer = useAIAssistantStore((state) => state.closeDrawer);
|
||||
|
||||
// Noz is already on screen in the drawer or modal, so the "needs you" dot would be noise.
|
||||
const showPendingBadge =
|
||||
pendingUserInputCount > 0 && !isDrawerOpen && !isModalOpen;
|
||||
|
||||
// The drawer does not render on the Noz full page, so the button would be inert.
|
||||
const isAIAssistantPage = pathname.startsWith(ROUTES.AI_ASSISTANT_BASE);
|
||||
|
||||
const handleOpen = useCallback((): void => {
|
||||
const handleClick = useCallback((): void => {
|
||||
if (isDrawerOpen) {
|
||||
closeDrawer();
|
||||
return;
|
||||
}
|
||||
void logEvent(AIAssistantEvents.Opened, {
|
||||
source: AIAssistantOpenSource.BottomStrip,
|
||||
currentPage: normalizePage(pathname),
|
||||
});
|
||||
openAIAssistant();
|
||||
}, [pathname]);
|
||||
}, [closeDrawer, isDrawerOpen, pathname]);
|
||||
|
||||
if (!isAIAssistantEnabled || isDrawerOpen || isAIAssistantPage) {
|
||||
if (!isAIAssistantEnabled || isAIAssistantPage) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -72,7 +80,9 @@ function AskNoz(): JSX.Element | null {
|
||||
color="secondary"
|
||||
size="sm"
|
||||
prefix={<Noz size={16} />}
|
||||
onClick={handleOpen}
|
||||
testId="bottom-strip-ask-noz-button"
|
||||
onClick={handleClick}
|
||||
aria-pressed={isDrawerOpen}
|
||||
aria-label={
|
||||
showPendingBadge
|
||||
? `Ask Noz, ${pendingUserInputCount} ${
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { fireEvent } from '@testing-library/react';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import {
|
||||
AIAssistantEvents,
|
||||
@@ -6,15 +5,11 @@ import {
|
||||
} from 'container/AIAssistant/events';
|
||||
import { openAIAssistant } from 'container/AIAssistant/store/useAIAssistantStore';
|
||||
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { render, userEvent } from 'tests/test-utils';
|
||||
|
||||
import AskNoz from '../AskNoz';
|
||||
|
||||
jest.mock('hooks/useIsAIAssistantEnabled');
|
||||
jest.mock('api/common/logEvent', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(),
|
||||
}));
|
||||
jest.mock('container/AIAssistant/store/useAIAssistantStore', () => ({
|
||||
openAIAssistant: jest.fn(),
|
||||
useAIAssistantStore: jest.fn(),
|
||||
@@ -24,6 +19,7 @@ const mockEnabled = useIsAIAssistantEnabled as jest.MockedFunction<
|
||||
typeof useIsAIAssistantEnabled
|
||||
>;
|
||||
const mockOpen = openAIAssistant as jest.MockedFunction<typeof openAIAssistant>;
|
||||
const mockClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const { useAIAssistantStore } = jest.requireMock(
|
||||
@@ -40,7 +36,12 @@ function mockStore({
|
||||
isModalOpen?: boolean;
|
||||
pendingCount?: number;
|
||||
} = {}): void {
|
||||
const state = { isDrawerOpen, isModalOpen, streams: {} };
|
||||
const state = {
|
||||
isDrawerOpen,
|
||||
isModalOpen,
|
||||
streams: {},
|
||||
closeDrawer: mockClose,
|
||||
};
|
||||
useAIAssistantStore.mockImplementation((selector: (s: unknown) => unknown) => {
|
||||
const picked = selector(state);
|
||||
// `selectPendingUserInputStreamCount` walks `streams`, which is empty here,
|
||||
@@ -49,9 +50,8 @@ function mockStore({
|
||||
});
|
||||
}
|
||||
|
||||
// `TooltipSimple` replaces its trigger's props, so the testId lives on the
|
||||
// wrapper and the button itself is reached by role — there is only ever one.
|
||||
const SLOT = 'bottom-strip-ask-noz';
|
||||
const BUTTON = 'bottom-strip-ask-noz-button';
|
||||
|
||||
describe('AskNoz', () => {
|
||||
beforeEach(() => {
|
||||
@@ -62,9 +62,9 @@ describe('AskNoz', () => {
|
||||
|
||||
describe('visibility', () => {
|
||||
it('renders when the assistant is enabled', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toBeInTheDocument();
|
||||
expect(getByTestId(BUTTON)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing when the assistant is disabled', () => {
|
||||
@@ -75,12 +75,12 @@ describe('AskNoz', () => {
|
||||
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing while the drawer is open', () => {
|
||||
it('stays pressed while the drawer is open', () => {
|
||||
mockStore({ isDrawerOpen: true });
|
||||
|
||||
const { queryByTestId } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-pressed', 'true');
|
||||
});
|
||||
|
||||
it('renders nothing on the Noz full page, where the drawer does not mount', () => {
|
||||
@@ -93,18 +93,32 @@ describe('AskNoz', () => {
|
||||
});
|
||||
|
||||
describe('what it does', () => {
|
||||
it('opens the drawer on click', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
it('opens the drawer on click', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
fireEvent.click(getByRole('button'));
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(mockOpen).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports the open as coming from the strip', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
it('closes the open drawer on the same chat instead of starting a new one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
mockStore({ isDrawerOpen: true });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
fireEvent.click(getByRole('button'));
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(mockClose).toHaveBeenCalledTimes(1);
|
||||
expect(mockOpen).not.toHaveBeenCalled();
|
||||
expect(logEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the open as coming from the strip', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
await user.click(getByTestId(BUTTON));
|
||||
|
||||
expect(logEvent).toHaveBeenCalledWith(
|
||||
AIAssistantEvents.Opened,
|
||||
@@ -117,9 +131,9 @@ describe('AskNoz', () => {
|
||||
it('announces the count when Noz is waiting on the user', () => {
|
||||
mockStore({ pendingCount: 2 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute(
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute(
|
||||
'aria-label',
|
||||
'Ask Noz, 2 actions need your response',
|
||||
);
|
||||
@@ -128,26 +142,34 @@ describe('AskNoz', () => {
|
||||
it('uses the singular for one pending action', () => {
|
||||
mockStore({ pendingCount: 1 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute(
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute(
|
||||
'aria-label',
|
||||
'Ask Noz, 1 action needs your response',
|
||||
);
|
||||
});
|
||||
|
||||
it('stays quiet when nothing is pending', () => {
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
|
||||
it('stays quiet while the drawer is open, Noz is already on screen', () => {
|
||||
mockStore({ isDrawerOpen: true, pendingCount: 3 });
|
||||
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
|
||||
it('stays quiet while the modal is open, Noz is already on screen', () => {
|
||||
mockStore({ isModalOpen: true, pendingCount: 3 });
|
||||
|
||||
const { getByRole } = render(<AskNoz />);
|
||||
const { getByTestId } = render(<AskNoz />);
|
||||
|
||||
expect(getByRole('button')).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import type { FloatingRect } from 'periscope/components/FloatingPanel/types';
|
||||
|
||||
import { supportChatObstacle } from '../supportChatObstacle';
|
||||
|
||||
type Pylon = Window['Pylon'];
|
||||
|
||||
const SUPPORT_CHAT: FloatingRect = { x: 882, y: 286, width: 384, height: 478 };
|
||||
const CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
|
||||
|
||||
const originalPylon = window.Pylon;
|
||||
const pylonCallbacks = new Map<string, unknown>();
|
||||
const unsubscribes: (() => void)[] = [];
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
const unsubscribe = supportChatObstacle.subscribe(onChange);
|
||||
unsubscribes.push(unsubscribe);
|
||||
return unsubscribe;
|
||||
}
|
||||
|
||||
function installPylon(): jest.MockedFunction<Pylon> {
|
||||
const pylon = jest.fn<ReturnType<Pylon>, Parameters<Pylon>>(
|
||||
(command, callback) => {
|
||||
pylonCallbacks.set(command, callback);
|
||||
},
|
||||
);
|
||||
window.Pylon = pylon;
|
||||
return pylon;
|
||||
}
|
||||
|
||||
function firePylon(event: 'onShow' | 'onHide'): void {
|
||||
const callback = pylonCallbacks.get(event);
|
||||
if (typeof callback === 'function') {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
|
||||
function renderSupportChat(): HTMLElement {
|
||||
const element = document.createElement('div');
|
||||
element.className = 'PylonChat-chatWindowFrameContainer';
|
||||
Object.defineProperties(element, {
|
||||
offsetLeft: { value: SUPPORT_CHAT.x },
|
||||
offsetTop: { value: SUPPORT_CHAT.y },
|
||||
offsetWidth: { value: SUPPORT_CHAT.width },
|
||||
offsetHeight: { value: SUPPORT_CHAT.height },
|
||||
});
|
||||
document.body.appendChild(element);
|
||||
return element;
|
||||
}
|
||||
|
||||
describe('supportChatObstacle', () => {
|
||||
beforeEach(() => pylonCallbacks.clear());
|
||||
|
||||
afterEach(() => {
|
||||
unsubscribes.splice(0).forEach((unsubscribe) => unsubscribe());
|
||||
window.Pylon = originalPylon;
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('reports the chat window box only while it is open', () => {
|
||||
const chat = renderSupportChat();
|
||||
|
||||
expect(supportChatObstacle.getRect()).toStrictEqual(SUPPORT_CHAT);
|
||||
|
||||
chat.classList.add(CLOSED_CLASS);
|
||||
|
||||
expect(supportChatObstacle.getRect()).toBeNull();
|
||||
});
|
||||
|
||||
it('treats the chat as closed once Pylon reports it hidden', () => {
|
||||
installPylon();
|
||||
renderSupportChat();
|
||||
subscribe(jest.fn());
|
||||
|
||||
firePylon('onHide');
|
||||
|
||||
expect(supportChatObstacle.getRect()).toBeNull();
|
||||
});
|
||||
|
||||
it('notifies every subscriber through one Pylon registration', () => {
|
||||
const pylon = installPylon();
|
||||
const first = jest.fn() as jest.MockedFunction<() => void>;
|
||||
const second = jest.fn() as jest.MockedFunction<() => void>;
|
||||
subscribe(first);
|
||||
subscribe(second);
|
||||
|
||||
firePylon('onShow');
|
||||
|
||||
expect(pylon.mock.calls.map(([command]) => command)).toStrictEqual([
|
||||
'onShow',
|
||||
'onHide',
|
||||
]);
|
||||
expect(first).toHaveBeenCalledTimes(1);
|
||||
expect(second).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('unregisters through the loaded widget, not the stub it registered with', () => {
|
||||
const stub = installPylon();
|
||||
const unsubscribe = subscribe(jest.fn());
|
||||
// Pylon's script swaps out the queueing stub, which then can no longer be called.
|
||||
const widget = installPylon();
|
||||
|
||||
unsubscribe();
|
||||
|
||||
expect(stub.mock.calls.map(([command]) => command)).toStrictEqual([
|
||||
'onShow',
|
||||
'onHide',
|
||||
]);
|
||||
expect(widget.mock.calls).toStrictEqual([
|
||||
['onShow', null],
|
||||
['onHide', null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,64 @@
|
||||
import type {
|
||||
FloatingObstacle,
|
||||
FloatingRect,
|
||||
} from 'periscope/components/FloatingPanel/types';
|
||||
|
||||
// Pylon's own class names, which styles.scss also targets.
|
||||
const SUPPORT_CHAT_SELECTOR = '.PylonChat-chatWindowFrameContainer';
|
||||
const SUPPORT_CHAT_CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
|
||||
|
||||
const listeners = new Set<() => void>();
|
||||
// Pylon's last show/hide while subscribed; undefined until one arrives.
|
||||
let isOpen: boolean | undefined;
|
||||
|
||||
function setOpen(open: boolean): void {
|
||||
isOpen = open;
|
||||
listeners.forEach((listener) => listener());
|
||||
}
|
||||
|
||||
const onShow = (): void => setOpen(true);
|
||||
const onHide = (): void => setOpen(false);
|
||||
|
||||
// Offsets ignore the scale animation Pylon opens with, so this is the settled box.
|
||||
function getSupportChatRect(): FloatingRect | null {
|
||||
const element = document.querySelector<HTMLElement>(SUPPORT_CHAT_SELECTOR);
|
||||
if (!element) {
|
||||
return null;
|
||||
}
|
||||
// Pylon's event decides; the class covers a chat opened before anyone subscribed.
|
||||
if (!(isOpen ?? !element.classList.contains(SUPPORT_CHAT_CLOSED_CLASS))) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
x: element.offsetLeft,
|
||||
y: element.offsetTop,
|
||||
width: element.offsetWidth,
|
||||
height: element.offsetHeight,
|
||||
};
|
||||
}
|
||||
|
||||
function subscribeToSupportChat(onChange: () => void): () => void {
|
||||
if (!window.Pylon) {
|
||||
return (): void => undefined;
|
||||
}
|
||||
listeners.add(onChange);
|
||||
// Pylon keeps a single callback per event, so all listeners share one registration.
|
||||
if (listeners.size === 1) {
|
||||
window.Pylon('onShow', onShow);
|
||||
window.Pylon('onHide', onHide);
|
||||
}
|
||||
return (): void => {
|
||||
listeners.delete(onChange);
|
||||
if (listeners.size === 0) {
|
||||
isOpen = undefined;
|
||||
// Read `window.Pylon` again: once loaded, the widget replaces the stub, which then throws.
|
||||
window.Pylon?.('onShow', null);
|
||||
window.Pylon?.('onHide', null);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const supportChatObstacle: FloatingObstacle = {
|
||||
getRect: getSupportChatRect,
|
||||
subscribe: subscribeToSupportChat,
|
||||
};
|
||||
@@ -40,6 +40,7 @@ export function getQueryNames(currentQuery: Query): BaseOptionType[] {
|
||||
[EQueryType.PROM]: () => getSelectedQueryOptions(currentQuery.promql),
|
||||
[EQueryType.CLICKHOUSE]: () =>
|
||||
getSelectedQueryOptions(currentQuery.clickhouse_sql),
|
||||
[EQueryType.AI_QUERY_BUILDER]: () => [],
|
||||
};
|
||||
|
||||
return queryConfig[currentQuery.queryType]?.() || [];
|
||||
|
||||
@@ -8,7 +8,8 @@
|
||||
background-color: var(--l1-background);
|
||||
border-top: 1px solid var(--l1-border);
|
||||
padding: 12px;
|
||||
z-index: 1000;
|
||||
// Below FloatingPanel (999), so the Noz panel stacks over the footer.
|
||||
z-index: 998;
|
||||
box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
@@ -31,7 +32,3 @@
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
body.ai-assistant-panel-open .create-alert-v2-footer {
|
||||
right: var(--ai-assistant-panel-width, 380px);
|
||||
}
|
||||
|
||||
@@ -160,11 +160,14 @@ describe('jira reopen duration', () => {
|
||||
).toMatchObject({ reopenDuration: sent });
|
||||
});
|
||||
|
||||
it('leaves a duration it cannot parse for the validator to reject', () => {
|
||||
expect(
|
||||
toChannelConfig(ChannelKind.jira, { reopenDuration: 'tomorrow' }).spec,
|
||||
).toMatchObject({ reopenDuration: 'tomorrow' });
|
||||
});
|
||||
it.each(['tomorrow', '30m1h'])(
|
||||
'leaves %s, which it cannot parse, for the validator to reject',
|
||||
(typed) => {
|
||||
expect(
|
||||
toChannelConfig(ChannelKind.jira, { reopenDuration: typed }).spec,
|
||||
).toMatchObject({ reopenDuration: typed });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('jira deployment', () => {
|
||||
|
||||
@@ -1,31 +1,18 @@
|
||||
import {
|
||||
PROMETHEUS_DURATION_UNIT_MS,
|
||||
prometheusDurationToMs,
|
||||
} from 'utils/prometheusDuration';
|
||||
|
||||
import { ChannelFormValues, WebhookAuth } from './types';
|
||||
|
||||
// mirrors go's prometheus model.Duration units
|
||||
const JIRA_DURATION_UNIT_MS: Record<string, number> = {
|
||||
ms: 1,
|
||||
s: 1_000,
|
||||
m: 60_000,
|
||||
h: 3_600_000,
|
||||
d: 86_400_000,
|
||||
w: 604_800_000,
|
||||
y: 31_536_000_000,
|
||||
};
|
||||
const JIRA_DURATION_RE = /^(\d+(ms|s|m|h|d|w|y))+$/;
|
||||
const JIRA_DURATION_TOKEN_RE = /(\d+)(ms|s|m|h|d|w|y)/g;
|
||||
const JIRA_MIN_REOPEN_MS = 60_000;
|
||||
|
||||
export const isValidJiraReopenDuration = (value: string): boolean => {
|
||||
if (!value || value === '0') {
|
||||
return true;
|
||||
}
|
||||
if (!JIRA_DURATION_RE.test(value)) {
|
||||
return false;
|
||||
}
|
||||
let totalMs = 0;
|
||||
for (const [, amount, unit] of value.matchAll(JIRA_DURATION_TOKEN_RE)) {
|
||||
totalMs += Number(amount) * JIRA_DURATION_UNIT_MS[unit];
|
||||
}
|
||||
return totalMs >= JIRA_MIN_REOPEN_MS;
|
||||
const totalMs = prometheusDurationToMs(value);
|
||||
return totalMs !== null && totalMs >= JIRA_MIN_REOPEN_MS;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -33,25 +20,23 @@ export const isValidJiraReopenDuration = (value: string): boolean => {
|
||||
* back: "72h" becomes "3d", "7d" becomes "1w".
|
||||
*/
|
||||
const JIRA_DURATION_FORMAT: { unit: string; ms: number; exact: boolean }[] = [
|
||||
{ unit: 'y', ms: JIRA_DURATION_UNIT_MS.y, exact: true },
|
||||
{ unit: 'w', ms: JIRA_DURATION_UNIT_MS.w, exact: true },
|
||||
{ unit: 'd', ms: JIRA_DURATION_UNIT_MS.d, exact: false },
|
||||
{ unit: 'h', ms: JIRA_DURATION_UNIT_MS.h, exact: false },
|
||||
{ unit: 'm', ms: JIRA_DURATION_UNIT_MS.m, exact: false },
|
||||
{ unit: 's', ms: JIRA_DURATION_UNIT_MS.s, exact: false },
|
||||
{ unit: 'ms', ms: JIRA_DURATION_UNIT_MS.ms, exact: false },
|
||||
{ unit: 'y', ms: PROMETHEUS_DURATION_UNIT_MS.y, exact: true },
|
||||
{ unit: 'w', ms: PROMETHEUS_DURATION_UNIT_MS.w, exact: true },
|
||||
{ unit: 'd', ms: PROMETHEUS_DURATION_UNIT_MS.d, exact: false },
|
||||
{ unit: 'h', ms: PROMETHEUS_DURATION_UNIT_MS.h, exact: false },
|
||||
{ unit: 'm', ms: PROMETHEUS_DURATION_UNIT_MS.m, exact: false },
|
||||
{ unit: 's', ms: PROMETHEUS_DURATION_UNIT_MS.s, exact: false },
|
||||
{ unit: 'ms', ms: PROMETHEUS_DURATION_UNIT_MS.ms, exact: false },
|
||||
];
|
||||
|
||||
/** The API rejects a duration it would print differently. */
|
||||
export const canonicalJiraReopenDuration = (value: string): string => {
|
||||
if (!value || value === '0' || !JIRA_DURATION_RE.test(value)) {
|
||||
const totalMs = value && value !== '0' ? prometheusDurationToMs(value) : null;
|
||||
if (totalMs === null) {
|
||||
return value;
|
||||
}
|
||||
|
||||
let remaining = 0;
|
||||
for (const [, amount, unit] of value.matchAll(JIRA_DURATION_TOKEN_RE)) {
|
||||
remaining += Number(amount) * JIRA_DURATION_UNIT_MS[unit];
|
||||
}
|
||||
let remaining = totalMs;
|
||||
if (remaining === 0) {
|
||||
return '0s';
|
||||
}
|
||||
|
||||
@@ -30,19 +30,6 @@ jest.mock('@signozhq/ui/sonner', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
|
||||
// popover ancestor costs ~1 s per open here, enough to time out under load.
|
||||
jest.mock('@floating-ui/dom', () => ({
|
||||
...jest.requireActual('@floating-ui/dom'),
|
||||
autoUpdate: (): (() => void) => (): void => {},
|
||||
computePosition: (
|
||||
_reference: unknown,
|
||||
_floating: unknown,
|
||||
{ placement = 'bottom', strategy = 'absolute' } = {},
|
||||
): Promise<unknown> =>
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
type AccountSettingsDrawerProps = ComponentProps<typeof AccountSettingsDrawer>;
|
||||
|
||||
const onClose = jest.fn() as jest.MockedFunction<
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
useHandleExplorerTabChange,
|
||||
} from 'hooks/useHandleExplorerTabChange';
|
||||
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { isEmpty } from 'lodash-es';
|
||||
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
|
||||
import { ExplorerViews } from 'pages/LogsExplorer/utils';
|
||||
@@ -186,7 +187,9 @@ function Explorer(): JSX.Element {
|
||||
|
||||
const isFilterApplied = useMemo(() => {
|
||||
// if any of the non-disabled queries has filters applied, return true
|
||||
const result = stagedQuery?.builder?.queryData?.filter(
|
||||
const result = (
|
||||
stagedQuery ? getActiveBuilder(stagedQuery) : undefined
|
||||
)?.queryData?.filter(
|
||||
(item) => !isEmpty(item.filters?.items) && !item.disabled,
|
||||
);
|
||||
return !!result?.length;
|
||||
|
||||
@@ -15,6 +15,7 @@ import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
|
||||
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import useUrlYAxisUnit from 'hooks/useUrlYAxisUnit';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { Warning } from 'types/api';
|
||||
import APIError from 'types/api/error';
|
||||
@@ -35,7 +36,7 @@ function TimeSeriesViewContainer({
|
||||
const isValidToConvertToMs = useMemo(() => {
|
||||
const isValid: boolean[] = [];
|
||||
|
||||
currentQuery.builder.queryData.forEach(
|
||||
getActiveBuilder(currentQuery).queryData.forEach(
|
||||
({ aggregateAttribute, aggregateOperator }) => {
|
||||
const isExistDurationNanoAttribute =
|
||||
aggregateAttribute?.key === 'durationNano' ||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
FilterDeps,
|
||||
replaceFirstQueryData,
|
||||
} from 'container/AIAssistant/pageActions/builderQueryHelpers';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import {
|
||||
ActionResult,
|
||||
PageAction,
|
||||
@@ -93,7 +94,7 @@ export function tracesRunQueryAction(
|
||||
},
|
||||
autoApply: true,
|
||||
execute: async ({ filters }): Promise<ActionResult> => {
|
||||
const baseQuery = deps.currentQuery.builder.queryData[0];
|
||||
const baseQuery = getActiveBuilder(deps.currentQuery).queryData[0];
|
||||
if (!baseQuery) {
|
||||
throw new Error('No active query found in Traces Explorer.');
|
||||
}
|
||||
@@ -117,7 +118,7 @@ export function tracesRunQueryAction(
|
||||
},
|
||||
getContext: (): Record<string, unknown> => ({
|
||||
filters:
|
||||
deps.currentQuery.builder.queryData[0]?.filters?.items?.map(
|
||||
getActiveBuilder(deps.currentQuery).queryData[0]?.filters?.items?.map(
|
||||
(f: TagFilterItem) => ({
|
||||
key: f.key?.key,
|
||||
op: f.op,
|
||||
@@ -158,7 +159,7 @@ export function tracesAddFilterAction(
|
||||
},
|
||||
autoApply: true,
|
||||
execute: async ({ key, op, value }): Promise<ActionResult> => {
|
||||
const baseQuery = deps.currentQuery.builder.queryData[0];
|
||||
const baseQuery = getActiveBuilder(deps.currentQuery).queryData[0];
|
||||
if (!baseQuery) {
|
||||
throw new Error('No active query found in Traces Explorer.');
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
import { OrderByPayload, Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { parseListOrderBy } from 'utils/explorerUtils';
|
||||
@@ -15,8 +16,9 @@ export const getListViewQuery = (
|
||||
? [parseListOrderBy(orderBy)]
|
||||
: [];
|
||||
|
||||
for (let i = 0; i < query.builder.queryData.length; i++) {
|
||||
const queryData = query.builder.queryData[i];
|
||||
const { queryData: builderQueries } = getActiveBuilder(query);
|
||||
for (let i = 0; i < builderQueries.length; i++) {
|
||||
const queryData = builderQueries[i];
|
||||
queryData.groupBy = [];
|
||||
queryData.having = {
|
||||
expression: '',
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
.alertListContainer {
|
||||
margin-top: auto;
|
||||
margin-bottom: auto;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.alertListViewContent {
|
||||
margin: auto;
|
||||
padding: 24px 0;
|
||||
width: calc(100% - 30px);
|
||||
max-width: 836px;
|
||||
}
|
||||
|
||||
@@ -18,19 +18,6 @@ import {
|
||||
|
||||
import { renderListAlertRules, runSearchQuery } from './_helpers';
|
||||
|
||||
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
|
||||
// popover ancestor costs ~1 s per open here, enough to time out under load.
|
||||
jest.mock('@floating-ui/dom', () => ({
|
||||
...jest.requireActual('@floating-ui/dom'),
|
||||
autoUpdate: (): (() => void) => (): void => {},
|
||||
computePosition: (
|
||||
_reference: unknown,
|
||||
_floating: unknown,
|
||||
{ placement = 'bottom', strategy = 'absolute' } = {},
|
||||
): Promise<unknown> =>
|
||||
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
|
||||
}));
|
||||
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
const VIEW_1_ORDER_BY = JSON.stringify({ columnName: 'name', order: 'asc' });
|
||||
|
||||
@@ -29,6 +29,7 @@ import { getMetricNameForQuery } from '../utils';
|
||||
import OptionRenderer from '../OptionRenderer/OptionRenderer';
|
||||
import { GroupByFilterProps } from './GroupByFilter.interfaces';
|
||||
import { toAttributeKey } from './utils';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
|
||||
export const GroupByFilter = memo(function GroupByFilter({
|
||||
query,
|
||||
@@ -45,6 +46,7 @@ export const GroupByFilter = memo(function GroupByFilter({
|
||||
|
||||
const debouncedValue = useDebounce(searchText, DEBOUNCE_DELAY);
|
||||
|
||||
const builderQueryType = useBuilderQueryType(query);
|
||||
const { data: fieldKeys, isFetching } = useFieldKeysSuggestion(
|
||||
{
|
||||
signal: DATA_SOURCE_TO_SIGNAL[query.dataSource],
|
||||
@@ -52,7 +54,7 @@ export const GroupByFilter = memo(function GroupByFilter({
|
||||
metricName: getMetricNameForQuery(query),
|
||||
searchText: debouncedValue,
|
||||
},
|
||||
query.builderQueryType,
|
||||
builderQueryType,
|
||||
{ enabled: !disabled && isFocused, keepPreviousData: true },
|
||||
);
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import { selectStyle } from '../QueryBuilderSearchV2/config';
|
||||
import { getMetricNameForQuery } from '../utils';
|
||||
import { OrderByFilterProps } from './OrderByFilter.interfaces';
|
||||
import { useOrderByFilter } from './useOrderByFilter';
|
||||
import { useBuilderQueryType } from 'hooks/queryBuilder/useBuilderQueryType';
|
||||
|
||||
export function OrderByFilter({
|
||||
query,
|
||||
@@ -34,6 +35,7 @@ export function OrderByFilter({
|
||||
handleSearchKeys,
|
||||
} = useOrderByFilter({ query, onChange, entityVersion });
|
||||
|
||||
const builderQueryType = useBuilderQueryType(query);
|
||||
const { data: fieldKeys, isFetching } = useFieldKeysSuggestion(
|
||||
{
|
||||
signal: DATA_SOURCE_TO_SIGNAL[query.dataSource],
|
||||
@@ -41,7 +43,7 @@ export function OrderByFilter({
|
||||
metricName: getMetricNameForQuery(query),
|
||||
searchText: debouncedSearchText,
|
||||
},
|
||||
query.builderQueryType,
|
||||
builderQueryType,
|
||||
{
|
||||
enabled: !!query.aggregateAttribute?.key || isRawQuery,
|
||||
keepPreviousData: true,
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
useState,
|
||||
} from 'react';
|
||||
import { type RefSelectProps, Select, Spin } from 'antd';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { Pill } from '@signozhq/ui/pill';
|
||||
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import cx from 'classnames';
|
||||
@@ -820,14 +821,10 @@ function QueryBuilderSearchV2(
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [query]);
|
||||
|
||||
const isLastQuery = useMemo(
|
||||
() =>
|
||||
isEqual(
|
||||
currentQuery.builder.queryData[currentQuery.builder.queryData.length - 1],
|
||||
query,
|
||||
),
|
||||
[currentQuery, query],
|
||||
);
|
||||
const isLastQuery = useMemo(() => {
|
||||
const { queryData } = getActiveBuilder(currentQuery);
|
||||
return isEqual(queryData[queryData.length - 1], query);
|
||||
}, [currentQuery, query]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLastQuery) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useMemo } from 'react';
|
||||
import { UseQueryResult } from 'react-query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import { isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { ContextLinksData } from 'types/api/widgets/widget';
|
||||
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -41,7 +42,7 @@ export function useGraphContextMenu({
|
||||
} {
|
||||
const drilldownQuery = useGetCompositeQueryParam() || query;
|
||||
|
||||
const isQueryTypeBuilder = drilldownQuery?.queryType === 'builder';
|
||||
const isQueryTypeBuilder = isBuilderQueryType(drilldownQuery.queryType);
|
||||
|
||||
const { aggregateDrilldownConfig } = useAggregateDrilldown({
|
||||
query: drilldownQuery,
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useAppParams } from 'lib/router/useAppParams';
|
||||
import cx from 'classnames';
|
||||
import { ResizeTable } from 'components/ResizeTable';
|
||||
import Download from 'container/Download/Download';
|
||||
import { isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import {
|
||||
createTableColumnsFromQuery,
|
||||
RowData,
|
||||
@@ -33,7 +34,7 @@ export function QueryTable({
|
||||
...props
|
||||
}: QueryTableProps): JSX.Element {
|
||||
const { isDownloadEnabled = false, fileName = '' } = downloadOption || {};
|
||||
const isQueryTypeBuilder = query.queryType === 'builder';
|
||||
const isQueryTypeBuilder = isBuilderQueryType(query.queryType);
|
||||
|
||||
const { servicename: encodedServiceName } = useAppParams<'servicename'>();
|
||||
const servicename = decodeURIComponent(encodedServiceName || '');
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import WidgetHeader from 'container/WidgetCard/Header';
|
||||
import { mockAppLocation } from 'tests/router-mocks';
|
||||
import { fireEvent, render } from 'tests/test-utils';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { QueryTable } from '../QueryTable';
|
||||
import { QueryTableProps, WidgetHeaderProps } from './mocks';
|
||||
@@ -29,6 +30,21 @@ describe('QueryTable -', () => {
|
||||
const tableRows = container.querySelectorAll('tr.ant-table-row');
|
||||
expect(tableRows).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('should enable drilldown cells for AI query builder queries', () => {
|
||||
const { container } = render(
|
||||
<QueryTable
|
||||
{...QueryTableProps}
|
||||
query={{
|
||||
...QueryTableProps.query,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: QueryTableProps.query.builder,
|
||||
}}
|
||||
enableDrillDown
|
||||
/>,
|
||||
);
|
||||
expect(container.querySelector('.clickable-cell')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
const setSearchTerm = jest.fn();
|
||||
|
||||
@@ -14,12 +14,12 @@ import { useNotifications } from 'hooks/useNotifications';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import createQueryParams from 'lib/createQueryParams';
|
||||
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import {
|
||||
getCustomTimeRangeWindowSweepInMS,
|
||||
getStartAndEndTimesInMilliseconds,
|
||||
} from 'pages/MessagingQueues/MessagingQueuesUtils';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { useGraphClickToShowButton } from 'container/WidgetCard/hooks/useGraphClickToShowButton';
|
||||
@@ -132,13 +132,13 @@ function WidgetGraphComponent({
|
||||
|
||||
const [searchTerm, setSearchTerm] = useState<string>('');
|
||||
|
||||
const widgetQueryData = widget?.query
|
||||
? getActiveBuilder(widget.query)?.queryData
|
||||
: undefined;
|
||||
|
||||
const graphClick = useGraphClickToShowButton({
|
||||
graphRef: currentGraphRef?.current ? currentGraphRef : graphRef,
|
||||
isButtonEnabled: (widget?.query?.builder?.queryData &&
|
||||
Array.isArray(widget.query.builder.queryData)
|
||||
? widget.query.builder.queryData
|
||||
: []
|
||||
).some(
|
||||
isButtonEnabled: (Array.isArray(widgetQueryData) ? widgetQueryData : []).some(
|
||||
(q) =>
|
||||
q.dataSource === DataSource.TRACES || q.dataSource === DataSource.LOGS,
|
||||
),
|
||||
@@ -219,7 +219,7 @@ function WidgetGraphComponent({
|
||||
customOnDragSelect={customOnDragSelect}
|
||||
setCurrentGraphRef={setCurrentGraphRef}
|
||||
enableDrillDown={
|
||||
enableDrillDown && widget?.query?.queryType === EQueryType.QUERY_BUILDER
|
||||
enableDrillDown && isBuilderQueryType(widget.query.queryType)
|
||||
}
|
||||
/>
|
||||
</Modal>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import {
|
||||
createColumnsAndDataSource,
|
||||
@@ -47,6 +48,18 @@ describe('Table Panel utils', () => {
|
||||
expect(getQueryLegend(query, 'B')).toBeUndefined();
|
||||
});
|
||||
|
||||
it('getQueryLegend reads the AI builder slot', () => {
|
||||
const builderQuery = widgetQueryWithLegend as Query;
|
||||
const query: Query = {
|
||||
...builderQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: { queryData: [], queryFormulas: [], queryTraceOperator: [] },
|
||||
builder_ai_query: builderQuery.builder,
|
||||
};
|
||||
|
||||
expect(getQueryLegend(query, 'A')).toBe('p99');
|
||||
});
|
||||
|
||||
it('sorter function for table sorting', () => {
|
||||
let rowA: {
|
||||
A: string | number;
|
||||
|
||||
@@ -4,6 +4,7 @@ import { ThresholdProps } from 'types/api/widgets/threshold';
|
||||
import { QUERY_TABLE_CONFIG } from 'container/QueryTable/config';
|
||||
import { QueryTableProps } from 'container/QueryTable/QueryTable.intefaces';
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { isEmpty, isNaN } from 'lodash-es';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
@@ -119,14 +120,15 @@ export function getQueryLegend(
|
||||
let legend: string | undefined;
|
||||
switch (currentQuery.queryType) {
|
||||
case EQueryType.QUERY_BUILDER:
|
||||
case EQueryType.AI_QUERY_BUILDER:
|
||||
// check if the value is present in the queries
|
||||
legend = currentQuery?.builder?.queryData?.find(
|
||||
legend = getActiveBuilder(currentQuery)?.queryData?.find(
|
||||
(query) => query.queryName === queryName,
|
||||
)?.legend;
|
||||
|
||||
if (!legend) {
|
||||
// check if the value is present in the formula
|
||||
legend = currentQuery?.builder?.queryFormulas?.find(
|
||||
legend = getActiveBuilder(currentQuery)?.queryFormulas?.find(
|
||||
(query) => query.queryName === queryName,
|
||||
)?.legend;
|
||||
}
|
||||
@@ -199,7 +201,7 @@ export function createColumnsAndDataSource(
|
||||
: undefined;
|
||||
|
||||
const isNewAggregation =
|
||||
currentQuery?.builder?.queryData?.find(
|
||||
getActiveBuilder(currentQuery).queryData?.find(
|
||||
(query) => query.queryName === item.queryName,
|
||||
)?.aggregations?.length || 0;
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import ValueGraph from 'components/ValueGraph';
|
||||
import { generateGridTitle } from 'utils/generateGridTitle';
|
||||
import useGraphContextMenu from 'container/QueryTable/Drilldown/useGraphContextMenu';
|
||||
import ContextMenu, { useCoordinates } from 'periscope/components/ContextMenu';
|
||||
import { isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import {
|
||||
@@ -73,7 +74,7 @@ function GridValueComponent({
|
||||
}
|
||||
|
||||
const isQueryTypeBuilder =
|
||||
widget?.query?.queryType === EQueryType.QUERY_BUILDER;
|
||||
!!widget && isBuilderQueryType(widget.query.queryType);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -58,6 +58,27 @@ describe('getLegend', () => {
|
||||
expect(legendsData).toBe('alias_sum');
|
||||
});
|
||||
|
||||
it('should read the AI builder slot for AI query builder queries', () => {
|
||||
const payloadQuery = getMockQuery({
|
||||
...mockQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: {
|
||||
...mockQuery.builder,
|
||||
queryData: [
|
||||
{
|
||||
...mockQuery.builder.queryData[0],
|
||||
queryName: mockQueryData.queryName,
|
||||
dataSource: DataSource.LOGS,
|
||||
aggregations: [{ expression: "sum(bytes) as 'alias_sum'" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
const legendsData = getLegend(mockQueryData, payloadQuery, MOCK_LABEL_NAME);
|
||||
expect(legendsData).toBe('alias_sum');
|
||||
});
|
||||
|
||||
it('should return legend when single builder query with no alias but legend set (builder)', () => {
|
||||
const payloadQuery = getMockQuery({
|
||||
...mockQuery,
|
||||
|
||||
@@ -73,4 +73,21 @@ describe('KeyboardHotkeysProvider', () => {
|
||||
|
||||
expect(handleShortcut).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores keydown events dispatched on document itself', () => {
|
||||
const handleShortcut = jest.fn() as jest.MockedFunction<() => void>;
|
||||
|
||||
render(
|
||||
<KeyboardHotkeysProvider>
|
||||
<TestComponentWithRegister handleShortcut={handleShortcut} />
|
||||
</KeyboardHotkeysProvider>,
|
||||
);
|
||||
|
||||
expect(() =>
|
||||
document.dispatchEvent(new KeyboardEvent('keydown', { key: 'a' })),
|
||||
).not.toThrow();
|
||||
document.dispatchEvent(new KeyboardEvent('keyup', { key: 'a' }));
|
||||
|
||||
expect(handleShortcut).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -79,11 +79,11 @@ export function KeyboardHotkeysProvider({
|
||||
const wasExtended = useRef(false);
|
||||
|
||||
const handleKeyDown = (event: KeyboardEvent): void => {
|
||||
if (event.repeat) {
|
||||
const { target } = event;
|
||||
if (event.repeat || !(target instanceof Element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const target = event.target as HTMLElement;
|
||||
const isCodeMirrorEditor = target.closest('.cm-editor') !== null;
|
||||
const isMonacoEditor = target.closest('.monaco-editor') !== null;
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import { QueryBuilderV2Provider } from 'components/QueryBuilderV2/QueryBuilderV2Context';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { AllTheProviders, renderHook } from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { BuilderQueryType } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { useBuilderQueryType } from '../useBuilderQueryType';
|
||||
|
||||
function renderBuilderQueryType(
|
||||
queryType: EQueryType,
|
||||
query: Pick<IBuilderQuery, 'builderQueryType'>,
|
||||
inQueryBuilder = true,
|
||||
): BuilderQueryType | undefined {
|
||||
return renderHook(() => useBuilderQueryType(query), {
|
||||
wrapper: ({ children }) => (
|
||||
<AllTheProviders
|
||||
queryBuilderOverrides={{
|
||||
currentQuery: { ...initialQueriesMap.traces, queryType },
|
||||
}}
|
||||
>
|
||||
{inQueryBuilder ? (
|
||||
<QueryBuilderV2Provider>{children}</QueryBuilderV2Provider>
|
||||
) : (
|
||||
children
|
||||
)}
|
||||
</AllTheProviders>
|
||||
),
|
||||
}).result.current;
|
||||
}
|
||||
|
||||
describe('useBuilderQueryType', () => {
|
||||
it('ignores the AI query type outside the query builder', () => {
|
||||
expect(
|
||||
renderBuilderQueryType(EQueryType.AI_QUERY_BUILDER, {}, false),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('is AI for every query while AI is the query type', () => {
|
||||
expect(renderBuilderQueryType(EQueryType.AI_QUERY_BUILDER, {})).toBe(
|
||||
'builder_ai_query',
|
||||
);
|
||||
});
|
||||
|
||||
it("follows the query's own tag otherwise", () => {
|
||||
expect(
|
||||
renderBuilderQueryType(EQueryType.QUERY_BUILDER, {
|
||||
builderQueryType: 'builder_ai_query',
|
||||
}),
|
||||
).toBe('builder_ai_query');
|
||||
expect(renderBuilderQueryType(EQueryType.QUERY_BUILDER, {})).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -2,6 +2,7 @@ import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { initialQueriesMap, initialQueryState } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useGetCompositeQueryParam } from 'hooks/queryBuilder/useGetCompositeQueryParam';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { AllTheProviders, renderHook } from 'tests/test-utils';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
@@ -105,21 +106,55 @@ describe('useGetCompositeQueryParam', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const { QUERY_BUILDER, AI_QUERY_BUILDER } = EQueryType;
|
||||
[
|
||||
[ROUTES.LOGS_EXPLORER, DataSource.LOGS, ''],
|
||||
[ROUTES.AI_OBSERVABILITY_EXPLORER, DataSource.TRACES, ''],
|
||||
[ROUTES.METRICS_EXPLORER_EXPLORER, DataSource.METRICS, ''],
|
||||
[ROUTES.METER_EXPLORER, DataSource.METRICS, TelemetrytypesSourceDTO.meter],
|
||||
].forEach(([route, dataSource, source]) => {
|
||||
[ROUTES.LOGS_EXPLORER, QUERY_BUILDER, DataSource.LOGS, ''],
|
||||
[ROUTES.AI_OBSERVABILITY_EXPLORER, AI_QUERY_BUILDER, DataSource.TRACES, ''],
|
||||
[ROUTES.METRICS_EXPLORER_EXPLORER, QUERY_BUILDER, DataSource.METRICS, ''],
|
||||
[
|
||||
ROUTES.METER_EXPLORER,
|
||||
QUERY_BUILDER,
|
||||
DataSource.METRICS,
|
||||
TelemetrytypesSourceDTO.meter,
|
||||
],
|
||||
].forEach(([route, queryType, dataSource, source]) => {
|
||||
const query = renderOn(clickhouseWithOperator, route);
|
||||
const builder = query && getActiveBuilder(query);
|
||||
|
||||
expect(query?.queryType).toBe(EQueryType.QUERY_BUILDER);
|
||||
expect(query?.builder.queryData[0].dataSource).toBe(dataSource);
|
||||
expect(query?.builder.queryData[0].source ?? '').toBe(source);
|
||||
expect(query?.builder.queryTraceOperator).toStrictEqual([]);
|
||||
expect(query?.queryType).toBe(queryType);
|
||||
expect(builder?.queryData[0].dataSource).toBe(dataSource);
|
||||
expect(builder?.queryData[0].source ?? '').toBe(source);
|
||||
expect(builder?.queryTraceOperator).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('converts the legacy fields of an older AI link moved into the AI slot', () => {
|
||||
const query = renderOn(
|
||||
JSON.stringify({
|
||||
...initialQueriesMap.traces,
|
||||
builder: {
|
||||
...initialQueriesMap.traces.builder,
|
||||
queryData: [
|
||||
{
|
||||
...initialQueriesMap.traces.builder.queryData[0],
|
||||
aggregateOperator: 'avg',
|
||||
aggregations: undefined,
|
||||
having: [],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
ROUTES.AI_OBSERVABILITY_EXPLORER,
|
||||
);
|
||||
const [aiQuery] = getActiveBuilder(query as Query).queryData;
|
||||
|
||||
expect(query?.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(aiQuery.having).toStrictEqual({ expression: '' });
|
||||
expect(aiQuery.aggregations).toStrictEqual([
|
||||
expect.objectContaining({ expression: expect.stringContaining('avg') }),
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps the query type on a route without constraints', () => {
|
||||
const query = renderOn(
|
||||
JSON.stringify({
|
||||
|
||||
@@ -1,16 +1,14 @@
|
||||
import {
|
||||
Querybuildertypesv5QueryTypeDTO,
|
||||
TelemetrytypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { TelemetrytypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { BuilderQueryType } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { BuilderQuerySource, DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
export type ExplorerQueryRules = {
|
||||
dataSource: DataSource;
|
||||
/** `meter` on the meter explorer, which shares the metrics signal; '' elsewhere. */
|
||||
source: BuilderQuerySource;
|
||||
builderQueryType: BuilderQueryType;
|
||||
/** AI_QUERY_BUILDER on the AI explorer, whose queries live in the AI slot. */
|
||||
queryType: EQueryType.QUERY_BUILDER | EQueryType.AI_QUERY_BUILDER;
|
||||
allowsTraceOperator: boolean;
|
||||
};
|
||||
|
||||
@@ -18,31 +16,31 @@ const EXPLORER_QUERY_RULES: Partial<Record<string, ExplorerQueryRules>> = {
|
||||
[ROUTES.LOGS_EXPLORER]: {
|
||||
dataSource: DataSource.LOGS,
|
||||
source: '',
|
||||
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
allowsTraceOperator: false,
|
||||
},
|
||||
[ROUTES.TRACES_EXPLORER]: {
|
||||
dataSource: DataSource.TRACES,
|
||||
source: '',
|
||||
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
allowsTraceOperator: true,
|
||||
},
|
||||
[ROUTES.AI_OBSERVABILITY_EXPLORER]: {
|
||||
dataSource: DataSource.TRACES,
|
||||
source: '',
|
||||
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_ai_query,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
allowsTraceOperator: false,
|
||||
},
|
||||
[ROUTES.METRICS_EXPLORER_EXPLORER]: {
|
||||
dataSource: DataSource.METRICS,
|
||||
source: '',
|
||||
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
allowsTraceOperator: false,
|
||||
},
|
||||
[ROUTES.METER_EXPLORER]: {
|
||||
dataSource: DataSource.METRICS,
|
||||
source: TelemetrytypesSourceDTO.meter,
|
||||
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_query,
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
allowsTraceOperator: false,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -8,11 +8,8 @@ import {
|
||||
initialQueryState,
|
||||
} from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
IBuilderQuery,
|
||||
Query,
|
||||
QueryMode,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
@@ -44,8 +41,9 @@ function firstBuilderQuery(
|
||||
queryData: unknown[],
|
||||
pathname: string,
|
||||
): IBuilderQuery {
|
||||
return normalizeCompositeQuery(withBuilderQueries(query, queryData), pathname)
|
||||
.query.builder.queryData[0];
|
||||
return getActiveBuilder(
|
||||
normalizeCompositeQuery(withBuilderQueries(query, queryData), pathname).query,
|
||||
).queryData[0];
|
||||
}
|
||||
|
||||
function without(builderQuery: object, key: keyof IBuilderQuery): object {
|
||||
@@ -62,9 +60,11 @@ describe('normalizeCompositeQuery', () => {
|
||||
queryType: EQueryType.CLICKHOUSE,
|
||||
extra: 'kept',
|
||||
};
|
||||
const aiQuery = withBuilderQueries(initialQueriesMap.traces, [
|
||||
{ ...tracesQuery, builderQueryType: QueryMode.AI_QUERY_BUILDER },
|
||||
]);
|
||||
const aiQuery: Query = {
|
||||
...initialQueriesMap.traces,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: initialQueriesMap.traces.builder,
|
||||
};
|
||||
|
||||
[NOT_AN_EXPLORER, ROUTES.LOGS_EXPLORER].forEach((pathname) =>
|
||||
expect(
|
||||
@@ -86,6 +86,33 @@ describe('normalizeCompositeQuery', () => {
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('moves the AI queries of an older link into the AI slot', () => {
|
||||
const aiQueryData = [
|
||||
{ ...tracesQuery, builderQueryType: EQueryType.AI_QUERY_BUILDER },
|
||||
];
|
||||
const { query, changed } = normalizeCompositeQuery(
|
||||
withBuilderQueries(initialQueriesMap.traces, aiQueryData),
|
||||
ROUTES.AI_OBSERVABILITY_EXPLORER,
|
||||
);
|
||||
|
||||
expect(changed).toBe(true);
|
||||
expect(query.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(query.builder_ai_query?.queryData).toStrictEqual([tracesQuery]);
|
||||
expect(query.builder).toStrictEqual(initialQueryState.builder);
|
||||
});
|
||||
|
||||
it('drops the AI slot outside the AI explorer', () => {
|
||||
const { query } = normalizeCompositeQuery(
|
||||
{
|
||||
...initialQueriesMap.traces,
|
||||
builder_ai_query: initialQueriesMap.traces.builder,
|
||||
},
|
||||
ROUTES.TRACES_EXPLORER,
|
||||
);
|
||||
|
||||
expect(query.builder_ai_query).toBeUndefined();
|
||||
});
|
||||
|
||||
it('adds missing blocks and a stable id without changing its inputs', () => {
|
||||
const { builder: _, ...builderless } = {
|
||||
...initialQueriesMap.logs,
|
||||
@@ -209,7 +236,7 @@ describe('normalizeCompositeQuery', () => {
|
||||
expect(
|
||||
firstBuilderQuery(
|
||||
logs,
|
||||
[{ ...logsQuery, builderQueryType: QueryMode.AI_QUERY_BUILDER }],
|
||||
[{ ...logsQuery, builderQueryType: EQueryType.AI_QUERY_BUILDER }],
|
||||
ROUTES.LOGS_EXPLORER,
|
||||
).builderQueryType,
|
||||
).toBeUndefined();
|
||||
@@ -220,7 +247,7 @@ describe('normalizeCompositeQuery', () => {
|
||||
{
|
||||
...tracesQuery,
|
||||
queryName: 'D',
|
||||
builderQueryType: QueryMode.AI_QUERY_BUILDER,
|
||||
builderQueryType: EQueryType.AI_QUERY_BUILDER,
|
||||
...llmFilter,
|
||||
},
|
||||
],
|
||||
@@ -243,10 +270,7 @@ describe('normalizeCompositeQuery', () => {
|
||||
).toBe(TelemetrytypesSourceDTO.meter);
|
||||
expect(
|
||||
firstBuilderQuery(traces, [{ ...tracesQuery, ...llmFilter }], ai),
|
||||
).toMatchObject({
|
||||
builderQueryType: QueryMode.AI_QUERY_BUILDER,
|
||||
...llmFilter,
|
||||
});
|
||||
).toStrictEqual({ ...tracesQuery, ...llmFilter });
|
||||
expect(
|
||||
firstBuilderQuery(
|
||||
traces,
|
||||
@@ -260,17 +284,13 @@ describe('normalizeCompositeQuery', () => {
|
||||
],
|
||||
ai,
|
||||
),
|
||||
).toMatchObject({
|
||||
builderQueryType: QueryMode.AI_QUERY_BUILDER,
|
||||
queryName: 'B',
|
||||
filter: { expression: '' },
|
||||
});
|
||||
).toStrictEqual({ ...tracesQuery, queryName: 'B', ...llmFilter });
|
||||
expect(
|
||||
firstBuilderQuery(traces, [{ ...logsQuery, queryName: 'C' }], ai),
|
||||
).toMatchObject({
|
||||
builderQueryType: QueryMode.AI_QUERY_BUILDER,
|
||||
dataSource: DataSource.TRACES,
|
||||
queryName: 'C',
|
||||
filter: { expression: '' },
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -7,8 +7,10 @@ import {
|
||||
Querybuildertypesv5QueryTypeDTO,
|
||||
TelemetrytypesSourceDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import type { QueryBuilderData } from 'types/common/queryBuilder';
|
||||
import { v5 as uuidv5 } from 'uuid';
|
||||
|
||||
import {
|
||||
@@ -78,6 +80,14 @@ function addMissingBlocks(query: Query, urlQuery: object): void {
|
||||
if (!query.builder.queryTraceOperator) {
|
||||
query.builder.queryTraceOperator = [];
|
||||
}
|
||||
|
||||
if (isPlainObject(query.builder_ai_query)) {
|
||||
const aiBuilder = query.builder_ai_query as QueryBuilderData;
|
||||
aiBuilder.queryFormulas = aiBuilder.queryFormulas ?? [];
|
||||
aiBuilder.queryTraceOperator = aiBuilder.queryTraceOperator ?? [];
|
||||
} else {
|
||||
delete query.builder_ai_query;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -93,8 +103,24 @@ function isListOfObjects(value: unknown): boolean {
|
||||
}
|
||||
|
||||
function fitQueryToExplorer(query: Query, rules: ExplorerQueryRules): void {
|
||||
// Explorers only have the query builder: no PromQL or ClickHouse editor.
|
||||
query.queryType = EQueryType.QUERY_BUILDER;
|
||||
// Explorers only have a query builder: no PromQL or ClickHouse editor.
|
||||
query.queryType = rules.queryType;
|
||||
if (rules.queryType === EQueryType.AI_QUERY_BUILDER) {
|
||||
// Older links carry the AI queries inside `builder`.
|
||||
if (!query.builder_ai_query) {
|
||||
query.builder_ai_query = query.builder;
|
||||
query.builder = cloneDeep(initialQueryState.builder);
|
||||
}
|
||||
} else {
|
||||
delete query.builder_ai_query;
|
||||
}
|
||||
const activeBuilder = getActiveBuilder(query);
|
||||
if (
|
||||
!isListOfObjects(activeBuilder.queryData) ||
|
||||
activeBuilder.queryData.length === 0
|
||||
) {
|
||||
activeBuilder.queryData = cloneDeep(initialQueryState.builder.queryData);
|
||||
}
|
||||
|
||||
if (query.promql.some((promql) => promql.query !== '')) {
|
||||
query.promql = cloneDeep(initialQueryState.promql);
|
||||
@@ -105,10 +131,10 @@ function fitQueryToExplorer(query: Query, rules: ExplorerQueryRules): void {
|
||||
}
|
||||
|
||||
if (!rules.allowsTraceOperator) {
|
||||
query.builder.queryTraceOperator = [];
|
||||
activeBuilder.queryTraceOperator = [];
|
||||
}
|
||||
|
||||
query.builder.queryData = query.builder.queryData.map((builderQuery) =>
|
||||
activeBuilder.queryData = activeBuilder.queryData.map((builderQuery) =>
|
||||
fitBuilderQueryToExplorer(builderQuery, rules),
|
||||
);
|
||||
}
|
||||
@@ -148,12 +174,9 @@ function fillMissingSignal(
|
||||
builderQuery.source = rules.source;
|
||||
}
|
||||
|
||||
// A missing `builderQueryType` already means builder_query, so only AI needs it written.
|
||||
if (
|
||||
builderQuery.builderQueryType === undefined &&
|
||||
rules.builderQueryType === Querybuildertypesv5QueryTypeDTO.builder_ai_query
|
||||
) {
|
||||
builderQuery.builderQueryType = rules.builderQueryType;
|
||||
// The AI slot marks its queries as AI; a tag from an older link is redundant.
|
||||
if (rules.queryType === EQueryType.AI_QUERY_BUILDER) {
|
||||
delete builderQuery.builderQueryType;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,15 +192,11 @@ function belongsToExplorer(
|
||||
return false;
|
||||
}
|
||||
|
||||
const builderQueryType =
|
||||
builderQuery.builderQueryType ??
|
||||
Querybuildertypesv5QueryTypeDTO.builder_query;
|
||||
|
||||
if (builderQueryType !== rules.builderQueryType) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
// Only the AI explorer runs AI queries.
|
||||
return (
|
||||
builderQuery.builderQueryType !==
|
||||
Querybuildertypesv5QueryTypeDTO.builder_ai_query
|
||||
);
|
||||
}
|
||||
|
||||
function getDefaultBuilderQuery(rules: ExplorerQueryRules): IBuilderQuery {
|
||||
@@ -186,11 +205,5 @@ function getDefaultBuilderQuery(rules: ExplorerQueryRules): IBuilderQuery {
|
||||
);
|
||||
builderQuery.source = rules.source;
|
||||
|
||||
if (
|
||||
rules.builderQueryType === Querybuildertypesv5QueryTypeDTO.builder_ai_query
|
||||
) {
|
||||
builderQuery.builderQueryType = rules.builderQueryType;
|
||||
}
|
||||
|
||||
return builderQuery;
|
||||
}
|
||||
|
||||
22
frontend/src/hooks/queryBuilder/useBuilderQueryType.ts
Normal file
22
frontend/src/hooks/queryBuilder/useBuilderQueryType.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
import { useIsInQueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2Context';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { BuilderQueryType } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
/**
|
||||
* The query's builder type, for picking the field suggestion endpoints. The AI query type
|
||||
* applies only inside the query builder; elsewhere, and in alert editors, which keep AI
|
||||
* queries in `builder`, the query's own tag decides.
|
||||
*/
|
||||
export function useBuilderQueryType(
|
||||
query: Pick<IBuilderQuery, 'builderQueryType'>,
|
||||
): BuilderQueryType | undefined {
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const isInQueryBuilder = useIsInQueryBuilderV2();
|
||||
|
||||
return isInQueryBuilder &&
|
||||
currentQuery?.queryType === EQueryType.AI_QUERY_BUILDER
|
||||
? 'builder_ai_query'
|
||||
: query.builderQueryType;
|
||||
}
|
||||
@@ -9,13 +9,48 @@ import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import { isPlainObject } from 'lodash-es';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import {
|
||||
NormalizedQuery,
|
||||
normalizeCompositeQuery,
|
||||
} from './normalizeCompositeQuery';
|
||||
|
||||
function toExpressionQuery(query: IBuilderQuery): IBuilderQuery {
|
||||
const existingExpression = query.filter?.expression || '';
|
||||
const convertedQuery = { ...query };
|
||||
|
||||
const convertedFilter = convertFiltersToExpressionWithExistingQuery(
|
||||
query.filters || { items: [], op: 'AND' },
|
||||
existingExpression,
|
||||
);
|
||||
convertedQuery.filter = convertedFilter.filter;
|
||||
convertedQuery.filters = convertedFilter.filters;
|
||||
|
||||
// Convert having if needed
|
||||
if (Array.isArray(query.having)) {
|
||||
const convertedHaving = convertHavingToExpression(
|
||||
query.having.filter(isPlainObject),
|
||||
);
|
||||
convertedQuery.having = convertedHaving;
|
||||
}
|
||||
|
||||
// Convert aggregation if needed
|
||||
if (!query.aggregations && query.aggregateOperator) {
|
||||
const convertedAggregation = convertAggregationToExpression({
|
||||
aggregateOperator: query.aggregateOperator,
|
||||
aggregateAttribute: query.aggregateAttribute as BaseAutocompleteData,
|
||||
dataSource: query.dataSource,
|
||||
timeAggregation: query.timeAggregation,
|
||||
spaceAggregation: query.spaceAggregation,
|
||||
reduceTo: query.reduceTo,
|
||||
temporality: query.temporality,
|
||||
}) as any; // Type assertion to handle union type
|
||||
convertedQuery.aggregations = convertedAggregation;
|
||||
}
|
||||
return convertedQuery;
|
||||
}
|
||||
|
||||
export const useNormalizedCompositeQueryParam = (): NormalizedQuery | null => {
|
||||
const urlQuery = useUrlQuery();
|
||||
const { pathname } = useAppLocation();
|
||||
@@ -44,44 +79,15 @@ export const useNormalizedCompositeQueryParam = (): NormalizedQuery | null => {
|
||||
pathname,
|
||||
));
|
||||
|
||||
// Convert old format to new format for each query in builder.queryData
|
||||
if (parsedCompositeQuery?.builder?.queryData) {
|
||||
parsedCompositeQuery.builder.queryData =
|
||||
parsedCompositeQuery.builder.queryData.map((query) => {
|
||||
const existingExpression = query.filter?.expression || '';
|
||||
const convertedQuery = { ...query };
|
||||
|
||||
const convertedFilter = convertFiltersToExpressionWithExistingQuery(
|
||||
query.filters || { items: [], op: 'AND' },
|
||||
existingExpression,
|
||||
);
|
||||
convertedQuery.filter = convertedFilter.filter;
|
||||
convertedQuery.filters = convertedFilter.filters;
|
||||
|
||||
// Convert having if needed
|
||||
if (Array.isArray(query.having)) {
|
||||
const convertedHaving = convertHavingToExpression(
|
||||
query.having.filter(isPlainObject),
|
||||
);
|
||||
convertedQuery.having = convertedHaving;
|
||||
}
|
||||
|
||||
// Convert aggregation if needed
|
||||
if (!query.aggregations && query.aggregateOperator) {
|
||||
const convertedAggregation = convertAggregationToExpression({
|
||||
aggregateOperator: query.aggregateOperator,
|
||||
aggregateAttribute: query.aggregateAttribute as BaseAutocompleteData,
|
||||
dataSource: query.dataSource,
|
||||
timeAggregation: query.timeAggregation,
|
||||
spaceAggregation: query.spaceAggregation,
|
||||
reduceTo: query.reduceTo,
|
||||
temporality: query.temporality,
|
||||
}) as any; // Type assertion to handle union type
|
||||
convertedQuery.aggregations = convertedAggregation;
|
||||
}
|
||||
return convertedQuery;
|
||||
});
|
||||
}
|
||||
// Convert old format to new format in every builder slot
|
||||
[
|
||||
parsedCompositeQuery?.builder,
|
||||
parsedCompositeQuery?.builder_ai_query,
|
||||
].forEach((builder) => {
|
||||
if (builder?.queryData) {
|
||||
builder.queryData = builder.queryData.map(toExpressionQuery);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
parsedCompositeQuery = null;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
saveAsPreviousQuery,
|
||||
} from 'components/QueryBuilderV2/QueryV2/previousQuery.utils';
|
||||
import { ENTITY_VERSION_V4, ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { getActiveBuilder } from 'lib/query/builderSlot';
|
||||
import { LEGEND } from 'constants/global';
|
||||
import {
|
||||
ATTRIBUTE_TYPES,
|
||||
@@ -488,13 +489,15 @@ export const useQueryOperations: UseQueryOperations = ({
|
||||
],
|
||||
);
|
||||
|
||||
const activeQueryCount = getActiveBuilder(currentQuery).queryData.length;
|
||||
|
||||
const handleDeleteQuery = useCallback(() => {
|
||||
if (currentQuery.builder.queryData.length > 1) {
|
||||
if (activeQueryCount > 1) {
|
||||
removeQueryBuilderEntityByIndex('queryData', index);
|
||||
}
|
||||
setLastUsedQuery(0);
|
||||
}, [
|
||||
currentQuery.builder.queryData.length,
|
||||
activeQueryCount,
|
||||
setLastUsedQuery,
|
||||
removeQueryBuilderEntityByIndex,
|
||||
index,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
import { initialFormulaBuilderFormValues } from 'constants/queryBuilder';
|
||||
import {
|
||||
IBuilderFormula,
|
||||
IClickHouseQuery,
|
||||
@@ -67,6 +68,23 @@ describe('useGetQueryLabels', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('AI_QUERY_BUILDER type', () => {
|
||||
it('returns formula labels from builder_ai_query', () => {
|
||||
const query = buildQuery({
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: {
|
||||
queryData: [],
|
||||
queryFormulas: [{ ...initialFormulaBuilderFormValues, queryName: 'F1' }],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useGetQueryLabels(query));
|
||||
|
||||
expect(result.current).toStrictEqual([{ label: 'F1', value: 'F1' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CLICKHOUSE type', () => {
|
||||
it('returns empty array when clickhouse_sql is undefined', () => {
|
||||
const query = buildQuery({
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMemo } from 'react';
|
||||
import { getQueryLabelWithAggregation } from 'components/QueryBuilderV2/utils';
|
||||
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
@@ -7,25 +8,24 @@ export const useGetQueryLabels = (
|
||||
currentQuery: Query,
|
||||
): { label: string; value: string }[] =>
|
||||
useMemo(() => {
|
||||
if (currentQuery?.queryType === EQueryType.QUERY_BUILDER) {
|
||||
if (isBuilderQueryType(currentQuery.queryType)) {
|
||||
const activeBuilder = getActiveBuilder(currentQuery);
|
||||
const queryLabels = getQueryLabelWithAggregation(
|
||||
currentQuery?.builder?.queryData || [],
|
||||
);
|
||||
const formulaLabels = (currentQuery?.builder?.queryFormulas ?? []).map(
|
||||
(formula) => ({
|
||||
label: formula.queryName,
|
||||
value: formula.queryName,
|
||||
}),
|
||||
activeBuilder.queryData ?? [],
|
||||
);
|
||||
const formulaLabels = (activeBuilder.queryFormulas ?? []).map((formula) => ({
|
||||
label: formula.queryName,
|
||||
value: formula.queryName,
|
||||
}));
|
||||
return [...queryLabels, ...formulaLabels];
|
||||
}
|
||||
if (currentQuery?.queryType === EQueryType.CLICKHOUSE) {
|
||||
return (currentQuery?.clickhouse_sql ?? []).map((q) => ({
|
||||
if (currentQuery.queryType === EQueryType.CLICKHOUSE) {
|
||||
return (currentQuery.clickhouse_sql ?? []).map((q) => ({
|
||||
label: q.name,
|
||||
value: q.name,
|
||||
}));
|
||||
}
|
||||
return (currentQuery?.promql ?? []).map((q) => ({
|
||||
return (currentQuery.promql ?? []).map((q) => ({
|
||||
label: q.name,
|
||||
value: q.name,
|
||||
}));
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
QueryRangeResponseV5,
|
||||
} from 'types/api/v5/queryRange';
|
||||
import { QueryData } from 'types/api/widgets/getQuery';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { prepareQueryRangePayload } from './prepareQueryRangePayload';
|
||||
@@ -36,11 +36,11 @@ import { prepareQueryRangePayload } from './prepareQueryRangePayload';
|
||||
* Validates if metric name is available for METRICS data source
|
||||
*/
|
||||
function validateMetricNameForMetricsDataSource(query: Query): boolean {
|
||||
if (query.queryType !== 'builder') {
|
||||
if (!isBuilderQueryType(query.queryType)) {
|
||||
return true; // Non-builder queries don't need this validation
|
||||
}
|
||||
|
||||
const { queryData } = query.builder;
|
||||
const { queryData } = getActiveBuilder(query);
|
||||
|
||||
// Check if any METRICS data source queries exist
|
||||
const metricsQueries = queryData.filter(
|
||||
@@ -124,14 +124,15 @@ export const getLegend = (
|
||||
labelName: string,
|
||||
): string => {
|
||||
// For non-query builder queries, return the label name directly
|
||||
if (payloadQuery.queryType !== EQueryType.QUERY_BUILDER) {
|
||||
if (!isBuilderQueryType(payloadQuery.queryType)) {
|
||||
return labelName;
|
||||
}
|
||||
|
||||
const activeBuilder = getActiveBuilder(payloadQuery);
|
||||
// Combine queryData and queryTraceOperator
|
||||
const allQueries = [
|
||||
...(payloadQuery?.builder?.queryData || []),
|
||||
...(payloadQuery?.builder?.queryTraceOperator || []),
|
||||
...(activeBuilder?.queryData || []),
|
||||
...(activeBuilder?.queryTraceOperator || []),
|
||||
];
|
||||
|
||||
const aggregationPerQuery = allQueries.reduce((acc, query) => {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { initialQueryBuilderFormValues } from 'constants/queryBuilder';
|
||||
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
@@ -161,6 +162,37 @@ describe('extractQueryTextStrings', () => {
|
||||
expect(texts).toStrictEqual(['env = $deployment_environment']);
|
||||
});
|
||||
|
||||
it('extracts from the AI slot, not builder, for an AI query', () => {
|
||||
const query: Query = {
|
||||
...baseQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: {
|
||||
queryData: [
|
||||
{
|
||||
...initialQueryBuilderFormValues,
|
||||
filter: { expression: 'env = $ignored' },
|
||||
},
|
||||
],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
builder_ai_query: {
|
||||
queryData: [
|
||||
{
|
||||
...initialQueryBuilderFormValues,
|
||||
filter: { expression: 'service.name = $service' },
|
||||
},
|
||||
],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
};
|
||||
|
||||
expect(extractQueryTextStrings(query)).toStrictEqual([
|
||||
'service.name = $service',
|
||||
]);
|
||||
});
|
||||
|
||||
it('skips non-string filter values', () => {
|
||||
const query: Query = {
|
||||
...baseQuery,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { escapeRegExp, isArray } from 'lodash-es';
|
||||
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { Query, TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import type { QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
/**
|
||||
* Builds a RegExp that matches any recognized variable reference syntax:
|
||||
@@ -50,9 +52,11 @@ export function containsAnyVariableReference(text: string): boolean {
|
||||
return !!text && ANY_VARIABLE_REFERENCE.test(text);
|
||||
}
|
||||
|
||||
function extractQueryBuilderTexts(query: Query): string[] {
|
||||
function extractQueryBuilderTexts(
|
||||
builder: QueryBuilderData | undefined,
|
||||
): string[] {
|
||||
const texts: string[] = [];
|
||||
const queryDataList = query.builder?.queryData;
|
||||
const queryDataList = builder?.queryData;
|
||||
if (isArray(queryDataList)) {
|
||||
queryDataList.forEach((queryData) => {
|
||||
queryData.filters?.items?.forEach((filter: TagFilterItem) => {
|
||||
@@ -102,13 +106,13 @@ function extractClickhouseSQLTexts(query: Query): string[] {
|
||||
/**
|
||||
* Extracts all text strings from a widget Query that could contain variable
|
||||
* references. Covers:
|
||||
* - QUERY_BUILDER: filter items' string values + filter.expression
|
||||
* - QUERY_BUILDER / AI_QUERY_BUILDER: filter items' string values + filter.expression
|
||||
* - PROM: each promql[].query
|
||||
* - CLICKHOUSE: each clickhouse_sql[].query
|
||||
*/
|
||||
export function extractQueryTextStrings(query: Query): string[] {
|
||||
if (query.queryType === EQueryType.QUERY_BUILDER) {
|
||||
return extractQueryBuilderTexts(query);
|
||||
if (isBuilderQueryType(query.queryType)) {
|
||||
return extractQueryBuilderTexts(getActiveBuilder(query));
|
||||
}
|
||||
|
||||
if (query.queryType === EQueryType.PROM) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
import {
|
||||
initialQueryBuilderFormValuesMap,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { mapCompositeQueryFromQuery } from '../mapCompositeQueryFromQuery';
|
||||
|
||||
const emptyBuilder = {
|
||||
queryData: [],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
};
|
||||
|
||||
describe('mapCompositeQueryFromQuery', () => {
|
||||
it('sends an AI query as builder_ai_query envelopes under the builder query type', () => {
|
||||
const query: Query = {
|
||||
id: 'q',
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
promql: [],
|
||||
clickhouse_sql: [],
|
||||
builder: {
|
||||
...emptyBuilder,
|
||||
queryData: [
|
||||
{ ...initialQueryBuilderFormValuesMap.metrics, queryName: 'M' },
|
||||
],
|
||||
},
|
||||
builder_ai_query: {
|
||||
...emptyBuilder,
|
||||
queryData: [{ ...initialQueryBuilderFormValuesMap.traces, queryName: 'A' }],
|
||||
},
|
||||
};
|
||||
|
||||
const composite = mapCompositeQueryFromQuery(query, PANEL_TYPES.TIME_SERIES);
|
||||
|
||||
expect(composite.queryType).toBe(EQueryType.QUERY_BUILDER);
|
||||
expect(
|
||||
composite.queries?.map((q) => [q.type, (q.spec as { name: string }).name]),
|
||||
).toStrictEqual([['builder_ai_query', 'A']]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
|
||||
import { foldAISlot } from 'lib/query/builderSlot';
|
||||
import {
|
||||
BuilderClickHouseResource,
|
||||
BuilderPromQLResource,
|
||||
@@ -91,8 +92,13 @@ const buildPromQuery = (
|
||||
return compositeQuery;
|
||||
};
|
||||
|
||||
const queryTypeMethodMapping = {
|
||||
const queryTypeMethodMapping: Record<
|
||||
EQueryType,
|
||||
(query: Query, panelType: PANEL_TYPES | null) => ICompositeMetricQuery
|
||||
> = {
|
||||
[EQueryType.QUERY_BUILDER]: buildBuilderQuery,
|
||||
[EQueryType.AI_QUERY_BUILDER]: (query, panelType) =>
|
||||
buildBuilderQuery(foldAISlot(query), panelType),
|
||||
[EQueryType.CLICKHOUSE]: buildClickHouseQuery,
|
||||
[EQueryType.PROM]: buildPromQuery,
|
||||
};
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
PromQuery,
|
||||
QueryBuilderFormula,
|
||||
} from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import {
|
||||
convertBuilderQueryToIBuilderQuery,
|
||||
convertQueryBuilderFormulaToIBuilderFormula,
|
||||
@@ -37,6 +38,7 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
|
||||
> = {};
|
||||
const promQueries: IPromQLQuery[] = [];
|
||||
const clickhouseQueries: IClickHouseQuery[] = [];
|
||||
const isAIQuery = compositeQuery.queryType === EQueryType.AI_QUERY_BUILDER;
|
||||
|
||||
compositeQuery.queries?.forEach((q) => {
|
||||
const spec = q.spec as BuilderQuery | PromQuery | ClickHouseQuery;
|
||||
@@ -49,10 +51,13 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
|
||||
}
|
||||
} else if (q.type === 'builder_ai_query') {
|
||||
if (spec.name) {
|
||||
builderQueries[spec.name] = {
|
||||
...convertBuilderQueryToIBuilderQuery(spec as BuilderQuery),
|
||||
builderQueryType: 'builder_ai_query',
|
||||
};
|
||||
const builderQuery = convertBuilderQueryToIBuilderQuery(
|
||||
spec as BuilderQuery,
|
||||
);
|
||||
// Only AI queries kept in `builder` (alerts) need the tag; the AI slot marks its own.
|
||||
builderQueries[spec.name] = isAIQuery
|
||||
? builderQuery
|
||||
: { ...builderQuery, builderQueryType: 'builder_ai_query' };
|
||||
builderQueryTypes[spec.name] = 'builder_ai_query';
|
||||
}
|
||||
} else if (q.type === 'builder_formula') {
|
||||
@@ -87,8 +92,14 @@ const mapQueryFromV5 = (compositeQuery: ICompositeMetricQuery): Query => {
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
const builder = transformQueryBuilderDataModel(
|
||||
builderQueries,
|
||||
builderQueryTypes,
|
||||
);
|
||||
return {
|
||||
builder: transformQueryBuilderDataModel(builderQueries, builderQueryTypes),
|
||||
builder: isAIQuery ? transformQueryBuilderDataModel({}) : builder,
|
||||
...(isAIQuery && { builder_ai_query: builder }),
|
||||
promql: promQueries,
|
||||
clickhouse_sql: clickhouseQueries,
|
||||
queryType: compositeQuery.queryType,
|
||||
|
||||
131
frontend/src/lib/query/__tests__/builderSlot.test.ts
Normal file
131
frontend/src/lib/query/__tests__/builderSlot.test.ts
Normal file
@@ -0,0 +1,131 @@
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryAIWithType,
|
||||
} from 'constants/queryBuilder';
|
||||
import {
|
||||
getActiveBuilder,
|
||||
getBuilderSlotKeyForQueryType,
|
||||
isAIQueryType,
|
||||
isBuilderQueryType,
|
||||
foldAISlot,
|
||||
toSlotQuery,
|
||||
} from 'lib/query/builderSlot';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
const baseQuery = initialQueriesMap[DataSource.METRICS];
|
||||
const aiBuilder = getActiveBuilder(initialQueryAIWithType);
|
||||
|
||||
describe('isBuilderQueryType', () => {
|
||||
it.each([
|
||||
[EQueryType.QUERY_BUILDER, true],
|
||||
[EQueryType.AI_QUERY_BUILDER, true],
|
||||
[EQueryType.CLICKHOUSE, false],
|
||||
[EQueryType.PROM, false],
|
||||
])('%s → %s', (queryType, expected) => {
|
||||
expect(isBuilderQueryType(queryType)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBuilderSlotKeyForQueryType', () => {
|
||||
it.each([
|
||||
[EQueryType.QUERY_BUILDER, EQueryType.QUERY_BUILDER],
|
||||
[EQueryType.CLICKHOUSE, EQueryType.QUERY_BUILDER],
|
||||
[EQueryType.PROM, EQueryType.QUERY_BUILDER],
|
||||
[EQueryType.AI_QUERY_BUILDER, EQueryType.AI_QUERY_BUILDER],
|
||||
])('maps %s to %s', (queryType, slotKey) => {
|
||||
expect(getBuilderSlotKeyForQueryType(queryType)).toBe(slotKey);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getActiveBuilder', () => {
|
||||
it('reads builder for the Query Builder type', () => {
|
||||
const query: Query = { ...baseQuery, builder_ai_query: aiBuilder };
|
||||
expect(getActiveBuilder(query)).toBe(baseQuery.builder);
|
||||
});
|
||||
|
||||
it('reads the AI slot for the AI type', () => {
|
||||
const query: Query = {
|
||||
...baseQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: aiBuilder,
|
||||
};
|
||||
expect(getActiveBuilder(query)).toBe(aiBuilder);
|
||||
});
|
||||
|
||||
it('reads an unused AI slot as holding no queries', () => {
|
||||
const query: Query = { ...baseQuery, queryType: EQueryType.AI_QUERY_BUILDER };
|
||||
expect(getActiveBuilder(query)).toStrictEqual({
|
||||
queryData: [],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps builder for ClickHouse and PromQL', () => {
|
||||
const query: Query = { ...baseQuery, queryType: EQueryType.PROM };
|
||||
expect(getActiveBuilder(query)).toBe(baseQuery.builder);
|
||||
});
|
||||
});
|
||||
|
||||
describe('foldAISlot', () => {
|
||||
it('passes non-AI queries through untouched', () => {
|
||||
expect(foldAISlot(baseQuery)).toBe(baseQuery);
|
||||
});
|
||||
|
||||
it('sends AI as a builder query holding the AI slot, every query tagged', () => {
|
||||
const untagged = {
|
||||
...aiBuilder.queryData[0],
|
||||
builderQueryType: undefined,
|
||||
};
|
||||
const query: Query = {
|
||||
...baseQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: { ...aiBuilder, queryData: [untagged] },
|
||||
};
|
||||
|
||||
const foldedQuery = foldAISlot(query);
|
||||
|
||||
expect(foldedQuery.queryType).toBe(EQueryType.QUERY_BUILDER);
|
||||
expect(foldedQuery.builder.queryData).toStrictEqual([
|
||||
{ ...untagged, builderQueryType: 'builder_ai_query' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isAIQueryType', () => {
|
||||
it.each([
|
||||
[EQueryType.AI_QUERY_BUILDER, true],
|
||||
[EQueryType.QUERY_BUILDER, false],
|
||||
[EQueryType.CLICKHOUSE, false],
|
||||
[EQueryType.PROM, false],
|
||||
])('%s → %s', (queryType, expected) => {
|
||||
expect(isAIQueryType(queryType)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('toSlotQuery', () => {
|
||||
it('returns non-AI queries unchanged', () => {
|
||||
expect(toSlotQuery(baseQuery, baseQuery)).toBe(baseQuery);
|
||||
});
|
||||
|
||||
it('moves request-shape builder edits back into the AI slot', () => {
|
||||
const slotQuery: Query = {
|
||||
...baseQuery,
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder_ai_query: aiBuilder,
|
||||
};
|
||||
const requestQuery = foldAISlot(slotQuery);
|
||||
const refined: Query = {
|
||||
...requestQuery,
|
||||
builder: { ...requestQuery.builder, queryFormulas: [] },
|
||||
};
|
||||
|
||||
const restored = toSlotQuery(refined, slotQuery);
|
||||
|
||||
expect(restored.queryType).toBe(EQueryType.AI_QUERY_BUILDER);
|
||||
expect(restored.builder).toBe(baseQuery.builder);
|
||||
expect(restored.builder_ai_query).toBe(refined.builder);
|
||||
});
|
||||
});
|
||||
98
frontend/src/lib/query/builderSlot.ts
Normal file
98
frontend/src/lib/query/builderSlot.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import { Querybuildertypesv5QueryTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type {
|
||||
Query,
|
||||
QueryState,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import type { QueryBuilderData } from 'types/common/queryBuilder';
|
||||
|
||||
export type BuilderSlotKey =
|
||||
| EQueryType.QUERY_BUILDER
|
||||
| EQueryType.AI_QUERY_BUILDER;
|
||||
|
||||
const EMPTY_BUILDER: QueryBuilderData = {
|
||||
queryData: [],
|
||||
queryFormulas: [],
|
||||
queryTraceOperator: [],
|
||||
};
|
||||
|
||||
/** Query Builder and AI Query Builder; both author builder queries, each in its own slot. */
|
||||
export function isBuilderQueryType(queryType: EQueryType): boolean {
|
||||
return (
|
||||
queryType === EQueryType.QUERY_BUILDER ||
|
||||
queryType === EQueryType.AI_QUERY_BUILDER
|
||||
);
|
||||
}
|
||||
|
||||
export function isAIQueryType(queryType: EQueryType): boolean {
|
||||
return queryType === EQueryType.AI_QUERY_BUILDER;
|
||||
}
|
||||
|
||||
/** The `Query` slot builder edits land in; non-builder types keep `builder`, as they always have. */
|
||||
export function getBuilderSlotKeyForQueryType(
|
||||
queryType: EQueryType,
|
||||
): BuilderSlotKey {
|
||||
return isAIQueryType(queryType)
|
||||
? EQueryType.AI_QUERY_BUILDER
|
||||
: EQueryType.QUERY_BUILDER;
|
||||
}
|
||||
|
||||
/**
|
||||
* The query as the backend takes it. AI goes out as a `builder` query whose queries carry
|
||||
* `builderQueryType: builder_ai_query`, the tag set from the slot so a stale one can't leak.
|
||||
*/
|
||||
export function foldAISlot(query: Query): Query {
|
||||
if (!isAIQueryType(query.queryType)) {
|
||||
return query;
|
||||
}
|
||||
const aiBuilder = getActiveBuilder(query);
|
||||
return {
|
||||
...query,
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
builder: {
|
||||
...aiBuilder,
|
||||
queryData: aiBuilder.queryData.map((queryData) => ({
|
||||
...queryData,
|
||||
builderQueryType: Querybuildertypesv5QueryTypeDTO.builder_ai_query,
|
||||
})),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Undoes `foldAISlot` for `slotQuery`: builder edits made on the request shape land back in its slot. */
|
||||
export function toSlotQuery(requestQuery: Query, slotQuery: Query): Query {
|
||||
if (!isAIQueryType(slotQuery.queryType)) {
|
||||
return requestQuery;
|
||||
}
|
||||
return {
|
||||
...requestQuery,
|
||||
queryType: slotQuery.queryType,
|
||||
builder: slotQuery.builder,
|
||||
builder_ai_query: requestQuery.builder,
|
||||
};
|
||||
}
|
||||
|
||||
/** The builder at `slotKey`; an unused AI slot holds none. */
|
||||
export function getBuilderBySlotKey(
|
||||
state: QueryState,
|
||||
slotKey: BuilderSlotKey,
|
||||
): QueryBuilderData {
|
||||
return state[slotKey] ?? EMPTY_BUILDER;
|
||||
}
|
||||
|
||||
/** `state` with the builder at `slotKey` replaced. */
|
||||
export function replaceBuilderBySlotKey<T extends QueryState>(
|
||||
state: T,
|
||||
slotKey: BuilderSlotKey,
|
||||
builder: QueryBuilderData,
|
||||
): T {
|
||||
return { ...state, [slotKey]: builder };
|
||||
}
|
||||
|
||||
/** The builder queries `queryType` authors; an unused AI slot holds none. */
|
||||
export function getActiveBuilder(query: Query): QueryBuilderData {
|
||||
return getBuilderBySlotKey(
|
||||
query,
|
||||
getBuilderSlotKeyForQueryType(query.queryType),
|
||||
);
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
import { FORMULA_REGEXP } from 'constants/regExp';
|
||||
import { QUERY_TABLE_CONFIG } from 'container/QueryTable/config';
|
||||
import { QueryTableProps } from 'container/QueryTable/QueryTable.intefaces';
|
||||
import { getActiveBuilder, isBuilderQueryType } from 'lib/query/builderSlot';
|
||||
import { get, isEqual, isNaN, isObject } from 'lodash-es';
|
||||
import {
|
||||
IBuilderFormula,
|
||||
@@ -93,8 +94,8 @@ const getQueryByName = <T extends keyof QueryBuilderData>(
|
||||
queryArray.find((q) => q.name === currentQueryName) || defaultQueryValue
|
||||
);
|
||||
}
|
||||
if (query.queryType === EQueryType.QUERY_BUILDER) {
|
||||
const queryArray = (query.builder[type] || []) as (
|
||||
if (isBuilderQueryType(query.queryType)) {
|
||||
const queryArray = (getActiveBuilder(query)[type] || []) as (
|
||||
| IBuilderQuery
|
||||
| IBuilderFormula
|
||||
)[];
|
||||
@@ -173,7 +174,7 @@ const addOperatorFormulaColumns = (
|
||||
return;
|
||||
}
|
||||
|
||||
if (queryType === EQueryType.QUERY_BUILDER) {
|
||||
if (isBuilderQueryType(queryType)) {
|
||||
const currentQueryData = query as IBuilderQuery;
|
||||
let operatorLabel = `${currentQueryData.aggregateOperator}`;
|
||||
if (currentQueryData.aggregateAttribute?.key) {
|
||||
|
||||
@@ -124,50 +124,59 @@ export function handleQueryChange(
|
||||
): Query {
|
||||
return {
|
||||
...supersetQuery,
|
||||
builder: {
|
||||
...supersetQuery.builder,
|
||||
queryData: supersetQuery.builder.queryData.map((query, index) => {
|
||||
const { dataSource } = query;
|
||||
const tempQuery = cloneDeep(initialQueryBuilderFormValuesMap[dataSource]);
|
||||
|
||||
const fieldsToSelect =
|
||||
panelTypeDataSourceFormValuesMap[newPanelType][dataSource].builder
|
||||
.queryData;
|
||||
|
||||
fieldsToSelect.forEach((field) => {
|
||||
set(tempQuery, field, supersetQuery.builder.queryData[index][field]);
|
||||
});
|
||||
|
||||
if (newPanelType === PANEL_TYPES.LIST) {
|
||||
set(tempQuery, 'aggregateOperator', 'noop');
|
||||
set(tempQuery, 'offset', 0);
|
||||
set(tempQuery, 'pageSize', 10);
|
||||
set(tempQuery, 'orderBy', undefined);
|
||||
} else if (tempQuery.aggregateOperator === 'noop') {
|
||||
// this condition takes care of the part where we start with the list panel type and then shift to other panels
|
||||
// because in other cases we never set list operator and other fields in superset query rather just update in the current / staged query
|
||||
set(tempQuery, 'aggregateOperator', 'count');
|
||||
unset(tempQuery, 'offset');
|
||||
unset(tempQuery, 'pageSize');
|
||||
}
|
||||
|
||||
if (
|
||||
currentPanelType === PANEL_TYPES.LIST &&
|
||||
newPanelType !== PANEL_TYPES.LIST
|
||||
) {
|
||||
set(tempQuery, 'orderBy', undefined);
|
||||
}
|
||||
|
||||
return tempQuery;
|
||||
}),
|
||||
queryFormulas: withHeatmapBucketOptions(
|
||||
supersetQuery.builder.queryFormulas,
|
||||
newPanelType,
|
||||
),
|
||||
queryTraceOperator:
|
||||
newPanelType === PANEL_TYPES.LIST || newPanelType === PANEL_TYPES.SCATTER
|
||||
? []
|
||||
: supersetQuery.builder.queryTraceOperator,
|
||||
},
|
||||
builder: rebuildBuilderForPanelType(
|
||||
newPanelType,
|
||||
supersetQuery.builder,
|
||||
currentPanelType,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
export function rebuildBuilderForPanelType(
|
||||
newPanelType: keyof PartialPanelTypes,
|
||||
builder: Query['builder'],
|
||||
currentPanelType: PANEL_TYPES,
|
||||
): Query['builder'] {
|
||||
return {
|
||||
...builder,
|
||||
queryData: builder.queryData.map((query, index) => {
|
||||
const { dataSource } = query;
|
||||
const tempQuery = cloneDeep(initialQueryBuilderFormValuesMap[dataSource]);
|
||||
|
||||
const fieldsToSelect =
|
||||
panelTypeDataSourceFormValuesMap[newPanelType][dataSource].builder
|
||||
.queryData;
|
||||
|
||||
fieldsToSelect.forEach((field) => {
|
||||
set(tempQuery, field, builder.queryData[index][field]);
|
||||
});
|
||||
|
||||
if (newPanelType === PANEL_TYPES.LIST) {
|
||||
set(tempQuery, 'aggregateOperator', 'noop');
|
||||
set(tempQuery, 'offset', 0);
|
||||
set(tempQuery, 'pageSize', 10);
|
||||
set(tempQuery, 'orderBy', undefined);
|
||||
} else if (tempQuery.aggregateOperator === 'noop') {
|
||||
// this condition takes care of the part where we start with the list panel type and then shift to other panels
|
||||
// because in other cases we never set list operator and other fields in superset query rather just update in the current / staged query
|
||||
set(tempQuery, 'aggregateOperator', 'count');
|
||||
unset(tempQuery, 'offset');
|
||||
unset(tempQuery, 'pageSize');
|
||||
}
|
||||
|
||||
if (
|
||||
currentPanelType === PANEL_TYPES.LIST &&
|
||||
newPanelType !== PANEL_TYPES.LIST
|
||||
) {
|
||||
set(tempQuery, 'orderBy', undefined);
|
||||
}
|
||||
|
||||
return tempQuery;
|
||||
}),
|
||||
queryFormulas: withHeatmapBucketOptions(builder.queryFormulas, newPanelType),
|
||||
queryTraceOperator:
|
||||
newPanelType === PANEL_TYPES.LIST || newPanelType === PANEL_TYPES.SCATTER
|
||||
? []
|
||||
: builder.queryTraceOperator,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
import {
|
||||
BuilderVariant,
|
||||
type Query,
|
||||
QueryMode,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
/** Which variant the `builder` slot holds, whatever query type is active. */
|
||||
export function getBuilderVariant(builder: Query['builder']): BuilderVariant {
|
||||
return builder.queryData[0]?.builderQueryType === QueryMode.AI_QUERY_BUILDER
|
||||
? BuilderVariant.AI
|
||||
: BuilderVariant.MAIN;
|
||||
}
|
||||
|
||||
/** The variant a tab authors; `undefined` for tabs that own their own slot. */
|
||||
export function toBuilderVariant(mode: QueryMode): BuilderVariant | undefined {
|
||||
if (mode === QueryMode.AI_QUERY_BUILDER) {
|
||||
return BuilderVariant.AI;
|
||||
}
|
||||
return mode === QueryMode.QUERY_BUILDER ? BuilderVariant.MAIN : undefined;
|
||||
}
|
||||
|
||||
/** The tab a query belongs to: its query type, or AI when a builder query carries the tag. */
|
||||
export function getQueryMode(query: Query): QueryMode {
|
||||
if (query.queryType !== QueryMode.QUERY_BUILDER) {
|
||||
return query.queryType;
|
||||
}
|
||||
return getBuilderVariant(query.builder) === BuilderVariant.AI
|
||||
? QueryMode.AI_QUERY_BUILDER
|
||||
: QueryMode.QUERY_BUILDER;
|
||||
}
|
||||
|
||||
/** Query Builder and AI both author `Query.builder`; the other modes own their own slot. */
|
||||
export function isBuilderMode(mode: QueryMode): boolean {
|
||||
return toBuilderVariant(mode) !== undefined;
|
||||
}
|
||||
|
||||
/** Drops the AI tag, leaving the same query readable as a plain builder query. */
|
||||
export function withoutAIQueryTag(query: Query): Query {
|
||||
if (getBuilderVariant(query.builder) !== BuilderVariant.AI) {
|
||||
return query;
|
||||
}
|
||||
return {
|
||||
...query,
|
||||
builder: {
|
||||
...query.builder,
|
||||
queryData: query.builder.queryData.map(
|
||||
({ builderQueryType: _tag, ...queryData }) => queryData,
|
||||
),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
@@ -102,6 +103,23 @@ describe('saveRecentQuery', () => {
|
||||
expect(store.list('metrics')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('saves from the AI slot when the query type is AI', () => {
|
||||
saveRecentQuery({
|
||||
queryType: EQueryType.AI_QUERY_BUILDER,
|
||||
builder: buildComposite([{ filter: { expression: "service.name = 'qb'" } }])
|
||||
.builder,
|
||||
builder_ai_query: buildComposite([
|
||||
{
|
||||
dataSource: DataSource.TRACES,
|
||||
filter: { expression: "service.name = 'ai'" },
|
||||
},
|
||||
]).builder,
|
||||
});
|
||||
|
||||
expect(store.list('logs')).toHaveLength(0);
|
||||
expect(store.list('traces')[0].filter.expression).toBe("service.name = 'ai'");
|
||||
});
|
||||
|
||||
it('is a no-op when the composite is null, undefined, or empty', () => {
|
||||
saveRecentQuery(null);
|
||||
saveRecentQuery(undefined);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { getBuilderSlotKeyForQueryType } from 'lib/query/builderSlot';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import type { SignalType } from 'types/api/v5/queryRange';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
import { validateQuery } from 'utils/queryValidationUtils';
|
||||
|
||||
import * as store from './recentQueriesStore';
|
||||
@@ -16,7 +18,9 @@ function toSignal(dataSource: IBuilderQuery['dataSource']): SignalType | null {
|
||||
}
|
||||
|
||||
type CompositeWithBuilder = {
|
||||
queryType?: EQueryType;
|
||||
builder?: { queryData?: IBuilderQuery[] };
|
||||
builder_ai_query?: { queryData?: IBuilderQuery[] };
|
||||
};
|
||||
|
||||
export function saveRecentQueryByExpression(
|
||||
@@ -43,13 +47,16 @@ export function saveRecentQueryByExpression(
|
||||
});
|
||||
}
|
||||
|
||||
// Persists each builder query in the composite as a recent entry. Call this
|
||||
// Persists each query of the composite's active builder as a recent entry. Call this
|
||||
// only from explicit user-driven Run triggers — reacting to stagedQuery or any
|
||||
// other derived state pollutes recents with navigation/refresh/go-to traffic.
|
||||
export function saveRecentQuery(
|
||||
query: CompositeWithBuilder | null | undefined,
|
||||
): void {
|
||||
const queryData = query?.builder?.queryData;
|
||||
const slotKey = getBuilderSlotKeyForQueryType(
|
||||
query?.queryType ?? EQueryType.QUERY_BUILDER,
|
||||
);
|
||||
const queryData = query?.[slotKey]?.queryData;
|
||||
if (!Array.isArray(queryData) || queryData.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -107,9 +107,13 @@ function JsonEditorDrawer({
|
||||
} else if (!readOnly && !validity.valid) {
|
||||
applyDisabledReason = 'Fix the JSON errors first';
|
||||
}
|
||||
const validationText = validity.valid
|
||||
? `Valid JSON · ${validity.lineCount} lines`
|
||||
: `Line ${validity.errorLine ?? '?'} · ${validity.message ?? 'Invalid JSON'}`;
|
||||
const errorText = validity.message ?? 'Invalid JSON';
|
||||
let validationText = `Valid JSON · ${validity.lineCount} lines`;
|
||||
if (!validity.valid) {
|
||||
validationText = validity.errorLine
|
||||
? `Line ${validity.errorLine} · ${errorText}`
|
||||
: errorText;
|
||||
}
|
||||
const plural = (n: number): string => (n === 1 ? '' : 's');
|
||||
const danglingWarning =
|
||||
danglingPanelIds.length > 0
|
||||
@@ -135,15 +139,17 @@ function JsonEditorDrawer({
|
||||
footer={
|
||||
<div className={styles.footer}>
|
||||
<div className={styles.footerStatus}>
|
||||
<Typography.Text
|
||||
className={cx(styles.validation, {
|
||||
[styles.validationValid]: validity.valid,
|
||||
[styles.validationInvalid]: !validity.valid,
|
||||
})}
|
||||
data-testid="json-editor-validation"
|
||||
>
|
||||
{validationText}
|
||||
</Typography.Text>
|
||||
<Tooltip title={validity.valid ? undefined : validationText}>
|
||||
<Typography.Text
|
||||
className={cx(styles.validation, {
|
||||
[styles.validationValid]: validity.valid,
|
||||
[styles.validationInvalid]: !validity.valid,
|
||||
})}
|
||||
data-testid="json-editor-validation"
|
||||
>
|
||||
{validationText}
|
||||
</Typography.Text>
|
||||
</Tooltip>
|
||||
{danglingWarning && (
|
||||
<Tooltip title={danglingPanelIds.join(', ')}>
|
||||
<span
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
import { fireEvent, render, screen, userEvent } from 'tests/test-utils';
|
||||
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import JsonEditorDrawer from '../JsonEditorDrawer';
|
||||
@@ -170,6 +170,36 @@ describe('JsonEditorDrawer', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('shows only the message when the error line is unknown', () => {
|
||||
mockUseJsonEditor.mockReturnValue(
|
||||
hookValue({
|
||||
validity: { valid: false, lineCount: 4, message: 'Bad value' },
|
||||
}),
|
||||
);
|
||||
render(<JsonEditorDrawer dashboard={dashboard} isOpen onClose={jest.fn()} />);
|
||||
|
||||
expect(screen.getByTestId('json-editor-validation')).toHaveTextContent(
|
||||
/^Bad value$/,
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the whole error on hover', async () => {
|
||||
const message = 'A long error that the footer cuts off';
|
||||
mockUseJsonEditor.mockReturnValue(
|
||||
hookValue({
|
||||
validity: { valid: false, lineCount: 4, errorLine: 2, message },
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<JsonEditorDrawer dashboard={dashboard} isOpen onClose={jest.fn()} />);
|
||||
|
||||
await user.hover(screen.getByTestId('json-editor-validation'));
|
||||
|
||||
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
|
||||
`Line 2 · ${message}`,
|
||||
);
|
||||
});
|
||||
|
||||
it('disables Apply when not dirty, invalid, or saving', () => {
|
||||
mockUseJsonEditor.mockReturnValue(hookValue({ isDirty: false }));
|
||||
const { rerender } = render(
|
||||
|
||||
@@ -95,6 +95,54 @@ describe('useJsonEditor', () => {
|
||||
expect(result.current.isDirty).toBe(true);
|
||||
});
|
||||
|
||||
const withDuration = (duration: unknown): string =>
|
||||
JSON.stringify({ ...redacted, spec: { ...redacted.spec, duration } });
|
||||
|
||||
it.each(['1s', '90s', '500ms', '0m', 'abc', '30m1h', '1m1m', 30])(
|
||||
'rejects a spec.duration of %p the time picker cannot open',
|
||||
(duration) => {
|
||||
const { result } = renderHook(() =>
|
||||
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),
|
||||
);
|
||||
|
||||
act(() => result.current.setDraft(withDuration(duration)));
|
||||
|
||||
expect(result.current.validity).toStrictEqual({
|
||||
valid: false,
|
||||
lineCount: 1,
|
||||
errorLine: 1,
|
||||
message:
|
||||
'"spec.duration" must be a whole number of minutes above zero, like 30m, 6h or 1d. The time picker has no seconds.',
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
['spec.duration', '{\n "spec": {\n "duration": "1s"\n }\n}', 3],
|
||||
['image', '{\n "spec": {},\n "image": "https://x.io/a.png"\n}', 3],
|
||||
])('points at the line of an invalid %s', (_field, draft, errorLine) => {
|
||||
const { result } = renderHook(() =>
|
||||
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),
|
||||
);
|
||||
|
||||
act(() => result.current.setDraft(draft));
|
||||
|
||||
expect(result.current.validity.errorLine).toBe(errorLine);
|
||||
});
|
||||
|
||||
it.each(['', '30m', '1h30m', '60s', '1y'])(
|
||||
'accepts a spec.duration of %p',
|
||||
(duration) => {
|
||||
const { result } = renderHook(() =>
|
||||
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),
|
||||
);
|
||||
|
||||
act(() => result.current.setDraft(withDuration(duration)));
|
||||
|
||||
expect(result.current.validity.valid).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it('format() pretty-prints valid JSON and leaves invalid JSON untouched', () => {
|
||||
const { result } = renderHook(() =>
|
||||
useJsonEditor({ dashboard, isOpen: true, onApplied: jest.fn() }),
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
import { escapeRegExp } from 'lodash-es';
|
||||
|
||||
// ponytail: a text match, not a JSON path, so an identical `"key": value` earlier
|
||||
// in the document wins. Switch to a JSON tree parser (jsonc-parser) if that bites.
|
||||
export function lineOfJsonEntry(
|
||||
source: string,
|
||||
key: string,
|
||||
value: unknown,
|
||||
): number | undefined {
|
||||
const entry = new RegExp(
|
||||
`"${escapeRegExp(key)}"\\s*:\\s*${escapeRegExp(JSON.stringify(value))}`,
|
||||
);
|
||||
const index = source.search(entry);
|
||||
return index < 0 ? undefined : source.slice(0, index).split('\n').length;
|
||||
}
|
||||
@@ -12,8 +12,10 @@ import { toAPIError } from 'utils/errorUtils';
|
||||
|
||||
import { dashboardToUpdatable } from './dashboardToUpdatable';
|
||||
import { findPanelLayoutIssues } from './danglingPanels';
|
||||
import { lineOfJsonEntry } from './lineOfJsonEntry';
|
||||
import { compactSpecLayouts } from '../../layoutCompaction';
|
||||
import { isValidDashboardImage } from '../../dashboardIcons';
|
||||
import { dashboardDurationError } from '../../utils/dashboardDuration';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
|
||||
export interface JsonValidity {
|
||||
@@ -109,7 +111,7 @@ export function useJsonEditor({
|
||||
|
||||
const validity = useMemo<JsonValidity>(() => {
|
||||
const lineCount = draft.split('\n').length;
|
||||
let parsed: { image?: unknown };
|
||||
let parsed: { image?: unknown; spec?: { duration?: unknown } };
|
||||
try {
|
||||
parsed = JSON.parse(draft);
|
||||
} catch (error) {
|
||||
@@ -131,10 +133,21 @@ export function useJsonEditor({
|
||||
return {
|
||||
valid: false,
|
||||
lineCount,
|
||||
errorLine: lineOfJsonEntry(draft, 'image', image),
|
||||
message:
|
||||
'"image" must be an /assets/Icons/<name> or /assets/Logos/<name> path, or a base64 image data URI',
|
||||
};
|
||||
}
|
||||
const duration = parsed.spec?.duration;
|
||||
const durationError = dashboardDurationError(duration);
|
||||
if (durationError) {
|
||||
return {
|
||||
valid: false,
|
||||
lineCount,
|
||||
errorLine: lineOfJsonEntry(draft, 'duration', duration),
|
||||
message: durationError,
|
||||
};
|
||||
}
|
||||
return { valid: true, lineCount };
|
||||
}, [draft]);
|
||||
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
.infoItemContainer {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.infoTitle {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.defaultTimeRangeInput {
|
||||
[data-radix-popper-content-wrapper] {
|
||||
z-index: 1100 !important;
|
||||
}
|
||||
|
||||
// Radix sets --radix-select-trigger-width on the content element (the wrapper's
|
||||
// child), so match it there to make the dropdown take the trigger's width.
|
||||
[data-radix-popper-content-wrapper] > * {
|
||||
width: var(--radix-select-trigger-width);
|
||||
min-width: var(--radix-select-trigger-width);
|
||||
}
|
||||
}
|
||||
|
||||
.defaultTimeRangeSelect {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.infoHint {
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { SelectSimple } from '@signozhq/ui/select';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import { buildDefaultTimeRangeItems, DEFAULT_TIME_RANGE_UNSET } from '../utils';
|
||||
import settingsStyles from '../../DashboardSettings.module.scss';
|
||||
import styles from './DefaultTimeRange.module.scss';
|
||||
|
||||
interface DefaultTimeRangeProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
}
|
||||
|
||||
function DefaultTimeRange({
|
||||
value,
|
||||
onChange,
|
||||
}: DefaultTimeRangeProps): JSX.Element {
|
||||
return (
|
||||
<div className={settingsStyles.settingsCard}>
|
||||
<div className={styles.infoItemContainer}>
|
||||
<Typography className={styles.infoTitle}>Default time range</Typography>
|
||||
<section className={styles.defaultTimeRangeInput}>
|
||||
<SelectSimple
|
||||
className={styles.defaultTimeRangeSelect}
|
||||
testId="dashboard-default-time-range"
|
||||
items={buildDefaultTimeRangeItems(value)}
|
||||
value={value && value !== '30m' ? value : DEFAULT_TIME_RANGE_UNSET}
|
||||
withPortal={false}
|
||||
onChange={(value): void =>
|
||||
onChange(value === DEFAULT_TIME_RANGE_UNSET ? '' : (value as string))
|
||||
}
|
||||
/>
|
||||
</section>
|
||||
<Typography className={styles.infoHint}>
|
||||
Applies by default when a viewer opens the dashboard for the first time.
|
||||
</Typography>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default DefaultTimeRange;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user