Compare commits

..

2 Commits

Author SHA1 Message Date
Gaurav Tewari
8d2e024cb2 refactor: recent query 2026-06-01 02:48:57 +05:30
Gaurav Tewari
90cb4e99f9 feat: initial commit 2026-06-01 02:00:50 +05:30
48 changed files with 2243 additions and 1302 deletions

View File

@@ -190,7 +190,7 @@ services:
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:v0.126.0
image: signoz/signoz:v0.125.1
ports:
- "8080:8080" # signoz port
# - "6060:6060" # pprof port

View File

@@ -117,7 +117,7 @@ services:
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:v0.126.0
image: signoz/signoz:v0.125.1
ports:
- "8080:8080" # signoz port
volumes:

View File

@@ -181,7 +181,7 @@ services:
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:${VERSION:-v0.126.0}
image: signoz/signoz:${VERSION:-v0.125.1}
container_name: signoz
ports:
- "8080:8080" # signoz port

View File

@@ -109,7 +109,7 @@ services:
# - ../common/clickhouse/storage.xml:/etc/clickhouse-server/config.d/storage.xml
signoz:
!!merge <<: *db-depend
image: signoz/signoz:${VERSION:-v0.126.0}
image: signoz/signoz:${VERSION:-v0.125.1}
container_name: signoz
ports:
- "8080:8080" # signoz port

View File

