Compare commits

...

21 Commits

Author SHA1 Message Date
Vinícius Lourenço
87ef8b9c5c test(storybook): drop stories that duplicate existing ones 2026-11-18 18:54:52 -03:00
Vinícius Lourenço
7a028a6b75 test(storybook): move and guard the new banner, trace and log plays 2026-11-18 18:52:30 -03:00
Vinícius Lourenço
b52cc3f00e test(storybook): move and guard the new settings, integration and LLM plays 2026-11-18 18:52:30 -03:00
Vinícius Lourenço
0e34b86654 test(storybook): move and guard the new dashboard, alert and home plays 2026-11-18 18:52:30 -03:00
Vinícius Lourenço
51d52925d3 test(storybook): skip invite, reset and add-card plays when controls remove their target 2026-11-18 18:48:31 -03:00
Vinícius Lourenço
74de165361 test(storybook): move the feedback plays into a play file 2026-11-18 18:48:31 -03:00
Vinícius Lourenço
45b7e74cd9 test(storybook): give exception filter keys their own context and data type 2026-11-18 18:48:30 -03:00
Vinícius Lourenço
8cbcfc249e test(storybook): name the save and rename view stories after the action 2026-11-18 18:48:30 -03:00
Vinícius Lourenço
db61ce762b test(storybook): move the remaining logs, traces and pods plays into their play files 2026-11-18 18:48:29 -03:00
Vinícius Lourenço
04a3cf6cb2 test(stories): add sso attribute and claim mapping expanded stories 2026-11-18 18:48:29 -03:00
Vinícius Lourenço
e211c56fdf test(storybook): collect page banner and notice stories under foundations 2026-11-18 18:48:29 -03:00
Vinícius Lourenço
f4b325a452 test(storybook): add shell banner host stories for fixed footers, drawers and dialogs 2026-11-18 18:48:29 -03:00
Vinícius Lourenço
bd8895c1ab test(storybook): add shell banner stories for every license, trial and no-auth state 2026-11-18 18:48:28 -03:00
Vinícius Lourenço
8b8e514908 test(stories): add query builder add-on stories with few and many values 2026-11-18 18:48:28 -03:00
Vinícius Lourenço
57de4bd6ad test(storybook): cover the trace details thread tab 2026-11-18 18:48:28 -03:00
Vinícius Lourenço
6ad36a9058 test(storybook): cover workspace domain conflict and onboarding facing issues 2026-11-18 18:48:28 -03:00
Vinícius Lourenço
cca7fcd29c test(storybook): cover the members invite roles dropdown 2026-11-18 18:48:28 -03:00
Vinícius Lourenço
939ed1577f test(storybook): add changelog modal stories for cloud and self-hosted 2026-11-18 18:48:27 -03:00
Vinícius Lourenço
e6e011fa30 test(stories): cover the channel edit form, editable and read-only 2026-11-18 18:48:27 -03:00
Vinícius Lourenço
ad2230e129 test(stories): add K8s drawer depth and pods log details stories 2026-11-18 18:48:27 -03:00
Manika Malhotra
784320b060 test(stories): cover the states the component migration changes 2026-11-18 18:48:27 -03:00
99 changed files with 4678 additions and 870 deletions

View File

@@ -0,0 +1,51 @@
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

@@ -0,0 +1,67 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
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

@@ -0,0 +1,39 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, waitFor } from 'storybook/test';
import { isCloudShell } from '@/storybook/globals/appShellMocks';
const TITLE = /What’s New ⎯ Changelog : November 3, 2026/;
interface PlayContext {
args: Record<string, unknown>;
}
export const showsCloudChangelog = async ({
args,
}: PlayContext): Promise<void> => {
await screen.findByRole('dialog', { name: TITLE });
// The License and Banner controls decide the platform, which decides the footer.
if (isCloudShell(args)) {
await expect(
screen.queryByRole('button', { name: /Skip for now/ }),
).not.toBeInTheDocument();
return;
}
await screen.findByRole('button', { name: /Skip for now/ });
};
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

@@ -0,0 +1,77 @@
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,16 +8,50 @@ 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 { Query } from 'types/api/queryBuilder/queryBuilderData';
import {
BaseAutocompleteData,
DataTypes,
} from 'types/api/queryBuilder/queryAutocompleteResponse';
import { IBuilderQuery, Query } from 'types/api/queryBuilder/queryBuilderData';
import type { QueryBuilderV2 } from '../QueryBuilderV2';
import {
mergeQueryBuilderFieldsConfig,
RAW_QUERY_FIELDS,
resolveQueryBuilderFields,
} from '../queryBuilderFields.utils';
import { BASE_ADD_ONS } from '../QueryV2/QueryAddOns/constants';
type QueryBuilderProps = Parameters<typeof QueryBuilderV2>[0];
export type QueryBuilderProps = Parameters<typeof QueryBuilderV2>[0];
/** The builder's provider reads its starting query from the URL, as every host seeds it. */
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: {
@@ -132,3 +166,30 @@ export const DEFAULT_ARGS: Partial<QueryBuilderProps> = {
panelType: PANEL_TYPES.TIME_SERIES,
version: 'v3',
};
/**
* A where-clause view has no add-ons and a Value panel offers the legend
* alone; a raw query or a fields config hides or disables the rest.
*/
export const offersEveryAddOn = (args: Partial<QueryBuilderProps>): boolean => {
if (args.showOnlyWhereClause || args.panelType === PANEL_TYPES.VALUE) {
return false;
}
const resolved = resolveQueryBuilderFields(
BASE_ADD_ONS.map((addOn) => addOn.key),
mergeQueryBuilderFieldsConfig(
args.isRawQuery ? RAW_QUERY_FIELDS : undefined,
args.fieldsConfig,
),
);
return [...resolved.values()].every(
({ hidden, disabled }) => !hidden && !disabled,
);
};
/** A metrics query's group by sits in the aggregation row, which a where-clause view drops. */
export const showsAggregationGroupBy = (
args: Partial<QueryBuilderProps>,
): boolean => !args.showOnlyWhereClause;

View File

@@ -0,0 +1,62 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, waitFor, within } from 'storybook/test';
import {
offersEveryAddOn,
type QueryBuilderProps,
showsAggregationGroupBy,
} from '../QueryBuilderV2.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: Partial<QueryBuilderProps>;
}
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, args }: PlayContext): Promise<void> => {
if (!offersEveryAddOn(args)) {
return;
}
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, args }: PlayContext): Promise<void> => {
if (!showsAggregationGroupBy(args)) {
return;
}
const query = within(canvasElement).getByTestId('query-A');
await waitFor(() => expect(groupByTags(query)).toHaveLength(groupByCount));
};

View File

@@ -0,0 +1,73 @@
/**
* 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,6 +98,15 @@ 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,6 +1,7 @@
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';
@@ -16,8 +17,9 @@ import {
queryBuilder,
selectedServiceQueryBuilder,
noSavedFiltersHandler,
noSavedTracesFiltersHandler,
} from './QuickFilters.stories.mocks';
import { QuickFiltersSource } from '../types';
import { FiltersType, QuickFiltersSource } from '../types';
const meta = {
title: 'Components/Quick Filters',
@@ -110,6 +112,29 @@ 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

@@ -60,3 +60,11 @@ type Story = StoryObj<DrawerArgs>;
export const Default: Story = {
args: { ...podEntityConfig.details } 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

@@ -8,7 +8,7 @@ import removeSessionStorage from 'api/browser/sessionstorage/remove';
import ROUTES from 'constants/routes';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { rest, type RequestHandler } from 'msw';
import { expect, userEvent, waitFor, within } from 'storybook/test';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import {
choiceControl,
@@ -20,6 +20,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import { globalConfigResponse } from '@/storybook/msw/__story_mockdata__/appShell';
import { dashboardsForUserResponse } from '@/storybook/msw/__story_mockdata__/dashboards';
import type { MockResolver } from '@/storybook/msw/types';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
AGENT_STATES,
@@ -86,6 +87,15 @@ const onBothBases = (
const ok: MockResolver = (_req, res, ctx) => res(ctx.status(200), ctx.json({}));
/** The sidebar always lists the open conversation, which the thread list answers first. */
const listedConversations = ({
conversation,
history,
}: {
conversation: boolean;
history: number;
}): number => (conversation ? Math.max(1, history) : history);
const startedExecution: MockResolver = (_req, res, ctx) =>
res(ctx.status(200), ctx.json({ executionId: EXECUTION_ID }));
@@ -153,10 +163,7 @@ export const aiAssistantMocks = defineStoryMocks({
: // A thread the sidebar does not list is one the server does not
// know, and the store drops those, so an open conversation is
// always the first row.
threadListResponse(
values.conversation ? Math.max(1, values.history) : values.history,
false,
),
threadListResponse(listedConversations(values), false),
),
),
...onBothBases(
@@ -327,3 +334,42 @@ export const failVoiceInput = (error: 'network' | 'not-allowed'): void => {
window as unknown as { webkitSpeechRecognition: StorySpeechRecognition }
).webkitSpeechRecognition.listening?.onerror?.({ error });
};
export type AIAssistantArgs = PageStoryArgs<typeof aiAssistantMocks>;
/** The thread list answers through the Data control, and an empty one leaves no row to act on. */
export const showsConversationRows = (args: AIAssistantArgs): boolean =>
args.dataState === 'loaded' && listedConversations(args) > 0;
/** The form comes with the thread detail, which a new conversation never fetches. */
export const hasPendingClarification = (args: AIAssistantArgs): boolean =>
args.conversation &&
args.dataState === 'loaded' &&
!!threadDetailResponse(args.contents, args.agent).pendingClarification;
/** The thread list resolves before the thread does, which outlasts the 1s default. */
export const untilLoaded = { timeout: 15_000 };
/** How long what a click opened has to stay on screen to count as open. */
const HOLD_MS = 1_000;
/**
* Click something, and keep clicking until what it opens is on screen. The
* message list remounts its items while it measures a freshly loaded thread, so
* a single click can land on a row that is about to be replaced, taking the
* state it just set with it. The replacement can land after that state has
* rendered, so it has to still be there `HOLD_MS` later.
*/
export const clickUntil = async (
find: () => Promise<HTMLElement>,
opens: RegExp,
): Promise<void> => {
await waitFor(async () => {
await userEvent.click(await find());
await screen.findByText(opens, undefined, { timeout: 1_000 });
await new Promise((resolve) => {
setTimeout(resolve, HOLD_MS);
});
screen.getByText(opens);
}, untilLoaded);
};

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';
@@ -9,13 +9,19 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import AIAssistantPage from '../AIAssistantPage';
import {
aiAssistantMocks,
clickUntil,
failVoiceInput,
forgetVoiceFailure,
longActionTooltipHandlers,
speak,
startVoiceInput,
untilLoaded,
} from './AIAssistantPage.stories.mocks';
import type { ThreadPart } from './__story_mockdata__/aiAssistant';
import {
openClarificationSelect,
renameConversation,
} from './__story_mockdata__/aiAssistant.play';
type AIAssistantArgs = PageStoryArgs<typeof aiAssistantMocks>;
@@ -47,33 +53,6 @@ export default meta;
type Story = StoryObj<AIAssistantArgs>;
/** The thread list resolves before the thread does, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** How long what a click opened has to stay on screen to count as open. */
const HOLD_MS = 1_000;
/**
* Click something, and keep clicking until what it opens is on screen. The
* message list remounts its items while it measures a freshly loaded thread, so
* a single click can land on a row that is about to be replaced, taking the
* state it just set with it. The replacement can land after that state has
* rendered, so it has to still be there `HOLD_MS` later.
*/
const clickUntil = async (
find: () => Promise<HTMLElement>,
opens: RegExp,
): Promise<void> => {
await waitFor(async () => {
await userEvent.click(await find());
await screen.findByText(opens, undefined, { timeout: 1_000 });
await new Promise((resolve) => {
setTimeout(resolve, HOLD_MS);
});
screen.getByText(opens);
}, untilLoaded);
};
/** The blocks the agent renders as cards the user answers in place. */
const INTERACTIVE: ThreadPart[] = [
'question',
@@ -139,6 +118,12 @@ 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: openClarificationSelect,
};
/** Reopening the page on a thread that has not come back yet. */
export const LoadingThread: Story = {
args: { dataState: 'loading' },
@@ -231,6 +216,11 @@ export const NegativeFeedback: Story = {
},
};
/** Renaming a thread: the title input the row swaps in. */
export const ConversationRename: Story = {
play: renameConversation,
};
/** What a conversation row offers: rename, a link to it, and archiving. */
export const ConversationActions: Story = {
play: async ({ canvasElement }): Promise<void> => {

View File

@@ -0,0 +1,70 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, waitFor, within } from 'storybook/test';
import {
type AIAssistantArgs,
clickUntil,
hasPendingClarification,
showsConversationRows,
untilLoaded,
} from '../AIAssistantPage.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: AIAssistantArgs;
}
export const openClarificationSelect = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!hasPendingClarification(args)) {
return;
}
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);
};
export const renameConversation = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsConversationRows(args)) {
return;
}
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);
};

