Compare commits

..

4 Commits

Author SHA1 Message Date
Swapnil Nakade
ac789df15b Merge branch 'main' into test/fileauditor-write-path 2026-11-17 07:08:22 +05:30
swapnil-signoz
7c3e2c04e6 test(fileauditor): drop the login and no-license absence checks 2026-11-16 23:23:50 +05:30
swapnil-signoz
734839323c test(fileauditor): inline otlp attribute parsing 2026-11-16 19:44:10 +05:30
swapnil-signoz
346e6cee67 test(fileauditor): cover the audit file write path end to end 2026-11-16 18:30:11 +05:30
81 changed files with 919 additions and 3335 deletions

View File

@@ -44,6 +44,7 @@ jobs:
- callbackauthn
- cloudintegrations
- dashboard
- fileauditor
- ingestionkeys
- inframonitoring
- llmpricingrules

View File

@@ -1,51 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { createAppContextMock } from 'tests/fixtures/appContextMock';
import { LicensePlatform } from 'types/api/licensesV3/getActive';
import { USER_ROLES } from 'types/roles';
import { fn } from 'storybook/test';
import { storyChangelog } from './__story_mockdata__/changelog';
import {
showsCloudChangelog,
showsSelfHostedChangelog,
} from './__story_mockdata__/changelogModal.play';
import ChangelogModal from '../ChangelogModal';
const { activeLicense } = createAppContextMock(USER_ROLES.ADMIN);
/** `AppLayout` opens it one second after load, for a version the user has not seen. */
const meta = {
title: 'Components/Changelog Modal',
component: ChangelogModal,
tags: ['play'],
parameters: { signoz: {} },
args: {
changelog: storyChangelog,
onClose: fn(),
},
} satisfies Meta<typeof ChangelogModal>;
export default meta;
type Story = StoryObj<typeof meta>;
/** Cloud workspaces update on their own, so the footer has no update actions. */
export const Cloud: Story = {
play: showsCloudChangelog,
};
/** Self-hosted workspaces get "Skip for now" and "Update my workspace". */
export const SelfHosted: Story = {
parameters: {
signoz: {
appContext: {
activeLicense: activeLicense && {
...activeLicense,
platform: LicensePlatform.SELF_HOSTED,
},
},
},
},
play: showsSelfHostedChangelog,
};

View File

@@ -1,62 +0,0 @@
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
const TIMESTAMP = '2026-11-03T12:00:00Z';
function feature(
id: number,
title: string,
description: string,
): ChangelogSchema['features'][number] {
return {
id,
documentId: `feature-${id}`,
title,
description,
media: null,
sort_order: id,
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
publishedAt: TIMESTAMP,
deployment_type: DeploymentType.ALL,
};
}
/** Long enough to scroll, so the "Scroll for more" button shows. */
export const storyChangelog: ChangelogSchema = {
id: 1,
documentId: 'changelog-v0.99.0',
version: 'v0.99.0',
release_date: '2026-11-03',
createdAt: TIMESTAMP,
updatedAt: TIMESTAMP,
publishedAt: TIMESTAMP,
features: [
feature(
1,
'Dashboard sections',
'Group panels into **sections** you can collapse, rename and drag. Existing dashboards move into a single section the first time you edit them.',
),
feature(
2,
'Service accounts',
'Create service accounts with their own API keys and roles. Keys can expire, and you can revoke them without touching the account. See the [docs](https://signoz.io/docs/) for the API.',
),
feature(
3,
'Faster log search',
'Full-text search over log bodies now uses a token index:\n\n- queries over a day of logs return up to 4x faster\n- `has()` and `hasToken()` use the same index\n- the old behaviour stays behind a setting for a release',
),
feature(
4,
'Routing policies',
'Send an alert to a channel based on its labels instead of picking the channel in every rule. Policies are evaluated in order and the first match wins.',
),
],
bug_fixes:
'- Fixed the time picker losing the selected range after a refresh.\n- Fixed trace waterfall rows overlapping when a span name wraps.\n- Fixed CSV export dropping columns with dots in their names.',
maintenance:
'- Upgraded the OpenTelemetry collector to the latest release.\n- Reduced the memory used by the query service on large dashboards.',
};

View File

@@ -1,19 +0,0 @@
import { expect, screen, waitFor } from 'storybook/test';
const TITLE = /What’s New ⎯ Changelog : November 3, 2026/;
export const showsCloudChangelog = async (): Promise<void> => {
await screen.findByRole('dialog', { name: TITLE });
await expect(
screen.queryByRole('button', { name: /Skip for now/ }),
).not.toBeInTheDocument();
};
export const showsSelfHostedChangelog = async (): Promise<void> => {
await screen.findByRole('dialog', { name: TITLE });
await waitFor(() =>
expect(
screen.getByRole('button', { name: /Update my workspace/ }),
).toBeVisible(),
);
};

View File

@@ -1,77 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import { QueryBuilderV2 } from '../QueryBuilderV2';
import {
metricsFewGroupBy,
metricsManyGroupBy,
tracesFewAddOns,
tracesManyAddOns,
} from './__story_mockdata__/queryBuilderAddOns';
import {
expectMetricsGroupBy,
expectTracesAddOnsOpen,
} from './__story_mockdata__/queryBuilderAddOns.play';
import {
DEFAULT_ARGS,
PANEL_EDITOR_ARGS,
PANEL_EDITOR_PATH,
routeWith,
} from './QueryBuilderV2.stories.mocks';
import QueryProbe from './QueryProbe';
/**
* The add-ons a query opens with values already set: group by, having, order
* by, limit and legend format side by side, with one value each and with
* enough to wrap.
*/
const meta = {
title: 'Components/Query Builder/Add-ons',
component: QueryBuilderV2,
tags: ['play'],
decorators: [withCanvas({ maxWidth: 1100 })],
args: { ...DEFAULT_ARGS, ...PANEL_EDITOR_ARGS },
render: (args): JSX.Element => (
<>
<QueryBuilderV2 {...args} />
<QueryProbe />
</>
),
} satisfies Meta<typeof QueryBuilderV2>;
export default meta;
type Story = StoryObj<typeof meta>;
/** Traces with every add-on open, one value in each. */
export const FewValues: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, tracesFewAddOns) },
},
play: expectTracesAddOnsOpen(1),
};
/** Traces with every add-on open and filled past one line. */
export const ManyValues: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, tracesManyAddOns) },
},
play: expectTracesAddOnsOpen(9),
};
/** A histogram grouped by one key, beside the aggregation selects. */
export const MetricsFewGroupBy: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, metricsFewGroupBy) },
},
play: expectMetricsGroupBy(1),
};
/** A histogram grouped by enough keys to wrap the group-by select. */
export const MetricsManyGroupBy: Story = {
parameters: {
signoz: { route: routeWith(PANEL_EDITOR_PATH, metricsManyGroupBy) },
},
play: expectMetricsGroupBy(7),
};

View File