@@ -102,11 +102,7 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
return <>{children}</>;
}
if (
(pathname === ROUTES.AI_ASSISTANT_BASE ||
pathname.startsWith('/ai-assistant/')) &&
!isAIAssistantEnabled
) {
if (pathname.startsWith('/ai-assistant/') && !isAIAssistantEnabled) {
return <Redirect to={ROUTES.HOME} />;
}

View File

@@ -229,18 +229,18 @@ function App(): JSX.Element {
}
setRoutes((prev) => {
const hasAi = prev.some((r) => r.key === 'AI_ASSISTANT');
const hasAi = prev.some((r) => r.path === ROUTES.AI_ASSISTANT);
if (isAIAssistantEnabled === hasAi) {
return prev;
}
if (isAIAssistantEnabled) {
const aiRoute = defaultRoutes.find((r) => r.key === 'AI_ASSISTANT');
const aiRoute = defaultRoutes.find((r) => r.path === ROUTES.AI_ASSISTANT);
if (!aiRoute) {
return prev;
}
return [...prev.filter((r) => r.key !== 'AI_ASSISTANT'), aiRoute];
return [...prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT), aiRoute];
}
return prev.filter((r) => r.key !== 'AI_ASSISTANT');
return prev.filter((r) => r.path !== ROUTES.AI_ASSISTANT);
});
}, [isLoggedInState, isAIAssistantEnabled]);
@@ -254,7 +254,6 @@ function App(): JSX.Element {
if (
pathname === ROUTES.ONBOARDING ||
pathname.startsWith('/public/dashboard/') ||
pathname === '/ai-assistant' ||
pathname.startsWith('/ai-assistant/')
) {
window.Pylon?.('hideChatBubble');

View File

@@ -501,7 +501,7 @@ const routes: AppRoutes[] = [
isPrivate: true,
},
{
path: [ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT],
path: ROUTES.AI_ASSISTANT,
exact: true,
component: AIAssistantPage,
key: 'AI_ASSISTANT',

View File

@@ -40,7 +40,6 @@ export function setAIBackendUrl(url: string | null): void {
if (aiBackendUrl === url) {
return;
}
aiBackendUrl = url;
AIAssistantInstance.defaults.baseURL = url ? `${url}${AI_API_PATH}` : '';
}

View File

@@ -37,16 +37,6 @@ export enum ApplyFilterSignalDTO {
traces = 'traces',
metrics = 'metrics',
}
export enum ApprovalStateDTO {
pending = 'pending',
approved = 'approved',
rejected = 'rejected',
superseded = 'superseded',
}
export enum ApprovalActionTypeDTO {
modify = 'modify',
delete = 'delete',
}
/**
* Resolved approval (approved/rejected/superseded) anchored on the assistant message that proposed it. Pending approvals never appear here - they live at the top-level pendingApproval slot.
*/
@@ -73,6 +63,16 @@ export interface ApprovalActionSummaryDTO {
resolvedAt: string;
}
export enum ApprovalActionTypeDTO {
modify = 'modify',
delete = 'delete',
}
export enum ApprovalStateDTO {
pending = 'pending',
approved = 'approved',
rejected = 'rejected',
superseded = 'superseded',
}
export type ApprovalSummaryDTODiff = { [key: string]: unknown };
export interface ApprovalSummaryDTO {
@@ -139,16 +139,6 @@ export interface CancelRequestDTO {
threadId: string;
}
export enum ExecutionStateDTO {
queued = 'queued',
running = 'running',
awaiting_approval = 'awaiting_approval',
awaiting_clarification = 'awaiting_clarification',
resumed = 'resumed',
completed = 'completed',
failed = 'failed',
canceled = 'canceled',
}
export interface CancelResponseDTO {
/**
* @type string
@@ -163,13 +153,6 @@ export type ClarificationFieldDTOOptions = string[] | null;
export type ClarificationFieldDTODefault = string | string[] | null;
export enum ClarificationFieldTypeDTO {
text = 'text',
number = 'number',
select = 'select',
multi_select = 'multi_select',
boolean = 'boolean',
}
export interface ClarificationFieldDTO {
/**
* @type string
@@ -192,6 +175,13 @@ export interface ClarificationFieldDTO {
default?: ClarificationFieldDTODefault;
}
export enum ClarificationFieldTypeDTO {
text = 'text',
number = 'number',
select = 'select',
multi_select = 'multi_select',
boolean = 'boolean',
}
export enum ClarificationStateDTO {
pending = 'pending',
submitted = 'submitted',
@@ -262,21 +252,178 @@ export interface ClarifyResponseDTO {
executionId: string;
}
export type CreateMessageRequestDTOContexts = MessageContextDTO[] | null;
export type CreateMessageRequestDTOForkFromMessageId = string | null;
export interface CreateMessageRequestDTO {
/**
* @type string
* @maxLength 20000
* @minLength 1
*/
content: string;
contexts?: CreateMessageRequestDTOContexts;
forkFromMessageId?: CreateMessageRequestDTOForkFromMessageId;
}
export interface CreateMessageResponseDTO {
/**
* @type string
* @format uuid
*/
executionId: string;
}
export type CreateThreadRequestDTOTitle = string | null;
export interface CreateThreadRequestDTO {
title?: CreateThreadRequestDTOTitle;
}
export interface CreateThreadResponseDTO {
/**
* @type string
* @format uuid
*/
threadId: string;
}
export type ErrorBodyDTOErrors = ErrorResponseAdditionalDTO[] | null;
export type ErrorBodyDTOUrl = string | null;
/**
* Identifier exposed on the wire for each counter row.
Mirrors the ``RateLimitCounterType`` model enum minus the cost
counter. The daily-cost limit is enforced internally (Redis
counter + 429 from the pre-flight gate) but never surfaced on the
customer-facing API: shipping the raw provider cost to tenant users
pins our public pricing model to what we pay Anthropic and forecloses
markup, per-seat bundling, or tiered pricing. Cost stays internal on
``assistant_executions`` + Redis for billing.
*/
export enum CounterTypeNameDTO {
hourly_message = 'hourly_message',
daily_message = 'daily_message',
daily_token = 'daily_token',
* Inner error object — matches Go ErrorsJSON.
*/
export interface ErrorBodyDTO {
/**
* @type string
* @pattern ^[a-z_]+$
*/
code: string;
/**
* @type string
*/
message: string;
errors?: ErrorBodyDTOErrors;
url?: ErrorBodyDTOUrl;
}
/**
* Top-level error envelope — matches Go RenderErrorResponse.
*/
export interface ErrorResponseDTO {
/**
* @type string
*/
status?: string;
error: ErrorBodyDTO;
}
/**
* Single sub-error entry — matches Go ErrorsResponseerroradditional.
*/
export interface ErrorResponseAdditionalDTO {
/**
* @type string
*/
message: string;
}
export enum ExecutionStateDTO {
queued = 'queued',
running = 'running',
awaiting_approval = 'awaiting_approval',
awaiting_clarification = 'awaiting_clarification',
resumed = 'resumed',
completed = 'completed',
failed = 'failed',
canceled = 'canceled',
}
export enum FeedbackRatingDTO {
positive = 'positive',
negative = 'negative',
}
export type FeedbackRequestDTOComment = string | null;
export interface FeedbackRequestDTO {
rating: FeedbackRatingDTO;
comment?: FeedbackRequestDTOComment;
}
export interface FeedbackResponseDTO {
[key: string]: unknown;
}
export interface HTTPValidationErrorDTO {
/**
* @type array
*/
detail?: ValidationErrorDTO[];
}
export const HealthResponseDTOValue = {
/**
* @type string
*/
status: 'ok',
} as const;
export type HealthResponseDTO = typeof HealthResponseDTOValue;
export type MessageActionDTOActionMetadataId = string | null;
export type MessageActionDTOResourceType = string | null;
export type MessageActionDTOResourceId = string | null;
export type MessageActionDTOState = string | null;
export type MessageActionDTOInputAnyOf = { [key: string]: unknown };
export type MessageActionDTOInput = MessageActionDTOInputAnyOf | null;
export type MessageActionDTOTooltip = string | null;
export type MessageActionDTOSignal = ApplyFilterSignalDTO | null;
export type MessageActionDTOQueryAnyOf = { [key: string]: unknown };
export type MessageActionDTOQuery = MessageActionDTOQueryAnyOf | null;
export type MessageActionDTOUrl = string | null;
/**
* Assistant action. Kind-specific requirements: rollback actions require actionMetadataId/resourceType/resourceId; follow_up requires input.intent; open_resource requires resourceType/resourceId; apply_filter requires signal and query; open_docs requires a SigNoz docs url.
*/
export interface MessageActionDTO {
kind: MessageActionKindDTO;
/**
* @type string
*/
label: string;
actionMetadataId?: MessageActionDTOActionMetadataId;
resourceType?: MessageActionDTOResourceType;
resourceId?: MessageActionDTOResourceId;
state?: MessageActionDTOState;
input?: MessageActionDTOInput;
tooltip?: MessageActionDTOTooltip;
signal?: MessageActionDTOSignal;
query?: MessageActionDTOQuery;
url?: MessageActionDTOUrl;
}
export enum MessageActionKindDTO {
undo = 'undo',
revert = 'revert',
restore = 'restore',
follow_up = 'follow_up',
open_resource = 'open_resource',
open_docs = 'open_docs',
apply_filter = 'apply_filter',
}
export enum MessageContentTypeDTO {
markdown = 'markdown',
}
/**
* "auto" if derived from current page; "mention" if explicitly @-picked.
@@ -335,193 +482,6 @@ export interface MessageContextDTO {
metadata?: MessageContextDTOMetadata;
}
export type CreateMessageRequestDTOContexts = MessageContextDTO[] | null;
export type CreateMessageRequestDTOForkFromMessageId = string | null;
export interface CreateMessageRequestDTO {
/**
* @type string
* @maxLength 20000
* @minLength 1
*/
content: string;
contexts?: CreateMessageRequestDTOContexts;
forkFromMessageId?: CreateMessageRequestDTOForkFromMessageId;
}
export interface CreateMessageResponseDTO {
/**
* @type string
* @format uuid
*/
executionId: string;
}
export type CreateThreadRequestDTOTitle = string | null;
export interface CreateThreadRequestDTO {
title?: CreateThreadRequestDTOTitle;
}
export interface CreateThreadResponseDTO {
/**
* @type string
* @format uuid
*/
threadId: string;
}
/**
* Single sub-error entry — matches Go ErrorsResponseerroradditional.
*/
export interface ErrorResponseAdditionalDTO {
/**
* @type string
*/
message: string;
}
export type ErrorBodyDTOErrors = ErrorResponseAdditionalDTO[] | null;
export type ErrorBodyDTOUrl = string | null;
/**
* Inner error object — matches Go ErrorsJSON.
*/
export interface ErrorBodyDTO {
/**
* @type string
* @pattern ^[a-z_]+$
*/
code: string;
/**
* @type string
*/
message: string;
errors?: ErrorBodyDTOErrors;
url?: ErrorBodyDTOUrl;
}
/**
* Top-level error envelope — matches Go RenderErrorResponse.
*/
export interface ErrorResponseDTO {
/**
* @type string
*/
status?: string;
error: ErrorBodyDTO;
}
export enum FeedbackRatingDTO {
positive = 'positive',
negative = 'negative',
}
export type FeedbackRequestDTOComment = string | null;
export interface FeedbackRequestDTO {
rating: FeedbackRatingDTO;
comment?: FeedbackRequestDTOComment;
}
export interface FeedbackResponseDTO {
[key: string]: unknown;
}
export type ValidationErrorDTOLocItem = string | number;
export type ValidationErrorDTOCtx = { [key: string]: unknown };
export interface ValidationErrorDTO {
/**
* @type array
*/
loc: ValidationErrorDTOLocItem[];
/**
* @type string
*/
msg: string;
/**
* @type string
*/
type: string;
input?: unknown;
/**
* @type object
*/
ctx?: ValidationErrorDTOCtx;
}
export interface HTTPValidationErrorDTO {
/**
* @type array
*/
detail?: ValidationErrorDTO[];
}
export const HealthResponseDTOValue = {
/**
* @type string
*/
status: 'ok',
} as const;
export type HealthResponseDTO = typeof HealthResponseDTOValue;
export type MessageActionDTOActionMetadataId = string | null;
export type MessageActionDTOResourceType = string | null;
export type MessageActionDTOResourceId = string | null;
export type MessageActionDTOState = string | null;
export type MessageActionDTOInputAnyOf = { [key: string]: unknown };
export type MessageActionDTOInput = MessageActionDTOInputAnyOf | null;
export type MessageActionDTOTooltip = string | null;
export type MessageActionDTOSignal = ApplyFilterSignalDTO | null;
export type MessageActionDTOQueryAnyOf = { [key: string]: unknown };
export type MessageActionDTOQuery = MessageActionDTOQueryAnyOf | null;
export type MessageActionDTOUrl = string | null;
export enum MessageActionKindDTO {
undo = 'undo',
revert = 'revert',
restore = 'restore',
follow_up = 'follow_up',
open_resource = 'open_resource',
open_docs = 'open_docs',
apply_filter = 'apply_filter',
}
/**
* Assistant action. Kind-specific requirements: rollback actions require actionMetadataId/resourceType/resourceId; follow_up requires input.intent; open_resource requires resourceType/resourceId; apply_filter requires signal and query; open_docs requires a SigNoz docs url.
*/
export interface MessageActionDTO {
kind: MessageActionKindDTO;
/**
* @type string
*/
label: string;
actionMetadataId?: MessageActionDTOActionMetadataId;
resourceType?: MessageActionDTOResourceType;
resourceId?: MessageActionDTOResourceId;
state?: MessageActionDTOState;
input?: MessageActionDTOInput;
tooltip?: MessageActionDTOTooltip;
signal?: MessageActionDTOSignal;
query?: MessageActionDTOQuery;
url?: MessageActionDTOUrl;
}
export enum MessageContentTypeDTO {
markdown = 'markdown',
}
export enum MessageRoleDTO {
user = 'user',
assistant = 'assistant',
@@ -656,10 +616,6 @@ export interface RevertRequestDTO {
actionMetadataId: string;
}
export enum ScopeDTO {
user = 'user',
org = 'org',
}
export type ThreadDetailResponseDTOTitle = string | null;
export type ThreadDetailResponseDTOState = ExecutionStateDTO | null;
@@ -707,6 +663,18 @@ export interface ThreadDetailResponseDTO {
export type ThreadListResponseDTONextCursor = string | null;
export interface ThreadListResponseDTO {
/**
* @type array
*/
threads: ThreadSummaryDTO[];
nextCursor?: ThreadListResponseDTONextCursor;
/**
* @type boolean
*/
hasMore?: boolean;
}
export type ThreadSummaryDTOTitle = string | null;
export type ThreadSummaryDTOState = ExecutionStateDTO | null;
@@ -741,18 +709,6 @@ export interface ThreadSummaryDTO {
updatedAt: string;
}
export interface ThreadListResponseDTO {
/**
* @type array
*/
threads: ThreadSummaryDTO[];
nextCursor?: ThreadListResponseDTONextCursor;
/**
* @type boolean
*/
hasMore?: boolean;
}
export interface UndoRequestDTO {
/**
* @type string
@@ -770,29 +726,28 @@ export interface UpdateThreadRequestDTO {
archived?: UpdateThreadRequestDTOArchived;
}
export type UsageResponseDTONextPage = string | null;
export type ValidationErrorDTOLocItem = string | number;
/**
* One row in the ``GET /usage`` response.
*/
export interface UsageRowDTO {
type: CounterTypeNameDTO;
scope: ScopeDTO;
used: number;
limit: number;
/**
* @type string
* @format date-time
*/
resetsAt: string;
}
export type ValidationErrorDTOCtx = { [key: string]: unknown };
export interface UsageResponseDTO {
export interface ValidationErrorDTO {
/**
* @type array
*/
data: UsageRowDTO[];
nextPage?: UsageResponseDTONextPage;
loc: ValidationErrorDTOLocItem[];
/**
* @type string
*/
msg: string;
/**
* @type string
*/
type: string;
input?: unknown;
/**
* @type object
*/
ctx?: ValidationErrorDTOCtx;
}
export type ApprovalEventDTODiff = { [key: string]: unknown };
@@ -954,20 +909,6 @@ export interface ErrorEventDTO {
retryAction?: RetryActionDTO;
}
/**
* Per-connection SSE keep-alive emitted every `sse_heartbeat_interval_seconds`.
Carries no `executionId` and no `eventId` — heartbeats are wire-level
keep-alives, not part of the replayable event log.
*/
export const HeartbeatEventDTOValue = {
/**
* @type string
*/
type: 'heartbeat',
} as const;
export type HeartbeatEventDTO = typeof HeartbeatEventDTOValue;
export type MessageActionEventDTOActionMetadataId = string | null;
export type MessageActionEventDTOResourceType = string | null;
@@ -1374,14 +1315,3 @@ export type SubmitFeedbackApiV1AssistantMessagesMessageIdFeedbackPostHeaders = {
*/
'X-SigNoz-URL'?: string | null;
};
export type GetUsageApiV1AssistantUsageGetHeaders = {
/**
* @description SigNoz auth token (Bearer or raw JWT)
*/
authorization?: string | null;
/**
* @description SigNoz instance base URL for multi-tenant deployments. Falls back to SIGNOZ_API_URL env var when omitted.
*/
'X-SigNoz-URL'?: string | null;
};

View File

@@ -0,0 +1 @@
<svg width="14" height="14" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#prefix__clip0_4062_7291)" stroke-width="1.167" stroke-linecap="round" stroke-linejoin="round"><path d="M7 12.833A5.833 5.833 0 107 1.167a5.833 5.833 0 000 11.666z" fill="#E5484D" stroke="#E5484D"/><path d="M8.75 5.25l-3.5 3.5M5.25 5.25l3.5 3.5" stroke="#121317"/></g><defs><clipPath id="prefix__clip0_4062_7291"><path fill="#fff" d="M0 0h14v14H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 467 B

View File

@@ -117,7 +117,37 @@
width: 100% !important;
max-width: 100% !important;
font-family: 'Space Mono', monospace !important;
min-height: 200px !important;
// Default cap = ~5 suggestion rows + section header + footer.
// Anything beyond scrolls inside this container.
max-height: 250px !important;
overflow-y: auto !important;
// Grow the cap proportionally to the number of recent search
// rows present so all recents render in full while ~5
// suggestions remain visible below them. Each pill card is
// ~52px (36px row + 8px margin top/bottom + 8px padding) plus
// a one-time ~30px for the "Recent searches" section header.
//
// CodeMirror renders recents first (rank: 1), then
// `<completion-section>` between groups, then suggestions —
// so the first N `<li>` direct children are the recents.
// `:nth-of-type` counts only `<li>` (sections use a different
// tag), making the count-via-position trick reliable.
&:has(> li:nth-of-type(1) .cm-completionIcon-recent) {
max-height: 332px !important;
}
&:has(> li:nth-of-type(2) .cm-completionIcon-recent) {
max-height: 384px !important;
}
&:has(> li:nth-of-type(3) .cm-completionIcon-recent) {
max-height: 436px !important;
}
&:has(> li:nth-of-type(4) .cm-completionIcon-recent) {
max-height: 488px !important;
}
&:has(> li:nth-of-type(5) .cm-completionIcon-recent) {
max-height: 540px !important;
}
&::-webkit-scrollbar {
width: 0.3rem;
@@ -133,6 +163,31 @@
background: transparent;
}
// CodeMirror renders <completion-section> headers between
// option groups when the `section` field is set on each
// Completion. Style them as small caps labels with a top
// divider so the Suggestions and Recent searches groups are
// clearly distinct.
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-top: 1px solid var(--l1-border);
background-color: transparent;
}
// The first section header doesn't need a divider above it.
completion-section:first-child,
> li:first-child + completion-section,
completion-section:first-of-type {
border-top: 0;
}
li {
width: 100% !important;
max-width: 100% !important;
@@ -159,11 +214,136 @@
display: none !important;
}
// Tag the "recent" detail column so it reads as a label,
// not as an inline value. CodeMirror puts the option's
// `detail` string in `.cm-completionDetail`.
.cm-completionDetail {
margin-left: auto;
font-style: normal;
font-size: 10px;
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;
}
}
// Recent search rows render as pill-style cards: rounded
// background per row, padded inset, design-token text color.
// Targeted via the icon class CodeMirror emits — even though
// the icon itself is hidden, its element still carries the
// type class.
li:has(.cm-completionIcon-recent) {
height: auto !important;
margin: 4px 8px !important;
padding: 6px 12px !important;
width: calc(100% - 16px) !important;
max-width: calc(100% - 16px) !important;
background: #23262e !important;
color: var(--text-vanilla-400) !important;
border: 1px solid var(--l1-border) !important;
border-radius: 6px !important;
line-height: 24px !important;
// Long filter expressions truncate to a single line with
// an ellipsis instead of wrapping or pushing the inline
// delete button off-screen. `min-width: 0` on the label
// is required for ellipsis to work inside a flex parent.
.cm-completionLabel {
flex: 1;
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
&:hover,
&[aria-selected='true'] {
background: color-mix(
in srgb,
#23262e 80%,
var(--text-vanilla-400)
) !important;
color: var(--text-vanilla-400) !important;
}
// Reveal the inline delete button more strongly on hover
// or when the row is keyboard-selected.
&:hover .cm-recent-delete,
&[aria-selected='true'] .cm-recent-delete {
opacity: 1;
}
}
// Apply the same truncation to regular suggestion rows so
// long attribute names (e.g. `service.cluster.namespace.x`)
// don't push other cells off the row.
li:not(:has(.cm-completionIcon-recent)) .cm-completionLabel {
flex: 1;
min-width: 0;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
// Inline per-row delete affordance for recent searches,
// injected via the autocompletion `addToOptions` config.
.cm-recent-delete {
margin-left: auto;
display: inline-flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
padding: 0;
border: 0;
border-radius: 4px;
background: transparent;
color: var(--text-vanilla-400);
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(--text-vanilla-400) 18%,
transparent
);
}
}
}
// Footer hint bar: keyboard shortcuts at the bottom of the
// dropdown. Rendered via ::after so we don't need to inject DOM
// — the popover's outer container gets a pseudo-element below
// the scrollable list.
&::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;
}
}

View File

@@ -29,6 +29,8 @@ import {
import { useDashboardVariablesByType } from 'hooks/dashboard/useDashboardVariablesByType';
import { useIsDarkMode } from 'hooks/useDarkMode';
import useDebounce from 'hooks/useDebounce';
import * as recentQueriesStore from 'lib/recentQueries/store';
import { normalizeFilterExpression } from 'lib/recentQueries/normalize';
import { debounce, isNull } from 'lodash-es';
import {
IDetailedError,
@@ -89,6 +91,24 @@ interface QuerySearchProps {
initialExpression?: string;
}
// Maps the legacy `DataSource` enum to the V5 `SignalType` union. The string
// values match (`'logs'` / `'traces'` / `'metrics'`); narrow with a runtime
// check rather than blindly casting. Return type is inlined to keep this
// module's import surface minimal (avoids a transitive dep cycle through
// the v5 queryRange types).
function dataSourceToSignal(
dataSource: DataSource,
): 'logs' | 'traces' | 'metrics' | null {
if (
dataSource === DataSource.LOGS ||
dataSource === DataSource.TRACES ||
dataSource === DataSource.METRICS
) {
return dataSource;
}
return null;
}
function QuerySearch({
placeholder,
onChange,
@@ -1249,6 +1269,144 @@ function QuerySearch({
};
}
// Whole-expression recent-search completions. Folded into the same
// `CompletionResult` as `autoSuggestions` (see `combinedSuggestions` below)
// rather than registered as a separate completion source — CodeMirror picks
// the source with the rightmost `from`, so a parallel source with
// `from: 0` would be silently dropped in favour of the positional one.
const recentsSignal = useMemo(() => dataSourceToSignal(dataSource), [dataSource]);
// Stable section objects so CodeMirror can group options under labelled
// headers in the dropdown. `rank` orders the sections — Recent searches
// render first (top) so users can scan their own history before falling
// through to the larger Suggestions list.
const recentsSection = useMemo(
() => ({ name: 'Recent searches', rank: 1 }),
[],
);
const suggestionsSection = useMemo(() => ({ name: 'Suggestions', rank: 2 }), []);
function getRecentOptions(
fullDoc: string,
): {
label: string;
type: string;
boost: number;
section: typeof recentsSection;
recentId: string;
recentSignal: 'logs' | 'traces' | 'metrics';
apply: (
view: EditorView,
completion: unknown,
from: number,
to: number,
) => void;
}[] {
// Display gates only on signal. Recents are shown across all panel
// types for the same signal so a user can replay a query they built
// anywhere.
if (!recentsSignal) {
return [];
}
const all = recentQueriesStore.list(recentsSignal);
// Normalize both sides before substring matching so formatting
// variations (leading/trailing whitespace, spaces around operators,
// keyword casing) don't accidentally exclude a recent. `attempt != 1`
// stored, ` attempt != 1 ` typed → both normalize to `attempt!=1` and
// substring-match.
const normalizedDoc = normalizeFilterExpression(fullDoc);
const seen = new Set<string>();
const matches = all
.filter((e) => {
if (normalizedDoc === '') {
return true;
}
return normalizeFilterExpression(e.filter.expression).includes(
normalizedDoc,
);
})
// Dedupe by raw expression in case old (pre-strip) entries with
// different ID formats still live in localStorage alongside the
// new ones — most-recently-used wins.
.filter((e) => {
const key = e.filter.expression.toLowerCase().trim();
if (seen.has(key)) {
return false;
}
seen.add(key);
return true;
})
.slice(0, 5);
return matches.map((entry) => ({
label: entry.filter.expression,
type: 'recent',
boost: -50,
section: recentsSection,
// Custom fields read by the addToOptions delete-button renderer
// so it can call store.remove on click.
recentId: entry.id,
recentSignal: entry.signal,
apply: (view: EditorView): void => {
// Replace the whole document with the recent's filter
// expression. The editor's onChange fires synchronously and
// pushes the new expression up to the parent via
// `handleSearchChange`, so non-filter fields on the current
// builder query stay as-is.
view.dispatch({
changes: {
from: 0,
to: view.state.doc.length,
insert: entry.filter.expression,
},
selection: { anchor: entry.filter.expression.length },
});
},
}));
}
function combinedSuggestions(
context: CompletionContext,
): CompletionResult | null {
const fullDoc = context.state.doc.toString();
const recentOptions = getRecentOptions(fullDoc);
const result = autoSuggestions(context);
// Tag positional suggestions with the "Suggestions" section so
// CodeMirror renders a section header above them. No cap — the full
// list scrolls inside the dropdown's max-height container so users
// can always reach any key/value, with or without recents present.
const sectionedSuggestions = (result?.options || []).map((opt) => ({
...opt,
section: suggestionsSection,
}));
if (recentOptions.length === 0 && sectionedSuggestions.length === 0) {
return result;
}
// `filter: false` tells CodeMirror to skip its built-in prefix scorer.
// Both option groups are pre-filtered in their respective sources
// (autoSuggestions filters positional options by the current token;
// getRecentOptions filters recents by full-doc prefix), so disabling
// CM's scorer keeps both visible when our filters allowed them through.
if (!result) {
return {
from: 0,
to: fullDoc.length,
options: recentOptions,
filter: false,
};
}
return {
...result,
options: [...recentOptions, ...sectionedSuggestions],
filter: false,
};
}
// Effect to handle focus state and trigger suggestions
useEffect(() => {
const clearTimeout = toggleSuggestions(10);
@@ -1394,11 +1552,94 @@ function QuerySearch({
})}
extensions={[
autocompletion({
override: [autoSuggestions],
override: [combinedSuggestions],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
// Inject a delete (×) button into recent-search
// rows so users can remove individual entries
// without opening any other UI. Non-recent rows
// render an empty placeholder.
addToOptions: [
{
// Attach a native `title` tooltip to the row for
// long recent-search expressions. The pill cell
// truncates with ellipsis (see CSS); the tooltip
// reveals the full text on hover. We can't set
// attributes on the `<li>` directly from this
// render — CodeMirror appends our returned Node
// as a cell — so we defer the title-set to a
// microtask once the parent linkage is in place.
render: (completion): Node => {
const cell = document.createElement('span');
cell.style.display = 'none';
if (completion.type === 'recent') {
queueMicrotask(() => {
if (cell.parentElement) {
cell.parentElement.title = completion.label;
}
});
}
return cell;
},
position: 5,
},
{
render: (completion, _state, view): Node => {
if (completion.type !== 'recent') {
const empty = document.createElement('span');
empty.style.display = 'none';
return empty;
}
const c = completion as typeof completion & {
recentId?: string;
recentSignal?: 'logs' | 'traces' | 'metrics';
};
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 = '×';
// Stop pointerdown / mousedown / click so the
// delete doesn't also fire the apply-completion
// path. CodeMirror uses pointerdown to commit
// the selected option, so we must intercept it.
const stop = (e: Event): void => {
e.preventDefault();
e.stopPropagation();
};
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,
);
// The store mutation alone doesn't tell
// CodeMirror to re-render the open
// dropdown. Re-trigger the completion
// source so the deleted row disappears
// immediately, and re-focus the editor
// so the dropdown stays interactive.
if (view) {
view.focus();
startCompletion(view);
}
});
return btn;
},
position: 100,
},
],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,

View File

@@ -88,7 +88,6 @@ const ROUTES = {
PUBLIC_DASHBOARD: '/public/dashboard/:dashboardId',
SERVICE_ACCOUNTS_SETTINGS: '/settings/service-accounts',
AI_ASSISTANT: '/ai-assistant/:conversationId',
AI_ASSISTANT_BASE: '/ai-assistant',
AI_ASSISTANT_ICON_PREVIEW: '/ai-assistant-icon-preview',
MCP_SERVER: '/settings/mcp-server',
} as const;

View File

@@ -178,7 +178,7 @@ export default function MessageBubble({
</div>
</div>
{!isUser && !message.isRateLimitError && (
{!isUser && (
<MessageFeedback
message={message}
onRegenerate={onRegenerate}

View File

@@ -1,12 +1,10 @@
/* eslint-disable sonarjs/cognitive-complexity */
import axios from 'axios';
import { v4 as uuidv4 } from 'uuid';
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
import type {
ErrorResponseDTO,
MessageActionDTO,
MessageSummaryDTOBlocksAnyOfItem,
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
@@ -23,6 +21,7 @@ import {
regenerateMessage,
rejectExecution,
sendMessage as sendMessageToThread,
SSEStreamError,
streamEvents,
submitFeedback,
ThreadSummary,
@@ -194,75 +193,13 @@ function resetStreamingState(
};
}
/**
* Marker thrown by `runStreamingLoop` when an SSE event reports
* `invalid_token`. Callers that own an originating action (sendMessage /
* approve / clarify / regenerate) catch this and re-issue that action via
* `streamWithAuthRetry`; the retry's first REST call will 401, at which point
* the shared axios `interceptorRejected` rotates the access token and replays.
*/
class AuthExpiredError extends Error {
constructor() {
super('Access token expired during execution');
this.name = 'AuthExpiredError';
}
}
/**
* Runs the originating action (e.g. sendMessage POST) and streams the
* resulting execution. On `AuthExpiredError`, re-issues `start` once — the
* retry's REST call hits 401, the shared axios interceptor rotates the
* access token and replays, and the new SSE picks up the rotated token from
* localStorage. Backend signals `retryAction: 'manual'` for `invalid_token`,
* so the dead execution can't be resumed — only a fresh one helps.
*/
async function streamWithAuthRetry(
conversationId: string,
start: () => Promise<string>,
set: StoreSetter,
): Promise<void> {
for (let attempt = 0; attempt <= 1; attempt += 1) {
if (attempt > 0) {
// Drop any partial content/events from the previous attempt so the
// retried execution's stream isn't concatenated with the dead one.
set((s) => {
resetStreamingState(s, conversationId);
});
}
// eslint-disable-next-line no-await-in-loop
const executionId = await start();
const ctrl = newStreamController(conversationId);
try {
// eslint-disable-next-line no-await-in-loop
await runStreamingLoop(executionId, {
conversationId,
set,
signal: ctrl.signal,
});
streamControllers.delete(conversationId);
return;
} catch (err) {
streamControllers.delete(conversationId);
if (err instanceof AuthExpiredError && attempt < 1) {
continue;
}
throw err;
}
}
}
/**
* Runs one SSE execution stream, updating the per-conversation stream state.
*
* Breaks early and sets pendingApproval / pendingClarification when the
* agent needs user input before it can continue.
*
* On an `invalid_token` error event (e.g. MCP auth expired mid-execution),
* throws `AuthExpiredError` so the caller can re-issue the originating
* action via `streamWithAuthRetry`. We don't refresh here ourselves — the
* retry's REST call will 401 and the shared axios `interceptorRejected`
* handles rotation + replay. Throws on any other `error` event — the
* caller's catch block handles UI feedback.
* Throws on `error` events — the caller's catch block handles UI feedback.
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
async function runStreamingLoop(
@@ -388,15 +325,6 @@ async function runStreamingLoop(
});
break;
} else if (event.type === 'error') {
// MCP/SigNoz auth expired mid-execution — signal the caller to
// re-issue the originating action. The retry's REST call will hit
// 401 and the shared axios `interceptorRejected` will rotate the
// access token + replay, so we don't refresh here ourselves.
// (Backend sets `retryAction: 'manual'`, so the failed execution
// can't itself be resumed — only a fresh one helps.)
if (event.error.code === 'invalid_token') {
throw new AuthExpiredError();
}
throw Object.assign(new Error(event.error.message), {
retryAction: event.retryAction,
});
@@ -484,41 +412,13 @@ function hasPendingInput(conversationId: string, get: StoreGetter): boolean {
return Boolean(stream?.pendingApproval || stream?.pendingClarification);
}
function parseErrorBody(value: unknown): string | null {
if (typeof value === 'string') {
try {
return parseErrorBody(JSON.parse(value));
} catch {
return null;
}
}
const message = (value as ErrorResponseDTO | undefined)?.error?.message;
return typeof message === 'string' && message.length > 0 ? message : null;
}
/**
* Returns the backend's `error.message` when `err` is a 429 axios response
* (typically from the threads API surface — createThread, sendMessage, approve,
* clarify, regenerate). Returns null for any other error so callers fall
* through to their generic copy.
*/
function rateLimitMessage(err: unknown): string | null {
if (axios.isAxiosError(err) && err.response?.status === 429) {
return parseErrorBody(err.response.data);
}
return null;
}
/**
* Commits an error message and removes the stream entry. When `isRateLimit`
* is true, the committed message is flagged so the feedback/regenerate bar
* is hidden — clicking regenerate would just 429 again.
* Commits an error message and removes the stream entry.
*/
function finalizeStreamingError(
conversationId: string,
errorContent: string,
set: StoreSetter,
isRateLimit = false,
): void {
set((s) => {
const conv = s.conversations[conversationId];
@@ -528,7 +428,6 @@ function finalizeStreamingError(
role: 'assistant',
content: errorContent,
createdAt: Date.now(),
...(isRateLimit ? { isRateLimitError: true } : {}),
});
conv.updatedAt = Date.now();
}
@@ -902,12 +801,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
});
// Reconnect to SSE if backend execution is still running
// and we don't already have an active SSE reader for this
// thread. No auth-retry wrapper here: on `invalid_token`
// there's no "originating action" to redo — reopening the
// same dead executionId would just re-emit the failure.
// Let the error bubble; the user can send a new message,
// which will go through `streamWithAuthRetry`.
// and we don't already have an active SSE reader for this thread
if (
detail.activeExecutionId &&
!streamControllers.has(threadId) &&
@@ -1158,12 +1052,14 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
}
});
}
const tid = threadId;
await streamWithAuthRetry(
convId,
() => sendMessageToThread(tid, text, contexts),
const executionId = await sendMessageToThread(threadId, text, contexts);
const ctrl = newStreamController(convId);
await runStreamingLoop(executionId, {
conversationId: convId,
set,
);
signal: ctrl.signal,
});
streamControllers.delete(convId);
if (!hasPendingInput(convId, get)) {
finalizeStreamingMessage(convId, set, get);
@@ -1174,14 +1070,11 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
return;
}
console.error('[AIAssistant] sendMessage failed:', err);
const rateLimit = rateLimitMessage(err);
finalizeStreamingError(
convId,
rateLimit ??
'Something went wrong while fetching the response. Please try again.',
set,
rateLimit !== null,
);
const message =
err instanceof SSEStreamError && err.status === 429
? 'You sent that a bit too quickly. Please wait a moment and try again.'
: 'Something went wrong while fetching the response. Please try again.';
finalizeStreamingError(convId, message, set);
}
},
@@ -1201,11 +1094,14 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
});
try {
await streamWithAuthRetry(
const executionId = await approveExecution(approvalId);
const ctrl = newStreamController(conversationId);
await runStreamingLoop(executionId, {
conversationId,
() => approveExecution(approvalId),
set,
);
signal: ctrl.signal,
});
streamControllers.delete(conversationId);
if (!hasPendingInput(conversationId, get)) {
finalizeStreamingMessage(conversationId, set, get);
}
@@ -1214,13 +1110,10 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
return;
}
console.error('[AIAssistant] approveAction failed:', err);
const rateLimit = rateLimitMessage(err);
finalizeStreamingError(
conversationId,
rateLimit ??
'Something went wrong while processing the approval. Please try again.',
'Something went wrong while processing the approval. Please try again.',
set,
rateLimit !== null,
);
}
},
@@ -1283,11 +1176,14 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
});
try {
await streamWithAuthRetry(
const executionId = await regenerateMessage(messageId);
const ctrl = newStreamController(conversationId);
await runStreamingLoop(executionId, {
conversationId,
() => regenerateMessage(messageId),
set,
);
signal: ctrl.signal,
});
streamControllers.delete(conversationId);
if (!hasPendingInput(conversationId, get)) {
finalizeStreamingMessage(conversationId, set, get);
}
@@ -1296,13 +1192,10 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
return;
}
console.error('[AIAssistant] regenerateAssistantMessage failed:', err);
const rateLimit = rateLimitMessage(err);
finalizeStreamingError(
conversationId,
rateLimit ??
'Something went wrong while regenerating the response. Please try again.',
'Something went wrong while regenerating the response. Please try again.',
set,
rateLimit !== null,
);
}
},
@@ -1352,11 +1245,14 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
});
try {
await streamWithAuthRetry(
const executionId = await clarifyExecution(clarificationId, answers);
const ctrl = newStreamController(conversationId);
await runStreamingLoop(executionId, {
conversationId,
() => clarifyExecution(clarificationId, answers),
set,
);
signal: ctrl.signal,
});
streamControllers.delete(conversationId);
if (!hasPendingInput(conversationId, get)) {
finalizeStreamingMessage(conversationId, set, get);
}
@@ -1365,13 +1261,10 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
return;
}
console.error('[AIAssistant] submitClarification failed:', err);
const rateLimit = rateLimitMessage(err);
finalizeStreamingError(
conversationId,
rateLimit ??
'Something went wrong while processing your answers. Please try again.',
'Something went wrong while processing your answers. Please try again.',
set,
rateLimit !== null,
);
}
},