View File

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

View File

@@ -3,11 +3,18 @@
* Do not hand-edit: regenerate instead.
*/
import {
buildNotificationChannelReadPermission,
buildNotificationChannelUpdatePermission,
NotificationChannelCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/notification-channel.permissions';
import { rest } from 'msw';
import { grantsAll } from '@/storybook/access/access';
import { choiceControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { MockResolver } from '@/storybook/msw/types';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
CHANNEL_ACTION_OUTCOMES,
@@ -21,6 +28,10 @@ import {
WEBHOOK_AUTHS,
type WebhookAuthChoice,
} from '../../stories/__story_mockdata__/alerts';
import {
recordChannelTestRequest,
resetChannelTestRequests,
} from './__story_mockdata__/channelsEdit';
const STORY_CHANNEL_ID = '1';
@@ -87,6 +98,13 @@ 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'
@@ -95,4 +113,42 @@ export const channelsEditMocks = defineStoryMocks({
),
],
config: () => ({ route: `/alerts/channels/edit/${STORY_CHANNEL_ID}` }),
effect: () => resetChannelTestRequests(),
});
export type ChannelsEditArgs = PageStoryArgs<typeof channelsEditMocks>;
type ChannelFormState = 'absent' | 'readOnly' | 'editable';
/**
* The form needs the saved channel and `read`. Without `update` it renders
* read-only, and a check that fails rather than denies leaves it editable.
*/
export const channelFormState = (args: ChannelsEditArgs): ChannelFormState => {
if (args.dataState !== 'loaded') {
return 'absent';
}
if (args.authzState === 'error') {
return 'editable';
}
const read = buildNotificationChannelReadPermission(STORY_CHANNEL_ID);
if (!grantsAll(args, read)) {
return 'absent';
}
return grantsAll(
args,
read,
buildNotificationChannelUpdatePermission(STORY_CHANNEL_ID),
)
? 'editable'
: 'readOnly';
};
/** A test send is a create on the collection; a failed check leaves it enabled. */
export const canTestChannel = (args: ChannelsEditArgs): boolean =>
args.authzState === 'error' ||
grantsAll(args, NotificationChannelCreatePermission);

View File

@@ -4,6 +4,11 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
expectEditableForm,
expectJiraAdvancedFields,
expectJiraConnectionFields,
} from './__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from './ChannelsEdit.stories.mocks';
import AlertList from '../../index';
@@ -36,8 +41,10 @@ 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 = {};
export const Default: Story = { play: expectEditableForm };
/** Mutation: clearing the required webhook URL surfaces the form's validation feedback. */
export const InvalidRequiredFields: Story = {
@@ -110,21 +117,25 @@ 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,
};
/**
@@ -133,6 +144,7 @@ export const WebhookWithoutAuth: Story = {
*/
export const Opsgenie: Story = {
args: { channelType: 'opsgenie' },
play: expectEditableForm,
};
/**
@@ -141,6 +153,7 @@ export const Opsgenie: Story = {
*/
export const Email: Story = {
args: { channelType: 'email' },
play: expectEditableForm,
};
/**
@@ -149,11 +162,13 @@ 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,
};
/**
@@ -163,17 +178,7 @@ export const GoogleChat: Story = {
*/
export const Jira: Story = {
args: { channelType: 'jira' },
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(
await within(canvasElement).findByTestId(
'jira-reopen-duration-textbox',
undefined,
{ timeout: 15_000 },
),
).toBeVisible();
},
play: expectJiraAdvancedFields,
};
/**
@@ -183,17 +188,7 @@ export const Jira: Story = {
*/
export const JiraSelfHosted: Story = {
args: { channelType: 'jira', jiraDeployment: 'selfhosted' },
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await expect(
await canvas.findByTestId('jira-pat-textbox', undefined, {
timeout: 15_000,
}),
).toHaveValue('story-jira-pat');
await expect(
canvas.queryByTestId('jira-email-textbox'),
).not.toBeInTheDocument();
},
play: expectJiraConnectionFields,
};
/**
@@ -202,6 +197,7 @@ export const JiraSelfHosted: Story = {
*/
export const JiraServiceManagementOps: Story = {
args: { channelType: 'jsmops' },
play: expectEditableForm,
};
/**
@@ -210,9 +206,11 @@ 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

@@ -0,0 +1,240 @@
/**
* 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 { channelSpec } from '../../../stories/__story_mockdata__/alerts';
import { expectDisabled, PAGE_LOAD } from '../../../stories/channelAuthz';
import {
canTestChannel,
channelFormState,
type ChannelsEditArgs,
} from '../ChannelsEdit.stories.mocks';
import { channelTestRequests } from './channelsEdit';
interface PlayContext {
canvasElement: HTMLElement;
args: ChannelsEditArgs;
}
/** 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,
args,
}: PlayContext): Promise<void> => {
if (channelFormState(args) !== 'editable') {
return;
}
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> => {
if (channelFormState(args) !== 'readOnly') {
return;
}
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,
channelType: ChannelsEditArgs['channelType'],
radio: RegExp,
): Promise<void> => {
const { canvasElement, args } = context;
if (
args.channelType !== channelType ||
channelFormState(args) !== 'readOnly'
) {
return;
}
await expectReadOnlyForm(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, 'webhook', /bearer/i);
export const expectJiraDeploymentLocked = (
context: PlayContext,
): Promise<void> => expectModeRadioLocked(context, 'jira', /self-hosted/i);
export const expectReadOnlyFormTestLocked = async (
context: PlayContext,
): Promise<void> => {
const { canvasElement, args } = context;
await expectReadOnlyForm(context);
if (channelFormState(args) !== 'readOnly') {
return;
}
await expectDisabled(
await within(canvasElement).findByTestId('test-channel-button'),
!canTestChannel(args),
);
};
export const sendSavedConfig = async (context: PlayContext): Promise<void> => {
const { canvasElement, args } = context;
if (channelFormState(args) !== 'readOnly' || !canTestChannel(args)) {
return;
}
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),
});
};
export const expectJiraAdvancedFields = async (
context: PlayContext,
): Promise<void> => {
const { canvasElement, args } = context;
await expectEditableForm(context);
if (args.channelType !== 'jira' || channelFormState(args) === 'absent') {
return;
}
// the advanced fields have their own card now, so nothing has to be
// expanded before they can be read
await expect(
await within(canvasElement).findByTestId(
'jira-reopen-duration-textbox',
undefined,
{ timeout: 15_000 },
),
).toBeVisible();
};
export const expectJiraConnectionFields = async (
context: PlayContext,
): Promise<void> => {
const { canvasElement, args } = context;
await expectEditableForm(context);
if (args.channelType !== 'jira' || channelFormState(args) === 'absent') {
return;
}
const canvas = within(canvasElement);
if (args.jiraDeployment === 'selfhosted') {
await expect(
await canvas.findByTestId('jira-pat-textbox', undefined, {
timeout: 15_000,
}),
).toHaveValue('story-jira-pat');
await expect(
canvas.queryByTestId('jira-email-textbox'),
).not.toBeInTheDocument();
return;
}
await canvas.findByTestId('jira-email-textbox', undefined, {
timeout: 15_000,
});
await expect(canvas.queryByTestId('jira-pat-textbox')).not.toBeInTheDocument();
};

View File

@@ -0,0 +1,22 @@
/**
* 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,6 +13,13 @@ import {
READ,
UPDATE,
} from '../../../stories/channelAuthz';
import {
expectJiraDeploymentLocked,
expectReadOnlyForm,
expectReadOnlyFormTestLocked,
expectWebhookAuthLocked,
sendSavedConfig,
} from '../__story_mockdata__/channelsEdit.play';
import { channelsEditMocks } from '../ChannelsEdit.stories.mocks';
import AlertList from '../../../index';
@@ -56,18 +63,12 @@ export const NoRead: Story = {
/**
* Reading is enough to open the page, so losing `update` alone leaves it
* standing read-only: the fields go disabled and Save is locked, not hidden.
* standing read-only: every field goes disabled and Save is locked, not hidden.
* The Channel type control walks the same check across every integration.
*/
export const NoUpdate: Story = {
args: { revoked: [UPDATE] },
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'));
},
play: expectReadOnlyForm,
};
/**
@@ -101,15 +102,17 @@ export const NoCreate: Story = {
*/
export const ReadOnly: Story = {
args: { revoked: [UPDATE, CREATE, DELETE] },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
play: expectReadOnlyFormTestLocked,
};
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'));
},
/**
* 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,
};
/**
@@ -145,6 +148,25 @@ 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>> = {
},
};
const channelSpec = (
export const channelSpec = (
type: ChannelType,
webhookAuth: WebhookAuthChoice,
jiraDeployment: JiraDeploymentChoice,

View File

@@ -120,17 +120,6 @@ 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,14 +14,9 @@ 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 {
@@ -298,28 +293,43 @@ export const exceptionAttributeValuesResponse = (
};
};
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' },
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 },
];
/** The quick filter settings panel lists its "other filters" from `/fields/keys`. */
/**
* The resource filter and the quick filter settings panel both list keys from
* `/fields/keys`; each key keeps its own context and data type.
*/
export const exceptionFieldKeysResponse = (
searchText: string | null,
): GetFieldsKeys200 => {
const search = (searchText ?? '').toLowerCase();
return fieldKeysResponse(
ATTRIBUTE_KEYS.map(({ key }) => key).filter((key) =>
key.toLowerCase().includes(search),
),
{ signal: TelemetrytypesSignalDTO.logs, fieldContext: resource },
);
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 }],
]),
),
},
};
};

View File

@@ -182,14 +182,3 @@ 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,28 +59,6 @@ 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