@@ -8,11 +8,7 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import {
BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import type { QueryBuilderV2 } from '../QueryBuilderV2';
@@ -22,30 +18,6 @@ type QueryBuilderProps = Parameters<typeof QueryBuilderV2>[0];
export const routeWith = (path: string, query: Query): string =>
`${path}?compositeQuery=${encodeURIComponent(JSON.stringify(query))}`;
/** `query` with its first builder query's fields replaced by `fields`. */
export const queryWith = (
query: Query,
fields: Partial<IBuilderQuery>,
): Query => ({
...query,
builder: {
...query.builder,
queryData: [{ ...query.builder.queryData[0], ...fields }],
},
});
/** A group-by key as the builder stores it: `id` is the select's option value. */
export const groupByKey = (
key: string,
type = 'tag',
dataType: DataTypes = DataTypes.String,
): BaseAutocompleteData => ({
key,
dataType,
type,
id: `${key}--${dataType}--${type}`,
});
export const meterQuery: Query = {
...initialQueriesMap.metrics,
builder: {

View File

@@ -1,43 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, waitFor, within } from 'storybook/test';
const TRACES_ADD_ONS = [
'group-by-content',
'having-content',
'order-by-content',
'limit-content',
'legend-format-content',
];
const groupByTags = (scope: HTMLElement): string[] =>
Array.from(
within(scope)
.getByTestId('group-by')
.querySelectorAll('.ant-select-selection-item'),
).map((tag) => tag.textContent ?? '');
/** Every add-on the seeded query fills opens on mount, group by with all its keys. */
export const expectTracesAddOnsOpen =
(groupByCount: number) =>
async ({ canvasElement }: { canvasElement: HTMLElement }): Promise<void> => {
const query = within(canvasElement).getByTestId('query-A');
await waitFor(async () => {
for (const testId of TRACES_ADD_ONS) {
await expect(within(query).getByTestId(testId)).toBeVisible();
}
});
const groupBy = within(query).getByTestId('group-by-content');
await waitFor(() => expect(groupByTags(groupBy)).toHaveLength(groupByCount));
};
/** The aggregation row's group by shows every seeded key. */
export const expectMetricsGroupBy =
(groupByCount: number) =>
async ({ canvasElement }: { canvasElement: HTMLElement }): Promise<void> => {
const query = within(canvasElement).getByTestId('query-A');
await waitFor(() => expect(groupByTags(query)).toHaveLength(groupByCount));
};

View File

@@ -1,73 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { initialQueriesMap } from 'constants/queryBuilder';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { groupByKey, queryWith } from '../QueryBuilderV2.stories.mocks';
/** Every traces add-on holding one short value. */
export const tracesFewAddOns: Query = queryWith(initialQueriesMap.traces, {
groupBy: [groupByKey('service.name', 'resource')],
having: { expression: 'count() > 10' },
orderBy: [{ columnName: 'count()', order: 'desc' }],
limit: 10,
legend: '{{service.name}}',
});
/** Every traces add-on filled past one line, so group by and order by wrap. */
export const tracesManyAddOns: Query = queryWith(initialQueriesMap.traces, {
groupBy: [
groupByKey('service.name', 'resource'),
groupByKey('deployment.environment', 'resource'),
groupByKey('host.name', 'resource'),
groupByKey('name', ''),
groupByKey('http.method'),
groupByKey('http.route'),
groupByKey('response_status_code'),
groupByKey('rpc.method'),
groupByKey('hasError', '', DataTypes.bool),
],
having: {
expression: 'count() > 10 AND count() < 5000 AND count() != 250',
},
orderBy: [
{ columnName: 'count()', order: 'desc' },
{ columnName: 'service.name', order: 'asc' },
{ columnName: 'http.route', order: 'asc' },
],
limit: 100,
legend:
'{{service.name}} {{deployment.environment}} {{http.method}} {{http.route}}',
});
const histogramWith = (keys: string[]): Query =>
queryWith(initialQueriesMap.metrics, {
aggregations: [
{
metricName: 'signoz_latency_bucket',
temporality: '',
timeAggregation: '',
spaceAggregation: 'p90',
reduceTo: undefined,
},
],
groupBy: keys.map((key) => groupByKey(key)),
});
/** A histogram grouped by one key in the aggregation row. */
export const metricsFewGroupBy: Query = histogramWith(['service_name']);
/** A histogram grouped by enough keys to wrap the aggregation row's select. */
export const metricsManyGroupBy: Query = histogramWith([
'service_name',
'operation',
'status_code',
'le',
'resource_deployment.environment',
'resource_host.name',
'resource_k8s.cluster.name',
]);

View File

@@ -98,15 +98,6 @@ export const noSavedFiltersHandler = rest.get(
),
);
export const noSavedTracesFiltersHandler = rest.get(
'http://localhost/api/v2/quick_filters/traces',
(_req, res, ctx) =>
res(
ctx.status(200),
ctx.json(quickFiltersResponse(QuickfiltertypesSourceDTO.traces, [])),
),
);
export const loadingFiltersHandlers = [
rest.get('http://localhost/api/v2/quick_filters/logs', (_req, res, ctx) =>
res(ctx.delay('infinite')),

View File

@@ -1,7 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { ComponentProps, ComponentType } from 'react';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import type { GlobalMockArgs } from '@/storybook/globals';
@@ -17,9 +16,8 @@ import {
queryBuilder,
selectedServiceQueryBuilder,
noSavedFiltersHandler,
noSavedTracesFiltersHandler,
} from './QuickFilters.stories.mocks';
import { FiltersType, QuickFiltersSource } from '../types';
import { QuickFiltersSource } from '../types';
const meta = {
title: 'Components/Quick Filters',
@@ -112,29 +110,6 @@ export const SelectedExpandedCheckbox: Story = {
},
};
/** The duration min/max row, which a checkbox-only config never reaches. */
export const DurationFilter: Story = {
args: {
quickFilterSource: QuickFiltersSource.TRACES_EXPLORER,
config: [
...checkboxConfig,
{
attributeKey: {
dataType: DataTypes.Float64,
key: 'duration_nano',
type: '',
},
defaultOpen: true,
title: 'Duration',
type: FiltersType.DURATION,
},
],
},
parameters: {
msw: { handlers: [noSavedTracesFiltersHandler, ...handlers] },
},
};
/**
* Every tooltip the panel renders, held open: the reveal on each truncated
* filter value. Nothing bounds those values, so the panel is answered with

View File

@@ -16,42 +16,13 @@ import {
} from './K8sBaseDetails.stories.mocks';
import type { K8sBaseDetailsProps } from './types';
import {
DrawerHistoryEntry,
getDrawerHistoryDepth,
useDrawerHistoryStore,
pushDrawerHistory,
resetDrawerHistory,
} from './useDrawerHistoryStore';
type DrawerArgs = PageStoryArgs<typeof drawerMocks> &
K8sBaseDetailsProps<unknown> & { earlierSteps?: number };
const TRAIL: DrawerHistoryEntry[] = [
{
category: InfraMonitoringEntity.CLUSTERS,
label: 'mgmt',
queryKeyPrefix: 'cluster',
},
{
category: InfraMonitoringEntity.NAMESPACES,
label: 'generator',
queryKeyPrefix: 'namespace',
},
{
category: InfraMonitoringEntity.DEPLOYMENTS,
label: 'app-demo-loadgenerator',
queryKeyPrefix: 'deployment',
},
{
category: InfraMonitoringEntity.NODES,
label: NODE_NAME,
queryKeyPrefix: 'node',
},
].map(({ category, label, queryKeyPrefix }) => ({
params: { selectedItem: label, category },
category,
label,
entity: { name: label },
queryKeyPrefix,
}));
K8sBaseDetailsProps<unknown>;
const route = `/infrastructure-monitoring/kubernetes?${INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY}=pods&${INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM}=${POD_UID}`;
@@ -62,13 +33,19 @@ const meta = {
decorators: [
(Story, context): JSX.Element => {
// The back control appears only for a resource opened from another
const steps =
context.args.earlierSteps ?? (context.args.openedFromANode ? 1 : 0);
if (getDrawerHistoryDepth() !== steps) {
useDrawerHistoryStore.setState({
entries: TRAIL.slice(TRAIL.length - steps),
const depth = getDrawerHistoryDepth();
if (context.args.openedFromANode && depth === 0) {
pushDrawerHistory({
params: { selectedItem: NODE_NAME, category: InfraMonitoringEntity.NODES },
category: InfraMonitoringEntity.NODES,
label: NODE_NAME,
entity: { nodeName: NODE_NAME },
queryKeyPrefix: 'node',
});
}
if (!context.args.openedFromANode && depth > 0) {
resetDrawerHistory();
}
return <Story />;
},
@@ -83,19 +60,3 @@ type Story = StoryObj<DrawerArgs>;
export const Default: Story = {
args: { ...podEntityConfig.details } as Partial<DrawerArgs> as DrawerArgs,
};
/** A pod drilled through a cluster, namespace, deployment and node, so the back control names the node. */
export const DeepTrail: Story = {
args: {
...podEntityConfig.details,
earlierSteps: 4,
} as Partial<DrawerArgs> as DrawerArgs,
};
/** A pod opened from the list, so the header shows the close control in place of back. */
export const OpenedFromTheList: Story = {
args: {
...podEntityConfig.details,
openedFromANode: false,
} as Partial<DrawerArgs> as DrawerArgs,
};

View File

@@ -139,35 +139,6 @@ export const AwaitingClarification: Story = {
args: { agent: 'awaiting-clarification', contents: BRIEF },
};
/** The severity select open, including the free-text option the form's Select renders. */
export const ClarificationSelectOpen: Story = {
args: { agent: 'awaiting-clarification', contents: BRIEF },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
// Open from the keyboard, and retry: the message list remounts its items
// while it measures the thread, which can close the popup again. The
// "Other" checkbox in the Notify field carries the same text, so assert
// on the popup's option role.
await waitFor(async () => {
const severityLabel = canvas.getByText('Severity');
const field = severityLabel.closest('div');
if (!field) {
throw new Error('Severity field is not in the clarification form');
}
within(field).getByRole('combobox').focus();
await userEvent.keyboard('{Enter}');
await screen.findByRole(
'option',
{ name: 'Other (type your own)' },
{ timeout: 1_000 },
);
}, untilLoaded);
},
};
/** Reopening the page on a thread that has not come back yet. */
export const LoadingThread: Story = {
args: { dataState: 'loading' },
@@ -260,23 +231,6 @@ export const NegativeFeedback: Story = {
},
};
/** Renaming a thread: the title input the row swaps in. */
export const ConversationRename: Story = {
play: async ({ canvasElement }): Promise<void> => {
await clickUntil(async () => {
const [actions] = await within(canvasElement).findAllByLabelText(
/conversation actions/i,
undefined,
untilLoaded,
);
return actions;
}, /^Rename$/);
await userEvent.click(screen.getByText('Rename'));
await within(canvasElement).findByDisplayValue(/checkout p99 regression/i);
},
};
/** What a conversation row offers: rename, a link to it, and archiving. */
export const ConversationActions: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -121,12 +121,12 @@ export const RailCollapsed: Story = {
};
/** The popover that names the current filters as a new saved view. */
export const SaveView: Story = {
export const SaveViewPopover: Story = {
play: openSaveViewPopover,
};
/** A saved view's rename popover, opened from its row. */
export const RenameView: Story = {
export const RenameViewPopover: Story = {
play: openRenameViewPopover,
};

View File

@@ -21,10 +21,6 @@ import {
WEBHOOK_AUTHS,
type WebhookAuthChoice,
} from '../../stories/__story_mockdata__/alerts';
import {
recordChannelTestRequest,
resetChannelTestRequests,
} from './__story_mockdata__/channelsEdit';
const STORY_CHANNEL_ID = '1';
@@ -91,13 +87,6 @@ export const channelsEditMocks = defineStoryMocks({
: resolveChannelActionSuccess,
),
rest.post(
'http://localhost/api/v2/notification_channels/test',
async (req) => {
recordChannelTestRequest(await req.json());
},
),
rest.post(
'http://localhost/api/v2/notification_channels/test',
values.testOutcome === 'fails'
@@ -106,5 +95,4 @@ export const channelsEditMocks = defineStoryMocks({
),
],
config: () => ({ route: `/alerts/channels/edit/${STORY_CHANNEL_ID}` }),
effect: () => resetChannelTestRequests(),
});

View File

@@ -4,7 +4,6 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { expectEditableForm } from './__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from './ChannelsEdit.stories.mocks';
import AlertList from '../../index';
@@ -37,10 +36,8 @@ type Story = StoryObj<ChannelsEditArgs>;
/**
* A saved notification channel opened for editing: the name and the type are
* fixed, and the integration's own settings are filled from what was stored.
* The Channel type control swaps the integration, and typing into any field
* unlocks Save.
*/
export const Default: Story = { play: expectEditableForm };
export const Default: Story = {};
/** Mutation: clearing the required webhook URL surfaces the form's validation feedback. */
export const InvalidRequiredFields: Story = {
@@ -113,25 +110,21 @@ export const SaveFailure: Story = {
*/
export const PagerDuty: Story = {
args: { channelType: 'pagerduty' },
play: expectEditableForm,
};
/** The webhook channel, saved with basic auth on the outgoing request. */
export const Webhook: Story = {
args: { channelType: 'webhook' },
play: expectEditableForm,
};
/** The webhook channel saved with a bearer token: only the token field shows. */
export const WebhookBearerToken: Story = {
args: { channelType: 'webhook', webhookAuth: 'bearer' },
play: expectEditableForm,
};
/** The webhook channel saved without credentials: the auth option is None. */
export const WebhookWithoutAuth: Story = {
args: { channelType: 'webhook', webhookAuth: 'none' },
play: expectEditableForm,
};
/**
@@ -140,7 +133,6 @@ export const WebhookWithoutAuth: Story = {
*/
export const Opsgenie: Story = {
args: { channelType: 'opsgenie' },
play: expectEditableForm,
};
/**
@@ -149,7 +141,6 @@ export const Opsgenie: Story = {
*/
export const Email: Story = {
args: { channelType: 'email' },
play: expectEditableForm,
};
/**
@@ -158,13 +149,11 @@ export const Email: Story = {
*/
export const MicrosoftTeams: Story = {
args: { channelType: 'msteams' },
play: expectEditableForm,
};
/** The Google Chat channel, filled from the space's incoming webhook. */
export const GoogleChat: Story = {
args: { channelType: 'googlechat' },
play: expectEditableForm,
};
/**
@@ -174,8 +163,7 @@ export const GoogleChat: Story = {
*/
export const Jira: Story = {
args: { channelType: 'jira' },
play: async ({ canvasElement, args }): Promise<void> => {
await expectEditableForm({ canvasElement, args });
play: async ({ canvasElement }): Promise<void> => {
// the advanced fields have their own card now, so nothing has to be
// expanded before they can be read
await expect(
@@ -195,8 +183,7 @@ export const Jira: Story = {
*/
export const JiraSelfHosted: Story = {
args: { channelType: 'jira', jiraDeployment: 'selfhosted' },
play: async ({ canvasElement, args }): Promise<void> => {
await expectEditableForm({ canvasElement, args });
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await expect(
await canvas.findByTestId('jira-pat-textbox', undefined, {
@@ -215,7 +202,6 @@ export const JiraSelfHosted: Story = {
*/
export const JiraServiceManagementOps: Story = {
args: { channelType: 'jsmops' },
play: expectEditableForm,
};
/**
@@ -224,11 +210,9 @@ export const JiraServiceManagementOps: Story = {
*/
export const IncidentIO: Story = {
args: { channelType: 'incidentio' },
play: expectEditableForm,
};
/** A Telegram channel, with its bot token masked behind the password field. */
export const Telegram: Story = {
args: { channelType: 'telegram' },
play: expectEditableForm,
};

View File

@@ -1,146 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { channelSpec } from '../../../stories/__story_mockdata__/alerts';
import { PAGE_LOAD } from '../../../stories/channelAuthz';
import type { channelsEditMocks } from '../ChannelsEdit.stories.mocks';
import { channelTestRequests } from './channelsEdit';
interface PlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof channelsEditMocks>;
}
/** Native text controls only: the switches and radios keep a hidden input of their own. */
const FIELD_SELECTOR =
'form input:not([aria-hidden="true"]):not([type="hidden"]), form textarea';
const allFields = (canvasElement: HTMLElement): HTMLElement[] =>
Array.from(canvasElement.querySelectorAll<HTMLElement>(FIELD_SELECTOR));
/** A saved channel's name is fixed, so it is off whether or not the form is. */
const editableFields = (canvasElement: HTMLElement): HTMLElement[] =>
allFields(canvasElement).filter((field) => field.id !== 'channel-name');
const SLACK_ROW_BUTTONS = /^slack-(field|action)-(remove-\d+|add)$/;
const slackRowButtons = (canvasElement: HTMLElement): HTMLElement[] =>
within(canvasElement).queryAllByTestId(SLACK_ROW_BUTTONS);
export const expectEditableForm = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const save = await within(canvasElement).findByTestId(
'save-channel-button',
undefined,
PAGE_LOAD,
);
await waitFor(
() => expect(editableFields(canvasElement).length).toBeGreaterThan(0),
PAGE_LOAD,
);
for (const field of editableFields(canvasElement)) {
await expect(field).toBeEnabled();
}
await expect(save).toHaveAttribute('aria-disabled', 'true');
await userEvent.type(editableFields(canvasElement)[0], 'x');
await waitFor(
() => expect(save).toHaveAttribute('aria-disabled', 'false'),
PAGE_LOAD,
);
};
/**
* The permission check answers after the form has mounted editable, so the
* fields are polled until they lock rather than read once.
*/
export const expectReadOnlyForm = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const canvas = within(canvasElement);
const save = await canvas.findByTestId(
'save-channel-button',
undefined,
PAGE_LOAD,
);
await waitFor(() => {
const fields = allFields(canvasElement);
void expect(fields.length).toBeGreaterThan(1);
fields.forEach((field) => {
void expect(field).toBeDisabled();
});
}, PAGE_LOAD);
await expect(save).toHaveAttribute('aria-disabled', 'true');
if (args.channelType === 'slack') {
const buttons = slackRowButtons(canvasElement);
const fieldCount = allFields(canvasElement).length;
// two field rows, one action row, and an add button for each list
await expect(buttons).toHaveLength(5);
for (const button of buttons) {
await userEvent.click(button);
}
await expect(slackRowButtons(canvasElement)).toHaveLength(5);
await expect(allFields(canvasElement)).toHaveLength(fieldCount);
}
};
/**
* Switching the mode swaps which credential fields render, so a click that
* landed would change how many fields the form holds.
*/
export const expectModeRadioLocked = async (
context: PlayContext,
radio: RegExp,
): Promise<void> => {
await expectReadOnlyForm(context);
const { canvasElement } = context;
const fieldCount = allFields(canvasElement).length;
await userEvent.click(
within(canvasElement).getByRole('radio', { name: radio }),
);
await expect(allFields(canvasElement)).toHaveLength(fieldCount);
};
export const expectWebhookAuthLocked = (context: PlayContext): Promise<void> =>
expectModeRadioLocked(context, /bearer/i);
export const expectJiraDeploymentLocked = (
context: PlayContext,
): Promise<void> => expectModeRadioLocked(context, /self-hosted/i);
export const sendSavedConfig = async (context: PlayContext): Promise<void> => {
const { canvasElement, args } = context;
await expectReadOnlyForm(context);
const test = await within(canvasElement).findByTestId('test-channel-button');
await waitFor(
() => expect(test).toHaveAttribute('aria-disabled', 'false'),
PAGE_LOAD,
);
await userEvent.click(test);
await waitFor(() => expect(channelTestRequests()).toHaveLength(1), PAGE_LOAD);
await expect(channelTestRequests()[0].config).toMatchObject({
kind: args.channelType,
spec: channelSpec(args.channelType, args.webhookAuth, args.jiraDeployment),
});
};

View File

@@ -1,22 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import type { AlertmanagertypesTestableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
/** Every test send the form made since the story mounted, oldest first. */
const testRequests: AlertmanagertypesTestableNotificationChannelDTO[] = [];
export const recordChannelTestRequest = (
request: AlertmanagertypesTestableNotificationChannelDTO,
): void => {
testRequests.push(request);
};
export const channelTestRequests =
(): readonly AlertmanagertypesTestableNotificationChannelDTO[] => testRequests;
export const resetChannelTestRequests = (): void => {
testRequests.length = 0;
};

View File

@@ -13,12 +13,6 @@ import {
READ,
UPDATE,
} from '../../../stories/channelAuthz';
import {
expectJiraDeploymentLocked,
expectReadOnlyForm,
expectWebhookAuthLocked,
sendSavedConfig,
} from '../__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from '../ChannelsEdit.stories.mocks';
import AlertList from '../../../index';
@@ -62,12 +56,18 @@ export const NoRead: Story = {
/**
* Reading is enough to open the page, so losing `update` alone leaves it
* standing read-only: every field goes disabled and Save is locked, not hidden.
* The Channel type control walks the same check across every integration.
* standing read-only: the fields go disabled and Save is locked, not hidden.
*/
export const NoUpdate: Story = {
args: { revoked: [UPDATE] },
play: expectReadOnlyForm,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expectDisabled(
await canvas.findByTestId('save-channel-button', undefined, PAGE_LOAD),
);
await expectDisabled(await canvas.findByTestId('slack-channel-textbox'));
},
};
/**
@@ -101,22 +101,15 @@ export const NoCreate: Story = {
*/
export const ReadOnly: Story = {
args: { revoked: [UPDATE, CREATE, DELETE] },
play: async (context) => {
await expectReadOnlyForm(context);
await expectDisabled(
await within(context.canvasElement).findByTestId('test-channel-button'),
);
},
};
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
/**
* Read-only keeps Test: sending is a create on the collection, so a reader who
* cannot edit the channel can still test it. The request carries the saved
* config.
*/
export const NoUpdateTest: Story = {
args: { revoked: [UPDATE] },
play: sendSavedConfig,
await expectDisabled(
await canvas.findByTestId('save-channel-button', undefined, PAGE_LOAD),
);
await expectDisabled(await canvas.findByTestId('test-channel-button'));
await expectDisabled(await canvas.findByTestId('slack-channel-textbox'));
},
};
/**
@@ -152,25 +145,6 @@ export const TelegramReadOnly: Story = {
},
};
/**
* The same denial on a webhook saved with basic auth. The credential fields are
* off, and so is the radio that would swap them for a bearer token.
*/
export const WebhookReadOnly: Story = {
args: { channelType: 'webhook', revoked: [UPDATE, CREATE, DELETE] },
play: expectWebhookAuthLocked,
};
/**
* The same denial on a Jira Cloud channel. Every field is off, including the
* advanced ones, and so is the radio that would swap the Atlassian email and API
* token for a personal access token.
*/
export const JiraReadOnly: Story = {
args: { channelType: 'jira', revoked: [UPDATE, CREATE, DELETE] },
play: expectJiraDeploymentLocked,
};
/** No channel permission at all: the page is denied before the form exists. */
export const NoChannelAccess: Story = {
args: { revoked: NOTIFICATION_CHANNEL },

View File

@@ -954,7 +954,7 @@ const CHANNEL_SPECS: Record<ChannelType, Record<string, unknown>> = {
},
};
export const channelSpec = (
const channelSpec = (
type: ChannelType,
webhookAuth: WebhookAuthChoice,
jiraDeployment: JiraDeploymentChoice,

View File

@@ -120,6 +120,17 @@ export const QuickFiltersSettingsDirty: Story = {
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};
/** The resource filter opened: every key the exceptions can be narrowed by. */
export const FilterKeySuggestions: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -14,9 +14,14 @@ import type {
GetQuickFilters200,
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
type BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import type { Exception, Order, OrderBy } from 'types/api/errors/getAll';
import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';
import { fieldKeysResponse } from '@/storybook/msw/__story_mockdata__/fields';
import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';
export interface ExceptionShape {
@@ -293,43 +298,28 @@ export const exceptionAttributeValuesResponse = (
};
};
const ATTRIBUTE_KEYS: TelemetrytypesTelemetryFieldKeyDTO[] = [
...QUICK_FILTERS,
{
name: 'service.namespace',
fieldDataType: stringType,
fieldContext: resource,
},
{ name: 'k8s.pod.name', fieldDataType: stringType, fieldContext: resource },
{
name: 'k8s.cluster.name',
fieldDataType: stringType,
fieldContext: resource,
},
{ name: 'cloud.region', fieldDataType: stringType, fieldContext: resource },
const ATTRIBUTE_KEYS: BaseAutocompleteData[] = [
...QUICK_FILTERS.map(({ name, fieldDataType, fieldContext }) => ({
key: name,
dataType: fieldDataType === bool ? DataTypes.bool : DataTypes.String,
type: fieldContext === attribute ? 'tag' : String(fieldContext),
})),
{ key: 'service.namespace', dataType: DataTypes.String, type: 'resource' },
{ key: 'k8s.pod.name', dataType: DataTypes.String, type: 'resource' },
{ key: 'k8s.cluster.name', dataType: DataTypes.String, type: 'resource' },
{ key: 'cloud.region', dataType: DataTypes.String, type: 'resource' },
];
/**
* The resource filter and the quick filter settings panel both list keys from
* `/fields/keys`; each key keeps its own context and data type.
*/
/** The quick filter settings panel lists its "other filters" from `/fields/keys`. */
export const exceptionFieldKeysResponse = (
searchText: string | null,
): GetFieldsKeys200 => {
const search = (searchText ?? '').toLowerCase();
return {
status: 'success',
data: {
complete: true,
keys: Object.fromEntries(
ATTRIBUTE_KEYS.filter(({ name }) =>
name.toLowerCase().includes(search),
).map((key) => [
key.name,
[{ ...key, signal: TelemetrytypesSignalDTO.traces }],
]),
),
},
};
return fieldKeysResponse(
ATTRIBUTE_KEYS.map(({ key }) => key).filter((key) =>
key.toLowerCase().includes(search),
),
{ signal: TelemetrytypesSignalDTO.logs, fieldContext: resource },
);
};

View File

@@ -182,3 +182,14 @@ export const QuickFiltersSettings: Story = {
export const QuickFiltersSettingsDirty: Story = {
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};

View File

@@ -59,6 +59,28 @@ export const AnomalyAlert: Story = {
args: { alertMode: 'anomaly' },
};
/**
* An anomaly alert handed to routing policies: the channel picker leaves the
* condition, and the banner points at the policies that route it instead.
*/
export const AnomalyAlertRoutingPolicies: Story = {
args: { alertMode: 'anomaly' },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByTestId('routing-policies-switch', undefined, {
timeout: 15_000,
}),
);
await waitFor(() =>
expect(
canvas.queryByTestId('threshold-notification-channel-select'),
).not.toBeInTheDocument(),
);
},
};
/**
* The match-type tooltip on the threshold sentence: a paragraph on what an
* aggregated data point is, a worked example over five of them, and the docs

View File

@@ -1,40 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { createAlertMocks } from '../CreateAlert.stories.mocks';
type CreateAlertArgs = PageStoryArgs<typeof createAlertMocks>;
interface PlayContext {
canvasElement: HTMLElement;
args: Pick<CreateAlertArgs, 'alertMode'>;
}
const untilLoaded = { timeout: 15_000 };
/** Every rule type carries the banner; only the type picker has no form. */
export const enableRoutingPolicies = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.alertMode === 'select-type') {
return;
}
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByTestId('routing-policies-switch', undefined, untilLoaded),
);
await waitFor(() =>
expect(
canvas.queryByTestId('threshold-notification-channel-select'),
).not.toBeInTheDocument(),
);
};

View File

@@ -63,20 +63,6 @@ const expandConfigSections: Story['play'] = async ({ canvasElement }) => {
*/
export const Default: Story = {};
/** The ClickHouse query tab, including its info callout. */
export const ClickHouseQuery: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText('ClickHouse Query', undefined, {
timeout: 15000,
}),
);
await screen.findByText(/ClickHouse query agent skill/i, undefined, {
timeout: 15000,
});
},
};
/** The create route, seeding an unsaved panel of the chosen kind. */
export const NewPanel: Story = {
args: { panel: 'new' },
@@ -97,21 +83,6 @@ export const PieChartPanel: Story = {
args: { panel: 'traffic-share' },
};
/** A new area chart: the time series options with the area filled. */
export const AreaChartPanel: Story = {
args: { panel: 'new', newPanelKind: 'area-chart' },
};
/** A new histogram, where the display options are its buckets. */
export const HistogramPanel: Story = {
args: { panel: 'new', newPanelKind: 'histogram' },
};
/** A new text panel: a markdown body in place of the query builder. */
export const TextPanel: Story = {
args: { panel: 'new', newPanelKind: 'text' },
};
/** A list panel, where the config pane is the column editor. */
export const ListPanel: Story = {
args: { panel: 'recent-logs' },

View File

@@ -105,19 +105,6 @@ export const ChartAppearance: Story = {
},
};
/** Disconnect-values in threshold mode, with an invalid duration showing the inline error. */
export const ChartAppearanceDisconnectThreshold: Story = {
play: async (context) => {
await ChartAppearance.play?.(context);
await pickSegment('panel-editor-v2-span-gaps', 'threshold');
const input = await screen.findByTestId('panel-editor-v2-span-gaps-value');
await userEvent.clear(input);
await userEvent.type(input, '5x');
await screen.findByText(/enter a valid duration/i);
},
};
/** Dashed lines under a gradient fill, with the points drawn. */
export const ChartAppearanceDashedGradient: Story = {
play: async (context) => {

View File

@@ -191,22 +191,6 @@ export const TooltipsInViewPanelModal: Story = {
},
};
/** A list or table panel's search field, expanded and filled. */
export const PanelSearchExpanded: Story = {
play: async ({ canvasElement }) => {
// Both the table and the log list render a search trigger; expand the first.
const [trigger] = await within(canvasElement).findAllByTestId(
'panel-header-search-trigger',
{},
{ timeout: 15000 },
);
await userEvent.click(trigger);
const input = await screen.findByTestId('panel-header-search-input');
await userEvent.type(input, 'error');
},
};
/**
* The dashboard's own Actions menu, open: rename, clone, lock, full screen and
* delete, the menu the toolbar's Actions button carries.
@@ -259,34 +243,6 @@ export const SectionActionsMenu: Story = {
},
};
/** Delete dashboard, the confirm dialog the Actions menu opens. */
export const DeleteDashboardDialog: Story = {
play: async (context) => {
await ActionsMenu.play?.(context);
// The row stays inert until its authz checks resolve, so one click can
// land too early; keep clicking until the confirm dialog is up.
await waitFor(
async () => {
const item = screen.queryByTestId('dashboard-action-delete');
if (item) {
await userEvent.click(item);
}
screen.getByText('This action cannot be undone.');
},
{ timeout: 10000 },
);
},
};
/** Rename section, the title dialog a section menu opens. */
export const RenameSectionDialog: Story = {
play: async (context) => {
await SectionActionsMenu.play?.(context);
await userEvent.click(await screen.findByText('Rename section'));
await screen.findByRole('dialog', { name: /rename section/i });
},
};
const openNewPanelPicker = async (
canvasElement: HTMLElement,
): Promise<void> => {

View File

@@ -22,7 +22,6 @@ import {
openEditTagsDialog,
openFirstRowActions,
openRenameDialog,
openRenameViewPopover,
openSaveViewPopover,
openTemplateTab,
pinDashboard,
@@ -140,15 +139,10 @@ export const EditTagsDialog: Story = {
};
/** The popover that names the current filters as a new saved view. */
export const SaveView: Story = {
export const SaveViewPopover: Story = {
play: openSaveViewPopover,
};
/** A saved view's rename popover, opened from its row. */
export const RenameView: Story = {
play: openRenameViewPopover,
};
/** The renamed toast, raised once the PATCH answers. */
export const DashboardRenamedToast: Story = {
play: renameDashboard,

View File

@@ -165,22 +165,6 @@ export const openSaveViewPopover = async ({
await screen.findByText('Save as view');
};
export const openRenameViewPopover = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const [rename] = await within(canvasElement).findAllByRole(
'button',
{ name: 'Rename view' },
{ timeout: TOAST_TIMEOUT },
);
// The actions only take pointer events while the row is hovered by CSS.
await userEvent.click(rename, { pointerEventsCheck: 0 });
await screen.findByTestId('rename-view-name', undefined, {
timeout: TOAST_TIMEOUT,
});
};
export const renameDashboard = async ({
canvasElement,
args,

View File

@@ -97,12 +97,3 @@ export const NavSettingsMenu: Story = {
await screen.findByRole('menu');
},
};
/** The command palette, opened with the same shortcut the shell listens for. */
export const CommandPalette: Story = {
play: async (): Promise<void> => {
await userEvent.keyboard('{Meta>}k{/Meta}');
await screen.findByPlaceholderText('Search…', undefined, { timeout: 10000 });
await screen.findByText('Go to Home');
},
};

View File

@@ -11,7 +11,6 @@ import {
import {
copyPodMetadata,
copyPodName,
openDrawerLogDetails,
openDrawerLogsTab,
openTableOptions,
suggestFilterKeys,
@@ -64,12 +63,6 @@ export const DetailsDrawerLogsTab: StoryObj<PodsArgs> = {
play: openDrawerLogsTab,
};
/** A log opened from the pod's logs tab, over the details drawer. */
export const DetailsDrawerLogDetails: StoryObj<PodsArgs> = {
args: { drawer: true },
play: openDrawerLogDetails,
};
/** The copy button beside the pod name in the drawer, which toasts the copy. */
export const PodNameCopiedToast: StoryObj<PodsArgs> = {
args: { drawer: true },

View File

@@ -32,28 +32,6 @@ export const openDrawerLogsTab = async ({
await drawer.findAllByText(/handled request in/, {}, { timeout: 10000 });
};
export const openDrawerLogDetails = async ({
args,
}: PlayContext): Promise<void> => {
if (!args.drawer || args.dataState !== 'loaded' || args.telemetryRows === 0) {
return;
}
const drawer = within(
await screen.findByRole('dialog', {}, { timeout: 10000 }),
);
await userEvent.click(await drawer.findByText('Logs', {}, { timeout: 10000 }));
const [line] = await drawer.findAllByText(
/handled request in/,
{},
{ timeout: 10000 },
);
await userEvent.click(line);
await screen.findByTestId('log-detail-drawer', {}, { timeout: 10000 });
};
export const copyPodName = async ({ args }: PlayContext): Promise<void> => {
if (!args.drawer) {
return;

View File

@@ -117,43 +117,6 @@ export const ConnectAccount: Story = {
},
};
/** Azure's connect dialog, which the AWS regions form does not open. */
export const AzureConnectAccount: Story = {
args: { provider: 'azure', accounts: 0 },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/integrate now/i,
undefined,
untilLoaded,
),
);
await screen.findByRole('dialog', undefined, untilLoaded);
},
};
/** The GCP region combobox, opened from the connect drawer. */
export const GcpRegionDropdown: Story = {
args: { provider: 'gcp', accounts: 0 },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/integrate now/i,
undefined,
untilLoaded,
),
);
await userEvent.click(
await screen.findByTestId(
'gcp-deployment-region-select',
undefined,
untilLoaded,
),
);
await screen.findByRole('listbox');
},
};
/** The regions an already-connected account collects from. */
export const EditAccount: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -14,7 +14,6 @@ import {
type GroupSave,
MAPPING_GROUP_MAX,
spanMapperGroupsResponse,
spanMappersResponse,
wideConditionGroupsResponse,
} from './__story_mockdata__/attributeMapping';
@@ -29,15 +28,6 @@ export const wideConditionGroup = rest.get(
res(ctx.status(200), ctx.json(wideConditionGroupsResponse())),
);
export const groupMappers = rest.get(
'http://localhost/api/v1/span_mapper_groups/:groupId/span_mappers',
(req, res, ctx) =>
res(
ctx.status(200),
ctx.json(spanMappersResponse(String(req.params.groupId))),
),
);
export const attributeMappingMocks = defineStoryMocks({
controls: {
groups: countControl('Mapping groups', {

View File

@@ -7,7 +7,6 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import LLMObservabilityPage from '../../index';
import {
attributeMappingMocks,
groupMappers,
wideConditionGroup,
} from './AttributeMapping.stories.mocks';
@@ -80,29 +79,6 @@ export const GroupFormDrawer: Story = {
},
};
/** The drawer that adds a mapping to the first group. */
export const AddMappingDrawer: Story = {
parameters: { msw: { handlers: [groupMappers] } },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
const [firstGroup] = await canvas.findAllByTestId(
/^group-expand-/,
{},
{ timeout: 15000 },
);
await userEvent.click(firstGroup);
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /add mapping/i },
{ timeout: 15000 },
),
);
await screen.findByText('New custom mapping');
},
};
/**
* A group toggled off and saved: the toast announcing the saved changes, raised
* once the PATCH and the list refetch answer. Set Save changes to `error`,

View File

@@ -5,15 +5,10 @@
import type {
ListSpanMapperGroups200,
ListSpanMappers200,
SpantypesSpanMapperGroupConditionKeyDTO,
SpantypesSpanMapperGroupDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
SpantypesFieldContextDTO,
SpantypesSpanMapperOperationDTO,
SpantypesSpanMapperOriginDTO,
} from 'api/generated/services/sigNoz.schemas';
import { SpantypesSpanMapperOriginDTO } from 'api/generated/services/sigNoz.schemas';
const ORG_ID = 'org-signoz';
@@ -77,38 +72,6 @@ export const spanMapperGroupsResponse = (
data: { items: GROUPS.slice(0, count).map(group) },
});
/** The mappings an expanded group lists, which the groups response does not carry. */
export const spanMappersResponse = (groupId: string): ListSpanMappers200 => ({
status: 'success',
data: {
items: [
{
id: `${groupId}-mapper-1`,
groupId,
name: 'gen_ai.request.model',
enabled: true,
origin: SpantypesSpanMapperOriginDTO.user,
fieldContext: SpantypesFieldContextDTO.attribute,
config: {
sources: [
{
key: 'langchain.model',
context: SpantypesFieldContextDTO.attribute,
operation: SpantypesSpanMapperOperationDTO.copy,
priority: 0,
enabled: true,
},
],
},
createdAt: '2026-07-18T11:20:00Z',
createdBy: 'anna@signoz.io',
updatedAt: '2026-08-05T08:40:00Z',
updatedBy: 'anna@signoz.io',
},
],
},
});
const MANY_ATTRIBUTES = [
'langchain.model',
'langchain.prompt_tokens',

View File

@@ -168,6 +168,17 @@ export const QuickFiltersSettingsDirty: Story = {
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};
/** A quick-filter value selected against the LLM span query. */
export const QuickFilterSelected: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -39,34 +39,6 @@ export const NothingPriced: Story = {
args: { rules: 0 },
};
/** Models seen in spans that no rule prices yet. */
export const UnpricedModels: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'tab',
{ name: /unpriced models/i },
{ timeout: 15000 },
),
);
await screen.findByRole('tab', { name: /unpriced models/i, selected: true });
},
};
/** Creating a rule: the blank drawer, with the provider select enabled. */
export const ModelCostDrawerCreate: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /add model cost/i },
{ timeout: 15000 },
),
);
await screen.findByTestId('drawer-provider-select');
},
};
/**
* The first pricing rule's menu, open over the table: edit the rule or drop it.
*/

View File

@@ -116,16 +116,6 @@ export const AddProcessor: Story = {
},
};
/** Severity Parser is the type whose mapping fields are CSV inputs. */
export const AddSeverityParserProcessor: Story = {
play: async (context): Promise<void> => {
await AddProcessor.play?.(context);
await userEvent.click(await screen.findByText('Grok'));
await userEvent.click(await screen.findByTitle('Severity Parser'));
await screen.findByText('Parse Severity Value From');
},
};
/**
* The logs a pipeline matches, over the interval the preview asks for, with the
* simulation of its processors one click away.

View File

@@ -9,7 +9,6 @@ import {
copyLogDetailsLink,
copyLogLinkFromRow,
dirtyQuickFiltersSettings,
openFormatMenu,
openLogContext,
openLogDetails,
openLogDetailsMenu,
@@ -83,12 +82,6 @@ export const RawFormat: Story = {
args: { format: 'raw' },
};
/** The format popover: the format list, the max-lines stepper, and the font-size control. */
export const FormatMenuOpen: Story = {
args: { format: 'raw' },
play: openFormatMenu,
};
/** An explorer with no configured quick filters. */
export const NoQuickFilters: Story = {
args: { quickFilters: 0 },
@@ -171,6 +164,17 @@ export const QuickFiltersSettingsDirty: Story = {
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};
/**
* Every tooltip the explorer renders, held open at once: the quick filters'
* severity, host and service values on the left, and the drawer's move to

View File

@@ -122,25 +122,6 @@ export const openLogDetailsMenu = async ({
await screen.findByText('Copy link to log');
};
/** The format options sit in the list view's toolbar. */
export const openFormatMenu = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.view !== 'list') {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'periscope-btn-format-options',
undefined,
untilLoaded,
),
);
await screen.findByTestId('max-lines-per-row', undefined, untilLoaded);
};
export const openQuickFiltersSettings = async ({
args,
}: PlayContext): Promise<void> => {

View File

@@ -1,6 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { MessagingQueuesViewTypeOptions } from 'pages/MessagingQueues/MessagingQueuesUtils';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { expect, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -98,21 +98,6 @@ export const DropRate: Story = {
args: { view: MessagingQueuesViewTypeOptions.DropRate },
};
/** The custom-interval input inside the evaluation-time dropdown. */
export const DropRateIntervalOpen: Story = {
args: { view: MessagingQueuesViewTypeOptions.DropRate },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText('10ms', undefined, untilLoaded),
);
await screen.findByPlaceholderText(
'Enter custom time (ms)',
undefined,
untilLoaded,
);
},
};
/** The broker, producer, consumer and JVM metrics kafka itself reports. */
export const MetricView: Story = {
args: { view: MessagingQueuesViewTypeOptions.MetricPage },

View File

@@ -85,6 +85,24 @@ export const NoUsage: Story = {
args: { signals: [], quickFilters: 0, savedViews: 0 },
};
/**
* A window from the meter's beta phase, which a cloud tenant is warned about
* because the numbers from before 22 August 2025 are not billable.
*/
export const BeforeMeterLaunch: Story = {
args: { timeRange: 'august-2025' },
};
/** The warning shown when the selected window is shorter than one hour. */
export const ShortWindowNotice: Story = {
args: { timeRange: 'last-30-minutes' },
};
/** The returning-user meter view after the billing notice was dismissed. */
export const BillingNoticeDismissed: Story = {
args: { billingNotice: false },
};
/** Meter usage where only logs are currently ingesting. */
export const PartialIngestion: Story = {
args: { signals: ['logs'] },
@@ -106,3 +124,14 @@ export const QuickFiltersSettingsDirty: Story = {
args: { tab: 'explorer' },
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { tab: 'explorer', banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};

View File

@@ -1,7 +1,7 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { renderAtRoute } from '@/storybook/renderAtRoute';
import { screen, userEvent, waitFor, within } from 'storybook/test';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -76,26 +76,3 @@ export const DownloadMenu: Story = {
await screen.findByRole('menu');
},
};
/** The apdex threshold popover, opened from the overview's settings control. */
export const ApDexSettingsOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
const trigger = await waitFor(
() => {
const found = canvasElement.querySelector<HTMLElement>(
'.ap-dex-settings-popover-content button',
);
if (!found) {
throw new Error('Apdex settings control is not rendered');
}
return found;
},
{ timeout: 15000 },
);
await userEvent.click(trigger);
await screen.findByText(/apdex threshold/i);
},
};

View File

@@ -613,22 +613,6 @@ const RULE_UPDATED_AT = '2026-08-20T09:24:00Z';
const RULE_EFFECTIVE_FROM = '2026-08-20T09:29:00Z';
const isPendingRule = (index: number, pending: boolean): boolean =>
pending && index % 4 === 0;
/** Whether the drawer's metric has a rule that has not taken effect yet. */
export const hasPendingRule = (
type: DrawerMetricType,
count: number,
pending: boolean,
): boolean => {
const index = REDUCTION_RULES.findIndex(
({ metricName }) => metricName === drawerMetricName(type),
);
return index >= 0 && index < count && isPendingRule(index, pending);
};
const ruleOf = (
seed: ReductionRuleSeed,
index: number,
@@ -643,7 +627,7 @@ const ruleOf = (
labels: seed.labels,
// A rule takes about five minutes to take effect; until then the table
// badges it as pending.
active: !isPendingRule(index, pending),
active: !(pending && index % 4 === 0),
effectiveFrom: RULE_EFFECTIVE_FROM,
ingestedSeries: timeseries,
retainedSeries: Math.round(timeseries * (1 - seed.reduction)),

View File

@@ -86,11 +86,6 @@ export const onboardingV2Mocks = defineStoryMocks({
'http://localhost/api/v1/roles',
response.json(() => rolesListResponse(0)),
),
// Add Credit Card creates the subscription; an empty redirect keeps the
// story from opening a billing tab.
rest.post('http://localhost/api/v1/subscriptions', (_req, res, ctx) =>
res(ctx.json({ status: 'success', data: { redirectURL: '' } })),
),
rest.post('http://localhost/api/v2/users', (_req, res, ctx) => {
if (values.invite === 'loading') {
return res(ctx.delay('infinite'));

View File

@@ -1,20 +1,82 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import OnboardingPageV2 from '../OnboardingPageV2';
import { onboardingV2Mocks } from './OnboardingPageV2.stories.mocks';
import {
openAddCreditCard,
openInviteModal,
searchWithoutResults,
sendInvite,
walkToStep,
} from './__story_mockdata__/onboardingV2.play';
onboardingV2Mocks,
SETUP_STEPS,
type SetupStep,
} from './OnboardingPageV2.stories.mocks';
type OnboardingV2Args = PageStoryArgs<typeof onboardingV2Mocks>;
type Canvas = ReturnType<typeof within>;
/** The catalogue mounts before the first group of sources paints. */
const untilRendered = { timeout: 15_000 };
/**
* Every option is a button wrapping its own logo, so the accessible name carries
* the label twice and matches the other sources with the label as a prefix
* (`Java`, `JavaScript`). The label's own text node is the one thing that is
* exact.
*/
const chooseOption = async (canvas: Canvas, label: string): Promise<void> => {
const option = await canvas.findByText(label, undefined, untilRendered);
await userEvent.click(option.closest('button') as HTMLElement);
};
const answerDataSource = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Java');
const answerFramework = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Spring Boot');
const answerEnvironment = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'VM');
const openConfigureProduct = async (canvas: Canvas): Promise<void> => {
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /configure your product/i },
untilRendered,
),
);
};
const ANSWER_STEP = [
answerDataSource,
answerFramework,
answerEnvironment,
openConfigureProduct,
];
const advanceToSetupStep = async (
canvasElement: HTMLElement,
step: SetupStep,
): Promise<void> => {
const canvas = within(canvasElement);
// A source that arrived through the param is already on the setup
// instructions, with no question left to answer.
if (!canvas.queryByText('Select your data source')) {
return;
}
const answers = ANSWER_STEP.slice(0, SETUP_STEPS.indexOf(step));
// Sequential: each answer is what renders the question the next one reads.
await answers.reduce(
(walked, answer) => walked.then(() => answer(canvas)),
Promise.resolve(),
);
};
const pageStory = storyMocks(onboardingV2Mocks, { layout: 'app' });
/**
@@ -27,7 +89,16 @@ const meta = {
title: 'Pages/Onboarding/Add Data Source',
tags: ['play'],
component: OnboardingPageV2,
play: walkToStep,
/**
* Destructuring `mount` is what makes the step control a control: Storybook
* re-runs a play function on an arg change only for a story that asks to be
* remounted, and otherwise re-renders the one it already walked.
*/
play: async ({ mount, args, canvasElement }): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
},
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<OnboardingV2Args>;
@@ -66,12 +137,35 @@ export const SourcePreselected: Story = {
/** The one thing the header offers besides support: bringing the team along. */
export const InviteTeammate: Story = {
play: openInviteModal,
play: async ({ mount, args, canvasElement }): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
await userEvent.click(
within(canvasElement).getByRole('button', { name: /invite a teammate/i }),
);
// antd portals the modal out of the story root.
await screen.findByText('Invite a team member', undefined, untilRendered);
},
};
/** A search nothing answers, where the catalogue offers to add the source instead. */
export const NoSearchResults: Story = {
play: searchWithoutResults,
play: async ({ mount, canvasElement }): Promise<void> => {
await mount();
const canvas = within(canvasElement);
await userEvent.type(
await canvas.findByPlaceholderText('Search', undefined, untilRendered),
'ledger',
);
// The search is debounced, so the miss lands a beat after the last keystroke.
await canvas.findByText(/no results for ledger/i, undefined, untilRendered);
},
};
/**
@@ -80,14 +174,48 @@ export const NoSearchResults: Story = {
* is accepted; Invite result changes how it answers.
*/
export const InvitesSentToast: Story = {
play: sendInvite,
};
play: async ({ mount, args, canvasElement }): Promise<void> => {
await mount();
/**
* A cloud trial without premium support, whose Contact Support in the header asks
* for a card to unlock chat support instead of opening the chat.
*/
export const FacingIssuesAddCard: Story = {
args: { support: 'add-card' },
play: openAddCreditCard,
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /invite a teammate/i },
untilRendered,
),
);
const dialog = await screen.findByRole('dialog', undefined, untilRendered);
const [email] = await within(dialog).findAllByTestId(
/^invite-email-/,
undefined,
untilRendered,
);
await userEvent.type(email, 'jon@winterfell.dev');
const [roles] = await within(dialog).findAllByRole('combobox');
await userEvent.click(roles);
const viewers = await screen.findAllByText(
'viewer',
undefined,
untilRendered,
);
await userEvent.click(
viewers[viewers.length - 1].closest(
'.ant-select-item-option',
) as HTMLElement,
);
await userEvent.keyboard('{Escape}');
await userEvent.click(
await within(dialog).findByRole('button', { name: /send invites/i }),
);
if (args.invite === 'success') {
await waitFor(() =>
expect(screen.getByText(/invites sent successfully/i)).toBeVisible(),
);
}
},
};

View File

@@ -1,227 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
onboardingV2Mocks,
SETUP_STEPS,
type SetupStep,
} from '../OnboardingPageV2.stories.mocks';
type OnboardingV2Args = PageStoryArgs<typeof onboardingV2Mocks>;
interface PlayContext {
mount: () => Promise<unknown>;
args: OnboardingV2Args;
canvasElement: HTMLElement;
}
type Canvas = ReturnType<typeof within>;
/** The catalogue mounts before the first group of sources paints. */
const untilRendered = { timeout: 15_000 };
/**
* Every option is a button wrapping its own logo, so the accessible name carries
* the label twice and matches the other sources with the label as a prefix
* (`Java`, `JavaScript`). The label's own text node is the one thing that is
* exact.
*/
const chooseOption = async (canvas: Canvas, label: string): Promise<void> => {
const option = await canvas.findByText(label, undefined, untilRendered);
await userEvent.click(option.closest('button') as HTMLElement);
};
const answerDataSource = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Java');
const answerFramework = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'Spring Boot');
const answerEnvironment = (canvas: Canvas): Promise<void> =>
chooseOption(canvas, 'VM');
const openConfigureProduct = async (canvas: Canvas): Promise<void> => {
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /configure your product/i },
untilRendered,
),
);
};
const ANSWER_STEP = [
answerDataSource,
answerFramework,
answerEnvironment,
openConfigureProduct,
];
const advanceToSetupStep = async (
canvasElement: HTMLElement,
step: SetupStep,
): Promise<void> => {
const canvas = within(canvasElement);
// A source that arrived through the param is already on the setup
// instructions, with no question left to answer.
if (!canvas.queryByText('Select your data source')) {
return;
}
const answers = ANSWER_STEP.slice(0, SETUP_STEPS.indexOf(step));
// Sequential: each answer is what renders the question the next one reads.
await answers.reduce(
(walked, answer) => walked.then(() => answer(canvas)),
Promise.resolve(),
);
};
/**
* Destructuring `mount` is what makes the step control a control: Storybook
* re-runs a play function on an arg change only for a story that asks to be
* remounted, and otherwise re-renders the one it already walked.
*/
export const walkToStep = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
};
export const openInviteModal = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await advanceToSetupStep(canvasElement, args.step);
await userEvent.click(
within(canvasElement).getByRole('button', { name: /invite a teammate/i }),
);
// antd portals the modal out of the story root.
await screen.findByText('Invite a team member', undefined, untilRendered);
};
export const searchWithoutResults = async ({
mount,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
const canvas = within(canvasElement);
await userEvent.type(
await canvas.findByPlaceholderText('Search', undefined, untilRendered),
'ledger',
);
// The search is debounced, so the miss lands a beat after the last keystroke.
await canvas.findByText(/no results for ledger/i, undefined, untilRendered);
};
export const sendInvite = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /invite a teammate/i },
untilRendered,
),
);
const dialog = await screen.findByRole('dialog', undefined, untilRendered);
const [email] = await within(dialog).findAllByTestId(
/^invite-email-/,
undefined,
untilRendered,
);
await userEvent.type(email, 'jon@winterfell.dev');
const [roles] = await within(dialog).findAllByRole('combobox');
await userEvent.click(roles);
const viewers = await screen.findAllByText('viewer', undefined, untilRendered);
await userEvent.click(
viewers[viewers.length - 1].closest('.ant-select-item-option') as HTMLElement,
);
await userEvent.keyboard('{Escape}');
await userEvent.click(
await within(dialog).findByRole('button', { name: /send invites/i }),
);
if (args.invite === 'success') {
await waitFor(
() => expect(screen.getByText(/invites sent successfully/i)).toBeVisible(),
{ timeout: 5_000 },
);
}
};
/** Banners that turn the cloud license into a self-hosted one. */
const SELF_HOSTED_BANNERS: readonly OnboardingV2Args['banner'][] = [
'license-expired',
'license-terminated',
];
/** Only a cloud workspace without premium support is offered the card. */
const offersAddCard = (args: OnboardingV2Args): boolean =>
args.support === 'add-card' &&
args.license === 'cloud' &&
!SELF_HOSTED_BANNERS.includes(args.banner);
const ADD_CARD_DIALOG = { name: /Add Credit Card for Chat Support/i };
export const openAddCreditCard = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
const canvas = within(canvasElement);
if (!offersAddCard(args)) {
await canvas.findByRole(
'button',
{ name: /invite a teammate/i },
untilRendered,
);
await expect(
screen.queryByRole('dialog', ADD_CARD_DIALOG),
).not.toBeInTheDocument();
return;
}
await userEvent.click(
await canvas.findByRole(
'button',
{ name: /contact support/i },
untilRendered,
),
);
// antd portals the modal out of the story root.
await screen.findByRole('dialog', ADD_CARD_DIALOG, untilRendered);
};