View File

@@ -86,11 +86,6 @@ export interface Message {
actions?: MessageActionDTO[];
/** Persisted feedback rating — set after user votes and the API confirms. */
feedbackRating?: FeedbackRating | null;
/**
* Set on client-side rate-limit error messages so the feedback/regenerate
* bar (copy/vote/regenerate) is hidden — retrying would just 429 again.
*/
isRateLimitError?: boolean;
createdAt: number;
}

View File

@@ -24,6 +24,7 @@ import {
} from 'container/TopNav/DateTimeSelectionV2/types';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useResizeObserver } from 'hooks/useDimensions';
import useUrlQuery from 'hooks/useUrlQuery';
@@ -195,6 +196,8 @@ function ChartPreview({
},
);
useSaveRecentQuery(query);
useEffect(() => {
onFetchingStateChange?.(queryResponse.isFetching);
}, [queryResponse.isFetching, onFetchingStateChange]);

View File

@@ -11,6 +11,7 @@ import { populateMultipleResults } from 'container/NewWidget/LeftContainer/Widge
import { CustomTimeType } from 'container/TopNav/DateTimeSelectionV2/types';
import { useIsPanelWaitingOnVariable } from 'hooks/dashboard/useVariableFetchState';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import { useIntersectionObserver } from 'hooks/useIntersectionObserver';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { getDashboardVariables } from 'lib/dashboardVariables/getDashboardVariables';
@@ -283,6 +284,8 @@ function GridCardGraph({
},
);
useSaveRecentQuery(widget?.query);
const isEmptyLayout = widget?.id === PANEL_TYPES.EMPTY_WIDGET;
if (queryResponse.data && widget.panelTypes === PANEL_TYPES.BAR) {

View File

@@ -9,6 +9,8 @@ import { useOptionsMenu } from 'container/OptionsMenu';
import { ArrowUp10, Minus } from '@signozhq/icons';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import QueryStatus from './QueryStatus';
function LogsActionsContainer({
listQuery,
selectedPanelType,
@@ -16,6 +18,10 @@ function LogsActionsContainer({
handleToggleFrequencyChart,
orderBy,
setOrderBy,
isFetching,
isLoading,
isError,
isSuccess,
}: {
listQuery: any;
selectedPanelType: PANEL_TYPES;
@@ -23,6 +29,10 @@ function LogsActionsContainer({
handleToggleFrequencyChart: () => void;
orderBy: string;
setOrderBy: (value: string) => void;
isFetching: boolean;
isLoading: boolean;
isError: boolean;
isSuccess: boolean;
}): JSX.Element {
const { options, config } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
@@ -96,6 +106,17 @@ function LogsActionsContainer({
</div>
</>
)}
{(selectedPanelType === PANEL_TYPES.TIME_SERIES ||
selectedPanelType === PANEL_TYPES.TABLE) && (
<div className="query-stats">
<QueryStatus
loading={isLoading || isFetching}
error={isError}
success={isSuccess}
/>
</div>
)}
</div>
</div>
</div>

View File

@@ -155,6 +155,40 @@
}
}
.query-stats {
display: flex;
align-items: center;
gap: 12px;
align-self: flex-end;
.rows {
color: var(--l2-foreground);
font-family: 'Geist Mono';
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 18px; /* 150% */
letter-spacing: 0.36px;
}
.divider {
width: 1px;
height: 14px;
background: var(--l3-background);
}
.time {
color: var(--l2-foreground);
font-family: 'Geist Mono';
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 18px; /* 150% */
letter-spacing: 0.36px;
}
}
.ant-btn {
border: none;
}

View File

@@ -0,0 +1,4 @@
.query-status {
display: flex;
align-items: center;
}

View File

@@ -0,0 +1,49 @@
import React, { useMemo } from 'react';
import { Color } from '@signozhq/design-tokens';
import { LoaderCircle, CircleCheck } from '@signozhq/icons';
import { Spin } from 'antd';
import solidXCircleUrl from '@/assets/Icons/solid-x-circle.svg';
import './QueryStatus.styles.scss';
interface IQueryStatusProps {
loading: boolean;
error: boolean;
success: boolean;
}
export default function QueryStatus(
props: IQueryStatusProps,
): React.ReactElement {
const { loading, error, success } = props;
const content = useMemo((): React.ReactElement => {
if (loading) {
return (
<Spin
spinning
size="small"
indicator={<LoaderCircle className="animate-spin" size="md" />}
/>
);
}
if (error) {
return (
<img
src={solidXCircleUrl}
alt="header"
className="error"
style={{ height: '14px', width: '14px' }}
/>
);
}
if (success) {
return (
<CircleCheck className="success" size={14} fill={Color.BG_ROBIN_500} />
);
}
return <div />;
}, [error, loading, success]);
return <div className="query-status">{content}</div>;
}

View File

@@ -37,6 +37,7 @@ import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
import { useCopyLogLink } from 'hooks/logs/useCopyLogLink';
import { useGetExplorerQueryRange } from 'hooks/queryBuilder/useGetExplorerQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQueryData from 'hooks/useUrlQueryData';
import useUrlYAxisUnit from 'hooks/useUrlYAxisUnit';
@@ -160,7 +161,7 @@ function LogsExplorerViewsContainer({
'custom',
);
const { data, isLoading, isFetching, isError, error } =
const { data, isLoading, isFetching, isError, isSuccess, error } =
useGetExplorerQueryRange(
requestData,
selectedPanelType,
@@ -188,6 +189,8 @@ function LogsExplorerViewsContainer({
'custom',
);
useSaveRecentQuery(stagedQuery);
const getRequestData = useCallback(
(
query: Query | null,
@@ -437,6 +440,10 @@ function LogsExplorerViewsContainer({
handleToggleFrequencyChart={handleToggleFrequencyChart}
orderBy={orderBy}
setOrderBy={setOrderBy}
isFetching={isFetching}
isLoading={isLoading}
isError={isError}
isSuccess={isSuccess}
/>
)}

View File

@@ -16,6 +16,7 @@ import { QueryBuilderProps } from 'container/QueryBuilder/QueryBuilder.interface
import DateTimeSelector from 'container/TopNav/DateTimeSelectionV2';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import {
ICurrentQueryData,
useHandleExplorerTabChange,
@@ -62,6 +63,9 @@ function Explorer(): JSX.Element {
handleSetQueryData,
redirectWithQueryBuilderData,
} = useQueryBuilder();
useSaveRecentQuery(stagedQuery);
const { safeNavigate } = useSafeNavigate();
const { handleExplorerTabChange } = useHandleExplorerTabChange();
const isAIAssistantEnabled = useIsAIAssistantEnabled();

View File

@@ -25,6 +25,7 @@ import { usePageSize } from 'container/InfraMonitoringK8s/utils';
import NoLogs from 'container/NoLogs/NoLogs';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { AppState } from 'store/reducers';
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
@@ -69,6 +70,8 @@ function Summary(): JSX.Element {
const { currentQuery, stagedQuery, redirectWithQueryBuilderData } =
useQueryBuilder();
useSaveRecentQuery(stagedQuery);
useShareBuilderUrl({ defaultValue: initialQueriesMap[DataSource.METRICS] });
const query = useMemo(

View File

@@ -7,6 +7,7 @@ import { PANEL_TYPES } from 'constants/queryBuilder';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
@@ -64,6 +65,8 @@ function LeftContainer({
keepPreviousData: true,
});
useSaveRecentQuery(stagedQuery);
useEffect(() => {
if (queryResponse.isFetching) {
setIsCancelled(false);

View File

@@ -16,6 +16,7 @@ import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { QueryTable } from 'container/QueryTable';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import { AppState } from 'store/reducers';
import { Warning } from 'types/api';
import APIError from 'types/api/error';
@@ -71,6 +72,8 @@ function TableView({
},
);
useSaveRecentQuery(stagedQuery);
useEffect(() => {
if (isLoading || isFetching) {
setIsLoadingQueries(true);

View File

@@ -0,0 +1,88 @@
import { act, renderHook } from '@testing-library/react';
import * as store from 'lib/recentQueries/store';
import type { RecentQueryInput } from 'lib/recentQueries/store';
import { useRecentQueries } from './useRecentQueries';
const baseInput = (
overrides: Partial<RecentQueryInput> = {},
): RecentQueryInput => ({
signal: 'logs',
filter: { expression: 'a = 1' },
...overrides,
});
describe('useRecentQueries', () => {
beforeEach(() => {
store.__resetForTests();
});
it('returns the entries for the given signal', () => {
act(() => {
store.save(baseInput({ filter: { expression: 'a = 1' } }));
store.save(baseInput({ filter: { expression: 'b = 2' } }));
});
const { result } = renderHook(() => useRecentQueries('logs'));
expect(result.current.entries).toHaveLength(2);
expect(result.current.entries.map((e) => e.filter.expression)).toStrictEqual([
'b = 2',
'a = 1',
]);
});
it('does not return entries from other signals', () => {
act(() => {
store.save(baseInput({ signal: 'logs' }));
store.save(baseInput({ signal: 'traces' }));
});
const { result } = renderHook(() => useRecentQueries('logs'));
expect(result.current.entries).toHaveLength(1);
expect(result.current.entries[0].signal).toBe('logs');
});
it('re-renders when a new entry is saved', () => {
const { result } = renderHook(() => useRecentQueries('logs'));
expect(result.current.entries).toHaveLength(0);
act(() => {
store.save(baseInput());
});
expect(result.current.entries).toHaveLength(1);
});
it('re-renders when an entry is removed via the returned remove fn', () => {
const { result } = renderHook(() => useRecentQueries('logs'));
act(() => {
store.save(baseInput());
});
expect(result.current.entries).toHaveLength(1);
const id = result.current.entries[0].id;
act(() => {
result.current.remove(id);
});
expect(result.current.entries).toHaveLength(0);
});
it('keeps a stable entries reference when nothing changed', () => {
act(() => {
store.save(baseInput());
});
const { result, rerender } = renderHook(() => useRecentQueries('logs'));
const first = result.current.entries;
rerender();
const second = result.current.entries;
expect(second).toBe(first);
});
});

View File

@@ -0,0 +1,39 @@
import { useCallback, useSyncExternalStore } from 'react';
import type { SignalType } from 'types/api/v5/queryRange';
import * as store from 'lib/recentQueries/store';
import type { RecentQueryEntry } from 'lib/recentQueries/types';
export interface UseRecentQueriesReturn {
entries: RecentQueryEntry[];
remove: (id: string) => void;
}
/**
* Returns the recent-query entries for a given signal, sorted by
* most-recently-used first (the underlying store already maintains that
* order). Subscribes to the store so saves and removes — including those
* driven by another tab via the `storage` event — re-render the consumer.
*/
export function useRecentQueries(
signal: SignalType,
): UseRecentQueriesReturn {
const getSnapshot = useCallback((): RecentQueryEntry[] => store.list(signal), [
signal,
]);
const entries = useSyncExternalStore(
store.subscribe,
getSnapshot,
getSnapshot,
);
const remove = useCallback(
(id: string): void => {
store.remove(id, signal);
},
[signal],
);
return { entries, remove };
}

View File

@@ -0,0 +1,144 @@
import { renderHook } from '@testing-library/react';
import { EQueryType } from 'types/common/dashboard';
import { DataSource } from 'types/common/queryBuilder';
import type {
IBuilderQuery,
Query,
} from 'types/api/queryBuilder/queryBuilderData';
import { validateQuery } from 'utils/queryValidationUtils';
import * as store from 'lib/recentQueries/store';
import { useSaveRecentQuery } from './useSaveRecentQuery';
jest.mock('utils/queryValidationUtils', () => ({
validateQuery: jest.fn(),
}));
const mockedValidateQuery = validateQuery as jest.MockedFunction<
typeof validateQuery
>;
const buildQuery = (overrides: Partial<IBuilderQuery>[] = [{}]): Query => ({
queryType: EQueryType.QUERY_BUILDER,
promql: [],
clickhouse_sql: [],
id: 'q1',
builder: {
queryFormulas: [],
queryTraceOperator: [],
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('useSaveRecentQuery', () => {
beforeEach(() => {
store.__resetForTests();
mockedValidateQuery.mockReturnValue({
isValid: true,
message: '',
errors: [],
});
});
it('saves the staged query when validation passes', () => {
const stagedQuery = buildQuery();
renderHook(() => useSaveRecentQuery(stagedQuery));
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: [],
});
const stagedQuery = buildQuery();
renderHook(() => useSaveRecentQuery(stagedQuery));
expect(store.list('logs')).toHaveLength(0);
});
it('does not save a builder query with an empty filter expression', () => {
const stagedQuery = buildQuery([{ filter: { expression: '' } }]);
renderHook(() => useSaveRecentQuery(stagedQuery));
expect(store.list('logs')).toHaveLength(0);
});
it('saves each builder query in the composite separately', () => {
const stagedQuery = buildQuery([
{
dataSource: DataSource.LOGS,
filter: { expression: 'service.name = "a"' },
},
{
dataSource: DataSource.TRACES,
filter: { expression: 'service.name = "b"' },
},
]);
renderHook(() => useSaveRecentQuery(stagedQuery));
expect(store.list('logs')).toHaveLength(1);
expect(store.list('traces')).toHaveLength(1);
});
it('does not re-save when the staged query has not changed', () => {
const stagedQuery = buildQuery();
const { rerender } = renderHook(
({ q }: { q: Query }) => useSaveRecentQuery(q),
{ initialProps: { q: stagedQuery } },
);
const firstTimestamp = store.list('logs')[0].lastUsedAt;
rerender({ q: stagedQuery });
const second = store.list('logs');
expect(second).toHaveLength(1);
expect(second[0].lastUsedAt).toBe(firstTimestamp);
});
it('re-saves when the staged query filter changes', () => {
const initial = buildQuery([{ filter: { expression: 'a = 1' } }]);
const changed = buildQuery([{ filter: { expression: 'b = 2' } }]);
const { rerender } = renderHook(
({ q }: { q: Query }) => useSaveRecentQuery(q),
{ initialProps: { q: initial } },
);
expect(store.list('logs')).toHaveLength(1);
rerender({ q: changed });
expect(store.list('logs')).toHaveLength(2);
});
it('is a no-op when stagedQuery is null', () => {
renderHook(() => useSaveRecentQuery(null));
expect(store.list('logs')).toHaveLength(0);
});
});

View File

@@ -0,0 +1,94 @@
import { useEffect, useRef } from 'react';
import type {
IBuilderQuery,
Query,
} from 'types/api/queryBuilder/queryBuilderData';
import type { SignalType } from 'types/api/v5/queryRange';
import { validateQuery } from 'utils/queryValidationUtils';
import * as store from 'lib/recentQueries/store';
// Legacy `IBuilderQuery.dataSource` uses the `DataSource` enum, whose string
// values match `SignalType`. Narrow with a runtime check rather than blindly
// casting — guards against any future drift.
function toSignal(dataSource: IBuilderQuery['dataSource']): SignalType | null {
if (
dataSource === 'logs' ||
dataSource === 'traces' ||
dataSource === 'metrics'
) {
return dataSource;
}
return null;
}
// Build a stable signature of the staged filter expressions so the effect
// knows when a re-save is genuinely warranted vs. when we're seeing the same
// state across renders.
function buildSignature(stagedQuery: Query | null | undefined): string | null {
if (!stagedQuery) {
return null;
}
const queryData = stagedQuery.builder?.queryData;
if (!Array.isArray(queryData) || queryData.length === 0) {
return null;
}
return JSON.stringify(
queryData.map((q) => ({
ds: q.dataSource,
f: q.filter?.expression ?? '',
})),
);
}
/**
* Save each builder query's filter expression in
* `stagedQuery.builder.queryData[]` to the recent-queries store.
*
* Gate: frontend grammar — `validateQuery(expression)` must accept it.
*
* We intentionally do NOT gate on a backend `isSuccess` flag. An
* investigation often runs queries that return zero results (e.g. searching
* for a rare error condition that doesn't currently exist in the data),
* and the user still wants to replay that query later. The frontend
* grammar check rejects expressions that don't parse; everything else is
* the user's intent worth preserving.
*
* The hook saves only the filter expression. Selecting a recent restores
* only the filter; the rest of the user's builder query (groupBy/orderBy/
* having/limit) is left untouched.
*/
export function useSaveRecentQuery(
stagedQuery: Query | null | undefined,
): void {
const lastSavedSignatureRef = useRef<string | null>(null);
useEffect(() => {
const signature = buildSignature(stagedQuery);
if (!signature || signature === lastSavedSignatureRef.current) {
return;
}
const queryData = stagedQuery?.builder?.queryData ?? [];
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,
filter: q.filter ?? { expression: '' },
});
});
lastSavedSignatureRef.current = signature;
}, [stagedQuery]);
}

View File

@@ -0,0 +1,65 @@
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('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"`,
);
});
});

View File

@@ -0,0 +1,53 @@
// Lowercase only the standalone keywords/operators that have case-insensitive
// semantics in the query grammar. Identifiers and unquoted values are left
// alone — case may be meaningful there.
const KEYWORDS_RE = /\b(AND|OR|NOT|IN|LIKE|ILIKE|CONTAINS|EXISTS|BETWEEN|IS|NULL|TRUE|FALSE)\b/gi;
// Match a quoted string literal (single- or double-quoted) with simple
// backslash escapes. Used to skip over value regions so we don't touch their
// casing or whitespace.
const QUOTED_RE = /'(?:\\.|[^'\\])*'|"(?:\\.|[^"\\])*"/g;
function processOutsideQuotes(s: string): string {
// 1. Lowercase keywords while spaces are still in place so word-boundary
// matching works (`\bAND\b`).
// 2. Strip all remaining whitespace. Glued identifiers are acceptable —
// this string is only used as an internal dedup key, never displayed.
return s.replace(KEYWORDS_RE, (m) => m.toLowerCase()).replace(/\s+/g, '');
}
/**
* Normalize a filter expression for dedup purposes only.
*
* Pipeline: lowercase known keywords/operators (AND, OR, IN, NOT, LIKE, …)
* outside quoted strings, then strip all whitespace outside quoted strings.
* Casing and whitespace inside quoted string values are preserved.
*
* The result is intentionally not human-readable — it's an internal dedup key.
* The original raw expression text stays on the entry for display and prefix
* matching.
*
* This is not a parser — it catches the common formatting drift
* (`a = "x"` vs `a="x"` vs `a = 'x'` vs `A AND B` vs `a and b`) without
* trying to canonicalize the AST.
*/
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();
}

View File

@@ -0,0 +1,206 @@
import * as store from './store';
import type { RecentQueryInput } from './store';
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.__resetForTests();
});
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: 'a = 1' } }));
store.save(baseInput({ filter: { expression: 'b = 2' } }));
store.save(baseInput({ filter: { expression: 'c = 3' } }));
const entries = store.list('logs');
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
'c = 3',
'b = 2',
'a = 1',
]);
});
it('re-saving an existing filter bumps it to the front', () => {
store.save(baseInput({ filter: { expression: 'a = 1' } }));
store.save(baseInput({ filter: { expression: 'b = 2' } }));
store.save(baseInput({ filter: { expression: 'a = 1' } }));
const entries = store.list('logs');
expect(entries).toHaveLength(2);
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
'a = 1',
'b = 2',
]);
});
});
describe('dedup', () => {
it('treats formatting variations of the same filter as one entry', () => {
store.save(baseInput({ filter: { expression: 'a = 1 AND b = 2' } }));
store.save(baseInput({ filter: { expression: 'a=1 and b=2' } }));
expect(store.list('logs')).toHaveLength(1);
});
});
describe('signal partitioning', () => {
it('saves to the right bucket per signal', () => {
store.save(baseInput({ signal: 'logs', filter: { expression: 'a = 1' } }));
store.save(
baseInput({ signal: 'traces', filter: { expression: 'b = 2' } }),
);
store.save(
baseInput({ signal: 'metrics', filter: { expression: 'c = 3' } }),
);
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('a = 1');
expect(store.list('traces')[0].filter.expression).toBe('b = 2');
expect(store.list('metrics')[0].filter.expression).toBe('c = 3');
});
it('does not leak between signals on dedup', () => {
store.save(baseInput({ signal: 'logs', filter: { expression: 'a = 1' } }));
store.save(
baseInput({ signal: 'traces', filter: { expression: 'a = 1' } }),
);
expect(store.list('logs')).toHaveLength(1);
expect(store.list('traces')).toHaveLength(1);
});
});
describe('LRU cap', () => {
it('caps the bucket at 10 entries and evicts the oldest', () => {
for (let i = 0; i < 11; i += 1) {
store.save(baseInput({ filter: { expression: `attr_${i} = 1` } }));
}
const entries = store.list('logs');
expect(entries).toHaveLength(10);
expect(entries[0].filter.expression).toBe('attr_10 = 1');
expect(
entries.some((e) => e.filter.expression === 'attr_0 = 1'),
).toBe(false);
});
});
describe('remove', () => {
it('removes an entry by id', () => {
store.save(baseInput({ filter: { expression: 'a = 1' } }));
const saved = saveOrThrow(baseInput({ filter: { expression: 'b = 2' } }));
store.remove(saved.id, 'logs');
const entries = store.list('logs');
expect(entries).toHaveLength(1);
expect(entries[0].filter.expression).toBe('a = 1');
});
it('is a no-op when the id does not exist', () => {
store.save(baseInput({ filter: { expression: 'a = 1' } }));
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: 'a = 1' } }),
);
store.save(baseInput({ signal: 'traces', filter: { expression: 'a = 1' } }));
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 cache is dropped', () => {
store.save(baseInput({ filter: { expression: 'a = 1' } }));
store.save(baseInput({ filter: { expression: 'b = 2' } }));
store.__dropCacheForTests();
const entries = store.list('logs');
expect(entries.map((e) => e.filter.expression)).toStrictEqual([
'b = 2',
'a = 1',
]);
});
});
describe('subscribe', () => {
it('notifies subscribers on save', () => {
const cb = jest.fn();
store.subscribe(cb);
store.save(baseInput({ filter: { expression: 'a = 1' } }));
expect(cb).toHaveBeenCalledTimes(1);
});
it('notifies subscribers on remove', () => {
const saved = saveOrThrow(baseInput({ filter: { expression: 'a = 1' } }));
const cb = jest.fn();
store.subscribe(cb);
store.remove(saved.id, 'logs');
expect(cb).toHaveBeenCalledTimes(1);
});
it('stops notifying after unsubscribe', () => {
const cb = jest.fn();
const unsubscribe = store.subscribe(cb);
unsubscribe();
store.save(baseInput({ filter: { expression: 'a = 1' } }));
expect(cb).not.toHaveBeenCalled();
});
it('does not notify for no-op removes', () => {
const cb = jest.fn();
store.subscribe(cb);
store.remove('does-not-exist', 'logs');
expect(cb).not.toHaveBeenCalled();
});
});
});

