mirror of
https://github.com/SigNoz/signoz.git
synced 2026-10-09 03:30:55 +01:00
Compare commits
10 Commits
feat/trace
...
test/route
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
179e607b6b | ||
|
|
8ad3410c34 | ||
|
|
534c06d781 | ||
|
|
ee4dde1736 | ||
|
|
ec4bb0dff9 | ||
|
|
b19ee361df | ||
|
|
490a2fccc7 | ||
|
|
de635f8baf | ||
|
|
f33b887426 | ||
|
|
5cafe15b17 |
1
.gitattributes
vendored
1
.gitattributes
vendored
@@ -1,3 +1,4 @@
|
||||
*.css linguist-detectable=false
|
||||
*.stories.mocks.tsx linguist-generated=true
|
||||
**/__story_mockdata__/** linguist-generated=true
|
||||
tests/e2e/drivers/** linguist-generated=true
|
||||
|
||||
1
.github/workflows/integrationci.yaml
vendored
1
.github/workflows/integrationci.yaml
vendored
@@ -68,7 +68,6 @@ jobs:
|
||||
- semconvfamilies
|
||||
- serviceaccount
|
||||
- spanmapper
|
||||
- tracedetail
|
||||
- querier_json_body
|
||||
- querier_skip_resource_fingerprint
|
||||
- ttl
|
||||
|
||||
@@ -9844,40 +9844,6 @@ components:
|
||||
required:
|
||||
- aggregations
|
||||
type: object
|
||||
SpantypesGettableTraceSummary:
|
||||
properties:
|
||||
ai:
|
||||
$ref: '#/components/schemas/SpantypesTraceAISummary'
|
||||
endTimestampMillis:
|
||||
minimum: 0
|
||||
type: integer
|
||||
hasMissingSpans:
|
||||
type: boolean
|
||||
rootServiceEntryPoint:
|
||||
type: string
|
||||
rootServiceName:
|
||||
type: string
|
||||
rootSpanStatusCode:
|
||||
type: string
|
||||
startTimestampMillis:
|
||||
minimum: 0
|
||||
type: integer
|
||||
totalErrorSpansCount:
|
||||
minimum: 0
|
||||
type: integer
|
||||
totalSpansCount:
|
||||
minimum: 0
|
||||
type: integer
|
||||
required:
|
||||
- startTimestampMillis
|
||||
- endTimestampMillis
|
||||
- rootServiceName
|
||||
- rootServiceEntryPoint
|
||||
- rootSpanStatusCode
|
||||
- totalSpansCount
|
||||
- totalErrorSpansCount
|
||||
- hasMissingSpans
|
||||
type: object
|
||||
SpantypesGettableWaterfallTrace:
|
||||
properties:
|
||||
endTimestampMillis:
|
||||
@@ -10192,39 +10158,6 @@ components:
|
||||
nullable: true
|
||||
type: object
|
||||
type: object
|
||||
SpantypesTraceAISummary:
|
||||
properties:
|
||||
tokens:
|
||||
$ref: '#/components/schemas/SpantypesTraceAITokens'
|
||||
totalCost:
|
||||
type: number
|
||||
required:
|
||||
- tokens
|
||||
type: object
|
||||
SpantypesTraceAITokens:
|
||||
properties:
|
||||
cacheRead:
|
||||
minimum: 0
|
||||
type: integer
|
||||
cacheWrite:
|
||||
minimum: 0
|
||||
type: integer
|
||||
input:
|
||||
minimum: 0
|
||||
type: integer
|
||||
output:
|
||||
minimum: 0
|
||||
type: integer
|
||||
reasoning:
|
||||
minimum: 0
|
||||
type: integer
|
||||
required:
|
||||
- input
|
||||
- output
|
||||
- cacheRead
|
||||
- cacheWrite
|
||||
- reasoning
|
||||
type: object
|
||||
SpantypesUpdatableSpanMapper:
|
||||
properties:
|
||||
config:
|
||||
@@ -15949,66 +15882,6 @@ paths:
|
||||
tags:
|
||||
- tracedetail
|
||||
x-signoz-stability: alpha
|
||||
/api/v1/traces/{traceID}/summary:
|
||||
get:
|
||||
deprecated: false
|
||||
description: Returns the trace's time range, root span, span and error counts,
|
||||
and whether any spans are missing. AI traces also include token and cost totals.
|
||||
operationId: GetTraceSummary
|
||||
parameters:
|
||||
- in: path
|
||||
name: traceID
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
responses:
|
||||
"200":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
properties:
|
||||
data:
|
||||
$ref: '#/components/schemas/SpantypesGettableTraceSummary'
|
||||
status:
|
||||
type: string
|
||||
required:
|
||||
- status
|
||||
- data
|
||||
type: object
|
||||
description: OK
|
||||
"401":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Unauthorized
|
||||
"403":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Forbidden
|
||||
"404":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Not Found
|
||||
"500":
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/RenderErrorResponse'
|
||||
description: Internal Server Error
|
||||
security:
|
||||
- api_key:
|
||||
- VIEWER
|
||||
- tokenizer:
|
||||
- VIEWER
|
||||
summary: Get summary for a trace
|
||||
tags:
|
||||
- tracedetail
|
||||
x-signoz-stability: alpha
|
||||
/api/v1/user/me:
|
||||
get:
|
||||
deprecated: true
|
||||
|
||||
@@ -86,6 +86,9 @@ tests/
|
||||
├── .env.local # generated by bootstrap/setup.py (gitignored)
|
||||
├── bootstrap/
|
||||
│ └── setup.py # test_setup / test_teardown — pytest lifecycle
|
||||
├── drivers/ # the driver kit and one driver per feature
|
||||
│ ├── kit.ts
|
||||
│ └── routing.ts
|
||||
├── fixtures/ # Playwright test fixtures (test.extend) only
|
||||
│ └── auth.ts
|
||||
├── helpers/ # function helpers + the constants they share with tests
|
||||
@@ -112,6 +115,24 @@ These two folders look similar but mean different things:
|
||||
|
||||
Rule of thumb: if it's a `test.extend` fixture, put it in `fixtures/`. If it's a function you call explicitly (or a constant the function uses), put it in `helpers/`. If it's a static file the helpers read, put it in `testdata/`.
|
||||
|
||||
### Drivers
|
||||
|
||||
New suites use a driver rather than loose helpers. A driver is a function that closes over the page and returns the feature's actions and locators. `drivers/kit.ts` turns it into a fixture, so a spec imports one module and never passes a `page` around:
|
||||
|
||||
```ts
|
||||
import { expect, PATH, test } from '../../drivers/routing';
|
||||
|
||||
test('TC-09 RouteTab switches the url', async ({ routing }) => {
|
||||
await routing.goto(PATH.metricsSummary);
|
||||
await expect(routing.activeRouteTab(PATH.metricsSummary)).toBeVisible();
|
||||
});
|
||||
```
|
||||
|
||||
- `driver(name, build)` adds a test-scoped fixture built on `authedPage`.
|
||||
- `seeded(name, open, close)` adds a worker-scoped seed. `open` and `close` run on a throwaway admin page.
|
||||
- A driver reuses helpers by calling them, never by reaching for another fixture.
|
||||
- `drivers/` is AI-owned: coding agents generate and maintain it with the specs, and `.gitattributes` collapses it in diffs.
|
||||
|
||||
### Extended fixtures
|
||||
|
||||
For features needing complex setup (API-seeded data, ruler evaluation waits, cleanup), create domain-specific fixtures that extend `auth`. Group them in `fixtures/<domain>/`.
|
||||
|
||||
@@ -417,7 +417,7 @@ for (const theme of themes.length ? themes : [null]) {
|
||||
break;
|
||||
}
|
||||
|
||||
height = Math.ceil(needed);
|
||||
height = needed;
|
||||
await page.setViewportSize({ width: Number(opts.width), height });
|
||||
await page.waitForTimeout(Number(opts.settle));
|
||||
}
|
||||
|
||||
@@ -11335,82 +11335,6 @@ export interface SpantypesGettableTraceAggregationsDTO {
|
||||
aggregations: SpantypesSpanAggregationResultDTO[];
|
||||
}
|
||||
|
||||
export interface SpantypesTraceAITokensDTO {
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
cacheRead: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
cacheWrite: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
input: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
output: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
reasoning: number;
|
||||
}
|
||||
|
||||
export interface SpantypesTraceAISummaryDTO {
|
||||
tokens: SpantypesTraceAITokensDTO;
|
||||
/**
|
||||
* @type number
|
||||
*/
|
||||
totalCost?: number;
|
||||
}
|
||||
|
||||
export interface SpantypesGettableTraceSummaryDTO {
|
||||
ai?: SpantypesTraceAISummaryDTO;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
endTimestampMillis: number;
|
||||
/**
|
||||
* @type boolean
|
||||
*/
|
||||
hasMissingSpans: boolean;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
rootServiceEntryPoint: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
rootServiceName: string;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
rootSpanStatusCode: string;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
startTimestampMillis: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
totalErrorSpansCount: number;
|
||||
/**
|
||||
* @type integer
|
||||
* @minimum 0
|
||||
*/
|
||||
totalSpansCount: number;
|
||||
}
|
||||
|
||||
export interface SpantypesOtelSpanRefDTO {
|
||||
/**
|
||||
* @type string
|
||||
@@ -13099,17 +13023,6 @@ export type GetTraceAggregations200 = {
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type GetTraceSummaryPathParameters = {
|
||||
traceID: string;
|
||||
};
|
||||
export type GetTraceSummary200 = {
|
||||
data: SpantypesGettableTraceSummaryDTO;
|
||||
/**
|
||||
* @type string
|
||||
*/
|
||||
status: string;
|
||||
};
|
||||
|
||||
export type ListUserPreferences200 = {
|
||||
/**
|
||||
* @type array
|
||||
|
||||
@@ -4,17 +4,11 @@
|
||||
* * regenerate with 'pnpm generate:api'
|
||||
* SigNoz
|
||||
*/
|
||||
import { useMutation, useQuery } from 'react-query';
|
||||
import { useMutation } from 'react-query';
|
||||
import type {
|
||||
InvalidateOptions,
|
||||
MutationFunction,
|
||||
QueryClient,
|
||||
QueryFunction,
|
||||
QueryKey,
|
||||
UseMutationOptions,
|
||||
UseMutationResult,
|
||||
UseQueryOptions,
|
||||
UseQueryResult,
|
||||
} from 'react-query';
|
||||
|
||||
import type {
|
||||
@@ -22,8 +16,6 @@ import type {
|
||||
GetFlamegraphPathParameters,
|
||||
GetTraceAggregations200,
|
||||
GetTraceAggregationsPathParameters,
|
||||
GetTraceSummary200,
|
||||
GetTraceSummaryPathParameters,
|
||||
GetWaterfallV4200,
|
||||
GetWaterfallV4PathParameters,
|
||||
RenderErrorResponseDTO,
|
||||
@@ -35,26 +27,6 @@ import type {
|
||||
import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
|
||||
import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
|
||||
|
||||
const withQueryKey = <T extends object, K>(
|
||||
query: T,
|
||||
queryKey: K,
|
||||
): T & { queryKey: K } => {
|
||||
const result = { queryKey } as T & { queryKey: K };
|
||||
for (const key of Object.keys(query)) {
|
||||
// The explicit queryKey always wins, matching the previous
|
||||
// `{ ...query, queryKey }` spread where it was set last.
|
||||
if (key === 'queryKey') {
|
||||
continue;
|
||||
}
|
||||
Object.defineProperty(result, key, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: () => (query as Record<string, unknown>)[key],
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* Computes span aggregations grouped by requested field.
|
||||
* @summary Get aggregations for a trace
|
||||
@@ -155,108 +127,6 @@ export const useGetTraceAggregations = <
|
||||
> => {
|
||||
return useMutation(getGetTraceAggregationsMutationOptions(options));
|
||||
};
|
||||
/**
|
||||
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
|
||||
* @summary Get summary for a trace
|
||||
*/
|
||||
export const getTraceSummary = (
|
||||
{ traceID }: GetTraceSummaryPathParameters,
|
||||
signal?: AbortSignal,
|
||||
) => {
|
||||
return GeneratedAPIInstance<GetTraceSummary200>({
|
||||
url: `/api/v1/traces/${traceID}/summary`,
|
||||
method: 'GET',
|
||||
signal,
|
||||
});
|
||||
};
|
||||
|
||||
export const getGetTraceSummaryQueryKey = ({
|
||||
traceID,
|
||||
}: GetTraceSummaryPathParameters) => {
|
||||
return [`/api/v1/traces/${traceID}/summary`] as const;
|
||||
};
|
||||
|
||||
export const getGetTraceSummaryQueryOptions = <
|
||||
TData = Awaited<ReturnType<typeof getTraceSummary>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID }: GetTraceSummaryPathParameters,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceSummary>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
) => {
|
||||
const { query: queryOptions } = options ?? {};
|
||||
|
||||
const queryKey =
|
||||
queryOptions?.queryKey ?? getGetTraceSummaryQueryKey({ traceID });
|
||||
|
||||
const queryFn: QueryFunction<Awaited<ReturnType<typeof getTraceSummary>>> = ({
|
||||
signal,
|
||||
}) => getTraceSummary({ traceID }, signal);
|
||||
|
||||
return {
|
||||
queryKey,
|
||||
queryFn,
|
||||
enabled: traceID !== null && traceID !== undefined,
|
||||
...queryOptions,
|
||||
} as UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceSummary>>,
|
||||
TError,
|
||||
TData
|
||||
> & { queryKey: QueryKey };
|
||||
};
|
||||
|
||||
export type GetTraceSummaryQueryResult = NonNullable<
|
||||
Awaited<ReturnType<typeof getTraceSummary>>
|
||||
>;
|
||||
export type GetTraceSummaryQueryError = ErrorType<RenderErrorResponseDTO>;
|
||||
|
||||
/**
|
||||
* @summary Get summary for a trace
|
||||
*/
|
||||
|
||||
export function useGetTraceSummary<
|
||||
TData = Awaited<ReturnType<typeof getTraceSummary>>,
|
||||
TError = ErrorType<RenderErrorResponseDTO>,
|
||||
>(
|
||||
{ traceID }: GetTraceSummaryPathParameters,
|
||||
options?: {
|
||||
query?: UseQueryOptions<
|
||||
Awaited<ReturnType<typeof getTraceSummary>>,
|
||||
TError,
|
||||
TData
|
||||
>;
|
||||
},
|
||||
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
|
||||
const queryOptions = getGetTraceSummaryQueryOptions({ traceID }, options);
|
||||
|
||||
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
|
||||
queryKey: QueryKey;
|
||||
};
|
||||
|
||||
return withQueryKey(query, queryOptions.queryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* @summary Get summary for a trace
|
||||
*/
|
||||
export const invalidateGetTraceSummary = async (
|
||||
queryClient: QueryClient,
|
||||
{ traceID }: GetTraceSummaryPathParameters,
|
||||
options?: InvalidateOptions,
|
||||
): Promise<QueryClient> => {
|
||||
await queryClient.invalidateQueries(
|
||||
{ queryKey: getGetTraceSummaryQueryKey({ traceID }) },
|
||||
options,
|
||||
);
|
||||
|
||||
return queryClient;
|
||||
};
|
||||
|
||||
/**
|
||||
* Returns the flamegraph view of spans for a given trace ID.
|
||||
* @summary Get flamegraph view for a trace
|
||||
|
||||
@@ -72,6 +72,8 @@ interface CustomTimePickerProps {
|
||||
maxTime: number;
|
||||
/** When true, zoom-out button is hidden (e.g. in drawer/modal time selection) */
|
||||
isModalTimeSelection?: boolean;
|
||||
/** Lands on the trigger input. Not spread — the component takes no rest props. */
|
||||
'data-testid'?: string;
|
||||
}
|
||||
|
||||
function CustomTimePicker({
|
||||
@@ -95,6 +97,7 @@ function CustomTimePicker({
|
||||
minTime,
|
||||
maxTime,
|
||||
isModalTimeSelection = false,
|
||||
'data-testid': dataTestId,
|
||||
}: CustomTimePickerProps): JSX.Element {
|
||||
const [selectedTimePlaceholderValue, setSelectedTimePlaceholderValue] =
|
||||
useState('Select / Enter Time Range');
|
||||
@@ -596,6 +599,7 @@ function CustomTimePicker({
|
||||
>
|
||||
<Input
|
||||
ref={inputRef}
|
||||
data-testid={dataTestId}
|
||||
autoComplete="off"
|
||||
className={cx(
|
||||
'timeSelection-input',
|
||||
@@ -682,4 +686,5 @@ CustomTimePicker.defaultProps = {
|
||||
onExitLiveLogs: noop,
|
||||
showLiveLogs: false,
|
||||
showRecentlyUsed: true,
|
||||
'data-testid': undefined,
|
||||
};
|
||||
|
||||
@@ -180,6 +180,7 @@ function CustomTimePickerPopoverContent({
|
||||
type="text"
|
||||
className="time-btns"
|
||||
key={option.label + option.value}
|
||||
data-testid={`time-chip-${option.value}`}
|
||||
onClick={(): void => {
|
||||
handleExitLiveLogs();
|
||||
onSelectHandler(option.label, option.value);
|
||||
@@ -259,6 +260,7 @@ function CustomTimePickerPopoverContent({
|
||||
<Button
|
||||
type="text"
|
||||
key={option.label + option.value}
|
||||
data-testid={`time-option-${option.value}`}
|
||||
onClick={(e: React.MouseEvent<HTMLButtonElement>): void => {
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
|
||||
@@ -98,6 +98,7 @@ exports[`Not Found page test should render Not Found page without errors 1`] = `
|
||||
|
||||
<div
|
||||
class="c0"
|
||||
data-testid="not-found"
|
||||
>
|
||||
<img
|
||||
alt="not-found"
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Button, Container, Text, TextContainer } from './styles';
|
||||
|
||||
function NotFound({ text = defaultText }: Props): JSX.Element {
|
||||
return (
|
||||
<Container>
|
||||
<Container data-testid="not-found">
|
||||
<NotFoundImage />
|
||||
|
||||
<TextContainer>
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
overflow: visible;
|
||||
position: relative;
|
||||
align-self: stretch;
|
||||
clip-path: inset(0 -100vw 0 0);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -57,7 +57,6 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
showFilterCollapse = true,
|
||||
showQueryName = true,
|
||||
useFieldApis,
|
||||
savedViewsHeader,
|
||||
} = props;
|
||||
const [isSettingsOpen, setIsSettingsOpen] = useState(false);
|
||||
const [params, setParams] = useApiMonitoringParams();
|
||||
@@ -380,7 +379,6 @@ export default function QuickFilters(props: IQuickFiltersProps): JSX.Element {
|
||||
return (
|
||||
<div className="quick-filters-container">
|
||||
<div className="quick-filters">
|
||||
{savedViewsHeader}
|
||||
{source !== QuickFiltersSource.INFRA_MONITORING && (
|
||||
<section className="header">
|
||||
{renderLeftActions()}
|
||||
|
||||
@@ -8,7 +8,9 @@
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
// Positioned so overlays (settings drawer) paint above the content pane
|
||||
// without changing this pane's layout width.
|
||||
.filters {
|
||||
width: 280px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
@@ -19,44 +21,6 @@
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
.savedViews {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--l1-background);
|
||||
border-right: 1px solid var(--l1-border);
|
||||
}
|
||||
|
||||
.quickFilters {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
background: var(--l1-background);
|
||||
transition: transform 0.2s ease-in-out;
|
||||
z-index: 1;
|
||||
|
||||
&.isOpen {
|
||||
transform: translateX(100%);
|
||||
}
|
||||
}
|
||||
|
||||
// No quick filters: the header sits in flow and the list stays under it
|
||||
.isStatic {
|
||||
border-right: 1px solid var(--l1-border);
|
||||
|
||||
.quickFilters {
|
||||
position: static;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.savedViews {
|
||||
border-right: 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Bounded box for the OverlayScrollbar inside it (`.overlay-scrollbar` is
|
||||
// `height: 100%`), which owns the scrolling.
|
||||
.content {
|
||||
@@ -67,7 +31,3 @@
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.contentInner {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { ComponentProps, ReactNode, useState } from 'react';
|
||||
import { ComponentProps, ReactNode } from 'react';
|
||||
import cx from 'classnames';
|
||||
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
|
||||
import SavedViewsHeader from 'container/SavedViews/SavedViewsHeader';
|
||||
import SavedViewsPanel from 'container/SavedViews/SavedViewsPanel';
|
||||
import { useSavedViewEnabled } from 'hooks/useSavedViewEnabled';
|
||||
|
||||
import QuickFilters from '../QuickFilters';
|
||||
|
||||
@@ -15,15 +12,8 @@ type QuickFiltersElementProps = JSX.LibraryManagedAttributes<
|
||||
ComponentProps<typeof QuickFilters>
|
||||
>;
|
||||
|
||||
// What the page configures; the layout adds the open / close wiring.
|
||||
type SavedViewsElementProps = Omit<
|
||||
ComponentProps<typeof SavedViewsPanel>,
|
||||
'onClose'
|
||||
>;
|
||||
|
||||
export interface QuickFiltersLayoutProps {
|
||||
quickFilterProps?: QuickFiltersElementProps;
|
||||
savedViewProps?: SavedViewsElementProps;
|
||||
quickFilterProps: QuickFiltersElementProps;
|
||||
showFilters: boolean;
|
||||
className?: string;
|
||||
contentClassName?: string;
|
||||
@@ -33,60 +23,20 @@ export interface QuickFiltersLayoutProps {
|
||||
|
||||
function QuickFiltersLayout({
|
||||
quickFilterProps,
|
||||
savedViewProps,
|
||||
showFilters,
|
||||
className,
|
||||
contentClassName,
|
||||
testId,
|
||||
children,
|
||||
}: QuickFiltersLayoutProps): JSX.Element {
|
||||
const [isViewsOpen, setIsViewsOpen] = useState(false);
|
||||
const isSavedViewEnabled = useSavedViewEnabled();
|
||||
|
||||
const hasQuickFilters = !!quickFilterProps;
|
||||
const hasSavedViews = !!savedViewProps && isSavedViewEnabled;
|
||||
|
||||
const showSidebar = showFilters && (hasQuickFilters || hasSavedViews);
|
||||
|
||||
const isPanelPinned = hasSavedViews && !hasQuickFilters;
|
||||
|
||||
const isSliding = hasQuickFilters && isViewsOpen;
|
||||
|
||||
const savedViewsHeader = hasSavedViews ? (
|
||||
<SavedViewsHeader
|
||||
{...savedViewProps}
|
||||
onOpenViews={isPanelPinned ? undefined : (): void => setIsViewsOpen(true)}
|
||||
/>
|
||||
) : undefined;
|
||||
|
||||
return (
|
||||
<div className={cx(styles.layout, className)} data-testid={testId}>
|
||||
{showSidebar && (
|
||||
{showFilters && (
|
||||
<aside
|
||||
className={cx(styles.sidebar, { [styles.isStatic]: !hasQuickFilters })}
|
||||
className={styles.filters}
|
||||
data-testid="quick-filters-layout-filters"
|
||||
>
|
||||
<div
|
||||
className={cx(styles.quickFilters, { [styles.isOpen]: isSliding })}
|
||||
data-testid="quick-filters-layout-drawer"
|
||||
>
|
||||
{hasQuickFilters ? (
|
||||
<QuickFilters
|
||||
{...quickFilterProps}
|
||||
savedViewsHeader={savedViewsHeader}
|
||||
/>
|
||||
) : (
|
||||
savedViewsHeader
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.savedViews}>
|
||||
{hasSavedViews && (isPanelPinned || isViewsOpen) && (
|
||||
<SavedViewsPanel
|
||||
{...savedViewProps}
|
||||
onClose={isPanelPinned ? undefined : (): void => setIsViewsOpen(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<QuickFilters {...quickFilterProps} />
|
||||
</aside>
|
||||
)}
|
||||
<section
|
||||
@@ -94,7 +44,7 @@ function QuickFiltersLayout({
|
||||
data-testid="quick-filters-layout-content"
|
||||
>
|
||||
<OverlayScrollbar>
|
||||
<div className={styles.contentInner}>{children}</div>
|
||||
<div>{children}</div>
|
||||
</OverlayScrollbar>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useSavedViewEnabled } from 'hooks/useSavedViewEnabled';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { QuickFiltersSource } from '../../types';
|
||||
import QuickFiltersLayout from '../QuickFiltersLayout';
|
||||
@@ -9,33 +7,15 @@ jest.mock('../QuickFiltersLayout.module.scss', () => ({
|
||||
__esModule: true,
|
||||
default: {
|
||||
layout: 'layout',
|
||||
sidebar: 'sidebar',
|
||||
isStatic: 'isStatic',
|
||||
savedViews: 'savedViews',
|
||||
quickFilters: 'quickFilters',
|
||||
isOpen: 'isOpen',
|
||||
filters: 'filters',
|
||||
content: 'content',
|
||||
contentInner: 'contentInner',
|
||||
},
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useSavedViewEnabled', () => ({
|
||||
useSavedViewEnabled: jest.fn(() => true),
|
||||
}));
|
||||
|
||||
jest.mock('../../QuickFilters', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
source,
|
||||
savedViewsHeader,
|
||||
}: {
|
||||
source: string;
|
||||
savedViewsHeader?: React.ReactNode;
|
||||
}): JSX.Element => (
|
||||
<div data-testid="quick-filters">
|
||||
{savedViewsHeader}
|
||||
{source}
|
||||
</div>
|
||||
default: ({ source }: { source: string }): JSX.Element => (
|
||||
<div data-testid="quick-filters">{source}</div>
|
||||
),
|
||||
}));
|
||||
|
||||
@@ -43,16 +23,8 @@ const quickFilterProps = {
|
||||
source: QuickFiltersSource.TRACES_EXPLORER,
|
||||
handleFilterVisibilityChange: jest.fn(),
|
||||
};
|
||||
const savedViewProps = { source: SavedviewtypesSourceDTO.traces };
|
||||
|
||||
const drawer = (): HTMLElement =>
|
||||
screen.getByTestId('quick-filters-layout-drawer');
|
||||
|
||||
describe('QuickFiltersLayout', () => {
|
||||
beforeEach(() => {
|
||||
jest.mocked(useSavedViewEnabled).mockReturnValue(true);
|
||||
});
|
||||
|
||||
it('renders QuickFilters with the given props inside the filters pane', () => {
|
||||
render(
|
||||
<QuickFiltersLayout showFilters quickFilterProps={quickFilterProps}>
|
||||
@@ -68,16 +40,11 @@ describe('QuickFiltersLayout', () => {
|
||||
expect(screen.getByTestId('quick-filters-layout-content')).toHaveTextContent(
|
||||
'content',
|
||||
);
|
||||
expect(screen.queryByTestId('saved-views-header')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render the filters pane when showFilters is false', () => {
|
||||
render(
|
||||
<QuickFiltersLayout
|
||||
showFilters={false}
|
||||
quickFilterProps={quickFilterProps}
|
||||
savedViewProps={savedViewProps}
|
||||
>
|
||||
<QuickFiltersLayout showFilters={false} quickFilterProps={quickFilterProps}>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
@@ -89,138 +56,24 @@ describe('QuickFiltersLayout', () => {
|
||||
expect(screen.getByText('content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders no sidebar at all without quick filters or saved views', () => {
|
||||
render(
|
||||
<QuickFiltersLayout showFilters>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('quick-filters-layout-filters'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.getByText('content')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('merges classNames onto the root and content panes', () => {
|
||||
render(
|
||||
<QuickFiltersLayout
|
||||
showFilters
|
||||
quickFilterProps={quickFilterProps}
|
||||
className="root-extra"
|
||||
contentClassName="content-extra"
|
||||
testId="layout"
|
||||
className="page-root"
|
||||
contentClassName="page-content"
|
||||
testId="page"
|
||||
>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('layout')).toHaveClass('layout', 'root-extra');
|
||||
const root = screen.getByTestId('page');
|
||||
expect(root).toHaveClass('layout', 'page-root');
|
||||
expect(screen.getByTestId('quick-filters-layout-content')).toHaveClass(
|
||||
'content',
|
||||
'content-extra',
|
||||
'page-content',
|
||||
);
|
||||
});
|
||||
|
||||
describe('saved views', () => {
|
||||
it('ignores savedViewProps while the flag is off', () => {
|
||||
jest.mocked(useSavedViewEnabled).mockReturnValue(false);
|
||||
const { unmount } = render(
|
||||
<QuickFiltersLayout
|
||||
showFilters
|
||||
quickFilterProps={quickFilterProps}
|
||||
savedViewProps={savedViewProps}
|
||||
>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('quick-filters')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('saved-views-header')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('saved-views-panel')).not.toBeInTheDocument();
|
||||
|
||||
// Saved views only, so nothing is left to show.
|
||||
unmount();
|
||||
render(
|
||||
<QuickFiltersLayout showFilters savedViewProps={savedViewProps}>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
expect(
|
||||
screen.queryByTestId('quick-filters-layout-filters'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens the panel from the header and slides the quick filters drawer, keeping the same QuickFilters node', async () => {
|
||||
render(
|
||||
<QuickFiltersLayout
|
||||
showFilters
|
||||
quickFilterProps={quickFilterProps}
|
||||
savedViewProps={savedViewProps}
|
||||
>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
const quickFilters = screen.getByTestId('quick-filters');
|
||||
|
||||
expect(quickFilters).toContainElement(
|
||||
screen.getByTestId('saved-views-header'),
|
||||
);
|
||||
expect(drawer()).toContainElement(quickFilters);
|
||||
expect(screen.queryByTestId('saved-views-panel')).not.toBeInTheDocument();
|
||||
expect(drawer()).not.toHaveClass('isOpen');
|
||||
|
||||
await user.click(screen.getByTestId('saved-views-open'));
|
||||
|
||||
expect(screen.getByTestId('saved-views-panel')).toBeInTheDocument();
|
||||
expect(drawer()).toHaveClass('isOpen');
|
||||
expect(screen.getByTestId('quick-filters')).toBe(quickFilters);
|
||||
|
||||
await user.click(screen.getByTestId('saved-views-close'));
|
||||
|
||||
expect(screen.queryByTestId('saved-views-panel')).not.toBeInTheDocument();
|
||||
expect(drawer()).not.toHaveClass('isOpen');
|
||||
expect(screen.getByTestId('quick-filters')).toBe(quickFilters);
|
||||
});
|
||||
|
||||
it('hands the source to the header and the panel', async () => {
|
||||
render(
|
||||
<QuickFiltersLayout
|
||||
showFilters
|
||||
quickFilterProps={quickFilterProps}
|
||||
savedViewProps={savedViewProps}
|
||||
>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('saved-views-header')).toHaveAttribute(
|
||||
'data-source',
|
||||
SavedviewtypesSourceDTO.traces,
|
||||
);
|
||||
await userEvent.setup().click(screen.getByTestId('saved-views-open'));
|
||||
expect(screen.getByTestId('saved-views-panel')).toHaveAttribute(
|
||||
'data-source',
|
||||
SavedviewtypesSourceDTO.traces,
|
||||
);
|
||||
});
|
||||
|
||||
it('without quick filters: static sidebar, header on top, list always on screen with no open or close controls', () => {
|
||||
render(
|
||||
<QuickFiltersLayout showFilters savedViewProps={savedViewProps}>
|
||||
<div>content</div>
|
||||
</QuickFiltersLayout>,
|
||||
);
|
||||
|
||||
const sidebar = screen.getByTestId('quick-filters-layout-filters');
|
||||
expect(sidebar).toHaveClass('isStatic');
|
||||
expect(screen.queryByTestId('quick-filters')).not.toBeInTheDocument();
|
||||
expect(screen.getByTestId('saved-views-header')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('saved-views-panel')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('saved-views-open')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('saved-views-close')).not.toBeInTheDocument();
|
||||
expect(drawer()).not.toHaveClass('isOpen');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -8,20 +8,12 @@
|
||||
width: 342px;
|
||||
height: 100%;
|
||||
background: var(--l1-background);
|
||||
border-right: 1px solid var(--l1-border);
|
||||
transition: width 0.05s ease-in-out;
|
||||
overflow: hidden;
|
||||
color: var(--l1-foreground);
|
||||
transition:
|
||||
transform 0.2s ease-in-out,
|
||||
visibility 0s;
|
||||
|
||||
&.hidden {
|
||||
transform: translateX(-100%);
|
||||
visibility: hidden;
|
||||
pointer-events: none;
|
||||
transition:
|
||||
transform 0.2s ease-in-out,
|
||||
visibility 0s 0.2s;
|
||||
width: 0;
|
||||
}
|
||||
.qf-header {
|
||||
display: flex;
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
@@ -62,7 +61,6 @@ export interface IQuickFiltersProps {
|
||||
showFilterCollapse?: boolean;
|
||||
showQueryName?: boolean;
|
||||
useFieldApis?: QuickFilterCheckboxUseFieldApis;
|
||||
savedViewsHeader?: ReactNode;
|
||||
}
|
||||
|
||||
export enum QuickFiltersSource {
|
||||
|
||||
@@ -35,7 +35,8 @@ function TanStackRowCellInner<TData>({
|
||||
<td
|
||||
className={cx(tableStyles.tableCell, 'tanstack-cell-' + cell.column.id)}
|
||||
data-single-column={hasSingleColumn || undefined}
|
||||
onClick={onClick}
|
||||
// While loading, rowData may be a placeholder ({ id: 'skeleton-N' }).
|
||||
onClick={showSkeleton ? undefined : onClick}
|
||||
>
|
||||
{showSkeleton ? (
|
||||
<Skeleton.Input
|
||||
|
||||
@@ -83,6 +83,18 @@ describe('TanStackTableView Integration', () => {
|
||||
expect(screen.getByRole('table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not call onRowClick for skeleton rows', async () => {
|
||||
const user = userEvent.setup();
|
||||
const onRowClick = jest.fn();
|
||||
renderTanStackTable({
|
||||
props: { data: [], isLoading: true, onRowClick },
|
||||
});
|
||||
|
||||
await user.click(screen.getAllByRole('cell')[0]);
|
||||
|
||||
expect(onRowClick).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows loading spinner for infinite scroll when loading', () => {
|
||||
renderTanStackTable({
|
||||
props: { isLoading: true, onEndReached: jest.fn() },
|
||||
|
||||
@@ -32,7 +32,6 @@ export const REACT_QUERY_KEY = {
|
||||
GET_TRACE_AGGREGATIONS: 'GET_TRACE_AGGREGATIONS',
|
||||
GET_TRACE_V2_FLAMEGRAPH: 'GET_TRACE_V2_FLAMEGRAPH',
|
||||
GET_TRACE_V3_FLAMEGRAPH: 'GET_TRACE_V3_FLAMEGRAPH',
|
||||
GET_TRACE_THREAD: 'GET_TRACE_THREAD',
|
||||
GET_POD_LIST: 'GET_POD_LIST',
|
||||
GET_NODE_LIST: 'GET_NODE_LIST',
|
||||
GET_DEPLOYMENT_LIST: 'GET_DEPLOYMENT_LIST',
|
||||
|
||||
@@ -10,8 +10,6 @@ import WarningPopover from 'components/WarningPopover/WarningPopover';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { usePageActions } from 'container/AIAssistant/pageActions/usePageActions';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import QuickFiltersLayout from 'components/QuickFilters/QuickFiltersLayout/QuickFiltersLayout';
|
||||
import ExplorerOptionWrapper from 'container/ExplorerOptions/ExplorerOptionWrapper';
|
||||
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
|
||||
import DateTimeSelector from 'container/TopNav/DateTimeSelectionV2';
|
||||
@@ -349,62 +347,57 @@ function Explorer(): JSX.Element {
|
||||
|
||||
return (
|
||||
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
|
||||
<QuickFiltersLayout
|
||||
showFilters
|
||||
savedViewProps={{ source: SavedviewtypesSourceDTO.metrics }}
|
||||
>
|
||||
<div className="metrics-explorer-explore-container">
|
||||
<div className="explore-header">
|
||||
<div className="explore-header-left-actions">
|
||||
<span>1 chart/query</span>
|
||||
<Tooltip
|
||||
open={disableOneChartPerQuery ? undefined : false}
|
||||
title={oneChartPerQueryDisabledTooltip}
|
||||
>
|
||||
<Switch
|
||||
value={showOneChartPerQuery}
|
||||
onChange={handleToggleShowOneChartPerQuery}
|
||||
disabled={disableOneChartPerQuery || splitedQueries.length <= 1}
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="explore-header-right-actions">
|
||||
{!isEmpty(warning) && <WarningPopover warningData={warning} />}
|
||||
<DateTimeSelector showAutoRefresh />
|
||||
<RightToolbarActions
|
||||
onStageRunQuery={(): void => handleRunQuery()}
|
||||
isLoadingQueries={isLoadingQueries}
|
||||
handleCancelQuery={handleCancelQuery}
|
||||
<div className="metrics-explorer-explore-container">
|
||||
<div className="explore-header">
|
||||
<div className="explore-header-left-actions">
|
||||
<span>1 chart/query</span>
|
||||
<Tooltip
|
||||
open={disableOneChartPerQuery ? undefined : false}
|
||||
title={oneChartPerQueryDisabledTooltip}
|
||||
>
|
||||
<Switch
|
||||
value={showOneChartPerQuery}
|
||||
onChange={handleToggleShowOneChartPerQuery}
|
||||
disabled={disableOneChartPerQuery || splitedQueries.length <= 1}
|
||||
/>
|
||||
</div>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<QueryBuilderV2
|
||||
config={{ initialDataSource: DataSource.METRICS, queryVariant: 'static' }}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
showFunctions={false}
|
||||
version="v3"
|
||||
/>
|
||||
<div className="explore-content">
|
||||
<TimeSeries
|
||||
onFetchingStateChange={setIsLoadingQueries}
|
||||
showOneChartPerQuery={showOneChartPerQuery}
|
||||
setWarning={setWarning}
|
||||
areAllMetricUnitsSame={areAllMetricUnitsSame}
|
||||
isMetricUnitsLoading={isMetricUnitsLoading}
|
||||
isMetricUnitsError={isMetricUnitsError}
|
||||
metricUnits={units}
|
||||
metricNames={metricNames}
|
||||
metrics={metrics}
|
||||
handleOpenMetricDetails={handleOpenMetricDetails}
|
||||
yAxisUnit={yAxisUnit}
|
||||
setYAxisUnit={setYAxisUnit}
|
||||
showYAxisUnitSelector={showYAxisUnitSelector}
|
||||
isCancelled={isCancelled}
|
||||
exportDefaultQuery={exportDefaultQuery}
|
||||
<div className="explore-header-right-actions">
|
||||
{!isEmpty(warning) && <WarningPopover warningData={warning} />}
|
||||
<DateTimeSelector showAutoRefresh />
|
||||
<RightToolbarActions
|
||||
onStageRunQuery={(): void => handleRunQuery()}
|
||||
isLoadingQueries={isLoadingQueries}
|
||||
handleCancelQuery={handleCancelQuery}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</QuickFiltersLayout>
|
||||
<QueryBuilderV2
|
||||
config={{ initialDataSource: DataSource.METRICS, queryVariant: 'static' }}
|
||||
panelType={PANEL_TYPES.TIME_SERIES}
|
||||
showFunctions={false}
|
||||
version="v3"
|
||||
/>
|
||||
<div className="explore-content">
|
||||
<TimeSeries
|
||||
onFetchingStateChange={setIsLoadingQueries}
|
||||
showOneChartPerQuery={showOneChartPerQuery}
|
||||
setWarning={setWarning}
|
||||
areAllMetricUnitsSame={areAllMetricUnitsSame}
|
||||
isMetricUnitsLoading={isMetricUnitsLoading}
|
||||
isMetricUnitsError={isMetricUnitsError}
|
||||
metricUnits={units}
|
||||
metricNames={metricNames}
|
||||
metrics={metrics}
|
||||
handleOpenMetricDetails={handleOpenMetricDetails}
|
||||
yAxisUnit={yAxisUnit}
|
||||
setYAxisUnit={setYAxisUnit}
|
||||
showYAxisUnitSelector={showYAxisUnitSelector}
|
||||
isCancelled={isCancelled}
|
||||
exportDefaultQuery={exportDefaultQuery}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<ExplorerOptionWrapper
|
||||
disabled={!stagedQuery}
|
||||
query={exportDefaultQuery}
|
||||
|
||||
@@ -308,7 +308,7 @@ function CreateEditRolePageContent(): JSX.Element {
|
||||
cancelText="Keep editing"
|
||||
onConfirm={confirmNavigation}
|
||||
onCancel={cancelNavigation}
|
||||
data-testid="discard-changes-dialog"
|
||||
testId="discard-changes-dialog"
|
||||
>
|
||||
<Typography>
|
||||
{isCreateMode
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--spacing-2);
|
||||
padding: var(--spacing-2) var(--spacing-3);
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
color: var(--l1-foreground);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.name {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import { Menu } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import styles from './SavedViewsHeader.module.scss';
|
||||
|
||||
// Temp Placeholder data till main functionality is plugged in
|
||||
const PLACEHOLDER_VIEW_NAME = 'My view';
|
||||
|
||||
function SavedViewsHeader({
|
||||
source,
|
||||
onOpenViews,
|
||||
}: {
|
||||
source: SavedviewtypesSourceDTO;
|
||||
// Absent when the list is always on screen.
|
||||
onOpenViews?: () => void;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
className={styles.header}
|
||||
data-testid="saved-views-header"
|
||||
data-source={source}
|
||||
>
|
||||
<Typography.Text className={styles.name}>
|
||||
{PLACEHOLDER_VIEW_NAME}
|
||||
</Typography.Text>
|
||||
{onOpenViews && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
aria-label="All views"
|
||||
prefix={<Menu size={14} />}
|
||||
onClick={onOpenViews}
|
||||
data-testid="saved-views-open"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SavedViewsHeader;
|
||||
@@ -1,21 +0,0 @@
|
||||
.panel {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: var(--spacing-2) var(--spacing-3);
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--font-size-sm);
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
import { X } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import styles from './SavedViewsPanel.module.scss';
|
||||
|
||||
function SavedViewsPanel({
|
||||
source,
|
||||
onClose,
|
||||
}: {
|
||||
source: SavedviewtypesSourceDTO;
|
||||
// Absent when the list is always on screen.
|
||||
onClose?: () => void;
|
||||
}): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
className={styles.panel}
|
||||
data-testid="saved-views-panel"
|
||||
data-source={source}
|
||||
>
|
||||
<div className={styles.header}>
|
||||
<Typography.Text className={styles.title}>All views</Typography.Text>
|
||||
{onClose && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="icon"
|
||||
aria-label="Close"
|
||||
prefix={<X size={14} />}
|
||||
onClick={onClose}
|
||||
data-testid="saved-views-close"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SavedViewsPanel;
|
||||
@@ -2,7 +2,6 @@ import type { ComponentType } from 'react';
|
||||
import type { Meta, StoryObj } from '@storybook/react-vite';
|
||||
import { Route } from 'react-router-dom';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { userEvent, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
@@ -23,7 +22,6 @@ const pageStory = storyMocks(panelEditorMocks, { layout: 'app' });
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Pages/Dashboards/Panel Editor',
|
||||
tags: ['play'],
|
||||
// The page is wrapped in `withAuthZPage`, which types its props as an index
|
||||
// signature; the story's args are what the controls resolve to.
|
||||
component: PanelEditorPage as ComponentType<PanelEditorArgs>,
|
||||
@@ -40,25 +38,6 @@ export default meta;
|
||||
|
||||
type Story = StoryObj<PanelEditorArgs>;
|
||||
|
||||
const expandConfigSections: Story['play'] = async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
const headers = await canvas.findAllByTestId(
|
||||
/^config-section-/,
|
||||
{},
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
for (const header of headers) {
|
||||
if (header.getAttribute('aria-expanded') === 'false') {
|
||||
await userEvent.click(header);
|
||||
}
|
||||
}
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
for (let el = headers[0].parentElement; el; el = el.parentElement) {
|
||||
el.scrollTop = 0;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Editing a saved time series panel: the live preview over the query builder on
|
||||
* the left, the panel's formatting, legend, axes and thresholds on the right.
|
||||
@@ -107,57 +86,3 @@ export const ReadOnly: Story = {
|
||||
export const Tooltips: Story = {
|
||||
args: { tooltipsOpen: true },
|
||||
};
|
||||
|
||||
/** A new time series panel's config pane, every section expanded. */
|
||||
export const ConfigTimeSeries: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'time-series' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new number panel's config pane, every section expanded. */
|
||||
export const ConfigNumber: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'number' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new table panel's config pane, every section expanded. */
|
||||
export const ConfigTable: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'table' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new bar chart panel's config pane, every section expanded. */
|
||||
export const ConfigBarChart: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'bar-chart' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new area chart panel's config pane, every section expanded. */
|
||||
export const ConfigAreaChart: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'area-chart' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new pie chart panel's config pane, every section expanded. */
|
||||
export const ConfigPieChart: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'pie-chart' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new histogram panel's config pane, every section expanded. */
|
||||
export const ConfigHistogram: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'histogram' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new list panel's config pane, every section expanded. */
|
||||
export const ConfigList: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'list' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
/** A new text panel's config pane, every section expanded. */
|
||||
export const ConfigText: Story = {
|
||||
args: { panel: 'new', newPanelKind: 'text' },
|
||||
play: expandConfigSections,
|
||||
};
|
||||
|
||||
@@ -21,14 +21,12 @@ import type { PanelKind } from '../../../DashboardContainer/Panels/types/panelKi
|
||||
*/
|
||||
export const NEW_PANEL_KINDS = [
|
||||
'time-series',
|
||||
'number',
|
||||
'table',
|
||||
'bar-chart',
|
||||
'area-chart',
|
||||
'number',
|
||||
'pie-chart',
|
||||
'table',
|
||||
'histogram',
|
||||
'list',
|
||||
'text',
|
||||
] as const;
|
||||
|
||||
export type NewPanelKind = (typeof NEW_PANEL_KINDS)[number];
|
||||
@@ -36,13 +34,11 @@ export type NewPanelKind = (typeof NEW_PANEL_KINDS)[number];
|
||||
const KIND_BY_OPTION: Record<NewPanelKind, PanelKind> = {
|
||||
'time-series': 'signoz/TimeSeriesPanel',
|
||||
'bar-chart': 'signoz/BarChartPanel',
|
||||
'area-chart': 'signoz/AreaChartPanel',
|
||||
number: 'signoz/NumberPanel',
|
||||
'pie-chart': 'signoz/PieChartPanel',
|
||||
table: 'signoz/TablePanel',
|
||||
histogram: 'signoz/HistogramPanel',
|
||||
list: 'signoz/ListPanel',
|
||||
text: 'signoz/TextPanel',
|
||||
};
|
||||
|
||||
export const newPanelKindOf = (option: NewPanelKind): PanelKind =>
|
||||
|
||||
@@ -285,70 +285,6 @@ export const SectionActionsMenu: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The new-panel picker opened from the toolbar: the panel kinds as tiles, with
|
||||
* the target section to place the panel in.
|
||||
*/
|
||||
export const NewPanelPicker: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByTestId('add-panel-header', {}, { timeout: 10000 }),
|
||||
);
|
||||
await screen.findByTestId('panel-type-signoz/TimeSeriesPanel');
|
||||
},
|
||||
};
|
||||
|
||||
/** The new-panel picker with a kind picked, waiting on the section to confirm. */
|
||||
export const NewPanelPickerTypeSelected: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByTestId('add-panel-header', {}, { timeout: 10000 }),
|
||||
);
|
||||
await userEvent.click(
|
||||
await screen.findByTestId('panel-type-signoz/TimeSeriesPanel'),
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The new-panel picker on a dashboard without sections, where there is no
|
||||
* section to choose.
|
||||
*/
|
||||
export const NewPanelPickerNoSections: Story = {
|
||||
args: { sectioned: false },
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
await userEvent.click(
|
||||
await canvas.findByTestId('add-panel-header', {}, { timeout: 10000 }),
|
||||
);
|
||||
await screen.findByTestId('panel-type-signoz/TimeSeriesPanel');
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* The new-panel picker opened from the second section's menu, targeting that
|
||||
* section.
|
||||
*/
|
||||
export const NewPanelPickerFromSection: Story = {
|
||||
play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
|
||||
const [, secondSection] = await canvas.findAllByRole(
|
||||
'button',
|
||||
{ name: 'Section actions' },
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
await userEvent.click(secondSection);
|
||||
await userEvent.click(await screen.findByText('Add panel'));
|
||||
await screen.findByTestId('panel-type-signoz/TimeSeriesPanel');
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* A dashboard id nobody has, which is what a deleted or mistyped link opens on.
|
||||
*
|
||||
|
||||
@@ -4,10 +4,15 @@
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
|
||||
.log-quick-filter-left-section {
|
||||
width: 0%;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.log-module-right-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
min-height: 0;
|
||||
|
||||
.log-explorer-query-container {
|
||||
@@ -34,4 +39,26 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
&.filter-visible {
|
||||
.log-quick-filter-left-section {
|
||||
width: 260px;
|
||||
height: 100%;
|
||||
overflow: visible;
|
||||
min-height: 0;
|
||||
position: relative;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.quick-filters-container {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.log-module-right-section {
|
||||
width: calc(100% - 260px);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,10 +3,10 @@ import { useQueryClient } from 'react-query';
|
||||
import * as Sentry from '@sentry/react';
|
||||
import getLocalStorageKey from 'api/browser/localstorage/get';
|
||||
import setLocalStorageApi from 'api/browser/localstorage/set';
|
||||
import cx from 'classnames';
|
||||
import ExplorerCard from 'components/ExplorerCard/ExplorerCard';
|
||||
import QueryCancelledPlaceholder from 'components/QueryCancelledPlaceholder';
|
||||
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import QuickFiltersLayout from 'components/QuickFilters/QuickFiltersLayout/QuickFiltersLayout';
|
||||
import QuickFilters from 'components/QuickFilters/QuickFilters';
|
||||
import { useSignalFieldApis } from 'components/QuickFilters/hooks/useSignalFieldApis';
|
||||
import { QuickFiltersSource, SignalType } from 'components/QuickFilters/types';
|
||||
import WarningPopover from 'components/WarningPopover/WarningPopover';
|
||||
@@ -225,19 +225,21 @@ function LogsExplorer(): JSX.Element {
|
||||
return (
|
||||
<Sentry.ErrorBoundary fallback={<ErrorBoundaryFallback />}>
|
||||
<EventSourceProvider>
|
||||
<QuickFiltersLayout
|
||||
className="logs-module-page"
|
||||
showFilters={showFilters}
|
||||
savedViewProps={{ source: SavedviewtypesSourceDTO.logs }}
|
||||
quickFilterProps={{
|
||||
className: 'qf-logs-explorer',
|
||||
signal: SignalType.LOGS,
|
||||
source: QuickFiltersSource.LOGS_EXPLORER,
|
||||
handleFilterVisibilityChange,
|
||||
useFieldApis: quickFilterFieldApis,
|
||||
}}
|
||||
<div
|
||||
className={cx('logs-module-page', showFilters ? 'filter-visible' : '')}
|
||||
>
|
||||
<section className="log-module-right-section">
|
||||
{showFilters && (
|
||||
<section className={cx('log-quick-filter-left-section')}>
|
||||
<QuickFilters
|
||||
className="qf-logs-explorer"
|
||||
signal={SignalType.LOGS}
|
||||
source={QuickFiltersSource.LOGS_EXPLORER}
|
||||
handleFilterVisibilityChange={handleFilterVisibilityChange}
|
||||
useFieldApis={quickFilterFieldApis}
|
||||
/>
|
||||
</section>
|
||||
)}
|
||||
<section className={cx('log-module-right-section')}>
|
||||
<Toolbar
|
||||
showAutoRefresh={false}
|
||||
leftActions={
|
||||
@@ -290,7 +292,7 @@ function LogsExplorer(): JSX.Element {
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</QuickFiltersLayout>
|
||||
</div>
|
||||
</EventSourceProvider>
|
||||
</Sentry.ErrorBoundary>
|
||||
);
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
.message {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.roleHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.parts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-4);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.empty {
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-style: italic;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.textBox {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-3);
|
||||
padding: var(--spacing-3) var(--spacing-5);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l2-background);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.text {
|
||||
font-size: var(--periscope-font-size-base);
|
||||
line-height: var(--line-height-20);
|
||||
color: var(--l1-foreground);
|
||||
word-break: break-word;
|
||||
|
||||
:global(p) {
|
||||
margin: 0 0 var(--spacing-4);
|
||||
}
|
||||
|
||||
:global(p:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
:global(ol),
|
||||
:global(ul) {
|
||||
margin: 0 0 var(--spacing-4);
|
||||
padding-left: var(--spacing-10);
|
||||
}
|
||||
}
|
||||
|
||||
.plainText {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.showMore {
|
||||
align-self: flex-start;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
align-self: flex-start;
|
||||
max-width: 100%;
|
||||
padding: var(--spacing-2) var(--spacing-4);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l2-background);
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--l1-foreground);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.dot {
|
||||
flex-shrink: 0;
|
||||
width: var(--spacing-3);
|
||||
height: var(--spacing-3);
|
||||
border-radius: var(--radius-round);
|
||||
|
||||
&[data-tone='success'] {
|
||||
background: var(--accent-forest);
|
||||
}
|
||||
|
||||
&[data-tone='warning'] {
|
||||
background: var(--accent-amber);
|
||||
}
|
||||
|
||||
&[data-tone='error'] {
|
||||
background: var(--accent-cherry);
|
||||
}
|
||||
}
|
||||
|
||||
.chipLabel {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.chipSeparator {
|
||||
flex-shrink: 0;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.chipValue {
|
||||
display: inline-flex;
|
||||
gap: var(--spacing-2);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
min-width: 0;
|
||||
color: var(--accent-primary);
|
||||
}
|
||||
|
||||
.chipKey {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.toolName {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
color: var(--accent-amber);
|
||||
}
|
||||
|
||||
.toolCall,
|
||||
.toolResult {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-3);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.toolCall {
|
||||
border-radius: var(--radius-2);
|
||||
transition: outline-color 0.3s ease;
|
||||
outline: 1px solid transparent;
|
||||
outline-offset: var(--spacing-1);
|
||||
|
||||
&.isHighlighted {
|
||||
outline-color: var(--primary);
|
||||
}
|
||||
}
|
||||
|
||||
.toolLink {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--l2-foreground);
|
||||
cursor: pointer;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
color: var(--primary);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.collapsible {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-4);
|
||||
min-width: 0;
|
||||
|
||||
&.boxed {
|
||||
gap: 0;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l2-background);
|
||||
|
||||
.collapsibleToggle {
|
||||
justify-content: space-between;
|
||||
padding: var(--spacing-3) var(--spacing-5);
|
||||
}
|
||||
|
||||
.collapsibleBody {
|
||||
padding: 0 var(--spacing-5) var(--spacing-4);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.collapsibleToggle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
min-width: 0;
|
||||
padding: 0;
|
||||
border: none;
|
||||
background: none;
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--l2-foreground);
|
||||
cursor: pointer;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.collapsibleLabel {
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.collapsibleBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.json {
|
||||
min-width: 0;
|
||||
padding: var(--spacing-3) var(--spacing-4);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
cursor: auto;
|
||||
|
||||
:global(.pretty-view) {
|
||||
padding: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.mediaChip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
align-self: flex-start;
|
||||
padding: var(--spacing-2) var(--spacing-4);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-round);
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
|
||||
import { ThreadMessage } from '../TraceDetailsThread/types';
|
||||
import CollapsibleBlock from './CollapsibleBlock';
|
||||
import MessagePart from './MessagePart';
|
||||
import PartChip from './PartChip';
|
||||
import { getFinishReasonTone, getRoleLabel } from './utils';
|
||||
|
||||
import styles from './AIThreadMessage.module.scss';
|
||||
|
||||
export interface AIThreadMessageProps {
|
||||
message: ThreadMessage;
|
||||
isOutput?: boolean;
|
||||
isToolLinkEnabled?: (toolCallId: string) => boolean;
|
||||
onToolLinkClick?: (toolCallId: string) => void;
|
||||
}
|
||||
|
||||
function AIThreadMessage({
|
||||
message,
|
||||
isOutput,
|
||||
isToolLinkEnabled,
|
||||
onToolLinkClick,
|
||||
}: AIThreadMessageProps): JSX.Element {
|
||||
const { role, content, finishReason } = message;
|
||||
const roleLabel = getRoleLabel(role);
|
||||
const tone = getFinishReasonTone(finishReason);
|
||||
|
||||
const parts = (
|
||||
<div className={styles.parts}>
|
||||
{content.length === 0 ? (
|
||||
<span className={styles.empty}>No content</span>
|
||||
) : (
|
||||
content.map((part, index) => (
|
||||
<MessagePart
|
||||
// Parts have no stable id and never reorder.
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={index}
|
||||
part={part}
|
||||
isToolLinkEnabled={isToolLinkEnabled}
|
||||
onToolLinkClick={onToolLinkClick}
|
||||
/>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={styles.message}
|
||||
data-testid={`ai-thread-message-${role || 'unknown'}`}
|
||||
>
|
||||
{role === 'system' ? (
|
||||
<CollapsibleBlock label={roleLabel} testId="ai-message-system-toggle">
|
||||
{parts}
|
||||
</CollapsibleBlock>
|
||||
) : (
|
||||
<>
|
||||
{roleLabel && (
|
||||
<div className={styles.roleHeader}>
|
||||
{roleLabel}
|
||||
{isOutput && (
|
||||
<Badge color={tone} testId="ai-message-output-badge">
|
||||
Output
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
{parts}
|
||||
</>
|
||||
)}
|
||||
{finishReason && (
|
||||
<PartChip
|
||||
label="Finish Reason"
|
||||
value={finishReason}
|
||||
tone={tone}
|
||||
testId="ai-message-finish-reason"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
AIThreadMessage.defaultProps = {
|
||||
isOutput: false,
|
||||
isToolLinkEnabled: undefined,
|
||||
onToolLinkClick: undefined,
|
||||
};
|
||||
|
||||
export default AIThreadMessage;
|
||||
@@ -1,50 +0,0 @@
|
||||
import { MouseEvent, ReactNode, useState } from 'react';
|
||||
import { ChevronDown, ChevronUp } from '@signozhq/icons';
|
||||
import cx from 'classnames';
|
||||
|
||||
import styles from './AIThreadMessage.module.scss';
|
||||
|
||||
interface CollapsibleBlockProps {
|
||||
label: ReactNode;
|
||||
// Boxed: full-width bordered row with the chevron on the right.
|
||||
isBoxed?: boolean;
|
||||
testId?: string;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function CollapsibleBlock({
|
||||
label,
|
||||
isBoxed = false,
|
||||
testId,
|
||||
children,
|
||||
}: CollapsibleBlockProps): JSX.Element {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
|
||||
const handleToggle = (event: MouseEvent): void => {
|
||||
event.stopPropagation();
|
||||
setIsOpen((prev) => !prev);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={cx(styles.collapsible, isBoxed && styles.boxed)}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.collapsibleToggle}
|
||||
onClick={handleToggle}
|
||||
aria-expanded={isOpen}
|
||||
data-testid={testId}
|
||||
>
|
||||
<span className={styles.collapsibleLabel}>{label}</span>
|
||||
{isOpen ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
|
||||
</button>
|
||||
{isOpen && <div className={styles.collapsibleBody}>{children}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
CollapsibleBlock.defaultProps = {
|
||||
isBoxed: false,
|
||||
testId: undefined,
|
||||
};
|
||||
|
||||
export default CollapsibleBlock;
|
||||
@@ -1,56 +0,0 @@
|
||||
import { MouseEvent, useState } from 'react';
|
||||
import cx from 'classnames';
|
||||
import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
|
||||
|
||||
import { MAX_TEXT_LENGTH } from './utils';
|
||||
|
||||
import styles from './AIThreadMessage.module.scss';
|
||||
|
||||
interface ExpandableTextProps {
|
||||
text: string;
|
||||
isMarkdown?: boolean;
|
||||
}
|
||||
|
||||
function ExpandableText({
|
||||
text,
|
||||
isMarkdown = false,
|
||||
}: ExpandableTextProps): JSX.Element {
|
||||
const [isExpanded, setIsExpanded] = useState(false);
|
||||
const isTruncated = !isExpanded && text.length > MAX_TEXT_LENGTH;
|
||||
const visibleText = isTruncated ? `${text.slice(0, MAX_TEXT_LENGTH)}…` : text;
|
||||
|
||||
const handleToggle = (event: MouseEvent): void => {
|
||||
event.stopPropagation();
|
||||
setIsExpanded((prev) => !prev);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{isMarkdown ? (
|
||||
<MarkdownRenderer
|
||||
className={styles.text}
|
||||
markdownContent={visibleText}
|
||||
variables={{}}
|
||||
/>
|
||||
) : (
|
||||
<div className={cx(styles.text, styles.plainText)}>{visibleText}</div>
|
||||
)}
|
||||
{text.length > MAX_TEXT_LENGTH && (
|
||||
<button
|
||||
type="button"
|
||||
className={styles.showMore}
|
||||
onClick={handleToggle}
|
||||
data-testid="ai-message-show-more"
|
||||
>
|
||||
{isExpanded ? 'Show less' : 'Show more'}
|
||||
</button>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
ExpandableText.defaultProps = {
|
||||
isMarkdown: false,
|
||||
};
|
||||
|
||||
export default ExpandableText;
|
||||
@@ -1,26 +0,0 @@
|
||||
import { PrettyView } from 'periscope/components/PrettyView';
|
||||
|
||||
import styles from './AIThreadMessage.module.scss';
|
||||
|
||||
interface JsonBlockProps {
|
||||
data: object;
|
||||
}
|
||||
|
||||
// Expanding tree nodes must not count as a click on the message.
|
||||
function JsonBlock({ data }: JsonBlockProps): JSX.Element {
|
||||
return (
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions
|
||||
<div
|
||||
className={styles.json}
|
||||
onClick={(event): void => event.stopPropagation()}
|
||||
>
|
||||
<PrettyView
|
||||
data={data as Record<string, unknown>}
|
||||
searchable={false}
|
||||
drawerKey="ai-thread-message"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default JsonBlock;
|
||||
@@ -1,64 +0,0 @@
|
||||
import { MessagePart as MessagePartType } from '../TraceDetailsThread/types';
|
||||
import MediaPart from './parts/MediaPart';
|
||||
import ThinkingPart from './parts/ThinkingPart';
|
||||
import ToolCallPart from './parts/ToolCallPart';
|
||||
import ToolResultPart from './parts/ToolResultPart';
|
||||
import TextContent from './TextContent';
|
||||
|
||||
interface MessagePartProps {
|
||||
part: MessagePartType;
|
||||
isToolLinkEnabled?: (toolCallId: string) => boolean;
|
||||
onToolLinkClick?: (toolCallId: string) => void;
|
||||
}
|
||||
|
||||
function MessagePart({
|
||||
part,
|
||||
isToolLinkEnabled,
|
||||
onToolLinkClick,
|
||||
}: MessagePartProps): JSX.Element | null {
|
||||
switch (part.type) {
|
||||
case 'text':
|
||||
return <TextContent text={part.content} isMarkdown />;
|
||||
case 'thinking':
|
||||
return <ThinkingPart content={part.content} />;
|
||||
case 'tool_call':
|
||||
return (
|
||||
<ToolCallPart
|
||||
id={part.id}
|
||||
name={part.name}
|
||||
args={part.arguments}
|
||||
server={part.server}
|
||||
/>
|
||||
);
|
||||
case 'tool_result':
|
||||
return (
|
||||
<ToolResultPart
|
||||
toolCallId={part.toolCallId}
|
||||
name={part.name}
|
||||
content={part.content}
|
||||
isError={part.isError}
|
||||
isLinkEnabled={!!isToolLinkEnabled?.(part.toolCallId)}
|
||||
onLinkClick={onToolLinkClick}
|
||||
/>
|
||||
);
|
||||
case 'media':
|
||||
return (
|
||||
<MediaPart
|
||||
modality={part.modality}
|
||||
mimeType={part.mimeType}
|
||||
name={part.name}
|
||||
/>
|
||||
);
|
||||
case 'generic':
|
||||
return <TextContent text={part.content} />;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
MessagePart.defaultProps = {
|
||||
isToolLinkEnabled: undefined,
|
||||
onToolLinkClick: undefined,
|
||||
};
|
||||
|
||||
export default MessagePart;
|
||||
@@ -1,44 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
import { MessageTone } from './utils';
|
||||
|
||||
import styles from './AIThreadMessage.module.scss';
|
||||
|
||||
interface PartChipProps {
|
||||
label: string;
|
||||
value?: ReactNode;
|
||||
tone?: MessageTone;
|
||||
testId?: string;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
function PartChip({
|
||||
label,
|
||||
value,
|
||||
tone = 'success',
|
||||
testId,
|
||||
children,
|
||||
}: PartChipProps): JSX.Element {
|
||||
return (
|
||||
<span className={styles.chip} data-testid={testId}>
|
||||
<span className={styles.dot} data-tone={tone} />
|
||||
<span className={styles.chipLabel}>{label}</span>
|
||||
{value !== undefined && (
|
||||
<>
|
||||
<span className={styles.chipSeparator}>—</span>
|
||||
<span className={styles.chipValue}>{value}</span>
|
||||
</>
|
||||
)}
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
PartChip.defaultProps = {
|
||||
value: undefined,
|
||||
tone: 'success',
|
||||
testId: undefined,
|
||||
children: undefined,
|
||||
};
|
||||
|
||||
export default PartChip;
|
||||
@@ -1,35 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import ExpandableText from './ExpandableText';
|
||||
import JsonBlock from './JsonBlock';
|
||||
import { parseJsonObject } from './utils';
|
||||
|
||||
import styles from './AIThreadMessage.module.scss';
|
||||
|
||||
interface TextContentProps {
|
||||
text: string;
|
||||
isMarkdown?: boolean;
|
||||
}
|
||||
|
||||
/** Renders JSON text as a tree, anything else as (markdown) text. */
|
||||
function TextContent({
|
||||
text,
|
||||
isMarkdown = false,
|
||||
}: TextContentProps): JSX.Element {
|
||||
const json = useMemo(() => parseJsonObject(text), [text]);
|
||||
|
||||
if (json) {
|
||||
return <JsonBlock data={json} />;
|
||||
}
|
||||
return (
|
||||
<div className={styles.textBox}>
|
||||
<ExpandableText text={text} isMarkdown={isMarkdown} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
TextContent.defaultProps = {
|
||||
isMarkdown: false,
|
||||
};
|
||||
|
||||
export default TextContent;
|
||||
@@ -1,43 +0,0 @@
|
||||
import { RefObject, useCallback } from 'react';
|
||||
|
||||
import { TOOL_CALL_ID_ATTR } from './utils';
|
||||
|
||||
import styles from './AIThreadMessage.module.scss';
|
||||
|
||||
const HIGHLIGHT_MS = 1500;
|
||||
|
||||
interface ToolCallLinks {
|
||||
isToolLinkEnabled: (toolCallId: string) => boolean;
|
||||
onToolLinkClick: (toolCallId: string) => void;
|
||||
}
|
||||
|
||||
/** Links tool results to their calls in `rootRef`; enabled only for ids in `toolCallIds`. */
|
||||
export function useToolCallLinks(
|
||||
rootRef: RefObject<HTMLElement>,
|
||||
toolCallIds: Set<string>,
|
||||
): ToolCallLinks {
|
||||
const isToolLinkEnabled = useCallback(
|
||||
(toolCallId: string): boolean => toolCallIds.has(toolCallId),
|
||||
[toolCallIds],
|
||||
);
|
||||
|
||||
const onToolLinkClick = useCallback(
|
||||
(toolCallId: string): void => {
|
||||
const target = rootRef.current?.querySelector<HTMLElement>(
|
||||
`[${TOOL_CALL_ID_ATTR}="${CSS.escape(toolCallId)}"]`,
|
||||
);
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
|
||||
target.classList.add(styles.isHighlighted);
|
||||
window.setTimeout(
|
||||
() => target.classList.remove(styles.isHighlighted),
|
||||
HIGHLIGHT_MS,
|
||||
);
|
||||
},
|
||||
[rootRef],
|
||||
);
|
||||
|
||||
return { isToolLinkEnabled, onToolLinkClick };
|
||||
}
|
||||
@@ -1,53 +0,0 @@
|
||||
import { ThreadMessage } from '../TraceDetailsThread/types';
|
||||
|
||||
export const MAX_TEXT_LENGTH = 1000;
|
||||
|
||||
export const MAX_INLINE_RESULT_LENGTH = 80;
|
||||
|
||||
export const TOOL_CALL_ID_ATTR = 'data-tool-call-id';
|
||||
|
||||
const ROLE_LABELS: Record<string, string> = {
|
||||
system: 'System',
|
||||
user: 'User',
|
||||
assistant: 'Assistant',
|
||||
tool: 'Tool',
|
||||
};
|
||||
|
||||
export type MessageTone = 'success' | 'warning' | 'error';
|
||||
|
||||
const FINISH_REASON_TONES: Record<string, MessageTone> = {
|
||||
length: 'warning',
|
||||
content_filter: 'warning',
|
||||
error: 'error',
|
||||
};
|
||||
|
||||
/** Undefined for missing or unknown roles, which render headerless. */
|
||||
export function getRoleLabel(role?: string): string | undefined {
|
||||
return role ? ROLE_LABELS[role] : undefined;
|
||||
}
|
||||
|
||||
export function getFinishReasonTone(reason?: string): MessageTone {
|
||||
return (reason && FINISH_REASON_TONES[reason]) || 'success';
|
||||
}
|
||||
|
||||
/** Parses objects and arrays only; scalars and invalid JSON return undefined. */
|
||||
export function parseJsonObject(text: string): object | undefined {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) {
|
||||
return undefined;
|
||||
}
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(trimmed);
|
||||
return typeof parsed === 'object' && parsed !== null ? parsed : undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export function collectToolCallIds(messages: ThreadMessage[]): string[] {
|
||||
return messages.flatMap((message) =>
|
||||
message.content.flatMap((part) =>
|
||||
part.type === 'tool_call' ? [part.id] : [],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -5,23 +5,18 @@ import { Typography } from '@signozhq/ui/typography';
|
||||
import styles from './EntityMetadataItem.module.scss';
|
||||
|
||||
interface EntityMetadataItemProps {
|
||||
tooltip: ReactNode;
|
||||
tooltipClassName?: string;
|
||||
tooltip: string;
|
||||
icon?: ReactNode;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function EntityMetadataItem({
|
||||
tooltip,
|
||||
tooltipClassName,
|
||||
icon,
|
||||
children,
|
||||
}: EntityMetadataItemProps): JSX.Element {
|
||||
return (
|
||||
<TooltipSimple
|
||||
title={tooltip}
|
||||
tooltipContentProps={{ className: tooltipClassName }}
|
||||
>
|
||||
<TooltipSimple title={tooltip}>
|
||||
<span className={styles.item}>
|
||||
{icon}
|
||||
<Typography.Text as="span">{children}</Typography.Text>
|
||||
@@ -32,7 +27,6 @@ function EntityMetadataItem({
|
||||
|
||||
EntityMetadataItem.defaultProps = {
|
||||
icon: null,
|
||||
tooltipClassName: undefined,
|
||||
};
|
||||
|
||||
export default EntityMetadataItem;
|
||||
|
||||
@@ -8,7 +8,3 @@
|
||||
// Keep Typography.Text at the row's size (it reads this var, not inherited font-size).
|
||||
--typography-font-size: var(--periscope-font-size-base);
|
||||
}
|
||||
|
||||
.tokenTooltip {
|
||||
min-width: 160px;
|
||||
}
|
||||
|
||||
@@ -1,21 +1,11 @@
|
||||
import {
|
||||
CalendarClock,
|
||||
CircleDollarSign,
|
||||
Coins,
|
||||
Server,
|
||||
Timer,
|
||||
} from '@signozhq/icons';
|
||||
import { CalendarClock, Server, Timer } from '@signozhq/icons';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import cx from 'classnames';
|
||||
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
|
||||
import HttpStatusBadge from 'components/HttpStatusBadge/HttpStatusBadge';
|
||||
|
||||
import { formatCost, formatTokens } from '../SpanHoverCard/aiUsage';
|
||||
import { TraceTokenUsage } from '../TraceDetailsHeader/types';
|
||||
import EntityMetadataItem from './EntityMetadataItem';
|
||||
import TokenUsageTooltip from './TokenUsageTooltip';
|
||||
|
||||
import tooltipStyles from '../TraceTooltip/TraceTooltip.module.scss';
|
||||
import styles from './EntityMetadataRow.module.scss';
|
||||
|
||||
interface EntityMetadataRowProps {
|
||||
@@ -26,8 +16,6 @@ interface EntityMetadataRowProps {
|
||||
execTimePercent?: number;
|
||||
timestamp?: string;
|
||||
statusCode?: string | number;
|
||||
tokens?: TraceTokenUsage;
|
||||
cost?: number | null;
|
||||
}
|
||||
|
||||
const ICON_SIZE = 14;
|
||||
@@ -44,8 +32,6 @@ function EntityMetadataRow({
|
||||
execTimePercent,
|
||||
timestamp,
|
||||
statusCode,
|
||||
tokens,
|
||||
cost,
|
||||
}: EntityMetadataRowProps): JSX.Element {
|
||||
const entityLabel = entity === 'trace' ? 'Trace' : 'Span';
|
||||
const durationTooltip =
|
||||
@@ -105,25 +91,6 @@ function EntityMetadataRow({
|
||||
<HttpStatusBadge statusCode={statusCode} />
|
||||
</EntityMetadataItem>
|
||||
)}
|
||||
|
||||
{tokens && (
|
||||
<EntityMetadataItem
|
||||
tooltip={<TokenUsageTooltip tokens={tokens} />}
|
||||
tooltipClassName={tooltipStyles.tooltipContent}
|
||||
icon={<Coins size={ICON_SIZE} />}
|
||||
>
|
||||
Tokens: {formatTokens(tokens.input)} → {formatTokens(tokens.output)}
|
||||
</EntityMetadataItem>
|
||||
)}
|
||||
|
||||
{cost != null && (
|
||||
<EntityMetadataItem
|
||||
tooltip="Total cost"
|
||||
icon={<CircleDollarSign size={ICON_SIZE} />}
|
||||
>
|
||||
{formatCost(cost)}
|
||||
</EntityMetadataItem>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -135,8 +102,6 @@ EntityMetadataRow.defaultProps = {
|
||||
execTimePercent: undefined,
|
||||
timestamp: undefined,
|
||||
statusCode: undefined,
|
||||
tokens: undefined,
|
||||
cost: undefined,
|
||||
};
|
||||
|
||||
export default EntityMetadataRow;
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import { formatTokens } from '../SpanHoverCard/aiUsage';
|
||||
import TooltipRow from '../TraceTooltip/TooltipRow';
|
||||
import TooltipSection from '../TraceTooltip/TooltipSection';
|
||||
import { TraceTokenUsage } from '../TraceDetailsHeader/types';
|
||||
|
||||
import tooltipStyles from '../TraceTooltip/TraceTooltip.module.scss';
|
||||
import styles from './EntityMetadataRow.module.scss';
|
||||
|
||||
interface TokenUsageTooltipProps {
|
||||
tokens: TraceTokenUsage;
|
||||
}
|
||||
|
||||
function TokenUsageTooltip({ tokens }: TokenUsageTooltipProps): JSX.Element {
|
||||
const { input, output, cacheRead, cacheWrite, reasoning } = tokens;
|
||||
|
||||
return (
|
||||
<div className={`${tooltipStyles.body} ${styles.tokenTooltip}`}>
|
||||
<TooltipSection>
|
||||
<TooltipRow label="Tokens" value={formatTokens(input + output)} isTotal />
|
||||
</TooltipSection>
|
||||
<TooltipSection>
|
||||
<TooltipRow label="Input" value={formatTokens(input)} />
|
||||
<TooltipRow label="Output" value={formatTokens(output)} />
|
||||
{cacheRead !== undefined && (
|
||||
<TooltipRow label="Cache read" value={formatTokens(cacheRead)} />
|
||||
)}
|
||||
{cacheWrite !== undefined && (
|
||||
<TooltipRow label="Cache write" value={formatTokens(cacheWrite)} />
|
||||
)}
|
||||
{reasoning !== undefined && (
|
||||
<TooltipRow label="Reasoning" value={formatTokens(reasoning)} />
|
||||
)}
|
||||
</TooltipSection>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TokenUsageTooltip;
|
||||
@@ -1,25 +0,0 @@
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-4);
|
||||
padding: var(--spacing-4) 0;
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--l2-foreground);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: var(--letter-spacing-wide);
|
||||
}
|
||||
|
||||
.scroll {
|
||||
max-height: 480px;
|
||||
overflow-y: auto;
|
||||
padding: var(--spacing-4);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
}
|
||||
@@ -1,62 +0,0 @@
|
||||
import { useMemo, useRef, useState } from 'react';
|
||||
|
||||
import { useToolCallLinks } from '../../AIThreadMessage/useToolCallLinks';
|
||||
import SpanMessages from '../../SpanMessages/SpanMessages';
|
||||
import {
|
||||
getSpanMessages,
|
||||
hasAnyMessages,
|
||||
hasFormattedMessages,
|
||||
} from '../../SpanMessages/utils';
|
||||
import { ThreadSpan, ThreadView } from '../../TraceDetailsThread/types';
|
||||
import ThreadViewToggle from '../../TraceDetailsThread/ThreadViewToggle';
|
||||
import { buildToolCallIndex } from '../../TraceDetailsThread/utils';
|
||||
|
||||
import styles from './SpanAIMessages.module.scss';
|
||||
|
||||
interface SpanAIMessagesProps {
|
||||
span: ThreadSpan;
|
||||
}
|
||||
|
||||
/** Waterfall spans only carry raw attributes, so they get the JSON view alone. */
|
||||
function SpanAIMessages({ span }: SpanAIMessagesProps): JSX.Element | null {
|
||||
const data = useMemo(() => getSpanMessages(span), [span]);
|
||||
const canFormat = hasFormattedMessages(data);
|
||||
const [view, setView] = useState(ThreadView.Formatted);
|
||||
const effectiveView = canFormat ? view : ThreadView.Json;
|
||||
|
||||
const scrollRef = useRef<HTMLDivElement>(null);
|
||||
const toolCallIds = useMemo(() => buildToolCallIndex([span]), [span]);
|
||||
const { isToolLinkEnabled, onToolLinkClick } = useToolCallLinks(
|
||||
scrollRef,
|
||||
toolCallIds,
|
||||
);
|
||||
|
||||
if (!hasAnyMessages(data)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.root} data-testid="span-ai-messages">
|
||||
<div className={styles.header}>
|
||||
Messages
|
||||
{canFormat && (
|
||||
<ThreadViewToggle
|
||||
value={effectiveView}
|
||||
onChange={setView}
|
||||
testId="span-ai-messages-view-toggle"
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<div className={styles.scroll} ref={scrollRef}>
|
||||
<SpanMessages
|
||||
span={span}
|
||||
view={effectiveView}
|
||||
isToolLinkEnabled={isToolLinkEnabled}
|
||||
onToolLinkClick={onToolLinkClick}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SpanAIMessages;
|
||||
@@ -52,7 +52,6 @@ import Events from './Events/Events';
|
||||
import OpenInLogsExplorer from './SpanLogs/OpenInLogsExplorer';
|
||||
import SpanLogs from './SpanLogs/SpanLogs';
|
||||
import { useSpanContextLogs } from './SpanLogs/useSpanContextLogs';
|
||||
import SpanAIMessages from './SpanAIMessages/SpanAIMessages';
|
||||
import SpanSummary from './SpanSummary';
|
||||
|
||||
import styles from './SpanDetailsPanel.module.scss';
|
||||
@@ -321,7 +320,6 @@ function SpanDetailsContent({
|
||||
<div className={styles.tabsScroll}>
|
||||
<TabsContent value="overview">
|
||||
{isWide && summary}
|
||||
<SpanAIMessages span={selectedSpan} />
|
||||
<DataViewer
|
||||
data={spanDisplayData}
|
||||
drawerKey="trace-details"
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Link2 } from '@signozhq/icons';
|
||||
import dayjs from 'dayjs';
|
||||
import KeyValueLabel from 'periscope/components/KeyValueLabel';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import EntityMetadataRow from '../EntityMetadata/EntityMetadataRow';
|
||||
import { getSpanAiDetails, getSpanTokenUsage } from '../SpanHoverCard/aiUsage';
|
||||
import { HIGHLIGHTED_OPTIONS } from './config';
|
||||
import {
|
||||
LinkedSpansPanel,
|
||||
@@ -33,11 +31,6 @@ function SpanSummary({
|
||||
}: SpanSummaryProps): JSX.Element {
|
||||
const percentile = useSpanPercentile(selectedSpan);
|
||||
const linkedSpans = useLinkedSpans((selectedSpan as any).references);
|
||||
const tokens = useMemo(() => getSpanTokenUsage(selectedSpan), [selectedSpan]);
|
||||
const cost = useMemo(
|
||||
() => getSpanAiDetails(selectedSpan)?.usage?.cost,
|
||||
[selectedSpan],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -70,8 +63,6 @@ function SpanSummary({
|
||||
: undefined
|
||||
}
|
||||
timestamp={dayjs(selectedSpan.timestamp).format('HH:mm:ss — MMM D, YYYY')}
|
||||
tokens={tokens}
|
||||
cost={cost}
|
||||
/>
|
||||
|
||||
<div className={styles.spanInfoItem}>
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
import { CSSProperties } from 'react';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import HttpStatusBadge from 'components/HttpStatusBadge/HttpStatusBadge';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import { getAiSpanKind } from '../utils/genAi';
|
||||
import { AI_SPAN_BADGES } from './constants';
|
||||
|
||||
interface SpanHintBadgeProps {
|
||||
span: SpanV3;
|
||||
}
|
||||
|
||||
function SpanHintBadge({ span }: SpanHintBadgeProps): JSX.Element | null {
|
||||
const aiSpanKind = getAiSpanKind(span);
|
||||
|
||||
if (aiSpanKind) {
|
||||
const { label, color } = AI_SPAN_BADGES[aiSpanKind];
|
||||
return (
|
||||
<Badge
|
||||
variant="outline"
|
||||
// The outline variant derives text, fill and border from this color.
|
||||
style={{ '--badge-background': color } as CSSProperties}
|
||||
data-testid={`span-hint-badge-${aiSpanKind}`}
|
||||
>
|
||||
{label}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
|
||||
if (!span.response_status_code) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <HttpStatusBadge statusCode={span.response_status_code} />;
|
||||
}
|
||||
|
||||
export default SpanHintBadge;
|
||||
@@ -1,39 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import SpanHintBadge from '../SpanHintBadge';
|
||||
|
||||
const spanWith = (
|
||||
attributes: Record<string, string | number>,
|
||||
responseStatusCode = '',
|
||||
): SpanV3 =>
|
||||
({
|
||||
attributes,
|
||||
resource: {},
|
||||
response_status_code: responseStatusCode,
|
||||
}) as unknown as SpanV3;
|
||||
|
||||
describe('SpanHintBadge', () => {
|
||||
it.each([
|
||||
[{ 'gen_ai.request.model': 'gpt-4o' }, 'LLM'],
|
||||
[{ 'gen_ai.tool.name': 'search' }, 'TOOL'],
|
||||
[{ 'gen_ai.agent.name': 'planner' }, 'AGENT'],
|
||||
])('shows only the AI badge for %p', (attributes, label) => {
|
||||
render(<SpanHintBadge span={spanWith(attributes, '200')} />);
|
||||
|
||||
expect(screen.getByText(label)).toBeInTheDocument();
|
||||
expect(screen.queryByText('200')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('falls back to the HTTP status code for non-AI spans', () => {
|
||||
render(<SpanHintBadge span={spanWith({}, '503')} />);
|
||||
|
||||
expect(screen.getByText('503')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders nothing for a non-AI span without a status code', () => {
|
||||
const { container } = render(<SpanHintBadge span={spanWith({})} />);
|
||||
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
@@ -1,10 +0,0 @@
|
||||
import { AiSpanKind } from '../utils/genAi';
|
||||
|
||||
export const AI_SPAN_BADGES: Record<
|
||||
AiSpanKind,
|
||||
{ label: string; color: string }
|
||||
> = {
|
||||
[AiSpanKind.Llm]: { label: 'LLM', color: 'rgba(155, 255, 0, 1)' },
|
||||
[AiSpanKind.Tool]: { label: 'TOOL', color: 'rgba(255, 209, 0, 1)' },
|
||||
[AiSpanKind.Agent]: { label: 'AGENT', color: 'rgba(255, 10, 138, 1)' },
|
||||
};
|
||||
@@ -12,16 +12,37 @@
|
||||
// Hover card may be rendered while the SpanDetailsPanel is docked as
|
||||
// a FloatingPanel (z-index 999); bump above the default tooltip z-index.
|
||||
--tooltip-z-index: 1000;
|
||||
background-color: var(--l1-background);
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid var(--l2-border);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.content {
|
||||
min-width: 220px;
|
||||
max-width: 320px;
|
||||
font-size: 12px;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding-bottom: 8px;
|
||||
.name {
|
||||
font-weight: 600;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.row {
|
||||
line-height: 1.5;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.preview {
|
||||
// container for additional preview rows
|
||||
}
|
||||
|
||||
.previewKey {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.previewValue {
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
@@ -4,8 +4,6 @@ import {
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@signozhq/ui/tooltip';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import cx from 'classnames';
|
||||
import { convertTimeToRelevantUnit } from 'utils/traceUtils';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { useTraceStore } from 'pages/TraceDetailsV3/stores/traceStore';
|
||||
@@ -14,12 +12,6 @@ import { useMemo } from 'react';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
import { toFixed } from 'utils/toFixed';
|
||||
|
||||
import { getSpanAiDetails, SpanAiDetails } from './aiUsage';
|
||||
import SpanUsageBreakdown from './SpanUsageBreakdown';
|
||||
import TooltipRow from '../TraceTooltip/TooltipRow';
|
||||
import TooltipSection from '../TraceTooltip/TooltipSection';
|
||||
|
||||
import tooltipStyles from '../TraceTooltip/TraceTooltip.module.scss';
|
||||
import styles from './SpanHoverCard.module.scss';
|
||||
|
||||
/**
|
||||
@@ -46,7 +38,6 @@ export interface SpanTooltipContentProps {
|
||||
relativeStartMs: number;
|
||||
durationMs: number;
|
||||
previewRows?: SpanPreviewRow[];
|
||||
ai?: SpanAiDetails;
|
||||
}
|
||||
|
||||
export function SpanTooltipContent({
|
||||
@@ -56,46 +47,33 @@ export function SpanTooltipContent({
|
||||
relativeStartMs,
|
||||
durationMs,
|
||||
previewRows,
|
||||
ai,
|
||||
}: SpanTooltipContentProps): JSX.Element {
|
||||
const { time: formattedDuration, timeUnitName } =
|
||||
convertTimeToRelevantUnit(durationMs);
|
||||
|
||||
return (
|
||||
<div className={cx(tooltipStyles.body, styles.content)}>
|
||||
<div className={styles.header}>
|
||||
<Typography.Text className={tooltipStyles.title} style={{ color }}>
|
||||
{spanName}
|
||||
</Typography.Text>
|
||||
{ai?.usage && (
|
||||
<Typography.Text size="small" weight="medium">
|
||||
Usage Breakdown
|
||||
</Typography.Text>
|
||||
)}
|
||||
<div className={styles.content}>
|
||||
<div className={styles.name} style={{ color }}>
|
||||
{spanName}
|
||||
</div>
|
||||
<div className={styles.row}>status: {hasError ? 'error' : 'ok'}</div>
|
||||
<div className={styles.row}>start: {toFixed(relativeStartMs, 2)} ms</div>
|
||||
<div className={styles.row}>
|
||||
duration: {toFixed(formattedDuration, 2)} {timeUnitName}
|
||||
</div>
|
||||
{ai?.usage && <SpanUsageBreakdown usage={ai.usage} />}
|
||||
<TooltipSection>
|
||||
{ai?.model && <TooltipRow label="model" value={ai.model} />}
|
||||
{ai?.toolName && <TooltipRow label="tool" value={ai.toolName} />}
|
||||
{ai?.agentName && <TooltipRow label="agent" value={ai.agentName} />}
|
||||
<TooltipRow label="status" value={hasError ? 'error' : 'ok'} />
|
||||
<TooltipRow label="start" value={`${toFixed(relativeStartMs, 2)} ms`} />
|
||||
<TooltipRow
|
||||
label="duration"
|
||||
value={`${toFixed(formattedDuration, 2)} ${timeUnitName}`}
|
||||
/>
|
||||
</TooltipSection>
|
||||
{previewRows && previewRows.length > 0 && (
|
||||
<TooltipSection>
|
||||
<div className={styles.preview}>
|
||||
{previewRows.map((row) => (
|
||||
<TooltipRow
|
||||
<div
|
||||
key={row.key}
|
||||
label={row.key}
|
||||
value={row.value}
|
||||
testId={`span-hover-card-preview-${row.key}`}
|
||||
/>
|
||||
className={styles.row}
|
||||
data-testid={`span-hover-card-preview-${row.key}`}
|
||||
>
|
||||
<span className={styles.previewKey}>{row.key}:</span>{' '}
|
||||
<span className={styles.previewValue}>{row.value}</span>
|
||||
</div>
|
||||
))}
|
||||
</TooltipSection>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
@@ -159,7 +137,6 @@ export function SpanHoverCard({
|
||||
relativeStartMs: span.timestamp - traceStartTime,
|
||||
durationMs: span.duration_nano / 1e6,
|
||||
previewRows,
|
||||
ai: getSpanAiDetails(span),
|
||||
},
|
||||
};
|
||||
}, [
|
||||
@@ -189,7 +166,7 @@ export function SpanHoverCard({
|
||||
side="right"
|
||||
align="start"
|
||||
sideOffset={8}
|
||||
className={cx(tooltipStyles.tooltipContent, styles.popover)}
|
||||
className={styles.popover}
|
||||
>
|
||||
{hoverCardData && <SpanTooltipContent {...hoverCardData.tooltip} />}
|
||||
</TooltipContent>
|
||||
|
||||
@@ -1,47 +0,0 @@
|
||||
import {
|
||||
formatCost,
|
||||
formatTokens,
|
||||
getUsageTotals,
|
||||
SpanAiUsage,
|
||||
} from './aiUsage';
|
||||
import TooltipRow from '../TraceTooltip/TooltipRow';
|
||||
import TooltipSection from '../TraceTooltip/TooltipSection';
|
||||
|
||||
interface SpanUsageBreakdownProps {
|
||||
usage: SpanAiUsage;
|
||||
}
|
||||
|
||||
function SpanUsageBreakdown({ usage }: SpanUsageBreakdownProps): JSX.Element {
|
||||
const { outputTokens = 0, cacheReadTokens, cacheCreationTokens, cost } = usage;
|
||||
const { inputUsage, totalUsage } = getUsageTotals(usage);
|
||||
|
||||
return (
|
||||
<>
|
||||
<TooltipSection>
|
||||
<TooltipRow label="Input usage" value={formatTokens(inputUsage)} isTotal />
|
||||
{cacheReadTokens !== undefined && (
|
||||
<TooltipRow label="cache read" value={formatTokens(cacheReadTokens)} />
|
||||
)}
|
||||
{cacheCreationTokens !== undefined && (
|
||||
<TooltipRow
|
||||
label="cache creation"
|
||||
value={formatTokens(cacheCreationTokens)}
|
||||
/>
|
||||
)}
|
||||
</TooltipSection>
|
||||
<TooltipSection>
|
||||
<TooltipRow
|
||||
label="Output usage"
|
||||
value={formatTokens(outputTokens)}
|
||||
isTotal
|
||||
/>
|
||||
</TooltipSection>
|
||||
<TooltipSection>
|
||||
<TooltipRow label="Total usage" value={formatTokens(totalUsage)} isTotal />
|
||||
{cost !== undefined && <TooltipRow label="cost" value={formatCost(cost)} />}
|
||||
</TooltipSection>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default SpanUsageBreakdown;
|
||||
@@ -1,144 +0,0 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import { getSpanAiDetails, getUsageTotals } from '../aiUsage';
|
||||
import { SpanTooltipContent } from '../SpanHoverCard';
|
||||
|
||||
const baseProps = {
|
||||
spanName: 'chat gpt-4o',
|
||||
color: '#fff',
|
||||
hasError: false,
|
||||
relativeStartMs: 268,
|
||||
durationMs: 1110,
|
||||
};
|
||||
|
||||
const spanWith = (attributes: Record<string, string | number>): SpanV3 =>
|
||||
({ attributes, resource: {} }) as unknown as SpanV3;
|
||||
|
||||
const usageAttributes = {
|
||||
'gen_ai.usage.input_tokens': 1000,
|
||||
'gen_ai.usage.output_tokens': 200,
|
||||
'gen_ai.usage.cache_read.input_tokens': 600,
|
||||
'gen_ai.usage.cache_creation.input_tokens': 100,
|
||||
};
|
||||
|
||||
describe('getSpanAiDetails', () => {
|
||||
it('returns undefined for a span without gen_ai attributes', () => {
|
||||
expect(getSpanAiDetails(spanWith({ 'http.method': 'GET' }))).toBeUndefined();
|
||||
});
|
||||
|
||||
it('reads model, tool, agent, token usage and cost', () => {
|
||||
expect(
|
||||
getSpanAiDetails(
|
||||
spanWith({
|
||||
'gen_ai.request.model': 'gpt-4o',
|
||||
'gen_ai.tool.name': 'search',
|
||||
'gen_ai.agent.name': 'planner',
|
||||
'gen_ai.usage.input_tokens': '120',
|
||||
'gen_ai.usage.output_tokens': 30,
|
||||
'signoz.gen_ai.usage.tokens.cost': '0.00000056',
|
||||
}),
|
||||
),
|
||||
).toStrictEqual({
|
||||
model: 'gpt-4o',
|
||||
toolName: 'search',
|
||||
agentName: 'planner',
|
||||
usage: {
|
||||
inputTokens: 120,
|
||||
outputTokens: 30,
|
||||
cacheReadTokens: undefined,
|
||||
cacheCreationTokens: undefined,
|
||||
cost: 0.00000056,
|
||||
isAnthropic: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each<Record<string, string>>([
|
||||
{ 'gen_ai.provider.name': 'Anthropic' },
|
||||
{ 'gen_ai.system': 'anthropic' },
|
||||
{ 'gen_ai.response.model': 'claude-sonnet-4' },
|
||||
{ 'gen_ai.request.model': 'anthropic.claude-v2' },
|
||||
])('detects Anthropic from %p', (attributes) => {
|
||||
expect(
|
||||
getSpanAiDetails(spanWith({ ...usageAttributes, ...attributes }))?.usage
|
||||
?.isAnthropic,
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getUsageTotals', () => {
|
||||
it('adds cache tokens to input for Anthropic', () => {
|
||||
const usage = getSpanAiDetails(
|
||||
spanWith({ ...usageAttributes, 'gen_ai.provider.name': 'anthropic' }),
|
||||
)?.usage;
|
||||
|
||||
expect(usage && getUsageTotals(usage)).toStrictEqual({
|
||||
inputUsage: 1700,
|
||||
totalUsage: 1900,
|
||||
});
|
||||
});
|
||||
|
||||
it('treats input as already including cache tokens for other providers', () => {
|
||||
const usage = getSpanAiDetails(
|
||||
spanWith({ ...usageAttributes, 'gen_ai.provider.name': 'openai' }),
|
||||
)?.usage;
|
||||
|
||||
expect(usage && getUsageTotals(usage)).toStrictEqual({
|
||||
inputUsage: 1000,
|
||||
totalUsage: 1200,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('SpanTooltipContent', () => {
|
||||
it('renders status, start and duration for a non-AI span', () => {
|
||||
render(<SpanTooltipContent {...baseProps} />);
|
||||
|
||||
expect(screen.getByText('chat gpt-4o')).toBeInTheDocument();
|
||||
expect(screen.getByText('ok')).toBeInTheDocument();
|
||||
expect(screen.getByText('268 ms')).toBeInTheDocument();
|
||||
expect(screen.getByText('1.11 s')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Usage Breakdown')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders the usage breakdown with cache rows and cost', () => {
|
||||
render(
|
||||
<SpanTooltipContent
|
||||
{...baseProps}
|
||||
ai={{
|
||||
model: 'gpt-4o',
|
||||
usage: {
|
||||
inputTokens: 1000,
|
||||
outputTokens: 200,
|
||||
cacheReadTokens: 600,
|
||||
cacheCreationTokens: 100,
|
||||
cost: 0.00000056,
|
||||
isAnthropic: false,
|
||||
},
|
||||
}}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText('Usage Breakdown')).toBeInTheDocument();
|
||||
expect(screen.getByText('1,000')).toBeInTheDocument();
|
||||
expect(screen.getByText('cache read')).toBeInTheDocument();
|
||||
expect(screen.getByText('600')).toBeInTheDocument();
|
||||
expect(screen.getByText('cache creation')).toBeInTheDocument();
|
||||
expect(screen.getByText('1,200')).toBeInTheDocument();
|
||||
expect(screen.getByText('$ 0.00000056')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides cache rows and cost when the attributes are absent', () => {
|
||||
render(
|
||||
<SpanTooltipContent
|
||||
{...baseProps}
|
||||
ai={{ usage: { inputTokens: 10, outputTokens: 5, isAnthropic: false } }}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.queryByText('cache read')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('cache creation')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('cost')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,112 +0,0 @@
|
||||
import { getSpanAttribute } from 'pages/TraceDetailsV3/utils';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import { TraceTokenUsage } from '../TraceDetailsHeader/types';
|
||||
import { GEN_AI_KEYS } from '../utils/genAi';
|
||||
|
||||
export interface SpanAiUsage {
|
||||
inputTokens?: number;
|
||||
outputTokens?: number;
|
||||
cacheReadTokens?: number;
|
||||
cacheCreationTokens?: number;
|
||||
cost?: number;
|
||||
isAnthropic: boolean;
|
||||
}
|
||||
|
||||
export interface SpanAiDetails {
|
||||
model?: string;
|
||||
toolName?: string;
|
||||
agentName?: string;
|
||||
usage?: SpanAiUsage;
|
||||
}
|
||||
|
||||
function getNumber(span: SpanV3, key: string): number | undefined {
|
||||
const value = getSpanAttribute(span, key);
|
||||
if (value === undefined || value === '') {
|
||||
return undefined;
|
||||
}
|
||||
const parsed = Number(value);
|
||||
return Number.isFinite(parsed) ? parsed : undefined;
|
||||
}
|
||||
|
||||
function isAnthropicSpan(span: SpanV3): boolean {
|
||||
const provider = (
|
||||
getSpanAttribute(span, GEN_AI_KEYS.providerName) ??
|
||||
getSpanAttribute(span, GEN_AI_KEYS.system) ??
|
||||
''
|
||||
).toLowerCase();
|
||||
const model = (
|
||||
getSpanAttribute(span, GEN_AI_KEYS.responseModel) ??
|
||||
getSpanAttribute(span, GEN_AI_KEYS.requestModel) ??
|
||||
''
|
||||
).toLowerCase();
|
||||
|
||||
return (
|
||||
provider === 'anthropic' ||
|
||||
model.includes('claude') ||
|
||||
model.includes('anthropic')
|
||||
);
|
||||
}
|
||||
|
||||
export function getSpanAiDetails(span: SpanV3): SpanAiDetails | undefined {
|
||||
const usage: SpanAiUsage = {
|
||||
inputTokens: getNumber(span, GEN_AI_KEYS.inputTokens),
|
||||
outputTokens: getNumber(span, GEN_AI_KEYS.outputTokens),
|
||||
cacheReadTokens: getNumber(span, GEN_AI_KEYS.cacheReadTokens),
|
||||
cacheCreationTokens: getNumber(span, GEN_AI_KEYS.cacheCreationTokens),
|
||||
cost: getNumber(span, GEN_AI_KEYS.cost),
|
||||
isAnthropic: isAnthropicSpan(span),
|
||||
};
|
||||
const hasUsage =
|
||||
usage.inputTokens !== undefined || usage.outputTokens !== undefined;
|
||||
|
||||
const details: SpanAiDetails = {
|
||||
model: getSpanAttribute(span, GEN_AI_KEYS.requestModel) || undefined,
|
||||
toolName: getSpanAttribute(span, GEN_AI_KEYS.toolName) || undefined,
|
||||
agentName: getSpanAttribute(span, GEN_AI_KEYS.agentName) || undefined,
|
||||
usage: hasUsage ? usage : undefined,
|
||||
};
|
||||
|
||||
return details.model || details.toolName || details.agentName || hasUsage
|
||||
? details
|
||||
: undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Anthropic reports input_tokens without cached tokens; every other provider
|
||||
* (OpenAI, Azure OpenAI, Gemini, Mistral, DeepSeek, Groq, xAI) counts cached
|
||||
* tokens inside input_tokens.
|
||||
*/
|
||||
export function getUsageTotals(usage: SpanAiUsage): {
|
||||
inputUsage: number;
|
||||
totalUsage: number;
|
||||
} {
|
||||
const input = usage.inputTokens ?? 0;
|
||||
const inputUsage = usage.isAnthropic
|
||||
? input + (usage.cacheReadTokens ?? 0) + (usage.cacheCreationTokens ?? 0)
|
||||
: input;
|
||||
|
||||
return { inputUsage, totalUsage: inputUsage + (usage.outputTokens ?? 0) };
|
||||
}
|
||||
|
||||
export function formatTokens(value: number): string {
|
||||
return value.toLocaleString('en-US');
|
||||
}
|
||||
|
||||
export function formatCost(value: number): string {
|
||||
return `$ ${value.toLocaleString('en-US', { maximumFractionDigits: 10 })}`;
|
||||
}
|
||||
|
||||
export function getSpanTokenUsage(span: SpanV3): TraceTokenUsage | undefined {
|
||||
const usage = getSpanAiDetails(span)?.usage;
|
||||
if (!usage) {
|
||||
return undefined;
|
||||
}
|
||||
return {
|
||||
input: usage.inputTokens ?? 0,
|
||||
output: usage.outputTokens ?? 0,
|
||||
cacheRead: usage.cacheReadTokens,
|
||||
cacheWrite: usage.cacheCreationTokens,
|
||||
reasoning: getNumber(span, GEN_AI_KEYS.reasoningTokens),
|
||||
};
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import AIThreadMessage, {
|
||||
AIThreadMessageProps,
|
||||
} from '../AIThreadMessage/AIThreadMessage';
|
||||
import { ThreadMessage, ThreadView } from '../TraceDetailsThread/types';
|
||||
import RawMessages from './RawMessages';
|
||||
import { RawMessagesValue } from './utils';
|
||||
|
||||
import styles from './SpanMessages.module.scss';
|
||||
|
||||
type MessageProps = Pick<
|
||||
AIThreadMessageProps,
|
||||
'isOutput' | 'isToolLinkEnabled' | 'onToolLinkClick'
|
||||
>;
|
||||
|
||||
interface MessagesSectionProps extends MessageProps {
|
||||
title?: string;
|
||||
view: ThreadView;
|
||||
messages: ThreadMessage[];
|
||||
raw?: RawMessagesValue;
|
||||
testId: string;
|
||||
}
|
||||
|
||||
function MessagesSection({
|
||||
title,
|
||||
view,
|
||||
messages,
|
||||
raw,
|
||||
testId,
|
||||
isOutput,
|
||||
isToolLinkEnabled,
|
||||
onToolLinkClick,
|
||||
}: MessagesSectionProps): JSX.Element | null {
|
||||
const isFormatted = view === ThreadView.Formatted;
|
||||
if (isFormatted ? messages.length === 0 : !raw) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<section className={styles.section} data-testid={testId}>
|
||||
{title && <div className={styles.sectionTitle}>{title}</div>}
|
||||
{isFormatted ? (
|
||||
<div className={styles.messages}>
|
||||
{messages.map((message, index) => (
|
||||
<AIThreadMessage
|
||||
// Messages have no stable id and never reorder.
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={index}
|
||||
message={message}
|
||||
isOutput={isOutput}
|
||||
isToolLinkEnabled={isToolLinkEnabled}
|
||||
onToolLinkClick={onToolLinkClick}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<RawMessages value={raw as RawMessagesValue} />
|
||||
)}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
MessagesSection.defaultProps = {
|
||||
title: undefined,
|
||||
raw: undefined,
|
||||
};
|
||||
|
||||
export default MessagesSection;
|
||||
@@ -1,21 +0,0 @@
|
||||
import JsonBlock from '../AIThreadMessage/JsonBlock';
|
||||
import { RawMessagesValue } from './utils';
|
||||
|
||||
import styles from './SpanMessages.module.scss';
|
||||
|
||||
interface RawMessagesProps {
|
||||
value: RawMessagesValue;
|
||||
}
|
||||
|
||||
function RawMessages({ value }: RawMessagesProps): JSX.Element {
|
||||
if (typeof value === 'object') {
|
||||
return <JsonBlock data={value} />;
|
||||
}
|
||||
return (
|
||||
<pre className={styles.raw} data-testid="span-raw-messages">
|
||||
{value}
|
||||
</pre>
|
||||
);
|
||||
}
|
||||
|
||||
export default RawMessages;
|
||||
@@ -1,49 +0,0 @@
|
||||
.root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-10);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
font-size: var(--font-size-xs);
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.messages {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-10);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.raw {
|
||||
margin: 0;
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l2-background);
|
||||
font-family: var(--font-family-sf-mono);
|
||||
font-size: var(--font-size-xs);
|
||||
line-height: var(--line-height-18);
|
||||
color: var(--l1-foreground);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.missing {
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-style: italic;
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import { AIThreadMessageProps } from '../AIThreadMessage/AIThreadMessage';
|
||||
import { ThreadSpan, ThreadView } from '../TraceDetailsThread/types';
|
||||
import MessagesSection from './MessagesSection';
|
||||
import { getSpanMessages, hasAnyMessages } from './utils';
|
||||
|
||||
import styles from './SpanMessages.module.scss';
|
||||
|
||||
interface SpanMessagesProps extends Pick<
|
||||
AIThreadMessageProps,
|
||||
'isToolLinkEnabled' | 'onToolLinkClick'
|
||||
> {
|
||||
span: ThreadSpan;
|
||||
view: ThreadView;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/** Input and output messages of one AI span, shared by Thread and Span Details. */
|
||||
function SpanMessages({
|
||||
span,
|
||||
view,
|
||||
className,
|
||||
isToolLinkEnabled,
|
||||
onToolLinkClick,
|
||||
}: SpanMessagesProps): JSX.Element {
|
||||
const data = useMemo(() => getSpanMessages(span), [span]);
|
||||
const isFormatted = view === ThreadView.Formatted;
|
||||
const callbacks = { isToolLinkEnabled, onToolLinkClick };
|
||||
|
||||
if (!hasAnyMessages(data)) {
|
||||
return (
|
||||
<div className={styles.missing}>
|
||||
This span has no input or output messages.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={cx(styles.root, className)}>
|
||||
<MessagesSection
|
||||
title={isFormatted ? undefined : 'Input'}
|
||||
view={view}
|
||||
messages={data.formattedInput}
|
||||
raw={data.rawInput}
|
||||
testId="span-messages-input"
|
||||
{...callbacks}
|
||||
/>
|
||||
<MessagesSection
|
||||
title={isFormatted ? undefined : 'Output'}
|
||||
view={view}
|
||||
messages={data.formattedOutput}
|
||||
raw={data.rawOutput}
|
||||
isOutput
|
||||
testId="span-messages-output"
|
||||
{...callbacks}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
SpanMessages.defaultProps = {
|
||||
className: undefined,
|
||||
};
|
||||
|
||||
export default SpanMessages;
|
||||
@@ -1,40 +0,0 @@
|
||||
import { parseJsonObject } from '../AIThreadMessage/utils';
|
||||
import { ThreadMessage, ThreadSpan } from '../TraceDetailsThread/types';
|
||||
import { GEN_AI_KEYS } from '../utils/genAi';
|
||||
|
||||
/** Parsed JSON, or the original string when it isn't JSON. */
|
||||
export type RawMessagesValue = object | string;
|
||||
|
||||
export interface SpanMessagesData {
|
||||
formattedInput: ThreadMessage[];
|
||||
formattedOutput: ThreadMessage[];
|
||||
rawInput?: RawMessagesValue;
|
||||
rawOutput?: RawMessagesValue;
|
||||
}
|
||||
|
||||
function toRawValue(value: unknown): RawMessagesValue | undefined {
|
||||
if (value === undefined || value === null || value === '') {
|
||||
return undefined;
|
||||
}
|
||||
if (typeof value === 'string') {
|
||||
return parseJsonObject(value) ?? value;
|
||||
}
|
||||
return typeof value === 'object' ? value : JSON.stringify(value);
|
||||
}
|
||||
|
||||
export function getSpanMessages(span: ThreadSpan): SpanMessagesData {
|
||||
return {
|
||||
formattedInput: span.formatted_input ?? [],
|
||||
formattedOutput: span.formatted_output ?? [],
|
||||
rawInput: toRawValue(span.attributes?.[GEN_AI_KEYS.inputMessages]),
|
||||
rawOutput: toRawValue(span.attributes?.[GEN_AI_KEYS.outputMessages]),
|
||||
};
|
||||
}
|
||||
|
||||
export function hasFormattedMessages(data: SpanMessagesData): boolean {
|
||||
return data.formattedInput.length > 0 || data.formattedOutput.length > 0;
|
||||
}
|
||||
|
||||
export function hasAnyMessages(data: SpanMessagesData): boolean {
|
||||
return hasFormattedMessages(data) || !!data.rawInput || !!data.rawOutput;
|
||||
}
|
||||
@@ -34,15 +34,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.tabs {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.tab {
|
||||
flex: unset;
|
||||
padding: 0 24px;
|
||||
}
|
||||
|
||||
.filterSection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import {
|
||||
@@ -18,26 +18,40 @@ import KeyValueLabel from 'periscope/components/KeyValueLabel';
|
||||
import { TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { TraceDetailEventKeys, TraceDetailEvents } from '../events';
|
||||
import { useTraceDetailLogEvent } from '../hooks/useTraceDetailLogEvent';
|
||||
import { useTraceDetailsTab } from '../hooks/useTraceDetailsTab';
|
||||
import { useTraceStore } from '../stores/traceStore';
|
||||
import TraceDownloadPanel from './TraceDownloadPanel';
|
||||
import EntityMetadataRow from '../EntityMetadata/EntityMetadataRow';
|
||||
import AnalyticsPanel from '../SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel';
|
||||
import Filters from '../TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters';
|
||||
import { useTraceDetailsStripInfo } from '../useTraceDetailsStripInfo';
|
||||
import MissingSpansBanner from './MissingSpansBanner';
|
||||
import { useTraceSummary } from './useTraceSummary';
|
||||
import TraceDetailsTabs from './TraceDetailsTabs';
|
||||
import TraceOptionsMenu from './TraceOptionsMenu';
|
||||
|
||||
import styles from './TraceDetailsHeader.module.scss';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
|
||||
interface FilterMetadata {
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
traceId: string;
|
||||
}
|
||||
|
||||
export interface TraceMetadataForHeader {
|
||||
startTimestampMillis: number;
|
||||
endTimestampMillis: number;
|
||||
rootServiceName: string;
|
||||
rootServiceEntryPoint: string;
|
||||
rootSpanStatusCode: string;
|
||||
hasMissingSpans: boolean;
|
||||
totalSpansCount: number;
|
||||
}
|
||||
|
||||
interface TraceDetailsHeaderProps {
|
||||
onFilteredSpansChange?: (spanIds: string[], isFilterActive: boolean) => void;
|
||||
filterMetadata: FilterMetadata;
|
||||
onFilteredSpansChange: (spanIds: string[], isFilterActive: boolean) => void;
|
||||
isDataLoaded?: boolean;
|
||||
traceMetadata?: TraceMetadataForHeader;
|
||||
}
|
||||
|
||||
const SKELETON_COUNT = 3;
|
||||
@@ -59,22 +73,16 @@ function DetailsLoader(): JSX.Element {
|
||||
}
|
||||
|
||||
function TraceDetailsHeader({
|
||||
filterMetadata,
|
||||
onFilteredSpansChange,
|
||||
isDataLoaded,
|
||||
traceMetadata,
|
||||
}: TraceDetailsHeaderProps): JSX.Element {
|
||||
const { id: traceID } = useParams<TraceDetailV3URLProps>();
|
||||
const { data: summary, isLoading } = useTraceSummary();
|
||||
const [showTraceDetails, setShowTraceDetails] = useState(true);
|
||||
const [isFilterExpanded, setIsFilterExpanded] = useState(false);
|
||||
const [isPreviewFieldsOpen, setIsPreviewFieldsOpen] = useState(false);
|
||||
const [isAnalyticsOpen, setIsAnalyticsOpen] = useState(false);
|
||||
const [tab] = useTraceDetailsTab();
|
||||
const isOverview = tab === TraceDetailsTab.Overview;
|
||||
|
||||
// Overview-only panels must not linger over another tab.
|
||||
useEffect(() => {
|
||||
setIsPreviewFieldsOpen(false);
|
||||
setIsAnalyticsOpen(false);
|
||||
}, [tab]);
|
||||
const previewFields = useTraceStore((s) => s.previewFields);
|
||||
const setPreviewFields = useTraceStore((s) => s.setPreviewFields);
|
||||
|
||||
@@ -108,13 +116,9 @@ function TraceDetailsHeader({
|
||||
setShowTraceDetails((prev) => !prev);
|
||||
}, []);
|
||||
|
||||
useTraceDetailsStripInfo({
|
||||
totalSpansCount: summary?.totalSpansCount ?? 0,
|
||||
totalErrorSpansCount: summary?.totalErrorSpansCount ?? 0,
|
||||
});
|
||||
|
||||
const startTime = (summary?.startTimestampMillis ?? 0) / 1e3;
|
||||
const endTime = (summary?.endTimestampMillis ?? 0) / 1e3;
|
||||
const durationMs = traceMetadata
|
||||
? traceMetadata.endTimestampMillis - traceMetadata.startTimestampMillis
|
||||
: 0;
|
||||
|
||||
return (
|
||||
<div className={styles.wrapper}>
|
||||
@@ -136,10 +140,9 @@ function TraceDetailsHeader({
|
||||
badgeValue={traceID || ''}
|
||||
maxCharacters={100}
|
||||
/>
|
||||
<TraceDetailsTabs />
|
||||
</div>
|
||||
)}
|
||||
{isOverview && onFilteredSpansChange && summary && (
|
||||
{isDataLoaded && (
|
||||
<div
|
||||
className={cx(
|
||||
styles.filterSection,
|
||||
@@ -168,9 +171,9 @@ function TraceDetailsHeader({
|
||||
onToggleTraceDetails={handleToggleTraceDetails}
|
||||
onOpenPreviewFields={(): void => setIsPreviewFieldsOpen(true)}
|
||||
traceId={traceID || ''}
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
totalSpansCount={summary.totalSpansCount}
|
||||
startTime={filterMetadata.startTime}
|
||||
endTime={filterMetadata.endTime}
|
||||
totalSpansCount={traceMetadata?.totalSpansCount || 0}
|
||||
/>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
@@ -180,9 +183,9 @@ function TraceDetailsHeader({
|
||||
className={cx(styles.filter, isFilterExpanded && styles.isExpanded)}
|
||||
>
|
||||
<Filters
|
||||
startTime={startTime}
|
||||
endTime={endTime}
|
||||
traceID={traceID || ''}
|
||||
startTime={filterMetadata.startTime}
|
||||
endTime={filterMetadata.endTime}
|
||||
traceID={filterMetadata.traceId}
|
||||
onFilteredSpansChange={onFilteredSpansChange}
|
||||
isExpanded={isFilterExpanded}
|
||||
onExpand={(): void => setIsFilterExpanded(true)}
|
||||
@@ -193,29 +196,28 @@ function TraceDetailsHeader({
|
||||
)}
|
||||
</div>
|
||||
|
||||
{(showTraceDetails || !isOverview) && (
|
||||
{showTraceDetails && (
|
||||
<div className={styles.subHeader}>
|
||||
{isLoading || !summary ? (
|
||||
<DetailsLoader />
|
||||
) : (
|
||||
{traceMetadata ? (
|
||||
<EntityMetadataRow
|
||||
entity="trace"
|
||||
service={{
|
||||
name: summary.rootServiceName,
|
||||
entryPoint: summary.rootServiceEntryPoint,
|
||||
name: traceMetadata.rootServiceName,
|
||||
entryPoint: traceMetadata.rootServiceEntryPoint,
|
||||
}}
|
||||
durationMs={summary.endTimestampMillis - summary.startTimestampMillis}
|
||||
timestamp={dayjs(summary.startTimestampMillis).format(
|
||||
durationMs={durationMs}
|
||||
timestamp={dayjs(traceMetadata.startTimestampMillis).format(
|
||||
DATE_TIME_FORMATS.DD_MMM_YYYY_HH_MM_SS,
|
||||
)}
|
||||
tokens={summary.ai?.tokens}
|
||||
cost={summary.ai?.totalCost}
|
||||
statusCode={traceMetadata.rootSpanStatusCode}
|
||||
/>
|
||||
) : (
|
||||
<DetailsLoader />
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isOverview && summary?.hasMissingSpans && <MissingSpansBanner />}
|
||||
{traceMetadata?.hasMissingSpans && <MissingSpansBanner />}
|
||||
|
||||
<FieldsSelector
|
||||
isOpen={isPreviewFieldsOpen}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { ToggleGroup, ToggleGroupItem } from '@signozhq/ui/toggle-group';
|
||||
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { useTraceDetailsTab } from '../hooks/useTraceDetailsTab';
|
||||
|
||||
import styles from './TraceDetailsHeader.module.scss';
|
||||
|
||||
function TraceDetailsTabs(): JSX.Element {
|
||||
const [tab, setTab] = useTraceDetailsTab();
|
||||
|
||||
const handleChange = (value: string): void => {
|
||||
// Clicking the active item deselects it and reports ''.
|
||||
if (value) {
|
||||
void setTab(value as TraceDetailsTab);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ToggleGroup
|
||||
type="single"
|
||||
value={tab}
|
||||
onChange={handleChange}
|
||||
className={styles.tabs}
|
||||
size="sm"
|
||||
>
|
||||
<ToggleGroupItem
|
||||
value={TraceDetailsTab.Overview}
|
||||
className={styles.tab}
|
||||
data-testid="trace-details-tab-overview"
|
||||
>
|
||||
Overview
|
||||
</ToggleGroupItem>
|
||||
<ToggleGroupItem
|
||||
value={TraceDetailsTab.Thread}
|
||||
className={styles.tab}
|
||||
data-testid="trace-details-tab-thread"
|
||||
>
|
||||
Thread
|
||||
</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
);
|
||||
}
|
||||
|
||||
export default TraceDetailsTabs;
|
||||
@@ -1,12 +1,9 @@
|
||||
import { fireEvent, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
|
||||
import { NuqsTestingAdapter } from 'nuqs/adapters/testing';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { render } from 'tests/test-utils';
|
||||
|
||||
import { MOCK_TRACE_SUMMARY } from '../mockTraceSummary';
|
||||
import * as traceSummaryModule from '../useTraceSummary';
|
||||
import TraceDetailsHeader from '../TraceDetailsHeader';
|
||||
|
||||
const mockGoBack = jest.fn();
|
||||
@@ -53,9 +50,15 @@ jest.mock('components/FieldsSelector', () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
const baseProps = { onFilteredSpansChange: jest.fn() };
|
||||
|
||||
const metadataText = /Missing Span/;
|
||||
const baseProps = {
|
||||
filterMetadata: {
|
||||
startTime: 0,
|
||||
endTime: 1,
|
||||
traceId: 'trace-123',
|
||||
},
|
||||
onFilteredSpansChange: jest.fn(),
|
||||
isDataLoaded: false,
|
||||
};
|
||||
|
||||
describe('TraceDetailsHeader – back button', () => {
|
||||
beforeEach(() => {
|
||||
@@ -91,8 +94,8 @@ describe('TraceDetailsHeader – action cluster', () => {
|
||||
mockReplace.mockClear();
|
||||
});
|
||||
|
||||
it('does not render the action buttons without a filter handler', () => {
|
||||
render(<TraceDetailsHeader />);
|
||||
it('does not render the action buttons while data is still loading', () => {
|
||||
render(<TraceDetailsHeader {...baseProps} isDataLoaded={false} />);
|
||||
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /^analytics$/i }),
|
||||
@@ -102,8 +105,8 @@ describe('TraceDetailsHeader – action cluster', () => {
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders Analytics and Settings action buttons', () => {
|
||||
render(<TraceDetailsHeader {...baseProps} />);
|
||||
it('renders Analytics and Settings action buttons once data is loaded', () => {
|
||||
render(<TraceDetailsHeader {...baseProps} isDataLoaded />);
|
||||
|
||||
expect(
|
||||
screen.getByRole('button', { name: /^analytics$/i }),
|
||||
@@ -114,7 +117,7 @@ describe('TraceDetailsHeader – action cluster', () => {
|
||||
});
|
||||
|
||||
it('toggles the AnalyticsPanel open state when the Analytics button is clicked', () => {
|
||||
render(<TraceDetailsHeader {...baseProps} />);
|
||||
render(<TraceDetailsHeader {...baseProps} isDataLoaded />);
|
||||
|
||||
const panel = screen.getByTestId('analytics-panel');
|
||||
expect(panel).toHaveAttribute('data-open', 'false');
|
||||
@@ -130,125 +133,68 @@ describe('TraceDetailsHeader – action cluster', () => {
|
||||
});
|
||||
|
||||
describe('TraceDetailsHeader – trace metadata row', () => {
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
// Plain prop, no API mock needed: traceMetadata is passed straight in.
|
||||
const traceMetadata = {
|
||||
startTimestampMillis: 1_700_000_000_000,
|
||||
endTimestampMillis: 1_700_000_120_000, // +120000ms = 2 min
|
||||
rootServiceName: 'inventory-frontend',
|
||||
rootServiceEntryPoint: 'large-trace-root',
|
||||
rootSpanStatusCode: '404',
|
||||
hasMissingSpans: false,
|
||||
totalSpansCount: 42,
|
||||
};
|
||||
|
||||
it('shows skeletons instead of the metadata while the summary loads', () => {
|
||||
jest
|
||||
.spyOn(traceSummaryModule, 'useTraceSummary')
|
||||
.mockReturnValue({ data: undefined, isLoading: true });
|
||||
const { container } = render(<TraceDetailsHeader {...baseProps} />);
|
||||
|
||||
expect(screen.queryByText(metadataText)).not.toBeInTheDocument();
|
||||
expect(container.querySelectorAll('.ant-skeleton-input')).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('renders the summary metadata with tokens and cost', () => {
|
||||
render(<TraceDetailsHeader {...baseProps} />);
|
||||
|
||||
const { startTimestampMillis, endTimestampMillis } = MOCK_TRACE_SUMMARY;
|
||||
const duration = getYAxisFormattedValue(
|
||||
`${endTimestampMillis - startTimestampMillis}`,
|
||||
'ms',
|
||||
it('renders the metadata (service, entry point, duration, status) when provided', () => {
|
||||
render(
|
||||
<TraceDetailsHeader
|
||||
{...baseProps}
|
||||
isDataLoaded
|
||||
traceMetadata={traceMetadata}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(metadataText)).toBeInTheDocument();
|
||||
expect(screen.getByText(/inventory-frontend/)).toBeInTheDocument();
|
||||
expect(screen.getByText('large-trace-root')).toBeInTheDocument();
|
||||
expect(screen.getByText('404')).toBeInTheDocument();
|
||||
// Duration goes through the shared formatter (e.g. "2 min").
|
||||
const duration = getYAxisFormattedValue(
|
||||
`${traceMetadata.endTimestampMillis - traceMetadata.startTimestampMillis}`,
|
||||
'ms',
|
||||
);
|
||||
expect(screen.getByText(duration)).toBeInTheDocument();
|
||||
expect(screen.getByText('Tokens: 12,040 → 3,110')).toBeInTheDocument();
|
||||
expect(screen.getByText('$ 0.0421')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('is shown by default and can be hidden / shown again via the Trace options menu', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
render(<TraceDetailsHeader {...baseProps} />);
|
||||
render(
|
||||
<TraceDetailsHeader
|
||||
{...baseProps}
|
||||
isDataLoaded
|
||||
traceMetadata={traceMetadata}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByText(metadataText)).toBeInTheDocument();
|
||||
// Visible by default (showTraceDetails defaults to true).
|
||||
expect(screen.getByText(/inventory-frontend/)).toBeInTheDocument();
|
||||
|
||||
// Hide it.
|
||||
await user.click(screen.getByRole('button', { name: /trace options/i }));
|
||||
await user.click(
|
||||
await screen.findByRole('menuitem', { name: /hide trace details/i }),
|
||||
);
|
||||
expect(screen.queryByText(metadataText)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText(/inventory-frontend/)).not.toBeInTheDocument();
|
||||
|
||||
// Show it again.
|
||||
await user.click(screen.getByRole('button', { name: /trace options/i }));
|
||||
await user.click(
|
||||
await screen.findByRole('menuitem', { name: /show trace details/i }),
|
||||
);
|
||||
expect(screen.getByText(metadataText)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TraceDetailsHeader – tabs', () => {
|
||||
// In-memory URL state, so a tab switch can't leak into the next test.
|
||||
const renderHeader = (): void => {
|
||||
render(
|
||||
<NuqsTestingAdapter hasMemory>
|
||||
<TraceDetailsHeader {...baseProps} />
|
||||
</NuqsTestingAdapter>,
|
||||
);
|
||||
};
|
||||
|
||||
it('shows the Overview-only sections on the Overview tab', () => {
|
||||
renderHeader();
|
||||
|
||||
expect(screen.getByTestId('filters-stub')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /^analytics$/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByRole('button', { name: /trace options/i }),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByTestId('missing-spans-banner')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps only the metadata row on the Thread tab', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderHeader();
|
||||
|
||||
await user.click(screen.getByTestId('trace-details-tab-thread'));
|
||||
|
||||
expect(screen.queryByTestId('filters-stub')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /^analytics$/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: /trace options/i }),
|
||||
).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('missing-spans-banner')).not.toBeInTheDocument();
|
||||
expect(screen.getByText(metadataText)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the metadata row on the Thread tab even when hidden on Overview', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderHeader();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /trace options/i }));
|
||||
await user.click(
|
||||
await screen.findByRole('menuitem', { name: /hide trace details/i }),
|
||||
);
|
||||
expect(screen.queryByText(metadataText)).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByTestId('trace-details-tab-thread'));
|
||||
|
||||
expect(screen.getByText(metadataText)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes the Analytics panel when switching to the Thread tab', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderHeader();
|
||||
|
||||
await user.click(screen.getByRole('button', { name: /^analytics$/i }));
|
||||
expect(screen.getByTestId('analytics-panel')).toHaveAttribute(
|
||||
'data-open',
|
||||
'true',
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('trace-details-tab-thread'));
|
||||
|
||||
expect(screen.getByTestId('analytics-panel')).toHaveAttribute(
|
||||
'data-open',
|
||||
'false',
|
||||
);
|
||||
expect(screen.getByText(/inventory-frontend/)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render the metadata row when traceMetadata is absent', () => {
|
||||
render(<TraceDetailsHeader {...baseProps} isDataLoaded />);
|
||||
|
||||
expect(screen.queryByText(/inventory-frontend/)).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
import { TraceSummary } from './types';
|
||||
|
||||
// Placeholder until GET /api/v1/traces/{id}/summary feeds the header.
|
||||
export const MOCK_TRACE_SUMMARY: TraceSummary = {
|
||||
startTimestampMillis: 1789627365929,
|
||||
endTimestampMillis: 1789627367867,
|
||||
rootServiceName: '',
|
||||
rootServiceEntryPoint: 'Missing Span',
|
||||
totalSpansCount: 3,
|
||||
totalErrorSpansCount: 0,
|
||||
hasMissingSpans: true,
|
||||
ai: {
|
||||
tokens: {
|
||||
input: 12040,
|
||||
output: 3110,
|
||||
cacheRead: 8000,
|
||||
cacheWrite: 1200,
|
||||
reasoning: 900,
|
||||
},
|
||||
totalCost: 0.0421,
|
||||
},
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
export interface TraceTokenUsage {
|
||||
input: number;
|
||||
output: number;
|
||||
cacheRead?: number;
|
||||
cacheWrite?: number;
|
||||
reasoning?: number;
|
||||
}
|
||||
|
||||
/** Response of GET /api/v1/traces/{id}/summary. */
|
||||
export interface TraceSummary {
|
||||
startTimestampMillis: number;
|
||||
endTimestampMillis: number;
|
||||
rootServiceName: string;
|
||||
rootServiceEntryPoint: string;
|
||||
totalSpansCount: number;
|
||||
totalErrorSpansCount: number;
|
||||
hasMissingSpans: boolean;
|
||||
ai?: {
|
||||
tokens?: TraceTokenUsage;
|
||||
// null when no span has a cost attribute
|
||||
totalCost: number | null;
|
||||
};
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { MOCK_TRACE_SUMMARY } from './mockTraceSummary';
|
||||
import { TraceSummary } from './types';
|
||||
|
||||
interface UseTraceSummaryResult {
|
||||
data: TraceSummary | undefined;
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
// Placeholder until GET /api/v1/traces/{id}/summary is available.
|
||||
export function useTraceSummary(): UseTraceSummaryResult {
|
||||
return { data: MOCK_TRACE_SUMMARY, isLoading: false };
|
||||
}
|
||||
@@ -1,500 +0,0 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import {
|
||||
ChartNoAxesGantt,
|
||||
ChevronDown,
|
||||
ChevronRight,
|
||||
Info,
|
||||
TriangleAlert,
|
||||
} from '@signozhq/icons';
|
||||
import getLocalStorageKey from 'api/browser/localstorage/get';
|
||||
import setLocalStorageKey from 'api/browser/localstorage/set';
|
||||
import { Collapse } from 'antd';
|
||||
import { useDetailsPanel } from 'components/DetailsPanel';
|
||||
import WarningPopover from 'components/WarningPopover/WarningPopover';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import useGetTraceV4 from 'hooks/trace/useGetTraceV4';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { ResizableBox } from 'periscope/components/ResizableBox';
|
||||
import { SpanV3, TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import { TraceDetailEventKeys, TraceDetailEvents } from '../events';
|
||||
import { useTraceDetailLogEvent } from '../hooks/useTraceDetailLogEvent';
|
||||
import NoData from '../NoData/NoData';
|
||||
import {
|
||||
setTraceStoreAvailableColorByFields,
|
||||
useTraceStore,
|
||||
} from '../stores/traceStore';
|
||||
import { SpanDetailVariant } from '../SpanDetailsPanel/constants';
|
||||
import SpanDetailsPanel from '../SpanDetailsPanel/SpanDetailsPanel';
|
||||
import { FLAMEGRAPH_SPAN_LIMIT } from '../TraceFlamegraph/constants';
|
||||
import TraceFlamegraph from '../TraceFlamegraph/TraceFlamegraph';
|
||||
import TraceWaterfall from '../TraceWaterfall/TraceWaterfall';
|
||||
import { IInterestedSpan } from '../TraceWaterfall/types';
|
||||
import { getAncestorSpanIds } from '../TraceWaterfall/utils';
|
||||
import { getAvailableColorByFieldNames } from '../utils';
|
||||
|
||||
import cx from 'classnames';
|
||||
|
||||
import styles from './TraceDetailsOverview.module.scss';
|
||||
|
||||
// Lucide chevrons for the flame/waterfall accordion headers, matching the
|
||||
// span-tree chevrons in the waterfall.
|
||||
function renderPanelExpandIcon({
|
||||
isActive,
|
||||
}: {
|
||||
isActive?: boolean;
|
||||
}): JSX.Element {
|
||||
return isActive ? <ChevronDown size={14} /> : <ChevronRight size={14} />;
|
||||
}
|
||||
|
||||
interface TraceDetailsOverviewProps {
|
||||
filteredSpanIds: string[];
|
||||
isFilterActive: boolean;
|
||||
}
|
||||
|
||||
function TraceDetailsOverview({
|
||||
filteredSpanIds,
|
||||
isFilterActive,
|
||||
}: TraceDetailsOverviewProps): JSX.Element {
|
||||
const { id: traceId } = useParams<TraceDetailV3URLProps>();
|
||||
const urlQuery = useUrlQuery();
|
||||
const [interestedSpanId, setInterestedSpanId] = useState<IInterestedSpan>(
|
||||
() => ({
|
||||
spanId: urlQuery.get('spanId') || '',
|
||||
isUncollapsed: urlQuery.get('spanId') !== '',
|
||||
}),
|
||||
);
|
||||
const [uncollapsedNodes, setUncollapsedNodes] = useState<string[]>([]);
|
||||
const [localUncollapsedNodes, setLocalUncollapsedNodes] = useState<
|
||||
Set<string>
|
||||
>(new Set());
|
||||
const [selectedSpan, setSelectedSpan] = useState<SpanV3>();
|
||||
|
||||
const selectedSpanId = urlQuery.get('spanId') || undefined;
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
|
||||
const logTraceEvent = useTraceDetailLogEvent('v3', traceId || '');
|
||||
// Tracks which traceId the load event already fired for, so navigating
|
||||
// between traces (the route component stays mounted) re-fires it once each.
|
||||
const dataLoadedFiredForRef = useRef('');
|
||||
const colorByField = useTraceStore((s) => s.colorByField);
|
||||
const previewFieldsCount = useTraceStore((s) => s.previewFields.length);
|
||||
const userPrefsReady = useTraceStore((s) => s.userPreferences !== null);
|
||||
|
||||
const handleSpanDetailsClose = useCallback((): void => {
|
||||
urlQuery.delete('spanId');
|
||||
safeNavigate({ search: urlQuery.toString() }, { replace: true });
|
||||
}, [urlQuery, safeNavigate]);
|
||||
|
||||
const panelState = useDetailsPanel({
|
||||
entityId: selectedSpanId,
|
||||
onClose: handleSpanDetailsClose,
|
||||
});
|
||||
|
||||
const allSpansRef = useRef<SpanV3[]>([]);
|
||||
const deepLinkResolvedRef = useRef(false);
|
||||
|
||||
// Refetch only when the URL target isn't already loaded. Keeps row clicks
|
||||
// and other in-window URL navigation from triggering a backend window slide.
|
||||
useEffect(() => {
|
||||
const spanId = urlQuery.get('spanId') || '';
|
||||
if (!spanId) {
|
||||
return;
|
||||
}
|
||||
const idx = allSpansRef.current.findIndex((s) => s.span_id === spanId);
|
||||
if (idx !== -1) {
|
||||
setSelectedSpan(allSpansRef.current[idx]);
|
||||
return;
|
||||
}
|
||||
setInterestedSpanId({ spanId, isUncollapsed: true });
|
||||
}, [urlQuery]);
|
||||
|
||||
// Once all spans are loaded (frontend mode), freeze query params so
|
||||
// subsequent interestedSpanId changes don't trigger unnecessary refetches.
|
||||
const fullDataLoadedRef = useRef(false);
|
||||
const frozenParamsRef = useRef({
|
||||
selectedSpanId: interestedSpanId.spanId,
|
||||
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
|
||||
uncollapsedSpans: uncollapsedNodes,
|
||||
});
|
||||
|
||||
const queryParams = fullDataLoadedRef.current
|
||||
? frozenParamsRef.current
|
||||
: {
|
||||
selectedSpanId: interestedSpanId.spanId,
|
||||
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
|
||||
uncollapsedSpans: uncollapsedNodes,
|
||||
};
|
||||
|
||||
const {
|
||||
data: traceData,
|
||||
isFetching: isFetchingTraceData,
|
||||
error: errorFetchingTraceData,
|
||||
} = useGetTraceV4({
|
||||
traceId,
|
||||
uncollapsedSpans: queryParams.uncollapsedSpans,
|
||||
selectedSpanId: queryParams.selectedSpanId,
|
||||
isSelectedSpanIDUnCollapsed: queryParams.isSelectedSpanIDUnCollapsed,
|
||||
});
|
||||
|
||||
const allSpans = traceData?.payload?.spans || [];
|
||||
const totalSpansCount = traceData?.payload?.totalSpansCount || 0;
|
||||
|
||||
const isFullDataLoaded =
|
||||
totalSpansCount > 0 && totalSpansCount <= allSpans.length;
|
||||
|
||||
// Color-by options, gated on fields in loaded spans. Resource attrs are
|
||||
// trace-wide, so any window has the full set — no need to accumulate.
|
||||
const availableColorByFields = useMemo(() => {
|
||||
const spans = traceData?.payload?.spans;
|
||||
return spans?.length ? getAvailableColorByFieldNames(spans) : undefined;
|
||||
}, [traceData?.payload?.spans]);
|
||||
|
||||
useEffect(() => {
|
||||
setTraceStoreAvailableColorByFields(availableColorByFields);
|
||||
}, [availableColorByFields]);
|
||||
|
||||
// Lock the ref once we confirm all data is loaded
|
||||
if (isFullDataLoaded && !fullDataLoadedRef.current) {
|
||||
fullDataLoadedRef.current = true;
|
||||
frozenParamsRef.current = {
|
||||
selectedSpanId: interestedSpanId.spanId,
|
||||
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
|
||||
uncollapsedSpans: uncollapsedNodes,
|
||||
};
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
allSpansRef.current = allSpans;
|
||||
}, [allSpans]);
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!traceId ||
|
||||
dataLoadedFiredForRef.current === traceId ||
|
||||
!userPrefsReady
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const payload = traceData?.payload;
|
||||
if (!payload?.spans?.length) {
|
||||
return;
|
||||
}
|
||||
dataLoadedFiredForRef.current = traceId;
|
||||
const numServices = new Set(payload.spans.map((s) => s['service.name'])).size;
|
||||
logTraceEvent(TraceDetailEvents.DataLoaded, {
|
||||
[TraceDetailEventKeys.TotalSpansCount]: totalSpansCount,
|
||||
[TraceDetailEventKeys.NumServices]: numServices,
|
||||
[TraceDetailEventKeys.TraceDurationMs]:
|
||||
payload.endTimestampMillis - payload.startTimestampMillis,
|
||||
[TraceDetailEventKeys.HadErrors]: (payload.totalErrorSpansCount || 0) > 0,
|
||||
[TraceDetailEventKeys.FlamegraphSampled]:
|
||||
totalSpansCount > FLAMEGRAPH_SPAN_LIMIT,
|
||||
[TraceDetailEventKeys.SpanPanelVariant]:
|
||||
getLocalStorageKey(LOCALSTORAGE.TRACE_DETAILS_SPAN_DETAILS_POSITION) ||
|
||||
SpanDetailVariant.DOCKED_RIGHT,
|
||||
[TraceDetailEventKeys.ColorByField]: colorByField.name,
|
||||
[TraceDetailEventKeys.PreviewFieldsCount]: previewFieldsCount,
|
||||
});
|
||||
}, [
|
||||
traceId,
|
||||
userPrefsReady,
|
||||
traceData,
|
||||
totalSpansCount,
|
||||
colorByField,
|
||||
previewFieldsCount,
|
||||
logTraceEvent,
|
||||
]);
|
||||
|
||||
// Frontend mode: expand all parents by default when full data arrives
|
||||
useEffect(() => {
|
||||
if (isFullDataLoaded && allSpans.length > 0) {
|
||||
const parentIds = new Set(
|
||||
allSpans.filter((s) => s.has_children).map((s) => s.span_id),
|
||||
);
|
||||
setLocalUncollapsedNodes(parentIds);
|
||||
}
|
||||
}, [isFullDataLoaded, allSpans]);
|
||||
|
||||
// Backend mode: sync uncollapsed state from API response
|
||||
useEffect(() => {
|
||||
if (
|
||||
!isFullDataLoaded &&
|
||||
traceData &&
|
||||
traceData.payload &&
|
||||
traceData.payload.uncollapsedSpans
|
||||
) {
|
||||
setUncollapsedNodes(traceData.payload.uncollapsedSpans);
|
||||
}
|
||||
}, [traceData, isFullDataLoaded]);
|
||||
|
||||
// Tracks whether we've already done the initial URL→selectedSpan handoff
|
||||
//Lets `interestedSpanId` stay purely as the refetch trigger in frontend mode.
|
||||
useEffect(() => {
|
||||
if (deepLinkResolvedRef.current) {
|
||||
return;
|
||||
}
|
||||
if (allSpans.length === 0) {
|
||||
return;
|
||||
}
|
||||
if (selectedSpanId) {
|
||||
const span = allSpans.find((s) => s.span_id === selectedSpanId);
|
||||
if (!span) {
|
||||
// Span not in the current window — wait for more data (backend
|
||||
// pagination) before marking resolved.
|
||||
return;
|
||||
}
|
||||
setSelectedSpan(span);
|
||||
} else {
|
||||
setSelectedSpan((prev) => prev ?? allSpans[0]);
|
||||
}
|
||||
deepLinkResolvedRef.current = true;
|
||||
}, [selectedSpanId, allSpans]);
|
||||
|
||||
// Frontend mode: auto-expand ancestors of the URL-targeted span so it's
|
||||
// visible. Keyed on URL `spanId`(selectedSpanId).
|
||||
useEffect(() => {
|
||||
if (!isFullDataLoaded || !selectedSpanId || allSpans.length === 0) {
|
||||
return;
|
||||
}
|
||||
const ancestors = getAncestorSpanIds(allSpans, selectedSpanId);
|
||||
if (ancestors.size === 0) {
|
||||
return;
|
||||
}
|
||||
setLocalUncollapsedNodes((prev) => {
|
||||
// Check if all ancestors are already expanded — avoid unnecessary state update
|
||||
let allPresent = true;
|
||||
for (const id of ancestors) {
|
||||
if (!prev.has(id)) {
|
||||
allPresent = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (allPresent) {
|
||||
return prev;
|
||||
}
|
||||
|
||||
const next = new Set(prev);
|
||||
for (const id of ancestors) {
|
||||
next.add(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, [isFullDataLoaded, selectedSpanId, allSpans]);
|
||||
|
||||
const [activeKeys, setActiveKeys] = useState<string[]>(['flame', 'waterfall']);
|
||||
|
||||
const handleCollapseChange = (key: string): void => {
|
||||
logTraceEvent(
|
||||
key === 'flame'
|
||||
? TraceDetailEvents.FlameGraphToggled
|
||||
: TraceDetailEvents.WaterfallToggled,
|
||||
{ [TraceDetailEventKeys.Expanded]: !activeKeys.includes(key) },
|
||||
);
|
||||
setActiveKeys((prev) =>
|
||||
prev.includes(key) ? prev.filter((k) => k !== key) : [...prev, key],
|
||||
);
|
||||
};
|
||||
|
||||
const [spanDetailVariant, setSpanDetailVariant] = useState<SpanDetailVariant>(
|
||||
() =>
|
||||
(getLocalStorageKey(
|
||||
LOCALSTORAGE.TRACE_DETAILS_SPAN_DETAILS_POSITION,
|
||||
) as SpanDetailVariant) || SpanDetailVariant.DOCKED_RIGHT,
|
||||
);
|
||||
|
||||
const RIGHT_DOCK_MIN = 480;
|
||||
const RIGHT_DOCK_MAX = 720;
|
||||
const [rightDockWidth, setRightDockWidth] = useState(RIGHT_DOCK_MIN);
|
||||
|
||||
const handleVariantChange = useCallback(
|
||||
(newVariant: SpanDetailVariant): void => {
|
||||
setLocalStorageKey(
|
||||
LOCALSTORAGE.TRACE_DETAILS_SPAN_DETAILS_POSITION,
|
||||
newVariant,
|
||||
);
|
||||
setSpanDetailVariant(newVariant);
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const showNoData =
|
||||
!isFetchingTraceData &&
|
||||
(!!errorFetchingTraceData || !traceData?.payload?.spans?.length);
|
||||
|
||||
const isDocked = spanDetailVariant === SpanDetailVariant.DOCKED;
|
||||
const isRightDocked = spanDetailVariant === SpanDetailVariant.DOCKED_RIGHT;
|
||||
const isWaterfallDocked = panelState.isOpen && isDocked;
|
||||
const showRightDock = panelState.isOpen && isRightDocked;
|
||||
|
||||
const waterfallChildren = (
|
||||
<ResizableBox
|
||||
defaultHeight={300}
|
||||
minHeight={150}
|
||||
disabled={!isWaterfallDocked}
|
||||
>
|
||||
<TraceWaterfall
|
||||
traceData={traceData}
|
||||
isFetchingTraceData={isFetchingTraceData}
|
||||
errorFetchingTraceData={errorFetchingTraceData}
|
||||
traceId={traceId || ''}
|
||||
interestedSpanId={interestedSpanId}
|
||||
setInterestedSpanId={setInterestedSpanId}
|
||||
uncollapsedNodes={uncollapsedNodes}
|
||||
isFullDataLoaded={isFullDataLoaded}
|
||||
localUncollapsedNodes={localUncollapsedNodes}
|
||||
setLocalUncollapsedNodes={setLocalUncollapsedNodes}
|
||||
selectedSpan={selectedSpan}
|
||||
setSelectedSpan={setSelectedSpan}
|
||||
filteredSpanIds={filteredSpanIds}
|
||||
isFilterActive={isFilterActive}
|
||||
/>
|
||||
</ResizableBox>
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{showNoData ? (
|
||||
<NoData />
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.layoutRow}>
|
||||
<div className={styles.content}>
|
||||
<Collapse
|
||||
// @ts-expect-error motion is passed through to rc-collapse to disable animation
|
||||
motion={false}
|
||||
activeKey={activeKeys.filter((k) => k === 'flame')}
|
||||
onChange={(): void => handleCollapseChange('flame')}
|
||||
size="small"
|
||||
expandIcon={renderPanelExpandIcon}
|
||||
className={styles.flameCollapse}
|
||||
items={[
|
||||
{
|
||||
key: 'flame',
|
||||
label: (
|
||||
<div className={styles.collapseLabel}>
|
||||
<span className={styles.collapseTitle}>
|
||||
Flame Graph
|
||||
{traceData?.payload?.totalSpansCount &&
|
||||
traceData.payload.totalSpansCount > FLAMEGRAPH_SPAN_LIMIT && (
|
||||
<WarningPopover
|
||||
message="The total span count exceeds the visualization limit. Displaying a sampled subset of spans in flamegraph."
|
||||
placement="bottomLeft"
|
||||
>
|
||||
<Info
|
||||
size={16}
|
||||
color="var(--l2-foreground)"
|
||||
style={{ cursor: 'pointer' }}
|
||||
/>
|
||||
</WarningPopover>
|
||||
)}
|
||||
</span>
|
||||
{traceData?.payload?.totalSpansCount ? (
|
||||
<span className={styles.collapseCount}>
|
||||
<span className={styles.collapseCountItem}>
|
||||
<ChartNoAxesGantt size={13} />
|
||||
Spans: {traceData.payload.totalSpansCount}
|
||||
</span>
|
||||
<span
|
||||
className={cx(styles.collapseCountItem, {
|
||||
[styles.hasErrors]: traceData.payload.totalErrorSpansCount > 0,
|
||||
})}
|
||||
>
|
||||
<TriangleAlert size={13} />
|
||||
Errors:{' '}
|
||||
{traceData.payload.totalErrorSpansCount ?? (
|
||||
<span className="translate-safe">{0}</span>
|
||||
)}
|
||||
</span>
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
),
|
||||
children: (
|
||||
<ResizableBox defaultHeight={300} minHeight={100} maxHeight={400}>
|
||||
<TraceFlamegraph
|
||||
filteredSpanIds={filteredSpanIds}
|
||||
isFilterActive={isFilterActive}
|
||||
selectedSpan={selectedSpan}
|
||||
totalSpansCount={totalSpansCount}
|
||||
/>
|
||||
</ResizableBox>
|
||||
),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
<Collapse
|
||||
// @ts-expect-error motion is passed through to rc-collapse to disable animation
|
||||
motion={false}
|
||||
activeKey={activeKeys.filter((k) => k === 'waterfall')}
|
||||
onChange={(): void => handleCollapseChange('waterfall')}
|
||||
size="small"
|
||||
expandIcon={renderPanelExpandIcon}
|
||||
className={cx(styles.waterfallCollapse, {
|
||||
[styles.isDocked]: isWaterfallDocked,
|
||||
})}
|
||||
items={[
|
||||
{
|
||||
key: 'waterfall',
|
||||
label: 'Waterfall',
|
||||
children: activeKeys.includes('waterfall') ? waterfallChildren : null,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
|
||||
{panelState.isOpen && isDocked && (
|
||||
<div className={styles.dockedSpanDetails}>
|
||||
<SpanDetailsPanel
|
||||
panelState={panelState}
|
||||
selectedSpan={selectedSpan}
|
||||
variant={SpanDetailVariant.DOCKED}
|
||||
onVariantChange={handleVariantChange}
|
||||
traceStartTime={traceData?.payload?.startTimestampMillis}
|
||||
traceEndTime={traceData?.payload?.endTimestampMillis}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{showRightDock && (
|
||||
<ResizableBox
|
||||
handle="left"
|
||||
defaultWidth={rightDockWidth}
|
||||
minWidth={RIGHT_DOCK_MIN}
|
||||
maxWidth={RIGHT_DOCK_MAX}
|
||||
onResize={setRightDockWidth}
|
||||
className={styles.rightDock}
|
||||
>
|
||||
<SpanDetailsPanel
|
||||
panelState={panelState}
|
||||
selectedSpan={selectedSpan}
|
||||
variant={SpanDetailVariant.DOCKED_RIGHT}
|
||||
onVariantChange={handleVariantChange}
|
||||
traceStartTime={traceData?.payload?.startTimestampMillis}
|
||||
traceEndTime={traceData?.payload?.endTimestampMillis}
|
||||
/>
|
||||
</ResizableBox>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{panelState.isOpen && spanDetailVariant === SpanDetailVariant.DIALOG && (
|
||||
<SpanDetailsPanel
|
||||
panelState={panelState}
|
||||
selectedSpan={selectedSpan}
|
||||
variant={SpanDetailVariant.DIALOG}
|
||||
onVariantChange={handleVariantChange}
|
||||
traceStartTime={traceData?.payload?.startTimestampMillis}
|
||||
traceEndTime={traceData?.payload?.endTimestampMillis}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default TraceDetailsOverview;
|
||||
@@ -1,32 +0,0 @@
|
||||
.root {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--spacing-4);
|
||||
padding: var(--spacing-16);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: var(--periscope-font-size-medium);
|
||||
font-weight: var(--font-weight-medium);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.description {
|
||||
max-width: 420px;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: var(--spacing-4);
|
||||
margin-top: var(--spacing-4);
|
||||
}
|
||||
@@ -1,34 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
import styles from './ThreadEmptyState.module.scss';
|
||||
|
||||
interface ThreadEmptyStateProps {
|
||||
icon: ReactNode;
|
||||
title: string;
|
||||
description: string;
|
||||
actions?: ReactNode;
|
||||
testId: string;
|
||||
}
|
||||
|
||||
function ThreadEmptyState({
|
||||
icon,
|
||||
title,
|
||||
description,
|
||||
actions,
|
||||
testId,
|
||||
}: ThreadEmptyStateProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.root} data-testid={testId}>
|
||||
<span className={styles.icon}>{icon}</span>
|
||||
<span className={styles.title}>{title}</span>
|
||||
<span className={styles.description}>{description}</span>
|
||||
{actions && <div className={styles.actions}>{actions}</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
ThreadEmptyState.defaultProps = {
|
||||
actions: undefined,
|
||||
};
|
||||
|
||||
export default ThreadEmptyState;
|
||||
@@ -1,17 +0,0 @@
|
||||
import { Skeleton } from '@signozhq/ui/skeleton';
|
||||
|
||||
import styles from './ThreadSpanList.module.scss';
|
||||
|
||||
interface ThreadPageLoaderProps {
|
||||
testId: string;
|
||||
}
|
||||
|
||||
function ThreadPageLoader({ testId }: ThreadPageLoaderProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.pageLoader} data-testid={testId}>
|
||||
<Skeleton active title={{ width: '30%' }} paragraph={{ rows: 2 }} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ThreadPageLoader;
|
||||
@@ -1,16 +0,0 @@
|
||||
.card {
|
||||
padding: var(--spacing-8);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l1-background);
|
||||
min-width: 0;
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--l3-border);
|
||||
}
|
||||
|
||||
&.isSelected {
|
||||
border-color: var(--primary);
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { memo } from 'react';
|
||||
import cx from 'classnames';
|
||||
|
||||
import SpanMessages from '../SpanMessages/SpanMessages';
|
||||
import { ThreadSpan, ThreadView } from './types';
|
||||
|
||||
import styles from './ThreadSpanCard.module.scss';
|
||||
|
||||
interface ThreadSpanCardProps {
|
||||
span: ThreadSpan;
|
||||
view: ThreadView;
|
||||
isSelected: boolean;
|
||||
onSelect: (span: ThreadSpan) => void;
|
||||
isToolLinkEnabled: (toolCallId: string) => boolean;
|
||||
onToolLinkClick: (toolCallId: string) => void;
|
||||
}
|
||||
|
||||
function ThreadSpanCard({
|
||||
span,
|
||||
view,
|
||||
isSelected,
|
||||
onSelect,
|
||||
isToolLinkEnabled,
|
||||
onToolLinkClick,
|
||||
}: ThreadSpanCardProps): JSX.Element {
|
||||
return (
|
||||
// eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-noninteractive-element-interactions
|
||||
<article
|
||||
className={cx(styles.card, isSelected && styles.isSelected)}
|
||||
onClick={(): void => onSelect(span)}
|
||||
data-span-id={span.span_id}
|
||||
data-testid="thread-span-card"
|
||||
>
|
||||
<SpanMessages
|
||||
span={span}
|
||||
view={view}
|
||||
isToolLinkEnabled={isToolLinkEnabled}
|
||||
onToolLinkClick={onToolLinkClick}
|
||||
/>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(ThreadSpanCard);
|
||||
@@ -1,47 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { DetailsPanelState } from 'components/DetailsPanel/types';
|
||||
import { ResizableBox } from 'periscope/components/ResizableBox';
|
||||
|
||||
import SpanDetailsPanel from '../SpanDetailsPanel/SpanDetailsPanel';
|
||||
import { SpanDetailVariant } from '../SpanDetailsPanel/constants';
|
||||
import { useTraceSummary } from '../TraceDetailsHeader/useTraceSummary';
|
||||
import { ThreadSpan } from './types';
|
||||
|
||||
import styles from './TraceDetailsThread.module.scss';
|
||||
|
||||
const RIGHT_DOCK_MIN = 480;
|
||||
const RIGHT_DOCK_MAX = 720;
|
||||
|
||||
interface ThreadSpanDetailsProps {
|
||||
panelState: DetailsPanelState;
|
||||
span: ThreadSpan;
|
||||
}
|
||||
|
||||
function ThreadSpanDetails({
|
||||
panelState,
|
||||
span,
|
||||
}: ThreadSpanDetailsProps): JSX.Element {
|
||||
const { data: summary } = useTraceSummary();
|
||||
const [width, setWidth] = useState(RIGHT_DOCK_MIN);
|
||||
|
||||
return (
|
||||
<ResizableBox
|
||||
handle="left"
|
||||
defaultWidth={width}
|
||||
minWidth={RIGHT_DOCK_MIN}
|
||||
maxWidth={RIGHT_DOCK_MAX}
|
||||
onResize={setWidth}
|
||||
className={styles.rightDock}
|
||||
>
|
||||
<SpanDetailsPanel
|
||||
panelState={panelState}
|
||||
selectedSpan={span}
|
||||
variant={SpanDetailVariant.DOCKED_RIGHT}
|
||||
traceStartTime={summary?.startTimestampMillis}
|
||||
traceEndTime={summary?.endTimestampMillis}
|
||||
/>
|
||||
</ResizableBox>
|
||||
);
|
||||
}
|
||||
|
||||
export default ThreadSpanDetails;
|
||||
@@ -1,23 +0,0 @@
|
||||
.list {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
padding: var(--spacing-6) var(--spacing-8);
|
||||
// Prepend compensation is manual; native anchoring would double-shift.
|
||||
overflow-anchor: none;
|
||||
}
|
||||
|
||||
.sentinel {
|
||||
flex-shrink: 0;
|
||||
height: 1px;
|
||||
}
|
||||
|
||||
.pageLoader {
|
||||
flex-shrink: 0;
|
||||
padding: var(--spacing-4) var(--spacing-6);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
import { ReactNode, RefObject } from 'react';
|
||||
|
||||
import { useThreadInfiniteScroll } from './hooks/useThreadInfiniteScroll';
|
||||
import ThreadPageLoader from './ThreadPageLoader';
|
||||
|
||||
import styles from './ThreadSpanList.module.scss';
|
||||
|
||||
interface ThreadSpanListProps {
|
||||
listRef: RefObject<HTMLDivElement>;
|
||||
firstItemKey?: string;
|
||||
hasNextPage: boolean;
|
||||
hasPreviousPage: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
isFetchingPreviousPage: boolean;
|
||||
fetchNextPage: () => Promise<unknown>;
|
||||
fetchPreviousPage: () => Promise<unknown>;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function ThreadSpanList({
|
||||
listRef,
|
||||
firstItemKey,
|
||||
hasNextPage,
|
||||
hasPreviousPage,
|
||||
isFetchingNextPage,
|
||||
isFetchingPreviousPage,
|
||||
fetchNextPage,
|
||||
fetchPreviousPage,
|
||||
children,
|
||||
}: ThreadSpanListProps): JSX.Element {
|
||||
const { topSentinelRef, bottomSentinelRef } = useThreadInfiniteScroll({
|
||||
containerRef: listRef,
|
||||
firstItemKey,
|
||||
hasNextPage,
|
||||
hasPreviousPage,
|
||||
isFetchingNextPage,
|
||||
isFetchingPreviousPage,
|
||||
fetchNextPage,
|
||||
fetchPreviousPage,
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={styles.list} ref={listRef} data-testid="thread-span-list">
|
||||
<div ref={topSentinelRef} className={styles.sentinel} />
|
||||
{isFetchingPreviousPage && (
|
||||
<ThreadPageLoader testId="thread-loading-previous" />
|
||||
)}
|
||||
{children}
|
||||
{isFetchingNextPage && <ThreadPageLoader testId="thread-loading-next" />}
|
||||
<div ref={bottomSentinelRef} className={styles.sentinel} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default ThreadSpanList;
|
||||
@@ -1,47 +0,0 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { ArrowLeft, MessagesSquare, SearchX } from '@signozhq/icons';
|
||||
|
||||
import ThreadEmptyState from './ThreadEmptyState';
|
||||
|
||||
interface ThreadSpanNotFoundProps {
|
||||
onGoBack: () => void;
|
||||
onShowThread: () => void;
|
||||
}
|
||||
|
||||
function ThreadSpanNotFound({
|
||||
onGoBack,
|
||||
onShowThread,
|
||||
}: ThreadSpanNotFoundProps): JSX.Element {
|
||||
return (
|
||||
<ThreadEmptyState
|
||||
icon={<SearchX size={32} />}
|
||||
title="Span not found in this thread"
|
||||
description="The requested span isn't part of this trace's AI thread."
|
||||
testId="thread-span-not-found"
|
||||
actions={
|
||||
<>
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
prefix={<ArrowLeft size={14} />}
|
||||
onClick={onGoBack}
|
||||
testId="thread-span-not-found-go-back"
|
||||
>
|
||||
Go back
|
||||
</Button>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<MessagesSquare size={14} />}
|
||||
onClick={onShowThread}
|
||||
testId="thread-span-not-found-show-thread"
|
||||
>
|
||||
Show thread
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default ThreadSpanNotFound;
|
||||
@@ -1,44 +0,0 @@
|
||||
import { ToggleGroupSimple } from '@signozhq/ui/toggle-group';
|
||||
|
||||
import { ThreadView } from './types';
|
||||
|
||||
const VIEW_OPTIONS = [
|
||||
{ label: 'Formatted', value: ThreadView.Formatted },
|
||||
{ label: 'JSON', value: ThreadView.Json },
|
||||
];
|
||||
|
||||
interface ThreadViewToggleProps {
|
||||
value: ThreadView;
|
||||
onChange: (view: ThreadView) => void;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function ThreadViewToggle({
|
||||
value,
|
||||
onChange,
|
||||
testId,
|
||||
}: ThreadViewToggleProps): JSX.Element {
|
||||
const handleChange = (next: string): void => {
|
||||
// Clicking the active item deselects it and reports ''.
|
||||
if (next) {
|
||||
onChange(next as ThreadView);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<ToggleGroupSimple
|
||||
type="single"
|
||||
size="sm"
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
items={VIEW_OPTIONS}
|
||||
testId={testId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
ThreadViewToggle.defaultProps = {
|
||||
testId: 'thread-view-toggle',
|
||||
};
|
||||
|
||||
export default ThreadViewToggle;
|
||||
@@ -1,44 +0,0 @@
|
||||
.root {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
border-top: 1px solid var(--l2-border);
|
||||
}
|
||||
|
||||
.content {
|
||||
// Leaves room on the right for the span details dock.
|
||||
flex: 0 1 70%;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--spacing-4);
|
||||
padding: var(--spacing-4) var(--spacing-8);
|
||||
border-bottom: 1px solid var(--l2-border);
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.notice {
|
||||
margin: var(--spacing-6) var(--spacing-8) 0;
|
||||
}
|
||||
|
||||
.initialLoader {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
padding: var(--spacing-6) var(--spacing-8);
|
||||
}
|
||||
|
||||
.rightDock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
border-left: 1px solid var(--l2-border);
|
||||
}
|
||||
@@ -1,142 +0,0 @@
|
||||
import { useMemo, useRef } from 'react';
|
||||
import { useParams } from 'react-router-dom';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { MessagesSquare } from '@signozhq/icons';
|
||||
import { TraceDetailV3URLProps } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import { useToolCallLinks } from '../AIThreadMessage/useToolCallLinks';
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { useTraceDetailsTab } from '../hooks/useTraceDetailsTab';
|
||||
import { useScrollToAnchorSpan } from './hooks/useScrollToAnchorSpan';
|
||||
import { useThreadSpanSelection } from './hooks/useThreadSpanSelection';
|
||||
import { useThreadView } from './hooks/useThreadView';
|
||||
import { useTraceThread } from './hooks/useTraceThread';
|
||||
import ThreadEmptyState from './ThreadEmptyState';
|
||||
import ThreadPageLoader from './ThreadPageLoader';
|
||||
import ThreadSpanCard from './ThreadSpanCard';
|
||||
import ThreadSpanDetails from './ThreadSpanDetails';
|
||||
import ThreadSpanList from './ThreadSpanList';
|
||||
import ThreadSpanNotFound from './ThreadSpanNotFound';
|
||||
import ThreadViewToggle from './ThreadViewToggle';
|
||||
import { AnchorStatus } from './types';
|
||||
import { buildToolCallIndex, getAnchorStatus } from './utils';
|
||||
|
||||
import styles from './TraceDetailsThread.module.scss';
|
||||
|
||||
const INITIAL_LOADER_COUNT = 3;
|
||||
|
||||
function TraceDetailsThread(): JSX.Element {
|
||||
const { id: traceId } = useParams<TraceDetailV3URLProps>();
|
||||
const [, setTab] = useTraceDetailsTab();
|
||||
const [view, setView] = useThreadView();
|
||||
const { anchorSpanId, clearAnchor, selectedSpanId, selectSpan, panelState } =
|
||||
useThreadSpanSelection();
|
||||
const thread = useTraceThread(traceId || '', anchorSpanId);
|
||||
const { spans, isLoading, isError } = thread;
|
||||
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const toolCallIds = useMemo(() => buildToolCallIndex(spans), [spans]);
|
||||
const { isToolLinkEnabled, onToolLinkClick } = useToolCallLinks(
|
||||
listRef,
|
||||
toolCallIds,
|
||||
);
|
||||
|
||||
const anchorStatus = getAnchorStatus(anchorSpanId, spans, isLoading);
|
||||
useScrollToAnchorSpan(
|
||||
listRef,
|
||||
anchorSpanId,
|
||||
anchorStatus === AnchorStatus.Found,
|
||||
);
|
||||
|
||||
const selectedSpan = spans.find((span) => span.span_id === selectedSpanId);
|
||||
|
||||
const renderBody = (): JSX.Element => {
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className={styles.initialLoader} data-testid="thread-loading">
|
||||
{Array.from({ length: INITIAL_LOADER_COUNT }).map((_, i) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<ThreadPageLoader key={i} testId="thread-loading-item" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (anchorStatus === AnchorStatus.NotFound) {
|
||||
return (
|
||||
<ThreadSpanNotFound
|
||||
onGoBack={(): void => {
|
||||
void setTab(TraceDetailsTab.Overview);
|
||||
}}
|
||||
onShowThread={clearAnchor}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (isError || spans.length === 0) {
|
||||
return (
|
||||
<ThreadEmptyState
|
||||
icon={<MessagesSquare size={32} />}
|
||||
title="No AI thread for this trace"
|
||||
description="Threads show the input and output messages of LLM spans. This trace has none."
|
||||
testId="thread-empty"
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{anchorStatus === AnchorStatus.NoMessages && (
|
||||
<Callout
|
||||
type="info"
|
||||
size="small"
|
||||
className={styles.notice}
|
||||
title="The requested span has no input or output messages. Showing the rest of the thread."
|
||||
testId="thread-anchor-no-messages"
|
||||
/>
|
||||
)}
|
||||
<ThreadSpanList
|
||||
listRef={listRef}
|
||||
firstItemKey={spans[0]?.span_id}
|
||||
hasNextPage={thread.hasNextPage}
|
||||
hasPreviousPage={thread.hasPreviousPage}
|
||||
isFetchingNextPage={thread.isFetchingNextPage}
|
||||
isFetchingPreviousPage={thread.isFetchingPreviousPage}
|
||||
fetchNextPage={thread.fetchNextPage}
|
||||
fetchPreviousPage={thread.fetchPreviousPage}
|
||||
>
|
||||
{spans.map((span) => (
|
||||
<ThreadSpanCard
|
||||
key={span.span_id}
|
||||
span={span}
|
||||
view={view}
|
||||
isSelected={span.span_id === selectedSpanId}
|
||||
onSelect={selectSpan}
|
||||
isToolLinkEnabled={isToolLinkEnabled}
|
||||
onToolLinkClick={onToolLinkClick}
|
||||
/>
|
||||
))}
|
||||
</ThreadSpanList>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={styles.root} data-testid="trace-details-thread">
|
||||
<div className={styles.content}>
|
||||
<div className={styles.toolbar}>
|
||||
<ThreadViewToggle
|
||||
value={view}
|
||||
onChange={(next): void => {
|
||||
void setView(next);
|
||||
}}
|
||||
/>
|
||||
{spans.length > 0 && <span>Showing {spans.length} spans</span>}
|
||||
</div>
|
||||
{renderBody()}
|
||||
</div>
|
||||
{panelState.isOpen && selectedSpan && (
|
||||
<ThreadSpanDetails panelState={panelState} span={selectedSpan} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TraceDetailsThread;
|
||||
@@ -1,69 +0,0 @@
|
||||
import { MOCK_TRACE_THREAD_SPANS } from './mockThread';
|
||||
import { ThreadSpan, TraceThreadResponse } from './types';
|
||||
|
||||
export interface TraceThreadParams {
|
||||
traceId: string;
|
||||
limit: number;
|
||||
after?: string;
|
||||
before?: string;
|
||||
spanId?: string;
|
||||
}
|
||||
|
||||
// Mock-only knobs; the real endpoint pages by `limit`.
|
||||
const MOCK_PAGE_SIZE = 5;
|
||||
const MOCK_LATENCY_MS = 400;
|
||||
const SPANS_BEFORE_ANCHOR = 2;
|
||||
|
||||
type WireSpan = Omit<ThreadSpan, 'timestamp' | 'service.name'> & {
|
||||
time_unix: number;
|
||||
};
|
||||
|
||||
function toThreadSpan(span: WireSpan): ThreadSpan {
|
||||
return {
|
||||
...span,
|
||||
'service.name': span.resource?.['service.name'] || '',
|
||||
timestamp: span.time_unix,
|
||||
};
|
||||
}
|
||||
|
||||
function getStartIndex(
|
||||
spans: WireSpan[],
|
||||
{ after, before, spanId }: TraceThreadParams,
|
||||
): number {
|
||||
if (after) {
|
||||
return Number(after);
|
||||
}
|
||||
if (before) {
|
||||
return Math.max(0, Number(before) - MOCK_PAGE_SIZE);
|
||||
}
|
||||
if (spanId) {
|
||||
const index = spans.findIndex((s) => s.span_id === spanId);
|
||||
return index === -1 ? -1 : Math.max(0, index - SPANS_BEFORE_ANCHOR);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Placeholder for GET /api/v1/traces/{id}/thread; an unknown `spanId` yields no spans. */
|
||||
export async function getTraceThread(
|
||||
params: TraceThreadParams,
|
||||
): Promise<TraceThreadResponse> {
|
||||
await new Promise((resolve) => {
|
||||
setTimeout(resolve, MOCK_LATENCY_MS);
|
||||
});
|
||||
|
||||
const all = MOCK_TRACE_THREAD_SPANS as unknown as WireSpan[];
|
||||
const start = getStartIndex(all, params);
|
||||
if (start === -1) {
|
||||
return { spans: [] };
|
||||
}
|
||||
|
||||
const end = params.before
|
||||
? Number(params.before)
|
||||
: Math.min(all.length, start + MOCK_PAGE_SIZE);
|
||||
|
||||
return {
|
||||
spans: all.slice(start, end).map(toThreadSpan),
|
||||
prevCursor: start > 0 ? String(start) : undefined,
|
||||
nextCursor: end < all.length ? String(end) : undefined,
|
||||
};
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import { RefObject, useEffect } from 'react';
|
||||
|
||||
const ROOT_MARGIN = '200px 0px';
|
||||
|
||||
/** Calls `onVisible` while enabled and the sentinel is within reach of the container's viewport. */
|
||||
export function useIntersectionSentinel(
|
||||
containerRef: RefObject<HTMLElement>,
|
||||
sentinelRef: RefObject<HTMLElement>,
|
||||
isEnabled: boolean,
|
||||
onVisible: () => void,
|
||||
): void {
|
||||
useEffect(() => {
|
||||
const sentinel = sentinelRef.current;
|
||||
if (!isEnabled || !sentinel) {
|
||||
return undefined;
|
||||
}
|
||||
const observer = new IntersectionObserver(
|
||||
(entries) => {
|
||||
if (entries.some((entry) => entry.isIntersecting)) {
|
||||
onVisible();
|
||||
}
|
||||
},
|
||||
{ root: containerRef.current, rootMargin: ROOT_MARGIN },
|
||||
);
|
||||
observer.observe(sentinel);
|
||||
return (): void => observer.disconnect();
|
||||
}, [containerRef, sentinelRef, isEnabled, onVisible]);
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import { RefObject, useEffect, useRef } from 'react';
|
||||
|
||||
/** Scrolls the anchor span's card into view once, after it first renders. */
|
||||
export function useScrollToAnchorSpan(
|
||||
containerRef: RefObject<HTMLElement>,
|
||||
anchorSpanId: string | undefined,
|
||||
isAnchorLoaded: boolean,
|
||||
): void {
|
||||
const scrolledForRef = useRef<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (
|
||||
!anchorSpanId ||
|
||||
!isAnchorLoaded ||
|
||||
scrolledForRef.current === anchorSpanId
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const card = containerRef.current?.querySelector<HTMLElement>(
|
||||
`[data-span-id="${CSS.escape(anchorSpanId)}"]`,
|
||||
);
|
||||
if (card) {
|
||||
scrolledForRef.current = anchorSpanId;
|
||||
card.scrollIntoView({ block: 'start' });
|
||||
}
|
||||
}, [containerRef, anchorSpanId, isAnchorLoaded]);
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
import { RefObject, useLayoutEffect, useRef } from 'react';
|
||||
|
||||
import { useIntersectionSentinel } from './useIntersectionSentinel';
|
||||
|
||||
interface UseThreadInfiniteScrollOptions {
|
||||
containerRef: RefObject<HTMLDivElement>;
|
||||
firstItemKey?: string;
|
||||
hasNextPage: boolean;
|
||||
hasPreviousPage: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
isFetchingPreviousPage: boolean;
|
||||
fetchNextPage: () => Promise<unknown>;
|
||||
fetchPreviousPage: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
interface UseThreadInfiniteScrollResult {
|
||||
topSentinelRef: RefObject<HTMLDivElement>;
|
||||
bottomSentinelRef: RefObject<HTMLDivElement>;
|
||||
}
|
||||
|
||||
/** Loads pages as either list edge nears view, holding position on prepend. */
|
||||
export function useThreadInfiniteScroll({
|
||||
containerRef,
|
||||
firstItemKey,
|
||||
hasNextPage,
|
||||
hasPreviousPage,
|
||||
isFetchingNextPage,
|
||||
isFetchingPreviousPage,
|
||||
fetchNextPage,
|
||||
fetchPreviousPage,
|
||||
}: UseThreadInfiniteScrollOptions): UseThreadInfiniteScrollResult {
|
||||
const topSentinelRef = useRef<HTMLDivElement>(null);
|
||||
const bottomSentinelRef = useRef<HTMLDivElement>(null);
|
||||
const heightBeforePrependRef = useRef<number | null>(null);
|
||||
|
||||
const loadPreviousRef = useRef((): void => {});
|
||||
loadPreviousRef.current = (): void => {
|
||||
heightBeforePrependRef.current = containerRef.current?.scrollHeight ?? null;
|
||||
void fetchPreviousPage();
|
||||
};
|
||||
// Stable wrapper so the observer isn't recreated on every render.
|
||||
const stableLoadPrevious = useRef((): void =>
|
||||
loadPreviousRef.current(),
|
||||
).current;
|
||||
|
||||
useIntersectionSentinel(
|
||||
containerRef,
|
||||
bottomSentinelRef,
|
||||
hasNextPage && !isFetchingNextPage,
|
||||
fetchNextPage,
|
||||
);
|
||||
useIntersectionSentinel(
|
||||
containerRef,
|
||||
topSentinelRef,
|
||||
hasPreviousPage && !isFetchingPreviousPage,
|
||||
stableLoadPrevious,
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const container = containerRef.current;
|
||||
const previousHeight = heightBeforePrependRef.current;
|
||||
if (!container || previousHeight === null) {
|
||||
return;
|
||||
}
|
||||
heightBeforePrependRef.current = null;
|
||||
container.scrollTop += container.scrollHeight - previousHeight;
|
||||
}, [containerRef, firstItemKey]);
|
||||
|
||||
return { topSentinelRef, bottomSentinelRef };
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useDetailsPanel } from 'components/DetailsPanel';
|
||||
import { DetailsPanelState } from 'components/DetailsPanel/types';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
|
||||
import { ThreadSpan } from '../types';
|
||||
|
||||
const SPAN_ID_PARAM = 'spanId';
|
||||
|
||||
interface ThreadSpanSelection {
|
||||
// The spanId the thread was opened with; it shapes the first page fetched.
|
||||
anchorSpanId?: string;
|
||||
clearAnchor: () => void;
|
||||
selectedSpanId?: string;
|
||||
selectSpan: (span: ThreadSpan) => void;
|
||||
panelState: DetailsPanelState;
|
||||
}
|
||||
|
||||
export function useThreadSpanSelection(): ThreadSpanSelection {
|
||||
const urlQuery = useUrlQuery();
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const selectedSpanId = urlQuery.get(SPAN_ID_PARAM) || undefined;
|
||||
const [anchorSpanId, setAnchorSpanId] = useState(selectedSpanId);
|
||||
|
||||
const setSpanIdParam = useCallback(
|
||||
(spanId?: string): void => {
|
||||
if (spanId) {
|
||||
urlQuery.set(SPAN_ID_PARAM, spanId);
|
||||
} else {
|
||||
urlQuery.delete(SPAN_ID_PARAM);
|
||||
}
|
||||
safeNavigate({ search: urlQuery.toString() }, { replace: true });
|
||||
},
|
||||
[urlQuery, safeNavigate],
|
||||
);
|
||||
|
||||
const handleClose = useCallback(
|
||||
(): void => setSpanIdParam(undefined),
|
||||
[setSpanIdParam],
|
||||
);
|
||||
|
||||
const panelState = useDetailsPanel({
|
||||
entityId: selectedSpanId,
|
||||
onClose: handleClose,
|
||||
});
|
||||
|
||||
const { open: openPanel } = panelState;
|
||||
const selectSpan = useCallback(
|
||||
(span: ThreadSpan): void => {
|
||||
setSpanIdParam(span.span_id);
|
||||
openPanel();
|
||||
},
|
||||
[setSpanIdParam, openPanel],
|
||||
);
|
||||
|
||||
const clearAnchor = useCallback((): void => {
|
||||
setAnchorSpanId(undefined);
|
||||
setSpanIdParam(undefined);
|
||||
}, [setSpanIdParam]);
|
||||
|
||||
return useMemo(
|
||||
() => ({
|
||||
anchorSpanId,
|
||||
clearAnchor,
|
||||
selectedSpanId,
|
||||
selectSpan,
|
||||
panelState,
|
||||
}),
|
||||
[anchorSpanId, clearAnchor, selectedSpanId, selectSpan, panelState],
|
||||
);
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { parseAsStringEnum, useQueryState, UseQueryStateReturn } from 'nuqs';
|
||||
|
||||
import { ThreadView } from '../types';
|
||||
|
||||
export function useThreadView(): UseQueryStateReturn<ThreadView, ThreadView> {
|
||||
return useQueryState(
|
||||
'view',
|
||||
parseAsStringEnum(Object.values(ThreadView)).withDefault(
|
||||
ThreadView.Formatted,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -1,68 +0,0 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useInfiniteQuery } from 'react-query';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
|
||||
import { getTraceThread } from '../getTraceThread';
|
||||
import { ThreadSpan, TraceThreadResponse } from '../types';
|
||||
|
||||
const THREAD_PAGE_LIMIT = 100;
|
||||
|
||||
interface PageParam {
|
||||
after?: string;
|
||||
before?: string;
|
||||
}
|
||||
|
||||
interface UseTraceThreadResult {
|
||||
spans: ThreadSpan[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
hasNextPage: boolean;
|
||||
hasPreviousPage: boolean;
|
||||
isFetchingNextPage: boolean;
|
||||
isFetchingPreviousPage: boolean;
|
||||
fetchNextPage: () => Promise<unknown>;
|
||||
fetchPreviousPage: () => Promise<unknown>;
|
||||
}
|
||||
|
||||
export function useTraceThread(
|
||||
traceId: string,
|
||||
anchorSpanId?: string,
|
||||
): UseTraceThreadResult {
|
||||
const query = useInfiniteQuery<TraceThreadResponse>({
|
||||
queryKey: [REACT_QUERY_KEY.GET_TRACE_THREAD, traceId, anchorSpanId],
|
||||
queryFn: ({ pageParam }) => {
|
||||
const { after, before } = (pageParam ?? {}) as PageParam;
|
||||
return getTraceThread({
|
||||
traceId,
|
||||
limit: THREAD_PAGE_LIMIT,
|
||||
after,
|
||||
before,
|
||||
// The anchor only shapes the first page; cursors drive the rest.
|
||||
spanId: after || before ? undefined : anchorSpanId,
|
||||
});
|
||||
},
|
||||
getNextPageParam: (lastPage): PageParam | undefined =>
|
||||
lastPage.nextCursor ? { after: lastPage.nextCursor } : undefined,
|
||||
getPreviousPageParam: (firstPage): PageParam | undefined =>
|
||||
firstPage.prevCursor ? { before: firstPage.prevCursor } : undefined,
|
||||
enabled: !!traceId,
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
const spans = useMemo(
|
||||
() => query.data?.pages.flatMap((page) => page.spans) ?? [],
|
||||
[query.data],
|
||||
);
|
||||
|
||||
return {
|
||||
spans,
|
||||
isLoading: query.isLoading,
|
||||
isError: query.isError,
|
||||
hasNextPage: !!query.hasNextPage,
|
||||
hasPreviousPage: !!query.hasPreviousPage,
|
||||
isFetchingNextPage: query.isFetchingNextPage,
|
||||
isFetchingPreviousPage: query.isFetchingPreviousPage,
|
||||
fetchNextPage: query.fetchNextPage,
|
||||
fetchPreviousPage: query.fetchPreviousPage,
|
||||
};
|
||||
}
|
||||
@@ -1,722 +0,0 @@
|
||||
// Placeholder until GET /api/v1/traces/{id}/thread is available. Wire format: spans carry time_unix.
|
||||
|
||||
const TRACE_ID = '7a1f0c2d9e8b4a6f5c3d2e1f0a9b8c7d';
|
||||
|
||||
const IMAGE_DATA_URL =
|
||||
'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAUDBAQEAwUEBAQFBQUGBwwIBwcHBw8LCwkMEQ8SEhEPERETFhwXExQaFRERGCEYGh0dHx8fExciJCIeJBweHx7/2wBDAQUFBQcGBw4ICA4eFBEUHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh4eHh7/wAARCAEAAQADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL';
|
||||
|
||||
const OBSERVABILITY_PROMPT =
|
||||
"You are an observability assistant. Observability is understanding a system's internal state from the telemetry it emits: traces, metrics, and logs. For LLM and agent workloads these signals also carry the model used, input and output token counts, the cost those tokens imply, the tools an agent invoked, and whether each call succeeded or failed. Always answer concisely. ".repeat(
|
||||
18,
|
||||
);
|
||||
|
||||
const SPAN_DEFAULTS = {
|
||||
events: [],
|
||||
flags: 0,
|
||||
has_children: false,
|
||||
has_error: false,
|
||||
is_remote: '',
|
||||
level: 1,
|
||||
parent_span_id: '0000000000000r00',
|
||||
references: [],
|
||||
resource: { 'service.name': 'travel-agent' },
|
||||
sub_tree_node_count: 0,
|
||||
trace_id: TRACE_ID,
|
||||
trace_state: '',
|
||||
};
|
||||
|
||||
export const MOCK_TRACE_THREAD_SPANS = [
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"system","content":"You are a research assistant. Use the search-web and get-weather tools as needed."},{"role":"user","content":[{"type":"text","text":"Search for SigNoz AI observability docs, then tell me the weather in Bengaluru."}]},{"role":"assistant","content":[{"type":"tool-call","toolCallId":"call_opFrOeFM5pF9PnXe6lWcl0ui","toolName":"searchWeb","args":{"query":"SigNoz AI observability documentation"}},{"type":"tool-call","toolCallId":"call_HxRE0JdcM3F32SCbIu3SGk3G","toolName":"getWeather","args":{"city":"Bengaluru"}}]},{"role":"tool","content":[{"type":"tool-result","toolCallId":"call_opFrOeFM5pF9PnXe6lWcl0ui","toolName":"searchWeb","result":{"query":"SigNoz AI observability documentation","results":[{"title":"SigNoz docs","snippet":"AI observability ..."},{"title":"OTel GenAI","snippet":"semantic conventions ..."}]}},{"type":"tool-result","toolCallId":"call_HxRE0JdcM3F32SCbIu3SGk3G","toolName":"getWeather","result":{"city":"Bengaluru","temperatureC":18,"summary":"Clear"}}]}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'I found some information on SigNoz AI observability documentation. Here are a couple of relevant links:\n\n1. **SigNoz docs** - This includes details about AI observability.\n2. **OTel GenAI** - This document discusses semantic conventions related to observability.\n\nAs for the weather in Bengaluru, it is currently clear with a temperature of 18°C.',
|
||||
'gen_ai.provider.name': 'openai.chat',
|
||||
'gen_ai.request.model': 'gpt-4o-mini',
|
||||
'gen_ai.usage.input_tokens': 243,
|
||||
'gen_ai.usage.output_tokens': 77,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.0006075000000000001,
|
||||
'signoz.gn_ai.usage.output_tokens.cost': 0.0007700000000000001,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.0013775,
|
||||
},
|
||||
duration_nano: 1770290125,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'system',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'You are a research assistant. Use the search-web and get-weather tools as needed.',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'Search for SigNoz AI observability docs, then tell me the weather in Bengaluru.',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_call',
|
||||
id: 'call_opFrOeFM5pF9PnXe6lWcl0ui',
|
||||
name: 'searchWeb',
|
||||
arguments: { query: 'SigNoz AI observability documentation' },
|
||||
},
|
||||
{
|
||||
type: 'tool_call',
|
||||
id: 'call_HxRE0JdcM3F32SCbIu3SGk3G',
|
||||
name: 'getWeather',
|
||||
arguments: { city: 'Bengaluru' },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
role: 'tool',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_result',
|
||||
content:
|
||||
'{"query":"SigNoz AI observability documentation","results":[{"snippet":"AI observability ...","title":"SigNoz docs"},{"snippet":"semantic conventions ...","title":"OTel GenAI"}]}',
|
||||
name: 'searchWeb',
|
||||
toolCallId: 'call_opFrOeFM5pF9PnXe6lWcl0ui',
|
||||
},
|
||||
{
|
||||
type: 'tool_result',
|
||||
content: '{"city":"Bengaluru","summary":"Clear","temperatureC":18}',
|
||||
name: 'getWeather',
|
||||
toolCallId: 'call_HxRE0JdcM3F32SCbIu3SGk3G',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'I found some information on SigNoz AI observability documentation. Here are a couple of relevant links:\n\n1. **SigNoz docs** - This includes details about AI observability.\n2. **OTel GenAI** - This document discusses semantic conventions related to observability.\n\nAs for the weather in Bengaluru, it is currently clear with a temperature of 18°C.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
kind_string: 'Internal',
|
||||
name: 'ai.generateText.doGenerate',
|
||||
span_id: '6cee8072961624a0',
|
||||
time_unix: 1789627365000,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"content": "A bat and a ball cost $1.10. The bat costs $1 more than the ball. How much is the ball?", "role": "user"}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'{"id":"resp_017c5eb995d99968006a199f9b483481979ca790db905506fc","created_at":1780064155.0,"error":null,"instructions":"You solve problems step by step and give a final answer.","model":"o3-mini-2025-01-31","object":"response","output":[{"id":"rs_017c5eb995d99968006a199f9bff248197978bf9193f34c29a","summary":[],"type":"reasoning","content":null},{"id":"msg_017c5eb995d99968006a199f9c8dcc81979f4e10afbe5350a1","content":[{"annotations":[],"text":"Step 1: Let the cost of the ball be x dollars.\\nStep 2: Since the bat costs $1 more than the ball, its cost is x + 1 dollars.\\nStep 3: According to the problem, the total cost of the bat and ball is $1.10. Set up the equation:\\n x + (x + 1) = 1.10\\nStep 4: Simplify the equation:\\n 2x + 1 = 1.10\\nStep 5: Subtract 1 from both sides:\\n 2x = 0.10\\nStep 6: Divide both sides by 2:\\n x = 0.05\\n\\nFinal Answer: The ball costs $0.05.","type":"output_text","logprobs":[]}],"role":"assistant","status":"completed","type":"message"}],"status":"completed","usage":{"input_tokens":49,"input_tokens_details":{"cached_tokens":0},"output_tokens":431,"output_tokens_details":{"reasoning_tokens":128},"total_tokens":480}}',
|
||||
'gen_ai.request.model': 'o3-mini-2025-01-31',
|
||||
'gen_ai.usage.cache_read.input_tokens': 0,
|
||||
'gen_ai.usage.input_tokens': 49,
|
||||
'gen_ai.usage.output_tokens': 431,
|
||||
'gen_ai.usage.reasoning.output_tokens': 128,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.00012250000000000002,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.0043100000000000005,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.004432500000000001,
|
||||
},
|
||||
duration_nano: 2927763968,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'A bat and a ball cost $1.10. The bat costs $1 more than the ball. How much is the ball?',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{ role: 'assistant', content: [{ type: 'thinking' }] },
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'Step 1: Let the cost of the ball be x dollars.\nStep 2: Since the bat costs $1 more than the ball, its cost is x + 1 dollars.\nStep 3: According to the problem, the total cost of the bat and ball is $1.10. Set up the equation:\n x + (x + 1) = 1.10\nStep 4: Simplify the equation:\n 2x + 1 = 1.10\nStep 5: Subtract 1 from both sides:\n 2x = 0.10\nStep 6: Divide both sides by 2:\n x = 0.05\n\nFinal Answer: The ball costs $0.05.',
|
||||
},
|
||||
],
|
||||
finishReason: 'stop',
|
||||
},
|
||||
],
|
||||
kind_string: 'Internal',
|
||||
name: 'response',
|
||||
span_id: '9d1af71602a60828',
|
||||
time_unix: 1789627367500,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'{"messages":[{"role":"user","content":"A bat and a ball cost $1.10. The bat costs $1 more than the ball. How much is the ball?"}]}',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'{"completion":"Let x be the cost of the ball. Then the bat costs x + 1 dollars. The total cost is given as:\\n\\n x + (x + 1) = 1.10\\n\\nCombine like terms:\\n\\n 2x + 1 = 1.10\\n\\nSubtract 1 from both sides:\\n\\n 2x = 0.10\\n\\nDivide both sides by 2:\\n\\n x = 0.05\\n\\nSo, the ball costs 5 cents.","reasoning":"**Calculating ball price**\\n\\nI\'m determining the price of the ball based on a scenario where a bat and ball combined cost $1.10, with the bat costing $1 more than the ball. I set up the equation: let the cost of the ball be x, making the bat x + 1. Solving the equation x + (x + 1) = 1.10 leads me to find that x equals $0.05 for the ball. I need to confirm that this works: the ball at $0.05 and the bat at $1.05 totals $1.10.","rawRequest":{"model":"openai/o3-mini","max_completion_tokens":2000}}',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'openai/o3-mini',
|
||||
'gen_ai.usage.cache_read.input_tokens': 0,
|
||||
'gen_ai.usage.input_tokens': 33,
|
||||
'gen_ai.usage.output_tokens': 629,
|
||||
'gen_ai.usage.reasoning.output_tokens': 256,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.00008250000000000001,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.0062900000000000005,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.0063725000000000006,
|
||||
},
|
||||
duration_nano: 4209000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'A bat and a ball cost $1.10. The bat costs $1 more than the ball. How much is the ball?',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'thinking',
|
||||
content:
|
||||
"**Calculating ball price**\n\nI'm determining the price of the ball based on a scenario where a bat and ball combined cost $1.10, with the bat costing $1 more than the ball. I set up the equation: let the cost of the ball be x, making the bat x + 1. Solving the equation x + (x + 1) = 1.10 leads me to find that x equals $0.05 for the ball. I need to confirm that this works: the ball at $0.05 and the bat at $1.05 totals $1.10.",
|
||||
},
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'Let x be the cost of the ball. Then the bat costs x + 1 dollars. The total cost is given as:\n\n x + (x + 1) = 1.10\n\nCombine like terms:\n\n 2x + 1 = 1.10\n\nSubtract 1 from both sides:\n\n 2x = 0.10\n\nDivide both sides by 2:\n\n x = 0.05\n\nSo, the ball costs 5 cents.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'LLM Generation',
|
||||
span_id: 'af95cec99712ad26',
|
||||
time_unix: 1789627370000,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role": "user", "parts": [{"type": "text", "content": "What\'s the weather in Bengaluru? Use the tool."}]}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role": "assistant", "parts": [], "finish_reason": "tool_calls"}]',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o-mini',
|
||||
'gen_ai.usage.input_tokens': 66,
|
||||
'gen_ai.usage.output_tokens': 18,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.00016500000000000003,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00018,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.00034500000000000004,
|
||||
},
|
||||
duration_nano: 1652955648,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content: "What's the weather in Bengaluru? Use the tool.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{ role: 'assistant', content: [], finishReason: 'tool_call' },
|
||||
],
|
||||
kind_string: 'Internal',
|
||||
name: 'litellm_request',
|
||||
span_id: 'adfbedf6477f7f24',
|
||||
time_unix: 1789627372500,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'{"city": "Bengaluru", "temp_c": 28, "summary": "Partly cloudy"}',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'The current weather in Bengaluru is partly cloudy with a temperature of 28°C.',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o-mini',
|
||||
},
|
||||
duration_nano: 939838834,
|
||||
formatted_input: [
|
||||
{
|
||||
content: [
|
||||
{
|
||||
type: 'generic',
|
||||
content:
|
||||
'{"city": "Bengaluru", "temp_c": 28, "summary": "Partly cloudy"}',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'The current weather in Bengaluru is partly cloudy with a temperature of 28°C.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
kind_string: 'Server',
|
||||
name: '/openai/v1/chat/completions',
|
||||
span_id: '0ed3e2f860c741b9',
|
||||
time_unix: 1789627375000,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages': `[{"role": "user", "parts": [{"type": "text", "text": "What animal is in this image? One sentence."}, {"type": "image_url", "image_url": {"url": "${IMAGE_DATA_URL}"}}]}]`,
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o-mini',
|
||||
},
|
||||
duration_nano: 412100096,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content: 'What animal is in this image? One sentence.',
|
||||
},
|
||||
{
|
||||
type: 'generic',
|
||||
content: `{"image_url":{"url":"${IMAGE_DATA_URL}"},"type":"image_url"}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
has_error: true,
|
||||
kind_string: 'Internal',
|
||||
name: 'litellm_request',
|
||||
span_id: '61c74044c542ed88',
|
||||
status_code: 2,
|
||||
status_code_string: 'Error',
|
||||
time_unix: 1789627377500,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role": "user", "parts": [{"type": "text", "content": "Stream a short haiku about telemetry."}]}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role": "unknown", "parts": [{"type": "text", "content": "Data whispers loud, \\nSignals traverse through the night, \\nTruth in every byte."}], "finish_reason": "stop"}]',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o-mini',
|
||||
'gen_ai.usage.cache_read.input_tokens': 0,
|
||||
'gen_ai.usage.input_tokens': 15,
|
||||
'gen_ai.usage.output_tokens': 17,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.000037500000000000003,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00017,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.00020750000000000003,
|
||||
},
|
||||
duration_nano: 1129929000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', content: 'Stream a short haiku about telemetry.' },
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'unknown',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'Data whispers loud, \nSignals traverse through the night, \nTruth in every byte.',
|
||||
},
|
||||
],
|
||||
finishReason: 'stop',
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'ChatOpenAI.chat',
|
||||
span_id: 'e9d08ec1ac3417d5',
|
||||
time_unix: 1789627380000,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages': JSON.stringify([
|
||||
{ role: 'system', content: OBSERVABILITY_PROMPT },
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', text: 'In one sentence, what is observability?' },
|
||||
],
|
||||
},
|
||||
]),
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
"Observability is the ability to understand a system's internal state through the telemetry it emits, such as traces, metrics, and logs.",
|
||||
'gen_ai.provider.name': 'openai.chat',
|
||||
'gen_ai.request.model': 'gpt-4o-mini',
|
||||
'gen_ai.usage.input_tokens': 1371,
|
||||
'gen_ai.usage.output_tokens': 27,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.0034275000000000004,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00027,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.0036975000000000003,
|
||||
},
|
||||
duration_nano: 959577625,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'system',
|
||||
content: [{ type: 'text', content: OBSERVABILITY_PROMPT }],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', content: 'In one sentence, what is observability?' },
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
"Observability is the ability to understand a system's internal state through the telemetry it emits, such as traces, metrics, and logs.",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
kind_string: 'Internal',
|
||||
name: 'ai.generateText.doGenerate',
|
||||
span_id: '6bf32b44d3456393',
|
||||
time_unix: 1789627382500,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"user","content":"List three things to pack for Paris in October."}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role":"assistant","content":"1. A light waterproof jacket\\n2. Comfortable walking shoes\\n3. A","finish_reason":"length"}]',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o',
|
||||
'gen_ai.usage.input_tokens': 18,
|
||||
'gen_ai.usage.output_tokens': 16,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.000045,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00016,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.00020500000000000002,
|
||||
},
|
||||
duration_nano: 900000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content: 'List three things to pack for Paris in October.',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content:
|
||||
'1. A light waterproof jacket\n2. Comfortable walking shoes\n3. A',
|
||||
},
|
||||
],
|
||||
finishReason: 'length',
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'chat gpt-4o',
|
||||
span_id: '5e00000000000001',
|
||||
time_unix: 1789627385000,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"user","content":"Write a fake 5-star review for my hotel."}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role":"assistant","content":null,"refusal":"I can\'t help write fake reviews.","finish_reason":"content_filter"}]',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o',
|
||||
'gen_ai.usage.input_tokens': 15,
|
||||
'gen_ai.usage.output_tokens': 9,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.000037500000000000003,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00009,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.0001275,
|
||||
},
|
||||
duration_nano: 900000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{ type: 'text', content: 'Write a fake 5-star review for my hotel.' },
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', content: "I can't help write fake reviews." }],
|
||||
finishReason: 'content_filter',
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'chat gpt-4o',
|
||||
span_id: '5e00000000000002',
|
||||
time_unix: 1789627387500,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"user","content":[{"type":"tool_result","tool_use_id":"toolu_01","content":[{"type":"text","text":"rate limited, retry after 30s"}],"is_error":true}]}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role":"assistant","content":[{"type":"text","text":"The booking API is rate limited, retrying."},{"type":"tool_use","id":"toolu_02","name":"book_hotel","input":{"city":"Paris","nights":2}}],"stop_reason":"tool_use"}]',
|
||||
'gen_ai.provider.name': 'anthropic',
|
||||
'gen_ai.request.model': 'claude-sonnet-4',
|
||||
'gen_ai.usage.input_tokens': 210,
|
||||
'gen_ai.usage.output_tokens': 48,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.0005250000000000001,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00048000000000000007,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.001005,
|
||||
},
|
||||
duration_nano: 900000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_result',
|
||||
content: 'rate limited, retry after 30s',
|
||||
toolCallId: 'toolu_01',
|
||||
isError: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{ type: 'text', content: 'The booking API is rate limited, retrying.' },
|
||||
{
|
||||
type: 'tool_call',
|
||||
id: 'toolu_02',
|
||||
name: 'book_hotel',
|
||||
arguments: { city: 'Paris', nights: 2 },
|
||||
},
|
||||
],
|
||||
finishReason: 'tool_call',
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'chat claude-sonnet-4',
|
||||
span_id: '5e00000000000003',
|
||||
time_unix: 1789627390000,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"system","content":"Reply with JSON only."},{"role":"user","content":"Extract city and nights: two nights in Paris"}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role":"assistant","content":"{\\"city\\":\\"Paris\\",\\"nights\\":2}","finish_reason":"stop"}]',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o-mini',
|
||||
'gen_ai.usage.input_tokens': 31,
|
||||
'gen_ai.usage.output_tokens': 11,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.0000775,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00011,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.0001875,
|
||||
},
|
||||
duration_nano: 900000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'system',
|
||||
content: [{ type: 'text', content: 'Reply with JSON only.' }],
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
content: 'Extract city and nights: two nights in Paris',
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', content: '{"city":"Paris","nights":2}' }],
|
||||
finishReason: 'stop',
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'chat gpt-4o-mini',
|
||||
span_id: '5e00000000000004',
|
||||
time_unix: 1789627392500,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"user","content":"Weather in Paris and Tokyo?"}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role":"assistant","content":null,"tool_calls":[{"id":"call_a","type":"function","function":{"name":"get_weather","arguments":"{\\"city\\":\\"Paris\\"}"}},{"id":"call_b","type":"function","function":{"name":"get_weather","arguments":"{\\"city\\":\\"Tok"}}],"finish_reason":"tool_calls"}]',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o',
|
||||
'gen_ai.usage.input_tokens': 40,
|
||||
'gen_ai.usage.output_tokens': 30,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.0001,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00030000000000000003,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.0004,
|
||||
},
|
||||
duration_nano: 900000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [{ type: 'text', content: 'Weather in Paris and Tokyo?' }],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [
|
||||
{
|
||||
type: 'tool_call',
|
||||
id: 'call_a',
|
||||
name: 'get_weather',
|
||||
arguments: { city: 'Paris' },
|
||||
},
|
||||
{
|
||||
type: 'tool_call',
|
||||
id: 'call_b',
|
||||
name: 'get_weather',
|
||||
arguments: '{"city":"Tok',
|
||||
},
|
||||
],
|
||||
finishReason: 'tool_call',
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'chat gpt-4o',
|
||||
span_id: '5e00000000000005',
|
||||
time_unix: 1789627395000,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"user","content":"Summarise the trip plan."}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role":"assistant","content":[{"type":"text","text":"Paris, 2 nights, arriving"}],"stop_reason":"pause_turn"}]',
|
||||
'gen_ai.provider.name': 'anthropic',
|
||||
'gen_ai.request.model': 'claude-sonnet-4',
|
||||
'gen_ai.usage.input_tokens': 22,
|
||||
'gen_ai.usage.output_tokens': 7,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.000055,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00007000000000000001,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.000125,
|
||||
},
|
||||
duration_nano: 900000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [{ type: 'text', content: 'Summarise the trip plan.' }],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', content: 'Paris, 2 nights, arriving' }],
|
||||
finishReason: 'pause_turn',
|
||||
},
|
||||
],
|
||||
kind_string: 'Client',
|
||||
name: 'chat claude-sonnet-4',
|
||||
span_id: '5e00000000000006',
|
||||
time_unix: 1789627397500,
|
||||
},
|
||||
{
|
||||
...SPAN_DEFAULTS,
|
||||
attributes: {
|
||||
'gen_ai.input.messages':
|
||||
'[{"role":"user","content":"Confirm the booking."}]',
|
||||
'gen_ai.operation.name': 'chat',
|
||||
'gen_ai.output.messages':
|
||||
'[{"role":"assistant","content":"Booking failed upstream.","finish_reason":"error"}]',
|
||||
'gen_ai.provider.name': 'openai',
|
||||
'gen_ai.request.model': 'gpt-4o',
|
||||
'gen_ai.usage.input_tokens': 12,
|
||||
'gen_ai.usage.output_tokens': 5,
|
||||
'signoz.gen_ai.usage.input_tokens.cost': 0.000030000000000000004,
|
||||
'signoz.gen_ai.usage.output_tokens.cost': 0.00005,
|
||||
'signoz.gen_ai.usage.tokens.cost': 0.00008,
|
||||
},
|
||||
duration_nano: 900000000,
|
||||
formatted_input: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [{ type: 'text', content: 'Confirm the booking.' }],
|
||||
},
|
||||
],
|
||||
formatted_output: [
|
||||
{
|
||||
role: 'assistant',
|
||||
content: [{ type: 'text', content: 'Booking failed upstream.' }],
|
||||
finishReason: 'error',
|
||||
},
|
||||
],
|
||||
has_error: true,
|
||||
kind_string: 'Client',
|
||||
name: 'chat gpt-4o',
|
||||
span_id: '5e00000000000007',
|
||||
status_code: 2,
|
||||
status_code_string: 'Error',
|
||||
time_unix: 1789627400000,
|
||||
},
|
||||
];
|
||||
@@ -1,62 +0,0 @@
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
export type MessagePart =
|
||||
| { type: 'text'; content: string }
|
||||
| { type: 'thinking'; content?: string }
|
||||
| {
|
||||
type: 'tool_call';
|
||||
id: string;
|
||||
name: string;
|
||||
arguments: unknown;
|
||||
server?: boolean;
|
||||
}
|
||||
| {
|
||||
type: 'tool_result';
|
||||
toolCallId: string;
|
||||
name?: string;
|
||||
content: string;
|
||||
isError?: boolean;
|
||||
}
|
||||
| {
|
||||
type: 'media';
|
||||
modality?: string;
|
||||
mimeType?: string;
|
||||
uri?: string;
|
||||
name?: string;
|
||||
sizeBytes?: number;
|
||||
}
|
||||
| { type: 'generic'; content: string };
|
||||
|
||||
export interface ThreadMessage {
|
||||
// system | user | assistant | tool; any other value renders headerless.
|
||||
role?: string;
|
||||
content: MessagePart[];
|
||||
// stop | tool_call | length | content_filter | error, or provider-specific.
|
||||
finishReason?: string;
|
||||
}
|
||||
|
||||
export type ThreadSpan = SpanV3 & {
|
||||
formatted_input?: ThreadMessage[];
|
||||
formatted_output?: ThreadMessage[];
|
||||
};
|
||||
|
||||
/** Response of GET /api/v1/traces/{id}/thread. */
|
||||
export interface TraceThreadResponse {
|
||||
spans: ThreadSpan[];
|
||||
prevCursor?: string;
|
||||
nextCursor?: string;
|
||||
}
|
||||
|
||||
export enum ThreadView {
|
||||
Formatted = 'formatted',
|
||||
Json = 'json',
|
||||
}
|
||||
|
||||
export enum AnchorStatus {
|
||||
None = 'none',
|
||||
Loading = 'loading',
|
||||
Found = 'found',
|
||||
// Backend anchors on the span's position but drops it for lacking messages.
|
||||
NoMessages = 'noMessages',
|
||||
NotFound = 'notFound',
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { collectToolCallIds } from '../AIThreadMessage/utils';
|
||||
import { AnchorStatus, ThreadSpan } from './types';
|
||||
|
||||
export function buildToolCallIndex(spans: ThreadSpan[]): Set<string> {
|
||||
return new Set(
|
||||
spans.flatMap((span) => [
|
||||
...collectToolCallIds(span.formatted_input ?? []),
|
||||
...collectToolCallIds(span.formatted_output ?? []),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
export function getAnchorStatus(
|
||||
anchorSpanId: string | undefined,
|
||||
spans: ThreadSpan[],
|
||||
isLoading: boolean,
|
||||
): AnchorStatus {
|
||||
if (!anchorSpanId) {
|
||||
return AnchorStatus.None;
|
||||
}
|
||||
if (isLoading) {
|
||||
return AnchorStatus.Loading;
|
||||
}
|
||||
if (spans.length === 0) {
|
||||
return AnchorStatus.NotFound;
|
||||
}
|
||||
return spans.some((span) => span.span_id === anchorSpanId)
|
||||
? AnchorStatus.Found
|
||||
: AnchorStatus.NoMessages;
|
||||
}
|
||||
@@ -1,3 +1,10 @@
|
||||
.root {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.layoutRow {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
@@ -1,6 +0,0 @@
|
||||
.root {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
import TraceStoreSync from '../stores/TraceStoreSync';
|
||||
|
||||
import styles from './TraceDetailsWrapper.module.scss';
|
||||
|
||||
interface TraceDetailsWrapperProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function TraceDetailsWrapper({
|
||||
children,
|
||||
}: TraceDetailsWrapperProps): JSX.Element {
|
||||
return (
|
||||
<TraceStoreSync>
|
||||
<div className={styles.root}>{children}</div>
|
||||
</TraceStoreSync>
|
||||
);
|
||||
}
|
||||
|
||||
export default TraceDetailsWrapper;
|
||||
@@ -33,5 +33,10 @@
|
||||
position: fixed;
|
||||
z-index: 1000;
|
||||
pointer-events: none;
|
||||
background-color: var(--l1-background);
|
||||
padding: 8px 12px;
|
||||
border-radius: 4px;
|
||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
|
||||
border: 1px solid var(--l2-border);
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import cx from 'classnames';
|
||||
import TimelineV3 from 'components/TimelineV3/TimelineV3';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
|
||||
@@ -18,7 +17,6 @@ import { useFlamegraphZoom } from './hooks/useFlamegraphZoom';
|
||||
import { useScrollToSpan } from './hooks/useScrollToSpan';
|
||||
import { EventRect, FlamegraphCanvasProps, SpanRect } from './types';
|
||||
|
||||
import tooltipStyles from '../TraceTooltip/TraceTooltip.module.scss';
|
||||
import styles from './FlamegraphCanvas.module.scss';
|
||||
|
||||
function FlamegraphCanvas(props: FlamegraphCanvasProps): JSX.Element {
|
||||
@@ -205,7 +203,7 @@ function FlamegraphCanvas(props: FlamegraphCanvasProps): JSX.Element {
|
||||
const tooltipElement = tooltipContent
|
||||
? createPortal(
|
||||
<div
|
||||
className={cx(tooltipStyles.surface, styles.tooltip)}
|
||||
className={styles.tooltip}
|
||||
style={{
|
||||
left: Math.min(tooltipContent.clientX + 15, window.innerWidth - 220),
|
||||
top: Math.min(tooltipContent.clientY + 15, window.innerHeight - 100),
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import styles from './TraceTooltip.module.scss';
|
||||
|
||||
interface TooltipRowProps {
|
||||
label: string;
|
||||
value: string;
|
||||
isTotal?: boolean;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function TooltipRow({
|
||||
label,
|
||||
value,
|
||||
isTotal,
|
||||
testId,
|
||||
}: TooltipRowProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.row} data-testid={testId}>
|
||||
<Typography.Text
|
||||
size="small"
|
||||
color={isTotal ? undefined : 'muted'}
|
||||
truncate={1}
|
||||
>
|
||||
{label}
|
||||
</Typography.Text>
|
||||
<Typography.Text size="small" truncate={1} className={styles.rowValue}>
|
||||
{value}
|
||||
</Typography.Text>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TooltipRow;
|
||||
@@ -1,13 +0,0 @@
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
import styles from './TraceTooltip.module.scss';
|
||||
|
||||
interface TooltipSectionProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
function TooltipSection({ children }: TooltipSectionProps): JSX.Element {
|
||||
return <div className={styles.section}>{children}</div>;
|
||||
}
|
||||
|
||||
export default TooltipSection;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user