View File

@@ -1,5 +1,4 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { screen, userEvent } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -36,20 +35,3 @@ export const ExpiredLink: Story = {
// The deliberate 410 is the state under test.
parameters: { allowConsoleErrors: true },
};
/** The mismatch callout, after the two password fields disagree and blur. */
export const PasswordMismatch: Story = {
play: async ({ canvasElement }): Promise<void> => {
const password = await screen.findByTestId('password', undefined, {
timeout: 15000,
});
const confirm = await screen.findByPlaceholderText(
/confirm your new password/i,
);
await userEvent.type(password, 'password123');
await userEvent.type(confirm, 'password456');
await userEvent.click(canvasElement);
await screen.findByText(/passwords don't match/i);
},
};

View File

@@ -46,3 +46,8 @@ export const Default: Story = {};
export const PaginatedOperations: Story = {
args: { operations: 120 },
};
/** The documented 2,500-operation threshold is exceeded by one entry point. */
export const ThresholdWarning: Story = {
args: { operations: 2501 },
};

View File

@@ -210,8 +210,30 @@ export const openMember = async (
await userEvent.click(cell.closest('tr') as HTMLElement);
};
export const openInviteForm = async (
/**
* Selects `viewer` in the roles dropdown at `index`. The option's content ignores
* pointer events, so the click goes to the option around it. A click on the
* label closes the dropdown, where Escape would close the dialog too.
*/
const pickRole = async (index: number): Promise<void> => {
const comboboxes = await screen.findAllByRole(
'combobox',
undefined,
untilLoaded,
);
await userEvent.click(comboboxes[index]);
const options = await screen.findAllByText('viewer', undefined, untilLoaded);
await userEvent.click(
options[options.length - 1].closest('.ant-select-item-option') as HTMLElement,
);
await userEvent.click(await screen.findByText('Email address'));
};
export const sendInvites = async (
canvasElement: HTMLElement,
emails: string[],
): Promise<void> => {
await clickWhenEnabled(
await within(canvasElement).findByText(
@@ -220,49 +242,6 @@ export const openInviteForm = async (
untilLoaded,
),
);
// The form opens with a row per seat, each carrying its own email field.
await screen.findAllByTestId(/^invite-email-/, undefined, untilLoaded);
};
/** A click on the label closes the dropdown, where Escape would close the dialog too. */
export const closeRoles = async (): Promise<void> => {
await userEvent.click(await screen.findByText('Email address'));
};
/**
* Picks `role` in the open roles dropdown. The option's content ignores pointer
* events, so the click goes to the option around it.
*/
export const pickOpenRole = async (role: string): Promise<void> => {
const options = await screen.findAllByText(role, undefined, untilLoaded);
await userEvent.click(
options[options.length - 1].closest('.ant-select-item-option') as HTMLElement,
);
};
/** Opens the roles dropdown of the invite row at `index`. */
export const openInviteRoleDropdown = async (index: number): Promise<void> => {
const comboboxes = await screen.findAllByRole(
'combobox',
undefined,
untilLoaded,
);
await userEvent.click(comboboxes[index]);
};
const pickRole = async (index: number): Promise<void> => {
await openInviteRoleDropdown(index);
await pickOpenRole('viewer');
await closeRoles();
};
export const sendInvites = async (
canvasElement: HTMLElement,
emails: string[],
): Promise<void> => {
await openInviteForm(canvasElement);
const fields = await screen.findAllByTestId(
/^invite-email-/,
undefined,

View File

@@ -15,13 +15,11 @@ import {
openEditMember,
openFilterMenu,
openInviteForm,
openInviteRoles,
openPendingMember,
openRoleDropdown,
revokeInviteToast,
saveMemberName,
searchNoResults,
selectInviteRoles,
sendInvitesToast,
sendPartialInvitesToast,
} from './__story_mockdata__/members.play';
@@ -131,16 +129,6 @@ export const InviteMembers: Story = {
play: openInviteForm,
};
/** The invite form with the first row's roles dropdown open. */
export const InviteRolesOpen: Story = {
play: openInviteRoles,
};
/** The invite form after three roles were picked on the first row. */
export const InviteRolesSelected: Story = {
play: selectInviteRoles,
};
/**
* Invites sent to every address: the toast confirming it. Set Sending invites
* to `error` or `loading` to see the form instead.

View File

@@ -9,13 +9,10 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
clickWhenEnabled,
closeRoles,
MEMBERS_PAGE_SIZE,
membersMocks,
openInviteRoleDropdown,
openMember,
openResetLink,
pickOpenRole,
sendInvites,
untilLoaded,
} from '../Members.stories.mocks';
@@ -165,33 +162,6 @@ export const openInviteForm = async ({
await screen.findAllByTestId(/^invite-email-/, undefined, untilLoaded);
};
export const openInviteRoles = async (context: PlayContext): Promise<void> => {
await openInviteForm(context);
await openInviteRoleDropdown(0);
await screen.findAllByText('viewer', undefined, untilLoaded);
};
export const selectInviteRoles = async (
context: PlayContext,
): Promise<void> => {
await openInviteForm(context);
await openInviteRoleDropdown(0);
for (const role of ['viewer', 'editor', 'oncall-responder']) {
await pickOpenRole(role);
}
await closeRoles();
// The open list titles its options too, so the check is scoped to the selected tags.
await waitFor(
() =>
expect(
document.querySelector(
'.ant-select-selection-item[title="oncall-responder"]',
),
).toBeVisible(),
untilLoaded,
);
};
export const sendInvitesToast = async ({
canvasElement,
args,

View File

@@ -1,20 +1,10 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { singleSignOnMocks } from './SingleSignOn.stories.mocks';
import {
deleteDomain,
expandAttributeMapping,
expandRoleMappings,
openAddDomain,
openConfigureDomain,
openDeleteDomain,
openProviderSelector,
submitEmptyProvider,
updateDisplayName,
} from './__story_mockdata__/singleSignOn.play';
import SettingsPage from '../../Settings';
@@ -40,6 +30,23 @@ export default meta;
type Story = StoryObj<SingleSignOnArgs>;
/** The table fetches before it renders a row, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** Row actions repeat per domain, so a story that opens one takes the first. */
const clickFirst = async (
canvasElement: HTMLElement,
testId: string,
): Promise<void> => {
const [action] = await within(canvasElement).findAllByTestId(
testId,
undefined,
untilLoaded,
);
await userEvent.click(action);
};
/**
* The org's display name and the email domains that sign in through an identity
* provider, with whether each one is allowed to fall back to a password.
@@ -68,46 +75,88 @@ export const SsoNotEnforced: Story = {
/** The form behind a domain's provider: what SigNoz sends the IdP and reads back. */
export const ConfigureDomain: Story = {
play: openConfigureDomain,
play: async ({ canvasElement }): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-configure');
await screen.findByText(/attribute mapping/i, undefined, untilLoaded);
},
};
/** Adding a domain: the provider chosen first decides the rest of the form. */
export const AddDomain: Story = {
play: openAddDomain,
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'auth-domain-add',
undefined,
untilLoaded,
),
);
},
};
/** Interaction: adding a domain opens the real provider selector. */
export const ProviderSelectorOpen: Story = {
play: openProviderSelector,
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'auth-domain-add',
undefined,
untilLoaded,
),
);
await screen.findByText(
/configure authentication method/i,
undefined,
untilLoaded,
);
},
};
/** Interaction: advanced role mappings expand from a configured identity provider. */
export const RoleMappingsExpanded: Story = {
play: expandRoleMappings,
};
/**
* Interaction: the SAML attribute mapping open on a configured domain. Set
* Identity provider to `oidc` for its claim mapping; Google has neither.
*/
export const AttributeMappingExpanded: Story = {
play: expandAttributeMapping,
};
/** Interaction: the OIDC claim mapping open on a configured domain. */
export const ClaimMappingExpanded: Story = {
args: { provider: 'oidc' },
play: expandAttributeMapping,
play: async ({ canvasElement }): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-configure');
await userEvent.click(
await screen.findByTestId('role-mapping-header', undefined, untilLoaded),
);
await screen.findByText(/group to role mappings/i, undefined, untilLoaded);
},
};
/** Validation: submitting a new provider without required fields leaves form errors visible. */
export const CreateDomainValidation: Story = {
play: submitEmptyProvider,
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'auth-domain-add',
undefined,
untilLoaded,
),
);
await userEvent.click(
await screen.findByTestId(
'authn-provider-configure-google',
undefined,
untilLoaded,
),
);
await userEvent.click(
await screen.findByTestId('auth-domain-save', undefined, untilLoaded),
);
await screen.findByText(/domain is required/i, undefined, untilLoaded);
},
};
/** What removing a domain warns about before its members lose SSO. */
export const DeleteDomain: Story = {
play: openDeleteDomain,
play: async ({ canvasElement }): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-delete');
await screen.findByTestId(
'auth-domain-delete-confirm',
undefined,
untilLoaded,
);
},
};
/**
@@ -115,7 +164,22 @@ export const DeleteDomain: Story = {
* update to `error` or `loading` to see the modal instead.
*/
export const DisplayNameUpdatedToast: Story = {
play: updateDisplayName,
play: async ({ canvasElement, args }): Promise<void> => {
const input = await within(canvasElement).findByLabelText(
/display name/i,
undefined,
untilLoaded,
);
await userEvent.clear(input);
await userEvent.type(input, 'Night Watch');
await userEvent.click(
await within(canvasElement).findByRole('button', { name: /^submit$/i }),
);
if (args.displayNameUpdate === 'success') {
await waitFor(() => expect(screen.getByText(/^success$/i)).toBeVisible());
}
},
};
/**
@@ -123,5 +187,19 @@ export const DisplayNameUpdatedToast: Story = {
* `loading` to see the modal instead.
*/
export const DomainDeletedToast: Story = {
play: deleteDomain,
play: async ({ canvasElement, args }): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-delete');
await userEvent.click(
await screen.findByTestId(
'auth-domain-delete-confirm',
undefined,
untilLoaded,
),
);
if (args.domainDelete === 'success') {
await waitFor(() =>
expect(screen.getByText(/domain deleted successfully/i)).toBeVisible(),
);
}
},
};