@@ -0,0 +1,40 @@
/**
* 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

@@ -4,11 +4,14 @@
*/
import { rest } from 'msw';
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
import { buildDashboardReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import { grantsAll } from '@/storybook/access/access';
import { choiceControl, toggleControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import {
@@ -19,6 +22,7 @@ import {
listMetricsResponse,
metricMetadataResponse,
} from '@/storybook/msw/__story_mockdata__/metrics';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
NEW_PANEL_ID,
@@ -32,6 +36,8 @@ import {
import {
currentDashboardDocument,
PANEL_IDS,
type PanelId,
panelQueryShape,
patchDashboardDocument,
seedDashboardDocument,
STORY_DASHBOARD_ID,
@@ -213,6 +219,55 @@ export const panelEditorMocks = defineStoryMocks({
},
});
export type PanelEditorArgs = PageStoryArgs<typeof panelEditorMocks>;
const SAVED_TIME_SERIES: readonly PanelId[] = ['request-rate', 'error-rate'];
const NEW_PANEL_KINDS_WITHOUT_CLICKHOUSE: readonly NewPanelKind[] = [
'list',
'text',
];
const NEW_PANEL_KINDS_WITH_SPAN_GAPS: readonly NewPanelKind[] = [
'time-series',
'area-chart',
];
/**
* The page mounts on `read`. A check that fails rather than denies still
* renders it.
*/
export const showsEditor = (args: PanelEditorArgs): boolean =>
args.authzState === 'error' ||
grantsAll(args, buildDashboardReadPermission(STORY_DASHBOARD_ID));
/** The list and text kinds offer no ClickHouse query mode. */
export const hasClickHouseTab = (args: PanelEditorArgs): boolean => {
if (!showsEditor(args)) {
return false;
}
if (args.panel === NEW_PANEL_ID) {
return !NEW_PANEL_KINDS_WITHOUT_CLICKHOUSE.includes(args.newPanelKind);
}
return (
panelQueryShape(args.panel).requestType !==
Querybuildertypesv5RequestTypeDTO.raw
);
};
/** Only the time series and area kinds offer "When data is missing". */
export const hasDisconnectValues = (args: PanelEditorArgs): boolean => {
if (!showsEditor(args)) {
return false;
}
return args.panel === NEW_PANEL_ID
? NEW_PANEL_KINDS_WITH_SPAN_GAPS.includes(args.newPanelKind)
: SAVED_TIME_SERIES.includes(args.panel);
};
export const savePanel = async (): Promise<void> => {
const save = await screen.findByTestId(
'panel-editor-v2-save',

View File

@@ -12,6 +12,7 @@ import {
expandConfigSections,
openAddColumn,
openAIQueryBuilder,
openClickHouseQuery,
openPanelTypeSwitcher,
saveAndExpectToast,
} from './__story_mockdata__/panelEditor.play';
@@ -51,6 +52,11 @@ type Story = StoryObj<PanelEditorArgs>;
*/
export const Default: Story = {};
/** The ClickHouse query tab, including its info callout. */
export const ClickHouseQuery: Story = {
play: openClickHouseQuery,
};
/** The create route, seeding an unsaved panel of the chosen kind. */
export const NewPanel: Story = {
args: { panel: 'new' },

View File

@@ -6,13 +6,20 @@
import { EQueryType } from 'types/common/dashboard';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { savePanel } from '../PanelEditorPage.stories.mocks';
import {
hasClickHouseTab,
hasDisconnectValues,
type PanelEditorArgs,
pickSegment,
savePanel,
} from '../PanelEditorPage.stories.mocks';
import { openChartAppearance } from './chartOptions.play';
const EDITOR_LOAD = { timeout: 10_000 };
interface PlayContext {
canvasElement: HTMLElement;
args: { panelSave?: string };
args: PanelEditorArgs;
}
export const expandConfigSections = async ({
@@ -105,3 +112,37 @@ export const openAIQueryBuilder = async ({
);
}
};
export const openClickHouseQuery = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!hasClickHouseTab(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByText('ClickHouse Query', undefined, {
timeout: 15000,
}),
);
await screen.findByText(/ClickHouse query agent skill/i, undefined, {
timeout: 15000,
});
};
export const enterInvalidDisconnectThreshold = async ({
args,
}: PlayContext): Promise<void> => {
if (!hasDisconnectValues(args)) {
return;
}
await openChartAppearance();
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);
};

View File

@@ -23,6 +23,7 @@ import {
pickLogScale,
stackBars,
} from '../__story_mockdata__/chartOptions.play';
import { enterInvalidDisconnectThreshold } from '../__story_mockdata__/panelEditor.play';
import PanelEditorPage from '../../PanelEditorPage';
@@ -90,6 +91,11 @@ export const ChartAppearance: Story = {
play: openChartAppearance,
};
/** Disconnect-values in threshold mode, with an invalid duration showing the inline error. */
export const ChartAppearanceDisconnectThreshold: Story = {
play: enterInvalidDisconnectThreshold,
};
/** Dashed lines under a gradient fill, with the points drawn. */
export const ChartAppearanceDashedGradient: Story = {
play: pickDashedGradientWithPoints,

View File

@@ -8,9 +8,16 @@ import ROUTES from 'constants/routes';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import type { GetPublicDashboard200 } from 'api/generated/services/sigNoz.schemas';
import { useDashboardPreferencesStore } from 'hooks/dashboard/useDashboardPreference';
import {
buildDashboardDeletePermission,
buildDashboardReadPermission,
buildDashboardUpdatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/dashboard.permissions';
import type { BrandedPermission } from 'lib/authz/hooks/useAuthZ/types';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import { grantsAll } from '@/storybook/access/access';
import {
choiceControl,
countControl,
@@ -23,6 +30,7 @@ import {
fieldValuesResponse,
} from '@/storybook/msw/__story_mockdata__/fields';
import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
currentDashboardDocument,
@@ -35,6 +43,7 @@ import {
VARIABLE_KINDS,
type DashboardArgs,
type DurationChoice,
type PanelId,
type VariableKind,
} from './__story_mockdata__/dashboard';
import { publicDashboardMeta } from './__story_mockdata__/publicDashboard';
@@ -381,6 +390,42 @@ export const dashboardMocks = defineStoryMocks({
},
});
export type DashboardPageArgs = PageStoryArgs<typeof dashboardMocks>;
const SEARCHABLE_PANELS: readonly PanelId[] = ['top-endpoints', 'recent-logs'];
/**
* The page mounts on `read`. A check that fails rather than denies still
* renders it.
*/
export const showsDashboard = (args: DashboardPageArgs): boolean =>
!args.notFound &&
(args.authzState === 'error' ||
grantsAll(args, buildDashboardReadPermission(STORY_DASHBOARD_ID)));
/** A menu row whose check errors stays enabled; a lock disables it otherwise. */
const rowEnabled = (
args: DashboardPageArgs,
...checks: BrandedPermission[]
): boolean =>
showsDashboard(args) &&
(args.authzState === 'error' || (!args.locked && grantsAll(args, ...checks)));
export const hasPanelSearch = (args: DashboardPageArgs): boolean =>
showsDashboard(args) &&
PANEL_IDS.slice(0, args.panels).some((id) => SEARCHABLE_PANELS.includes(id));
export const canDeleteDashboard = (args: DashboardPageArgs): boolean =>
rowEnabled(args, buildDashboardDeletePermission(STORY_DASHBOARD_ID));
export const canEditSections = (args: DashboardPageArgs): boolean =>
args.sectioned &&
rowEnabled(
args,
buildDashboardReadPermission(STORY_DASHBOARD_ID),
buildDashboardUpdatePermission(STORY_DASHBOARD_ID),
);
/**
* One panel's query answered with a warning beside its value, so its header
* carries the status indicator while the rest of the dashboard is untouched.

View File

@@ -22,7 +22,12 @@ import {
tooltipRoute,
warnedPanelQueryHandler,
} from './DashboardPage.stories.mocks';
import { hoverJsonValidation } from './__story_mockdata__/dashboard.play';
import {
expandPanelSearch,
hoverJsonValidation,
openDeleteDashboardDialog,
openRenameSectionDialog,
} from './__story_mockdata__/dashboard.play';
import { TOOLTIP_PANEL_NAME } from './__story_mockdata__/tooltipDashboard';
import DashboardPage from '../DashboardPage';
@@ -200,6 +205,11 @@ export const TooltipsInViewPanelModal: Story = {
},
};
/** A list or table panel's search field, expanded and filled. */
export const PanelSearchExpanded: Story = {
play: expandPanelSearch,
};
/**
* The dashboard's own Actions menu, open: rename, clone, lock, full screen and
* delete, the menu the toolbar's Actions button carries.
@@ -252,6 +262,16 @@ export const SectionActionsMenu: Story = {
},
};
/** Delete dashboard, the confirm dialog the Actions menu opens. */
export const DeleteDashboardDialog: Story = {
play: openDeleteDashboardDialog,
};
/** Rename section, the title dialog a section menu opens. */
export const RenameSectionDialog: Story = {
play: openRenameSectionDialog,
};
const openNewPanelPicker = async (
canvasElement: HTMLElement,
): Promise<void> => {

View File

@@ -5,11 +5,14 @@
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { dashboardDurationError } from '../../DashboardContainer/utils/dashboardDuration';
import {
type dashboardMocks,
canDeleteDashboard,
canEditSections,
clickSectionAction,
type DashboardPageArgs,
hasPanelSearch,
openActionsMenu,
openJsonEditor,
openSettings,
PAGE_LOAD,
@@ -17,7 +20,7 @@ import {
interface DashboardPlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof dashboardMocks>;
args: DashboardPageArgs;
}
const findDefaultTimeRange = async ({
@@ -89,3 +92,58 @@ export const hoverJsonValidation = async ({
await userEvent.hover(validation);
await screen.findByRole('tooltip', {}, PAGE_LOAD);
};
export const expandPanelSearch = async ({
canvasElement,
args,
}: DashboardPlayContext): Promise<void> => {
if (!hasPanelSearch(args)) {
return;
}
// 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');
};
export const openDeleteDashboardDialog = async ({
canvasElement,
args,
}: DashboardPlayContext): Promise<void> => {
if (!canDeleteDashboard(args)) {
return;
}
await openActionsMenu(canvasElement);
// 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 },
);
};
export const openRenameSectionDialog = async ({
canvasElement,
args,
}: DashboardPlayContext): Promise<void> => {
if (!canEditSections(args)) {
return;
}
await clickSectionAction(canvasElement, 'Rename section');
await screen.findByRole('dialog', { name: /rename section/i });
};

View File

@@ -30,7 +30,6 @@ import {
waitFor,
within,
} from 'storybook/test';
import { LicensePlatform } from 'types/api/licensesV3/getActive';
import { grantsAll } from '@/storybook/access/access';
import {
@@ -40,7 +39,6 @@ import {
toggleControl,
} from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import { appShellMocks } from '@/storybook/globals/appShellMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
@@ -611,10 +609,6 @@ export const showsWorkspaceEmpty = (args: DashboardsListArgs): boolean =>
canList(args) &&
args.dashboards === 0;
export const isCloudTenant = (args: DashboardsListArgs): boolean =>
appShellMocks.config?.(appShellMocks.read(args)).appContext?.activeLicense
?.platform === LicensePlatform.CLOUD;
/** Opens the actions menu of the row at `index`. */
export const openRowActions = async (
canvasElement: HTMLElement,

View File

@@ -22,6 +22,7 @@ import {
openEditTagsDialog,
openFirstRowActions,
openRenameDialog,
openRenameViewPopover,
openSaveViewPopover,
openTemplateTab,
pinDashboard,
@@ -139,10 +140,15 @@ export const EditTagsDialog: Story = {
};
/** The popover that names the current filters as a new saved view. */
export const SaveViewPopover: Story = {
export const SaveView: 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

@@ -5,6 +5,8 @@
import { expect, screen, userEvent, within } from 'storybook/test';
import { isCloudShell } from '@/storybook/globals/appShellMocks';
import {
canCreate,
canDelete,
@@ -13,7 +15,6 @@ import {
canUpdate,
clickRowAction,
type DashboardsListArgs,
isCloudTenant,
listedDashboards,
openLegacyDialog,
openRowActions,
@@ -165,6 +166,27 @@ export const openSaveViewPopover = async ({
await screen.findByText('Save as view');
};
export const openRenameViewPopover = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsSavedViews(args)) {
return;
}
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,
@@ -444,7 +466,7 @@ export const submitTemplateRequest = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canCreate(args) || !isCloudTenant(args)) {
if (!canCreate(args) || !isCloudShell(args)) {
return;
}

View File

@@ -3,9 +3,11 @@
* Do not hand-edit: regenerate instead.
*/
import { createShortcutActions } from 'constants/shortcutActions';
import { listRulesV3Response } from 'mocks-server/__mockdata__/alert_rules';
import { rest } from 'msw';
import { accessFor } from '@/storybook/access/access';
import {
countControl,
choiceControl,
@@ -13,6 +15,7 @@ import {
toggleControl,
} from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
buildAlertRules,
buildServices,
@@ -201,3 +204,18 @@ export const homeMocks = defineStoryMocks({
appContext: { featureFlags: homeFeatureFlags(servicesSource) },
}),
});
export type HomeArgs = PageStoryArgs<typeof homeMocks>;
const noop = (): void => undefined;
/** The palette only lists the actions the role it runs as is allowed. */
export const paletteListsHome = (args: HomeArgs): boolean => {
const { legacyRole } = accessFor(args.access, args.permissions, args.revoked);
const home = createShortcutActions({
navigate: noop,
handleThemeChange: noop,
}).find((action) => action.id === 'home');
return !home?.roles || home.roles.includes(legacyRole);
};

View File

@@ -5,6 +5,7 @@ import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { homeMocks } from './HomePage.stories.mocks';
import { openCommandPalette } from './__story_mockdata__/home.play';
import HomePage from '../HomePage';
@@ -97,3 +98,8 @@ 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: openCommandPalette,
};

View File

@@ -0,0 +1,23 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent } from 'storybook/test';
import { type HomeArgs, paletteListsHome } from '../HomePage.stories.mocks';
interface PlayContext {
args: HomeArgs;
}
export const openCommandPalette = async ({
args,
}: PlayContext): Promise<void> => {
await userEvent.keyboard('{Meta>}k{/Meta}');
await screen.findByPlaceholderText('Search…', undefined, { timeout: 10000 });
if (paletteListsHome(args)) {
await screen.findByText('Go to Home');
}
};

View File

@@ -11,6 +11,7 @@ import {
import {
copyPodMetadata,
copyPodName,
openDrawerLogDetails,
openDrawerLogsTab,
openTableOptions,
suggestFilterKeys,
@@ -63,6 +64,12 @@ 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,6 +32,28 @@ 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

@@ -14,6 +14,7 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { MockResolver } from '@/storybook/msw/types';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
ACCOUNT_CAP,
@@ -286,6 +287,12 @@ export const cloudIntegrationMocks = defineStoryMocks({
},
});
export type CloudIntegrationArgs = PageStoryArgs<typeof cloudIntegrationMocks>;
/** The hero offers Integrate Now only once the account list has answered with none. */
export const offersIntegrateNow = (args: CloudIntegrationArgs): boolean =>
args.dataState === 'loaded' && args.accounts === 0;
/** The page picks its first service before it can render it. */
export const untilLoaded = { timeout: 20_000 };

View File

@@ -22,6 +22,10 @@ import {
updateGcpProjects,
updateTaggedAccount,
} from './CloudIntegration.stories.mocks';
import {
openConnectDialog,
openGcpRegionDropdown,
} from './__story_mockdata__/cloudIntegration.play';
import IntegrationsDetailsPage from '../../index';
@@ -117,6 +121,12 @@ 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: openConnectDialog,
};
/** The regions an already-connected account collects from. */
export const EditAccount: Story = {
play: async ({ canvasElement }): Promise<void> => {
@@ -321,17 +331,7 @@ export const GcpAccountConnectedToast: Story = {
/** Interaction: the deployment region menu of the GCP setup drawer. */
export const GcpRegionOpen: Story = {
args: { provider: 'gcp', accounts: 0 },
play: async ({ canvasElement }): Promise<void> => {
await openConnectFlow(canvasElement);
await userEvent.click(
await screen.findByTestId(
'gcp-deployment-region-select',
undefined,
untilLoaded,
),
);
await screen.findByRole('listbox');
},
play: openGcpRegionDropdown,
};
/**

View File

@@ -0,0 +1,50 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent } from 'storybook/test';
import {
type CloudIntegrationArgs,
offersIntegrateNow,
openConnectFlow,
untilLoaded,
} from '../CloudIntegration.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: CloudIntegrationArgs;
}
export const openConnectDialog = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!offersIntegrateNow(args)) {
return;
}
await openConnectFlow(canvasElement);
await screen.findByRole('dialog', undefined, untilLoaded);
};
export const openGcpRegionDropdown = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!offersIntegrateNow(args)) {
return;
}
await openConnectFlow(canvasElement);
if (args.provider !== 'gcp') {
return;
}
await userEvent.click(
await screen.findByTestId(
'gcp-deployment-region-select',
undefined,
untilLoaded,
),
);
await screen.findByRole('listbox');
};

View File

@@ -4,16 +4,20 @@
*/
import ROUTES from 'constants/routes';
import { IsAdminPermission } from 'lib/authz/hooks/useAuthZ/legacy';
import { rest } from 'msw';
import { grantsAll } from '@/storybook/access/access';
import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
GROUP_SAVES,
type GroupSave,
MAPPING_GROUP_MAX,
spanMapperGroupsResponse,
spanMappersResponse,
wideConditionGroupsResponse,
} from './__story_mockdata__/attributeMapping';
@@ -28,6 +32,15 @@ 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', {
@@ -78,3 +91,9 @@ export const attributeMappingMocks = defineStoryMocks({
},
config: () => ({ route: ROUTES.AI_OBSERVABILITY_ATTRIBUTE_MAPPING }),
});
export type AttributeMappingArgs = PageStoryArgs<typeof attributeMappingMocks>;
/** Adding a mapping needs a group to open, and the admin grant the page gates managing on. */
export const canAddMapping = (args: AttributeMappingArgs): boolean =>
args.groups > 0 && grantsAll(args, IsAdminPermission);

View File

@@ -7,8 +7,10 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import LLMObservabilityPage from '../../index';
import {
attributeMappingMocks,
groupMappers,
wideConditionGroup,
} from './AttributeMapping.stories.mocks';
import { openAddMappingDrawer } from './__story_mockdata__/attributeMapping.play';
type AttributeMappingArgs = PageStoryArgs<typeof attributeMappingMocks>;
@@ -79,6 +81,12 @@ export const GroupFormDrawer: Story = {
},
};
/** The drawer that adds a mapping to the first group. */
export const AddMappingDrawer: Story = {
parameters: { msw: { handlers: [groupMappers] } },
play: openAddMappingDrawer,
};
/**
* 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

@@ -0,0 +1,41 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, within } from 'storybook/test';
import {
type AttributeMappingArgs,
canAddMapping,
} from '../AttributeMapping.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: AttributeMappingArgs;
}
export const openAddMappingDrawer = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canAddMapping(args)) {
return;
}
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');
};

View File

@@ -5,10 +5,15 @@
import type {
ListSpanMapperGroups200,
ListSpanMappers200,
SpantypesSpanMapperGroupConditionKeyDTO,
SpantypesSpanMapperGroupDTO,
} from 'api/generated/services/sigNoz.schemas';
import { SpantypesSpanMapperOriginDTO } from 'api/generated/services/sigNoz.schemas';
import {
SpantypesFieldContextDTO,
SpantypesSpanMapperOperationDTO,
SpantypesSpanMapperOriginDTO,
} from 'api/generated/services/sigNoz.schemas';
const ORG_ID = 'org-signoz';
@@ -72,6 +77,38 @@ 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,17 +168,6 @@ 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

@@ -5,9 +5,12 @@
import ROUTES from 'constants/routes';
import { rest } from 'msw';
import { componentPermission } from 'utils/permission';
import { accessFor } from '@/storybook/access/access';
import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
PRICING_RULE_MAX,
@@ -110,3 +113,11 @@ export const modelPricingMocks = defineStoryMocks({
],
config: () => ({ route: ROUTES.AI_OBSERVABILITY_CONFIGURATION }),
});
export type ModelPricingArgs = PageStoryArgs<typeof modelPricingMocks>;
/** Add model cost is gated on the legacy role rather than an authz check. */
export const canManagePricing = (args: ModelPricingArgs): boolean =>
componentPermission.manage_llm_pricing.includes(
accessFor(args.access, args.permissions, args.revoked).legacyRole,
);

View File

@@ -6,6 +6,10 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import LLMObservabilityPage from '../../index';
import { modelPricingMocks } from './ModelPricing.stories.mocks';
import {
openModelCostDrawerCreate,
openUnpricedModels,
} from './__story_mockdata__/modelPricing.play';
type ModelPricingArgs = PageStoryArgs<typeof modelPricingMocks>;
@@ -39,6 +43,16 @@ export const NothingPriced: Story = {
args: { rules: 0 },
};
/** Models seen in spans that no rule prices yet. */
export const UnpricedModels: Story = {
play: openUnpricedModels,
};
/** Creating a rule: the blank drawer, with the provider select enabled. */
export const ModelCostDrawerCreate: Story = {
play: openModelCostDrawerCreate,
};
/**
* The first pricing rule's menu, open over the table: edit the rule or drop it.
*/

View File

@@ -0,0 +1,46 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, within } from 'storybook/test';
import {
canManagePricing,
type ModelPricingArgs,
} from '../ModelPricing.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: ModelPricingArgs;
}
export const openUnpricedModels = async ({
canvasElement,
}: PlayContext): 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 });
};
export const openModelCostDrawerCreate = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canManagePricing(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /add model cost/i },
{ timeout: 15000 },
),
);
await screen.findByTestId('drawer-provider-select');
};

View File

@@ -4,6 +4,12 @@ import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
addSeverityParserProcessor,
clickFirst,
enterEditMode,
untilLoaded,
} from './__story_mockdata__/pipelines.play';
import { pipelinesMocks } from './Pipelines.stories.mocks';
import LogsModulePage from '../../LogsModulePage';
@@ -30,37 +36,6 @@ export default meta;
type Story = StoryObj<PipelinesArgs>;
/** The page fetches before it renders a row, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** Row actions repeat per pipeline, 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);
};
/**
* Editing is a mode the whole table is in: the row actions, the drag handles and
* the save bar only exist inside it.
*/
const enterEditMode = async (canvasElement: HTMLElement): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/enter edit mode/i,
undefined,
untilLoaded,
),
);
};
/**
* The pipelines tab: the processors the org runs over logs before storing them,
* in the order they run, with the version that is deployed on the collector.
@@ -116,6 +91,11 @@ export const AddProcessor: Story = {
},
};
/** Severity Parser is the type whose mapping fields are CSV inputs. */
export const AddSeverityParserProcessor: Story = {
play: addSeverityParserProcessor,
};
/**
* The logs a pipeline matches, over the interval the preview asks for, with the
* simulation of its processors one click away.

View File

@@ -0,0 +1,67 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { pipelinesMocks } from '../Pipelines.stories.mocks';
type PipelinesArgs = PageStoryArgs<typeof pipelinesMocks>;
interface PlayContext {
canvasElement: HTMLElement;
args: Pick<PipelinesArgs, 'pipelines' | 'dataState'>;
}
/** The page fetches before it renders a row, which outlasts the 1s default. */
export const untilLoaded = { timeout: 15_000 };
/** Row actions repeat per pipeline, so a story that opens one takes the first. */
export const clickFirst = async (
canvasElement: HTMLElement,
testId: string,
): Promise<void> => {
const [action] = await within(canvasElement).findAllByTestId(
testId,
undefined,
untilLoaded,
);
await userEvent.click(action);
};
/**
* Editing is a mode the whole table is in: the row actions, the drag handles and
* the save bar only exist inside it.
*/
export const enterEditMode = async (
canvasElement: HTMLElement,
): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/enter edit mode/i,
undefined,
untilLoaded,
),
);
};
export const addSeverityParserProcessor = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.dataState !== 'loaded' || args.pipelines === 0) {
return;
}
await enterEditMode(canvasElement);
await clickFirst(canvasElement, 'pipeline-row-expand');
await userEvent.click(await screen.findByText(/add processor/i));
await screen.findByText(/create new processor/i);
await userEvent.click(await screen.findByText('Grok'));
await userEvent.click(await screen.findByTitle('Severity Parser'));
await screen.findByText('Parse Severity Value From');
};

