Compare commits

...

29 Commits

Author SHA1 Message Date
Gaurav Tewari
82121d5f62 refactor(noz): remove the V1 context 2026-12-03 17:10:29 +05:30
Gaurav Tewari
7e81a24e84 feat(noz): send messages and chips in the context V2 shape
Dismissing the page pill drops the page for that surface and root; time, filter and tab
changes don't bring it back. Follow-ups send the time only.
2026-12-03 17:10:26 +05:30
Gaurav Tewari
1f79c21c29 feat(noz): send the pinned point with the dashboard panel 2026-12-03 17:10:24 +05:30
Gaurav Tewari
078f1ca450 feat(noz): read the pinned point from a dashboard time chart's series
Stacked charts plot running totals, so the value comes from the series.
2026-12-03 17:10:21 +05:30
Gaurav Tewari
e4e2293be3 feat(charts): report the pinned tooltip point to the chart's owner 2026-12-03 17:10:18 +05:30
Gaurav Tewari
f767c53543 feat(noz): send the dashboard list's filter, sort, page and view
Pinned and recent narrow rows in the browser, so they go as a view setting.
2026-12-03 17:10:16 +05:30
Gaurav Tewari
dfd64e05a1 feat(noz): send the services list's resource filter
Search, sort and page live inside the antd table's own state.
2026-12-03 17:10:14 +05:30
Gaurav Tewari
ab3b465252 feat(noz): send the triggered alert list's search, labels, grouping and sort
Label chips become a filter: values of one key are an IN, keys are ANDed.
2026-12-03 17:10:11 +05:30
Gaurav Tewari
4d71cfd031 feat(noz): send the alert rule list's filter, sort, page and saved view
Built-in views are presets, so only the user's saved views are sent.
2026-12-03 17:10:09 +05:30
Gaurav Tewari
247f91506a fix(noz): name the alert root by the saved rule, not the unsaved name 2026-12-03 17:10:07 +05:30
Gaurav Tewari
4471c11a5f feat(noz): send the alert history filter, state tab and page
Sort isn't sent: the order param can't tell the user's choice from the default.
2026-12-03 17:10:05 +05:30
Gaurav Tewari
1950d69bb7 feat(noz): send the alert editor's mode, unsaved flag and the query it ran
The query goes only once the run query differs from the saved rule.
2026-12-03 17:10:02 +05:30
Gaurav Tewari
f55283e6fa chore(alerts): right-align the rule table's Actions header without text-align
Reuses the cells' flex class; text-align is banned in JS and SCSS.
2026-12-03 17:10:00 +05:30
Gaurav Tewari
cce56c5bb1 feat(noz): send the live log list and whether the stream is paused 2026-12-03 17:09:56 +05:30
Gaurav Tewari
fc023a3272 feat(noz): switch the context V2 page to live logs in live mode 2026-12-03 17:09:54 +05:30
Gaurav Tewari
3bd72c534e refactor(live-logs): move the format menu items to constants 2026-12-03 17:09:52 +05:30
Gaurav Tewari
f5c663a1a0 feat(noz): send the metric open in the details drawer and Inspect 2026-12-03 17:09:50 +05:30
Gaurav Tewari
b1098c901b feat(noz): add the Metrics Summary views to the context V2 page 2026-12-03 17:09:45 +05:30
Gaurav Tewari
fc73871025 feat(noz): send the panel being edited in the panel editor 2026-12-03 17:09:43 +05:30
Gaurav Tewari
59a131317d feat(noz): send the panel open in the dashboard View modal 2026-12-03 17:09:41 +05:30
Gaurav Tewari
106ebf02b2 feat(noz): add the dashboard panel node to the context V2 page 2026-12-03 17:09:38 +05:30
Gaurav Tewari
344bde2fd3 feat(noz): report the service, alert and trace detail tabs 2026-12-03 17:09:35 +05:30
Gaurav Tewari
08503f106e feat(noz): add the tab owner hook to the context V2 page store 2026-12-03 17:09:33 +05:30
Gaurav Tewari
2e2d108dc6 test(noz): cover the traces explorer view 2026-12-03 17:09:31 +05:30
Gaurav Tewari
43e0f83ef8 feat(noz): add the explorer view to the context V2 page 2026-12-03 17:09:30 +05:30
Gaurav Tewari
1f5e3b1feb feat(noz): add the dashboard and AI overview to the context V2 page 2026-12-03 17:09:27 +05:30
Gaurav Tewari
7bd3d14165 feat(noz): merge shared context views per field and cap value sizes 2026-12-03 17:09:25 +05:30
Gaurav Tewari
1ed382ad90 feat(noz): send the picker's time with the context V2 page 2026-12-03 17:09:23 +05:30
Gaurav Tewari
f414e212e0 feat(noz): add the context V2 store and route surfaces 2026-12-03 17:09:20 +05:30
166 changed files with 7021 additions and 1460 deletions

View File

@@ -56,7 +56,7 @@
"@sentry/vite-plugin": "5.3.0",
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/noz-client": "1.13.0",
"@signozhq/noz-client": "1.15.0-experimental.5",
"@signozhq/ui": "0.4.1-rc.2",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",

View File

