mirror of
https://github.com/SigNoz/signoz.git
synced 2026-12-03 13:40:42 +00:00
Compare commits
8 Commits
feat/noz-c
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bef1303ace | ||
|
|
51828488b8 | ||
|
|
0346b0c04c | ||
|
|
86d9862462 | ||
|
|
c2c0f0a766 | ||
|
|
455e667378 | ||
|
|
e1346d7e9c | ||
|
|
fe0f68589a |
36
.github/CODEOWNERS
vendored
36
.github/CODEOWNERS
vendored
@@ -113,21 +113,21 @@ go.mod @therealpandey
|
||||
/pkg/modules/role/ @therealpandey
|
||||
/pkg/types/coretypes/ @therealpandey @vikrantgupta25
|
||||
|
||||
/frontend/src/lib/authz/ @H4ad
|
||||
/frontend/src/container/RolesSettings/ @H4ad
|
||||
/frontend/src/components/RolesSelect/ @H4ad
|
||||
/frontend/src/pages/MembersSettings/ @H4ad
|
||||
/frontend/src/container/MembersSettings/ @H4ad
|
||||
/frontend/src/components/MembersTable/ @H4ad
|
||||
/frontend/src/components/EditMemberDrawer/ @H4ad
|
||||
/frontend/src/components/InviteMembersModal/ @H4ad
|
||||
/frontend/src/hooks/member/ @H4ad
|
||||
/frontend/src/pages/ServiceAccountsSettings/ @H4ad
|
||||
/frontend/src/container/ServiceAccountsSettings/ @H4ad
|
||||
/frontend/src/components/ServiceAccountsTable/ @H4ad
|
||||
/frontend/src/components/ServiceAccountDrawer/ @H4ad
|
||||
/frontend/src/components/CreateServiceAccountModal/ @H4ad
|
||||
/frontend/src/hooks/serviceAccount/ @H4ad
|
||||
/frontend/src/lib/authz/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/container/RolesSettings/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/components/RolesSelect/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/pages/MembersSettings/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/container/MembersSettings/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/components/MembersTable/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/components/EditMemberDrawer/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/components/InviteMembersModal/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/hooks/member/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/pages/ServiceAccountsSettings/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/container/ServiceAccountsSettings/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/components/ServiceAccountsTable/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/components/ServiceAccountDrawer/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/components/CreateServiceAccountModal/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/hooks/serviceAccount/ @SigNoz/frontend-maintainers
|
||||
|
||||
# IdentN Owners
|
||||
|
||||
@@ -308,9 +308,9 @@ go.mod @therealpandey
|
||||
/frontend/src/container/BottomStrip/ @aks07
|
||||
|
||||
## Storybook
|
||||
/frontend/.storybook/ @H4ad
|
||||
/frontend/src/storybook/ @H4ad
|
||||
/.claude/skills/signoz-page-story/ @H4ad
|
||||
/frontend/.storybook/ @SigNoz/frontend-maintainers
|
||||
/frontend/src/storybook/ @SigNoz/frontend-maintainers
|
||||
/.claude/skills/signoz-page-story/ @SigNoz/frontend-maintainers
|
||||
|
||||
## AI Assistant
|
||||
/frontend/src/container/AIAssistant/ @SigNoz/nerve @SigNoz/frontend-maintainers
|
||||
|
||||
@@ -13065,6 +13065,12 @@ components:
|
||||
additionalProperties: {}
|
||||
description: All of them for a span read by ID; the selected ones in a list.
|
||||
type: object
|
||||
db_name:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
db_operation:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
duration_nano:
|
||||
minimum: 0
|
||||
type: integer
|
||||
@@ -13073,8 +13079,26 @@ components:
|
||||
items:
|
||||
$ref: '#/components/schemas/SpantypesEvent'
|
||||
type: array
|
||||
external_http_method:
|
||||
description: Method of an outgoing HTTP call. Omitted when empty, and in
|
||||
a list unless selected.
|
||||
type: string
|
||||
external_http_url:
|
||||
description: Host of an outgoing HTTP call. Omitted when empty, and in a
|
||||
list unless selected.
|
||||
type: string
|
||||
has_error:
|
||||
type: boolean
|
||||
http_host:
|
||||
description: Host or server address. Omitted when empty, and in a list unless
|
||||
selected.
|
||||
type: string
|
||||
http_method:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
http_url:
|
||||
description: Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
kind_string:
|
||||
description: For example Server, Client or Internal.
|
||||
type: string
|
||||
@@ -13097,6 +13121,11 @@ components:
|
||||
response_status_code:
|
||||
description: HTTP or gRPC status code, for example 404.
|
||||
type: string
|
||||
scope:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/SpantypesScope'
|
||||
description: Instrumentation scope. Omitted when empty, and in a list unless
|
||||
selected.
|
||||
span_id:
|
||||
type: string
|
||||
status_code_string:
|
||||
@@ -13110,6 +13139,9 @@ components:
|
||||
type: integer
|
||||
trace_id:
|
||||
type: string
|
||||
trace_state:
|
||||
description: W3C trace state. Omitted when empty, and in a list unless selected.
|
||||
type: string
|
||||
required:
|
||||
- span_id
|
||||
- trace_id
|
||||
|
||||
@@ -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.15.0-experimental.5",
|
||||
"@signozhq/noz-client": "1.13.0",
|
||||
"@signozhq/ui": "0.4.1-rc.2",
|
||||
"@tanstack/react-table": "8.21.3",
|
||||
"@tanstack/react-virtual": "3.13.22",
|
||||
|
||||
10
frontend/pnpm-lock.yaml
generated
10
frontend/pnpm-lock.yaml
generated
@@ -83,8 +83,8 @@ importers:
|
||||
specifier: 0.4.0
|
||||
version: 0.4.0
|
||||
'@signozhq/noz-client':
|
||||
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)
|
||||
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)
|
||||
'@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.15.0-experimental.5':
|
||||
resolution: {integrity: sha512-CxLEj9g+/QK9zjumREhg2U+D5RShGa6N73XucEbgISCQpWdNKEasSh6vmpDyZpEgLEKq7g4g38Pb6EGN7yg5Pg==}
|
||||
'@signozhq/noz-client@1.13.0':
|
||||
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
|
||||
peerDependencies:
|
||||
axios: ^1.20.0
|
||||
react: ^18.2.0
|
||||
@@ -12058,7 +12058,7 @@ snapshots:
|
||||
|
||||
'@signozhq/icons@0.4.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)':
|
||||
'@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)':
|
||||
dependencies:
|
||||
axios: 1.21.1
|
||||
react: 18.2.0
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
|
||||
|
||||
/** Path-only base for the AI Assistant API. */
|
||||
export const AI_API_PATH = '/api/v2/assistant';
|
||||
export const AI_API_PATH = '/api/v1/assistant';
|
||||
|
||||
/** Header that tells the AI backend which SigNoz instance to query against. */
|
||||
export const SIGNOZ_URL_HEADER = 'X-SigNoz-URL';
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -2,9 +2,9 @@
|
||||
* AI Assistant API client.
|
||||
*
|
||||
* Flow:
|
||||
* 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')
|
||||
* 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')
|
||||
*
|
||||
* For subsequent messages in the same thread, repeat steps 2–3.
|
||||
* Approval/clarification events pause the stream; use approveExecution/clarifyExecution
|
||||
@@ -33,20 +33,23 @@ import type {
|
||||
ApproveResponseDTO,
|
||||
CancelResponseDTO,
|
||||
ClarifyResponseDTO,
|
||||
CreateMessageRequestV2DTO,
|
||||
CreateMessageResponseDTO,
|
||||
CreateThreadResponseDTO,
|
||||
ExecutionStateDTO,
|
||||
FeedbackRatingDTO,
|
||||
ListThreadsApiV2AssistantThreadsGetArchived,
|
||||
ListThreadsApiV2AssistantThreadsGetParams,
|
||||
MessageSummaryV2DTO,
|
||||
ListThreadsApiV1AssistantThreadsGetArchived,
|
||||
ListThreadsApiV1AssistantThreadsGetParams,
|
||||
MessageContextDTO,
|
||||
MessageContextDTOSource,
|
||||
MessageContextDTOType,
|
||||
MessageSummaryDTO,
|
||||
RegenerateResponseDTO,
|
||||
ThreadDetailResponseV2DTO,
|
||||
ThreadDetailResponseDTO,
|
||||
ThreadListResponseDTO,
|
||||
ThreadSummaryDTO,
|
||||
ChipDTO,
|
||||
ChipsResponseDTO,
|
||||
PageTypeDTO,
|
||||
} from '@signozhq/noz-client';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
@@ -183,16 +186,26 @@ export type ExecutionState = `${ExecutionStateDTO}`;
|
||||
|
||||
export type ThreadSummary = ThreadSummaryDTO;
|
||||
export type ThreadListResponse = ThreadListResponseDTO;
|
||||
export type ThreadDetailResponse = ThreadDetailResponseV2DTO;
|
||||
export type MessageSummary = MessageSummaryV2DTO;
|
||||
export type ThreadDetailResponse = ThreadDetailResponseDTO;
|
||||
export type MessageSummary = MessageSummaryDTO;
|
||||
export type CancelResponse = CancelResponseDTO;
|
||||
|
||||
/** Construction-friendly view of `ListThreadsApiV2AssistantThreadsGetParams`. */
|
||||
/**
|
||||
* 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`. */
|
||||
export type ListThreadsOptions = Omit<
|
||||
ListThreadsApiV2AssistantThreadsGetParams,
|
||||
ListThreadsApiV1AssistantThreadsGetParams,
|
||||
'archived'
|
||||
> & {
|
||||
archived?: `${ListThreadsApiV2AssistantThreadsGetArchived}`;
|
||||
archived?: `${ListThreadsApiV1AssistantThreadsGetArchived}`;
|
||||
};
|
||||
|
||||
/** String-literal view of `FeedbackRatingDTO` so call-sites can pass `'positive'`/`'negative'`. */
|
||||
@@ -247,7 +260,7 @@ export async function getThreadDetail(
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step 1 — Create thread
|
||||
// POST /api/v2/assistant/threads → { threadId }
|
||||
// POST /api/v1/assistant/threads → { threadId }
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export async function createThread(signal?: AbortSignal): Promise<string> {
|
||||
@@ -261,13 +274,13 @@ export async function createThread(signal?: AbortSignal): Promise<string> {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step 2 — Send message
|
||||
// POST /api/v2/assistant/threads/{threadId}/messages → { executionId }
|
||||
// POST /api/v1/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<ThreadDetailResponse>(
|
||||
const response = await AIAssistantInstance.get<ThreadDetailResponseDTO>(
|
||||
`/threads/${threadId}`,
|
||||
);
|
||||
return response.data.activeExecutionId ?? null;
|
||||
@@ -278,13 +291,17 @@ async function getActiveExecutionId(threadId: string): Promise<string | null> {
|
||||
|
||||
export async function sendMessage(
|
||||
threadId: string,
|
||||
body: CreateMessageRequestV2DTO,
|
||||
content: string,
|
||||
contexts?: MessageContext[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<string> {
|
||||
try {
|
||||
const response = await AIAssistantInstance.post<CreateMessageResponseDTO>(
|
||||
`/threads/${threadId}/messages`,
|
||||
body,
|
||||
{
|
||||
content,
|
||||
...(contexts && contexts.length > 0 ? { contexts } : {}),
|
||||
},
|
||||
{ signal },
|
||||
);
|
||||
return response.data.executionId;
|
||||
@@ -303,7 +320,7 @@ export async function sendMessage(
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Step 3 — Stream execution events
|
||||
// GET /api/v2/assistant/executions/{executionId}/events → SSE
|
||||
// GET /api/v1/assistant/executions/{executionId}/events → SSE
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function parseSSELine(line: string): SSEEvent | null {
|
||||
@@ -504,30 +521,16 @@ export async function submitFeedback(
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Contextual empty-state chips
|
||||
// GET /api/v2/assistant/empty-state/chips?surface=…&active_view_path=… → { chips }
|
||||
// GET /api/v1/assistant/empty-state/chips?page_type=… → { chips }
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface ChipsPage {
|
||||
surface: string;
|
||||
/** Selected tabs, outermost first. */
|
||||
activeViewPath: string[];
|
||||
}
|
||||
|
||||
export async function getEmptyStateChips(
|
||||
{ surface, activeViewPath }: ChipsPage,
|
||||
pageType: PageTypeDTO,
|
||||
signal?: AbortSignal,
|
||||
): Promise<ChipDTO[]> {
|
||||
const response = await AIAssistantInstance.get<ChipsResponseDTO>(
|
||||
'/empty-state/chips',
|
||||
{
|
||||
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,
|
||||
},
|
||||
{ params: { page_type: pageType }, signal },
|
||||
);
|
||||
return response.data.chips;
|
||||
}
|
||||
|
||||
@@ -14681,6 +14681,16 @@ export interface SpantypesSpanDTO {
|
||||
* @description All of them for a span read by ID; the selected ones in a list.
|
||||
*/
|
||||
attributes: SpantypesSpanDTOAttributes;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
db_name?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
db_operation?: string;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
@@ -14691,10 +14701,35 @@ export interface SpantypesSpanDTO {
|
||||
* @description All of them for a span read by ID; none in a list.
|
||||
*/
|
||||
events: SpantypesEventDTO[];
|
||||
/**
|
||||
* @type string
|
||||
* @description Method of an outgoing HTTP call. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
external_http_method?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Host of an outgoing HTTP call. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
external_http_url?: string;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
has_error: boolean;
|
||||
/**
|
||||
* @type string
|
||||
* @description Host or server address. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
http_host?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
http_method?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
http_url?: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description For example Server, Client or Internal.
|
||||
@@ -14724,6 +14759,10 @@ export interface SpantypesSpanDTO {
|
||||
* @description HTTP or gRPC status code, for example 404.
|
||||
*/
|
||||
response_status_code: string;
|
||||
/**
|
||||
* @description Instrumentation scope. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
scope?: SpantypesScopeDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
@@ -14747,6 +14786,11 @@ export interface SpantypesSpanDTO {
|
||||
* @type string
|
||||
*/
|
||||
trace_id: string;
|
||||
/**
|
||||
* @type string
|
||||
* @description W3C trace state. Omitted when empty, and in a list unless selected.
|
||||
*/
|
||||
trace_state?: string;
|
||||
}
|
||||
|
||||
export interface SpantypesSpanTextMatchDTO {
|
||||
|
||||
@@ -72,7 +72,6 @@ function LogDetailBody({
|
||||
target.closest('.cm-tooltip-autocomplete') ||
|
||||
target.closest('.drawer-popover') ||
|
||||
target.closest('.query-status-popover') ||
|
||||
target.closest('[data-radix-popper-content-wrapper]') ||
|
||||
target.closest('[data-base-ui-portal]')
|
||||
) {
|
||||
return;
|
||||
|
||||
@@ -155,14 +155,6 @@
|
||||
background: var(--l2-background);
|
||||
box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
|
||||
|
||||
.context-btn {
|
||||
width: 50% !important;
|
||||
}
|
||||
.copy-link-btn {
|
||||
width: 50% !important;
|
||||
border-left: 1px solid var(--l1-border) !important;
|
||||
}
|
||||
|
||||
.ant-btn-default {
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
|
||||
@@ -83,9 +83,3 @@ export const LogText = styled.div<LogTextProps>`
|
||||
: 'white-space: nowrap;'};
|
||||
};
|
||||
`;
|
||||
|
||||
export const SelectedLog = styled.div`
|
||||
display: flex;
|
||||
width: 100%;
|
||||
overflow: hidden;
|
||||
`;
|
||||
|
||||
@@ -27,14 +27,3 @@
|
||||
border-color: var(--l1-border) !important;
|
||||
}
|
||||
}
|
||||
|
||||
// In table/column view, keep action buttons visible at the viewport's right edge
|
||||
.log-line-action-buttons.table-view-log-actions {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 8px;
|
||||
left: auto;
|
||||
transform: translateY(-50%);
|
||||
margin: 0;
|
||||
z-index: 5;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,4 @@
|
||||
import { blue } from '@ant-design/colors';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import Space from 'periscope/components/Space/Space';
|
||||
import Col from 'periscope/components/Col/Col';
|
||||
import Row from 'periscope/components/Row/Row';
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { Info } from '@signozhq/icons';
|
||||
@@ -73,12 +70,6 @@ export const InfoIconWrapper = styled(Info)`
|
||||
height: auto;
|
||||
`;
|
||||
|
||||
export const ExpandIconWrapper = styled(Col)`
|
||||
color: ${blue[6]};
|
||||
padding: 0.25rem 0.375rem;
|
||||
cursor: pointer;
|
||||
`;
|
||||
|
||||
export const RawLogContent = styled.div<RawLogContentProps>`
|
||||
margin-bottom: 0;
|
||||
font-family: 'SF Mono', monospace;
|
||||
@@ -112,11 +103,3 @@ export const RawLogContent = styled.div<RawLogContentProps>`
|
||||
cursor: ${({ $isActiveLog, $isReadOnly }): string =>
|
||||
$isActiveLog || $isReadOnly ? 'initial' : 'pointer'};
|
||||
`;
|
||||
|
||||
export const ActionButtonsWrapper = styled(Space)`
|
||||
position: absolute;
|
||||
transform: translate(-50%, -50%);
|
||||
top: 50%;
|
||||
right: 0;
|
||||
cursor: pointer;
|
||||
`;
|
||||
|
||||
@@ -187,177 +187,6 @@
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.add-new-column-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.add-new-column-header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
padding: 8px;
|
||||
gap: 8px;
|
||||
|
||||
.back-icon {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
align-items: center;
|
||||
color: var(--muted-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.add-new-column-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
padding-bottom: 16px;
|
||||
|
||||
min-height: 240px;
|
||||
max-height: 400px;
|
||||
|
||||
.loading-container {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.column-format-new-options {
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
|
||||
.column-name {
|
||||
padding: 4px 8px;
|
||||
border-radius: 1px;
|
||||
color: var(--l2-foreground);
|
||||
|
||||
&.selected {
|
||||
background-color: var(--l3-background);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
height: 1rem;
|
||||
width: 0.2rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.selected-item-content-container {
|
||||
.add-new-column-header {
|
||||
padding: 8px;
|
||||
}
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
|
||||
margin-bottom: 12px;
|
||||
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
|
||||
.lucide {
|
||||
color: var(--l2-foreground);
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.horizontal-line {
|
||||
height: 1px;
|
||||
background: var(--l3-background);
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
margin: 12px 0;
|
||||
}
|
||||
|
||||
.item-content {
|
||||
padding: 12px;
|
||||
|
||||
.column-format,
|
||||
.column-format-new-options {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
flex-direction: column;
|
||||
margin-top: 12px;
|
||||
|
||||
.column-name {
|
||||
color: var(--l2-foreground);
|
||||
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
cursor: pointer;
|
||||
|
||||
&.default-column {
|
||||
color: var(--l2-foreground);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
&.no-columns-selected {
|
||||
color: var(--l3-foreground);
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
&.add-new-column-btn {
|
||||
color: var(--l2-foreground);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.name {
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.delete-btn {
|
||||
display: none;
|
||||
flex: 0 0 16px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
.delete-btn {
|
||||
display: block;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
overflow-x: hidden;
|
||||
|
||||
&::-webkit-scrollbar {
|
||||
height: 1rem;
|
||||
width: 0.2rem;
|
||||
}
|
||||
}
|
||||
|
||||
.column-format {
|
||||
max-height: 150px;
|
||||
overflow: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.column-format-new-options {
|
||||
max-height: 150px;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
.column-divider {
|
||||
margin: 12px 0;
|
||||
border-top: 2px solid var(--l1-border);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.active {
|
||||
.nested-menu-container {
|
||||
backdrop-filter: blur(18px);
|
||||
@@ -368,26 +197,6 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.selected-item-content-container {
|
||||
width: 110%;
|
||||
margin-left: -5%;
|
||||
|
||||
border-radius: 4px;
|
||||
border: 1px solid var(--l1-border);
|
||||
background: linear-gradient(
|
||||
139deg,
|
||||
color-mix(in srgb, var(--surface-2) 80%, transparent) 0%,
|
||||
color-mix(in srgb, var(--surface-2) 90%, transparent) 98.68%
|
||||
);
|
||||
|
||||
box-shadow: 4px 10px 16px 2px rgba(0, 0, 0, 0.2);
|
||||
backdrop-filter: blur(20px);
|
||||
|
||||
.column-format {
|
||||
margin-top: 0px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,9 +26,3 @@
|
||||
width: max-content;
|
||||
}
|
||||
}
|
||||
|
||||
.select-label-with-coming-soon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
@@ -1,39 +1,8 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Tooltip } from 'antd';
|
||||
import type { DefaultOptionType } from 'antd/es/select';
|
||||
import { Info } from '@signozhq/icons';
|
||||
|
||||
import './MQCommon.styles.scss';
|
||||
|
||||
export function ComingSoon(): JSX.Element {
|
||||
return (
|
||||
<Tooltip
|
||||
title={
|
||||
<div>
|
||||
Join our Slack community for more details:{' '}
|
||||
<a
|
||||
href="https://signoz.io/slack"
|
||||
rel="noopener noreferrer"
|
||||
target="_blank"
|
||||
onClick={(e): void => e.stopPropagation()}
|
||||
>
|
||||
SigNoz Community
|
||||
</a>
|
||||
</div>
|
||||
}
|
||||
placement="top"
|
||||
overlayClassName="tooltip-overlay"
|
||||
>
|
||||
<div className="coming-soon">
|
||||
<div className="coming-soon__text">Coming Soon</div>
|
||||
<div className="coming-soon__icon">
|
||||
<Info size={10} color={Color.BG_SIENNA_400} />
|
||||
</div>
|
||||
</div>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function SelectMaxTagPlaceholder(
|
||||
omittedValues: Partial<DefaultOptionType>[],
|
||||
): JSX.Element {
|
||||
@@ -43,15 +12,3 @@ export function SelectMaxTagPlaceholder(
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
export function SelectLabelWithComingSoon({
|
||||
label,
|
||||
}: {
|
||||
label: string;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div className="select-label-with-coming-soon">
|
||||
{label} <ComingSoon />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { useCallback } from 'react';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import ROUTES from 'constants/routes';
|
||||
@@ -22,6 +23,10 @@ function NotificationChannelsNotFound({
|
||||
}: NotificationChannelsNotFoundProps): JSX.Element {
|
||||
const { isGranted, isLoading, error } = useAuthZ(CREATE_CHECKS);
|
||||
const canCreate = !!error || isGranted(NotificationChannelCreatePermission);
|
||||
const openCreateChannel = useCallback(
|
||||
(): void => openInNewTab(ROUTES.CHANNELS_NEW),
|
||||
[],
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
@@ -43,7 +48,7 @@ function NotificationChannelsNotFound({
|
||||
color="primary"
|
||||
size="sm"
|
||||
testId="channels-not-found-create"
|
||||
onClick={(): void => openInNewTab(ROUTES.CHANNELS_NEW)}
|
||||
onClick={openCreateChannel}
|
||||
>
|
||||
Create one here.
|
||||
</Button>
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
startCompletion,
|
||||
} from '@codemirror/autocomplete';
|
||||
import { javascript } from '@codemirror/lang-javascript';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { copilot } from '@uiw/codemirror-theme-copilot';
|
||||
import { githubLight } from '@uiw/codemirror-theme-github';
|
||||
@@ -361,9 +362,12 @@ function QuerySearch({
|
||||
metricNamespace,
|
||||
},
|
||||
builderQueryType,
|
||||
);
|
||||
).catch((error: unknown) => {
|
||||
Sentry.captureException(error);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (response.data.keys) {
|
||||
if (response?.data.keys) {
|
||||
const { keys } = response.data;
|
||||
const options = generateOptions(keys);
|
||||
// Deduplicate by full variant identity (name + context + data type), NOT by
|
||||
|
||||
@@ -1,24 +1,27 @@
|
||||
import { useCallback, useLayoutEffect, useState } from 'react';
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
useState,
|
||||
} from 'react';
|
||||
import cx from 'classnames';
|
||||
import type {
|
||||
ManualReferenceDTO,
|
||||
MessageContextV2DTO,
|
||||
} from '@signozhq/noz-client';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
|
||||
import logEvent from 'api/common/logEvent';
|
||||
|
||||
import ChatInput from '../components/ChatInput';
|
||||
import ChatInput, { autoContextKey } 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';
|
||||
|
||||
@@ -32,6 +35,7 @@ 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);
|
||||
@@ -57,7 +61,7 @@ export default function ConversationView({
|
||||
const pendingClarificationHere = useAIAssistantStore(
|
||||
(s) => s.streams[conversationId]?.pendingClarification ?? null,
|
||||
);
|
||||
const sendMessage = useSendMessage();
|
||||
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
|
||||
const cancelStream = useAIAssistantStore((s) => s.cancelStream);
|
||||
const analyticsCtx = useAIAssistantAnalyticsContext(conversationId);
|
||||
|
||||
@@ -72,17 +76,50 @@ export default function ConversationView({
|
||||
}
|
||||
}, [hasUnreadReply, conversationId, markReplyRead]);
|
||||
|
||||
const { page, dismiss, refresh, snapshotPage } = usePageContext();
|
||||
// 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 handleSend = useCallback(
|
||||
(
|
||||
text: string,
|
||||
attachments?: MessageAttachment[],
|
||||
mentions?: ManualReferenceDTO[],
|
||||
contexts?: MessageContext[],
|
||||
) => {
|
||||
const pageContext = snapshotPage();
|
||||
const hasAuto = pageContext !== null;
|
||||
const hasManual = Boolean(mentions?.length);
|
||||
const hasAuto = contexts?.some((c) => c.source === 'auto') ?? false;
|
||||
const hasManual = contexts?.some((c) => c.source === 'mention') ?? false;
|
||||
let contextType: 'manual' | 'auto' | 'both' | undefined;
|
||||
if (hasAuto && hasManual) {
|
||||
contextType = 'both';
|
||||
@@ -98,16 +135,9 @@ export default function ConversationView({
|
||||
contextType,
|
||||
respondingToClarification: Boolean(pendingClarificationHere),
|
||||
});
|
||||
const context: MessageContextV2DTO = {
|
||||
...(pageContext ? { page: pageContext } : {}),
|
||||
...(hasManual ? { mentions } : {}),
|
||||
};
|
||||
void sendMessage(text, {
|
||||
attachments,
|
||||
context: hasAuto || hasManual ? context : undefined,
|
||||
});
|
||||
void sendMessage(text, attachments, contexts);
|
||||
},
|
||||
[sendMessage, snapshotPage, analyticsCtx, pendingClarificationHere],
|
||||
[sendMessage, analyticsCtx, pendingClarificationHere],
|
||||
);
|
||||
|
||||
// When the current reply began, kept with the stream so a reopened view carries on from it.
|
||||
@@ -174,8 +204,8 @@ export default function ConversationView({
|
||||
onSend={handleSend}
|
||||
disabled
|
||||
disabledTooltip="Wait for the conversation to load"
|
||||
page={page}
|
||||
onDismissPage={dismiss}
|
||||
autoContexts={autoContexts}
|
||||
onDismissAutoContext={handleDismissAutoContext}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -190,7 +220,13 @@ export default function ConversationView({
|
||||
messages={messages}
|
||||
isStreaming={isStreamingHere}
|
||||
onSnakeGameChange={handleSnakeGameChange}
|
||||
onSendSuggestedPrompt={(text): void => handleSend(text)}
|
||||
onSendSuggestedPrompt={(text): void => {
|
||||
handleSend(
|
||||
text,
|
||||
undefined,
|
||||
autoContexts.length > 0 ? autoContexts : undefined,
|
||||
);
|
||||
}}
|
||||
/>
|
||||
{showDisclaimer && (
|
||||
<div className={disclaimerClass} role="note" aria-live="polite">
|
||||
@@ -210,9 +246,8 @@ export default function ConversationView({
|
||||
isStreaming={isStreamingHere}
|
||||
streamStartedAt={streamStartedAt}
|
||||
showNozPeek={messages.length === 0 && !isStreamingHere}
|
||||
page={page}
|
||||
onDismissPage={dismiss}
|
||||
onFocus={refresh}
|
||||
autoContexts={autoContexts}
|
||||
onDismissAutoContext={handleDismissAutoContext}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,37 +1,41 @@
|
||||
import type { ManualReferenceDTO, PageContextDTO } from '@signozhq/noz-client';
|
||||
import { registerAssistantContext } from 'container/AIAssistant/pageContext/store/usePageContextStore';
|
||||
import { fireEvent, render } from '@testing-library/react';
|
||||
import { MessageContext } from 'api/ai-assistant/chat';
|
||||
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
|
||||
import type { SendMessageOptions } from 'container/AIAssistant/types';
|
||||
import { VariantContext } from 'container/AIAssistant/VariantContext';
|
||||
import { fireEvent, render, screen } from 'tests/test-utils';
|
||||
import { TestRouter } from 'tests/router';
|
||||
import { screen } from 'tests/test-utils';
|
||||
|
||||
const CHIP_ID = 'recent-errors';
|
||||
const CHIP_TEXT = 'Show me recent errors';
|
||||
const DASHBOARD_PAGE: PageContextDTO = {
|
||||
surface: 'dashboard.detail',
|
||||
root: {
|
||||
kind: 'dashboard',
|
||||
|
||||
// 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',
|
||||
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; the stub sends one mention and dismisses the page on demand.
|
||||
// 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.
|
||||
jest.mock('container/AIAssistant/components/ChatInput', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
@@ -39,19 +43,11 @@ 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"
|
||||
@@ -59,25 +55,9 @@ 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', () => ({
|
||||
@@ -145,34 +125,24 @@ import ConversationView from '../ConversationView';
|
||||
|
||||
const CONVERSATION_ID = 'conv-1';
|
||||
|
||||
function renderView(
|
||||
variant: 'panel' | 'page' | 'modal',
|
||||
initialRoute = '/dashboard/dashboard-123',
|
||||
): {
|
||||
function renderView(variant: 'panel' | 'page' | 'modal'): {
|
||||
getByTestId: (id: string) => HTMLElement;
|
||||
} {
|
||||
return render(
|
||||
<VariantContext.Provider value={variant}>
|
||||
<ConversationView conversationId={CONVERSATION_ID} />
|
||||
</VariantContext.Provider>,
|
||||
undefined,
|
||||
{ initialRoute },
|
||||
<TestRouter initialRoute="/dashboard/dashboard-123">
|
||||
<VariantContext.Provider value={variant}>
|
||||
<ConversationView conversationId={CONVERSATION_ID} />
|
||||
</VariantContext.Provider>
|
||||
</TestRouter>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ConversationView — sent context', () => {
|
||||
const storeSend = useAIAssistantStore.getState().sendMessage;
|
||||
let sendMessage: jest.MockedFunction<
|
||||
(text: string, options: SendMessageOptions) => Promise<void>
|
||||
>;
|
||||
let leaveDashboard: () => void;
|
||||
describe('ConversationView — empty-state chip context', () => {
|
||||
let sendMessage: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
sendMessage = jest.fn();
|
||||
leaveDashboard = registerAssistantContext('dashboard', () => ({
|
||||
root: DASHBOARD_PAGE.root ?? undefined,
|
||||
}));
|
||||
useAIAssistantStore.setState({
|
||||
conversations: {
|
||||
[CONVERSATION_ID]: {
|
||||
@@ -186,44 +156,30 @@ describe('ConversationView — sent context', () => {
|
||||
activeConversationId: CONVERSATION_ID,
|
||||
loadingThreadIds: [],
|
||||
sendMessage,
|
||||
});
|
||||
} as unknown as Partial<ReturnType<typeof useAIAssistantStore.getState>>);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
leaveDashboard();
|
||||
useAIAssistantStore.setState({ sendMessage: storeSend });
|
||||
});
|
||||
|
||||
it('sends the page with a chip, as a typed message would', () => {
|
||||
it('forwards the page auto-contexts when a chip is clicked (embedded variant)', () => {
|
||||
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.mock.calls[0][0]).toBe(CHIP_TEXT);
|
||||
expect(sendMessage.mock.calls[0][1].context).toStrictEqual({
|
||||
page: DASHBOARD_PAGE,
|
||||
});
|
||||
expect(sendMessage).toHaveBeenCalledWith(
|
||||
CHIP_TEXT,
|
||||
undefined,
|
||||
mockAutoContexts,
|
||||
);
|
||||
});
|
||||
|
||||
it('sends no page from the Noz page, which has no surface', () => {
|
||||
const { getByTestId } = renderView('page', '/ai-assistant/conv-1');
|
||||
it('sends undefined contexts on the standalone page (no page context to attach)', () => {
|
||||
const { getByTestId } = renderView('page');
|
||||
|
||||
fireEvent.click(getByTestId(`empty-state-chip-${CHIP_ID}`));
|
||||
|
||||
expect(sendMessage).toHaveBeenCalledTimes(1);
|
||||
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],
|
||||
});
|
||||
expect(sendMessage).toHaveBeenCalledWith(CHIP_TEXT, undefined, undefined);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,104 +0,0 @@
|
||||
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' },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,90 +0,0 @@
|
||||
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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -37,7 +37,7 @@ import logEvent from 'api/common/logEvent';
|
||||
|
||||
import { AIAssistantEvents, SuggestedPromptCategory } from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useSendMessage } from '../../hooks/useSendMessage';
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
|
||||
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 = useSendMessage();
|
||||
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
|
||||
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
|
||||
const { redirectWithQueryBuilderData, handleSetQueryData } = useQueryBuilder();
|
||||
const dispatch = useDispatch();
|
||||
|
||||
@@ -25,6 +25,13 @@
|
||||
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;
|
||||
|
||||
@@ -5,18 +5,26 @@ 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 type { ManualReferenceDTO } from '@signozhq/noz-client';
|
||||
import { useListDashboardsForUserV2 } from 'api/generated/services/dashboard';
|
||||
import { useListRulesV3 } from 'api/generated/services/rules';
|
||||
import {
|
||||
getListDashboardsForUserV2QueryKey,
|
||||
useListDashboardsForUserV2,
|
||||
} from 'api/generated/services/dashboard';
|
||||
import {
|
||||
getListRulesV3QueryKey,
|
||||
useListRulesV3,
|
||||
} from 'api/generated/services/rules';
|
||||
import type {
|
||||
DashboardtypesListedDashboardForUserV2DTO,
|
||||
ListDashboardsForUserV2200,
|
||||
ListDashboardsForUserV2Params,
|
||||
ListRulesV3200,
|
||||
ListRulesV3Params,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { useQueryService } from 'hooks/useQueryService';
|
||||
@@ -25,29 +33,31 @@ 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 ContextPills from './ContextPills/ContextPills';
|
||||
import ContextPill from './ContextPill/ContextPill';
|
||||
import EdgeSweep from './EdgeSweep/EdgeSweep';
|
||||
import NozPeek from './NozPeek/NozPeek';
|
||||
import {
|
||||
AUTO_CONTEXT_ICONS,
|
||||
CONTEXT_CATEGORIES,
|
||||
CONTEXT_CATEGORY_KINDS,
|
||||
CONTEXT_CATEGORY_ICONS,
|
||||
CONTEXT_CATEGORY_SINGULAR,
|
||||
CONTEXT_TYPE_LABELS,
|
||||
ContextCategory,
|
||||
MAX_MENTIONS,
|
||||
} from './contextPicker';
|
||||
|
||||
interface ChatInputProps {
|
||||
onSend: (
|
||||
text: string,
|
||||
attachments?: MessageAttachment[],
|
||||
mentions?: ManualReferenceDTO[],
|
||||
contexts?: MessageContext[],
|
||||
) => void;
|
||||
onCancel?: () => void;
|
||||
disabled?: boolean;
|
||||
@@ -62,11 +72,71 @@ interface ChatInputProps {
|
||||
streamStartedAt?: number | null;
|
||||
/** Noz peeks over the top edge; meant for an empty conversation. */
|
||||
showNozPeek?: boolean;
|
||||
/** 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;
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
const MAX_INPUT_LENGTH = 20000;
|
||||
@@ -76,7 +146,11 @@ 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. */
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
const DASHBOARD_LIST_PARAMS: ListDashboardsForUserV2Params = { limit: 1000 };
|
||||
|
||||
/** Same as dashboards. 200 is the most the rules list returns per call. */
|
||||
@@ -94,12 +168,32 @@ interface SelectedContextItem {
|
||||
value: string;
|
||||
}
|
||||
|
||||
function toMention(item: SelectedContextItem): ManualReferenceDTO {
|
||||
return {
|
||||
kind: CONTEXT_CATEGORY_KINDS[item.category],
|
||||
resourceId: item.entityId,
|
||||
resourceName: item.value,
|
||||
};
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
interface ContextEntityItem {
|
||||
@@ -127,9 +221,8 @@ export default function ChatInput({
|
||||
isStreaming = false,
|
||||
streamStartedAt = null,
|
||||
showNozPeek = false,
|
||||
page,
|
||||
onDismissPage,
|
||||
onFocus,
|
||||
autoContexts,
|
||||
onDismissAutoContext,
|
||||
}: ChatInputProps): JSX.Element {
|
||||
const { selectedTime } = useSelector<AppState, GlobalReducer>(
|
||||
(state) => state.globalTime,
|
||||
@@ -163,6 +256,7 @@ 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
|
||||
@@ -220,9 +314,6 @@ 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) {
|
||||
@@ -385,13 +476,18 @@ export default function ChatInput({
|
||||
}),
|
||||
);
|
||||
|
||||
const mentions = selectedContexts.map(toMention);
|
||||
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 payload = capText(trimmed);
|
||||
|
||||
onSend(
|
||||
payload,
|
||||
attachments.length > 0 ? attachments : undefined,
|
||||
mentions.length > 0 ? mentions : undefined,
|
||||
contexts.length > 0 ? contexts : undefined,
|
||||
);
|
||||
setText('');
|
||||
setPendingFiles([]);
|
||||
@@ -404,6 +500,7 @@ export default function ChatInput({
|
||||
sendDisabled,
|
||||
onSend,
|
||||
selectedContexts,
|
||||
autoContexts,
|
||||
capText,
|
||||
]);
|
||||
|
||||
@@ -483,6 +580,55 @@ 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:
|
||||
@@ -578,12 +724,38 @@ export default function ChatInput({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ContextPills
|
||||
page={page}
|
||||
onDismissPage={onDismissPage}
|
||||
picked={selectedContexts}
|
||||
onRemovePicked={removeContext}
|
||||
/>
|
||||
{(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>
|
||||
)}
|
||||
|
||||
<div className={styles.composer}>
|
||||
<textarea
|
||||
@@ -598,7 +770,6 @@ export default function ChatInput({
|
||||
syncContextPickerFromText(next, e.target.selectionStart ?? next.length);
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
onFocus={onFocus}
|
||||
disabled={disabled}
|
||||
maxLength={MAX_INPUT_LENGTH}
|
||||
rows={2}
|
||||
|
||||
@@ -8,7 +8,6 @@ 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. */
|
||||
@@ -17,13 +16,12 @@ export default function ContextPill({
|
||||
category,
|
||||
label,
|
||||
onRemove,
|
||||
testId = 'ai-context-pill',
|
||||
}: ContextPillProps): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
className={styles.pill}
|
||||
title={`${category}: ${label}`}
|
||||
data-testid={testId}
|
||||
data-testid="ai-context-pill"
|
||||
>
|
||||
<Icon size={14} className={styles.icon} />
|
||||
<span className={styles.category}>{category} :</span>
|
||||
@@ -36,7 +34,7 @@ export default function ContextPill({
|
||||
color="secondary"
|
||||
onClick={onRemove}
|
||||
aria-label={`Remove ${category}: ${label} context`}
|
||||
testId={`${testId}-remove`}
|
||||
testId="ai-context-pill-remove"
|
||||
>
|
||||
<X size={12} />
|
||||
</Button>
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
.pills {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
padding: var(--spacing-4) var(--spacing-5) 0;
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -1,82 +1,35 @@
|
||||
import type { ComponentProps } from 'react';
|
||||
import {
|
||||
KnownAssistantSurfaceDTO,
|
||||
type ManualReferenceDTO,
|
||||
} from '@signozhq/noz-client';
|
||||
import {
|
||||
NO_DELAY_USER_EVENT,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
} from 'tests/test-utils';
|
||||
import type { MessageContext } from 'api/ai-assistant/chat';
|
||||
import { 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';
|
||||
|
||||
type ChatInputProps = ComponentProps<typeof ChatInput>;
|
||||
const serviceContext: MessageContext = {
|
||||
source: 'auto',
|
||||
type: 'service',
|
||||
resourceId: 'checkout',
|
||||
};
|
||||
|
||||
describe('ChatInput — context pills', () => {
|
||||
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']>
|
||||
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']>
|
||||
>;
|
||||
render(
|
||||
<ChatInput
|
||||
onSend={jest.fn()}
|
||||
page={{
|
||||
surface: KnownAssistantSurfaceDTO.servicedetail,
|
||||
root: {
|
||||
kind: 'service',
|
||||
resourceId: 'checkout',
|
||||
resourceName: 'checkout',
|
||||
},
|
||||
}}
|
||||
onDismissPage={onDismissPage}
|
||||
autoContexts={[serviceContext]}
|
||||
onDismissAutoContext={onDismissAutoContext}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('ai-page-pill')).toHaveTextContent(
|
||||
expect(screen.getByTestId('ai-context-pill')).toHaveTextContent(
|
||||
'Service :checkout',
|
||||
);
|
||||
await user.click(screen.getByTestId('ai-page-pill-remove'));
|
||||
|
||||
expect(onDismissPage).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
await user.click(screen.getByTestId('ai-context-pill-remove'));
|
||||
|
||||
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);
|
||||
expect(onDismissAutoContext).toHaveBeenCalledWith('auto:service:checkout:');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,15 +1,13 @@
|
||||
import {
|
||||
BarChart,
|
||||
Bell,
|
||||
Bug,
|
||||
DraftingCompass,
|
||||
HardDrive,
|
||||
LayoutDashboard,
|
||||
Package,
|
||||
ScrollText,
|
||||
Settings,
|
||||
} from '@signozhq/icons';
|
||||
import type { ManualReferenceDTO } from '@signozhq/noz-client';
|
||||
|
||||
import { MessageContext } from '../../../../api/ai-assistant/chat';
|
||||
|
||||
/** Ordered category tabs shown in the @-mention context picker. */
|
||||
export const CONTEXT_CATEGORIES = ['Dashboards', 'Alerts', 'Services'] as const;
|
||||
@@ -33,54 +31,30 @@ export const CONTEXT_CATEGORY_SINGULAR: Record<ContextCategory, string> = {
|
||||
Services: 'Service',
|
||||
};
|
||||
|
||||
/** 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',
|
||||
/** 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',
|
||||
};
|
||||
|
||||
// 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;
|
||||
}
|
||||
/** 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,
|
||||
};
|
||||
|
||||
/**
|
||||
* Resolved copy + composer prefill for one render of the context picker's empty
|
||||
|
||||
@@ -1,22 +1,28 @@
|
||||
import cx from 'classnames';
|
||||
import type { ManualReferenceDTO } from '@signozhq/noz-client';
|
||||
import { Package } from '@signozhq/icons';
|
||||
|
||||
import { MessageContext } from 'api/ai-assistant/chat';
|
||||
|
||||
import { useVariant } from '../../VariantContext';
|
||||
import { getMentionPill } from '../ChatInput/contextPicker';
|
||||
import {
|
||||
AUTO_CONTEXT_ICONS,
|
||||
CONTEXT_TYPE_LABELS,
|
||||
} from '../ChatInput/contextPicker';
|
||||
import ContextPill from '../ChatInput/ContextPill/ContextPill';
|
||||
|
||||
import styles from './AddedContexts.module.scss';
|
||||
|
||||
interface AddedContextsProps {
|
||||
mentions: ManualReferenceDTO[];
|
||||
contexts: MessageContext[];
|
||||
}
|
||||
|
||||
/** The resources a message was sent with, by @-pick; the page it came from is left out. */
|
||||
export default function AddedContexts({
|
||||
mentions,
|
||||
contexts,
|
||||
}: AddedContextsProps): JSX.Element | null {
|
||||
const variant = useVariant();
|
||||
if (mentions.length === 0) {
|
||||
const picked = contexts.filter((ctx) => ctx.source === 'mention');
|
||||
if (picked.length === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -27,17 +33,15 @@ export default function AddedContexts({
|
||||
})}
|
||||
data-testid="ai-added-contexts"
|
||||
>
|
||||
{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}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{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 ?? ''}
|
||||
/>
|
||||
))}
|
||||
<span className={styles.note}>added to context</span>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -231,9 +231,7 @@ export default function MessageBubble({
|
||||
{isUser && <UserMessageActions message={message} />}
|
||||
</div>
|
||||
</div>
|
||||
{isUser && message.context?.mentions && (
|
||||
<AddedContexts mentions={message.context.mentions} />
|
||||
)}
|
||||
{isUser && message.contexts && <AddedContexts contexts={message.contexts} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -89,16 +89,15 @@ describe('MessageBubble — added contexts', () => {
|
||||
id: 'q-1',
|
||||
role: 'user',
|
||||
content: 'Why is checkout slow?',
|
||||
context: {
|
||||
page: { surface: 'log.explorer' },
|
||||
mentions: [
|
||||
{
|
||||
kind: 'dashboard',
|
||||
resourceId: 'dash-1',
|
||||
resourceName: 'Checkout latency',
|
||||
},
|
||||
],
|
||||
},
|
||||
contexts: [
|
||||
{
|
||||
source: 'mention',
|
||||
type: 'dashboard',
|
||||
resourceId: 'dash-1',
|
||||
resourceName: 'Checkout latency',
|
||||
},
|
||||
{ source: 'auto', type: 'logs_explorer' },
|
||||
],
|
||||
createdAt: 0,
|
||||
}}
|
||||
/>,
|
||||
|
||||
@@ -1,112 +0,0 @@
|
||||
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'));
|
||||
});
|
||||
});
|
||||
@@ -5,12 +5,9 @@ import { getEmptyStateChips } from 'api/ai-assistant/chat';
|
||||
import type { ChipDTO } from '@signozhq/noz-client';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
|
||||
import { useAssistantPageStore } from '../../pageContext/store/useAssistantPageStore';
|
||||
import { useAssistantSurface } from '../../pageContext/hooks/useAssistantSurface';
|
||||
import { EMPTY_STATE_CHIPS_FALLBACK } from './emptyStateChipsFallback';
|
||||
import { useResolvePageType } from 'hooks/aiAssistant/useResolvePageType';
|
||||
|
||||
// Unknown to the backend, so it gets the general chips, as V1's `page_type=other` did.
|
||||
const NO_SURFACE = 'other';
|
||||
import { EMPTY_STATE_CHIPS_FALLBACK } from './emptyStateChipsFallback';
|
||||
|
||||
interface UseEmptyStateChipsResult {
|
||||
chips: ChipDTO[];
|
||||
@@ -18,13 +15,11 @@ interface UseEmptyStateChipsResult {
|
||||
}
|
||||
|
||||
export function useEmptyStateChips(enabled: boolean): UseEmptyStateChipsResult {
|
||||
const surface = useAssistantSurface() ?? NO_SURFACE;
|
||||
const activeViewPath = useAssistantPageStore((state) => state.activeViewPath);
|
||||
const pageType = useResolvePageType();
|
||||
|
||||
// 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, surface, activeViewPath],
|
||||
({ signal }) => getEmptyStateChips({ surface, activeViewPath }, signal),
|
||||
[REACT_QUERY_KEY.AI_ASSISTANT_EMPTY_STATE_CHIPS, pageType],
|
||||
({ signal }) => getEmptyStateChips(pageType, signal),
|
||||
{ enabled },
|
||||
);
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ 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';
|
||||
|
||||
@@ -40,7 +39,7 @@ export default function ConfirmBlock({
|
||||
const { messageId } = useMessageContext();
|
||||
const answeredBlocks = useAIAssistantStore((s) => s.answeredBlocks);
|
||||
const markBlockAnswered = useAIAssistantStore((s) => s.markBlockAnswered);
|
||||
const sendMessage = useSendMessage();
|
||||
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
|
||||
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
|
||||
|
||||
// Durable answered state — survives re-renders/remounts
|
||||
|
||||
@@ -7,7 +7,6 @@ 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';
|
||||
|
||||
@@ -40,7 +39,7 @@ export default function InteractiveQuestion({
|
||||
const { messageId } = useMessageContext();
|
||||
const answeredBlocks = useAIAssistantStore((s) => s.answeredBlocks);
|
||||
const markBlockAnswered = useAIAssistantStore((s) => s.markBlockAnswered);
|
||||
const sendMessage = useSendMessage();
|
||||
const sendMessage = useAIAssistantStore((s) => s.sendMessage);
|
||||
const { threadId, page, mode } = useAIAssistantAnalyticsContext();
|
||||
|
||||
// Persist selected state locally only for the pending (not-yet-submitted) case
|
||||
|
||||
380
frontend/src/container/AIAssistant/getAutoContexts.ts
Normal file
380
frontend/src/container/AIAssistant/getAutoContexts.ts
Normal file
@@ -0,0 +1,380 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
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' },
|
||||
},
|
||||
],
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,25 +0,0 @@
|
||||
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],
|
||||
);
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
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,
|
||||
};
|
||||
@@ -1,37 +0,0 @@
|
||||
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']);
|
||||
});
|
||||
});
|
||||
@@ -1,69 +0,0 @@
|
||||
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([]);
|
||||
});
|
||||
});
|
||||
@@ -1,62 +0,0 @@
|
||||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,80 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,17 +0,0 @@
|
||||
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]);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
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]);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
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],
|
||||
);
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
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],
|
||||
);
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
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,
|
||||
}),
|
||||
],
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
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;
|
||||
});
|
||||
}
|
||||
@@ -1,330 +0,0 @@
|
||||
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',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
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 },
|
||||
}));
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,59 +0,0 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -1,58 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,216 +0,0 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,85 +0,0 @@
|
||||
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 },
|
||||
);
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
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);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
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',
|
||||
};
|
||||
@@ -1,27 +0,0 @@
|
||||
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 };
|
||||
}
|
||||
71
frontend/src/container/AIAssistant/resolvePageType.ts
Normal file
71
frontend/src/container/AIAssistant/resolvePageType.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,11 +1,12 @@
|
||||
import {
|
||||
ErrorCodeDTO,
|
||||
type MessageContextV2DTO,
|
||||
MessageContextDTOSource,
|
||||
MessageContextDTOType,
|
||||
MessageRoleDTO,
|
||||
type MessageTimeContextDTO,
|
||||
RetryActionDTO,
|
||||
} from '@signozhq/noz-client';
|
||||
import type {
|
||||
MessageContext,
|
||||
SSEEvent,
|
||||
ThreadDetailResponse,
|
||||
ThreadSummary,
|
||||
@@ -41,11 +42,6 @@ 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) {
|
||||
@@ -95,9 +91,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore
|
||||
.getState()
|
||||
.sendMessage('hello', { timeContext: TIME });
|
||||
await useAIAssistantStore.getState().sendMessage('hello');
|
||||
|
||||
const conv = useAIAssistantStore.getState().conversations['thread-1'];
|
||||
expect(conv.messages).toHaveLength(2);
|
||||
@@ -124,9 +118,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore
|
||||
.getState()
|
||||
.sendMessage('hello', { timeContext: TIME });
|
||||
await useAIAssistantStore.getState().sendMessage('hello');
|
||||
|
||||
// The retry succeeds this time.
|
||||
chat.streamEvents.mockReturnValueOnce(
|
||||
@@ -155,10 +147,6 @@ 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 () => {
|
||||
@@ -173,9 +161,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
const sending = useAIAssistantStore
|
||||
.getState()
|
||||
.sendMessage('hi', { timeContext: TIME });
|
||||
const sending = useAIAssistantStore.getState().sendMessage('hi');
|
||||
await jest.runAllTimersAsync();
|
||||
await sending;
|
||||
|
||||
@@ -198,7 +184,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore.getState().sendMessage('hi', { timeContext: TIME });
|
||||
await useAIAssistantStore.getState().sendMessage('hi');
|
||||
|
||||
expect(lastMessage('thread-3')).toMatchObject({
|
||||
isError: true,
|
||||
@@ -238,9 +224,7 @@ describe('useAIAssistantStore — streaming error handling', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
const sending = useAIAssistantStore
|
||||
.getState()
|
||||
.sendMessage('hi', { timeContext: TIME });
|
||||
const sending = useAIAssistantStore.getState().sendMessage('hi');
|
||||
await jest.runAllTimersAsync();
|
||||
await sending;
|
||||
|
||||
@@ -349,16 +333,12 @@ describe('useAIAssistantStore — resumed replies', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('useAIAssistantStore — message context', () => {
|
||||
const context: MessageContextV2DTO = {
|
||||
page: { surface: 'service.detail' },
|
||||
mentions: [
|
||||
{
|
||||
kind: 'dashboard',
|
||||
resourceId: 'dash-1',
|
||||
resourceName: 'Checkout latency',
|
||||
},
|
||||
],
|
||||
describe('useAIAssistantStore — message contexts', () => {
|
||||
const pickedDashboard: MessageContext = {
|
||||
source: 'mention',
|
||||
type: 'dashboard',
|
||||
resourceId: 'dash-1',
|
||||
resourceName: 'Checkout latency',
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -370,7 +350,7 @@ describe('useAIAssistantStore — message context', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('sends the V2 body and keeps the context a question was sent with', async () => {
|
||||
it('keeps the contexts a question was sent with', async () => {
|
||||
chat.createThread.mockResolvedValue('thread-1');
|
||||
chat.sendMessage.mockResolvedValue('exec-1');
|
||||
chat.streamEvents.mockReturnValueOnce(eventStream([]));
|
||||
@@ -378,18 +358,13 @@ describe('useAIAssistantStore — message context', () => {
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore
|
||||
.getState()
|
||||
.sendMessage('Why is checkout slow?', { timeContext: TIME, context });
|
||||
.sendMessage('Why is checkout slow?', undefined, [pickedDashboard]);
|
||||
|
||||
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].context).toStrictEqual(context);
|
||||
expect(conv.messages[0].contexts).toStrictEqual([pickedDashboard]);
|
||||
});
|
||||
|
||||
it('reopens a chat with the context its questions were sent with', async () => {
|
||||
it('reopens a chat with the contexts its questions were sent with', async () => {
|
||||
const detail: ThreadDetailResponse = {
|
||||
threadId: 'thread-1',
|
||||
createdAt: '2026-11-17T00:00:00Z',
|
||||
@@ -399,8 +374,14 @@ describe('useAIAssistantStore — message context', () => {
|
||||
messageId: 'q-1',
|
||||
role: MessageRoleDTO.user,
|
||||
content: 'Why is checkout slow?',
|
||||
context,
|
||||
timeContext: TIME,
|
||||
contexts: [
|
||||
{
|
||||
source: MessageContextDTOSource.mention,
|
||||
type: MessageContextDTOType.dashboard,
|
||||
resourceId: 'dash-1',
|
||||
resourceName: 'Checkout latency',
|
||||
},
|
||||
],
|
||||
createdAt: '2026-11-17T00:00:00Z',
|
||||
updatedAt: '2026-11-17T00:00:00Z',
|
||||
},
|
||||
@@ -410,7 +391,7 @@ describe('useAIAssistantStore — message context', () => {
|
||||
|
||||
await useAIAssistantStore.getState().loadThread('thread-1');
|
||||
|
||||
expect(lastMessage('thread-1').context).toStrictEqual(context);
|
||||
expect(lastMessage('thread-1').contexts).toStrictEqual([pickedDashboard]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -450,7 +431,7 @@ describe('useAIAssistantStore — unread replies', () => {
|
||||
);
|
||||
|
||||
useAIAssistantStore.getState().startNewConversation();
|
||||
await useAIAssistantStore.getState().sendMessage('hi', { timeContext: TIME });
|
||||
await useAIAssistantStore.getState().sendMessage('hi');
|
||||
|
||||
expect(useAIAssistantStore.getState().unreadReplyIds).toStrictEqual([
|
||||
'thread-reply',
|
||||
|
||||
@@ -6,7 +6,7 @@ import { immer } from 'zustand/middleware/immer';
|
||||
|
||||
import type {
|
||||
MessageActionDTO,
|
||||
MessageSummaryV2DTOBlocksAnyOfItem,
|
||||
MessageSummaryDTOBlocksAnyOfItem,
|
||||
} from '@signozhq/noz-client';
|
||||
import { RetryActionDTO } from '@signozhq/noz-client';
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
createThread,
|
||||
getThreadDetail,
|
||||
listThreads,
|
||||
MessageContext,
|
||||
MessageSummary,
|
||||
regenerateMessage,
|
||||
rejectExecution,
|
||||
@@ -31,9 +32,9 @@ import {
|
||||
ConversationStreamState,
|
||||
FeedbackRating,
|
||||
Message,
|
||||
MessageAttachment,
|
||||
MessageBlock,
|
||||
MessageRole,
|
||||
SendMessageOptions,
|
||||
} from '../types';
|
||||
import {
|
||||
resolveAssistantError,
|
||||
@@ -677,7 +678,11 @@ export interface AIAssistantStore {
|
||||
restoreConversation: (id: string) => void;
|
||||
renameConversation: (id: string, title: string) => Promise<void>;
|
||||
markBlockAnswered: (messageId: string, answer: string) => void;
|
||||
sendMessage: (text: string, options: SendMessageOptions) => Promise<void>;
|
||||
sendMessage: (
|
||||
text: string,
|
||||
attachments?: MessageAttachment[],
|
||||
contexts?: MessageContext[],
|
||||
) => Promise<void>;
|
||||
approveAction: (conversationId: string, approvalId: string) => Promise<void>;
|
||||
rejectAction: (conversationId: string, approvalId: string) => Promise<void>;
|
||||
submitClarification: (
|
||||
@@ -709,7 +714,7 @@ export interface AIAssistantStore {
|
||||
* the UI renders against.
|
||||
*/
|
||||
function toBlocks(
|
||||
raw: MessageSummaryV2DTOBlocksAnyOfItem[] | null | undefined,
|
||||
raw: MessageSummaryDTOBlocksAnyOfItem[] | null | undefined,
|
||||
): MessageBlock[] | undefined {
|
||||
if (!raw || raw.length === 0) {
|
||||
return undefined;
|
||||
@@ -775,7 +780,7 @@ function toMessage(m: MessageSummary): Message {
|
||||
id: m.messageId,
|
||||
role: m.role as MessageRole,
|
||||
content,
|
||||
context: m.context ?? undefined,
|
||||
contexts: m.contexts ?? undefined,
|
||||
blocks: toBlocks(m.blocks),
|
||||
actions: m.actions ?? undefined,
|
||||
feedbackRating: m.feedbackRating ?? undefined,
|
||||
@@ -1220,7 +1225,8 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
sendMessage: async (
|
||||
text: string,
|
||||
{ timeContext, attachments, context }: SendMessageOptions,
|
||||
attachments?: MessageAttachment[],
|
||||
contexts?: MessageContext[],
|
||||
): Promise<void> => {
|
||||
const convId = get().activeConversationId;
|
||||
if (!convId || !get().conversations[convId]) {
|
||||
@@ -1251,7 +1257,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
|
||||
role: 'user',
|
||||
content: text,
|
||||
attachments,
|
||||
context,
|
||||
contexts,
|
||||
createdAt: Date.now(),
|
||||
};
|
||||
|
||||
@@ -1301,12 +1307,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
|
||||
const tid = threadId;
|
||||
await streamWithRetry(
|
||||
targetConvId,
|
||||
() =>
|
||||
sendMessageToThread(tid, {
|
||||
content: text,
|
||||
timeContext,
|
||||
...(context ? { context } : {}),
|
||||
}),
|
||||
() => sendMessageToThread(tid, text, contexts),
|
||||
set,
|
||||
);
|
||||
|
||||
|
||||
@@ -18,10 +18,9 @@ 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 {
|
||||
@@ -31,14 +30,7 @@ export interface MessageAttachment {
|
||||
dataUrl: string;
|
||||
}
|
||||
|
||||
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. */
|
||||
/** Narrowed from DTO `MessageSummaryDTO.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. */
|
||||
@@ -79,7 +71,7 @@ export interface ToolCallBlock {
|
||||
export type MessageBlock = TextBlock | ThinkingBlock | ToolCallBlock;
|
||||
|
||||
/**
|
||||
* UI shape for an assistant or user message. Differs from `MessageSummaryV2DTO`:
|
||||
* UI shape for an assistant or user message. Differs from `MessageSummaryDTO`:
|
||||
* • `id` instead of `messageId`
|
||||
* • `createdAt` is a millisecond epoch instead of ISO string
|
||||
* • `blocks` is the typed discriminated union above
|
||||
@@ -91,7 +83,7 @@ export interface Message {
|
||||
content: string;
|
||||
attachments?: MessageAttachment[];
|
||||
/** What a user message was sent with: its @-picked resources and the page it came from. */
|
||||
context?: MessageContextV2DTO;
|
||||
contexts?: MessageContext[];
|
||||
/** Ordered content blocks for structured rendering of assistant replies. */
|
||||
blocks?: MessageBlock[];
|
||||
/** Suggested follow-up actions returned by the assistant (final message only). */
|
||||
@@ -119,7 +111,7 @@ export interface Message {
|
||||
}
|
||||
|
||||
/**
|
||||
* UI shape for a conversation. Differs from `ThreadDetailResponseV2DTO`:
|
||||
* UI shape for a conversation. Differs from `ThreadDetailResponseDTO`:
|
||||
* • UI-minted `id` (assigned before the server returns a `threadId`)
|
||||
* • `createdAt`/`updatedAt` are ms epochs
|
||||
* • `messages` is the typed `Message[]` above
|
||||
|
||||
@@ -23,7 +23,6 @@ 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';
|
||||
|
||||
@@ -33,7 +32,6 @@ 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();
|
||||
|
||||
@@ -1,71 +0,0 @@
|
||||
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 });
|
||||
});
|
||||
});
|
||||
@@ -1,38 +0,0 @@
|
||||
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,
|
||||
},
|
||||
],
|
||||
},
|
||||
}));
|
||||
}
|
||||
@@ -1,51 +1,3 @@
|
||||
export const MOCK_USE_QUERIES_DATA = [
|
||||
{
|
||||
isLoading: false,
|
||||
isError: false,
|
||||
error: null,
|
||||
data: {
|
||||
statusCode: 200,
|
||||
payload: [
|
||||
{
|
||||
exceptionType: '*errors.errorString',
|
||||
exceptionMessage: 'redis timeout',
|
||||
exceptionCount: 2510,
|
||||
lastSeen: '2025-04-14T18:27:57.797616374Z',
|
||||
firstSeen: '2025-04-14T17:58:00.262775497Z',
|
||||
serviceName: 'redis-manual',
|
||||
groupID: '511b9c91a92b9c5166ecb77235f5743b',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
status: 'success',
|
||||
isLoading: false,
|
||||
isSuccess: true,
|
||||
isError: false,
|
||||
isIdle: false,
|
||||
data: {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
payload: 525,
|
||||
},
|
||||
dataUpdatedAt: 1744661020341,
|
||||
error: null,
|
||||
errorUpdatedAt: 0,
|
||||
failureCount: 0,
|
||||
errorUpdateCount: 0,
|
||||
isFetched: true,
|
||||
isFetchedAfterMount: true,
|
||||
isFetching: false,
|
||||
isRefetching: false,
|
||||
isLoadingError: false,
|
||||
isPlaceholderData: false,
|
||||
isPreviousData: false,
|
||||
isRefetchError: false,
|
||||
isStale: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const INIT_URL_WITH_COMMON_QUERY =
|
||||
'/exceptions?compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522dataSource%2522%253A%2522traces%2522%252C%2522queryName%2522%253A%2522A%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522id%2522%253A%2522----resource--false%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522key%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522type%2522%253A%2522resource%2522%252C%2522isJSON%2522%253Afalse%257D%252C%2522timeAggregation%2522%253A%2522rate%2522%252C%2522spaceAggregation%2522%253A%2522sum%2522%252C%2522functions%2522%253A%255B%255D%252C%2522filters%2522%253A%257B%2522items%2522%253A%255B%257B%2522id%2522%253A%2522db118ac7-9313-4adb-963f-f31b5b32c496%2522%252C%2522op%2522%253A%2522in%2522%252C%2522key%2522%253A%257B%2522key%2522%253A%2522deployment.environment%2522%252C%2522dataType%2522%253A%2522string%2522%252C%2522type%2522%253A%2522resource%2522%252C%2522isColumn%2522%253Afalse%252C%2522isJSON%2522%253Afalse%257D%252C%2522value%2522%253A%2522mq-kafka%2522%257D%255D%252C%2522op%2522%253A%2522AND%2522%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522stepInterval%2522%253A60%252C%2522having%2522%253A%255B%255D%252C%2522limit%2522%253Anull%252C%2522orderBy%2522%253A%255B%255D%252C%2522groupBy%2522%253A%255B%255D%252C%2522legend%2522%253A%2522%2522%252C%2522reduceTo%2522%253A%2522avg%2522%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%252C%2522promql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522query%2522%253A%2522%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%257D%255D%252C%2522clickhouse_sql%2522%253A%255B%257B%2522name%2522%253A%2522A%2522%252C%2522legend%2522%253A%2522%2522%252C%2522disabled%2522%253Afalse%252C%2522query%2522%253A%2522%2522%257D%255D%252C%2522id%2522%253A%2522dd576d04-0822-476d-b0c2-807a7af2e5e7%2522%257D';
|
||||
|
||||
|
||||
@@ -50,16 +50,6 @@
|
||||
font-family: var(--code-base-500-font-family);
|
||||
}
|
||||
|
||||
.radio-button {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding-top: var(--padding-1);
|
||||
border: 1px solid var(--l1-border);
|
||||
background: var(--l3-background);
|
||||
box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
|
||||
.round-metric-tag {
|
||||
display: inline-flex;
|
||||
padding: 2px 8px;
|
||||
@@ -783,80 +773,5 @@
|
||||
gap: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.no-dependent-services-message-container {
|
||||
height: 30vh;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
|
||||
.no-dependent-services-message-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
|
||||
width: fit-content;
|
||||
padding: 24px;
|
||||
}
|
||||
|
||||
.no-dependent-services-message {
|
||||
margin-top: 8px;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.end-point-details-zero-state-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
height: 100%;
|
||||
|
||||
.end-point-details-zero-state-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
gap: 4px;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.end-point-details-zero-state-content-wrapper {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: flex-start;
|
||||
gap: 12px;
|
||||
|
||||
.end-point-details-zero-state-text-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
|
||||
.title {
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.description {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.ant-select {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-select-item,
|
||||
.ant-select-item-option-content {
|
||||
flex: auto;
|
||||
white-space: normal;
|
||||
overflow-wrap: break-word;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,13 +69,6 @@ jest.mock('antd', () => {
|
||||
))}
|
||||
</div>
|
||||
)),
|
||||
Typography: {
|
||||
Text: jest
|
||||
.fn()
|
||||
.mockImplementation(({ children }) => (
|
||||
<div data-testid="typography-text">{children}</div>
|
||||
)),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -130,13 +130,6 @@ jest.mock('antd', () => {
|
||||
{children}
|
||||
</div>
|
||||
)),
|
||||
Typography: {
|
||||
Text: jest
|
||||
.fn()
|
||||
.mockImplementation(({ children }) => (
|
||||
<div data-testid="typography-text">{children}</div>
|
||||
)),
|
||||
},
|
||||
Button: {
|
||||
...originalModule.Button,
|
||||
Group: jest.fn().mockImplementation(({ children, className }) => (
|
||||
|
||||
@@ -46,13 +46,6 @@ jest.mock('antd', () => {
|
||||
)}
|
||||
</div>
|
||||
)),
|
||||
Typography: {
|
||||
Text: jest.fn().mockImplementation(({ children, className }) => (
|
||||
<div data-testid="typography-text" className={className}>
|
||||
{children}
|
||||
</div>
|
||||
)),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -1,16 +1,3 @@
|
||||
import { domainNameKey } from './constants';
|
||||
|
||||
export interface APIMonitoringResponseRow {
|
||||
data: {
|
||||
endpoints: number | string;
|
||||
error_rate: number | string;
|
||||
lastseen: number | string;
|
||||
[domainNameKey]: string;
|
||||
p99: number | string;
|
||||
rps: number | string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface APIMonitoringResponseColumn {
|
||||
name: string;
|
||||
signal: string;
|
||||
@@ -22,12 +9,6 @@ export interface APIMonitoringResponseColumn {
|
||||
columnType: string;
|
||||
}
|
||||
|
||||
export interface EndPointsResponseRow {
|
||||
data: {
|
||||
[key: string]: string | number | undefined;
|
||||
};
|
||||
}
|
||||
|
||||
export interface APIDomainsRowData {
|
||||
key: string;
|
||||
domainName: string;
|
||||
|
||||
@@ -1,32 +1,24 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { TableColumnType as ColumnType, Tooltip } from 'antd';
|
||||
import { Progress } from '@signozhq/ui/progress';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { combineInitialAndUserExpression } from 'components/QueryBuilderV2/QueryV2/QuerySearch/utils';
|
||||
import { formatValueForExpression } from 'components/QueryBuilderV2/utils';
|
||||
import {
|
||||
FiltersType,
|
||||
IQuickFiltersConfig,
|
||||
} from 'components/QuickFilters/types';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { GraphClickMetaData } from 'container/WidgetCard/hooks/useNavigateToExplorerPages';
|
||||
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
|
||||
import { convertNanoToMilliseconds } from 'container/MetricsExplorer/Summary/utils';
|
||||
import dayjs from 'dayjs';
|
||||
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
|
||||
import { cloneDeep } from 'lodash-es';
|
||||
import { ArrowUpDown, ChevronDown, ChevronRight, Info } from '@signozhq/icons';
|
||||
import { ArrowUpDown, Info } from '@signozhq/icons';
|
||||
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
|
||||
import { Widgets } from 'types/api/widgets/widget';
|
||||
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
|
||||
import {
|
||||
BaseAutocompleteData,
|
||||
DataTypes,
|
||||
} from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import {
|
||||
IBuilderQuery,
|
||||
OrderByPayload,
|
||||
TagFilterItem,
|
||||
} from 'types/api/queryBuilder/queryBuilderData';
|
||||
import {
|
||||
@@ -41,11 +33,7 @@ import { v4 } from 'uuid';
|
||||
|
||||
import { domainNameKey } from './constants';
|
||||
import { SPAN_ATTRIBUTES } from './Explorer/Domains/DomainDetails/constants';
|
||||
import {
|
||||
APIDomainsRowData,
|
||||
APIMonitoringResponseColumn,
|
||||
EndPointsResponseRow,
|
||||
} from './types';
|
||||
import { APIDomainsRowData, APIMonitoringResponseColumn } from './types';
|
||||
|
||||
function metricProgressColor(
|
||||
percent: number,
|
||||
@@ -91,40 +79,6 @@ export const getDomainScopeExpression = (
|
||||
.filter(Boolean)
|
||||
.join(' AND ');
|
||||
|
||||
export const ApiMonitoringQuickFiltersConfig: IQuickFiltersConfig[] = [
|
||||
{
|
||||
type: FiltersType.CHECKBOX,
|
||||
title: 'Environment',
|
||||
|
||||
attributeKey: {
|
||||
key: 'deployment.environment',
|
||||
dataType: DataTypes.String,
|
||||
type: 'resource',
|
||||
},
|
||||
defaultOpen: true,
|
||||
},
|
||||
{
|
||||
type: FiltersType.CHECKBOX,
|
||||
title: 'Service Name',
|
||||
attributeKey: {
|
||||
key: 'service.name',
|
||||
dataType: DataTypes.String,
|
||||
type: 'resource',
|
||||
},
|
||||
defaultOpen: true,
|
||||
},
|
||||
{
|
||||
type: FiltersType.CHECKBOX,
|
||||
title: 'RPC Method',
|
||||
attributeKey: {
|
||||
key: 'rpc.method',
|
||||
dataType: DataTypes.String,
|
||||
type: 'tag',
|
||||
},
|
||||
defaultOpen: true,
|
||||
},
|
||||
];
|
||||
|
||||
export const getLastUsedRelativeTime = (lastRefresh: number): string => {
|
||||
const currentTime = dayjs();
|
||||
|
||||
@@ -571,258 +525,6 @@ const defaultGroupBy = [
|
||||
// },
|
||||
];
|
||||
|
||||
export const getEndPointsQueryPayload = (
|
||||
groupBy: BaseAutocompleteData[],
|
||||
domainName: string,
|
||||
start: number,
|
||||
end: number,
|
||||
): GetQueryResultsProps[] => {
|
||||
const isGroupedByAttribute = groupBy.length > 0;
|
||||
return [
|
||||
{
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
graphType: PANEL_TYPES.TABLE,
|
||||
query: {
|
||||
builder: {
|
||||
queryData: [
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.String,
|
||||
key: 'span_id',
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count',
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'A',
|
||||
filters: {
|
||||
items: [
|
||||
{
|
||||
id: 'ec316e57',
|
||||
key: {
|
||||
dataType: DataTypes.String,
|
||||
key: SPAN_ATTRIBUTES.SERVER_NAME,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: domainName,
|
||||
},
|
||||
{
|
||||
id: '212678b9',
|
||||
key: {
|
||||
key: 'kind_string',
|
||||
dataType: DataTypes.String,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: 'Client',
|
||||
},
|
||||
],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
|
||||
having: [],
|
||||
legend: '',
|
||||
limit: 1000,
|
||||
orderBy: [],
|
||||
queryName: 'A',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: 60,
|
||||
timeAggregation: 'count',
|
||||
},
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.Float64,
|
||||
key: 'duration_nano',
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'p99',
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'B',
|
||||
filters: {
|
||||
items: [
|
||||
{
|
||||
id: '46d57857',
|
||||
key: {
|
||||
dataType: DataTypes.String,
|
||||
key: SPAN_ATTRIBUTES.SERVER_NAME,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: domainName,
|
||||
},
|
||||
{
|
||||
id: '212678b9',
|
||||
key: {
|
||||
key: 'kind_string',
|
||||
dataType: DataTypes.String,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: 'Client',
|
||||
},
|
||||
],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
|
||||
having: [],
|
||||
legend: '',
|
||||
limit: 1000,
|
||||
orderBy: [],
|
||||
queryName: 'B',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: 60,
|
||||
timeAggregation: 'p99',
|
||||
},
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.String,
|
||||
id: 'timestamp------false',
|
||||
key: 'timestamp',
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'max',
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: false,
|
||||
expression: 'C',
|
||||
filters: {
|
||||
items: [
|
||||
{
|
||||
id: '4a237616',
|
||||
key: {
|
||||
dataType: DataTypes.String,
|
||||
key: SPAN_ATTRIBUTES.SERVER_NAME,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: domainName,
|
||||
},
|
||||
{
|
||||
id: '212678b9',
|
||||
key: {
|
||||
key: 'kind_string',
|
||||
dataType: DataTypes.String,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: 'Client',
|
||||
},
|
||||
],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
|
||||
having: [],
|
||||
legend: '',
|
||||
limit: 1000,
|
||||
orderBy: [],
|
||||
queryName: 'C',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: 60,
|
||||
timeAggregation: 'max',
|
||||
},
|
||||
{
|
||||
aggregateAttribute: {
|
||||
dataType: DataTypes.String,
|
||||
key: 'span_id',
|
||||
type: '',
|
||||
},
|
||||
aggregateOperator: 'count',
|
||||
dataSource: DataSource.TRACES,
|
||||
disabled: true,
|
||||
expression: 'D',
|
||||
filters: {
|
||||
items: [
|
||||
{
|
||||
id: 'f162de1e',
|
||||
key: {
|
||||
dataType: DataTypes.String,
|
||||
key: SPAN_ATTRIBUTES.SERVER_NAME,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: domainName,
|
||||
},
|
||||
{
|
||||
id: '3df0ac1d',
|
||||
key: {
|
||||
dataType: DataTypes.bool,
|
||||
key: 'has_error',
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: 'true',
|
||||
},
|
||||
{
|
||||
id: '212678b9',
|
||||
key: {
|
||||
key: 'kind_string',
|
||||
dataType: DataTypes.String,
|
||||
type: '',
|
||||
},
|
||||
op: '=',
|
||||
value: 'Client',
|
||||
},
|
||||
],
|
||||
op: 'AND',
|
||||
},
|
||||
functions: [],
|
||||
groupBy: isGroupedByAttribute ? groupBy : defaultGroupBy,
|
||||
having: [],
|
||||
legend: '',
|
||||
limit: 1000,
|
||||
orderBy: [],
|
||||
queryName: 'D',
|
||||
reduceTo: ReduceOperators.AVG,
|
||||
spaceAggregation: 'sum',
|
||||
stepInterval: 60,
|
||||
timeAggregation: 'count',
|
||||
},
|
||||
],
|
||||
queryFormulas: [
|
||||
{
|
||||
queryName: 'F1',
|
||||
expression: '(D/A)*100',
|
||||
disabled: false,
|
||||
legend: 'error percentage',
|
||||
},
|
||||
],
|
||||
queryTraceOperator: [],
|
||||
},
|
||||
clickhouse_sql: [
|
||||
{
|
||||
disabled: false,
|
||||
legend: '',
|
||||
name: 'A',
|
||||
query: '',
|
||||
},
|
||||
],
|
||||
id: '315b15fa-ff0c-442f-89f8-2bf4fb1af2f2',
|
||||
promql: [
|
||||
{
|
||||
disabled: false,
|
||||
legend: '',
|
||||
name: 'A',
|
||||
query: '',
|
||||
},
|
||||
],
|
||||
queryType: EQueryType.QUERY_BUILDER,
|
||||
},
|
||||
variables: {},
|
||||
formatForWeb: true,
|
||||
start,
|
||||
end,
|
||||
step: 60,
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
function buildFilterExpression(
|
||||
domainName: string,
|
||||
filterExpression: string,
|
||||
@@ -907,16 +609,6 @@ export const getTopErrorsQueryPayload = (
|
||||
};
|
||||
};
|
||||
|
||||
export interface EndPointsTableRowData {
|
||||
key: string;
|
||||
endpointName: string;
|
||||
callCount: number | string;
|
||||
latency: number | string;
|
||||
errorRate: number | string;
|
||||
lastUsed: string | number;
|
||||
groupedByMeta?: Record<string, string | number>;
|
||||
}
|
||||
|
||||
export const extractPortAndEndpoint = (
|
||||
url: string,
|
||||
): { port: string; endpoint: string } => {
|
||||
@@ -937,258 +629,6 @@ export const extractPortAndEndpoint = (
|
||||
}
|
||||
};
|
||||
|
||||
export const getEndPointsColumnsConfig = (
|
||||
isGroupedByAttribute: boolean,
|
||||
expandedRowKeys: React.Key[],
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
): ColumnType<EndPointsTableRowData>[] => [
|
||||
{
|
||||
title: (
|
||||
<div className="endpoint-name-header">
|
||||
{isGroupedByAttribute ? 'Endpoint group' : 'Endpoint'}
|
||||
</div>
|
||||
),
|
||||
dataIndex: 'endpointName',
|
||||
key: 'endpointName',
|
||||
width: 180,
|
||||
ellipsis: true,
|
||||
sorter: false,
|
||||
className: 'column',
|
||||
render: (text: string, record: EndPointsTableRowData): React.ReactNode => {
|
||||
const endPointName = isGroupedByAttribute
|
||||
? text
|
||||
: extractPortAndEndpoint(record.endpointName).endpoint;
|
||||
return (
|
||||
<div className="endpoint-name-value">
|
||||
{((): React.ReactNode => {
|
||||
if (!isGroupedByAttribute) {
|
||||
return null;
|
||||
}
|
||||
return expandedRowKeys.includes(record.key) ? (
|
||||
<ChevronDown size={14} />
|
||||
) : (
|
||||
<ChevronRight size={14} />
|
||||
);
|
||||
})()}
|
||||
{isGroupedByAttribute
|
||||
? text.split(',').map((value) => (
|
||||
<Badge
|
||||
textTransform="none"
|
||||
variant="solid"
|
||||
key={value}
|
||||
color="secondary"
|
||||
>
|
||||
{value === '' ? '<no-value>' : value}
|
||||
</Badge>
|
||||
))
|
||||
: endPointName}
|
||||
</div>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
title: <div className="column-header">Port</div>,
|
||||
dataIndex: 'port',
|
||||
key: 'port',
|
||||
width: 180,
|
||||
ellipsis: true,
|
||||
sorter: false,
|
||||
align: 'right',
|
||||
className: `column`,
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<div className="column-header">
|
||||
Num of calls <ArrowUpDown size={14} />
|
||||
</div>
|
||||
),
|
||||
dataIndex: 'callCount',
|
||||
key: 'callCount',
|
||||
width: 180,
|
||||
ellipsis: true,
|
||||
align: 'right',
|
||||
className: `column`,
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<div>
|
||||
Error <span className="round-metric-tag">%</span>
|
||||
</div>
|
||||
),
|
||||
dataIndex: 'errorRate',
|
||||
key: 'errorRate',
|
||||
width: 120,
|
||||
sorter: true,
|
||||
align: 'right',
|
||||
className: `column`,
|
||||
render: (errorRate: number | string): React.ReactNode => (
|
||||
<div className="progress-bar error-rate">
|
||||
<Progress
|
||||
percent={Number(
|
||||
(
|
||||
(errorRate === 'n/a' || errorRate === '-' ? 0 : errorRate) as number
|
||||
).toFixed(1),
|
||||
)}
|
||||
showInfo
|
||||
color={metricProgressColor(
|
||||
Number(
|
||||
(
|
||||
(errorRate === 'n/a' || errorRate === '-' ? 0 : errorRate) as number
|
||||
).toFixed(1),
|
||||
),
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<div>
|
||||
Latency <span className="round-metric-tag">ms</span>
|
||||
</div>
|
||||
),
|
||||
dataIndex: 'latency',
|
||||
key: 'latency',
|
||||
width: 120,
|
||||
sorter: true,
|
||||
align: 'right',
|
||||
className: `column`,
|
||||
},
|
||||
{
|
||||
title: <div>Last used</div>,
|
||||
dataIndex: 'lastUsed',
|
||||
key: 'lastUsed',
|
||||
width: 120,
|
||||
sorter: true,
|
||||
align: 'right',
|
||||
className: `column`,
|
||||
// eslint-disable-next-line sonarjs/no-identical-functions
|
||||
render: (lastUsed: string): string =>
|
||||
lastUsed === 'n/a' || lastUsed === '-'
|
||||
? '-'
|
||||
: getLastUsedRelativeTime(new Date(lastUsed).getTime()),
|
||||
},
|
||||
];
|
||||
|
||||
export const formatEndPointsDataForTable = (
|
||||
data: EndPointsResponseRow[] | undefined,
|
||||
groupBy: BaseAutocompleteData[],
|
||||
orderBy?: OrderByPayload | null,
|
||||
// eslint-disable-next-line sonarjs/cognitive-complexity
|
||||
): EndPointsTableRowData[] => {
|
||||
if (!data) {
|
||||
return [];
|
||||
}
|
||||
const isGroupedByAttribute = groupBy.length > 0;
|
||||
|
||||
let formattedData: EndPointsTableRowData[] = [];
|
||||
|
||||
if (!isGroupedByAttribute) {
|
||||
formattedData = data?.map((endpoint) => {
|
||||
const { port } = extractPortAndEndpoint(
|
||||
(endpoint.data[SPAN_ATTRIBUTES.HTTP_URL] as string) || '',
|
||||
);
|
||||
return {
|
||||
key: v4(),
|
||||
endpointName: (endpoint.data[SPAN_ATTRIBUTES.HTTP_URL] as string) || '-',
|
||||
port,
|
||||
callCount:
|
||||
endpoint.data.A === 'n/a' || endpoint.data.A === undefined
|
||||
? '-'
|
||||
: endpoint.data.A,
|
||||
latency:
|
||||
endpoint.data.B === 'n/a' || endpoint.data.B === undefined
|
||||
? '-'
|
||||
: Math.round(Number(endpoint.data.B) / 1000000), // Convert from nanoseconds to milliseconds
|
||||
lastUsed:
|
||||
endpoint.data.C === 'n/a' || endpoint.data.C === undefined
|
||||
? '-'
|
||||
: new Date(Math.floor(Number(endpoint.data.C) / 1000000)).toISOString(), // Convert from nanoseconds to milliseconds
|
||||
|
||||
errorRate:
|
||||
endpoint.data.F1 === undefined || endpoint.data.F1 === 'n/a'
|
||||
? 0
|
||||
: Number(endpoint.data.F1),
|
||||
};
|
||||
});
|
||||
} else {
|
||||
const groupedByAttributeData = groupBy.map((attribute) => attribute.key);
|
||||
|
||||
formattedData = data?.map((endpoint) => {
|
||||
const newEndpointName = groupedByAttributeData
|
||||
.map((attribute) => endpoint.data[attribute])
|
||||
.join(',');
|
||||
return {
|
||||
key: v4(),
|
||||
endpointName: newEndpointName,
|
||||
callCount:
|
||||
endpoint.data.A === 'n/a' || endpoint.data.A === undefined
|
||||
? '-'
|
||||
: endpoint.data.A,
|
||||
latency:
|
||||
endpoint.data.B === 'n/a' || endpoint.data.B === undefined
|
||||
? '-'
|
||||
: Math.round(Number(endpoint.data.B) / 1000000), // Convert from nanoseconds to milliseconds
|
||||
lastUsed:
|
||||
endpoint.data.C === 'n/a' || endpoint.data.C === undefined
|
||||
? '-'
|
||||
: getLastUsedRelativeTime(Math.floor(Number(endpoint.data.C) / 1000000)), // Convert from nanoseconds to milliseconds
|
||||
errorRate:
|
||||
endpoint.data.D === 'n/a' || endpoint.data.D === undefined
|
||||
? 0
|
||||
: Number(endpoint.data.D),
|
||||
groupedByMeta: groupedByAttributeData.reduce(
|
||||
(acc, attribute) => {
|
||||
acc[attribute] = endpoint.data[attribute] || '';
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string | number>,
|
||||
),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// Apply sorting if orderBy is provided
|
||||
if (orderBy) {
|
||||
formattedData.sort((a, b) => {
|
||||
let valueA: number | string = a[
|
||||
orderBy.columnName as keyof EndPointsTableRowData
|
||||
] as number | string;
|
||||
let valueB: number | string = b[
|
||||
orderBy.columnName as keyof EndPointsTableRowData
|
||||
] as number | string;
|
||||
|
||||
// Handle special cases for each column type
|
||||
if (
|
||||
orderBy.columnName === 'callCount' ||
|
||||
orderBy.columnName === 'latency' ||
|
||||
orderBy.columnName === 'errorRate'
|
||||
) {
|
||||
valueA = valueA === '-' || valueA === 'n/a' ? 0 : Number(valueA);
|
||||
valueB = valueB === '-' || valueB === 'n/a' ? 0 : Number(valueB);
|
||||
} else if (orderBy.columnName === 'lastUsed') {
|
||||
// confirm once the implication of this
|
||||
valueA =
|
||||
valueA === '-' || valueA === 'n/a'
|
||||
? new Date(0).getTime()
|
||||
: new Date(valueA as string).getTime();
|
||||
valueB =
|
||||
valueB === '-' || valueB === 'n/a'
|
||||
? new Date(0).getTime()
|
||||
: new Date(valueB as string).getTime();
|
||||
}
|
||||
|
||||
// Apply sort direction
|
||||
if (orderBy.order === 'asc') {
|
||||
return valueA > valueB ? 1 : -1;
|
||||
}
|
||||
return valueA < valueB ? 1 : -1;
|
||||
});
|
||||
}
|
||||
|
||||
return formattedData;
|
||||
};
|
||||
|
||||
export type TopErrorsResponseRow = ScalarData;
|
||||
|
||||
export interface TopErrorsTableRowData {
|
||||
@@ -1333,37 +773,6 @@ export const getTopErrorsColumnsConfig =
|
||||
},
|
||||
];
|
||||
|
||||
export const createFiltersForSelectedRowData = (
|
||||
selectedRowData: EndPointsTableRowData,
|
||||
currentFilters?: IBuilderQuery['filters'],
|
||||
): IBuilderQuery['filters'] => {
|
||||
const baseFilters: IBuilderQuery['filters'] = {
|
||||
items: [...(currentFilters?.items || [])],
|
||||
op: 'and',
|
||||
};
|
||||
|
||||
if (!selectedRowData) {
|
||||
return baseFilters;
|
||||
}
|
||||
|
||||
const { groupedByMeta = {} } = selectedRowData;
|
||||
|
||||
// Replace for...of with Object.keys().map()
|
||||
baseFilters.items.push(
|
||||
...Object.keys(groupedByMeta).map((key) => ({
|
||||
key: {
|
||||
key,
|
||||
type: null,
|
||||
},
|
||||
op: '=',
|
||||
value: groupedByMeta[key] || '',
|
||||
id: key,
|
||||
})),
|
||||
);
|
||||
|
||||
return baseFilters;
|
||||
};
|
||||
|
||||
// First query payload for endpoint metrics
|
||||
// Second query payload for endpoint status code table
|
||||
// Third query payload for endpoint dependant services
|
||||
@@ -2465,21 +1874,6 @@ export const dependentServicesColumns: ColumnType<DependentServicesData>[] = [
|
||||
},
|
||||
];
|
||||
|
||||
export const getFormattedChartData = (
|
||||
data: MetricRangePayloadProps,
|
||||
newLegendArray: string[],
|
||||
): MetricRangePayloadProps => {
|
||||
const result = cloneDeep(data);
|
||||
if (result?.data?.result) {
|
||||
result.data.result = result?.data?.result?.map((series, index) => ({
|
||||
...series,
|
||||
legend: newLegendArray[index],
|
||||
}));
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const getStatusCodeClass = (statusCode: string): string => {
|
||||
const code = parseInt(statusCode, 10);
|
||||
|
||||
@@ -3100,40 +2494,6 @@ const getStartAndEndStatusCode = (
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates filter items for bar chart based on group by fields and request data
|
||||
* Used specifically for filtering status code ranges in bar charts
|
||||
* @param groupBy Array of group by fields to create filters for
|
||||
* @param requestData Data from graph click containing values to filter on
|
||||
* @returns Array of TagFilterItems with >= and < operators for status code ranges
|
||||
*/
|
||||
export const createGroupByFiltersForBarChart = (
|
||||
groupBy: BaseAutocompleteData[],
|
||||
requestData: GraphClickMetaData,
|
||||
): TagFilterItem[] =>
|
||||
groupBy
|
||||
.map((gb) => {
|
||||
const value = requestData[gb.key];
|
||||
const [startStatusCode, endStatusCode] = getStartAndEndStatusCode(value);
|
||||
return value
|
||||
? [
|
||||
{
|
||||
id: v4(),
|
||||
key: gb,
|
||||
op: '>=',
|
||||
value: startStatusCode,
|
||||
},
|
||||
{
|
||||
id: v4(),
|
||||
key: gb,
|
||||
op: '<=',
|
||||
value: endStatusCode,
|
||||
},
|
||||
]
|
||||
: [];
|
||||
})
|
||||
.flat();
|
||||
|
||||
export const getCustomFiltersForBarChart = (
|
||||
metric:
|
||||
| {
|
||||
|
||||
@@ -191,7 +191,6 @@ function ThresholdItem({
|
||||
updateThreshold(threshold.id, 'channels', value)
|
||||
}
|
||||
data-testid="threshold-notification-channel-select"
|
||||
popupMatchSelectWidth={false}
|
||||
style={{ width: 350 }}
|
||||
options={channelOptions}
|
||||
onDropdownVisibleChange={onPickerVisibleChange}
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
NotificationChannelCreatePermission,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
|
||||
import { buildRuleDetachPermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import type { UseAuthZResult } from 'lib/authz/hooks/useAuthZ/types';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { formatPermission } from 'lib/authz/hooks/useAuthZ/utils';
|
||||
import {
|
||||
@@ -532,7 +531,7 @@ describe('ThresholdItem', () => {
|
||||
...mockUseAuthZDeny()([]),
|
||||
isLoading: true,
|
||||
permissions: null,
|
||||
} as UseAuthZResult);
|
||||
});
|
||||
renderThresholdItem();
|
||||
await openPicker();
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -3,7 +3,6 @@ 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';
|
||||
@@ -25,7 +24,6 @@ function CreateAlert({ alertType }: CreateAlertProps): JSX.Element {
|
||||
|
||||
return (
|
||||
<CreateAlertProvider initialAlertType={alertType}>
|
||||
<AlertEditorAssistantContext />
|
||||
<Spinner />
|
||||
<div className="create-alert-v2-container">
|
||||
<CreateAlertHeader />
|
||||
|
||||
@@ -22,13 +22,13 @@ export function useAlertRuleSaveChecks(): UseAlertRuleSaveChecksReturn {
|
||||
useCreateAlertState();
|
||||
const { data: channels, isLoading } = useChannelOptions();
|
||||
|
||||
const selectedChannels = useMemo(
|
||||
const selectedChannelNames = useMemo(
|
||||
() => thresholdState.thresholds.flatMap((threshold) => threshold.channels),
|
||||
[thresholdState.thresholds],
|
||||
);
|
||||
|
||||
return useMemo(() => {
|
||||
const selectedChannelIds = getChannelIds(channels, selectedChannels);
|
||||
const selectedChannelIds = getChannelIds(channels, selectedChannelNames);
|
||||
|
||||
return {
|
||||
saveChecks: getRuleSaveChecks({
|
||||
@@ -38,11 +38,12 @@ export function useAlertRuleSaveChecks(): UseAlertRuleSaveChecksReturn {
|
||||
}),
|
||||
testChecks: getRuleCreateChecks(selectedChannelIds),
|
||||
isResolvingChannels:
|
||||
isLoading && (selectedChannels.length > 0 || savedChannelNames.length > 0),
|
||||
isLoading &&
|
||||
(selectedChannelNames.length > 0 || savedChannelNames.length > 0),
|
||||
};
|
||||
}, [
|
||||
channels,
|
||||
selectedChannels,
|
||||
selectedChannelNames,
|
||||
savedChannelNames,
|
||||
isEditMode,
|
||||
ruleId,
|
||||
|
||||
@@ -1,122 +0,0 @@
|
||||
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' }],
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,66 +0,0 @@
|
||||
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,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,47 +0,0 @@
|
||||
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),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -3,15 +3,11 @@ 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 {
|
||||
getCreateAlertLocalStateFromAlertDef,
|
||||
Spinner,
|
||||
} from '../CreateAlert/utils';
|
||||
import { Spinner } from '../CreateAlert/utils';
|
||||
import { getEditAlertQuery } from './utils';
|
||||
|
||||
import '../CreateAlert/CreateAlert.styles.scss';
|
||||
@@ -36,17 +32,8 @@ 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 />
|
||||
|
||||
@@ -13,11 +13,6 @@ export const DashedContainer = styled.div`
|
||||
align-items: center;
|
||||
`;
|
||||
|
||||
export const ButtonContainer = styled.div`
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
`;
|
||||
|
||||
export const EventContainer = styled.div`
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
|
||||
@@ -14,8 +14,8 @@ import Card from 'periscope/components/Card/Card';
|
||||
import { isModifierKeyPressed } from 'utils/app';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import {
|
||||
RuleCreatePermission,
|
||||
RuleListPermission,
|
||||
RuleCreateChecks,
|
||||
RuleListChecks,
|
||||
} from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import { withAuthZContent } from 'lib/authz/components/withAuthZ/withAuthZContent';
|
||||
|
||||
@@ -26,9 +26,6 @@ import AlertRulesDenied from './AlertRulesDenied';
|
||||
import AlertRulesLoading from './AlertRulesLoading';
|
||||
import { useHomeAlertRules } from './useHomeAlertRules';
|
||||
|
||||
const LIST_CHECKS = [RuleListPermission];
|
||||
const CREATE_CHECKS = [RuleCreatePermission];
|
||||
|
||||
function AlertRules({
|
||||
onUpdateChecklistDoneItem,
|
||||
loadingUserPreferences,
|
||||
@@ -73,7 +70,7 @@ function AlertRules({
|
||||
|
||||
<div className="empty-actions-container">
|
||||
<AuthZButton
|
||||
checks={CREATE_CHECKS}
|
||||
checks={RuleCreateChecks}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
@@ -224,8 +221,8 @@ function AlertRules({
|
||||
}
|
||||
|
||||
export default withAuthZContent(AlertRules, {
|
||||
checks: LIST_CHECKS,
|
||||
preloadChecks: CREATE_CHECKS,
|
||||
checks: RuleListChecks,
|
||||
preloadChecks: RuleCreateChecks,
|
||||
fallback: ({ deniedPermissions }) => (
|
||||
<AlertRulesDenied deniedPermissions={deniedPermissions} />
|
||||
),
|
||||
|
||||
@@ -6,7 +6,6 @@ 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';
|
||||
@@ -64,7 +63,6 @@ function Explorer(): JSX.Element {
|
||||
handleSetQueryData,
|
||||
redirectWithQueryBuilderData,
|
||||
} = useQueryBuilder();
|
||||
useExplorerAssistantContext(SavedviewtypesSourceDTO.ai_observability);
|
||||
|
||||
const isAIAssistantEnabled = useIsAIAssistantEnabled();
|
||||
|
||||
|
||||
@@ -2,13 +2,9 @@ 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 {
|
||||
SYSTEM_DASHBOARD_NAME,
|
||||
useSystemDashboard,
|
||||
} from './hooks/useSystemDashboard';
|
||||
import { useSystemDashboard } from './hooks/useSystemDashboard';
|
||||
import styles from './Overview.module.scss';
|
||||
|
||||
function Overview(): JSX.Element {
|
||||
@@ -18,15 +14,6 @@ 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..." />;
|
||||
|
||||
@@ -11,7 +11,7 @@ import type {
|
||||
GetDashboardV2200,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
|
||||
const SYSTEM_DASHBOARD_NAME = 'ai-o11y-overview';
|
||||
|
||||
const DASHBOARD_ID = 'llm-observability-overview';
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Typography } from '@signozhq/ui/typography';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import ROUTES from 'constants/routes';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { RuleCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import { RuleCreateChecks } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { isModifierKeyPressed } from 'utils/app';
|
||||
@@ -32,8 +32,6 @@ const alertLogEvents = (
|
||||
void logEvent(title, dataSource ? { ...attributes, dataSource } : attributes);
|
||||
};
|
||||
|
||||
const CREATE_CHECKS = [RuleCreatePermission];
|
||||
|
||||
interface AlertsEmptyStateProps {
|
||||
onRefresh?: () => void;
|
||||
}
|
||||
@@ -91,7 +89,7 @@ export function AlertsEmptyState({
|
||||
<div className={styles.actionContainer}>
|
||||
<div className={styles.buttonGroup}>
|
||||
<AuthZButton
|
||||
checks={CREATE_CHECKS}
|
||||
checks={RuleCreateChecks}
|
||||
size="md"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
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 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,83 +0,0 @@
|
||||
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 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { AllTheProviders, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useRuleViews } from '../useRuleViews';
|
||||
|
||||
describe('useRuleViews', () => {
|
||||
it('reports loading while the views query is held', () => {
|
||||
const { result } = renderHook(() => useRuleViews({ enabled: false }), {
|
||||
wrapper: AllTheProviders,
|
||||
});
|
||||
|
||||
expect(result.current.isLoading).toBe(true);
|
||||
expect(result.current.views).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -4,14 +4,12 @@ import { ColumnSelector } from 'components/TanStackTableView';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView';
|
||||
import TextToolTip from 'components/TextToolTip';
|
||||
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
|
||||
import { RuleCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
import { RuleCreateChecks } from 'lib/authz/hooks/useAuthZ/permissions/rule.permissions';
|
||||
|
||||
import type { AlertRule } from '../types';
|
||||
|
||||
import styles from './AlertRulesHeaderActions.module.scss';
|
||||
|
||||
const CREATE_CHECKS = [RuleCreatePermission];
|
||||
|
||||
interface Props {
|
||||
columns: TableColumnDef<AlertRule>[];
|
||||
/** False on the empty list, whose own button creates the first rule. */
|
||||
@@ -33,7 +31,7 @@ function AlertRulesHeaderActions({
|
||||
/>
|
||||
{showNewAlert && (
|
||||
<AuthZButton
|
||||
checks={CREATE_CHECKS}
|
||||
checks={RuleCreateChecks}
|
||||
variant="solid"
|
||||
size="sm"
|
||||
prefix={<Plus size={14} />}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user