View File

@@ -0,0 +1,187 @@
import type { SignalType } from 'types/api/v5/queryRange';
import { normalizeFilterExpression } from './normalize';
import type {
RecentQueriesStoreShape,
RecentQueryEntry,
} from './types';
const STORAGE_KEY_PREFIX = 'qb_recent_v1';
const STORAGE_VERSION = 1;
const MAX_ENTRIES = 10;
const QUOTA_RETRY_FRACTION = 0.8;
const SIGNALS: readonly SignalType[] = ['logs', 'traces', 'metrics'];
const storageKey = (signal: SignalType): string =>
`${STORAGE_KEY_PREFIX}:${signal}`;
const cache = new Map<SignalType, RecentQueryEntry[]>();
const subscribers = new Set<() => void>();
function hasLocalStorage(): boolean {
return (
typeof window !== 'undefined' && typeof window.localStorage !== 'undefined'
);
}
function readFromStorage(signal: SignalType): RecentQueryEntry[] {
if (!hasLocalStorage()) {
return [];
}
try {
const raw = window.localStorage.getItem(storageKey(signal));
if (!raw) {
return [];
}
const parsed = JSON.parse(raw) as RecentQueriesStoreShape;
if (parsed?.version !== STORAGE_VERSION || !Array.isArray(parsed.entries)) {
return [];
}
return parsed.entries;
} catch {
return [];
}
}
// Attempts to persist; on write failure (typically QuotaExceededError), drops
// the oldest fraction and retries once. Returns the entries that were actually
// written (caller should mirror this into the in-memory cache so reads stay
// consistent).
function writeToStorage(
signal: SignalType,
entries: RecentQueryEntry[],
): RecentQueryEntry[] {
if (!hasLocalStorage()) {
return entries;
}
const persist = (toWrite: RecentQueryEntry[]): boolean => {
try {
window.localStorage.setItem(
storageKey(signal),
JSON.stringify({ version: STORAGE_VERSION, entries: toWrite }),
);
return true;
} catch {
// Swallow quota and other write errors. Caller retries with a trimmed
// list when this returns false.
return false;
}
};
if (persist(entries)) {
return entries;
}
const trimmed = entries.slice(
0,
Math.max(1, Math.floor(entries.length * QUOTA_RETRY_FRACTION)),
);
if (persist(trimmed)) {
return trimmed;
}
return entries;
}
function getCache(signal: SignalType): RecentQueryEntry[] {
const existing = cache.get(signal);
if (existing) {
return existing;
}
const fresh = readFromStorage(signal);
cache.set(signal, fresh);
return fresh;
}
function notify(): void {
subscribers.forEach((cb) => cb());
}
// Deterministic id derived from the dedup key. Two saves with the same
// (signal, normalized filter) produce the same id and upsert.
function makeId(signal: SignalType, normalizedFilter: string): string {
return `${signal}|${normalizedFilter}`;
}
export type RecentQueryInput = Omit<RecentQueryEntry, 'id' | 'lastUsedAt'>;
export function list(signal: SignalType): RecentQueryEntry[] {
return getCache(signal);
}
export function save(entry: RecentQueryInput): RecentQueryEntry | null {
const normalized = normalizeFilterExpression(entry.filter.expression);
if (!normalized) {
return null;
}
const id = makeId(entry.signal, normalized);
const current = getCache(entry.signal);
const filtered = current.filter((e) => e.id !== id);
const newEntry: RecentQueryEntry = {
...entry,
id,
lastUsedAt: Date.now(),
};
const next = [newEntry, ...filtered].slice(0, MAX_ENTRIES);
const persisted = writeToStorage(entry.signal, next);
cache.set(entry.signal, persisted);
notify();
return newEntry;
}
export function remove(id: string, signal: SignalType): void {
const current = getCache(signal);
const next = current.filter((e) => e.id !== id);
if (next.length === current.length) {
return;
}
const persisted = writeToStorage(signal, next);
cache.set(signal, persisted);
notify();
}
export function subscribe(cb: () => void): () => void {
subscribers.add(cb);
return (): void => {
subscribers.delete(cb);
};
}
function handleCrossTabStorageEvent(event: StorageEvent): void {
if (!event.key || !event.key.startsWith(`${STORAGE_KEY_PREFIX}:`)) {
return;
}
const signal = event.key.slice(STORAGE_KEY_PREFIX.length + 1) as SignalType;
if (!SIGNALS.includes(signal)) {
return;
}
cache.set(signal, readFromStorage(signal));
notify();
}
if (
typeof window !== 'undefined' &&
typeof window.addEventListener === 'function'
) {
window.addEventListener('storage', handleCrossTabStorageEvent);
}
// Test-only escape hatch. Clears in-memory cache, subscribers, and the
// localStorage keys we own. Should not be called from production code.
export function __resetForTests(): void {
cache.clear();
subscribers.clear();
if (hasLocalStorage()) {
SIGNALS.forEach((s) => window.localStorage.removeItem(storageKey(s)));
}
}
// Test-only escape hatch. Drops the in-memory cache without touching
// localStorage, letting tests simulate a fresh page load that rehydrates from
// persisted data. Should not be called from production code.
export function __dropCacheForTests(): void {
cache.clear();
}