View File

@@ -9,6 +9,7 @@ import {
copyLogDetailsLink,
copyLogLinkFromRow,
dirtyQuickFiltersSettings,
openFormatMenu,
openLogContext,
openLogDetails,
openLogDetailsMenu,
@@ -82,6 +83,12 @@ 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 },
@@ -164,17 +171,6 @@ 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,6 +122,25 @@ 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

@@ -6,6 +6,7 @@ import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { kafkaDetailMocks } from './MQDetailPage.stories.mocks';
import { openCustomInterval } from './__story_mockdata__/kafkaDetail.play';
import MessagingQueuesMainPage from '../../MessagingQueuesMainPage';
@@ -98,6 +99,12 @@ 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: openCustomInterval,
};
/** The broker, producer, consumer and JVM metrics kafka itself reports. */
export const MetricView: Story = {
args: { view: MessagingQueuesViewTypeOptions.MetricPage },

View File

@@ -0,0 +1,37 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { MessagingQueuesViewTypeOptions } from 'pages/MessagingQueues/MessagingQueuesUtils';
import { screen, userEvent, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import type { kafkaDetailMocks } from '../MQDetailPage.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: PageStoryArgs<typeof kafkaDetailMocks>;
}
const untilLoaded = { timeout: 15_000 };
/** Only the drop rate view carries the evaluation interval selector. */
export const openCustomInterval = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.view !== MessagingQueuesViewTypeOptions.DropRate) {
return;
}
await userEvent.click(
await within(canvasElement).findByText('10ms', undefined, untilLoaded),
);
await screen.findByPlaceholderText(
'Enter custom time (ms)',
undefined,
untilLoaded,
);
};