View File

@@ -1,161 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { singleSignOnMocks } from '../SingleSignOn.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof singleSignOnMocks>;
}
/** The table fetches before it renders a row, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** Row actions repeat per domain, so a story that opens one takes the first. */
const clickFirst = async (
canvasElement: HTMLElement,
testId: string,
): Promise<void> => {
const [action] = await within(canvasElement).findAllByTestId(
testId,
undefined,
untilLoaded,
);
await userEvent.click(action);
};
/** Google maps no IdP attributes, so only SAML and OIDC have this section. */
const MAPPING_SECTION = {
saml: { header: /attribute mapping \(advanced\)/i, field: 'email-attribute' },
oidc: { header: /claim mapping \(advanced\)/i, field: 'email-claim' },
google: null,
} as const;
export const openConfigureDomain = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-configure');
await screen.findByText(/role mapping \(advanced\)/i, undefined, untilLoaded);
};
export const openAddDomain = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'auth-domain-add',
undefined,
untilLoaded,
),
);
};
export const openProviderSelector = async (
context: PlayContext,
): Promise<void> => {
await openAddDomain(context);
await screen.findByText(
/configure authentication method/i,
undefined,
untilLoaded,
);
};
export const expandRoleMappings = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-configure');
await userEvent.click(
await screen.findByTestId('role-mapping-header', undefined, untilLoaded),
);
await screen.findByText(/group to role mappings/i, undefined, untilLoaded);
};
export const expandAttributeMapping = async (
context: PlayContext,
): Promise<void> => {
await openConfigureDomain(context);
const section = MAPPING_SECTION[context.args.provider];
if (!section) {
return;
}
await userEvent.click(screen.getByText(section.header));
await waitFor(() =>
expect(document.getElementById(section.field)).toBeVisible(),
);
};
export const submitEmptyProvider = async (
context: PlayContext,
): Promise<void> => {
await openAddDomain(context);
await userEvent.click(
await screen.findByTestId(
'authn-provider-configure-google',
undefined,
untilLoaded,
),
);
await userEvent.click(
await screen.findByTestId('auth-domain-save', undefined, untilLoaded),
);
await screen.findByText(/domain is required/i, undefined, untilLoaded);
};
export const openDeleteDomain = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-delete');
await screen.findByTestId(
'auth-domain-delete-confirm',
undefined,
untilLoaded,
);
};
export const updateDisplayName = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const input = await within(canvasElement).findByLabelText(
/display name/i,
undefined,
untilLoaded,
);
await userEvent.clear(input);
await userEvent.type(input, 'Night Watch');
await userEvent.click(
await within(canvasElement).findByRole('button', { name: /^submit$/i }),
);
if (args.displayNameUpdate === 'success') {
await waitFor(() => expect(screen.getByText(/^success$/i)).toBeVisible());
}
};
export const deleteDomain = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-delete');
await userEvent.click(
await screen.findByTestId(
'auth-domain-delete-confirm',
undefined,
untilLoaded,
),
);
if (args.domainDelete === 'success') {
await waitFor(() =>
expect(screen.getByText(/domain deleted successfully/i)).toBeVisible(),
);
}
};

