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: show recent queries to user (#11523)

Gaurav Tewari7b2882abdeeb
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss
index 4eb2fdf0d6..2074c145c8 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.styles.scss
@@ -1,5 +1,11 @@
// TODO: Improve the styling of the query aggregation container and its components. - @YounixM , @H4ad
+$dropdown-base-height: 250px;
+$recents-header-height: 30px;
+$recent-row-height: 36px;
+// how many recents are rendered, this caps how tall the dropdown can grow to fit them.
+$max-recents-shown: 5;
+
.code-mirror-where-clause {
width: 100%;
display: flex;
@@ -117,7 +123,23 @@
width: 100% !important;
max-width: 100% !important;
font-family: 'Space Mono', monospace !important;
- min-height: 200px !important;
+ max-height: $dropdown-base-height !important;
+ overflow-y: auto !important;
+
+ // Recents render at the top of the dropdown ahead of regular suggestions.
+ // At the base max-height, having recents in view would crowd out the
+ // suggestion list below. This loop grows the dropdown by one row's worth
+ // of height for every recent present (up to $max-recents-shown), plus the
+ // section header. `:has(> li:nth-of-type(N) .cm-completionIcon-recent)`
+ // matches when the Nth child of <ul> is a recent — i.e. there are at
+ // least N recents visible.
+ @for $i from 1 through $max-recents-shown {
+ &:has(> li:nth-of-type(#{$i}) .cm-completionIcon-recent) {
+ max-height: $dropdown-base-height +
+ $recents-header-height +
+ ($i * $recent-row-height) !important;
+ }
+ }
&::-webkit-scrollbar {
width: 0.3rem;
@@ -133,6 +155,19 @@
background: transparent;
}
+ completion-section {
+ display: block;
+ padding: 10px 12px 6px;
+ font-size: 10px !important;
+ font-weight: 700;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--l3-foreground, var(--l2-foreground));
+ opacity: 0.7;
+ border-bottom: 0;
+ background-color: transparent;
+ }
+
li {
width: 100% !important;
max-width: 100% !important;
@@ -159,11 +194,78 @@
display: none !important;
}
+ .cm-completionDetail {
+ margin-left: auto;
+ font-style: normal;
+ font-size: var(--periscope-font-size-small, 11px);
+ font-weight: 600;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ opacity: 0.55;
+ }
+
&[aria-selected='true'] {
background: var(--l3-background) !important;
font-weight: 600 !important;
}
}
+
+ li:has(.cm-completionIcon-recent) {
+ &:hover .cm-recent-delete,
+ &[aria-selected='true'] .cm-recent-delete {
+ opacity: 1;
+ }
+ }
+
+ li .cm-completionLabel {
+ flex: 1;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+
+ .cm-recent-delete {
+ margin-left: 8px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ padding: 0;
+ border: 0;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--l2-foreground);
+ font-size: 18px;
+ line-height: 1;
+ cursor: pointer;
+ opacity: 0.5;
+ transition:
+ opacity 0.12s ease,
+ background-color 0.12s ease;
+
+ &:hover {
+ opacity: 1;
+ background: color-mix(in srgb, var(--l2-foreground) 18%, transparent);
+ }
+ }
+ }
+
+ &::after {
+ content: '↓↑ to navigate · ↵ to apply · esc to dismiss';
+ display: block;
+ padding: 8px 12px;
+ border-top: 1px solid var(--l1-border);
+ font-family: 'Space Mono', monospace;
+ font-size: 11px;
+ font-weight: 500;
+ letter-spacing: 0.02em;
+ color: var(--l2-foreground);
+ opacity: 0.6;
+ background: color-mix(in srgb, var(--l1-background) 50%, transparent);
+ border-bottom-left-radius: 4px;
+ border-bottom-right-radius: 4px;
}
}
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
index 8e7e5fc246..4a45128283 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch.tsx
@@ -46,8 +46,15 @@ import {
import { validateQuery } from 'utils/queryValidationUtils';
import { unquote } from 'utils/stringUtils';
-import { queryExamples } from './constants';
-import { combineInitialAndUserExpression } from './utils';
+import { getRecentQueries } from 'lib/recentQueries/getRecentQueries';
+import type { SignalType } from 'types/api/v5/queryRange';
+
+import { queryExamples, SUGGESTIONS_SECTION } from './constants';
+import {
+ combineInitialAndUserExpression,
+ getRecentOptions,
+ renderRecentDeleteButton,
+} from './utils';
import './QuerySearch.styles.scss';
@@ -1250,6 +1257,41 @@ function QuerySearch({
};
}
+ const signal = dataSource as SignalType;
+
+ function combinedSuggestions(
+ context: CompletionContext,
+ ): CompletionResult | null {
+ const fullDoc = context.state.doc.toString();
+ const recentOptions = getRecentOptions(
+ getRecentQueries(signal, signalSource ?? ''),
+ fullDoc,
+ );
+ const result = autoSuggestions(context);
+
+ const suggestionOptions = (result?.options || []).map((opt) => ({
+ ...opt,
+ section: SUGGESTIONS_SECTION,
+ }));
+
+ if (recentOptions.length === 0 && suggestionOptions.length === 0) {
+ return result;
+ }
+
+ if (!result) {
+ return {
+ from: 0,
+ to: fullDoc.length,
+ options: recentOptions,
+ };
+ }
+
+ return {
+ ...result,
+ options: [...recentOptions, ...suggestionOptions],
+ };
+ }
+
// Effect to handle focus state and trigger suggestions
useEffect(() => {
const clearTimeout = toggleSuggestions(10);
@@ -1398,11 +1440,12 @@ function QuerySearch({
})}
extensions={[
autocompletion({
- override: [autoSuggestions],
+ override: [combinedSuggestions],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
+ addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.ts
index 7ba9d3d866..251ffdceea 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.ts
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/constants.ts
@@ -1,3 +1,14 @@
+export const RECENTS_SECTION = { name: 'Recent searches', rank: 1 } as const;
+export const SUGGESTIONS_SECTION = { name: 'Suggestions', rank: 2 } as const;
+
+// Custom CodeMirror Completion.type for recent-query entries. Used to discriminate
+// recents from regular autocomplete completions in renderers and event handlers.
+export const RECENT_COMPLETION_TYPE = 'recent';
+
+// Max number of recents rendered in the autocomplete dropdown.
+// Do change $max-recents-shown: in QuerySearch.styles.scss if you change this.
+export const RECENTS_DISPLAY_CAP = 5;
+
export const queryExamples = [
{
label: 'Basic Query',
diff --git a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts
index 6f75e92e33..8705fd3eb1 100644
--- a/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts
+++ b/frontend/src/components/QueryBuilderV2/QueryV2/QuerySearch/utils.ts
@@ -1,3 +1,19 @@
+import { closeCompletion, startCompletion } from '@codemirror/autocomplete';
+import type { Completion } from '@codemirror/autocomplete';
+import type { EditorView } from '@uiw/react-codemirror';
+import dayjs from 'dayjs';
+import { normalizeFilterExpression } from 'lib/recentQueries/normalize';
+import * as recentQueriesStore from 'lib/recentQueries/recentQueriesStore';
+import type { RecentQueryEntry } from 'lib/recentQueries/types';
+import type { SignalType } from 'types/api/v5/queryRange';
+import 'utils/timeUtils';
+
+import {
+ RECENT_COMPLETION_TYPE,
+ RECENTS_DISPLAY_CAP,
+ RECENTS_SECTION,
+} from './constants';
+
export function combineInitialAndUserExpression(
initial: string,
user: string,
@@ -38,3 +54,106 @@ export function getUserExpressionFromCombined(
}
return c;
}
+
+// Filters and projects a list of recent-query entries into CodeMirror completions.
+// Entries are supplied by the caller (typically via the useRecents hook) so this
+// function stays pure and React doesn't have to re-subscribe inside CodeMirror's
+// autocomplete callback.
+export function getRecentOptions(
+ entries: RecentQueryEntry[],
+ fullDoc: string,
+): Completion[] {
+ const normalizedDoc = normalizeFilterExpression(fullDoc);
+
+ const matches = entries
+ .filter((e) => {
+ const normalizedRecent = normalizeFilterExpression(e.filter.expression);
+ if (normalizedRecent === normalizedDoc) {
+ return false;
+ }
+ if (normalizedDoc === '') {
+ return true;
+ }
+ return normalizedRecent.includes(normalizedDoc);
+ })
+ .slice(0, RECENTS_DISPLAY_CAP);
+
+ return matches.map((entry, index) => ({
+ label: entry.filter.expression,
+ type: RECENT_COMPLETION_TYPE,
+ // CodeMirror sorts within a section by boost desc, then label asc. The store
+ // returns entries newest-first, so we mirror that by giving the newest entry
+ // the highest boost — otherwise CM falls back to alphabetical order and the
+ // "most recently used" expectation breaks. Stays within the recents section
+ // because section.rank keeps recents above suggestions regardless of boost.
+ boost: matches.length - index,
+ section: RECENTS_SECTION,
+ detail: dayjs(entry.lastUsedAt).fromNow(),
+ recentId: entry.id,
+ recentSignal: entry.signal,
+ recentSource: entry.source,
+ apply: (view: EditorView): void => {
+ view.dispatch({
+ changes: {
+ from: 0,
+ to: view.state.doc.length,
+ insert: entry.filter.expression,
+ },
+ selection: { anchor: entry.filter.expression.length },
+ });
+ closeCompletion(view);
+ },
+ }));
+}
+
+export function renderRecentDeleteButton(
+ completion: Completion,
+ _state: unknown,
+ view: EditorView | null,
+): Node | null {
+ if (completion.type !== RECENT_COMPLETION_TYPE) {
+ return null;
+ }
+
+ const c = completion as Completion & {
+ recentId?: string;
+ recentSignal?: SignalType;
+ recentSource?: string;
+ };
+
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'cm-recent-delete';
+ btn.setAttribute('aria-label', 'Remove from recent searches');
+ btn.title = 'Remove from recent searches';
+ btn.textContent = '×';
+ queueMicrotask(() => {
+ if (btn.parentElement) {
+ btn.parentElement.title = completion.label;
+ }
+ });
+
+ const stop = (e: Event): void => {
+ e.preventDefault();
+ e.stopPropagation();
+ };
+ // CodeMirror's autocomplete closes the popup on pointerdown / mousedown outside
+ // the editor. The delete button lives inside the popup, so we must stop those
+ // events early — otherwise clicking × would dismiss the dropdown before the
+ // click handler fires and the entry wouldn't actually get removed.
+ btn.addEventListener('pointerdown', stop);
+ btn.addEventListener('mousedown', stop);
+ btn.addEventListener('click', (e) => {
+ stop(e);
+ if (!c.recentId || !c.recentSignal) {
+ return;
+ }
+ recentQueriesStore.remove(c.recentId, c.recentSignal, c.recentSource ?? '');
+ if (view) {
+ view.focus();
+ startCompletion(view);
+ }
+ });
+
+ return btn;
+}
diff --git a/frontend/src/lib/recentQueries/constants.ts b/frontend/src/lib/recentQueries/constants.ts
new file mode 100644
index 0000000000..a5f84fef03
--- /dev/null
+++ b/frontend/src/lib/recentQueries/constants.ts
@@ -0,0 +1,5 @@
+export const STORAGE_KEY_PREFIX = 'qb_recent_v1';
+export const STORAGE_VERSION = 1;
+// Maximum entries kept per (signal, source) bucket. Larger than the UI's
+// RECENTS_DISPLAY_CAP so deleting a visible entry surfaces an older one.
+export const MAX_ENTRIES = 10;
diff --git a/frontend/src/lib/recentQueries/getRecentQueries.ts b/frontend/src/lib/recentQueries/getRecentQueries.ts
new file mode 100644
index 0000000000..4ab5846d01
--- /dev/null
+++ b/frontend/src/lib/recentQueries/getRecentQueries.ts
@@ -0,0 +1,15 @@
+import type { SignalType } from 'types/api/v5/queryRange';
+
+import * as store from './recentQueriesStore';
+import type { RecentQueryEntry } from './types';
+
+// Synchronous, non-subscribing read of the recent-queries bucket for a given
+// (signal, source). Read-on-demand by design — subscribing here would
+// reconfigure CodeMirror on every store change and close any open completion
+// popup. Pair with saveQuery() for the write path.
+export function getRecentQueries(
+ signal: SignalType,
+ source = '',
+): RecentQueryEntry[] {
+ return store.list(signal, source);
+}
diff --git a/frontend/src/lib/recentQueries/normalize.test.ts b/frontend/src/lib/recentQueries/normalize.test.ts
new file mode 100644
index 0000000000..5dbac9729f
--- /dev/null
+++ b/frontend/src/lib/recentQueries/normalize.test.ts
@@ -0,0 +1,100 @@
+import { normalizeFilterExpression } from './normalize';
+
+describe('normalizeFilterExpression', () => {
+ it('returns empty string for empty input', () => {
+ expect(normalizeFilterExpression('')).toBe('');
+ });
+
+ it('returns empty string for whitespace-only input', () => {
+ expect(normalizeFilterExpression(' \t ')).toBe('');
+ });
+
+ it('strips whitespace around operators', () => {
+ expect(normalizeFilterExpression(' a = 1 ')).toBe('a=1');
+ expect(normalizeFilterExpression('a = 1')).toBe('a=1');
+ expect(normalizeFilterExpression('a=1')).toBe('a=1');
+ });
+
+ it('lowercases AND / OR / NOT outside quotes', () => {
+ expect(normalizeFilterExpression('A AND B OR NOT C')).toBe('AandBornotC');
+ });
+
+ it('lowercases IN / LIKE / ILIKE / CONTAINS', () => {
+ expect(normalizeFilterExpression('host IN [1, 2] AND name LIKE "foo"')).toBe(
+ 'hostin[1,2]andnamelike"foo"',
+ );
+ });
+
+ it('lowercases REGEXP', () => {
+ expect(normalizeFilterExpression('path REGEXP "foo"')).toBe(
+ 'pathregexp"foo"',
+ );
+ expect(normalizeFilterExpression('path REGEXP "foo"')).toBe(
+ normalizeFilterExpression('path regexp "foo"'),
+ );
+ });
+
+ it('lowercases HAS / HASANY / HASALL / HASTOKEN function names', () => {
+ expect(normalizeFilterExpression('HAS(tags, "x")')).toBe(
+ normalizeFilterExpression('has(tags, "x")'),
+ );
+ expect(normalizeFilterExpression('HASANY(tags, ["a","b"])')).toBe(
+ normalizeFilterExpression('hasAny(tags, ["a","b"])'),
+ );
+ expect(normalizeFilterExpression('HASALL(tags, ["a","b"])')).toBe(
+ normalizeFilterExpression('hasAll(tags, ["a","b"])'),
+ );
+ expect(normalizeFilterExpression('HASTOKEN(msg, "err")')).toBe(
+ normalizeFilterExpression('hasToken(msg, "err")'),
+ );
+ });
+
+ it('lowercases TRUE / FALSE boolean literals', () => {
+ expect(normalizeFilterExpression('active = TRUE')).toBe(
+ normalizeFilterExpression('active = true'),
+ );
+ expect(normalizeFilterExpression('active = FALSE')).toBe(
+ normalizeFilterExpression('active = false'),
+ );
+ });
+
+ it('preserves whitespace and casing inside single-quoted strings', () => {
+ expect(normalizeFilterExpression("a = 'X Y'")).toBe("a='X Y'");
+ });
+
+ it('preserves whitespace and casing inside double-quoted strings', () => {
+ expect(normalizeFilterExpression('a = "X Y"')).toBe('a="X Y"');
+ });
+
+ it('does not lowercase keyword-looking substrings inside quotes', () => {
+ expect(normalizeFilterExpression("msg = 'AND ERROR'")).toBe(
+ "msg='AND ERROR'",
+ );
+ });
+
+ it('handles escaped quotes inside strings', () => {
+ expect(normalizeFilterExpression("msg = 'a\\'b' AND x = 1")).toBe(
+ "msg='a\\'b'andx=1",
+ );
+ });
+
+ it('treats two formattings of the same expression as identical', () => {
+ const a = normalizeFilterExpression(
+ 'service.name = "frontend" AND severity = error',
+ );
+ const b = normalizeFilterExpression(
+ 'service.name="frontend" and severity=error',
+ );
+ expect(a).toBe(b);
+ });
+
+ it('preserves unquoted value casing (treats them as identifiers)', () => {
+ expect(normalizeFilterExpression('status = OK')).toBe('status=OK');
+ });
+
+ it('handles mixed quotes in one expression', () => {
+ expect(normalizeFilterExpression(`a = 'X' AND b = "Y"`)).toBe(
+ `a='X'andb="Y"`,
+ );
+ });
+});
diff --git a/frontend/src/lib/recentQueries/normalize.ts b/frontend/src/lib/recentQueries/normalize.ts
new file mode 100644
index 0000000000..924fb591da
--- /dev/null
+++ b/frontend/src/lib/recentQueries/normalize.ts
@@ -0,0 +1,56 @@
+import {
+ OPERATORS,
+ QUERY_BUILDER_FUNCTIONS,
+ TRACE_OPERATOR_OPERATORS,
+} from 'constants/antlrQueryConstants';
+
+// Reserved keywords sourced from the ANTLR grammar constants so this list stays
+// in sync with the parser. `\b` prevents partial matches inside identifiers
+// (e.g. `OR` inside `originator`). `TRUE`/`FALSE` are BOOL literals, included
+// so case variants of boolean values also dedup.
+const WORD_KEYWORDS = [
+ ...Object.keys(OPERATORS).filter((k) => /^[A-Z]+$/.test(k)),
+ ...Object.keys(TRACE_OPERATOR_OPERATORS).filter((k) => /^[A-Z]+$/.test(k)),
+ ...Object.values(QUERY_BUILDER_FUNCTIONS),
+ 'TRUE',
+ 'FALSE',
+];
+
+const KEYWORDS_RE = new RegExp(`\\b(${WORD_KEYWORDS.join('|')})\\b`, 'gi');
+
+// Matches single- or double-quoted string literals, supporting escaped quotes
+// (e.g. `'it\'s'` or `"a \" b"`). We preserve quoted spans verbatim during
+// normalisation so user-meaningful whitespace and casing inside string values
+// stays intact: `name = "Foo Bar"` must not collapse to `name="foobar"`.
+const QUOTED_RE = /'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g;
+
+// Lowercases reserved keywords and strips ALL whitespace from the unquoted regions
+// of the input. Keywords are normalised so casing variants dedup; whitespace is
+// dropped so formatting variants (`a=1` vs `a = 1`) dedup too.
+function processOutsideQuotes(s: string): string {
+ return s.replace(KEYWORDS_RE, (m) => m.toLowerCase()).replace(/\s+/g, '');
+}
+
+// Produces a canonical form of a filter expression suitable for dedup-key derivation.
+// Walks the input alternating between unquoted regions (where we normalise keywords
+// and whitespace) and quoted regions (which we copy verbatim).
+export function normalizeFilterExpression(input: string): string {
+ if (!input) {
+ return '';
+ }
+
+ let result = '';
+ let lastIndex = 0;
+ QUOTED_RE.lastIndex = 0;
+
+ let match = QUOTED_RE.exec(input);
+ while (match !== null) {
+ result += processOutsideQuotes(input.slice(lastIndex, match.index));
+ result += match[0];
+ lastIndex = QUOTED_RE.lastIndex;
+ match = QUOTED_RE.exec(input);
+ }
+ result += processOutsideQuotes(input.slice(lastIndex));
+
+ return result.trim();
+}
diff --git a/frontend/src/lib/recentQueries/recentQueriesStore.test.ts b/frontend/src/lib/recentQueries/recentQueriesStore.test.ts
new file mode 100644
index 0000000000..d379cfba4d
--- /dev/null
+++ b/frontend/src/lib/recentQueries/recentQueriesStore.test.ts
@@ -0,0 +1,247 @@
+import { MAX_ENTRIES } from './constants';
+import * as store from './recentQueriesStore';
+import type { RecentQueryInput } from './recentQueriesStore';
+import type { RecentQueryEntry } from './types';
+
+const baseInput = (
+ overrides: Partial<RecentQueryInput> = {},
+): RecentQueryInput => ({
+ signal: 'logs',
+ filter: { expression: "service.name = 'frontend'" },
+ ...overrides,
+});
+
+function saveOrThrow(input: RecentQueryInput): RecentQueryEntry {
+ const saved = store.save(input);
+ if (!saved) {
+ throw new Error('expected save to return an entry');
+ }
+ return saved;
+}
+
+describe('recentQueries store', () => {
+ beforeEach(() => {
+ store.useRecentQueriesStore.setState({ buckets: {} });
+ localStorage.clear();
+ });
+
+ describe('save + list', () => {
+ it('saves an entry and lists it', () => {
+ store.save(baseInput());
+ const entries = store.list('logs');
+ expect(entries).toHaveLength(1);
+ expect(entries[0].filter.expression).toBe("service.name = 'frontend'");
+ expect(entries[0].id).toBeTruthy();
+ expect(entries[0].lastUsedAt).toBeGreaterThan(0);
+ });
+
+ it('does not save when the filter expression is empty', () => {
+ const result = store.save(baseInput({ filter: { expression: '' } }));
+ expect(result).toBeNull();
+ expect(store.list('logs')).toHaveLength(0);
+ });
+
+ it('does not save when the filter expression is whitespace only', () => {
+ const result = store.save(baseInput({ filter: { expression: ' ' } }));
+ expect(result).toBeNull();
+ expect(store.list('logs')).toHaveLength(0);
+ });
+ });
+
+ describe('LRU ordering', () => {
+ it('places the most recently saved entry at the front', () => {
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+ store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
+ store.save(baseInput({ filter: { expression: 'attempt = 1' } }));
+
+ const entries = store.list('logs');
+ expect(entries.map((e) => e.filter.expression)).toStrictEqual([
+ 'attempt = 1',
+ 'http.status_code >= 500',
+ "severity_text = 'ERROR'",
+ ]);
+ });
+
+ it('re-saving an existing filter bumps it to the front', () => {
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+ store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+
+ const entries = store.list('logs');
+ expect(entries).toHaveLength(2);
+ expect(entries.map((e) => e.filter.expression)).toStrictEqual([
+ "severity_text = 'ERROR'",
+ 'http.status_code >= 500',
+ ]);
+ });
+ });
+
+ describe('dedup', () => {
+ it('treats formatting variations of the same filter as one entry', () => {
+ store.save(
+ baseInput({
+ filter: { expression: "severity_text = 'ERROR' AND attempt = 1" },
+ }),
+ );
+ store.save(
+ baseInput({
+ filter: { expression: "severity_text='ERROR' and attempt=1" },
+ }),
+ );
+
+ expect(store.list('logs')).toHaveLength(1);
+ });
+ });
+
+ describe('signal partitioning', () => {
+ it('saves to the right bucket per signal', () => {
+ store.save(
+ baseInput({
+ signal: 'logs',
+ filter: { expression: "severity_text = 'ERROR'" },
+ }),
+ );
+ store.save(
+ baseInput({
+ signal: 'traces',
+ filter: { expression: "service.name = 'orders-api'" },
+ }),
+ );
+ store.save(
+ baseInput({
+ signal: 'metrics',
+ filter: { expression: 'cpu_usage > 80' },
+ }),
+ );
+
+ expect(store.list('logs')).toHaveLength(1);
+ expect(store.list('traces')).toHaveLength(1);
+ expect(store.list('metrics')).toHaveLength(1);
+ expect(store.list('logs')[0].filter.expression).toBe(
+ "severity_text = 'ERROR'",
+ );
+ expect(store.list('traces')[0].filter.expression).toBe(
+ "service.name = 'orders-api'",
+ );
+ expect(store.list('metrics')[0].filter.expression).toBe('cpu_usage > 80');
+ });
+
+ it('does not leak between signals on dedup', () => {
+ store.save(
+ baseInput({
+ signal: 'logs',
+ filter: { expression: "service.name = 'frontend'" },
+ }),
+ );
+ store.save(
+ baseInput({
+ signal: 'traces',
+ filter: { expression: "service.name = 'frontend'" },
+ }),
+ );
+
+ expect(store.list('logs')).toHaveLength(1);
+ expect(store.list('traces')).toHaveLength(1);
+ });
+ });
+
+ describe('LRU cap', () => {
+ it('caps the bucket at MAX_ENTRIES and evicts the oldest', () => {
+ const total = MAX_ENTRIES + 1;
+ for (let i = 0; i < total; i += 1) {
+ store.save(baseInput({ filter: { expression: `attempt = ${i}` } }));
+ }
+
+ const entries = store.list('logs');
+ expect(entries).toHaveLength(MAX_ENTRIES);
+ expect(entries[0].filter.expression).toBe(`attempt = ${total - 1}`);
+ expect(entries.some((e) => e.filter.expression === 'attempt = 0')).toBe(
+ false,
+ );
+ });
+ });
+
+ describe('remove', () => {
+ it('removes an entry by id', () => {
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+ const saved = saveOrThrow(
+ baseInput({ filter: { expression: 'http.status_code >= 500' } }),
+ );
+ store.remove(saved.id, 'logs');
+
+ const entries = store.list('logs');
+ expect(entries).toHaveLength(1);
+ expect(entries[0].filter.expression).toBe("severity_text = 'ERROR'");
+ });
+
+ it('is a no-op when the id does not exist', () => {
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+ store.remove('does-not-exist', 'logs');
+ expect(store.list('logs')).toHaveLength(1);
+ });
+
+ it('does not touch other signals', () => {
+ const logsEntry = saveOrThrow(
+ baseInput({
+ signal: 'logs',
+ filter: { expression: "service.name = 'frontend'" },
+ }),
+ );
+ store.save(
+ baseInput({
+ signal: 'traces',
+ filter: { expression: "service.name = 'frontend'" },
+ }),
+ );
+
+ store.remove(logsEntry.id, 'logs');
+
+ expect(store.list('logs')).toHaveLength(0);
+ expect(store.list('traces')).toHaveLength(1);
+ });
+ });
+
+ describe('persistence', () => {
+ it('reads back the same entries after the in-memory state is reset', () => {
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+ store.save(baseInput({ filter: { expression: 'http.status_code >= 500' } }));
+
+ store.useRecentQueriesStore.setState({ buckets: {} });
+
+ const entries = store.list('logs');
+ expect(entries.map((e) => e.filter.expression)).toStrictEqual([
+ 'http.status_code >= 500',
+ "severity_text = 'ERROR'",
+ ]);
+ });
+ });
+
+ describe('reactive subscription via zustand', () => {
+ it('notifies zustand subscribers on save', () => {
+ const cb = jest.fn();
+ const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+ expect(cb).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ });
+
+ it('notifies zustand subscribers on remove', () => {
+ const saved = saveOrThrow(
+ baseInput({ filter: { expression: "severity_text = 'ERROR'" } }),
+ );
+ const cb = jest.fn();
+ const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
+ store.remove(saved.id, 'logs');
+ expect(cb).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ });
+
+ it('stops notifying after unsubscribe', () => {
+ const cb = jest.fn();
+ const unsubscribe = store.useRecentQueriesStore.subscribe(cb);
+ unsubscribe();
+ store.save(baseInput({ filter: { expression: "severity_text = 'ERROR'" } }));
+ expect(cb).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/frontend/src/lib/recentQueries/recentQueriesStore.ts b/frontend/src/lib/recentQueries/recentQueriesStore.ts
new file mode 100644
index 0000000000..2b69cbd6e8
--- /dev/null
+++ b/frontend/src/lib/recentQueries/recentQueriesStore.ts
@@ -0,0 +1,144 @@
+import get from 'api/browser/localstorage/get';
+import set from 'api/browser/localstorage/set';
+import type { SignalType } from 'types/api/v5/queryRange';
+import { create } from 'zustand';
+
+import { MAX_ENTRIES, STORAGE_VERSION } from './constants';
+import { normalizeFilterExpression } from './normalize';
+import type { RecentQueriesStoreShape, RecentQueryEntry } from './types';
+import { bucketKey, makeId, normalizeSource, storageKeyFor } from './utils';
+
+// Mirrors parsed localStorage so equal raw strings return the same array ref —
+// preserves Object.is for zustand selector bail-out.
+const persistedBucketCache = new Map<
+ string,
+ { raw: string; parsed: RecentQueryEntry[] }
+>();
+
+function loadBucketFromStorage(
+ signal: SignalType,
+ source: string,
+): RecentQueryEntry[] | null {
+ const key = bucketKey(signal, source);
+ try {
+ const raw = get(storageKeyFor(signal, source));
+ if (!raw) {
+ persistedBucketCache.delete(key);
+ return null;
+ }
+ const cached = persistedBucketCache.get(key);
+ if (cached && cached.raw === raw) {
+ return cached.parsed;
+ }
+ const parsedShape = JSON.parse(raw) as RecentQueriesStoreShape;
+ if (
+ parsedShape?.version !== STORAGE_VERSION ||
+ !Array.isArray(parsedShape.entries)
+ ) {
+ persistedBucketCache.delete(key);
+ return null;
+ }
+ persistedBucketCache.set(key, { raw, parsed: parsedShape.entries });
+ return parsedShape.entries;
+ } catch {
+ persistedBucketCache.delete(key);
+ return null;
+ }
+}
+
+function saveBucketToStorage(
+ signal: SignalType,
+ source: string,
+ entries: RecentQueryEntry[],
+): void {
+ try {
+ const raw = JSON.stringify({ version: STORAGE_VERSION, entries });
+ if (set(storageKeyFor(signal, source), raw)) {
+ persistedBucketCache.set(bucketKey(signal, source), {
+ raw,
+ parsed: entries,
+ });
+ }
+ } catch {
+ // Ignore storage errors (e.g. quota exceeded, JSON.stringify failure).
+ }
+}
+
+export type RecentQueryInput = Omit<
+ RecentQueryEntry,
+ 'id' | 'lastUsedAt' | 'source'
+> & {
+ source?: string;
+};
+
+type RecentQueriesState = {
+ buckets: Record<string, RecentQueryEntry[]>;
+ save: (entry: RecentQueryInput) => RecentQueryEntry | null;
+ remove: (id: string, signal: SignalType, source?: string) => void;
+};
+
+export const useRecentQueriesStore = create<RecentQueriesState>()(
+ (set, get) => ({
+ buckets: {},
+
+ save: (entry): RecentQueryEntry | null => {
+ const normalized = normalizeFilterExpression(entry.filter.expression);
+ if (!normalized) {
+ return null;
+ }
+ const source = normalizeSource(entry.source);
+ const key = bucketKey(entry.signal, source);
+
+ const current =
+ get().buckets[key] ?? loadBucketFromStorage(entry.signal, source) ?? [];
+ const filtered = current.filter(
+ (e) => normalizeFilterExpression(e.filter.expression) !== normalized,
+ );
+
+ const newEntry: RecentQueryEntry = {
+ ...entry,
+ source,
+ id: makeId(entry.signal, source, normalized),
+ lastUsedAt: Date.now(),
+ };
+
+ const next = [newEntry, ...filtered].slice(0, MAX_ENTRIES);
+ set({ buckets: { ...get().buckets, [key]: next } });
+ saveBucketToStorage(entry.signal, source, next);
+ return newEntry;
+ },
+
+ remove: (id, signal, source = ''): void => {
+ const key = bucketKey(signal, source);
+ const current = get().buckets[key] ?? loadBucketFromStorage(signal, source);
+ if (!current) {
+ return;
+ }
+ const next = current.filter((e) => e.id !== id);
+ if (next.length === current.length) {
+ return;
+ }
+ set({ buckets: { ...get().buckets, [key]: next } });
+ saveBucketToStorage(signal, source, next);
+ },
+ }),
+);
+
+// Plain-function wrappers for non-React callers — same pattern as useColumnStore.ts.
+export function save(entry: RecentQueryInput): RecentQueryEntry | null {
+ return useRecentQueriesStore.getState().save(entry);
+}
+
+export function remove(id: string, signal: SignalType, source = ''): void {
+ useRecentQueriesStore.getState().remove(id, signal, source);
+}
+
+// Synchronous bucket read with localStorage fallback for non-React callers.
+export function list(signal: SignalType, source = ''): RecentQueryEntry[] {
+ const key = bucketKey(signal, source);
+ const state = useRecentQueriesStore.getState();
+ if (state.buckets[key]) {
+ return state.buckets[key];
+ }
+ return loadBucketFromStorage(signal, source) ?? [];
+}
diff --git a/frontend/src/lib/recentQueries/saveRecentQuery.test.ts b/frontend/src/lib/recentQueries/saveRecentQuery.test.ts
new file mode 100644
index 0000000000..e4e639e52d
--- /dev/null
+++ b/frontend/src/lib/recentQueries/saveRecentQuery.test.ts
@@ -0,0 +1,113 @@
+import { DataSource } from 'types/common/queryBuilder';
+import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+import { validateQuery } from 'utils/queryValidationUtils';
+
+import * as store from './recentQueriesStore';
+import { saveRecentQuery } from './saveRecentQuery';
+
+jest.mock('utils/queryValidationUtils', () => ({
+ validateQuery: jest.fn(),
+}));
+
+const mockedValidateQuery = validateQuery as jest.MockedFunction<
+ typeof validateQuery
+>;
+
+const buildComposite = (
+ overrides: Partial<IBuilderQuery>[] = [{}],
+): { builder: { queryData: IBuilderQuery[] } } => ({
+ builder: {
+ queryData: overrides.map((o, i) => ({
+ queryName: `Q${i}`,
+ dataSource: DataSource.LOGS,
+ aggregateOperator: 'count',
+ aggregateAttribute: undefined as never,
+ functions: [],
+ filter: { expression: 'service.name = "frontend"' },
+ groupBy: [],
+ expression: `Q${i}`,
+ disabled: false,
+ having: [],
+ limit: null,
+ stepInterval: null,
+ orderBy: [],
+ legend: '',
+ ...o,
+ })) as IBuilderQuery[],
+ },
+});
+
+describe('saveRecentQuery', () => {
+ beforeEach(() => {
+ store.useRecentQueriesStore.setState({ buckets: {} });
+ localStorage.clear();
+ mockedValidateQuery.mockReturnValue({
+ isValid: true,
+ message: '',
+ errors: [],
+ });
+ });
+
+ it('saves the composite query when validation passes', () => {
+ saveRecentQuery(buildComposite());
+
+ const entries = store.list('logs');
+ expect(entries).toHaveLength(1);
+ expect(entries[0].filter.expression).toBe('service.name = "frontend"');
+ });
+
+ it('does not save when validateQuery rejects the expression', () => {
+ mockedValidateQuery.mockReturnValue({
+ isValid: false,
+ message: 'bad',
+ errors: [],
+ });
+
+ saveRecentQuery(buildComposite());
+
+ expect(store.list('logs')).toHaveLength(0);
+ });
+
+ it('does not save a builder query with an empty filter expression', () => {
+ saveRecentQuery(buildComposite([{ filter: { expression: '' } }]));
+
+ expect(store.list('logs')).toHaveLength(0);
+ });
+
+ it('saves each builder query in the composite separately', () => {
+ saveRecentQuery(
+ buildComposite([
+ {
+ dataSource: DataSource.LOGS,
+ filter: { expression: "service.name = 'frontend'" },
+ },
+ {
+ dataSource: DataSource.TRACES,
+ filter: { expression: "service.name = 'orders-api'" },
+ },
+ ]),
+ );
+
+ expect(store.list('logs')).toHaveLength(1);
+ expect(store.list('traces')).toHaveLength(1);
+ });
+
+ it('skips builder queries whose dataSource is not a supported signal', () => {
+ saveRecentQuery(
+ buildComposite([{ dataSource: 'unknown' as IBuilderQuery['dataSource'] }]),
+ );
+
+ expect(store.list('logs')).toHaveLength(0);
+ expect(store.list('traces')).toHaveLength(0);
+ expect(store.list('metrics')).toHaveLength(0);
+ });
+
+ it('is a no-op when the composite is null, undefined, or empty', () => {
+ saveRecentQuery(null);
+ saveRecentQuery(undefined);
+ saveRecentQuery({ builder: { queryData: [] } });
+ saveRecentQuery({});
+
+ expect(store.list('logs')).toHaveLength(0);
+ });
+});
diff --git a/frontend/src/lib/recentQueries/saveRecentQuery.ts b/frontend/src/lib/recentQueries/saveRecentQuery.ts
new file mode 100644
index 0000000000..385a97e6f6
--- /dev/null
+++ b/frontend/src/lib/recentQueries/saveRecentQuery.ts
@@ -0,0 +1,52 @@
+import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
+import type { SignalType } from 'types/api/v5/queryRange';
+import { validateQuery } from 'utils/queryValidationUtils';
+
+import * as store from './recentQueriesStore';
+
+function toSignal(dataSource: IBuilderQuery['dataSource']): SignalType | null {
+ if (
+ dataSource === 'logs' ||
+ dataSource === 'traces' ||
+ dataSource === 'metrics'
+ ) {
+ return dataSource;
+ }
+ return null;
+}
+
+type CompositeWithBuilder = {
+ builder?: { queryData?: IBuilderQuery[] };
+};
+
+// Persists each builder query in the composite 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;
+ if (!Array.isArray(queryData) || queryData.length === 0) {
+ return;
+ }
+
+ queryData.forEach((q) => {
+ const expression = q.filter?.expression?.trim();
+ if (!expression) {
+ return;
+ }
+ const validation = validateQuery(expression);
+ if (!validation.isValid) {
+ return;
+ }
+ const signal = toSignal(q.dataSource);
+ if (!signal) {
+ return;
+ }
+ store.save({
+ signal,
+ source: q.source ?? '',
+ filter: q.filter ?? { expression: '' },
+ });
+ });
+}
diff --git a/frontend/src/lib/recentQueries/types.ts b/frontend/src/lib/recentQueries/types.ts
new file mode 100644
index 0000000000..867d1b66a5
--- /dev/null
+++ b/frontend/src/lib/recentQueries/types.ts
@@ -0,0 +1,14 @@
+import type { Filter, SignalType } from 'types/api/v5/queryRange';
+
+export interface RecentQueryEntry {
+ id: string;
+ signal: SignalType;
+ source: string;
+ filter: Filter;
+ lastUsedAt: number;
+}
+
+export interface RecentQueriesStoreShape {
+ version: 1;
+ entries: RecentQueryEntry[];
+}
diff --git a/frontend/src/lib/recentQueries/utils.ts b/frontend/src/lib/recentQueries/utils.ts
new file mode 100644
index 0000000000..336f5c8e0b
--- /dev/null
+++ b/frontend/src/lib/recentQueries/utils.ts
@@ -0,0 +1,24 @@
+import type { SignalType } from 'types/api/v5/queryRange';
+
+import { STORAGE_KEY_PREFIX } from './constants';
+
+export function normalizeSource(source: string | undefined): string {
+ return source ?? '';
+}
+
+export function bucketKey(signal: SignalType, source: string): string {
+ return `${signal}:${source}`;
+}
+
+export function storageKeyFor(signal: SignalType, source: string): string {
+ return `${STORAGE_KEY_PREFIX}:${bucketKey(signal, source)}`;
+}
+
+// Same (signal, source, normalized filter) ⇒ same id ⇒ upsert.
+export function makeId(
+ signal: SignalType,
+ source: string,
+ normalizedFilter: string,
+): string {
+ return `${signal}|${source}|${normalizedFilter}`;
+}
diff --git a/frontend/src/providers/QueryBuilder.tsx b/frontend/src/providers/QueryBuilder.tsx
index 77fea27e20..d9fe9d3b4b 100644
--- a/frontend/src/providers/QueryBuilder.tsx
+++ b/frontend/src/providers/QueryBuilder.tsx
@@ -41,6 +41,7 @@ import useUrlQuery from 'hooks/useUrlQuery';
import { createIdFromObjectFields } from 'lib/createIdFromObjectFields';
import { createNewBuilderItemName } from 'lib/newQueryBuilder/createNewBuilderItemName';
import { getOperatorsBySourceAndPanelType } from 'lib/newQueryBuilder/getOperatorsBySourceAndPanelType';
+import { saveRecentQuery } from 'lib/recentQueries/saveRecentQuery';
import { replaceIncorrectObjectFields } from 'lib/replaceIncorrectObjectFields';
import { cloneDeep, get, isEqual, set } from 'lodash-es';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
@@ -1031,6 +1032,8 @@ export function QueryBuilderProvider({
if (isExplorer) {
setCalledFromHandleRunQuery(true);
}
+ saveRecentQuery(currentQuery);
+
const currentQueryData = {
...currentQuery,
builder: {
diff --git a/frontend/src/utils/timeUtils.ts b/frontend/src/utils/timeUtils.ts
index d875dc7c24..6136e86176 100644
--- a/frontend/src/utils/timeUtils.ts
+++ b/frontend/src/utils/timeUtils.ts
@@ -2,6 +2,7 @@ import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import duration from 'dayjs/plugin/duration';
+import relativeTime from 'dayjs/plugin/relativeTime';
import timezone from 'dayjs/plugin/timezone';
import utc from 'dayjs/plugin/utc';
@@ -9,6 +10,7 @@ dayjs.extend(utc);
dayjs.extend(customParseFormat);
dayjs.extend(duration);
dayjs.extend(timezone);
+dayjs.extend(relativeTime);
export function toUTCEpoch(time: number): number {
const x = new Date();