View File

@@ -85,24 +85,6 @@ 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'] },
@@ -124,14 +106,3 @@ 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

@@ -8,6 +8,7 @@ import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import MetricsApplication from '../MetricsApplication';
import { metricsApplicationMocks } from './MetricsApplication.stories.mocks';
import { openApDexSettings } from './__story_mockdata__/metricsApplication.play';
type MetricsApplicationArgs = PageStoryArgs<typeof metricsApplicationMocks>;
@@ -76,3 +77,8 @@ export const DownloadMenu: Story = {
await screen.findByRole('menu');
},
};
/** The apdex threshold popover, opened from the overview's settings control. */
export const ApDexSettingsOpen: Story = {
play: openApDexSettings,
};

View File

@@ -0,0 +1,32 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, waitFor } from 'storybook/test';
interface PlayContext {
canvasElement: HTMLElement;
}
export const openApDexSettings = async ({
canvasElement,
}: PlayContext): 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,6 +613,22 @@ 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,
@@ -627,7 +643,7 @@ const ruleOf = (
labels: seed.labels,
// A rule takes about five minutes to take effect; until then the table
// badges it as pending.
active: !(pending && index % 4 === 0),
active: !isPendingRule(index, pending),
effectiveFrom: RULE_EFFECTIVE_FROM,
ingestedSeries: timeseries,
retainedSeries: Math.round(timeseries * (1 - seed.reduction)),

View File

@@ -4,13 +4,21 @@
*/
import { QueryParams } from 'constants/query';
import { FeatureKeys } from 'constants/features';
import ROUTES from 'constants/routes';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { rest } from 'msw';
import { ingestionKeysResponse } from 'pages/Settings/Ingestion/stories/__story_mockdata__/ingestion';
import { rolesListResponse } from 'pages/Settings/stories/__story_mockdata__/roles';
import { grantsAll } from '@/storybook/access/access';
import { choiceControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import {
isCloudShell,
shellFeatureActive,
} from '@/storybook/globals/appShellMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
const SOURCE = 'Onboarding · source';
const INVITES = 'Onboarding · invites';
@@ -48,6 +56,8 @@ export type SetupStep = (typeof SETUP_STEPS)[number];
export const INVITE_RESULTS = ['success', 'loading', 'error'] as const;
const INVITE_CUSTOM_ROLES = 0;
export type InviteResult = (typeof INVITE_RESULTS)[number];
export const onboardingV2Mocks = defineStoryMocks({
@@ -84,7 +94,12 @@ export const onboardingV2Mocks = defineStoryMocks({
// The header's invite modal offers the roles a new teammate can be given.
rest.get(
'http://localhost/api/v1/roles',
response.json(() => rolesListResponse(0)),
response.json(() => rolesListResponse(INVITE_CUSTOM_ROLES)),
),
// 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') {
@@ -115,3 +130,22 @@ export const onboardingV2Mocks = defineStoryMocks({
};
},
});
export type OnboardingV2Args = PageStoryArgs<typeof onboardingV2Mocks>;
/** Only a cloud workspace with chat support and without premium support is offered the card. */
export const offersAddCard = (args: OnboardingV2Args): boolean =>
isCloudShell(args) &&
shellFeatureActive(args, FeatureKeys.CHAT_SUPPORT) &&
!shellFeatureActive(args, FeatureKeys.PREMIUM_SUPPORT);
/** `AuthZButton` leaves Send Invites enabled when the check itself fails. */
export const canInvite = (args: OnboardingV2Args): boolean =>
args.authzState === 'error' || grantsAll(args, UserCreatePermission);
/** The roles dropdown lists what the roles endpoint answers, which State holds back or fails. */
export const offersRole = (args: OnboardingV2Args, role: string): boolean =>
args.dataState === 'loaded' &&
rolesListResponse(INVITE_CUSTOM_ROLES).data.some(
(listed) => listed.name === role,
);

View File

@@ -1,82 +1,20 @@
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 {
onboardingV2Mocks,
SETUP_STEPS,
type SetupStep,
} from './OnboardingPageV2.stories.mocks';
openAddCreditCard,
openInviteModal,
searchWithoutResults,
sendInvite,
walkToStep,
} from './__story_mockdata__/onboardingV2.play';
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' });
/**
@@ -89,16 +27,7 @@ const meta = {
title: 'Pages/Onboarding/Add Data Source',
tags: ['play'],
component: OnboardingPageV2,
/**
* 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);
},
play: walkToStep,
...pageStory,
parameters: { ...pageStory.parameters },
} satisfies Meta<OnboardingV2Args>;
@@ -137,35 +66,12 @@ export const SourcePreselected: Story = {
/** The one thing the header offers besides support: bringing the team along. */
export const InviteTeammate: Story = {
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);
},
play: openInviteModal,
};
/** A search nothing answers, where the catalogue offers to add the source instead. */
export const NoSearchResults: Story = {
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);
},
play: searchWithoutResults,
};
/**
@@ -174,48 +80,14 @@ export const NoSearchResults: Story = {
* is accepted; Invite result changes how it answers.
*/
export const InvitesSentToast: Story = {
play: async ({ mount, args, canvasElement }): 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(),
);
}
},
play: sendInvite,
};
/**
* 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,
};

View File

@@ -0,0 +1,223 @@
/**
* 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 {
canInvite,
offersAddCard,
offersRole,
type OnboardingV2Args,
SETUP_STEPS,
type SetupStep,
} from '../OnboardingPageV2.stories.mocks';
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,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
if (args.source !== 'catalogue') {
return;
}
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();
if (!canInvite(args) || !offersRole(args, 'viewer')) {
return;
}
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 },
);
}
};
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

@@ -9,6 +9,7 @@ import { rest } from 'msw';
import { choiceControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
const LINK = 'Reset password · link';
@@ -64,3 +65,9 @@ export const resetPasswordMocks = defineStoryMocks({
appContext: { isLoggedIn: false },
}),
});
export type ResetPasswordArgs = PageStoryArgs<typeof resetPasswordMocks>;
/** The form renders once the token verifies, which the State control can hold back or fail. */
export const showsResetForm = (args: ResetPasswordArgs): boolean =>
args.token === 'valid' && args.dataState === 'loaded';

View File

@@ -1,12 +1,13 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import ResetPassword from '../index';
import { resetPasswordMocks } from './ResetPassword.stories.mocks';
type ResetPasswordArgs = PageStoryArgs<typeof resetPasswordMocks>;
import {
type ResetPasswordArgs,
resetPasswordMocks,
} from './ResetPassword.stories.mocks';
import { showPasswordMismatch } from './__story_mockdata__/resetPassword.play';
const pageStory = storyMocks(resetPasswordMocks, { layout: 'app' });
@@ -35,3 +36,8 @@ 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: showPasswordMismatch,
};

View File

@@ -0,0 +1,36 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent } from 'storybook/test';
import {
type ResetPasswordArgs,
showsResetForm,
} from '../ResetPassword.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: ResetPasswordArgs;
}
export const showPasswordMismatch = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsResetForm(args)) {
return;
}
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,8 +46,3 @@ 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

@@ -4,11 +4,14 @@
*/
import ROUTES from 'constants/routes';
import { UserCreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/user.permissions';
import { rest } from 'msw';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
ACTIVE_MEMBER_MAX,
@@ -177,6 +180,17 @@ export const membersMocks = defineStoryMocks({
config: () => ({ route: ROUTES.MEMBERS_SETTINGS }),
});
export type MembersArgs = PageStoryArgs<typeof membersMocks>;
/** `AuthZButton` leaves Invite member enabled when the check itself fails. */
export const canInvite = (args: MembersArgs): boolean =>
args.authzState === 'error' || grantsAll(args, UserCreatePermission);
/** The roles dropdown lists what the roles endpoint answers, which State holds back or fails. */
export const offersRole = (args: MembersArgs, role: string): boolean =>
args.dataState === 'loaded' &&
rolesListResponse(args.roles).data.some((listed) => listed.name === role);
/** The table fetches before it renders a row, which outlasts the 1s default. */
export const MEMBERS_PAGE_SIZE = 20;
@@ -210,30 +224,8 @@ export const openMember = async (
await userEvent.click(cell.closest('tr') as HTMLElement);
};
/**
* 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 (
export const openInviteForm = async (
canvasElement: HTMLElement,
emails: string[],
): Promise<void> => {
await clickWhenEnabled(
await within(canvasElement).findByText(
@@ -242,6 +234,49 @@ export const sendInvites = 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,11 +15,13 @@ import {
openEditMember,
openFilterMenu,
openInviteForm,
openInviteRoles,
openPendingMember,
openRoleDropdown,
revokeInviteToast,
saveMemberName,
searchNoResults,
selectInviteRoles,
sendInvitesToast,
sendPartialInvitesToast,
} from './__story_mockdata__/members.play';
@@ -129,6 +131,16 @@ 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

@@ -8,11 +8,16 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
canInvite,
clickWhenEnabled,
closeRoles,
MEMBERS_PAGE_SIZE,
membersMocks,
offersRole,
openInviteRoleDropdown,
openMember,
openResetLink,
pickOpenRole,
sendInvites,
untilLoaded,
} from '../Members.stories.mocks';
@@ -150,7 +155,11 @@ export const openRoleDropdown = async ({
export const openInviteForm = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canInvite(args)) {
return;
}
await clickWhenEnabled(
await within(canvasElement).findByText(
/invite member/i,
@@ -162,10 +171,53 @@ export const openInviteForm = async ({
await screen.findAllByTestId(/^invite-email-/, undefined, untilLoaded);
};
export const openInviteRoles = async (context: PlayContext): Promise<void> => {
const { args } = context;
if (!canInvite(args) || !offersRole(args, 'viewer')) {
return;
}
await openInviteForm(context);
await openInviteRoleDropdown(0);
await screen.findAllByText('viewer', undefined, untilLoaded);
};
export const selectInviteRoles = async (
context: PlayContext,
): Promise<void> => {
const { args } = context;
const roles = ['viewer', 'editor', 'oncall-responder'].filter((role) =>
offersRole(args, role),
);
if (!canInvite(args) || roles.length === 0) {
return;
}
await openInviteForm(context);
await openInviteRoleDropdown(0);
for (const role of roles) {
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="${roles[roles.length - 1]}"]`,
),
).toBeVisible(),
untilLoaded,
);
};
export const sendInvitesToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canInvite(args) || !offersRole(args, 'viewer')) {
return;
}
await sendInvites(canvasElement, [
'bran@nightswatch.io',
'hodor@nightswatch.io',
@@ -181,6 +233,9 @@ export const sendPartialInvitesToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canInvite(args) || !offersRole(args, 'viewer')) {
return;
}
await sendInvites(canvasElement, [
'bran@nightswatch.io',
'hodor@blocked.example',

View File

@@ -5,13 +5,16 @@
import ROUTES from 'constants/routes';
import { rest } from 'msw';
import { componentPermission } from 'utils/permission';
import { accessFor } from '@/storybook/access/access';
import {
choiceControl,
countControl,
toggleControl,
} from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
AUTHN_PROVIDERS,
@@ -122,3 +125,18 @@ export const singleSignOnMocks = defineStoryMocks({
],
config: () => ({ route: ROUTES.ORG_SETTINGS }),
});
export type SingleSignOnArgs = PageStoryArgs<typeof singleSignOnMocks>;
/** The Settings page lists the organization tab for the admin role only. */
export const showsOrgSettings = (args: SingleSignOnArgs): boolean =>
componentPermission.current_org_settings.includes(
accessFor(args.access, args.permissions, args.revoked).legacyRole,
);
/** Rows come from the domains handler, which State can hold back or fail. */
export const listsDomains = (args: SingleSignOnArgs): boolean =>
showsOrgSettings(args) &&
args.dataState === 'loaded' &&
authDomainsResponse(args.domains, args.provider, args.enforced).data.length >
0;

View File

@@ -1,10 +1,20 @@
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';
@@ -30,23 +40,6 @@ 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.
@@ -75,88 +68,46 @@ export const SsoNotEnforced: Story = {
/** The form behind a domain's provider: what SigNoz sends the IdP and reads back. */
export const ConfigureDomain: Story = {
play: async ({ canvasElement }): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-configure');
await screen.findByText(/attribute mapping/i, undefined, untilLoaded);
},
play: openConfigureDomain,
};
/** Adding a domain: the provider chosen first decides the rest of the form. */
export const AddDomain: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'auth-domain-add',
undefined,
untilLoaded,
),
);
},
play: openAddDomain,
};
/** Interaction: adding a domain opens the real provider selector. */
export const ProviderSelectorOpen: Story = {
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,
);
},
play: openProviderSelector,
};
/** Interaction: advanced role mappings expand from a configured identity provider. */
export const RoleMappingsExpanded: Story = {
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);
},
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,
};
/** Validation: submitting a new provider without required fields leaves form errors visible. */
export const CreateDomainValidation: Story = {
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);
},
play: submitEmptyProvider,
};
/** What removing a domain warns about before its members lose SSO. */
export const DeleteDomain: Story = {
play: async ({ canvasElement }): Promise<void> => {
await clickFirst(canvasElement, 'auth-domain-delete');
await screen.findByTestId(
'auth-domain-delete-confirm',
undefined,
untilLoaded,
);
},
play: openDeleteDomain,
};
/**
@@ -164,22 +115,7 @@ export const DeleteDomain: Story = {
* update to `error` or `loading` to see the modal instead.
*/
export const DisplayNameUpdatedToast: Story = {
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());
}
},
play: updateDisplayName,
};
/**
@@ -187,19 +123,5 @@ export const DisplayNameUpdatedToast: Story = {
* `loading` to see the modal instead.
*/
export const DomainDeletedToast: Story = {
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(),
);
}
},
play: deleteDomain,
};