View File

@@ -100,10 +100,6 @@ export const workspaceMocks = defineStoryMocks({
)
: res(ctx.status(204));
}),
rest.post('http://localhost/api/v1/subscriptions', (_req, res, ctx) =>
res(ctx.status(200), ctx.json({ data: { redirectURL: '' } })),
),
],
config: () => ({ route: ROUTES.SETTINGS }),
});

View File

@@ -1,14 +1,9 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
copyLicenseKey,
openAddCreditCardFromConflict,
openCustomDomainMenu,
updateCustomDomain,
} from './__story_mockdata__/workspace.play';
import { workspaceMocks } from './Workspace.stories.mocks';
import SettingsPage from '../../Settings';
@@ -66,7 +61,16 @@ export const NoColdStorage: Story = {
* of them is the active one.
*/
export const CustomDomainMenu: Story = {
play: openCustomDomainMenu,
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'custom-domain-menu-trigger',
{},
{ timeout: 10000 },
),
);
await screen.findByRole('menu');
},
};
/**
@@ -75,21 +79,38 @@ export const CustomDomainMenu: Story = {
* instead.
*/
export const CustomDomainUpdatedToast: Story = {
play: updateCustomDomain,
};
/**
* A workspace link change the instance refuses with a 409: the edit modal swaps
* Apply Changes for Contact Support, which on a cloud trial without a card opens
* the Add Credit Card modal.
*/
export const CustomDomainConflictAddCard: Story = {
args: { domainUpdate: 'error', support: 'add-card' },
parameters: { allowConsoleErrors: true },
play: openAddCreditCardFromConflict,
play: async ({ canvasElement, args }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /edit workspace link/i },
{ timeout: 10000 },
),
);
const input = await screen.findByRole('textbox');
await userEvent.clear(input);
await userEvent.type(input, 'watchers');
await userEvent.click(
await screen.findByRole('button', { name: /apply changes/i }),
);
if (args.domainUpdate === 'success') {
await waitFor(() =>
expect(screen.getByText(/workspace url is being updated/i)).toBeVisible(),
);
}
},
};
/** The license key copied: the toast confirming it. */
export const LicenseKeyCopiedToast: Story = {
play: copyLicenseKey,
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'license-key-row-copy-btn',
{},
{ timeout: 10000 },
),
);
await screen.findByText(/license key copied to clipboard/i);
},
};

View File

@@ -1,109 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { USER_ROLES } from 'types/roles';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { accessFor } from '@/storybook/access/access';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { workspaceMocks } from '../Workspace.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof workspaceMocks>;
}
const untilLoaded = { timeout: 10000 };
/** The domain card only renders for an admin on cloud. */
const canEditDomain = ({ args }: Pick<PlayContext, 'args'>): boolean =>
args.license === 'cloud' &&
accessFor(args.access, args.permissions, args.revoked).legacyRole ===
USER_ROLES.ADMIN;
const submitNewSubdomain = async (
canvasElement: HTMLElement,
): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /edit workspace link/i },
untilLoaded,
),
);
const input = await screen.findByRole('textbox');
await userEvent.clear(input);
await userEvent.type(input, 'watchers');
await userEvent.click(
await screen.findByRole('button', { name: /apply changes/i }),
);
};
export const openCustomDomainMenu = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'custom-domain-menu-trigger',
undefined,
untilLoaded,
),
);
await screen.findByRole('menu');
};
export const updateCustomDomain = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
await submitNewSubdomain(canvasElement);
if (args.domainUpdate === 'success') {
await waitFor(() =>
expect(screen.getByText(/workspace url is being updated/i)).toBeVisible(),
);
}
};
export const copyLicenseKey = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'license-key-row-copy-btn',
undefined,
untilLoaded,
),
);
await screen.findByText(/license key copied to clipboard/i);
};
export const openAddCreditCardFromConflict = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canEditDomain({ args })) {
return;
}
await submitNewSubdomain(canvasElement);
if (args.domainUpdate !== 'error') {
return;
}
await userEvent.click(
await screen.findByRole('button', { name: /contact support/i }, untilLoaded),
);
// Only a plan without premium support is offered the modal over the chat widget.
if (args.support === 'add-card') {
await screen.findByRole(
'dialog',
{ name: /Add Credit Card for Chat Support/i },
untilLoaded,
);
}
};

View File

@@ -32,8 +32,6 @@ import {
timeSeriesPoints,
} from '@/storybook/msw/__story_mockdata__/queryRange';
import { traceFunnelsResponse } from '../../TracesModulePage/stories/__story_mockdata__/traces';
import { TraceDetailsTab } from '../constants';
import { SpanDetailVariant } from '../SpanDetailsPanel/constants';
import {
focusSpanIndex,
@@ -48,7 +46,6 @@ import {
traceDetailFieldValues,
traceFlamegraphResponse,
traceSummaryResponse,
traceThreadResponse,
TRACE_SCENARIOS,
type TraceScenario,
traceWaterfallResponse,
@@ -63,8 +60,6 @@ const EXPORT_STATES = ['success', 'loading', 'error'] as const;
type ExportState = (typeof EXPORT_STATES)[number];
const TABS = [TraceDetailsTab.Overview, TraceDetailsTab.Thread] as const;
const PANEL_POSITIONS = [
SpanDetailVariant.DOCKED_RIGHT,
SpanDetailVariant.DOCKED,
@@ -130,13 +125,6 @@ export const traceDetailsMocks = defineStoryMocks({
'Marks the payment and shipping spans as errored, each with an exception event, which is what the error counts and the red bars read.',
value: true,
}),
tab: choiceControl<TraceDetailsTab>('Tab', {
group: TRACE,
description:
'The tab the page opens on. `thread` lists the LLM calls as a conversation, and shows its no-AI-spans state outside the `ai` scenario.',
options: TABS,
value: TraceDetailsTab.Overview,
}),
missingSpans: toggleControl('Missing spans', {
group: TRACE,
description:
@@ -219,11 +207,6 @@ export const traceDetailsMocks = defineStoryMocks({
),
),
rest.get(
'http://localhost/api/v1/traces/:traceId/thread',
response.json(() => traceThreadResponse(trace)),
),
rest.post(
'http://localhost/api/v3/traces/:traceId/flamegraph',
response.json(() => traceFlamegraphResponse(trace)),
@@ -238,11 +221,6 @@ export const traceDetailsMocks = defineStoryMocks({
}),
),
rest.get(
'http://localhost/api/v1/trace-funnels/list',
response.json(() => traceFunnelsResponse(3)),
),
rest.post(
'http://localhost/api/v1/span_percentile',
response.json(spanPercentilesResponse),
@@ -328,28 +306,11 @@ export const traceDetailsMocks = defineStoryMocks({
),
];
},
config: (values) => {
const params = new URLSearchParams();
if (values.tab !== TraceDetailsTab.Overview) {
params.set('tab', values.tab);
}
if (values.spanPanel) {
params.set(
'spanId',
spanIdAt(focusSpanIndex(values.scenario, values.spans)),
);
}
const search = params.toString();
return {
route: search
? `/trace/${STORY_TRACE_ID}?${search}`
: `/trace/${STORY_TRACE_ID}`,
};
},
config: (values) => ({
route: values.spanPanel
? `/trace/${STORY_TRACE_ID}?spanId=${spanIdAt(focusSpanIndex(values.scenario, values.spans))}`
: `/trace/${STORY_TRACE_ID}`,
}),
effect: (values) => {
set(LOCALSTORAGE.TRACE_DETAILS_SPAN_DETAILS_POSITION, values.panelPosition);
},

View File

@@ -24,7 +24,6 @@ import {
traceDetailsMocks,
untilLoaded,
} from './TraceDetailsV3.stories.mocks';
import { TraceDetailsTab } from '../constants';
import TraceDetailsV3 from '../index';
type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
@@ -120,22 +119,6 @@ export const AiTrace: Story = {
},
};
/**
* The same agent run on the Thread tab: each LLM call's messages in order, with
* the tool call and its response, the model's reasoning folded into a thinking
* block, and the span panel open on the Claude call.
*/
export const AiThread: Story = {
args: { scenario: 'ai', spans: AI_SPANS, tab: TraceDetailsTab.Thread },
play: async ({ canvasElement }): Promise<void> => {
await within(canvasElement).findAllByText(
/Let me check the upgrade notes/,
undefined,
untilLoaded,
);
},
};
/**
* Turns on Highlight errors, which writes `has_error = true` into the filter and
* expands the bar to show it.
@@ -265,60 +248,6 @@ export const SpanPercentileOpen: Story = {
},
};
/** The analytics panel the header toggle opens. */
export const AnalyticsOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Analytics' },
untilLoaded,
),
);
await screen.findByTestId('trace-analytics-panel', undefined, untilLoaded);
},
};
/** The download progress panel, held open by an export that never answers. */
export const TraceDownload: Story = {
args: { exportState: 'loading' },
play: async ({ canvasElement }): Promise<void> => {
await startDownload(canvasElement);
await screen.findByTestId('trace-download-panel', undefined, untilLoaded);
},
};
const openAddSpanToFunnel = async (
canvasElement: HTMLElement,
): Promise<void> => {
const [button] = await within(canvasElement).findAllByTestId(
'span-add-to-funnel-btn',
undefined,
untilLoaded,
);
await fireEvent.click(button);
await screen.findByText('Add span to funnel', undefined, untilLoaded);
};
/** The funnel picker a span row's add-to-funnel action opens. */
export const AddSpanToFunnel: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openAddSpanToFunnel(canvasElement);
},
};
/** The name field behind "Create new funnel" in that picker. */
export const AddSpanToFunnelCreateStep: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openAddSpanToFunnel(canvasElement);
await userEvent.click(
await screen.findByRole('button', { name: /create new funnel/i }),
);
await screen.findByTestId('create-funnel-name-input');
},
};
/** The span has no logs of its own but its trace does, so the Logs tab points to the trace's. */
export const SpanPanelTraceOnlyLogs: Story = {
args: { traceOnlyLogs: true },

View File

@@ -1,39 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { TraceDetailsTab } from '../../constants';
import {
type traceDetailsMocks,
untilLoaded,
} from '../TraceDetailsV3.stories.mocks';
type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
interface PlayContext {
args: Pick<TraceDetailsArgs, 'missingSpans' | 'tab' | 'dataState'>;
}
/** The header reads the flag off the summary, and only the overview tab shows it. */
export const showsMissingSpansBanner = async ({
args,
}: PlayContext): Promise<void> => {
if (
!args.missingSpans ||
args.tab !== TraceDetailsTab.Overview ||
args.dataState !== 'loaded'
) {
return;
}
await screen.findByText(
/this trace has missing spans/i,
undefined,
untilLoaded,
);
};

View File

@@ -4,16 +4,12 @@
*/
import type {
AiobservabilitytypesInputMessagesDTO,
AiobservabilitytypesOutputMessagesDTO,
GetFlamegraph200,
GetTraceAggregations200,
GetTraceSummary200,
GetTraceThread200,
GetWaterfallV4200,
SpantypesFlamegraphSpanDTO,
SpantypesSpanAggregationDTO,
SpantypesThreadSpanDTO,
SpantypesWaterfallSpanDTO,
} from 'api/generated/services/sigNoz.schemas';
import { SpantypesSpanAggregationTypeDTO } from 'api/generated/services/sigNoz.schemas';
@@ -32,26 +28,8 @@ interface SpanTemplate {
/** `response_status_code`; failing spans default to 503, the rest to 200. */
statusCode?: string;
attributes: Record<string, string | number | boolean>;
/** The LLM call's messages. Only spans that carry them are in the thread. */
messages?: {
input: AiobservabilitytypesInputMessagesDTO;
output: AiobservabilitytypesOutputMessagesDTO;
};
}
const SUPPORT_SYSTEM_PROMPT =
'You are the SigNoz support agent. Answer from the docs, cite the page you used, and open a ticket only when the docs do not cover the problem.';
const SUPPORT_QUESTION =
'My checkout traces stopped showing up after I upgraded the collector to 0.110. What changed?';
const SEARCH_DOCS_CALL = {
type: 'tool_call',
id: 'call_search_docs_1',
name: 'search_docs',
arguments: { query: 'otel collector 0.110 breaking changes traces', limit: 3 },
};
/** Walked in order, so the tree keeps the same services at the same depths. */
const SPAN_TEMPLATES: SpanTemplate[] = [
{
@@ -204,28 +182,6 @@ const AI_TEMPLATES: SpanTemplate[] = [
'gen_ai.usage.cache_creation.input_tokens': 0,
'signoz.gen_ai.usage.tokens.cost': 0.00566,
},
messages: {
input: [
{
role: 'system',
parts: [{ type: 'text', content: SUPPORT_SYSTEM_PROMPT }],
},
{ role: 'user', parts: [{ type: 'text', content: SUPPORT_QUESTION }] },
],
output: [
{
role: 'assistant',
finish_reason: 'tool_call',
parts: [
{
type: 'text',
content: 'Let me check the upgrade notes for that release.',
},
SEARCH_DOCS_CALL,
],
},
],
},
},
{
service: 'support-agent',
@@ -246,52 +202,6 @@ const AI_TEMPLATES: SpanTemplate[] = [
'gen_ai.usage.cache_creation.input_tokens': 1300,
'signoz.gen_ai.usage.tokens.cost': 0.01853,
},
messages: {
input: [
{
role: 'system',
parts: [{ type: 'text', content: SUPPORT_SYSTEM_PROMPT }],
},
{ role: 'user', parts: [{ type: 'text', content: SUPPORT_QUESTION }] },
{ role: 'assistant', parts: [SEARCH_DOCS_CALL] },
{
role: 'tool',
parts: [
{
type: 'tool_call_response',
id: 'call_search_docs_1',
response: {
results: [
{
title: 'Collector 0.110 upgrade notes',
snippet:
'The otlp exporter now sends over gRPC on 4317 by default. Pipelines that pointed it at the HTTP port 4318 must set the endpoint explicitly.',
},
],
},
},
],
},
],
output: [
{
role: 'assistant',
finish_reason: 'stop',
parts: [
{
type: 'reasoning',
content:
'The traces stopped right after the upgrade, and the notes say the otlp exporter changed its default transport. If their exporter still points at 4318, every export now fails against a port that expects HTTP. That fits better than a sampling change, which would thin the traces out rather than stop them.',
},
{
type: 'text',
content:
'Collector 0.110 changed the default transport of the `otlp` exporter to gRPC on port **4317**. If your exporter still points at `:4318`, every export fails and no traces arrive.\n\nSet the endpoint explicitly:\n\n```yaml\nexporters:\n otlp:\n endpoint: ingest.example.signoz.cloud:4317\n```\n\nSource: Collector 0.110 upgrade notes.',
},
],
},
],
},
},
{
service: 'docs-api',
@@ -337,39 +247,6 @@ const AI_TEMPLATES: SpanTemplate[] = [
'gen_ai.usage.reasoning.output_tokens': 1152,
'signoz.gen_ai.usage.tokens.cost': 0.007524,
},
messages: {
input: [
{
role: 'system',
parts: [
{
type: 'text',
content:
'You are the triage agent. Write a one-line summary and a priority for the support queue.',
},
],
},
{ role: 'user', parts: [{ type: 'text', content: SUPPORT_QUESTION }] },
],
output: [
{
role: 'assistant',
finish_reason: 'stop',
parts: [
{
type: 'reasoning',
content:
'No data loss beyond the gap, and the fix is a config change the docs already describe, so this is not urgent.',
},
{
type: 'text',
content:
'Summary: traces stopped after a collector upgrade to 0.110, caused by the otlp exporter default port. Priority: P3.',
},
],
},
],
},
},
];
@@ -549,43 +426,6 @@ const waterfallSpan = (span: BuiltSpan): SpantypesWaterfallSpanDTO => ({
trace_state: '',
});
const threadSpan = (span: BuiltSpan): SpantypesThreadSpanDTO => ({
span_id: span.spanId,
trace_id: STORY_TRACE_ID,
parent_span_id: span.parentSpanId,
time_unix: Math.round(span.startMs),
duration_nano: Math.round(span.durationMs * 1_000_000),
name: span.template.name,
kind_string: span.template.kind,
has_error: span.hasError,
status_code_string: span.hasError ? 'Error' : 'Ok',
status_message: span.hasError ? 'upstream unavailable' : '',
attributes: span.template.attributes,
resource: resourceOf(span),
events: eventsOf(span) ?? [],
references: [],
formattedInput: span.template.messages?.input ?? [],
formattedOutput: span.template.messages?.output ?? [],
formatterWarnings: [],
});
/**
* The spans with messages, in start order, on one page: no cursors, so the
* list never asks for another. A scenario with no LLM calls answers empty,
* which is the tab's no-AI-spans state.
*/
export const traceThreadResponse = (
options: TraceOptions,
): GetTraceThread200 => ({
status: 'success',
data: {
spans: buildSpans(options)
.filter(({ template }) => template.messages)
.sort((a, b) => a.startMs - b.startMs)
.map(threadSpan),
},
});
/**
* `totalSpansCount` equals what the response carries, which is what puts the
* waterfall in its all-loaded mode: every parent expands and no further window

View File

@@ -7,9 +7,7 @@ import { type TracesArgs, tracesMocks } from './TracesModulePage.stories.mocks';
import {
dirtyQuickFiltersSettings,
loadNextListPage,
openCreateFunnel,
openQuickFiltersSettings,
openRenameFunnel,
showRootSpansNextPage,
suggestBooleanValues,
suggestFilterKeys,
@@ -84,18 +82,6 @@ export const Funnels: Story = {
args: { tab: 'funnels' },
};
/** The name field for a funnel that does not exist yet. */
export const CreateFunnel: Story = {
args: { tab: 'funnels' },
play: openCreateFunnel,
};
/** The rename field for a funnel already on the list. */
export const RenameFunnel: Story = {
args: { tab: 'funnels' },
play: openRenameFunnel,
};
/**
* A fresh workspace: nothing ingested in the window and no quick filters
* configured yet, so the table and the filter panel both show their empty
@@ -132,6 +118,17 @@ export const QuickFiltersSettingsDirty: Story = {
play: dirtyQuickFiltersSettings,
};
/**
* The same panel with a banner above the shell. The banner takes 48px off the
* layout, so this is the case where the footer used to be pushed off screen:
* the panel is sized from the filters pane rather than the viewport, which
* keeps Save changes reachable.
*/
export const QuickFiltersSettingsWithBanner: Story = {
args: { banner: 'trial-expiry' },
play: dirtyQuickFiltersSettings,
};
/** The filter focused before anything is typed: span and resource keys together. */
export const FilterKeySuggestions: Story = {
play: suggestFilterKeys,

View File

@@ -1,153 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
interface MountContext {
mount: () => Promise<unknown>;
}
/** The page fetches before it renders its rows, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
// The quick filters list the same span name, so the row is found by its test
// id; the table renders its rows a few at a time, so it waits for this one.
const findOrdersRow = (): Promise<HTMLElement> =>
waitFor(async (): Promise<HTMLElement> => {
const match = screen
.getAllByTestId(/^traces-table-row-/)
.find((candidate) => candidate.textContent?.includes('POST /api/orders'));
await expect(match).toBeDefined();
return match as HTMLElement;
}, untilLoaded);
const openDrawer = async (): Promise<HTMLElement> => {
const row = await findOrdersRow();
await userEvent.click(within(row).getByText('POST /api/orders'));
return screen.findByTestId('span-details-drawer');
};
const openLogsTab = async (): Promise<HTMLElement> => {
const drawer = await openDrawer();
await userEvent.click(within(drawer).getByRole('tab', { name: /Logs/ }));
return drawer;
};
export const showsSpanDetails = async (): Promise<void> => {
const drawer = await openDrawer();
await expect(
await within(drawer).findByText(/of total exec time/, undefined, untilLoaded),
).toBeVisible();
};
export const openSpanDetails = async ({
mount,
}: MountContext): Promise<void> => {
await mount();
await showsSpanDetails();
};
export const hoverOrdersRow = async ({
mount,
}: MountContext): Promise<void> => {
await mount();
await userEvent.hover(await findOrdersRow());
await expect(await screen.findByTestId('span-row-open-trace')).toBeVisible();
};
export const showsSpanLogs = async ({ mount }: MountContext): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
(
await within(drawer).findAllByText(
/payment provider timed out/,
undefined,
untilLoaded,
)
)[0],
).toBeVisible();
};
export const showsTraceOnlyLogs = async ({
mount,
}: MountContext): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for selected span. View logs for the current trace.',
undefined,
untilLoaded,
),
).toBeVisible();
};
export const showsNoLogs = async ({ mount }: MountContext): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for this trace.',
undefined,
untilLoaded,
),
).toBeVisible();
};
export const showsWithoutTraceSummary = async ({
mount,
}: MountContext): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for this span.',
undefined,
untilLoaded,
),
).toBeVisible();
await expect(
within(drawer).queryByText(/of total exec time/),
).not.toBeInTheDocument();
};
export const showsTraceSummaryLoading = async ({
mount,
}: MountContext): Promise<void> => {
await mount();
await openLogsTab();
await expect(
await screen.findByTestId('open-in-explorer-button'),
).toHaveAttribute('aria-disabled', 'true');
};
export const showsLogsError = async ({
mount,
}: MountContext): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
/Something went wrong/,
undefined,
untilLoaded,
),
).toBeVisible();
};

View File

@@ -189,47 +189,3 @@ export const showFilterSyntaxError = async ({
await showFilterErrors(canvasElement, 'has_error = true AND');
};
export const openCreateFunnel = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.tab !== 'funnels') {
return;
}
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /new funnel/i },
untilLoaded,
),
);
await screen.findByRole('dialog', { name: /create new funnel/i });
};
/** Row actions exist only once the list holds a funnel. */
export const openRenameFunnel = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.tab !== 'funnels' || args.funnels === 0) {
return;
}
const action = await waitFor(() => {
const found = canvasElement.querySelector<HTMLElement>(
'.funnel-item__action-icon',
);
if (!found) {
throw new Error('Funnel row actions are not rendered');
}
return found;
}, untilLoaded);
await userEvent.click(action);
await userEvent.click(await screen.findByRole('button', { name: 'Rename' }));
await screen.findByRole('dialog', { name: /rename funnel/i });
};

