Skip to content

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

feat(query-search-v2): add initial expression support & store to manage (#11062)

Vinicius Lourençode6e4890ae61
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/QuerySearchV2.provider.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/QuerySearchV2.provider.tsx
new file mode 100644
index 0000000000..70065dd4a5
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/QuerySearchV2.provider.tsx
@@ -0,0 +1,126 @@
+import { ReactNode, useCallback, useEffect, useMemo, useRef } from 'react';
+import { parseAsString, useQueryState } from 'nuqs';
+import { useStore } from 'zustand';
+
+import {
+ combineInitialAndUserExpression,
+ getUserExpressionFromCombined,
+} from '../utils';
+import { QuerySearchV2Context } from './context';
+import type { QuerySearchV2ContextValue } from './QuerySearchV2.store';
+import { createExpressionStore } from './QuerySearchV2.store';
+
+export interface QuerySearchV2ProviderProps {
+ queryParamKey: string;
+ initialExpression?: string;
+ /**
+ * @default false
+ */
+ persistOnUnmount?: boolean;
+ children: ReactNode;
+}
+
+/**
+ * Provider component that creates a scoped zustand store and exposes
+ * expression state to children via context.
+ */
+export function QuerySearchV2Provider({
+ initialExpression = '',
+ persistOnUnmount = false,
+ queryParamKey,
+ children,
+}: QuerySearchV2ProviderProps): JSX.Element {
+ const storeRef = useRef(createExpressionStore());
+ const store = storeRef.current;
+
+ const [urlExpression, setUrlExpression] = useQueryState(
+ queryParamKey,
+ parseAsString,
+ );
+
+ const committedExpression = useStore(store, (s) => s.committedExpression);
+ const setInputExpression = useStore(store, (s) => s.setInputExpression);
+ const commitExpression = useStore(store, (s) => s.commitExpression);
+ const initializeFromUrl = useStore(store, (s) => s.initializeFromUrl);
+ const resetExpression = useStore(store, (s) => s.resetExpression);
+
+ const isInitialized = useRef(false);
+ useEffect(() => {
+ if (!isInitialized.current && urlExpression) {
+ const cleanedExpression = getUserExpressionFromCombined(
+ initialExpression,
+ urlExpression,
+ );
+ initializeFromUrl(cleanedExpression);
+ isInitialized.current = true;
+ }
+ }, [urlExpression, initialExpression, initializeFromUrl]);
+
+ useEffect(() => {
+ if (isInitialized.current || !urlExpression) {
+ setUrlExpression(committedExpression || null);
+ }
+ }, [committedExpression, setUrlExpression, urlExpression]);
+
+ useEffect(() => {
+ return (): void => {
+ if (!persistOnUnmount) {
+ setUrlExpression(null);
+ resetExpression();
+ }
+ };
+ }, [persistOnUnmount, setUrlExpression, resetExpression]);
+
+ const handleChange = useCallback(
+ (expression: string): void => {
+ const userOnly = getUserExpressionFromCombined(
+ initialExpression,
+ expression,
+ );
+ setInputExpression(userOnly);
+ },
+ [initialExpression, setInputExpression],
+ );
+
+ const handleRun = useCallback(
+ (expression: string): void => {
+ const userOnly = getUserExpressionFromCombined(
+ initialExpression,
+ expression,
+ );
+ commitExpression(userOnly);
+ },
+ [initialExpression, commitExpression],
+ );
+
+ const combinedExpression = useMemo(
+ () => combineInitialAndUserExpression(initialExpression, committedExpression),
+ [initialExpression, committedExpression],
+ );
+
+ const contextValue = useMemo<QuerySearchV2ContextValue>(
+ () => ({
+ expression: combinedExpression,
+ userExpression: committedExpression,
+ initialExpression,
+ querySearchProps: {
+ initialExpression: initialExpression.trim() ? initialExpression : undefined,
+ onChange: handleChange,
+ onRun: handleRun,
+ },
+ }),
+ [
+ combinedExpression,
+ committedExpression,
+ initialExpression,
+ handleChange,
+ handleRun,
+ ],
+ );
+
+ return (
+ <QuerySearchV2Context.Provider value={contextValue}>
+ {children}
+ </QuerySearchV2Context.Provider>
+ );
+}
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/QuerySearchV2.store.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/QuerySearchV2.store.ts
new file mode 100644
index 0000000000..5ea1a82d44
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/QuerySearchV2.store.ts
@@ -0,0 +1,60 @@
+import { createStore, StoreApi } from 'zustand';
+
+export type QuerySearchV2Store = {
+ /**
+ * User-typed expression (local state, updates on typing)
+ */
+ inputExpression: string;
+ /**
+ * Committed expression (synced to URL, updates on submit)
+ */
+ committedExpression: string;
+ setInputExpression: (expression: string) => void;
+ commitExpression: (expression: string) => void;
+ resetExpression: () => void;
+ initializeFromUrl: (urlExpression: string) => void;
+};
+
+export interface QuerySearchProps {
+ initialExpression: string | undefined;
+ onChange: (expression: string) => void;
+ onRun: (expression: string) => void;
+}
+
+export interface QuerySearchV2ContextValue {
+ /**
+ * Combined expression: "initialExpression AND (userExpression)"
+ */
+ expression: string;
+ userExpression: string;
+ initialExpression: string;
+ querySearchProps: QuerySearchProps;
+}
+
+export function createExpressionStore(): StoreApi<QuerySearchV2Store> {
+ return createStore<QuerySearchV2Store>((set) => ({
+ inputExpression: '',
+ committedExpression: '',
+ setInputExpression: (expression: string): void => {
+ set({ inputExpression: expression });
+ },
+ commitExpression: (expression: string): void => {
+ set({
+ inputExpression: expression,
+ committedExpression: expression,
+ });
+ },
+ resetExpression: (): void => {
+ set({
+ inputExpression: '',
+ committedExpression: '',
+ });
+ },
+ initializeFromUrl: (urlExpression: string): void => {
+ set({
+ inputExpression: urlExpression,
+ committedExpression: urlExpression,
+ });
+ },
+ }));
+}
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/__tests__/QuerySearchExpressionProvider.test.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/__tests__/QuerySearchExpressionProvider.test.tsx
new file mode 100644
index 0000000000..cedfe57ebb
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/__tests__/QuerySearchExpressionProvider.test.tsx
@@ -0,0 +1,95 @@
+import { ReactNode } from 'react';
+import { act, renderHook } from '@testing-library/react';
+
+import { useQuerySearchV2Context } from '../context';
+import {
+ QuerySearchV2Provider,
+ QuerySearchV2ProviderProps,
+} from '../QuerySearchV2.provider';
+
+const mockSetQueryState = jest.fn();
+let mockUrlValue: string | null = null;
+
+jest.mock('nuqs', () => ({
+ parseAsString: {},
+ useQueryState: jest.fn(() => [mockUrlValue, mockSetQueryState]),
+}));
+
+function createWrapper(
+ props: Partial<QuerySearchV2ProviderProps> = {},
+): ({ children }: { children: ReactNode }) => JSX.Element {
+ return function Wrapper({ children }: { children: ReactNode }): JSX.Element {
+ return (
+ <QuerySearchV2Provider queryParamKey="testExpression" {...props}>
+ {children}
+ </QuerySearchV2Provider>
+ );
+ };
+}
+
+describe('QuerySearchExpressionProvider', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockUrlValue = null;
+ });
+
+ it('should provide initial context values', () => {
+ const { result } = renderHook(() => useQuerySearchV2Context(), {
+ wrapper: createWrapper(),
+ });
+
+ expect(result.current.expression).toBe('');
+ expect(result.current.userExpression).toBe('');
+ expect(result.current.initialExpression).toBe('');
+ });
+
+ it('should combine initialExpression with userExpression', () => {
+ const { result } = renderHook(() => useQuerySearchV2Context(), {
+ wrapper: createWrapper({ initialExpression: 'k8s.pod.name = "my-pod"' }),
+ });
+
+ expect(result.current.expression).toBe('k8s.pod.name = "my-pod"');
+ expect(result.current.initialExpression).toBe('k8s.pod.name = "my-pod"');
+
+ act(() => {
+ result.current.querySearchProps.onChange('service = "api"');
+ });
+ act(() => {
+ result.current.querySearchProps.onRun('service = "api"');
+ });
+
+ expect(result.current.expression).toBe(
+ 'k8s.pod.name = "my-pod" AND (service = "api")',
+ );
+ expect(result.current.userExpression).toBe('service = "api"');
+ });
+
+ it('should provide querySearchProps with correct callbacks', () => {
+ const { result } = renderHook(() => useQuerySearchV2Context(), {
+ wrapper: createWrapper({ initialExpression: 'initial' }),
+ });
+
+ expect(result.current.querySearchProps.initialExpression).toBe('initial');
+ expect(typeof result.current.querySearchProps.onChange).toBe('function');
+ expect(typeof result.current.querySearchProps.onRun).toBe('function');
+ });
+
+ it('should initialize from URL value on mount', () => {
+ mockUrlValue = 'status = 500';
+
+ const { result } = renderHook(() => useQuerySearchV2Context(), {
+ wrapper: createWrapper(),
+ });
+
+ expect(result.current.userExpression).toBe('status = 500');
+ expect(result.current.expression).toBe('status = 500');
+ });
+
+ it('should throw error when used outside provider', () => {
+ expect(() => {
+ renderHook(() => useQuerySearchV2Context());
+ }).toThrow(
+ 'useQuerySearchV2Context must be used within a QuerySearchV2Provider',
+ );
+ });
+});
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/__tests__/store.test.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/__tests__/store.test.ts
new file mode 100644
index 0000000000..f0b24f781a
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/__tests__/store.test.ts
@@ -0,0 +1,61 @@
+import { createExpressionStore } from '../QuerySearchV2.store';
+
+describe('createExpressionStore', () => {
+ it('should create a store with initial state', () => {
+ const store = createExpressionStore();
+ const state = store.getState();
+
+ expect(state.inputExpression).toBe('');
+ expect(state.committedExpression).toBe('');
+ });
+
+ it('should update inputExpression via setInputExpression', () => {
+ const store = createExpressionStore();
+
+ store.getState().setInputExpression('service.name = "api"');
+
+ expect(store.getState().inputExpression).toBe('service.name = "api"');
+ expect(store.getState().committedExpression).toBe('');
+ });
+
+ it('should update both expressions via commitExpression', () => {
+ const store = createExpressionStore();
+
+ store.getState().setInputExpression('service.name = "api"');
+ store.getState().commitExpression('service.name = "api"');
+
+ expect(store.getState().inputExpression).toBe('service.name = "api"');
+ expect(store.getState().committedExpression).toBe('service.name = "api"');
+ });
+
+ it('should reset all state via resetExpression', () => {
+ const store = createExpressionStore();
+
+ store.getState().setInputExpression('service.name = "api"');
+ store.getState().commitExpression('service.name = "api"');
+ store.getState().resetExpression();
+
+ expect(store.getState().inputExpression).toBe('');
+ expect(store.getState().committedExpression).toBe('');
+ });
+
+ it('should initialize from URL value', () => {
+ const store = createExpressionStore();
+
+ store.getState().initializeFromUrl('status = 500');
+
+ expect(store.getState().inputExpression).toBe('status = 500');
+ expect(store.getState().committedExpression).toBe('status = 500');
+ });
+
+ it('should create isolated store instances', () => {
+ const store1 = createExpressionStore();
+ const store2 = createExpressionStore();
+
+ store1.getState().setInputExpression('expr1');
+ store2.getState().setInputExpression('expr2');
+
+ expect(store1.getState().inputExpression).toBe('expr1');
+ expect(store2.getState().inputExpression).toBe('expr2');
+ });
+});
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/context.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/context.ts
new file mode 100644
index 0000000000..cfb43b411c
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/context.ts
@@ -0,0 +1,17 @@
+// eslint-disable-next-line no-restricted-imports -- React Context required for scoped store pattern
+import { createContext, useContext } from 'react';
+
+import type { QuerySearchV2ContextValue } from './QuerySearchV2.store';
+
+export const QuerySearchV2Context =
+ createContext<QuerySearchV2ContextValue | null>(null);
+
+export function useQuerySearchV2Context(): QuerySearchV2ContextValue {
+ const context = useContext(QuerySearchV2Context);
+ if (!context) {
+ throw new Error(
+ 'useQuerySearchV2Context must be used within a QuerySearchV2Provider',
+ );
+ }
+ return context;
+}
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/index.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/index.ts
new file mode 100644
index 0000000000..4e2315de01
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/Provider/index.ts
@@ -0,0 +1,8 @@
+export { useQuerySearchV2Context } from './context';
+export type { QuerySearchV2ProviderProps } from './QuerySearchV2.provider';
+export { QuerySearchV2Provider } from './QuerySearchV2.provider';
+export type {
+ QuerySearchProps,
+ QuerySearchV2ContextValue,
+ QuerySearchV2Store,
+} from './QuerySearchV2.store';
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss
index 079a945a52..4eb2fdf0d6 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss
@@ -19,6 +19,13 @@
display: flex;
flex-direction: row;
+ .query-search-initial-scope-label {
+ position: absolute;
+ left: 8px;
+ top: 10px;
+ z-index: 10;
+ }
+
.query-where-clause-editor {
flex: 1;
min-width: 400px;
@@ -53,6 +60,10 @@
}
}
}
+
+ &.hasInitialExpression .cm-editor .cm-content {
+ padding-left: 22px !important;
+ }
}
.cm-editor {
@@ -68,7 +79,6 @@
border-radius: 2px;
border: 1px solid var(--l1-border);
padding: 0px !important;
- background-color: var(--l1-background) !important;
&:focus-within {
border-color: var(--l1-border);
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
index d5707159e3..ac7fa69612 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
@@ -30,7 +30,7 @@ import { useDashboardVariablesByType } from 'hooks/dashboard/useDashboardVariabl
import { useIsDarkMode } from 'hooks/useDarkMode';
import useDebounce from 'hooks/useDebounce';
import { debounce, isNull } from 'lodash-es';
-import { Info, TriangleAlert } from 'lucide-react';
+import { Filter, Info, TriangleAlert } from 'lucide-react';
import {
IDetailedError,
IQueryContext,
@@ -47,6 +47,7 @@ import { validateQuery } from 'utils/queryValidationUtils';
import { unquote } from 'utils/stringUtils';
import { queryExamples } from './constants';
+import { combineInitialAndUserExpression } from './utils';
import './QuerySearch.styles.scss';
@@ -85,6 +86,8 @@ interface QuerySearchProps {
hardcodedAttributeKeys?: QueryKeyDataSuggestionsProps[];
onRun?: (query: string) => void;
showFilterSuggestionsWithoutMetric?: boolean;
+ /** When set, the editor shows only the user expression; API/filter uses `initial AND (user)`. */
+ initialExpression?: string;
}
function QuerySearch({
@@ -96,6 +99,7 @@ function QuerySearch({
signalSource,
hardcodedAttributeKeys,
showFilterSuggestionsWithoutMetric,
+ initialExpression,
}: QuerySearchProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const [valueSuggestions, setValueSuggestions] = useState<any[]>([]);
@@ -112,18 +116,26 @@ function QuerySearch({
const [isFocused, setIsFocused] = useState(false);
const editorRef = useRef<EditorView | null>(null);
- const handleQueryValidation = useCallback((newExpression: string): void => {
- try {
- const validationResponse = validateQuery(newExpression);
- setValidation(validationResponse);
- } catch (error) {
- setValidation({
- isValid: false,
- message: 'Failed to process query',
- errors: [error as IDetailedError],
- });
- }
- }, []);
+ const isScopedFilter = initialExpression !== undefined;
+
+ const validateExpressionForEditor = useCallback(
+ (editorDoc: string): void => {
+ const toValidate = isScopedFilter
+ ? combineInitialAndUserExpression(initialExpression ?? '', editorDoc)
+ : editorDoc;
+ try {
+ const validationResponse = validateQuery(toValidate);
+ setValidation(validationResponse);
+ } catch (error) {
+ setValidation({
+ isValid: false,
+ message: 'Failed to process query',
+ errors: [error as IDetailedError],
+ });
+ }
+ },
+ [initialExpression, isScopedFilter],
+ );
const getCurrentExpression = useCallback(
(): string => editorRef.current?.state.doc.toString() || '',
@@ -165,6 +177,8 @@ function QuerySearch({
setIsEditorReady(true);
}, []);
+ const prevQueryDataExpressionRef = useRef<string | undefined>();
+
useEffect(
() => {
if (!isEditorReady) {
@@ -173,13 +187,22 @@ function QuerySearch({
const newExpression = queryData.filter?.expression || '';
const currentExpression = getCurrentExpression();
+ const prevExpression = prevQueryDataExpressionRef.current;
+
+ // Only sync editor when queryData.filter?.expression actually changed from external source
+ // Not when focus changed (which would reset uncommitted user input)
+ const queryDataExpressionChanged = prevExpression !== newExpression;
+ prevQueryDataExpressionRef.current = newExpression;
- // Do not update codemirror editor if the expression is the same
- if (newExpression !== currentExpression && !isFocused) {
+ if (
+ queryDataExpressionChanged &&
+ newExpression !== currentExpression &&
+ !isFocused
+ ) {
updateEditorValue(newExpression, { skipOnChange: true });
- if (newExpression) {
- handleQueryValidation(newExpression);
- }
+ }
+ if (!isFocused) {
+ validateExpressionForEditor(currentExpression);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -284,7 +307,7 @@ function QuerySearch({
}
});
}
- setKeySuggestions(Array.from(merged.values()));
+ setKeySuggestions([...merged.values()]);
// Force reopen the completion if editor is available and focused
if (editorRef.current) {
@@ -337,7 +360,7 @@ function QuerySearch({
// If value contains single quotes, escape them and wrap in single quotes
if (value.includes("'")) {
// Replace single quotes with escaped single quotes
- const escapedValue = value.replace(/'/g, "\\'");
+ const escapedValue = value.replaceAll(/'/g, "\\'");
return `'${escapedValue}'`;
}
@@ -614,7 +637,7 @@ function QuerySearch({
const handleBlur = (): void => {
const currentExpression = getCurrentExpression();
- handleQueryValidation(currentExpression);
+ validateExpressionForEditor(currentExpression);
setIsFocused(false);
};
@@ -632,7 +655,6 @@ function QuerySearch({
);
const handleExampleClick = (exampleQuery: string): void => {
- // If there's an existing query, append the example with AND
const currentExpression = getCurrentExpression();
const newExpression = currentExpression
? `${currentExpression} AND ${exampleQuery}`
@@ -897,12 +919,12 @@ function QuerySearch({
// If we have previous pairs, we can prioritize keys that haven't been used yet
if (queryContext.queryPairs && queryContext.queryPairs.length > 0) {
- const usedKeys = queryContext.queryPairs.map((pair) => pair.key);
+ const usedKeys = new Set(queryContext.queryPairs.map((pair) => pair.key));
// Add boost to unused keys to prioritize them
options = options.map((option) => ({
...option,
- boost: usedKeys.includes(option.label) ? -10 : 10,
+ boost: usedKeys.has(option.label) ? -10 : 10,
}));
}
@@ -1317,6 +1339,19 @@ function QuerySearch({
)}
<div className="query-where-clause-editor-container">
+ {isScopedFilter ? (
+ <Tooltip title={initialExpression || ''} placement="left">
+ <div className="query-search-initial-scope-label">
+ <Filter
+ size={14}
+ style={{
+ opacity: 0.9,
+ color: isDarkMode ? Color.BG_VANILLA_100 : Color.BG_INK_500,
+ }}
+ />
+ </div>
+ </Tooltip>
+ ) : null}
<Tooltip
title={<div data-log-detail-ignore="true">{getTooltipContent()}</div>}
placement="left"
@@ -1356,6 +1391,7 @@ function QuerySearch({
className={cx('query-where-clause-editor', {
isValid: validation.isValid === true,
hasErrors: validation.errors.length > 0,
+ hasInitialExpression: isScopedFilter,
})}
extensions={[
autocompletion({
@@ -1390,7 +1426,12 @@ function QuerySearch({
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
run: (): boolean => {
if (onRun && typeof onRun === 'function') {
- onRun(getCurrentExpression());
+ const user = getCurrentExpression();
+ onRun(
+ isScopedFilter
+ ? combineInitialAndUserExpression(initialExpression ?? '', user)
+ : user,
+ );
}
return true;
},
@@ -1555,6 +1596,7 @@ QuerySearch.defaultProps = {
placeholder:
"Enter your filter query (e.g., http.status_code >= 500 AND service.name = 'frontend')",
showFilterSuggestionsWithoutMetric: false,
+ initialExpression: undefined,
};
export default QuerySearch;
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.ts
new file mode 100644
index 0000000000..482194b5b6
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/__tests__/utils.ts
@@ -0,0 +1,58 @@
+import {
+ combineInitialAndUserExpression,
+ getUserExpressionFromCombined,
+} from '../utils';
+
+describe('entityLogsExpression', () => {
+ describe('combineInitialAndUserExpression', () => {
+ it('returns user when initial is empty', () => {
+ expect(combineInitialAndUserExpression('', 'body contains error')).toBe(
+ 'body contains error',
+ );
+ });
+
+ it('returns initial when user is empty', () => {
+ expect(combineInitialAndUserExpression('k8s.pod.name = "x"', '')).toBe(
+ 'k8s.pod.name = "x"',
+ );
+ });
+
+ it('wraps user in parentheses with AND', () => {
+ expect(
+ combineInitialAndUserExpression('k8s.pod.name = "x"', 'body = "a"'),
+ ).toBe('k8s.pod.name = "x" AND (body = "a")');
+ });
+ });
+
+ describe('getUserExpressionFromCombined', () => {
+ it('returns empty when combined equals initial', () => {
+ expect(
+ getUserExpressionFromCombined('k8s.pod.name = "x"', 'k8s.pod.name = "x"'),
+ ).toBe('');
+ });
+
+ it('extracts user from wrapped form', () => {
+ expect(
+ getUserExpressionFromCombined(
+ 'k8s.pod.name = "x"',
+ 'k8s.pod.name = "x" AND (body = "a")',
+ ),
+ ).toBe('body = "a"');
+ });
+
+ it('extracts user from legacy AND without parens', () => {
+ expect(
+ getUserExpressionFromCombined(
+ 'k8s.pod.name = "x"',
+ 'k8s.pod.name = "x" AND body = "a"',
+ ),
+ ).toBe('body = "a"');
+ });
+
+ it('returns full combined when initial is empty', () => {
+ expect(getUserExpressionFromCombined('', 'service.name = "a"')).toBe(
+ 'service.name = "a"',
+ );
+ });
+ });
+});
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts
new file mode 100644
index 0000000000..6f75e92e33
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts
@@ -0,0 +1,40 @@
+export function combineInitialAndUserExpression(
+ initial: string,
+ user: string,
+): string {
+ const i = initial.trim();
+ const u = user.trim();
+ if (!i) {
+ return u;
+ }
+ if (!u) {
+ return i;
+ }
+ return `${i} AND (${u})`;
+}
+
+export function getUserExpressionFromCombined(
+ initial: string,
+ combined: string | null | undefined,
+): string {
+ const i = initial.trim();
+ const c = (combined ?? '').trim();
+ if (!c) {
+ return '';
+ }
+ if (!i) {
+ return c;
+ }
+ if (c === i) {
+ return '';
+ }
+ const wrappedPrefix = `${i} AND (`;
+ if (c.startsWith(wrappedPrefix) && c.endsWith(')')) {
+ return c.slice(wrappedPrefix.length, -1);
+ }
+ const plainPrefix = `${i} AND `;
+ if (c.startsWith(plainPrefix)) {
+ return c.slice(plainPrefix.length);
+ }
+ return c;
+}
diff --git a/frontend/src/components/QueryBuilderV2/index.ts b/frontend/src/components/QueryBuilderV2/index.ts
new file mode 100644
index 0000000000..cab4d564bd
--- /dev/null
+++ b/frontend/src/components/QueryBuilderV2/index.ts
@@ -0,0 +1,14 @@
+export type {
+ QuerySearchProps,
+ QuerySearchV2ContextValue,
+ QuerySearchV2ProviderProps,
+} from './QueryV2/QuerySearch/Provider';
+export {
+ QuerySearchV2Provider,
+ useQuerySearchV2Context,
+} from './QueryV2/QuerySearch/Provider';
+export { QueryBuilderV2 } from './QueryBuilderV2';
+export {
+ QueryBuilderV2Provider,
+ useQueryBuilderV2Context,
+} from './QueryBuilderV2Context';