View File

@@ -0,0 +1,194 @@
/**
* 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 {
listsDomains,
showsOrgSettings,
type SingleSignOnArgs,
} from '../SingleSignOn.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: 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);
};
/** 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,
args,
}: PlayContext): Promise<void> => {
if (!listsDomains(args)) {
return;
}
await clickFirst(canvasElement, 'auth-domain-configure');
await screen.findByText(/role mapping \(advanced\)/i, undefined, untilLoaded);
};
export const openAddDomain = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsOrgSettings(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'auth-domain-add',
undefined,
untilLoaded,
),
);
};
export const openProviderSelector = async (
context: PlayContext,
): Promise<void> => {
if (!showsOrgSettings(context.args)) {
return;
}
await openAddDomain(context);
await screen.findByText(
/configure authentication method/i,
undefined,
untilLoaded,
);
};
export const expandRoleMappings = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsDomains(args)) {
return;
}
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> => {
if (!listsDomains(context.args)) {
return;
}
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> => {
if (!showsOrgSettings(context.args)) {
return;
}
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,
args,
}: PlayContext): Promise<void> => {
if (!listsDomains(args)) {
return;
}
await clickFirst(canvasElement, 'auth-domain-delete');
await screen.findByTestId(
'auth-domain-delete-confirm',
undefined,
untilLoaded,
);
};
export const updateDisplayName = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsOrgSettings(args)) {
return;
}
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> => {
if (!listsDomains(args)) {
return;
}
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

@@ -3,12 +3,22 @@
* Do not hand-edit: regenerate instead.
*/
import { FeatureKeys } from 'constants/features';
import ROUTES from 'constants/routes';
import { buildLicenseReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/license.permissions';
import { rest } from 'msw';
import type { TStatus } from 'types/api/settings/getRetention';
import { USER_ROLES } from 'types/roles';
import { accessFor, grantsAll } from '@/storybook/access/access';
import { choiceControl, toggleControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import {
isCloudShell,
shellFeatureActive,
shellLicense,
} from '@/storybook/globals/appShellMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
disksResponse,
@@ -100,6 +110,34 @@ 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 }),
});
export type WorkspaceArgs = PageStoryArgs<typeof workspaceMocks>;
/** The domain card only renders for an admin on cloud. */
export const showsDomainCard = (args: WorkspaceArgs): boolean =>
isCloudShell(args) &&
accessFor(args.access, args.permissions, args.revoked).legacyRole ===
USER_ROLES.ADMIN;
/** Contact Support, which the edit modal offers after a 409, needs the chat support flag. */
export const offersContactSupport = (args: WorkspaceArgs): boolean =>
showsDomainCard(args) && shellFeatureActive(args, FeatureKeys.CHAT_SUPPORT);
/** Only a plan without premium support is offered the modal over the chat widget. */
export const offersAddCard = (args: WorkspaceArgs): boolean =>
offersContactSupport(args) &&
!shellFeatureActive(args, FeatureKeys.PREMIUM_SUPPORT);
/** The key is fetched once `authz/check` has granted the read on the active license. */
export const showsLicenseKey = (args: WorkspaceArgs): boolean => {
const license = shellLicense(args);
return !!license && grantsAll(args, buildLicenseReadPermission(license.id));
};

View File

@@ -1,9 +1,14 @@
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';
@@ -61,16 +66,7 @@ export const NoColdStorage: Story = {
* of them is the active one.
*/
export const CustomDomainMenu: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByTestId(
'custom-domain-menu-trigger',
{},
{ timeout: 10000 },
),
);
await screen.findByRole('menu');
},
play: openCustomDomainMenu,
};
/**
@@ -79,38 +75,21 @@ export const CustomDomainMenu: Story = {
* instead.
*/
export const CustomDomainUpdatedToast: Story = {
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(),
);
}
},
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,
};
/** The license key copied: the toast confirming it. */
export const LicenseKeyCopiedToast: Story = {
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);
},
play: copyLicenseKey,
};

View File

@@ -0,0 +1,116 @@
/**
* 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 {
offersAddCard,
offersContactSupport,
showsDomainCard,
showsLicenseKey,
type WorkspaceArgs,
} from '../Workspace.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: WorkspaceArgs;
}
const untilLoaded = { timeout: 10000 };
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,
args,
}: PlayContext): Promise<void> => {
if (!showsDomainCard(args)) {
return;
}
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> => {
if (!showsDomainCard(args)) {
return;
}
await submitNewSubdomain(canvasElement);
if (args.domainUpdate === 'success') {
await waitFor(() =>
expect(screen.getByText(/workspace url is being updated/i)).toBeVisible(),
);
}
};
export const copyLicenseKey = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsLicenseKey(args)) {
return;
}
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 (!showsDomainCard(args)) {
return;
}
await submitNewSubdomain(canvasElement);
if (args.domainUpdate !== 'error' || !offersContactSupport(args)) {
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 (offersAddCard(args)) {
await screen.findByRole(
'dialog',
{ name: /Add Credit Card for Chat Support/i },
untilLoaded,
);
}
};

View File

@@ -21,6 +21,7 @@ import {
toggleControl,
} from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
fieldKeysResponse,
fieldValuesResponse,
@@ -32,6 +33,8 @@ 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,
@@ -41,11 +44,13 @@ import {
spanMatchRows,
spanPercentilesResponse,
STORY_TRACE_ID,
threadSpanCount,
traceAggregationsResponse,
traceDetailFieldKeys,
traceDetailFieldValues,
traceFlamegraphResponse,
traceSummaryResponse,
traceThreadResponse,
TRACE_SCENARIOS,
type TraceScenario,
traceWaterfallResponse,
@@ -60,6 +65,8 @@ 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,
@@ -125,6 +132,13 @@ 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:
@@ -207,6 +221,11 @@ 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)),
@@ -221,6 +240,11 @@ 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),
@@ -306,19 +330,60 @@ export const traceDetailsMocks = defineStoryMocks({
),
];
},
config: (values) => ({
route: values.spanPanel
? `/trace/${STORY_TRACE_ID}?spanId=${spanIdAt(focusSpanIndex(values.scenario, values.spans))}`
: `/trace/${STORY_TRACE_ID}`,
}),
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}`,
};
},
effect: (values) => {
set(LOCALSTORAGE.TRACE_DETAILS_SPAN_DETAILS_POSITION, values.panelPosition);
},
});
export type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
/** The waterfall renders once the trace resolves, which outlasts the 1s default. */
export const untilLoaded = { timeout: 15_000 };
/** The header actions and the span rows are the overview tab's, once a trace loads. */
export const showsTrace = ({
tab,
spans,
dataState,
}: Pick<TraceDetailsArgs, 'tab' | 'spans' | 'dataState'>): boolean =>
tab === TraceDetailsTab.Overview && spans > 0 && dataState === 'loaded';
/** The thread lists the spans that carry messages, which only the AI scenario has. */
export const listsThread = ({
tab,
scenario,
spans,
dataState,
}: Pick<
TraceDetailsArgs,
'tab' | 'scenario' | 'spans' | 'dataState'
>): boolean =>
tab === TraceDetailsTab.Thread &&
dataState === 'loaded' &&
threadSpanCount(scenario, spans) > 0;
/** Opens the pretty view's action menu on the first row that offers `item`. */
export const openRowMenu = async (
canvasElement: HTMLElement,

View File

@@ -18,12 +18,20 @@ import {
scenarioSpanCount,
spanIdAt,
} from './__story_mockdata__/traceDetails';
import {
openAddSpanToFunnel,
openAnalytics,
openCreateFunnelStep,
showsAiThread,
showsDownloadPanel,
} from './__story_mockdata__/traceDetails.play';
import {
openRowMenu,
startDownload,
traceDetailsMocks,
untilLoaded,
} from './TraceDetailsV3.stories.mocks';
import { TraceDetailsTab } from '../constants';
import TraceDetailsV3 from '../index';
type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
@@ -119,6 +127,16 @@ 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: showsAiThread,
};
/**
* Turns on Highlight errors, which writes `has_error = true` into the filter and
* expands the bar to show it.
@@ -248,6 +266,27 @@ export const SpanPercentileOpen: Story = {
},
};
/** The analytics panel the header toggle opens. */
export const AnalyticsOpen: Story = {
play: openAnalytics,
};
/** The download progress panel, held open by an export that never answers. */
export const TraceDownload: Story = {
args: { exportState: 'loading' },
play: showsDownloadPanel,
};
/** The funnel picker a span row's add-to-funnel action opens. */
export const AddSpanToFunnel: Story = {
play: openAddSpanToFunnel,
};
/** The name field behind "Create new funnel" in that picker. */
export const AddSpanToFunnelCreateStep: Story = {
play: openCreateFunnelStep,
};
/** 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

@@ -0,0 +1,129 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { fireEvent, screen, userEvent, within } from 'storybook/test';
import { TraceDetailsTab } from '../../constants';
import {
listsThread,
showsTrace,
startDownload,
type TraceDetailsArgs,
untilLoaded,
} from '../TraceDetailsV3.stories.mocks';
interface PlayContext {
args: Pick<TraceDetailsArgs, 'missingSpans' | 'tab' | 'dataState'>;
}
interface PageContext {
canvasElement: HTMLElement;
args: TraceDetailsArgs;
}
/** 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,
);
};
export const showsAiThread = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!listsThread(args)) {
return;
}
await within(canvasElement).findAllByText(
/Let me check the upgrade notes/,
undefined,
untilLoaded,
);
};
export const openAnalytics = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Analytics' },
untilLoaded,
),
);
await screen.findByTestId('trace-analytics-panel', undefined, untilLoaded);
};
export const showsDownloadPanel = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await startDownload(canvasElement);
// Only an export that never answers keeps the panel up.
if (args.exportState === 'loading') {
await screen.findByTestId('trace-download-panel', undefined, untilLoaded);
}
};
const openFunnelPicker = 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);
};
export const openAddSpanToFunnel = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await openFunnelPicker(canvasElement);
};
export const openCreateFunnelStep = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await openFunnelPicker(canvasElement);
await userEvent.click(
await screen.findByRole('button', { name: /create new funnel/i }),
);
await screen.findByTestId('create-funnel-name-input');
};

View File

@@ -4,12 +4,16 @@
*/
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';
@@ -28,8 +32,26 @@ 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[] = [
{
@@ -182,6 +204,28 @@ 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',
@@ -202,6 +246,52 @@ 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',
@@ -247,6 +337,39 @@ 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.',
},
],
},
],
},
},
];
@@ -426,6 +549,50 @@ 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),
},
});
export const threadSpanCount = (
scenario: TraceScenario,
spans: number,
): number =>
traceThreadResponse({ scenario, spans, errors: false, traceStart: 0 }).data
.spans.length;
/**
* `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

@@ -10,8 +10,10 @@ import { USER_PREFERENCES } from 'constants/userPreferences';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { spanPercentilesResponse } from 'pages/TraceDetailsV3/stories/__story_mockdata__/traceDetails';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import { USER_ROLES } from 'types/roles';
import { explorerViewToPanelType } from 'utils/explorerUtils';
import { accessFor } from '@/storybook/access/access';
import {
choiceControl,
countControl,
@@ -29,6 +31,7 @@ import {
import {
exportDashboardsResponse,
ORDERS_SPAN_ROWS,
savedTraceViewsResponse,
SPAN_LOGS_STATES,
spanLogRows,
@@ -357,3 +360,50 @@ export const tracesMocks = defineStoryMocks({
});
export type TracesArgs = PageStoryArgs<typeof tracesMocks>;
/** The span drawer opens from a row of the spans list, so no other view has one. */
export const listsOrdersSpan = (args: TracesArgs): boolean =>
args.tab === 'explorer' &&
args.view === ExplorerViews.LIST &&
args.dataState === 'loaded' &&
args.spans >= ORDERS_SPAN_ROWS;
/** What the drawer's Logs tab settles on, from the two controls that decide it. */
export type DrawerLogs =
| 'waiting'
| 'error'
| 'logs'
| 'trace-only'
| 'none'
| 'span-empty';
export const drawerLogsOf = ({
spanLogs,
traceSummary,
}: Pick<TracesArgs, 'spanLogs' | 'traceSummary'>): DrawerLogs => {
if (traceSummary === 'loading' || spanLogs === 'loading') {
return 'waiting';
}
if (spanLogs === 'error') {
return 'error';
}
if (spanLogs === 'span') {
return 'logs';
}
// Without the trace bounds the drawer never checks the trace's own logs.
if (traceSummary === 'not found') {
return 'span-empty';
}
return spanLogs === 'trace only' ? 'trace-only' : 'none';
};
/** `hasEditPermission`, which every funnel action gates on. */
export const canEditFunnels = (args: TracesArgs): boolean => {
const { legacyRole } = accessFor(args.access, args.permissions, args.revoked);
return legacyRole === USER_ROLES.ADMIN || legacyRole === USER_ROLES.EDITOR;
};