View File

@@ -1,18 +1,10 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { tracesMocks } from '../TracesModulePage.stories.mocks';
import {
hoverOrdersRow,
openSpanDetails,
showsLogsError,
showsNoLogs,
showsSpanLogs,
showsTraceOnlyLogs,
showsTraceSummaryLoading,
showsWithoutTraceSummary,
} from '../__story_mockdata__/spanDrawer.play';
import TracesModulePage from '../../TracesModulePage';
@@ -39,12 +31,55 @@ export default meta;
type Story = StoryObj<TracesArgs>;
/** The page fetches before it renders its rows, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
// The quick filters list the same span name, so the row is found by its test
// id; the table renders its rows a few at a time, so it waits for this one.
const findOrdersRow = (): Promise<HTMLElement> =>
waitFor((): HTMLElement => {
const match = screen
.getAllByTestId(/^traces-table-row-/)
.find((candidate) => candidate.textContent?.includes('POST /api/orders'));
expect(match).toBeDefined();
return match as HTMLElement;
}, untilLoaded);
const openDrawer = async (): Promise<HTMLElement> => {
const row = await findOrdersRow();
await userEvent.click(within(row).getByText('POST /api/orders'));
return screen.findByTestId('span-details-drawer');
};
const openLogsTab = async (): Promise<HTMLElement> => {
const drawer = await openDrawer();
await userEvent.click(within(drawer).getByRole('tab', { name: /Logs/ }));
return drawer;
};
/**
* The drawer on a failing span: its summary with % exec time, attributes, the
* exception event and a linked span, with up and down stepping through the page.
*/
export const Default: Story = {
play: openSpanDetails,
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openDrawer();
await expect(
await within(drawer).findByText(
/of total exec time/,
undefined,
untilLoaded,
),
).toBeVisible();
},
};
/**
@@ -52,25 +87,65 @@ export const Default: Story = {
* tab, without opening the drawer.
*/
export const OpenTraceIcon: Story = {
play: hoverOrdersRow,
play: async ({ mount }): Promise<void> => {
await mount();
await userEvent.hover(await findOrdersRow());
await expect(await screen.findByTestId('span-row-open-trace')).toBeVisible();
},
};
/** The Logs tab with the span's logs, between the logs just before and after them. */
export const Logs: Story = {
args: { spanLogs: 'span' },
play: showsSpanLogs,
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
(
await within(drawer).findAllByText(
/payment provider timed out/,
undefined,
untilLoaded,
)
)[0],
).toBeVisible();
},
};
/** The span has no logs of its own but its trace does, so the tab points to the trace's. */
export const TraceOnlyLogs: Story = {
args: { spanLogs: 'trace only' },
play: showsTraceOnlyLogs,
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for selected span. View logs for the current trace.',
undefined,
untilLoaded,
),
).toBeVisible();
},
};
/** Neither the span nor its trace has logs. */
export const NoLogs: Story = {
args: { spanLogs: 'none' },
play: showsNoLogs,
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for this trace.',
undefined,
untilLoaded,
),
).toBeVisible();
},
};
/**
@@ -81,13 +156,34 @@ export const WithoutTraceSummary: Story = {
args: { traceSummary: 'not found', spanLogs: 'none' },
// The deliberate 404 is the state under test.
parameters: { allowConsoleErrors: true },
play: showsWithoutTraceSummary,
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for this span.',
undefined,
untilLoaded,
),
).toBeVisible();
await expect(
within(drawer).queryByText(/of total exec time/),
).not.toBeInTheDocument();
},
};
/** The trace summary never answers: the Logs tab waits and its explorer link is off. */
export const TraceSummaryLoading: Story = {
args: { traceSummary: 'loading' },
play: showsTraceSummaryLoading,
play: async ({ mount }): Promise<void> => {
await mount();
await openLogsTab();
await expect(
await screen.findByTestId('open-in-explorer-button'),
).toHaveAttribute('aria-disabled', 'true');
},
};
/** The log queries fail while the rest of the drawer renders. */
@@ -95,5 +191,16 @@ export const LogsError: Story = {
args: { spanLogs: 'error' },
// The deliberate 500 is the state under test.
parameters: { allowConsoleErrors: true },
play: showsLogsError,
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
/Something went wrong/,
undefined,
untilLoaded,
),
).toBeVisible();
},
};

View File

@@ -1,153 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { GlobalMockArgs } from '@/storybook/globals';
import { renderAtRoute } from '@/storybook/renderAtRoute';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import CreateAlertPage from 'pages/CreateAlert';
import { enableRoutingPolicies } from 'pages/CreateAlert/stories/__story_mockdata__/createAlert.play';
import { createAlertMocks } from 'pages/CreateAlert/stories/CreateAlert.stories.mocks';
import MeterExplorerPage from 'pages/MeterExplorer/MeterExplorerPage';
import { meterMocks } from 'pages/MeterExplorer/stories/MeterExplorer.stories.mocks';
import MetricsExplorerPage from 'pages/MetricsExplorer/MetricsExplorerPage';
import { metricsMocks } from 'pages/MetricsExplorer/stories/MetricsExplorerPage.stories.mocks';
import ServiceTopLevelOperations from 'pages/ServiceTopLevelOperations';
import { serviceTopLevelOperationsMocks } from 'pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.mocks';
import SettingsPage from 'pages/Settings/Settings';
import { billingMocks } from 'pages/Settings/Billing/stories/Billing.stories.mocks';
import TraceDetailsV3 from 'pages/TraceDetailsV3';
import { showsMissingSpansBanner } from 'pages/TraceDetailsV3/stories/__story_mockdata__/traceDetails.play';
import { traceDetailsMocks } from 'pages/TraceDetailsV3/stories/TraceDetailsV3.stories.mocks';
import {
showsCancelSubscription,
showsClickHouseInfo,
showsMeterBeforeLaunch,
showsMeterBillingNotice,
showsMeterShortWindow,
showsPendingActivation,
showsTopLevelOperationsThreshold,
} from './__story_mockdata__/pageBanners.play';
type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
type MetricsArgs = PageStoryArgs<typeof metricsMocks>;
type BillingArgs = PageStoryArgs<typeof billingMocks>;
type CreateAlertArgs = PageStoryArgs<typeof createAlertMocks>;
type MeterArgs = PageStoryArgs<typeof meterMocks>;
type TopLevelOperationsArgs = PageStoryArgs<
typeof serviceTopLevelOperationsMocks
>;
const traceDetails = storyMocks(traceDetailsMocks, { layout: 'app' });
const metrics = storyMocks(metricsMocks, { layout: 'app' });
const billing = storyMocks(billingMocks, { layout: 'app' });
const createAlert = storyMocks(createAlertMocks, { layout: 'app' });
const meter = storyMocks(meterMocks, { layout: 'app' });
const topLevelOperations = storyMocks(serviceTopLevelOperationsMocks, {
layout: 'app',
});
/**
* Every banner and notice a page renders inside its own content, one per story on
* the page that shows it. The shell's own banners are under Shell.
*
* Route: each story uses its page's own.
*/
const meta = {
title: 'Foundations/Banners/Page',
tags: ['play'],
} satisfies Meta<GlobalMockArgs>;
export default meta;
/** "This trace has missing spans": the backend never received some of the trace's spans. */
export const MissingSpans: StoryObj<TraceDetailsArgs> = {
...traceDetails,
args: { ...traceDetails.args, missingSpans: true },
render: renderAtRoute(ROUTES.TRACE_DETAIL, TraceDetailsV3),
play: showsMissingSpansBanner,
};
/**
* "Volume changes take effect within about 5 minutes": the metric's reduction
* rule was saved moments ago and is not active yet.
*/
export const PendingActivation: StoryObj<MetricsArgs> = {
...metrics,
args: { ...metrics.args, drawer: 'details', drawerMetric: 'histogram' },
render: () => <MetricsExplorerPage />,
play: showsPendingActivation,
};
/** "Cancel your subscription": at the foot of Billing on an activated cloud workspace. */
export const CancelSubscription: StoryObj<BillingArgs> = {
...billing,
// The banner sits below the fold of the default 1200px viewport.
parameters: { ...billing.parameters, sbshot: { viewport: { height: 1400 } } },
render: () => <SettingsPage />,
play: showsCancelSubscription,
};
/**
* "Use Routing Policies for dynamic routing": under the thresholds of every rule
* type, here switched on, which takes the channel picker off the condition.
*/
export const RoutingPolicies: StoryObj<CreateAlertArgs> = {
...createAlert,
args: { ...createAlert.args, alertMode: 'anomaly' },
render: () => <CreateAlertPage />,
play: enableRoutingPolicies,
};
/** "Learn to write faster, optimized queries": above the ClickHouse query editor. */
export const ClickHouseQuery: StoryObj<CreateAlertArgs> = {
...createAlert,
args: { ...createAlert.args, alertMode: 'logs' },
render: () => <CreateAlertPage />,
play: showsClickHouseInfo,
};
/** "Billing is calculated in UTC": above the breakdown until it is dismissed. */
export const MeterBillingNotice: StoryObj<MeterArgs> = {
...meter,
render: () => <MeterExplorerPage />,
play: showsMeterBillingNotice,
};
/** The same notice closed, which the app remembers across visits. */
export const MeterBillingNoticeDismissed: StoryObj<MeterArgs> = {
...meter,
args: { ...meter.args, billingNotice: false },
render: () => <MeterExplorerPage />,
play: showsMeterBillingNotice,
};
/** "Meter module data is accurate only from 22nd August 2025": a cloud window from the beta phase. */
export const MeterBeforeLaunch: StoryObj<MeterArgs> = {
...meter,
args: { ...meter.args, timeRange: 'august-2025' },
render: () => <MeterExplorerPage />,
play: showsMeterBeforeLaunch,
};
/** "Meter metrics data is aggregated over 1 hour period": a window shorter than an hour. */
export const MeterShortWindow: StoryObj<MeterArgs> = {
...meter,
args: { ...meter.args, timeRange: 'last-30-minutes' },
render: () => <MeterExplorerPage />,
play: showsMeterShortWindow,
};
/**
* "SigNoz calculates the RED metrics using the entry-point spans": above the list
* of top level operations.
*/
export const TopLevelOperationsThreshold: StoryObj<TopLevelOperationsArgs> = {
...topLevelOperations,
render: renderAtRoute(
ROUTES.SERVICE_TOP_LEVEL_OPERATIONS,
ServiceTopLevelOperations,
),
play: showsTopLevelOperationsThreshold,
};

View File