@@ -83,8 +83,8 @@ importers:
specifier: 0.4.0
version: 0.4.0
'@signozhq/noz-client':
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
specifier: 1.15.0-experimental.5
version: 1.15.0-experimental.5(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@signozhq/ui':
specifier: 0.4.1-rc.2
version: 0.4.1-rc.2(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -3094,8 +3094,8 @@ packages:
'@signozhq/icons@0.4.0':
resolution: {integrity: sha512-QctNvNPlQlsefFdIVmSy/P/7a1IcQ3IryKP0KPMqtoqew3q89FGUmFa5IfEJ7Z3CHhtG1zaXwBKqP72QkLyA3g==}
'@signozhq/noz-client@1.13.0':
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
'@signozhq/noz-client@1.15.0-experimental.5':
resolution: {integrity: sha512-CxLEj9g+/QK9zjumREhg2U+D5RShGa6N73XucEbgISCQpWdNKEasSh6vmpDyZpEgLEKq7g4g38Pb6EGN7yg5Pg==}
peerDependencies:
axios: ^1.20.0
react: ^18.2.0
@@ -12058,7 +12058,7 @@ snapshots:
'@signozhq/icons@0.4.0': {}
'@signozhq/noz-client@1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
'@signozhq/noz-client@1.15.0-experimental.5(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)':
dependencies:
axios: 1.21.1
react: 18.2.0

View File

@@ -9,7 +9,7 @@ import {
import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
/** Path-only base for the AI Assistant API. */
export const AI_API_PATH = '/api/v1/assistant';
export const AI_API_PATH = '/api/v2/assistant';
/** Header that tells the AI backend which SigNoz instance to query against. */
export const SIGNOZ_URL_HEADER = 'X-SigNoz-URL';

View File

@@ -0,0 +1,58 @@
import type { CreateMessageRequestV2DTO } from '@signozhq/noz-client';
import { setAIBackendUrl } from 'api/AIAPIInstance';
import { rest, server } from 'mocks-server/server';
import { getEmptyStateChips, sendMessage } from '../chat';
const NOZ_URL = 'http://noz.test';
beforeAll(() => setAIBackendUrl(NOZ_URL));
afterAll(() => setAIBackendUrl(null));
describe('ai-assistant chat API — V2', () => {
it('asks chips for the surface with each selected tab as its own param, in order', async () => {
let search = '';
server.use(
rest.get(
`${NOZ_URL}/api/v2/assistant/empty-state/chips`,
(req, res, ctx) => {
search = req.url.search;
return res(ctx.json({ chips: [] }));
},
),
);
await getEmptyStateChips({
surface: 'trace.detail',
activeViewPath: ['thread', 'formatted'],
});
expect(search).toBe(
'?surface=trace.detail&active_view_path=thread&active_view_path=formatted',
);
});
it('posts the V2 message body to the V2 thread', async () => {
const body: CreateMessageRequestV2DTO = {
content: 'Why is p99 up?',
timeContext: { capturedAtMs: 1795948200000, timeZone: 'Asia/Kolkata' },
context: {
page: { surface: 'dashboard.detail' },
mentions: [{ kind: 'service', resourceId: 'cart', resourceName: 'cart' }],
},
};
let posted: unknown;
server.use(
rest.post(
`${NOZ_URL}/api/v2/assistant/threads/t1/messages`,
async (req, res, ctx) => {
posted = await req.json();
return res(ctx.json({ executionId: 'e1' }));
},
),
);
await expect(sendMessage('t1', body)).resolves.toBe('e1');
expect(posted).toStrictEqual(body);
});
});

View File

@@ -2,9 +2,9 @@
* AI Assistant API client.
*
* Flow:
* 1. POST /api/v1/assistant/threads → { threadId }
* 2. POST /api/v1/assistant/threads/{threadId}/messages → { executionId }
* 3. GET /api/v1/assistant/executions/{executionId}/events → SSE stream (closes on 'done')
* 1. POST /api/v2/assistant/threads → { threadId }
* 2. POST /api/v2/assistant/threads/{threadId}/messages → { executionId }
* 3. GET /api/v2/assistant/executions/{executionId}/events → SSE stream (closes on 'done')
*
* For subsequent messages in the same thread, repeat steps 2–3.
* Approval/clarification events pause the stream; use approveExecution/clarifyExecution
@@ -33,23 +33,20 @@ import type {
ApproveResponseDTO,
CancelResponseDTO,
ClarifyResponseDTO,
CreateMessageRequestV2DTO,
CreateMessageResponseDTO,
CreateThreadResponseDTO,
ExecutionStateDTO,
FeedbackRatingDTO,
ListThreadsApiV1AssistantThreadsGetArchived,
ListThreadsApiV1AssistantThreadsGetParams,
MessageContextDTO,
MessageContextDTOSource,
MessageContextDTOType,
MessageSummaryDTO,
ListThreadsApiV2AssistantThreadsGetArchived,
ListThreadsApiV2AssistantThreadsGetParams,
MessageSummaryV2DTO,
RegenerateResponseDTO,
ThreadDetailResponseDTO,
ThreadDetailResponseV2DTO,
ThreadListResponseDTO,
ThreadSummaryDTO,
ChipDTO,
ChipsResponseDTO,
PageTypeDTO,
} from '@signozhq/noz-client';
import { LOCALSTORAGE } from 'constants/localStorage';
@@ -186,26 +183,16 @@ export type ExecutionState = `${ExecutionStateDTO}`;
export type ThreadSummary = ThreadSummaryDTO;
export type ThreadListResponse = ThreadListResponseDTO;
export type ThreadDetailResponse = ThreadDetailResponseDTO;
export type MessageSummary = MessageSummaryDTO;
export type ThreadDetailResponse = ThreadDetailResponseV2DTO;
export type MessageSummary = MessageSummaryV2DTO;
export type CancelResponse = CancelResponseDTO;
/**
* Construction-friendly view of `MessageContextDTO`: enum fields are widened
* to their string-literal unions so call-sites can pass `'mention'` instead
* of `MessageContextDTOSource.mention`.
*/
export type MessageContext = Omit<MessageContextDTO, 'source' | 'type'> & {
source: `${MessageContextDTOSource}`;
type: `${MessageContextDTOType}`;
};
/** Construction-friendly view of `ListThreadsApiV1AssistantThreadsGetParams`. */
/** Construction-friendly view of `ListThreadsApiV2AssistantThreadsGetParams`. */
export type ListThreadsOptions = Omit<
ListThreadsApiV1AssistantThreadsGetParams,
ListThreadsApiV2AssistantThreadsGetParams,
'archived'
> & {
archived?: `${ListThreadsApiV1AssistantThreadsGetArchived}`;
archived?: `${ListThreadsApiV2AssistantThreadsGetArchived}`;
};
/** String-literal view of `FeedbackRatingDTO` so call-sites can pass `'positive'`/`'negative'`. */
@@ -260,7 +247,7 @@ export async function getThreadDetail(
// ---------------------------------------------------------------------------
// Step 1 — Create thread
// POST /api/v1/assistant/threads → { threadId }
// POST /api/v2/assistant/threads → { threadId }
// ---------------------------------------------------------------------------
export async function createThread(signal?: AbortSignal): Promise<string> {
@@ -274,13 +261,13 @@ export async function createThread(signal?: AbortSignal): Promise<string> {
// ---------------------------------------------------------------------------
// Step 2 — Send message
// POST /api/v1/assistant/threads/{threadId}/messages → { executionId }
// POST /api/v2/assistant/threads/{threadId}/messages → { executionId }
// ---------------------------------------------------------------------------
/** Fetches the thread's active executionId for reconnect on thread_busy (409). */
async function getActiveExecutionId(threadId: string): Promise<string | null> {
try {
const response = await AIAssistantInstance.get<ThreadDetailResponseDTO>(
const response = await AIAssistantInstance.get<ThreadDetailResponse>(
`/threads/${threadId}`,
);
return response.data.activeExecutionId ?? null;
@@ -291,17 +278,13 @@ async function getActiveExecutionId(threadId: string): Promise<string | null> {
export async function sendMessage(
threadId: string,
content: string,
contexts?: MessageContext[],
body: CreateMessageRequestV2DTO,
signal?: AbortSignal,
): Promise<string> {
try {
const response = await AIAssistantInstance.post<CreateMessageResponseDTO>(
`/threads/${threadId}/messages`,
{
content,
...(contexts && contexts.length > 0 ? { contexts } : {}),
},
body,
{ signal },
);
return response.data.executionId;
@@ -320,7 +303,7 @@ export async function sendMessage(
// ---------------------------------------------------------------------------
// Step 3 — Stream execution events
// GET /api/v1/assistant/executions/{executionId}/events → SSE
// GET /api/v2/assistant/executions/{executionId}/events → SSE
// ---------------------------------------------------------------------------
function parseSSELine(line: string): SSEEvent | null {
@@ -521,16 +504,30 @@ export async function submitFeedback(
// ---------------------------------------------------------------------------
// Contextual empty-state chips
// GET /api/v1/assistant/empty-state/chips?page_type=… → { chips }
// GET /api/v2/assistant/empty-state/chips?surface=…&active_view_path=… → { chips }
// ---------------------------------------------------------------------------
export interface ChipsPage {
surface: string;
/** Selected tabs, outermost first. */
activeViewPath: string[];
}
export async function getEmptyStateChips(
pageType: PageTypeDTO,
{ surface, activeViewPath }: ChipsPage,
signal?: AbortSignal,
): Promise<ChipDTO[]> {
const response = await AIAssistantInstance.get<ChipsResponseDTO>(
'/empty-state/chips',
{ params: { page_type: pageType }, signal },
{
params: {
surface,
...(activeViewPath.length ? { active_view_path: activeViewPath } : {}),
},
// The backend reads `active_view_path=a&active_view_path=b`, not `active_view_path[]=a`.
paramsSerializer: { indexes: null },
signal,
},
);
return response.data.chips;
}

View File

@@ -1,27 +1,24 @@
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useState,
} from 'react';
import { useCallback, useLayoutEffect, useState } from 'react';
import cx from 'classnames';
import { useAppLocation } from 'lib/router/useAppLocation';
import type {
ManualReferenceDTO,
MessageContextV2DTO,
} from '@signozhq/noz-client';
import logEvent from 'api/common/logEvent';
import ChatInput, { autoContextKey } from '../components/ChatInput';
import ChatInput from '../components/ChatInput';
import ConversationSkeleton from '../components/ConversationSkeleton';
import VirtualizedMessages from '../components/VirtualizedMessages';
import { AIAssistantEvents } from '../events';
import { getAutoContexts } from '../getAutoContexts';
import { useAIAssistantAnalyticsContext } from '../hooks/useAIAssistantAnalyticsContext';
import { useSendMessage } from '../hooks/useSendMessage';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { MessageAttachment } from '../types';
import { MessageContext } from '../../../api/ai-assistant/chat';
import { useVariant } from '../VariantContext';
import styles from './ConversationView.module.scss';
import { usePageContext } from './usePageContext';
const SNAKE_PLACEHOLDER = 'Playing Snake · Esc to quit';
@@ -35,7 +32,6 @@ export default function ConversationView({
const variant = useVariant();
const isCompact = variant === 'panel';
const isFullPage = variant === 'page';
const location = useAppLocation();
const [isPlayingSnake, setIsPlayingSnake] = useState(false);
const [inputFocusRequest, setInputFocusRequest] = useState(0);
@@ -61,7 +57,7 @@ export default function ConversationView({
const pendingClarificationHere = useAIAssistantStore(
(s) => s.streams[conversationId]?.pendingClarification ?? null,
);
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const sendMessage = useSendMessage();
const cancelStream = useAIAssistantStore((s) => s.cancelStream);
const analyticsCtx = useAIAssistantAnalyticsContext(conversationId);
@@ -76,50 +72,17 @@ export default function ConversationView({
}
}, [hasUnreadReply, conversationId, markReplyRead]);
// Auto-derived contexts come from the route the user is currently looking
// at (dashboard detail, service metrics, an explorer, …). Skip when the
// user is on the standalone AI Assistant page — there's no "underlying"
// page context to attach. ChatInput renders these as chips and merges
// them with the user's `@`-mention picks before invoking onSend.
const allAutoContexts = useMemo(
() =>
variant === 'page'
? []
: getAutoContexts(location.pathname, location.search),
[variant, location.pathname, location.search],
);
// User-dismissed auto-context entries. Reset whenever the URL changes —
// dismissals are scoped to "this page", not the whole conversation.
const [dismissedAutoKeys, setDismissedAutoKeys] = useState<Set<string>>(
() => new Set(),
);
useEffect(() => {
setDismissedAutoKeys(new Set());
}, [location.pathname, location.search]);
const autoContexts = useMemo(
() =>
allAutoContexts.filter((ctx) => !dismissedAutoKeys.has(autoContextKey(ctx))),
[allAutoContexts, dismissedAutoKeys],
);
const handleDismissAutoContext = useCallback((key: string): void => {
setDismissedAutoKeys((prev) => {
const next = new Set(prev);
next.add(key);
return next;
});
}, []);
const { page, dismiss, refresh, snapshotPage } = usePageContext();
const handleSend = useCallback(
(
text: string,
attachments?: MessageAttachment[],
contexts?: MessageContext[],
mentions?: ManualReferenceDTO[],
) => {
const hasAuto = contexts?.some((c) => c.source === 'auto') ?? false;
const hasManual = contexts?.some((c) => c.source === 'mention') ?? false;
const pageContext = snapshotPage();
const hasAuto = pageContext !== null;
const hasManual = Boolean(mentions?.length);
let contextType: 'manual' | 'auto' | 'both' | undefined;
if (hasAuto && hasManual) {
contextType = 'both';
@@ -135,9 +98,16 @@ export default function ConversationView({
contextType,
respondingToClarification: Boolean(pendingClarificationHere),
});
void sendMessage(text, attachments, contexts);
const context: MessageContextV2DTO = {
...(pageContext ? { page: pageContext } : {}),
...(hasManual ? { mentions } : {}),
};
void sendMessage(text, {
attachments,
context: hasAuto || hasManual ? context : undefined,
});
},
[sendMessage, analyticsCtx, pendingClarificationHere],
[sendMessage, snapshotPage, analyticsCtx, pendingClarificationHere],
);
// When the current reply began, kept with the stream so a reopened view carries on from it.
@@ -204,8 +174,8 @@ export default function ConversationView({
onSend={handleSend}
disabled
disabledTooltip="Wait for the conversation to load"
autoContexts={autoContexts}
onDismissAutoContext={handleDismissAutoContext}
page={page}
onDismissPage={dismiss}
/>
</div>
</div>
@@ -220,13 +190,7 @@ export default function ConversationView({
messages={messages}
isStreaming={isStreamingHere}
onSnakeGameChange={handleSnakeGameChange}
onSendSuggestedPrompt={(text): void => {
handleSend(
text,
undefined,
autoContexts.length > 0 ? autoContexts : undefined,
);
}}
onSendSuggestedPrompt={(text): void => handleSend(text)}
/>
{showDisclaimer && (
<div className={disclaimerClass} role="note" aria-live="polite">
@@ -246,8 +210,9 @@ export default function ConversationView({
isStreaming={isStreamingHere}
streamStartedAt={streamStartedAt}
showNozPeek={messages.length === 0 && !isStreamingHere}
autoContexts={autoContexts}
onDismissAutoContext={handleDismissAutoContext}
page={page}
onDismissPage={dismiss}
onFocus={refresh}
/>
</div>
</div>

View File

@@ -1,41 +1,37 @@
import { fireEvent, render } from '@testing-library/react';
import { MessageContext } from 'api/ai-assistant/chat';
import type { ManualReferenceDTO, PageContextDTO } from '@signozhq/noz-client';
import { registerAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import type { SendMessageOptions } from 'container/AIAssistant/types';
import { VariantContext } from 'container/AIAssistant/VariantContext';
import { TestRouter } from 'tests/router';
import { screen } from 'tests/test-utils';
import { fireEvent, render, screen } from 'tests/test-utils';
const CHIP_ID = 'recent-errors';
const CHIP_TEXT = 'Show me recent errors';
// Auto-derived page context that a normal (typed) send would attach. The chip
// send must forward the exact same array.
const mockAutoContexts: MessageContext[] = [
{
source: 'auto',
type: 'dashboard',
const DASHBOARD_PAGE: PageContextDTO = {
surface: 'dashboard.detail',
root: {
kind: 'dashboard',
resourceId: 'dashboard-123',
resourceName: 'Checkout dashboard',
},
];
};
const MENTION: ManualReferenceDTO = {
kind: 'service',
resourceId: 'cart',
resourceName: 'cart',
};
jest.mock('api/common/logEvent', () => ({
__esModule: true,
default: jest.fn(),
}));
jest.mock('container/AIAssistant/getAutoContexts', () => ({
getAutoContexts: jest.fn(() => mockAutoContexts),
}));
jest.mock('container/AIAssistant/hooks/useAIAssistantAnalyticsContext', () => ({
normalizePage: (page: string): string => page,
useAIAssistantAnalyticsContext: (): unknown => ({ threadId: 'thread-1' }),
}));
// ChatInput is heavy and irrelevant here — the chip path lives entirely in the
// empty state. Provide a lightweight stub plus the `autoContextKey` named export
// ConversationView imports for its dismissed-context filter.
// ChatInput is heavy; the stub sends one mention and dismisses the page on demand.
jest.mock('container/AIAssistant/components/ChatInput', () => ({
__esModule: true,
default: ({
@@ -43,11 +39,19 @@ jest.mock('container/AIAssistant/components/ChatInput', () => ({
disabled,
placeholder,
focusRequest,
onSend,
onDismissPage,
}: {
streamStartedAt?: number | null;
disabled?: boolean;
placeholder?: string;
focusRequest?: number;
onSend: (
text: string,
attachments: undefined,
mentions: ManualReferenceDTO[],
) => void;
onDismissPage?: () => void;
}): JSX.Element => (
<div
data-testid="chat-input"
@@ -55,9 +59,25 @@ jest.mock('container/AIAssistant/components/ChatInput', () => ({
data-disabled={String(Boolean(disabled))}
data-placeholder={placeholder ?? ''}
data-focus-request={focusRequest ?? 0}
/>
>
<button
type="button"
data-testid="send-with-mention"
aria-label="Send with a mention"
onClick={(): void =>
onSend('Why is cart slow?', undefined, [
{ kind: 'service', resourceId: 'cart', resourceName: 'cart' },
])
}
/>
<button
type="button"
data-testid="dismiss-page"
aria-label="Dismiss the page"
onClick={(): void => onDismissPage?.()}
/>
</div>
),
autoContextKey: (): string => '',
}));
jest.mock('container/AIAssistant/components/ConversationSkeleton', () => ({
@@ -125,24 +145,34 @@ import ConversationView from '../ConversationView';
const CONVERSATION_ID = 'conv-1';
function renderView(variant: 'panel' | 'page' | 'modal'): {
function renderView(
variant: 'panel' | 'page' | 'modal',
initialRoute = '/dashboard/dashboard-123',
): {
getByTestId: (id: string) => HTMLElement;
} {
return render(
<TestRouter initialRoute="/dashboard/dashboard-123">
<VariantContext.Provider value={variant}>
<ConversationView conversationId={CONVERSATION_ID} />
</VariantContext.Provider>
</TestRouter>,
<VariantContext.Provider value={variant}>
<ConversationView conversationId={CONVERSATION_ID} />
</VariantContext.Provider>,
undefined,
{ initialRoute },
);
}
describe('ConversationView — empty-state chip context', () => {
let sendMessage: jest.Mock;
describe('ConversationView — sent context', () => {
const storeSend = useAIAssistantStore.getState().sendMessage;
let sendMessage: jest.MockedFunction<
(text: string, options: SendMessageOptions) => Promise<void>
>;
let leaveDashboard: () => void;
beforeEach(() => {
jest.clearAllMocks();
sendMessage = jest.fn();
leaveDashboard = registerAssistantContext('dashboard', () => ({
root: DASHBOARD_PAGE.root ?? undefined,
}));
useAIAssistantStore.setState({
conversations: {
[CONVERSATION_ID]: {
@@ -156,30 +186,44 @@ describe('ConversationView — empty-state chip context', () => {
activeConversationId: CONVERSATION_ID,
loadingThreadIds: [],
sendMessage,
} as unknown as Partial<ReturnType<typeof useAIAssistantStore.getState>>);
});
});
it('forwards the page auto-contexts when a chip is clicked (embedded variant)', () => {
afterEach(() => {
leaveDashboard();
useAIAssistantStore.setState({ sendMessage: storeSend });
});
it('sends the page with a chip, as a typed message would', () => {
const { getByTestId } = renderView('panel');
fireEvent.click(getByTestId(`empty-state-chip-${CHIP_ID}`));
// The chip send must carry the same auto-contexts a typed message would.
expect(sendMessage).toHaveBeenCalledTimes(1);
expect(sendMessage).toHaveBeenCalledWith(
CHIP_TEXT,
undefined,
mockAutoContexts,
);
expect(sendMessage.mock.calls[0][0]).toBe(CHIP_TEXT);
expect(sendMessage.mock.calls[0][1].context).toStrictEqual({
page: DASHBOARD_PAGE,
});
});
it('sends undefined contexts on the standalone page (no page context to attach)', () => {
const { getByTestId } = renderView('page');
it('sends no page from the Noz page, which has no surface', () => {
const { getByTestId } = renderView('page', '/ai-assistant/conv-1');
fireEvent.click(getByTestId(`empty-state-chip-${CHIP_ID}`));
expect(sendMessage).toHaveBeenCalledTimes(1);
expect(sendMessage).toHaveBeenCalledWith(CHIP_TEXT, undefined, undefined);
expect(sendMessage.mock.calls[0][1].context).toBeUndefined();
});
it('drops a dismissed page and keeps the mentions', () => {
const { getByTestId } = renderView('panel');
fireEvent.click(getByTestId('dismiss-page'));
fireEvent.click(getByTestId('send-with-mention'));
expect(sendMessage.mock.calls[0][1].context).toStrictEqual({
mentions: [MENTION],
});
});
});

View File

@@ -0,0 +1,104 @@
import {
type ContextTargetRefDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import { getCurrentLocation, navigate } from 'lib/router/navigation';
import {
act,
AllTheProviders,
renderHook,
type RenderHookResult,
} from 'tests/test-utils';
import { registerAssistantContext } from '../../pageContext/store/usePageContextStore';
import type { AssistantContextGetter } from '../../pageContext/types';
import { usePageContext } from '../usePageContext';
const SURFACE = KnownAssistantSurfaceDTO.dashboarddetail;
const cleanups: (() => void)[] = [];
function register(id: string, getter: AssistantContextGetter): () => void {
const cleanup = registerAssistantContext(id, getter);
cleanups.push(cleanup);
return cleanup;
}
function renderPageContext(): RenderHookResult<
ReturnType<typeof usePageContext>,
unknown
> {
return renderHook(() => usePageContext(), {
wrapper: ({ children }): JSX.Element => (
<AllTheProviders initialRoute="/dashboard/d1">{children}</AllTheProviders>
),
});
}
afterEach(() => {
cleanups.splice(0).forEach((cleanup) => cleanup());
});
describe('usePageContext', () => {
it('re-reads the root when an owner registers, and its name on refresh', () => {
const dashboard: ContextTargetRefDTO = {
kind: 'dashboard',
resourceId: 'd1',
};
const { result } = renderPageContext();
expect(result.current.page).toStrictEqual({ surface: SURFACE, root: null });
act(() => {
register('dashboard', () => ({ root: { ...dashboard } }));
});
expect(result.current.page?.root).toStrictEqual({
kind: 'dashboard',
resourceId: 'd1',
});
dashboard.resourceName = 'Prod overview';
act(() => result.current.refresh());
expect(result.current.page?.root).toStrictEqual({
kind: 'dashboard',
resourceId: 'd1',
resourceName: 'Prod overview',
});
});
it('re-reads the root after a route change, from an owner that stays mounted', () => {
register('dashboard', () => ({
root: {
kind: 'dashboard',
resourceId: getCurrentLocation().pathname.split('/').pop(),
},
}));
const { result } = renderPageContext();
act(() => navigate('/dashboard/d2'));
expect(result.current.page?.root?.resourceId).toBe('d2');
});
it('keeps a dismissed page out across time changes, and sends the next root', () => {
const leave = register('dashboard', () => ({
root: { kind: 'dashboard', resourceId: 'd1' },
}));
const { result } = renderPageContext();
act(() => result.current.dismiss());
act(() => navigate('/dashboard/d1?relativeTime=1h'));
expect(result.current.page).toBeNull();
expect(result.current.snapshotPage()).toBeNull();
act(() => {
leave();
register('dashboard', () => ({
root: { kind: 'dashboard', resourceId: 'd2' },
}));
});
expect(result.current.page?.root?.resourceId).toBe('d2');
expect(result.current.snapshotPage()).toStrictEqual({
surface: SURFACE,
root: { kind: 'dashboard', resourceId: 'd2' },
});
});
});

View File

@@ -0,0 +1,90 @@
import { useCallback, useEffect, useState } from 'react';
import type {
ContextTargetRefDTO,
KnownAssistantSurfaceDTO,
PageContextDTO,
} from '@signozhq/noz-client';
import { useAppLocation } from 'lib/router/useAppLocation';
import {
peekAssistantRoot,
snapshotAssistantContext,
usePageContextStore,
} from '../pageContext/store/usePageContextStore';
import { useAssistantPageStore } from '../pageContext/store/useAssistantPageStore';
import { useAssistantSurface } from '../pageContext/hooks/useAssistantSurface';
export interface PagePill {
surface: KnownAssistantSurfaceDTO;
root: ContextTargetRefDTO | null;
}
interface UsePageContextResult {
/** The page the next message carries; null when there is none or it was dismissed. */
page: PagePill | null;
dismiss: () => void;
/** Re-reads the root, whose name can load after the page mounts. */
refresh: () => void;
/** The page to send, read now; null when there is none or it was dismissed. */
snapshotPage: () => PageContextDTO | null;
}
// Time, filters and tabs aren't in it, so they never bring a dismissed page back.
function pageKey(
surface: string,
root: ContextTargetRefDTO | null | undefined,
): string {
return JSON.stringify([surface, root?.kind ?? null, root?.resourceId ?? null]);
}
function sameRoot(
a: ContextTargetRefDTO | null,
b: ContextTargetRefDTO | null,
): boolean {
return (
a?.kind === b?.kind &&
a?.resourceId === b?.resourceId &&
a?.resourceName === b?.resourceName
);
}
/** The page context for the composer: what it shows, and what Send carries. */
export function usePageContext(): UsePageContextResult {
const surface = useAssistantSurface();
const activeViewPath = useAssistantPageStore((state) => state.activeViewPath);
const { pathname, search } = useAppLocation();
const [root, setRoot] = useState<ContextTargetRefDTO | null>(null);
const [dismissedKey, setDismissedKey] = useState<string | null>(null);
const getters = usePageContextStore((state) => state.getters);
const refresh = useCallback((): void => {
const next = peekAssistantRoot();
setRoot((prev) => (sameRoot(prev, next) ? prev : next));
}, []);
// An effect, so the route's owners have committed their latest getters.
useEffect(() => {
refresh();
}, [refresh, pathname, search, getters]);
const dismiss = useCallback((): void => {
if (surface) {
setDismissedKey(pageKey(surface, root));
}
}, [surface, root]);
const snapshotPage = useCallback((): PageContextDTO | null => {
const page = snapshotAssistantContext({ surface, activeViewPath });
return page && pageKey(page.surface, page.root) !== dismissedKey
? page
: null;
}, [surface, activeViewPath, dismissedKey]);
const isShown = surface !== null && pageKey(surface, root) !== dismissedKey;
return {
page: isShown ? { surface, root } : null,
dismiss,
refresh,
snapshotPage,
};
}

View File

@@ -1,264 +0,0 @@
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { getAutoContexts } from '../getAutoContexts';
describe('getAutoContexts', () => {
it('returns alert detail context on alert overview with ruleId', () => {
const ruleId = 'rule-abc';
const search = `?${QueryParams.ruleId}=${ruleId}&${QueryParams.relativeTime}=1h`;
const contexts = getAutoContexts(ROUTES.ALERT_OVERVIEW, search);
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: ruleId,
metadata: {
page: 'alert_detail',
ruleId,
},
},
]);
});
it('returns alert detail context on alert history with ruleId', () => {
const ruleId = 'rule-xyz';
const startTime = '1700000000000';
const endTime = '1700003600000';
const search = `?${QueryParams.ruleId}=${ruleId}&${QueryParams.startTime}=${startTime}&${QueryParams.endTime}=${endTime}`;
const contexts = getAutoContexts(ROUTES.ALERT_HISTORY, search);
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: ruleId,
metadata: {
page: 'alert_detail',
ruleId,
timeRange: {
start: Number(startTime),
end: Number(endTime),
},
},
},
]);
});
it('includes the query in alert edit context', () => {
const ruleId = 'rule-edit';
const query = { queryType: 'builder', builder: { queryData: [] } };
const compositeQuery = encodeURIComponent(JSON.stringify(query));
const search = `?${QueryParams.ruleId}=${ruleId}&${QueryParams.compositeQuery}=${compositeQuery}`;
const contexts = getAutoContexts(ROUTES.EDIT_ALERTS, search);
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: ruleId,
metadata: {
page: 'alert_edit',
ruleId,
query,
},
},
]);
});
it('includes the query in alert new context (no ruleId)', () => {
const query = { queryType: 'builder', builder: { queryData: [] } };
const compositeQuery = encodeURIComponent(JSON.stringify(query));
const search = `?${QueryParams.compositeQuery}=${compositeQuery}`;
const contexts = getAutoContexts(ROUTES.ALERTS_NEW, search);
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: {
page: 'alert_new',
query,
},
},
]);
});
it('returns triggered alerts context on alert history without ruleId', () => {
const contexts = getAutoContexts(ROUTES.ALERT_HISTORY, '');
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: {
page: 'alerts_triggered',
},
},
]);
});
it('resolves alert list tabs on /alerts', () => {
expect(getAutoContexts(ROUTES.LIST_ALL_ALERT, '')).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: { page: 'alert_list' },
},
]);
expect(
getAutoContexts(ROUTES.LIST_ALL_ALERT, '?tab=AlertRules'),
).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: { page: 'alert_list' },
},
]);
expect(
getAutoContexts(ROUTES.LIST_ALL_ALERT, '?tab=TriggeredAlerts'),
).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: { page: 'alerts_triggered' },
},
]);
expect(
getAutoContexts(ROUTES.LIST_ALL_ALERT, '?tab=Configuration'),
).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: { page: 'alert_list' },
},
]);
expect(
getAutoContexts(ROUTES.LIST_ALL_ALERT, '?tab=RoutingPolicies'),
).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: { page: 'alert_list' },
},
]);
expect(
getAutoContexts(ROUTES.LIST_ALL_ALERT, '?tab=PlannedDowntime'),
).toStrictEqual([
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: { page: 'alert_list' },
},
]);
});
it('returns dashboard detail context on dashboard page', () => {
const dashboardId = 'dash-123';
const pathname = ROUTES.DASHBOARD.replace(':dashboardId', dashboardId);
const contexts = getAutoContexts(pathname, '');
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'dashboard',
resourceId: dashboardId,
metadata: {
page: 'dashboard_detail',
},
},
]);
});
it('returns panel edit context on the V2 panel editor', () => {
const dashboardId = 'dash-123';
const panelId = 'panel-abc';
const pathname = ROUTES.DASHBOARD_PANEL_EDITOR.replace(
':dashboardId',
dashboardId,
).replace(':panelId', panelId);
const contexts = getAutoContexts(pathname, '');
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'dashboard',
resourceId: dashboardId,
metadata: {
page: 'panel_edit',
widgetId: panelId,
},
},
]);
});
it('returns new panel context on the unsaved new-panel editor', () => {
const dashboardId = 'dash-123';
const pathname = ROUTES.DASHBOARD_PANEL_EDITOR.replace(
':dashboardId',
dashboardId,
).replace(':panelId', 'new');
const startTime = '1700000000000';
const endTime = '1700003600000';
const contexts = getAutoContexts(
pathname,
`?panelKind=TimeSeries&${QueryParams.startTime}=${startTime}&${QueryParams.endTime}=${endTime}`,
);
expect(contexts).toStrictEqual([
{
source: 'auto',
type: 'dashboard',
resourceId: dashboardId,
metadata: {
page: 'panel_create',
timeRange: { start: Number(startTime), end: Number(endTime) },
},
},
]);
});
it('returns empty array on alert overview without ruleId', () => {
const contexts = getAutoContexts(ROUTES.ALERT_OVERVIEW, '');
expect(contexts).toStrictEqual([]);
});
it('emits no auto-context on /home (no attachable resource)', () => {
expect(getAutoContexts(ROUTES.HOME, '')).toStrictEqual([]);
});
it('emits no auto-context on infrastructure monitoring routes', () => {
expect(
getAutoContexts(ROUTES.INFRASTRUCTURE_MONITORING_BASE, ''),
).toStrictEqual([]);
expect(
getAutoContexts(
ROUTES.INFRASTRUCTURE_MONITORING_HOSTS,
'?selectedItem=host-1',
),
).toStrictEqual([]);
});
});

View File

@@ -1,115 +0,0 @@
import { PageTypeDTO } from '@signozhq/noz-client';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { resolvePageType } from '../resolvePageType';
describe('resolvePageType', () => {
it('returns other for the standalone assistant surface', () => {
expect(
resolvePageType('/services', '', { isStandaloneAssistant: true }),
).toBe(PageTypeDTO.other);
});
it('returns dashboard_detail on a dashboard page', () => {
const pathname = ROUTES.DASHBOARD.replace(':dashboardId', 'dash-123');
expect(resolvePageType(pathname, '')).toBe(PageTypeDTO.dashboard_detail);
});
it('returns panel_edit on the V2 panel editor', () => {
const pathname = ROUTES.DASHBOARD_PANEL_EDITOR.replace(
':dashboardId',
'dash-123',
).replace(':panelId', 'panel-abc');
expect(resolvePageType(pathname, '')).toBe(PageTypeDTO.panel_edit);
});
// `panel_create` has no PageTypeDTO counterpart yet, so it reports
// `panel_edit` rather than degrading to `other`.
it('returns panel_edit on the unsaved new-panel editor', () => {
const pathname = ROUTES.DASHBOARD_PANEL_EDITOR.replace(
':dashboardId',
'dash-123',
).replace(':panelId', 'new');
expect(resolvePageType(pathname, '?panelKind=TimeSeries')).toBe(
PageTypeDTO.panel_edit,
);
});
it('returns alerts_triggered on alert history without ruleId', () => {
expect(resolvePageType(ROUTES.ALERT_HISTORY, '')).toBe(
PageTypeDTO.alerts_triggered,
);
});
it('resolves alert list tabs on /alerts', () => {
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '')).toBe(
PageTypeDTO.alert_list,
);
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=AlertRules')).toBe(
PageTypeDTO.alert_list,
);
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=TriggeredAlerts')).toBe(
PageTypeDTO.alerts_triggered,
);
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=Configuration')).toBe(
PageTypeDTO.alert_list,
);
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=RoutingPolicies')).toBe(
PageTypeDTO.alert_list,
);
expect(resolvePageType(ROUTES.LIST_ALL_ALERT, '?tab=PlannedDowntime')).toBe(
PageTypeDTO.alert_list,
);
});
it('returns log_detail when logs explorer has activeLogId', () => {
const search = `?${QueryParams.activeLogId}=log-1`;
expect(resolvePageType(ROUTES.LOGS_EXPLORER, search)).toBe(
PageTypeDTO.log_detail,
);
});
it('returns other for unmapped routes', () => {
expect(resolvePageType(ROUTES.ALERT_OVERVIEW, '')).toBe(PageTypeDTO.other);
});
it('returns other for the app root route (no contextual mapping)', () => {
expect(resolvePageType(ROUTES.HOME_PAGE, '')).toBe(PageTypeDTO.other);
});
it('returns homepage on /home', () => {
expect(resolvePageType(ROUTES.HOME, '')).toBe(PageTypeDTO.homepage);
});
it('returns infra_entity_detail on infrastructure monitoring routes', () => {
expect(resolvePageType(ROUTES.INFRASTRUCTURE_MONITORING_BASE, '')).toBe(
PageTypeDTO.infra_entity_detail,
);
expect(resolvePageType(ROUTES.INFRASTRUCTURE_MONITORING_HOSTS, '')).toBe(
PageTypeDTO.infra_entity_detail,
);
expect(resolvePageType(ROUTES.INFRASTRUCTURE_MONITORING_KUBERNETES, '')).toBe(
PageTypeDTO.infra_entity_detail,
);
});
it('returns metrics_explorer on all metrics explorer routes', () => {
expect(resolvePageType(ROUTES.METRICS_EXPLORER_BASE, '')).toBe(
PageTypeDTO.metrics_explorer,
);
expect(resolvePageType(ROUTES.METRICS_EXPLORER, '')).toBe(
PageTypeDTO.metrics_explorer,
);
expect(resolvePageType(ROUTES.METRICS_EXPLORER_EXPLORER, '')).toBe(
PageTypeDTO.metrics_explorer,
);
expect(resolvePageType('/metrics-explorer/views', '')).toBe(
PageTypeDTO.metrics_explorer,
);
});
});

View File

@@ -37,7 +37,7 @@ import logEvent from 'api/common/logEvent';
import { AIAssistantEvents, SuggestedPromptCategory } from '../../events';
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { useSendMessage } from '../../hooks/useSendMessage';
import { getOpenResourceTarget } from './utils/getOpenResourceTarget';
import {
@@ -385,7 +385,7 @@ export default function ActionsSection({
messageId,
}: ActionsSectionProps): JSX.Element | null {
const { pathname, search } = useAppLocation();
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const sendMessage = useSendMessage();
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
const { redirectWithQueryBuilderData, handleSetQueryData } = useQueryBuilder();
const dispatch = useDispatch();

View File

@@ -25,13 +25,6 @@
padding: var(--spacing-4) var(--spacing-5) 0;
}
.contextTags {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: var(--spacing-4) var(--spacing-5) 0;
}
.attachmentChip {
display: inline-flex;
align-items: center;

View File

@@ -5,26 +5,18 @@ import {
useRef,
useState,
} from 'react';
import { useQueryClient } from 'react-query';
import cx from 'classnames';
import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import { Popover, usePopoverHandle } from '@signozhq/ui/popover';
import { Tooltip } from '@signozhq/ui/tooltip';
import type { UploadFile } from 'antd';
import {
getListDashboardsForUserV2QueryKey,
useListDashboardsForUserV2,
} from 'api/generated/services/dashboard';
import {
getListRulesV3QueryKey,
useListRulesV3,
} from 'api/generated/services/rules';
import type { ManualReferenceDTO } from '@signozhq/noz-client';
import { useListDashboardsForUserV2 } from 'api/generated/services/dashboard';
import { useListRulesV3 } from 'api/generated/services/rules';
import type {
DashboardtypesListedDashboardForUserV2DTO,
ListDashboardsForUserV2200,
ListDashboardsForUserV2Params,
ListRulesV3200,
ListRulesV3Params,
} from 'api/generated/services/sigNoz.schemas';
import { useQueryService } from 'hooks/useQueryService';
@@ -33,31 +25,29 @@ import { useSelector } from 'react-redux';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
import type { PagePill } from '../../ConversationView/usePageContext';
import { MessageAttachment } from '../../types';
import { useVariant } from '../../VariantContext';
import { MessageContext } from '../../../../api/ai-assistant/chat';
import { ArrowUp, AtSign, Square, TriangleAlert, X } from '@signozhq/icons';
import styles from './ChatInput.module.scss';
import ComposerCaret from './ComposerCaret/ComposerCaret';
import ContextPickerEmptyState from './ContextPickerEmptyState';
import ContextPill from './ContextPill/ContextPill';
import ContextPills from './ContextPills/ContextPills';
import EdgeSweep from './EdgeSweep/EdgeSweep';
import NozPeek from './NozPeek/NozPeek';
import {
AUTO_CONTEXT_ICONS,
CONTEXT_CATEGORIES,
CONTEXT_CATEGORY_ICONS,
CONTEXT_CATEGORY_SINGULAR,
CONTEXT_TYPE_LABELS,
CONTEXT_CATEGORY_KINDS,
ContextCategory,
MAX_MENTIONS,
} from './contextPicker';
interface ChatInputProps {
onSend: (
text: string,
attachments?: MessageAttachment[],
contexts?: MessageContext[],
mentions?: ManualReferenceDTO[],
) => void;
onCancel?: () => void;
disabled?: boolean;
@@ -72,71 +62,11 @@ interface ChatInputProps {
streamStartedAt?: number | null;
/** Noz peeks over the top edge; meant for an empty conversation. */
showNozPeek?: boolean;
/**
* URL-derived `source: 'auto'` contexts representing the page the user is
* currently looking at. Rendered as chips alongside the user's `@`-mention
* picks and merged into the outgoing `contexts` array.
*/
autoContexts?: MessageContext[];
/**
* Called when the user dismisses an auto-context chip. The parent owns
* the dismissed set and is responsible for filtering the next render's
* `autoContexts` to exclude the key.
*/
onDismissAutoContext?: (key: string) => void;
}
/** Stable identity for an auto-context entry — used as React key + dismissal id. */
export function autoContextKey(ctx: MessageContext): string {
const page = (ctx.metadata as { page?: string } | null | undefined)?.page;
return `auto:${ctx.type}:${ctx.resourceId ?? ''}:${page ?? ''}`;
}
/**
* Friendly label for an auto-derived context chip. We don't fetch resource
* names from the URL alone, so we lean on the page identity that already
* lives in `metadata.page`, falling back to the resource type.
*/
function autoContextLabel(ctx: MessageContext): string {
const page = (ctx.metadata as { page?: string } | null | undefined)?.page;
switch (page) {
case 'dashboard_detail':
return 'Current dashboard';
case 'panel_edit':
return 'Editing panel';
case 'panel_create':
return 'New panel';
case 'panel_fullscreen':
return 'Panel (fullscreen)';
case 'dashboard_list':
return 'Dashboards';
case 'alert_detail':
return 'Current alert';
case 'alert_edit':
return 'Editing alert';
case 'alert_new':
return 'New alert';
case 'alerts_triggered':
return 'Triggered alerts';
case 'alert_list':
return 'Alerts';
case 'service_detail':
return 'Current service';
case 'services_list':
return 'Services';
case 'logs_explorer':
return 'Logs explorer';
case 'log_detail':
return 'Log details';
case 'traces_explorer':
return 'Traces explorer';
case 'trace_detail':
return 'Trace details';
case 'metrics_explorer':
return 'Metrics explorer';
default:
return ctx.type;
}
/** The page the next message carries, shown as a pill; null when there is none. */
page?: PagePill | null;
/** Drops the page from the messages sent from it. */
onDismissPage?: () => void;
onFocus?: () => void;
}
const MAX_INPUT_LENGTH = 20000;
@@ -146,11 +76,7 @@ const WARNING_THRESHOLD = 15000;
// squeezed in tighter container variants (e.g. the floating panel).
const TEXTAREA_MAX_HEIGHT_PX = 200;
const HOME_SERVICES_INTERVAL = 30 * 60 * 1000;
/**
* The picker filters client-side, so it pulls one large page instead of
* paginating. Shared with `getQueryData` below — the params are part of the
* generated query key, so both sides must use the same object.
*/
/** The picker filters client-side, so it pulls one large page instead of paginating. */
const DASHBOARD_LIST_PARAMS: ListDashboardsForUserV2Params = { limit: 1000 };
/** Same as dashboards. 200 is the most the rules list returns per call. */
@@ -168,32 +94,12 @@ interface SelectedContextItem {
value: string;
}
function toMessageContext(item: SelectedContextItem): MessageContext | null {
switch (item.category) {
case 'Dashboards':
return {
source: 'mention',
type: 'dashboard',
resourceId: item.entityId,
resourceName: item.value,
};
case 'Alerts':
return {
source: 'mention',
type: 'alert',
resourceId: item.entityId,
resourceName: item.value,
};
case 'Services':
return {
source: 'mention',
type: 'service',
resourceId: item.entityId,
resourceName: item.value,
};
default:
return null;
}
function toMention(item: SelectedContextItem): ManualReferenceDTO {
return {
kind: CONTEXT_CATEGORY_KINDS[item.category],
resourceId: item.entityId,
resourceName: item.value,
};
}
interface ContextEntityItem {
@@ -221,8 +127,9 @@ export default function ChatInput({
isStreaming = false,
streamStartedAt = null,
showNozPeek = false,
autoContexts,
onDismissAutoContext,
page,
onDismissPage,
onFocus,
}: ChatInputProps): JSX.Element {
const { selectedTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
@@ -256,7 +163,6 @@ export default function ChatInput({
// entities with ArrowUp/Down. Array is rewritten each render — there's
// only ever one tab panel mounted so stale indices clear naturally.
const entityRefs = useRef<(HTMLButtonElement | null)[]>([]);
const queryClient = useQueryClient();
// When the picker was opened by typing `@` in the textarea, this holds the
// span of `@<query>` (start / end indices into `text`). Used both for live
@@ -314,6 +220,9 @@ export default function ChatInput({
const wasSelected = selectedContexts.some(
(item) => item.category === category && item.entityId === entityId,
);
if (!wasSelected && selectedContexts.length >= MAX_MENTIONS) {
return;
}
setSelectedContexts((prev) => {
if (wasSelected) {
@@ -476,18 +385,13 @@ export default function ChatInput({
}),
);
const userContexts = selectedContexts
.map(toMessageContext)
.filter((context): context is MessageContext => context !== null);
// Auto contexts come first so the agent reads "current page" before
// any explicit @-mentions when both are present.
const contexts = [...(autoContexts ?? []), ...userContexts];
const mentions = selectedContexts.map(toMention);
const payload = capText(trimmed);
onSend(
payload,
attachments.length > 0 ? attachments : undefined,
contexts.length > 0 ? contexts : undefined,
mentions.length > 0 ? mentions : undefined,
);
setText('');
setPendingFiles([]);
@@ -500,7 +404,6 @@ export default function ChatInput({
sendDisabled,
onSend,
selectedContexts,
autoContexts,
capText,
]);
@@ -580,55 +483,6 @@ export default function ChatInput({
},
});
/**
* Resolves an auto-context to a human label: dashboard title, alert name,
* service name (the service `resourceId` IS the name), or a generic page
* label as fallback while the lookup data is still loading.
*
* Reads passively from the React Query cache via `getQueryData` —
* never triggers a fetch. If the cache is empty (e.g. assistant opened
* on a page that hasn't loaded the resource list yet), the chip falls
* back to a generic label and resolves once the cache fills via the
* picker or another page.
*/
const resolveAutoContextName = useCallback(
(ctx: MessageContext): string => {
if (ctx.type === 'service' && ctx.resourceId) {
return ctx.resourceId;
}
if (ctx.type === 'dashboard' && ctx.resourceId) {
const cached = queryClient.getQueryData<ListDashboardsForUserV2200>(
getListDashboardsForUserV2QueryKey(DASHBOARD_LIST_PARAMS),
);
const dash = cached?.data?.dashboards?.find((d) => d.id === ctx.resourceId);
if (dash) {
return dashboardTitle(dash);
}
}
if (ctx.type === 'alert' && ctx.resourceId) {
const cached = queryClient.getQueryData<ListRulesV3200>(
getListRulesV3QueryKey(ALERT_RULE_LIST_PARAMS),
);
const rule = cached?.data.rules.find((r) => r.id === ctx.resourceId);
if (rule?.alert) {
return rule.alert;
}
}
const page = (
ctx.metadata as { page?: string; traceId?: string } | null | undefined
)?.page;
if (page === 'trace_detail') {
const traceId = (ctx.metadata as { traceId?: string } | null | undefined)
?.traceId;
if (traceId) {
return `${traceId.slice(0, 8)}…`;
}
}
return autoContextLabel(ctx);
},
[queryClient],
);
const contextEntitiesByCategory: Record<ContextCategory, ContextEntityItem[]> =
{
Dashboards:
@@ -724,38 +578,12 @@ export default function ChatInput({
</div>
)}
{(selectedContexts.length > 0 ||
(autoContexts && autoContexts.length > 0)) && (
<div className={styles.contextTags}>
{autoContexts?.map((ctx) => {
const key = autoContextKey(ctx);
return (
<ContextPill
key={key}
icon={AUTO_CONTEXT_ICONS[ctx.type]}
category={CONTEXT_TYPE_LABELS[ctx.type]}
label={resolveAutoContextName(ctx)}
onRemove={
onDismissAutoContext
? (): void => onDismissAutoContext(key)
: undefined
}
/>
);
})}
{selectedContexts.map((contextItem) => (
<ContextPill
key={`${contextItem.category}:${contextItem.entityId}`}
icon={CONTEXT_CATEGORY_ICONS[contextItem.category]}
category={CONTEXT_CATEGORY_SINGULAR[contextItem.category]}
label={contextItem.value}
onRemove={(): void =>
removeContext(contextItem.category, contextItem.entityId)
}
/>
))}
</div>
)}
<ContextPills
page={page}
onDismissPage={onDismissPage}
picked={selectedContexts}
onRemovePicked={removeContext}
/>
<div className={styles.composer}>
<textarea
@@ -770,6 +598,7 @@ export default function ChatInput({
syncContextPickerFromText(next, e.target.selectionStart ?? next.length);
}}
onKeyDown={handleKeyDown}
onFocus={onFocus}
disabled={disabled}
maxLength={MAX_INPUT_LENGTH}
rows={2}

View File

@@ -8,6 +8,7 @@ interface ContextPillProps {
category: string;
label: string;
onRemove?: () => void;
testId?: string;
}
/** A context attached to the next message; the remove button shows on hover or focus. */
@@ -16,12 +17,13 @@ export default function ContextPill({
category,
label,
onRemove,
testId = 'ai-context-pill',
}: ContextPillProps): JSX.Element {
return (
<div
className={styles.pill}
title={`${category}: ${label}`}
data-testid="ai-context-pill"
data-testid={testId}
>
<Icon size={14} className={styles.icon} />
<span className={styles.category}>{category} :</span>
@@ -34,7 +36,7 @@ export default function ContextPill({
color="secondary"
onClick={onRemove}
aria-label={`Remove ${category}: ${label} context`}
testId="ai-context-pill-remove"
testId={`${testId}-remove`}
>
<X size={12} />
</Button>

View File

@@ -0,0 +1,6 @@
.pills {
display: flex;
flex-wrap: wrap;
gap: 6px;
padding: var(--spacing-4) var(--spacing-5) 0;
}

View File

@@ -0,0 +1,53 @@
import { SURFACE_LABELS } from '../../../pageContext/utils/surfaceLabels';
import type { PagePill } from '../../../ConversationView/usePageContext';
import ContextPill from '../ContextPill/ContextPill';
import {
CONTEXT_CATEGORY_ICONS,
CONTEXT_CATEGORY_SINGULAR,
type ContextCategory,
getSurfaceIcon,
} from '../contextPicker';
import styles from './ContextPills.module.scss';
interface ContextPillsProps {
page?: PagePill | null;
onDismissPage?: () => void;
picked: { category: ContextCategory; entityId: string; value: string }[];
onRemovePicked: (category: ContextCategory, entityId: string) => void;
}
/** What the next message carries: the page first, then the @-picked resources. */
export default function ContextPills({
page,
onDismissPage,
picked,
onRemovePicked,
}: ContextPillsProps): JSX.Element | null {
if (!page && picked.length === 0) {
return null;
}
return (
<div className={styles.pills}>
{page && (
<ContextPill
icon={getSurfaceIcon(page.surface)}
category={SURFACE_LABELS[page.surface]}
label={page.root?.resourceName || 'Current page'}
onRemove={onDismissPage}
testId="ai-page-pill"
/>
)}
{picked.map(({ category, entityId, value }) => (
<ContextPill
key={`${category}:${entityId}`}
icon={CONTEXT_CATEGORY_ICONS[category]}
category={CONTEXT_CATEGORY_SINGULAR[category]}
label={value}
onRemove={(): void => onRemovePicked(category, entityId)}
/>
))}
</div>
);
}

View File

@@ -1,35 +1,82 @@
import type { ComponentProps } from 'react';
import type { MessageContext } from 'api/ai-assistant/chat';
import { render, screen, userEvent } from 'tests/test-utils';
import {
KnownAssistantSurfaceDTO,
type ManualReferenceDTO,
} from '@signozhq/noz-client';
import {
NO_DELAY_USER_EVENT,
render,
screen,
userEvent,
} from 'tests/test-utils';
const mockDashboards = Array.from({ length: 9 }, (_, index) => ({
id: `d${index + 1}`,
name: `Dashboard ${index + 1}`,
spec: { display: { name: `Dashboard ${index + 1}` } },
}));
jest.mock('api/generated/services/dashboard', () => ({
useListDashboardsForUserV2: (): unknown => ({
data: { data: { dashboards: mockDashboards } },
isLoading: false,
isError: false,
}),
}));
// eslint-disable-next-line import/first
import ChatInput from '../ChatInput';
const serviceContext: MessageContext = {
source: 'auto',
type: 'service',
resourceId: 'checkout',
};
type ChatInputProps = ComponentProps<typeof ChatInput>;
describe('ChatInput — context pills', () => {
it('names a page context by its type and drops it on remove', async () => {
const user = userEvent.setup();
const onDismissAutoContext = jest.fn() as jest.MockedFunction<
NonNullable<ComponentProps<typeof ChatInput>['onDismissAutoContext']>
it('names the page by its surface and root, and dismisses it', async () => {
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onDismissPage = jest.fn() as jest.MockedFunction<
NonNullable<ChatInputProps['onDismissPage']>
>;
render(
<ChatInput
onSend={jest.fn()}
autoContexts={[serviceContext]}
onDismissAutoContext={onDismissAutoContext}
page={{
surface: KnownAssistantSurfaceDTO.servicedetail,
root: {
kind: 'service',
resourceId: 'checkout',
resourceName: 'checkout',
},
}}
onDismissPage={onDismissPage}
/>,
);
expect(screen.getByTestId('ai-context-pill')).toHaveTextContent(
expect(screen.getByTestId('ai-page-pill')).toHaveTextContent(
'Service :checkout',
);
await user.click(screen.getByTestId('ai-page-pill-remove'));
await user.click(screen.getByTestId('ai-context-pill-remove'));
expect(onDismissPage).toHaveBeenCalledTimes(1);
});
expect(onDismissAutoContext).toHaveBeenCalledWith('auto:service:checkout:');
it('sends picked resources as mentions, at most eight', async () => {
const user = userEvent.setup(NO_DELAY_USER_EVENT);
const onSend = jest.fn() as jest.MockedFunction<ChatInputProps['onSend']>;
render(<ChatInput onSend={onSend} />);
await user.click(screen.getByTestId('ai-chat-input-add-context'));
for (const { id } of mockDashboards) {
// eslint-disable-next-line no-await-in-loop
await user.click(screen.getByTestId(`ai-context-option-Dashboards-${id}`));
}
await user.type(screen.getByTestId('ai-chat-input-textarea'), 'hi{Enter}');
const mentions: ManualReferenceDTO[] = mockDashboards
.slice(0, 8)
.map(({ id, name }) => ({
kind: 'dashboard',
resourceId: id,
resourceName: name,
}));
expect(onSend).toHaveBeenCalledWith('hi', undefined, mentions);
});
});

View File

@@ -1,13 +1,15 @@
import {
BarChart,
Bell,
Bug,
DraftingCompass,
HardDrive,
LayoutDashboard,
Package,
ScrollText,
Settings,
} from '@signozhq/icons';
import { MessageContext } from '../../../../api/ai-assistant/chat';
import type { ManualReferenceDTO } from '@signozhq/noz-client';
/** Ordered category tabs shown in the @-mention context picker. */
export const CONTEXT_CATEGORIES = ['Dashboards', 'Alerts', 'Services'] as const;
@@ -31,30 +33,54 @@ export const CONTEXT_CATEGORY_SINGULAR: Record<ContextCategory, string> = {
Services: 'Service',
};
/** What one item of each context type is called. */
export const CONTEXT_TYPE_LABELS: Record<MessageContext['type'], string> = {
dashboard: 'Dashboard',
alert: 'Alert',
service: 'Service',
logs_explorer: 'Logs',
traces_explorer: 'Traces',
metrics_explorer: 'Metrics',
saved_view: 'Saved view',
/** The most mentions one message may carry; the backend rejects more. */
export const MAX_MENTIONS = 8;
/** The mention kind each category sends. */
export const CONTEXT_CATEGORY_KINDS: Record<ContextCategory, string> = {
Dashboards: 'dashboard',
Alerts: 'alert',
Services: 'service',
};
/** Icon per page context: the picker's for the categories it shares, the side nav's for explorers. */
export const AUTO_CONTEXT_ICONS: Record<
MessageContext['type'],
typeof Package
> = {
dashboard: CONTEXT_CATEGORY_ICONS.Dashboards,
alert: CONTEXT_CATEGORY_ICONS.Alerts,
service: CONTEXT_CATEGORY_ICONS.Services,
logs_explorer: ScrollText,
traces_explorer: DraftingCompass,
metrics_explorer: BarChart,
saved_view: Package,
};
// Maps, not objects: a kind like `constructor` must not resolve to Object.prototype.
const MENTION_KIND_CATEGORIES = new Map<string, ContextCategory>(
CONTEXT_CATEGORIES.map((category) => [
CONTEXT_CATEGORY_KINDS[category],
category,
]),
);
/** How a sent mention is shown; the server may name a kind this client predates. */
export function getMentionPill({ kind }: ManualReferenceDTO): {
icon: typeof Package;
category: string;
} {
const category = MENTION_KIND_CATEGORIES.get(kind);
return category
? {
icon: CONTEXT_CATEGORY_ICONS[category],
category: CONTEXT_CATEGORY_SINGULAR[category],
}
: { icon: Package, category: kind };
}
const SURFACE_AREA_ICONS = new Map<string, typeof Package>([
['dashboard', CONTEXT_CATEGORY_ICONS.Dashboards],
['alert', CONTEXT_CATEGORY_ICONS.Alerts],
['service', CONTEXT_CATEGORY_ICONS.Services],
['log', ScrollText],
['trace', DraftingCompass],
['metric', BarChart],
['infrastructure', HardDrive],
['exception', Bug],
['settings', Settings],
]);
/** The page pill's icon, by the surface's first segment: the picker's, else the side nav's. */
export function getSurfaceIcon(surface: string): typeof Package {
return SURFACE_AREA_ICONS.get(surface.split('.')[0]) ?? Package;
}
/**
* Resolved copy + composer prefill for one render of the context picker's empty

View File

@@ -1,28 +1,22 @@
import cx from 'classnames';
import { Package } from '@signozhq/icons';
import { MessageContext } from 'api/ai-assistant/chat';
import type { ManualReferenceDTO } from '@signozhq/noz-client';
import { useVariant } from '../../VariantContext';
import {
AUTO_CONTEXT_ICONS,
CONTEXT_TYPE_LABELS,
} from '../ChatInput/contextPicker';
import { getMentionPill } from '../ChatInput/contextPicker';
import ContextPill from '../ChatInput/ContextPill/ContextPill';
import styles from './AddedContexts.module.scss';
interface AddedContextsProps {
contexts: MessageContext[];
mentions: ManualReferenceDTO[];
}
/** The resources a message was sent with, by @-pick; the page it came from is left out. */
export default function AddedContexts({
contexts,
mentions,
}: AddedContextsProps): JSX.Element | null {
const variant = useVariant();
const picked = contexts.filter((ctx) => ctx.source === 'mention');
if (picked.length === 0) {
if (mentions.length === 0) {
return null;
}
@@ -33,15 +27,17 @@ export default function AddedContexts({
})}
data-testid="ai-added-contexts"
>
{picked.map((ctx) => (
<ContextPill
key={`${ctx.type}:${ctx.resourceId ?? ctx.resourceName}`}
// The server may name a type this client predates.
icon={AUTO_CONTEXT_ICONS[ctx.type] ?? Package}
category={CONTEXT_TYPE_LABELS[ctx.type] ?? ctx.type}
label={ctx.resourceName ?? ctx.resourceId ?? ''}
/>
))}
{mentions.map((mention) => {
const { icon, category } = getMentionPill(mention);
return (
<ContextPill
key={JSON.stringify([mention.kind, mention.resourceId])}
icon={icon}
category={category}
label={mention.resourceName ?? mention.resourceId}
/>
);
})}
<span className={styles.note}>added to context</span>
</div>
);

View File

@@ -231,7 +231,9 @@ export default function MessageBubble({
{isUser && <UserMessageActions message={message} />}
</div>
</div>
{isUser && message.contexts && <AddedContexts contexts={message.contexts} />}
{isUser && message.context?.mentions && (
<AddedContexts mentions={message.context.mentions} />
)}
</>
);
}

View File

@@ -89,15 +89,16 @@ describe('MessageBubble — added contexts', () => {
id: 'q-1',
role: 'user',
content: 'Why is checkout slow?',
contexts: [
{
source: 'mention',
type: 'dashboard',
resourceId: 'dash-1',
resourceName: 'Checkout latency',
},
{ source: 'auto', type: 'logs_explorer' },
],
context: {
page: { surface: 'log.explorer' },
mentions: [
{
kind: 'dashboard',
resourceId: 'dash-1',
resourceName: 'Checkout latency',
},
],
},
createdAt: 0,
}}
/>,

View File

@@ -0,0 +1,112 @@
import type { ChipDTO } from '@signozhq/noz-client';
import { setAIBackendUrl } from 'api/AIAPIInstance';
import { rest, server } from 'mocks-server/server';
import {
act,
AllTheProviders,
renderHook,
type RenderHookResult,
waitFor,
} from 'tests/test-utils';
import { useAssistantActiveView } from '../../../pageContext/hooks/useAssistantActiveView';
import { useEmptyStateChips } from '../useEmptyStateChips';
const NOZ_URL = 'http://noz.test';
interface TabProps {
tab: string;
}
type ChipsHook = RenderHookResult<
ReturnType<typeof useEmptyStateChips>,
TabProps
>;
/** Answers with one chip naming the surface and tab it was asked for. */
function serveChips(slowTab?: string): { release: () => void } {
let release = (): void => {};
const held = new Promise<void>((resolve) => {
release = resolve;
});
server.use(
rest.get(
`${NOZ_URL}/api/v2/assistant/empty-state/chips`,
async (req, res, ctx) => {
const tab = req.url.searchParams.getAll('active_view_path').join('/');
if (tab === slowTab) {
await held;
}
const chips: ChipDTO[] = [
{ id: tab, text: `${req.url.searchParams.get('surface')} ${tab}` },
];
return res(ctx.json({ chips }));
},
),
);
return { release: (): void => release() };
}
/** The trace page publishes its tab, as the real tab owner does. */
function renderOnTraceTab(tab: string): ChipsHook {
return renderHook(
(props: TabProps) => {
useAssistantActiveView(props.tab);
return useEmptyStateChips(true);
},
{
initialProps: { tab },
wrapper: ({ children }): JSX.Element => (
<AllTheProviders initialRoute="/trace/abc">{children}</AllTheProviders>
),
},
);
}
function chipFor(tab: string): ChipDTO[] {
return [{ id: tab, text: `trace.detail ${tab}` }];
}
beforeAll(() => setAIBackendUrl(NOZ_URL));
afterAll(() => setAIBackendUrl(null));
describe('useEmptyStateChips', () => {
it('asks for the tab a deep link opens on', async () => {
serveChips();
const { result } = renderOnTraceTab('thread');
await waitFor(() =>
expect(result.current.chips).toStrictEqual(chipFor('thread')),
);
});
it("shows a tab's chips again after going back to it", async () => {
serveChips();
const { result, rerender } = renderOnTraceTab('thread');
await waitFor(() =>
expect(result.current.chips).toStrictEqual(chipFor('thread')),
);
rerender({ tab: 'flamegraph' });
await waitFor(() =>
expect(result.current.chips).toStrictEqual(chipFor('flamegraph')),
);
rerender({ tab: 'thread' });
expect(result.current.chips).toStrictEqual(chipFor('thread'));
});
it('ignores a slow answer for the previous tab', async () => {
const { release } = serveChips('thread');
const { result, rerender } = renderOnTraceTab('thread');
rerender({ tab: 'flamegraph' });
await waitFor(() =>
expect(result.current.chips).toStrictEqual(chipFor('flamegraph')),
);
release();
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
expect(result.current.chips).toStrictEqual(chipFor('flamegraph'));
});
});

View File

@@ -5,21 +5,26 @@ import { getEmptyStateChips } from 'api/ai-assistant/chat';
import type { ChipDTO } from '@signozhq/noz-client';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useResolvePageType } from 'hooks/aiAssistant/useResolvePageType';
import { useAssistantPageStore } from '../../pageContext/store/useAssistantPageStore';
import { useAssistantSurface } from '../../pageContext/hooks/useAssistantSurface';
import { EMPTY_STATE_CHIPS_FALLBACK } from './emptyStateChipsFallback';
// Unknown to the backend, so it gets the general chips, as V1's `page_type=other` did.
const NO_SURFACE = 'other';
interface UseEmptyStateChipsResult {
chips: ChipDTO[];
isLoading: boolean;
}
export function useEmptyStateChips(enabled: boolean): UseEmptyStateChipsResult {
const pageType = useResolvePageType();
const surface = useAssistantSurface() ?? NO_SURFACE;
const activeViewPath = useAssistantPageStore((state) => state.activeViewPath);
// Keyed by tab, so a slow answer for the previous tab never shows on this one.
const { data, isError, isLoading } = useQuery(
[REACT_QUERY_KEY.AI_ASSISTANT_EMPTY_STATE_CHIPS, pageType],
({ signal }) => getEmptyStateChips(pageType, signal),
[REACT_QUERY_KEY.AI_ASSISTANT_EMPTY_STATE_CHIPS, surface, activeViewPath],
({ signal }) => getEmptyStateChips({ surface, activeViewPath }, signal),
{ enabled },
);

View File

@@ -5,6 +5,7 @@ import { Check, X } from '@signozhq/icons';
import { AIAssistantEvents } from '../../../events';
import { useAIAssistantAnalyticsContext } from '../../../hooks/useAIAssistantAnalyticsContext';
import { useSendMessage } from '../../../hooks/useSendMessage';
import { useAIAssistantStore } from '../../../store/useAIAssistantStore';
import { useMessageContext } from '../../MessageContext';
@@ -39,7 +40,7 @@ export default function ConfirmBlock({
const { messageId } = useMessageContext();
const answeredBlocks = useAIAssistantStore((s) => s.answeredBlocks);
const markBlockAnswered = useAIAssistantStore((s) => s.markBlockAnswered);
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const sendMessage = useSendMessage();
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
// Durable answered state — survives re-renders/remounts

View File

@@ -7,6 +7,7 @@ import { RadioGroup } from '@signozhq/ui/radio-group';
import { AIAssistantEvents } from '../../../events';
import { useAIAssistantAnalyticsContext } from '../../../hooks/useAIAssistantAnalyticsContext';
import { useSendMessage } from '../../../hooks/useSendMessage';
import { useAIAssistantStore } from '../../../store/useAIAssistantStore';
import { useMessageContext } from '../../MessageContext';
@@ -39,7 +40,7 @@ export default function InteractiveQuestion({
const { messageId } = useMessageContext();
const answeredBlocks = useAIAssistantStore((s) => s.answeredBlocks);
const markBlockAnswered = useAIAssistantStore((s) => s.markBlockAnswered);
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const sendMessage = useSendMessage();
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
// Persist selected state locally only for the pending (not-yet-submitted) case

View File

@@ -1,380 +0,0 @@
import type { MessageContext } from 'api/ai-assistant/chat';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { matchRoute } from 'lib/router/matchRoute';
import { AlertListTabs } from 'pages/AlertList/types';
import { NEW_PANEL_ID } from 'pages/DashboardPage/DashboardContainer/PanelEditor/newPanelRoute';
/**
* Resolves the page the user is currently on into structured `MessageContext`
* entries with `source: 'auto'`. The agent uses these as implicit context
* (e.g. "the user is currently looking at dashboard X with this time range
* and this query").
*
* **URL-only.** All inputs come from `pathname` + `search`; we never reach
* into Redux / context. SigNoz already encodes most page state into the URL
* (`compositeQuery`, `startTime`/`endTime`, `viewKey`,
* `variables`, `expandedWidgetId`, `activeLogId`, …), so URL parsing is
* sufficient. Anything not in the URL is simply omitted from `metadata` —
* the server applies its own defaults.
*
* Returns `[]` when no mapping exists, so callers can spread the result
* unconditionally before user-picked contexts.
*/
// eslint-disable-next-line sonarjs/cognitive-complexity
export function getAutoContexts(
pathname: string,
search: string,
): MessageContext[] {
const params = new URLSearchParams(search);
const sharedMetadata = collectSharedMetadata(params);
// ── Dashboards ────────────────────────────────────────────────────────────
// Panel editor (V2). `panel/new` has no widget id yet and the schema requires
// a non-empty `panel_edit.widgetId`, so it reports `panel_create` instead.
const panelEditorMatch = matchRoute<'dashboardId' | 'panelId'>(
pathname,
ROUTES.DASHBOARD_PANEL_EDITOR,
{ exact: true },
);
if (panelEditorMatch) {
const { dashboardId, panelId } = panelEditorMatch.params;
const isNewPanel = panelId === NEW_PANEL_ID;
return [
{
source: 'auto',
type: 'dashboard',
resourceId: dashboardId,
metadata: isNewPanel
? { page: 'panel_create', ...sharedMetadata }
: { page: 'panel_edit', widgetId: panelId, ...sharedMetadata },
},
];
}
// Dashboard detail — `/dashboard/:dashboardId`. The `expandedWidgetId`
// query param signals the panel-fullscreen overlay; otherwise it's the
// plain dashboard view.
const dashboardMatch = matchRoute<'dashboardId'>(pathname, ROUTES.DASHBOARD, {
exact: true,
});
if (dashboardMatch) {
const expandedWidgetId = params.get(QueryParams.expandedWidgetId);
if (expandedWidgetId) {
return [
{
source: 'auto',
type: 'dashboard',
resourceId: dashboardMatch.params.dashboardId,
metadata: {
page: 'panel_fullscreen',
widgetId: expandedWidgetId,
...sharedMetadata,
},
},
];
}
return [
{
source: 'auto',
type: 'dashboard',
resourceId: dashboardMatch.params.dashboardId,
metadata: {
page: 'dashboard_detail',
...sharedMetadata,
},
},
];
}
// Dashboard list — `/dashboard`.
if (matchRoute(pathname, ROUTES.ALL_DASHBOARD, { exact: true })) {
return [
{
source: 'auto',
type: 'dashboard',
resourceId: null,
metadata: { page: 'dashboard_list' },
},
];
}
// ── Alerts ────────────────────────────────────────────────────────────────
// Alert detail (overview / per-rule history) — `/alerts/overview?ruleId=…`
// or `/alerts/history?ruleId=…`. Mirrors dashboard_detail: resourceId is the
// rule id and shared metadata carries the URL time range when present.
if (
matchRoute(pathname, ROUTES.ALERT_OVERVIEW, { exact: true }) ||
matchRoute(pathname, ROUTES.ALERT_HISTORY, { exact: true })
) {
const ruleId = params.get(QueryParams.ruleId);
if (ruleId) {
return [
{
source: 'auto',
type: 'alert',
resourceId: ruleId,
metadata: {
page: 'alert_detail',
ruleId,
...sharedMetadata,
},
},
];
}
}
// Alert edit — `/alerts/edit?ruleId=…`. The form syncs its query-builder
// state to the URL (`useShareBuilderUrl`), so shared metadata carries the
// alert's query + time range, mirroring the dashboard panel editor.
if (matchRoute(pathname, ROUTES.EDIT_ALERTS, { exact: true })) {
const ruleId = params.get(QueryParams.ruleId);
if (ruleId) {
return [
{
source: 'auto',
type: 'alert',
resourceId: ruleId,
metadata: { page: 'alert_edit', ruleId, ...sharedMetadata },
},
];
}
}
// Alert new — `/alerts/new`. No rule id yet (draft), but the query-builder
// state is on the URL, so shared metadata carries the in-progress query.
if (matchRoute(pathname, ROUTES.ALERTS_NEW, { exact: true })) {
return [
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: { page: 'alert_new', ...sharedMetadata },
},
];
}
// Triggered-alerts index — `/alerts/history` without a rule id.
if (matchRoute(pathname, ROUTES.ALERT_HISTORY, { exact: true })) {
return [
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: {
page: 'alerts_triggered',
...sharedMetadata,
},
},
];
}
// Alerts index — `/alerts` with tab query param (defaults to Alert Rules).
if (matchRoute(pathname, ROUTES.LIST_ALL_ALERT, { exact: true })) {
const page = resolveAlertsIndexPage(params.get(QueryParams.tab));
return [
{
source: 'auto',
type: 'alert',
resourceId: null,
metadata: {
page,
...(page === 'alerts_triggered' ? sharedMetadata : {}),
},
},
];
}
// ── Services ──────────────────────────────────────────────────────────────
// Service detail (covers sub-routes like top-level-operations) —
// `/services/:servicename[/...]`.
const serviceMatch = matchRoute<'servicename'>(
pathname,
ROUTES.SERVICE_METRICS,
);
if (serviceMatch?.params.servicename) {
return [
{
source: 'auto',
type: 'service',
resourceId: serviceMatch.params.servicename,
metadata: {
page: 'service_detail',
...sharedMetadata,
},
},
];
}
// Services list — `/services`.
if (matchRoute(pathname, ROUTES.APPLICATION, { exact: true })) {
return [
{
source: 'auto',
type: 'service',
resourceId: null,
metadata: {
page: 'services_list',
...sharedMetadata,
},
},
];
}
// ── Logs ──────────────────────────────────────────────────────────────────
if (matchRoute(pathname, ROUTES.LOGS_EXPLORER)) {
const activeLogId = params.get(QueryParams.activeLogId);
// `?activeLogId=…` indicates a log-detail panel is open. Per the
// schema, log_detail requires payload fields (timestamp, service,
// body) we can't recover from the URL alone, so we still emit the
// surrounding logs_explorer page context — the panel registry can
// layer richer log_detail context on top in a follow-up.
return [
{
source: 'auto',
type: 'logs_explorer',
resourceId: null,
metadata: {
page: 'logs_explorer',
...sharedMetadata,
...(activeLogId ? { activeLogId } : {}),
},
},
];
}
// ── Traces ────────────────────────────────────────────────────────────────
// Trace detail — `/trace/:id`. Treated as a detail-as-metadata page
// (resourceId null, `traceId` lives in metadata).
const traceMatch = matchRoute<'id'>(pathname, ROUTES.TRACE_DETAIL, {
exact: true,
});
if (traceMatch?.params.id) {
const spanId = params.get(QueryParams.selectedTimelineQuery);
return [
{
source: 'auto',
type: 'traces_explorer',
resourceId: null,
metadata: {
page: 'trace_detail',
traceId: traceMatch.params.id,
...(spanId ? { spanId } : {}),
...sharedMetadata,
},
},
];
}
if (matchRoute(pathname, ROUTES.TRACES_EXPLORER)) {
return [
{
source: 'auto',
type: 'traces_explorer',
resourceId: null,
metadata: {
page: 'traces_explorer',
...sharedMetadata,
},
},
];
}
// ── Metrics ───────────────────────────────────────────────────────────────
// Metrics explorer — `/metrics-explorer` and sub-routes (summary, explorer).
if (matchRoute(pathname, ROUTES.METRICS_EXPLORER_BASE)) {
return [
{
source: 'auto',
type: 'metrics_explorer',
resourceId: null,
metadata: {
page: 'metrics_explorer',
...sharedMetadata,
},
},
];
}
// NOTE: Homepage (`/home`) and infrastructure monitoring
// (`/infrastructure-monitoring/*`) intentionally emit no auto-context here.
// They have no resource that maps to `MessageContextDTOType`, so attaching
// a chip would misrepresent the page (e.g. a bogus "metrics_explorer"
// context). Their `page_type` for empty-state chips is resolved directly
// from the route in `resolvePageType`.
return [];
}
type AlertsIndexPage = 'alert_list' | 'alerts_triggered';
function resolveAlertsIndexPage(tab: string | null): AlertsIndexPage {
if (tab === AlertListTabs.TRIGGERED_ALERTS) {
return 'alerts_triggered';
}
return 'alert_list';
}
/**
* Pulls metadata fields that any page may carry in its query string —
* `timeRange`, `query`, saved-view selectors, dashboard variables. Each
* piece is omitted when the URL doesn't carry it (rather than being filled
* in with a stale default).
*/
function collectSharedMetadata(
params: URLSearchParams,
): Record<string, unknown> {
const out: Record<string, unknown> = {};
// Time range — emit only when both bounds are explicit. SigNoz writes
// `startTime` / `endTime` in milliseconds when the user picks a custom
// range; relative ranges (`relativeTime=15m`) are left out because the
// server applies its own freshly-anchored window.
const startTime = numericParam(params, QueryParams.startTime);
const endTime = numericParam(params, QueryParams.endTime);
if (startTime !== null && endTime !== null) {
out.timeRange = { start: startTime, end: endTime };
}
// Query Builder state — URL-encoded JSON written by `QueryBuilderProvider`.
const compositeQueryRaw = params.get(QueryParams.compositeQuery);
if (compositeQueryRaw) {
try {
out.query = JSON.parse(decodeURIComponent(compositeQueryRaw));
} catch {
// Malformed JSON in the URL — drop silently rather than throw
// inside a context-collection helper.
}
}
// Saved view selectors (logs / traces explorer) and dashboard variables.
const viewKey = params.get(QueryParams.viewKey);
if (viewKey) {
out.savedViewId = viewKey;
}
const variablesRaw = params.get(QueryParams.variables);
if (variablesRaw) {
try {
out.variables = JSON.parse(decodeURIComponent(variablesRaw));
} catch {
// Same fallback as compositeQuery — keep silent on malformed JSON.
}
}
return out;
}
function numericParam(params: URLSearchParams, key: string): number | null {
const raw = params.get(key);
if (raw === null) {
return null;
}
const value = Number(raw);
return Number.isFinite(value) ? value : null;
}

View File

@@ -0,0 +1,51 @@
import removeLocalStorageKey from 'api/browser/localstorage/remove';
import setLocalStorageKey from 'api/browser/localstorage/set';
import { LOCALSTORAGE } from 'constants/localStorage';
import { act, AllTheProviders, renderHook } from 'tests/test-utils';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import type { SendMessageOptions } from '../../types';
import { useSendMessage } from '../useSendMessage';
const storeSend = useAIAssistantStore.getState().sendMessage;
afterEach(() => {
useAIAssistantStore.setState({ sendMessage: storeSend });
removeLocalStorageKey(LOCALSTORAGE.PREFERRED_TIMEZONE);
jest.restoreAllMocks();
});
describe('useSendMessage', () => {
it('stamps each send with the time it was pressed, in the selected timezone', async () => {
setLocalStorageKey(LOCALSTORAGE.PREFERRED_TIMEZONE, 'Asia/Kolkata');
const sendMessage = jest.fn() as jest.MockedFunction<
(text: string, options: SendMessageOptions) => Promise<void>
>;
useAIAssistantStore.setState({ sendMessage });
const now = jest.spyOn(Date, 'now');
const { result } = renderHook(() => useSendMessage(), {
wrapper: AllTheProviders,
});
now.mockReturnValue(1795948200000);
await act(() => result.current('first', { context: { mentions: [] } }));
now.mockReturnValue(1795948260000);
await act(() => result.current('second'));
expect(sendMessage.mock.calls).toStrictEqual([
[
'first',
{
context: { mentions: [] },
timeContext: { capturedAtMs: 1795948200000, timeZone: 'Asia/Kolkata' },
},
],
[
'second',
{
timeContext: { capturedAtMs: 1795948260000, timeZone: 'Asia/Kolkata' },
},
],
]);
});
});

View File

@@ -0,0 +1,25 @@
import { useCallback } from 'react';
import { useTimezone } from 'providers/Timezone';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import type { SendMessageOptions } from '../types';
type SendMessage = (
text: string,
options?: Omit<SendMessageOptions, 'timeContext'>,
) => Promise<void>;
/** Sends with the time the user pressed Send and the timezone selected in SigNoz. */
export function useSendMessage(): SendMessage {
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
const { timezone } = useTimezone();
return useCallback<SendMessage>(
(text, options) =>
sendMessage(text, {
...options,
timeContext: { capturedAtMs: Date.now(), timeZone: timezone.value },
}),
[sendMessage, timezone.value],
);
}

View File

@@ -0,0 +1,113 @@
import { KnownAssistantSurfaceDTO as Surface } from '@signozhq/noz-client';
import ROUTES from 'constants/routes';
import { AlertListSubTabs, AlertListTabs } from 'pages/AlertList/types';
import type { RouteKey } from './types';
// Copied from the backend (signoz-ai-assistant app/schemas/context.py); one over cuts the page to `surface` and `root`.
export const MAX_PATHS = 4;
export const MAX_PATH_NODES = 6;
export const MAX_VIEW_PATH = 6;
export const MAX_DATA_VIEWS = 8;
export const MAX_SELECTIONS = 4;
export const MAX_VARIABLES = 32;
export const MAX_SETTINGS = 16;
export const MAX_VALUE_LIST = 32;
export const MAX_VARIABLE_TEXT = 1024;
export const MAX_SETTING_TEXT = 256;
// View keys the backend's `KnownDataViewKeyDTO` doesn't list yet.
export const METER_CHART_VIEW = 'meter_chart';
export const METRIC_INSPECT_VIEW = 'metric_inspect';
// Maps, not objects: a `?tab=constructor` must not resolve to Object.prototype.
export const ALERT_TAB_SURFACES = new Map<string | null, Surface>([
[AlertListTabs.TRIGGERED_ALERTS, Surface.alerttriggered],
[AlertListTabs.CHANNELS, Surface.alertchannellist],
[AlertListTabs.ROUTING_POLICIES, Surface.alertrouting],
[AlertListTabs.PLANNED_DOWNTIME, Surface.alertdowntime],
]);
export const ALERT_SUB_TAB_SURFACES = new Map<string | null, Surface>([
[AlertListSubTabs.ROUTING_POLICIES, Surface.alertrouting],
[AlertListSubTabs.PLANNED_DOWNTIME, Surface.alertdowntime],
]);
export const SETTINGS_SURFACES: [string, Surface][] = [
[ROUTES.SETTINGS, Surface.settingsworkspace],
[ROUTES.MY_SETTINGS, Surface.settingsaccount],
[ROUTES.ORG_SETTINGS, Surface.settingssso],
[ROUTES.INGESTION_SETTINGS, Surface.settingsingestion],
[ROUTES.BILLING, Surface.settingsbilling],
[ROUTES.MEMBERS_SETTINGS, Surface.settingsmembers],
[ROUTES.ROLES_SETTINGS, Surface.settingsroles],
[ROUTES.ROLE_CREATE, Surface.settingsroles],
[ROUTES.ROLE_DETAILS, Surface.settingsroles],
[ROUTES.ROLE_EDIT, Surface.settingsroles],
[ROUTES.SERVICE_ACCOUNTS_SETTINGS, Surface.settingsservice_accounts],
[ROUTES.SHORTCUTS, Surface.settingsshortcuts],
[ROUTES.MCP_SERVER, Surface.settingsmcp_server],
];
/** Every key in the route table but those in `URL_SURFACES`, with its surface; `null` sends no page. */
export const ROUTE_SURFACES: Partial<Record<RouteKey, Surface | null>> = {
HOME: Surface.homeoverview,
APPLICATION: Surface.servicelist,
SERVICE_METRICS: Surface.servicedetail,
SERVICE_TOP_LEVEL_OPERATIONS: Surface.servicedetail,
SERVICE_MAP: Surface.servicemap,
ALL_DASHBOARD: Surface.dashboardlist,
DASHBOARD: Surface.dashboarddetail,
DASHBOARD_PANEL_EDITOR: Surface.dashboardpaneleditor,
ALERT_OVERVIEW: Surface.alertruledetail,
ALERT_HISTORY: Surface.alertruledetail,
EDIT_ALERTS: Surface.alertruledetail,
ALERTS_NEW: Surface.alertruleeditor,
CHANNELS_NEW: Surface.alertchanneleditor,
CHANNELS_EDIT: Surface.alertchanneleditor,
LOGS: Surface.logexplorer,
LOGS_PIPELINES: Surface.logpipeline,
// The backend has no surface for logs settings yet.
LOGS_INDEX_FIELDS: null,
TRACES_EXPLORER: Surface.traceexplorer,
TRACE_DETAIL: Surface.tracedetail,
TRACES_FUNNELS: Surface.tracefunnellist,
TRACES_FUNNELS_DETAIL: Surface.tracefunneldetail,
METRICS_EXPLORER: Surface.metricsummary,
METRICS_EXPLORER_EXPLORER: Surface.metricexplorer,
METRICS_EXPLORER_VOLUME_CONTROL: Surface.metricvolume_control,
ALL_ERROR: Surface.exceptionlist,
ERROR_DETAIL: Surface.exceptiondetail,
INFRASTRUCTURE_MONITORING_HOSTS: Surface.infrastructurehostlist,
INFRASTRUCTURE_MONITORING_KUBERNETES: Surface.infrastructurekuberneteslist,
API_MONITORING: Surface.api_monitoringexplorer,
MESSAGING_QUEUES_OVERVIEW: Surface.messagingoverview,
MESSAGING_QUEUES_KAFKA: Surface.messagingkafka,
MESSAGING_QUEUES_KAFKA_DETAIL: Surface.messagingkafkadetail,
MESSAGING_QUEUES_CELERY_TASK: Surface.messagingcelery,
METER: Surface.meteroverview,
METER_EXPLORER: Surface.meterexplorer,
USAGE_EXPLORER: Surface.usageexplorer,
INTEGRATIONS: Surface.integrationcatalog,
INTEGRATIONS_DETAIL: Surface.integrationdetail,
AI_OBSERVABILITY_OVERVIEW: Surface.ai_observabilityoverview,
AI_OBSERVABILITY_EXPLORER: Surface.ai_observabilityexplorer,
AI_OBSERVABILITY_CONFIGURATION: Surface.ai_observabilitymodel_pricing,
AI_OBSERVABILITY_ATTRIBUTE_MAPPING: Surface.ai_observabilityattribute_mapping,
ONBOARDING: Surface.onboardingorganization,
GET_STARTED_WITH_CLOUD: Surface.onboardingdata_source,
SUPPORT: Surface.supportoverview,
LIST_LICENSES: Surface.licenseapply,
AI_ASSISTANT: null,
PUBLIC_DASHBOARD: null,
VERSION: null,
SIGN_UP: null,
LOGIN: null,
FORGOT_PASSWORD: null,
PASSWORD_RESET: null,
UN_AUTHORIZED: null,
SOMETHING_WENT_WRONG: null,
WORKSPACE_LOCKED: null,
WORKSPACE_SUSPENDED: null,
WORKSPACE_ACCESS_RESTRICTED: null,
};

View File

@@ -0,0 +1,37 @@
import { renderHook } from 'tests/test-utils';
import { useAssistantActiveView } from '../useAssistantActiveView';
import { useAssistantPageStore } from '../../store/useAssistantPageStore';
function activeViewPath(): string[] {
return useAssistantPageStore.getState().activeViewPath;
}
afterEach(() => {
useAssistantPageStore.setState({ activeViewPath: [] });
});
describe('useAssistantActiveView', () => {
it('publishes the tab while its owner is mounted, and follows a tab change', () => {
const { rerender, unmount } = renderHook(
({ tab }: { tab: string | null }) => useAssistantActiveView(tab),
{ initialProps: { tab: 'overview' } },
);
expect(activeViewPath()).toStrictEqual(['overview']);
rerender({ tab: 'db_calls' });
expect(activeViewPath()).toStrictEqual(['db_calls']);
unmount();
expect(activeViewPath()).toStrictEqual([]);
});
it("never clears the next owner's tab when an old owner leaves", () => {
const old = renderHook(() => useAssistantActiveView('history'));
renderHook(() => useAssistantActiveView('overview'));
old.unmount();
expect(activeViewPath()).toStrictEqual(['overview']);
});
});

View File

@@ -0,0 +1,69 @@
import {
type ContextNodeDTO,
KnownAssistantSurfaceDTO,
type PageContextDTO,
} from '@signozhq/noz-client';
import { renderHook } from 'tests/test-utils';
import { snapshotAssistantContext } from '../../store/usePageContextStore';
import type { AssistantContextPart } from '../../types';
import { useAssistantState } from '../useAssistantState';
const SURFACE = KnownAssistantSurfaceDTO.dashboarddetail;
function snapshot(): PageContextDTO | null {
return snapshotAssistantContext({
surface: SURFACE,
activeViewPath: [],
});
}
function panelPath(id: string): ContextNodeDTO[] {
return [{ target: { kind: 'dashboard_panel', resourceId: id } }];
}
function focusedPanels(): (string | null | undefined)[] {
return (snapshot()?.activePaths ?? [])
.filter((path) => path.focused)
.map((path) => path.nodes[0].target.resourceId);
}
describe('useAssistantState', () => {
it('reads the latest getter only on Send, and leaves the page on unmount', () => {
const getter = jest.fn((env: string) => ({
state: { variableValues: [{ name: 'env', value: env }] },
})) as jest.MockedFunction<(env: string) => AssistantContextPart>;
const { rerender, unmount } = renderHook(
({ env }) => useAssistantState(() => getter(env)),
{ initialProps: { env: 'prod' } },
);
rerender({ env: 'staging' });
expect(getter).not.toHaveBeenCalled();
expect(snapshot()?.state?.variableValues).toStrictEqual([
{ name: 'env', value: 'staging' },
]);
unmount();
expect(snapshot()).toStrictEqual({ surface: SURFACE });
});
it('marks its path focused only while `focused` is set', () => {
renderHook(() => useAssistantState(() => ({ path: panelPath('a') })));
const { rerender, unmount } = renderHook(
({ focused }: { focused: boolean }) =>
useAssistantState(() => ({ path: panelPath('b') }), { focused }),
{ initialProps: { focused: true } },
);
expect(focusedPanels()).toStrictEqual(['b']);
rerender({ focused: false });
expect(focusedPanels()).toStrictEqual([]);
rerender({ focused: true });
unmount();
expect(focusedPanels()).toStrictEqual([]);
});
});

View File

@@ -0,0 +1,62 @@
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { render, screen } from 'tests/test-utils';
import { useAssistantScreen } from '../useAssistantScreen';
import { useAssistantSurface } from '../useAssistantSurface';
function LiveLogs({ liveMode }: { liveMode: boolean }): null {
useAssistantScreen({ liveMode });
return null;
}
function SurfaceProbe(): JSX.Element {
return <span data-testid="surface">{useAssistantSurface() ?? 'none'}</span>;
}
function LogsScreen({
liveMode,
mounted = true,
}: {
liveMode: boolean;
mounted?: boolean;
}): JSX.Element {
return (
<>
{mounted && <LiveLogs liveMode={liveMode} />}
<SurfaceProbe />
</>
);
}
describe('useAssistantSurface', () => {
it('follows live mode on the logs explorer, and drops it when the screen goes', () => {
const { rerender } = render(<LogsScreen liveMode />, undefined, {
initialRoute: '/logs/logs-explorer',
});
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.loglive,
);
rerender(<LogsScreen liveMode={false} />);
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.logexplorer,
);
rerender(<LogsScreen liveMode />);
rerender(<LogsScreen liveMode mounted={false} />);
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.logexplorer,
);
});
it('reads the URL query', () => {
render(<SurfaceProbe />, undefined, {
initialRoute: '/alerts?tab=TriggeredAlerts',
});
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.alerttriggered,
);
});
});

View File

@@ -0,0 +1,80 @@
import {
DataShapeDTO,
type DataViewDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { makeView } from 'container/SavedViews/__tests__/savedViewsTestUtils';
import { useActiveSavedView } from 'container/SavedViews/hooks/useActiveSavedView';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import { snapshotAssistantContext } from '../../store/usePageContextStore';
import { useExplorerAssistantContext } from '../useExplorerAssistantContext';
jest.mock('container/SavedViews/hooks/useActiveSavedView', () => ({
useActiveSavedView: jest.fn(),
}));
const mockUseActiveSavedView = jest.mocked(useActiveSavedView);
function explorerView(): DataViewDTO | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.logexplorer,
activeViewPath: [],
})?.state?.dataViews?.[0];
}
function renderExplorer(panelType: PANEL_TYPES): void {
renderHook(() => useExplorerAssistantContext(SavedviewtypesSourceDTO.logs), {
wrapper: ({ children }): JSX.Element => (
<AllTheProviders
queryBuilderOverrides={{ stagedQuery: initialQueriesMap.logs, panelType }}
>
{children}
</AllTheProviders>
),
});
}
describe('useExplorerAssistantContext', () => {
beforeEach(() => {
mockUseActiveSavedView.mockReturnValue({
view: makeView({
id: 'v1',
displayName: 'Checkout errors',
source: SavedviewtypesSourceDTO.logs,
dataSource: DataSource.LOGS,
}),
isLoading: false,
isError: false,
isReadDenied: false,
errorMessage: undefined,
hasUnsavedChanges: true,
});
});
it('adds the view with the query that ran, the columns shown and the applied saved view', () => {
renderExplorer(PANEL_TYPES.LIST);
expect(explorerView()).toMatchObject({
key: 'log_explorer',
shape: DataShapeDTO.list,
signal: 'logs',
focused: true,
query: { requestType: 'raw' },
savedView: { id: 'v1', name: 'Checkout errors', dirty: true },
});
expect(explorerView()?.visibleFields).toStrictEqual([
{ name: 'timestamp', fieldContext: 'log' },
{ name: 'body', fieldContext: 'log' },
]);
});
it('sends no columns outside the list view', () => {
renderExplorer(PANEL_TYPES.TIME_SERIES);
expect(explorerView()).toMatchObject({ shape: DataShapeDTO.timeseries });
expect(explorerView()?.visibleFields).toBeUndefined();
});
});

View File

@@ -0,0 +1,17 @@
import { useEffect } from 'react';
import {
clearAssistantActiveView,
setAssistantActiveViewPath,
} from '../store/useAssistantPageStore';
/** Publishes the tab the user is on as the page's `activeViewPath`; `key` is the backend's snake_case name. */
export function useAssistantActiveView(key: string | null): void {
useEffect(() => {
if (!key) {
return undefined;
}
setAssistantActiveViewPath([key]);
return (): void => clearAssistantActiveView(key);
}, [key]);
}

View File

@@ -0,0 +1,12 @@
import { useEffect } from 'react';
import type { AssistantScreenState } from '../types';
import { setAssistantScreen } from '../store/useAssistantPageStore';
/** Publishes what the screen knows about itself, and clears it when the screen goes. */
export function useAssistantScreen({ liveMode }: AssistantScreenState): void {
useEffect(() => {
setAssistantScreen({ liveMode });
return (): void => setAssistantScreen({ liveMode: undefined });
}, [liveMode]);
}

View File

@@ -0,0 +1,32 @@
import { useEffect, useId, useLayoutEffect, useRef } from 'react';
import type { AssistantContextGetter } from '../types';
import {
focusAssistantContext,
registerAssistantContext,
} from '../store/usePageContextStore';
interface UseAssistantStateOptions {
/** The user is working in the path this component adds, such as an open panel. */
focused?: boolean;
}
/** Adds this component's part to the page context while it is mounted; `getter` runs only on Send. */
export function useAssistantState(
getter: AssistantContextGetter,
{ focused = false }: UseAssistantStateOptions = {},
): void {
const id = useId();
const getterRef = useRef(getter);
useLayoutEffect(() => {
getterRef.current = getter;
});
useEffect(() => registerAssistantContext(id, () => getterRef.current()), [id]);
useEffect(
() => (focused ? focusAssistantContext(id) : undefined),
[id, focused],
);
}

View File

@@ -0,0 +1,16 @@
import { useMemo } from 'react';
import type { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { useAppLocation } from 'lib/router/useAppLocation';
import { getSurface } from '../utils/routeSurfaces';
import { useAssistantPageStore } from '../store/useAssistantPageStore';
/** The surface of the screen the user is on; `null` sends no page. */
export function useAssistantSurface(): KnownAssistantSurfaceDTO | null {
const { pathname, search } = useAppLocation();
const screen = useAssistantPageStore((state) => state.screen);
return useMemo(
() => getSurface({ pathname, search }, screen),
[pathname, search, screen],
);
}

View File

@@ -0,0 +1,61 @@
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';
import useOptionsMenu from 'container/OptionsMenu/useOptionsMenu';
import { useActiveSavedView } from 'container/SavedViews/hooks/useActiveSavedView';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { isPreferenceSourcePage } from 'providers/preferences/utils';
import {
EXPLORER_VIEWS,
toExplorerDataView,
toVisibleFields,
} from '../utils/explorerViews';
import { useAssistantState } from './useAssistantState';
interface UseExplorerAssistantContextOptions {
/** Off while another view, such as live logs, replaces the explorer. */
enabled?: boolean;
}
/** Adds the explorer's view: the query that ran, the columns shown and the applied saved view. */
export function useExplorerAssistantContext(
source: SavedviewtypesSourceDTO,
{ enabled = true }: UseExplorerAssistantContextOptions = {},
): void {
const { stagedQuery, panelType } = useQueryBuilder();
const { view, hasUnsavedChanges } = useActiveSavedView(source);
const hasColumns = isPreferenceSourcePage(source);
const { options } = useOptionsMenu({
sourcePage: hasColumns ? source : SavedviewtypesSourceDTO.logs,
});
const viewPanelType = panelType ?? PANEL_TYPES.LIST;
useAssistantState(() => {
const explorerView = EXPLORER_VIEWS[source];
if (!explorerView || !enabled) {
return null;
}
const showsColumns = hasColumns && viewPanelType === PANEL_TYPES.LIST;
return {
state: {
dataViews: [
toExplorerDataView({
view: explorerView,
panelType: viewPanelType,
stagedQuery,
visibleFields: showsColumns
? toVisibleFields(options.selectColumns)
: undefined,
savedView: view
? {
id: view.id,
name: view.spec.displayName,
dirty: hasUnsavedChanges,
}
: undefined,
}),
],
},
};
});
}

View File

@@ -0,0 +1,14 @@
import { useGlobalTimeStore } from 'store/globalTime';
import { toPageTime } from '../utils/time';
import { useAssistantState } from './useAssistantState';
/** While a picker bound to the global time is on screen, the page carries that time. */
export function useGlobalPageTime(enabled: boolean): void {
const selectedTime = useGlobalTimeStore((state) => state.selectedTime);
useAssistantState(() => {
const time = enabled ? toPageTime(selectedTime) : null;
return time ? { state: { time } } : null;
});
}

View File

@@ -0,0 +1,330 @@
import {
type ContextNodeDTO,
type DataViewDTO,
DataShapeDTO,
type PageContextDTO,
type SeriesPointSelectionDTO,
StreamStateDTO,
type TimeRangeDTO,
} from '@signozhq/noz-client';
import type { AssistantContextGetter } from '../../types';
import {
focusAssistantContext,
peekAssistantRoot,
registerAssistantContext,
snapshotAssistantContext,
} from '../usePageContextStore';
const SURFACE = 'dashboard.detail';
const TIME: TimeRangeDTO = {
mode: 'range',
startMs: 1795946400000,
endMs: 1795950000000,
preset: '1h',
};
const POINT: SeriesPointSelectionDTO = {
kind: 'series_point',
atMs: 1795948200000,
value: 812,
};
const cleanups: (() => void)[] = [];
function register(id: string, getter: AssistantContextGetter): () => void {
const cleanup = registerAssistantContext(id, getter);
cleanups.push(cleanup);
return cleanup;
}
function focus(id: string): () => void {
const cleanup = focusAssistantContext(id);
cleanups.push(cleanup);
return cleanup;
}
function snapshot(activeViewPath: string[] = []): PageContextDTO {
const page = snapshotAssistantContext({
surface: SURFACE,
activeViewPath,
});
if (!page) {
throw new Error('expected a page');
}
return page;
}
function panelNode(id: string, view?: Partial<DataViewDTO>): ContextNodeDTO {
return {
target: { kind: 'dashboard_panel', resourceId: id },
state: view
? {
dataViews: [
{ key: 'panel_chart', shape: DataShapeDTO.timeseries, ...view },
],
}
: undefined,
};
}
afterEach(() => {
cleanups.splice(0).forEach((cleanup) => cleanup());
});
describe('usePageContextStore', () => {
it('returns no page without a surface, and the surface alone when nothing is registered', () => {
expect(
snapshotAssistantContext({ surface: null, activeViewPath: [] }),
).toBeNull();
expect(snapshot()).toStrictEqual({ surface: SURFACE });
});
it('merges every owner into one page state, later owners winning by name and key', () => {
register('dashboard', () => ({
root: { kind: 'dashboard', resourceId: 'd1', resourceName: null },
state: {
variableValues: [{ name: 'env', value: 'prod' }],
dataViews: [{ key: 'panel_chart', shape: DataShapeDTO.value }],
},
}));
register('time', () => ({ state: { time: TIME } }));
register('variables', () => ({
state: {
variableValues: [
{ name: 'env', value: 'staging' },
{ name: 'service', value: ['cart'] },
],
dataViews: [{ key: 'panel_chart', shape: DataShapeDTO.timeseries }],
},
}));
expect(snapshot(['overview'])).toStrictEqual({
surface: SURFACE,
root: { kind: 'dashboard', resourceId: 'd1' },
state: {
time: TIME,
activeViewPath: ['overview'],
variableValues: [
{ name: 'env', value: 'staging' },
{ name: 'service', value: ['cart'] },
],
dataViews: [{ key: 'panel_chart', shape: DataShapeDTO.timeseries }],
},
});
});
it('merges the fields owners add to the same view', () => {
register('query', () => ({
state: {
dataViews: [
{ key: 'log_explorer', shape: DataShapeDTO.table, signal: 'logs' },
],
},
}));
register('columns', () => ({
state: {
dataViews: [
{
key: 'log_explorer',
shape: DataShapeDTO.list,
visibleFields: [{ name: 'service.name' }],
},
],
},
}));
expect(snapshot().state?.dataViews).toStrictEqual([
{
key: 'log_explorer',
shape: DataShapeDTO.list,
signal: 'logs',
visibleFields: [{ name: 'service.name' }],
},
]);
});
it("marks only the focused owner's path, puts it first, and clears focus when that owner leaves", () => {
register('panel-a', () => ({ path: [panelNode('a')] }));
const leaveB = register('panel-b', () => ({ path: [panelNode('b')] }));
focus('panel-b');
expect(snapshot().activePaths).toStrictEqual([
{
focused: true,
nodes: [{ target: { kind: 'dashboard_panel', resourceId: 'b' } }],
},
{ nodes: [{ target: { kind: 'dashboard_panel', resourceId: 'a' } }] },
]);
leaveB();
register('panel-b', () => ({ path: [panelNode('b')] }));
expect(snapshot().activePaths?.some((path) => path.focused)).toBe(false);
});
it('clears focus only from the owner that still holds it', () => {
register('panel-a', () => ({ path: [panelNode('a')] }));
register('panel-b', () => ({ path: [panelNode('b')] }));
const blurA = focus('panel-a');
const blurB = focus('panel-b');
blurA();
expect(snapshot().activePaths?.[0]).toStrictEqual({
focused: true,
nodes: [{ target: { kind: 'dashboard_panel', resourceId: 'b' } }],
});
blurB();
expect(snapshot().activePaths?.some((path) => path.focused)).toBe(false);
});
it('keeps selections only on the one focused view of a focused path', () => {
register('pinned', () => ({
path: [panelNode('a', { focused: true, selections: [POINT] })],
}));
register('open', () => ({
path: [panelNode('b', { focused: true, selections: [POINT] })],
}));
register('page', () => ({
state: {
dataViews: [
{ key: 'first', shape: DataShapeDTO.table, focused: true },
{ key: 'second', shape: DataShapeDTO.table, focused: true },
],
},
}));
focus('open');
const page = snapshot();
expect(page.activePaths?.map((path) => path.nodes[0].state)).toStrictEqual([
{
dataViews: [
{
key: 'panel_chart',
shape: DataShapeDTO.timeseries,
focused: true,
selections: [POINT],
},
],
},
{
dataViews: [
{ key: 'panel_chart', shape: DataShapeDTO.timeseries, focused: true },
],
},
]);
expect(page.state?.dataViews).toStrictEqual([
{ key: 'first', shape: DataShapeDTO.table, focused: true },
{ key: 'second', shape: DataShapeDTO.table },
]);
});
it('never lets an old cleanup remove a newer getter under the same id', () => {
const leaveStale = register('picker', () => ({ state: { time: TIME } }));
register('picker', () => ({ state: { stream: StreamStateDTO.active } }));
leaveStale();
expect(snapshot().state).toStrictEqual({ stream: StreamStateDTO.active });
});
it('leaves out a getter that throws', () => {
register('broken', () => {
throw new Error('unmounted store');
});
register('time', () => ({ state: { time: TIME } }));
expect(snapshot()).toStrictEqual({ surface: SURFACE, state: { time: TIME } });
});
it('drops every time on a streaming state', () => {
register('picker', () => ({ state: { time: TIME } }));
register('live', () => ({
state: {
stream: StreamStateDTO.active,
dataViews: [{ key: 'live_log_list', shape: DataShapeDTO.list, time: TIME }],
},
}));
expect(snapshot().state).toStrictEqual({
stream: StreamStateDTO.active,
dataViews: [{ key: 'live_log_list', shape: DataShapeDTO.list }],
});
});
it('keeps lists within the backend limits', () => {
register('variables', () => ({
state: {
variableValues: Array.from({ length: 40 }, (_, i) => ({
name: `v${i}`,
value: i,
})),
},
}));
register('too-deep', () => ({
path: Array.from({ length: 7 }, (_, i) => panelNode(`deep-${i}`)),
}));
['a', 'b', 'c', 'd', 'e'].forEach((id) =>
register(`panel-${id}`, () => ({ path: [panelNode(id)] })),
);
register('panel-a-again', () => ({ path: [panelNode('a')] }));
focus('panel-e');
const page = snapshot(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
expect(page.state?.variableValues).toHaveLength(32);
expect(page.state?.activeViewPath).toStrictEqual([
'a',
'b',
'c',
'd',
'e',
'f',
]);
expect(
page.activePaths?.map((path) => path.nodes[0].target.resourceId),
).toStrictEqual(['e', 'a', 'b', 'c']);
});
it('cuts long value lists and texts to the backend limits', () => {
register('variables', () => ({
state: {
variableValues: [
{ name: 'service', value: Array.from({ length: 40 }, (_, i) => `s${i}`) },
{ name: 'note', value: 'x'.repeat(2000) },
],
settings: [{ name: 'format', value: 'y'.repeat(300) }],
},
}));
const { variableValues, settings } = snapshot().state ?? {};
expect(variableValues?.[0].value).toHaveLength(32);
expect(variableValues?.[1].value).toHaveLength(1024);
expect(settings?.[0].value).toHaveLength(256);
});
it('peeks the latest root, falling back as owners leave', () => {
expect(peekAssistantRoot()).toBeNull();
register('dashboard', () => ({
root: { kind: 'dashboard', resourceId: 'd1', resourceName: null },
}));
const leaveAlert = register('alert', () => ({
root: { kind: 'alert', resourceId: 'a1', resourceName: 'High CPU' },
}));
register('time', () => ({ state: {} }));
expect(peekAssistantRoot()).toStrictEqual({
kind: 'alert',
resourceId: 'a1',
resourceName: 'High CPU',
});
leaveAlert();
expect(peekAssistantRoot()).toStrictEqual({
kind: 'dashboard',
resourceId: 'd1',
});
});
});

View File

@@ -0,0 +1,34 @@
import { create } from 'zustand';
import type { AssistantScreenState } from '../types';
interface AssistantPageState {
/** Selected tabs on the screen, outermost first. */
activeViewPath: string[];
screen: AssistantScreenState;
}
export const useAssistantPageStore = create<AssistantPageState>()(() => ({
activeViewPath: [],
screen: {},
}));
export function setAssistantActiveViewPath(activeViewPath: string[]): void {
useAssistantPageStore.setState({ activeViewPath });
}
/** Clears the path only while it is still `[key]`, so a closing tab never clears the next owner's. */
export function clearAssistantActiveView(key: string): void {
useAssistantPageStore.setState((state) =>
state.activeViewPath.length === 1 && state.activeViewPath[0] === key
? { activeViewPath: [] }
: state,
);
}
/** Merges into the screen state; a field set to `undefined` is cleared. */
export function setAssistantScreen(screen: AssistantScreenState): void {
useAssistantPageStore.setState((state) => ({
screen: { ...state.screen, ...screen },
}));
}

View File

@@ -0,0 +1,93 @@
import type { ContextTargetRefDTO, PageContextDTO } from '@signozhq/noz-client';
import { create } from 'zustand';
import { buildPageContext, pickRoot } from '../utils/buildPageContext';
import type {
AssistantContextGetter,
AssistantPageInput,
RegisteredPart,
} from '../types';
interface AssistantContextState {
/** The mounted owners' getters, in the order they registered; read only on Send. */
getters: Map<string, AssistantContextGetter>;
/** The owner whose path the user is working in. */
focusedId: string | null;
}
export const usePageContextStore = create<AssistantContextState>()(() => ({
getters: new Map(),
focusedId: null,
}));
/** Returns the cleanup; it removes only this getter, never a later one under the same id. */
export function registerAssistantContext(
id: string,
getter: AssistantContextGetter,
): () => void {
usePageContextStore.setState((state) => ({
getters: new Map(state.getters).set(id, getter),
}));
return (): void => {
usePageContextStore.setState((state) => {
if (state.getters.get(id) !== getter) {
return state;
}
const getters = new Map(state.getters);
getters.delete(id);
return {
getters,
focusedId: state.focusedId === id ? null : state.focusedId,
};
});
};
}
/** Marks the path `id` adds as the one the user is working in; the cleanup clears it only while `id` holds it. */
export function focusAssistantContext(id: string): () => void {
usePageContextStore.setState({ focusedId: id });
return (): void => {
usePageContextStore.setState((state) =>
state.focusedId === id ? { focusedId: null } : state,
);
};
}
function readParts(
getters: Map<string, AssistantContextGetter>,
): RegisteredPart[] {
const parts: RegisteredPart[] = [];
getters.forEach((getter, id) => {
try {
const part = getter();
if (part) {
parts.push({ id, part });
}
} catch {
// A broken getter leaves its part out; the message still sends.
}
});
return parts;
}
/** The root Send would carry now. */
export function peekAssistantRoot(): ContextTargetRefDTO | null {
return pickRoot(readParts(usePageContextStore.getState().getters)) ?? null;
}
/** The page Send carries: every registered getter, read now. */
export function snapshotAssistantContext({
surface,
activeViewPath,
}: AssistantPageInput): PageContextDTO | null {
if (!surface) {
return null;
}
const { getters, focusedId } = usePageContextStore.getState();
return buildPageContext({
surface,
activeViewPath,
parts: readParts(getters),
focusedId,
});
}

View File

@@ -0,0 +1,42 @@
import type {
ActivePathDTO,
ContextStateDTO,
ContextTargetRefDTO,
} from '@signozhq/noz-client';
import type ROUTES from 'constants/routes';
/** Page state one owner adds; `activeViewPath` comes from the page store instead. */
export type AssistantPartState = Omit<ContextStateDTO, 'activeViewPath'>;
/** What one mounted owner adds to the page context when the user presses Send. */
export interface AssistantContextPart {
root?: ContextTargetRefDTO;
state?: AssistantPartState;
/** One opened thing, as a chain of nodes below `root`, outermost first. */
path?: ActivePathDTO['nodes'];
}
export type AssistantContextGetter = () => AssistantContextPart | null;
export interface RegisteredPart {
id: string;
part: AssistantContextPart;
}
export interface AssistantPageInput {
surface: string | null;
activeViewPath: string[];
}
export type RouteKey = keyof typeof ROUTES;
export interface SurfaceLocation {
pathname: string;
search: string;
}
/** What a screen knows about itself that the URL doesn't carry. */
export interface AssistantScreenState {
/** The logs explorer is streaming live logs. */
liveMode?: boolean;
}

View File

@@ -0,0 +1,157 @@
import {
DataShapeDTO,
KnownDataSignalDTO,
KnownDataViewKeyDTO,
} from '@signozhq/noz-client';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import {
initialQueriesMap,
initialQueryAIWithType,
initialQueryMeterWithType,
PANEL_TYPES,
} from 'constants/queryBuilder';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EXPLORER_VIEWS, toExplorerDataView } from '../explorerViews';
const EXPRESSION = "service.name = 'checkout' AND severity_text = 'ERROR'";
function withFilter(query: Query): Query {
return {
...query,
builder: {
...query.builder,
queryData: query.builder.queryData.map((data) => ({
...data,
filter: { expression: EXPRESSION },
})),
},
};
}
describe('explorerViews', () => {
it('sends the logs explorer as the guide shows it: the query that ran, columns and saved view', () => {
const view = toExplorerDataView({
view: {
key: KnownDataViewKeyDTO.log_explorer,
signal: KnownDataSignalDTO.logs,
},
panelType: PANEL_TYPES.LIST,
stagedQuery: withFilter(initialQueriesMap.logs),
visibleFields: [{ name: 'service.name', fieldContext: 'resource' }],
savedView: { id: 'v1', name: 'Checkout errors', dirty: false },
});
expect(view).toMatchObject({
key: 'log_explorer',
shape: DataShapeDTO.list,
signal: 'logs',
focused: true,
query: {
requestType: 'raw',
compositeQuery: {
queries: [
{
type: 'builder_query',
spec: { name: 'A', signal: 'logs', filter: { expression: EXPRESSION } },
},
],
},
},
visibleFields: [{ name: 'service.name', fieldContext: 'resource' }],
savedView: { id: 'v1', name: 'Checkout errors', dirty: false },
});
});
it('sends the traces explorer with its builder query on the traces view', () => {
const view = toExplorerDataView({
view: EXPLORER_VIEWS[SavedviewtypesSourceDTO.traces] ?? { key: '' },
panelType: PANEL_TYPES.LIST,
stagedQuery: withFilter(initialQueriesMap.traces),
});
expect(view).toMatchObject({
key: 'trace_explorer',
shape: DataShapeDTO.list,
signal: 'traces',
focused: true,
query: {
requestType: 'raw',
compositeQuery: {
queries: [
{
type: 'builder_query',
spec: {
name: 'A',
signal: 'traces',
filter: { expression: EXPRESSION },
},
},
],
},
},
});
});
it('marks the AI explorer by its query type, on the traces view', () => {
const view = toExplorerDataView({
view: EXPLORER_VIEWS[SavedviewtypesSourceDTO.ai_observability] ?? {
key: '',
},
panelType: PANEL_TYPES.TRACE,
stagedQuery: initialQueryAIWithType,
});
expect(view).toMatchObject({
key: 'trace_explorer',
shape: DataShapeDTO.list,
signal: 'traces',
query: {
requestType: 'trace',
compositeQuery: { queries: [{ type: 'builder_ai_query' }] },
},
});
});
it.each([
[
SavedviewtypesSourceDTO.metrics,
PANEL_TYPES.TIME_SERIES,
'metric_chart',
'metrics',
],
[SavedviewtypesSourceDTO.meter, PANEL_TYPES.BAR, 'meter_chart', undefined],
])(
'sends the %s explorer chart as a time series',
(source, panelType, key, signal) => {
const view = toExplorerDataView({
view: EXPLORER_VIEWS[source] ?? { key: '' },
panelType,
stagedQuery:
source === SavedviewtypesSourceDTO.meter
? initialQueryMeterWithType
: initialQueriesMap.metrics,
});
expect(view).toMatchObject({
key,
shape: DataShapeDTO.timeseries,
query: { requestType: 'time_series' },
});
expect(view.signal).toBe(signal);
},
);
it('sends no query before one has run', () => {
expect(
toExplorerDataView({
view: {
key: KnownDataViewKeyDTO.log_explorer,
signal: KnownDataSignalDTO.logs,
},
panelType: PANEL_TYPES.LIST,
stagedQuery: null,
}).query,
).toBeUndefined();
});
});

View File

@@ -0,0 +1,59 @@
import { KnownAssistantSurfaceDTO as Surface } from '@signozhq/noz-client';
import routes, { LIST_LICENSES, SUPPORT_ROUTE } from 'AppRoutes/routes';
import { ROUTE_SURFACES } from '../../constants';
import { findRouteKey, getSurface, URL_SURFACES } from '../routeSurfaces';
const TABLE = [...routes, LIST_LICENSES, SUPPORT_ROUTE];
describe('routeSurfaces', () => {
it('names a surface, or no page, once for exactly the routes in the table', () => {
const tableKeys = new Set(TABLE.map(({ key }) => key));
const mappedKeys = [
...Object.keys(ROUTE_SURFACES),
...Object.keys(URL_SURFACES),
];
expect(mappedKeys.sort()).toStrictEqual([...tableKeys].sort());
});
it('finds its own entry for every path in the table, and none outside it', () => {
const misses = TABLE.flatMap(({ key, path, nested }) =>
(Array.isArray(path) ? path : [path])
.map((pattern) => pattern.replace(/:[^/]+/g, 'id'))
.flatMap((pathname) =>
nested ? [pathname, `${pathname}/sub`] : [pathname],
)
.filter((pathname) => findRouteKey(pathname) !== key)
.map((pathname) => `${pathname} -> ${findRouteKey(pathname)}, not ${key}`),
);
expect(misses).toStrictEqual([]);
expect(findRouteKey('/')).toBeNull();
expect(findRouteKey('/not-a-route')).toBeNull();
});
it('reports live logs on no screen but the logs explorer', () => {
expect(
getSurface({ pathname: '/traces-explorer', search: '' }, { liveMode: true }),
).toBe(Surface.traceexplorer);
});
it.each([
['', Surface.alertrulelist],
['?tab=TriggeredAlerts', Surface.alerttriggered],
['?tab=Configuration', Surface.alertchannellist],
['?tab=Configuration&subTab=routing-policies', Surface.alertrouting],
['?tab=constructor', Surface.alertrulelist],
])('resolves the alerts list at "%s" to %s', (search, surface) => {
expect(getSurface({ pathname: '/alerts', search }, {})).toBe(surface);
});
it.each([
['/settings', Surface.settingsworkspace],
['/settings/roles/r1/edit', Surface.settingsroles],
['/settings/unknown', null],
])('resolves the settings page at %s to %s', (pathname, surface) => {
expect(getSurface({ pathname, search: '' }, {})).toBe(surface);
});
});

View File

@@ -0,0 +1,58 @@
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
import { createCustomTimeRange } from 'store/globalTime';
import { toPageTime } from '../time';
const NOW_MS = 1795950000000;
const HOUR_MS = 60 * 60 * 1000;
describe('context time', () => {
beforeEach(() => {
jest.useFakeTimers({ now: NOW_MS });
});
afterEach(() => {
jest.useRealTimers();
});
it('recomputes a relative range at Send and labels it with its preset', () => {
expect(toPageTime('1h')).toStrictEqual({
mode: 'range',
startMs: NOW_MS - HOUR_MS,
endMs: NOW_MS,
preset: '1h',
});
});
it('sends the default picker range as the last 30 minutes', () => {
expect(toPageTime(DEFAULT_TIME_RANGE)).toStrictEqual({
mode: 'range',
startMs: NOW_MS - 30 * 60 * 1000,
endMs: NOW_MS,
preset: '30m',
});
});
it('sends a custom range as stored, in whole milliseconds and without a preset', () => {
expect(
toPageTime(
createCustomTimeRange(
(NOW_MS - HOUR_MS) * 1e6 + 600_000,
NOW_MS * 1e6 + 400_000,
),
),
).toStrictEqual({
mode: 'range',
startMs: NOW_MS - HOUR_MS + 1,
endMs: NOW_MS,
});
});
it('sends no time for a range it cannot read or that does not end after it starts', () => {
expect(
toPageTime(createCustomTimeRange(NOW_MS * 1e6, NOW_MS * 1e6)),
).toBeNull();
expect(toPageTime('x||_||y')).toBeNull();
expect(toPageTime('custom')).toBeNull();
});
});

View File

@@ -0,0 +1,216 @@
import type {
ActivePathDTO,
ContextNodeDTO,
ContextStateDTO,
ContextTargetRefDTO,
DataViewDTO,
NamedValueDTO,
PageContextDTO,
} from '@signozhq/noz-client';
import { isNil, omitBy } from 'lodash-es';
import {
MAX_DATA_VIEWS,
MAX_PATH_NODES,
MAX_PATHS,
MAX_SELECTIONS,
MAX_SETTING_TEXT,
MAX_SETTINGS,
MAX_VALUE_LIST,
MAX_VARIABLE_TEXT,
MAX_VARIABLES,
MAX_VIEW_PATH,
} from '../constants';
import type { AssistantPartState, RegisteredPart } from '../types';
interface BuildPageContextInput {
surface: string;
activeViewPath: string[];
parts: RegisteredPart[];
focusedId: string | null;
}
function compact<T extends object>(value: T): T {
return omitBy(value, isNil) as T;
}
/** `uniqBy`, but the last item per key wins; it keeps the first one's position. */
function uniqByLast<T>(items: T[], keyOf: (item: T) => string): T[] {
return [...new Map(items.map((item) => [keyOf(item), item])).values()];
}
/** Owners that share a view key each add fields to that one view; a later owner wins a field. */
function mergeViews(views: DataViewDTO[]): DataViewDTO[] {
const byKey = new Map<string, DataViewDTO>();
views.forEach((view) => {
byKey.set(view.key, { ...byKey.get(view.key), ...compact(view) });
});
return [...byKey.values()];
}
function cleanNamedValues(
values: NamedValueDTO[],
maxCount: number,
maxText: number,
): NamedValueDTO[] {
const clip = <V>(value: V): V =>
(typeof value === 'string' ? value.slice(0, maxText) : value) as V;
return uniqByLast(values, (v) => v.name)
.slice(0, maxCount)
.map(({ name, value }) => ({
name,
value: Array.isArray(value)
? value.slice(0, MAX_VALUE_LIST).map(clip)
: clip(value),
}));
}
function cleanViews(
views: DataViewDTO[],
allowSelections: boolean,
dropTime: boolean,
): DataViewDTO[] {
let hasFocus = false;
return mergeViews(views)
.slice(0, MAX_DATA_VIEWS)
.map(({ focused, selections, time, ...view }) => {
const isFocused = focused === true && !hasFocus;
hasFocus ||= isFocused;
const keptSelections =
isFocused && allowSelections && selections?.length
? selections.slice(0, MAX_SELECTIONS)
: undefined;
return compact({
...view,
time: dropTime ? undefined : time,
focused: isFocused || undefined,
selections: keptSelections,
});
});
}
function cleanState(
state: ContextStateDTO | null | undefined,
allowSelections: boolean,
): ContextStateDTO | undefined {
if (!state) {
return undefined;
}
const { activeViewPath, variableValues, settings, dataViews, ...rest } = state;
// A live stream has no window, so any time on it or its views cuts the page.
const isStreaming = Boolean(rest.stream);
const cleaned = compact({
...rest,
time: isStreaming ? undefined : rest.time,
activeViewPath: activeViewPath?.length
? activeViewPath.slice(0, MAX_VIEW_PATH)
: undefined,
variableValues: variableValues?.length
? cleanNamedValues(variableValues, MAX_VARIABLES, MAX_VARIABLE_TEXT)
: undefined,
settings: settings?.length
? cleanNamedValues(settings, MAX_SETTINGS, MAX_SETTING_TEXT)
: undefined,
dataViews: dataViews?.length
? cleanViews(dataViews, allowSelections, isStreaming)
: undefined,
});
return Object.keys(cleaned).length ? cleaned : undefined;
}
function mergeStates(
states: (AssistantPartState | undefined)[],
activeViewPath: string[],
): ContextStateDTO {
return states.reduce<ContextStateDTO>(
(merged, state) => {
if (!state) {
return merged;
}
return {
...merged,
...compact(state),
activeViewPath,
variableValues: [
...(merged.variableValues ?? []),
...(state.variableValues ?? []),
],
settings: [...(merged.settings ?? []), ...(state.settings ?? [])],
dataViews: [...(merged.dataViews ?? []), ...(state.dataViews ?? [])],
};
},
{ activeViewPath },
);
}
function pathKey(nodes: ContextNodeDTO[]): string {
return JSON.stringify(
nodes.map(({ target }) => [target.kind, target.resourceId ?? null]),
);
}
function buildPaths(
parts: RegisteredPart[],
focusedId: string | null,
): ActivePathDTO[] {
const candidates = parts.flatMap(({ id, part }) =>
part.path?.length && part.path.length <= MAX_PATH_NODES
? [{ focused: id === focusedId, nodes: part.path }]
: [],
);
const seen = new Set<string>();
return [
...candidates.filter((path) => path.focused),
...candidates.filter((path) => !path.focused),
]
.filter(({ nodes }) => {
const key = pathKey(nodes);
const isNew = !seen.has(key);
seen.add(key);
return isNew;
})
.slice(0, MAX_PATHS)
.map(({ focused, nodes }) =>
compact({
focused: focused || undefined,
nodes: nodes.map((node) =>
compact({
target: compact(node.target),
state: cleanState(node.state, focused),
}),
),
}),
);
}
/** The latest owner with a root wins. */
export function pickRoot(
parts: RegisteredPart[],
): ContextTargetRefDTO | undefined {
const rootOwner = [...parts].reverse().find(({ part }) => part.root);
return rootOwner?.part.root ? compact(rootOwner.part.root) : undefined;
}
/** Merges every owner's part into one page, within the backend's list limits. */
export function buildPageContext({
surface,
activeViewPath,
parts,
focusedId,
}: BuildPageContextInput): PageContextDTO {
const root = pickRoot(parts);
const state = cleanState(
mergeStates(
parts.map(({ part }) => part.state),
activeViewPath,
),
true,
);
const paths = buildPaths(parts, focusedId);
return compact({
surface,
root,
state,
activePaths: paths.length ? paths : undefined,
});
}

View File

@@ -0,0 +1,17 @@
import { DataShapeDTO } from '@signozhq/noz-client';
import { PANEL_TYPES } from 'constants/queryBuilder';
const PANEL_SHAPES: Partial<Record<PANEL_TYPES, DataShapeDTO>> = {
[PANEL_TYPES.LIST]: DataShapeDTO.list,
[PANEL_TYPES.TRACE]: DataShapeDTO.list,
[PANEL_TYPES.TIME_SERIES]: DataShapeDTO.timeseries,
[PANEL_TYPES.BAR]: DataShapeDTO.timeseries,
[PANEL_TYPES.AREA]: DataShapeDTO.timeseries,
[PANEL_TYPES.HEATMAP]: DataShapeDTO.timeseries,
[PANEL_TYPES.VALUE]: DataShapeDTO.value,
};
/** How a view lays out its data; grouped values (tables, pies, histograms) read as a table. */
export function toDataShape(panelType: PANEL_TYPES): DataShapeDTO {
return PANEL_SHAPES[panelType] ?? DataShapeDTO.table;
}

View File

@@ -0,0 +1,85 @@
import {
type DataViewDTO,
type FieldRefDTO,
type SavedViewRefDTO,
KnownDataSignalDTO,
KnownDataViewKeyDTO,
} from '@signozhq/noz-client';
import { mapPanelTypeToRequestType } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import type { TelemetryFieldKey } from 'api/v5/v5';
import type { PANEL_TYPES } from 'constants/queryBuilder';
import { mapCompositeQueryFromQuery } from 'lib/newQueryBuilder/queryBuilderMappers/mapCompositeQueryFromQuery';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { toDataShape } from './dataShapes';
import { METER_CHART_VIEW } from '../constants';
interface ExplorerView {
key: string;
signal?: string;
}
interface ExplorerDataViewInput {
view: ExplorerView;
panelType: PANEL_TYPES;
stagedQuery: Query | null;
visibleFields?: FieldRefDTO[];
savedView?: SavedViewRefDTO;
}
/** The view each explorer sends; the AI explorer is a traces explorer whose query type marks it AI. */
export const EXPLORER_VIEWS: Partial<
Record<SavedviewtypesSourceDTO, ExplorerView>
> = {
[SavedviewtypesSourceDTO.logs]: {
key: KnownDataViewKeyDTO.log_explorer,
signal: KnownDataSignalDTO.logs,
},
[SavedviewtypesSourceDTO.traces]: {
key: KnownDataViewKeyDTO.trace_explorer,
signal: KnownDataSignalDTO.traces,
},
[SavedviewtypesSourceDTO.ai_observability]: {
key: KnownDataViewKeyDTO.trace_explorer,
signal: KnownDataSignalDTO.traces,
},
[SavedviewtypesSourceDTO.metrics]: {
key: KnownDataViewKeyDTO.metric_chart,
signal: KnownDataSignalDTO.metrics,
},
[SavedviewtypesSourceDTO.meter]: { key: METER_CHART_VIEW },
};
/** The explorer's view as the user sees it; the query is the one that ran, not unrun edits. */
export function toExplorerDataView({
view,
panelType,
stagedQuery,
visibleFields,
savedView,
}: ExplorerDataViewInput): DataViewDTO {
const queries = stagedQuery
? mapCompositeQueryFromQuery(stagedQuery, panelType).queries
: undefined;
return {
key: view.key,
shape: toDataShape(panelType),
signal: view.signal,
focused: true,
query: queries?.length
? {
compositeQuery: { queries },
requestType: mapPanelTypeToRequestType(panelType) || undefined,
}
: undefined,
visibleFields,
savedView,
};
}
export function toVisibleFields(columns: TelemetryFieldKey[]): FieldRefDTO[] {
return columns.map(({ name, fieldContext }) =>
fieldContext ? { name, fieldContext } : { name },
);
}

View File

@@ -0,0 +1,22 @@
import { type SavedViewRefDTO, SortDirectionDTO } from '@signozhq/noz-client';
import type { UseListViewsResult } from 'hooks/listViews/types';
type ListViews = Pick<
UseListViewsResult<unknown>,
'activeView' | 'isCustomActive' | 'isModified'
>;
/** The user's applied saved view; built-in views are presets, so they send none. */
export function toListSavedView({
activeView,
isCustomActive,
isModified,
}: ListViews): SavedViewRefDTO | undefined {
return isCustomActive && activeView
? { id: activeView.id, name: activeView.name, dirty: isModified }
: undefined;
}
export function toSortDirection(order: string): SortDirectionDTO {
return order === 'asc' ? SortDirectionDTO.asc : SortDirectionDTO.desc;
}

View File

@@ -0,0 +1,66 @@
import { KnownAssistantSurfaceDTO as Surface } from '@signozhq/noz-client';
import routes, { LIST_LICENSES, SUPPORT_ROUTE } from 'AppRoutes/routes';
import { matchRoute } from 'lib/router/matchRoute';
import { AlertListTabs } from 'pages/AlertList/types';
import {
ALERT_SUB_TAB_SURFACES,
ALERT_TAB_SURFACES,
ROUTE_SURFACES,
SETTINGS_SURFACES,
} from '../constants';
import type { AssistantScreenState, RouteKey, SurfaceLocation } from '../types';
/** Mirrors the tab the alerts page shows for `tab` and `subTab`. */
function alertListSurface({ search }: SurfaceLocation): Surface {
const params = new URLSearchParams(search);
const tab = params.get('tab');
if (tab === AlertListTabs.CONFIGURATION) {
return (
ALERT_SUB_TAB_SURFACES.get(params.get('subTab')) ?? Surface.alertchannellist
);
}
return ALERT_TAB_SURFACES.get(tab) ?? Surface.alertrulelist;
}
function settingsSurface({ pathname }: SurfaceLocation): Surface | null {
const entry = SETTINGS_SURFACES.find(([pattern]) =>
matchRoute(pathname, pattern, { exact: true }),
);
return entry?.[1] ?? null;
}
/** Routes whose surface depends on more of the URL than the route itself. */
export const URL_SURFACES: Partial<
Record<RouteKey, (location: SurfaceLocation) => Surface | null>
> = {
LIST_ALL_ALERT: alertListSurface,
SETTINGS: settingsSurface,
};
const ROUTE_TABLE = [...routes, LIST_LICENSES, SUPPORT_ROUTE];
/** The route table entry the router renders at `pathname`; a nested entry also owns its sub-paths. */
export function findRouteKey(pathname: string): RouteKey | null {
const entry = ROUTE_TABLE.find(({ path, nested }) =>
(Array.isArray(path) ? path : [path]).some((pattern) =>
matchRoute(pathname, pattern, { exact: !nested }),
),
);
return entry?.key ?? null;
}
export function getSurface(
location: SurfaceLocation,
screen: AssistantScreenState,
): Surface | null {
const routeKey = findRouteKey(location.pathname);
if (!routeKey) {
return null;
}
if (routeKey === 'LOGS' && screen.liveMode) {
return Surface.loglive;
}
const fromUrl = URL_SURFACES[routeKey];
return fromUrl ? fromUrl(location) : (ROUTE_SURFACES[routeKey] ?? null);
}

View File

@@ -0,0 +1,65 @@
import type { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
/** What the composer's page pill calls each surface. */
export const SURFACE_LABELS: Record<`${KnownAssistantSurfaceDTO}`, string> = {
'ai_observability.attribute_mapping': 'Attribute mapping',
'ai_observability.explorer': 'AI explorer',
'ai_observability.model_pricing': 'Model pricing',
'ai_observability.overview': 'AI overview',
'alert.channel.editor': 'Notification channel',
'alert.channel.list': 'Notification channels',
'alert.downtime': 'Planned downtime',
'alert.routing': 'Routing policies',
'alert.rule.detail': 'Alert',
'alert.rule.editor': 'Alert editor',
'alert.rule.list': 'Alert rules',
'alert.triggered': 'Triggered alerts',
'api_monitoring.explorer': 'API monitoring',
'dashboard.detail': 'Dashboard',
'dashboard.list': 'Dashboards',
'dashboard.panel.editor': 'Panel editor',
'exception.detail': 'Exception',
'exception.list': 'Exceptions',
'home.overview': 'Home',
'infrastructure.host.entity': 'Host',
'infrastructure.host.list': 'Hosts',
'infrastructure.kubernetes.entity': 'Kubernetes resource',
'infrastructure.kubernetes.list': 'Kubernetes',
'integration.catalog': 'Integrations',
'integration.detail': 'Integration',
'license.apply': 'License',
'log.detail': 'Log',
'log.explorer': 'Logs explorer',
'log.live': 'Live logs',
'log.pipeline': 'Log pipelines',
'messaging.celery': 'Celery',
'messaging.kafka': 'Kafka',
'messaging.kafka.detail': 'Kafka detail',
'messaging.overview': 'Messaging queues',
'meter.explorer': 'Meter explorer',
'meter.overview': 'Meter',
'metric.explorer': 'Metrics explorer',
'metric.summary': 'Metrics summary',
'metric.volume_control': 'Metric volume control',
'onboarding.data_source': 'Onboarding',
'onboarding.organization': 'Onboarding',
'service.detail': 'Service',
'service.list': 'Services',
'service.map': 'Service map',
'settings.account': 'Account settings',
'settings.billing': 'Billing',
'settings.ingestion': 'Ingestion settings',
'settings.mcp_server': 'MCP server',
'settings.members': 'Members',
'settings.roles': 'Roles',
'settings.service_accounts': 'Service accounts',
'settings.shortcuts': 'Keyboard shortcuts',
'settings.sso': 'SSO settings',
'settings.workspace': 'Workspace settings',
'support.overview': 'Support',
'trace.detail': 'Trace',
'trace.explorer': 'Traces explorer',
'trace.funnel.detail': 'Trace funnel',
'trace.funnel.list': 'Trace funnels',
'usage.explorer': 'Usage explorer',
};

View File

@@ -0,0 +1,27 @@
import type { TimeRangeDTO } from '@signozhq/noz-client';
import GetMinMax, { isValidShortHandDateTimeFormat } from 'lib/getMinMax';
import { parseCustomTimeRange } from 'store/globalTime';
import { nanoToMilli } from 'utils/timeUtils';
/**
* A time store's `selectedTime` at Send: a shorthand (`30m`) is recomputed
* from now and keeps its label; a custom `<minNs>||_||<maxNs>` keeps its bounds.
*/
export function toPageTime(selectedTime: string): TimeRangeDTO | null {
const isRelative = isValidShortHandDateTimeFormat(selectedTime);
const range = isRelative
? GetMinMax(selectedTime)
: parseCustomTimeRange(selectedTime);
if (!range) {
return null;
}
// Whole milliseconds; a fraction cuts the page.
const startMs = Math.round(nanoToMilli(range.minTime));
const endMs = Math.round(nanoToMilli(range.maxTime));
if (!(startMs < endMs)) {
return null;
}
return isRelative
? { mode: 'range', startMs, endMs, preset: selectedTime }
: { mode: 'range', startMs, endMs };
}

View File

@@ -1,71 +0,0 @@
import { PageTypeDTO } from '@signozhq/noz-client';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import { matchRoute } from 'lib/router/matchRoute';
import { getAutoContexts } from './getAutoContexts';
const PAGE_METADATA_TO_DTO: Record<string, PageTypeDTO> = {
dashboard_detail: PageTypeDTO.dashboard_detail,
dashboard_list: PageTypeDTO.dashboard_list,
panel_edit: PageTypeDTO.panel_edit,
// There is no panel_create, so sending panel_edit temporarily
panel_create: PageTypeDTO.panel_edit,
panel_fullscreen: PageTypeDTO.panel_fullscreen,
logs_explorer: PageTypeDTO.logs_explorer,
trace_detail: PageTypeDTO.trace_detail,
traces_explorer: PageTypeDTO.traces_explorer,
metrics_explorer: PageTypeDTO.metrics_explorer,
service_detail: PageTypeDTO.service_detail,
services_list: PageTypeDTO.services_list,
alert_edit: PageTypeDTO.alert_edit,
alert_list: PageTypeDTO.alert_list,
alert_new: PageTypeDTO.alert_new,
alerts_triggered: PageTypeDTO.alerts_triggered,
};
interface ResolvePageTypeOptions {
/** Standalone `/ai-assistant` surface — no underlying observability page. */
isStandaloneAssistant?: boolean;
}
/**
* Maps the current URL (and assistant surface) to the backend `page_type`
* enum used by contextual empty-state chips.
*/
export function resolvePageType(
pathname: string,
search: string,
options?: ResolvePageTypeOptions,
): PageTypeDTO {
if (options?.isStandaloneAssistant) {
return PageTypeDTO.other;
}
// Pseudo-pages with no attachable resource: resolved straight from the
// route. They deliberately emit no auto-context chip (see `getAutoContexts`),
// so they can't be derived from `metadata.page` like the pages below.
if (matchRoute(pathname, ROUTES.HOME, { exact: true })) {
return PageTypeDTO.homepage;
}
if (matchRoute(pathname, ROUTES.INFRASTRUCTURE_MONITORING_BASE)) {
return PageTypeDTO.infra_entity_detail;
}
const contexts = getAutoContexts(pathname, search);
const page = contexts[0]?.metadata?.page;
if (typeof page === 'string') {
if (page === 'logs_explorer') {
const activeLogId = new URLSearchParams(search).get(QueryParams.activeLogId);
if (activeLogId) {
return PageTypeDTO.log_detail;
}
}
const mapped = PAGE_METADATA_TO_DTO[page];
if (mapped) {
return mapped;
}
}
return PageTypeDTO.other;
}

View File

@@ -1,12 +1,11 @@
import {
ErrorCodeDTO,
MessageContextDTOSource,
MessageContextDTOType,
type MessageContextV2DTO,
MessageRoleDTO,
type MessageTimeContextDTO,
RetryActionDTO,
} from '@signozhq/noz-client';
import type {
MessageContext,
SSEEvent,
ThreadDetailResponse,
ThreadSummary,
@@ -42,6 +41,11 @@ const chat = jest.requireMock('api/ai-assistant/chat') as Record<
jest.Mock
>;
const TIME: MessageTimeContextDTO = {
capturedAtMs: 1795948200000,
timeZone: 'Asia/Kolkata',
};
// Builds a single-use async stream from a fixed list of SSE events.
async function* eventStream(events: SSEEvent[]): AsyncGenerator<SSEEvent> {
for (const event of events) {
@@ -91,7 +95,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore.getState().sendMessage('hello');
await useAIAssistantStore
.getState()
.sendMessage('hello', { timeContext: TIME });
const conv = useAIAssistantStore.getState().conversations['thread-1'];
expect(conv.messages).toHaveLength(2);
@@ -118,7 +124,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore.getState().sendMessage('hello');
await useAIAssistantStore
.getState()
.sendMessage('hello', { timeContext: TIME });
// The retry succeeds this time.
chat.streamEvents.mockReturnValueOnce(
@@ -147,6 +155,10 @@ describe('useAIAssistantStore — streaming error handling', () => {
// Thread already existed on retry; the user message was never re-sent as new.
expect(chat.createThread).toHaveBeenCalledTimes(1);
expect(chat.sendMessage).toHaveBeenCalledTimes(2);
expect(chat.sendMessage.mock.calls[1]).toStrictEqual([
'thread-1',
{ content: 'hello', timeContext: TIME },
]);
});
it('silently retries auto-flagged errors, then downgrades to manual once spent', async () => {
@@ -161,7 +173,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
const sending = useAIAssistantStore.getState().sendMessage('hi');
const sending = useAIAssistantStore
.getState()
.sendMessage('hi', { timeContext: TIME });
await jest.runAllTimersAsync();
await sending;
@@ -184,7 +198,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore.getState().sendMessage('hi');
await useAIAssistantStore.getState().sendMessage('hi', { timeContext: TIME });
expect(lastMessage('thread-3')).toMatchObject({
isError: true,
@@ -224,7 +238,9 @@ describe('useAIAssistantStore — streaming error handling', () => {
);
useAIAssistantStore.getState().startNewConversation();
const sending = useAIAssistantStore.getState().sendMessage('hi');
const sending = useAIAssistantStore
.getState()
.sendMessage('hi', { timeContext: TIME });
await jest.runAllTimersAsync();
await sending;
@@ -333,12 +349,16 @@ describe('useAIAssistantStore — resumed replies', () => {
});
});
describe('useAIAssistantStore — message contexts', () => {
const pickedDashboard: MessageContext = {
source: 'mention',
type: 'dashboard',
resourceId: 'dash-1',
resourceName: 'Checkout latency',
describe('useAIAssistantStore — message context', () => {
const context: MessageContextV2DTO = {
page: { surface: 'service.detail' },
mentions: [
{
kind: 'dashboard',
resourceId: 'dash-1',
resourceName: 'Checkout latency',
},
],
};
beforeEach(() => {
@@ -350,7 +370,7 @@ describe('useAIAssistantStore — message contexts', () => {
});
});
it('keeps the contexts a question was sent with', async () => {
it('sends the V2 body and keeps the context a question was sent with', async () => {
chat.createThread.mockResolvedValue('thread-1');
chat.sendMessage.mockResolvedValue('exec-1');
chat.streamEvents.mockReturnValueOnce(eventStream([]));
@@ -358,13 +378,18 @@ describe('useAIAssistantStore — message contexts', () => {
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore
.getState()
.sendMessage('Why is checkout slow?', undefined, [pickedDashboard]);
.sendMessage('Why is checkout slow?', { timeContext: TIME, context });
expect(chat.sendMessage).toHaveBeenCalledWith('thread-1', {
content: 'Why is checkout slow?',
timeContext: TIME,
context,
});
const conv = useAIAssistantStore.getState().conversations['thread-1'];
expect(conv.messages[0].contexts).toStrictEqual([pickedDashboard]);
expect(conv.messages[0].context).toStrictEqual(context);
});
it('reopens a chat with the contexts its questions were sent with', async () => {
it('reopens a chat with the context its questions were sent with', async () => {
const detail: ThreadDetailResponse = {
threadId: 'thread-1',
createdAt: '2026-11-17T00:00:00Z',
@@ -374,14 +399,8 @@ describe('useAIAssistantStore — message contexts', () => {
messageId: 'q-1',
role: MessageRoleDTO.user,
content: 'Why is checkout slow?',
contexts: [
{
source: MessageContextDTOSource.mention,
type: MessageContextDTOType.dashboard,
resourceId: 'dash-1',
resourceName: 'Checkout latency',
},
],
context,
timeContext: TIME,
createdAt: '2026-11-17T00:00:00Z',
updatedAt: '2026-11-17T00:00:00Z',
},
@@ -391,7 +410,7 @@ describe('useAIAssistantStore — message contexts', () => {
await useAIAssistantStore.getState().loadThread('thread-1');
expect(lastMessage('thread-1').contexts).toStrictEqual([pickedDashboard]);
expect(lastMessage('thread-1').context).toStrictEqual(context);
});
});
@@ -431,7 +450,7 @@ describe('useAIAssistantStore — unread replies', () => {
);
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore.getState().sendMessage('hi');
await useAIAssistantStore.getState().sendMessage('hi', { timeContext: TIME });
expect(useAIAssistantStore.getState().unreadReplyIds).toStrictEqual([
'thread-reply',

View File

@@ -6,7 +6,7 @@ import { immer } from 'zustand/middleware/immer';
import type {
MessageActionDTO,
MessageSummaryDTOBlocksAnyOfItem,
MessageSummaryV2DTOBlocksAnyOfItem,
} from '@signozhq/noz-client';
import { RetryActionDTO } from '@signozhq/noz-client';
@@ -17,7 +17,6 @@ import {
createThread,
getThreadDetail,
listThreads,
MessageContext,
MessageSummary,
regenerateMessage,
rejectExecution,
@@ -32,9 +31,9 @@ import {
ConversationStreamState,
FeedbackRating,
Message,
MessageAttachment,
MessageBlock,
MessageRole,
SendMessageOptions,
} from '../types';
import {
resolveAssistantError,
@@ -678,11 +677,7 @@ export interface AIAssistantStore {
restoreConversation: (id: string) => void;
renameConversation: (id: string, title: string) => Promise<void>;
markBlockAnswered: (messageId: string, answer: string) => void;
sendMessage: (
text: string,
attachments?: MessageAttachment[],
contexts?: MessageContext[],
) => Promise<void>;
sendMessage: (text: string, options: SendMessageOptions) => Promise<void>;
approveAction: (conversationId: string, approvalId: string) => Promise<void>;
rejectAction: (conversationId: string, approvalId: string) => Promise<void>;
submitClarification: (
@@ -714,7 +709,7 @@ export interface AIAssistantStore {
* the UI renders against.
*/
function toBlocks(
raw: MessageSummaryDTOBlocksAnyOfItem[] | null | undefined,
raw: MessageSummaryV2DTOBlocksAnyOfItem[] | null | undefined,
): MessageBlock[] | undefined {
if (!raw || raw.length === 0) {
return undefined;
@@ -780,7 +775,7 @@ function toMessage(m: MessageSummary): Message {
id: m.messageId,
role: m.role as MessageRole,
content,
contexts: m.contexts ?? undefined,
context: m.context ?? undefined,
blocks: toBlocks(m.blocks),
actions: m.actions ?? undefined,
feedbackRating: m.feedbackRating ?? undefined,
@@ -1225,8 +1220,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// eslint-disable-next-line sonarjs/cognitive-complexity
sendMessage: async (
text: string,
attachments?: MessageAttachment[],
contexts?: MessageContext[],
{ timeContext, attachments, context }: SendMessageOptions,
): Promise<void> => {
const convId = get().activeConversationId;
if (!convId || !get().conversations[convId]) {
@@ -1257,7 +1251,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
role: 'user',
content: text,
attachments,
contexts,
context,
createdAt: Date.now(),
};
@@ -1307,7 +1301,12 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
const tid = threadId;
await streamWithRetry(
targetConvId,
() => sendMessageToThread(tid, text, contexts),
() =>
sendMessageToThread(tid, {
content: text,
timeContext,
...(context ? { context } : {}),
}),
set,
);

View File

@@ -18,9 +18,10 @@ import type {
FeedbackRatingDTO,
MessageActionDTO,
MessageActionKindDTO,
MessageContextV2DTO,
MessageTimeContextDTO,
RetryActionDTO,
} from '@signozhq/noz-client';
import type { MessageContext } from 'api/ai-assistant/chat';
/** Client-only file attachment — no API equivalent (uploads happen via data URLs). */
export interface MessageAttachment {
@@ -30,7 +31,14 @@ export interface MessageAttachment {
dataUrl: string;
}
/** Narrowed from DTO `MessageSummaryDTO.role: string`. The UI only cares about user/assistant. */
export interface SendMessageOptions {
/** When the user pressed Send, in their SigNoz timezone; retries reuse it. */
timeContext: MessageTimeContextDTO;
attachments?: MessageAttachment[];
context?: MessageContextV2DTO;
}
/** Narrowed from DTO `MessageSummaryV2DTO.role: string`. The UI only cares about user/assistant. */
export type MessageRole = 'user' | 'assistant';
/** String-literal view of `MessageActionKindDTO` for ergonomic comparisons in switch statements. */
@@ -71,7 +79,7 @@ export interface ToolCallBlock {
export type MessageBlock = TextBlock | ThinkingBlock | ToolCallBlock;
/**
* UI shape for an assistant or user message. Differs from `MessageSummaryDTO`:
* UI shape for an assistant or user message. Differs from `MessageSummaryV2DTO`:
* • `id` instead of `messageId`
* • `createdAt` is a millisecond epoch instead of ISO string
* • `blocks` is the typed discriminated union above
@@ -83,7 +91,7 @@ export interface Message {
content: string;
attachments?: MessageAttachment[];
/** What a user message was sent with: its @-picked resources and the page it came from. */
contexts?: MessageContext[];
context?: MessageContextV2DTO;
/** Ordered content blocks for structured rendering of assistant replies. */
blocks?: MessageBlock[];
/** Suggested follow-up actions returned by the assistant (final message only). */
@@ -111,7 +119,7 @@ export interface Message {
}
/**
* UI shape for a conversation. Differs from `ThreadDetailResponseDTO`:
* UI shape for a conversation. Differs from `ThreadDetailResponseV2DTO`:
* • UI-minted `id` (assigned before the server returns a `threadId`)
* • `createdAt`/`updatedAt` are ms epochs
* • `messages` is the typed `Message[]` above

View File

@@ -23,6 +23,7 @@ import { useTimezone } from 'providers/Timezone';
import { AlertRuleTimelineTableResponse } from 'types/api/alerts/def';
import { DataSource } from 'types/common/queryBuilder';
import { useAlertHistoryAssistantContext } from './useAlertHistoryAssistantContext';
import { useAlertHistoryFilterSuggestions } from './useAlertHistoryFilterSuggestions';
import { timelineTableColumns } from './useTimelineTable';
@@ -32,6 +33,7 @@ export const ALERT_HISTORY_EXPRESSION_KEY = 'alertHistoryExpression';
function TimelineTableContent(): JSX.Element {
const expression = useExpression();
useAlertHistoryAssistantContext(expression);
const inputExpression = useInputExpression();
const querySearchOnChange = useQuerySearchOnChange();
const querySearchOnRun = useQuerySearchOnRun();

View File

@@ -0,0 +1,71 @@
import {
type DataViewDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import ROUTES from 'constants/routes';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { TimelineFilter } from 'container/AlertHistory/types';
import { render } from 'tests/test-utils';
import TimelineTable, { ALERT_HISTORY_EXPRESSION_KEY } from '../Table';
import { useAlertHistoryAssistantContext } from '../useAlertHistoryAssistantContext';
const CRITICAL = "severity = 'critical'";
function History({ filterExpression }: { filterExpression: string }): null {
useAlertHistoryAssistantContext(filterExpression);
return null;
}
function historyView(): DataViewDTO | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.alertruledetail,
activeViewPath: [],
})?.state?.dataViews?.[0];
}
function renderHistory(filterExpression: string, search: string): void {
render(<History filterExpression={filterExpression} />, undefined, {
initialRoute: `${ROUTES.ALERT_HISTORY}?ruleId=1${search}`,
});
}
describe('useAlertHistoryAssistantContext', () => {
it('sends the history table with the filter that ran, the Fired tab and the page', () => {
renderHistory(CRITICAL, `&page=3&timelineFilter=${TimelineFilter.FIRED}`);
expect(historyView()).toStrictEqual({
key: 'alert_history',
shape: 'table',
filter: { expression: CRITICAL },
pagination: { page: 3, pageSize: 20 },
settings: [{ name: 'state', value: 'firing' }],
});
});
it('sends the Resolved tab as inactive', () => {
renderHistory('', `&timelineFilter=${TimelineFilter.RESOLVED}`);
expect(historyView()?.settings).toStrictEqual([
{ name: 'state', value: 'inactive' },
]);
});
it('sends only the first page while no filter or tab narrows it', () => {
renderHistory('', `&timelineFilter=${TimelineFilter.ALL}`);
expect(historyView()).toStrictEqual({
key: 'alert_history',
shape: 'table',
pagination: { page: 1, pageSize: 20 },
});
});
it('is added by the timeline table with the filter it applied', () => {
render(<TimelineTable />, undefined, {
initialRoute: `${ROUTES.ALERT_HISTORY}?ruleId=1&${ALERT_HISTORY_EXPRESSION_KEY}=${encodeURIComponent(CRITICAL)}`,
});
expect(historyView()?.filter).toStrictEqual({ expression: CRITICAL });
});
});

View File

@@ -0,0 +1,38 @@
import { DataShapeDTO, KnownDataViewKeyDTO } from '@signozhq/noz-client';
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
import { TIMELINE_TABLE_PAGE_SIZE } from 'container/AlertHistory/constants';
import { TimelineFilter } from 'container/AlertHistory/types';
import useUrlQuery from 'hooks/useUrlQuery';
import { useTimelineTablePage } from './useTimelineTableCursor';
const STATE_FILTERS = new Map<string | null, RuletypesAlertStateDTO>([
[TimelineFilter.FIRED, RuletypesAlertStateDTO.firing],
[TimelineFilter.RESOLVED, RuletypesAlertStateDTO.inactive],
]);
/** Adds the history table: the filter that ran, the Fired or Resolved tab, and the page. */
export function useAlertHistoryAssistantContext(
filterExpression: string,
): void {
const [page] = useTimelineTablePage();
const timelineFilter = useUrlQuery().get('timelineFilter');
const stateFilter = STATE_FILTERS.get(timelineFilter);
useAssistantState(() => ({
state: {
dataViews: [
{
key: KnownDataViewKeyDTO.alert_history,
shape: DataShapeDTO.table,
filter: filterExpression ? { expression: filterExpression } : undefined,
pagination: { page, pageSize: TIMELINE_TABLE_PAGE_SIZE },
settings: stateFilter
? [{ name: 'state', value: stateFilter }]
: undefined,
},
],
},
}));
}

View File

@@ -0,0 +1,60 @@
import { EditorModeDTO } from '@signozhq/noz-client';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { isEqual } from 'lodash-es';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import {
hasAlertQueryChanged,
toAlertQueryView,
} from './alertAssistantContext';
import { useCreateAlertState } from './context';
import type { CreateAlertState } from './context/types';
interface AlertEditorAssistantContextProps {
/** The rule as saved; absent while creating one. */
saved?: { query: Query; state: CreateAlertState };
}
/** Adds the editor's mode and unsaved flag, and the query the preview ran once it differs from the saved rule. */
export function AlertEditorAssistantContext({
saved,
}: AlertEditorAssistantContextProps): null {
const { currentQuery, stagedQuery } = useQueryBuilder();
const {
alertState,
thresholdState,
evaluationWindow,
advancedOptions,
notificationSettings,
} = useCreateAlertState();
useAssistantState(() => {
const form: CreateAlertState = {
basic: alertState,
threshold: thresholdState,
evaluationWindow,
advancedOptions,
notificationSettings,
};
const dirty =
!saved ||
!isEqual(form, saved.state) ||
hasAlertQueryChanged(saved.query, currentQuery);
const showsQuery =
stagedQuery && (!saved || hasAlertQueryChanged(saved.query, stagedQuery));
return {
state: {
editor: {
mode: saved ? EditorModeDTO.edit : EditorModeDTO.create,
dirty,
},
dataViews: showsQuery
? [toAlertQueryView(stagedQuery, alertState.yAxisUnit)]
: undefined,
},
};
});
return null;
}

View File

@@ -3,6 +3,7 @@ import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
import AlertCondition from './AlertCondition';
import { AlertEditorAssistantContext } from './AlertEditorAssistantContext';
import { CreateAlertProvider } from './context';
import { buildInitialAlertDef } from './context/utils';
import CreateAlertHeader from './CreateAlertHeader';
@@ -24,6 +25,7 @@ function CreateAlert({ alertType }: CreateAlertProps): JSX.Element {
return (
<CreateAlertProvider initialAlertType={alertType}>
<AlertEditorAssistantContext />
<Spinner />
<div className="create-alert-v2-container">
<CreateAlertHeader />

View File

@@ -0,0 +1,122 @@
import {
type ContextStateDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import EditAlert from 'container/EditAlert/EditAlert';
import { getEditAlertQuery } from 'container/EditAlert/utils';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
import { render, waitFor } from 'tests/test-utils';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { defaultPostableAlertRuleV2 } from '../constants';
import { CreateAlertProvider } from '../context';
import { buildInitialAlertDef } from '../context/utils';
import CreateAlert from '../CreateAlert';
import { getCreateAlertLocalStateFromAlertDef } from '../utils';
jest.mock('container/CreateAlert/CreateAlertHeader', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/CreateAlert/QuerySection', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/CreateAlert/AlertCondition', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/CreateAlert/NotificationSettings', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/CreateAlert/Footer', () => ({
__esModule: true,
default: (): null => null,
}));
const savedState = getCreateAlertLocalStateFromAlertDef(
defaultPostableAlertRuleV2,
);
// The editor writes its query to the URL on mount; the test navigation never does, so start there.
function withQuery(path: string, query: Query): string {
return `${path}&compositeQuery=${encodeURIComponent(
encodeURIComponent(JSON.stringify(query)),
)}`;
}
function editorState(): ContextStateDTO | null | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.alertruledetail,
activeViewPath: [],
})?.state;
}
function renderEditor(formState = savedState): void {
render(
<CreateAlertProvider
ruleId="r-1"
isEditMode
initialAlertType={AlertTypes.METRICS_BASED_ALERT}
initialAlertState={formState}
>
<EditAlert initialAlert={defaultPostableAlertRuleV2} />
</CreateAlertProvider>,
undefined,
{
initialRoute: withQuery(
'/alerts/overview?ruleId=r-1',
getEditAlertQuery(
defaultPostableAlertRuleV2.condition.compositeQuery,
AlertTypes.METRICS_BASED_ALERT,
),
),
},
);
}
describe('AlertEditorAssistantContext', () => {
it('sends a saved rule as clean, with no query, once it loads', async () => {
renderEditor();
await waitFor(() =>
expect(editorState()).toStrictEqual({
editor: { mode: 'edit', dirty: false },
}),
);
});
it('marks the rule dirty once the form differs from the saved one', async () => {
renderEditor({
...savedState,
basic: { ...savedState.basic, name: 'Renamed, not saved' },
});
await waitFor(() =>
expect(editorState()?.editor).toStrictEqual({ mode: 'edit', dirty: true }),
);
expect(editorState()?.dataViews).toBeUndefined();
});
it('sends a new rule as unsaved, with the query the preview ran', async () => {
const alertType = AlertTypes.METRICS_BASED_ALERT;
render(<CreateAlert alertType={alertType} />, undefined, {
initialRoute: withQuery(
`/alerts/new?alertType=${alertType}`,
mapQueryDataFromApi(
buildInitialAlertDef(alertType).condition.compositeQuery,
),
),
});
await waitFor(() =>
expect(editorState()).toMatchObject({
editor: { mode: 'create', dirty: true },
dataViews: [{ key: 'alert_query', signal: 'metrics' }],
}),
);
});
});

View File

@@ -0,0 +1,66 @@
import { initialQueriesMap } from 'constants/queryBuilder';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
import {
hasAlertQueryChanged,
toAlertQueryView,
} from '../alertAssistantContext';
const metricsQuery = initialQueriesMap.metrics;
const [metricsQueryData] = metricsQuery.builder.queryData;
const [logsQueryData] = initialQueriesMap.logs.builder.queryData;
function withFilter(expression: string): Query {
return {
...metricsQuery,
builder: {
...metricsQuery.builder,
queryData: [{ ...metricsQueryData, filter: { expression } }],
},
};
}
describe('alertAssistantContext', () => {
it('sends the query the preview ran, with its signal and unit', () => {
const view = toAlertQueryView(metricsQuery, 'ms');
expect(view).toMatchObject({
key: 'alert_query',
shape: 'timeseries',
signal: 'metrics',
unit: 'ms',
focused: true,
query: { requestType: 'time_series' },
});
expect(view.query?.compositeQuery).toStrictEqual({
queries: [expect.objectContaining({ type: 'builder_query' })],
});
});
it('leaves out the signal when the queries mix signals or are not builder queries, and an empty unit', () => {
const mixed: Query = {
...metricsQuery,
builder: {
...metricsQuery.builder,
queryData: [metricsQueryData, { ...logsQueryData, queryName: 'B' }],
},
};
const promql: Query = { ...metricsQuery, queryType: EQueryType.PROM };
expect(toAlertQueryView(mixed, '').signal).toBeUndefined();
expect(toAlertQueryView(mixed, '').unit).toBeUndefined();
expect(toAlertQueryView(promql).signal).toBeUndefined();
});
it('counts a changed filter as an edit, and a copy of the same query as none', () => {
const saved = withFilter("service.name = 'checkout'");
expect(
hasAlertQueryChanged(saved, withFilter("service.name = 'checkout'")),
).toBe(false);
expect(hasAlertQueryChanged(saved, withFilter("service.name = 'cart'"))).toBe(
true,
);
});
});

View File

@@ -0,0 +1,47 @@
import {
DataShapeDTO,
type DataViewDTO,
KnownDataViewKeyDTO,
} from '@signozhq/noz-client';
import { mapPanelTypeToRequestType } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { mapCompositeQueryFromQuery } from 'lib/newQueryBuilder/queryBuilderMappers/mapCompositeQueryFromQuery';
import { isEqual } from 'lodash-es';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { EQueryType } from 'types/common/dashboard';
type QueryEnvelopes = ReturnType<typeof mapCompositeQueryFromQuery>['queries'];
function toQueryEnvelopes(query: Query): QueryEnvelopes {
return mapCompositeQueryFromQuery(query, PANEL_TYPES.TIME_SERIES).queries;
}
/** Compares the queries as the backend receives them. */
export function hasAlertQueryChanged(saved: Query, shown: Query): boolean {
return !isEqual(toQueryEnvelopes(saved), toQueryEnvelopes(shown));
}
function toSignal(query: Query): string | undefined {
if (query.queryType !== EQueryType.QUERY_BUILDER) {
return undefined;
}
const signals = new Set(
query.builder.queryData.map(({ dataSource }) => dataSource),
);
return signals.size === 1 ? [...signals][0] : undefined;
}
/** The alert's chart as the preview ran it. */
export function toAlertQueryView(query: Query, unit?: string): DataViewDTO {
return {
key: KnownDataViewKeyDTO.alert_query,
shape: DataShapeDTO.timeseries,
signal: toSignal(query),
unit: unit || undefined,
focused: true,
query: {
compositeQuery: { queries: toQueryEnvelopes(query) },
requestType: mapPanelTypeToRequestType(PANEL_TYPES.TIME_SERIES),
},
};
}

View File

@@ -3,11 +3,15 @@ import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
import { AlertTypes, PostableAlertRuleV2 } from 'types/api/alerts/alertTypes';
import AlertCondition from '../CreateAlert/AlertCondition';
import { AlertEditorAssistantContext } from '../CreateAlert/AlertEditorAssistantContext';
import { buildInitialAlertDef } from '../CreateAlert/context/utils';
import Footer from '../CreateAlert/Footer';
import NotificationSettings from '../CreateAlert/NotificationSettings';
import QuerySection from '../CreateAlert/QuerySection';
import { Spinner } from '../CreateAlert/utils';
import {
getCreateAlertLocalStateFromAlertDef,
Spinner,
} from '../CreateAlert/utils';
import { getEditAlertQuery } from './utils';
import '../CreateAlert/CreateAlert.styles.scss';
@@ -32,8 +36,17 @@ function EditAlert({
useShareBuilderUrl({ defaultValue: currentQueryToRedirect });
const savedAlert = useMemo(
() => ({
query: currentQueryToRedirect,
state: getCreateAlertLocalStateFromAlertDef(initialAlert),
}),
[currentQueryToRedirect, initialAlert],
);
return (
<>
<AlertEditorAssistantContext saved={savedAlert} />
<Spinner />
<div className="create-alert-v2-container">
<QuerySection />

View File

@@ -6,6 +6,7 @@ import logEvent from 'api/common/logEvent';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import QueryCancelledPlaceholder from 'components/QueryCancelledPlaceholder';
import QuickFiltersLayout from 'components/QuickFilters/QuickFiltersLayout/QuickFiltersLayout';
import { useExplorerAssistantContext } from 'container/AIAssistant/pageContext/hooks/useExplorerAssistantContext';
import { useSignalFieldApis } from 'components/QuickFilters/hooks/useSignalFieldApis';
import { QuickFiltersSource } from 'components/QuickFilters/types';
import WarningPopover from 'components/WarningPopover/WarningPopover';
@@ -63,6 +64,7 @@ function Explorer(): JSX.Element {
handleSetQueryData,
redirectWithQueryBuilderData,
} = useQueryBuilder();
useExplorerAssistantContext(SavedviewtypesSourceDTO.ai_observability);
const isAIAssistantEnabled = useIsAIAssistantEnabled();

View File

@@ -2,9 +2,13 @@ import { useEffect } from 'react';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import Spinner from 'components/Spinner';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
import DashboardContainer from 'pages/DashboardPage/DashboardContainer';
import { useSystemDashboard } from './hooks/useSystemDashboard';
import {
SYSTEM_DASHBOARD_NAME,
useSystemDashboard,
} from './hooks/useSystemDashboard';
import styles from './Overview.module.scss';
function Overview(): JSX.Element {
@@ -14,6 +18,15 @@ function Overview(): JSX.Element {
void logEvent('AI Observability Overview: Page visited', {});
}, []);
// The container's id is made up; this kind gets no fetch hint, so the assistant won't try it.
useAssistantState(() => ({
root: {
kind: 'system_dashboard',
resourceId: SYSTEM_DASHBOARD_NAME,
resourceName: dashboard?.spec.display.name,
},
}));
const renderContent = (): JSX.Element => {
if (isLoading) {
return <Spinner tip="Loading dashboard..." />;

View File

@@ -11,7 +11,7 @@ import type {
GetDashboardV2200,
} from 'api/generated/services/sigNoz.schemas';
const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
export const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
const DASHBOARD_ID = 'llm-observability-overview';

View File

@@ -0,0 +1,44 @@
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import {
alertRulesFixture,
listRulesV3Response,
} from 'mocks-server/__mockdata__/alert_rules';
import { server } from 'mocks-server/server';
import { rest } from 'msw';
import { screen } from 'tests/test-utils';
import { renderListAlertRules } from './_helpers';
const CPU = "name CONTAINS 'CPU'";
describe('ListAlertRules — assistant context', () => {
beforeEach(() => {
server.use(
rest.get('http://localhost/api/v3/rules', (req, res, ctx) =>
res(
ctx.status(200),
ctx.json(listRulesV3Response(alertRulesFixture, req.url.searchParams)),
),
),
);
});
it('adds the rule table with the applied filter and page', async () => {
renderListAlertRules({
initialRoute: `/alerts?query=${encodeURIComponent(CPU)}&page=2`,
});
await screen.findByTestId('alert-rules-list-search');
expect(
snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.alertrulelist,
activeViewPath: [],
})?.state?.dataViews?.[0],
).toMatchObject({
key: 'alert_rule_list',
filter: { expression: CPU },
pagination: { page: 2 },
});
});
});

View File

@@ -0,0 +1,83 @@
import {
type DataViewDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import {
RuletypesListOrderDTO,
RuletypesListSortDTO,
} from 'api/generated/services/sigNoz.schemas';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { renderHook } from 'tests/test-utils';
import type { RuleListFilter } from '../types';
import { useAlertRulesListAssistantContext } from '../useAlertRulesListAssistantContext';
const CPU = "name CONTAINS 'cpu'";
function ruleListView(): DataViewDTO | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.alertrulelist,
activeViewPath: [],
})?.state?.dataViews?.[0];
}
describe('useAlertRulesListAssistantContext', () => {
it('sends the applied filter, status chips, sort, page and the saved view', () => {
const filter: RuleListFilter = {
query: CPU,
states: ['firing'],
sort: RuletypesListSortDTO.name,
order: RuletypesListOrderDTO.asc,
};
renderHook(() =>
useAlertRulesListAssistantContext({
filter,
page: 2,
limit: 25,
views: {
activeView: { id: 'v1', name: 'Infra rules', filter },
isCustomActive: true,
isModified: true,
},
}),
);
expect(ruleListView()).toStrictEqual({
key: 'alert_rule_list',
shape: 'table',
filter: { expression: CPU },
sort: [{ field: { name: 'name' }, direction: 'asc' }],
pagination: { page: 2, pageSize: 25 },
settings: [{ name: 'states', value: ['firing'] }],
savedView: { id: 'v1', name: 'Infra rules', dirty: true },
});
});
it('sends no filter, chips or saved view on a built-in view', () => {
const filter: RuleListFilter = {
query: '',
states: [],
sort: RuletypesListSortDTO.state,
order: RuletypesListOrderDTO.desc,
};
renderHook(() =>
useAlertRulesListAssistantContext({
filter,
page: 1,
limit: 10,
views: {
activeView: { id: 'all', name: 'All rules', filter },
isCustomActive: false,
isModified: false,
},
}),
);
expect(ruleListView()).toStrictEqual({
key: 'alert_rule_list',
shape: 'table',
sort: [{ field: { name: 'state' }, direction: 'desc' }],
pagination: { page: 1, pageSize: 10 },
});
});
});

View File

@@ -29,6 +29,7 @@ import { useAlertRulesStripInfo } from './useAlertRulesStripInfo';
import { useAlertRulesData } from './useAlertRulesData';
import { useAlertRulesFilterSource } from './useAlertRulesFilterSource';
import { useAlertRulesHandlers } from './useAlertRulesHandlers';
import { useAlertRulesListAssistantContext } from './useAlertRulesListAssistantContext';
import { useAlertRulesListFilter } from './useAlertRulesListFilter';
import { useAlertRuleViews } from './useAlertRuleViews';
import { useAlertRuleViewsStore } from './useAlertRuleViewsStore';
@@ -162,6 +163,7 @@ function ListAlertRules(): JSX.Element {
shownCount: rules.length,
totalCount: total,
});
useAlertRulesListAssistantContext({ filter, page, limit, views: ruleViews });
const columnsWithActions = useMemo(() => {
return [
@@ -169,7 +171,7 @@ function ListAlertRules(): JSX.Element {
{
id: 'actions',
header: (): JSX.Element => (
<span style={{ textAlign: 'right', display: 'block' }}>Actions</span>
<span className={styles.actionsColumn}>Actions</span>
),
accessorKey: 'id',
width: { fixed: '80px', ignoreLastColumnFill: true },

View File

@@ -0,0 +1,51 @@
import { DataShapeDTO, KnownDataViewKeyDTO } from '@signozhq/noz-client';
import {
toListSavedView,
toSortDirection,
} from 'container/AIAssistant/pageContext/utils/listViews';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
import type { UseListViewsResult } from 'hooks/listViews/types';
import type { RuleListFilter } from './types';
interface AlertRulesListAssistantContext {
/** The applied filter, not the draft in the search box. */
filter: RuleListFilter;
page: number;
limit: number;
views: Pick<
UseListViewsResult<RuleListFilter>,
'activeView' | 'isCustomActive' | 'isModified'
>;
}
/** Adds the rule table: its filter, status chips, sort, page and saved view; no rows. */
export function useAlertRulesListAssistantContext({
filter,
page,
limit,
views,
}: AlertRulesListAssistantContext): void {
useAssistantState(() => ({
state: {
dataViews: [
{
key: KnownDataViewKeyDTO.alert_rule_list,
shape: DataShapeDTO.table,
filter: filter.query ? { expression: filter.query } : undefined,
sort: [
{
field: { name: filter.sort },
direction: toSortDirection(filter.order),
},
],
pagination: { page, pageSize: limit },
settings: filter.states.length
? [{ name: 'states', value: filter.states }]
: undefined,
savedView: toListSavedView(views),
},
],
},
}));
}

View File

@@ -0,0 +1,65 @@
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { initialQueriesMap } from 'constants/queryBuilder';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { useEventSource } from 'providers/EventSource';
import { render } from 'tests/test-utils';
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import LiveLogsContainer from '..';
jest.mock('providers/EventSource', () => ({
useEventSource: jest.fn(),
}));
jest.mock('container/LiveLogs/LiveLogsList', () => ({
__esModule: true,
default: (): JSX.Element => <div>Live logs</div>,
}));
jest.mock('container/LiveLogs/LiveLogsListChart', () => ({
__esModule: true,
default: (): JSX.Element => <div>Frequency chart</div>,
}));
const CHECKOUT = "service.name = 'checkout'";
const [logsQueryData] = initialQueriesMap.logs.builder.queryData;
const checkoutQuery: Query = {
...initialQueriesMap.logs,
builder: {
...initialQueriesMap.logs.builder,
queryData: [{ ...logsQueryData, filter: { expression: CHECKOUT } }],
},
};
describe('LiveLogsContainer', () => {
it('adds the live list to the assistant page with the builder filter and the paused stream', () => {
jest.mocked(useEventSource).mockReturnValue({
eventSourceInstance: null,
isConnectionOpen: false,
isConnectionLoading: false,
isConnectionError: false,
initialLoading: false,
reconnectDueToError: false,
handleStartOpenConnection: jest.fn(),
handleCloseConnection: jest.fn(),
handleSetInitialLoading: jest.fn(),
});
render(<LiveLogsContainer />, undefined, {
queryBuilderOverrides: {
currentQuery: checkoutQuery,
stagedQuery: checkoutQuery,
},
});
expect(
snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.loglive,
activeViewPath: [],
})?.state,
).toMatchObject({
stream: 'paused',
dataViews: [{ key: 'live_log_list', filter: { expression: CHECKOUT } }],
});
});
});

View File

@@ -0,0 +1,86 @@
import {
type ContextStateDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import type { TelemetryFieldKey } from 'api/v5/v5';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { renderHook } from 'tests/test-utils';
import { useLiveLogsAssistantContext } from '../useLiveLogsAssistantContext';
const CHECKOUT = "service.name = 'checkout'";
const COLUMNS: TelemetryFieldKey[] = [
{ name: 'body', fieldContext: 'log' },
{ name: 'service.name', fieldContext: 'resource' },
];
function liveState(): ContextStateDTO | null | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.loglive,
activeViewPath: [],
})?.state;
}
describe('useLiveLogsAssistantContext', () => {
it('sends the playing stream with its filter, columns and format', () => {
renderHook(() =>
useLiveLogsAssistantContext({
filterExpression: CHECKOUT,
isPlaying: true,
options: { format: 'raw', selectColumns: COLUMNS },
}),
);
expect(liveState()?.stream).toBe('active');
expect(liveState()?.dataViews).toStrictEqual([
{
key: 'live_log_list',
shape: 'list',
signal: 'logs',
filter: { expression: CHECKOUT },
visibleFields: [
{ name: 'body', fieldContext: 'log' },
{ name: 'service.name', fieldContext: 'resource' },
],
settings: [{ name: 'format', value: 'raw' }],
},
]);
});
it('keeps the filter the stream runs while the builder holds one that does not validate', () => {
const { rerender } = renderHook(
({ filterExpression }: { filterExpression: string }) =>
useLiveLogsAssistantContext({
filterExpression,
isPlaying: true,
options: { format: 'list', selectColumns: COLUMNS },
}),
{ initialProps: { filterExpression: CHECKOUT } },
);
rerender({ filterExpression: "service.name = 'checkout' AND" });
expect(liveState()?.dataViews?.[0].filter).toStrictEqual({
expression: CHECKOUT,
});
});
it('marks a paused stream, and sends no filter or columns when there are none', () => {
renderHook(() =>
useLiveLogsAssistantContext({
isPlaying: false,
options: { format: 'list', selectColumns: [] },
}),
);
expect(liveState()?.stream).toBe('paused');
expect(liveState()?.dataViews).toStrictEqual([
{
key: 'live_log_list',
shape: 'list',
signal: 'logs',
settings: [{ name: 'format', value: 'list' }],
},
]);
});
});

View File

@@ -19,11 +19,14 @@ import { useEventSource } from 'providers/EventSource';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import { validateQuery } from 'utils/queryValidationUtils';
import { LIVE_LOGS_FORMAT_ITEMS } from '../constants';
import LiveLogsList from '../LiveLogsList';
import { ILiveLogsLog } from '../LiveLogsList/types';
import LiveLogsListChart from '../LiveLogsListChart';
import { QueryHistoryState } from '../types';
import { useLiveLogsAssistantContext } from './useLiveLogsAssistantContext';
import './LiveLogsContainer.styles.scss';
interface LiveLogsContainerProps {
@@ -61,36 +64,22 @@ function LiveLogsContainer({
const [isFieldsSelectorOpen, setIsFieldsSelectorOpen] = useState(false);
const formatItems = [
{
key: 'raw',
label: 'Raw',
data: {
title: 'max lines per row',
},
},
{
key: 'list',
label: 'Default',
},
{
key: 'table',
label: 'Column',
data: {
title: 'columns',
},
},
];
const {
handleStartOpenConnection,
handleCloseConnection,
initialLoading,
isConnectionOpen,
isConnectionLoading,
isConnectionError,
reconnectDueToError,
} = useEventSource();
useLiveLogsAssistantContext({
filterExpression: currentQuery?.builder.queryData[0]?.filter?.expression,
isPlaying: isConnectionOpen || isConnectionLoading || initialLoading,
options,
});
const compositeQuery = useGetCompositeQueryParam();
const updateLogs = useCallback((newLogs: ILiveLogsLog[]) => {
@@ -250,7 +239,7 @@ function LiveLogsContainer({
</div>
<LogsFormatOptionsMenu
items={formatItems}
items={LIVE_LOGS_FORMAT_ITEMS}
selectedOptionFormat={options.format}
config={config}
onOpenColumns={(): void => setIsFieldsSelectorOpen(true)}

View File

@@ -0,0 +1,55 @@
import { useEffect, useRef } from 'react';
import {
DataShapeDTO,
StreamStateDTO,
KnownDataSignalDTO,
KnownDataViewKeyDTO,
} from '@signozhq/noz-client';
import { toVisibleFields } from 'container/AIAssistant/pageContext/utils/explorerViews';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
import type { OptionsQuery } from 'container/OptionsMenu/types';
import { validateQuery } from 'utils/queryValidationUtils';
interface LiveLogsAssistantContext {
/** The builder's filter; the stream switches only to one that validates. */
filterExpression?: string;
isPlaying: boolean;
options: Pick<OptionsQuery, 'format' | 'selectColumns'>;
}
/** Adds the live log list: the filter the stream runs, its columns and format, and whether it is paused. */
export function useLiveLogsAssistantContext({
filterExpression,
isPlaying,
options,
}: LiveLogsAssistantContext): void {
const expression = filterExpression?.trim() || '';
const streamFilterRef = useRef('');
useEffect(() => {
if (validateQuery(expression).isValid) {
streamFilterRef.current = expression;
}
}, [expression]);
useAssistantState(() => {
const streamFilter = streamFilterRef.current;
return {
state: {
stream: isPlaying ? StreamStateDTO.active : StreamStateDTO.paused,
dataViews: [
{
key: KnownDataViewKeyDTO.live_log_list,
shape: DataShapeDTO.list,
signal: KnownDataSignalDTO.logs,
filter: streamFilter ? { expression: streamFilter } : undefined,
visibleFields: options.selectColumns.length
? toVisibleFields(options.selectColumns)
: undefined,
settings: [{ name: 'format', value: options.format }],
},
],
},
};
});
}

View File

@@ -50,3 +50,24 @@ export const idObject: BaseAutocompleteData = {
type: '',
dataType: DataTypes.String,
};
export const LIVE_LOGS_FORMAT_ITEMS = [
{
key: 'raw',
label: 'Raw',
data: {
title: 'max lines per row',
},
},
{
key: 'list',
label: 'Default',
},
{
key: 'table',
label: 'Column',
data: {
title: 'columns',
},
},
];

View File

@@ -6,6 +6,7 @@ import logEvent from 'api/common/logEvent';
import { QueryBuilderV2 } from 'components/QueryBuilderV2/QueryBuilderV2';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import QuickFiltersLayout from 'components/QuickFilters/QuickFiltersLayout/QuickFiltersLayout';
import { useExplorerAssistantContext } from 'container/AIAssistant/pageContext/hooks/useExplorerAssistantContext';
import { useSignalFieldApis } from 'components/QuickFilters/hooks/useSignalFieldApis';
import { QuickFiltersSource } from 'components/QuickFilters/types';
import { initialQueryMeterWithType, PANEL_TYPES } from 'constants/queryBuilder';
@@ -26,6 +27,7 @@ import './Explorer.styles.scss';
function Explorer(): JSX.Element {
const quickFilterFieldApis = useSignalFieldApis();
const { handleRunQuery, updateAllQueriesOperators } = useQueryBuilder();
useExplorerAssistantContext(SavedviewtypesSourceDTO.meter);
const queryClient = useQueryClient();
const [isLoadingQueries, setIsLoadingQueries] = useState(false);
const [isCancelled, setIsCancelled] = useState(false);

View File

@@ -14,6 +14,7 @@ import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { usePageActions } from 'container/AIAssistant/pageActions/usePageActions';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import QuickFiltersLayout from 'components/QuickFilters/QuickFiltersLayout/QuickFiltersLayout';
import { useExplorerAssistantContext } from 'container/AIAssistant/pageContext/hooks/useExplorerAssistantContext';
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
import DateTimeSelector from 'container/TopNav/DateTimeSelectionV2';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
@@ -52,6 +53,7 @@ function Explorer(): JSX.Element {
handleSetQueryData,
redirectWithQueryBuilderData,
} = useQueryBuilder();
useExplorerAssistantContext(SavedviewtypesSourceDTO.metrics);
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const [isMetricDetailsOpen, setIsMetricDetailsOpen] = useState(false);
const [showSidebar, setShowSidebar] = useState(true);

View File

@@ -28,6 +28,7 @@ import {
MetricInspectionAction,
} from './types';
import { useInspectMetrics } from './useInspectMetrics';
import { useMetricAssistantPath } from '../useMetricAssistantPath';
import './Inspect.styles.scss';
@@ -105,7 +106,12 @@ function Inspect({
aggregatedTimeSeries,
timeAggregatedSeriesMap,
reset,
timeWindow,
} = useInspectMetrics(appliedMetricName);
useMetricAssistantPath(appliedMetricName, {
options: metricInspectionOptions.appliedOptions,
time: { mode: 'range', ...timeWindow },
});
const [isCancelled, setIsCancelled] = useState(false);

View File

@@ -2,8 +2,10 @@ import { QueryClient, QueryClientProvider } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { Provider } from 'react-redux';
import { render, screen } from '@testing-library/react';
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import * as metricsGeneratedAPI from 'api/generated/services/metrics';
import { MetrictypesTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import * as appContextHooks from 'providers/App/App';
import store from 'store';
@@ -89,6 +91,7 @@ const baseHookReturn: UseInspectMetricsReturnData = {
aggregatedTimeSeries: [],
timeAggregatedSeriesMap: new Map(),
reset: jest.fn(),
timeWindow: { startMs: 1795948200000, endMs: 1795950000000 },
};
describe('Inspect', () => {
@@ -122,6 +125,51 @@ describe('Inspect', () => {
expect(screen.getByText('Query Builder')).toBeInTheDocument();
});
it('adds the inspected metric and its chart window to the assistant page', () => {
jest
.spyOn(useInspectMetricsModule, 'useInspectMetrics')
.mockReturnValue(baseHookReturn);
render(
<QueryClientProvider client={queryClient}>
<Provider store={store}>
<Inspect {...defaultProps} />
</Provider>
</QueryClientProvider>,
);
expect(
snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.metricsummary,
activeViewPath: [],
})?.activePaths,
).toStrictEqual([
{
focused: true,
nodes: [
{
target: { kind: 'metric', resourceId: 'test_metric' },
state: {
dataViews: [
{
key: 'metric_inspect',
shape: 'timeseries',
signal: 'metrics',
focused: true,
time: {
mode: 'range',
startMs: 1795948200000,
endMs: 1795950000000,
},
},
],
},
},
],
},
]);
});
it('renders loading state', () => {
jest.spyOn(useInspectMetricsModule, 'useInspectMetrics').mockReturnValue({
...baseHookReturn,

View File

@@ -34,6 +34,8 @@ export interface UseInspectMetricsReturnData {
aggregatedTimeSeries: InspectMetricsSeries[];
timeAggregatedSeriesMap: Map<number, GraphPopoverData[]>;
reset: () => void;
/** What Inspect charts: the 30 minutes before it opened, in epoch ms. */
timeWindow: { startMs: number; endMs: number };
}
export interface GraphViewProps {

View File

@@ -283,6 +283,11 @@ export function useInspectMetrics(
setAggregatedTimeSeries(inspectMetricsTimeSeries);
}, [dispatchMetricInspectionOptions, inspectMetricsTimeSeries]);
const timeWindow = useMemo(
() => ({ startMs: start, endMs: end }),
[start, end],
);
return {
inspectMetricsTimeSeries,
isInspectMetricsLoading,
@@ -297,5 +302,6 @@ export function useInspectMetrics(
aggregatedTimeSeries,
timeAggregatedSeriesMap,
reset,
timeWindow,
};
}

View File

@@ -24,6 +24,7 @@ import Metadata from './Metadata';
import VolumeControlSection from '../VolumeControl/components/VolumeControlSection/VolumeControlSection';
import { MetricDetailsProps } from './types';
import { getMetricDetailsQuery } from './utils';
import { useMetricAssistantPath } from '../useMetricAssistantPath';
import './MetricDetails.styles.scss';
import '../Summary/Summary.styles.scss';
@@ -36,6 +37,7 @@ function MetricDetails({
}: MetricDetailsProps): JSX.Element {
const isDarkMode = useIsDarkMode();
const { handleExplorerTabChange } = useHandleExplorerTabChange();
useMetricAssistantPath(isOpen ? metricName : null);
const { maxTime, minTime } = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);

View File

@@ -1,5 +1,7 @@
import { render, screen } from '@testing-library/react';
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import * as metricsExplorerHooks from 'api/generated/services/metrics';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import * as useHandleExplorerTabChange from 'hooks/useHandleExplorerTabChange';
import { userEvent } from 'tests/test-utils';
@@ -128,4 +130,40 @@ describe('MetricDetails', () => {
await userEvent.click(screen.getByTestId('inspect-metric-button'));
expect(mockOpenInspectModal).toHaveBeenCalled();
});
it('adds the metric to the assistant page while open, and drops it once closed', () => {
const activePaths = (): unknown =>
snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.metricsummary,
activeViewPath: [],
})?.activePaths;
const { rerender } = render(
<MetricDetails
onClose={mockOnClose}
isOpen
metricName={mockMetricName}
isModalTimeSelection
openInspectModal={mockOpenInspectModal}
/>,
);
expect(activePaths()).toStrictEqual([
{
focused: true,
nodes: [{ target: { kind: 'metric', resourceId: mockMetricName } }],
},
]);
rerender(
<MetricDetails
onClose={mockOnClose}
isOpen={false}
metricName={mockMetricName}
isModalTimeSelection
openInspectModal={mockOpenInspectModal}
/>,
);
expect(activePaths()).toBeUndefined();
});
});

View File

@@ -22,6 +22,7 @@ import eyesEmojiUrl from 'assets/Images/eyesEmoji.svg';
import { convertExpressionToFilters } from 'components/QueryBuilderV2/utils';
import { initialQueriesMap } from 'constants/queryBuilder';
import { usePageSize } from './usePageSize';
import { useMetricsSummaryAssistantContext } from './useMetricsSummaryAssistantContext';
import NoLogs from 'container/NoLogs/NoLogs';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useShareBuilderUrl } from 'hooks/queryBuilder/useShareBuilderUrl';
@@ -109,6 +110,14 @@ function Summary(): JSX.Element {
[appliedFilterExpression],
);
useMetricsSummaryAssistantContext({
filterExpression: appliedFilterExpression,
orderBy,
page: currentPage,
pageSize,
treemapMode: heatmapView,
});
useEffect(() => {
logEvent(MetricsExplorerEvents.TabChanged, {
[MetricsExplorerEventKeys.Tab]: 'summary',

View File

@@ -1,6 +1,8 @@
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import * as metricsHooks from 'api/generated/services/metrics';
import { initialQueriesMap } from 'constants/queryBuilder';
import ROUTES from 'constants/routes';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import * as useQueryBuilderHooks from 'hooks/queryBuilder/useQueryBuilder';
import { render, screen, waitFor } from 'tests/test-utils';
import { DataSource, QueryBuilderContextType } from 'types/common/queryBuilder';
@@ -149,6 +151,33 @@ describe('Summary', () => {
});
});
it('adds the metric table and treemap to the assistant page as the screen shows them', () => {
render(<Summary />, undefined, {
initialRoute: ROUTES.METRICS_EXPLORER_BASE,
});
expect(
snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.metricsummary,
activeViewPath: [],
})?.state?.dataViews,
).toStrictEqual([
{
key: 'metric_list',
shape: 'table',
signal: 'metrics',
sort: [{ field: { name: 'samples' }, direction: 'desc' }],
pagination: { page: 1, pageSize: 10 },
},
{
key: 'metric_proportion',
shape: 'treemap',
signal: 'metrics',
settings: [{ name: 'size_by', value: 'samples' }],
},
]);
});
it('persists inspect modal open state across page refresh', () => {
render(<Summary />, undefined, {
initialRoute: `${ROUTES.METRICS_EXPLORER_BASE}?isInspectModalOpen=true&selectedMetricName=test-metric`,

View File

@@ -0,0 +1,74 @@
import {
KnownAssistantSurfaceDTO,
type DataViewDTO,
} from '@signozhq/noz-client';
import {
MetricsexplorertypesTreemapModeDTO,
Querybuildertypesv5OrderDirectionDTO,
} from 'api/generated/services/sigNoz.schemas';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { renderHook } from 'tests/test-utils';
import { useMetricsSummaryAssistantContext } from '../useMetricsSummaryAssistantContext';
function summaryViews(): DataViewDTO[] | null | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.metricsummary,
activeViewPath: [],
})?.state?.dataViews;
}
describe('useMetricsSummaryAssistantContext', () => {
it('sends the table with its filter, sort and page, and the treemap with what sizes it', () => {
renderHook(() =>
useMetricsSummaryAssistantContext({
filterExpression: "service.name = 'checkout'",
orderBy: {
key: { name: 'timeseries' },
direction: Querybuildertypesv5OrderDirectionDTO.asc,
},
page: 2,
pageSize: 25,
treemapMode: MetricsexplorertypesTreemapModeDTO.timeseries,
}),
);
const filter = { expression: "service.name = 'checkout'" };
expect(summaryViews()).toStrictEqual([
{
key: 'metric_list',
shape: 'table',
signal: 'metrics',
filter,
sort: [{ field: { name: 'timeseries' }, direction: 'asc' }],
pagination: { page: 2, pageSize: 25 },
},
{
key: 'metric_proportion',
shape: 'treemap',
signal: 'metrics',
filter,
settings: [{ name: 'size_by', value: 'timeseries' }],
},
]);
});
it('leaves out a filter and a sort that are not set', () => {
renderHook(() =>
useMetricsSummaryAssistantContext({
filterExpression: '',
orderBy: {},
page: 1,
pageSize: 10,
treemapMode: MetricsexplorertypesTreemapModeDTO.samples,
}),
);
expect(summaryViews()?.[0]).toStrictEqual({
key: 'metric_list',
shape: 'table',
signal: 'metrics',
pagination: { page: 1, pageSize: 10 },
});
});
});

View File

@@ -0,0 +1,68 @@
import {
DataShapeDTO,
SortDirectionDTO,
KnownDataSignalDTO,
KnownDataViewKeyDTO,
} from '@signozhq/noz-client';
import {
type MetricsexplorertypesTreemapModeDTO,
type Querybuildertypesv5OrderByDTO,
Querybuildertypesv5OrderDirectionDTO,
} from 'api/generated/services/sigNoz.schemas';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
interface MetricsSummaryAssistantContext {
/** The filter that ran, not the text still being typed. */
filterExpression: string;
orderBy: Querybuildertypesv5OrderByDTO;
page: number;
pageSize: number;
treemapMode: MetricsexplorertypesTreemapModeDTO;
}
/** Adds the metric table and treemap; the model lists metrics itself, so no query. */
export function useMetricsSummaryAssistantContext({
filterExpression,
orderBy,
page,
pageSize,
treemapMode,
}: MetricsSummaryAssistantContext): void {
useAssistantState(() => {
const filter = filterExpression
? { expression: filterExpression }
: undefined;
const sortField = orderBy.key?.name;
return {
state: {
dataViews: [
{
key: KnownDataViewKeyDTO.metric_list,
shape: DataShapeDTO.table,
signal: KnownDataSignalDTO.metrics,
filter,
sort: sortField
? [
{
field: { name: sortField },
direction:
orderBy.direction === Querybuildertypesv5OrderDirectionDTO.asc
? SortDirectionDTO.asc
: SortDirectionDTO.desc,
},
]
: undefined,
pagination: { page, pageSize },
},
{
key: KnownDataViewKeyDTO.metric_proportion,
shape: DataShapeDTO.treemap,
signal: KnownDataSignalDTO.metrics,
filter,
settings: [{ name: 'size_by', value: treemapMode }],
},
],
},
};
});
}

View File

@@ -0,0 +1,95 @@
import {
type ActivePathDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { renderHook } from 'tests/test-utils';
import { INITIAL_INSPECT_METRICS_OPTIONS } from '../Inspect/constants';
import {
SpaceAggregationOptions,
TimeAggregationOptions,
} from '../Inspect/types';
import { useMetricAssistantPath } from '../useMetricAssistantPath';
const METRIC = 'system.cpu.utilization';
const TIME = {
mode: 'range' as const,
startMs: 1795948200000,
endMs: 1795950000000,
};
const METRIC_TARGET = { kind: 'metric', resourceId: METRIC };
function activePaths(): ActivePathDTO[] | null | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.metricsummary,
activeViewPath: [],
})?.activePaths;
}
describe('useMetricAssistantPath', () => {
it('sends the metric a drawer shows as the focused path', () => {
renderHook(() => useMetricAssistantPath(METRIC));
expect(activePaths()).toStrictEqual([
{ focused: true, nodes: [{ target: METRIC_TARGET }] },
]);
});
it('sends nothing while no metric is open', () => {
renderHook(() => useMetricAssistantPath(null));
expect(activePaths()).toBeUndefined();
});
it('sends the inspected chart with its own window, the filter and the steps that ran', () => {
renderHook(() =>
useMetricAssistantPath(METRIC, {
options: {
timeAggregationOption: TimeAggregationOptions.AVG,
timeAggregationInterval: 60,
spaceAggregationOption: SpaceAggregationOptions.SUM_BY,
spaceAggregationLabels: ['host.name'],
filterExpression: "host.name = 'web-1'",
},
time: TIME,
}),
);
expect(activePaths()?.[0].nodes[0].state?.dataViews).toStrictEqual([
{
key: 'metric_inspect',
shape: 'timeseries',
signal: 'metrics',
focused: true,
time: TIME,
filter: { expression: "host.name = 'web-1'" },
settings: [
{ name: 'time_aggregation', value: 'avg' },
{ name: 'time_aggregation_interval', value: 60 },
{ name: 'space_aggregation', value: 'sum_by' },
{ name: 'space_aggregation_labels', value: ['host.name'] },
],
},
]);
});
it('sends only the window before any step has run', () => {
renderHook(() =>
useMetricAssistantPath(METRIC, {
options: INITIAL_INSPECT_METRICS_OPTIONS.appliedOptions,
time: TIME,
}),
);
expect(activePaths()?.[0].nodes[0].state?.dataViews).toStrictEqual([
{
key: 'metric_inspect',
shape: 'timeseries',
signal: 'metrics',
focused: true,
time: TIME,
},
]);
});
});

View File

@@ -0,0 +1,76 @@
import {
type ContextSettingDTO,
DataShapeDTO,
type DataViewDTO,
type TimeRangeDTO,
KnownDataSignalDTO,
} from '@signozhq/noz-client';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
import type { MetricInspectionOptions } from './Inspect/types';
import { METRIC_INSPECT_VIEW } from 'container/AIAssistant/pageContext/constants';
interface MetricInspection {
/** The steps that ran, not the ones still being picked. */
options: MetricInspectionOptions;
/** Inspect charts its own window, not the page picker's. */
time: TimeRangeDTO;
}
function toInspectSettings({
timeAggregationOption,
timeAggregationInterval,
spaceAggregationOption,
spaceAggregationLabels,
}: MetricInspectionOptions): ContextSettingDTO[] {
const steps: [string, ContextSettingDTO['value'] | undefined][] = [
['time_aggregation', timeAggregationOption],
['time_aggregation_interval', timeAggregationInterval],
['space_aggregation', spaceAggregationOption],
[
'space_aggregation_labels',
spaceAggregationLabels.length ? spaceAggregationLabels : undefined,
],
];
return steps.flatMap(([name, value]) =>
value === undefined ? [] : [{ name, value }],
);
}
function toInspectView({ options, time }: MetricInspection): DataViewDTO {
const settings = toInspectSettings(options);
return {
key: METRIC_INSPECT_VIEW,
shape: DataShapeDTO.timeseries,
signal: KnownDataSignalDTO.metrics,
focused: true,
time,
filter: options.filterExpression
? { expression: options.filterExpression }
: undefined,
settings: settings.length ? settings : undefined,
};
}
/** Adds the metric a drawer or Inspect shows; Inspect also adds its chart. */
export function useMetricAssistantPath(
metricName: string | null,
inspection?: MetricInspection,
): void {
useAssistantState(
() =>
metricName
? {
path: [
{
target: { kind: 'metric', resourceId: metricName },
state: inspection
? { dataViews: [toInspectView(inspection)] }
: undefined,
},
],
}
: null,
{ focused: true },
);
}

View File

@@ -0,0 +1,44 @@
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import type { IResourceAttribute } from 'hooks/useResourceAttribute/types';
import { encode } from 'js-base64';
import { render } from 'tests/test-utils';
import Services from '..';
jest.mock('container/ServiceApplication/ServiceTraces', () => ({
__esModule: true,
default: (): null => null,
}));
jest.mock('container/ServiceApplication/ServiceMetrics', () => ({
__esModule: true,
default: (): null => null,
}));
const PROD: IResourceAttribute[] = [
{
id: '1',
tagKey: 'resource_deployment.environment',
operator: 'IN',
tagValue: ['prod'],
},
];
describe('Services — assistant context', () => {
it('adds the services table with the resource filter from the url', () => {
render(<Services />, undefined, {
initialRoute: `/services?resourceAttribute=${encode(JSON.stringify(PROD))}`,
});
expect(
snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.servicelist,
activeViewPath: [],
})?.state?.dataViews?.[0],
).toStrictEqual({
key: 'service_list',
shape: 'table',
filter: { expression: "deployment.environment in ['prod']" },
});
});
});

View File

@@ -0,0 +1,55 @@
import {
type DataViewDTO,
KnownAssistantSurfaceDTO,
} from '@signozhq/noz-client';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import type { IResourceAttribute } from 'hooks/useResourceAttribute/types';
import { renderHook } from 'tests/test-utils';
import { useServicesListAssistantContext } from '../useServicesListAssistantContext';
const PROD_NOT_KUBE: IResourceAttribute[] = [
{
id: '1',
tagKey: 'resource_deployment.environment',
operator: 'IN',
tagValue: ['prod', 'staging'],
},
{
id: '2',
tagKey: 'resource_k8s.namespace.name',
operator: 'Not IN',
tagValue: ['kube-system'],
},
];
function servicesView(): DataViewDTO | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.servicelist,
activeViewPath: [],
})?.state?.dataViews?.[0];
}
describe('useServicesListAssistantContext', () => {
it('sends the resource filter as an expression', () => {
renderHook(() => useServicesListAssistantContext(PROD_NOT_KUBE));
expect(servicesView()).toStrictEqual({
key: 'service_list',
shape: 'table',
filter: {
expression:
"deployment.environment in ['prod', 'staging'] AND k8s.namespace.name NOT IN ['kube-system']",
},
});
});
it('sends the table alone while no resource filter applies', () => {
renderHook(() => useServicesListAssistantContext([]));
expect(servicesView()).toStrictEqual({
key: 'service_list',
shape: 'table',
});
});
});

View File

@@ -1,14 +1,18 @@
import * as Sentry from '@sentry/react';
import { FeatureKeys } from 'constants/features';
import useResourceAttribute from 'hooks/useResourceAttribute';
import ErrorBoundaryFallback from 'pages/ErrorBoundaryFallback/ErrorBoundaryFallback';
import { useAppContext } from 'providers/App/App';
import ServiceMetrics from './ServiceMetrics';
import ServiceTraces from './ServiceTraces';
import { Container } from './styles';
import { useServicesListAssistantContext } from './useServicesListAssistantContext';
function Services(): JSX.Element {
const { featureFlags } = useAppContext();
const { queries } = useResourceAttribute();
useServicesListAssistantContext(queries);
const isSpanMetricEnabled =
featureFlags?.find((flag) => flag.name === FeatureKeys.USE_SPAN_METRICS)
?.active || false;

View File

@@ -0,0 +1,28 @@
import { DataShapeDTO, KnownDataViewKeyDTO } from '@signozhq/noz-client';
import { convertFiltersToExpression } from 'components/QueryBuilderV2/utils';
import { useAssistantState } from 'container/AIAssistant/pageContext/hooks/useAssistantState';
import type { IResourceAttribute } from 'hooks/useResourceAttribute/types';
import { resourceAttributesToTracesFilterItems } from 'hooks/useResourceAttribute/utils';
/** Adds the services table with its resource filter; search, sort and page live inside the antd table, out of reach. */
export function useServicesListAssistantContext(
resourceFilters: IResourceAttribute[],
): void {
useAssistantState(() => {
const { expression } = convertFiltersToExpression({
items: resourceAttributesToTracesFilterItems(resourceFilters),
op: 'AND',
});
return {
state: {
dataViews: [
{
key: KnownDataViewKeyDTO.service_list,
shape: DataShapeDTO.table,
filter: expression ? { expression } : undefined,
},
],
},
};
});
}

View File

@@ -0,0 +1,55 @@
import {
KnownAssistantSurfaceDTO,
type ContextStateDTOTime,
} from '@signozhq/noz-client';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { defaultGlobalTimeStore } from 'store/globalTime/globalTimeStore';
import { render } from 'tests/test-utils';
import DateTimeSelection from '../index';
const HOUR_MS = 60 * 60 * 1000;
const initialTimeState = defaultGlobalTimeStore.getState();
function pageTime(): ContextStateDTOTime | undefined {
return snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.servicelist,
activeViewPath: [],
})?.state?.time;
}
describe('DateTimeSelectionV2 - assistant page time', () => {
beforeEach(() => {
defaultGlobalTimeStore.setState({ selectedTime: '1h' });
});
afterEach(() => {
defaultGlobalTimeStore.setState(initialTimeState, true);
});
it('adds the global time to the page', () => {
render(<DateTimeSelection showAutoRefresh={false} />, undefined, {
initialRoute: '/services',
});
const time = pageTime();
expect(time).toMatchObject({ mode: 'range', preset: '1h' });
expect(time?.mode === 'range' ? time.endMs - time.startMs : undefined).toBe(
HOUR_MS,
);
});
it('leaves the time out when the picker holds its own time in a modal', () => {
render(
<DateTimeSelection
showAutoRefresh={false}
isModalTimeSelection
onTimeChange={jest.fn()}
/>,
undefined,
{ initialRoute: '/services' },
);
expect(pageTime()).toBeUndefined();
});
});

View File

@@ -8,6 +8,7 @@ import { Button } from 'antd';
import getLocalStorageKey from 'api/browser/localstorage/get';
import setLocalStorageKey from 'api/browser/localstorage/set';
import CustomTimePicker from 'components/CustomTimePicker/CustomTimePicker';
import { useGlobalPageTime } from 'container/AIAssistant/pageContext/hooks/useGlobalPageTime';
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
import { LOCALSTORAGE } from 'constants/localStorage';
import { QueryParams } from 'constants/query';
@@ -80,6 +81,7 @@ function DateTimeSelection({
const { safeNavigate } = useSafeNavigate();
const navigationType = useAppNavigationType(); // Returns 'POP' for back/forward navigation
const dispatch = useDispatch();
useGlobalPageTime(!isModalTimeSelection);
const { maxTime, minTime, selectedTime } = useSelector<
AppState,

View File

@@ -0,0 +1,28 @@
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { snapshotAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
import { waitFor } from 'tests/test-utils';
import { TRIGGERED_ALERTS_PARAMS } from '../hooks';
import { renderTriggeredAlerts } from './_helpers';
describe('TriggeredAlerts — assistant context', () => {
it('adds the alert table with the label filter and grouping from the url', async () => {
const filters = encodeURIComponent(JSON.stringify(['severity:critical']));
const groupBy = encodeURIComponent(JSON.stringify(['severity']));
renderTriggeredAlerts({
initialRoute: `/alerts?tab=TriggeredAlerts&${TRIGGERED_ALERTS_PARAMS.FILTERS}=${filters}&${TRIGGERED_ALERTS_PARAMS.GROUP_BY}=${groupBy}`,
});
await waitFor(() =>
expect(
snapshotAssistantContext({
surface: KnownAssistantSurfaceDTO.alerttriggered,
activeViewPath: [],
})?.state?.dataViews?.[0],
).toMatchObject({
key: 'triggered_alert_list',
filter: { expression: "severity = 'critical'" },
groupBy: [{ name: 'severity' }],
}),
);
});
});

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