View File

@@ -7,7 +7,9 @@ import { type TracesArgs, tracesMocks } from './TracesModulePage.stories.mocks';
import {
dirtyQuickFiltersSettings,
loadNextListPage,
openCreateFunnel,
openQuickFiltersSettings,
openRenameFunnel,
showRootSpansNextPage,
suggestBooleanValues,
suggestFilterKeys,
@@ -82,6 +84,18 @@ 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
@@ -118,17 +132,6 @@ 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

@@ -0,0 +1,227 @@
/**
* 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 {
drawerLogsOf,
listsOrdersSpan,
type TracesArgs,
} from '../TracesModulePage.stories.mocks';
import { ORDERS_OPERATION } from './traces';
interface PlayContext {
args: TracesArgs;
}
interface MountContext extends PlayContext {
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(ORDERS_OPERATION));
await expect(match).toBeDefined();
return match as HTMLElement;
}, untilLoaded);
const openDrawer = async (): Promise<HTMLElement> => {
const row = await findOrdersRow();
await userEvent.click(within(row).getByText(ORDERS_OPERATION));
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;
};
/** Mounts, then opens the Logs tab, unless the list has no span to open it on. */
const mountOnLogsTab = async (
mount: MountContext['mount'],
args: TracesArgs,
): Promise<HTMLElement | null> => {
await mount();
return listsOrdersSpan(args) ? openLogsTab() : null;
};
export const showsSpanDetails = async ({
args,
}: PlayContext): Promise<void> => {
if (!listsOrdersSpan(args)) {
return;
}
const drawer = await openDrawer();
// The percentage is read off the trace summary.
if (args.traceSummary === 'found') {
await expect(
await within(drawer).findByText(
/of total exec time/,
undefined,
untilLoaded,
),
).toBeVisible();
}
};
export const openSpanDetails = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
await showsSpanDetails({ args });
};
export const hoverOrdersRow = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
if (!listsOrdersSpan(args)) {
return;
}
await userEvent.hover(await findOrdersRow());
await expect(await screen.findByTestId('span-row-open-trace')).toBeVisible();
};
export const showsSpanLogs = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'logs') {
return;
}
await expect(
(
await within(drawer).findAllByText(
/payment provider timed out/,
undefined,
untilLoaded,
)
)[0],
).toBeVisible();
};
export const showsTraceOnlyLogs = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'trace-only') {
return;
}
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,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'none') {
return;
}
await expect(
await within(drawer).findByText(
'No logs found for this trace.',
undefined,
untilLoaded,
),
).toBeVisible();
};
export const showsWithoutTraceSummary = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer) {
return;
}
if (drawerLogsOf(args) === 'span-empty') {
await expect(
await within(drawer).findByText(
'No logs found for this span.',
undefined,
untilLoaded,
),
).toBeVisible();
}
if (args.traceSummary === 'not found') {
await expect(
within(drawer).queryByText(/of total exec time/),
).not.toBeInTheDocument();
}
};
export const showsTraceSummaryLoading = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || args.traceSummary !== 'loading') {
return;
}
await expect(
await screen.findByTestId('open-in-explorer-button'),
).toHaveAttribute('aria-disabled', 'true');
};
export const showsLogsError = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'error') {
return;
}
await expect(
await within(drawer).findByText(
/Something went wrong/,
undefined,
untilLoaded,
),
).toBeVisible();
};

View File

@@ -15,7 +15,10 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import type { TracesArgs } from '../TracesModulePage.stories.mocks';
import {
canEditFunnels,
type TracesArgs,
} from '../TracesModulePage.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
@@ -189,3 +192,53 @@ export const showFilterSyntaxError = async ({
await showFilterErrors(canvasElement, 'has_error = true AND');
};
export const openCreateFunnel = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.tab !== 'funnels' || !canEditFunnels(args)) {
return;
}
// With no funnels the empty state offers the same button beside the header's.
const [newFunnel] = await within(canvasElement).findAllByRole(
'button',
{ name: /new funnel/i },
untilLoaded,
);
await userEvent.click(newFunnel);
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 ||
args.dataState !== 'loaded' ||
!canEditFunnels(args)
) {
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

@@ -108,6 +108,12 @@ const SPANS: SpanShape[] = [
},
];
export const ORDERS_OPERATION = 'POST /api/orders';
/** Rows the list needs before the span the drawer stories open is on it. */
export const ORDERS_SPAN_ROWS =
SPANS.findIndex(({ operation }) => operation === ORDERS_OPERATION) + 1;
const TRACE_SERVICE_NAMES = SPANS.map(({ service }) => service);
const hex = (prefix: string, index: number): string =>

View File

@@ -1,10 +1,18 @@
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';
@@ -31,55 +39,12 @@ 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: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openDrawer();
await expect(
await within(drawer).findByText(
/of total exec time/,
undefined,
untilLoaded,
),
).toBeVisible();
},
play: openSpanDetails,
};
/**
@@ -87,65 +52,25 @@ export const Default: Story = {
* tab, without opening the drawer.
*/
export const OpenTraceIcon: Story = {
play: async ({ mount }): Promise<void> => {
await mount();
await userEvent.hover(await findOrdersRow());
await expect(await screen.findByTestId('span-row-open-trace')).toBeVisible();
},
play: hoverOrdersRow,
};
/** The Logs tab with the span's logs, between the logs just before and after them. */
export const Logs: Story = {
args: { spanLogs: 'span' },
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();
},
play: showsSpanLogs,
};
/** 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: 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();
},
play: showsTraceOnlyLogs,
};
/** Neither the span nor its trace has logs. */
export const NoLogs: Story = {
args: { spanLogs: 'none' },
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();
},
play: showsNoLogs,
};
/**
@@ -156,34 +81,13 @@ export const WithoutTraceSummary: Story = {
args: { traceSummary: 'not found', spanLogs: 'none' },
// The deliberate 404 is the state under test.
parameters: { allowConsoleErrors: true },
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();
},
play: showsWithoutTraceSummary,
};
/** The trace summary never answers: the Logs tab waits and its explorer link is off. */
export const TraceSummaryLoading: Story = {
args: { traceSummary: 'loading' },
play: async ({ mount }): Promise<void> => {
await mount();
await openLogsTab();
await expect(
await screen.findByTestId('open-in-explorer-button'),
).toHaveAttribute('aria-disabled', 'true');
},
play: showsTraceSummaryLoading,
};
/** The log queries fail while the rest of the drawer renders. */
@@ -191,16 +95,5 @@ export const LogsError: Story = {
args: { spanLogs: 'error' },
// The deliberate 500 is the state under test.
parameters: { allowConsoleErrors: true },
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
/Something went wrong/,
undefined,
untilLoaded,
),
).toBeVisible();
},
play: showsLogsError,
};

View File

@@ -0,0 +1,153 @@
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

@@ -0,0 +1,176 @@
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

@@ -0,0 +1,93 @@
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

@@ -0,0 +1,90 @@
/**
* 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,
shellLicense,
} from '@/storybook/globals/appShellMocks';
type Banner = AppShellArgs['banner'];
type ShellArgs = Pick<AppShellArgs, 'banner' | 'license'>;
interface PlayContext {
args: ShellArgs;
}
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;
}
// The trial banner needs a license to read, which unlicensed deployments lack.
if (args.banner === 'trial-expiry' && !shellLicense(args)) {
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

@@ -0,0 +1,41 @@
/**
* 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';
type HostArgs = Pick<AppShellArgs, 'banner' | 'license'>;
interface HostPlayContext<TArgs extends HostArgs> {
mount: () => Promise<unknown>;
args: TArgs;
canvasElement: HTMLElement;
}
type OpenOverlay<TArgs extends HostArgs> = (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 HostArgs>(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

@@ -0,0 +1,173 @@
/**
* 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 { isCloudShell, shellLicense } from '@/storybook/globals/appShellMocks';
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';
import { LicensePlatform, LicenseState } from 'types/api/licensesV3/getActive';
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 };
const offersCancelSubscription = (
args: Pick<GlobalMockArgs, 'license' | 'banner'>,
): boolean => {
const license = shellLicense(args);
return (
license?.platform === LicensePlatform.CLOUD &&
license.state === LicenseState.ACTIVATED
);
};
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 (!offersCancelSubscription(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) => isCloudShell(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,18 +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,
openNozPanel,
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
@@ -54,14 +54,7 @@ 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: 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,
});
},
play: openAddCardModal,
};
/**
@@ -75,20 +68,7 @@ export const NozAwaitingYou: Story = {
/** The Noz chat opened from Ask Noz, floating above the strip; its header drags it. */
export const NozPanel: Story = {
args: { noz: true, support: 'pylon' },
play: async ({ args }): Promise<void> => {
// Ask Noz is not rendered with Noz off, so there is no panel to open.
if (!args.noz) {
return;
}
await userEvent.click(
await screen.findByTestId(
'bottom-strip-ask-noz-button',
undefined,
untilLoaded,
),
);
await screen.findByTestId('ai-assistant-panel-close');
},
play: openNozPanel,
};
/** Every tooltip the strip carries, held open. */
@@ -96,12 +76,6 @@ 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