@@ -1,176 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { renderAtRoute } from '@/storybook/renderAtRoute';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { GlobalMockArgs } from '@/storybook/globals';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
openAddCardModal,
raiseToast,
} from '../__story_mockdata__/bottomStrip.play';
import CreateAlertPage from 'pages/CreateAlert';
import { createAlertMocks } from 'pages/CreateAlert/stories/CreateAlert.stories.mocks';
import DashboardPage from 'pages/DashboardPage/DashboardPage';
import PanelEditorPage from 'pages/DashboardPage/PanelEditorPage/PanelEditorPage';
import { panelEditorMocks } from 'pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks';
import { dashboardMocks } from 'pages/DashboardPage/stories/DashboardPage.stories.mocks';
import DashboardsListPage from 'pages/DashboardsListPage/DashboardsListPage';
import { dashboardsListMocks } from 'pages/DashboardsListPage/stories/DashboardsListPage.stories.mocks';
import { openRenameDialog } from 'pages/DashboardsListPage/stories/__story_mockdata__/dashboardsList.play';
import HomePage from 'pages/HomePage/HomePage';
import { homeMocks } from 'pages/HomePage/stories/HomePage.stories.mocks';
import InfrastructureMonitoringPage from 'pages/InfrastructureMonitoring/InfrastructureMonitoringPage';
import { podsMocks } from 'pages/InfrastructureMonitoring/stories/Kubernetes.stories.mocks';
import { openDrawerLogsTab } from 'pages/InfrastructureMonitoring/stories/__story_mockdata__/pods.play';
import LogsModulePage from 'pages/LogsModulePage/LogsModulePage';
import { logsMocks } from 'pages/LogsModulePage/stories/LogsModulePage.stories.mocks';
import { dirtyQuickFiltersSettings as dirtyLogsQuickFilters } from 'pages/LogsModulePage/stories/__story_mockdata__/logs.play';
import MetricsExplorerPage from 'pages/MetricsExplorer/MetricsExplorerPage';
import { metricsMocks } from 'pages/MetricsExplorer/stories/MetricsExplorerPage.stories.mocks';
import TraceDetailsV3 from 'pages/TraceDetailsV3';
import { traceDetailsMocks } from 'pages/TraceDetailsV3/stories/TraceDetailsV3.stories.mocks';
import TracesModulePage from 'pages/TracesModulePage/TracesModulePage';
import { tracesMocks } from 'pages/TracesModulePage/stories/TracesModulePage.stories.mocks';
import { showsSpanDetails } from 'pages/TracesModulePage/stories/__story_mockdata__/spanDrawer.play';
import { dirtyQuickFiltersSettings as dirtyTracesQuickFilters } from 'pages/TracesModulePage/stories/__story_mockdata__/traces.play';
import { withTrialBanner } from './__story_mockdata__/hostBanners.play';
type HomeArgs = PageStoryArgs<typeof homeMocks>;
type CreateAlertArgs = PageStoryArgs<typeof createAlertMocks>;
type DashboardArgs = PageStoryArgs<typeof dashboardMocks>;
type MetricsArgs = PageStoryArgs<typeof metricsMocks>;
type LogsArgs = PageStoryArgs<typeof logsMocks>;
type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
type TracesArgs = PageStoryArgs<typeof tracesMocks>;
type PodsArgs = PageStoryArgs<typeof podsMocks>;
type DashboardsListArgs = PageStoryArgs<typeof dashboardsListMocks>;
type PanelEditorArgs = PageStoryArgs<typeof panelEditorMocks>;
const home = storyMocks(homeMocks, { route: ROUTES.HOME, layout: 'app' });
const createAlert = storyMocks(createAlertMocks, { layout: 'app' });
const dashboard = storyMocks(dashboardMocks, { layout: 'app' });
const metrics = storyMocks(metricsMocks, { layout: 'app' });
const logs = storyMocks(logsMocks, { layout: 'app' });
const traceDetails = storyMocks(traceDetailsMocks, { layout: 'app' });
const traces = storyMocks(tracesMocks, { layout: 'app' });
const pods = storyMocks(podsMocks, { layout: 'app' });
const dashboardsList = storyMocks(dashboardsListMocks, { layout: 'app' });
const panelEditor = storyMocks(panelEditorMocks, { layout: 'app' });
/**
* The trial-expiry banner on every host that pins something to the bottom of the
* shell or opens an overlay, one story per host.
*
* Route: each story uses its host page's own.
*/
const meta = {
title: 'Foundations/Banners/Shell Hosts',
tags: ['play'],
args: { banner: 'trial-expiry' },
} satisfies Meta<GlobalMockArgs>;
export default meta;
/** Home: nothing fixed to the bottom but the strip. */
export const Home: StoryObj<HomeArgs> = {
...home,
render: () => <HomePage />,
play: withTrialBanner(),
};
/** Create alert: the fixed footer with the save and test actions. */
export const AlertsCreate: StoryObj<CreateAlertArgs> = {
...createAlert,
render: () => <CreateAlertPage />,
play: withTrialBanner(),
};
/** A locked dashboard: the lock indicator fixed to the bottom of the grid. */
export const DashboardLocked: StoryObj<DashboardArgs> = {
...dashboard,
args: { ...dashboard.args, locked: true },
render: renderAtRoute(ROUTES.DASHBOARD, DashboardPage),
play: withTrialBanner(),
};
/** Metrics summary: the pagination fixed to the bottom of the list. */
export const MetricsSummary: StoryObj<MetricsArgs> = {
...metrics,
render: () => <MetricsExplorerPage />,
play: withTrialBanner(),
};
/** Logs explorer: the list and the frequency chart under the query builder. */
export const LogsExplorer: StoryObj<LogsArgs> = {
...logs,
render: () => <LogsModulePage />,
play: withTrialBanner(),
};
/** Trace details: the waterfall and the span panel filling the page. */
export const TraceDetails: StoryObj<TraceDetailsArgs> = {
...traceDetails,
render: renderAtRoute(ROUTES.TRACE_DETAIL, TraceDetailsV3),
play: withTrialBanner(),
};
/** Logs quick filters settings: the action footer with an unsaved change. */
export const QuickFiltersSettingsLogs: StoryObj<LogsArgs> = {
...logs,
render: () => <LogsModulePage />,
play: withTrialBanner(dirtyLogsQuickFilters),
};
/** Traces quick filters settings: the action footer with an unsaved change. */
export const QuickFiltersSettingsTraces: StoryObj<TracesArgs> = {
...traces,
render: () => <TracesModulePage />,
play: withTrialBanner(dirtyTracesQuickFilters),
};
/** Span drawer: the details drawer opened from a row of the traces list. */
export const SpanDrawer: StoryObj<TracesArgs> = {
...traces,
render: () => <TracesModulePage />,
play: withTrialBanner(showsSpanDetails),
};
/** Pods details drawer: the drawer over the list, on its logs tab. */
export const PodsDetailsDrawer: StoryObj<PodsArgs> = {
...pods,
args: { ...pods.args, drawer: true },
render: () => <InfrastructureMonitoringPage />,
play: withTrialBanner(openDrawerLogsTab),
};
/** Dashboards list: the rename dialog opened from a row. */
export const RenameDashboardDialog: StoryObj<DashboardsListArgs> = {
...dashboardsList,
render: () => <DashboardsListPage />,
play: withTrialBanner(openRenameDialog),
};
/** Add Credit Card modal opened from the strip's Support. */
export const AddCreditCardModal: StoryObj<GlobalMockArgs> = {
args: { noz: true, support: 'add-card' },
parameters: { signoz: { route: ROUTES.HOME, layout: 'app' } },
render: () => <div />,
play: withTrialBanner(openAddCardModal),
};
/** A toast raised over the strip. */
export const Toast: StoryObj<GlobalMockArgs> = {
args: { noz: true, support: 'pylon' },
parameters: { signoz: { route: ROUTES.HOME, layout: 'app' } },
render: () => <div />,
play: withTrialBanner(raiseToast),
};
/** Panel editor: a full-screen route with no bottom strip. */
export const PanelEditor: StoryObj<PanelEditorArgs> = {
...panelEditor,
render: renderAtRoute(ROUTES.DASHBOARD_PANEL_EDITOR, PanelEditorPage),
play: withTrialBanner(),
};

View File

@@ -1,93 +0,0 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import HomePage from 'pages/HomePage/HomePage';
import { homeMocks } from 'pages/HomePage/stories/HomePage.stories.mocks';
import {
dismissNoAuthBanner,
forgetNoAuthDismissal,
showsBanner,
} from './__story_mockdata__/banners.play';
type HomeArgs = PageStoryArgs<typeof homeMocks>;
const pageStory = storyMocks(homeMocks, { route: ROUTES.HOME, layout: 'app' });
/**
* Every banner the shell can show, one per story, on Home. The `Banner`
* control switches between them on any page story.
*
* Route: every page inside the app shell; these stories use `/home`.
*/
const meta = {
title: 'Foundations/Banners/Shell',
tags: ['play'],
component: HomePage,
...pageStory,
parameters: { ...pageStory.parameters },
beforeEach: forgetNoAuthDismissal,
play: showsBanner,
} satisfies Meta<HomeArgs>;
export default meta;
type Story = StoryObj<HomeArgs>;
/** A cloud trial with three days left. */
export const TrialExpiry: Story = {
args: { banner: 'trial-expiry' },
};
/** The last payment failed; the workspace is suspended in seven days. */
export const PaymentFailed: Story = {
args: { banner: 'payment-failed' },
};
/** Self-hosted license past its end date. */
export const LicenseExpired: Story = {
args: { banner: 'license-expired' },
};
/** Self-hosted license terminated; enterprise features are off. */
export const LicenseTerminated: Story = {
args: { banner: 'license-terminated' },
};
/** Self-hosted license cancelled. */
export const LicenseCancelled: Story = {
args: { banner: 'license-cancelled' },
};
/** Self-hosted license defaulted on its bill. */
export const LicenseDefaulted: Story = {
args: { banner: 'license-defaulted' },
};
/** Self-hosted evaluation license past its trial. */
export const EvaluationExpired: Story = {
args: { banner: 'evaluation-expired' },
};
/** An expired license during a trial: both banners at once. */
export const LicenseExpiredWithTrial: Story = {
args: { banner: 'license-expired-with-trial' },
};
/** An expired license with a failed payment: both banners at once. */
export const LicenseExpiredWithPaymentFailed: Story = {
args: { banner: 'license-expired-with-payment-failed' },
};
/** Impersonation mode: authentication is off. */
export const NoAuth: Story = {
args: { banner: 'no-auth' },
};
/** The impersonation banner closed; it stays closed across reloads. */
export const NoAuthDismissed: Story = {
args: { banner: 'no-auth' },
play: dismissNoAuthBanner,
};

View File

@@ -1,80 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import removeLocalStorageKey from 'api/browser/localstorage/remove';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { AppShellArgs } from '@/storybook/globals/appShellMocks';
type Banner = AppShellArgs['banner'];
interface PlayContext {
args: Pick<AppShellArgs, 'banner'>;
}
export const NO_AUTH_STORAGE_KEY = 'no-auth-banner-v1';
const NO_AUTH_BANNER = 'no-auth-banner';
/** The shell renders its banners after the license and the trial settle. */
const untilLoaded = { timeout: 10_000 };
const TRIAL = /You are in free trial period/;
const PAYMENT_FAILED = /Your bill payment has failed/;
const LICENSE_EXPIRED = /Your SigNoz license has expired/;
const BANNER_TEXT: Record<Exclude<Banner, 'none' | 'no-auth'>, RegExp[]> = {
'trial-expiry': [TRIAL],
'payment-failed': [PAYMENT_FAILED],
'license-expired': [LICENSE_EXPIRED],
'license-terminated': [/Your SigNoz license is terminated/],
'license-cancelled': [/Your SigNoz license is cancelled/],
'license-defaulted': [/Your SigNoz license is defaulted/],
'evaluation-expired': [/Your SigNoz trial has ended/],
'license-expired-with-trial': [LICENSE_EXPIRED, TRIAL],
'license-expired-with-payment-failed': [LICENSE_EXPIRED, PAYMENT_FAILED],
};
/** A dismissal is kept in `localStorage`, so it would outlive the story. */
export const forgetNoAuthDismissal = (): void => {
removeLocalStorageKey(NO_AUTH_STORAGE_KEY);
};
export const showsBanner = async ({ args }: PlayContext): Promise<void> => {
if (args.banner === 'none') {
return;
}
if (args.banner === 'no-auth') {
await screen.findByTestId(NO_AUTH_BANNER, undefined, untilLoaded);
return;
}
await Promise.all(
BANNER_TEXT[args.banner].map((text) =>
screen.findByText(text, undefined, untilLoaded),
),
);
};
export const dismissNoAuthBanner = async ({
args,
}: PlayContext): Promise<void> => {
if (args.banner !== 'no-auth') {
await showsBanner({ args });
return;
}
const banner = await screen.findByTestId(
NO_AUTH_BANNER,
undefined,
untilLoaded,
);
await userEvent.click(within(banner).getByRole('button'));
await waitFor(() =>
expect(screen.queryByTestId(NO_AUTH_BANNER)).not.toBeInTheDocument(),
);
};

View File

@@ -1,41 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import type { AppShellArgs } from '@/storybook/globals/appShellMocks';
import { showsBanner } from './banners.play';
interface HostPlayContext<TArgs extends Pick<AppShellArgs, 'banner'>> {
mount: () => Promise<unknown>;
args: TArgs;
canvasElement: HTMLElement;
}
type OpenOverlay<TArgs extends Pick<AppShellArgs, 'banner'>> = (context: {
args: TArgs;
canvasElement: HTMLElement;
}) => Promise<void>;
/**
* Mounts the host, waits for the trial banner, then opens the host's own
* overlay. `mount` is destructured so a control change replays all of it.
*/
export const withTrialBanner =
<TArgs extends Pick<AppShellArgs, 'banner'>>(
openOverlay?: OpenOverlay<TArgs>,
) =>
async ({
mount,
args,
canvasElement,
}: HostPlayContext<TArgs>): Promise<void> => {
await mount();
if (args.banner === 'trial-expiry') {
await showsBanner({ args });
}
await openOverlay?.({ args, canvasElement });
};

View File

@@ -1,167 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, within } from 'storybook/test';
import type { GlobalMockArgs } from '@/storybook/globals';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { createAlertMocks } from 'pages/CreateAlert/stories/CreateAlert.stories.mocks';
import type { meterMocks } from 'pages/MeterExplorer/stories/MeterExplorer.stories.mocks';
import { hasPendingRule } from 'pages/MetricsExplorer/stories/__story_mockdata__/metricsExplorer';
import type { metricsMocks } from 'pages/MetricsExplorer/stories/MetricsExplorerPage.stories.mocks';
type CreateAlertArgs = PageStoryArgs<typeof createAlertMocks>;
type MeterArgs = PageStoryArgs<typeof meterMocks>;
type MetricsArgs = PageStoryArgs<typeof metricsMocks>;
/** The pages fetch before they render, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** A restricted license banner swaps the cloud license for a self-hosted one. */
const isCloud = ({
license,
banner,
}: Pick<GlobalMockArgs, 'license' | 'banner'>): boolean =>
license === 'cloud' && !/^(license|evaluation)-/.test(banner);
export const showsPendingActivation = async ({
args,
}: {
args: Pick<
MetricsArgs,
| 'tab'
| 'drawer'
| 'drawerMetric'
| 'rules'
| 'pendingRules'
| 'volumeControl'
| 'license'
| 'dataState'
>;
}): Promise<void> => {
const licensed = args.license === 'cloud' || args.license === 'enterprise';
if (
!licensed ||
!args.volumeControl ||
args.tab !== 'summary' ||
args.drawer !== 'details' ||
args.dataState !== 'loaded' ||
!hasPendingRule(args.drawerMetric, args.rules, args.pendingRules)
) {
return;
}
await screen.findByTestId(
'volume-control-pending-banner',
undefined,
untilLoaded,
);
};
export const showsCancelSubscription = async ({
args,
}: {
args: Pick<GlobalMockArgs, 'license' | 'banner' | 'dataState'>;
}): Promise<void> => {
if (!isCloud(args)) {
return;
}
await screen.findByTestId('cancel-subscription-btn', undefined, untilLoaded);
// The usage table pushes the banner down once it lands, so the scroll waits
// for it. A revoked read permission never renders it.
if (args.dataState !== 'loading') {
await screen
.findByText(/Billing metrics are updated once every 24 hours/, undefined, {
timeout: 5_000,
})
.catch(() => undefined);
}
// The button is swapped once its permission check answers, so it is looked up
// again.
screen.getByTestId('cancel-subscription-btn').scrollIntoView({
block: 'center',
});
};
export const showsClickHouseInfo = async ({
canvasElement,
args,
}: {
canvasElement: HTMLElement;
args: Pick<CreateAlertArgs, 'alertMode'>;
}): Promise<void> => {
// The picker has no query section, and anomaly rules disable the tab.
if (args.alertMode === 'select-type' || args.alertMode === 'anomaly') {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'clickhouse-tab',
undefined,
untilLoaded,
),
);
const link = await screen.findByText(
/Learn to write faster, optimized queries/,
undefined,
untilLoaded,
);
link.scrollIntoView({ block: 'center' });
};
type MeterNoticeArgs = Pick<
MeterArgs,
'tab' | 'timeRange' | 'license' | 'banner' | 'billingNotice'
>;
/** The notices sit on the Meter tab and are decided before any data lands. */
const meterNotice =
(text: RegExp, isShown: (args: MeterNoticeArgs) => boolean) =>
async ({ args }: { args: MeterNoticeArgs }): Promise<void> => {
if (args.tab !== 'meter') {
return;
}
if (isShown(args)) {
await screen.findByText(text, undefined, untilLoaded);
return;
}
await screen.findByTestId(
'meter-breakdown-section-total',
undefined,
untilLoaded,
);
await expect(screen.queryByText(text)).not.toBeInTheDocument();
};
export const showsMeterBillingNotice = meterNotice(
/Billing is calculated in UTC/,
({ billingNotice }) => billingNotice,
);
export const showsMeterBeforeLaunch = meterNotice(
/Meter module data is accurate only from 22nd August 2025/,
(args) => isCloud(args) && args.timeRange === 'august-2025',
);
export const showsMeterShortWindow = meterNotice(
/Meter metrics data is aggregated over 1 hour period/,
({ timeRange }) => timeRange === 'last-30-minutes',
);
export const showsTopLevelOperationsThreshold = async (): Promise<void> => {
await screen.findByText(
/SigNoz calculates the RED metrics for a service/,
undefined,
untilLoaded,
);
};