View File

@@ -0,0 +1,16 @@
import type { Filter, SignalType } from 'types/api/v5/queryRange';
// A stored recent search. We persist only the where-clause expression — the
// rest of the query bundle (groupBy/orderBy/having/limit) lives on the
// current builder query and is left untouched when a recent is selected.
export interface RecentQueryEntry {
id: string;
signal: SignalType;
filter: Filter;
lastUsedAt: number;
}
export interface RecentQueriesStoreShape {
version: 1;
entries: RecentQueryEntry[];
}

View File

@@ -8,7 +8,6 @@
align-items: center;
padding: 8px 16px;
gap: 8px;
min-height: 52px;
// KeyValueLabel renders with a global `.key-value-label` root; keep it from
// shrinking on the trace details header.
@@ -21,28 +20,6 @@
flex-shrink: 0;
}
.traceIdSection {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.filterSection {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
margin-left: auto;
}
.headerActions {
display: flex;
align-items: center;
gap: 8px;
flex-shrink: 0;
}
.filter {
min-width: 0;
}
@@ -52,6 +29,15 @@
flex: 1;
}
.oldViewBtn {
flex-shrink: 0;
}
.analyticsBtn {
flex-shrink: 0;
margin-left: auto;
}
.subHeader {
display: flex;
align-items: center;

View File

@@ -21,7 +21,6 @@ import {
ArrowLeft,
CalendarClock,
ChartPie,
CornerUpLeft,
Server,
Timer,
} from '@signozhq/icons';
@@ -118,7 +117,7 @@ function TraceDetailsHeader({
<div className={styles.wrapper}>
<div className={styles.header}>
{!isFilterExpanded && (
<div className={styles.traceIdSection}>
<>
<Button
variant="solid"
color="secondary"
@@ -134,39 +133,20 @@ function TraceDetailsHeader({
badgeValue={traceID || ''}
maxCharacters={100}
/>
</div>
</>
)}
{isDataLoaded && (
<div
className={cx(
styles.filterSection,
isFilterExpanded && styles.isExpanded,
)}
>
<>
{!isFilterExpanded && (
<TooltipProvider>
<div className={styles.headerActions}>
<>
<TooltipProvider>
<TooltipRoot>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
color="secondary"
aria-label="Switch to legacy trace view"
onClick={handleSwitchToOldView}
>
<CornerUpLeft size={14} />
</Button>
</TooltipTrigger>
<TooltipContent>Switch to legacy trace view</TooltipContent>
</TooltipRoot>
<TooltipRoot>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
color="secondary"
aria-label="Analytics"
className={styles.analyticsBtn}
onClick={(): void => setIsAnalyticsOpen((prev) => !prev)}
>
<ChartPie size={14} />
@@ -174,18 +154,15 @@ function TraceDetailsHeader({
</TooltipTrigger>
<TooltipContent>Analytics</TooltipContent>
</TooltipRoot>
<TraceOptionsMenu
showTraceDetails={showTraceDetails}
onToggleTraceDetails={handleToggleTraceDetails}
onOpenPreviewFields={(): void => setIsPreviewFieldsOpen(true)}
/>
</div>
</TooltipProvider>
</TooltipProvider>
<TraceOptionsMenu
showTraceDetails={showTraceDetails}
onToggleTraceDetails={handleToggleTraceDetails}
onOpenPreviewFields={(): void => setIsPreviewFieldsOpen(true)}
/>
</>
)}
<div
key="filter"
className={cx(styles.filter, isFilterExpanded && styles.isExpanded)}
>
<div className={cx(styles.filter, isFilterExpanded && styles.isExpanded)}>
<Filters
startTime={filterMetadata.startTime}
endTime={filterMetadata.endTime}
@@ -196,7 +173,18 @@ function TraceDetailsHeader({
onCollapse={(): void => setIsFilterExpanded(false)}
/>
</div>
</div>
{!isFilterExpanded && (
<Button
variant="solid"
color="secondary"
size="sm"
className={styles.oldViewBtn}
onClick={handleSwitchToOldView}
>
Legacy View
</Button>
)}
</>
)}
</div>

View File

@@ -2,7 +2,7 @@ import { useMemo } from 'react';
import type { MenuItem } from '@signozhq/ui/dropdown-menu';
import { Button } from '@signozhq/ui/button';
import { DropdownMenuSimple as Dropdown } from '@signozhq/ui/dropdown-menu';
import { Settings2 } from '@signozhq/icons';
import { Ellipsis } from '@signozhq/icons';
import { useTraceStore } from '../stores/traceStore';
@@ -93,8 +93,7 @@ function TraceOptionsMenu({
variant="ghost"
size="icon"
color="secondary"
aria-label="Trace options"
prefix={<Settings2 size={14} />}
prefix={<Ellipsis size={14} />}
/>
</Dropdown>
);

View File

@@ -6,7 +6,6 @@ import TraceDetailsHeader from '../TraceDetailsHeader';
const mockGoBack = jest.fn();
const mockPush = jest.fn();
const mockReplace = jest.fn();
const mockHasInAppHistory = jest.fn();
jest.mock('lib/history', () => ({
@@ -14,47 +13,13 @@ jest.mock('lib/history', () => ({
default: {
goBack: (): void => mockGoBack(),
push: (path: string): void => mockPush(path),
replace: (path: string): void => mockReplace(path),
replace: jest.fn(),
location: { pathname: '/', search: '' },
listen: (): (() => void) => (): void => undefined,
},
hasInAppHistory: (): boolean => mockHasInAppHistory(),
}));
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useParams: (): { id: string } => ({ id: 'trace-123' }),
}));
const mockSetLocalStorageKey = jest.fn();
jest.mock('api/browser/localstorage/set', () => ({
__esModule: true,
default: (key: string, value: string): void =>
mockSetLocalStorageKey(key, value),
}));
jest.mock(
'../../TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters',
() => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="filters-stub" />,
}),
);
jest.mock('../../SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel', () => ({
__esModule: true,
default: ({ isOpen }: { isOpen: boolean }): JSX.Element => (
<div data-testid="analytics-panel" data-open={isOpen ? 'true' : 'false'} />
),
}));
jest.mock('components/FieldsSelector', () => ({
__esModule: true,
default: ({ isOpen }: { isOpen: boolean }): JSX.Element => (
<div data-testid="fields-selector" data-open={isOpen ? 'true' : 'false'} />
),
}));
const baseProps = {
filterMetadata: {
startTime: 0,
@@ -93,70 +58,3 @@ describe('TraceDetailsHeader back button', () => {
expect(mockGoBack).not.toHaveBeenCalled();
});
});
describe('TraceDetailsHeader action cluster', () => {
beforeEach(() => {
mockReplace.mockClear();
mockSetLocalStorageKey.mockClear();
});
it('does not render the action buttons while data is still loading', () => {
render(<TraceDetailsHeader {...baseProps} isDataLoaded={false} />);
expect(
screen.queryByRole('button', { name: /switch to legacy trace view/i }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /^analytics$/i }),
).not.toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /trace options/i }),
).not.toBeInTheDocument();
});
it('renders Legacy View, Analytics, and Settings action buttons once data is loaded', () => {
render(<TraceDetailsHeader {...baseProps} isDataLoaded />);
expect(
screen.getByRole('button', { name: /switch to legacy trace view/i }),
).toBeInTheDocument();
expect(
screen.getByRole('button', { name: /^analytics$/i }),
).toBeInTheDocument();
expect(
screen.getByRole('button', { name: /trace options/i }),
).toBeInTheDocument();
});
it('routes to the legacy trace view and persists the preference on click', () => {
render(<TraceDetailsHeader {...baseProps} isDataLoaded />);
fireEvent.click(
screen.getByRole('button', { name: /switch to legacy trace view/i }),
);
expect(mockSetLocalStorageKey).toHaveBeenCalledWith(
'TRACE_DETAILS_PREFER_OLD_VIEW',
'true',
);
expect(mockReplace).toHaveBeenCalledTimes(1);
expect(mockReplace).toHaveBeenCalledWith(
expect.stringContaining('/trace-old/trace-123'),
);
});
it('toggles the AnalyticsPanel open state when the Analytics button is clicked', () => {
render(<TraceDetailsHeader {...baseProps} isDataLoaded />);
const panel = screen.getByTestId('analytics-panel');
expect(panel).toHaveAttribute('data-open', 'false');
const analyticsBtn = screen.getByRole('button', { name: /^analytics$/i });
fireEvent.click(analyticsBtn);
expect(panel).toHaveAttribute('data-open', 'true');
fireEvent.click(analyticsBtn);
expect(panel).toHaveAttribute('data-open', 'false');
});
});

View File

@@ -3,6 +3,12 @@
align-items: center;
gap: 12px;
// QuerySearch child sets `query-builder-search-v2` globally; size it to the
// search container by reaching into the descendant.
:global(.query-builder-search-v2) {
width: 100%;
}
// ToggleGroup children use generated class names; nest the global selectors
// under the local row so they only apply inside this filter row.
:global([class*='toggle-group']) {
@@ -14,43 +20,8 @@
}
}
// Expanded-mode root: grows to fill .filter wrapper, and lets the search
// input flex within. In collapsed mode none of these grow — the whole
// Filters region is content-sized (just the pill + result + toggle).
.isExpanded {
flex: 1;
.searchInput {
flex: 1;
}
.searchAndNav {
flex: 1;
}
}
.categoryControls {
display: flex;
align-items: center;
flex-shrink: 0;
}
.searchInput {
display: flex;
align-items: center;
min-width: 0;
}
.searchPill {
display: flex;
align-items: center;
flex-shrink: 0;
}
.searchAndNav {
display: flex;
align-items: center;
min-width: 0;
}
.searchContainer {
@@ -58,25 +29,6 @@
min-width: 0;
}
.resultActions {
display: flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
}
.expandedActions {
display: flex;
align-items: center;
gap: 2px;
}
.highlightControl {
display: flex;
align-items: center;
flex-shrink: 0;
}
.pill {
display: flex;
align-items: center;
@@ -133,6 +85,14 @@
border-radius: 4px;
}
.collapseBtn {
flex-shrink: 0;
display: flex;
align-items: center;
justify-content: center;
box-shadow: none;
}
.highlightErrorsToggle {
display: flex;
align-items: center;
@@ -140,3 +100,37 @@
flex-shrink: 0;
white-space: nowrap;
}
.preNextToggle {
display: flex;
flex-shrink: 0;
gap: 12px;
}
.preNextCount {
display: flex;
align-items: center;
margin: auto;
color: var(--l2-foreground);
font-family: 'Geist Mono';
font-size: 12px;
font-weight: 400;
line-height: 18px;
}
.filterStatus {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
color: var(--l2-foreground);
font-family: 'Geist Mono';
font-size: 12px;
font-weight: 400;
line-height: 18px;
}
.hasError {
color: var(--destructive);
cursor: help;
}

View File

@@ -1,7 +1,15 @@
import { useCallback, useRef, useState } from 'react';
import { useHistory, useLocation } from 'react-router-dom';
import { useCopyToClipboard } from 'react-use';
import { ChevronsRight, Copy, Search, X } from '@signozhq/icons';
import {
ChevronDown,
ChevronUp,
Copy,
Info,
Loader,
Search,
X,
} from '@signozhq/icons';
import { Switch } from '@signozhq/ui/switch';
import { ToggleGroup, ToggleGroupItem } from '@signozhq/ui/toggle-group';
import { toast } from '@signozhq/ui/sonner';
@@ -13,6 +21,7 @@ import {
TooltipTrigger,
} from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import { AxiosError } from 'axios';
import cx from 'classnames';
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
import { convertExpressionToFilters } from 'components/QueryBuilderV2/utils';
@@ -33,7 +42,6 @@ import {
SpanCategory,
useSpanCategoryFilter,
} from './hooks/useSpanCategoryFilter';
import QueryResult from './QueryResult';
import styles from './Filters.module.scss';
@@ -144,16 +152,6 @@ function Filters({
runQuery(expressionRef.current);
}, [runQuery]);
const handleClear = useCallback((): void => {
setExpression('');
expressionRef.current = '';
setFilters({ items: [], op: 'AND' });
setFilteredSpanIds([]);
onFilteredSpansChange?.([], false);
setCurrentSearchedIndex(0);
setNoData(false);
}, [onFilteredSpansChange]);
// Expression-based filter hooks
const filterProps = {
expression,
@@ -268,167 +266,164 @@ function Filters({
</div>
);
const hasExpression = expression.trim().length > 0;
const hasResults = filteredSpanIds.length > 0;
const handlePrev = useCallback((): void => {
handlePrevNext(currentSearchedIndex - 1);
setCurrentSearchedIndex((prev) => prev - 1);
}, [currentSearchedIndex, handlePrevNext]);
const handleNext = useCallback((): void => {
handlePrevNext(currentSearchedIndex + 1);
setCurrentSearchedIndex((prev) => prev + 1);
}, [currentSearchedIndex, handlePrevNext]);
const pill = (
/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */
<div className={styles.pill} onClick={onExpand}>
<Search size={12} />
<span className={styles.pillText}>{expression || 'Search...'}</span>
{expression && <span className={styles.pillIndicator} />}
</div>
const statusIndicators = (
<>
{isFetching && <Loader className="animate-spin" />}
{error && (
<TooltipRoot>
<TooltipTrigger asChild>
<span className={cx(styles.filterStatus, styles.hasError)}>
<Info />
API error
</span>
</TooltipTrigger>
<TooltipContent>
{(error as AxiosError)?.message || 'Something went wrong'}
</TooltipContent>
</TooltipRoot>
)}
{!error && noData && (
<Typography.Text className={styles.filterStatus}>
No results found
</Typography.Text>
)}
</>
);
const pillWithPopover = expression ? (
<TooltipRoot>
<TooltipTrigger asChild>{pill}</TooltipTrigger>
<TooltipContent side="bottom" align="start">
<div className={styles.pillPopover}>
<div className={styles.pillPopoverHeader}>
<Typography.Text>Search query</Typography.Text>
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={(): void => {
setCopy(expression);
toast.success('Copied to clipboard', {
richColors: false,
position: 'top-right',
});
}}
>
<Copy size={12} />
</Button>
</div>
<div className={styles.pillPopoverExpression}>{expression}</div>
</div>
</TooltipContent>
</TooltipRoot>
) : (
pill
);
// --- COLLAPSED VIEW ---
if (!isExpanded) {
const pill = (
/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */
<div className={styles.pill} onClick={onExpand}>
<Search size={12} />
<span className={styles.pillText}>{expression || 'Search...'}</span>
{expression && <span className={styles.pillIndicator} />}
</div>
);
// Mode-conditional render: only one of (pill | QuerySearch) is mounted
// at a time. Collapsing unmounts the editor — half-written queries are
// dropped, so collapse can't accidentally commit a malformed expression
// and fire an erroring /query_range request.
return (
<TooltipProvider>
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
className={cx(styles.root, isExpanded && styles.isExpanded)}
ref={containerRef}
onBlur={(e): void => {
const relatedTarget = e.relatedTarget as Node | null;
const blurredIntoSelf = !!containerRef.current?.contains(relatedTarget);
if (!blurredIntoSelf) {
handleBlur();
}
}}
>
{isExpanded && (
<div className={styles.categoryControls}>
<ToggleGroup
type="single"
value={selectedCategory}
onChange={(value): void => {
if (value) {
handleCategoryChange(value as SpanCategory);
}
}}
size="sm"
>
{categories.map((category) => (
<ToggleGroupItem key={category} value={category}>
{category}
</ToggleGroupItem>
))}
</ToggleGroup>
</div>
)}
<div className={styles.searchInput}>
{isExpanded ? (
<div className={styles.searchAndNav}>
<div className={styles.searchContainer}>
<QuerySearch
queryData={{
...BASE_FILTER_QUERY,
filters,
filter: { expression },
}}
onChange={handleExpressionChange}
onRun={handleRunQuery}
dataSource={DataSource.TRACES}
placeholder="Enter your filter query (e.g., http.status_code >= 500 AND service.name = 'frontend')"
/>
</div>
</div>
) : (
<div className={styles.searchPill}>{pillWithPopover}</div>
)}
</div>
<div className={styles.resultActions}>
<QueryResult
hasExpression={hasExpression}
hasResults={hasResults}
isFetching={isFetching}
error={error}
noData={noData}
currentIndex={currentSearchedIndex}
total={filteredSpanIds.length}
onPrev={handlePrev}
onNext={handleNext}
showNavigation={isExpanded}
/>
{isExpanded && (
<div className={styles.expandedActions}>
{hasExpression && (
<TooltipRoot>
<TooltipTrigger asChild>
return (
<TooltipProvider>
<div className={styles.root}>
{expression ? (
<TooltipRoot>
<TooltipTrigger asChild>{pill}</TooltipTrigger>
<TooltipContent side="bottom" align="start">
<div className={styles.pillPopover}>
<div className={styles.pillPopoverHeader}>
<Typography.Text>Search query</Typography.Text>
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={handleClear}
onClick={(): void => {
setCopy(expression);
toast.success('Copied to clipboard', {
richColors: false,
position: 'top-right',
});
}}
>
<X size={14} />
<Copy size={12} />
</Button>
</TooltipTrigger>
<TooltipContent>Clear filter</TooltipContent>
</TooltipRoot>
)}
<TooltipRoot>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
color="secondary"
onClick={onCollapse}
>
<ChevronsRight size={14} />
</Button>
</TooltipTrigger>
<TooltipContent>Collapse filters</TooltipContent>
</TooltipRoot>
</div>
</div>
<div className={styles.pillPopoverExpression}>{expression}</div>
</div>
</TooltipContent>
</TooltipRoot>
) : (
pill
)}
{highlightErrorsToggle}
{statusIndicators}
</div>
</TooltipProvider>
);
}
<div className={styles.highlightControl}>{highlightErrorsToggle}</div>
// --- EXPANDED VIEW ---
return (
<TooltipProvider>
<div className={cx(styles.root, styles.isExpanded)}>
<ToggleGroup
type="single"
value={selectedCategory}
onChange={(value): void => {
if (value) {
handleCategoryChange(value as SpanCategory);
}
}}
size="sm"
>
{categories.map((category) => (
<ToggleGroupItem key={category} value={category}>
{category}
</ToggleGroupItem>
))}
</ToggleGroup>
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
<div
className={styles.searchContainer}
ref={containerRef}
onBlur={(e): void => {
if (!containerRef.current?.contains(e.relatedTarget as Node)) {
handleBlur();
}
}}
>
<QuerySearch
queryData={{
...BASE_FILTER_QUERY,
filters,
filter: { expression },
}}
onChange={handleExpressionChange}
onRun={handleRunQuery}
dataSource={DataSource.TRACES}
placeholder="Enter your filter query (e.g., http.status_code >= 500 AND service.name = 'frontend')"
/>
</div>
{filteredSpanIds.length > 0 && (
<div className={styles.preNextToggle}>
<Typography.Text className={styles.preNextCount}>
{currentSearchedIndex + 1} / {filteredSpanIds.length}
</Typography.Text>
<Button
variant="ghost"
size="icon"
color="secondary"
disabled={currentSearchedIndex === 0}
onClick={(): void => {
handlePrevNext(currentSearchedIndex - 1);
setCurrentSearchedIndex((prev) => prev - 1);
}}
>
<ChevronUp size={14} />
</Button>
<Button
variant="ghost"
size="icon"
color="secondary"
disabled={currentSearchedIndex === filteredSpanIds.length - 1}
onClick={(): void => {
handlePrevNext(currentSearchedIndex + 1);
setCurrentSearchedIndex((prev) => prev + 1);
}}
>
<ChevronDown size={14} />
</Button>
</div>
)}
<Button
variant="ghost"
size="icon"
color="secondary"
className={styles.collapseBtn}
onClick={onCollapse}
>
<X size={14} />
</Button>
{highlightErrorsToggle}
{statusIndicators}
</div>
</TooltipProvider>
);

View File

@@ -1,32 +0,0 @@
.resultNavCount {
padding: 0 6px;
white-space: nowrap;
color: var(--l1-foreground);
font-family: 'Geist Mono';
font-size: 12px;
}
.resultNavDivider {
width: 1px;
height: 14px;
background: var(--l3-border);
margin: 0 4px;
flex-shrink: 0;
}
.filterStatus {
display: flex;
align-items: center;
gap: 6px;
flex-shrink: 0;
color: var(--l2-foreground);
font-family: 'Geist Mono';
font-size: 12px;
font-weight: 400;
line-height: 18px;
}
.hasError {
color: var(--destructive);
cursor: help;
}

View File

@@ -1,111 +0,0 @@
import { ChevronDown, ChevronUp, Info, Loader } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import {
TooltipContent,
TooltipRoot,
TooltipTrigger,
} from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import { AxiosError } from 'axios';
import cx from 'classnames';
import styles from './QueryResult.module.scss';
type QueryResultProps = {
hasExpression: boolean;
hasResults: boolean;
isFetching: boolean;
error: unknown;
noData: boolean;
currentIndex: number;
total: number;
onPrev: () => void;
onNext: () => void;
showNavigation?: boolean;
};
function QueryResult({
hasExpression,
hasResults,
isFetching,
error,
noData,
currentIndex,
total,
onPrev,
onNext,
showNavigation = true,
}: QueryResultProps): JSX.Element | null {
if (!hasExpression) {
return null;
}
let content: JSX.Element | null = null;
if (hasResults && showNavigation) {
// Prefer count over loader on refresh so stale results stay visible.
content = (
<>
<Typography.Text className={styles.resultNavCount}>
{currentIndex + 1} / {total}
</Typography.Text>
<Button
variant="ghost"
size="icon"
color="secondary"
disabled={currentIndex === 0}
onClick={onPrev}
>
<ChevronUp size={14} />
</Button>
<Button
variant="ghost"
size="icon"
color="secondary"
disabled={currentIndex === total - 1}
onClick={onNext}
>
<ChevronDown size={14} />
</Button>
</>
);
} else if (isFetching) {
content = <Loader className="animate-spin" />;
} else if (error) {
content = (
<TooltipRoot>
<TooltipTrigger asChild>
<span className={cx(styles.filterStatus, styles.hasError)}>
<Info />
API error
</span>
</TooltipTrigger>
<TooltipContent>
{(error as AxiosError)?.message || 'Something went wrong'}
</TooltipContent>
</TooltipRoot>
);
} else if (noData) {
content = (
<Typography.Text className={styles.filterStatus}>
No results found
</Typography.Text>
);
}
if (!content) {
return null;
}
return (
<>
{content}
{showNavigation && <span className={styles.resultNavDivider} />}
</>
);
}
QueryResult.defaultProps = {
showNavigation: true,
};
export default QueryResult;

View File

@@ -15,6 +15,7 @@ import TimeSeriesView from 'container/TimeSeriesView/TimeSeriesView';
import { convertDataValueToMs } from 'container/TimeSeriesView/utils';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useSaveRecentQuery } from 'hooks/recentQueries/useSaveRecentQuery';
import useUrlYAxisUnit from 'hooks/useUrlYAxisUnit';
import { AppState } from 'store/reducers';
import { Warning } from 'types/api';
@@ -94,6 +95,8 @@ function TimeSeriesViewContainer({
},
);
useSaveRecentQuery(stagedQuery);
useEffect(() => {
if (data?.payload) {
setWarning(data?.warning);

View File

@@ -825,5 +825,4 @@ body.ai-assistant-panel-open {
// overrides
:root {
--input-focus-outline-width: 0;
--radius-2: 4px;
}

View File

@@ -135,5 +135,4 @@ export const routePermission: Record<keyof typeof ROUTES, ROLES[]> = {
AI_ASSISTANT: ['ADMIN', 'EDITOR', 'VIEWER'],
AI_ASSISTANT_ICON_PREVIEW: ['ADMIN', 'EDITOR', 'VIEWER'],
MCP_SERVER: ['ADMIN', 'EDITOR', 'VIEWER'],
AI_ASSISTANT_BASE: ['ADMIN', 'EDITOR', 'VIEWER'],
};

View File

@@ -84,53 +84,244 @@ func New(
}
}
// extractShiftFromBuilderQuery extracts the shift value from timeShift function if present.
func extractShiftFromBuilderQuery[T any](spec qbtypes.QueryBuilderQuery[T]) int64 {
for _, fn := range spec.Functions {
if fn.Name == qbtypes.FunctionNameTimeShift && len(fn.Args) > 0 {
switch v := fn.Args[0].Value.(type) {
case float64:
return int64(v)
case int64:
return v
case int:
return int64(v)
case string:
if shiftFloat, err := strconv.ParseFloat(v, 64); err == nil {
return int64(shiftFloat)
}
}
}
}
return 0
}
// adjustTimeRangeForShift adjusts the time range based on the shift value from timeShift function.
func adjustTimeRangeForShift[T any](spec qbtypes.QueryBuilderQuery[T], tr qbtypes.TimeRange, kind qbtypes.RequestType) qbtypes.TimeRange {
// Only apply time shift for time series and scalar queries
// Raw/list queries don't support timeshift
if kind != qbtypes.RequestTypeTimeSeries && kind != qbtypes.RequestTypeScalar {
return tr
}
// Use the ShiftBy field if it's already populated, otherwise extract it
shiftBy := spec.ShiftBy
if shiftBy == 0 {
shiftBy = extractShiftFromBuilderQuery(spec)
}
if shiftBy == 0 {
return tr
}
// ShiftBy is in seconds, convert to milliseconds and shift backward in time
shiftMS := shiftBy * 1000
return qbtypes.TimeRange{
From: tr.From - uint64(shiftMS),
To: tr.To - uint64(shiftMS),
}
}
func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest) (*qbtypes.QueryRangeResponse, error) {
tmplVars := req.Variables
if tmplVars == nil {
tmplVars = make(map[string]qbtypes.VariableItem)
}
event := &qbtypes.QBEvent{
Version: "v5",
NumberOfQueries: len(req.CompositeQuery.Queries),
PanelType: req.RequestType.StringValue(),
}
q.populateQBEvent(event, req.CompositeQuery.Queries)
intervalWarnings := []string{}
// TraceOperatorQuery leverages other queries defined in the rangeRequest
// Eg: C := A => B
// Need to create dependency map { "A": true, "B": true }
dependencyQueries, err := q.constructTraceOperatorDependencyMap(req.CompositeQuery.Queries)
if err != nil {
return nil, err
dependencyQueries := make(map[string]bool)
traceOperatorQueries := make(map[string]qbtypes.QueryBuilderTraceOperator)
for _, query := range req.CompositeQuery.Queries {
if query.Type == qbtypes.QueryTypeTraceOperator {
if spec, ok := query.Spec.(qbtypes.QueryBuilderTraceOperator); ok {
// Parse expression to find dependencies
if err := spec.ParseExpression(); err != nil {
return nil, err
}
deps := spec.CollectReferencedQueries(spec.ParsedExpression)
for _, dep := range deps {
dependencyQueries[dep] = true
}
traceOperatorQueries[spec.Name] = spec
}
}
}
// Step interval is the aggregation parameter for timeseries requests.
// We need to set if it is unspecified or adjust it if value is not within recommended range
intervalWarnings := q.adjustStepInterval(req.CompositeQuery.Queries, req.Start, req.End)
// First pass: collect all metric names that need temporality
metricNames := make([]string, 0)
for idx, query := range req.CompositeQuery.Queries {
event.QueryType = query.Type.StringValue()
switch query.Type {
case qbtypes.QueryTypeBuilder:
if spec, ok := query.Spec.(qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]); ok {
for _, agg := range spec.Aggregations {
if agg.MetricName != "" {
metricNames = append(metricNames, agg.MetricName)
}
}
}
// if step interval is not set, we set it ourselves with recommended value
// if step interval is set to value which could result in points more than
// allowed, we override it.
switch spec := query.Spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:
event.TracesUsed = true
event.FilterApplied = spec.Filter != nil && spec.Filter.Expression != ""
event.GroupByApplied = len(spec.GroupBy) > 0
if spec.StepInterval.Seconds() == 0 {
spec.StepInterval = qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.RecommendedStepInterval(req.Start, req.End)),
}
}
if spec.StepInterval.Seconds() < float64(querybuilder.MinAllowedStepInterval(req.Start, req.End)) {
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepInterval(req.Start, req.End)),
}
intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
req.CompositeQuery.Queries[idx].Spec = spec
case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:
event.LogsUsed = true
event.FilterApplied = spec.Filter != nil && spec.Filter.Expression != ""
event.GroupByApplied = len(spec.GroupBy) > 0
if spec.StepInterval.Seconds() == 0 {
spec.StepInterval = qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.RecommendedStepInterval(req.Start, req.End)),
}
}
if spec.StepInterval.Seconds() < float64(querybuilder.MinAllowedStepInterval(req.Start, req.End)) {
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepInterval(req.Start, req.End)),
}
intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
req.CompositeQuery.Queries[idx].Spec = spec
case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
event.MetricsUsed = true
event.FilterApplied = spec.Filter != nil && spec.Filter.Expression != ""
event.GroupByApplied = len(spec.GroupBy) > 0
if spec.Source == telemetrytypes.SourceMeter {
if spec.StepInterval.Seconds() == 0 {
spec.StepInterval = qbtypes.Step{Duration: time.Second * time.Duration(querybuilder.RecommendedStepIntervalForMeter(req.Start, req.End))}
}
if spec.StepInterval.Seconds() < float64(querybuilder.MinAllowedStepIntervalForMeter(req.Start, req.End)) {
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepIntervalForMeter(req.Start, req.End)),
}
spec.StepInterval = newStep
}
} else {
if spec.StepInterval.Seconds() == 0 {
spec.StepInterval = qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.RecommendedStepIntervalForMetric(req.Start, req.End)),
}
}
if spec.StepInterval.Seconds() < float64(querybuilder.MinAllowedStepIntervalForMetric(req.Start, req.End)) {
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepIntervalForMetric(req.Start, req.End)),
}
intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
}
req.CompositeQuery.Queries[idx].Spec = spec
}
case qbtypes.QueryTypePromQL:
event.MetricsUsed = true
switch spec := query.Spec.(type) {
case qbtypes.PromQuery:
if spec.Step.Seconds() == 0 {
spec.Step = qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.RecommendedStepIntervalForMetric(req.Start, req.End)),
}
}
req.CompositeQuery.Queries[idx].Spec = spec
}
case qbtypes.QueryTypeClickHouseSQL:
switch spec := query.Spec.(type) {
case qbtypes.ClickHouseQuery:
if strings.TrimSpace(spec.Query) != "" {
event.MetricsUsed = strings.Contains(spec.Query, "signoz_metrics")
event.LogsUsed = strings.Contains(spec.Query, "signoz_logs")
event.TracesUsed = strings.Contains(spec.Query, "signoz_traces")
}
}
case qbtypes.QueryTypeTraceOperator:
if spec, ok := query.Spec.(qbtypes.QueryBuilderTraceOperator); ok {
if spec.StepInterval.Seconds() == 0 {
spec.StepInterval = qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.RecommendedStepInterval(req.Start, req.End)),
}
}
if spec.StepInterval.Seconds() < float64(querybuilder.MinAllowedStepInterval(req.Start, req.End)) {
newStep := qbtypes.Step{
Duration: time.Second * time.Duration(querybuilder.MinAllowedStepInterval(req.Start, req.End)),
}
intervalWarnings = append(intervalWarnings, fmt.Sprintf(intervalWarn, spec.Name, spec.StepInterval.Seconds(), newStep.Seconds()))
spec.StepInterval = newStep
}
req.CompositeQuery.Queries[idx].Spec = spec
}
}
}
queries := make(map[string]qbtypes.Query)
steps := make(map[string]qbtypes.Step)
// Resolve metric metadata once per request: patches each metric-aggregation
// query's spec in place, returns the queries whose every aggregation was
// missing (used for preseeded empty results), and any dormant-metric
// warning string. NotFound errors for never-seen metrics are propagated.
missingMetricQueries, dormantMetricsWarningMsg, err := q.resolveMetricMetadata(ctx, req.CompositeQuery.Queries, req.Start, req.End)
if err != nil {
return nil, err
}
missingMetricQuerySet := make(map[string]bool, len(missingMetricQueries))
for _, name := range missingMetricQueries {
missingMetricQuerySet[name] = true
}
missingMetrics := []string{}
missingMetricQueries := []string{}
for _, query := range req.CompositeQuery.Queries {
queryName := query.GetQueryName()
var queryName string
var isTraceOperator bool
// skip if it is dependecy of traceOperatorQuery
if query.GetType() != qbtypes.QueryTypeTraceOperator && dependencyQueries[queryName] {
switch query.Type {
case qbtypes.QueryTypeTraceOperator:
if spec, ok := query.Spec.(qbtypes.QueryBuilderTraceOperator); ok {
queryName = spec.Name
isTraceOperator = true
}
case qbtypes.QueryTypePromQL:
if spec, ok := query.Spec.(qbtypes.PromQuery); ok {
queryName = spec.Name
}
case qbtypes.QueryTypeClickHouseSQL:
if spec, ok := query.Spec.(qbtypes.ClickHouseQuery); ok {
queryName = spec.Name
}
case qbtypes.QueryTypeBuilder:
switch spec := query.Spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:
queryName = spec.Name
case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:
queryName = spec.Name
case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
queryName = spec.Name
}
}
if !isTraceOperator && dependencyQueries[queryName] {
continue
}
@@ -185,13 +376,40 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
queries[spec.Name] = bq
steps[spec.Name] = spec.StepInterval
case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
// Spec was already patched by resolveMetricMetadata. Queries
// whose every aggregation was missing live in
// missingMetricQuerySet and produce empty preseeded results
// rather than running here.
if missingMetricQuerySet[spec.Name] {
var metricTemporality map[string]metrictypes.Temporality
var metricTypes map[string]metrictypes.Type
if len(metricNames) > 0 {
var err error
metricTemporality, metricTypes, err = q.metadataStore.FetchTemporalityAndTypeMulti(ctx, req.Start, req.End, metricNames...)
if err != nil {
q.logger.WarnContext(ctx, "failed to fetch metric temporality", errors.Attr(err), slog.Any("metrics", metricNames))
return nil, errors.NewInternalf(errors.CodeInternal, "failed to fetch metrics temporality")
}
q.logger.DebugContext(ctx, "fetched metric temporalities and types", slog.Any("metric_temporality", metricTemporality), slog.Any("metric_types", metricTypes))
}
presentAggregations := []qbtypes.MetricAggregation{}
for i := range spec.Aggregations {
if spec.Aggregations[i].MetricName != "" && spec.Aggregations[i].Temporality == metrictypes.Unknown {
if temp, ok := metricTemporality[spec.Aggregations[i].MetricName]; ok && temp != metrictypes.Unknown {
spec.Aggregations[i].Temporality = temp
}
}
if spec.Aggregations[i].MetricName != "" && spec.Aggregations[i].Type == metrictypes.UnspecifiedType {
if foundMetricType, ok := metricTypes[spec.Aggregations[i].MetricName]; ok && foundMetricType != metrictypes.UnspecifiedType {
spec.Aggregations[i].Type = foundMetricType
}
}
if spec.Aggregations[i].Type == metrictypes.UnspecifiedType {
missingMetrics = append(missingMetrics, spec.Aggregations[i].MetricName)
continue
}
presentAggregations = append(presentAggregations, spec.Aggregations[i])
}
if len(presentAggregations) == 0 {
missingMetricQueries = append(missingMetricQueries, spec.Name)
continue
}
spec.Aggregations = presentAggregations
spec.ShiftBy = extractShiftFromBuilderQuery(spec)
timeRange := adjustTimeRangeForShift(spec, qbtypes.TimeRange{From: req.Start, To: req.End}, req.RequestType)
var bq *builderQuery[qbtypes.MetricAggregation]
@@ -210,6 +428,38 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
}
}
}
nonExistentMetrics := []string{}
var dormantMetricsWarningMsg string
if len(missingMetrics) > 0 {
lastSeenInfo, _ := q.metadataStore.FetchLastSeenInfoMulti(ctx, missingMetrics...)
for _, missingMetricName := range missingMetrics {
if ts, ok := lastSeenInfo[missingMetricName]; ok && ts > 0 {
continue
}
nonExistentMetrics = append(nonExistentMetrics, missingMetricName)
}
if len(nonExistentMetrics) == 1 {
return nil, errors.NewNotFoundf(errors.CodeNotFound, "could not find the metric %s", nonExistentMetrics[0])
} else if len(nonExistentMetrics) > 1 {
return nil, errors.NewNotFoundf(errors.CodeNotFound, "the following metrics were not found: %s", strings.Join(nonExistentMetrics, ", "))
}
lastSeenStr := func(name string) string {
if ts, ok := lastSeenInfo[name]; ok && ts > 0 {
ago := humanize.RelTime(time.UnixMilli(ts), time.Now(), "ago", "from now")
return fmt.Sprintf("%s (last seen %s)", name, ago)
}
return name // this case won't come cuz lastSeenStr is never called for metrics in nonExistentMetrics
}
if len(missingMetrics) == 1 {
dormantMetricsWarningMsg = fmt.Sprintf("no data found for the metric %s in the query time range", lastSeenStr(missingMetrics[0]))
} else {
parts := make([]string, len(missingMetrics))
for i, m := range missingMetrics {
parts[i] = lastSeenStr(m)
}
dormantMetricsWarningMsg = fmt.Sprintf("no data found for the following metrics in the query time range: %s", strings.Join(parts, ", "))
}
}
preseededResults := make(map[string]any)
for _, name := range missingMetricQueries { // at this point missing metrics will not have any non existent metrics, only normal ones
switch req.RequestType {
@@ -246,166 +496,6 @@ func (q *querier) QueryRange(ctx context.Context, orgID valuer.UUID, req *qbtype
return qbResp, qbErr
}
func (q *querier) populateQBEvent(event *qbtypes.QBEvent, queries []qbtypes.QueryEnvelope) {
for _, query := range queries {
// BUG: QueryType doesn't make sense as range_request can have multiple query types.
event.QueryType = query.Type.StringValue()
switch query.Type {
case qbtypes.QueryTypeBuilder:
filter := query.GetFilter()
event.FilterApplied = event.FilterApplied || (filter != nil && filter.Expression != "")
event.GroupByApplied = event.GroupByApplied || len(query.GetGroupBy()) > 0
switch query.Spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:
event.TracesUsed = true
case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:
event.LogsUsed = true
case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
event.MetricsUsed = true
}
case qbtypes.QueryTypePromQL:
event.MetricsUsed = true
case qbtypes.QueryTypeTraceOperator:
event.TracesUsed = true
case qbtypes.QueryTypeClickHouseSQL:
sql := query.GetQuery()
if strings.TrimSpace(sql) != "" {
event.MetricsUsed = strings.Contains(sql, "signoz_metrics")
event.LogsUsed = strings.Contains(sql, "signoz_logs")
event.TracesUsed = strings.Contains(sql, "signoz_traces")
}
}
}
}
// resolveMetricMetadata fetches metadata for every metric referenced by builder
// metric-aggregation queries, patches each query's aggregations in place with
// the resolved values, and classifies any metric that could not be resolved.
//
// Side effects on queries:
// - Aggregations with Unknown Temporality / UnspecifiedType are filled in from
// the metadata store.
// - Aggregations whose Type is still UnspecifiedType after the patch are
// dropped from the spec.
// - Queries whose entire aggregation list was dropped are NOT patched and are
// surfaced via the returned missingMetricQueries; the caller should skip
// them.
//
// Returns:
// - missingMetricQueries: names of queries whose every aggregation was
// missing. Used downstream to preseed empty result placeholders so the
// response still has an entry per requested query name.
// - dormantWarning: a human-readable warning describing metrics that exist in
// the store but produced no data within the query window. Empty when no
// such metrics are present.
// - err: NotFound when one or more referenced metrics have never been seen,
// or Internal when a metadata fetch fails.
func (q *querier) resolveMetricMetadata(ctx context.Context, queries []qbtypes.QueryEnvelope, start, end uint64) (missingMetricQueries []string, dormantWarning string, err error) {
metricNames := make([]string, 0)
for idx := range queries {
if queries[idx].Type != qbtypes.QueryTypeBuilder {
continue
}
spec, ok := queries[idx].Spec.(qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation])
if !ok {
continue
}
for _, agg := range spec.Aggregations {
if agg.MetricName != "" {
metricNames = append(metricNames, agg.MetricName)
}
}
}
if len(metricNames) == 0 {
return nil, "", nil
}
metricTemporality, metricTypes, err := q.metadataStore.FetchTemporalityAndTypeMulti(ctx, start, end, metricNames...)
if err != nil {
q.logger.WarnContext(ctx, "failed to fetch metric temporality", errors.Attr(err), slog.Any("metrics", metricNames))
return nil, "", errors.NewInternalf(errors.CodeInternal, "failed to fetch metrics temporality")
}
q.logger.DebugContext(ctx, "fetched metric temporalities and types", slog.Any("metric_temporality", metricTemporality), slog.Any("metric_types", metricTypes))
missingMetrics := []string{}
for idx := range queries {
if queries[idx].Type != qbtypes.QueryTypeBuilder {
continue
}
spec, ok := queries[idx].Spec.(qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation])
if !ok {
continue
}
presentAggregations := make([]qbtypes.MetricAggregation, 0, len(spec.Aggregations))
for i := range spec.Aggregations {
if spec.Aggregations[i].MetricName != "" && spec.Aggregations[i].Temporality == metrictypes.Unknown {
if temp, ok := metricTemporality[spec.Aggregations[i].MetricName]; ok && temp != metrictypes.Unknown {
spec.Aggregations[i].Temporality = temp
}
}
if spec.Aggregations[i].MetricName != "" && spec.Aggregations[i].Type == metrictypes.UnspecifiedType {
if foundMetricType, ok := metricTypes[spec.Aggregations[i].MetricName]; ok && foundMetricType != metrictypes.UnspecifiedType {
spec.Aggregations[i].Type = foundMetricType
}
}
if spec.Aggregations[i].Type == metrictypes.UnspecifiedType {
missingMetrics = append(missingMetrics, spec.Aggregations[i].MetricName)
continue
}
presentAggregations = append(presentAggregations, spec.Aggregations[i])
}
if len(presentAggregations) == 0 {
missingMetricQueries = append(missingMetricQueries, spec.Name)
continue
}
spec.Aggregations = presentAggregations
queries[idx].Spec = spec
}
if len(missingMetrics) == 0 {
return missingMetricQueries, "", nil
}
// Classify each missing metric: never-seen → NotFound error; seen-but-no-
// data-in-window → dormant warning.
lastSeenInfo, _ := q.metadataStore.FetchLastSeenInfoMulti(ctx, missingMetrics...)
nonExistentMetrics := []string{}
for _, name := range missingMetrics {
if ts, ok := lastSeenInfo[name]; ok && ts > 0 {
continue
}
nonExistentMetrics = append(nonExistentMetrics, name)
}
if len(nonExistentMetrics) == 1 {
return nil, "", errors.NewNotFoundf(errors.CodeNotFound, "could not find the metric %s", nonExistentMetrics[0])
}
if len(nonExistentMetrics) > 1 {
return nil, "", errors.NewNotFoundf(errors.CodeNotFound, "the following metrics were not found: %s", strings.Join(nonExistentMetrics, ", "))
}
// All missing metrics are dormant — assemble the warning string.
lastSeenStr := func(name string) string {
if ts, ok := lastSeenInfo[name]; ok && ts > 0 {
ago := humanize.RelTime(time.UnixMilli(ts), time.Now(), "ago", "from now")
return fmt.Sprintf("%s (last seen %s)", name, ago)
}
return name
}
if len(missingMetrics) == 1 {
dormantWarning = fmt.Sprintf("no data found for the metric %s in the query time range", lastSeenStr(missingMetrics[0]))
} else {
parts := make([]string, len(missingMetrics))
for i, m := range missingMetrics {
parts[i] = lastSeenStr(m)
}
dormantWarning = fmt.Sprintf("no data found for the following metrics in the query time range: %s", strings.Join(parts, ", "))
}
return missingMetricQueries, dormantWarning, nil
}
func (q *querier) QueryRawStream(ctx context.Context, orgID valuer.UUID, req *qbtypes.QueryRangeRequest, client *qbtypes.RawStream) {
event := &qbtypes.QBEvent{
@@ -1003,129 +1093,3 @@ func (q *querier) mergeTimeSeriesResults(cachedValue *qbtypes.TimeSeriesData, fr
return result
}
func secondsStep(s uint64) qbtypes.Step {
return qbtypes.Step{Duration: time.Second * time.Duration(s)}
}
// clampStep sets the step to recommended when zero and clamps to min when below it.
// When clamped and warn is true, a warning is appended for the user.
func clampStep(qe *qbtypes.QueryEnvelope, recommended, min uint64, warnings *[]string) {
step := qe.GetStepInterval()
if step.Seconds() == 0 {
step = secondsStep(recommended)
qe.SetStepInterval(step)
}
if step.Seconds() < float64(min) {
newStep := secondsStep(min)
*warnings = append(*warnings, fmt.Sprintf(intervalWarn, qe.GetQueryName(), step.Seconds(), newStep.Seconds()))
qe.SetStepInterval(newStep)
}
}
// extractShiftFromBuilderQuery extracts the shift value from timeShift function if present.
func extractShiftFromBuilderQuery[T any](spec qbtypes.QueryBuilderQuery[T]) int64 {
for _, fn := range spec.Functions {
if fn.Name == qbtypes.FunctionNameTimeShift && len(fn.Args) > 0 {
switch v := fn.Args[0].Value.(type) {
case float64:
return int64(v)
case int64:
return v
case int:
return int64(v)
case string:
if shiftFloat, err := strconv.ParseFloat(v, 64); err == nil {
return int64(shiftFloat)
}
}
}
}
return 0
}
// adjustTimeRangeForShift adjusts the time range based on the shift value from timeShift function.
func adjustTimeRangeForShift[T any](spec qbtypes.QueryBuilderQuery[T], tr qbtypes.TimeRange, kind qbtypes.RequestType) qbtypes.TimeRange {
// Only apply time shift for time series and scalar queries
// Raw/list queries don't support timeshift
if kind != qbtypes.RequestTypeTimeSeries && kind != qbtypes.RequestTypeScalar {
return tr
}
// Use the ShiftBy field if it's already populated, otherwise extract it
shiftBy := spec.ShiftBy
if shiftBy == 0 {
shiftBy = extractShiftFromBuilderQuery(spec)
}
if shiftBy == 0 {
return tr
}
// ShiftBy is in seconds, convert to milliseconds and shift backward in time
shiftMS := shiftBy * 1000
return qbtypes.TimeRange{
From: tr.From - uint64(shiftMS),
To: tr.To - uint64(shiftMS),
}
}
func (q *querier) constructTraceOperatorDependencyMap(queries []qbtypes.QueryEnvelope) (map[string]bool, error) {
dependencyQueries := make(map[string]bool)
for _, query := range queries {
if query.Type == qbtypes.QueryTypeTraceOperator {
if spec, ok := query.Spec.(qbtypes.QueryBuilderTraceOperator); ok {
// Parse expression to find dependencies
if err := spec.ParseExpression(); err != nil {
return nil, err
}
deps := spec.CollectReferencedQueries(spec.ParsedExpression)
for _, dep := range deps {
dependencyQueries[dep] = true
}
}
}
}
return dependencyQueries, nil
}
// adjustStepInterval normalizes each query's step interval in place and returns
// any clamp warnings emitted along the way.
func (q *querier) adjustStepInterval(queries []qbtypes.QueryEnvelope, start, end uint64) []string {
// Compute the per-signal bounds once per call — they only depend on start/end.
traceLogRecommended := querybuilder.RecommendedStepInterval(start, end)
traceLogMin := querybuilder.MinAllowedStepInterval(start, end)
meterRecommended := querybuilder.RecommendedStepIntervalForMeter(start, end)
meterMin := querybuilder.MinAllowedStepIntervalForMeter(start, end)
metricRecommended := querybuilder.RecommendedStepIntervalForMetric(start, end)
metricMin := querybuilder.MinAllowedStepIntervalForMetric(start, end)
warnings := make([]string, 0)
for idx := range queries {
qe := &queries[idx]
switch qe.Type {
case qbtypes.QueryTypeBuilder:
switch qe.Spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation], qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:
clampStep(qe, traceLogRecommended, traceLogMin, &warnings)
case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
if qe.GetSource() == telemetrytypes.SourceMeter {
clampStep(qe, meterRecommended, meterMin, &warnings)
} else {
clampStep(qe, metricRecommended, metricMin, &warnings)
}
}
case qbtypes.QueryTypePromQL:
// PromQL only fills an unset step — no min clamp.
if qe.GetStepInterval().Seconds() == 0 {
qe.SetStepInterval(secondsStep(metricRecommended))
}
case qbtypes.QueryTypeTraceOperator:
clampStep(qe, traceLogRecommended, traceLogMin, &warnings)
}
}
return warnings
}