@@ -1,7 +1,18 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { withCanvas } from '../decorators/withCanvas';
import {
closesConfirmationOnEscape,
showsActionableErrorToast,
showsDangerWithDescription,
showsInfoToast,
showsLongMultilineToast,
showsPromiseErrorToast,
showsPromiseLoadingToast,
showsSuccessToast,
showsToastOverConfirmation,
showsWarningToast,
} from './__story_mockdata__/feedback.play';
import FeedbackFixture from './FeedbackFixture';
const meta = {
@@ -18,50 +29,49 @@ type Story = StoryObj<typeof meta>;
/** Mutation: persistent success feedback from the application toaster. */
export const SuccessToast: Story = {
args: { state: 'success-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await screen.findByText('Retention policy updated successfully');
await waitFor(() =>
expect(
screen.getByText('Retention policy updated successfully'),
).toBeVisible(),
);
},
play: showsSuccessToast,
};
/** Mutation: an actionable error notification that exposes its retry control. */
export const ActionableErrorToast: Story = {
args: { state: 'actionable-error-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await screen.findByText('Failed to save the notification channel');
await waitFor(() =>
expect(
screen.getByText('Failed to save the notification channel'),
).toBeVisible(),
);
await screen.findByRole('button', { name: 'Retry' });
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Retry' })).toBeVisible(),
);
},
play: showsActionableErrorToast,
};
/** Density: a long notification validates wrapping and multi-line toast sizing. */
export const LongMultilineToast: Story = {
args: { state: 'long-toast' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
await expect(
await screen.findByText(/could not apply the retention policy/i),
).toBeVisible();
},
play: showsLongMultilineToast,
};
/** A request still in flight: the loading toast stays until the promise settles. */
export const PromiseLoadingToast: Story = {
args: { state: 'promise-loading-toast' },
play: showsPromiseLoadingToast,
};
/** A failed request: the rejected toast keeps a Dismiss action, stacked top-center. */
export const PromiseErrorToast: Story = {
args: { state: 'promise-error-toast' },
play: showsPromiseErrorToast,
};
/** A warning that stays up, matching invites that only partly succeed. */
export const WarningToast: Story = {
args: { state: 'warning-toast' },
play: showsWarningToast,
};
/** An info toast pinned to the bottom-right stack, as export cancellation does. */
export const InfoToast: Story = {
args: { state: 'info-toast' },
play: showsInfoToast,
};
/** An error toast with a description and a Dismiss action, bottom-right. */
export const DangerWithDescription: Story = {
args: { state: 'danger-description-toast' },
play: showsDangerWithDescription,
};
/** Mutation: the inline application alert preserves its action affordance. */
@@ -76,38 +86,11 @@ export const InlineAlert: Story = {
*/
export const Confirmation: Story = {
args: { state: 'confirmation' },
play: async ({ canvasElement }): Promise<void> => {
const trigger = within(canvasElement).getByTestId(
'open-feedback-confirmation',
);
await userEvent.click(trigger);
await screen.findByRole('dialog', { name: 'Delete environment' });
await userEvent.keyboard('{Escape}');
// Escape can close the dialog before the assertion runs, which
// `waitForElementToBeRemoved` treats as an error rather than a pass.
await waitFor(() =>
expect(
screen.queryByRole('dialog', { name: 'Delete environment' }),
).not.toBeInTheDocument(),
);
},
play: closesConfirmationOnEscape,
};
/** Interaction: an error toast remains visible above an open destructive confirmation. */
export const ToastOverConfirmation: Story = {
args: { state: 'toast-over-confirmation' },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('open-feedback-confirmation'),
);
await screen.findByRole('dialog', { name: 'Delete environment' });
await userEvent.click(
await screen.findByRole('button', { name: 'Show error notification' }),
);
await expect(
await screen.findByText(/could not apply the retention policy/i),
).toBeVisible();
},
play: showsToastOverConfirmation,
};

View File

@@ -10,6 +10,11 @@ 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';
@@ -21,6 +26,10 @@ 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);
@@ -37,13 +46,62 @@ 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 === 'long-toast' ||
state === 'promise-loading-toast' ||
state === 'promise-error-toast' ||
state === 'warning-toast' ||
state === 'info-toast' ||
state === 'danger-description-toast';
const confirmationTitle = 'Delete environment';
return (

View File

@@ -0,0 +1,57 @@
/**
* 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';
import type { GlobalMockArgs } from '@/storybook/globals';
import { isCloudShell } from '@/storybook/globals/appShellMocks';
/** The shell renders its entry points after the global config and the license settle. */
const untilLoaded = { timeout: 10_000 };
/** Support offers the modal only to a cloud workspace that has no premium support. */
export const openAddCardModal = async ({
args,
}: {
args: Pick<GlobalMockArgs, 'support' | 'license' | 'banner'>;
}): Promise<void> => {
if (args.support !== 'add-card' || !isCloudShell(args)) {
return;
}
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);
};
/** Ask Noz is not rendered with Noz off, so there is no panel to open. */
export const openNozPanel = async ({
args,
}: {
args: { noz: boolean };
}): Promise<void> => {
if (!args.noz) {
return;
}
await userEvent.click(
await screen.findByTestId(
'bottom-strip-ask-noz-button',
undefined,
untilLoaded,
),
);
await screen.findByTestId('ai-assistant-panel-close');
};

View File

@@ -0,0 +1,183 @@
/**
* 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 { FeedbackState } from '../FeedbackFixture';
interface PlayContext {
canvasElement: HTMLElement;
args: { state: FeedbackState };
}
const showFeedback = async (canvasElement: HTMLElement): Promise<void> => {
await userEvent.click(
within(canvasElement).getByTestId('show-feedback-toast'),
);
};
export const showsSuccessToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'success-toast') {
return;
}
await showFeedback(canvasElement);
await screen.findByText('Retention policy updated successfully');
await waitFor(() =>
expect(
screen.getByText('Retention policy updated successfully'),
).toBeVisible(),
);
};
export const showsActionableErrorToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'actionable-error-toast') {
return;
}
await showFeedback(canvasElement);
await screen.findByText('Failed to save the notification channel');
await waitFor(() =>
expect(
screen.getByText('Failed to save the notification channel'),
).toBeVisible(),
);
await screen.findByRole('button', { name: 'Retry' });
await waitFor(() =>
expect(screen.getByRole('button', { name: 'Retry' })).toBeVisible(),
);
};
export const showsLongMultilineToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'long-toast') {
return;
}
await showFeedback(canvasElement);
await expect(
await screen.findByText(/could not apply the retention policy/i),
).toBeVisible();
};
export const showsPromiseLoadingToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'promise-loading-toast') {
return;
}
await showFeedback(canvasElement);
await expect(await screen.findByText('Enabling the alert rule')).toBeVisible();
};
export const showsPromiseErrorToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'promise-error-toast') {
return;
}
await showFeedback(canvasElement);
await expect(
await screen.findByText('Could not clone the panel'),
).toBeVisible();
await screen.findByRole('button', { name: 'Dismiss' });
};
export const showsWarningToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'warning-toast') {
return;
}
await showFeedback(canvasElement);
await expect(await screen.findByText('Some invites failed')).toBeVisible();
};
export const showsInfoToast = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'info-toast') {
return;
}
await showFeedback(canvasElement);
await expect(await screen.findByText('Export cancelled')).toBeVisible();
};
export const showsDangerWithDescription = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'danger-description-toast') {
return;
}
await showFeedback(canvasElement);
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' });
};
export const closesConfirmationOnEscape = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'confirmation') {
return;
}
const trigger = within(canvasElement).getByTestId(
'open-feedback-confirmation',
);
await userEvent.click(trigger);
await screen.findByRole('dialog', { name: 'Delete environment' });
await userEvent.keyboard('{Escape}');
// Escape can close the dialog before the assertion runs, which
// `waitForElementToBeRemoved` treats as an error rather than a pass.
await waitFor(() =>
expect(
screen.queryByRole('dialog', { name: 'Delete environment' }),
).not.toBeInTheDocument(),
);
};
export const showsToastOverConfirmation = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.state !== 'toast-over-confirmation') {
return;
}
await userEvent.click(
within(canvasElement).getByTestId('open-feedback-confirmation'),
);
await screen.findByRole('dialog', { name: 'Delete environment' });
await userEvent.click(
await screen.findByRole('button', { name: 'Show error notification' }),
);
await expect(
await screen.findByText(/could not apply the retention policy/i),
).toBeVisible();
};

View File

@@ -2,7 +2,10 @@ import { StatusCodes } from 'http-status-codes';
import { FeatureKeys } from 'constants/features';
import { USER_PREFERENCES } from 'constants/userPreferences';
import type { IAppContext } from 'providers/App/types';
import { createAppContextMock } from 'tests/fixtures/appContextMock';
import {
createAppContextMock,
defaultFeatureFlags,
} from 'tests/fixtures/appContextMock';
import APIError from 'types/api/error';
import type { FeatureFlagProps } from 'types/api/features/getFeaturesFlags';
import {
@@ -39,6 +42,11 @@ 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;
@@ -153,56 +161,76 @@ 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 {
trialInfo: {
...baseTrialInfo,
onTrial: true,
trialStart: nowInSeconds - 27 * DAY_IN_SECONDS,
trialEnd: nowInSeconds + 3 * DAY_IN_SECONDS,
workSpaceBlock: false,
trialConvertedToSubscription: false,
gracePeriodEnd: -1,
},
};
return trialExpiryContext();
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(),
},
}));
return licensedBanner(activeLicense, withPaymentFailed);
// 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,
}));
case 'license-expired-with-trial':
return {
...trialExpiryContext(),
...licensedBanner(activeLicense, withRestricted(LicenseState.EXPIRED)),
};
case 'license-terminated':
return licensedBanner(activeLicense, (license) => ({
...license,
platform: LicensePlatform.SELF_HOSTED,
state: LicenseState.TERMINATED,
}));
case 'license-expired-with-payment-failed':
return licensedBanner(activeLicense, (license) =>
withRestricted(LicenseState.EXPIRED)(withPaymentFailed(license)),
);
default:
return {};
default: {
const state = RESTRICTED_STATES[banner];
return state ? licensedBanner(activeLicense, withRestricted(state)) : {};
}
}
};
@@ -254,7 +282,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.',
'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.',
options: BANNERS,
value: 'none',
}),
@@ -302,3 +330,24 @@ export const appShellMocks = defineStoryMocks({
});
export type AppShellArgs = StoryMockArgs<typeof appShellMocks>;
type ShellArgs = Parameters<typeof appShellMocks.read>[0];
const shellContext = (args: ShellArgs): Partial<IAppContext> | undefined =>
appShellMocks.config?.(appShellMocks.read(args)).appContext;
/** A restricted-license banner swaps the cloud license for a self-hosted one. */
export const shellLicense = (
args: ShellArgs,
): LicenseResModel | null | undefined => shellContext(args)?.activeLicense;
export const isCloudShell = (args: ShellArgs): boolean =>
shellLicense(args)?.platform === LicensePlatform.CLOUD;
export const shellFeatureActive = (
args: ShellArgs,
name: FeatureKeys,
): boolean =>
(shellContext(args)?.featureFlags ?? defaultFeatureFlags).some(
(flag) => flag.name === name && flag.active,
);