View File

@@ -1,17 +1,18 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { toast } from '@signozhq/ui/sonner';
import { screen, userEvent } from 'storybook/test';
import type { GlobalMockArgs } from '../globals';
import {
openAddCardModal,
raiseToast,
} from './__story_mockdata__/bottomStrip.play';
/** A page that puts nothing in the strip, so the shell is all there is. */
function EmptyPage(): JSX.Element {
return <div />;
}
/** The shell renders its entry points after the global config and the license settle. */
const untilLoaded = { timeout: 10_000 };
/**
* The strip along the foot of the shell: what the page puts on the left, the
* build version when it puts nothing, and the shell's own Ask Noz and Support
@@ -53,7 +54,14 @@ export const AddCard: Story = {
/** The Add Credit Card modal, opened from the strip's Support. */
export const AddCardModal: Story = {
args: { noz: true, support: 'add-card' },
play: openAddCardModal,
play: async (): Promise<void> => {
await userEvent.click(
await screen.findByTestId('bottom-strip-support', undefined, untilLoaded),
);
await screen.findByRole('dialog', {
name: /Add Credit Card for Chat Support/i,
});
},
};
/**
@@ -69,6 +77,12 @@ export const Tooltips: Story = {
args: { noz: true, support: 'pylon', tooltipsOpen: true },
};
/** Raises a toast and waits for it, so the shot is taken with it on screen. */
const raiseToast: NonNullable<Story['play']> = async () => {
toast.success('Service account deleted');
await screen.findByText('Service account deleted', undefined, untilLoaded);
};
/**
* A toast above the strip. Sonner pins itself to the foot of the viewport, so
* without an offset it lands on top of Ask Noz and Support.

View File

@@ -64,70 +64,6 @@ export const LongMultilineToast: Story = {
},
};
/** A request still in flight: the loading toast stays until the promise settles. */
export const PromiseLoadingToast: Story = {
args: { state: 'promise-loading-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(
await screen.findByText('Enabling the alert rule'),
).toBeVisible();
},
};
/** A failed request: the rejected toast keeps a Dismiss action, stacked top-center. */
export const PromiseErrorToast: Story = {
args: { state: 'promise-error-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(
await screen.findByText('Could not clone the panel'),
).toBeVisible();
await screen.findByRole('button', { name: 'Dismiss' });
},
};
/** A warning that stays up, matching invites that only partly succeed. */
export const WarningToast: Story = {
args: { state: 'warning-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(await screen.findByText('Some invites failed')).toBeVisible();
},
};
/** An info toast pinned to the bottom-right stack, as export cancellation does. */
export const InfoToast: Story = {
args: { state: 'info-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(await screen.findByText('Export cancelled')).toBeVisible();
},
};
/** An error toast with a description and a Dismiss action, bottom-right. */
export const DangerWithDescription: Story = {
args: { state: 'danger-description-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(
await screen.findByText('Failed to update account settings'),
).toBeVisible();
await screen.findByText(/does not have permission/i);
await screen.findByRole('button', { name: 'Dismiss' });
},
};
/** Mutation: the inline application alert preserves its action affordance. */
export const InlineAlert: Story = {
args: { state: 'inline-alert' },

View File

@@ -10,11 +10,6 @@ export type FeedbackState =
| 'success-toast'
| 'actionable-error-toast'
| 'long-toast'
| 'promise-loading-toast'
| 'promise-error-toast'
| 'warning-toast'
| 'info-toast'
| 'danger-description-toast'
| 'inline-alert'
| 'confirmation'
| 'toast-over-confirmation';
@@ -26,10 +21,6 @@ interface FeedbackFixtureProps {
const longMessage =
'We could not apply the retention policy because the selected storage tier is unavailable. Review the workspace settings, then try again.';
const pendingSave = new Promise<void>(() => undefined);
const dismissAction = { label: 'Dismiss', onClick: (): void => undefined };
function FeedbackFixture({ state }: FeedbackFixtureProps): JSX.Element {
const [isConfirmationOpen, setIsConfirmationOpen] = useState(false);
@@ -46,62 +37,13 @@ function FeedbackFixture({ state }: FeedbackFixtureProps): JSX.Element {
return;
}
if (state === 'promise-loading-toast') {
toast.promise(pendingSave, {
loading: 'Enabling the alert rule',
success: 'Alert rule enabled',
error: 'Could not enable the alert rule',
});
return;
}
if (state === 'promise-error-toast') {
toast.promise(Promise.reject(new Error('failed')), {
loading: 'Cloning the panel',
success: 'Panel cloned',
error: { message: 'Could not clone the panel', action: dismissAction },
position: 'top-center',
duration: Infinity,
});
return;
}
if (state === 'warning-toast') {
toast.warning('Some invites failed', { duration: Infinity });
return;
}
if (state === 'info-toast') {
toast.info('Export cancelled', {
position: 'bottom-right',
duration: Infinity,
});
return;
}
if (state === 'danger-description-toast') {
toast.error('Failed to update account settings', {
description:
'The service account does not have permission to change this connection.',
action: dismissAction,
position: 'bottom-right',
duration: Infinity,
});
return;
}
toast.error(longMessage, { duration: Infinity });
};
const isToastStory =
state === 'success-toast' ||
state === 'actionable-error-toast' ||
state === 'long-toast' ||
state === 'promise-loading-toast' ||
state === 'promise-error-toast' ||
state === 'warning-toast' ||
state === 'info-toast' ||
state === 'danger-description-toast';
state === 'long-toast';
const confirmationTitle = 'Delete environment';
return (

View File

@@ -1,25 +0,0 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { toast } from '@signozhq/ui/sonner';
import { screen, userEvent } from 'storybook/test';
/** The shell renders its entry points after the global config and the license settle. */
const untilLoaded = { timeout: 10_000 };
export const openAddCardModal = async (): Promise<void> => {
await userEvent.click(
await screen.findByTestId('bottom-strip-support', undefined, untilLoaded),
);
await screen.findByRole('dialog', {
name: /Add Credit Card for Chat Support/i,
});
};
/** Raises a toast and waits for it, so the shot is taken with it on screen. */
export const raiseToast = async (): Promise<void> => {
toast.success('Service account deleted');
await screen.findByText('Service account deleted', undefined, untilLoaded);
};

View File

@@ -39,11 +39,6 @@ const BANNERS = [
'payment-failed',
'license-expired',
'license-terminated',
'license-cancelled',
'license-defaulted',
'evaluation-expired',
'license-expired-with-trial',
'license-expired-with-payment-failed',
'no-auth',
] as const;
@@ -158,76 +153,56 @@ const licensedBanner = (
};
};
const trialExpiryContext = (): Partial<IAppContext> => {
const nowInSeconds = Math.floor(Date.now() / 1000);
return {
trialInfo: {
...baseTrialInfo,
onTrial: true,
trialStart: nowInSeconds - 27 * DAY_IN_SECONDS,
trialEnd: nowInSeconds + 3 * DAY_IN_SECONDS,
workSpaceBlock: false,
trialConvertedToSubscription: false,
gracePeriodEnd: -1,
},
};
};
const withPaymentFailed = (license: LicenseResModel): LicenseResModel => ({
...license,
eventQueue: {
...license.eventQueue,
event: LicenseEvent.DEFAULT,
scheduledAt: new Date(Date.now() + 7 * DAY_IN_SECONDS * 1000).toISOString(),
},
});
// The restricted-workspace banner needs a self-hosted license; the cloud
// platform redirects to the restricted page instead.
const withRestricted =
(state: LicenseState) =>
(license: LicenseResModel): LicenseResModel => ({
...license,
platform: LicensePlatform.SELF_HOSTED,
state,
});
const RESTRICTED_STATES: Partial<Record<Banner, LicenseState>> = {
'license-expired': LicenseState.EXPIRED,
'license-terminated': LicenseState.TERMINATED,
'license-cancelled': LicenseState.CANCELLED,
'license-defaulted': LicenseState.DEFAULTED,
'evaluation-expired': LicenseState.EVALUATION_EXPIRED,
};
const bannerContext = (
banner: Banner,
activeLicense: LicenseResModel | null,
): Partial<IAppContext> => {
const nowInSeconds = Math.floor(Date.now() / 1000);
switch (banner) {
case 'trial-expiry':
return trialExpiryContext();
case 'payment-failed':
return licensedBanner(activeLicense, withPaymentFailed);
case 'license-expired-with-trial':
return {
...trialExpiryContext(),
...licensedBanner(activeLicense, withRestricted(LicenseState.EXPIRED)),
trialInfo: {
...baseTrialInfo,
onTrial: true,
trialStart: nowInSeconds - 27 * DAY_IN_SECONDS,
trialEnd: nowInSeconds + 3 * DAY_IN_SECONDS,
workSpaceBlock: false,
trialConvertedToSubscription: false,
gracePeriodEnd: -1,
},
};
case 'license-expired-with-payment-failed':
return licensedBanner(activeLicense, (license) =>
withRestricted(LicenseState.EXPIRED)(withPaymentFailed(license)),
);
case 'payment-failed':
return licensedBanner(activeLicense, (license) => ({
...license,
eventQueue: {
...license.eventQueue,
event: LicenseEvent.DEFAULT,
scheduledAt: new Date(
Date.now() + 7 * DAY_IN_SECONDS * 1000,
).toISOString(),
},
}));
default: {
const state = RESTRICTED_STATES[banner];
// Both restricted-workspace banners need a self-hosted license; the cloud
// platform never reaches that branch.
case 'license-expired':
return licensedBanner(activeLicense, (license) => ({
...license,
platform: LicensePlatform.SELF_HOSTED,
state: LicenseState.EXPIRED,
}));
return state ? licensedBanner(activeLicense, withRestricted(state)) : {};
}
case 'license-terminated':
return licensedBanner(activeLicense, (license) => ({
...license,
platform: LicensePlatform.SELF_HOSTED,
state: LicenseState.TERMINATED,
}));
default:
return {};
}
};
@@ -279,7 +254,7 @@ export const appShellMocks = defineStoryMocks({
banner: choiceControl<Banner>('Banner', {
group: APP_SHELL,
description:
'License, trial and no-auth banners above the shell. The license ones need a license to read, so they override an unlicensed License control. The `-with-` values turn two banners on at once.',
'License, trial and no-auth banners above the shell. The license ones need a license to read, so they override an unlicensed License control.',
options: BANNERS,
value: 'none',
}),

46
tests/fixtures/fileauditor.py vendored Normal file
View File

@@ -0,0 +1,46 @@
import json
import time
import docker
from fixtures import types
AUDIT_FILE_PATH = "/tmp/audit.log"
def list_audit_events(signoz: types.SigNoz) -> list[dict]:
"""Each line of the audit file is one OTLP JSON batch of events; this flattens all batches into events."""
exit_code, output = docker.from_env().containers.get(signoz.self.id).exec_run(["cat", AUDIT_FILE_PATH])
assert exit_code == 0, output.decode()
events = []
for line in output.decode().splitlines():
for resource_logs in json.loads(line)["resourceLogs"]:
resource = {attribute["key"]: attribute["value"]["stringValue"] for attribute in resource_logs["resource"]["attributes"]}
for scope_logs in resource_logs["scopeLogs"]:
for log_record in scope_logs["logRecords"]:
events.append(
{
"event_name": log_record["eventName"],
"severity_text": log_record["severityText"],
"body": log_record["body"]["stringValue"],
"scope_name": scope_logs["scope"]["name"],
"resource": resource,
"attributes": {attribute["key"]: int(attribute["value"]["intValue"]) if "intValue" in attribute["value"] else attribute["value"]["stringValue"] for attribute in log_record["attributes"]},
}
)
return events
def wait_for_audit_event(signoz: types.SigNoz, event_name: str, resource_id: str, target_id: str | None = None, wait_seconds: int = 10) -> dict:
deadline = time.time() + wait_seconds
events = []
while time.time() < deadline:
events = list_audit_events(signoz)
matched = [event for event in events if event["event_name"] == event_name and event["resource"].get("signoz.resource.id") == resource_id and (target_id is None or event["attributes"].get("signoz.resource.target.id") == target_id)]
if len(matched) > 0:
return matched[0]
time.sleep(0.5)
raise AssertionError(f"No {event_name} audit event for resource {resource_id} (target {target_id}) within {wait_seconds}s, events: {events}")

View File

@@ -0,0 +1,151 @@
import uuid
from collections.abc import Callable
from http import HTTPStatus
import requests
from fixtures import types
from fixtures.auth import USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD, find_user_by_email
from fixtures.fileauditor import wait_for_audit_event
from fixtures.savedview import SAVED_VIEW_BASE, create_saved_view
from fixtures.serviceaccount import SERVICE_ACCOUNT_BASE, create_service_account, create_service_account_with_key, delete_service_account, get_first_key_id
def test_create_saved_view_writes_create_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
admin = find_user_by_email(signoz, token, USER_ADMIN_EMAIL)
view_id = create_saved_view(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
event = wait_for_audit_event(signoz, "signoz.audit.create", view_id)
assert event["severity_text"] == "INFO"
assert event["scope_name"] == "signoz.audit"
assert event["resource"]["service.name"] == "signoz"
assert event["resource"]["signoz.resource.kind"] == "saved-view"
assert event["attributes"]["signoz.audit.verb"] == "create"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["signoz.principal.id"] == admin["id"]
assert event["attributes"]["signoz.principal.email"] == USER_ADMIN_EMAIL
assert event["attributes"]["signoz.organization.id"] == admin["orgId"]
assert event["attributes"]["http.request.method"] == "POST"
assert event["attributes"]["http.route"] == "/api/v2/saved_views"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.CREATED
def test_update_service_account_writes_update_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id = create_service_account(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
response = requests.put(
signoz.self.host_configs["8080"].get(f"{SERVICE_ACCOUNT_BASE}/{service_account_id}"),
json={"name": f"fileauditor-{uuid.uuid4().hex[:8]}"},
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
event = wait_for_audit_event(signoz, "signoz.audit.update", service_account_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.audit.verb"] == "update"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NO_CONTENT
def test_delete_service_account_writes_delete_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id = create_service_account(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
delete_service_account(signoz, token, service_account_id)
event = wait_for_audit_event(signoz, "signoz.audit.delete", service_account_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.audit.verb"] == "delete"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NO_CONTENT
def test_create_service_account_key_writes_attach_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id = create_service_account(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
response = requests.post(
signoz.self.host_configs["8080"].get(f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys"),
json={"name": "fileauditor", "expiresAt": 0},
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.CREATED, response.text
key_id = response.json()["data"]["id"]
event = wait_for_audit_event(signoz, "signoz.audit.attach", service_account_id, target_id=key_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.resource.target.kind"] == "factor-api-key"
assert event["attributes"]["signoz.audit.verb"] == "attach"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}/keys"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.CREATED
def test_revoke_service_account_key_writes_detach_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
service_account_id, _ = create_service_account_with_key(signoz, token, f"fileauditor-{uuid.uuid4().hex[:8]}")
key_id = get_first_key_id(signoz, token, service_account_id)
response = requests.delete(
signoz.self.host_configs["8080"].get(f"{SERVICE_ACCOUNT_BASE}/{service_account_id}/keys/{key_id}"),
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.NO_CONTENT, response.text
event = wait_for_audit_event(signoz, "signoz.audit.detach", service_account_id, target_id=key_id)
assert event["resource"]["signoz.resource.kind"] == "serviceaccount"
assert event["attributes"]["signoz.resource.target.kind"] == "factor-api-key"
assert event["attributes"]["signoz.audit.verb"] == "detach"
assert event["attributes"]["signoz.audit.outcome"] == "success"
assert event["attributes"]["http.route"] == "/api/v1/service_accounts/{id}/keys/{fid}"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NO_CONTENT
def test_delete_missing_saved_view_writes_failure_event(
signoz: types.SigNoz,
apply_license: types.Operation, # pylint: disable=unused-argument
get_token: Callable[[str, str], str],
) -> None:
token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)
missing_view_id = str(uuid.uuid4())
response = requests.delete(
signoz.self.host_configs["8080"].get(f"{SAVED_VIEW_BASE}/{missing_view_id}"),
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.NOT_FOUND, response.text
event = wait_for_audit_event(signoz, "signoz.audit.delete", missing_view_id)
assert event["severity_text"] == "ERROR"
assert event["attributes"]["signoz.audit.outcome"] == "failure"
assert event["attributes"]["exception.type"] == "not-found"
assert event["attributes"]["http.response.status_code"] == HTTPStatus.NOT_FOUND

View File

@@ -0,0 +1,32 @@
import pytest
from testcontainers.core.container import Network
from fixtures import types
from fixtures.fileauditor import AUDIT_FILE_PATH
from fixtures.signoz import create_signoz
@pytest.fixture(name="signoz", scope="package")
def signoz_fileauditor(
network: Network,
zeus: types.TestContainerDocker,
gateway: types.TestContainerDocker,
sqlstore: types.TestContainerSQL,
clickhouse: types.TestContainerClickhouse,
request: pytest.FixtureRequest,
pytestconfig: pytest.Config,
) -> types.SigNoz:
return create_signoz(
network=network,
zeus=zeus,
gateway=gateway,
sqlstore=sqlstore,
clickhouse=clickhouse,
request=request,
pytestconfig=pytestconfig,
cache_key="signoz-fileauditor",
env_overrides={
"SIGNOZ_AUDITOR_PROVIDER": "file",
"SIGNOZ_AUDITOR_FILE_PATH": AUDIT_FILE_PATH,
},
)