SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(storybook): add stories for each existing page (#12734)
Vinicius Lourençoccb6ef68c187
diff --git a/.claude/skills/signoz-page-story/SKILL.md b/.claude/skills/signoz-page-story/SKILL.mdindex c157cf8e0b..ab7c9f0280 100644--- a/.claude/skills/signoz-page-story/SKILL.md+++ b/.claude/skills/signoz-page-story/SKILL.md@@ -26,6 +26,135 @@ process on top of it.5. **Verify in the browser**: [references/verify.md](references/verify.md). Neverreport the story as done without it.+## Where it lands in the sidebar++The sidebar mirrors the app's own side nav (`container/SideNav/menuItems.tsx`), so+a page sits where someone would click it in the product. Four things decide that,+and all four are part of writing the story, not a follow-up.++**Title.** `Pages/<Area>/<Page>`, where `<Area>` is the nav section and `<Page>`+is the label the nav gives it.++- The leaf is the product's label, never the component's name: `MetricsExplorer`+ is `Metrics/Explorer`, `MeterExplorer` is `Metering/Cost Meter`,+ `AIAssistantPage` is `Noz`.+- Never repeat the area in the leaf: `Alerts/Rules`, not `Alerts/AlertRules`.+- A leaf never shares its name with a sibling folder. The folder wins and the+ page becomes `List`, or `Overview` for a tab strip: `Services/List` beside+ `Services/Detail`.+- Title Case with spaces. No camelCase, no kebab.+- Four levels is the floor to stay under: `Pages/Alerts/Channels/New` is as deep+ as it goes.+- Pages nobody navigates to on purpose go under `Pages/System` (`Status`,+ `Unauthorized`, `Workspace Locked`), and the pre-session pages under+ `Pages/Auth`.+- A page whose permission stories earn their own folder becomes one:+ `Pages/Settings/Billing/Overview` beside `Pages/Settings/Billing/Authz`. See+ **Permission stories** below.++**Order.** The `storySort.order` literal in `.storybook/preview.tsx` carries the+order for every level. A new page in an existing area is appended to that area's+array, in the order the product lists it; a new area goes where the side nav+puts it. Storybook parses the order out of the file statically, so it has to+stay an inline literal. Missing entries fall to the end of their level rather+than disappearing, so a forgotten edit is a page at the bottom of its area, not+a broken sidebar.++**Tags.** Declared on the meta, right under `title`, and what the sidebar's tag+filter answers questions with. Only these:++| Tag | When |+| --- | --- |+| `authz` | The page gates UI on permission checks through `lib/authz` (`AuthZButton`, `AuthZGuard`, `useAuthZ`). Both the page's file and its `Authz` file carry it. |+| `role-gated` | The page still branches on the legacy role (`user.role`, `hasEditPermission`) and has no authz check. |+| `beta` | `isBeta` on its nav entry. Drop the tag when the product drops the badge. |+| `legacy` | Superseded by another page but still routed. The doc comment names the page to start from instead. |+| `play` | The story file has a `play` function, so at least one state is reached by an interaction. |++`autodocs` comes from `preview.tsx` and is never written on a meta.++**Doc comment on the meta.** What the page is, in the page's own terms, then a+blank line, then the route:++```tsx+const pageStory = storyMocks(logsExplorerMocks, {+ route: explorerRoute('explorer'),+ layout: 'app',+});++/**+ * The logs explorer: the query builder, the list, the frequency chart and the log+ * detail drawer, with quick filters and saved views beside them.+ *+ * Route: `/logs/logs-explorer`.+ */+const meta = {+ title: 'Pages/Logs/Explorer',+ tags: ['play'],+ component: LogsModulePage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<LogsExplorerArgs>;+```++The `pageStory` const and the trailing `parameters` line are what make the doc+comment safe. The comment compiles to a `parameters` property that the csf plugin+appends after the spread, so a meta that spreads `storyMocks(...)` and stops+there loses `parameters.signoz` and renders the page against the global handlers+alone: every one of the page's endpoints misses. Restating `parameters` as a+literal gives the plugin something to merge into. `resolveStory` logs the+combination that says it happened, so the console names it rather than leaving it+to be found by reading the page.++It is the description on the page's Docs page, which is the only place a reader+who is not in the code finds out what the page is for. Two or three sentences:+what it shows, what drives it, and the gating worth knowing about (`Gated on+authz permissions`, `follows the legacy editor role`). A control-driven route+says so instead of a path: ``Route: `/metrics-explorer/*`, the tab control picks+which``.++## Permission stories++A page that gates UI on `lib/authz` keeps its permission states in a folder of+their own, so the page's own file stays about the page and the sidebar answers+"what does this permission do" in one place.++**Layout.** A second story file at `stories/authz/<Page>.authz.stories.tsx`,+titled `Pages/<Area>/<Page>/Authz`, which turns the page into a folder: its own+file is retitled `Pages/<Area>/<Page>/Overview`, and `.storybook/preview.tsx`+gains the sub-order (`'Billing', ['Overview', 'Authz']`). Both files carry the+`authz` tag and share the page's one mocks module, which the authz file imports+as `../<Page>.stories.mocks`. It declares no controls and no mock data of its+own: a permission story that needs a new response is a control the page's mocks+were missing.++**One story per permission the page reads**, named for what is gone: `NoRead`,+`NoList`, `NoUpdate`, `NoCreate`, `NoDelete`. Then the combinations the page+itself distinguishes, and only those: `NoManage` where two permissions gate one+button, `ReadOnly` where everything but reading is denied, `NoSubscriptionAccess`+where none of the resource's permissions are held, and `CheckFailed` for+`authzState: 'error'`, which is the page's fail-open path rather than a denial.++**Revoke, never allow-list.** Each story is a full grant minus what its name+says: `args: { revoked: ['read:subscription'] }`. The `Revoked` control subtracts+from the preset, so the story stays "an admin missing one permission" as the+catalogue grows, and the diff against the page's `Default` is the one permission.+Rebuilding the allow-list by hand drifts the moment a resource is added.++**Never a role preset in this folder.** `access: 'viewer'` moves the legacy role,+the side nav and every other resource's permissions at the same time, so the+story no longer shows what its name claims. A persona is a story on the page's+own file, and only when the product has that persona.++**Pair the revocation with the state that renders the gated control.** A button+that only exists on a trial needs the plan too:+`args: { plan: 'on-trial', revoked: ['create:subscription'] }`. A permission+whose denial changes nothing on screen gets no story: say so in the PR.++Verify these by their disabled states, not their text. The page reads the same+either way, so a story that is wrong looks right: read `disabled` off the buttons+the permission gates, and check the denial callout is there or gone.+## Rules- **Default is the loaded page.** `export const Default: Story = {}` with no args,@@ -50,7 +179,29 @@ process on top of it.- **File layout**: every story file for a page lives under`src/pages/<Page>/stories/`: `<Page>.stories.tsx`, `<Page>.stories.mocks.tsx`,payload builders in `stories/__story_mockdata__/<page>.ts`. Nothing- page-specific in `src/storybook/controls/`.+ page-specific in `src/storybook/controls/`. A page that is a tab strip over+ several routes gets one story file per tab, in its own folder under the module+ page (`LogsModulePage/Pipelines/stories/Pipelines.stories.tsx`), each with its+ own mocks and `__story_mockdata__/`; the builders more than one tab needs stay+ in the module page's own `stories/__story_mockdata__/`+ (`AlertList/stories/__story_mockdata__/alerts.ts`), which a tab reaches as+ `../../stories/__story_mockdata__/alerts`. Every one of them renders the module page, so the tab+ strip is there, and the `route` its mocks return decides which tab is open.+ A page's permission stories go one level further down, in+ `stories/authz/<Page>.authz.stories.tsx`, on the page's own mocks: see+ **Permission stories**.+- **A state only a click reaches is a story with a `play` function**, not a+ control: a drawer, a modal, an edit mode the page holds in component state.+ Drive it with `userEvent` and the queries from `storybook/test`, take the first+ of a repeated row action, and wait on the state's own text. The page fetches+ before it renders a row, so the finder needs a timeout past the 1s default. A+ state the app drops again on its own, such as one keyed on an array identity+ that a refetch replaces, does not get a story: it would not survive being+ looked at. A *sequence* of such states, a wizard's steps or a+ questionnaire's pages, is still a control: declare the steps in the mocks+ module and walk them from a `play` on the meta that destructures `mount`, which+ is what makes Storybook replay it on an arg change. See+ [references/controls.md](references/controls.md).- **The mocks are AI-owned and say so.** `<Page>.stories.mocks.tsx` and every fileunder a `__story_mockdata__/` open with this banner, above the imports:@@ -74,6 +225,13 @@ process on top of it.writing a response shape inline, check if a builder exists; if not and theshape will repeat, add it there. Page-specific builders stay in the page's`__story_mockdata__/`.+- **The story's own doc comment is per state.** Every `export const` gets one:+ what that state shows, not how it is built. It renders in the States list on+ the page's Docs page, so `Undocumented.` there is a story nobody described.+- **Story names come from a fixed vocabulary** where one fits: `Default`,+ `Viewer`, `Empty`, `Loading`, `Error`. Page-specific states get page-specific+ names (`NoIngestion`, `Unlicensed`), never a second spelling of one of those+ (`ViewerAccess`, `NonAdmin`).- **No comment is the default.** Write one only for what the code cannot show:a shape the backend dictates, an app bug the mock reproduces, an ordering orcap the page depends on, a workaround and the reason for it. Never restate a@@ -85,6 +243,16 @@ process on top of it.## Done means- [ ] `Default` shows the page with data, checked in dark and light+- [ ] title follows the sidebar rules, tags declared, and the page's entry added+ to the `storySort.order` literal in `.storybook/preview.tsx`+- [ ] the meta carries its doc comment with the `Route:` line, the meta restates+ `parameters: { ...pageStory.parameters }` after the spread, and every story+ export carries its own doc comment+- [ ] the page's Docs page renders: description, controls table, and one row per+ state with no `Undocumented.`+- [ ] a page tagged `authz` has its `Authz` folder: one story per permission it+ reads, each reached by `revoked`, none of them a role preset, and each one+ checked by the `disabled` state of what the permission gates- [ ] the mocks module and every `__story_mockdata__` file carry the AI-owned banner- [ ] every control flipped once, its effect seen on screen- [ ] console clean: no `[storybook] no msw handler`, no 501, no msw unhandleddiff --git a/.claude/skills/signoz-page-story/references/controls.md b/.claude/skills/signoz-page-story/references/controls.mdindex 8a60b71a14..f441a0c2c2 100644--- a/.claude/skills/signoz-page-story/references/controls.md+++ b/.claude/skills/signoz-page-story/references/controls.md@@ -128,20 +128,83 @@ export const servicesMocks = defineStoryMocks({// src/pages/Services/stories/Services.stories.tsxtype ServicesArgs = PageStoryArgs<typeof servicesMocks>;+const pageStory = storyMocks(servicesMocks, {+ route: ROUTES.APPLICATION,+ layout: 'app',+});++/**+ * Every instrumented service with its p99, error rate and throughput.+ *+ * Route: `/services`.+ */const meta = {- title: 'Pages/Services',+ title: 'Pages/Services/List',component: Services,- ...storyMocks(servicesMocks, { route: ROUTES.APPLICATION, layout: 'app' }),+ ...pageStory,+ parameters: { ...pageStory.parameters },} satisfies Meta<ServicesArgs>;````PageStoryArgs` folds in the global controls, so a story's `args` can set`access`, `dataState` or `banner` next to the page's own knobs and stay typed.+## A step the page keeps in component state++A wizard's step, a questionnaire's page, a picker's next question: the page holds+it in `useState` and nothing in the URL says which one is open. It is still a+control. Declare the steps in the mocks module and drive them from a `play` on+the **meta**, so every story of the page inherits the walk and only sets `args`:++```tsx+// <Page>.stories.mocks.tsx+export const SETUP_STEPS = ['pick-source', 'pick-framework', 'configure'] as const;+export type SetupStep = (typeof SETUP_STEPS)[number];++controls: {+ step: choiceControl<SetupStep>('Setup step', { group: SETUP, options: SETUP_STEPS, value: 'pick-source' }),+},+```++```tsx+// <Page>.stories.tsx+const meta = {+ play: async ({ mount, args, canvasElement }): Promise<void> => {+ await mount();+ await advanceToSetupStep(canvasElement, args.step);+ },+ ...storyMocks(pageMocks),+} satisfies Meta<PageArgs>;++export const Configure: Story = { args: { step: 'configure' } };+```++**Destructuring `mount` is what makes it a control.** Storybook re-runs a play+function on an arg change only for a story whose play asks to be remounted+(`usesMount`); otherwise it re-renders the tree the previous walk left behind and+the panel looks broken. With `mount` destructured, the story renders when `play`+calls it, and every arg change replays the walk from a fresh mount.++The walk itself:++- one `answer` function per step, in an array indexed the same as the step list,+ so reaching step *n* is `answers.slice(0, STEPS.indexOf(step))`;+- answer each step with the least its Next button accepts, and prefer a "do this+ later" over filling a slider;+- run them sequentially (`reduce` over a promise), since each answer is what+ renders the step the next one reads;+- bail out when the page did not start where the walk expects, such as a source+ deep-linked past the questions. Check for the first step's own text rather than+ reading another control's value.++An endpoint that only settles the transition between two steps (the profile a+questionnaire saves before its last page) takes a plain resolver, or the Data+control on `loading` strands the walk halfway.+## Not a control- Anything the global controls already cover: banner, side nav, data state,- access preset, permissions, check state.+ access preset, granted permissions, revoked permissions, check state.- A knob whose effect nobody can see on the page. Delete it or find the widget itwas supposed to drive.- A raw payload as an object control. Controls carry intent (`5 dashboards`,@@ -155,9 +218,12 @@ const meta = {Default to a control. Write a story when the state is worth a link:- the fresh workspace, because that is what a new user sees-- the restricted user, when permissions visibly change the page- a page-defining mode (a tab, a category) that has its own layout+A permission that visibly changes the page is a story too, but it goes in the+page's `Authz` folder, one per permission, turned with the `Revoked` control.+See **Permission stories** in SKILL.md.+Combinations of controls do not need stories, which is what the panel is for.Each story gets one prose doc comment: what it shows, in the page's own terms.diff --git a/.claude/skills/signoz-page-story/references/verify.md b/.claude/skills/signoz-page-story/references/verify.mdindex 661a9ca7f5..7dc537295e 100644--- a/.claude/skills/signoz-page-story/references/verify.md+++ b/.claude/skills/signoz-page-story/references/verify.md@@ -12,11 +12,12 @@ cd frontend && pnpm storybook --ci --quiet # :6006, background itA newly added `.stories.tsx` takes a few seconds to appear in `index.json` on analready-running server; an empty first poll is not a broken `stories` glob.-Story ids come from the meta title: `Pages/Services` → `pages-services`, plus the-story export in kebab-case. Render one story on its own:+Story ids come from the meta title: `Pages/Services/List` →+`pages-services-list`, plus the story export in kebab-case. Render one story on+its own:```-http://localhost:6006/iframe.html?id=pages-services--default&viewMode=story+http://localhost:6006/iframe.html?id=pages-services-list--default&viewMode=story```## Flip controls from the URLdiff --git a/frontend/.oxlintrc.json b/frontend/.oxlintrc.jsonindex 5b5aeb8a6f..4e25dee635 100644--- a/frontend/.oxlintrc.json+++ b/frontend/.oxlintrc.json@@ -295,6 +295,8 @@// Prevents bracket access on CSS modules (styles['kebab-case']) which fails with camelCaseOnly config"signoz/no-dashboard-fetch-outside-root": "error",// Forces useDashboardFetchRequired() outside the root V2 pages (allowlisted in overrides below)+ "signoz/no-msw-in-story-file": "error",+ // Bans msw imports in *.stories.tsx; handlers/mock data belong in the sibling .stories.mocks.tsx"no-restricted-globals": ["error",{diff --git a/frontend/.storybook/main.ts b/frontend/.storybook/main.tsindex d746bc5eca..fd1bd9e0d1 100644--- a/frontend/.storybook/main.ts+++ b/frontend/.storybook/main.ts@@ -27,12 +27,22 @@ const mockAliases = [find: /^(?:src\/)?api\/common\/logEvent$/,replacement: `${srcPath}/storybook/mocks/logEvent.mock.ts`,},+ {+ // jest: not replaced, the suite mounts a mock store per test.+ find: /^(?:src\/)?store$/,+ replacement: `${srcPath}/storybook/mocks/store.mock.ts`,+ },{// jest: __mocks__/env.ts, which leaves `baseURL` empty because jsdom already// resolves a relative `/api/...` against `http://localhost`.find: /^(?:src\/)?constants\/env$/,replacement: `${srcPath}/storybook/mocks/env.mock.ts`,},+ {+ // jest: not replaced, a test opens the one tooltip it is about.+ find: /^@signozhq\/ui\/tooltip$/,+ replacement: `${srcPath}/storybook/mocks/tooltip.mock.tsx`,+ },];/**@@ -55,12 +65,12 @@ const isExcluded = (plugin: PluginOption): boolean =>const config: StorybookConfig = {framework: '@storybook/react-vite',- stories: ['../src/**/*.stories.@(ts|tsx)'],+ stories: ['../src/storybook/docs/**/*.mdx', '../src/**/*.stories.@(ts|tsx)'],// `../public` carries the fonts, icons and i18n bundles the app expects at// the root; `./public` carries the msw worker, which must not ship in a// production build.staticDirs: ['../public', './public'],- addons: ['@storybook/addon-a11y'],+ addons: ['@storybook/addon-a11y', '@storybook/addon-docs'],core: { disableTelemetry: true },viteFinal: async (viteConfig) => {const plugins = (viteConfig.plugins ?? [])@@ -77,6 +87,14 @@ const config: StorybookConfig = {return {...viteConfig,+ build: {+ ...viteConfig.build,+ // `vite.config.ts` sets this for the app; Storybook's builder replaces+ // `build` wholesale, which leaves rolldown-vite on its default+ // lightningcss. That one rejects `:global()` in a plain stylesheet, which+ // the app has, and the static build dies in CSS minification.+ cssMinify: 'esbuild',+ },plugins,resolve: {...viteConfig.resolve,diff --git a/frontend/.storybook/preview-head.html b/frontend/.storybook/preview-head.htmlindex 5117d25eb7..5fd75154ba 100644--- a/frontend/.storybook/preview-head.html+++ b/frontend/.storybook/preview-head.html@@ -6,6 +6,17 @@--><link rel="stylesheet" href="storybook-fonts.css" />+<!--+ Third-party frames are the one thing msw cannot answer: a cross-origin iframe+ navigates outside the service worker's scope, so the YouTube embeds and the+ docs pane in onboarding reach the real network. Same intent as the boot data+ below, enforced by the browser instead.+-->+<meta+ http-equiv="Content-Security-Policy"+ content="frame-src 'self' blob: data:"+/>+<link rel="stylesheet" href="css/uPlot.min.css" /><script>@@ -24,3 +35,38 @@},};</script>++<script>+ // The wall clock every story reads. Chart windows, `4 mins ago` labels and+ // trial countdowns all derive from `now`, and Chromatic does not freeze the+ // clock, so a live one redraws every chart axis between two builds of the+ // same code. `performance.now` and the timers keep running, so anything+ // waiting on a timeout still resolves. `?storyClock=live`, or an ISO+ // instant, overrides it.+ //+ // `new Date()` is the frozen instant, which is what the app renders from.+ // `Date.now()` runs on from it instead, because it is also what code measures+ // elapsed time with: `lodash.debounce` compares two `Date.now()` readings to+ // decide its trailing call is due, so a frozen one re-arms its timer forever+ // and every debounced input in the app (the onboarding catalogue search, the+ // pipelines search, the log filter) silently stops filtering.+ (() => {+ const asked = new URLSearchParams(window.location.search).get('storyClock');+ if (asked === 'live') return;++ const frozen = Date.parse(asked || '2026-06-15T12:00:00.000Z');+ if (Number.isNaN(frozen)) return;++ const RealDate = Date;+ const started = performance.now();+ class FrozenDate extends RealDate {+ constructor(...args) {+ super(...(args.length ? args : [frozen]));+ }+ static now() {+ return frozen + (performance.now() - started);+ }+ }+ Object.defineProperty(window, 'Date', { value: FrozenDate, writable: true });+ })();+</script>diff --git a/frontend/.storybook/preview.tsx b/frontend/.storybook/preview.tsxindex 203b7ee535..8dffd0b724 100644--- a/frontend/.storybook/preview.tsx+++ b/frontend/.storybook/preview.tsx@@ -3,6 +3,8 @@ import type { SetupWorker } from 'msw';import { setupWorker } from 'msw';import { settleForCapture } from '../src/storybook/visual/settleForCapture';+import PageDocs from '../src/storybook/docs/PageDocs';+import ThemedDocsContainer from '../src/storybook/docs/ThemedDocsContainer';import { withProviders } from '../src/storybook/decorators/withProviders';import { globalMocks } from '../src/storybook/globals';import { resetStoryHistory } from '../src/storybook/navigation/containment';@@ -13,7 +15,12 @@ import {} from '../src/storybook/runtime/resolveStory';import { allModes } from './modes';-import '../src/ReactI18';+import i18n from '../src/ReactI18';++// `src/index.tsx` does this at boot: without it `@monaco-editor/react` falls back+// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does+// not report because the requests look like static assets.+import '../src/lib/monaco/setup';import '../src/styles.scss';@@ -63,10 +70,127 @@ const { worker, ready } = (holder.__signozStorybookWorker ??=};})());+/**+ * `t()` answers with the key until the namespace's JSON has landed, and a `play`+ * that clicks as soon as the story renders is quick enough to catch it: the+ * channel form's "Channel name is mandatory" arrives as `channel_name_required`.+ * Every namespace under `public/locales/en` is loaded once, ahead of the first+ * story.+ */+const translationsReady = i18n.loadNamespaces(+ Object.keys(import.meta.glob('../public/locales/en/*.json')).map((path) =>+ path.slice(path.lastIndexOf('/') + 1, -'.json'.length),+ ),+);+const preview: Preview = {parameters: {layout: 'fullscreen',controls: { expanded: true },+ // The sidebar order, mirroring the app's own side nav+ // (`container/SideNav/menuItems.tsx`), so a page sits where someone would+ // click it in the product. Storybook's default is the order the story files+ // happen to be globbed in, which puts `src/modules` first. Anything missing+ // from a level lands after the entries listed for it, in file order, so a new+ // story shows up at the end of its area rather than disappearing. Stories+ // inside a file are never listed, so they keep the order they are declared+ // in, `Default` first. Storybook parses this out of the file, so it has to+ // stay an inline literal.+ options: {+ storySort: {+ order: [+ 'Docs',+ 'Pages',+ [+ 'Home',+ 'Alerts',+ [+ 'Rules',+ 'Triggered',+ 'Overview',+ 'History',+ 'Create',+ 'Edit',+ 'Planned Downtime',+ 'Routing Policies',+ 'Channels',+ ['List', 'New', 'Edit'],+ ],+ 'Dashboards',+ ['List', 'Detail', 'Panel Editor', 'Public'],+ 'Services',+ ['List', 'Detail', 'Top Level Operations', 'Service Map'],+ 'Logs',+ ['Explorer', 'Live Tail', 'Saved Views', 'Pipelines', 'Settings'],+ 'Traces',+ ['Explorer', 'Trace Details', 'Funnel Details'],+ 'Metrics',+ ['Explorer'],+ 'Infrastructure',+ [+ 'Overview',+ 'Kubernetes',+ [+ 'Clusters',+ 'Nodes',+ 'Namespaces',+ 'Pods',+ 'Deployments',+ 'DaemonSets',+ 'StatefulSets',+ 'Jobs',+ 'Volumes',+ ],+ ],+ 'Integrations',+ ['List', 'Details', 'Cloud Account'],+ 'Exceptions',+ ['List', 'Detail'],+ 'External APIs',+ 'AI Observability',+ ['Overview', 'Explorer', 'Model Pricing', 'Attribute Mapping'],+ 'Noz',+ 'Metering',+ ['Cost Meter', 'Usage Explorer'],+ 'Messaging Queues',+ ['Overview', 'Kafka', 'Kafka Detail', 'Celery'],+ 'Onboarding',+ ['Questionnaire', 'Add Data Source'],+ 'Settings',+ [+ 'Workspace',+ 'Account',+ 'Billing',+ ['Overview', 'Authz'],+ 'MCP Server',+ 'Roles',+ 'Role Details',+ 'Role Editor',+ 'Members',+ 'Service Accounts',+ 'Ingestion',+ 'Single Sign-on',+ 'Keyboard Shortcuts',+ ],+ 'Auth',+ ['Login', 'Sign Up', 'Forgot Password', 'Reset Password'],+ 'System',+ [+ 'Status',+ 'Support',+ 'License',+ 'Not Found',+ 'Unauthorized',+ 'Error Fallback',+ 'Workspace Locked',+ 'Workspace Suspended',+ 'Workspace Access Restricted',+ ],+ ],+ ],+ },+ },+ docs: { page: PageDocs, container: ThemedDocsContainer },// One cloud snapshot per theme, for every story. A mode carries Storybook// globals, so `theme` here is the same toolbar global the app reads out of// localStorage. Widths are Chromatic's only real dimension, as they are@@ -74,6 +198,9 @@ const preview: Preview = {// one it is given.chromatic: { modes: allModes },},+ // Every page story gets a docs page: the descriptions on the meta and on each+ // story are the page's documentation, and without this they render nowhere.+ tags: ['autodocs'],globalTypes: {theme: {description: 'SigNoz color scheme',@@ -119,12 +246,21 @@ const preview: Preview = {world.apply();world.install(worker);- await ready;+ await Promise.all([ready, translationsReady]);},],beforeEach: () => {clearBlockedNavigations();resetStoryHistory();++ // The runner clears its console/network buffer before it navigates, so+ // anything the outgoing story still has in flight would be reported+ // against this one. Stamping the moment this story starts gives the runner+ // a line to discard those by. `Date.now()` is faked for the stories, so+ // this reads the one clock the runner's own timestamps share.+ document.body.dataset.signozStoryStartedAt = String(+ performance.timeOrigin + performance.now(),+ );},// After `play`, which is the moment both capture stacks shoot at.afterEach: settleForCapture,diff --git a/frontend/.storybook/public/mockServiceWorker.js b/frontend/.storybook/public/mockServiceWorker.jsindex 51d85eeebf..2b3e91c9d3 100644--- a/frontend/.storybook/public/mockServiceWorker.js+++ b/frontend/.storybook/public/mockServiceWorker.js@@ -88,10 +88,16 @@ self.addEventListener('fetch', function (event) {const { request } = eventconst accept = request.headers.get('accept') || ''- // Bypass server-sent events.- if (accept.includes('text/event-stream')) {- return- }+ // msw bypasses server-sent events here, because it answers a request in one+ // piece and has no stream to hand back. A story is not a live connection+ // either: it wants the backlog a page renders, and one response carries that+ // fine. Left bypassed, `/api/v3/logs/livetail` reaches the real network and+ // the live tail story is a spinner over ERR_CONNECTION_REFUSED. Restore the+ // bypass and re-check `Pages/Logs/Live Tail` if msw regenerates this file.+ //+ // if (accept.includes('text/event-stream')) {+ // return+ // }// Bypass navigation requests.if (request.mode === 'navigate') {diff --git a/frontend/.storybook/test-runner.ts b/frontend/.storybook/test-runner.tsindex ea9f00cc0f..1bc435dda2 100644--- a/frontend/.storybook/test-runner.ts+++ b/frontend/.storybook/test-runner.ts@@ -25,7 +25,23 @@ const IGNORED_MESSAGES = [/violates the following Content Security Policy directive/,];-const messagesByPage = new WeakMap<Page, string[]>();+interface CapturedMessage {+ at: number;+ text: string;+}++const messagesByPage = new WeakMap<Page, CapturedMessage[]>();++/**+ * When the story under test started rendering, stamped by the preview's+ * `beforeEach`. Messages captured before it belong to the previous story: the+ * runner clears this buffer ahead of the navigation, so whatever that story+ * still had in flight lands here.+ */+const storyStartedAt = (page: Page): Promise<number> =>+ page+ .evaluate(() => Number(document.body.dataset.signozStoryStartedAt ?? 0))+ .catch(() => 0);/*** Only `console.error` fails a story. `console.warn` is dev-time advice from@@ -43,14 +59,14 @@ const config: TestRunnerConfig = {return;}- const messages: string[] = [];+ const messages: CapturedMessage[] = [];messagesByPage.set(page, messages);page.on('console', (message) => {if (message.type() === 'error' &&!IGNORED_MESSAGES.some((pattern) => pattern.test(message.text()))) {- messages.push(`[error] ${message.text()}`);+ messages.push({ at: Date.now(), text: `[error] ${message.text()}` });}});// The console message alone ("Failed to load resource") doesn't name the@@ -58,12 +74,23 @@ const config: TestRunnerConfig = {// actionable instead of just a status code.page.on('response', (response) => {if (response.status() >= 400) {- messages.push(`[response] ${response.status()} ${response.url()}`);+ messages.push({+ at: Date.now(),+ text: `[response] ${response.status()} ${response.url()}`,+ });}});},async postVisit(page, context): Promise<void> {- const messages = messagesByPage.get(page) ?? [];+ const captured = messagesByPage.get(page) ?? [];+ if (captured.length === 0) {+ return;+ }++ const startedAt = await storyStartedAt(page);+ const messages = captured+ .filter((message) => message.at >= startedAt)+ .map((message) => message.text);if (messages.length === 0) {return;}diff --git a/frontend/package.json b/frontend/package.jsonindex 626ecd7a4c..3a6dd29d1a 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -163,6 +163,7 @@"@jest/globals": "30.4.1","@jest/types": "30.2.0","@storybook/addon-a11y": "10.5.9",+ "@storybook/addon-docs": "10.5.9","@storybook/react-vite": "10.5.9","@storybook/test-runner": "0.24.5","@testing-library/dom": "8.20.0",diff --git a/frontend/plugins/rules/no-msw-in-story-file.mjs b/frontend/plugins/rules/no-msw-in-story-file.mjsnew file mode 100644index 0000000000..38a8513202--- /dev/null+++ b/frontend/plugins/rules/no-msw-in-story-file.mjs@@ -0,0 +1,41 @@+/**+ * Rule: no-msw-in-story-file+ *+ * A `.stories.tsx` file is the human-facing surface: it must not carry msw+ * handlers or response payloads. Those belong in the sibling+ * `<Page>.stories.mocks.tsx` module (and its `__story_mockdata__` builders).+ *+ * This rule flags any import from `msw` inside a `*.stories.tsx` file. It+ * does not match `*.stories.mocks.tsx`, which is where msw imports belong.+ */++export default {+ meta: {+ type: 'suggestion',+ docs: {+ description:+ 'Disallow importing from msw inside a .stories.tsx file; move handlers/mock data to the sibling .stories.mocks.tsx module',+ category: 'Storybook',+ },+ schema: [],+ messages: {+ noMsw:+ 'Do not import from msw in a .stories.tsx file. Move the handler and its mock data to the sibling <Page>.stories.mocks.tsx module (and __story_mockdata__ for builders).',+ },+ },++ create(context) {+ const filename = context.filename || '';+ if (!filename.endsWith('.stories.tsx')) {+ return {};+ }++ return {+ ImportDeclaration(node) {+ if (node.source.value === 'msw') {+ context.report({ node, messageId: 'noMsw' });+ }+ },+ };+ },+};diff --git a/frontend/plugins/signoz.mjs b/frontend/plugins/signoz.mjsindex c17a0c3632..038a9ef8be 100644--- a/frontend/plugins/signoz.mjs+++ b/frontend/plugins/signoz.mjs@@ -15,6 +15,7 @@ import noCssModuleBracketAccess from './rules/no-css-module-bracket-access.mjs';import noDashboardFetchOutsideRoot from './rules/no-dashboard-fetch-outside-root.mjs';import noConditionalTextNodesWithSiblings from './rules/no-conditional-text-nodes-with-siblings.mjs';import noReturnTextNodes from './rules/no-return-text-nodes.mjs';+import noMswInStoryFile from './rules/no-msw-in-story-file.mjs';export default {meta: {@@ -31,5 +32,6 @@ export default {'no-dashboard-fetch-outside-root': noDashboardFetchOutsideRoot,'no-conditional-text-nodes-with-siblings': noConditionalTextNodesWithSiblings,'no-return-text-nodes': noReturnTextNodes,+ 'no-msw-in-story-file': noMswInStoryFile,},};diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yamlindex 180d117899..e402e2e02c 100644--- a/frontend/pnpm-lock.yaml+++ b/frontend/pnpm-lock.yaml@@ -363,6 +363,9 @@ importers:'@storybook/addon-a11y':specifier: 10.5.9+ '@storybook/addon-docs':+ specifier: 10.5.9+ version: 10.5.9(@types/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected]))'@storybook/react-vite':specifier: 10.5.9version: 10.5.9(@types/[email protected])(@types/[email protected])([email protected])([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected]))([email protected])@@ -2184,6 +2187,12 @@ packages:'@marijn/[email protected]':resolution: {integrity: sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==}+ '@mdx-js/[email protected]':+ resolution: {integrity: sha512-f++rKLQgUVYDAtECQ6fn/is15GkEH9+nZPM3MS0RcxVqoTfawHvDlSCH7JbMhAM6uJ32v3eXLvLmLvjGu7PTQw==}+ peerDependencies:+ '@types/react': '>=16'+ react: '>=16'+'@monaco-editor/[email protected]':resolution: {integrity: sha512-gIwR1HrJrrx+vfyOhYmCZ0/JcWqG5kbfG7+d3f/C1LXk2EvzAbHSg3MQ5lO2sMlo9izoAZ04shohfKLVT6crVA==}@@ -3766,6 +3775,15 @@ packages:peerDependencies:storybook: ^10.5.9+ '@storybook/[email protected]':+ resolution: {integrity: sha512-8sFsMkZYrrdqCLdV+hnwTwDF7RaBsBPRwl4wfc8ve9Q/7Yhi5REe/Xjvd8x1yn6fBPPw9tnID9dx6Agdnr81fw==}+ peerDependencies:+ '@types/react': ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0+ storybook: ^10.5.9+ peerDependenciesMeta:+ '@types/react':+ optional: true+'@storybook/[email protected]':resolution: {integrity: sha512-Zg4JbGQiHFPGlFJ9HM+XPgzKmU/RFPCymhohVRJhBBYfmgaQgz0flWWzscseCDpl638MNd8/r/H+nwuoBgSYDg==}peerDependencies:@@ -4189,6 +4207,9 @@ packages:'@types/[email protected]':resolution: {integrity: sha512-LsjtqsyF+d2/yFOYaN22dHZI1Cpwkrj+g06G8+qtUKlhovPW89YhqSnfKtMbkgmEtYpH2gydRNULd6y8mciAFg==}+ '@types/[email protected]':+ resolution: {integrity: sha512-T48PeuJtvLosNTPVhfnIp3i/n3a4g4Bad7YCq5k64D4u7NwDrAotikQ+5+sjtUvBmxCMlbo3dVL+C2dP0rWHzg==}+'@types/[email protected]':resolution: {integrity: sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==}@@ -12199,6 +12220,12 @@ snapshots:'@marijn/[email protected]': {}+ dependencies:+ '@types/mdx': 2.0.14+ '@types/react': 18.0.26+ react: 18.2.0+'@monaco-editor/[email protected]':dependencies:state-local: 1.0.7@@ -13619,6 +13646,25 @@ snapshots:axe-core: 4.13.0+ '@storybook/[email protected](@types/[email protected])(@types/[email protected])([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected]))':+ dependencies:+ '@mdx-js/react': 3.1.1(@types/[email protected])([email protected])+ '@storybook/csf-plugin': 10.5.9([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected]))+ '@storybook/icons': 2.1.0([email protected])+ '@storybook/react-dom-shim': 10.5.9(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])([email protected](@types/[email protected])([email protected])([email protected]))+ react: 18.2.0+ react-dom: 18.2.0([email protected])+ ts-dedent: 2.3.0+ optionalDependencies:+ '@types/react': 18.0.26+ transitivePeerDependencies:+ - '@types/react-dom'+ - esbuild+ - rollup+ - vite+ - webpack+'@storybook/[email protected]([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected]))':dependencies:'@storybook/csf-plugin': 10.5.9([email protected])([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected]))@@ -14064,6 +14110,8 @@ snapshots:dependencies:'@types/unist': 3.0.2+ '@types/[email protected]': {}+'@types/[email protected]': {}'@types/[email protected]': {}diff --git a/frontend/scripts/test-storybook.sh b/frontend/scripts/test-storybook.shindex 03113e5107..2f05fa53d6 100755--- a/frontend/scripts/test-storybook.sh+++ b/frontend/scripts/test-storybook.sh@@ -28,4 +28,4 @@ until curl -sf http://127.0.0.1:6006/index.json >/dev/null 2>&1; dosleep 1done-pnpm exec test-storybook --ci --maxWorkers=2 "$@"+pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 30000 "$@"diff --git a/frontend/src/components/CustomTimePicker/stories/CustomTimePicker.stories.tsx b/frontend/src/components/CustomTimePicker/stories/CustomTimePicker.stories.tsxnew file mode 100644index 0000000000..632e365e2b--- /dev/null+++ b/frontend/src/components/CustomTimePicker/stories/CustomTimePicker.stories.tsx@@ -0,0 +1,69 @@+import { useState } from 'react';+import type { Meta, StoryObj } from '@storybook/react-vite';+import dayjs from 'dayjs';+import { screen, userEvent } from 'storybook/test';++import { withCanvas } from '@/storybook/decorators/withCanvas';++import CustomTimePicker from '../CustomTimePicker';++const minTime = dayjs('2025-01-15T11:00:00Z').valueOf() * 1_000_000;+const maxTime = dayjs('2025-01-15T12:00:00Z').valueOf() * 1_000_000;++function TimePickerFixture(): JSX.Element {+ const [open, setOpen] = useState(false);+ const [selectedTime, setSelectedTime] = useState('1h');++ return (+ <CustomTimePicker+ isModalTimeSelection+ items={[+ { label: 'Last 15 minutes', value: '15m' },+ { label: 'Last 1 hour', value: '1h' },+ { label: 'Last 6 hours', value: '6h' },+ { label: 'Custom', value: 'custom' },+ ]}+ maxTime={maxTime}+ minTime={minTime}+ newPopover+ open={open}+ onCustomDateHandler={(): void => undefined}+ onError={(): void => undefined}+ onSelect={(value): void => setSelectedTime(value)}+ onValidCustomDateChange={(): void => undefined}+ selectedTime={selectedTime}+ selectedValue="15 Jan 2025 11:00:00 - 15 Jan 2025 12:00:00"+ setOpen={setOpen}+ />+ );+}++const meta = {+ title: 'Components/Custom Time Picker',+ component: TimePickerFixture,+ tags: ['play'],+ decorators: [withCanvas({ maxWidth: 400 })],+} satisfies Meta<typeof TimePickerFixture>;++export default meta;++type Story = StoryObj<typeof meta>;++/** Interaction: the time-range menu is open with its relative-range choices. */+export const TimeRangeMenuOpen: Story = {+ play: async (): Promise<void> => {+ await userEvent.click(await screen.findByRole('textbox'));+ await screen.findByText('RELATIVE TIMES');+ },+};++/** Interaction: the timezone menu is reached through the real time-range footer. */+export const TimezoneMenuOpen: Story = {+ play: async (): Promise<void> => {+ await userEvent.click(await screen.findByRole('textbox'));+ await userEvent.click(+ await screen.findByRole('button', { name: 'Change Timezone' }),+ );+ await screen.findByPlaceholderText('Search timezones...');+ },+};diff --git a/frontend/src/components/FieldsSelector/stories/FieldsSelector.stories.mocks.tsx b/frontend/src/components/FieldsSelector/stories/FieldsSelector.stories.mocks.tsxnew file mode 100644index 0000000000..3262448bc8--- /dev/null+++ b/frontend/src/components/FieldsSelector/stories/FieldsSelector.stories.mocks.tsx@@ -0,0 +1,28 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { TelemetrytypesSignalDTO } from 'api/generated/services/sigNoz.schemas';+import { rest } from 'msw';++import { fieldKeysResponse } from '@/storybook/msw/__story_mockdata__/fields';++export const fieldSuggestionsHandlers = [+ rest.get('http://localhost/api/v1/fields/keys', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json(+ fieldKeysResponse(['service.name', 'body'], {+ signal: TelemetrytypesSignalDTO.logs,+ }),+ ),+ ),+ ),+];++export const noFieldSuggestionsHandlers = [+ rest.get('http://localhost/api/v1/fields/keys', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(fieldKeysResponse([]))),+ ),+];diff --git a/frontend/src/components/FieldsSelector/stories/FieldsSelector.stories.tsx b/frontend/src/components/FieldsSelector/stories/FieldsSelector.stories.tsxnew file mode 100644index 0000000000..8be344b07f--- /dev/null+++ b/frontend/src/components/FieldsSelector/stories/FieldsSelector.stories.tsx@@ -0,0 +1,102 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent } from 'storybook/test';+import { DataSource } from 'types/common/queryBuilder';++import FieldsSelector from '../FieldsSelector';+import {+ fieldSuggestionsHandlers,+ noFieldSuggestionsHandlers,+} from './FieldsSelector.stories.mocks';++const meta = {+ title: 'Components/Fields Selector',+ component: FieldsSelector,+ tags: ['play'],+ args: {+ allowCustomFields: true,+ defaultPosition: { x: 40, y: 40 },+ fields: [+ {+ fieldContext: 'log',+ fieldDataType: 'string',+ name: 'timestamp',+ signal: 'logs',+ },+ ],+ height: 560,+ isOpen: true,+ onClose: (): void => undefined,+ onFieldsChange: (): void => undefined,+ signal: DataSource.LOGS,+ title: 'Edit log columns',+ width: 420,+ },+ parameters: {+ msw: {+ handlers: fieldSuggestionsHandlers,+ },+ },+} satisfies Meta<typeof FieldsSelector>;++export default meta;++type Story = StoryObj<typeof meta>;++/** Open: the draggable field editor shows its selected and available columns. */+export const Open: Story = {};++/** Mutation: adding a suggested field exposes the real unsaved-change footer. */+export const UnsavedChanges: Story = {+ play: async (): Promise<void> => {+ // One Add per suggested field, so the first row's is the one clicked.+ const [addField] = await screen.findAllByRole('button', { name: 'Add' });++ await userEvent.click(addField);+ await screen.findByRole('button', { name: 'Save changes' });+ },+};++/** Empty: the suggestion request succeeds with no columns to add. */+export const NoResults: Story = {+ parameters: {+ msw: {+ handlers: noFieldSuggestionsHandlers,+ },+ },+};++/** Limit: available columns cannot be added once the configured maximum is reached. */+export const MaximumFields: Story = {+ args: {+ fields: [+ {+ fieldContext: 'log',+ fieldDataType: 'string',+ name: 'timestamp',+ signal: 'logs',+ },+ {+ fieldContext: 'log',+ fieldDataType: 'string',+ name: 'severity_text',+ signal: 'logs',+ },+ ],+ maxFields: 2,+ },+};++/** Required: mandatory fields remain present without removal controls. */+export const RequiredFields: Story = {+ args: {+ fields: [+ {+ fieldContext: 'resource',+ fieldDataType: 'string',+ name: 'service.name',+ signal: 'logs',+ },+ ],+ requiredFields: ['resource:service.name:string'],+ },+};diff --git a/frontend/src/components/NewSelect/stories/NewSelect.stories.tsx b/frontend/src/components/NewSelect/stories/NewSelect.stories.tsxnew file mode 100644index 0000000000..48b25e23e0--- /dev/null+++ b/frontend/src/components/NewSelect/stories/NewSelect.stories.tsx@@ -0,0 +1,156 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent } from 'storybook/test';++import { withCanvas } from '@/storybook/decorators/withCanvas';+import type { GlobalMockArgs } from '@/storybook/globals';++import { CustomMultiSelect, CustomSelect } from '../index';++const options = [+ { label: 'Checkout', value: 'checkout' },+ { label: 'Frontend', value: 'frontend' },+ { label: 'Payments', value: 'payments' },+ { label: 'Search', value: 'search' },+];++const longOptions = Array.from({ length: 24 }, (_, index) => ({+ label: `Service ${String(index + 1).padStart(2, '0')}`,+ value: `service-${index + 1}`,+}));++const meta = {+ title: 'Components/New Select',+ component: CustomSelect,+ tags: ['play'],+ decorators: [withCanvas({ maxWidth: 360 })],+ args: {+ 'aria-label': 'Service',+ options,+ placeholder: 'Select a service',+ },+} satisfies Meta<typeof CustomSelect>;++export default meta;++type Story = StoryObj<typeof meta>;++type TooltipsStory = StoryObj<GlobalMockArgs>;++/** Interaction: the body-portal menu is open for stacking and clipping review. */+export const PortalOpen: Story = {+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Service' }),+ );+ await screen.findByRole('listbox');+ },+};++/** Density: a long result list keeps the menu scrollable. */+export const LongResults: Story = {+ args: { options: longOptions },+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Service' }),+ );+ await screen.findByText('Service 24');+ },+};++/** Empty: the select reports its supported no-data state. */+export const NoResults: Story = {+ args: { noDataMessage: 'No services found', options: [] },+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Service' }),+ );+ await screen.findByText('No services found');+ },+};++/** Loading: the open menu keeps its in-progress refresh feedback visible. */+export const Loading: Story = {+ args: {+ loading: true,+ options: [],+ },+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Service' }),+ );+ await screen.findByText('Refreshing values...');+ },+};++/** Error: a retryable failed request remains visible in the open menu. */+export const Error: Story = {+ args: {+ errorMessage: 'Could not load services',+ onRetry: (): void => undefined,+ options: [],+ },+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Service' }),+ );+ await screen.findByText('Could not load services');+ },+};++/** Selection: selected and unavailable options are distinguishable before choosing. */+export const SelectedDisabled: Story = {+ args: {+ options: [+ { label: 'Checkout', value: 'checkout' },+ { disabled: true, label: 'Legacy billing', value: 'legacy-billing' },+ { label: 'Payments', value: 'payments' },+ ],+ value: 'checkout',+ },+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Service' }),+ );+ await screen.findByRole('option', { name: 'Legacy billing' });+ },+};++/** Overflow: a multi-select preserves its selected values when its trigger is constrained. */+export const MultiValueOverflow: Story = {+ render: (): JSX.Element => (+ <div style={{ maxWidth: 280 }}>+ <CustomMultiSelect+ aria-label="Services"+ maxTagCount={2}+ options={longOptions}+ value={['service-1', 'service-2', 'service-3', 'service-4']}+ />+ </div>+ ),+};++const LONG_LABEL_OPTION = {+ label:+ 'checkout-service.production-eu-central-1.svc.cluster.local:8080/v1/orders/{orderId}/payment-authorisation',+ value: 'checkout-payment-authorisation',+};++/**+ * Every tooltip the select renders, held open: the selected chip revealing the+ * option label it was cut from. Nothing bounds that label, so the chip is given+ * one long enough to need the reveal.+ */+export const Tooltips: TooltipsStory = {+ args: { tooltipsOpen: true },+ render: (): JSX.Element => (+ <div style={{ maxWidth: 280 }}>+ <CustomMultiSelect+ aria-label="Services"+ maxTagCount={1}+ maxTagTextLength={14}+ options={[LONG_LABEL_OPTION, ...options]}+ value={[LONG_LABEL_OPTION.value]}+ />+ </div>+ ),+};diff --git a/frontend/src/components/NotFound/stories/NotFound.stories.mocks.tsx b/frontend/src/components/NotFound/stories/NotFound.stories.mocks.tsxnew file mode 100644index 0000000000..3554eb29ef--- /dev/null+++ b/frontend/src/components/NotFound/stories/NotFound.stories.mocks.tsx@@ -0,0 +1,15 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++/**+ * The catch-all has no route of its own: it answers for whatever pathname the+ * `Switch` ran out of routes for, and it calls nothing.+ */+export const notFoundMocks = defineStoryMocks({+ controls: {},+ config: () => ({ route: '/no-such-page' }),+});diff --git a/frontend/src/components/NotFound/stories/NotFound.stories.tsx b/frontend/src/components/NotFound/stories/NotFound.stories.tsxnew file mode 100644index 0000000000..159ad6d487--- /dev/null+++ b/frontend/src/components/NotFound/stories/NotFound.stories.tsx@@ -0,0 +1,42 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import NotFound from '../index';+import { notFoundMocks } from './NotFound.stories.mocks';++type NotFoundArgs = PageStoryArgs<typeof notFoundMocks>;++/**+ * The catch-all route mounts it with no props, and its `defaultProps` is what+ * keeps the component itself from typing as one that takes the story's args.+ */+function CatchAllPage(): JSX.Element {+ return <NotFound />;+}++const pageStory = storyMocks(notFoundMocks, { layout: 'app' });++/**+ * The shell around a pathname no route matched: the side nav stays, the content+ * area carries the 404.+ *+ * Route: any unmatched path.+ */+const meta = {+ title: 'Pages/System/Not Found',+ component: CatchAllPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<NotFoundArgs>;++export default meta;++type Story = StoryObj<NotFoundArgs>;++/**+ * What the app shows for a pathname no route matched, inside the shell: the+ * side nav is still there, and the way back is the home button.+ */+export const Default: Story = {};diff --git a/frontend/src/components/QuickFilters/stories/QuickFilters.stories.mocks.tsx b/frontend/src/components/QuickFilters/stories/QuickFilters.stories.mocks.tsxnew file mode 100644index 0000000000..9eb55244ea--- /dev/null+++ b/frontend/src/components/QuickFilters/stories/QuickFilters.stories.mocks.tsx@@ -0,0 +1,126 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ QuickfiltertypesSourceDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesFieldDataTypeDTO,+} from 'api/generated/services/sigNoz.schemas';+import { rest, type RequestHandler } from 'msw';+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';++import { attributeValuesResponse } from '@/storybook/msw/__story_mockdata__/attributes';+import { fieldKeysResponse } from '@/storybook/msw/__story_mockdata__/fields';+import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';++import { FiltersType } from '../types';++const customFilters = [+ {+ name: 'service.name',+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ },+ {+ name: 'deployment.environment',+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ },+];++export const queryBuilder = {+ currentQuery: {+ builder: {+ queryData: [+ {+ filter: { expression: '' },+ filters: { items: [], op: 'AND' },+ queryName: 'Logs query',+ },+ ],+ },+ },+ lastUsedQuery: 0,+ panelType: 'graph',+ redirectWithQueryBuilderData: (): void => undefined,+ setLastUsedQuery: (): void => undefined,+};++export const checkboxConfig = [+ {+ attributeKey: {+ dataType: DataTypes.String,+ key: 'service.name',+ type: 'resource',+ },+ defaultOpen: true,+ title: 'Service name',+ type: FiltersType.CHECKBOX,+ },+];++export const attributeValuesHandler = (+ values: readonly string[],+): RequestHandler =>+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(attributeValuesResponse(values))),+ );++export const handlers = [+ rest.get('http://localhost/api/v2/quick_filters/logs', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json(+ quickFiltersResponse(QuickfiltertypesSourceDTO.logs, customFilters),+ ),+ ),+ ),+ rest.get('http://localhost/api/v1/fields/keys', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(fieldKeysResponse(['k8s.namespace.name']))),+ ),+ attributeValuesHandler(['checkout', 'frontend', 'payments']),+];++export const loadingFiltersHandlers = [+ rest.get('http://localhost/api/v2/quick_filters/logs', (_req, res, ctx) =>+ res(ctx.delay('infinite')),+ ),+];++export const LONG_FILTER_VALUES = [+ 'checkout-service.production-eu-central-1.svc.cluster.local',+ 'payments-authorisation-worker.production-us-east-2.svc.cluster.local',+ 'catalog-availability-projector.staging-ap-south-1.svc.cluster.local',+];++export const selectedServiceQueryBuilder = {+ ...queryBuilder,+ currentQuery: {+ builder: {+ queryData: [+ {+ filter: { expression: '' },+ filters: {+ items: [+ {+ key: {+ dataType: DataTypes.String,+ key: 'service.name',+ type: 'resource',+ },+ op: 'in',+ value: ['checkout', 'payments'],+ },+ ],+ op: 'AND',+ },+ queryName: 'Logs query',+ },+ ],+ },+ },+};diff --git a/frontend/src/components/QuickFilters/stories/QuickFilters.stories.tsx b/frontend/src/components/QuickFilters/stories/QuickFilters.stories.tsxnew file mode 100644index 0000000000..82cfdf0c5d--- /dev/null+++ b/frontend/src/components/QuickFilters/stories/QuickFilters.stories.tsx@@ -0,0 +1,119 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import type { ComponentProps, ComponentType } from 'react';+import { expect, screen, userEvent, waitFor, within } from 'storybook/test';++import { withCanvas } from '@/storybook/decorators/withCanvas';+import type { GlobalMockArgs } from '@/storybook/globals';++import QuickFilters from '../QuickFilters';+import {+ attributeValuesHandler,+ checkboxConfig,+ handlers,+ LONG_FILTER_VALUES,+ loadingFiltersHandlers,+ queryBuilder,+ selectedServiceQueryBuilder,+} from './QuickFilters.stories.mocks';+import { QuickFiltersSource, SignalType } from '../types';++const meta = {+ title: 'Components/Quick Filters',+ // `QuickFilters.defaultProps` declares `onFilterChange: null` against a prop+ // typed as an optional function, so the component does not satisfy+ // `ComponentType` as written. The defaults are load-bearing for the jest+ // suite, hence the cast rather than a change to them.+ component: QuickFilters as unknown as ComponentType<+ ComponentProps<typeof QuickFilters>+ >,+ tags: ['play'],+ // The rail the explorers give it (`Explorer.styles.scss`, `.filter`).+ decorators: [withCanvas({ width: 260 })],+ args: {+ config: checkboxConfig,+ handleFilterVisibilityChange: (): void => undefined,+ signal: SignalType.LOGS,+ source: QuickFiltersSource.LOGS_EXPLORER,+ },+ parameters: {+ msw: { handlers },+ signoz: { queryBuilder },+ },+} satisfies Meta<typeof QuickFilters>;++export default meta;++type Story = StoryObj<typeof meta>;++type TooltipsStory = StoryObj<+ ComponentProps<typeof QuickFilters> & GlobalMockArgs+>;++/**+ * The settings control renders disabled while its permission check is in+ * flight and is swapped for the enabled one once the check answers, so it is+ * looked up again on every attempt; a click on the disabled one is dropped in+ * silence.+ */+const settingsControl = (canvasElement: HTMLElement): Promise<HTMLElement> =>+ waitFor(() => {+ const control = within(canvasElement).getByTestId('settings-icon-container');++ expect(control).toBeEnabled();++ return control;+ });++/** Interaction: the settings panel is opened through the admin settings control. */+export const SettingsOpen: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(await settingsControl(canvasElement));+ await screen.findByText('Edit quick filters');+ },+};++/** Mutation: changing the settings list reveals the fixed save and discard footer. */+export const SettingsDirtyFooter: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(await settingsControl(canvasElement));+ await userEvent.click(await screen.findByRole('button', { name: 'Add' }));+ await screen.findByRole('button', { name: 'Save changes' });+ },+};++/** Loading: dynamic filters are intentionally left pending to display the panel skeleton. */+export const LoadingFilters: Story = {+ parameters: {+ msw: {+ handlers: loadingFiltersHandlers,+ },+ },+};++/** Empty: a loaded quick-filter configuration with no filters has no result rows. */+export const NoResults: Story = {+ args: { config: [], signal: undefined },+};++/** Selection: an expanded checkbox shows the actual selected service values. */+export const SelectedExpandedCheckbox: Story = {+ args: { signal: undefined },+ parameters: {+ signoz: {+ queryBuilder: selectedServiceQueryBuilder,+ },+ },+};++/**+ * Every tooltip the panel renders, held open: the reveal on each truncated+ * filter value. Nothing bounds those values, so the panel is answered with+ * service names long enough to be cut. The Service name filter carries them, so+ * the signal that would add the workspace's own dynamic filters is left off.+ */+export const Tooltips: TooltipsStory = {+ args: { signal: undefined, tooltipsOpen: true },+ parameters: {+ msw: { handlers: [attributeValuesHandler(LONG_FILTER_VALUES), ...handlers] },+ },+};diff --git a/frontend/src/components/SignozModal/stories/SignozModal.stories.tsx b/frontend/src/components/SignozModal/stories/SignozModal.stories.tsxnew file mode 100644index 0000000000..8b18b8c510--- /dev/null+++ b/frontend/src/components/SignozModal/stories/SignozModal.stories.tsx@@ -0,0 +1,64 @@+import { useState } from 'react';+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Button } from '@signozhq/ui/button';+import { expect, screen, userEvent, waitFor, within } from 'storybook/test';++import { withCanvas } from '@/storybook/decorators/withCanvas';++import { CustomSelect } from '../../NewSelect';+import SignozModal from '../SignozModal';++function ModalFixture(): JSX.Element {+ const [open, setOpen] = useState(false);++ return (+ <>+ <Button data-testid="open-signoz-modal" onClick={(): void => setOpen(true)}>+ Open modal+ </Button>+ <SignozModal+ footer={null}+ open={open}+ onCancel={(): void => setOpen(false)}+ title="Create saved view"+ >+ <CustomSelect+ aria-label="View scope"+ options={[+ { label: 'This workspace', value: 'workspace' },+ { label: 'My views', value: 'personal' },+ ]}+ placeholder="Select a scope"+ />+ </SignozModal>+ </>+ );+}++const meta = {+ title: 'Components/Signoz Modal',+ component: ModalFixture,+ tags: ['play'],+ decorators: [withCanvas({ maxWidth: 400 })],+} satisfies Meta<typeof ModalFixture>;++export default meta;++type Story = StoryObj<typeof meta>;++/** Interaction: the modal and its nested body-portal select are both genuinely open. */+export const OpenWithNestedSelect: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const trigger = within(canvasElement).getByTestId('open-signoz-modal');++ await userEvent.click(trigger);+ await screen.findByRole('dialog', { name: 'Create saved view' });+ await userEvent.keyboard('{Escape}');+ await waitFor(() => expect(trigger).toHaveFocus());+ await userEvent.click(trigger);+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'View scope' }),+ );+ await screen.findByRole('listbox');+ },+};diff --git a/frontend/src/components/TableV3/TableV3.tsx b/frontend/src/components/TableV3/TableV3.tsxindex f08f4c32dd..e429704d36 100644--- a/frontend/src/components/TableV3/TableV3.tsx+++ b/frontend/src/components/TableV3/TableV3.tsx@@ -71,7 +71,7 @@ interface ITableConfig {instance: Virtualizer<HTMLDivElement, Element>,) => void;}-interface ITableV3Props<T> {+export interface ITableV3Props<T> {columns: ColumnDef<T, any>[];data: T[];config: ITableConfig;@@ -201,5 +201,5 @@ export function TableV3<T>(props: ITableV3Props<T>): JSX.Element {TableV3.defaultProps = {customClassName: '',- virtualiserRef: null,+ virtualiserRef: undefined,};diff --git a/frontend/src/components/TableV3/stories/TableV3.stories.tsx b/frontend/src/components/TableV3/stories/TableV3.stories.tsxnew file mode 100644index 0000000000..db5ee42bc1--- /dev/null+++ b/frontend/src/components/TableV3/stories/TableV3.stories.tsx@@ -0,0 +1,54 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import type { ColumnDef } from '@tanstack/react-table';++import { withCanvas } from '@/storybook/decorators/withCanvas';++import type { ITableV3Props } from '../TableV3';+import { TableV3 } from '../TableV3';++type TraceRow = {+ id: string;+ traceId: string;+ service: string;+ duration: string;+ status: string;+};++const columns: ColumnDef<TraceRow>[] = [+ { accessorKey: 'traceId', header: 'Trace ID', size: 280 },+ { accessorKey: 'service', header: 'Service', size: 220 },+ { accessorKey: 'duration', header: 'Duration', size: 140 },+ { accessorKey: 'status', header: 'Status', size: 160 },+];++const rows: TraceRow[] = Array.from({ length: 40 }, (_, index) => ({+ id: `trace-${index + 1}`,+ traceId: `c0ffee${String(index + 1).padStart(10, '0')}7f4a9d1c`,+ service: index % 2 === 0 ? 'checkout-service' : 'catalog-service',+ duration: `${80 + index * 6} ms`,+ status: index % 5 === 0 ? 'Error' : 'OK',+}));++const meta = {+ title: 'Components/Table V3',+ component: TableV3,+ decorators: [withCanvas({ height: 360, maxWidth: 640, overflow: 'auto' })],+ args: {+ columns,+ config: { defaultColumnMinSize: 120, defaultColumnMaxSize: 400 },+ data: rows,+ setColumnWidths: (): void => undefined,+ },+} satisfies Meta<ITableV3Props<TraceRow>>;++export default meta;++type Story = StoryObj<typeof meta>;++/** Density and overflow: the virtualized table's wide, resizable column layout. */+export const WideVirtualizedDataset: Story = {};++/** Data: the table's native no-row layout, with headers retained for structural review. */+export const EmptyDataset: Story = {+ args: { data: [] },+};diff --git a/frontend/src/components/TanStackTableView/stories/TanStackTableView.stories.tsx b/frontend/src/components/TanStackTableView/stories/TanStackTableView.stories.tsxnew file mode 100644index 0000000000..246c769e8e--- /dev/null+++ b/frontend/src/components/TanStackTableView/stories/TanStackTableView.stories.tsx@@ -0,0 +1,239 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Color } from '@signozhq/design-tokens';+import { Ellipsis } from '@signozhq/icons';+import { Button } from '@signozhq/ui/button';+import { DropdownMenuSimple } from '@signozhq/ui/dropdown-menu';+import { GroupedStatusCounts } from 'container/InfraMonitoringK8sV2/components/GroupedStatusCounts';+import type { StatusCountItem } from 'container/InfraMonitoringK8sV2/components/GroupedStatusCounts';+import { ValidateColumnValueWrapper } from 'container/InfraMonitoringK8sV2/components/ValidateColumnValueWrapper';+import { InfraMonitoringEntity } from 'container/InfraMonitoringK8sV2/constants';+import { expect, screen, userEvent, within } from 'storybook/test';++import { withCanvas } from '@/storybook/decorators/withCanvas';+import type { GlobalMockArgs } from '@/storybook/globals';++import TanStackTable from '../index';+import type { TableColumnDef, TanStackTableProps } from '../types';++type ServiceRow = {+ id: string;+ service: string;+ endpoint: string;+ latency: string;+ owner: string;+};++const rows: ServiceRow[] = [+ {+ id: 'checkout',+ service: 'checkout-service',+ endpoint: 'POST /api/v1/checkout',+ latency: '184 ms',+ owner: 'Payments platform',+ },+ {+ id: 'catalog',+ service: 'catalog-service',+ endpoint: 'GET /api/v2/products/{productId}/availability',+ latency: '96 ms',+ owner: 'Storefront experience',+ },+ {+ id: 'identity',+ service: 'identity-service',+ endpoint: 'POST /api/v1/session/refresh',+ latency: '242 ms',+ owner: 'Identity and access management',+ },+];++const columns: TableColumnDef<ServiceRow>[] = [+ {+ id: 'service',+ header: 'Service',+ accessorKey: 'service',+ pin: 'left',+ width: { fixed: 180 },+ enableSort: true,+ cell: ({ value }): JSX.Element => (+ <TanStackTable.Text>{String(value)}</TanStackTable.Text>+ ),+ },+ {+ id: 'endpoint',+ header: 'Endpoint',+ accessorKey: 'endpoint',+ width: { fixed: 320 },+ cell: ({ value }): JSX.Element => (+ <TanStackTable.Text title={String(value)}>+ {String(value)}+ </TanStackTable.Text>+ ),+ },+ {+ id: 'latency',+ header: 'P95 latency',+ accessorKey: 'latency',+ width: { fixed: 140 },+ enableSort: true,+ cell: ({ value }): JSX.Element => (+ <TanStackTable.Text>{String(value)}</TanStackTable.Text>+ ),+ },+ {+ id: 'owner',+ header: 'Owner',+ accessorKey: 'owner',+ width: { fixed: 240 },+ cell: ({ value }): JSX.Element => (+ <TanStackTable.Text>{String(value)}</TanStackTable.Text>+ ),+ },+];++const rowActions = (): JSX.Element => (+ <DropdownMenuSimple+ align="end"+ menu={{+ items: [+ { key: 'open', label: 'Open service details' },+ { key: 'copy', label: 'Copy service link' },+ ],+ }}+ >+ <Button+ aria-label="Service actions"+ color="secondary"+ size="icon"+ variant="outlined"+ >+ <Ellipsis size={16} />+ </Button>+ </DropdownMenuSimple>+);++const meta = {+ title: 'Components/TanStack Table View',+ component: TanStackTable,+ tags: ['play'],+ decorators: [withCanvas({ height: 360, maxWidth: 640 })],+ args: {+ columns,+ data: rows,+ disableVirtualScroll: true,+ getRowKey: (row): string => row.id,+ },+} satisfies Meta<TanStackTableProps<ServiceRow>>;++export default meta;++type Story = StoryObj<typeof meta>;++type TooltipsStory = StoryObj<GlobalMockArgs>;++/** Data and overflow: pinned columns, clipped long cells, and a horizontal scroll surface. */+export const HorizontalOverflow: Story = {+ args: { testId: 'tanstack-table' },+};++/** Data: a page-sized result with the shared pagination controls and total count. */+export const Pagination: Story = {+ args: {+ pagination: { total: 42, defaultLimit: 10, showTotalCount: true },+ },+};++/** Data: the supported empty result keeps the table structure without a fabricated empty state. */+export const Empty: Story = {+ args: { data: [], testId: 'tanstack-empty-table' },+};++/** Data: the table's real skeleton rows shown while the first page is loading. */+export const Loading: Story = {+ args: { data: [], isLoading: true, skeletonRowCount: 5 },+};++/** Interaction: opens a row action menu rendered through the shared portal. */+export const RowActionsMenu: Story = {+ args: { renderRowActions: rowActions, testId: 'tanstack-actions-table' },+ play: async ({ canvasElement }): Promise<void> => {+ const firstRow = within(canvasElement).getByTestId('tanstack-actions-table');++ await userEvent.hover(firstRow.querySelector('tbody tr') as HTMLElement);+ await userEvent.click(+ await within(firstRow).findByLabelText('Service actions'),+ );+ await expect(+ await screen.findByRole('menuitem', { name: 'Open service details' }),+ ).toBeVisible();+ },+};++const RESTART_COUNTS: StatusCountItem[] = [+ {+ label: 'Restarts in the last 24 hours',+ value: 37,+ color: Color.BG_CHERRY_500,+ breakdown: [+ { label: 'CrashLoopBackOff', value: 14 },+ { label: 'OOMKilled', value: 11 },+ { label: 'Liveness probe failed', value: 6 },+ { label: 'Readiness probe failed', value: 4 },+ { label: 'Image pull backoff', value: 2 },+ ],+ },+];++const tooltipColumns: TableColumnDef<ServiceRow>[] = [+ columns[0],+ {+ id: 'cpuRequest',+ header: 'CPU request',+ width: { fixed: 140 },+ cell: ({ rowId }): JSX.Element => (+ <ValidateColumnValueWrapper+ attribute="CPU request"+ entity={InfraMonitoringEntity.PODS}+ rowId={rowId}+ value={-1}+ >+ <TanStackTable.Text>0.5</TanStackTable.Text>+ </ValidateColumnValueWrapper>+ ),+ },+ {+ id: 'restarts',+ header: 'Restarts',+ width: { fixed: 140 },+ cell: ({ rowId }): JSX.Element => (+ <GroupedStatusCounts items={RESTART_COUNTS} rowId={rowId} />+ ),+ },+];++/**+ * Both tooltips a hovered row carries, held open: the plain sentence explaining+ * a missing value, and the status breakdown, which is elements rather than text+ * and grows a row per reason. Neither is rendered until the row is hovered, so+ * the play hovers the first one and the control holds what it uncovered.+ */+export const Tooltips: TooltipsStory = {+ args: { tooltipsOpen: true },+ render: (): JSX.Element => (+ <TanStackTable+ columns={tooltipColumns}+ data={rows}+ disableVirtualScroll+ getRowKey={(row): string => row.id}+ testId="tanstack-tooltips-table"+ />+ ),+ play: async ({ canvasElement }): Promise<void> => {+ const table = within(canvasElement).getByTestId('tanstack-tooltips-table');++ await userEvent.hover(table.querySelector('tbody tr') as HTMLElement);+ // Both tooltips are rendered by the hovered row, so this is what says the+ // control has something to hold open.+ await screen.findByText('Restarts in the last 24 hours');+ },+};diff --git a/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.tsx b/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.tsxindex 6b6128e373..1e7095e072 100644--- a/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.tsx+++ b/frontend/src/container/AIAssistant/components/ChatInput/ChatInput.tsx@@ -450,6 +450,12 @@ export default function ChatInput({return;}el.style.height = 'auto';+ // A hidden composer (a closed drawer, a story swapping in) measures 0.+ // Leaving the height on `auto` keeps the `rows` fallback until there is+ // something real to measure, instead of pinning the field shut.+ if (el.scrollHeight === 0) {+ return;+ }el.style.height = `${Math.min(el.scrollHeight, TEXTAREA_MAX_HEIGHT_PX)}px`;}, [text]);diff --git a/frontend/src/container/CustomDomainSettings/CustomDomainSettings.tsx b/frontend/src/container/CustomDomainSettings/CustomDomainSettings.tsxindex ea68782f9e..cd905f165b 100644--- a/frontend/src/container/CustomDomainSettings/CustomDomainSettings.tsx+++ b/frontend/src/container/CustomDomainSettings/CustomDomainSettings.tsx@@ -207,7 +207,12 @@ export default function CustomDomainSettings(): JSX.Element {><DropdownMenu><DropdownMenuTrigger asChild>- <Button variant="link" color="none" disabled={isFetchingHosts}>+ <Button+ variant="link"+ color="none"+ data-testid="custom-domain-menu-trigger"+ disabled={isFetchingHosts}+ ><Link2 size={12} /><span>{stripProtocol(activeHost?.url ?? '')}</span><ChevronDown size={12} />diff --git a/frontend/src/container/Download/Download.tsx b/frontend/src/container/Download/Download.tsxindex 95ee5610d1..5cfa3b79fe 100644--- a/frontend/src/container/Download/Download.tsx+++ b/frontend/src/container/Download/Download.tsx@@ -71,6 +71,7 @@ function Download({ data, isLoading, fileName }: DownloadProps): JSX.Element {<DropdownMenuSimple menu={menu}><ButtonclassName="download-button"+ data-testid="download-menu-trigger"loading={isLoading || isDownloading}size="small"type="link"diff --git a/frontend/src/container/LLMObservability/Settings/ModelPricing/ModelCostTabPanel/components/ModelCostsTable/ModelCostActionsMenu.tsx b/frontend/src/container/LLMObservability/Settings/ModelPricing/ModelCostTabPanel/components/ModelCostsTable/ModelCostActionsMenu.tsxindex a11eaa31db..0d45966b7f 100644--- a/frontend/src/container/LLMObservability/Settings/ModelPricing/ModelCostTabPanel/components/ModelCostsTable/ModelCostActionsMenu.tsx+++ b/frontend/src/container/LLMObservability/Settings/ModelPricing/ModelCostTabPanel/components/ModelCostsTable/ModelCostActionsMenu.tsx@@ -50,6 +50,7 @@ function ModelCostActionsMenu({color="secondary"size="icon"className={styles.actionButton}+ aria-label="Model cost actions"testId={`model-cost-actions-${rule.id}`}><Ellipsis size={16} />diff --git a/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx b/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsxindex 12ae50c6de..e1045a7315 100644--- a/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx+++ b/frontend/src/container/MetricsExplorer/MetricDetails/DashboardsAndAlertsPopover.tsx@@ -136,6 +136,7 @@ function DashboardsAndAlertsPopover({><divclassName="dashboards-and-alerts-popover dashboards-popover"+ data-testid="metric-dashboards-popover"style={{ backgroundColor: `${Color.BG_SIENNA_500}33` }}><Grid2X2 size={12} color={Color.BG_SIENNA_500} />@@ -154,6 +155,7 @@ function DashboardsAndAlertsPopover({><divclassName="dashboards-and-alerts-popover alerts-popover"+ data-testid="metric-alerts-popover"style={{ backgroundColor: `${Color.BG_SAKURA_500}33` }}><Bell size={12} color={Color.BG_SAKURA_500} />diff --git a/frontend/src/modules/Servicemap/stories/ServiceMap.stories.mocks.tsx b/frontend/src/modules/Servicemap/stories/ServiceMap.stories.mocks.tsxnew file mode 100644index 0000000000..4e1aa7beb9--- /dev/null+++ b/frontend/src/modules/Servicemap/stories/ServiceMap.stories.mocks.tsx@@ -0,0 +1,131 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import { encode } from 'js-base64';+import type { Tags } from 'hooks/useResourceAttribute/types';++import {+ choiceControl,+ countControl,+ multiChoiceControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ attributeKeysFor,+ attributeKeysResponse,+ attributeValuesFor,+ attributeValuesResponse,+ dependencyGraphResponse,+ MAX_DEPENDENCIES,+ RESOURCE_FILTERS,+ type ResourceFilter,+ resourceFilterQueries,+ SERVICE_HEALTH,+ type ServiceHealth,+} from './__story_mockdata__/serviceMap';++const GRAPH = 'Service map · graph';+const FILTERS = 'Service map · filters';++interface DependencyGraphBody {+ tags?: Tags[];+}++const serviceMapRoute = (filters: readonly ResourceFilter[]): string => {+ if (filters.length === 0) {+ return ROUTES.SERVICE_MAP;+ }++ const params = new URLSearchParams({+ [QueryParams.resourceAttributes]: encode(+ JSON.stringify(resourceFilterQueries(filters)),+ ),+ });++ return `${ROUTES.SERVICE_MAP}?${params.toString()}`;+};++export const serviceMapMocks = defineStoryMocks({+ controls: {+ services: countControl('Dependencies', {+ group: GRAPH,+ description:+ 'Call edges the endpoint answers with. Every one of them is a link and its two nodes; 0 is the "No Service Found" card.',+ value: MAX_DEPENDENCIES,+ max: MAX_DEPENDENCIES,+ }),+ health: choiceControl<ServiceHealth>('Service health', {+ group: GRAPH,+ description:+ 'Error rate on the calls into a service, which is what turns its node red.',+ options: SERVICE_HEALTH,+ value: 'degraded',+ }),+ filters: multiChoiceControl<ResourceFilter>('Applied filters', {+ group: FILTERS,+ description:+ 'Resource attributes the page opens with, as the environment selector and a chip. The graph narrows to what they match.',+ options: RESOURCE_FILTERS,+ value: [],+ }),+ environments: countControl('Environments', {+ group: FILTERS,+ description: 'Values the environment selector offers.',+ value: 3,+ max: 5,+ }),+ resourceAttributes: toggleControl('Resource attributes ingested', {+ group: FILTERS,+ description:+ 'Off answers both autocomplete endpoints with nothing, which is what the filter reports as no resource attributes available.',+ value: true,+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v1/dependency_graph',+ response.json(async (req) => {+ const body = (await req.json()) as DependencyGraphBody;++ return dependencyGraphResponse({+ count: values.services,+ health: values.health,+ tags: body.tags,+ });+ }),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_keys',+ response.json((req) =>+ attributeKeysResponse(+ values.resourceAttributes+ ? attributeKeysFor(req.url.searchParams.get('searchText'))+ : [],+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ attributeValuesResponse(+ values.resourceAttributes+ ? attributeValuesFor(+ req.url.searchParams.get('attributeKey'),+ values.environments,+ )+ : [],+ ),+ ),+ ),+ ],+ config: (values) => ({ route: serviceMapRoute(values.filters) }),+});diff --git a/frontend/src/modules/Servicemap/stories/ServiceMap.stories.tsx b/frontend/src/modules/Servicemap/stories/ServiceMap.stories.tsxnew file mode 100644index 0000000000..117428ed07--- /dev/null+++ b/frontend/src/modules/Servicemap/stories/ServiceMap.stories.tsx@@ -0,0 +1,99 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { serviceMapMocks } from './ServiceMap.stories.mocks';++import ServiceMapContainer from '../index';++type ServiceMapArgs = PageStoryArgs<typeof serviceMapMocks>;++const pageStory = storyMocks(serviceMapMocks, { layout: 'app' });++/**+ * Service to service calls as a force graph over `/api/v1/dependency_graph`,+ * nodes sized by request rate and coloured by error rate, with link details on+ * hover.+ *+ * Route: `/service-map`.+ */+const meta = {+ title: 'Pages/Services/Service Map',+ tags: ['beta', 'play'],+ component: ServiceMapContainer,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ServiceMapArgs>;++export default meta;++type Story = StoryObj<ServiceMapArgs>;++/** The keys are only fetched once the select opens, past the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The whole topology: one node per service, sized by how many calls it takes,+ * red where those calls are failing, and a link per dependency carrying the+ * latency and error rate its tooltip reports.+ */+export const Default: Story = {};++/** A topology without service errors, preserving the healthy node treatment. */+export const HealthyTopology: Story = {+ args: { health: 'healthy' },+};++/**+ * The map narrowed to one environment and one cluster: the environment selector+ * carries the first, a chip carries the second, and the graph is what is left.+ */+export const Filtered: Story = {+ args: { filters: ['environment', 'cluster'] },+};++/** A workspace with no dependencies recorded in the selected time range. */+export const NoServices: Story = {+ args: { services: 0 },+};++/** The filter's real empty branch when no resource attributes have been ingested. */+export const NoResourceAttributes: Story = {+ args: { resourceAttributes: false },+ play: async ({ canvasElement }): Promise<void> => {+ const filter = await within(canvasElement).findByTestId(+ 'resource-attributes-filter',+ undefined,+ untilLoaded,+ );++ await userEvent.click(within(filter).getByRole('combobox'));+ await screen.findByText(+ /No resource attributes available to filter/i,+ undefined,+ untilLoaded,+ );+ },+};++/**+ * The attribute filter open: of everything the endpoint returns, the map only+ * offers the three keys it can send to `/dependency_graph`.+ */+export const FilterAttributes: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);+ const filter = await canvas.findByTestId(+ 'resource-attributes-filter',+ undefined,+ untilLoaded,+ );++ // The select opens on a press inside it: a click on the wrapper the test id+ // sits on never reaches the handler that opens the list.+ await userEvent.click(within(filter).getByRole('combobox'));+ await screen.findByText('k8s.cluster.name', undefined, untilLoaded);+ },+};diff --git a/frontend/src/modules/Servicemap/stories/__story_mockdata__/serviceMap.ts b/frontend/src/modules/Servicemap/stories/__story_mockdata__/serviceMap.tsnew file mode 100644index 0000000000..3ea5f4bcb1--- /dev/null+++ b/frontend/src/modules/Servicemap/stories/__story_mockdata__/serviceMap.ts@@ -0,0 +1,354 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ IResourceAttribute,+ Tags,+} from 'hooks/useResourceAttribute/types';+import { getResourceDeploymentKeys } from 'hooks/useResourceAttribute/utils';+import type { ServicesMapItem } from 'store/actions/serviceMap';+import type {+ TagKeysPayloadProps,+ TagValuesPayloadProps,+} from 'types/api/metrics/getResourceAttributes';+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';++export const SERVICE_HEALTH = ['healthy', 'degraded', 'failing'] as const;++export type ServiceHealth = (typeof SERVICE_HEALTH)[number];++interface Dependency {+ parent: string;+ child: string;+ callCount: number;+ callRate: number;+ /** Nanoseconds: the link tooltip divides by 1e6 to show milliseconds. */+ p99: number;+ environment: string;+ cluster: string;+}++/**+ * One call edge per entry, parents before children, so slicing the head of the+ * list keeps the graph connected instead of leaving orphaned nodes behind.+ */+const DEPENDENCIES: Dependency[] = [+ {+ parent: 'gateway',+ child: 'frontend',+ callCount: 41200,+ callRate: 68.4,+ p99: 184_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'frontend',+ child: 'auth',+ callCount: 12800,+ callRate: 21.3,+ p99: 46_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'frontend',+ child: 'catalogue',+ callCount: 18600,+ callRate: 31,+ p99: 92_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'frontend',+ child: 'cart',+ callCount: 9400,+ callRate: 15.6,+ p99: 58_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'cart',+ child: 'redis',+ callCount: 7300,+ callRate: 12.1,+ p99: 4_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'catalogue',+ child: 'mysql',+ callCount: 15200,+ callRate: 25.3,+ p99: 31_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'auth',+ child: 'mysql',+ callCount: 8100,+ callRate: 13.5,+ p99: 27_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'frontend',+ child: 'checkout',+ callCount: 6200,+ callRate: 10.3,+ p99: 210_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'checkout',+ child: 'payments',+ callCount: 5900,+ callRate: 9.8,+ p99: 340_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'checkout',+ child: 'shipping',+ callCount: 5400,+ callRate: 9,+ p99: 120_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'payments',+ child: 'stripe-proxy',+ callCount: 5100,+ callRate: 8.5,+ p99: 290_000_000,+ environment: 'production',+ cluster: 'prod-us-east',+ },+ {+ parent: 'shipping',+ child: 'geo-service',+ callCount: 4700,+ callRate: 7.8,+ p99: 76_000_000,+ environment: 'production',+ cluster: 'prod-eu-west',+ },+ {+ parent: 'geo-service',+ child: 'redis',+ callCount: 4300,+ callRate: 7.1,+ p99: 3_000_000,+ environment: 'production',+ cluster: 'prod-eu-west',+ },+ {+ parent: 'catalogue',+ child: 'recommendations',+ callCount: 3800,+ callRate: 6.3,+ p99: 150_000_000,+ environment: 'staging',+ cluster: 'staging-eu',+ },+ {+ parent: 'recommendations',+ child: 'ml-inference',+ callCount: 3500,+ callRate: 5.8,+ p99: 480_000_000,+ environment: 'staging',+ cluster: 'staging-eu',+ },+ {+ parent: 'notifications',+ child: 'email-relay',+ callCount: 900,+ callRate: 1.5,+ p99: 65_000_000,+ environment: 'staging',+ cluster: 'staging-eu',+ },+];++export const MAX_DEPENDENCIES = DEPENDENCIES.length;++const DEGRADED_SERVICES = ['payments', 'redis'];++const ERROR_RATES = [1.2, 3.4, 0.8, 6.1, 2.5];++const errorRateFor = (+ child: string,+ health: ServiceHealth,+ index: number,+): number => {+ if (health === 'healthy') {+ return 0;+ }++ if (health === 'degraded' && !DEGRADED_SERVICES.includes(child)) {+ return 0;+ }++ return ERROR_RATES[index % ERROR_RATES.length];+};++const ATTRIBUTE_BY_TAG_KEY: Record<string, 'environment' | 'cluster'> = {+ 'deployment.environment': 'environment',+ 'k8s.cluster.name': 'cluster',+};++/**+ * The page sends its resource-attribute chips as trace tags, so the response has+ * to narrow with them: a filter that changed nothing would look broken.+ */+const matchesTag = (dependency: Dependency, tag: Tags): boolean => {+ const attribute = ATTRIBUTE_BY_TAG_KEY[tag.Key];++ if (!attribute) {+ return true;+ }++ const matched = tag.StringValues.includes(dependency[attribute]);++ return tag.Operator === 'NotIn' ? !matched : matched;+};++interface DependencyGraphOptions {+ count: number;+ health: ServiceHealth;+ tags?: Tags[];+}++export const dependencyGraphResponse = ({+ count,+ health,+ tags = [],+}: DependencyGraphOptions): ServicesMapItem[] =>+ DEPENDENCIES.slice(0, count)+ .filter((dependency) => tags.every((tag) => matchesTag(dependency, tag)))+ .map(({ parent, child, callCount, callRate, p99 }, index) => ({+ parent,+ child,+ callCount,+ callRate,+ p99,+ errorRate: errorRateFor(child, health, index),+ }));++const ENVIRONMENT_KEY = 'resource_deployment_environment';+const CLUSTER_KEY = 'resource_k8s_cluster_name';+const NAMESPACE_KEY = 'resource_k8s_cluster_namespace';++/**+ * `service.name` and `host.name` are not in the service-map whitelist, so they+ * are here to be dropped: the page filters the keys it offers down to the three+ * it can send to `/dependency_graph`.+ */+const ATTRIBUTE_KEYS = [+ ENVIRONMENT_KEY,+ CLUSTER_KEY,+ NAMESPACE_KEY,+ 'resource_service_name',+ 'resource_host_name',+];++const ENVIRONMENTS = [+ 'production',+ 'staging',+ 'development',+ 'canary',+ 'load-test',+];++const CLUSTERS = ['prod-us-east', 'prod-eu-west', 'staging-eu'];++const NAMESPACES = ['default', 'checkout', 'ingest'];++/**+ * The environment selector asks the same endpoint as the attribute filter, and+ * the deployment key it matches on is the only thing telling the two apart.+ */+export const attributeKeysFor = (searchText: string | null): string[] =>+ searchText === getResourceDeploymentKeys()+ ? [getResourceDeploymentKeys()]+ : ATTRIBUTE_KEYS;++export const attributeValuesFor = (+ attributeKey: string | null,+ environments: number,+): string[] => {+ if (+ attributeKey === getResourceDeploymentKeys() ||+ attributeKey === ENVIRONMENT_KEY+ ) {+ return ENVIRONMENTS.slice(0, environments);+ }++ if (attributeKey === CLUSTER_KEY) {+ return CLUSTERS;+ }++ return attributeKey === NAMESPACE_KEY ? NAMESPACES : [];+};++export const attributeKeysResponse = (+ keys: readonly string[],+): TagKeysPayloadProps & { status: string } => ({+ status: 'success',+ data: {+ attributeKeys: keys.map((key) => ({+ key,+ type: 'resource',+ dataType: DataTypes.String,+ })),+ },+});++export const attributeValuesResponse = (+ values: readonly string[],+): TagValuesPayloadProps & { status: string } => ({+ status: 'success',+ data: {+ boolAttributeValues: null,+ numberAttributeValues: null,+ stringAttributeValues: [...values],+ },+});++export const RESOURCE_FILTERS = ['environment', 'cluster'] as const;++export type ResourceFilter = (typeof RESOURCE_FILTERS)[number];++/**+ * The environment query has to carry the deployment key the app derives, since+ * that is what routes it into the environment selector instead of a chip.+ */+const FILTER_QUERIES: Record<ResourceFilter, IResourceAttribute> = {+ environment: {+ id: 'storybook-environment',+ tagKey: getResourceDeploymentKeys(),+ operator: 'IN',+ tagValue: ['production'],+ },+ cluster: {+ id: 'storybook-cluster',+ tagKey: CLUSTER_KEY,+ operator: 'IN',+ tagValue: ['prod-us-east'],+ },+};++export const resourceFilterQueries = (+ filters: readonly ResourceFilter[],+): IResourceAttribute[] => filters.map((filter) => FILTER_QUERIES[filter]);diff --git a/frontend/src/modules/Usage/stories/Usage.stories.mocks.tsx b/frontend/src/modules/Usage/stories/Usage.stories.mocks.tsxnew file mode 100644index 0000000000..abbc6ecdd7--- /dev/null+++ b/frontend/src/modules/Usage/stories/Usage.stories.mocks.tsx@@ -0,0 +1,47 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ usageResponse,+ usageServicesResponse,+} from './__story_mockdata__/usage';++const SPANS = 'Usage · spans';++export const usageMocks = defineStoryMocks({+ controls: {+ spansPerBucket: countControl('Spans per bucket, in thousands', {+ group: SPANS,+ description:+ 'What each bar carries, which the total above the chart is the sum of. Zero is a workspace sending nothing.',+ value: 240,+ max: 2000,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/usage',+ response.json((req) =>+ usageResponse(+ Number(req.url.searchParams.get('start') ?? 0),+ Number(req.url.searchParams.get('end') ?? 0),+ Number(req.url.searchParams.get('step') ?? 3600),+ values.spansPerBucket * 1000,+ ),+ ),+ ),+ rest.post(+ 'http://localhost/api/v2/services',+ response.json(() => usageServicesResponse()),+ ),+ ],+ config: () => ({ route: ROUTES.USAGE_EXPLORER }),+});diff --git a/frontend/src/modules/Usage/stories/Usage.stories.tsx b/frontend/src/modules/Usage/stories/Usage.stories.tsxnew file mode 100644index 0000000000..46d4d7aeff--- /dev/null+++ b/frontend/src/modules/Usage/stories/Usage.stories.tsx@@ -0,0 +1,36 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import UsageExplorerContainer from '../index';+import { usageMocks } from './Usage.stories.mocks';++type UsageArgs = PageStoryArgs<typeof usageMocks>;++const pageStory = storyMocks(usageMocks, { layout: 'app' });++/**+ * Spans ingested per service over a period, the usage view that predates Cost+ * Meter.+ *+ * Route: `/usage-explorer`.+ */+const meta = {+ title: 'Pages/Metering/Usage Explorer',+ component: UsageExplorerContainer,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<UsageArgs>;++export default meta;++type Story = StoryObj<UsageArgs>;++/** Spans ingested over the window, and the total they add up to. */+export const Default: Story = {};++/** A workspace that has not sent anything yet. */+export const NoSpans: Story = {+ args: { spansPerBucket: 0 },+};diff --git a/frontend/src/modules/Usage/stories/__story_mockdata__/usage.ts b/frontend/src/modules/Usage/stories/__story_mockdata__/usage.tsnew file mode 100644index 0000000000..fc36ba9ab2--- /dev/null+++ b/frontend/src/modules/Usage/stories/__story_mockdata__/usage.ts@@ -0,0 +1,54 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { UsageDataItem } from 'store/actions';+import type { ServicesList } from 'types/api/metrics/getService';++export const USAGE_SERVICES = [+ 'frontend',+ 'checkout',+ 'cart',+ 'payment',+ 'shipping',+];++/** The select is the only thing this page reads a service for. */+export const usageServicesResponse = (): {+ status: string;+ data: ServicesList[];+} => ({+ status: 'success',+ data: USAGE_SERVICES.map((serviceName, index) => ({+ serviceName,+ p99: 120_000_000 + index * 9_000_000,+ avgDuration: 40_000_000,+ numCalls: 12_000 + index * 3_100,+ callRate: 6.4 + index,+ numErrors: 0,+ errorRate: 0,+ })),+});++/**+ * The page asks for its window in nanoseconds and steps through it in seconds,+ * so the buckets are derived from the request rather than pinned: whichever+ * range and interval the selects are on, the bars fill it.+ */+export const usageResponse = (+ startInNanoseconds: number,+ endInNanoseconds: number,+ stepInSeconds: number,+ spansPerBucket: number,+): UsageDataItem[] => {+ const start = Math.floor(startInNanoseconds / 1e9);+ const end = Math.floor(endInNanoseconds / 1e9);+ const step = Math.max(stepInSeconds, 1);+ const buckets = Math.min(Math.max(Math.floor((end - start) / step), 0), 1000);++ return Array.from({ length: buckets }, (_unused, index) => ({+ timestamp: (start + index * step) * 1_000_000_000,+ count: Math.round(spansPerBucket * (0.7 + ((index * 37) % 60) / 100)),+ }));+};diff --git a/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.mocks.tsx b/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.mocks.tsxnew file mode 100644index 0000000000..bbea32599a--- /dev/null+++ b/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.mocks.tsx@@ -0,0 +1,272 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { AI_API_PATH, setAIBackendUrl } from 'api/AIAPIInstance';+import ROUTES from 'constants/routes';+import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';+import { rest, type RequestHandler } from 'msw';++import {+ choiceControl,+ countControl,+ multiChoiceControl,+ toggleControl,+} from '@/storybook/controls/controls';+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 {+ AGENT_STATES,+ type AgentState,+ answeredBlocks,+ chipsResponse,+ EXECUTION_ID,+ executionEvents,+ newConversation,+ NEW_THREAD_ID,+ openConversation,+ THREAD_ID,+ streamingState,+ THREAD_PARTS,+ type ThreadPart,+ threadDetailResponse,+ threadListResponse,+} from './__story_mockdata__/aiAssistant';++const THREAD = 'AI assistant · thread';+const AGENT = 'AI assistant · agent';+const CONVERSATIONS = 'AI assistant · conversations';++/**+ * The assistant talks to its own backend, whose host comes from the global+ * config rather than being the SigNoz API. Pointing it at the same origin is+ * what puts its calls in front of the story's handlers.+ */+const AI_BACKEND_URL = 'http://localhost';++/** The analysis thread, without the turns that carry an interactive block. */+const ANALYSIS: ThreadPart[] = [+ 'prose',+ 'table',+ 'code',+ 'activity',+ 'actions',+ 'voted',+];++/** Suggestions the `@` picker offers under Dashboards. */+const CONTEXT_DASHBOARDS = [+ 'Checkout overview',+ 'Payments upstream',+ 'Ingestion health',+];++/**+ * `useIsAIAssistantEnabled` pushes the assistant's host into the axios instance+ * during render, and pushes `null` for as long as the global config query is in+ * flight. Every call that leaves in that window goes out against an empty base+ * and lands on the page's own origin, so each endpoint answers on both paths+ * rather than the story showing the 404 the app puts there. Reported as an app+ * bug.+ */+const onBothBases = (+ method: 'get' | 'post' | 'patch',+ path: string,+ resolver: MockResolver,+): RequestHandler[] => [+ rest[method](`${AI_BACKEND_URL}${AI_API_PATH}${path}`, resolver),+ rest[method](path, resolver),+];++const ok: MockResolver = (_req, res, ctx) => res(ctx.status(200), ctx.json({}));++const startedExecution: MockResolver = (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ executionId: EXECUTION_ID }));++export const aiAssistantMocks = defineStoryMocks({+ controls: {+ conversation: toggleControl('Open conversation', {+ group: THREAD,+ description:+ 'Off is the empty thread a first visit lands on, with the suggested prompts instead of an exchange.',+ value: true,+ }),+ contents: multiChoiceControl<ThreadPart>('Thread contents', {+ group: THREAD,+ description:+ 'What the open thread holds. Each interactive block arrives as its own turn, and `voted` is a rating already on the last answer.',+ options: THREAD_PARTS,+ value: ANALYSIS,+ }),+ answered: toggleControl('Interactive blocks answered', {+ group: THREAD,+ description:+ 'The question, confirm and action blocks after the user has picked. The choice lives in the store, keyed by message, so it survives a remount.',+ value: false,+ }),+ agent: choiceControl<AgentState>('Agent', {+ group: AGENT,+ description:+ 'What the agent is doing when the thread opens. Both waiting states block the composer until the user answers.',+ options: AGENT_STATES,+ value: 'idle',+ }),+ history: countControl('Past conversations', {+ group: CONVERSATIONS,+ description:+ 'Threads the sidebar lists, the first being the open one, so an open conversation holds the count at one. Their ages spread across every date group.',+ value: 6,+ max: 12,+ }),+ archived: countControl('Archived conversations', {+ group: CONVERSATIONS,+ description: 'Threads under the archived group at the foot of the sidebar.',+ value: 2,+ max: 6,+ }),+ },+ handlers: (values, response) => [+ rest.get('http://localhost/api/v1/global/config', (_req, res, ctx) =>+ res(+ ctx.json({+ ...globalConfigResponse,+ data: {+ ...globalConfigResponse.data,+ ai_assistant_url: AI_BACKEND_URL,+ },+ }),+ ),+ ),++ ...onBothBases(+ 'get',+ '/threads',+ response.json((req) =>+ req.url.searchParams.get('archived') === 'true'+ ? threadListResponse(values.archived, true)+ : // 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,+ ),+ ),+ ),+ ...onBothBases(+ 'get',+ '/threads/:threadId',+ response.json(() => threadDetailResponse(values.contents, values.agent)),+ ),+ ...onBothBases(+ 'get',+ '/empty-state/chips',+ response.json(() => chipsResponse()),+ ),++ // Everything the user can set off from the page. They answer plainly rather+ // than through `response`, so a click still lands while the Data control+ // holds the page's own endpoints on loading or error.+ // The first send of a new conversation mints a thread, and the page puts the+ // id it gets back in the pathname: the overlay reports that as a navigation+ // the story cannot follow, with the answer still streaming underneath.+ ...onBothBases('post', '/threads', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ threadId: THREAD_ID })),+ ),+ ...onBothBases('patch', '/threads/:threadId', ok),+ ...onBothBases('post', '/threads/:threadId/messages', startedExecution),+ ...onBothBases('post', '/messages/:messageId/regenerate', startedExecution),+ ...onBothBases('post', '/messages/:messageId/feedback', ok),+ ...onBothBases('post', '/approve', startedExecution),+ ...onBothBases('post', '/clarify', startedExecution),+ ...onBothBases('post', '/reject', ok),+ ...onBothBases('post', '/cancel', ok),+ ...onBothBases('post', '/undo', ok),+ ...onBothBases('post', '/revert', ok),+ ...onBothBases('post', '/restore', ok),+ ...onBothBases('get', '/executions/:executionId/events', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.set('Content-Type', 'text/event-stream'),+ ctx.body(executionEvents()),+ ),+ ),++ // The composer's `@` picker. Alert rules and services are answered by the+ // shared handlers already; the dashboard list is not.+ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json(() => dashboardsForUserResponse(CONTEXT_DASHBOARDS)),+ ),+ ],+ config: (values) => ({+ // The bare `/ai-assistant` always rewrites itself to the thread it opens,+ // so a story starts on the thread rather than on the redirect.+ route: ROUTES.AI_ASSISTANT.replace(+ ':conversationId',+ values.conversation ? THREAD_ID : NEW_THREAD_ID,+ ),+ }),+ effect: (values) => {+ // The layout fetches the thread list in its mount effect, before the global+ // config query it takes the assistant's host from has answered, so the+ // first call would go out against an empty base. Setting it here is what+ // the config response does, one render earlier.+ setAIBackendUrl(AI_BACKEND_URL);++ // The store is a zustand singleton and persists the answered blocks and the+ // active thread, so a story's state is put there before the tree mounts+ // rather than inherited from whichever story ran last.+ const conversation = values.conversation+ ? openConversation()+ : newConversation();++ useAIAssistantStore.setState({+ conversations: { [conversation.id]: conversation },+ activeConversationId: conversation.id,+ isLoadingThread: false,+ isLoadingThreads: false,+ answeredBlocks: values.answered ? answeredBlocks() : {},+ // A stream is client state with no response behind it: the events the+ // reducer folds into it only exist while the SSE connection is open.+ streams:+ values.agent === 'streaming' ? { [conversation.id]: streamingState() } : {},+ });+ },+});++/**+ * An action chip's tooltip is the one text on the page the backend writes, and+ * the thread fixture keeps it to a line. This answers with the same turns and a+ * chip whose tooltip runs long, so the Thread contents, Interactive blocks+ * answered and Agent controls do not reach the story that uses it. Both bases+ * are covered because the assistant's host is empty while the global config+ * query is in flight, as `onBothBases` above explains.+ */+const LONG_ACTION_TOOLTIP =+ 'Opens the logs explorer on payment.svc.cluster.local:8080, filtered to the 429s it answered between 14:00 and 15:00, with the retry attempt and the upstream quota window already on the table.';++export const longActionTooltipHandlers: RequestHandler[] = onBothBases(+ 'get',+ '/threads/:threadId',+ (_req, res, ctx) => {+ const thread = threadDetailResponse(aiAssistantMocks.args.contents, 'idle');++ return res(+ ctx.status(200),+ ctx.json({+ ...thread,+ messages: thread.messages?.map((message) => ({+ ...message,+ actions: message.actions?.map((action) =>+ action.tooltip ? { ...action, tooltip: LONG_ACTION_TOOLTIP } : action,+ ),+ })),+ }),+ );+ },+);diff --git a/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.tsx b/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.tsxnew file mode 100644index 0000000000..9a82581e28--- /dev/null+++ b/frontend/src/pages/AIAssistantPage/stories/AIAssistantPage.stories.tsx@@ -0,0 +1,245 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';+import { screen, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import AIAssistantPage from '../AIAssistantPage';+import {+ aiAssistantMocks,+ longActionTooltipHandlers,+} from './AIAssistantPage.stories.mocks';+import type { ThreadPart } from './__story_mockdata__/aiAssistant';++type AIAssistantArgs = PageStoryArgs<typeof aiAssistantMocks>;++const pageStory = storyMocks(aiAssistantMocks, { layout: 'app' });++/**+ * Noz, the assistant: a thread of messages over the workspace's telemetry, tool+ * calls and the artefacts they produce rendered inline, and the thread list beside+ * it. The answer arrives as SSE, so it streams inside the story.+ *+ * Route: `/ai-assistant/:conversationId`.+ */+const meta = {+ title: 'Pages/Noz',+ tags: ['play'],+ component: AIAssistantPage,+ // The conversation id is in the pathname, so the page renders under its own+ // route rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route+ path={[ROUTES.AI_ASSISTANT_BASE, ROUTES.AI_ASSISTANT]}+ component={AIAssistantPage}+ />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<AIAssistantArgs>;++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 };++/**+ * 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.+ */+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 });+ }, untilLoaded);+};++/** The blocks the agent renders as cards the user answers in place. */+const INTERACTIVE: ThreadPart[] = [+ 'question',+ 'checkboxes',+ 'confirm',+ 'suggested-action',+];++const QUESTIONS: ThreadPart[] = ['question', 'checkboxes'];++const COMMITMENTS: ThreadPart[] = ['confirm', 'suggested-action'];++/**+ * Two short exchanges and nothing else, so the state the story is about sits in+ * the first screen rather than under a scroll.+ */+const BRIEF: ThreadPart[] = [];++/** A thread mid-investigation, with the earlier ones beside it. */+export const Default: Story = {};++/** The first visit: the suggested prompts and nothing asked yet. */+export const NewConversation: Story = {+ args: { conversation: false, history: 0, archived: 0 },+};++/**+ * The cards the agent puts in the thread when it needs the user to pick: one+ * answer, or several.+ */+export const QuestionBlocks: Story = {+ args: { contents: QUESTIONS },+};++/**+ * The cards that ask the user to commit: a confirmation the agent acts on, and+ * a page action it will apply here.+ */+export const ActionBlocks: Story = {+ args: { contents: COMMITMENTS },+};++/** All four cards once the user has answered them, which the store remembers. */+export const AnsweredBlocks: Story = {+ args: { contents: INTERACTIVE, answered: true },+};++/**+ * Mid-answer: a step already done, the text so far, and a step still running+ * with the elapsed clock on it. The composer waits its turn.+ */+export const Streaming: Story = {+ args: { agent: 'streaming', contents: BRIEF },+};++/** A change the agent will not make until the user reads the diff and approves. */+export const AwaitingApproval: Story = {+ args: { agent: 'awaiting-approval', contents: BRIEF },+};++/** The agent asking for the details it needs, one field per detail. */+export const AwaitingClarification: Story = {+ args: { agent: 'awaiting-clarification', contents: BRIEF },+};++/** Reopening the page on a thread that has not come back yet. */+export const LoadingThread: Story = {+ args: { dataState: 'loading' },+};++/**+ * The steps behind an answer: what the agent thought, and each tool it called+ * with what went in and what came back.+ */+export const ActivityExpanded: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await clickUntil(+ () => canvas.findByText(/worked through/i, undefined, untilLoaded),+ /compared checkout p99/i,+ );+ await clickUntil(+ () => canvas.findByText(/compared checkout p99/i, undefined, untilLoaded),+ /^Output$/,+ );+ },+};++/** Opens the approval card's diff dialog. */+const openApprovalDiff: NonNullable<Story['play']> = async ({+ canvasElement,+}) => {+ await clickUntil(+ () =>+ within(canvasElement).findByLabelText(+ /expand diff/i,+ undefined,+ untilLoaded,+ ),+ /approval diff/i,+ );+};++/** The approval diff at full size, before against after. */+export const ApprovalDiff: Story = {+ args: { agent: 'awaiting-approval', contents: BRIEF },+ play: openApprovalDiff,+};++/** The comment box a thumbs down opens, which a thumbs up does not. */+export const NegativeFeedback: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await clickUntil(async () => {+ // Every assistant message carries the bar; only the last one shows it+ // without a hover.+ const bars = await within(canvasElement).findAllByLabelText(+ /bad response/i,+ undefined,+ untilLoaded,+ );++ return bars[bars.length - 1];+ }, /what went wrong/i);+ },+};++/** What a conversation row offers: rename, a link to it, and archiving. */+export const ConversationActions: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await clickUntil(async () => {+ const [actions] = await within(canvasElement).findAllByLabelText(+ /conversation actions/i,+ undefined,+ untilLoaded,+ );++ return actions;+ }, /copy link/i);+ },+};++/**+ * The composer's context picker: the dashboards, alerts and services a question+ * can be pinned to.+ */+export const AddContext: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await clickUntil(+ () =>+ within(canvasElement).findByRole(+ 'button',+ { name: /add context/i },+ untilLoaded,+ ),+ /checkout overview/i,+ );+ },+};++/**+ * Every tooltip the thread carries, held open at once: the composer's voice and+ * send buttons, the sidebar's new conversation, the copy chip under each user+ * message, the copy, rate and regenerate bar under each answer, the code block's+ * copy, and the action chip's own description.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+ parameters: { msw: { handlers: longActionTooltipHandlers } },+};++/**+ * The approval diff dialog's copy tooltips, one per side of the split view, with+ * the card's own expand held open behind it. Switching the dialog to the unified+ * view replaces the pair with a single Copy diff.+ */+export const TooltipsInApprovalDiff: Story = {+ args: { tooltipsOpen: true, agent: 'awaiting-approval', contents: BRIEF },+ play: openApprovalDiff,+};diff --git a/frontend/src/pages/AIAssistantPage/stories/__story_mockdata__/aiAssistant.ts b/frontend/src/pages/AIAssistantPage/stories/__story_mockdata__/aiAssistant.tsnew file mode 100644index 0000000000..892eb9f94b--- /dev/null+++ b/frontend/src/pages/AIAssistantPage/stories/__story_mockdata__/aiAssistant.ts@@ -0,0 +1,731 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ ApprovalSummaryDTO,+ ChipsResponseDTO,+ ClarificationSummaryDTO,+ MessageActionDTO,+ MessageSummaryDTO,+ ThreadDetailResponseDTO,+ ThreadListResponseDTO,+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';+import {+ ApplyFilterSignalDTO,+ ApprovalActionTypeDTO,+ ApprovalStateDTO,+ ClarificationFieldTypeDTO,+ ClarificationStateDTO,+ FeedbackRatingDTO,+ MessageActionKindDTO,+ MessageContentTypeDTO,+ MessageRoleDTO,+} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';+import type {+ Conversation,+ ConversationStreamState,+ MessageBlock,+} from 'container/AIAssistant/types';++export const THREAD_ID = 'thread-checkout-latency';++/** The thread a first visit mints, which the page opens with nothing in it. */+export const NEW_THREAD_ID = 'thread-new';++export const THREAD_TITLE = 'Checkout p99 regression after 14:00';++/** What the open thread contains, one entry per turn the builder can add. */+export const THREAD_PARTS = [+ 'prose',+ 'table',+ 'code',+ 'activity',+ 'actions',+ 'question',+ 'checkboxes',+ 'confirm',+ 'suggested-action',+ 'voted',+] as const;++export type ThreadPart = (typeof THREAD_PARTS)[number];++/** What the agent is doing when the thread opens. */+export const AGENT_STATES = [+ 'idle',+ 'streaming',+ 'awaiting-approval',+ 'awaiting-clarification',+] as const;++export type AgentState = (typeof AGENT_STATES)[number];++/**+ * Every interactive block reads `answeredBlocks[messageId]`, so a message holds+ * at most one of them: answering either block of a pair would otherwise mark+ * both. Reported as an app bug.+ */+export const MESSAGE_IDS = {+ analysis: 'message-analysis',+ question: 'message-question',+ checkboxes: 'message-checkboxes',+ confirm: 'message-confirm',+ suggestedAction: 'message-suggested-action',+ final: 'message-final',+} as const;++export const EXECUTION_ID = 'execution-checkout-latency';++// ---------------------------------------------------------------------------+// Assistant prose+// ---------------------------------------------------------------------------++const PROSE = `### What changed++\`checkout\` p99 went from **180 ms to 640 ms** at 14:05, and the whole increase sits in the+\`payment.authorize\` span. That span started retrying against a rate-limited upstream, so the+extra time is retry wait rather than compute.++- 12% of calls to \`payment.svc.cluster.local:8080\` answered \`429\`, up from none before 14:00+- retries are capped at three, which matches the 3x jump in span duration+- no deploy landed in the window, so this is upstream capacity and not a regression you shipped++> The upstream quota window resets at 14:00 UTC, which is exactly where the 429s begin.++The escalation path is in the [payment rate limit runbook](https://signoz.io/docs/userguide/payment-rate-limits/).`;++const TABLE = `| Service | p99 before | p99 after | Change | Error rate | Slowest span |+| --- | --- | --- | --- | --- | --- |+| checkout | 180 ms | 640 ms | +256% | 0.4% -> 2.1% | payment.authorize |+| payment | 95 ms | 410 ms | +331% | 0.1% -> 12.0% | upstream.authorize.retry |+| cart | 62 ms | 66 ms | +6% | 0.0% | redis.get |+| catalogue | 44 ms | 45 ms | +2% | 0.0% | postgres.query.products |+| notifications | 210 ms | 214 ms | +2% | 0.2% | kafka.publish |`;++/** The first line runs past the chat column, which is what makes the block scroll. */+const CODE = `Here is the query that isolates the retries:++\`\`\`sql+SELECT toStartOfMinute(timestamp) AS minute, quantile(0.99)(duration_nano / 1e6) AS p99_ms, countIf(status_code = 429) AS rate_limited, count() AS calls+FROM signoz_traces.distributed_signoz_index_v3+WHERE service_name = 'payment'+ AND name = 'upstream.authorize.retry'+ AND timestamp >= now() - INTERVAL 2 HOUR+GROUP BY minute+ORDER BY minute ASC+\`\`\``;++const proseFor = (parts: readonly ThreadPart[]): string =>+ [+ parts.includes('prose') ? PROSE : '',+ parts.includes('table') ? TABLE : '',+ parts.includes('code') ? CODE : '',+ ]+ .filter(Boolean)+ .join('\n\n') || 'The whole increase sits in the `payment.authorize` span.';++// ---------------------------------------------------------------------------+// Blocks+//+// `MessageSummaryDTO.blocks` is `unknown[]`, so the builders type against the+// union the renderer narrows to and cast once on the way into the payload.+// ---------------------------------------------------------------------------++const asBlocks = (blocks: MessageBlock[]): MessageSummaryDTO['blocks'] =>+ blocks as unknown as MessageSummaryDTO['blocks'];++const activityBlocks = (text: string): MessageBlock[] => [+ {+ type: 'thinking',+ content:+ 'The jump is sharp rather than gradual, so a capacity change is more likely than a slow leak. Comparing the span breakdown either side of 14:00 should say which span carries it, and the logs for that span should say why.',+ },+ {+ type: 'tool_call',+ toolCallId: 'call-service-metrics',+ toolName: 'signoz_query_service_metrics',+ displayText: 'Compared checkout p99 either side of 14:00',+ toolInput: {+ service: 'checkout',+ metrics: ['p99', 'error_rate'],+ window: { from: '2026-08-28T13:30:00Z', to: '2026-08-28T14:30:00Z' },+ groupBy: ['span_name'],+ },+ result: {+ p99_before_ms: 180.4,+ p99_after_ms: 640.2,+ top_span: 'payment.authorize',+ contribution: 0.97,+ },+ success: true,+ },+ {+ type: 'tool_call',+ toolCallId: 'call-search-logs',+ toolName: 'signoz_search_logs',+ toolInput: {+ expression:+ "service.name = 'payment' AND severity_text = 'WARN' AND body CONTAINS 'rate limit'",+ limit: 200,+ },+ result:+ '187 of 200 matching lines read: upstream rate limit hit for tenant=acme quota=payment.authorize window=60s retry_after=1.5s remaining=0 endpoint=payment.svc.cluster.local:8080 request_id=01J9Z4Q0R7X2N8M4K6H1F3D5B7',+ success: true,+ },+ { type: 'text', content: text },+ {+ type: 'tool_call',+ toolCallId: 'call-quota',+ toolName: 'signoz_get_upstream_quota',+ displayText: 'Read the upstream quota window',+ toolInput: { endpoint: 'payment.svc.cluster.local:8080' },+ result: { quota: 600, window_seconds: 60, resets_at: '14:00:00Z' },+ success: true,+ },+];++const ACTIONS: MessageActionDTO[] = [+ {+ kind: MessageActionKindDTO.follow_up,+ label: 'Show the retry spans',+ input: {+ intent: 'Show me the payment.authorize retry spans between 14:00 and 15:00.',+ },+ },+ {+ kind: MessageActionKindDTO.apply_filter,+ label: 'Filter logs to the 429s',+ signal: ApplyFilterSignalDTO.logs,+ tooltip: 'Opens the logs explorer with the rate-limit filter applied',+ query: {+ compositeQuery: {+ queries: [+ {+ type: 'builder_query',+ spec: {+ name: 'A',+ signal: 'logs',+ filter: {+ expression: "service.name = 'payment' AND http.status_code = 429",+ },+ },+ },+ ],+ },+ },+ },+ {+ kind: MessageActionKindDTO.open_resource,+ label: 'Open the Checkout dashboard',+ resourceType: 'dashboard',+ resourceId: 'storybook-dashboard-1',+ },+ {+ kind: MessageActionKindDTO.open_docs,+ label: 'Rate limit runbook',+ url: 'https://signoz.io/docs/userguide/payment-rate-limits/',+ },+ {+ kind: MessageActionKindDTO.undo,+ label: 'Undo the threshold change',+ actionMetadataId: 'action-threshold-change',+ resourceType: 'alert',+ resourceId: 'alert-checkout-p99',+ state: 'applied',+ },+ {+ kind: MessageActionKindDTO.revert,+ label: 'Revert the dashboard panel',+ actionMetadataId: 'action-dashboard-panel',+ resourceType: 'dashboard',+ resourceId: 'storybook-dashboard-1',+ },+ {+ kind: MessageActionKindDTO.restore,+ label: 'Restore the archived view',+ actionMetadataId: 'action-archived-view',+ resourceType: 'saved_view',+ resourceId: 'view-payment-retries',+ },+];++// ---------------------------------------------------------------------------+// Interactive blocks. The agent emits these as fenced `ai-<type>` code blocks,+// which `RichCodeBlock` resolves against the block registry.+// ---------------------------------------------------------------------------++const fence = (type: string, data: unknown): string =>+ ['```ai-'.concat(type), JSON.stringify(data, null, 2), '```'].join('\n');++const QUESTION_BLOCK = fence('question', {+ question: 'Which signal should the alert watch?',+ type: 'radio',+ options: [+ { value: 'p99', label: 'Trace p99 on checkout' },+ { value: 'errors', label: 'Error rate on payment' },+ { value: 'rate-limited', label: 'Upstream 429 count' },+ ],+});++const CHECKBOX_BLOCK = fence('question', {+ question: 'Who should the alert notify?',+ type: 'checkbox',+ options: [+ '#checkout-oncall',+ '[email protected]',+ 'PagerDuty: payments',+ ],+});++const CONFIRM_BLOCK = fence('confirm', {+ // The block renders its message as plain text, so markdown would show as+ // literal asterisks.+ message:+ "I'll create the alert Checkout p99 > 500 ms, evaluated every minute over a 5 minute window, notifying #checkout-oncall and PagerDuty.",+ acceptLabel: 'Create the alert',+ rejectLabel: 'Not now',+ acceptText: 'Yes, create it.',+ rejectText: 'No, leave it for now.',+});++const ACTION_BLOCK = fence('action', {+ actionId: 'logs.applyFilter',+ description: 'Filter the logs explorer to the failing payment retries.',+ parameters: {+ signal: 'logs',+ expression: "service.name = 'payment' AND http.status_code = 429",+ from: '2026-08-28T14:00:00Z',+ to: '2026-08-28T15:00:00Z',+ },+});++// ---------------------------------------------------------------------------+// Messages+// ---------------------------------------------------------------------------++type Turn = Omit<MessageSummaryDTO, 'createdAt' | 'updatedAt'>;++const user = (id: string, content: string): Turn => ({+ messageId: id,+ role: MessageRoleDTO.user,+ contentType: MessageContentTypeDTO.markdown,+ content,+});++const assistant = (+ id: string,+ content: string,+ extra: Partial<Turn> = {},+): Turn => ({+ messageId: id,+ role: MessageRoleDTO.assistant,+ contentType: MessageContentTypeDTO.markdown,+ content,+ complete: true,+ ...extra,+});++const turnsFor = (parts: readonly ThreadPart[]): Turn[] => {+ const prose = proseFor(parts);+ const turns: Turn[] = [+ user(+ 'message-opening',+ 'Why did checkout get slower after 14:00? Deploys look clean.',+ ),+ assistant(MESSAGE_IDS.analysis, prose, {+ blocks: parts.includes('activity')+ ? asBlocks(activityBlocks(prose))+ : undefined,+ actions: parts.includes('actions') ? ACTIONS : undefined,+ }),+ ];++ if (parts.includes('question')) {+ turns.push(+ user('message-alert-ask', 'Can you set up an alert so we catch it sooner?'),+ assistant(+ MESSAGE_IDS.question,+ `Before I create it, one choice.\n\n${QUESTION_BLOCK}`,+ ),+ );+ }++ if (parts.includes('checkboxes')) {+ turns.push(+ user('message-signal-pick', 'Trace p99 on checkout.'),+ assistant(MESSAGE_IDS.checkboxes, `Got it. One more.\n\n${CHECKBOX_BLOCK}`),+ );+ }++ if (parts.includes('confirm')) {+ turns.push(+ user('message-notify-pick', '#checkout-oncall and PagerDuty.'),+ assistant(MESSAGE_IDS.confirm, CONFIRM_BLOCK),+ );+ }++ if (parts.includes('suggested-action')) {+ turns.push(+ user('message-logs-ask', 'Show me the failing retries in the logs.'),+ assistant(+ MESSAGE_IDS.suggestedAction,+ `The retries are all on one endpoint, so a single filter covers them.\n\n${ACTION_BLOCK}`,+ ),+ );+ }++ turns.push(+ user('message-upstream-ask', 'Which upstream is rate-limiting us?'),+ assistant(+ MESSAGE_IDS.final,+ '`payment.svc.cluster.local:8080`. It answered `429` on 12% of calls between 14:00 and 15:00, and none in the hour before. The quota is 600 requests per minute and checkout alone asked for 780.',+ {+ feedbackRating: parts.includes('voted')+ ? FeedbackRatingDTO.positive+ : undefined,+ },+ ),+ );++ return turns;+};++/** Chronological, ending a few minutes ago so the feedback bar reads fresh. */+const stamped = (turns: Turn[]): MessageSummaryDTO[] => {+ const last = Date.now() - 4 * 60_000;+ const step = 40_000;+ const first = last - (turns.length - 1) * step;++ return turns.map((turn, index) => {+ const at = new Date(first + index * step).toISOString();+ return { ...turn, createdAt: at, updatedAt: at };+ });+};++// ---------------------------------------------------------------------------+// Pending user input+// ---------------------------------------------------------------------------++const pendingApproval = (): ApprovalSummaryDTO => ({+ approvalId: 'approval-checkout-alert',+ executionId: EXECUTION_ID,+ sourceMessageId: MESSAGE_IDS.final,+ state: ApprovalStateDTO.pending,+ actionType: ApprovalActionTypeDTO.modify,+ resourceType: 'alert',+ summary:+ 'Raise the Checkout p99 alert threshold to 500 ms and add the upstream 429 count as a second condition.',+ diff: {+ before: {+ alert: 'Checkout p99',+ condition: {+ target: 800,+ op: '>',+ matchType: 'atleastOnce',+ evalWindow: '5m0s',+ },+ labels: { severity: 'warning', team: 'checkout' },+ preferredChannels: ['#checkout-oncall'],+ },+ after: {+ alert: 'Checkout p99',+ condition: {+ target: 500,+ op: '>',+ matchType: 'allTheTimes',+ evalWindow: '5m0s',+ secondary: { metric: 'upstream_429_total', target: 50, op: '>' },+ },+ labels: {+ severity: 'critical',+ team: 'checkout',+ runbook: 'payment-rate-limits',+ },+ preferredChannels: ['#checkout-oncall', 'PagerDuty: payments'],+ },+ },+ createdAt: new Date(Date.now() - 30_000).toISOString(),+});++const pendingClarification = (): ClarificationSummaryDTO => ({+ clarificationId: 'clarification-alert-scope',+ executionId: EXECUTION_ID,+ sourceMessageId: MESSAGE_IDS.final,+ state: ClarificationStateDTO.pending,+ message:+ 'I can create the alert, but a few details change what it watches and who hears about it.',+ fields: [+ {+ id: 'service',+ type: ClarificationFieldTypeDTO.select,+ label: 'Service to watch',+ required: true,+ options: ['checkout', 'payment', 'cart'],+ default: 'checkout',+ },+ {+ id: 'window',+ type: ClarificationFieldTypeDTO.number,+ label: 'Evaluation window (minutes)',+ required: true,+ default: '5',+ },+ {+ id: 'severity',+ type: ClarificationFieldTypeDTO.select,+ label: 'Severity',+ options: ['critical', 'warning', 'info'],+ allowCustom: true,+ default: 'warning',+ },+ {+ id: 'channels',+ type: ClarificationFieldTypeDTO.multi_select,+ label: 'Notify',+ required: true,+ options: [+ '#checkout-oncall',+ '[email protected]',+ 'PagerDuty: payments',+ ],+ allowCustom: true,+ default: ['#checkout-oncall'],+ },+ {+ id: 'includeTraces',+ type: ClarificationFieldTypeDTO.boolean,+ label: 'Attach example traces to the notification',+ default: 'true',+ },+ {+ id: 'note',+ type: ClarificationFieldTypeDTO.text,+ label: 'Anything else I should know?',+ },+ ],+ createdAt: new Date(Date.now() - 30_000).toISOString(),+});++// ---------------------------------------------------------------------------+// Responses+// ---------------------------------------------------------------------------++export const threadDetailResponse = (+ parts: readonly ThreadPart[],+ agent: AgentState,+): ThreadDetailResponseDTO => {+ const messages = stamped(turnsFor(parts));++ return {+ threadId: THREAD_ID,+ title: THREAD_TITLE,+ archived: false,+ createdAt: messages[0].createdAt,+ updatedAt: messages[messages.length - 1].createdAt,+ messages,+ // `activeExecutionId` would reconnect the stream and overwrite the seeded+ // one, so the streaming state is left to the store.+ activeExecutionId: null,+ pendingApproval: agent === 'awaiting-approval' ? pendingApproval() : null,+ pendingClarification:+ agent === 'awaiting-clarification' ? pendingClarification() : null,+ };+};++/**+ * Ages that put the list across every bucket `groupByDate` builds: today,+ * yesterday, last 7 days, last 30 days and older.+ */+const AGES_IN_MINUTES = [+ 4, 95, 1_700, 4_400, 15_000, 65_000, 30, 300, 2_000, 6_000, 20_000, 90_000,+];++const TITLES = [+ THREAD_TITLE,+ 'Which endpoints are burning the most ingestion quota?',+ 'Kafka consumer lag on the notifications topic',+ 'Why are the ingestion workers restarting every twenty minutes on the production cluster?',+ 'Trace sampling rate for the cart service',+ 'Postgres connection pool saturation last Friday',+ 'Cost per service for August',+ 'Set up an alert for 5xx on the public API',+ 'Missing spans between gateway and auth',+ 'Log volume spike from the batch importer',+ 'Dashboard for the payments team',+ 'Retention on the debug log pipeline',+];++const ARCHIVED_TITLES = [+ 'Migrating the old APM dashboards',+ 'Alert noise from the staging cluster',+ 'Instrumenting the Go workers',+ 'Trace comparison for release 1.42',+ 'Cost meter setup',+ 'Old runbook questions',+];++export const threadListResponse = (+ count: number,+ archived: boolean,+): ThreadListResponseDTO => {+ const titles = archived ? ARCHIVED_TITLES : TITLES;++ return {+ threads: Array.from({ length: count }, (_unused, index) => {+ const at = new Date(+ Date.now() - AGES_IN_MINUTES[index % AGES_IN_MINUTES.length] * 60_000,+ ).toISOString();++ return {+ threadId:+ !archived && index === 0+ ? THREAD_ID+ : `${archived ? 'thread-archived' : 'thread'}-${index}`,+ title: titles[index % titles.length],+ createdAt: at,+ updatedAt: at,+ archived,+ };+ }),+ hasMore: false,+ };+};++/** The prompts the empty conversation offers before anything is typed. */+export const chipsResponse = (): ChipsResponseDTO => ({+ chips: [+ { id: 'top-errors', text: 'Show me the top errors in the last hour' },+ { id: 'slowest-services', text: 'What services have the highest latency?' },+ { id: 'slow-queries', text: 'Find slow database queries' },+ { id: 'health-overview', text: 'Give me an overview of system health' },+ ],+});++/**+ * One SSE execution, delivered in a single body: msw answers a mocked `fetch`+ * with the whole stream at once, and the reader splits it back into events. The+ * text delta still animates word by word, so a send in a story looks like a+ * send in the app.+ */+export const executionEvents = (): string =>+ [+ { type: 'status', state: 'running' },+ {+ type: 'thinking',+ content:+ 'The thread already has the span breakdown, so the remaining question is whether the quota is per tenant or per endpoint.',+ },+ {+ type: 'tool_call',+ toolName: 'signoz_get_upstream_quota',+ displayText: 'Read the upstream quota window',+ toolInput: { endpoint: 'payment.svc.cluster.local:8080' },+ },+ {+ type: 'tool_result',+ toolName: 'signoz_get_upstream_quota',+ result: { quota: 600, window_seconds: 60, scope: 'per_tenant' },+ },+ {+ type: 'message',+ messageId: 'message-streamed',+ delta:+ 'The quota is per tenant: 600 requests a minute across every endpoint, and checkout alone asked for 780 between 14:00 and 15:00. Raising the retry budget would make it worse, so the fix is either a quota increase or a client-side limiter in front of `payment.authorize`.',+ done: false,+ },+ { type: 'message', messageId: 'message-streamed', done: true },+ { type: 'done' },+ ]+ .map((event) => `data: ${JSON.stringify(event)}\n\n`)+ .join('');++// ---------------------------------------------------------------------------+// Store state+// ---------------------------------------------------------------------------++/**+ * The entry the page resumes on. Empty and hydrating is what the app restores+ * from its persisted active thread, and what makes `fetchThreads` follow up with+ * the thread detail the handlers answer.+ */+export const openConversation = (): Conversation => ({+ id: THREAD_ID,+ threadId: THREAD_ID,+ title: THREAD_TITLE,+ messages: [],+ createdAt: Date.now() - 20 * 60_000,+ updatedAt: Date.now() - 4 * 60_000,+ isHydrating: true,+});++export const newConversation = (): Conversation => ({+ id: NEW_THREAD_ID,+ messages: [],+ createdAt: Date.now(),+ updatedAt: Date.now(),+});++/**+ * A stream caught mid-answer: a finished step, some text, and a step still+ * running, which is the trailing group the elapsed timer ticks on.+ */+export const streamingState = (): ConversationStreamState => ({+ isStreaming: true,+ streamingStatus: 'running',+ streamingMessageId: 'message-streaming',+ streamingActions: null,+ pendingApproval: null,+ pendingClarification: null,+ streamingContent:+ 'The quota is per tenant rather than per endpoint, so every service shares the same 600 requests a minute.',+ streamingEvents: [+ {+ kind: 'thinking',+ content:+ 'The span breakdown is already in the thread, so what is left is whether the quota is scoped to the tenant or to the endpoint.',+ },+ {+ kind: 'tool',+ toolCall: {+ toolName: 'signoz_get_upstream_quota',+ displayText: 'Read the upstream quota window',+ input: { endpoint: 'payment.svc.cluster.local:8080' },+ result: { quota: 600, window_seconds: 60, scope: 'per_tenant' },+ done: true,+ },+ },+ {+ kind: 'text',+ content:+ 'The quota is per tenant rather than per endpoint, so every service shares the same 600 requests a minute.',+ },+ {+ kind: 'thinking',+ content: 'Checking how much of that budget checkout asked for on its own.',+ },+ {+ kind: 'tool',+ toolCall: {+ toolName: 'signoz_query_service_metrics',+ displayText: 'Counting checkout calls per minute',+ input: { service: 'checkout', metric: 'upstream_calls_total' },+ done: false,+ },+ },+ ],+});++/**+ * What each interactive block stores once the user has picked. The shape is+ * per block: a question keeps the answer text, a confirm the choice, an action+ * its outcome.+ */+export const answeredBlocks = (): Record<string, string> => ({+ [MESSAGE_IDS.question]: 'Trace p99 on checkout',+ [MESSAGE_IDS.checkboxes]: '#checkout-oncall, PagerDuty: payments',+ [MESSAGE_IDS.confirm]: 'accepted',+ [MESSAGE_IDS.suggestedAction]:+ 'applied:Filtered the logs explorer to 429s on payment.',+});diff --git a/frontend/src/pages/AlertList/AlertHistory/stories/AlertHistory.stories.mocks.tsx b/frontend/src/pages/AlertList/AlertHistory/stories/AlertHistory.stories.mocks.tsxnew file mode 100644index 0000000000..8ea05c440b--- /dev/null+++ b/frontend/src/pages/AlertList/AlertHistory/stories/AlertHistory.stories.mocks.tsx@@ -0,0 +1,158 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { TIMELINE_TABLE_PAGE_SIZE } from 'container/AlertHistory/constants';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ ruleHistoryFilterKeysResponse,+ ruleHistoryFilterValuesResponse,+ ruleHistoryOverallStatusResponse,+ ruleHistoryStatsResponse,+ ruleHistoryTimelineResponse,+ ruleHistoryTopContributorsResponse,+ TIMELINE_MAX,+ TOP_CONTRIBUTOR_MAX,+ type HistoryWindow,+} from './__story_mockdata__/alertHistory';++import {+ alertRuleByIdResponse,+ ALERT_SCHEMAS,+ channelsResponse,+ CHANNEL_MAX,+ FIRST_RULE_NAME,+ type AlertSchema,+} from '../../stories/__story_mockdata__/alerts';++const STORY_RULE_ID = 'rule-1';+const STORY_RELATIVE_TIME = '6h';++const STATISTICS = 'Alert history · statistics';+const TIMELINE = 'Alert history · timeline';++/** Every history endpoint is asked for the same window the page resolved. */+const windowOf = (req: { url: URL }): HistoryWindow => {+ const end = Number(req.url.searchParams.get('end'));+ const start = Number(req.url.searchParams.get('start'));++ return { start, end };+};++export const alertHistoryMocks = defineStoryMocks({+ controls: {+ triggers: countControl('Times triggered', {+ group: STATISTICS,+ description:+ 'Drives the Total Triggered card, the trigger sparkline and the counts the top contributors add up to. Zero is the card that says nothing fired.',+ value: 48,+ max: 200,+ }),+ resolutionMinutes: countControl('Avg. resolution, minutes', {+ group: STATISTICS,+ description: 'Zero is the card that says nothing was resolved.',+ value: 22,+ max: 180,+ }),+ topContributors: countControl('Top contributors', {+ group: STATISTICS,+ description: 'The label sets that fired most often in the window.',+ value: 5,+ max: TOP_CONTRIBUTOR_MAX,+ }),+ timelineEntries: countControl('Timeline entries', {+ group: TIMELINE,+ description: `The table pages at ${TIMELINE_TABLE_PAGE_SIZE}, so anything past that is a second page.`,+ value: 26,+ max: TIMELINE_MAX,+ }),+ statusWindows: countControl('Status bands', {+ group: TIMELINE,+ description: 'How finely the graph above the table slices the window.',+ value: 30,+ max: 60,+ }),+ alertSchema: choiceControl<AlertSchema>('Alert schema', {+ group: TIMELINE,+ description:+ 'Which form the Overview tab opens the rule in. The history tab only shows it in the breadcrumb and the header.',+ options: ALERT_SCHEMAS,+ value: 'v2',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/rules/:id/history/stats',+ response.json((req) =>+ ruleHistoryStatsResponse(+ windowOf(req),+ values.triggers,+ values.resolutionMinutes,+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/rules/:id/history/top_contributors',+ response.json(() =>+ ruleHistoryTopContributorsResponse(values.topContributors, values.triggers),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/rules/:id/history/overall_status',+ response.json((req) =>+ ruleHistoryOverallStatusResponse(windowOf(req), values.statusWindows),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/rules/:id/history/timeline',+ response.json((req) =>+ ruleHistoryTimelineResponse({+ total: values.timelineEntries,+ limit: TIMELINE_TABLE_PAGE_SIZE,+ end: windowOf(req).end,+ ruleId: String(req.params.id),+ ruleName: FIRST_RULE_NAME,+ }),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/rules/:id/history/filter_keys',+ response.json(() => ruleHistoryFilterKeysResponse()),+ ),++ rest.get(+ 'http://localhost/api/v2/rules/:id/history/filter_values',+ response.json((req) =>+ ruleHistoryFilterValuesResponse(req.url.searchParams.get('key') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/rules/:id',+ response.json((req) =>+ alertRuleByIdResponse(String(req.params.id), {+ severity: 'mixed',+ state: 'mixed',+ schema: values.alertSchema,+ }),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/channels',+ response.json(() => channelsResponse(CHANNEL_MAX)),+ ),+ ],+ config: () => ({+ route: `/alerts/history?ruleId=${STORY_RULE_ID}&relativeTime=${STORY_RELATIVE_TIME}`,+ }),+});diff --git a/frontend/src/pages/AlertList/AlertHistory/stories/AlertHistory.stories.tsx b/frontend/src/pages/AlertList/AlertHistory/stories/AlertHistory.stories.tsxnew file mode 100644index 0000000000..12f476a810--- /dev/null+++ b/frontend/src/pages/AlertList/AlertHistory/stories/AlertHistory.stories.tsx@@ -0,0 +1,51 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { alertHistoryMocks } from './AlertHistory.stories.mocks';++import AlertList from '../../index';++type AlertHistoryArgs = PageStoryArgs<typeof alertHistoryMocks>;++const pageStory = storyMocks(alertHistoryMocks, { layout: 'app' });++/**+ * One rule's firing history: the timeline of state changes, the overall status for+ * the period, and the series contributing most to it.+ *+ * Route: `/alerts/history?ruleId=...`.+ */+const meta = {+ title: 'Pages/Alerts/History',+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<AlertHistoryArgs>;++export default meta;++type Story = StoryObj<AlertHistoryArgs>;++/**+ * How one rule behaved over the selected window: how often it fired, how long+ * it took to resolve, what contributed most, and every state change in order.+ */+export const Default: Story = {};++/** A rule that never fired in the window: both cards say so and the table is empty. */+export const NeverTriggered: Story = {+ args: {+ triggers: 0,+ resolutionMinutes: 0,+ topContributors: 0,+ timelineEntries: 0,+ statusWindows: 0,+ },+};++/** A rule firing constantly, where the timeline pages rather than fits. */+export const Noisy: Story = {+ args: { triggers: 184, timelineEntries: 40, topContributors: 8 },+};diff --git a/frontend/src/pages/AlertList/AlertHistory/stories/__story_mockdata__/alertHistory.ts b/frontend/src/pages/AlertList/AlertHistory/stories/__story_mockdata__/alertHistory.tsnew file mode 100644index 0000000000..c1b3260416--- /dev/null+++ b/frontend/src/pages/AlertList/AlertHistory/stories/__story_mockdata__/alertHistory.ts@@ -0,0 +1,216 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ RuletypesAlertStateDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesSignalDTO,+ type GetRuleHistoryFilterKeys200,+ type GetRuleHistoryFilterValues200,+ type GetRuleHistoryOverallStatus200,+ type GetRuleHistoryStats200,+ type GetRuleHistoryTimeline200,+ type GetRuleHistoryTopContributors200,+ type Querybuildertypesv5LabelDTO,+ type Querybuildertypesv5TimeSeriesDTO,+ type RulestatehistorytypesGettableRuleStateHistoryDTO,+} from 'api/generated/services/sigNoz.schemas';++const MINUTE = 60 * 1000;++/** The labels a rule's history is broken down by, both in the table and the filters. */+export const HISTORY_LABEL_VALUES: Record<string, string[]> = {+ 'service.name': ['checkout', 'payments', 'auth', 'search'],+ 'deployment.environment': ['prod', 'staging'],+ 'host.name': ['ip-10-0-1-14', 'ip-10-0-2-31', 'ip-10-0-3-77'],+ severity: ['critical', 'error', 'warning'],+};++const HISTORY_LABEL_KEYS = Object.keys(HISTORY_LABEL_VALUES);++const labelsFor = (index: number): Querybuildertypesv5LabelDTO[] =>+ HISTORY_LABEL_KEYS.map((name) => {+ const values = HISTORY_LABEL_VALUES[name];++ return { key: { name }, value: values[index % values.length] };+ });++/** Points spread evenly across the window, derived from the index so a re-render redraws the same line. */+const series = (+ start: number,+ end: number,+ points: number,+ base: number,+ amplitude: number,+): Querybuildertypesv5TimeSeriesDTO => {+ const step = (end - start) / Math.max(points - 1, 1);++ return {+ labels: [],+ values: Array.from({ length: points }, (_unused, index) => ({+ timestamp: Math.round(start + index * step),+ value: Math.max(+ 0,+ Math.round(base + amplitude * Math.sin(index / 2.5) + amplitude * 0.4),+ ),+ })),+ };+};++export interface HistoryWindow {+ start: number;+ end: number;+}++/** `currentAvgResolutionTime` is seconds: `formatTime` picks the unit it prints. */+export const ruleHistoryStatsResponse = (+ { start, end }: HistoryWindow,+ triggers: number,+ avgResolutionMinutes: number,+): GetRuleHistoryStats200 => {+ const current = avgResolutionMinutes * 60;+ const past = Math.round(current * 1.35);++ return {+ status: 'success',+ data: {+ totalCurrentTriggers: triggers,+ totalPastTriggers: Math.round(triggers * 0.7),+ currentAvgResolutionTime: current,+ pastAvgResolutionTime: past,+ currentTriggersSeries: series(start, end, 24, triggers / 12, triggers / 8),+ pastTriggersSeries: series(start, end, 24, triggers / 16, triggers / 10),+ currentAvgResolutionTimeSeries: series(start, end, 24, current, current / 3),+ pastAvgResolutionTimeSeries: series(start, end, 24, past, past / 3),+ },+ };+};++export const TOP_CONTRIBUTOR_MAX = 8;++export const ruleHistoryTopContributorsResponse = (+ count: number,+ totalTriggers: number,+): GetRuleHistoryTopContributors200 => ({+ status: 'success',+ data: Array.from({ length: count }, (_unused, index) => ({+ fingerprint: 100_000 + index,+ count: Math.max(1, Math.round(totalTriggers / (index + 2))),+ labels: labelsFor(index),+ relatedLogsLink: 'http://localhost/logs/logs-explorer',+ relatedTracesLink: 'http://localhost/traces-explorer',+ })),+});++/**+ * The graph draws one band per window, so the windows have to tile the range+ * end to end: a gap reads as a hole in the timeline rather than a quiet period.+ */+export const ruleHistoryOverallStatusResponse = (+ { start, end }: HistoryWindow,+ windows: number,+): GetRuleHistoryOverallStatus200 => {+ const step = (end - start) / Math.max(windows, 1);++ return {+ status: 'success',+ data: Array.from({ length: windows }, (_unused, index) => ({+ start: Math.round(start + index * step),+ end: Math.round(start + (index + 1) * step),+ state:+ index % 5 === 0+ ? RuletypesAlertStateDTO.firing+ : RuletypesAlertStateDTO.inactive,+ })),+ };+};++export const TIMELINE_MAX = 40;++export interface TimelineShape {+ total: number;+ limit: number;+ end: number;+ state?: RuletypesAlertStateDTO;+ ruleId: string;+ ruleName: string;+}++const timelineItem = (+ index: number,+ shape: TimelineShape,+): RulestatehistorytypesGettableRuleStateHistoryDTO => {+ const state =+ shape.state ??+ (index % 2 === 0+ ? RuletypesAlertStateDTO.firing+ : RuletypesAlertStateDTO.inactive);++ return {+ ruleId: shape.ruleId,+ ruleName: shape.ruleName,+ fingerprint: 100_000 + (index % TOP_CONTRIBUTOR_MAX),+ labels: labelsFor(index),+ overallState: state,+ overallStateChanged: index % 3 === 0,+ state,+ stateChanged: index % 2 === 0,+ unixMilli: shape.end - index * 7 * MINUTE,+ value: Number((60 + (index % 9) * 4.5).toFixed(2)),+ relatedLogsLink: 'http://localhost/logs/logs-explorer',+ relatedTracesLink: 'http://localhost/traces-explorer',+ };+};++export const ruleHistoryTimelineResponse = (+ shape: TimelineShape,+): GetRuleHistoryTimeline200 => {+ const size = Math.min(shape.limit, shape.total);++ return {+ status: 'success',+ data: {+ total: shape.total,+ nextCursor: shape.total > size ? 'next-page-cursor' : '',+ items: Array.from({ length: size }, (_unused, index) =>+ timelineItem(index, shape),+ ),+ },+ };+};++export const ruleHistoryFilterKeysResponse =+ (): GetRuleHistoryFilterKeys200 => ({+ status: 'success',+ data: {+ complete: true,+ keys: Object.fromEntries(+ HISTORY_LABEL_KEYS.map((name) => [+ name,+ [+ {+ name,+ signal: TelemetrytypesSignalDTO.traces,+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ },+ ],+ ]),+ ),+ },+ });++export const ruleHistoryFilterValuesResponse = (+ key: string,+): GetRuleHistoryFilterValues200 => {+ const values = HISTORY_LABEL_VALUES[key] ?? [];++ return {+ status: 'success',+ data: {+ complete: true,+ values: { stringValues: values, relatedValues: values },+ },+ };+};diff --git a/frontend/src/pages/AlertList/AlertOverview/stories/AlertOverview.stories.mocks.tsx b/frontend/src/pages/AlertList/AlertOverview/stories/AlertOverview.stories.mocks.tsxnew file mode 100644index 0000000000..fef02dfbce--- /dev/null+++ b/frontend/src/pages/AlertList/AlertOverview/stories/AlertOverview.stories.mocks.tsx@@ -0,0 +1,148 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ alertRuleByIdResponse,+ ALERT_SCHEMAS,+ channelsResponse,+ CHANNEL_MAX,+ RULE_STATE_CHOICES,+ SEVERITY_CHOICES,+ type AlertSchema,+ type RuleStateChoice,+ type SeverityChoice,+} from '../../stories/__story_mockdata__/alerts';+import {+ alertFieldKeysResponse,+ alertFieldValuesResponse,+ alertMetricMetadataResponse,+ alertMetricsResponse,+ alertPreviewSeries,+} from '../../stories/__story_mockdata__/alertQuery';++const STORY_RULE_ID = 'rule-1';+const STORY_RELATIVE_TIME = '6h';++const RULE = 'Alert overview · rule';+const PREVIEW = 'Alert overview · preview';++export const alertOverviewMocks = defineStoryMocks({+ controls: {+ alertSchema: choiceControl<AlertSchema>('Alert schema', {+ group: RULE,+ description:+ '`v2` opens the stepper the new alert form uses; `classic` is the single-form page rules written before it still open in.',+ options: ALERT_SCHEMAS,+ value: 'v2',+ }),+ ruleState: choiceControl<RuleStateChoice>('State', {+ group: RULE,+ description: 'The badge next to the rule name in the header.',+ options: RULE_STATE_CHOICES,+ value: 'firing',+ }),+ ruleSeverity: choiceControl<SeverityChoice>('Severity', {+ group: RULE,+ options: SEVERITY_CHOICES,+ value: 'critical',+ }),+ channels: countControl('Notification channels', {+ group: RULE,+ description: 'What the thresholds can be routed to.',+ value: 5,+ max: CHANNEL_MAX,+ }),+ previewSeries: countControl('Preview series', {+ group: PREVIEW,+ description:+ 'Lines the chart above the condition draws. Zero is the preview with nothing to plot.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/rules/:id',+ response.json((req) =>+ alertRuleByIdResponse(String(req.params.id), {+ severity: values.ruleSeverity,+ state: values.ruleState,+ schema: values.alertSchema,+ }),+ ),+ ),++ rest.put('http://localhost/api/v2/rules/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.patch('http://localhost/api/v2/rules/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.delete('http://localhost/api/v2/rules/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.post('http://localhost/api/v2/rules/test', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: { alertCount: 2, message: 'Rule tested against the last 6 hours' },+ }),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/channels',+ response.json(() => channelsResponse(values.channels)),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => alertPreviewSeries(values.previewSeries, req)),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics',+ response.json((req) =>+ alertMetricsResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/metadata',+ response.json((req) =>+ alertMetricMetadataResponse(req.url.searchParams.get('metricName') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ alertFieldKeysResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ alertFieldValuesResponse(+ req.url.searchParams.get('name') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),+ ],+ config: () => ({+ route: `/alerts/overview?ruleId=${STORY_RULE_ID}&relativeTime=${STORY_RELATIVE_TIME}`,+ }),+});diff --git a/frontend/src/pages/AlertList/AlertOverview/stories/AlertOverview.stories.tsx b/frontend/src/pages/AlertList/AlertOverview/stories/AlertOverview.stories.tsxnew file mode 100644index 0000000000..096530a138--- /dev/null+++ b/frontend/src/pages/AlertList/AlertOverview/stories/AlertOverview.stories.tsx@@ -0,0 +1,77 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { alertOverviewMocks } from './AlertOverview.stories.mocks';++import AlertList from '../../index';++type AlertOverviewArgs = PageStoryArgs<typeof alertOverviewMocks>;++const pageStory = storyMocks(alertOverviewMocks, { layout: 'app' });++/**+ * One rule read only: its condition, the series it evaluates against, its state+ * and the channels it notifies.+ *+ * Route: `/alerts/overview?ruleId=...`.+ */+const meta = {+ title: 'Pages/Alerts/Overview',+ tags: ['play'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<AlertOverviewArgs>;++export default meta;++type Story = StoryObj<AlertOverviewArgs>;++/**+ * One alert rule opened up: the query it watches, the condition it fires on and+ * where the notification goes.+ */+export const Default: Story = {};++/** A rule written before the current schema, which opens in the classic form. */+export const ClassicSchema: Story = {+ args: { alertSchema: 'classic' },+};++/** A rule someone turned off: the toggle in the header is what turns it back on. */+export const Disabled: Story = {+ args: { ruleState: 'disabled' },+};++/** A rule with no matching series in the window, so the preview has nothing to draw. */+export const NoPreviewData: Story = {+ args: { previewSeries: 0 },+};++/** The rule id in the URL does not resolve, which is where the page gives up. */+export const RuleNotFound: Story = {+ args: { dataState: 'error' },+ // The mocked rule request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};++/**+ * The rule's own More options menu, open off the header: rename it, duplicate+ * it, or delete it.+ */+export const AlertActionsMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'alert-actions-menu',+ {},+ { timeout: 10000 },+ ),+ );+ await screen.findByRole('menu');+ },+};diff --git a/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.mocks.tsx b/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.mocks.tsxnew file mode 100644index 0000000000..930bfe1dd2--- /dev/null+++ b/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.mocks.tsx@@ -0,0 +1,57 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ alertRulesResponse,+ RULE_MAX,+ RULE_STATE_CHOICES,+ SEVERITY_CHOICES,+ type RuleStateChoice,+ type SeverityChoice,+} from '../../stories/__story_mockdata__/alerts';+import { AlertListTabs } from '../../types';++const LIST = 'Alert rules · list';++export const alertRulesMocks = defineStoryMocks({+ controls: {+ rules: countControl('Alert rules', {+ group: LIST,+ value: 8,+ max: RULE_MAX,+ }),+ ruleSeverity: choiceControl<SeverityChoice>('Severity', {+ group: LIST,+ description:+ 'The severity label every rule carries. `mixed` leaves each rule with its own.',+ options: SEVERITY_CHOICES,+ value: 'mixed',+ }),+ ruleState: choiceControl<RuleStateChoice>('State', {+ group: LIST,+ description:+ 'The evaluation state the Status column shows. `disabled` also switches the row action to Enable.',+ options: RULE_STATE_CHOICES,+ value: 'mixed',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/rules',+ response.json(() =>+ alertRulesResponse(values.rules, {+ severity: values.ruleSeverity,+ state: values.ruleState,+ }),+ ),+ ),+ ],+ config: () => ({ route: `/alerts?tab=${AlertListTabs.ALERT_RULES}` }),+});diff --git a/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.tsx b/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.tsxnew file mode 100644index 0000000000..65d4b0d7b8--- /dev/null+++ b/frontend/src/pages/AlertList/AlertRules/stories/AlertRules.stories.tsx@@ -0,0 +1,135 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { alertRulesMocks } from './AlertRules.stories.mocks';++import AlertList from '../../index';+import { RULE_MAX } from '../../stories/__story_mockdata__/alerts';++type AlertRulesArgs = PageStoryArgs<typeof alertRulesMocks>;++const pageStory = storyMocks(alertRulesMocks, { layout: 'app' });++/**+ * The rule list tab: every rule with its severity, state and channels. Creating+ * and editing follow the legacy editor role.+ *+ * Route: `/alerts?tab=AlertRules`.+ */+const meta = {+ title: 'Pages/Alerts/Rules',+ tags: ['role-gated', 'play'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<AlertRulesArgs>;++export default meta;++type Story = StoryObj<AlertRulesArgs>;++/** The page fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * Every alert rule the org has configured, with the state each one evaluated to+ * on its last run and the severity it fires at.+ */+export const Default: Story = {};++/** A workspace with no rule yet, which is where the tab explains itself. */+export const NoRules: Story = {+ args: { rules: 0 },+};++/** Search: an unmatched query retains the filters and renders the no-results branch. */+export const SearchNoResults: Story = {+ parameters: {+ signoz: { route: '/alerts?tab=AlertRules&search=no-matching-alert-rule' },+ },+};++/** Data: the list remains mounted while its initial request is pending. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** Data: the table's retryable error state after the rule request fails. */+export const LoadError: Story = {+ args: { dataState: 'error' },+ // The mocked rule request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};++/** Density: a second page of rules with the shared pagination controls visible. */+export const Paginated: Story = {+ args: { rules: RULE_MAX },+ parameters: {+ signoz: { route: '/alerts?tab=AlertRules&page=2&limit=10' },+ },+};++/**+ * A viewer: the row actions and the New Alert button are gone, so the tab is+ * read-only.+ */+export const Viewer: Story = {+ args: { access: 'viewer' },+};++/** The per-rule actions: enable or disable, edit, clone and delete. */+export const RowActions: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const [actions] = await within(canvasElement).findAllByTestId(+ 'alert-actions',+ undefined,+ untilLoaded,+ );++ await userEvent.click(actions);+ await screen.findByText(/clone/i);+ },+};++/** Interaction: a disabled rule exposes Enable in its real row-action menu. */+export const RowActionsDisabledRule: Story = {+ args: { ruleState: 'disabled' },+ play: async ({ canvasElement }): Promise<void> => {+ const [actions] = await within(canvasElement).findAllByTestId(+ 'alert-actions',+ undefined,+ untilLoaded,+ );++ await userEvent.click(actions);+ await screen.findByText(/^enable$/i);+ },+};++/** The columns the table can show, including the audit ones it hides by default. */+export const ColumnPicker: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'alert-columns-button',+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(/toggle columns/i);+ },+};++/**+ * Every label badge in the Labels column, held open: each one repeats its own+ * `key: value` with a copy button. The rules carry two labels apiece, which fit+ * the column, so the overflow chip and its list are on the Triggered tab+ * instead.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+};diff --git a/frontend/src/pages/AlertList/Channels/stories/Channels.stories.mocks.tsx b/frontend/src/pages/AlertList/Channels/stories/Channels.stories.mocks.tsxnew file mode 100644index 0000000000..c082fa5400--- /dev/null+++ b/frontend/src/pages/AlertList/Channels/stories/Channels.stories.mocks.tsx@@ -0,0 +1,35 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ CHANNEL_MAX,+ channelsResponse,+} from '../../stories/__story_mockdata__/alerts';+import { AlertListTabs } from '../../types';++const LIST = 'Channels · list';++export const channelsMocks = defineStoryMocks({+ controls: {+ channels: countControl('Notification channels', {+ group: LIST,+ description: 'One per channel type, in the order the seeds declare them.',+ value: 5,+ max: CHANNEL_MAX,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/channels',+ response.json(() => channelsResponse(values.channels)),+ ),+ ],+ config: () => ({ route: `/alerts?tab=${AlertListTabs.CHANNELS}` }),+});diff --git a/frontend/src/pages/AlertList/Channels/stories/Channels.stories.tsx b/frontend/src/pages/AlertList/Channels/stories/Channels.stories.tsxnew file mode 100644index 0000000000..c81fc14ff8--- /dev/null+++ b/frontend/src/pages/AlertList/Channels/stories/Channels.stories.tsx@@ -0,0 +1,61 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { channelsMocks } from './Channels.stories.mocks';++import AlertList from '../../index';++type ChannelsArgs = PageStoryArgs<typeof channelsMocks>;++const pageStory = storyMocks(channelsMocks, { layout: 'app' });++/**+ * Notification channels tab: what a rule can notify, one row per channel.+ *+ * Route: `/alerts?tab=Channels`.+ */+const meta = {+ title: 'Pages/Alerts/Channels/List',+ tags: ['role-gated'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ChannelsArgs>;++export default meta;++type Story = StoryObj<ChannelsArgs>;++/**+ * Where notifications go: every configured channel with the integration it+ * sends through.+ */+export const Default: Story = {};++/** A workspace with nowhere to send an alert yet. */+export const NoChannels: Story = {+ args: { channels: 0 },+};++/** Data: the channel list's existing loading spinner. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** Data: the channel list's retryable request-error branch. */+export const LoadError: Story = {+ args: { dataState: 'error' },+ // The mocked channels request intentionally fails; the resulting console error+ // is the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};++/**+ * A viewer: the Action column and the New Alert Channel button are gone, and+ * the button explains who to ask.+ */+export const Viewer: Story = {+ args: { access: 'viewer' },+};diff --git a/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.mocks.tsx b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.mocks.tsxnew file mode 100644index 0000000000..4e728bf2d1--- /dev/null+++ b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.mocks.tsx@@ -0,0 +1,75 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import type { MockResolver } from '@/storybook/msw/types';++import {+ CHANNEL_ACTION_OUTCOMES,+ channelActionError,+ CHANNEL_TYPES,+ channelResponse,+ type ChannelActionOutcome,+ type ChannelType,+} from '../../stories/__story_mockdata__/alerts';++const STORY_CHANNEL_ID = '1';++const CHANNEL = 'Channel · integration';+const ACTIONS = 'Channel · actions';++const resolveChannelActionSuccess: MockResolver = (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null }));++const rejectChannelAction: MockResolver = (_req, res, ctx) =>+ res(ctx.status(500), ctx.json(channelActionError()));++export const channelsEditMocks = defineStoryMocks({+ controls: {+ channelType: choiceControl<ChannelType>('Channel type', {+ group: CHANNEL,+ description:+ 'The integration the saved channel uses, which decides every field below the type picker.',+ options: CHANNEL_TYPES,+ value: 'slack',+ }),+ saveOutcome: choiceControl<ChannelActionOutcome>('Saving the channel', {+ group: ACTIONS,+ options: CHANNEL_ACTION_OUTCOMES,+ value: 'succeeds',+ }),+ testOutcome: choiceControl<ChannelActionOutcome>('Testing the channel', {+ group: ACTIONS,+ options: CHANNEL_ACTION_OUTCOMES,+ value: 'succeeds',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/channels/:id',+ response.json((req) =>+ channelResponse(String(req.params.id), values.channelType),+ ),+ ),++ rest.put(+ 'http://localhost/api/v1/channels/:id',+ values.saveOutcome === 'fails'+ ? rejectChannelAction+ : resolveChannelActionSuccess,+ ),++ rest.post(+ 'http://localhost/api/v1/testChannel',+ values.testOutcome === 'fails'+ ? rejectChannelAction+ : resolveChannelActionSuccess,+ ),+ ],+ config: () => ({ route: `/alerts/channels/edit/${STORY_CHANNEL_ID}` }),+});diff --git a/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.tsx b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.tsxnew file mode 100644index 0000000000..f2cde2336c--- /dev/null+++ b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.tsx@@ -0,0 +1,161 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { channelsEditMocks } from './ChannelsEdit.stories.mocks';++import AlertList from '../../index';++type ChannelsEditArgs = PageStoryArgs<typeof channelsEditMocks>;++const pageStory = storyMocks(channelsEditMocks, { layout: 'app' });++/**+ * One channel's settings, with the fields its type asks for and the test call the+ * form makes before saving.+ *+ * Route: `/alerts/channels/edit/:id`.+ */+const meta = {+ title: 'Pages/Alerts/Channels/Edit',+ tags: ['play'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ChannelsEditArgs>;++export default meta;++/** The page loads the saved channel before it renders the form. */+const untilLoaded = { timeout: 15_000 };++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.+ */+export const Default: Story = {};++/** Mutation: clearing the required webhook URL surfaces the form's validation feedback. */+export const InvalidRequiredFields: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);+ const webhookUrl = await canvas.findByTestId(+ 'webhook-url-textbox',+ undefined,+ untilLoaded,+ );++ await userEvent.clear(webhookUrl);+ await userEvent.click(+ await canvas.findByTestId('save-channel-button', undefined, untilLoaded),+ );+ await screen.findByText('Webhook URL is mandatory');+ },+};++/** Mutation: a failed test request keeps the edit form open and renders its error feedback. */+export const TestChannelFailure: Story = {+ args: { testOutcome: 'fails' },+ // The mocked test request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'test-channel-button',+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText('Storybook forced channel failure');+ },+};++/** Mutation: a failed save leaves the saved channel editable and surfaces the request error. */+export const SaveFailure: Story = {+ args: { saveOutcome: 'fails' },+ // The mocked save request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'save-channel-button',+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText('Storybook forced channel failure');+ },+};++/**+ * The PagerDuty channel, whose form carries the routing key and the extra+ * details sent with the incident.+ */+export const PagerDuty: Story = {+ args: { channelType: 'pagerduty' },+};++/** The webhook channel, saved with basic auth on the outgoing request. */+export const Webhook: Story = {+ args: { channelType: 'webhook' },+};++/**+ * The Opsgenie channel, whose form carries the integration API key and the+ * priority the alert is raised at.+ */+export const Opsgenie: Story = {+ args: { channelType: 'opsgenie' },+};++/**+ * The email channel, whose only editable field is the comma-separated recipient+ * list: the form keeps the HTML body and the headers it was saved with.+ */+export const Email: Story = {+ args: { channelType: 'email' },+};++/**+ * The Microsoft Teams channel, stored under `msteamsv2_configs` and filled from+ * the channel's incoming webhook.+ */+export const MicrosoftTeams: Story = {+ args: { channelType: 'msteams' },+};++/** The Google Chat channel, filled from the space's incoming webhook. */+export const GoogleChat: Story = {+ args: { channelType: 'googlechat' },+};++/**+ * The Jira channel, which files an issue: the site and project it files into,+ * the transitions that resolve and reopen it, and the API token behind the+ * Atlassian account, which the form reads off the basic auth block.+ */+export const Jira: Story = {+ args: { channelType: 'jira' },+};++/**+ * The Jira Service Management Ops channel, whose tags are stored as one+ * comma-separated string and come back as chips.+ */+export const JiraServiceManagementOps: Story = {+ args: { channelType: 'jsmops' },+};++/**+ * The incident.io channel, pointed at one alert source's events URL with the+ * token for it and the metadata merged over the alert's labels.+ */+export const IncidentIO: Story = {+ args: { channelType: 'incidentio' },+};diff --git a/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.mocks.tsx b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.mocks.tsxnew file mode 100644index 0000000000..f61b61155f--- /dev/null+++ b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.mocks.tsx@@ -0,0 +1,59 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import type { MockResolver } from '@/storybook/msw/types';++import {+ CHANNEL_ACTION_OUTCOMES,+ channelActionError,+ type ChannelActionOutcome,+} from '../../stories/__story_mockdata__/alerts';++const ACTIONS = 'Channel · actions';++const resolveChannelCreated: MockResolver = (_req, res, ctx) =>+ res(ctx.status(201), ctx.json({ status: 'success', data: null }));++const resolveChannelTested: MockResolver = (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null }));++const rejectChannelAction: MockResolver = (_req, res, ctx) =>+ res(ctx.status(500), ctx.json(channelActionError()));++/**+ * The form holds the channel type in component state, so the type itself is+ * stories with a `play` that picks one rather than a control; saving and+ * testing the channel are.+ */+export const channelsNewMocks = defineStoryMocks({+ controls: {+ saveOutcome: choiceControl<ChannelActionOutcome>('Saving the channel', {+ group: ACTIONS,+ options: CHANNEL_ACTION_OUTCOMES,+ value: 'succeeds',+ }),+ testOutcome: choiceControl<ChannelActionOutcome>('Testing the channel', {+ group: ACTIONS,+ options: CHANNEL_ACTION_OUTCOMES,+ value: 'succeeds',+ }),+ },+ handlers: (values) => [+ rest.post(+ 'http://localhost/api/v1/channels',+ values.saveOutcome === 'fails' ? rejectChannelAction : resolveChannelCreated,+ ),++ rest.post(+ 'http://localhost/api/v1/testChannel',+ values.testOutcome === 'fails' ? rejectChannelAction : resolveChannelTested,+ ),+ ],+ config: () => ({ route: '/alerts/channels/new' }),+});diff --git a/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.tsx b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.tsxnew file mode 100644index 0000000000..2bdd242d5e--- /dev/null+++ b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.tsx@@ -0,0 +1,178 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { channelsNewMocks } from './ChannelsNew.stories.mocks';++import AlertList from '../../index';++type ChannelsNewArgs = PageStoryArgs<typeof channelsNewMocks>;++const pageStory = storyMocks(channelsNewMocks, { layout: 'app' });++/**+ * The new channel form: pick a type, fill its fields, test it, save.+ *+ * Route: `/alerts/channels/new`.+ */+const meta = {+ title: 'Pages/Alerts/Channels/New',+ tags: ['play'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ChannelsNewArgs>;++export default meta;++type Story = StoryObj<ChannelsNewArgs>;++/**+ * The type is an antd Select: clicking the element carrying the test id does+ * nothing, the combobox inside it is what opens the list.+ */+const selectChannelType = async (+ canvasElement: HTMLElement,+ label: RegExp,+): Promise<void> => {+ const canvas = within(canvasElement);+ const select = await canvas.findByTestId('channel-type-select');++ await userEvent.click(within(select).getByRole('combobox'));+ await userEvent.click(await screen.findByTitle(label));+ // The form under the Select swaps a render after the option is taken, so the+ // Select's own value is what says the story is on the type it names.+ await within(select).findByTitle(label);+};++/** A new notification channel, on the Slack form the page opens with. */+export const Default: Story = {};++/** Interaction: the channel-type Select opens its real portal-backed option list. */+export const ChannelTypeSelectOpen: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const select = await within(canvasElement).findByTestId(+ 'channel-type-select',+ );++ await userEvent.click(within(select).getByRole('combobox'));+ await screen.findByRole('listbox');+ },+};++/** Mutation: saving without a channel name shows the form's required-field feedback. */+export const InvalidRequiredFields: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId('save-channel-button'),+ );+ await screen.findByText('Channel name is mandatory');+ },+};++/** Mutation: a failed test request opens the application's error feedback. */+export const TestChannelFailure: Story = {+ args: { testOutcome: 'fails' },+ // The mocked test request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId('test-channel-button'),+ );+ await screen.findByText('Storybook forced channel failure');+ },+};++/** Mutation: a failed create request leaves the form visible with error feedback. */+export const SaveFailure: Story = {+ args: { saveOutcome: 'fails' },+ // The mocked save request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.type(+ await canvas.findByTestId('channel-name-textbox'),+ 'Storybook channel',+ );+ await userEvent.type(+ await canvas.findByTestId('webhook-url-textbox'),+ 'https://hooks.slack.com/services/storybook',+ );+ await userEvent.click(await canvas.findByTestId('save-channel-button'));+ await screen.findByText('Storybook forced channel failure');+ },+};++/** The webhook form: the URL to post to and the auth to send with it. */+export const Webhook: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Webhook$/);+ },+};++/** The PagerDuty form: routing key, severity and the incident details. */+export const PagerDuty: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Pagerduty$/);+ },+};++/** The Opsgenie form: the integration API key, the alert body and its priority. */+export const Opsgenie: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Opsgenie$/);+ },+};++/** The email form: the recipients and the HTML body the alert is sent as. */+export const Email: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Email$/);+ },+};++/** The Microsoft Teams form: the channel's incoming webhook and the card text. */+export const MicrosoftTeams: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Microsoft Teams$/);+ },+};++/**+ * The Google Chat form, whose webhook URL is rejected unless it is an https URL+ * on `chat.googleapis.com`.+ */+export const GoogleChat: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Google Chat$/);+ },+};++/**+ * The Jira form: where the issue is filed, the transitions that close and+ * reopen it, and the Atlassian account the API token belongs to.+ */+export const Jira: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Jira$/);+ },+};++/** The Jira Service Management Ops form: the API key, priority and tags. */+export const JiraServiceManagementOps: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^Jira Service Management Ops$/);+ },+};++/** The incident.io form: the alert source's events URL and its token. */+export const IncidentIO: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectChannelType(canvasElement, /^incident\.io$/);+ },+};diff --git a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.mocks.tsx b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.mocks.tsxnew file mode 100644index 0000000000..a308d03310--- /dev/null+++ b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.mocks.tsx@@ -0,0 +1,103 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ DOWNTIME_KINDS,+ DOWNTIME_MAX,+ downtimeSchedulesResponse,+ type DowntimeKind,+} from './__story_mockdata__/plannedDowntime';++import {+ alertRulesResponse,+ RULE_MAX,+} from '../../stories/__story_mockdata__/alerts';+import { AlertListSubTabs, AlertListTabs } from '../../types';++const LIST = 'Planned downtime · list';+const REQUEST = 'Planned downtime · requests';++const REQUEST_STATES = ['loaded', 'error'] as const;+type RequestState = (typeof REQUEST_STATES)[number];++export const plannedDowntimeMocks = defineStoryMocks({+ controls: {+ schedules: countControl('Planned downtimes', {+ group: LIST,+ value: 4,+ max: DOWNTIME_MAX,+ }),+ downtimeKind: choiceControl<DowntimeKind>('Kind', {+ group: LIST,+ description:+ 'A recurring downtime carries a repeat rule instead of an end time, which is what the Repeats row shows.',+ options: DOWNTIME_KINDS,+ value: 'mixed',+ }),+ silencedRules: countControl('Alert rules to silence', {+ group: LIST,+ description:+ 'The rules the form offers, and the names a downtime resolves its silenced ids to.',+ value: 8,+ max: RULE_MAX,+ }),+ schedulesState: choiceControl<RequestState>('Schedules request', {+ group: REQUEST,+ options: REQUEST_STATES,+ value: 'loaded',+ }),+ rulesState: choiceControl<RequestState>('Alert rules request', {+ group: REQUEST,+ options: REQUEST_STATES,+ value: 'loaded',+ }),+ },+ handlers: (values, _response) => [+ rest.get('http://localhost/api/v1/downtime_schedules', (_req, res, ctx) =>+ values.schedulesState === 'error'+ ? res(ctx.status(500), ctx.json({ status: 'error' }))+ : res(+ ctx.json(+ downtimeSchedulesResponse(values.schedules, values.downtimeKind),+ ),+ ),+ ),++ rest.post('http://localhost/api/v1/downtime_schedules', (_req, res, ctx) =>+ res(ctx.status(201), ctx.json({ status: 'success', data: null })),+ ),++ rest.put('http://localhost/api/v1/downtime_schedules/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.delete(+ 'http://localhost/api/v1/downtime_schedules/:id',+ (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.get('http://localhost/api/v2/rules', (_req, res, ctx) =>+ values.rulesState === 'error'+ ? res(ctx.status(500), ctx.json({ status: 'error' }))+ : res(+ ctx.json(+ alertRulesResponse(values.silencedRules, {+ severity: 'mixed',+ state: 'mixed',+ }),+ ),+ ),+ ),+ ],+ config: () => ({+ route: `/alerts?tab=${AlertListTabs.CONFIGURATION}&subTab=${AlertListSubTabs.PLANNED_DOWNTIME}`,+ }),+});diff --git a/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsxnew file mode 100644index 0000000000..fca9eabad3--- /dev/null+++ b/frontend/src/pages/AlertList/PlannedDowntime/stories/PlannedDowntime.stories.tsx@@ -0,0 +1,157 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { plannedDowntimeMocks } from './PlannedDowntime.stories.mocks';+import { FIRST_DOWNTIME_NAME } from './__story_mockdata__/plannedDowntime';++import AlertList from '../../index';++type PlannedDowntimeArgs = PageStoryArgs<typeof plannedDowntimeMocks>;++const pageStory = storyMocks(plannedDowntimeMocks, { layout: 'app' });++/**+ * Windows that silence rules on a schedule, one off or recurring, with the rules+ * each window covers.+ *+ * Route: `/alerts?tab=Configuration&subTab=PlannedDowntime`.+ */+const meta = {+ title: 'Pages/Alerts/Planned Downtime',+ tags: ['role-gated', 'play'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<PlannedDowntimeArgs>;++export default meta;++type Story = StoryObj<PlannedDowntimeArgs>;++/** The page fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The windows where alerting is held back: what is running now, what is+ * scheduled, and which rules each one silences.+ */+export const Default: Story = {};++/** A workspace that has never scheduled a downtime. */+export const NoDowntimes: Story = {+ args: { schedules: 0 },+};++/**+ * A viewer: the edit and delete actions on a row and the New downtime button+ * are gone.+ */+export const Viewer: Story = {+ args: { access: 'viewer' },+};++/** A downtime opened up: who scheduled it, the window, and what it silences. */+export const Expanded: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText(FIRST_DOWNTIME_NAME, undefined, untilLoaded),+ );+ await canvas.findByText(/alerts silenced/i);+ },+};++/** The form a downtime is scheduled in: the window, the repeat and the rules. */+export const NewDowntime: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /new downtime/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(/new planned downtime/i);+ },+};++/** The deletion confirmation opened from the first schedule's real row action. */+export const DeleteDowntimeConfirm: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const action = (+ await within(canvasElement).findByText(+ FIRST_DOWNTIME_NAME,+ undefined,+ untilLoaded,+ )+ )+ .closest('.header-content')+ // The row action holds edit then delete, neither of them labelled.+ ?.querySelectorAll('.action-btn svg')[1];++ if (!action) {+ throw new Error('Downtime delete action did not render');+ }++ await userEvent.click(action);+ // The modal titles itself and its confirm button the same.+ await screen.findByRole('button', { name: 'Delete Schedule' });+ },+};++/** A client-side search with no matching downtime schedule. */+export const SearchNoResults: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);+ const search = await canvas.findByPlaceholderText(+ 'Search for a planned downtime...',+ undefined,+ untilLoaded,+ );++ await userEvent.type(search, 'no matching downtime');+ await canvas.findByRole('table');+ },+};++/** The schedule list request failed. */+export const LoadError: Story = {+ args: { schedulesState: 'error' },+ // The mocked schedules request intentionally fails; the resulting console error+ // is the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};++/** The new-downtime form with its alert-rules request failed. */+export const RulesLoadError: Story = {+ args: { rulesState: 'error' },+ // The mocked rules request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+ play: NewDowntime.play,+};++/** A recurring schedule exposes its recurrence and duration treatment. */+export const RecurringSchedule: Story = {+ args: { downtimeKind: 'recurring' },+};++/** A schedule currently in effect. */+export const ActiveNow: Story = {+ args: { schedules: 1 },+};++/** Native form validation after attempting to save an empty downtime. */+export const FormValidationError: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await NewDowntime.play?.({ canvasElement } as never);+ await userEvent.click(+ await screen.findByRole('button', { name: 'Add downtime schedule' }),+ );+ await screen.findByText('Please enter Name');+ },+};diff --git a/frontend/src/pages/AlertList/PlannedDowntime/stories/__story_mockdata__/plannedDowntime.ts b/frontend/src/pages/AlertList/PlannedDowntime/stories/__story_mockdata__/plannedDowntime.tsnew file mode 100644index 0000000000..313d960b1f--- /dev/null+++ b/frontend/src/pages/AlertList/PlannedDowntime/stories/__story_mockdata__/plannedDowntime.ts@@ -0,0 +1,164 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ AlertmanagertypesMaintenanceKindDTO,+ AlertmanagertypesMaintenanceStatusDTO,+ AlertmanagertypesRepeatOnDTO,+ AlertmanagertypesRepeatTypeDTO,+ type AlertmanagertypesPlannedMaintenanceDTO,+ type ListDowntimeSchedules200,+} from 'api/generated/services/sigNoz.schemas';++const MINUTE = 60 * 1000;+const HOUR = 60 * MINUTE;+const DAY = 24 * HOUR;++const at = (offsetMs: number): string =>+ new Date(Date.now() + offsetMs).toISOString();++export const DOWNTIME_KINDS = ['mixed', 'fixed', 'recurring'] as const;++export type DowntimeKind = (typeof DOWNTIME_KINDS)[number];++interface DowntimeSeed {+ name: string;+ description: string;+ kind: AlertmanagertypesMaintenanceKindDTO;+ status: AlertmanagertypesMaintenanceStatusDTO;+ timezone: string;+ /** Relative to now, so a story always has a live, an upcoming and a past one. */+ startsInMs: number;+ lastsMs: number;+ repeatType?: AlertmanagertypesRepeatTypeDTO;+ repeatOn?: AlertmanagertypesRepeatOnDTO[];+ /** Rule ids from the shared alert seeds; empty silences every rule. */+ alertIds: string[];+}++const SEEDS: DowntimeSeed[] = [+ {+ name: 'Postgres major version upgrade',+ description: 'Primary and replicas are cycled one at a time.',+ kind: AlertmanagertypesMaintenanceKindDTO.fixed,+ status: AlertmanagertypesMaintenanceStatusDTO.active,+ timezone: 'UTC',+ startsInMs: -2 * HOUR,+ lastsMs: 6 * HOUR,+ alertIds: ['rule-5', 'rule-3'],+ },+ {+ name: 'Nightly ETL window',+ description:+ 'The warehouse load runs every night and saturates the ingesters.',+ kind: AlertmanagertypesMaintenanceKindDTO.recurring,+ status: AlertmanagertypesMaintenanceStatusDTO.upcoming,+ timezone: 'Europe/Berlin',+ startsInMs: 8 * HOUR,+ lastsMs: 3 * HOUR,+ repeatType: AlertmanagertypesRepeatTypeDTO.daily,+ alertIds: ['rule-12'],+ },+ {+ name: 'Weekend cluster drain',+ description: 'Nodes are drained for kernel patching.',+ kind: AlertmanagertypesMaintenanceKindDTO.recurring,+ status: AlertmanagertypesMaintenanceStatusDTO.upcoming,+ timezone: 'America/New_York',+ startsInMs: 3 * DAY,+ lastsMs: 4 * HOUR,+ repeatType: AlertmanagertypesRepeatTypeDTO.weekly,+ repeatOn: [+ AlertmanagertypesRepeatOnDTO.saturday,+ AlertmanagertypesRepeatOnDTO.sunday,+ ],+ alertIds: [],+ },+ {+ name: 'Checkout release freeze',+ description: 'Deploy window for the checkout rewrite.',+ kind: AlertmanagertypesMaintenanceKindDTO.fixed,+ status: AlertmanagertypesMaintenanceStatusDTO.expired,+ timezone: 'UTC',+ startsInMs: -9 * DAY,+ lastsMs: 2 * HOUR,+ alertIds: ['rule-1', 'rule-2'],+ },+ {+ name: 'Kafka broker rebalance',+ description: 'Partitions move between brokers, lag spikes are expected.',+ kind: AlertmanagertypesMaintenanceKindDTO.fixed,+ status: AlertmanagertypesMaintenanceStatusDTO.upcoming,+ timezone: 'Asia/Kolkata',+ startsInMs: 26 * HOUR,+ lastsMs: 90 * MINUTE,+ alertIds: ['rule-4'],+ },+ {+ name: 'Monthly billing reconciliation',+ description: 'Batch jobs run long on the first of the month.',+ kind: AlertmanagertypesMaintenanceKindDTO.recurring,+ status: AlertmanagertypesMaintenanceStatusDTO.upcoming,+ timezone: 'UTC',+ startsInMs: 5 * DAY,+ lastsMs: 12 * HOUR,+ repeatType: AlertmanagertypesRepeatTypeDTO.monthly,+ alertIds: ['rule-9'],+ },+];++export const DOWNTIME_MAX = SEEDS.length;++/** The list sorts by last update, and the seeds are built newest first. */+export const FIRST_DOWNTIME_NAME = SEEDS[0].name;++const durationLabel = (ms: number): string =>+ ms % HOUR === 0 ? `${ms / HOUR}h0m0s` : `${Math.round(ms / MINUTE)}m0s`;++const buildSchedule = (+ index: number,+ kind: DowntimeKind,+): AlertmanagertypesPlannedMaintenanceDTO => {+ const seed = SEEDS[index % SEEDS.length];+ const resolvedKind =+ kind === 'mixed' ? seed.kind : (kind as AlertmanagertypesMaintenanceKindDTO);+ const isRecurring =+ resolvedKind === AlertmanagertypesMaintenanceKindDTO.recurring;++ return {+ id: `downtime-${index + 1}`,+ name: seed.name,+ description: seed.description,+ kind: resolvedKind,+ status: seed.status,+ alertIds: seed.alertIds,+ createdAt: at(-(index + 4) * DAY),+ createdBy: '[email protected]',+ updatedAt: at(-(index + 1) * DAY),+ updatedBy: '[email protected]',+ schedule: {+ timezone: seed.timezone,+ startTime: at(seed.startsInMs),+ endTime: isRecurring ? undefined : at(seed.startsInMs + seed.lastsMs),+ recurrence: isRecurring+ ? {+ duration: durationLabel(seed.lastsMs),+ repeatType: seed.repeatType ?? AlertmanagertypesRepeatTypeDTO.daily,+ repeatOn: seed.repeatOn ?? null,+ }+ : undefined,+ },+ };+};++export const downtimeSchedulesResponse = (+ count: number,+ kind: DowntimeKind,+): ListDowntimeSchedules200 => ({+ status: 'success',+ data: Array.from({ length: count }, (_unused, index) =>+ buildSchedule(index, kind),+ ),+});diff --git a/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.mocks.tsx b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.mocks.tsxnew file mode 100644index 0000000000..fa53cf8ac7--- /dev/null+++ b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.mocks.tsx@@ -0,0 +1,87 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ ROUTING_POLICY_MAX,+ routingPoliciesResponse,+} from './__story_mockdata__/routingPolicies';++import {+ CHANNEL_MAX,+ channelNames,+ channelsResponse,+} from '../../stories/__story_mockdata__/alerts';+import { AlertListSubTabs, AlertListTabs } from '../../types';++const LIST = 'Routing policies · list';+const REQUEST = 'Routing policies · requests';++const REQUEST_STATES = ['loaded', 'error'] as const;+type RequestState = (typeof REQUEST_STATES)[number];++export const routingPoliciesMocks = defineStoryMocks({+ controls: {+ policies: countControl('Routing policies', {+ group: LIST,+ description: 'The table paginates at five, so the cap is past that.',+ value: 4,+ max: ROUTING_POLICY_MAX,+ }),+ channels: countControl('Notification channels', {+ group: LIST,+ description:+ 'The channels a policy can route to, and the ones its Channels row names.',+ value: 6,+ max: CHANNEL_MAX,+ }),+ policiesState: choiceControl<RequestState>('Policies request', {+ group: REQUEST,+ options: REQUEST_STATES,+ value: 'loaded',+ }),+ channelsState: choiceControl<RequestState>('Channels request', {+ group: REQUEST,+ options: REQUEST_STATES,+ value: 'loaded',+ }),+ },+ handlers: (values, _response) => [+ rest.get('http://localhost/api/v1/route_policies', (_req, res, ctx) =>+ values.policiesState === 'error'+ ? res(ctx.status(500), ctx.json({ status: 'error' }))+ : res(+ ctx.json(+ routingPoliciesResponse(values.policies, channelNames(values.channels)),+ ),+ ),+ ),++ rest.post('http://localhost/api/v1/route_policies', (_req, res, ctx) =>+ res(ctx.status(201), ctx.json({ status: 'success', data: null })),+ ),++ rest.put('http://localhost/api/v1/route_policies/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.delete('http://localhost/api/v1/route_policies/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.get('http://localhost/api/v1/channels', (_req, res, ctx) =>+ values.channelsState === 'error'+ ? res(ctx.status(500), ctx.json({ status: 'error' }))+ : res(ctx.json(channelsResponse(values.channels))),+ ),+ ],+ config: () => ({+ route: `/alerts?tab=${AlertListTabs.CONFIGURATION}&subTab=${AlertListSubTabs.ROUTING_POLICIES}`,+ }),+});diff --git a/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.tsx b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.tsxnew file mode 100644index 0000000000..7620f7c51d--- /dev/null+++ b/frontend/src/pages/AlertList/RoutingPolicies/stories/RoutingPolicies.stories.tsx@@ -0,0 +1,139 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { routingPoliciesMocks } from './RoutingPolicies.stories.mocks';+import { FIRST_POLICY_NAME } from './__story_mockdata__/routingPolicies';++import AlertList from '../../index';++type RoutingPoliciesArgs = PageStoryArgs<typeof routingPoliciesMocks>;++const pageStory = storyMocks(routingPoliciesMocks, { layout: 'app' });++/**+ * Policies that route a firing alert to channels by expression, in the order they+ * are evaluated.+ *+ * Route: `/alerts?tab=Configuration&subTab=RoutingPolicies`.+ */+const meta = {+ title: 'Pages/Alerts/Routing Policies',+ tags: ['role-gated', 'play'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<RoutingPoliciesArgs>;++export default meta;++type Story = StoryObj<RoutingPoliciesArgs>;++/** The page fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The rules that decide which channel an alert reaches, matched on the labels+ * the alert carries.+ */+export const Default: Story = {};++/** A workspace routing everything through the rule's own channels. */+export const NoPolicies: Story = {+ args: { policies: 0 },+};++/** A viewer: the row actions and the New routing policy button are gone. */+export const Viewer: Story = {+ args: { access: 'viewer' },+};++/** A policy opened up: the expression it matches on and where it sends. */+export const Expanded: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText(FIRST_POLICY_NAME, undefined, untilLoaded),+ );+ await canvas.findByText(/expression/i);+ },+};++/** The form a policy is written in: the expression and the channels it routes to. */+export const NewPolicy: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /new routing policy/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(/create routing policy/i);+ },+};++/** The policy deletion confirmation, opened from the first row's real action. */+export const DeletePolicyConfirm: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ (+ await canvas.findAllByTestId(+ 'delete-routing-policy',+ undefined,+ untilLoaded,+ )+ )[0],+ );+ // The modal titles itself and its confirm button the same.+ await screen.findByRole('button', { name: 'Delete Routing Policy' });+ },+};++/** A client-side search that has no matching routing policies. */+export const SearchNoResults: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);+ const search = await canvas.findByPlaceholderText(+ 'Search for a routing policy...',+ undefined,+ untilLoaded,+ );++ await userEvent.type(search, 'no matching policy');+ await canvas.findByText('No matching routing policies found.');+ },+};++/** The list request failed while the rest of the alerts shell remains available. */+export const LoadError: Story = {+ args: { policiesState: 'error' },+ // The mocked policies request intentionally fails; the resulting console error+ // is the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};++/** The create form with its notification-channel request failed. */+export const ChannelsLoadError: Story = {+ args: { channelsState: 'error' },+ // The mocked channels request intentionally fails; the resulting console error+ // is the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+ play: NewPolicy.play,+};++/** Native form validation after submitting an empty routing-policy form. */+export const FormValidationError: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await NewPolicy.play?.({ canvasElement } as never);+ await userEvent.click(+ await screen.findByRole('button', { name: 'Save Routing Policy' }),+ );+ await screen.findByText('Please provide a name for the routing policy');+ },+};diff --git a/frontend/src/pages/AlertList/RoutingPolicies/stories/__story_mockdata__/routingPolicies.ts b/frontend/src/pages/AlertList/RoutingPolicies/stories/__story_mockdata__/routingPolicies.tsnew file mode 100644index 0000000000..0710e17a3f--- /dev/null+++ b/frontend/src/pages/AlertList/RoutingPolicies/stories/__story_mockdata__/routingPolicies.ts@@ -0,0 +1,96 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ ApiRoutingPolicy,+ GetRoutingPoliciesResponse,+} from 'api/routingPolicies/getRoutingPolicies';++const HOUR = 60 * 60 * 1000;+const DAY = 24 * HOUR;++const ago = (ms: number): string => new Date(Date.now() - ms).toISOString();++interface PolicySeed {+ name: string;+ description: string;+ expression: string;+ /** Indexes into the channel seeds the shared alert builders publish. */+ channels: number[];+}++const SEEDS: PolicySeed[] = [+ {+ name: 'Critical production to on-call',+ description: 'Anything critical in prod pages whoever is on call.',+ expression: 'severity = "critical" AND env = "prod"',+ channels: [1, 0],+ },+ {+ name: 'Payments team ownership',+ description: 'Payment alerts go to the team that owns the service.',+ expression: 'team = "payments"',+ channels: [0],+ },+ {+ name: 'Platform warnings to chat',+ description: 'Warnings from the platform team stay in chat.',+ expression: 'team = "platform" AND severity = "warning"',+ channels: [5],+ },+ {+ name: 'Staging is email only',+ description: 'Nothing from staging is allowed to page.',+ expression: 'env = "staging"',+ channels: [3],+ },+ {+ name: 'Database incidents',+ description: 'Anything touching Postgres opens an incident.',+ expression: 'component = "database"',+ channels: [4, 2],+ },+ {+ name: 'Catch-all',+ description: 'Everything not matched above lands in the ops channel.',+ expression: 'severity != ""',+ channels: [0],+ },+];++export const ROUTING_POLICY_MAX = SEEDS.length;++export const FIRST_POLICY_NAME = SEEDS[0].name;++const buildPolicy = (+ index: number,+ channelNames: string[],+): ApiRoutingPolicy => {+ const seed = SEEDS[index % SEEDS.length];++ return {+ id: `routing-policy-${index + 1}`,+ name: seed.name,+ description: seed.description,+ expression: seed.expression,+ channels: seed.channels+ .map((channelIndex) => channelNames[channelIndex])+ .filter(Boolean),+ createdAt: ago((index + 6) * DAY),+ updatedAt: ago((index + 1) * HOUR),+ createdBy: '[email protected]',+ updatedBy: '[email protected]',+ };+};++export const routingPoliciesResponse = (+ count: number,+ channelNames: string[],+): GetRoutingPoliciesResponse => ({+ status: 'success',+ data: Array.from({ length: count }, (_unused, index) =>+ buildPolicy(index, channelNames),+ ),+});diff --git a/frontend/src/pages/AlertList/TriggeredAlerts/stories/TriggeredAlerts.stories.mocks.tsx b/frontend/src/pages/AlertList/TriggeredAlerts/stories/TriggeredAlerts.stories.mocks.tsxnew file mode 100644index 0000000000..2ecbc56646--- /dev/null+++ b/frontend/src/pages/AlertList/TriggeredAlerts/stories/TriggeredAlerts.stories.mocks.tsx@@ -0,0 +1,90 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ SEVERITY_CHOICES,+ TRIGGERED_ALERT_MAX,+ TRIGGERED_STATES,+ triggeredAlertsResponse,+ type SeverityChoice,+ type TriggeredState,+} from '../../stories/__story_mockdata__/alerts';+import { AlertListTabs } from '../../types';++const LIST = 'Triggered alerts · list';++export const triggeredAlertsMocks = defineStoryMocks({+ controls: {+ alerts: countControl('Triggered alerts', {+ group: LIST,+ value: 9,+ max: TRIGGERED_ALERT_MAX,+ }),+ alertSeverity: choiceControl<SeverityChoice>('Severity', {+ group: LIST,+ description:+ 'The severity label every alert carries. `mixed` leaves each alert with its own, which is what the tag filter has something to narrow.',+ options: SEVERITY_CHOICES,+ value: 'mixed',+ }),+ alertState: choiceControl<TriggeredState>('Alert state', {+ group: LIST,+ description: 'Suppressed alerts are the ones a silence is holding back.',+ options: TRIGGERED_STATES,+ value: 'mixed',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/alerts',+ response.json(() =>+ triggeredAlertsResponse(values.alerts, {+ severity: values.alertSeverity,+ state: values.alertState,+ }),+ ),+ ),+ ],+ config: () => ({ route: `/alerts?tab=${AlertListTabs.TRIGGERED_ALERTS}` }),+});++/**+ * Long enough that the column can only fit the first badge, so the rest land in+ * the overflow tooltip as one joined line.+ */+const OVERFLOW_LABELS: Record<string, string> = {+ environment: 'production-eu-central-1',+ team: 'platform-observability-oncall',+ owner: '[email protected]',+ runbook: 'runbooks.internal.example.com/checkout/latency-budget',+ tier: 'tier-0-revenue-critical',+ compliance: 'soc2-type-2-in-scope',+};++export const overflowingLabels = rest.get(+ 'http://localhost/api/v1/alerts',+ (_req, res, ctx) => {+ const list = triggeredAlertsResponse(3, {+ severity: 'mixed',+ state: 'mixed',+ });++ return res(+ ctx.status(200),+ ctx.json({+ ...list,+ data: list.data.map((alert) => ({+ ...alert,+ labels: { ...alert.labels, ...OVERFLOW_LABELS },+ })),+ }),+ );+ },+);diff --git a/frontend/src/pages/AlertList/TriggeredAlerts/stories/TriggeredAlerts.stories.tsx b/frontend/src/pages/AlertList/TriggeredAlerts/stories/TriggeredAlerts.stories.tsxnew file mode 100644index 0000000000..d814da44dc--- /dev/null+++ b/frontend/src/pages/AlertList/TriggeredAlerts/stories/TriggeredAlerts.stories.tsx@@ -0,0 +1,150 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import {+ overflowingLabels,+ triggeredAlertsMocks,+} from './TriggeredAlerts.stories.mocks';++import AlertList from '../../index';+import { AlertListTabs } from '../../types';++type TriggeredAlertsArgs = PageStoryArgs<typeof triggeredAlertsMocks>;++const pageStory = storyMocks(triggeredAlertsMocks, { layout: 'app' });++/**+ * Alerts firing now, grouped and filtered from the query string, with severity and+ * state per row.+ *+ * Route: `/alerts?tab=TriggeredAlerts`.+ */+const meta = {+ title: 'Pages/Alerts/Triggered',+ tags: ['play'],+ component: AlertList,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<TriggeredAlertsArgs>;++export default meta;++type Story = StoryObj<TriggeredAlertsArgs>;++const tab = `/alerts?tab=${AlertListTabs.TRIGGERED_ALERTS}`;++/**+ * The alerts firing right now, newest first, with how long each one has been+ * firing and the labels the rule attached to it.+ */+export const Default: Story = {};++/** Nothing firing, which is the state an on-call engineer wants to see. */+export const NoAlerts: Story = {+ args: { alerts: 0 },+};++/** Search: an unmatched term retains the filters and renders the no-results state. */+export const SearchNoResults: Story = {+ parameters: {+ signoz: { route: `${tab}&search=no-matching-alert` },+ },+};++/** Data: the table's initial loading branch. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** Data: the retryable error branch when the alert request fails. */+export const LoadError: Story = {+ args: { dataState: 'error' },+ // The mocked alerts request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};++/**+ * The same alerts collapsed under the service they came from: one row per+ * group, each expanding to the alerts inside it.+ */+export const GroupedByService: Story = {+ parameters: {+ signoz: { route: `${tab}&groupBy=${JSON.stringify(['service'])}` },+ },+};++/**+ * A tag filter narrowing the list to the critical alerts, which is how the tab+ * is read during an incident.+ */+export const FilteredToCritical: Story = {+ parameters: {+ signoz: {+ route: `${tab}&alertFilters=${JSON.stringify(['severity:critical'])}`,+ },+ },+};++/** Interaction: the tag-filter menu is mounted in its portal. */+export const FilterComboboxOpen: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ within(canvasElement).getByTestId('triggered-alerts-filter-combobox'),+ );+ await screen.findByRole('listbox');+ },+};++/** Interaction: the group-by menu is mounted in its portal. */+export const GroupByComboboxOpen: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ within(canvasElement).getByTestId('triggered-alerts-groupby-combobox'),+ );+ await screen.findByRole('listbox');+ },+};++/** Interaction: a grouped row expands to its nested alert table. */+export const GroupedExpanded: Story = {+ parameters: {+ signoz: { route: `${tab}&groupBy=${JSON.stringify(['service'])}` },+ },+ play: async (): Promise<void> => {+ const [firstGroup] = await screen.findAllByTestId('group-expand-toggle');++ await userEvent.click(firstGroup);+ // The nested table is what the group opens, and it carries its own count.+ await screen.findByText(/showing 1 - 1 of 1/i);+ },+};++/** Density: four selected severity filters exercise collapsed filter-pill overflow. */+export const ManyFilterPills: Story = {+ parameters: {+ signoz: {+ route: `${tab}&alertFilters=${JSON.stringify([+ 'severity:critical',+ 'severity:error',+ 'severity:warning',+ 'severity:info',+ ])}`,+ },+ },+};++/**+ * Both tooltips the Labels column has, held open: the badge that fits, which+ * repeats its own `key: value`, and the overflow chip, which lists every label+ * that did not fit as one line. The alerts here carry far more labels than the+ * tab's own fixture, which is why the Triggered alerts, Severity and Alert+ * state controls do not reach this story.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+ parameters: { msw: { handlers: [overflowingLabels] } },+};diff --git a/frontend/src/pages/AlertList/stories/__story_mockdata__/alertQuery.ts b/frontend/src/pages/AlertList/stories/__story_mockdata__/alertQuery.tsnew file mode 100644index 0000000000..12dfce03d2--- /dev/null+++ b/frontend/src/pages/AlertList/stories/__story_mockdata__/alertQuery.ts@@ -0,0 +1,225 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesFieldDataTypeDTO,+ type GetFieldsKeys200,+ type GetFieldsValues200,+ type GetMetricMetadata200,+ type ListMetrics200,+ type MetricsexplorertypesListMetricDTO,+ type TelemetrytypesTelemetryFieldKeyDTO,+} from 'api/generated/services/sigNoz.schemas';+import type {+ MetricRangePayloadV5,+ QueryRangeRequestV5,+} from 'types/api/v5/queryRange';++import {+ queryRangeV5EmptyResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++const HOSTS = [+ 'ip-10-0-1-14',+ 'ip-10-0-2-31',+ 'ip-10-0-3-77',+ 'ip-10-0-4-08',+ 'ip-10-0-5-52',+ 'ip-10-0-6-19',+];++/**+ * The chart the alert form previews the condition against, plotted over the+ * window the form asked for and named after the query the request carried.+ */+export const alertPreviewSeries = async (+ count: number,+ req: { json: () => Promise<unknown> },+): Promise<MetricRangePayloadV5> => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const queryName =+ (body.compositeQuery?.queries?.[0]?.spec as { name?: string } | undefined)+ ?.name ?? 'A';++ if (count === 0) {+ return queryRangeV5EmptyResponse(queryName);+ }++ return queryRangeV5TimeSeriesResponse([+ {+ queryName,+ series: Array.from({ length: count }, (_unused, index) => ({+ labels: [+ { key: { name: 'host.name' }, value: HOSTS[index % HOSTS.length] },+ ],+ values: timeSeriesPoints({+ start: body.start,+ end: body.end,+ base: 55 + index * 6,+ amplitude: 12,+ seed: index * 3,+ }),+ })),+ },+ ]);+};++const METRIC_SEEDS: MetricsexplorertypesListMetricDTO[] = [+ {+ metricName: 'system_cpu_utilization',+ description: 'Ratio of the CPU that is in use, per host.',+ unit: 'percent',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ isMonotonic: false,+ },+ {+ metricName: 'system_memory_usage',+ description: 'Memory in use, per host.',+ unit: 'bytes',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ isMonotonic: false,+ },+ {+ metricName: 'http_server_duration',+ description: 'Duration of inbound HTTP requests.',+ unit: 'ms',+ type: MetrictypesTypeDTO.histogram,+ temporality: MetrictypesTemporalityDTO.cumulative,+ isMonotonic: false,+ },+ {+ metricName: 'kafka_consumer_lag',+ description: 'Messages a consumer group is behind.',+ unit: '',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ isMonotonic: false,+ },+ {+ metricName: 'postgresql_backends',+ description: 'Connections open against the database.',+ unit: '',+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.cumulative,+ isMonotonic: true,+ },+];++/** The metric picker in the query section, narrowed by whatever was typed. */+export const alertMetricsResponse = (searchText: string): ListMetrics200 => ({+ status: 'success',+ data: {+ metrics: METRIC_SEEDS.filter((metric) =>+ metric.metricName.includes(searchText.toLowerCase()),+ ),+ },+});++/** The unit the chart's y-axis defaults to when a metric is selected. */+export const alertMetricMetadataResponse = (+ metricName: string,+): GetMetricMetadata200 => {+ const metric =+ METRIC_SEEDS.find((seed) => seed.metricName === metricName) ??+ METRIC_SEEDS[0];++ return {+ status: 'success',+ data: {+ description: metric.description,+ unit: metric.unit,+ type: metric.type,+ temporality: metric.temporality,+ isMonotonic: metric.isMonotonic,+ },+ };+};++const FIELD_SEEDS: TelemetrytypesTelemetryFieldKeyDTO[] = [+ {+ name: 'service.name',+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ },+ {+ name: 'deployment.environment',+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ },+ {+ name: 'host.name',+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ },+ {+ name: 'http.route',+ fieldContext: TelemetrytypesFieldContextDTO.attribute,+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ },+ {+ name: 'http.status_code',+ fieldContext: TelemetrytypesFieldContextDTO.attribute,+ fieldDataType: TelemetrytypesFieldDataTypeDTO.int64,+ },+ {+ name: 'severity_text',+ fieldContext: TelemetrytypesFieldContextDTO.log,+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ },+];++const FIELD_VALUES: Record<string, string[]> = {+ 'service.name': ['checkout', 'payments', 'auth', 'search'],+ 'deployment.environment': ['production', 'staging'],+ 'host.name': ['ip-10-0-1-14', 'ip-10-0-2-31', 'ip-10-0-3-77'],+ 'http.route': ['/checkout', '/payments/charge', '/v1/login'],+ severity_text: ['ERROR', 'WARN', 'INFO'],+};++const NUMBER_FIELD_VALUES: Record<string, number[]> = {+ 'http.status_code': [200, 404, 500, 503],+};++const matching = <T>(values: T[], searchText: string): T[] =>+ values.filter((value) =>+ String(value).toLowerCase().includes(searchText.toLowerCase()),+ );++/** What the filter box in the alert's query section completes on. */+export const alertFieldKeysResponse = (+ searchText: string,+): GetFieldsKeys200 => ({+ status: 'success',+ data: {+ complete: true,+ keys: Object.fromEntries(+ FIELD_SEEDS.filter((field) =>+ field.name.includes(searchText.toLowerCase()),+ ).map((field) => [field.name, [field]]),+ ),+ },+});++export const alertFieldValuesResponse = (+ name: string,+ searchText: string,+): GetFieldsValues200 => ({+ status: 'success',+ data: {+ complete: true,+ values: {+ stringValues: matching(FIELD_VALUES[name] ?? [], searchText),+ numberValues: matching(NUMBER_FIELD_VALUES[name] ?? [], searchText),+ relatedValues: [],+ },+ },+});diff --git a/frontend/src/pages/AlertList/stories/__story_mockdata__/alerts.ts b/frontend/src/pages/AlertList/stories/__story_mockdata__/alerts.tsnew file mode 100644index 0000000000..8a7ef5e37e--- /dev/null+++ b/frontend/src/pages/AlertList/stories/__story_mockdata__/alerts.ts@@ -0,0 +1,744 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ MetrictypesSpaceAggregationDTO,+ MetrictypesTemporalityDTO,+ MetrictypesTimeAggregationDTO,+ Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricsSignal,+ Querybuildertypesv5QueryEnvelopeBuilderDTOType,+ Querybuildertypesv5ReduceToDTO,+ RuletypesAlertStateDTO,+ RuletypesAlertTypeDTO,+ RuletypesCompareOperatorDTO,+ RuletypesMatchTypeDTO,+ RuletypesPanelTypeDTO,+ RuletypesQueryTypeDTO,+ RuletypesRuleTypeDTO,+ RuletypesThresholdBasicDTOKind,+ type AlertmanagertypesDeprecatedGettableAlertDTO,+ type GetAlerts200,+ type GetRuleByID200,+ type ListRules200,+ type RenderErrorResponseDTO,+ type RuletypesAlertCompositeQueryDTO,+ type RuletypesRuleConditionDTO,+ type RuletypesRuleDTO,+} from 'api/generated/services/sigNoz.schemas';+import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';+import type { Channels } from 'types/api/channels/getAll';++const MINUTE = 60 * 1000;+const HOUR = 60 * MINUTE;+const DAY = 24 * HOUR;++const ago = (ms: number): string => new Date(Date.now() - ms).toISOString();++export const ALERT_SEVERITIES = [+ 'critical',+ 'error',+ 'warning',+ 'info',+] as const;++export type AlertSeverity = (typeof ALERT_SEVERITIES)[number];++/** `mixed` spreads the seeds' own severities instead of forcing one. */+export const SEVERITY_CHOICES = ['mixed', ...ALERT_SEVERITIES] as const;++export type SeverityChoice = (typeof SEVERITY_CHOICES)[number];++export const RULE_STATES = [+ 'firing',+ 'pending',+ 'inactive',+ 'disabled',+ 'nodata',+] as const;++export type RuleState = (typeof RULE_STATES)[number];++export const RULE_STATE_CHOICES = ['mixed', ...RULE_STATES] as const;++export type RuleStateChoice = (typeof RULE_STATE_CHOICES)[number];++export const ALERT_SCHEMAS = ['v2', 'classic'] as const;++export type AlertSchema = (typeof ALERT_SCHEMAS)[number];++export const CHANNEL_TYPES = [+ 'slack',+ 'webhook',+ 'pagerduty',+ 'opsgenie',+ 'email',+ 'msteams',+ 'googlechat',+ 'jira',+ 'jsmops',+ 'incidentio',+] as const;++export type ChannelType = (typeof CHANNEL_TYPES)[number];++/**+ * One query envelope is enough for the alert form to mount its query builder+ * over the rule, and it is the query the preview chart is drawn for.+ */+const compositeQuery = (seed: RuleSeed): RuletypesAlertCompositeQueryDTO => ({+ queryType: RuletypesQueryTypeDTO.builder,+ panelType: RuletypesPanelTypeDTO.graph,+ unit: seed.unit,+ queries: [+ {+ type: Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query,+ spec: {+ name: 'A',+ signal: MetricsSignal.metrics,+ disabled: false,+ aggregations: [+ {+ metricName: seed.metric,+ temporality: MetrictypesTemporalityDTO.unspecified,+ timeAggregation: MetrictypesTimeAggregationDTO.avg,+ spaceAggregation: MetrictypesSpaceAggregationDTO.avg,+ reduceTo: Querybuildertypesv5ReduceToDTO.last,+ },+ ],+ filter: { expression: '' },+ groupBy: [],+ order: [],+ stepInterval: 60,+ },+ },+ ],+});++const condition = (seed: RuleSeed): RuletypesRuleConditionDTO => ({+ compositeQuery: compositeQuery(seed),+ op: RuletypesCompareOperatorDTO.above,+ matchType: RuletypesMatchTypeDTO.at_least_once,+ selectedQueryName: 'A',+ target: seed.target,+ targetUnit: seed.unit,+ alertOnAbsent: false,+ requireMinPoints: false,+ thresholds: {+ kind: RuletypesThresholdBasicDTOKind.basic,+ spec: [+ {+ name: 'critical',+ matchType: RuletypesMatchTypeDTO.at_least_once,+ op: RuletypesCompareOperatorDTO.above,+ target: seed.target,+ targetUnit: seed.unit,+ channels: ['ops-slack'],+ },+ ],+ },+});++interface RuleSeed {+ alert: string;+ alertType: RuletypesAlertTypeDTO;+ state: RuletypesAlertStateDTO;+ severity: AlertSeverity;+ labels: Record<string, string>;+ metric: string;+ unit: string;+ target: number;+}++const RULE_SEEDS: RuleSeed[] = [+ {+ alert: 'Node CPU saturation',+ alertType: RuletypesAlertTypeDTO.METRIC_BASED_ALERT,+ state: RuletypesAlertStateDTO.firing,+ severity: 'critical',+ labels: { team: 'platform', env: 'prod' },+ metric: 'system_cpu_utilization',+ unit: 'percent',+ target: 85,+ },+ {+ alert: 'Checkout API latency above 2s',+ alertType: RuletypesAlertTypeDTO.TRACES_BASED_ALERT,+ state: RuletypesAlertStateDTO.firing,+ severity: 'critical',+ labels: { team: 'checkout', env: 'prod' },+ metric: 'http_server_duration',+ unit: 'ms',+ target: 2000,+ },+ {+ alert: 'Payment service error rate',+ alertType: RuletypesAlertTypeDTO.TRACES_BASED_ALERT,+ state: RuletypesAlertStateDTO.pending,+ severity: 'critical',+ labels: { team: 'payments', env: 'prod' },+ metric: 'http_server_duration',+ unit: 'percent',+ target: 5,+ },+ {+ alert: 'Kafka consumer lag',+ alertType: RuletypesAlertTypeDTO.METRIC_BASED_ALERT,+ state: RuletypesAlertStateDTO.pending,+ severity: 'error',+ labels: { team: 'platform', component: 'kafka' },+ metric: 'kafka_consumer_lag',+ unit: '',+ target: 10_000,+ },+ {+ alert: 'Postgres connections near limit',+ alertType: RuletypesAlertTypeDTO.METRIC_BASED_ALERT,+ state: RuletypesAlertStateDTO.inactive,+ severity: 'warning',+ labels: { team: 'platform', component: 'database' },+ metric: 'postgresql_backends',+ unit: '',+ target: 90,+ },+ {+ alert: 'Auth service 5xx spike',+ alertType: RuletypesAlertTypeDTO.LOGS_BASED_ALERT,+ state: RuletypesAlertStateDTO.inactive,+ severity: 'error',+ labels: { team: 'identity', env: 'prod' },+ metric: 'http_server_duration',+ unit: '',+ target: 20,+ },+ {+ alert: 'Unhandled exceptions in web',+ alertType: RuletypesAlertTypeDTO.EXCEPTIONS_BASED_ALERT,+ state: RuletypesAlertStateDTO.firing,+ severity: 'error',+ labels: { team: 'web', env: 'prod' },+ metric: 'http_server_duration',+ unit: '',+ target: 15,+ },+ {+ alert: 'Ingest pipeline dropped logs',+ alertType: RuletypesAlertTypeDTO.LOGS_BASED_ALERT,+ state: RuletypesAlertStateDTO.nodata,+ severity: 'warning',+ labels: { team: 'platform', component: 'collector' },+ metric: 'system_memory_usage',+ unit: '',+ target: 1,+ },+ {+ alert: 'Nightly batch job overran',+ alertType: RuletypesAlertTypeDTO.TRACES_BASED_ALERT,+ state: RuletypesAlertStateDTO.disabled,+ severity: 'info',+ labels: { team: 'data' },+ metric: 'http_server_duration',+ unit: 's',+ target: 3600,+ },+ {+ alert: 'Search p99 above budget',+ alertType: RuletypesAlertTypeDTO.TRACES_BASED_ALERT,+ state: RuletypesAlertStateDTO.inactive,+ severity: 'info',+ labels: { team: 'search', env: 'staging' },+ metric: 'http_server_duration',+ unit: 'ms',+ target: 800,+ },+ {+ alert: 'Cache hit ratio dropped',+ alertType: RuletypesAlertTypeDTO.METRIC_BASED_ALERT,+ state: RuletypesAlertStateDTO.inactive,+ severity: 'info',+ labels: { team: 'platform', component: 'redis' },+ metric: 'system_memory_usage',+ unit: 'percent',+ target: 70,+ },+ {+ alert: 'Disk usage on ingesters',+ alertType: RuletypesAlertTypeDTO.METRIC_BASED_ALERT,+ state: RuletypesAlertStateDTO.pending,+ severity: 'critical',+ labels: { team: 'platform', env: 'prod' },+ metric: 'system_memory_usage',+ unit: 'percent',+ target: 92,+ },+];++export const RULE_MAX = RULE_SEEDS.length;++/** The rule `rule-1` resolves to, which is the one the detail stories open. */+export const FIRST_RULE_NAME = RULE_SEEDS[0].alert;++const seedAt = (index: number): RuleSeed =>+ RULE_SEEDS[index % RULE_SEEDS.length];++const ruleName = (index: number): string => {+ const seed = seedAt(index);+ const round = Math.floor(index / RULE_SEEDS.length);++ return round === 0 ? seed.alert : `${seed.alert} (${round + 1})`;+};++export interface RuleShape {+ severity: SeverityChoice;+ state: RuleStateChoice;+ schema?: AlertSchema;+}++const buildRule = (index: number, shape: RuleShape): RuletypesRuleDTO => {+ const seed = seedAt(index);+ const severity = shape.severity === 'mixed' ? seed.severity : shape.severity;+ const state =+ shape.state === 'mixed'+ ? seed.state+ : (shape.state as RuletypesAlertStateDTO);++ return {+ id: `rule-${index + 1}`,+ alert: ruleName(index),+ alertType: seed.alertType,+ ruleType: RuletypesRuleTypeDTO.threshold_rule,+ state,+ disabled: state === RuletypesAlertStateDTO.disabled,+ condition: condition(seed),+ labels: { severity, ...seed.labels },+ annotations: {+ summary: `${seed.alert} crossed its threshold of ${seed.target}`,+ description:+ 'The rule threshold is set to {{$threshold}}, and the observed metric value is {{$value}}',+ },+ evalWindow: '5m0s',+ frequency: '1m0s',+ createdAt: ago((index + 3) * DAY),+ updatedAt: ago((index + 1) * HOUR),+ createdBy: '[email protected]',+ updatedBy: '[email protected]',+ schemaVersion:+ shape.schema === 'classic' ? undefined : NEW_ALERT_SCHEMA_VERSION,+ version: 'v5',+ source: 'http://localhost/alerts',+ preferredChannels: ['ops-slack'],+ notificationSettings: {+ groupBy: ['alertname'],+ usePolicy: false,+ renotify: { enabled: false, interval: '30m0s' },+ },+ };+};++export const alertRulesResponse = (+ count: number,+ shape: RuleShape,+): ListRules200 => ({+ status: 'success',+ data: Array.from({ length: count }, (_unused, index) =>+ buildRule(index, shape),+ ),+});++/**+ * The detail endpoint answers for whatever id the URL carries, so a story keeps+ * rendering after a row click lands on a rule the list never returned.+ */+export const alertRuleByIdResponse = (+ ruleId: string,+ shape: RuleShape,+): GetRuleByID200 => {+ const index = Math.max(Number.parseInt(ruleId.replace(/\D/g, ''), 10) - 1, 0);++ return {+ status: 'success',+ data: { ...buildRule(Number.isNaN(index) ? 0 : index, shape), id: ruleId },+ };+};++interface TriggeredSeed {+ alertname: string;+ severity: AlertSeverity;+ labels: Record<string, string>;+ summary: string;+ firingForMinutes: number;+}++const TRIGGERED_SEEDS: TriggeredSeed[] = [+ {+ alertname: 'Checkout API latency above 2s',+ severity: 'critical',+ labels: { service: 'checkout', env: 'prod', team: 'checkout' },+ summary: 'p99 latency is 3.4s against a 2s budget',+ firingForMinutes: 14,+ },+ {+ alertname: 'Payment service error rate',+ severity: 'critical',+ labels: { service: 'payments', env: 'prod', team: 'payments' },+ summary: '7.2% of payment spans failed in the last 5 minutes',+ firingForMinutes: 42,+ },+ {+ alertname: 'Node CPU saturation',+ severity: 'warning',+ labels: { service: 'kubelet', env: 'prod', team: 'platform' },+ summary: 'CPU utilisation held above 85% on 3 nodes',+ firingForMinutes: 128,+ },+ {+ alertname: 'Kafka consumer lag',+ severity: 'error',+ labels: { service: 'events-consumer', env: 'prod', team: 'platform' },+ summary: 'Lag is 24k messages and climbing',+ firingForMinutes: 300,+ },+ {+ alertname: 'Unhandled exceptions in web',+ severity: 'error',+ labels: { service: 'web', env: 'prod', team: 'web' },+ summary: '31 unhandled exceptions in the last 10 minutes',+ firingForMinutes: 8,+ },+ {+ alertname: 'Auth service 5xx spike',+ severity: 'error',+ labels: { service: 'auth', env: 'prod', team: 'identity' },+ summary: '5xx rate is 22 requests per second',+ firingForMinutes: 55,+ },+ {+ alertname: 'Search p99 above budget',+ severity: 'info',+ labels: { service: 'search', env: 'staging', team: 'search' },+ summary: 'p99 is 940ms against an 800ms budget',+ firingForMinutes: 1_450,+ },+ {+ alertname: 'Cache hit ratio dropped',+ severity: 'info',+ labels: { service: 'redis', env: 'prod', team: 'platform' },+ summary: 'Hit ratio fell to 61%',+ firingForMinutes: 620,+ },+ {+ alertname: 'Disk usage on ingesters',+ severity: 'critical',+ labels: { service: 'ingester', env: 'prod', team: 'platform' },+ summary: 'Two ingesters are above 92% disk',+ firingForMinutes: 3,+ },+ {+ alertname: 'Postgres connections near limit',+ severity: 'warning',+ labels: { service: 'postgres', env: 'prod', team: 'platform' },+ summary: '91% of the connection pool is in use',+ firingForMinutes: 240,+ },+ {+ alertname: 'Ingest pipeline dropped logs',+ severity: 'warning',+ labels: { service: 'otel-collector', env: 'prod', team: 'platform' },+ summary: 'The collector dropped 4.1k log records',+ firingForMinutes: 76,+ },+ {+ alertname: 'Nightly batch job overran',+ severity: 'info',+ labels: { service: 'batch-runner', env: 'prod', team: 'data' },+ summary: 'The nightly job ran 41 minutes past its window',+ firingForMinutes: 900,+ },+];++export const TRIGGERED_ALERT_MAX = TRIGGERED_SEEDS.length;++/** A resolved alert is one alertmanager still lists with an `endsAt` in the past. */+export const TRIGGERED_STATES = ['mixed', 'active', 'suppressed'] as const;++export type TriggeredState = (typeof TRIGGERED_STATES)[number];++export interface TriggeredShape {+ severity: SeverityChoice;+ state: TriggeredState;+}++const buildTriggeredAlert = (+ index: number,+ shape: TriggeredShape,+): AlertmanagertypesDeprecatedGettableAlertDTO => {+ const seed = TRIGGERED_SEEDS[index % TRIGGERED_SEEDS.length];+ const severity = shape.severity === 'mixed' ? seed.severity : shape.severity;+ const mixedState = index % 4 === 3 ? 'suppressed' : 'active';+ const state = shape.state === 'mixed' ? mixedState : shape.state;+ const ruleId = `rule-${(index % RULE_MAX) + 1}`;++ return {+ fingerprint: `fingerprint-${index + 1}`,+ startsAt: ago(seed.firingForMinutes * MINUTE),+ endsAt: new Date(Date.now() + HOUR).toISOString(),+ generatorURL: `http://localhost/alerts/overview?ruleId=${ruleId}`,+ labels: {+ alertname: seed.alertname,+ severity,+ ruleId,+ ...seed.labels,+ },+ annotations: {+ summary: seed.summary,+ description: `${seed.alertname} has been firing for ${seed.firingForMinutes} minutes`,+ },+ status: {+ state,+ silencedBy: state === 'suppressed' ? ['silence-1'] : [],+ inhibitedBy: [],+ },+ receivers: ['ops-slack'],+ };+};++export const triggeredAlertsResponse = (+ count: number,+ shape: TriggeredShape,+): GetAlerts200 => ({+ status: 'success',+ data: Array.from({ length: count }, (_unused, index) =>+ buildTriggeredAlert(index, shape),+ ),+});++interface ChannelSeed {+ name: string;+ type: ChannelType;+ /** The alertmanager receiver the channel serialises into its `data` field. */+ receiver: Record<string, unknown>;+}++const CHANNEL_SEEDS: ChannelSeed[] = [+ {+ name: 'ops-slack',+ type: 'slack',+ receiver: {+ slack_configs: [+ {+ api_url: 'https://hooks.slack.com/services/T000/B000/story-token',+ channel: '#ops-alerts',+ send_resolved: true,+ title: '[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}',+ text: '{{ range .Alerts -}}*Alert:* {{ .Labels.alertname }}\n{{ end }}',+ },+ ],+ },+ },+ {+ name: 'oncall-pagerduty',+ type: 'pagerduty',+ receiver: {+ pagerduty_configs: [+ {+ routing_key: 'story-routing-key',+ send_resolved: true,+ client: 'SigNoz',+ description: '{{ .CommonLabels.alertname }}',+ severity: 'critical',+ details: { firing: '{{ .Alerts.Firing | len }}' },+ },+ ],+ },+ },+ {+ name: 'platform-webhook',+ type: 'webhook',+ receiver: {+ webhook_configs: [+ {+ url: 'https://hooks.example.com/signoz',+ send_resolved: true,+ http_config: {+ basic_auth: { username: 'signoz', password: 'story-password' },+ },+ },+ ],+ },+ },+ {+ name: 'sre-email',+ type: 'email',+ receiver: {+ email_configs: [+ {+ to: '[email protected]',+ send_resolved: true,+ html: '<p>{{ .CommonLabels.alertname }}</p>',+ headers: { Subject: '[SigNoz] {{ .CommonLabels.alertname }}' },+ },+ ],+ },+ },+ {+ name: 'incident-opsgenie',+ type: 'opsgenie',+ receiver: {+ opsgenie_configs: [+ {+ api_key: 'story-api-key',+ send_resolved: true,+ message: '{{ .CommonLabels.alertname }}',+ description: '{{ .CommonLabels.alertname }} is firing',+ priority: 'P2',+ },+ ],+ },+ },+ {+ name: 'eng-msteams',+ type: 'msteams',+ receiver: {+ msteamsv2_configs: [+ {+ webhook_url: 'https://signoz.webhook.office.com/story',+ send_resolved: true,+ title: '{{ .CommonLabels.alertname }}',+ text: '{{ .CommonAnnotations.summary }}',+ },+ ],+ },+ },+ {+ name: 'support-googlechat',+ type: 'googlechat',+ receiver: {+ googlechat_configs: [+ {+ webhook_url: 'https://chat.googleapis.com/v1/spaces/story',+ send_resolved: true,+ title: '{{ .CommonLabels.alertname }}',+ text: '{{ .CommonAnnotations.summary }}',+ },+ ],+ },+ },+ {+ name: 'tickets-jira',+ type: 'jira',+ receiver: {+ jira_configs: [+ {+ site: 'https://signoz.atlassian.net',+ project: 'ALERT',+ issue_type: 'Task',+ send_resolved: true,+ summary: '{{ .CommonLabels.alertname }}',+ description: '{{ .CommonAnnotations.summary }}',+ priority: 'High',+ labels: ['signoz', 'platform'],+ resolve_transition: 'Done',+ reopen_transition: 'Reopen',+ wont_fix_resolution: "Won't Do",+ reopen_duration: '72h',+ // The form reads the credentials off the basic auth block rather than+ // off the config itself, which is where the backend stores them.+ http_config: {+ basic_auth: {+ username: '[email protected]',+ password: 'story-api-token',+ },+ },+ },+ ],+ },+ },+ {+ name: 'oncall-jsmops',+ type: 'jsmops',+ receiver: {+ jsmops_configs: [+ {+ api_key: 'story-jsm-api-key',+ send_resolved: true,+ message: '{{ .CommonLabels.alertname }}',+ description: '{{ .CommonAnnotations.summary }}',+ priority: 'P2',+ // Stored comma-separated, which is what the form splits into chips.+ tags: 'signoz,platform',+ },+ ],+ },+ },+ {+ name: 'oncall-incidentio',+ type: 'incidentio',+ receiver: {+ incidentio_configs: [+ {+ url: 'https://api.incident.io/v2/alert_events/http/story-source-config-id',+ token: 'story-source-token',+ send_resolved: true,+ title: '{{ .CommonLabels.alertname }}',+ description: '{{ .CommonAnnotations.summary }}',+ metadata: { team: 'platform' },+ },+ ],+ },+ },+];++export const CHANNEL_MAX = CHANNEL_SEEDS.length;++const buildChannel = (index: number): Channels => {+ const seed = CHANNEL_SEEDS[index % CHANNEL_SEEDS.length];++ return {+ id: String(index + 1),+ name: seed.name,+ type: seed.type,+ created_at: ago((index + 10) * DAY),+ updated_at: ago((index + 1) * DAY),+ data: JSON.stringify({ name: seed.name, ...seed.receiver }),+ };+};++export const channelsResponse = (+ count: number,+): { status: string; data: Channels[] } => ({+ status: 'success',+ data: Array.from({ length: count }, (_unused, index) => buildChannel(index)),+});++/** Channel names the alert form and the routing policies pick from. */+export const channelNames = (count: number): string[] =>+ channelsResponse(count).data.map((channel) => channel.name);++export const channelResponse = (+ id: string,+ type: ChannelType,+): { status: string; data: Channels } => {+ const index = CHANNEL_SEEDS.findIndex((seed) => seed.type === type);++ return {+ status: 'success',+ data: { ...buildChannel(Math.max(index, 0)), id },+ };+};++export const CHANNEL_ACTION_OUTCOMES = ['succeeds', 'fails'] as const;++export type ChannelActionOutcome = (typeof CHANNEL_ACTION_OUTCOMES)[number];++export const channelActionError = (): RenderErrorResponseDTO => ({+ status: 'error',+ error: {+ code: 'STORYBOOK_FAILURE',+ type: 'internal',+ message: 'Storybook forced channel failure',+ url: '',+ errors: [],+ suggestions: [],+ },+});diff --git a/frontend/src/pages/AllErrors/stories/AllErrors.stories.mocks.tsx b/frontend/src/pages/AllErrors/stories/AllErrors.stories.mocks.tsxnew file mode 100644index 0000000000..c5d15acf03--- /dev/null+++ b/frontend/src/pages/AllErrors/stories/AllErrors.stories.mocks.tsx@@ -0,0 +1,113 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import set from 'api/browser/localstorage/set';+import { LOCALSTORAGE } from 'constants/localStorage';++import { countControl, toggleControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import { fieldValuesResponse } from '@/storybook/msw/__story_mockdata__/fields';++import {+ EXCEPTION_CATALOGUE_SIZE,+ EXCEPTION_QUICK_FILTER_CAP,+ exceptionAttributeKeysResponse,+ exceptionAttributeValuesResponse,+ exceptionFieldKeysResponse,+ exceptionQuickFiltersResponse,+ exceptionRows,+ exceptionTotal,+ type ListErrorsBody,+} from './__story_mockdata__/exceptions';++const LIST = 'Exceptions · list';+const FILTERS = 'Exceptions · filters';++export const exceptionsMocks = defineStoryMocks({+ controls: {+ exceptions: countControl('Exception groups', {+ group: LIST,+ description:+ 'Groups the endpoint holds. The table asks for one page at a time and pages against `/countErrors`, so a count past ten paginates.',+ value: EXCEPTION_CATALOGUE_SIZE,+ max: EXCEPTION_CATALOGUE_SIZE,+ }),+ quickFilters: countControl('Quick filters', {+ group: FILTERS,+ description:+ 'Filters the org has configured for exceptions. At 0 the panel has nothing to render, which is what a workspace that never customised them shows.',+ value: 6,+ max: EXCEPTION_QUICK_FILTER_CAP,+ }),+ filterPanel: toggleControl('Quick filters panel', {+ group: FILTERS,+ description:+ 'Whether the panel starts expanded. The page keeps this in local storage, so it survives the collapse arrow being clicked.',+ value: true,+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v1/listErrors',+ response.json(async (req) => {+ const body = (await req.json()) as ListErrorsBody;++ return exceptionRows(values.exceptions, body);+ }),+ ),++ rest.post(+ 'http://localhost/api/v1/countErrors',+ response.json(async (req) => {+ const body = (await req.json()) as ListErrorsBody;++ return exceptionTotal(values.exceptions, body);+ }),+ ),++ rest.get(+ 'http://localhost/api/v2/quick_filters/:source',+ response.json(() => exceptionQuickFiltersResponse(values.quickFilters)),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ exceptionFieldKeysResponse(req.url.searchParams.get('searchText')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(+ exceptionAttributeValuesResponse(req.url.searchParams.get('name'), null)+ .data.stringAttributeValues ?? [],+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_keys',+ response.json((req) =>+ exceptionAttributeKeysResponse(req.url.searchParams.get('searchText')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ exceptionAttributeValuesResponse(+ req.url.searchParams.get('attributeKey'),+ req.url.searchParams.get('searchText'),+ ),+ ),+ ),+ ],+ effect: (values) => {+ set(LOCALSTORAGE.SHOW_EXCEPTIONS_QUICK_FILTERS, String(values.filterPanel));+ },+});diff --git a/frontend/src/pages/AllErrors/stories/AllErrors.stories.tsx b/frontend/src/pages/AllErrors/stories/AllErrors.stories.tsxnew file mode 100644index 0000000000..f18e3c9858--- /dev/null+++ b/frontend/src/pages/AllErrors/stories/AllErrors.stories.tsx@@ -0,0 +1,114 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import ROUTES from 'constants/routes';+import { expect, screen, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { exceptionsMocks } from './AllErrors.stories.mocks';+import AllErrors from '../index';++type AllErrorsArgs = PageStoryArgs<typeof exceptionsMocks>;++const pageStory = storyMocks(exceptionsMocks, {+ route: ROUTES.ALL_ERROR,+ layout: 'app',+});++/**+ * Exception groups over the period, with the quick filters and the filter panel+ * the explorers share.+ *+ * Route: `/exceptions`.+ */+const meta = {+ title: 'Pages/Exceptions/List',+ tags: ['play'],+ component: AllErrors,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<AllErrorsArgs>;++export default meta;++type Story = StoryObj<AllErrorsArgs>;++/** The page fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++const openQuickFiltersSettings = async (): Promise<void> => {+ // The settings control renders disabled while its permission check is in+ // flight and is swapped for the enabled one once the check answers, so it is+ // looked up again on every attempt; a click on the disabled one is dropped in+ // silence.+ const control = await waitFor(() => {+ const settings = screen.getByTestId('settings-icon-container');++ expect(settings).toBeEnabled();++ return settings;+ }, untilLoaded);++ await userEvent.click(control);+ await screen.findByText('Edit quick filters', undefined, untilLoaded);+};++/**+ * Every exception group in the window: the org's quick filters down the left, the+ * resource filter and the time range above, and the table sorted by application+ * with each type linking to its detail page.+ */+export const Default: Story = {};++/**+ * A workspace with nothing thrown in the window and no quick filters configured,+ * so the table and the filter panel both show their empty states.+ */+export const NoExceptions: Story = {+ args: { exceptions: 0, quickFilters: 0 },+};++/** The query area after the quick-filters panel is collapsed. */+export const FiltersCollapsed: Story = {+ args: { filterPanel: false },+};++/** The table mid-query, with the cancel action the toolbar offers while it runs. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/**+ * What cancelling a running query leaves behind: the table is dropped for a+ * placeholder until Run Query is pressed again.+ */+export const QueryCancelled: Story = {+ args: { dataState: 'loading' },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(/cancel/i, undefined, untilLoaded),+ );++ await screen.findByText(/query cancelled/i, undefined, untilLoaded);+ },+};++/** The editable quick-filter settings panel. */+export const QuickFiltersSettings: Story = {+ play: openQuickFiltersSettings,+};++/** Settings with an unsaved filter removal and the fixed action footer. */+export const QuickFiltersSettingsDirty: Story = {+ play: async (): Promise<void> => {+ await openQuickFiltersSettings();++ // One Remove per added filter; the first row's is the one clicked.+ const [removeFilter] = await screen.findAllByRole('button', {+ name: 'Remove',+ });++ await userEvent.click(removeFilter);+ await screen.findByRole('button', { name: 'Save changes' });+ },+};diff --git a/frontend/src/pages/AllErrors/stories/__story_mockdata__/exceptions.ts b/frontend/src/pages/AllErrors/stories/__story_mockdata__/exceptions.tsnew file mode 100644index 0000000000..146bb91d27--- /dev/null+++ b/frontend/src/pages/AllErrors/stories/__story_mockdata__/exceptions.ts@@ -0,0 +1,341 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ QuickfiltertypesSourceDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesFieldDataTypeDTO,+ TelemetrytypesSignalDTO,+} from 'api/generated/services/sigNoz.schemas';+import type {+ GetFieldsKeys200,+ GetQuickFilters200,+ TelemetrytypesTelemetryFieldKeyDTO,+} from 'api/generated/services/sigNoz.schemas';+import {+ type BaseAutocompleteData,+ DataTypes,+ type IQueryAutocompleteResponse,+} 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 {+ exceptionType: string;+ exceptionMessage: string;+ exceptionCount: number;+ serviceName: string;+ groupID: string;+}++/**+ * Ordered by count, the way the backend answers an unsorted request, so a slice+ * keeps a spread of services, languages and counts.+ */+export const EXCEPTION_CATALOGUE: ExceptionShape[] = [+ {+ exceptionType: '*errors.errorString',+ exceptionMessage: 'redis timeout',+ exceptionCount: 2510,+ serviceName: 'redis-manual',+ groupID: '511b9c91a92b9c5166ecb77235f5743b',+ },+ {+ exceptionType: 'ConnectionError',+ exceptionMessage:+ "HTTPConnectionPool(host='payments', port=8080): Read timed out. (read timeout=2)",+ exceptionCount: 1834,+ serviceName: 'checkout',+ groupID: '6a1f0c2d8e4b7a935c10d4f6b8e2a771',+ },+ {+ exceptionType: 'java.net.SocketTimeoutException',+ exceptionMessage: 'Read timed out',+ exceptionCount: 1290,+ serviceName: 'payment-java',+ groupID: 'c93d2f81a0b64e7f95d31c8e7a4b0d26',+ },+ {+ exceptionType: 'TypeError',+ exceptionMessage: "Cannot read properties of undefined (reading 'id')",+ exceptionCount: 964,+ serviceName: 'frontend',+ groupID: '1d7e4b93c05f8a26e91b4d70c3f85a12',+ },+ {+ exceptionType: 'psycopg2.OperationalError',+ exceptionMessage: 'could not connect to server: Connection refused',+ exceptionCount: 742,+ serviceName: 'orders',+ groupID: 'ab3c5d7e9f10234567890bcdef123456',+ },+ {+ exceptionType: 'KeyError',+ exceptionMessage: "'customer_id'",+ exceptionCount: 611,+ serviceName: 'cart',+ groupID: '77e0a1b2c3d4e5f60718293a4b5c6d7e',+ },+ {+ exceptionType: '*net.OpError',+ exceptionMessage: 'dial tcp 10.0.4.11:9092: connect: connection refused',+ exceptionCount: 508,+ serviceName: 'kafka-producer',+ groupID: '2f4a6c8e0b1d3f5709a2b4c6d8e0f135',+ },+ {+ exceptionType: 'ValidationError',+ exceptionMessage:+ '1 validation error for Order\nquantity: value is not a valid integer',+ exceptionCount: 402,+ serviceName: 'orders',+ groupID: '9b8a7c6d5e4f30211f2e3d4c5b6a7988',+ },+ {+ exceptionType: 'java.lang.NullPointerException',+ exceptionMessage: 'Cannot invoke "String.length()" because "sku" is null',+ exceptionCount: 355,+ serviceName: 'inventory-java',+ groupID: '3c1e5a79b2d4f68008a1c3e5b7d9f012',+ },+ {+ exceptionType: 'RuntimeError',+ exceptionMessage: 'Event loop is closed',+ exceptionCount: 287,+ serviceName: 'notifications',+ groupID: 'e5d4c3b2a1908f7e6d5c4b3a29180706',+ },+ {+ exceptionType: 'sqlalchemy.exc.IntegrityError',+ exceptionMessage:+ 'duplicate key value violates unique constraint "orders_pkey"',+ exceptionCount: 213,+ serviceName: 'orders',+ groupID: '0a1b2c3d4e5f60718293a4b5c6d7e8f9',+ },+ {+ exceptionType: 'AxiosError',+ exceptionMessage: 'Request failed with status code 503',+ exceptionCount: 168,+ serviceName: 'frontend',+ groupID: '4d6f8a0c2e4b6d8f0a1c3e5b7d9f1113',+ },+ {+ exceptionType: '*fmt.wrapError',+ exceptionMessage: 'publish message: context deadline exceeded',+ exceptionCount: 96,+ serviceName: 'kafka-producer',+ groupID: 'bb0a99887766554433221100ffeeddcc',+ },+ {+ exceptionType: 'RedisTimeoutError',+ exceptionMessage: 'Command timed out after 1000ms',+ exceptionCount: 41,+ serviceName: 'session-store',+ groupID: '8e7d6c5b4a39281706f5e4d3c2b1a099',+ },+];++export const EXCEPTION_CATALOGUE_SIZE = EXCEPTION_CATALOGUE.length;++export const EXCEPTION_SERVICE_NAMES = Array.from(+ new Set(EXCEPTION_CATALOGUE.map(({ serviceName }) => serviceName)),+);++export const EXCEPTION_TYPES = EXCEPTION_CATALOGUE.map(+ ({ exceptionType }) => exceptionType,+);++/** The nanoseconds every row carries, so `firstSeen` stays the table's row key. */+const SUBSECOND_NANOS = '797616374';++/**+ * `lastSeen` and `firstSeen` come back as RFC 3339 with nanoseconds, which is+ * what `getNanoSeconds` parses to build the link to the detail page.+ */+const seenAt = (atMs: number): string =>+ `${new Date(atMs).toISOString().slice(0, 19)}.${SUBSECOND_NANOS}Z`;++export interface ListErrorsBody {+ start: string;+ end: string;+ order?: Order;+ orderParam?: OrderBy;+ limit?: number;+ offset?: number;+ exceptionType?: string;+ serviceName?: string;+}++const MINUTE_MS = 60 * 1000;++const contains = (value: string, search: string | undefined): boolean =>+ !search || value.toLowerCase().includes(search.toLowerCase());++const compare = (left: Exception, right: Exception, by: OrderBy): number => {+ if (by === 'exceptionCount') {+ return left.exceptionCount - right.exceptionCount;+ }++ if (by === 'lastSeen' || by === 'firstSeen') {+ return Date.parse(left[by]) - Date.parse(right[by]);+ }++ return left[by].localeCompare(right[by]);+};++/**+ * The exception groups the endpoint holds for one request. The timestamps land+ * inside the window the time picker asked for, and the sorting and the column+ * searches are applied here: the table writes both into the query string and+ * sends them along, rather than sorting or filtering what it already has.+ */+const selectExceptions = (count: number, body: ListErrorsBody): Exception[] => {+ const endMs = Number(body.end) / 1e6;++ const rows: Exception[] = EXCEPTION_CATALOGUE.slice(0, count).map(+ (exception, index) => ({+ ...exception,+ lastSeen: seenAt(endMs - index * MINUTE_MS),+ firstSeen: seenAt(endMs - (index + 1) * 30 * MINUTE_MS),+ }),+ );++ const filtered = rows.filter(+ (row) =>+ contains(row.exceptionType, body.exceptionType) &&+ contains(row.serviceName, body.serviceName),+ );++ const orderParam = body.orderParam ?? 'serviceName';+ const direction = body.order === 'descending' ? -1 : 1;++ return filtered.sort(+ (left, right) => direction * compare(left, right, orderParam),+ );+};++export const exceptionRows = (+ count: number,+ body: ListErrorsBody,+): Exception[] => {+ const offset = body.offset ?? 0;+ const limit = body.limit ?? 10;++ return selectExceptions(count, body).slice(offset, offset + limit);+};++/** `/countErrors` answers the bare total the table pages against. */+export const exceptionTotal = (count: number, body: ListErrorsBody): number =>+ selectExceptions(count, body).length;++const { resource, attribute } = TelemetrytypesFieldContextDTO;+const { string: stringType, bool } = TelemetrytypesFieldDataTypeDTO;++const QUICK_FILTERS: TelemetrytypesTelemetryFieldKeyDTO[] = [+ { name: 'service.name', fieldDataType: stringType, fieldContext: resource },+ { name: 'exceptionType', fieldDataType: stringType, fieldContext: attribute },+ {+ name: 'deployment.environment',+ fieldDataType: stringType,+ fieldContext: resource,+ },+ {+ name: 'telemetry.sdk.language',+ fieldDataType: stringType,+ fieldContext: resource,+ },+ { name: 'host.name', fieldDataType: stringType, fieldContext: resource },+ {+ name: 'k8s.namespace.name',+ fieldDataType: stringType,+ fieldContext: resource,+ },+ { name: 'os.type', fieldDataType: stringType, fieldContext: resource },+ { name: 'hasError', fieldDataType: bool, fieldContext: attribute },+];++export const EXCEPTION_QUICK_FILTER_CAP = QUICK_FILTERS.length;++export const exceptionQuickFiltersResponse = (+ count: number,+): GetQuickFilters200 =>+ quickFiltersResponse(+ QuickfiltertypesSourceDTO.exceptions,+ QUICK_FILTERS.slice(0, count),+ );++const ATTRIBUTE_VALUES: Record<string, string[]> = {+ 'service.name': EXCEPTION_SERVICE_NAMES,+ exceptionType: EXCEPTION_TYPES,+ 'deployment.environment': ['production', 'staging', 'canary'],+ 'telemetry.sdk.language': ['go', 'python', 'java', 'nodejs'],+ 'host.name': ['ip-10-0-4-11', 'ip-10-0-4-12', 'ip-10-0-5-31'],+ 'k8s.namespace.name': ['default', 'otel-demo', 'payments'],+ 'os.type': ['linux', 'darwin'],+};++export const exceptionAttributeValuesResponse = (+ attributeKey: string | null,+ searchText: string | null,+): { status: string; data: IAttributeValuesResponse } => {+ const search = (searchText ?? '').toLowerCase();+ const values = (ATTRIBUTE_VALUES[attributeKey ?? ''] ?? []).filter((value) =>+ value.toLowerCase().includes(search),+ );++ return {+ status: 'success',+ data: {+ stringAttributeValues: values,+ numberAttributeValues: null,+ boolAttributeValues: attributeKey === 'hasError' ? ['true', 'false'] : null,+ },+ };+};++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' },+];++export const exceptionAttributeKeysResponse = (+ searchText: string | null,+): { status: string; data: IQueryAutocompleteResponse } => {+ const search = (searchText ?? '').toLowerCase();++ return {+ status: 'success',+ data: {+ attributeKeys: ATTRIBUTE_KEYS.filter(({ key }) =>+ key.toLowerCase().includes(search),+ ),+ },+ };+};++/** The quick filter settings panel lists its "other filters" from `/fields/keys`. */+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 },+ );+};diff --git a/frontend/src/pages/ApiMonitoring/stories/ApiMonitoringPage.stories.mocks.tsx b/frontend/src/pages/ApiMonitoring/stories/ApiMonitoringPage.stories.mocks.tsxnew file mode 100644index 0000000000..f77a25cff3--- /dev/null+++ b/frontend/src/pages/ApiMonitoring/stories/ApiMonitoringPage.stories.mocks.tsx@@ -0,0 +1,406 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { TelemetrytypesTelemetryFieldKeyDTO } from 'api/generated/services/sigNoz.schemas';+import {+ QuickfiltertypesSourceDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesFieldDataTypeDTO,+} from 'api/generated/services/sigNoz.schemas';+import ROUTES from 'constants/routes';+import { VIEWS } from 'container/ApiMonitoring/Explorer/Domains/DomainDetails/constants';+import { DEFAULT_PARAMS } from 'container/ApiMonitoring/queryParams';+import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';+import { rest } from 'msw';+import type { AppState } from 'store/reducers';+import type { Props as ListOverviewRequest } from 'types/api/thirdPartyApis/listOverview';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import { fieldValuesResponse } from '@/storybook/msw/__story_mockdata__/fields';+import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';++import {+ allEndpointsResponse,+ DEPENDENT_SERVICE_MAX,+ dependentServicesResponse,+ DOMAIN_MAX,+ domainListResponse,+ domainMetricsResponse,+ type DrawerDomain,+ DRAWER_DOMAINS,+ drawerDomainName,+ endpointDropdownResponse,+ ENDPOINT_MAX,+ endpointMetricsResponse,+ endpointUrl,+ groupByAttributeKeys,+ overTimeChartResponse,+ STATUS_CODE_MAX,+ statusCodeChartResponse,+ statusCodeTableResponse,+ TOP_ERROR_MAX,+ topErrorsResponse,+} from './__story_mockdata__/apiMonitoring';++const DOMAINS = 'External APIs · domains';+const DRAWER = 'External APIs · drawer';+const FILTERS = 'External APIs · filters';++const QUICK_FILTERS: TelemetrytypesTelemetryFieldKeyDTO[] = [+ {+ name: 'deployment.environment',+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ },+ {+ name: 'service.name',+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ },+ {+ name: 'rpc.method',+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ fieldContext: TelemetrytypesFieldContextDTO.attribute,+ },+];++const QUICK_FILTER_VALUES: Record<string, string[]> = {+ 'deployment.environment': ['production', 'staging'],+ 'service.name': ['checkout', 'payments', 'cart'],+ 'rpc.method': ['GET', 'POST'],+};++const DRAWER_STATES = [+ 'closed',+ 'all-endpoints',+ 'endpoint-stats',+ 'top-errors',+] as const;++type DrawerState = (typeof DRAWER_STATES)[number];++const VIEW_OF: Record<Exclude<DrawerState, 'closed'>, VIEWS> = {+ 'all-endpoints': VIEWS.ALL_ENDPOINTS,+ 'endpoint-stats': VIEWS.ENDPOINT_STATS,+ 'top-errors': VIEWS.TOP_ERRORS,+};++const RELATIVE_TIME: Time = '30m';++const THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;++const NANOSECONDS_IN_MS = 1_000_000;++/**+ * `globalTime` derives its window from `window.location.pathname`, which in a+ * story is the preview's rather than the page's, so without a seeded range the+ * time picker and the queries would disagree about the window.+ */+const timeRange = (): Partial<AppState> => {+ const now = Date.now();++ return {+ globalTime: {+ minTime: (now - THIRTY_MINUTES_IN_MS) * NANOSECONDS_IN_MS,+ maxTime: now * NANOSECONDS_IN_MS,+ loading: false,+ selectedTime: RELATIVE_TIME,+ isAutoRefreshDisabled: false,+ selectedAutoRefreshInterval: '',+ },+ };+};++const serviceFilterItems = {+ op: 'AND',+ items: [+ {+ id: 'storybook-service-filter',+ key: { key: 'service.name', dataType: 'string', type: 'resource' },+ op: '=',+ value: 'checkout',+ },+ ],+};++interface RouteValues {+ drawer: DrawerState;+ drawerDomain: DrawerDomain;+ domains: number;+ serviceFilter: boolean;+}++const apiMonitoringRoute = ({+ drawer,+ drawerDomain,+ domains,+ serviceFilter,+}: RouteValues): string => {+ const domainName = drawerDomainName(drawerDomain, domains);++ if (drawer === 'closed' || !domainName) {+ return ROUTES.API_MONITORING;+ }++ const params = {+ ...DEFAULT_PARAMS,+ selectedDomain: domainName,+ selectedView: VIEW_OF[drawer],+ selectedEndPointName:+ drawer === 'endpoint-stats' ? endpointUrl(domainName, 0) : '',+ ...(serviceFilter ? { endPointDetailsLocalFilters: serviceFilterItems } : {}),+ };++ return `${ROUTES.API_MONITORING}?apiMonitoringParams=${encodeURIComponent(+ JSON.stringify(params),+ )}`;+};++/** The parts of a query spec the handler tells the page's requests apart by. */+interface RequestSpec {+ name?: string;+ aggregations?: Array<{ expression?: string }>;+ groupBy?: Array<{ name: string }>;+ filter?: { expression?: string };+}++interface QueryShape {+ names: string[];+ expressions: string[];+ groupBy: string[];+ filters: string[];+ /** The endpoint the request pinned, when one is selected. */+ endPointName?: string;+}++const shapeOf = (body: QueryRangeRequestV5): QueryShape => {+ const specs = (body.compositeQuery?.queries ?? []).map(+ ({ spec }) => spec as RequestSpec,+ );+ const filters = specs.map((spec) => spec.filter?.expression ?? '');++ return {+ names: specs+ .map((spec) => spec.name)+ .filter((name): name is string => Boolean(name)),+ expressions: specs.flatMap((spec) =>+ (spec.aggregations ?? []).map((aggregation) => aggregation.expression ?? ''),+ ),+ // Every query in the request repeats the same group-by, so the columns the+ // response answers with are the distinct ones.+ groupBy: [+ ...new Set(+ specs.flatMap((spec) => (spec.groupBy ?? []).map(({ name }) => name)),+ ),+ ],+ filters,+ endPointName: filters+ .map((expression) => /http_url\s*=\s*'([^']+)'/.exec(expression)?.[1])+ .find(Boolean),+ };+};++export const apiMonitoringMocks = defineStoryMocks({+ controls: {+ domains: countControl('Domains', {+ group: DOMAINS,+ description:+ 'External hosts the workspace called in the window. At 0 the page shows what to instrument instead of the table.',+ value: DOMAIN_MAX,+ max: DOMAIN_MAX,+ }),+ drawer: choiceControl<DrawerState>('Domain drawer', {+ group: DRAWER,+ description:+ 'The drawer a domain row opens, and which of its three views is showing.',+ options: DRAWER_STATES,+ value: 'closed',+ }),+ drawerDomain: choiceControl<DrawerDomain>('Drawer domain', {+ group: DRAWER,+ description:+ 'Which row the drawer opens: a healthy host, one failing most calls, or a bare address on a non-standard port.',+ options: DRAWER_DOMAINS,+ value: 'healthy',+ }),+ endpoints: countControl('Endpoints', {+ group: DRAWER,+ description:+ 'Endpoints the domain has. Fills the Endpoint Overview table and the endpoint picker.',+ value: ENDPOINT_MAX,+ max: ENDPOINT_MAX,+ }),+ statusCodes: countControl('Status codes', {+ group: DRAWER,+ description:+ 'Distinct response codes the endpoint answered with, in the table and in the call response chart.',+ value: STATUS_CODE_MAX,+ max: STATUS_CODE_MAX,+ }),+ dependentServices: countControl('Dependent services', {+ group: DRAWER,+ description:+ 'Services calling the endpoint. Past five the list collapses behind Show more.',+ value: DEPENDENT_SERVICE_MAX,+ max: DEPENDENT_SERVICE_MAX,+ }),+ topErrors: countControl('Top errors', {+ group: DRAWER,+ description: 'Rows the Top 10 Errors table has for the domain.',+ value: TOP_ERROR_MAX,+ max: TOP_ERROR_MAX,+ }),+ serviceFilter: toggleControl('Service filter', {+ group: DRAWER,+ description:+ 'Puts a service.name filter on the endpoint stats view, which drops the Dependent Services block.',+ value: false,+ }),+ quickFilters: countControl('Quick filters', {+ group: FILTERS,+ description:+ 'Configured API Monitoring quick filters shown beside the domain list.',+ value: QUICK_FILTERS.length,+ max: QUICK_FILTERS.length,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/quick_filters/:source',+ response.json(() =>+ quickFiltersResponse(+ QuickfiltertypesSourceDTO.api_monitoring,+ QUICK_FILTERS.slice(0, values.quickFilters),+ ),+ ),+ ),++ rest.post(+ 'http://localhost/api/v1/third-party-apis/overview/list',+ response.json(async (req) => {+ const { show_ip: showIp } = (await req.json()) as ListOverviewRequest;++ return domainListResponse(values.domains, showIp, Date.now());+ }),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_keys',+ response.json((req) => ({+ status: 'success',+ data: {+ attributeKeys: groupByAttributeKeys(+ req.url.searchParams.get('searchText') ?? '',+ ),+ },+ })),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) => ({+ status: 'success',+ data: {+ boolAttributeValues: null,+ numberAttributeValues: null,+ stringAttributeValues:+ QUICK_FILTER_VALUES[req.url.searchParams.get('attributeKey') ?? ''] ?? [],+ },+ })),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(+ QUICK_FILTER_VALUES[req.url.searchParams.get('name') ?? ''] ?? [],+ ),+ ),+ ),++ // Every widget in the drawer asks the same endpoint, so what a request is+ // for is only in its shape: the panel type, what it groups by, and which+ // aggregations it names.+ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const shape = shapeOf(body);+ const domainName =+ drawerDomainName(values.drawerDomain, values.domains) ?? '';+ const window = { start: body.start, end: body.end };++ if (body.requestType === 'time_series') {+ if (shape.groupBy.includes('response_status_code')) {+ return statusCodeChartResponse(+ domainName,+ values.statusCodes,+ window,+ shape.expressions.includes('count()') ? 'calls' : 'latency',+ );+ }++ return overTimeChartResponse(+ domainName,+ window,+ shape.expressions.includes('rate()') ? 'rate' : 'latency',+ );+ }++ if (shape.groupBy.includes('status_message')) {+ return topErrorsResponse(+ domainName,+ values.topErrors,+ shape.filters.some((expression) =>+ expression.includes('status_message EXISTS'),+ ),+ shape.endPointName,+ );+ }++ if (shape.groupBy.includes('response_status_code')) {+ return statusCodeTableResponse(domainName, values.statusCodes);+ }++ if (shape.groupBy.includes('http_url')) {+ if (shape.names.length === 1) {+ return endpointDropdownResponse(domainName, values.endpoints);+ }++ return allEndpointsResponse(+ domainName,+ values.endpoints,+ shape.groupBy,+ Date.now(),+ );+ }++ if (shape.groupBy.includes('service.name')) {+ return dependentServicesResponse(domainName, values.dependentServices);+ }++ if (shape.expressions.includes('rate()')) {+ return endpointMetricsResponse(+ domainName,+ shape.endPointName ?? endpointUrl(domainName, 0),+ Date.now(),+ );+ }++ return domainMetricsResponse(domainName, Date.now());+ }),+ ),+ ],+ config: (values) => ({+ route: apiMonitoringRoute(values),+ reduxState: timeRange(),+ }),+});diff --git a/frontend/src/pages/ApiMonitoring/stories/ApiMonitoringPage.stories.tsx b/frontend/src/pages/ApiMonitoring/stories/ApiMonitoringPage.stories.tsxnew file mode 100644index 0000000000..64598fb9ff--- /dev/null+++ b/frontend/src/pages/ApiMonitoring/stories/ApiMonitoringPage.stories.tsx@@ -0,0 +1,145 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { apiMonitoringMocks } from './ApiMonitoringPage.stories.mocks';+import ApiMonitoringPage from '../ApiMonitoringPage';++type ApiMonitoringArgs = PageStoryArgs<typeof apiMonitoringMocks>;++const pageStory = storyMocks(apiMonitoringMocks, { layout: 'app' });++/**+ * Third party domains instrumented services call, their endpoints, status codes+ * and the services depending on them. The domain drawer is part of the route, so+ * it is a control rather than a play.+ *+ * Route: `/api-monitoring/explorer`.+ */+const meta = {+ title: 'Pages/External APIs',+ tags: ['play'],+ component: ApiMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ApiMonitoringArgs>;++export default meta;++type Story = StoryObj<ApiMonitoringArgs>;++/**+ * Every external host the workspace called in the window, with the endpoints it+ * uses, how often, how slow and how much of it failed. Clicking a row opens the+ * domain drawer.+ */+export const Default: Story = {};++/**+ * The domain drawer on All Endpoints: the host's own rate, latency and error+ * share above a table of every endpoint under it, groupable by any span+ * attribute.+ */+export const DomainEndpoints: Story = {+ args: { drawer: 'all-endpoints' },+};++/** The endpoint drawer scoped to checkout, which hides dependent services. */+export const ServiceFiltered: Story = {+ args: { drawer: 'endpoint-stats', serviceFilter: true },+};++/** A non-standard-port destination, preserving the endpoint metadata pill. */+export const PortDomain: Story = {+ args: { drawer: 'endpoint-stats', drawerDomain: 'ip-address' },+};++/** The page fetches before it renders a filter, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The quick-filter panel has no test id of its own, and it only mounts once the+ * workspace's filters have answered.+ */+const selectFirstQuickFilterValue = async (+ canvasElement: HTMLElement,+): Promise<void> => {+ const panel = await waitFor(() => {+ const found = canvasElement.querySelector<HTMLElement>('.quick-filters');++ if (!found) {+ throw new Error('Quick filters did not render');+ }++ return found;+ }, untilLoaded);++ // The V2 checkbox panel starts with every value selected, so its checkbox only+ // toggles an exclusion. The value's own label is what selects it on its own+ // ("Only"), which is the state this story shows.+ const [row] = await within(panel).findAllByTestId(+ /^checkbox-value-row-/,+ undefined,+ untilLoaded,+ );++ await userEvent.click(within(row).getAllByRole('button')[0]);++ // The panel re-renders around the new query, so the checkbox is looked up+ // again on every attempt rather than held from before the click.+ await waitFor(+ () => expect(within(panel).getAllByRole('checkbox')[0]).toBeChecked(),+ untilLoaded,+ );+};++/** The domain drawer's real empty endpoint-table branch. */+export const EmptyEndpointDrawer: Story = {+ args: { drawer: 'all-endpoints', endpoints: 0 },+};++/** A selected API Monitoring quick-filter value. */+export const QuickFilterSelected: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectFirstQuickFilterValue(canvasElement);+ },+};++/**+ * One endpoint's stats: the services calling it, the codes it answered with as+ * a chart and a table, and its rate and latency over the window.+ */+export const EndpointStats: Story = {+ args: { drawer: 'endpoint-stats' },+};++/**+ * The ten errors the domain returned most, by endpoint, status code and the+ * message that came back. A row opens the traces behind it.+ */+export const TopErrors: Story = {+ args: { drawer: 'top-errors' },+};++/**+ * A domain answering almost every call with an error, which is what the drawer+ * looks like when the host is the problem.+ */+export const FailingDomain: Story = {+ args: { drawer: 'endpoint-stats', drawerDomain: 'failing' },+};++/**+ * Nothing instrumented yet: no client spans carrying a URL, so the page explains+ * what to send instead of listing hosts.+ */+export const NoExternalCalls: Story = {+ args: { domains: 0 },+};++/** The domain list mid-query, with the cancel action the toolbar offers. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};diff --git a/frontend/src/pages/ApiMonitoring/stories/__story_mockdata__/apiMonitoring.ts b/frontend/src/pages/ApiMonitoring/stories/__story_mockdata__/apiMonitoring.tsnew file mode 100644index 0000000000..3c224ed1e7--- /dev/null+++ b/frontend/src/pages/ApiMonitoring/stories/__story_mockdata__/apiMonitoring.ts@@ -0,0 +1,556 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { domainNameKey } from 'container/ApiMonitoring/constants';+import { SPAN_ATTRIBUTES } from 'container/ApiMonitoring/Explorer/Domains/DomainDetails/constants';+import type { APIMonitoringResponseColumn } from 'container/ApiMonitoring/types';+import type { PayloadProps as ListOverviewResponse } from 'types/api/thirdPartyApis/listOverview';+import type { MetricRangePayloadV5 } from 'types/api/v5/queryRange';++import {+ queryRangeV5ScalarTableResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++interface Domain {+ name: string;+ /** Endpoints in use, which is also how many the drawer can list. */+ endpoints: number;+ rate: number;+ errorRate: number;+ latencyMs: number;+ lastSeenMinutesAgo: number;+ /** A bare address, which the Show IP addresses filter drops. */+ isIp?: boolean;+ /** Prefix its endpoint URLs carry, which is where the Port pill reads from. */+ origin?: string;+}++const DOMAINS: Domain[] = [+ {+ name: 'api.stripe.com',+ endpoints: 10,+ rate: 8.42,+ errorRate: 1.24,+ latencyMs: 241,+ lastSeenMinutesAgo: 2,+ },+ {+ name: 'api.github.com',+ endpoints: 7,+ rate: 3.16,+ errorRate: 0.42,+ latencyMs: 187,+ lastSeenMinutesAgo: 5,+ },+ {+ name: 's3.us-east-1.amazonaws.com',+ endpoints: 5,+ rate: 21.68,+ errorRate: 0.08,+ latencyMs: 96,+ lastSeenMinutesAgo: 1,+ },+ {+ name: 'api.segment.io',+ endpoints: 4,+ rate: 12.94,+ errorRate: 4.71,+ latencyMs: 318,+ lastSeenMinutesAgo: 11,+ },+ {+ name: 'hooks.slack.com',+ endpoints: 3,+ rate: 0.82,+ errorRate: 12.5,+ latencyMs: 642,+ lastSeenMinutesAgo: 46,+ },+ {+ name: 'api.twilio.com',+ endpoints: 4,+ rate: 1.64,+ errorRate: 61.9,+ latencyMs: 1184,+ lastSeenMinutesAgo: 184,+ },+ {+ name: '34.120.155.12',+ endpoints: 2,+ rate: 0.41,+ errorRate: 91.3,+ latencyMs: 2410,+ lastSeenMinutesAgo: 1620,+ isIp: true,+ origin: 'http://34.120.155.12:8080',+ },+ {+ name: 'api.sendgrid.com',+ endpoints: 3,+ rate: 2.27,+ errorRate: 0,+ latencyMs: 152,+ lastSeenMinutesAgo: 8,+ },+];++export const DOMAIN_MAX = DOMAINS.length;++const MS_IN_MINUTE = 60 * 1000;+const NS_IN_MS = 1_000_000;++const lastSeenIso = (minutesAgo: number, now: number): string =>+ new Date(now - minutesAgo * MS_IN_MINUTE).toISOString();++const listOverviewColumns: APIMonitoringResponseColumn[] = [+ {+ name: domainNameKey,+ signal: 'traces',+ fieldContext: '',+ fieldDataType: 'string',+ queryName: '',+ aggregationIndex: 0,+ meta: {},+ columnType: 'attribute',+ },+ ...['endpoints', 'rps', 'error_rate', 'p99', 'lastseen'].map((name) => ({+ name,+ signal: 'traces',+ fieldContext: '',+ fieldDataType: 'number',+ queryName: name,+ aggregationIndex: 0,+ meta: {},+ columnType: 'metric',+ })),+];++const domainsIn = (count: number, showIp: boolean): Domain[] =>+ DOMAINS.filter((domain) => showIp || !domain.isIp).slice(0, count);++export const domainNames = (count: number, showIp = true): string[] =>+ domainsIn(count, showIp).map((domain) => domain.name);++export const DRAWER_DOMAINS = ['healthy', 'failing', 'ip-address'] as const;++export type DrawerDomain = (typeof DRAWER_DOMAINS)[number];++const DRAWER_DOMAIN_OF: Record<DrawerDomain, string> = {+ healthy: 'api.stripe.com',+ failing: 'api.twilio.com',+ 'ip-address': '34.120.155.12',+};++/** Falls back to the first row when the chosen domain is past the list's count. */+export const drawerDomainName = (+ kind: DrawerDomain,+ count: number,+): string | undefined => {+ const available = domainNames(count);+ const target = DRAWER_DOMAIN_OF[kind];++ return available.includes(target) ? target : available[0];+};++export const domainListResponse = (+ count: number,+ showIp: boolean,+ now: number,+): ListOverviewResponse => ({+ status: 'success',+ data: {+ type: 'scalar',+ meta: { rowsScanned: count, bytesScanned: 0, durationMs: 0 },+ data: {+ results: [+ {+ columns: listOverviewColumns,+ // Typed as strings, but the error column calls `toFixed` on the cell+ // and the last-used column parses it with `new Date`, so the metrics+ // go out as numbers and the timestamp as a date string.+ data: domainsIn(count, showIp).map((domain) => [+ domain.name,+ domain.endpoints,+ domain.rate,+ domain.errorRate,+ domain.latencyMs * NS_IN_MS,+ lastSeenIso(domain.lastSeenMinutesAgo, now),+ ]) as unknown as string[][],+ },+ ],+ },+ },+});++const domainOf = (name: string): Domain =>+ DOMAINS.find((domain) => domain.name === name) ?? DOMAINS[0];++const ENDPOINT_PATHS = [+ '/v1/charges',+ '/v1/customers',+ '/v1/payment_intents',+ '/v1/refunds',+ '/v1/invoices',+ '/v1/subscriptions',+ '/v1/events',+ '/v1/payouts',+ '/v1/balance',+ '/v1/tokens',+];++export const ENDPOINT_MAX = ENDPOINT_PATHS.length;++/** Full URLs, port included, which is what the drawer splits into endpoint and port. */+export const endpointUrls = (domainName: string, count: number): string[] => {+ const { origin = `https://${domainName}` } = domainOf(domainName);++ return ENDPOINT_PATHS.slice(0, count).map((path) => `${origin}${path}`);+};++export const endpointUrl = (domainName: string, index = 0): string =>+ endpointUrls(domainName, ENDPOINT_MAX)[index];++const endpointScale = (domain: Domain, index: number): number =>+ 1 + ((index * 7) % 5) / 4;++export const domainMetricsResponse = (+ domainName: string,+ now: number,+): MetricRangePayloadV5 => {+ const domain = domainOf(domainName);++ return queryRangeV5ScalarTableResponse({+ aggregations: ['A', 'B', 'D', 'F1'],+ rows: [+ [+ domain.endpoints,+ domain.latencyMs * NS_IN_MS,+ lastSeenIso(domain.lastSeenMinutesAgo, now),+ domain.errorRate,+ ],+ ],+ });+};++export const endpointMetricsResponse = (+ domainName: string,+ endPointName: string,+ now: number,+): MetricRangePayloadV5 => {+ const domain = domainOf(domainName);+ const index = Math.max(+ endpointUrls(domainName, ENDPOINT_MAX).indexOf(endPointName),+ 0,+ );+ const scale = endpointScale(domain, index);++ return queryRangeV5ScalarTableResponse({+ aggregations: ['A', 'B', 'D', 'F1'],+ rows: [+ [+ Number((domain.rate * scale).toFixed(2)),+ Math.round(domain.latencyMs * scale) * NS_IN_MS,+ lastSeenIso(domain.lastSeenMinutesAgo, now),+ Number((domain.errorRate * scale).toFixed(2)),+ ],+ ],+ });+};++/**+ * The Endpoint Overview table. Extra group-by columns come from the request, so+ * a group-by picked in the panel widens the table instead of dropping its rows.+ */+export const allEndpointsResponse = (+ domainName: string,+ count: number,+ groupBy: string[],+ now: number,+): MetricRangePayloadV5 => {+ const domain = domainOf(domainName);+ const extraGroupBy = groupBy.filter(+ (name) => name !== SPAN_ATTRIBUTES.HTTP_URL,+ );++ return queryRangeV5ScalarTableResponse({+ groupBy: [SPAN_ATTRIBUTES.HTTP_URL, ...extraGroupBy],+ aggregations: ['A', 'B', 'C', 'F1'],+ rows: endpointUrls(domainName, count).map((url, index) => {+ const scale = endpointScale(domain, index);++ return [+ url,+ ...extraGroupBy.map((name) => groupByValue(name, index)),+ Math.round(domain.rate * scale * 600),+ Math.round(domain.latencyMs * scale) * NS_IN_MS,+ lastSeenIso(domain.lastSeenMinutesAgo + index, now),+ Number((domain.errorRate * scale).toFixed(2)),+ ];+ }),+ });+};++const GROUP_BY_VALUES: Record<string, string[]> = {+ 'service.name': ['checkout', 'payments', 'cart'],+ 'deployment.environment': ['production', 'staging'],+ 'rpc.method': ['POST', 'GET'],+};++function groupByValue(name: string, index: number): string {+ const values = GROUP_BY_VALUES[name] ?? ['value-a', 'value-b'];++ return values[index % values.length];+}++export const endpointDropdownResponse = (+ domainName: string,+ count: number,+): MetricRangePayloadV5 =>+ queryRangeV5ScalarTableResponse({+ groupBy: [SPAN_ATTRIBUTES.HTTP_URL],+ aggregations: ['A'],+ rows: endpointUrls(domainName, count).map((url, index) => [+ url,+ 1200 - index * 90,+ ]),+ });++const STATUS_CODES = ['200', '201', '304', '400', '404', '500'];++export const STATUS_CODE_MAX = STATUS_CODES.length;++const statusCodeCalls = (index: number): number =>+ [4820, 1960, 640, 210, 96, 41][index];++export const statusCodeTableResponse = (+ domainName: string,+ count: number,+): MetricRangePayloadV5 => {+ const domain = domainOf(domainName);++ return queryRangeV5ScalarTableResponse({+ groupBy: [SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE],+ aggregations: ['A', 'B', 'C'],+ rows: STATUS_CODES.slice(0, count).map((statusCode, index) => [+ statusCode,+ statusCodeCalls(index),+ Math.round(domain.latencyMs * (1 + index / 3)) * NS_IN_MS,+ Number((domain.rate / (index + 1)).toFixed(2)),+ ]),+ });+};++const DEPENDENT_SERVICES = [+ 'checkout',+ 'payments',+ 'cart',+ 'auth',+ 'notifications',+ 'search',+ 'orders',+ 'shipping',+];++export const DEPENDENT_SERVICE_MAX = DEPENDENT_SERVICES.length;++export const dependentServicesResponse = (+ domainName: string,+ count: number,+): MetricRangePayloadV5 => {+ const domain = domainOf(domainName);++ return queryRangeV5ScalarTableResponse({+ groupBy: ['service.name'],+ aggregations: ['A', 'B', 'C', 'F1'],+ rows: DEPENDENT_SERVICES.slice(0, count).map((service, index) => {+ const calls = Math.round(3800 / (index + 1));++ return [+ service,+ calls,+ Math.round(domain.latencyMs * (1 + index / 5)) * NS_IN_MS,+ Number((domain.rate / (index + 1)).toFixed(2)),+ Number((domain.errorRate * (1 + index / 4)).toFixed(2)),+ ];+ }),+ });+};++interface TopError {+ statusCode: string;+ message: string;+ count: number;+}++const TOP_ERRORS: TopError[] = [+ { statusCode: '500', message: 'upstream connect error', count: 412 },+ { statusCode: '429', message: 'rate limit exceeded', count: 318 },+ { statusCode: '503', message: 'upstream timeout', count: 244 },+ { statusCode: '502', message: 'connection reset by peer', count: 187 },+ { statusCode: '400', message: 'invalid request payload', count: 143 },+ { statusCode: '401', message: 'expired api key', count: 118 },+ { statusCode: '404', message: 'no such customer', count: 96 },+ { statusCode: '409', message: 'idempotency key reused', count: 71 },+ { statusCode: '422', message: 'card declined', count: 54 },+ { statusCode: '500', message: 'internal server error', count: 32 },+];++export const TOP_ERROR_MAX = TOP_ERRORS.length;++/**+ * The Top 10 Errors table, which reads the scalar result itself rather than the+ * legacy conversion, so its cells are keyed by column name.+ */+export const topErrorsResponse = (+ domainName: string,+ count: number,+ withStatusMessage: boolean,+ endPointName?: string,+): MetricRangePayloadV5 => {+ const urls = endpointUrls(domainName, ENDPOINT_MAX);++ return {+ data: {+ type: 'scalar',+ data: {+ results: [+ {+ columns: [+ {+ name: SPAN_ATTRIBUTES.HTTP_URL,+ queryName: '',+ aggregationIndex: 0,+ columnType: 'group',+ },+ {+ name: SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE,+ queryName: '',+ aggregationIndex: 0,+ columnType: 'group',+ },+ {+ name: 'status_message',+ queryName: '',+ aggregationIndex: 0,+ columnType: 'group',+ },+ {+ name: '__result_0',+ queryName: 'A',+ aggregationIndex: 0,+ columnType: 'aggregation',+ },+ ],+ data: TOP_ERRORS.slice(0, count).map((error, index) => [+ endPointName ?? urls[index % urls.length],+ error.statusCode,+ withStatusMessage ? error.message : 'n/a',+ error.count,+ ]),+ },+ ],+ },+ meta: {+ rowsScanned: count,+ bytesScanned: 0,+ durationMs: 0,+ stepIntervals: {},+ },+ },+ };+};++interface Window {+ start: number;+ end: number;+}++/**+ * Call response status, both the count and the latency the card switches to.+ * The chart buckets the codes into 2xx–5xx, so the per-code weights are the+ * ones the status code table shows and the buckets keep their relative size.+ */+export const statusCodeChartResponse = (+ domainName: string,+ count: number,+ window: Window,+ metric: 'calls' | 'latency',+): MetricRangePayloadV5 => {+ const domain = domainOf(domainName);++ return queryRangeV5TimeSeriesResponse([+ {+ queryName: 'A',+ series: STATUS_CODES.slice(0, count).map((statusCode, index) => {+ const base =+ metric === 'calls'+ ? statusCodeCalls(index) / 12+ : Math.round(domain.latencyMs * (1 + index / 3)) * NS_IN_MS;++ return {+ labels: [+ {+ key: { name: SPAN_ATTRIBUTES.RESPONSE_STATUS_CODE },+ value: statusCode,+ },+ ],+ values: timeSeriesPoints({+ ...window,+ seed: index * 3,+ base,+ amplitude: base / 5,+ }),+ };+ }),+ },+ ]);+};++/** The rate and latency charts at the bottom of the endpoint stats view. */+export const overTimeChartResponse = (+ domainName: string,+ window: Window,+ metric: 'rate' | 'latency',+): MetricRangePayloadV5 => {+ const domain = domainOf(domainName);+ const base = metric === 'rate' ? domain.rate : domain.latencyMs * NS_IN_MS;++ return queryRangeV5TimeSeriesResponse([+ {+ queryName: 'A',+ series: [+ {+ values: timeSeriesPoints({+ ...window,+ base,+ amplitude: base / 5,+ }),+ },+ ],+ },+ ]);+};++const GROUP_BY_KEYS = [+ 'service.name',+ 'deployment.environment',+ 'rpc.method',+ 'http.request.method',+ 'net.peer.name',+];++export const groupByAttributeKeys = (+ searchText: string,+): Array<{ key: string; dataType: string; type: string; isColumn: boolean }> =>+ GROUP_BY_KEYS.filter((key) =>+ key.toLowerCase().includes(searchText.toLowerCase()),+ ).map((key) => ({+ key,+ dataType: 'string',+ type: 'tag',+ isColumn: false,+ }));diff --git a/frontend/src/pages/CreateAlert/stories/CreateAlert.stories.mocks.tsx b/frontend/src/pages/CreateAlert/stories/CreateAlert.stories.mocks.tsxnew file mode 100644index 0000000000..6a65ce0ee4--- /dev/null+++ b/frontend/src/pages/CreateAlert/stories/CreateAlert.stories.mocks.tsx@@ -0,0 +1,157 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import { AlertDetectionTypes } from 'container/FormAlertRules';+import { rest } from 'msw';+import { AlertTypes } from 'types/api/alerts/alertTypes';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ alertFieldKeysResponse,+ alertFieldValuesResponse,+ alertMetricMetadataResponse,+ alertMetricsResponse,+ alertPreviewSeries,+} from '../../AlertList/stories/__story_mockdata__/alertQuery';+import {+ channelsResponse,+ CHANNEL_MAX,+} from '../../AlertList/stories/__story_mockdata__/alerts';++/**+ * Which alert the page is building. The page reads this off the URL, so the+ * control is a route rather than a response: with no type at all it stays on+ * the picker, anomaly detection routes to the classic form, and everything else+ * opens the current one.+ */+const ALERT_MODES = [+ 'select-type',+ 'metrics',+ 'logs',+ 'traces',+ 'exceptions',+ 'anomaly',+ 'classic-form',+] as const;++type AlertMode = (typeof ALERT_MODES)[number];++const ALERT_TYPE_BY_MODE: Partial<Record<AlertMode, AlertTypes>> = {+ metrics: AlertTypes.METRICS_BASED_ALERT,+ logs: AlertTypes.LOGS_BASED_ALERT,+ traces: AlertTypes.TRACES_BASED_ALERT,+ exceptions: AlertTypes.EXCEPTIONS_BASED_ALERT,+ anomaly: AlertTypes.METRICS_BASED_ALERT,+ 'classic-form': AlertTypes.METRICS_BASED_ALERT,+};++const routeFor = (mode: AlertMode): string => {+ const alertType = ALERT_TYPE_BY_MODE[mode];++ if (!alertType) {+ return ROUTES.ALERTS_NEW;+ }++ const params = new URLSearchParams({+ [QueryParams.alertType]: alertType,+ [QueryParams.ruleType]:+ mode === 'anomaly'+ ? AlertDetectionTypes.ANOMALY_DETECTION_ALERT+ : AlertDetectionTypes.THRESHOLD_ALERT,+ [QueryParams.relativeTime]: '6h',+ });++ if (mode === 'classic-form') {+ params.set(QueryParams.showClassicCreateAlertsPage, 'true');+ }++ return `${ROUTES.ALERTS_NEW}?${params.toString()}`;+};++const FORM = 'Create alert · form';++export const createAlertMocks = defineStoryMocks({+ controls: {+ alertMode: choiceControl<AlertMode>('Alert being created', {+ group: FORM,+ options: ALERT_MODES,+ value: 'metrics',+ }),+ channels: countControl('Notification channels', {+ group: FORM,+ description: 'What a threshold can be routed to.',+ value: 5,+ max: CHANNEL_MAX,+ }),+ previewSeries: countControl('Preview series', {+ group: FORM,+ description:+ 'Lines the chart above the condition draws once the query has something to run. A new metric alert has no metric picked yet, so it draws nothing until one is.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => [+ rest.post('http://localhost/api/v2/rules', (_req, res, ctx) =>+ res(ctx.status(201), ctx.json({ status: 'success', data: null })),+ ),++ rest.post('http://localhost/api/v2/rules/test', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: { alertCount: 2, message: 'Rule tested against the last 6 hours' },+ }),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/channels',+ response.json(() => channelsResponse(values.channels)),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => alertPreviewSeries(values.previewSeries, req)),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics',+ response.json((req) =>+ alertMetricsResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/metadata',+ response.json((req) =>+ alertMetricMetadataResponse(req.url.searchParams.get('metricName') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ alertFieldKeysResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ alertFieldValuesResponse(+ req.url.searchParams.get('name') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),+ ],+ config: (values) => ({ route: routeFor(values.alertMode) }),+});diff --git a/frontend/src/pages/CreateAlert/stories/CreateAlert.stories.tsx b/frontend/src/pages/CreateAlert/stories/CreateAlert.stories.tsxnew file mode 100644index 0000000000..9507c3a416--- /dev/null+++ b/frontend/src/pages/CreateAlert/stories/CreateAlert.stories.tsx@@ -0,0 +1,89 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { createAlertMocks } from './CreateAlert.stories.mocks';++import CreateAlertPage from '../index';++type CreateAlertArgs = PageStoryArgs<typeof createAlertMocks>;++const pageStory = storyMocks(createAlertMocks, { layout: 'app' });++/**+ * The new rule builder: the query, the condition, the evaluation preview against+ * `query_range`, and the channels to notify. The mode control picks the alert+ * type.+ *+ * Route: `/alerts/new`.+ */+const meta = {+ title: 'Pages/Alerts/Create',+ tags: ['play'],+ component: CreateAlertPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<CreateAlertArgs>;++export default meta;++type Story = StoryObj<CreateAlertArgs>;++/**+ * A new metric alert being written: the query it watches, the threshold it+ * fires on, and where the notification goes.+ */+export const Default: Story = {};++/** Where a new alert starts: the signal the rule is going to watch. */+export const SelectAlertType: Story = {+ args: { alertMode: 'select-type' },+};++/** A log-based alert, whose query section searches logs rather than metrics. */+export const LogsAlert: Story = {+ args: { alertMode: 'logs' },+};++/**+ * Anomaly detection, which is still written in the classic form: the seasonality+ * and the deviation take the place of a fixed threshold.+ */+export const AnomalyAlert: Story = {+ args: { alertMode: 'anomaly' },+};++/** The classic form, which `showClassicCreateAlertsPage` opts back into. */+export const ClassicForm: Story = {+ args: { alertMode: 'classic-form' },+};++/**+ * 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+ * link. There is one per match type, and they are antd tooltips rather than+ * `@signozhq/ui` ones, so the Tooltips control leaves them alone and only the+ * option under the pointer shows one. This opens the match-type list and holds+ * the tallest of the five, "all the time", whose example runs to two lines.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }): Promise<void> => {+ const select = await within(canvasElement).findByTestId(+ 'alert-threshold-match-type-select',+ undefined,+ { timeout: 15_000 },+ );++ // The select opens off a mousedown on its inner selector, so a click on+ // the wrapper the test id sits on reaches nothing.+ await userEvent.click(within(select).getByRole('combobox'));++ await userEvent.hover(+ await screen.findByText('ALL THE TIME', undefined, { timeout: 15_000 }),+ );+ await screen.findByText('Example:', undefined, { timeout: 15_000 });+ },+};diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks.tsxnew file mode 100644index 0000000000..79ebdb290a--- /dev/null+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.mocks.tsx@@ -0,0 +1,205 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import { generatePath } from 'react-router-dom';+import ROUTES from 'constants/routes';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';++import { choiceControl, toggleControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import {+ fieldKeysResponse,+ fieldValuesResponse,+} from '@/storybook/msw/__story_mockdata__/fields';+import {+ listMetricsResponse,+ metricMetadataResponse,+} from '@/storybook/msw/__story_mockdata__/metrics';++import {+ NEW_PANEL_ID,+ newPanelSearch,+} from '../../DashboardContainer/PanelEditor/newPanelRoute';+import {+ currentDashboardDocument,+ PANEL_IDS,+ patchDashboardDocument,+ seedDashboardDocument,+ STORY_DASHBOARD_ID,+ VARIABLE_KINDS,+ type DashboardArgs,+} from '../../stories/__story_mockdata__/dashboard';+import {+ emptyPanelResponse,+ NAMESPACE_VALUES,+ panelResponse,+ serviceVariableValues,+} from '../../stories/__story_mockdata__/panelData';+import {+ EDITOR_FIELD_KEYS,+ EDITOR_FIELD_VALUES,+ EDITOR_METRICS,+ NEW_PANEL_KINDS,+ newPanelKindOf,+ type NewPanelKind,+} from './__story_mockdata__/panelEditor';++const PANEL = 'Panel editor · panel';+const DATA = 'Panel editor · data';++const PANEL_OPTIONS = [...PANEL_IDS, NEW_PANEL_ID] as const;++type PanelOption = (typeof PANEL_OPTIONS)[number];++const editorRoute = (panel: PanelOption, kind: NewPanelKind): string => {+ const path = generatePath(ROUTES.DASHBOARD_PANEL_EDITOR, {+ dashboardId: STORY_DASHBOARD_ID,+ panelId: panel,+ });++ return panel === NEW_PANEL_ID+ ? `${path}${newPanelSearch(newPanelKindOf(kind))}`+ : path;+};++export const panelEditorMocks = defineStoryMocks({+ controls: {+ panel: choiceControl<PanelOption>('Panel', {+ group: PANEL,+ description:+ 'The panel the editor opens on. `new` is the create route, which seeds an unsaved panel of the kind below instead of loading one.',+ options: PANEL_OPTIONS,+ value: 'request-rate',+ }),+ newPanelKind: choiceControl<NewPanelKind>('New panel kind', {+ group: PANEL,+ description: 'Which kind the create route seeds. Ignored on a saved panel.',+ options: NEW_PANEL_KINDS,+ value: 'time-series',+ }),+ locked: toggleControl('Dashboard locked', {+ group: PANEL,+ description:+ 'A locked dashboard is read-only, so the editor loads but Save is refused with the reason.',+ value: false,+ }),+ noData: toggleControl('Preview returns nothing', {+ group: DATA,+ description: 'The preview query answers with an empty result.',+ value: false,+ }),+ },+ handlers: (values, response) => {+ const document: DashboardArgs = {+ panels: PANEL_IDS.length,+ sectioned: true,+ variables: VARIABLE_KINDS,+ locked: values.locked,+ };++ return [+ // The document the editor resolves its panel from, so it answers on its own+ // rather than through the Data control.+ rest.get('http://localhost/api/v2/dashboards/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(currentDashboardDocument(document))),+ ),++ // Saving the panel is a JSON Patch whose response replaces the cache, so+ // the ops are applied to the story's document and the edit stays.+ rest.patch(+ 'http://localhost/api/v2/dashboards/:id',+ async (req, res, ctx) => {+ const ops = (await req.json()) as Parameters<+ typeof patchDashboardDocument+ >[1];++ return res(+ ctx.status(200),+ ctx.json(patchDashboardDocument(document, ops)),+ );+ },+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ if (values.noData) {+ return emptyPanelResponse();+ }++ const body = (await req.json()) as QueryRangeRequestV5;+ const spec = body.compositeQuery?.queries?.[0]?.spec as+ | {+ aggregations?: { metricName?: string }[];+ groupBy?: { name?: string }[];+ }+ | undefined;++ return panelResponse({+ requestType: body.requestType,+ window: { start: body.start, end: body.end },+ metricName: spec?.aggregations?.[0]?.metricName,+ groupBy: spec?.groupBy?.[0]?.name,+ });+ }),+ ),++ rest.post(+ 'http://localhost/api/v2/variables/query',+ response.json(() => ({+ status: 'success',+ data: { variableValues: serviceVariableValues(4) },+ })),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics',+ response.json((req) =>+ listMetricsResponse(+ EDITOR_METRICS,+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/metadata',+ response.json((req) =>+ metricMetadataResponse(+ EDITOR_METRICS,+ req.url.searchParams.get('metricName') ?? '',+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json(() => fieldKeysResponse(EDITOR_FIELD_KEYS)),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(+ EDITOR_FIELD_VALUES[req.url.searchParams.get('name') ?? ''] ??+ NAMESPACE_VALUES,+ ),+ ),+ ),+ ];+ },+ config: (values) => ({+ route: editorRoute(values.panel, values.newPanelKind),+ }),+ effect: (values) => {+ seedDashboardDocument({+ panels: PANEL_IDS.length,+ sectioned: true,+ variables: VARIABLE_KINDS,+ locked: values.locked,+ });+ },+});diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.tsx b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.tsxnew file mode 100644index 0000000000..44675723ab--- /dev/null+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/PanelEditorPage.stories.tsx@@ -0,0 +1,86 @@+import type { ComponentType } from 'react';+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { panelEditorMocks } from './PanelEditorPage.stories.mocks';++import PanelEditorPage from '../PanelEditorPage';++type PanelEditorArgs = PageStoryArgs<typeof panelEditorMocks>;++const pageStory = storyMocks(panelEditorMocks, { layout: 'app' });++/**+ * The panel editor: the query builder on one side, the panel it renders on the+ * other, for a panel that exists or a new one of the chosen kind.+ *+ * Route: `/dashboard/:dashboardId/panel/:panelId`.+ */+const meta = {+ title: 'Pages/Dashboards/Panel Editor',+ // The page is wrapped in `withAuthZPage`, which types its props as an index+ // signature; the story's args are what the controls resolve to.+ component: PanelEditorPage as ComponentType<PanelEditorArgs>,+ // The dashboard and panel ids come out of the pathname, so the editor renders+ // under its own route rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route path={ROUTES.DASHBOARD_PANEL_EDITOR} component={PanelEditorPage} />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<PanelEditorArgs>;++export default meta;++type Story = StoryObj<PanelEditorArgs>;++/**+ * Editing a saved time series panel: the live preview over the query builder on+ * the left, the panel's formatting, legend, axes and thresholds on the right.+ */+export const Default: Story = {};++/** The create route, seeding an unsaved panel of the chosen kind. */+export const NewPanel: Story = {+ args: { panel: 'new' },+};++/** A list panel, where the config pane is the column editor. */+export const ListPanel: Story = {+ args: { panel: 'recent-logs' },+};++/** A table panel, with its column units and thresholds. */+export const TablePanel: Story = {+ args: { panel: 'top-endpoints' },+};++/** The editor and query configuration remain visible when its preview has no rows. */+export const NoPreviewData: Story = {+ args: { noData: true },+};++/** The editor remains usable while the independently fetched preview has failed. */+export const PreviewQueryError: Story = {+ args: { dataState: 'error' },+};++/** A locked dashboard: the editor still opens, but it cannot save. */+export const ReadOnly: Story = {+ args: { locked: true },+ // The deliberate 500s on the metrics queries are the state under test.+ parameters: { allowConsoleErrors: true },+};++/**+ * Every tooltip the editor carries, held open: the Quick Add beside the+ * Thresholds and Context links section headers, and the copy button on each of+ * the preview legend's series.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+};diff --git a/frontend/src/pages/DashboardPage/PanelEditorPage/stories/__story_mockdata__/panelEditor.ts b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/__story_mockdata__/panelEditor.tsnew file mode 100644index 0000000000..8f6d7e79a3--- /dev/null+++ b/frontend/src/pages/DashboardPage/PanelEditorPage/stories/__story_mockdata__/panelEditor.ts@@ -0,0 +1,98 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';++import {+ metricSeed,+ type MetricSeed,+} from '@/storybook/msw/__story_mockdata__/metrics';++import type { PanelKind } from '../../../DashboardContainer/Panels/types/panelKind';++/**+ * The panel kinds the create route can seed, spelled without the `signoz/`+ * prefix: a control value carrying a slash does not survive the story URL.+ */+export const NEW_PANEL_KINDS = [+ 'time-series',+ 'bar-chart',+ 'number',+ 'pie-chart',+ 'table',+ 'histogram',+ 'list',+] as const;++export type NewPanelKind = (typeof NEW_PANEL_KINDS)[number];++const KIND_BY_OPTION: Record<NewPanelKind, PanelKind> = {+ 'time-series': 'signoz/TimeSeriesPanel',+ 'bar-chart': 'signoz/BarChartPanel',+ number: 'signoz/NumberPanel',+ 'pie-chart': 'signoz/PieChartPanel',+ table: 'signoz/TablePanel',+ histogram: 'signoz/HistogramPanel',+ list: 'signoz/ListPanel',+};++export const newPanelKindOf = (option: NewPanelKind): PanelKind =>+ KIND_BY_OPTION[option];++/** Attributes the editor's query builder offers while filtering and grouping. */+export const EDITOR_FIELD_KEYS = [+ 'service.name',+ 'http.route',+ 'http.status_code',+ 'deployment.environment',+ 'k8s.namespace.name',+ 'host.name',+] as const;++export const EDITOR_FIELD_VALUES: Record<string, readonly string[]> = {+ 'service.name': ['checkout', 'payments', 'inventory', 'notifications'],+ 'http.route': ['/v1/checkout', '/v1/cart', '/v1/payment/authorize'],+ 'http.status_code': ['200', '404', '500', '503'],+ 'deployment.environment': ['production', 'staging', 'development'],+ 'k8s.namespace.name': ['checkout-prod', 'payments-prod', 'platform-prod'],+ 'host.name': ['ip-10-0-1-14', 'ip-10-0-2-31', 'ip-10-0-3-77'],+};++/** The metrics the editor's aggregation field offers, the panels' own included. */+export const EDITOR_METRICS: MetricSeed[] = [+ metricSeed('signoz_calls_total', 'Total spans received', 'count'),+ metricSeed('signoz_errors_total', 'Spans with an error status', 'count'),+ metricSeed(+ 'signoz_latency_bucket',+ 'Span duration histogram',+ 'ms',+ MetrictypesTypeDTO.histogram,+ MetrictypesTemporalityDTO.delta,+ ),+ metricSeed(+ 'signoz_apdex',+ 'Apdex score per service',+ '',+ MetrictypesTypeDTO.gauge,+ MetrictypesTemporalityDTO.unspecified,+ ),+ metricSeed(+ 'system_cpu_usage',+ 'CPU used per host',+ 'percent',+ MetrictypesTypeDTO.gauge,+ MetrictypesTemporalityDTO.unspecified,+ ),+ metricSeed(+ 'system_memory_usage',+ 'Memory used per host',+ 'bytes',+ MetrictypesTypeDTO.gauge,+ MetrictypesTemporalityDTO.unspecified,+ ),+];diff --git a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsxnew file mode 100644index 0000000000..cc10d046ba--- /dev/null+++ b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.mocks.tsx@@ -0,0 +1,329 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import { generatePath } from 'react-router-dom';+import ROUTES from 'constants/routes';+import type { GetPublicDashboard200 } from 'api/generated/services/sigNoz.schemas';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';++import {+ countControl,+ multiChoiceControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import { fieldValuesResponse } from '@/storybook/msw/__story_mockdata__/fields';+import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/queryRange';++import {+ currentDashboardDocument,+ patchDashboardDocument,+ PANEL_IDS,+ seedDashboardDocument,+ STORY_DASHBOARD_ID,+ VARIABLE_KINDS,+ type DashboardArgs,+ type VariableKind,+} from './__story_mockdata__/dashboard';+import {+ emptyPanelResponse,+ NAMESPACE_VALUES,+ panelResponse,+ serviceVariableValues,+} from './__story_mockdata__/panelData';+import {+ desyncedDashboardResponse,+ TOOLTIP_SELECTED_SERVICES,+ TOOLTIP_WARNED_METRIC,+ tooltipDashboardResponse,+} from './__story_mockdata__/tooltipDashboard';++const LAYOUT = 'Dashboard · layout';+const DATA = 'Dashboard · panels';+const SHARING = 'Dashboard · sharing';++export const dashboardRoute = (): string =>+ generatePath(ROUTES.DASHBOARD, { dashboardId: STORY_DASHBOARD_ID });++export const tooltipRoute = (): string =>+ `${dashboardRoute()}?variables=${encodeURIComponent(+ JSON.stringify({ service: TOOLTIP_SELECTED_SERVICES }),+ )}`;++const NOT_FOUND = {+ status: 'error',+ error: {+ code: 'not_found',+ message: `dashboard with id ${STORY_DASHBOARD_ID} not found`,+ url: '',+ errors: [],+ },+};++const ok = { status: 'success', data: null };++const publicMeta = (): GetPublicDashboard200 => ({+ status: 'success',+ data: {+ timeRangeEnabled: true,+ defaultTimeRange: '30m',+ publicPath: `/public/dashboard/${STORY_DASHBOARD_ID}`,+ },+});++const NOT_PUBLIC = {+ status: 'error',+ error: {+ code: 'public_dashboard_not_found',+ message: `dashboard with id ${STORY_DASHBOARD_ID} isn't public`,+ url: '',+ errors: [],+ },+};++interface PanelQuerySpec {+ signal?: string;+ aggregations?: { metricName?: string }[];+ groupBy?: { name?: string }[];+}++const readPanelQuery = (+ body: QueryRangeRequestV5,+): { metricName?: string; groupBy?: string } => {+ const spec = body.compositeQuery?.queries?.[0]?.spec as+ | PanelQuerySpec+ | undefined;++ return {+ metricName: spec?.aggregations?.[0]?.metricName,+ groupBy: spec?.groupBy?.[0]?.name,+ };+};++export const dashboardMocks = defineStoryMocks({+ controls: {+ panels: countControl('Panels', {+ group: LAYOUT,+ description:+ 'Panels the dashboard holds, taken in layout order. Zero is the blank dashboard a fresh one starts as.',+ value: PANEL_IDS.length,+ max: PANEL_IDS.length,+ }),+ sectioned: toggleControl('Sections', {+ group: LAYOUT,+ description:+ 'Titled, collapsible, reorderable sections. Off is the single untitled grid a dashboard without sections renders.',+ value: true,+ }),+ locked: toggleControl('Locked', {+ group: LAYOUT,+ description:+ 'A locked dashboard is read-only: the lock indicator shows and the edit affordances go.',+ value: false,+ }),+ variables: multiChoiceControl<VariableKind>('Variables', {+ group: LAYOUT,+ description:+ 'The variable bar above the panels, one control per kind: a custom list, a query-backed list, a dynamic attribute and a free-text value.',+ options: VARIABLE_KINDS,+ value: [...VARIABLE_KINDS],+ }),+ variableValues: countControl('Variable options', {+ group: DATA,+ description: 'Values the query-backed `service` variable resolves to.',+ value: 4,+ max: 12,+ }),+ noData: toggleControl('Panels return nothing', {+ group: DATA,+ description:+ 'Every panel query answers with an empty result, which is the no-data state each renderer draws on its own.',+ value: false,+ }),+ notFound: toggleControl('Dashboard not found', {+ group: LAYOUT,+ description:+ 'Answers the dashboard document with a 404, which is the page-level failure the shell renders around.',+ value: false,+ }),+ published: toggleControl('Published publicly', {+ group: SHARING,+ description:+ 'Whether this dashboard has a public link, which is what the header globe reports. Turning it off is the 404 the endpoint answers for a dashboard nobody published.',+ value: true,+ }),+ },+ handlers: (values, response) => {+ const document: DashboardArgs = {+ panels: values.panels,+ sectioned: values.sectioned,+ variables: values.variables,+ locked: values.locked,+ };++ return [+ // The document is what the page renders from, so it answers on its own+ // rather than through the Data control: the panels are what that holds in+ // the loading and failed states, with the dashboard already laid out.+ rest.get('http://localhost/api/v2/dashboards/:id', (_req, res, ctx) =>+ values.notFound+ ? res(ctx.status(404), ctx.json(NOT_FOUND))+ : res(ctx.status(200), ctx.json(currentDashboardDocument(document))),+ ),++ // Every spec edit travels as a JSON Patch, and its response is what+ // replaces the cache, so the ops are applied to the story's document+ // rather than answered away.+ rest.patch(+ 'http://localhost/api/v2/dashboards/:id',+ async (req, res, ctx) => {+ const ops = (await req.json()) as Parameters<+ typeof patchDashboardDocument+ >[1];++ return res(+ ctx.status(200),+ ctx.json(patchDashboardDocument(document, ops)),+ );+ },+ ),++ rest.post('http://localhost/api/v2/dashboards/:id/clone', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(currentDashboardDocument(document))),+ ),++ rest.delete('http://localhost/api/v2/dashboards/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(ok)),+ ),++ rest.put('http://localhost/api/v2/dashboards/:id/lock', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(ok)),+ ),++ rest.delete(+ 'http://localhost/api/v2/dashboards/:id/lock',+ (_req, res, ctx) => res(ctx.status(200), ctx.json(ok)),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ if (values.noData) {+ return emptyPanelResponse();+ }++ const body = (await req.json()) as QueryRangeRequestV5;++ return panelResponse({+ requestType: body.requestType,+ window: { start: body.start, end: body.end },+ ...readPanelQuery(body),+ });+ }),+ ),++ rest.post(+ 'http://localhost/api/v2/variables/query',+ response.json(() => ({+ status: 'success',+ data: { variableValues: serviceVariableValues(values.variableValues) },+ })),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json(() => fieldValuesResponse(NAMESPACE_VALUES)),+ ),++ // The header reads the public link on every load, so it answers even while+ // the panels are held in the loading or failed state.+ rest.get('http://localhost/api/v1/dashboards/:id/public', (_req, res, ctx) =>+ values.published+ ? res(ctx.status(200), ctx.json(publicMeta()))+ : res(ctx.status(404), ctx.json(NOT_PUBLIC)),+ ),++ rest.post(+ 'http://localhost/api/v1/dashboards/:id/public',+ (_req, res, ctx) => res(ctx.status(200), ctx.json(publicMeta())),+ ),++ rest.put('http://localhost/api/v1/dashboards/:id/public', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(publicMeta())),+ ),++ rest.delete(+ 'http://localhost/api/v1/dashboards/:id/public',+ (_req, res, ctx) => res(ctx.status(200), ctx.json(ok)),+ ),+ ];+ },+ config: () => ({ route: dashboardRoute() }),+ effect: (values) => {+ seedDashboardDocument({+ panels: values.panels,+ sectioned: values.sectioned,+ variables: values.variables,+ locked: values.locked,+ });+ },+});++/**+ * 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.+ * Every other query falls through to the page's own handler.+ */+export const warnedPanelQueryHandler = rest.post(+ 'http://localhost/api/v5/query_range',+ async (req, res, ctx) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const spec = body.compositeQuery?.queries?.[0]?.spec as+ | { aggregations?: { metricName?: string }[] }+ | undefined;++ if (spec?.aggregations?.[0]?.metricName !== TOOLTIP_WARNED_METRIC) {+ return undefined;+ }++ return res(+ ctx.status(200),+ ctx.json(+ queryRangeV5ScalarResponse(0.94, 'A', {+ warning: {+ code: 'partial_data',+ message: `Some series for ${TOOLTIP_WARNED_METRIC} were dropped: the metric changed temporality partway through the selected window.`,+ url: 'https://signoz.io/docs/metrics-management/types-and-aggregation/',+ warnings: [+ {+ message:+ 'Narrow the window to a period with one temporality, or re-record the metric as a delta.',+ },+ ],+ },+ }),+ ),+ );+ },+);++export const tooltipDashboardHandler = rest.get(+ 'http://localhost/api/v2/dashboards/:id',+ (_req, res, ctx) => res(ctx.status(200), ctx.json(tooltipDashboardResponse())),+);++export const desyncedDashboardHandler = rest.get(+ 'http://localhost/api/v2/dashboards/:id',+ (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(desyncedDashboardResponse())),+);++// The view modal mounts a query builder, which lists metrics before it renders.+export const metricsListHandler = rest.get(+ 'http://localhost/api/v2/metrics',+ (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: { metrics: [] } })),+);diff --git a/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.tsx b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.tsxnew file mode 100644index 0000000000..6a9750f32f--- /dev/null+++ b/frontend/src/pages/DashboardPage/stories/DashboardPage.stories.tsx@@ -0,0 +1,297 @@+import type { ComponentType } from 'react';+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import {+ dashboardMocks,+ desyncedDashboardHandler,+ metricsListHandler,+ tooltipDashboardHandler,+ tooltipRoute,+ warnedPanelQueryHandler,+} from './DashboardPage.stories.mocks';+import { TOOLTIP_PANEL_NAME } from './__story_mockdata__/tooltipDashboard';++import DashboardPage from '../DashboardPage';++type DashboardArgs = PageStoryArgs<typeof dashboardMocks>;++const pageStory = storyMocks(dashboardMocks, { layout: 'app' });++/**+ * One dashboard: its variables, its sections and every panel querying+ * `query_range`, plus the lock, clone and publish actions in the header.+ *+ * Route: `/dashboard/:dashboardId`.+ */+const meta = {+ title: 'Pages/Dashboards/Detail',+ tags: ['role-gated', 'play'],+ // The page is wrapped in `withAuthZPage`, which types its props as an index+ // signature; the story's args are what the controls resolve to.+ component: DashboardPage as ComponentType<DashboardArgs>,+ // The page reads the dashboard id out of the pathname, so it renders under+ // its own route rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route path={ROUTES.DASHBOARD} component={DashboardPage} />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<DashboardArgs>;++export default meta;++type Story = StoryObj<DashboardArgs>;++/**+ * A service dashboard with data: the variable bar over two titled sections, and+ * the panel kinds all drawn from the same query endpoint: time series, single+ * numbers, a table, a bar chart, a pie and a log list.+ */+export const Default: Story = {};++/**+ * The blank dashboard a freshly created one starts as, with the two steps that+ * populate it. A titled section renders its own add-panel state instead, so this+ * needs both no panels and no sections.+ */+export const Empty: Story = {+ args: { panels: 0, sectioned: false },+};++/**+ * A locked dashboard: the lock indicator sits over the grid and the edit+ * affordances are gone even for an admin.+ */+export const Locked: Story = {+ args: { locked: true },+};++/**+ * A viewer: the panels and the variable bar work, but nothing that would change+ * the dashboard is offered.+ */+export const Viewer: Story = {+ args: { access: 'viewer' },+};++/**+ * Every query ran and matched nothing, which each panel kind draws as its own+ * no-data state.+ */+export const NoData: Story = {+ args: { noData: true },+};++/** A partial data failure: the dashboard remains visible while panel queries fail. */+export const PanelQueryError: Story = {+ args: { dataState: 'error' },+};++/** The panels mid-fetch, with the header, variable bar and grid already laid out. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/**+ * Every tooltip the dashboard itself carries, held open at once: the title, the+ * description with its link, the public-page globe, the `+N` of tags that did+ * not fit, two panel descriptions, a panel's time-preference pill, the+ * collapsed panel search, the warning one panel's query came back with, the+ * `+N` of variables the bar hid, the values a multi-select pill stands for, the+ * add-variable `+`, and a legend's copy buttons.+ *+ * The document and one panel's query are answered by the story, so the Panels,+ * Sections, Variables and Locked controls do not reach it; the Variable options+ * control still does, and the selection comes from the route.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true, variableValues: 12 },+ parameters: {+ signoz: { route: tooltipRoute() },+ msw: { handlers: [tooltipDashboardHandler, warnedPanelQueryHandler] },+ },+};++/**+ * What a locked dashboard refuses, with the Actions menu open: the padlock+ * offering to unlock, the disabled Configure and New Panel buttons, and the+ * menu rows saying why they cannot be picked.+ */+export const TooltipsWhenLocked: Story = {+ args: { tooltipsOpen: true, locked: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ // The dropdown trigger's Slot merge drops the button's own test id.+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Actions' }, { timeout: 10000 }),+ );+ await screen.findByText('Clone dashboard');+ },+};++/**+ * The JSON editor's two warnings, held open: the panels the layout places+ * nowhere and the layout slots pointing at panels the spec no longer has, each+ * listing the ids behind it.+ *+ * The document is answered by the story, so the Panels, Sections, Variables and+ * Locked controls do not reach it.+ */+export const TooltipsInJsonDrawer: Story = {+ args: { tooltipsOpen: true },+ parameters: { msw: { handlers: [desyncedDashboardHandler] } },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId('edit-json', {}, { timeout: 10000 }),+ );+ await screen.findByTestId('json-editor-dangling-warning');+ },+};++/**+ * The Overview tab of dashboard settings, where Cross-Panel Sync explains what+ * syncing the crosshair does and links out to the docs.+ */+export const TooltipsInSettings: Story = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId('show-drawer', {}, { timeout: 10000 }),+ );+ await screen.findByText('Sync Mode');+ },+};++/**+ * The Variables tab of dashboard settings, where a dynamic variable's Apply to+ * all says whether it is already a filter on every panel. The row keeps its+ * actions invisible until it is hovered, which the story does first.+ */+export const TooltipsInVariableSettings: Story = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId('show-drawer', {}, { timeout: 10000 }),+ );+ await userEvent.click(await screen.findByRole('tab', { name: 'Variables' }));++ // The tooltip trigger's Slot merge drops the button's own test id.+ await userEvent.hover(+ await screen.findByRole(+ 'button',+ { name: 'Apply to all' },+ { timeout: 10000 },+ ),+ );+ await screen.findByText(+ 'Add this variable as a filter to every panel',+ undefined,+ { timeout: 10000 },+ );+ },+};++/**+ * A panel expanded into view mode, whose header carries the full panel name its+ * title truncates, over the dashboard's own tooltips behind the dialog.+ *+ * The document is answered by the story, so the Panels, Sections, Variables and+ * Locked controls do not reach it.+ */+export const TooltipsInViewPanelModal: Story = {+ args: { tooltipsOpen: true },+ parameters: {+ msw: { handlers: [tooltipDashboardHandler, metricsListHandler] },+ },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId(+ 'panel-actions-request-rate',+ {},+ { timeout: 10000 },+ ),+ );+ await userEvent.click(await screen.findByText('View'));+ await screen.findByText(`${TOOLTIP_PANEL_NAME} - (View mode)`);+ },+};++/**+ * The dashboard's own Actions menu, open: rename, clone, lock, full screen and+ * delete, the menu the toolbar's Actions button carries.+ */+export const ActionsMenu: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ // The dropdown trigger's Slot merge drops the button's own test id.+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Actions' }, { timeout: 10000 }),+ );+ await screen.findByText('Clone dashboard');+ },+};++/**+ * One panel's own menu, open over the grid: edit, clone, the download formats+ * its data can be taken in, and the move-to-section submenu.+ */+export const PanelActionsMenu: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId(+ 'panel-actions-p99-latency',+ {},+ { timeout: 10000 },+ ),+ );+ await screen.findByRole('menu');+ },+};++/**+ * A section's menu, open: add a panel to it, rename it, clone it, delete it.+ */+export const SectionActionsMenu: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ const [firstSection] = await canvas.findAllByRole(+ 'button',+ { name: 'Section actions' },+ { timeout: 10000 },+ );+ await userEvent.click(firstSection);+ await screen.findByRole('menu');+ },+};++/**+ * A dashboard id nobody has, which is what a deleted or mistyped link opens on.+ *+ * Kept last: test-runner shares one page across a file's stories, and the 404+ * this story is about can settle after the next story has already started,+ * which fails that one instead.+ */+export const NotFound: Story = {+ args: { notFound: true },+ // The deliberate 404 is the state under test.+ parameters: { allowConsoleErrors: true },+};diff --git a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.ts b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.tsnew file mode 100644index 0000000000..84d4f2a8c1--- /dev/null+++ b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/dashboard.ts@@ -0,0 +1,453 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ DashboardtypesDynamicVariableSignalDTO as DynamicSignal,+ DashboardtypesLayoutEnvelopeGithubComPersesSpecGoDashboardGridLayoutSpecDTOKind as GridKind,+ DashboardtypesPanelKindDTO as PanelKind,+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBarChartPanelSpecDTOKind as BarChartKind,+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesListPanelSpecDTOKind as ListKind,+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesNumberPanelSpecDTOKind as NumberKind,+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesPieChartPanelSpecDTOKind as PieChartKind,+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTablePanelSpecDTOKind as TableKind,+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind as TimeSeriesKind,+ DashboardtypesQueryPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesBuilderQuerySpecDTOKind as BuilderQueryKind,+ DashboardtypesSourceDTO,+ DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesListVariableSpecDTOKind as ListVariableKind,+ DashboardtypesVariableEnvelopeGithubComSigNozSignozPkgTypesDashboardtypesTextVariableSpecDTOKind as TextVariableKind,+ DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesCustomVariableSpecDTOKind as CustomVariableKind,+ DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesDynamicVariableSpecDTOKind as DynamicVariableKind,+ DashboardtypesVariablePluginVariantGithubComSigNozSignozPkgTypesDashboardtypesQueryVariableSpecDTOKind as QueryVariableKind,+ MetrictypesSpaceAggregationDTO as SpaceAggregation,+ MetrictypesTimeAggregationDTO as TimeAggregation,+ Querybuildertypesv5OrderDirectionDTO as OrderDirection,+ Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTOSignal as LogSignal,+ Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTOSignal as MetricSignal,+ Querybuildertypesv5RequestTypeDTO as RequestType,+ type DashboardtypesDashboardSpecDTOPanels,+ type DashboardtypesLayoutDTO,+ type DashboardtypesPanelDTO,+ type DashboardtypesGettableDashboardV2DTO,+ type DashboardtypesJSONPatchOperationDTO,+ type DashboardtypesQueryDTO,+ type DashboardtypesVariableDTO,+ type GetDashboardV2200,+ type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5LogAggregationDTO as LogBuilderQuery,+ type Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5MetricAggregationDTO as MetricBuilderQuery,+} from 'api/generated/services/sigNoz.schemas';++import { applyJsonPatch } from '../../DashboardContainer/optimistic/applyJsonPatch';++export const STORY_DASHBOARD_ID = 'storybook-dashboard-1';++interface MetricQueryArgs {+ metricName: string;+ requestType: RequestType;+ groupBy?: string;+ /** Only the plotted kinds label their series; a table would show it as a column header. */+ legend?: string;+}++const QUERY_NAME = 'A';++const metricQuery = ({+ metricName,+ requestType,+ groupBy,+ legend,+}: MetricQueryArgs): DashboardtypesQueryDTO[] => {+ const spec: MetricBuilderQuery = {+ name: QUERY_NAME,+ signal: MetricSignal.metrics,+ aggregations: [+ {+ metricName,+ spaceAggregation: SpaceAggregation.sum,+ timeAggregation: TimeAggregation.rate,+ },+ ],+ groupBy: groupBy ? [{ name: groupBy }] : undefined,+ legend,+ filter: { expression: 'deployment.environment = $environment' },+ };++ return [+ {+ kind: requestType,+ spec: {+ name: QUERY_NAME,+ plugin: { kind: BuilderQueryKind['signoz/BuilderQuery'], spec },+ },+ },+ ];+};++const logQuery = (): DashboardtypesQueryDTO[] => {+ const spec: LogBuilderQuery = {+ name: QUERY_NAME,+ signal: LogSignal.logs,+ selectFields: [{ name: 'body' }, { name: 'service.name' }],+ order: [{ key: { name: 'timestamp' }, direction: OrderDirection.desc }],+ };++ return [+ {+ kind: RequestType.raw,+ spec: {+ name: QUERY_NAME,+ plugin: { kind: BuilderQueryKind['signoz/BuilderQuery'], spec },+ },+ },+ ];+};++/**+ * The panels the dashboard holds, in the order the sections lay them out. Each+ * one names the query the handler answers for, so a panel's shape and its data+ * stay declared together.+ */+export const PANEL_IDS = [+ 'request-rate',+ 'error-rate',+ 'p99-latency',+ 'apdex',+ 'top-endpoints',+ 'errors-by-status',+ 'traffic-share',+ 'recent-logs',+] as const;++export type PanelId = (typeof PANEL_IDS)[number];++const PANELS: Record<PanelId, DashboardtypesPanelDTO> = {+ 'request-rate': {+ kind: PanelKind.Panel,+ spec: {+ display: { name: 'Request rate by service' },+ plugin: { kind: TimeSeriesKind['signoz/TimeSeriesPanel'], spec: {} },+ queries: metricQuery({+ metricName: 'signoz_calls_total',+ requestType: RequestType.time_series,+ groupBy: 'service.name',+ legend: '{{service.name}}',+ }),+ },+ },+ 'error-rate': {+ kind: PanelKind.Panel,+ spec: {+ display: {+ name: 'Error rate',+ description: 'Share of 5xx responses over the selected window.',+ },+ plugin: { kind: TimeSeriesKind['signoz/TimeSeriesPanel'], spec: {} },+ queries: metricQuery({+ metricName: 'signoz_errors_total',+ requestType: RequestType.time_series,+ legend: 'errors / sec',+ }),+ },+ },+ 'p99-latency': {+ kind: PanelKind.Panel,+ spec: {+ display: { name: 'p99 latency' },+ plugin: { kind: NumberKind['signoz/NumberPanel'], spec: {} },+ queries: metricQuery({+ metricName: 'signoz_latency_bucket',+ requestType: RequestType.scalar,+ }),+ },+ },+ apdex: {+ kind: PanelKind.Panel,+ spec: {+ display: { name: 'Apdex' },+ plugin: { kind: NumberKind['signoz/NumberPanel'], spec: {} },+ queries: metricQuery({+ metricName: 'signoz_apdex',+ requestType: RequestType.scalar,+ }),+ },+ },+ 'top-endpoints': {+ kind: PanelKind.Panel,+ spec: {+ display: { name: 'Top endpoints' },+ plugin: { kind: TableKind['signoz/TablePanel'], spec: {} },+ queries: metricQuery({+ metricName: 'signoz_calls_total',+ requestType: RequestType.scalar,+ groupBy: 'http.route',+ }),+ },+ },+ 'errors-by-status': {+ kind: PanelKind.Panel,+ spec: {+ display: { name: 'Errors by status code' },+ plugin: { kind: BarChartKind['signoz/BarChartPanel'], spec: {} },+ queries: metricQuery({+ metricName: 'signoz_errors_total',+ requestType: RequestType.time_series,+ groupBy: 'http.status_code',+ legend: '{{http.status_code}}',+ }),+ },+ },+ 'traffic-share': {+ kind: PanelKind.Panel,+ spec: {+ display: { name: 'Traffic share' },+ plugin: { kind: PieChartKind['signoz/PieChartPanel'], spec: {} },+ queries: metricQuery({+ metricName: 'signoz_calls_total',+ requestType: RequestType.scalar,+ groupBy: 'service.name',+ }),+ },+ },+ 'recent-logs': {+ kind: PanelKind.Panel,+ spec: {+ display: { name: 'Recent logs' },+ plugin: { kind: ListKind['signoz/ListPanel'], spec: {} },+ queries: logQuery(),+ },+ },+};++interface SectionSeed {+ title: string;+ panels: PanelId[];+}++const SECTIONS: SectionSeed[] = [+ {+ title: 'Golden signals',+ panels: ['p99-latency', 'apdex', 'error-rate', 'request-rate'],+ },+ {+ title: 'Breakdown',+ panels: ['top-endpoints', 'errors-by-status', 'traffic-share', 'recent-logs'],+ },+];++/** Half-width for the charts, quarter-width for the two single numbers. */+const PANEL_WIDTH: Partial<Record<PanelId, number>> = {+ 'p99-latency': 3,+ apdex: 3,+ 'request-rate': 12,+};++const gridItems = (+ panels: PanelId[],+): NonNullable<DashboardtypesLayoutDTO['spec']['items']> => {+ let x = 0;+ let y = 0;++ return panels.map((id) => {+ const width = PANEL_WIDTH[id] ?? 6;++ if (x + width > 12) {+ x = 0;+ y += 6;+ }++ const item = {+ x,+ y,+ width,+ height: 6,+ content: { $ref: `#/spec/panels/${id}` },+ };++ x += width;++ return item;+ });+};++export const VARIABLE_KINDS = ['custom', 'query', 'dynamic', 'text'] as const;++export type VariableKind = (typeof VARIABLE_KINDS)[number];++export const QUERY_VARIABLE_NAME = 'service';++export const DYNAMIC_VARIABLE_ATTRIBUTE = 'k8s.namespace.name';++const VARIABLES: Record<VariableKind, DashboardtypesVariableDTO> = {+ custom: {+ kind: ListVariableKind.ListVariable,+ spec: {+ name: 'environment',+ display: { name: 'environment' },+ allowMultiple: false,+ allowAllValue: false,+ defaultValue: 'production',+ plugin: {+ kind: CustomVariableKind['signoz/CustomVariable'],+ spec: { customValue: 'production,staging,development' },+ },+ },+ },+ query: {+ kind: ListVariableKind.ListVariable,+ spec: {+ name: QUERY_VARIABLE_NAME,+ display: { name: QUERY_VARIABLE_NAME },+ allowMultiple: true,+ allowAllValue: true,+ plugin: {+ kind: QueryVariableKind['signoz/QueryVariable'],+ spec: {+ queryValue:+ "SELECT DISTINCT service_name FROM signoz_metrics WHERE env = '$environment'",+ },+ },+ },+ },+ dynamic: {+ kind: ListVariableKind.ListVariable,+ spec: {+ name: 'namespace',+ display: { name: 'namespace' },+ allowMultiple: true,+ allowAllValue: true,+ plugin: {+ kind: DynamicVariableKind['signoz/DynamicVariable'],+ spec: {+ name: DYNAMIC_VARIABLE_ATTRIBUTE,+ signal: DynamicSignal.metrics,+ },+ },+ },+ },+ text: {+ kind: TextVariableKind.TextVariable,+ spec: {+ name: 'owner',+ display: { name: 'owner' },+ value: 'platform-team',+ constant: false,+ },+ },+};++export interface PanelQueryShape {+ requestType: string;+ metricName?: string;+ groupBy?: string;+}++/**+ * What a panel asks `query_range` for, read back off the panel itself. The+ * public viewer addresses a panel by key rather than by request body, so it+ * needs the same answer without a request to inspect.+ */+export const panelQueryShape = (id: PanelId): PanelQueryShape => {+ const query = PANELS[id].spec.queries[0];+ const spec = query.spec.plugin.spec as {+ aggregations?: { metricName?: string }[];+ groupBy?: { name?: string }[];+ };++ return {+ requestType: query.kind,+ metricName: spec.aggregations?.[0]?.metricName,+ groupBy: spec.groupBy?.[0]?.name,+ };+};++export interface DashboardArgs {+ /** Panels kept, taken off the front of `PANEL_IDS`. Zero is a blank dashboard. */+ panels: number;+ /** Titled sections, or the untitled single grid a dashboard without them renders. */+ sectioned: boolean;+ variables: readonly VariableKind[];+ locked: boolean;+}++export const dashboardResponse = ({+ panels,+ sectioned,+ variables,+ locked,+}: DashboardArgs): GetDashboardV2200 => {+ const kept = PANEL_IDS.slice(0, panels);++ const layouts: DashboardtypesLayoutDTO[] = sectioned+ ? SECTIONS.map((section) => ({+ kind: GridKind.Grid,+ spec: {+ display: { title: section.title, collapse: { open: true } },+ items: gridItems(section.panels.filter((id) => kept.includes(id))),+ },+ }))+ : [{ kind: GridKind.Grid, spec: { items: gridItems([...kept]) } }];++ return {+ status: 'success',+ data: {+ id: STORY_DASHBOARD_ID,+ orgId: 'storybook-org',+ name: 'Checkout service overview',+ image: '/assets/Icons/circus-tent',+ schemaVersion: 'v6',+ source: DashboardtypesSourceDTO.user,+ locked,+ createdBy: '[email protected]',+ updatedBy: '[email protected]',+ createdAt: '2026-05-04T09:12:00Z',+ updatedAt: '2026-08-21T16:40:00Z',+ tags: [+ { key: 'env', value: 'prod' },+ { key: 'team', value: 'platform' },+ ],+ spec: {+ display: {+ name: 'Checkout service overview',+ description:+ 'Traffic, errors and latency for the checkout path, broken down by service.',+ },+ layouts,+ panels: Object.fromEntries(+ kept.map((id) => [id, PANELS[id]]),+ ) as DashboardtypesDashboardSpecDTOPanels,+ variables: variables.map((kind) => VARIABLES[kind]),+ },+ },+ };+};++/**+ * The document the page is editing. Every spec edit (a panel moved, a section+ * renamed, a variable added) travels as a JSON Patch whose response replaces+ * the cache, so the story keeps the document where the handler can apply the ops+ * to it. Reseeded whenever a control changes, which is also when the story+ * remounts.+ */+let document: DashboardtypesGettableDashboardV2DTO | undefined;++export const seedDashboardDocument = (args: DashboardArgs): void => {+ document = dashboardResponse(args).data;+};++const envelope = (+ data: DashboardtypesGettableDashboardV2DTO,+): GetDashboardV2200 => ({ status: 'success', data });++export const currentDashboardDocument = (+ args: DashboardArgs,+): GetDashboardV2200 => envelope(document ?? dashboardResponse(args).data);++export const patchDashboardDocument = (+ args: DashboardArgs,+ ops: DashboardtypesJSONPatchOperationDTO[],+): GetDashboardV2200 => {+ document = applyJsonPatch(document ?? dashboardResponse(args).data, ops);++ return envelope(document);+};diff --git a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/panelData.ts b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/panelData.tsnew file mode 100644index 0000000000..ae7218ef6f--- /dev/null+++ b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/panelData.ts@@ -0,0 +1,175 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { MetricRangePayloadV5, RawRow } from 'types/api/v5/queryRange';++import {+ queryRangeV5EmptyResponse,+ queryRangeV5RawResponse,+ queryRangeV5ScalarResponse,+ queryRangeV5ScalarTableResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++const SERVICES = [+ 'checkout',+ 'payments',+ 'inventory',+ 'notifications',+] as const;++const ROUTES = [+ 'POST /v1/checkout',+ 'GET /v1/cart',+ 'POST /v1/payment/authorize',+ 'GET /v1/inventory/:sku',+ 'POST /v1/notifications/send',+] as const;++const STATUS_CODES = ['500', '502', '503'] as const;++const LOG_LEVELS = ['INFO', 'WARN', 'ERROR'] as const;++const pick = <T>(values: readonly T[], index: number): T =>+ values[index % values.length];++export interface PanelWindow {+ start: number;+ end: number;+}++/** One line per service, each with its own phase so the chart reads as a stack. */+const seriesByLabel = (+ { start, end }: PanelWindow,+ label: string,+ values: readonly string[],+ base: number,+ amplitude: number,+): MetricRangePayloadV5 =>+ queryRangeV5TimeSeriesResponse([+ {+ queryName: 'A',+ series: values.map((value, index) => ({+ labels: [{ key: { name: label }, value }],+ values: timeSeriesPoints({+ start,+ end,+ base: base - index * (base / (values.length + 2)),+ amplitude,+ seed: index * 3,+ }),+ })),+ },+ ]);++const singleSeries = ({ start, end }: PanelWindow): MetricRangePayloadV5 =>+ queryRangeV5TimeSeriesResponse([+ {+ queryName: 'A',+ series: [+ {+ labels: [],+ values: timeSeriesPoints({ start, end, base: 2.4, amplitude: 0.9 }),+ },+ ],+ },+ ]);++const logRows = ({ start, end }: PanelWindow, count: number): RawRow[] =>+ Array.from({ length: count }, (_unused, index) => {+ const severity = pick(LOG_LEVELS, index);+ const service = pick(SERVICES, index);++ return {+ timestamp: new Date(+ end - ((end - start) / Math.max(count, 1)) * index,+ ).toISOString(),+ data: {+ id: `storybook-log-${index + 1}`,+ body: `${severity} ${service} completed ${pick(ROUTES, index)} in ${+ 8 + index * 3+ }ms`,+ severity_text: severity,+ resources_string: { 'service.name': service },+ },+ };+ });++/**+ * Which answer a panel's request gets. Every panel names its query `A`, so the+ * request itself is what tells them apart: the request type, the group-by it+ * asks for, and the metric it aggregates.+ */+export interface PanelRequest {+ requestType: string;+ groupBy?: string;+ metricName?: string;+ window: PanelWindow;+}++const LOG_ROW_COUNT = 25;++export const panelResponse = ({+ requestType,+ groupBy,+ metricName,+ window,+}: PanelRequest): MetricRangePayloadV5 => {+ if (requestType === 'raw' || requestType === 'trace') {+ return queryRangeV5RawResponse(logRows(window, LOG_ROW_COUNT));+ }++ if (requestType === 'scalar') {+ if (groupBy === 'http.route') {+ return queryRangeV5ScalarTableResponse({+ groupBy: ['http.route'],+ aggregations: ['A'],+ rows: ROUTES.map((route, index) => [route, 4200 - index * 630]),+ });+ }++ if (groupBy) {+ return queryRangeV5ScalarTableResponse({+ groupBy: [groupBy],+ aggregations: ['A'],+ rows: SERVICES.map((service, index) => [service, 3800 - index * 720]),+ });+ }++ return queryRangeV5ScalarResponse(+ metricName === 'signoz_apdex' ? 0.94 : 812.6,+ );+ }++ if (groupBy === 'http.status_code') {+ return seriesByLabel(window, groupBy, STATUS_CODES, 18, 6);+ }++ if (groupBy) {+ return seriesByLabel(window, groupBy, SERVICES, 240, 55);+ }++ return singleSeries(window);+};++/** What a panel shows when the query runs but matches nothing. */+export const emptyPanelResponse = (): MetricRangePayloadV5 =>+ queryRangeV5EmptyResponse();++/** Values the `service` query variable offers. */+export const serviceVariableValues = (count: number): string[] =>+ Array.from({ length: count }, (_unused, index) =>+ index < SERVICES.length+ ? SERVICES[index]+ : `${pick(SERVICES, index)}-${Math.floor(index / SERVICES.length) + 1}`,+ );++/** Values the dynamic `namespace` variable resolves from the fields endpoint. */+export const NAMESPACE_VALUES = [+ 'checkout-prod',+ 'payments-prod',+ 'platform-prod',+] as const;diff --git a/frontend/src/pages/DashboardPage/stories/__story_mockdata__/tooltipDashboard.ts b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/tooltipDashboard.tsnew file mode 100644index 0000000000..34e61423be--- /dev/null+++ b/frontend/src/pages/DashboardPage/stories/__story_mockdata__/tooltipDashboard.ts@@ -0,0 +1,165 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ DashboardtypesPanelPluginVariantGithubComSigNozSignozPkgTypesDashboardtypesTimeSeriesPanelSpecDTOKind as TimeSeriesKind,+ DashboardtypesTimePreferenceDTO as TimePreference,+ type DashboardtypesDashboardSpecDTOPanels,+ type DashboardtypesGettableDashboardV2DTO,+ type GetDashboardV2200,+} from 'api/generated/services/sigNoz.schemas';++import { dashboardResponse, PANEL_IDS, VARIABLE_KINDS } from './dashboard';++export const TOOLTIP_DASHBOARD_NAME =+ 'Checkout service overview across every production region, by service and owner';++export const TOOLTIP_DASHBOARD_DESCRIPTION =+ 'Traffic, errors and latency for the checkout path, broken down by service, region and deployment channel. Owned by the platform observability team; the runbook is at https://signoz.io/docs/dashboards/ and the rotation is in PagerDuty.';++// Two fit beside the title; the rest fall behind the `+N` badge.+export const TOOLTIP_DASHBOARD_TAGS = [+ { key: 'env', value: 'production-eu-central-1' },+ { key: 'team', value: 'platform-observability' },+ { key: 'component', value: 'otel-collector' },+ { key: 'owner', value: 'sre-oncall-primary' },+ { key: 'tier', value: 'tier-0-revenue-critical' },+ { key: 'compliance', value: 'soc2-in-scope' },+];++export const TOOLTIP_PANEL_NAME =+ 'Request rate by service, region and deployment channel, excluding synthetic traffic';++export const TOOLTIP_PANEL_DESCRIPTIONS: Record<string, string> = {+ 'request-rate':+ 'Requests per second per service, taken from `signoz_calls_total` and filtered to the selected environment. Synthetic and health-check traffic is excluded, so this reads lower than the load balancer count.',+ 'error-rate':+ 'Share of 5xx responses over the selected window, rated against the error budget for the quarter.',+};++export const TOOLTIP_SELECTED_SERVICES = [+ 'checkout',+ 'payments',+ 'inventory',+ 'notifications',+ 'checkout-2',+ 'payments-2',+ 'inventory-2',+ 'notifications-2',+];++export const TOOLTIP_WARNED_METRIC = 'signoz_apdex';++/**+ * The page's own document, rewritten to the lengths the fixture is too tame to+ * show: a title and a description that overflow, six tags, panel descriptions+ * that run past a line, and a panel on its own time preference.+ */+export const tooltipDashboardDocument =+ (): DashboardtypesGettableDashboardV2DTO => {+ const document = dashboardResponse({+ panels: PANEL_IDS.length,+ sectioned: true,+ variables: [...VARIABLE_KINDS],+ locked: false,+ }).data;++ const panels = Object.fromEntries(+ Object.entries(document.spec.panels ?? {}).map(([id, panel]) => [+ id,+ {+ ...panel,+ spec: {+ ...panel.spec,+ display: {+ ...panel.spec.display,+ name:+ id === 'request-rate' ? TOOLTIP_PANEL_NAME : panel.spec.display.name,+ description:+ TOOLTIP_PANEL_DESCRIPTIONS[id] ?? panel.spec.display.description,+ },+ plugin:+ id === 'error-rate' &&+ panel.spec.plugin.kind === TimeSeriesKind['signoz/TimeSeriesPanel']+ ? {+ ...panel.spec.plugin,+ spec: {+ ...panel.spec.plugin.spec,+ visualization: { timePreference: TimePreference.last_1_month },+ },+ }+ : panel.spec.plugin,+ },+ },+ ]),+ ) as DashboardtypesDashboardSpecDTOPanels;++ return {+ ...document,+ name: TOOLTIP_DASHBOARD_NAME,+ tags: TOOLTIP_DASHBOARD_TAGS,+ spec: {+ ...document.spec,+ display: {+ name: TOOLTIP_DASHBOARD_NAME,+ description: TOOLTIP_DASHBOARD_DESCRIPTION,+ },+ panels,+ },+ };+ };++export const tooltipDashboardResponse = (): GetDashboardV2200 => ({+ status: 'success',+ data: tooltipDashboardDocument(),+});++/**+ * The tooltip document with its layouts scrambled, the shape the JSON editor's+ * dangling-reference warning is built to catch.+ */+export const desyncedDashboardResponse = (): GetDashboardV2200 => {+ const document = tooltipDashboardDocument();+ const [firstGrid, ...rest] = document.spec.layouts ?? [];++ return {+ status: 'success',+ data: {+ ...document,+ spec: {+ ...document.spec,+ // The second grid goes, orphaning the panels it placed, and the+ // first gains slots for panels that are not in the spec: the two+ // ways a hand-edited document desyncs panels and layouts.+ layouts: [+ {+ ...firstGrid,+ spec: {+ ...firstGrid.spec,+ items: [+ ...(firstGrid.spec?.items ?? []),+ {+ x: 0,+ y: 24,+ width: 6,+ height: 6,+ content: { $ref: '#/spec/panels/checkout-saturation' },+ },+ {+ x: 6,+ y: 24,+ width: 6,+ height: 6,+ content: { $ref: '#/spec/panels/payment-gateway-latency' },+ },+ ],+ },+ },+ ...rest.slice(1),+ ],+ },+ },+ };+};diff --git a/frontend/src/pages/DashboardsListPage/stories/DashboardsListPage.stories.mocks.tsx b/frontend/src/pages/DashboardsListPage/stories/DashboardsListPage.stories.mocks.tsxnew file mode 100644index 0000000000..c551e786ca--- /dev/null+++ b/frontend/src/pages/DashboardsListPage/stories/DashboardsListPage.stories.mocks.tsx@@ -0,0 +1,344 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import type { GetDashboardV2200 } from 'api/generated/services/sigNoz.schemas';+import ROUTES from 'constants/routes';++import {+ choiceControl,+ countControl,+ multiChoiceControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import { dashboardResponse } from '../../DashboardPage/stories/__story_mockdata__/dashboard';+import {+ dashboardIdAt,+ dashboardViewsResponse,+ dashboardsListResponse,+ orgUsersResponse,+ recentDashboardIds,+ ROW_MARKERS,+ savedView,+ seedPinnedDashboards,+ setDashboardPinned,+ STORY_USER_EMAIL,+ TOOLTIP_TAGS,+ type RowMarker,+} from './__story_mockdata__/dashboardsList';+import { useDashboardViewsStore } from '../store/useDashboardViewsStore';+import {+ type DashboardDynamicColumns,+ useDashboardsListVisibleColumnsStore,+} from '../store/useVisibleColumnsStore';+import { BuiltinViewId } from '../types';+import { builtinViewQuery } from '../utils/views';++const LIST = 'Dashboards · list';+const VIEWS = 'Dashboards · views';++const VIEWS_OPTIONS = [+ BuiltinViewId.All,+ BuiltinViewId.Mine,+ BuiltinViewId.Pinned,+ BuiltinViewId.Recent,+ BuiltinViewId.Locked,+ 'saved',+] as const;++type ViewOption = (typeof VIEWS_OPTIONS)[number];++const DETAIL_COLUMNS = ['updatedAt', 'updatedBy'] as const;++type DetailColumn = (typeof DETAIL_COLUMNS)[number];++const RECENT_COUNT = 4;++const PINNED_COUNT = 3;++/** A dashboard document, for the writes that echo the touched dashboard back. */+const writtenDashboard = (): GetDashboardV2200 =>+ dashboardResponse({+ panels: 0,+ sectioned: false,+ variables: [],+ locked: false,+ });++const ok = { status: 'success', data: null };++/**+ * `formatQueryErrorMessage` strips the `invalid filter query:` prefix and turns+ * the backticks into quotes, so the message carries both to show it doing it.+ */+const INVALID_QUERY_MESSAGE =+ 'invalid filter query: unexpected token `enviroment` at position 0, expected one of `name`, `description`, `created_by`, `created_at`, `updated_at`, `locked`';++/**+ * The rail applies a view by writing both `view` and `query`, so a story that+ * opens on one has to seed both or the header shows unsaved changes on mount.+ */+const listRoute = (view: ViewOption): string => {+ const { id, query } =+ view === 'saved'+ ? savedView(0)+ : { id: view, query: builtinViewQuery(view, STORY_USER_EMAIL) ?? '' };++ const params = new URLSearchParams({ view: id });++ if (query) {+ params.set('query', query);+ }++ return `${ROUTES.ALL_DASHBOARD}?${params.toString()}`;+};++const visibleColumns = (+ columns: readonly DetailColumn[],+): DashboardDynamicColumns => ({+ createdAt: true,+ createdBy: true,+ updatedAt: columns.includes('updatedAt'),+ updatedBy: columns.includes('updatedBy'),+});++/**+ * A row shows the full-name tooltip only past 50 characters of title and the+ * overflow chip only past three tags, and the page's own rows are under both.+ * This answers the list with rows over both instead, which is why the Dashboards+ * and Row markers controls do not reach this story.+ */+export const overflowingRows = rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ (_req, res, ctx) => {+ const list = dashboardsListResponse({+ count: 6,+ offset: 0,+ limit: 20,+ markers: [...ROW_MARKERS],+ query: '',+ });++ return res(+ ctx.status(200),+ ctx.json({+ ...list,+ data: {+ ...list.data,+ dashboards: list.data.dashboards.map((dashboard) => {+ const name = `${dashboard.name} across every production region, rolled up by service and owner`;++ // The row reads `spec.display.name`, not `name`.+ return {+ ...dashboard,+ name,+ spec: { ...dashboard.spec, display: { name } },+ tags: TOOLTIP_TAGS,+ };+ }),+ },+ }),+ );+ },+);++export const dashboardsListMocks = defineStoryMocks({+ controls: {+ dashboards: countControl('Dashboards', {+ group: LIST,+ description:+ 'Dashboards the org has. The list pages at 20, so a higher count adds a pager.',+ value: 24,+ max: 45,+ }),+ markers: multiChoiceControl<RowMarker>('Row markers', {+ group: LIST,+ description:+ 'Pinned rows float to the top, locked rows carry the padlock, and a legacy row opens the "not available in the new experience" dialog instead of the dashboard.',+ options: ROW_MARKERS,+ value: [...ROW_MARKERS],+ }),+ columns: multiChoiceControl<DetailColumn>('Detail columns', {+ group: LIST,+ description: 'The optional fields on each row’s second line.',+ options: DETAIL_COLUMNS,+ value: [...DETAIL_COLUMNS],+ }),+ invalidQuery: toggleControl('Reject the query', {+ group: LIST,+ description:+ 'Answers the list with a 400 and a parse error, which is the Invalid query state: the backend message replaces the generic one and Retry is gone.',+ value: false,+ }),+ view: choiceControl<ViewOption>('Active view', {+ group: VIEWS,+ description:+ 'The rail entry the page opens on. Pinned and Recently viewed constrain the fetched rows client-side; the rest apply a query.',+ options: VIEWS_OPTIONS,+ value: BuiltinViewId.All,+ }),+ savedViews: countControl('Saved views', {+ group: VIEWS,+ description: 'Org-shared views listed under the built-in ones.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => [+ ...(values.invalidQuery+ ? [+ rest.get('http://localhost/api/v2/users/me/dashboards', (_req, res, ctx) =>+ res(+ ctx.status(400),+ ctx.json({+ status: 'error',+ error: {+ code: 'invalid_input',+ message: INVALID_QUERY_MESSAGE,+ url: '',+ errors: [],+ },+ }),+ ),+ ),+ ]+ : []),++ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json((req) =>+ dashboardsListResponse({+ count: values.dashboards,+ offset: Number(req.url.searchParams.get('offset') ?? 0),+ limit: Number(req.url.searchParams.get('limit') ?? 20),+ markers: values.markers,+ query: req.url.searchParams.get('query') ?? '',+ }),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/dashboard_views',+ response.json(() => dashboardViewsResponse(values.savedViews)),+ ),++ rest.get(+ 'http://localhost/api/v2/users',+ response.json(() => orgUsersResponse()),+ ),++ // The writes the rows and the rail offer. Pinning is the one the page can+ // see the result of, so it is kept where the handler can write it; the rest+ // answer with success and the list re-reads the controls.+ rest.put(+ 'http://localhost/api/v2/users/me/dashboards/:id/pins',+ (req, res, ctx) => {+ setDashboardPinned(String(req.params.id), true);++ return res(ctx.status(200), ctx.json(ok));+ },+ ),++ rest.delete(+ 'http://localhost/api/v2/users/me/dashboards/:id/pins',+ (req, res, ctx) => {+ setDashboardPinned(String(req.params.id), false);++ return res(ctx.status(200), ctx.json(ok));+ },+ ),++ rest.post('http://localhost/api/v2/dashboards', (_req, res, ctx) =>+ res(ctx.status(201), ctx.json(writtenDashboard())),+ ),++ rest.put('http://localhost/api/v2/dashboards/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(writtenDashboard())),+ ),++ rest.post('http://localhost/api/v2/dashboards/:id/clone', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(writtenDashboard())),+ ),++ rest.post(+ 'http://localhost/api/v2/dashboards/:id/migrate',+ (_req, res, ctx) => res(ctx.status(200), ctx.json(writtenDashboard())),+ ),++ rest.delete('http://localhost/api/v2/dashboards/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(ok)),+ ),++ rest.put('http://localhost/api/v2/dashboards/:id/lock', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(ok)),+ ),++ rest.delete('http://localhost/api/v2/dashboards/:id/lock', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(ok)),+ ),++ rest.post(+ 'http://localhost/api/v2/dashboard_views',+ async (req, res, ctx) => {+ const body = (await req.json()) as { name: string };++ return res(+ ctx.status(201),+ ctx.json({+ status: 'success',+ data: {+ id: 'storybook-view-created',+ orgId: 'storybook-org',+ name: body.name,+ data: { version: 'v1' },+ },+ }),+ );+ },+ ),++ rest.put(+ 'http://localhost/api/v2/dashboard_views/:id',+ async (req, res, ctx) => {+ const body = (await req.json()) as { name: string; data: unknown };++ return res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: {+ id: String(req.params.id),+ orgId: 'storybook-org',+ name: body.name,+ data: body.data,+ },+ }),+ );+ },+ ),++ rest.delete('http://localhost/api/v2/dashboard_views/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(ok)),+ ),+ ],+ config: (values) => ({ route: listRoute(values.view) }),+ effect: (values) => {+ seedPinnedDashboards(+ values.markers.includes('pinned')+ ? Array.from({ length: PINNED_COUNT }, (_unused, index) =>+ dashboardIdAt(index),+ )+ : [],+ );+ useDashboardViewsStore.setState({+ recent: recentDashboardIds(RECENT_COUNT),+ });+ useDashboardsListVisibleColumnsStore.setState({+ visibleColumns: visibleColumns(values.columns),+ });+ },+});diff --git a/frontend/src/pages/DashboardsListPage/stories/DashboardsListPage.stories.tsx b/frontend/src/pages/DashboardsListPage/stories/DashboardsListPage.stories.tsxnew file mode 100644index 0000000000..bd142ba390--- /dev/null+++ b/frontend/src/pages/DashboardsListPage/stories/DashboardsListPage.stories.tsx@@ -0,0 +1,129 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { expect, userEvent, screen, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import {+ dashboardsListMocks,+ overflowingRows,+} from './DashboardsListPage.stories.mocks';+import { BuiltinViewId } from '../types';++import DashboardsListPage from '../DashboardsListPage';++type DashboardsListArgs = PageStoryArgs<typeof dashboardsListMocks>;++const pageStory = storyMocks(dashboardsListMocks, { layout: 'app' });++/**+ * Every dashboard in the workspace, with pins, the saved views over the list, and+ * the create, clone and lock actions. Creating follows the legacy editor role.+ *+ * Route: `/dashboard`.+ */+const meta = {+ title: 'Pages/Dashboards/List',+ tags: ['role-gated', 'play'],+ component: DashboardsListPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<DashboardsListArgs>;++export default meta;++type Story = StoryObj<DashboardsListArgs>;++/**+ * All dashboards: the views rail on the left, the query box and the Created-by+ * and Updated dropdowns above the rows, pinned dashboards first, and a pager+ * because the org has more than one page of them.+ */+export const Default: Story = {};++/**+ * An org-shared saved view applied on load, so the rail entry is selected and+ * its query is in the box.+ */+export const SavedView: Story = {+ args: { view: 'saved' },+};++/** What a new workspace shows: the create-your-first-dashboard call to action. */+export const EmptyWorkspace: Story = {+ args: { dashboards: 0, savedViews: 0 },+};++/**+ * A viewer: the rows and the rail are still browsable, but everything that+ * writes (New dashboard, saving a view, the row's edit actions) is gone.+ */+export const Viewer: Story = {+ args: { access: 'viewer' },+};++/** The rows the user pinned, which the page filters out of the fetched page. */+export const Pinned: Story = {+ args: { view: BuiltinViewId.Pinned },+};++/** The template tab of the New dashboard dialog. */+export const NewDashboardTemplateTab: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId('new-dashboard-cta', {}, { timeout: 10000 }),+ );++ await expect(+ await screen.findByRole('dialog', {}, { timeout: 10000 }),+ ).toHaveTextContent('New dashboard');+ await userEvent.click(await screen.findByText('From a template'));+ await screen.findByText('Dashboard templates');+ },+};++/**+ * Invalid JSON keeps the import dialog open behind the error the app raises for+ * it: the parse failure is handed to the API error modal, so it reads+ * `UPSTREAM_UNAVAILABLE` over the panel's own inline feedback. See BUGS.md 53.+ */+export const NewDashboardImportJsonInvalid: Story = {+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId('new-dashboard-cta', {}, { timeout: 10000 }),+ );+ await userEvent.click(await screen.findByText('Import JSON'));+ await userEvent.click(await screen.findByTestId('import-json-submit'));+ await screen.findByText(/error loading json/i);+ // The error modal and the toast under it carry the same message.+ await screen.findAllByText('Unexpected end of JSON input');+ },+};++/**+ * Every tooltip a row carries, held open at once: the full name a truncated+ * title falls back to, the padlock, the pin, the legacy row's refusal to be+ * pinned, and the overflow chip listing the tags that did not fit.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+ parameters: { msw: { handlers: [overflowingRows] } },+};++/**+ * The query the backend refused: the parse error it returned replaces the+ * generic failure copy, and there is nothing to retry.+ *+ * Kept last: test-runner shares one page across a file's stories, and the 400+ * this story is about can settle after the next story has already started,+ * which fails that one instead.+ */+export const InvalidQuery: Story = {+ args: { invalidQuery: true },+ // The deliberate 400 is the state under test.+ parameters: { allowConsoleErrors: true },+};diff --git a/frontend/src/pages/DashboardsListPage/stories/__story_mockdata__/dashboardsList.ts b/frontend/src/pages/DashboardsListPage/stories/__story_mockdata__/dashboardsList.tsnew file mode 100644index 0000000000..732183e6e8--- /dev/null+++ b/frontend/src/pages/DashboardsListPage/stories/__story_mockdata__/dashboardsList.ts@@ -0,0 +1,348 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ DashboardtypesListOrderDTO,+ DashboardtypesListSortDTO,+ DashboardtypesSourceDTO,+ type DashboardtypesListedDashboardForUserV2DTO,+ type ListDashboardViews200,+ type ListDashboardsForUserV2200,+ type ListUsers200,+ type TagtypesGettableTagDTO,+} from 'api/generated/services/sigNoz.schemas';+import { createAppContextMock } from 'tests/fixtures/appContextMock';+import { USER_ROLES } from 'types/roles';++/**+ * "My dashboards" matches on the signed-in address, so the rows have to be+ * created by the same user the providers mount.+ */+export const STORY_USER_EMAIL = createAppContextMock(USER_ROLES.ADMIN).user+ .email;++const TEAMMATE_EMAILS = [+ '[email protected]',+ '[email protected]',+ '[email protected]',+] as const;++const HOUR = 60 * 60 * 1000;++const ago = (hours: number): string =>+ new Date(Date.now() - hours * HOUR).toISOString();++const tag = (key: string, value: string): TagtypesGettableTagDTO => ({+ key,+ value,+});++interface DashboardSeed {+ name: string;+ icon: string;+ tags: TagtypesGettableTagDTO[];+ locked?: boolean;+}++const SEEDS: DashboardSeed[] = [+ {+ name: 'Kubernetes cluster health',+ icon: 'circus-tent',+ tags: [tag('env', 'prod'), tag('team', 'platform')],+ locked: true,+ },+ {+ name: 'API latency and errors',+ icon: 'siren',+ tags: [tag('env', 'prod'), tag('team', 'api')],+ },+ {+ name: 'Checkout funnel',+ icon: 'bagel',+ tags: [tag('team', 'growth')],+ },+ {+ name: 'Postgres connections',+ icon: 'cheese',+ tags: [tag('env', 'prod'), tag('component', 'database')],+ },+ {+ name: 'Kafka consumer lag',+ icon: 'drum',+ tags: [tag('team', 'platform'), tag('component', 'kafka')],+ },+ {+ name: 'Nginx ingress overview',+ icon: 'crane',+ tags: [tag('env', 'staging')],+ },+ {+ name: 'Billing jobs',+ icon: 'dartboard',+ tags: [tag('team', 'billing')],+ locked: true,+ },+ {+ name: 'Frontend web vitals',+ icon: 'basketball',+ tags: [tag('team', 'frontend')],+ },+ {+ name: 'Redis cache hit ratio',+ icon: 'cookie',+ tags: [tag('component', 'redis')],+ },+ {+ name: 'Collector pipeline throughput',+ icon: 'motorcycle',+ tags: [tag('env', 'prod'), tag('component', 'otel')],+ },+ {+ name: 'On-call triage board',+ icon: 'police-car',+ tags: [tag('team', 'sre')],+ },+ {+ name: 'Cost per service',+ icon: 'orange',+ tags: [tag('team', 'finops')],+ },+];++/** Row markers a story can put on the list, each landing on a slice of the rows. */+export const ROW_MARKERS = ['pinned', 'locked', 'legacy'] as const;++export type RowMarker = (typeof ROW_MARKERS)[number];++/** Tags on every row of the overflowing-rows fixture, six deep past the chip's cutoff. */+export const TOOLTIP_TAGS: TagtypesGettableTagDTO[] = [+ tag('env', 'production-eu-central-1'),+ tag('team', 'platform-observability'),+ tag('component', 'otel-collector'),+ tag('owner', 'sre-oncall-primary'),+ tag('tier', 'tier-0-revenue-critical'),+ tag('compliance', 'soc2-in-scope'),+];++export const dashboardIdAt = (index: number): string =>+ `storybook-dashboard-${index + 1}`;++/**+ * Pins are per-user state the endpoint owns, and the page writes them: keeping+ * them here is what lets the pin button stick instead of being answered away by+ * the next list fetch.+ */+const pinned = new Set<string>();++export const seedPinnedDashboards = (ids: readonly string[]): void => {+ pinned.clear();+ ids.forEach((id) => pinned.add(id));+};++export const setDashboardPinned = (id: string, isPinned: boolean): void => {+ if (isPinned) {+ pinned.add(id);+ } else {+ pinned.delete(id);+ }+};++interface ListArgs {+ count: number;+ offset: number;+ limit: number;+ markers: readonly RowMarker[];+ query: string;+}++const seedAt = (index: number): DashboardSeed => SEEDS[index % SEEDS.length];++const nameAt = (index: number): string => {+ const seed = seedAt(index);+ const round = Math.floor(index / SEEDS.length);++ return round === 0 ? seed.name : `${seed.name} (${round + 1})`;+};++const dashboardAt = (+ index: number,+ markers: readonly RowMarker[],+): DashboardtypesListedDashboardForUserV2DTO => {+ const seed = seedAt(index);+ const name = nameAt(index);+ const mine = index % 3 === 0;++ return {+ id: dashboardIdAt(index),+ orgId: 'storybook-org',+ name,+ spec: { display: { name } },+ image: `/assets/Icons/${seed.icon}`,+ schemaVersion: 'v2',+ source: DashboardtypesSourceDTO.user,+ pinned: pinned.has(dashboardIdAt(index)),+ locked: markers.includes('locked') && !!seed.locked,+ legacy: markers.includes('legacy') && index % 7 === 4,+ tags: seed.tags,+ createdBy: mine+ ? STORY_USER_EMAIL+ : TEAMMATE_EMAILS[index % TEAMMATE_EMAILS.length],+ updatedBy: TEAMMATE_EMAILS[(index + 1) % TEAMMATE_EMAILS.length],+ createdAt: ago(24 * (index + 3)),+ updatedAt: ago(index * 5 + 1),+ };+};++/** `key OP value`, the only term shape the mock evaluates. */+const TERM = /(\w+)\s*(=|!=|CONTAINS|IN)\s*(\[[^\]]*\]|'[^']*'|true|false)/gi;++const quoted = (raw: string): string[] =>+ Array.from(raw.matchAll(/'([^']*)'/g), (match) => match[1]);++const matchesTerm = (+ dashboard: DashboardtypesListedDashboardForUserV2DTO,+ key: string,+ operator: string,+ value: string,+): boolean => {+ const values = quoted(value);+ const [first = ''] = values;++ switch (key.toLowerCase()) {+ case 'locked':+ return dashboard.locked === (value.toLowerCase() === 'true');+ case 'created_by':+ return values.includes(dashboard.createdBy ?? '');+ case 'updated_by':+ return values.includes(dashboard.updatedBy ?? '');+ case 'name':+ return operator.toUpperCase() === 'CONTAINS'+ ? dashboard.name.toLowerCase().includes(first.toLowerCase())+ : dashboard.name === first;+ case 'created_at':+ case 'updated_at':+ case 'description':+ return true;+ default:+ return dashboard.tags.some((t) => t.key === key && values.includes(t.value));+ }+};++/**+ * The AND-joined subset of the list DSL the built-in views, the saved views and+ * the Created-by dropdown emit. A term the mock cannot read is treated as+ * matching, so an unsupported query answers with the unfiltered page rather than+ * an empty one.+ */+const matchesQuery = (+ dashboard: DashboardtypesListedDashboardForUserV2DTO,+ query: string,+): boolean =>+ Array.from(query.matchAll(TERM)).every(([, key, operator, value]) =>+ matchesTerm(dashboard, key, operator, value),+ );++export const dashboardsListResponse = ({+ count,+ offset,+ limit,+ markers,+ query,+}: ListArgs): ListDashboardsForUserV2200 => {+ const all = Array.from({ length: count }, (_, index) =>+ dashboardAt(index, markers),+ );+ const matched = query ? all.filter((d) => matchesQuery(d, query)) : all;++ // Pins float to the top of the requested ordering, server-side.+ matched.sort((a, b) => Number(b.pinned) - Number(a.pinned));++ const tags = matched.flatMap((dashboard) => dashboard.tags);+ const uniqueTags = Array.from(+ new Map(tags.map((t) => [`${t.key}:${t.value}`, t])).values(),+ );++ return {+ status: 'success',+ data: {+ total: matched.length,+ reservedKeywords: [+ 'name',+ 'description',+ 'created_by',+ 'created_at',+ 'updated_at',+ 'locked',+ ],+ tags: uniqueTags,+ dashboards: matched.slice(offset, offset + limit),+ },+ };+};++const SAVED_VIEW_SEEDS = [+ { name: 'Production dashboards', query: "env = 'prod'" },+ { name: 'Platform team', query: "team = 'platform'" },+ { name: 'Locked dashboards', query: 'locked = true' },+ { name: 'Database dashboards', query: "component = 'database'" },+] as const;++/**+ * A saved view as the rail addresses it. Selecting one applies its query, so a+ * story that opens on a saved view has to seed the route with both.+ */+export const savedView = (index: number): { id: string; query: string } => ({+ id: `storybook-view-${index + 1}`,+ query: SAVED_VIEW_SEEDS[index % SAVED_VIEW_SEEDS.length].query,+});++export const dashboardViewsResponse = (+ count: number,+): ListDashboardViews200 => ({+ status: 'success',+ data: {+ views: Array.from({ length: count }, (_, index) => {+ const seed = SAVED_VIEW_SEEDS[index % SAVED_VIEW_SEEDS.length];++ return {+ id: savedView(index).id,+ orgId: 'storybook-org',+ name: index < SAVED_VIEW_SEEDS.length ? seed.name : `${seed.name} ${index}`,+ data: {+ version: 'v1',+ query: seed.query,+ sort: DashboardtypesListSortDTO.updated_at,+ order: DashboardtypesListOrderDTO.desc,+ },+ createdAt: ago(24 * (index + 1)),+ updatedAt: ago(index + 1),+ };+ }),+ },+});++/** The org's users, which is where the Created-by dropdown gets its options. */+export const orgUsersResponse = (): ListUsers200 => ({+ status: 'success',+ data: [+ {+ id: 'storybook-user-me',+ email: STORY_USER_EMAIL,+ displayName: 'John Doe',+ },+ ...TEAMMATE_EMAILS.map((email, index) => ({+ id: `storybook-user-${index + 1}`,+ email,+ displayName: email.split('@')[0].replace(/^./, (c) => c.toUpperCase()),+ })),+ ],+});++/** Ids the Recently-viewed rail entry reads out of local state. */+export const recentDashboardIds = (count: number): string[] =>+ Array.from(+ { length: count },+ (_, index) => `storybook-dashboard-${index + 4}`,+ );diff --git a/frontend/src/pages/EditRules/stories/EditRules.stories.mocks.tsx b/frontend/src/pages/EditRules/stories/EditRules.stories.mocks.tsxnew file mode 100644index 0000000000..5491876e1a--- /dev/null+++ b/frontend/src/pages/EditRules/stories/EditRules.stories.mocks.tsx@@ -0,0 +1,122 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ alertFieldKeysResponse,+ alertFieldValuesResponse,+ alertMetricMetadataResponse,+ alertMetricsResponse,+ alertPreviewSeries,+} from '../../AlertList/stories/__story_mockdata__/alertQuery';+import {+ alertRuleByIdResponse,+ ALERT_SCHEMAS,+ channelsResponse,+ CHANNEL_MAX,+ type AlertSchema,+} from '../../AlertList/stories/__story_mockdata__/alerts';++const STORY_RULE_ID = 'rule-1';++const RULE = 'Edit rule · rule';++export const editRulesMocks = defineStoryMocks({+ controls: {+ alertSchema: choiceControl<AlertSchema>('Alert schema', {+ group: RULE,+ description:+ '`classic` is the single-form page this route was built for. `v2` throws: the new form reads `CreateAlertProvider`, which only `pages/AlertDetails` mounts, so this route crashes on any rule saved on the current schema.',+ options: ALERT_SCHEMAS,+ value: 'classic',+ }),+ channels: countControl('Notification channels', {+ group: RULE,+ value: 5,+ max: CHANNEL_MAX,+ }),+ previewSeries: countControl('Preview series', {+ group: RULE,+ description: 'Lines the chart above the condition draws.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/rules/:id',+ response.json((req) =>+ alertRuleByIdResponse(String(req.params.id), {+ severity: 'critical',+ state: 'firing',+ schema: values.alertSchema,+ }),+ ),+ ),++ rest.put('http://localhost/api/v2/rules/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.post('http://localhost/api/v2/rules/test', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: { alertCount: 2, message: 'Rule tested against the last 6 hours' },+ }),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/channels',+ response.json(() => channelsResponse(values.channels)),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => alertPreviewSeries(values.previewSeries, req)),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics',+ response.json((req) =>+ alertMetricsResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/metadata',+ response.json((req) =>+ alertMetricMetadataResponse(req.url.searchParams.get('metricName') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ alertFieldKeysResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ alertFieldValuesResponse(+ req.url.searchParams.get('name') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),+ ],+ config: () => ({+ route: `${ROUTES.EDIT_ALERTS}?ruleId=${STORY_RULE_ID}&relativeTime=6h`,+ }),+});diff --git a/frontend/src/pages/EditRules/stories/EditRules.stories.tsx b/frontend/src/pages/EditRules/stories/EditRules.stories.tsxnew file mode 100644index 0000000000..449756bdf4--- /dev/null+++ b/frontend/src/pages/EditRules/stories/EditRules.stories.tsx@@ -0,0 +1,55 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { editRulesMocks } from './EditRules.stories.mocks';++import EditRules from '../index';++type EditRulesArgs = PageStoryArgs<typeof editRulesMocks>;++const pageStory = storyMocks(editRulesMocks, { layout: 'app' });++/**+ * An existing rule in the builder that created it, loaded from+ * `/api/v2/rules/:id`.+ *+ * Route: `/alerts/edit?ruleId=...`.+ */+const meta = {+ title: 'Pages/Alerts/Edit',+ component: EditRules,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<EditRulesArgs>;++export default meta;++type Story = StoryObj<EditRulesArgs>;++/**+ * The alert form on its own route, without the alert-details tabs around it.+ * Metrics Explorer and the assistant link here when they send someone to a rule.+ * The rule is on the classic schema, which is the only one this route renders:+ * see the Alert schema control for what a current-schema rule does here.+ */+export const Default: Story = {};++/** The rule id in the URL does not resolve, so the page offers the way back. */+export const RuleNotFound: Story = {+ args: { dataState: 'error' },+ // The mocked rule request intentionally fails; the resulting console error is+ // the point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};++/**+ * The preview chart's legend, one tooltip per series carrying the full label a+ * truncated legend entry falls back to. The Preview series control is turned up+ * to its maximum so the legend wraps to a second row, which is where a label+ * gets clipped.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true, previewSeries: 6 },+};diff --git a/frontend/src/pages/ErrorBoundaryFallback/stories/ErrorBoundaryFallback.stories.mocks.tsx b/frontend/src/pages/ErrorBoundaryFallback/stories/ErrorBoundaryFallback.stories.mocks.tsxnew file mode 100644index 0000000000..254860cc82--- /dev/null+++ b/frontend/src/pages/ErrorBoundaryFallback/stories/ErrorBoundaryFallback.stories.mocks.tsx@@ -0,0 +1,17 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';++import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++/**+ * The screen every error boundary in the app falls back to. It calls nothing;+ * where its support button leads follows the License control.+ */+export const errorBoundaryFallbackMocks = defineStoryMocks({+ controls: {},+ config: () => ({ route: ROUTES.SOMETHING_WENT_WRONG }),+});diff --git a/frontend/src/pages/ErrorBoundaryFallback/stories/ErrorBoundaryFallback.stories.tsx b/frontend/src/pages/ErrorBoundaryFallback/stories/ErrorBoundaryFallback.stories.tsxnew file mode 100644index 0000000000..ac29966441--- /dev/null+++ b/frontend/src/pages/ErrorBoundaryFallback/stories/ErrorBoundaryFallback.stories.tsx@@ -0,0 +1,38 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import ErrorBoundaryFallback from '../ErrorBoundaryFallback';+import { errorBoundaryFallbackMocks } from './ErrorBoundaryFallback.stories.mocks';++type ErrorBoundaryFallbackArgs = PageStoryArgs<+ typeof errorBoundaryFallbackMocks+>;++const pageStory = storyMocks(errorBoundaryFallbackMocks, { layout: 'app' });++/**+ * What a render error leaves on screen: the error boundary's own page, with+ * nothing fetching behind it.+ *+ * Route: `/something-went-wrong`.+ */+const meta = {+ title: 'Pages/System/Error Fallback',+ component: ErrorBoundaryFallback,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ErrorBoundaryFallbackArgs>;++export default meta;++type Story = StoryObj<ErrorBoundaryFallbackArgs>;++/** What a page that threw is replaced with, anywhere in the app. */+export const Default: Story = {};++/** The self-hosted spelling, where support is the community rather than chat. */+export const SelfHosted: Story = {+ args: { license: 'enterprise' },+};diff --git a/frontend/src/pages/ErrorDetails/stories/ErrorDetails.stories.mocks.tsx b/frontend/src/pages/ErrorDetails/stories/ErrorDetails.stories.mocks.tsxnew file mode 100644index 0000000000..2b0b117b6e--- /dev/null+++ b/frontend/src/pages/ErrorDetails/stories/ErrorDetails.stories.mocks.tsx@@ -0,0 +1,100 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import ROUTES from 'constants/routes';++import { choiceControl, toggleControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import type { MockResolver } from '@/storybook/msw/types';++import {+ DETAIL_PARAMS,+ type DetailParams,+ ERROR_EVENT_NOT_FOUND,+ errorDetailsSearch,+ errorEvent,+ errorNeighbours,+ EXCEPTION_LANGUAGES,+ type ExceptionLanguage,+ NEIGHBOUR_STATES,+ type NeighbourState,+} from './__story_mockdata__/errorDetails';++const eventNotFound: MockResolver = (_req, res, ctx) =>+ res(ctx.status(404), ctx.json(ERROR_EVENT_NOT_FOUND));++const EVENT = 'Exception details · event';+const NAVIGATION = 'Exception details · navigation';++export const errorDetailsMocks = defineStoryMocks({+ controls: {+ language: choiceControl<ExceptionLanguage>('Exception', {+ group: EVENT,+ description:+ 'Which exception group the page is opened on, which is what the stack trace panel renders.',+ options: EXCEPTION_LANGUAGES,+ value: 'go',+ }),+ found: toggleControl('Event found', {+ group: EVENT,+ description:+ 'Off, the lookup answers 404 and the page prints the error type it came back with. It answers that way whatever the Data control is set to, since a status code is not something a response body can carry.',+ value: true,+ }),+ params: choiceControl<DetailParams>('URL parameters', {+ group: NAVIGATION,+ description:+ '`group` is what the list links with and reads `/errorFromGroupID`; `event` carries the id Older and Newer add and reads `/errorFromErrorID`; `no-timestamp` is the incomplete link the page refuses to render.',+ options: DETAIL_PARAMS,+ value: 'group',+ }),+ neighbours: choiceControl<NeighbourState>('Neighbouring events', {+ group: NAVIGATION,+ description:+ 'Which of Older and Newer the group has, and so which of the two buttons is enabled.',+ options: NEIGHBOUR_STATES,+ value: 'surrounded',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/errorFromGroupID',+ values.found+ ? response.json((req) =>+ errorEvent(values.language, {+ timestamp: req.url.searchParams.get('timestamp'),+ }),+ )+ : eventNotFound,+ ),++ rest.get(+ 'http://localhost/api/v1/errorFromErrorID',+ values.found+ ? response.json((req) =>+ errorEvent(values.language, {+ timestamp: req.url.searchParams.get('timestamp'),+ errorId: req.url.searchParams.get('errorID'),+ }),+ )+ : eventNotFound,+ ),++ rest.get(+ 'http://localhost/api/v1/nextPrevErrorIDs',+ response.json((req) =>+ errorNeighbours(+ values.language,+ values.neighbours,+ req.url.searchParams.get('timestamp'),+ ),+ ),+ ),+ ],+ config: (values) => ({+ route: `${ROUTES.ERROR_DETAIL}?${errorDetailsSearch(values.language, values.params)}`,+ }),+});diff --git a/frontend/src/pages/ErrorDetails/stories/ErrorDetails.stories.tsx b/frontend/src/pages/ErrorDetails/stories/ErrorDetails.stories.tsxnew file mode 100644index 0000000000..0510d8f15f--- /dev/null+++ b/frontend/src/pages/ErrorDetails/stories/ErrorDetails.stories.tsx@@ -0,0 +1,78 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { errorDetailsMocks } from './ErrorDetails.stories.mocks';+import ErrorDetails from '../index';++type ErrorDetailsArgs = PageStoryArgs<typeof errorDetailsMocks>;++const pageStory = storyMocks(errorDetailsMocks, { layout: 'app' });++/**+ * One exception: its stack trace rendered for the language it came from, the span+ * it belongs to, and the occurrence before and after it.+ *+ * Route: `/error-detail?...`.+ */+const meta = {+ title: 'Pages/Exceptions/Detail',+ component: ErrorDetails,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ErrorDetailsArgs>;++export default meta;++type Story = StoryObj<ErrorDetailsArgs>;++/**+ * One exception event as the list opens it: the type and message it was grouped+ * under, when it was seen, its stack trace, and the span and trace it came from.+ * Older and Newer walk the group's other events in place.+ */+export const Default: Story = {};++/** A Java exception stack trace, including JVM frame formatting. */+export const JavaStack: Story = {+ args: { language: 'java' },+};++/** A Python exception stack trace, including chained traceback formatting. */+export const PythonStack: Story = {+ args: { language: 'python' },+};++/** The oldest event in the group, with Older disabled. */+export const OldestEvent: Story = {+ args: { neighbours: 'oldest' },+};++/** The newest event in the group, with Newer disabled. */+export const NewestEvent: Story = {+ args: { neighbours: 'newest' },+};++/**+ * A link to an event the backend no longer has, which is what a bookmarked+ * exception past its retention window opens.+ */+export const EventMissing: Story = {+ args: { found: false },+ // The mocked event lookup deliberately 404s; the resulting console error is the state under test.+ parameters: { allowConsoleErrors: true },+};++/** The page mid-fetch, shell included. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/**+ * The page without a timestamp to look the event up by, which is the link the+ * page refuses and sends back to the exceptions list.+ */+export const IncompleteLink: Story = {+ args: { params: 'no-timestamp' },+};diff --git a/frontend/src/pages/ErrorDetails/stories/__story_mockdata__/errorDetails.ts b/frontend/src/pages/ErrorDetails/stories/__story_mockdata__/errorDetails.tsnew file mode 100644index 0000000000..22b5b27bb5--- /dev/null+++ b/frontend/src/pages/ErrorDetails/stories/__story_mockdata__/errorDetails.ts@@ -0,0 +1,232 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { EXCEPTION_CATALOGUE } from 'pages/AllErrors/stories/__story_mockdata__/exceptions';+import type { ExceptionShape } from 'pages/AllErrors/stories/__story_mockdata__/exceptions';+import type { PayloadProps as ErrorEvent } from 'types/api/errors/getByErrorTypeAndService';+import type { PayloadProps as NextPrevIds } from 'types/api/errors/getNextPrevId';++export const EXCEPTION_LANGUAGES = ['go', 'python', 'java'] as const;++export type ExceptionLanguage = (typeof EXCEPTION_LANGUAGES)[number];++export const NEIGHBOUR_STATES = [+ 'surrounded',+ 'oldest',+ 'newest',+ 'only-event',+] as const;++export type NeighbourState = (typeof NEIGHBOUR_STATES)[number];++/** The three parameter sets the page distinguishes, in the order it reads them. */+export const DETAIL_PARAMS = ['group', 'event', 'no-timestamp'] as const;++export type DetailParams = (typeof DETAIL_PARAMS)[number];++/**+ * The three events the group holds, oldest first. Both lookups key on the+ * timestamp, so walking with Older and Newer, which is the page rewriting the+ * `timestamp` param, is what moves between them.+ */+const WALK = ['older', 'event', 'newer'] as const;++type Step = (typeof WALK)[number];++/** RFC 3339 as the payload carries it, and the nanoseconds the URL carries. */+const STEP_TIMESTAMPS: Record<Step, { at: string; nanos: string }> = {+ older: { at: '2025-04-14T18:11:04.113904221Z', nanos: '1744654264113904221' },+ event: { at: '2025-04-14T18:27:57.797616374Z', nanos: '1744655277797616374' },+ newer: { at: '2025-04-14T18:44:12.550118903Z', nanos: '1744656252550118903' },+};++const stepAt = (nanos: string | null): Step =>+ WALK.find((step) => STEP_TIMESTAMPS[step].nanos === nanos) ?? 'event';++const eventIdAt = (step: Step, errorId: string): string =>+ step === 'event' ? errorId : `${step}-${errorId}`;++const STACK_TRACES: Record<ExceptionLanguage, string> = {+ go: `*errors.errorString: redis timeout+goroutine 51 [running]:+github.com/signoz/sample/pkg/cache.(*Client).Get(0xc000112a80, {0x1096f40, 0xc0001a2000}, {0xf8a3c1, 0x11})+\t/app/pkg/cache/client.go:118 +0x2c5+github.com/signoz/sample/pkg/orders.(*Service).Lookup(0xc0000b8060, {0x1096f40, 0xc0001a2000}, 0x1f4)+\t/app/pkg/orders/service.go:64 +0x11f+github.com/signoz/sample/internal/http.(*Handler).ServeHTTP(0xc0000ba018, {0x1094e80, 0xc00019c0e0}, 0xc0001c4000)+\t/app/internal/http/handler.go:41 +0x1a8+net/http.serverHandler.ServeHTTP({0xc00018e000}, {0x1094e80, 0xc00019c0e0}, 0xc0001c4000)+\t/usr/local/go/src/net/http/server.go:2938 +0x8e`,+ python: `Traceback (most recent call last):+ File "/usr/local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 715, in urlopen+ httplib_response = self._make_request(+ File "/usr/local/lib/python3.11/site-packages/urllib3/connectionpool.py", line 467, in _make_request+ raise ReadTimeoutError(self, url, "Read timed out")+urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='payments', port=8080): Read timed out. (read timeout=2)++During handling of the above exception, another exception occurred:++Traceback (most recent call last):+ File "/app/checkout/views.py", line 82, in place_order+ response = session.post(f"{PAYMENTS_URL}/charge", json=payload, timeout=2)+ File "/usr/local/lib/python3.11/site-packages/requests/sessions.py", line 637, in post+ return self.request("POST", url, data=data, json=json, **kwargs)+requests.exceptions.ConnectionError: HTTPConnectionPool(host='payments', port=8080): Read timed out. (read timeout=2)`,+ java: `java.net.SocketTimeoutException: Read timed out+\tat java.base/java.net.SocketInputStream.socketRead0(Native Method)+\tat java.base/java.net.SocketInputStream.read(SocketInputStream.java:168)+\tat okhttp3.internal.http1.Http1ExchangeCodec.readResponseHeaders(Http1ExchangeCodec.kt:180)+\tat okhttp3.internal.connection.Exchange.readResponseHeaders(Exchange.kt:106)+\tat io.signoz.sample.payment.GatewayClient.authorize(GatewayClient.java:74)+\tat io.signoz.sample.payment.PaymentService.charge(PaymentService.java:112)+\tat io.signoz.sample.payment.PaymentController.pay(PaymentController.java:48)+\tat java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1136)`,+};++interface EventShape {+ group: ExceptionShape;+ errorId: string;+ spanID: string;+ traceID: string;+}++const groupOf = (exceptionType: string): ExceptionShape => {+ const found = EXCEPTION_CATALOGUE.find(+ (exception) => exception.exceptionType === exceptionType,+ );++ if (!found) {+ throw new Error(`no exception group for ${exceptionType} in the catalogue`);+ }++ return found;+};++const EVENTS: Record<ExceptionLanguage, EventShape> = {+ go: {+ group: groupOf('*errors.errorString'),+ errorId: '7c1ba0d4e6f84a1f9d2b3c4e5f607182',+ spanID: '3a5c7e9b1d0f2468',+ traceID: 'd41f8c2a6b3e5079a1c4e6b8d0f2a468',+ },+ python: {+ group: groupOf('ConnectionError'),+ errorId: 'b2d4f60819a3c5e7092b4d6f8a0c1e35',+ spanID: '9f1d3b5a7c9e0246',+ traceID: '5e7a9c1b3d5f7911a3c5e7b9d1f30517',+ },+ java: {+ group: groupOf('java.net.SocketTimeoutException'),+ errorId: 'e6c8a0f2d4b60819273a5c7e9b1d3f50',+ spanID: '2c4e6a8b0d2f4618',+ traceID: 'a0c2e4b6d8f01325476a8c0e2b4d6f81',+ },+};++/** The parameters the list links with, and the ones Older and Newer add to them. */+export const errorDetailsSearch = (+ language: ExceptionLanguage,+ params: DetailParams,+): string => {+ const { group, errorId } = EVENTS[language];+ const search = new URLSearchParams({ groupId: group.groupID });++ if (params === 'no-timestamp') {+ return search.toString();+ }++ search.set('timestamp', STEP_TIMESTAMPS.event.nanos);++ if (params === 'event') {+ search.set('errorId', errorId);+ }++ return search.toString();+};++export interface EventLookup {+ timestamp: string | null;+ errorId?: string | null;+}++/**+ * `/errorFromGroupID` and `/errorFromErrorID` both answer with the event itself,+ * unwrapped: the api module hands the whole body through as the payload.+ */+export const errorEvent = (+ language: ExceptionLanguage,+ lookup: EventLookup,+): ErrorEvent => {+ const event = EVENTS[language];+ const step = stepAt(lookup.timestamp);++ return {+ errorId: lookup.errorId || eventIdAt(step, event.errorId),+ exceptionType: event.group.exceptionType,+ exceptionMessage: event.group.exceptionMessage,+ exceptionStacktrace: STACK_TRACES[language],+ exceptionEscaped: 'false',+ timestamp: STEP_TIMESTAMPS[step].at,+ spanID: event.spanID,+ traceID: event.traceID,+ serviceName: event.group.serviceName,+ groupID: event.group.groupID,+ };+};++const neighbourSteps = (+ step: Step,+ state: NeighbourState,+): { older: Step | null; newer: Step | null } => {+ if (step === 'older') {+ return { older: null, newer: 'event' };+ }++ if (step === 'newer') {+ return { older: 'event', newer: null };+ }++ return {+ older: state === 'surrounded' || state === 'newest' ? 'older' : null,+ newer: state === 'surrounded' || state === 'oldest' ? 'newer' : null,+ };+};++/**+ * An empty id is how the backend says there is nothing further in that+ * direction, and it is what the Older and Newer buttons read to disable+ * themselves. Which end of the walk the page is on comes from the timestamp it+ * asks with, so a step in either direction lands somewhere it can step back+ * from.+ */+export const errorNeighbours = (+ language: ExceptionLanguage,+ state: NeighbourState,+ timestamp: string | null,+): NextPrevIds => {+ const event = EVENTS[language];+ const { older, newer } = neighbourSteps(stepAt(timestamp), state);++ return {+ groupID: event.group.groupID,+ prevErrorID: older ? eventIdAt(older, event.errorId) : '',+ prevTimestamp: older ? STEP_TIMESTAMPS[older].at : '',+ nextErrorID: newer ? eventIdAt(newer, event.errorId) : '',+ nextTimestamp: newer ? STEP_TIMESTAMPS[newer].at : '',+ };+};++/**+ * What the backend answers when no event matches the group and timestamp: a 404+ * carrying its own envelope, which `ErrorResponseHandler` reduces to the+ * `errorType` the page prints. A `null` body instead of this reaches the page as+ * a TypeError, so the `idPayload === null` branch it guards for is unreachable.+ */+export const ERROR_EVENT_NOT_FOUND = {+ status: 'error',+ errorType: 'not_found',+ error: 'Error/Exception not found',+ data: null,+};diff --git a/frontend/src/pages/ForgotPassword/stories/ForgotPassword.stories.mocks.tsx b/frontend/src/pages/ForgotPassword/stories/ForgotPassword.stories.mocks.tsxnew file mode 100644index 0000000000..f98791e230--- /dev/null+++ b/frontend/src/pages/ForgotPassword/stories/ForgotPassword.stories.mocks.tsx@@ -0,0 +1,67 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { StatusCodes } from 'http-status-codes';+import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ forgotPasswordRouteState,+ ORG_MAX,+} from './__story_mockdata__/forgotPassword';++const RESET = 'Forgot password · reset';++const REQUESTS = ['accepted', 'rejected'] as const;++type ResetRequest = (typeof REQUESTS)[number];++export const forgotPasswordMocks = defineStoryMocks({+ controls: {+ orgs: countControl('Organizations', {+ group: RESET,+ description:+ 'Workspaces the email belongs to. More than one adds the organization select, because the reset is scoped to one.',+ value: 1,+ max: ORG_MAX,+ }),+ request: choiceControl<ResetRequest>('Reset request', {+ group: RESET,+ description:+ 'What the reset endpoint answers when the form is sent: the check-your-inbox screen, or the error above the button.',+ options: REQUESTS,+ value: 'accepted',+ }),+ },+ handlers: (values) => [+ rest.post(+ 'http://localhost/api/v2/factor_password/forgot',+ (_req, res, ctx) =>+ values.request === 'accepted'+ ? res(ctx.status(StatusCodes.NO_CONTENT))+ : res(+ ctx.status(StatusCodes.TOO_MANY_REQUESTS),+ ctx.json({+ error: {+ code: 'rate_limited',+ message: 'Too many reset emails were sent. Try again in an hour.',+ url: '',+ errors: [],+ },+ }),+ ),+ ),+ ],+ config: (values) => ({+ route: ROUTES.FORGOT_PASSWORD,+ routeState: forgotPasswordRouteState(values.orgs),+ // Resetting a password is what a signed-out browser does, so the shell has+ // no side nav, top nav or banners to draw.+ appContext: { isLoggedIn: false },+ }),+});diff --git a/frontend/src/pages/ForgotPassword/stories/ForgotPassword.stories.tsx b/frontend/src/pages/ForgotPassword/stories/ForgotPassword.stories.tsxnew file mode 100644index 0000000000..ba4c88370b--- /dev/null+++ b/frontend/src/pages/ForgotPassword/stories/ForgotPassword.stories.tsx@@ -0,0 +1,66 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import ForgotPassword from '../index';+import { forgotPasswordMocks } from './ForgotPassword.stories.mocks';++type ForgotPasswordArgs = PageStoryArgs<typeof forgotPasswordMocks>;++const pageStory = storyMocks(forgotPasswordMocks, { layout: 'app' });++/**+ * The reset request form, before any session exists.+ *+ * Route: `/forgot-password`.+ */+const meta = {+ title: 'Pages/Auth/Forgot Password',+ tags: ['play'],+ component: ForgotPassword,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ForgotPasswordArgs>;++export default meta;++type Story = StoryObj<ForgotPasswordArgs>;++const submit = async (canvasElement: HTMLElement): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByRole('button', {+ name: /send reset link/i,+ }),+ );+};++/** The email the login form carried over, ready to have a reset link sent to it. */+export const Default: Story = {};++/** An email in three workspaces: the reset is scoped to one, so it has to be picked. */+export const MultipleOrganizations: Story = {+ args: { orgs: 3 },+};++/** The link sent: what the page shows instead of the form. */+export const LinkSent: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await submit(canvasElement);+ await within(canvasElement).findByRole('heading', {+ name: /check your email/i,+ });+ },+};++/** Asked once too often, which the backend rate-limits. */+export const RateLimited: Story = {+ args: { request: 'rejected' },+ // The deliberate 429 is the state under test.+ parameters: { allowConsoleErrors: true },+ play: async ({ canvasElement }): Promise<void> => {+ await submit(canvasElement);+ await within(canvasElement).findByText(/rate_limited/i);+ },+};diff --git a/frontend/src/pages/ForgotPassword/stories/__story_mockdata__/forgotPassword.ts b/frontend/src/pages/ForgotPassword/stories/__story_mockdata__/forgotPassword.tsnew file mode 100644index 0000000000..ddbb0fa9b1--- /dev/null+++ b/frontend/src/pages/ForgotPassword/stories/__story_mockdata__/forgotPassword.ts@@ -0,0 +1,33 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { ForgotPasswordRouteState } from 'container/ForgotPassword';+import type { OrgSessionContext } from 'types/api/v2/sessions/context/get';++export const FORGOT_PASSWORD_EMAIL = '[email protected]';++const ORGS: OrgSessionContext[] = [+ { id: 'org-signoz', name: 'SigNoz' },+ { id: 'org-acme', name: 'Acme Corp' },+ { id: 'org-globex', name: 'Globex' },+].map((org) => ({+ ...org,+ authNSupport: { password: [{ provider: 'password' }], callback: [] },+}));++export const ORG_MAX = ORGS.length;++/**+ * The page is reached by a push from the login form rather than by its URL, so+ * the email and the workspaces it resolved to arrive as `location.state`. With+ * none the page bounces straight back to login.+ */+export const forgotPasswordRouteState = (+ orgs: number,+): ForgotPasswordRouteState => ({+ email: FORGOT_PASSWORD_EMAIL,+ orgId: orgs === 1 ? ORGS[0].id : undefined,+ orgs: ORGS.slice(0, orgs),+});diff --git a/frontend/src/pages/HomePage/stories/HomePage.stories.tsx b/frontend/src/pages/HomePage/stories/HomePage.stories.tsxindex bf2758aafb..046777d601 100644--- a/frontend/src/pages/HomePage/stories/HomePage.stories.tsx+++ b/frontend/src/pages/HomePage/stories/HomePage.stories.tsx@@ -1,5 +1,6 @@import type { Meta, StoryObj } from '@storybook/react-vite';import ROUTES from 'constants/routes';+import { screen, userEvent, within } from 'storybook/test';import { storyMocks } from '@/storybook/controls/defineStoryMocks';import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';@@ -9,10 +10,21 @@ import HomePage from '../HomePage';type HomeArgs = PageStoryArgs<typeof homeMocks>;+const pageStory = storyMocks(homeMocks, { route: ROUTES.HOME, layout: 'app' });++/**+ * The workspace landing page: ingestion state per signal, the welcome checklist+ * while a signal is missing, then alert rules, dashboards, saved views and the+ * services table.+ *+ * Route: `/home`.+ */const meta = {title: 'Pages/Home',+ tags: ['role-gated', 'play'],component: HomePage,- ...storyMocks(homeMocks, { route: ROUTES.HOME, layout: 'app' }),+ ...pageStory,+ parameters: { ...pageStory.parameters },} satisfies Meta<HomeArgs>;export default meta;@@ -51,3 +63,37 @@ export const ViewerAccess: Story = {export const Loading: Story = {args: { dataState: 'loading' },};++/**+ * The sidebar's Help & Support menu, open. The nav is part of the app shell, so+ * this menu is the same on every page; Home is where it is shot.+ */+export const NavHelpMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'help-support-nav-item',+ {},+ { timeout: 10000 },+ ),+ );+ await screen.findByRole('menu');+ },+};++/**+ * The sidebar's Settings menu, open: the workspace and account sections the nav+ * reaches without leaving the page.+ */+export const NavSettingsMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'settings-nav-item',+ {},+ { timeout: 10000 },+ ),+ );+ await screen.findByRole('menu');+ },+};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Clusters.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Clusters.stories.tsxnew file mode 100644index 0000000000..7cc07baa3a--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Clusters.stories.tsx@@ -0,0 +1,46 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { clustersMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type ClustersArgs = PageStoryArgs<typeof clustersMocks>;++const pageStory = storyMocks(clustersMocks, { layout: 'app' });++/**+ * The Kubernetes clusters tab: CPU, memory and pod counts per cluster, each row+ * opening the drawer.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=clusters`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/Clusters',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ClustersArgs>;++export default meta;++/**+ * Clusters with their node readiness and pod status counts, and CPU and memory+ * against the cluster's allocatable capacity. The drawer carries the counts cards+ * that jump to the nodes and pods of the cluster.+ */+export const Default: StoryObj<ClustersArgs> = {};++/**+ * The tooltips of the cluster's details drawer: one per counts card, each naming+ * the cluster it would filter the namespaces, nodes or workloads by, the cluster+ * name above them, and on every metrics chart the header's own paragraph, its+ * docs link, the Go to Metrics Explorer button and the series names in the+ * legend. The counts cards are the clusters and namespaces tabs only, so this is+ * where they are reviewable.+ */+export const Tooltips: StoryObj<ClustersArgs> = {+ args: { tooltipsOpen: true, drawer: true },+};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/DaemonSets.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/DaemonSets.stories.tsxnew file mode 100644index 0000000000..983c0e1b93--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/DaemonSets.stories.tsx@@ -0,0 +1,34 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { daemonSetsMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type DaemonSetsArgs = PageStoryArgs<typeof daemonSetsMocks>;++const pageStory = storyMocks(daemonSetsMocks, { layout: 'app' });++/**+ * The Kubernetes daemon sets tab: desired against ready nodes, with CPU and+ * memory beside them.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=daemonsets`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/DaemonSets',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<DaemonSetsArgs>;++export default meta;++/**+ * DaemonSets by namespace: ready, current, desired and misscheduled nodes beside+ * the CPU and memory of the pods they run. The drawer adds the by-pod metrics+ * tab.+ */+export const Default: StoryObj<DaemonSetsArgs> = {};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Deployments.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Deployments.stories.tsxnew file mode 100644index 0000000000..02c8542f5b--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Deployments.stories.tsx@@ -0,0 +1,34 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { deploymentsMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type DeploymentsArgs = PageStoryArgs<typeof deploymentsMocks>;++const pageStory = storyMocks(deploymentsMocks, { layout: 'app' });++/**+ * The Kubernetes deployments tab: desired against available replicas, with CPU and+ * memory against request and limit.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=deployments`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/Deployments',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<DeploymentsArgs>;++export default meta;++/**+ * Deployments by namespace: available against desired pods, the replica count and+ * the pod status counts. The drawer adds the by-pod metrics tab, one series per+ * pod of the deployment.+ */+export const Default: StoryObj<DeploymentsArgs> = {};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/InfrastructureMonitoring.stories.mocks.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/InfrastructureMonitoring.stories.mocks.tsxnew file mode 100644index 0000000000..dc17ac4790--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/InfrastructureMonitoring.stories.mocks.tsx@@ -0,0 +1,466 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import ROUTES from 'constants/routes';+import {+ INFRA_MONITORING_ATTR_KEYS,+ INFRA_MONITORING_K8S_PARAMS_KEYS,+ InfraMonitoringEntity,+ VIEWS,+} from 'container/InfraMonitoringK8sV2/constants';+import type {+ QueryEnvelope,+ QueryRangeRequestV5,+ RawRow,+ TimeSeries,+} from 'types/api/v5/queryRange';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import type { MockControl, StoryMocks } from '@/storybook/controls/types';+import {+ fieldKeysResponse,+ fieldValuesResponse,+} from '@/storybook/msw/__story_mockdata__/fields';+import {+ queryRangeV5RawResponse,+ queryRangeV5ScalarResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++import {+ CHECKS_STATES,+ type ChecksState,+ entityForChecksType,+ entityForResource,+ entityEventRows,+ entityLogRows,+ entitySelection,+ entityTraceRows,+ GROUP_BY_KEY_BY_ENTITY,+ type InfraEntity,+ infraChecksResponse,+ infraFieldKeys,+ infraFieldValues,+ infraListResponse,+ type MetricScale,+ metricScale,+ RATIO_SCALE,+} from './__story_mockdata__/infraMonitoring';++const LIST = 'Infra · list';+const CHECKS = 'Infra · checks';+const DRAWER = 'Infra · drawer';++const EMPTY_REASONS = ['no-results', 'before-retention'] as const;++type EmptyReason = (typeof EMPTY_REASONS)[number];++/**+ * The drawer tabs each entity ends up with: `K8sBaseDetailsContent` starts from+ * all four signals, Hosts turns events off, Volumes hides the strip entirely,+ * and the workload entities add the by-pod metrics tab.+ */+const DRAWER_TABS_BY_ENTITY: Record<InfraEntity, readonly VIEWS[]> = {+ [InfraMonitoringEntity.HOSTS]: [VIEWS.METRICS, VIEWS.LOGS, VIEWS.TRACES],+ [InfraMonitoringEntity.PODS]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ ],+ [InfraMonitoringEntity.NODES]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ ],+ [InfraMonitoringEntity.CLUSTERS]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ ],+ [InfraMonitoringEntity.NAMESPACES]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ VIEWS.POD_METRICS,+ ],+ [InfraMonitoringEntity.DEPLOYMENTS]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ VIEWS.POD_METRICS,+ ],+ [InfraMonitoringEntity.JOBS]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ VIEWS.POD_METRICS,+ ],+ [InfraMonitoringEntity.DAEMONSETS]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ VIEWS.POD_METRICS,+ ],+ [InfraMonitoringEntity.STATEFULSETS]: [+ VIEWS.METRICS,+ VIEWS.LOGS,+ VIEWS.TRACES,+ VIEWS.EVENTS,+ VIEWS.POD_METRICS,+ ],+ [InfraMonitoringEntity.VOLUMES]: [VIEWS.METRICS],+};++interface InfraListBody {+ filter?: { expression?: string; filterByStatus?: string };+ groupBy?: { name: string }[];+ offset?: number;+ limit?: number;+}++interface RouteValues {+ groupRows: boolean;+ drawer: boolean;+ drawerTab: VIEWS;+}++const infraRoute = (+ entity: InfraEntity,+ { groupRows, drawer, drawerTab }: RouteValues,+): string => {+ const isHosts = entity === InfraMonitoringEntity.HOSTS;++ const pathname = isHosts+ ? ROUTES.INFRASTRUCTURE_MONITORING_HOSTS+ : ROUTES.INFRASTRUCTURE_MONITORING_KUBERNETES;++ const params = new URLSearchParams();++ if (!isHosts) {+ params.set(INFRA_MONITORING_K8S_PARAMS_KEYS.CATEGORY, entity);+ }++ if (groupRows) {+ params.set(+ INFRA_MONITORING_K8S_PARAMS_KEYS.GROUP_BY,+ JSON.stringify([GROUP_BY_KEY_BY_ENTITY[entity]]),+ );+ }++ if (drawer) {+ const selection = entitySelection(entity);++ params.set(+ INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM,+ selection.selectedItem,+ );+ params.set(INFRA_MONITORING_K8S_PARAMS_KEYS.VIEW, drawerTab);++ if (selection.clusterName) {+ params.set(+ INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM_CLUSTER_NAME,+ selection.clusterName,+ );+ }++ if (selection.namespaceName) {+ params.set(+ INFRA_MONITORING_K8S_PARAMS_KEYS.SELECTED_ITEM_NAMESPACE_NAME,+ selection.namespaceName,+ );+ }+ }++ const search = params.toString();++ return search ? `${pathname}?${search}` : pathname;+};++type QuerySpec = QueryEnvelope['spec'];++const specOf = (body: QueryRangeRequestV5): QuerySpec | undefined =>+ body.compositeQuery?.queries?.[0]?.spec;++const signalOf = (body: QueryRangeRequestV5): string | undefined => {+ const spec = specOf(body);++ return spec && 'signal' in spec ? spec.signal : undefined;+};++const metricNameOf = (spec: QuerySpec): string | undefined => {+ if (!('aggregations' in spec)) {+ return undefined;+ }++ const [aggregation] = spec.aggregations ?? [];++ return aggregation && 'metricName' in aggregation+ ? aggregation.metricName+ : undefined;+};++/**+ * The percentage widgets disable their operand queries and plot a `A/B` formula+ * over them, so a response has to answer per query name: the formula reads as a+ * ratio, the raw queries in the unit of the metric they ask for.+ */+const plottedQueries = (body: QueryRangeRequestV5): QueryEnvelope[] => {+ const queries = body.compositeQuery?.queries ?? [];++ const plotted = queries.filter(+ ({ spec }) => !('disabled' in spec && spec.disabled),+ );++ return plotted.length > 0 ? plotted : queries;+};++const scaleOf = ({ type, spec }: QueryEnvelope): MetricScale =>+ type === 'builder_formula' ? RATIO_SCALE : metricScale(metricNameOf(spec));++const groupByKeysOf = (spec: QuerySpec): string[] =>+ 'groupBy' in spec ? (spec.groupBy ?? []).map(({ name }) => name) : [];++/**+ * A formula carries no group-by of its own: it is grouped by whatever the+ * queries it combines were, and those are the disabled ones, so its keys come+ * off every query in the request.+ */+const groupByKeysFor = (+ query: QueryEnvelope,+ queries: QueryEnvelope[],+): string[] => {+ const own = groupByKeysOf(query.spec);++ if (own.length > 0 || query.type !== 'builder_formula') {+ return own;+ }++ return [...new Set(queries.flatMap(({ spec }) => groupByKeysOf(spec)))];+};++/** Series a grouped widget draws, which is how many the by-pod charts legend. */+const GROUPED_SERIES = 4;++const labelValue = (key: string, index: number): string => {+ const pool = infraFieldValues(key);++ return pool.length > 0 ? pool[index % pool.length] : `${key}-${index + 1}`;+};++const seriesFor = (+ query: QueryEnvelope,+ queries: QueryEnvelope[],+ { start, end }: Pick<QueryRangeRequestV5, 'start' | 'end'>,+ seed: number,+): TimeSeries[] => {+ const scale = scaleOf(query);+ const keys = groupByKeysFor(query, queries);++ if (keys.length === 0) {+ return [+ { labels: [], values: timeSeriesPoints({ start, end, seed, ...scale }) },+ ];+ }++ return Array.from({ length: GROUPED_SERIES }, (_unused, index) => ({+ labels: keys.map((name) => ({+ key: { name },+ value: labelValue(name, index),+ })),+ values: timeSeriesPoints({ start, end, seed: seed + index * 3, ...scale }),+ }));+};++/**+ * Events and logs are the same signal on the same endpoint; the events tab is+ * the one that filters on `k8s.object.kind`.+ */+const isEventsQuery = (body: QueryRangeRequestV5): boolean => {+ const spec = specOf(body);+ const expression =+ spec && 'filter' in spec ? spec.filter?.expression : undefined;++ return Boolean(+ expression?.includes(INFRA_MONITORING_ATTR_KEYS.K8S_OBJECT_KIND),+ );+};++/** A type alias, not an interface: `MockControlMap` needs an index signature. */+export type InfraControls = {+ rows: MockControl<number>;+ groupRows: MockControl<boolean>;+ warning: MockControl<boolean>;+ emptyReason: MockControl<EmptyReason>;+ checks: MockControl<ChecksState>;+ drawer: MockControl<boolean>;+ drawerTab: MockControl<VIEWS>;+ telemetryRows: MockControl<number>;+};++const infraControls = (entity: InfraEntity): InfraControls => ({+ rows: countControl('Rows', {+ group: LIST,+ description:+ 'Rows the endpoint has. The table asks for as many as fit its height, so a higher count paginates.',+ value: 20,+ max: 40,+ }),+ groupRows: toggleControl('Group rows', {+ group: LIST,+ description: `Answers with a grouped_list: one expandable row per value of ${GROUP_BY_KEY_BY_ENTITY[entity]}.`,+ value: false,+ }),+ warning: toggleControl('Query warning', {+ group: LIST,+ description: 'Attaches a warning to the response, next to the pagination.',+ value: false,+ }),+ emptyReason: choiceControl<EmptyReason>('Empty state', {+ group: LIST,+ description: 'Which empty state the table shows when Rows is 0.',+ options: EMPTY_REASONS,+ value: 'no-results',+ }),+ checks: choiceControl<ChecksState>('Instrumentation checks', {+ group: CHECKS,+ description:+ 'The callout above the table. `ready` and `no-checks` both hide it, which is what a fully instrumented cluster shows.',+ options: CHECKS_STATES,+ value: 'missing',+ }),+ drawer: toggleControl('Details drawer', {+ group: DRAWER,+ description: 'Opens the drawer on the first row.',+ value: false,+ }),+ drawerTab: choiceControl<VIEWS>('Drawer tab', {+ group: DRAWER,+ description:+ 'The tabs this entity has. Volumes hides its tab strip, so there the drawer only ever shows metrics.',+ options: DRAWER_TABS_BY_ENTITY[entity],+ value: VIEWS.METRICS,+ }),+ telemetryRows: countControl('Drawer log and trace rows', {+ group: DRAWER,+ value: 12,+ max: 20,+ }),+});++/**+ * The mocks both module tabs run on: the list endpoint of one entity, its+ * instrumentation checks, the attribute keys its filters offer, and the drawer's+ * metrics, logs, traces and events. The entity decides the route the story+ * starts on, so the Kubernetes tab passes its category and the Hosts tab does+ * not pass one at all.+ */+export const infraStoryMocks = (+ entity: InfraEntity,+): StoryMocks<InfraControls> =>+ defineStoryMocks({+ controls: infraControls(entity),+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/infra_monitoring/checks',+ response.json((req) =>+ infraChecksResponse(+ entityForChecksType(req.url.searchParams.get('type')) ?? entity,+ values.checks,+ ),+ ),+ ),++ rest.post(+ 'http://localhost/api/v2/infra_monitoring/:resource',+ response.json(async (req) => {+ const requested = entityForResource(String(req.params.resource));+ const body = (await req.json()) as InfraListBody;++ // The drawer asks the same endpoint for one record; everything else is+ // the table, its grouped rows or an expanded group.+ const isDetailsFetch = body.limit === 1;++ return infraListResponse({+ entity: requested ?? entity,+ count: isDetailsFetch ? Math.max(values.rows, 1) : values.rows,+ offset: body.offset ?? 0,+ limit: body.limit ?? 10,+ groupBy: body.groupBy?.map(({ name }) => name),+ status: body.filter?.filterByStatus,+ warning: values.warning && !isDetailsFetch,+ endTimeBeforeRetention:+ values.rows === 0 && values.emptyReason === 'before-retention',+ });+ }),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json(() => fieldKeysResponse(infraFieldKeys(entity))),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(infraFieldValues(req.url.searchParams.get('name'))),+ ),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const { start, end, requestType } = body;++ if (requestType === 'raw') {+ const rows = ((): RawRow[] => {+ if (signalOf(body) === 'traces') {+ return entityTraceRows(start, end, values.telemetryRows);+ }++ return isEventsQuery(body)+ ? entityEventRows(start, end, values.telemetryRows)+ : entityLogRows(start, end, values.telemetryRows);+ })();++ return queryRangeV5RawResponse(rows);+ }++ const queries = body.compositeQuery?.queries ?? [];+ const plotted = plottedQueries(body);++ if (requestType === 'scalar') {+ return queryRangeV5ScalarResponse(scaleOf(plotted[0]).base);+ }++ return queryRangeV5TimeSeriesResponse(+ plotted.map((query, index) => ({+ queryName: 'name' in query.spec ? (query.spec.name ?? 'A') : 'A',+ series: seriesFor(query, queries, { start, end }, index),+ })),+ );+ }),+ ),+ ],+ config: (values) => ({ route: infraRoute(entity, values) }),+ });++export const infraMonitoringMocks = infraStoryMocks(+ InfraMonitoringEntity.HOSTS,+);diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/InfrastructureMonitoring.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/InfrastructureMonitoring.stories.tsxnew file mode 100644index 0000000000..48d9775e7c--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/InfrastructureMonitoring.stories.tsx@@ -0,0 +1,94 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { VIEWS } from 'container/InfraMonitoringK8sV2/constants';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { infraMonitoringMocks } from './InfrastructureMonitoring.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type InfraArgs = PageStoryArgs<typeof infraMonitoringMocks>;++const pageStory = storyMocks(infraMonitoringMocks, { layout: 'app' });++/**+ * The host list, and the way into the Kubernetes tabs: the table, its quick+ * filters and the entity drawer.+ *+ * Route: `/infrastructure-monitoring/hosts`.+ */+const meta = {+ title: 'Pages/Infrastructure/Overview',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<InfraArgs>;++export default meta;++type Story = StoryObj<InfraArgs>;++/**+ * The Hosts tab with a full page of hosts: quick filters on the left, the status+ * toggle and group-by toolbar above the table, and an instrumentation checks+ * callout reporting an optional metric and a required attribute nobody is+ * sending yet. The Kubernetes tab is the other half of the module, one story per+ * resource under `Kubernetes`.+ */+export const Default: Story = {};++/**+ * Hosts grouped by one attribute: one expandable row per OS, with the active and+ * inactive counts of the hosts behind it.+ */+export const GroupedRows: Story = {+ args: { groupRows: true },+};++/** Nothing reporting yet, which is what a fleet with no collector shows. */+export const NoData: Story = {+ args: { rows: 0, checks: 'no-checks' },+};++/** An empty range that predates retention, distinct from an uninstrumented fleet. */+export const BeforeRetention: Story = {+ args: { rows: 0, emptyReason: 'before-retention', checks: 'no-checks' },+};++/** The host list remains usable while its query reports a response warning. */+export const QueryWarning: Story = {+ args: { warning: true },+};++/** The selected host's metrics drawer, reached through the route's detail state. */+export const HostDetailsMetrics: Story = {+ args: { drawer: true, drawerTab: VIEWS.METRICS },+};++/** The selected host's logs drawer, including its independently queried rows. */+export const HostDetailsLogs: Story = {+ args: { drawer: true, drawerTab: VIEWS.LOGS },+};++/** The selected host's traces drawer, including its independently queried rows. */+export const HostDetailsTraces: Story = {+ args: { drawer: true, drawerTab: VIEWS.TRACES },+};++/** The table and the drawer widgets mid-load, shell included. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/**+ * Every tooltip the host list carries, held open: the Options button above the+ * table, the Hostname, IOWait and load average headers sharing the generic note+ * and its docs link, the Status header's own sentence about the ten minute+ * window, and the CPU, memory and disk headers, whose tooltip is the whole+ * threshold legend rather than a sentence. The Collapse Filters control beside+ * the quick filters is an antd tooltip and stays closed.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Jobs.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Jobs.stories.tsxnew file mode 100644index 0000000000..a34f0fc5a0--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Jobs.stories.tsx@@ -0,0 +1,33 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { jobsMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type JobsArgs = PageStoryArgs<typeof jobsMocks>;++const pageStory = storyMocks(jobsMocks, { layout: 'app' });++/**+ * The Kubernetes jobs tab: active, succeeded and failed pods per job, and how long+ * each has been running.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=jobs`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/Jobs',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<JobsArgs>;++export default meta;++/**+ * Jobs by namespace, with active, failed and successful pods against the+ * completions the job asked for. The drawer adds the by-pod metrics tab.+ */+export const Default: StoryObj<JobsArgs> = {};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Kubernetes.stories.mocks.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Kubernetes.stories.mocks.tsxnew file mode 100644index 0000000000..8fc314cd59--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Kubernetes.stories.mocks.tsx@@ -0,0 +1,74 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import {+ INFRA_MONITORING_ATTR_KEYS,+ InfraMonitoringEntity,+} from 'container/InfraMonitoringK8sV2/constants';++import { infraStoryMocks } from './InfrastructureMonitoring.stories.mocks';+import { infraListResponse } from './__story_mockdata__/infraMonitoring';++/**+ * A node name long enough that the pod's metadata tooltip has to wrap, which the+ * page's own fixture is too short to show. The Rows, Query warning and Empty+ * state controls do not reach the story using this handler.+ */+export const podLongNodeName = rest.post(+ 'http://localhost/api/v2/infra_monitoring/pods',+ async (req, res, ctx) => {+ const body = (await req.json()) as { offset?: number; limit?: number };++ const list = infraListResponse({+ entity: InfraMonitoringEntity.PODS,+ count: 20,+ offset: body.offset ?? 0,+ limit: body.limit ?? 10,+ });++ return res(+ ctx.status(200),+ ctx.json({+ ...list,+ data: {+ ...list.data,+ records: list.data.records.map((record) => ({+ ...record,+ meta: {+ ...record.meta,+ [INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME]:+ 'ip-10-0-3-17.eu-central-1.compute.internal (spot, gpu-a10g, capacity-reservation cr-0f21a8b7)',+ },+ })),+ },+ }),+ );+ },+);++/**+ * One mocks module per resource the Kubernetes tab lists. They all answer the+ * same endpoints; the entity they carry is what picks the list resource, the+ * checks type, the group-by attribute and the tabs the drawer offers, and it is+ * what puts `?category=` on the route the story starts on.+ */+export const podsMocks = infraStoryMocks(InfraMonitoringEntity.PODS);+export const nodesMocks = infraStoryMocks(InfraMonitoringEntity.NODES);+export const namespacesMocks = infraStoryMocks(+ InfraMonitoringEntity.NAMESPACES,+);+export const clustersMocks = infraStoryMocks(InfraMonitoringEntity.CLUSTERS);+export const deploymentsMocks = infraStoryMocks(+ InfraMonitoringEntity.DEPLOYMENTS,+);+export const jobsMocks = infraStoryMocks(InfraMonitoringEntity.JOBS);+export const daemonSetsMocks = infraStoryMocks(+ InfraMonitoringEntity.DAEMONSETS,+);+export const statefulSetsMocks = infraStoryMocks(+ InfraMonitoringEntity.STATEFULSETS,+);+export const volumesMocks = infraStoryMocks(InfraMonitoringEntity.VOLUMES);diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Namespaces.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Namespaces.stories.tsxnew file mode 100644index 0000000000..bbf4b2a05d--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Namespaces.stories.tsx@@ -0,0 +1,40 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { VIEWS } from 'container/InfraMonitoringK8sV2/constants';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { namespacesMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type NamespacesArgs = PageStoryArgs<typeof namespacesMocks>;++const pageStory = storyMocks(namespacesMocks, { layout: 'app' });++/**+ * The Kubernetes namespaces tab: CPU and memory aggregated per namespace, each row+ * opening the drawer.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=namespaces`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/Namespaces',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<NamespacesArgs>;++export default meta;++/**+ * Namespaces with the pod counts by status behind each one. The drawer carries+ * the counts cards that jump back to this list filtered, plus the by-pod metrics+ * tab.+ */+export const Default: StoryObj<NamespacesArgs> = {};++/** The selected namespace's by-pod metrics tab, opened through its detail route. */+export const NamespaceDetailsPodMetrics: StoryObj<NamespacesArgs> = {+ args: { drawer: true, drawerTab: VIEWS.POD_METRICS },+};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Nodes.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Nodes.stories.tsxnew file mode 100644index 0000000000..9407ce04ba--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Nodes.stories.tsx@@ -0,0 +1,56 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { nodesMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type NodesArgs = PageStoryArgs<typeof nodesMocks>;++const pageStory = storyMocks(nodesMocks, { layout: 'app' });++/**+ * The Kubernetes nodes tab: allocatable against used CPU and memory, and the+ * node's condition.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=nodes`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/Nodes',+ tags: ['play'],+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<NodesArgs>;++export default meta;++/**+ * Nodes of the cluster, with the Ready and Not Ready condition counts, the pods+ * scheduled on each and CPU and memory read against what the node has left to+ * allocate.+ */+export const Default: StoryObj<NodesArgs> = {};++/**+ * Every tooltip the node list carries, held open over a hovered row: the Pod+ * Status cell, whose tooltip is a count per phase and only exists while the row+ * is hovered, beside the column headers sharing the generic note and the+ * Collapse Filters and Options buttons. The pod list renders its own count cells+ * only once grouped, so this is where that breakdown is reviewable.+ */+export const Tooltips: StoryObj<NodesArgs> = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.hover(+ await canvas.findByText('ip-10-0-1-24-1', {}, { timeout: 10000 }),+ );+ // The pod-status breakdown is only rendered for the hovered row.+ await screen.findByText('Running: 8', {}, { timeout: 10000 });+ },+};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Pods.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Pods.stories.tsxnew file mode 100644index 0000000000..014611c0c9--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Pods.stories.tsx@@ -0,0 +1,88 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';+import { VIEWS } from 'container/InfraMonitoringK8sV2/constants';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { podLongNodeName, podsMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type PodsArgs = PageStoryArgs<typeof podsMocks>;++const pageStory = storyMocks(podsMocks, { layout: 'app' });++/**+ * The Kubernetes pods tab: status, restarts and age beside CPU and memory read+ * against the pod's own request and limit. The drawer adds the pod's events.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=pods`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/Pods',+ tags: ['play'],+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<PodsArgs>;++export default meta;++/**+ * Pods across every namespace: the status pill, restart count and age beside the+ * CPU and memory columns, each of those reading against the pod's own request and+ * limit. The drawer adds the events tab, which is the pod's Kubernetes events.+ */+export const Default: StoryObj<PodsArgs> = {};++/** The selected pod's Kubernetes events tab, opened through its detail route. */+export const PodDetailsEvents: StoryObj<PodsArgs> = {+ args: { drawer: true, drawerTab: VIEWS.EVENTS },+};++/**+ * Every tooltip the pod list carries, held open: Collapse Filters beside the+ * quick filters, Options above the table, the Pod Name, Status, Age and Restarts+ * headers sharing the generic note and its docs link, and the CPU and memory+ * limit headers, whose tooltip is the whole threshold legend rather than a+ * sentence. The matching request columns are hidden until the Options panel adds+ * them, and their legend is the same shape.+ */+export const Tooltips: StoryObj<PodsArgs> = {+ args: { tooltipsOpen: true },+};++/**+ * The tooltips of the pod's details drawer on its logs tab: the namespace,+ * cluster and node metadata values, the node one long enough to wrap, and the+ * Go to Logs Explorer button beside the tab strip, with the list's own header+ * tooltips still open behind the drawer.+ */+export const TooltipsInDetailsDrawer: StoryObj<PodsArgs> = {+ args: { tooltipsOpen: true, drawer: true, drawerTab: VIEWS.LOGS },+ parameters: { msw: { handlers: [podLongNodeName] } },+};++/**+ * The Options panel over the list: the tooltip on the disabled switch of the+ * column the table cannot do without, and, because the panel lists the columns+ * the table is hiding, the CPU and memory request threshold legends the list+ * itself never renders.+ */+export const TooltipsInOptionsPanel: StoryObj<PodsArgs> = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByTestId(+ 'k8s-table-options-button',+ {},+ { timeout: 10000 },+ ),+ );++ await screen.findByText('Columns');+ },+};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/StatefulSets.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/StatefulSets.stories.tsxnew file mode 100644index 0000000000..8f389729f6--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/StatefulSets.stories.tsx@@ -0,0 +1,33 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { statefulSetsMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type StatefulSetsArgs = PageStoryArgs<typeof statefulSetsMocks>;++const pageStory = storyMocks(statefulSetsMocks, { layout: 'app' });++/**+ * The Kubernetes stateful sets tab: desired against ready replicas, with CPU and+ * memory beside them.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=statefulsets`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/StatefulSets',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<StatefulSetsArgs>;++export default meta;++/**+ * StatefulSets by namespace: current against desired pods, the replica count and+ * the pod status counts. The drawer adds the by-pod metrics tab.+ */+export const Default: StoryObj<StatefulSetsArgs> = {};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/Volumes.stories.tsx b/frontend/src/pages/InfrastructureMonitoring/stories/Volumes.stories.tsxnew file mode 100644index 0000000000..7a1e53b13a--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/Volumes.stories.tsx@@ -0,0 +1,40 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { VIEWS } from 'container/InfraMonitoringK8sV2/constants';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { volumesMocks } from './Kubernetes.stories.mocks';++import InfrastructureMonitoringPage from '../InfrastructureMonitoringPage';++type VolumesArgs = PageStoryArgs<typeof volumesMocks>;++const pageStory = storyMocks(volumesMocks, { layout: 'app' });++/**+ * The Kubernetes volumes tab: capacity, used and available per persistent volume+ * claim.+ *+ * Route: `/infrastructure-monitoring/kubernetes?category=volumes`.+ */+const meta = {+ title: 'Pages/Infrastructure/Kubernetes/Volumes',+ component: InfrastructureMonitoringPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<VolumesArgs>;++export default meta;++/**+ * Persistent volume claims by namespace, with usage against capacity and the+ * inode counts beside it. The volume drawer hides its tab strip, so it opens on+ * the metrics widgets and stays there.+ */+export const Default: StoryObj<VolumesArgs> = {};++/** The selected volume's metrics-only detail drawer. */+export const VolumeDetails: StoryObj<VolumesArgs> = {+ args: { drawer: true, drawerTab: VIEWS.METRICS },+};diff --git a/frontend/src/pages/InfrastructureMonitoring/stories/__story_mockdata__/infraMonitoring.ts b/frontend/src/pages/InfrastructureMonitoring/stories/__story_mockdata__/infraMonitoring.tsnew file mode 100644index 0000000000..3e7fede987--- /dev/null+++ b/frontend/src/pages/InfrastructureMonitoring/stories/__story_mockdata__/infraMonitoring.ts@@ -0,0 +1,1165 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ type InframonitoringtypesAssociatedComponentDTO,+ InframonitoringtypesCheckComponentTypeDTO,+ InframonitoringtypesCheckTypeDTO,+ type InframonitoringtypesChecksDTO,+ type InframonitoringtypesClusterRecordDTO,+ type InframonitoringtypesDaemonSetRecordDTO,+ type InframonitoringtypesDeploymentRecordDTO,+ type InframonitoringtypesHostRecordDTO,+ InframonitoringtypesHostStatusDTO,+ type InframonitoringtypesJobRecordDTO,+ type InframonitoringtypesNamespaceRecordDTO,+ InframonitoringtypesNodeConditionDTO,+ type InframonitoringtypesNodeRecordDTO,+ type InframonitoringtypesPodCountsByStatusDTO,+ type InframonitoringtypesPodRecordDTO,+ InframonitoringtypesPodStatusDTO,+ InframonitoringtypesResponseTypeDTO,+ type InframonitoringtypesStatefulSetRecordDTO,+ type InframonitoringtypesVolumeRecordDTO,+ type Querybuildertypesv5QueryWarnDataDTO,+} from 'api/generated/services/sigNoz.schemas';+import {+ INFRA_MONITORING_ATTR_KEYS,+ InfraMonitoringEntity,+} from 'container/InfraMonitoringK8sV2/constants';+import type { RawRow } from 'types/api/v5/queryRange';++/** The nine entities `entityRegistry` registers under the `category` param. */+export const K8S_CATEGORIES = [+ InfraMonitoringEntity.PODS,+ InfraMonitoringEntity.NODES,+ InfraMonitoringEntity.NAMESPACES,+ InfraMonitoringEntity.CLUSTERS,+ InfraMonitoringEntity.DEPLOYMENTS,+ InfraMonitoringEntity.JOBS,+ InfraMonitoringEntity.DAEMONSETS,+ InfraMonitoringEntity.STATEFULSETS,+ InfraMonitoringEntity.VOLUMES,+] as const;++export type K8sCategory = (typeof K8S_CATEGORIES)[number];++export type InfraEntity = K8sCategory | InfraMonitoringEntity.HOSTS;++/** Volumes are the one entity whose path segment is not its category name. */+const RESOURCE_BY_ENTITY: Record<InfraEntity, string> = {+ [InfraMonitoringEntity.HOSTS]: 'hosts',+ [InfraMonitoringEntity.PODS]: 'pods',+ [InfraMonitoringEntity.NODES]: 'nodes',+ [InfraMonitoringEntity.NAMESPACES]: 'namespaces',+ [InfraMonitoringEntity.CLUSTERS]: 'clusters',+ [InfraMonitoringEntity.DEPLOYMENTS]: 'deployments',+ [InfraMonitoringEntity.JOBS]: 'jobs',+ [InfraMonitoringEntity.DAEMONSETS]: 'daemonsets',+ [InfraMonitoringEntity.STATEFULSETS]: 'statefulsets',+ [InfraMonitoringEntity.VOLUMES]: 'pvcs',+};++const ENTITY_BY_RESOURCE = new Map(+ Object.entries(RESOURCE_BY_ENTITY).map(([entity, resource]) => [+ resource,+ entity as InfraEntity,+ ]),+);++export const entityForResource = (resource: string): InfraEntity | undefined =>+ ENTITY_BY_RESOURCE.get(resource);++const ENTITY_BY_NAME = new Map<string, InfraEntity>(+ Object.keys(RESOURCE_BY_ENTITY).map((entity) => [+ entity,+ entity as InfraEntity,+ ]),+);++/** The `type` the checks endpoint is asked for, which is the entity's own name. */+export const entityForChecksType = (+ type: string | null,+): InfraEntity | undefined => (type ? ENTITY_BY_NAME.get(type) : undefined);++const CLUSTERS = ['prod-us-east-1', 'prod-eu-west-1', 'staging-us-east-1'];+const NAMESPACES = ['default', 'signoz', 'kube-system', 'payments'];+const NODES = ['ip-10-0-1-24', 'ip-10-0-2-88', 'ip-10-0-3-17'];+const ENVIRONMENTS = ['production', 'production', 'staging'];+const OS_TYPES = ['linux', 'linux', 'darwin'];+const WORKLOADS = [+ 'checkout',+ 'frontend',+ 'query-service',+ 'otel-collector',+ 'redis',+ 'cart',+ 'payments',+ 'recommendation',+ 'shipping',+ 'ad-service',+ 'currency',+ 'email',+];++const pick = <T>(pool: readonly T[], index: number): T =>+ pool[index % pool.length];++/** Stable pseudo-noise in `[0, 1)`, so a re-render redraws the same numbers. */+const fraction = (index: number, seed: number): number =>+ (((index + 1) * 37 + seed * 13) % 97) / 97;++const HOUR_MS = 60 * 60 * 1000;+const MIB = 1024 * 1024;+const GIB = 1024 * MIB;++/** Working-set bytes, the unit the memory columns run through `formatBytes`. */+const bytes = (index: number, seed: number, scaleGib = 1): number =>+ Math.round((0.2 + fraction(index, seed) * 0.8) * scaleGib * GIB);++/** CPU cores, the unit the usage columns print with two decimals. */+const cores = (index: number, seed: number, scale = 1): number =>+ (0.2 + fraction(index, seed) * 3.5) * scale;++const POD_STATUS_ZEROES: InframonitoringtypesPodCountsByStatusDTO = {+ completed: 0,+ containerCannotRun: 0,+ containerCreating: 0,+ crashLoopBackOff: 0,+ createContainerConfigError: 0,+ errImagePull: 0,+ error: 0,+ evicted: 0,+ failed: 0,+ imagePullBackOff: 0,+ nodeAffinity: 0,+ nodeLost: 0,+ oomKilled: 0,+ pending: 0,+ running: 0,+ shutdown: 0,+ unexpectedAdmissionError: 0,+ unknown: 0,+};++const podCounts = (+ counts: Partial<InframonitoringtypesPodCountsByStatusDTO>,+): InframonitoringtypesPodCountsByStatusDTO => ({+ ...POD_STATUS_ZEROES,+ ...counts,+});++const workloadMeta = (index: number): Record<string, string> => ({+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME]: pick(CLUSTERS, index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME]: pick(NAMESPACES, index),+ [INFRA_MONITORING_ATTR_KEYS.DEPLOYMENT_ENVIRONMENT]: pick(ENVIRONMENTS, index),+});++const hostRecord = (index: number): InframonitoringtypesHostRecordDTO => {+ const hostName = `${pick(WORKLOADS, index)}-${index + 1}.ec2.internal`;++ return {+ hostName,+ status:+ index % 7 === 6+ ? InframonitoringtypesHostStatusDTO.inactive+ : InframonitoringtypesHostStatusDTO.active,+ cpu: fraction(index, 1),+ memory: fraction(index, 2),+ diskUsage: fraction(index, 3),+ wait: fraction(index, 4) / 20,+ load15: 1 + fraction(index, 5) * 4,+ activeHostCount: 0,+ inactiveHostCount: 0,+ meta: {+ [INFRA_MONITORING_ATTR_KEYS.HOST_NAME]: hostName,+ [INFRA_MONITORING_ATTR_KEYS.OS_TYPE]: pick(OS_TYPES, index),+ [INFRA_MONITORING_ATTR_KEYS.DEPLOYMENT_ENVIRONMENT]: pick(+ ENVIRONMENTS,+ index,+ ),+ },+ };+};++const POD_STATUSES = [+ InframonitoringtypesPodStatusDTO.running,+ InframonitoringtypesPodStatusDTO.running,+ InframonitoringtypesPodStatusDTO.running,+ InframonitoringtypesPodStatusDTO.pending,+ InframonitoringtypesPodStatusDTO.crashloopbackoff,+ InframonitoringtypesPodStatusDTO.completed,+];++const podRecord = (index: number): InframonitoringtypesPodRecordDTO => {+ const podStatus = pick(POD_STATUSES, index);+ const podName = `${pick(WORKLOADS, index)}-7d9f${index + 10}-${pick(+ ['x4k2p', 'm7vqz', 'r2n8t', 'b6h1w'],+ index,+ )}`;++ return {+ podUID: `pod-uid-${index + 1}`,+ podStatus,+ podAge: (index + 1) * 6 * HOUR_MS,+ podCPU: cores(index, 6),+ podCPULimit: fraction(index, 7),+ podCPURequest: fraction(index, 8),+ podMemory: bytes(index, 9),+ podMemoryLimit: fraction(index, 10),+ podMemoryRequest: fraction(index, 11),+ podRestarts:+ podStatus === InframonitoringtypesPodStatusDTO.crashloopbackoff+ ? 4 + (index % 5)+ : 0,+ podCountsByStatus: podCounts({ [podStatus]: 1 }),+ meta: {+ ...workloadMeta(index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_POD_NAME]: podName,+ [INFRA_MONITORING_ATTR_KEYS.K8S_POD_UID]: `pod-uid-${index + 1}`,+ [INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME]: pick(NODES, index),+ },+ };+};++const nodeRecord = (index: number): InframonitoringtypesNodeRecordDTO => {+ const nodeName = `${pick(NODES, index)}-${index + 1}`;+ const isReady = index % 6 !== 5;++ return {+ nodeName,+ condition: isReady+ ? InframonitoringtypesNodeConditionDTO.ready+ : InframonitoringtypesNodeConditionDTO.not_ready,+ nodeCPU: cores(index, 12),+ nodeCPUAllocatable: 4,+ nodeMemory: bytes(index, 13, 8),+ nodeMemoryAllocatable: 16 * GIB,+ nodeCountsByReadiness: { ready: isReady ? 1 : 0, notReady: isReady ? 0 : 1 },+ podCountsByStatus: podCounts({+ running: 8 + (index % 5),+ pending: index % 3,+ }),+ meta: {+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME]: pick(CLUSTERS, index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME]: nodeName,+ [INFRA_MONITORING_ATTR_KEYS.K8S_NODE_UID]: `node-uid-${index + 1}`,+ },+ };+};++const namespaceRecord = (+ index: number,+): InframonitoringtypesNamespaceRecordDTO => {+ const namespaceName = `${pick(NAMESPACES, index)}-${index + 1}`;++ return {+ namespaceName,+ namespaceCPU: cores(index, 14, 2),+ namespaceMemory: bytes(index, 15, 4),+ counts: {+ daemonSets: 1 + (index % 3),+ deployments: 2 + (index % 4),+ jobs: index % 3,+ statefulSets: index % 2,+ },+ podCountsByStatus: podCounts({+ running: 6 + (index % 7),+ pending: index % 2,+ }),+ meta: {+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME]: pick(CLUSTERS, index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME]: namespaceName,+ },+ };+};++const clusterRecord = (index: number): InframonitoringtypesClusterRecordDTO => {+ const clusterName = `${pick(CLUSTERS, index)}-${index + 1}`;++ return {+ clusterName,+ clusterCPU: cores(index, 16, 8),+ clusterCPUAllocatable: 48,+ clusterMemory: bytes(index, 17, 40),+ clusterMemoryAllocatable: 192 * GIB,+ counts: {+ daemonSets: 3 + (index % 3),+ deployments: 12 + (index % 6),+ jobs: 2 + (index % 4),+ namespaces: 4 + (index % 3),+ nodes: 6 + (index % 5),+ statefulSets: 1 + (index % 3),+ },+ nodeCountsByReadiness: { ready: 6 + (index % 5), notReady: index % 2 },+ podCountsByStatus: podCounts({+ running: 40 + index,+ pending: index % 3,+ crashLoopBackOff: index % 2,+ }),+ meta: {+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME]: clusterName,+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_UID]: `cluster-uid-${index + 1}`,+ },+ };+};++const deploymentRecord = (+ index: number,+): InframonitoringtypesDeploymentRecordDTO => {+ const deploymentName = `${pick(WORKLOADS, index)}-deployment`;+ const desiredPods = 2 + (index % 4);++ return {+ deploymentName,+ desiredPods,+ availablePods: index % 5 === 4 ? desiredPods - 1 : desiredPods,+ deploymentCPU: cores(index, 18),+ deploymentCPULimit: fraction(index, 19),+ deploymentCPURequest: fraction(index, 20),+ deploymentMemory: bytes(index, 21, 2),+ deploymentMemoryLimit: fraction(index, 22),+ deploymentMemoryRequest: fraction(index, 23),+ podCountsByStatus: podCounts({ running: desiredPods }),+ meta: {+ ...workloadMeta(index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_DEPLOYMENT_NAME]: deploymentName,+ },+ };+};++const jobRecord = (index: number): InframonitoringtypesJobRecordDTO => {+ const jobName = `${pick(WORKLOADS, index)}-migration-${index + 1}`;+ const failedPods = index % 6 === 5 ? 1 : 0;++ return {+ jobName,+ activePods: index % 3 === 0 ? 1 : 0,+ desiredSuccessfulPods: 1,+ successfulPods: failedPods === 0 ? 1 : 0,+ failedPods,+ jobCPU: cores(index, 24),+ jobCPULimit: fraction(index, 25),+ jobCPURequest: fraction(index, 26),+ jobMemory: bytes(index, 27),+ jobMemoryLimit: fraction(index, 28),+ jobMemoryRequest: fraction(index, 29),+ podCountsByStatus: podCounts({+ completed: failedPods === 0 ? 1 : 0,+ failed: failedPods,+ }),+ meta: {+ ...workloadMeta(index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_JOB_NAME]: jobName,+ },+ };+};++const daemonSetRecord = (+ index: number,+): InframonitoringtypesDaemonSetRecordDTO => {+ const daemonSetName = `${pick(+ ['otel-agent', 'node-exporter', 'fluent-bit', 'kube-proxy'],+ index,+ )}-${index + 1}`;+ const desiredNodes = 4 + (index % 3);+ const readyNodes = index % 5 === 4 ? desiredNodes - 1 : desiredNodes;++ return {+ daemonSetName,+ desiredNodes,+ currentNodes: desiredNodes,+ readyNodes,+ misscheduledNodes: index % 7 === 6 ? 1 : 0,+ daemonSetCPU: cores(index, 30),+ daemonSetCPULimit: fraction(index, 31),+ daemonSetCPURequest: fraction(index, 32),+ daemonSetMemory: bytes(index, 33),+ daemonSetMemoryLimit: fraction(index, 34),+ daemonSetMemoryRequest: fraction(index, 35),+ podCountsByStatus: podCounts({ running: readyNodes }),+ meta: {+ ...workloadMeta(index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_DAEMONSET_NAME]: daemonSetName,+ },+ };+};++const statefulSetRecord = (+ index: number,+): InframonitoringtypesStatefulSetRecordDTO => {+ const statefulSetName = `${pick(+ ['postgres', 'clickhouse', 'zookeeper', 'kafka'],+ index,+ )}-${index + 1}`;+ const desiredPods = 3;++ return {+ statefulSetName,+ desiredPods,+ currentPods: index % 4 === 3 ? desiredPods - 1 : desiredPods,+ statefulSetCPU: cores(index, 36),+ statefulSetCPULimit: fraction(index, 37),+ statefulSetCPURequest: fraction(index, 38),+ statefulSetMemory: bytes(index, 39, 3),+ statefulSetMemoryLimit: fraction(index, 40),+ statefulSetMemoryRequest: fraction(index, 41),+ podCountsByStatus: podCounts({ running: desiredPods }),+ meta: {+ ...workloadMeta(index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_STATEFULSET_NAME]: statefulSetName,+ },+ };+};++const volumeRecord = (index: number): InframonitoringtypesVolumeRecordDTO => {+ const persistentVolumeClaimName = `${pick(WORKLOADS, index)}-data-${index + 1}`;+ const volumeCapacity = 20 * GIB;+ const volumeUsage = volumeCapacity * (0.2 + fraction(index, 42) * 0.6);+ const volumeInodes = 1310720;+ const volumeInodesUsed = Math.round(volumeInodes * fraction(index, 43));++ return {+ persistentVolumeClaimName,+ volumeCapacity,+ volumeUsage,+ volumeAvailable: volumeCapacity - volumeUsage,+ volumeInodes,+ volumeInodesUsed,+ volumeInodesFree: volumeInodes - volumeInodesUsed,+ meta: {+ ...workloadMeta(index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_PERSISTENT_VOLUME_CLAIM_NAME]:+ persistentVolumeClaimName,+ [INFRA_MONITORING_ATTR_KEYS.K8S_VOLUME_TYPE]: 'persistentVolumeClaim',+ },+ };+};++export type InfraRecord =+ | InframonitoringtypesHostRecordDTO+ | InframonitoringtypesPodRecordDTO+ | InframonitoringtypesNodeRecordDTO+ | InframonitoringtypesNamespaceRecordDTO+ | InframonitoringtypesClusterRecordDTO+ | InframonitoringtypesDeploymentRecordDTO+ | InframonitoringtypesJobRecordDTO+ | InframonitoringtypesDaemonSetRecordDTO+ | InframonitoringtypesStatefulSetRecordDTO+ | InframonitoringtypesVolumeRecordDTO;++const RECORD_BUILDERS: Record<InfraEntity, (index: number) => InfraRecord> = {+ [InfraMonitoringEntity.HOSTS]: hostRecord,+ [InfraMonitoringEntity.PODS]: podRecord,+ [InfraMonitoringEntity.NODES]: nodeRecord,+ [InfraMonitoringEntity.NAMESPACES]: namespaceRecord,+ [InfraMonitoringEntity.CLUSTERS]: clusterRecord,+ [InfraMonitoringEntity.DEPLOYMENTS]: deploymentRecord,+ [InfraMonitoringEntity.JOBS]: jobRecord,+ [InfraMonitoringEntity.DAEMONSETS]: daemonSetRecord,+ [InfraMonitoringEntity.STATEFULSETS]: statefulSetRecord,+ [InfraMonitoringEntity.VOLUMES]: volumeRecord,+};++/**+ * The attribute the Group rows control groups by: the one every record of that+ * entity carries, so no row lands in `<no-value>`.+ */+export const GROUP_BY_KEY_BY_ENTITY: Record<InfraEntity, string> = {+ [InfraMonitoringEntity.HOSTS]: INFRA_MONITORING_ATTR_KEYS.OS_TYPE,+ [InfraMonitoringEntity.PODS]: INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ [InfraMonitoringEntity.NODES]: INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME,+ [InfraMonitoringEntity.NAMESPACES]:+ INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME,+ [InfraMonitoringEntity.CLUSTERS]: INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME,+ [InfraMonitoringEntity.DEPLOYMENTS]:+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ [InfraMonitoringEntity.JOBS]: INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ [InfraMonitoringEntity.DAEMONSETS]:+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ [InfraMonitoringEntity.STATEFULSETS]:+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ [InfraMonitoringEntity.VOLUMES]: INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+};++const buildRecords = (entity: InfraEntity, count: number): InfraRecord[] =>+ Array.from({ length: count }, (_unused, index) =>+ RECORD_BUILDERS[entity](index),+ );++const isHostRecord = (+ record: InfraRecord,+): record is InframonitoringtypesHostRecordDTO => 'hostName' in record;++const hasPodCounts = (+ record: InfraRecord,+): record is InfraRecord & {+ podCountsByStatus: InframonitoringtypesPodCountsByStatusDTO;+} => 'podCountsByStatus' in record;++/**+ * A grouped row carries only the grouped-by attributes in `meta` and the counts+ * of the rows behind it; the table reads the names from the group cell, not from+ * the record.+ */+const groupRow = (+ record: InfraRecord,+ meta: Record<string, string>,+ size: number,+): InfraRecord => {+ const grouped = { ...record, meta };++ if (isHostRecord(grouped)) {+ return {+ ...grouped,+ activeHostCount: size,+ inactiveHostCount: size > 2 ? 1 : 0,+ };+ }++ if (hasPodCounts(grouped)) {+ return {+ ...grouped,+ podCountsByStatus: podCounts({+ running: size * 2,+ pending: size > 2 ? 1 : 0,+ }),+ };+ }++ return grouped;+};++const groupRecords = (+ records: InfraRecord[],+ groupBy: string[],+): InfraRecord[] => {+ const groups = new Map<+ string,+ { meta: Record<string, string>; size: number }+ >();++ records.forEach((record) => {+ const meta = Object.fromEntries(+ groupBy.map((key) => [key, record.meta?.[key] ?? '']),+ );+ const groupKey = JSON.stringify(meta);+ const group = groups.get(groupKey);++ if (group) {+ group.size += 1;+ return;+ }++ groups.set(groupKey, { meta, size: 1 });+ });++ return [...groups.values()].map(({ meta, size }, index) =>+ groupRow(records[index], meta, size),+ );+};++export interface InfraListResponseOptions {+ entity: InfraEntity;+ count: number;+ offset?: number;+ limit?: number;+ groupBy?: string[];+ status?: string;+ warning?: boolean;+ endTimeBeforeRetention?: boolean;+}++const LIST_WARNING: Querybuildertypesv5QueryWarnDataDTO = {+ message: 'Some series were dropped to keep the query within limits.',+ url: 'https://signoz.io/docs/userguide/query-builder/',+ warnings: [+ { message: 'The metric k8s.pod.cpu.usage has partial data for this range.' },+ ],+};++export const infraListResponse = ({+ entity,+ count,+ offset = 0,+ limit = 10,+ groupBy = [],+ status,+ warning = false,+ endTimeBeforeRetention = false,+}: InfraListResponseOptions): {+ status: string;+ data: {+ type: InframonitoringtypesResponseTypeDTO;+ records: InfraRecord[];+ total: number;+ endTimeBeforeRetention: boolean;+ warning?: Querybuildertypesv5QueryWarnDataDTO;+ };+} => {+ const all = buildRecords(entity, count).filter(+ (record) => !status || !isHostRecord(record) || record.status === status,+ );++ const rows = groupBy.length > 0 ? groupRecords(all, groupBy) : all;++ return {+ status: 'success',+ data: {+ type:+ groupBy.length > 0+ ? InframonitoringtypesResponseTypeDTO.grouped_list+ : InframonitoringtypesResponseTypeDTO.list,+ records: rows.slice(offset, offset + limit),+ total: rows.length,+ endTimeBeforeRetention,+ ...(warning ? { warning: LIST_WARNING } : {}),+ },+ };+};++export interface EntitySelection {+ selectedItem: string;+ clusterName?: string;+ namespaceName?: string;+}++/**+ * The row the Details drawer opens on: the first record of the entity, keyed the+ * way its `getItemKey` keys it, so the drawer's own fetch resolves to it.+ */+export const entitySelection = (entity: InfraEntity): EntitySelection => {+ const record = RECORD_BUILDERS[entity](0);+ const meta = record.meta ?? {};++ const selectedItem = ((): string => {+ switch (entity) {+ case InfraMonitoringEntity.HOSTS:+ return isHostRecord(record) ? record.hostName : '';+ case InfraMonitoringEntity.PODS:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_POD_UID] ?? '';+ case InfraMonitoringEntity.NODES:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME] ?? '';+ case InfraMonitoringEntity.NAMESPACES:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME] ?? '';+ case InfraMonitoringEntity.CLUSTERS:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME] ?? '';+ case InfraMonitoringEntity.DEPLOYMENTS:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_DEPLOYMENT_NAME] ?? '';+ case InfraMonitoringEntity.JOBS:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_JOB_NAME] ?? '';+ case InfraMonitoringEntity.DAEMONSETS:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_DAEMONSET_NAME] ?? '';+ case InfraMonitoringEntity.STATEFULSETS:+ return meta[INFRA_MONITORING_ATTR_KEYS.K8S_STATEFULSET_NAME] ?? '';+ default:+ return (+ meta[INFRA_MONITORING_ATTR_KEYS.K8S_PERSISTENT_VOLUME_CLAIM_NAME] ?? ''+ );+ }+ })();++ return {+ selectedItem,+ clusterName: meta[INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME],+ namespaceName: meta[INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME],+ };+};++export const CHECKS_STATES = [+ 'missing',+ 'all-present',+ 'ready',+ 'no-checks',+] as const;++export type ChecksState = (typeof CHECKS_STATES)[number];++const CHECK_TYPE_BY_ENTITY: Record<+ InfraEntity,+ InframonitoringtypesCheckTypeDTO+> = {+ [InfraMonitoringEntity.HOSTS]: InframonitoringtypesCheckTypeDTO.hosts,+ [InfraMonitoringEntity.PODS]: InframonitoringtypesCheckTypeDTO.pods,+ [InfraMonitoringEntity.NODES]: InframonitoringtypesCheckTypeDTO.nodes,+ [InfraMonitoringEntity.NAMESPACES]:+ InframonitoringtypesCheckTypeDTO.namespaces,+ [InfraMonitoringEntity.CLUSTERS]: InframonitoringtypesCheckTypeDTO.clusters,+ [InfraMonitoringEntity.DEPLOYMENTS]:+ InframonitoringtypesCheckTypeDTO.deployments,+ [InfraMonitoringEntity.JOBS]: InframonitoringtypesCheckTypeDTO.jobs,+ [InfraMonitoringEntity.DAEMONSETS]:+ InframonitoringtypesCheckTypeDTO.daemonsets,+ [InfraMonitoringEntity.STATEFULSETS]:+ InframonitoringtypesCheckTypeDTO.statefulsets,+ [InfraMonitoringEntity.VOLUMES]: InframonitoringtypesCheckTypeDTO.volumes,+};++interface CheckComponents {+ receiver: InframonitoringtypesAssociatedComponentDTO;+ processor: InframonitoringtypesAssociatedComponentDTO;+ presentMetrics: string[];+ presentAttributes: string[];+ missingMetrics: string[];+ missingMetricsMessage: string;+ missingAttributes: string[];+ missingAttributesMessage: string;+ documentationLink: string;+}++/**+ * Which collector reports an entity, and the metrics and attributes it carries:+ * kubeletstats scrapes the node for pods, nodes and volumes, k8scluster watches+ * the API server for the workload objects. Every name is one the app already+ * knows, so a renamed metric moves with `INFRA_MONITORING_ATTR_KEYS`.+ */+interface EntityChecks {+ receiver: string;+ presentMetrics: string[];+ presentAttributes: string[];+ missingMetric: string;+}++const KUBELETSTATS = 'kubeletstatsreceiver';+const K8SCLUSTER = 'k8sclusterreceiver';++const CHECKS_BY_K8S_ENTITY: Record<K8sCategory, EntityChecks> = {+ [InfraMonitoringEntity.PODS]: {+ receiver: KUBELETSTATS,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_USAGE,+ INFRA_MONITORING_ATTR_KEYS.K8S_POD_MEMORY_USAGE,+ ],+ presentAttributes: [+ INFRA_MONITORING_ATTR_KEYS.K8S_POD_UID,+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ ],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_LIMIT_UTILIZATION,+ },+ [InfraMonitoringEntity.NODES]: {+ receiver: KUBELETSTATS,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_NODE_CPU_USAGE,+ INFRA_MONITORING_ATTR_KEYS.K8S_NODE_MEMORY_USAGE,+ ],+ presentAttributes: [INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_NODE_FILESYSTEM_USAGE,+ },+ // A namespace and a cluster have no metrics of their own: the app reads them+ // off the pods and the nodes they hold, which is what+ // `METRIC_NAMESPACE_BY_ENTITY` maps them to.+ [InfraMonitoringEntity.NAMESPACES]: {+ receiver: KUBELETSTATS,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_POD_CPU_USAGE,+ INFRA_MONITORING_ATTR_KEYS.K8S_POD_MEMORY_USAGE,+ ],+ presentAttributes: [INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_POD_MEMORY_LIMIT_UTILIZATION,+ },+ [InfraMonitoringEntity.CLUSTERS]: {+ receiver: KUBELETSTATS,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_NODE_CPU_USAGE,+ INFRA_MONITORING_ATTR_KEYS.K8S_NODE_MEMORY_USAGE,+ ],+ presentAttributes: [INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_NODE_FILESYSTEM_USAGE,+ },+ [InfraMonitoringEntity.DEPLOYMENTS]: {+ receiver: K8SCLUSTER,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_DEPLOYMENT_AVAILABLE,+ INFRA_MONITORING_ATTR_KEYS.K8S_DEPLOYMENT_DESIRED,+ ],+ presentAttributes: [+ INFRA_MONITORING_ATTR_KEYS.K8S_DEPLOYMENT_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ ],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_CONTAINER_CPU_LIMIT,+ },+ [InfraMonitoringEntity.JOBS]: {+ receiver: K8SCLUSTER,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_JOB_ACTIVE_PODS,+ INFRA_MONITORING_ATTR_KEYS.K8S_JOB_SUCCESSFUL_PODS,+ ],+ presentAttributes: [+ INFRA_MONITORING_ATTR_KEYS.K8S_JOB_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ ],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_JOB_DESIRED_SUCCESSFUL_PODS,+ },+ [InfraMonitoringEntity.DAEMONSETS]: {+ receiver: K8SCLUSTER,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_DAEMONSET_CURRENT_SCHEDULED_NODES,+ INFRA_MONITORING_ATTR_KEYS.K8S_DAEMONSET_DESIRED_SCHEDULED_NODES,+ ],+ presentAttributes: [+ INFRA_MONITORING_ATTR_KEYS.K8S_DAEMONSET_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ ],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_DAEMONSET_MISSCHEDULED_NODES,+ },+ [InfraMonitoringEntity.STATEFULSETS]: {+ receiver: K8SCLUSTER,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_STATEFULSET_CURRENT_PODS,+ INFRA_MONITORING_ATTR_KEYS.K8S_STATEFULSET_DESIRED_PODS,+ ],+ presentAttributes: [+ INFRA_MONITORING_ATTR_KEYS.K8S_STATEFULSET_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ ],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_STATEFULSET_UPDATED_PODS,+ },+ [InfraMonitoringEntity.VOLUMES]: {+ receiver: KUBELETSTATS,+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.K8S_VOLUME_AVAILABLE,+ INFRA_MONITORING_ATTR_KEYS.K8S_VOLUME_CAPACITY,+ ],+ presentAttributes: [+ INFRA_MONITORING_ATTR_KEYS.K8S_PERSISTENT_VOLUME_CLAIM_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ ],+ missingMetric: INFRA_MONITORING_ATTR_KEYS.K8S_VOLUME_INODES_FREE,+ },+};++const k8sComponents = (entity: K8sCategory): CheckComponents => {+ const checks = CHECKS_BY_K8S_ENTITY[entity];++ return {+ receiver: {+ name: checks.receiver,+ type: InframonitoringtypesCheckComponentTypeDTO.receiver,+ },+ processor: {+ name: 'k8sattributesprocessor',+ type: InframonitoringtypesCheckComponentTypeDTO.processor,+ },+ presentMetrics: checks.presentMetrics,+ presentAttributes: checks.presentAttributes,+ missingMetrics: [checks.missingMetric],+ missingMetricsMessage: `Set \`${checks.missingMetric}\` to \`enabled: true\` on the ${checks.receiver}.`,+ missingAttributes: [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME],+ missingAttributesMessage:+ 'Add `k8s.cluster.name` to the k8sattributes processor so rows can be grouped by cluster.',+ documentationLink:+ 'https://signoz.io/docs/infrastructure-monitoring/kubernetes/',+ };+};++const HOST_COMPONENTS: CheckComponents = {+ receiver: {+ name: 'hostmetricsreceiver',+ type: InframonitoringtypesCheckComponentTypeDTO.receiver,+ },+ processor: {+ name: 'resourcedetectionprocessor',+ type: InframonitoringtypesCheckComponentTypeDTO.processor,+ },+ presentMetrics: [+ INFRA_MONITORING_ATTR_KEYS.SYSTEM_CPU_LOAD_AVERAGE_15M,+ 'system.memory.usage',+ ],+ presentAttributes: [INFRA_MONITORING_ATTR_KEYS.HOST_NAME],+ missingMetrics: ['system.filesystem.usage'],+ missingMetricsMessage:+ 'Enable the filesystem scraper on the hostmetrics receiver to report disk usage.',+ missingAttributes: [INFRA_MONITORING_ATTR_KEYS.OS_TYPE],+ missingAttributesMessage:+ 'Add the system detector to the resourcedetection processor so hosts report their OS type.',+ documentationLink:+ 'https://signoz.io/docs/infrastructure-monitoring/hostmetrics/',+};++const EMPTY_CHECKS = {+ presentDefaultEnabledMetrics: null,+ presentOptionalMetrics: null,+ presentRequiredAttributes: null,+ missingDefaultEnabledMetrics: null,+ missingOptionalMetrics: null,+ missingRequiredAttributes: null,+};++const presentChecks = (+ components: CheckComponents,+): Partial<InframonitoringtypesChecksDTO> => ({+ presentDefaultEnabledMetrics: [+ {+ associatedComponent: components.receiver,+ metrics: components.presentMetrics,+ },+ ],+ presentRequiredAttributes: [+ {+ associatedComponent: components.processor,+ attributes: components.presentAttributes,+ },+ ],+});++const missingChecks = (+ components: CheckComponents,+): Partial<InframonitoringtypesChecksDTO> => ({+ missingOptionalMetrics: [+ {+ associatedComponent: components.receiver,+ metrics: components.missingMetrics,+ message: components.missingMetricsMessage,+ documentationLink: components.documentationLink,+ },+ ],+ missingRequiredAttributes: [+ {+ associatedComponent: components.processor,+ attributes: components.missingAttributes,+ message: components.missingAttributesMessage,+ documentationLink: components.documentationLink,+ },+ ],+});++export const infraChecksResponse = (+ entity: InfraEntity,+ state: ChecksState,+): { status: string; data: InframonitoringtypesChecksDTO } => {+ const type = CHECK_TYPE_BY_ENTITY[entity];++ const components =+ entity === InfraMonitoringEntity.HOSTS+ ? HOST_COMPONENTS+ : k8sComponents(entity);++ const checks = ((): Omit<InframonitoringtypesChecksDTO, 'ready' | 'type'> => {+ switch (state) {+ case 'missing':+ return {+ ...EMPTY_CHECKS,+ ...presentChecks(components),+ ...missingChecks(components),+ };+ case 'all-present':+ return { ...EMPTY_CHECKS, ...presentChecks(components) };+ default:+ return EMPTY_CHECKS;+ }+ })();++ return {+ status: 'success',+ data: { ...checks, ready: state === 'ready', type },+ };+};++/**+ * Resource keys the toolbar's Group by select and the search bar offer for the+ * entity, all of them attributes the records carry.+ */+export const infraFieldKeys = (entity: InfraEntity): string[] =>+ entity === InfraMonitoringEntity.HOSTS+ ? [+ INFRA_MONITORING_ATTR_KEYS.HOST_NAME,+ INFRA_MONITORING_ATTR_KEYS.OS_TYPE,+ INFRA_MONITORING_ATTR_KEYS.DEPLOYMENT_ENVIRONMENT,+ ]+ : [+ INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME,+ INFRA_MONITORING_ATTR_KEYS.K8S_POD_NAME,+ INFRA_MONITORING_ATTR_KEYS.DEPLOYMENT_ENVIRONMENT,+ ];++const FIELD_VALUES: Record<string, readonly string[]> = {+ [INFRA_MONITORING_ATTR_KEYS.HOST_NAME]: WORKLOADS.slice(0, 6).map(+ (workload, index) => `${workload}-${index + 1}.ec2.internal`,+ ),+ [INFRA_MONITORING_ATTR_KEYS.OS_TYPE]: ['linux', 'darwin'],+ [INFRA_MONITORING_ATTR_KEYS.DEPLOYMENT_ENVIRONMENT]: ['production', 'staging'],+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME]: CLUSTERS,+ [INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME]: NAMESPACES,+ [INFRA_MONITORING_ATTR_KEYS.K8S_NODE_NAME]: NODES,+ [INFRA_MONITORING_ATTR_KEYS.K8S_POD_NAME]: WORKLOADS.slice(0, 6),+ [INFRA_MONITORING_ATTR_KEYS.K8S_DEPLOYMENT_NAME]: WORKLOADS.slice(0, 6).map(+ (workload) => `${workload}-deployment`,+ ),+ [INFRA_MONITORING_ATTR_KEYS.K8S_JOB_NAME]: WORKLOADS.slice(0, 4).map(+ (workload, index) => `${workload}-migration-${index + 1}`,+ ),+ [INFRA_MONITORING_ATTR_KEYS.K8S_DAEMONSET_NAME]: [+ 'otel-agent',+ 'node-exporter',+ 'fluent-bit',+ 'kube-proxy',+ ],+ [INFRA_MONITORING_ATTR_KEYS.K8S_STATEFULSET_NAME]: [+ 'postgres',+ 'clickhouse',+ 'zookeeper',+ 'kafka',+ ],+ [INFRA_MONITORING_ATTR_KEYS.K8S_PERSISTENT_VOLUME_CLAIM_NAME]: WORKLOADS.slice(+ 0,+ 4,+ ).map((workload, index) => `${workload}-data-${index + 1}`),+};++export const infraFieldValues = (name: string | null): readonly string[] =>+ (name && FIELD_VALUES[name]) || [];++const LOG_LEVELS = ['INFO', 'INFO', 'WARN', 'ERROR'];++export const entityLogRows = (+ start: number,+ end: number,+ count: number,+): RawRow[] =>+ Array.from({ length: count }, (_unused, index) => {+ const timestamp = new Date(+ end - ((end - start) / Math.max(count, 1)) * index,+ ).toISOString();+ const severity = pick(LOG_LEVELS, index);++ return {+ timestamp,+ data: {+ id: `log-${index + 1}`,+ body: `${severity} ${pick(WORKLOADS, index)} handled request in ${+ 12 + index+ }ms`,+ severity_text: severity,+ severity_number: severity === 'ERROR' ? 17 : 9,+ attributes_string: {+ 'log.level': severity,+ [INFRA_MONITORING_ATTR_KEYS.K8S_POD_NAME]: pick(WORKLOADS, index),+ },+ attributes_bool: {},+ attributes_int64: {},+ attributes_float64: {},+ resources_string: {+ [INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME]: pick(NAMESPACES, index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME]: pick(CLUSTERS, index),+ },+ trace_id: '',+ span_id: '',+ trace_flags: 0,+ },+ };+ });++const K8S_EVENT_BODIES = [+ { severity: 'INFO', body: 'Created container checkout' },+ { severity: 'INFO', body: 'Started container checkout' },+ { severity: 'WARN', body: 'Back-off restarting failed container' },+ {+ severity: 'INFO',+ body: 'Successfully assigned default/checkout to ip-10-0-1-24',+ },+ {+ severity: 'WARN',+ body: 'Readiness probe failed: HTTP probe failed with statuscode: 503',+ },+ { severity: 'INFO', body: 'Pulled image "signoz/checkout:1.4.2" in 812ms' },+];++export const entityEventRows = (+ start: number,+ end: number,+ count: number,+): RawRow[] =>+ Array.from({ length: count }, (_unused, index) => {+ const event = pick(K8S_EVENT_BODIES, index);++ return {+ timestamp: new Date(+ end - ((end - start) / Math.max(count, 1)) * index,+ ).toISOString(),+ data: {+ id: `event-${index + 1}`,+ body: event.body,+ severity_text: event.severity,+ severity_number: event.severity === 'WARN' ? 13 : 9,+ attributes_string: {+ [INFRA_MONITORING_ATTR_KEYS.K8S_OBJECT_KIND]: 'Pod',+ [INFRA_MONITORING_ATTR_KEYS.K8S_OBJECT_NAME]: pick(WORKLOADS, index),+ },+ attributes_bool: {},+ attributes_int64: {},+ attributes_float64: {},+ resources_string: {+ [INFRA_MONITORING_ATTR_KEYS.K8S_NAMESPACE_NAME]: pick(NAMESPACES, index),+ [INFRA_MONITORING_ATTR_KEYS.K8S_CLUSTER_NAME]: pick(CLUSTERS, index),+ },+ trace_id: '',+ span_id: '',+ trace_flags: 0,+ },+ };+ });++const HTTP_METHODS = ['GET', 'POST', 'GET', 'PUT'];+const STATUS_CODES = ['200', '200', '500', '404'];++export const entityTraceRows = (+ start: number,+ end: number,+ count: number,+): RawRow[] =>+ Array.from({ length: count }, (_unused, index) => ({+ timestamp: new Date(+ end - ((end - start) / Math.max(count, 1)) * index,+ ).toISOString(),+ data: {+ serviceName: pick(WORKLOADS, index),+ name: `${pick(HTTP_METHODS, index)} /api/v1/${pick(WORKLOADS, index)}`,+ durationNano: (20 + index * 7) * 1000000,+ httpMethod: pick(HTTP_METHODS, index),+ responseStatusCode: pick(STATUS_CODES, index),+ spanID: `span-${index + 1}`,+ traceID: `trace-${index + 1}`,+ },+ }));++export interface MetricScale {+ base: number;+ amplitude: number;+}++/** What a `percentunit` widget expects: a fraction of one. */+export const RATIO_SCALE: MetricScale = { base: 0.45, amplitude: 0.2 };++/**+ * The magnitude a drawer widget expects, taken from the metric it asks for: the+ * charts format their own axis, so a byte widget fed a ratio reads "0.7 B".+ */+export const metricScale = (metricName: string | undefined): MetricScale => {+ const name = metricName ?? '';++ if (name.includes('utilization')) {+ return RATIO_SCALE;+ }++ if (+ name.includes('memory') ||+ name.includes('filesystem') ||+ name.includes('network.io')+ ) {+ return { base: 700 * MIB, amplitude: 220 * MIB };+ }++ if (name.includes('errors') || name.includes('restarts')) {+ return { base: 3, amplitude: 2 };+ }++ if (name.includes('cpu')) {+ return { base: 1.2, amplitude: 0.6 };+ }++ return RATIO_SCALE;+};diff --git a/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.mocks.tsx b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.mocks.tsxnew file mode 100644index 0000000000..67cd9da5c3--- /dev/null+++ b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.mocks.tsx@@ -0,0 +1,150 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import type { CloudintegrationtypesUpdatableServiceDTO } from 'api/generated/services/sigNoz.schemas';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import type { MockResolver } from '@/storybook/msw/types';++import {+ ACCOUNT_CAP,+ accountResponse,+ accountsResponse,+ CLOUD_PROVIDERS,+ CLOUD_SERVICE_CAP,+ type CloudProvider,+ createdAccountResponse,+ BUILT_IN_INTEGRATION_NOT_FOUND,+ credentialsResponse,+ seedServiceSignals,+ serviceResponse,+ servicesMetadataResponse,+ setServiceSignals,+} from './__story_mockdata__/cloudIntegration';++/**+ * Answered whatever the Data control says, because it is not the page's data:+ * the request goes out and its failure is discarded either way.+ */+const builtInIntegrationNotFound: MockResolver = (_req, res, ctx) =>+ res(ctx.status(404), ctx.json(BUILT_IN_INTEGRATION_NOT_FOUND));++const PROVIDER = 'Cloud integration · provider';+const SERVICES = 'Cloud integration · services';++export const cloudIntegrationMocks = defineStoryMocks({+ controls: {+ provider: choiceControl<CloudProvider>('Provider', {+ group: PROVIDER,+ description:+ 'The last segment of the pathname, so it decides which provider the page is for: its logo and copy, which setup flow Add New Account opens, and the account configuration the settings drawer edits.',+ options: CLOUD_PROVIDERS,+ value: 'aws',+ }),+ accounts: countControl('Connected accounts', {+ group: PROVIDER,+ description:+ 'At 0 the hero offers Integrate Now and the service list is read-only: the page falls back to the provider catalogue and the collection switches are disabled.',+ value: 1,+ max: ACCOUNT_CAP,+ }),+ services: countControl('Services', {+ group: SERVICES,+ description:+ 'Services the provider answers with. GCP ships six, so anything past that shows the same list.',+ value: 8,+ max: CLOUD_SERVICE_CAP,+ }),+ enabledServices: countControl('Enabled', {+ group: SERVICES,+ description:+ 'How many of them have a signal switched on, taken from the top of the list. At 0 the sidebar says so and every service sits under Not Enabled.',+ value: 3,+ max: CLOUD_SERVICE_CAP,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/integrations/:integrationId',+ builtInIntegrationNotFound,+ ),++ rest.put(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/accounts/:id/services/:serviceId',+ response.json(async (req) => {+ const body = (await req.json()) as CloudintegrationtypesUpdatableServiceDTO;++ setServiceSignals(String(req.params.serviceId), body.config ?? {});++ return { status: 'success', data: null };+ }),+ ),++ rest.get(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/accounts/:id/services/:serviceId',+ response.json((req) =>+ serviceResponse(values.provider, String(req.params.serviceId), true),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/accounts/:id/services',+ response.json(() =>+ servicesMetadataResponse(values.provider, values.services, true),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/services/:serviceId',+ response.json((req) =>+ serviceResponse(values.provider, String(req.params.serviceId), false),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/services',+ response.json(() =>+ servicesMetadataResponse(values.provider, values.services, false),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/credentials',+ response.json(() => credentialsResponse()),+ ),++ rest.post(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/accounts',+ response.json(() => createdAccountResponse(values.provider)),+ ),++ rest.put(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/accounts/:id',+ response.json((req) =>+ accountResponse(values.provider, String(req.params.id)),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/accounts/:id',+ response.json((req) =>+ accountResponse(values.provider, String(req.params.id)),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/cloud_integrations/:cloudProvider/accounts',+ response.json(() => accountsResponse(values.provider, values.accounts)),+ ),+ ],+ config: (values) => ({+ route: `/integrations/${values.provider}`,+ }),+ effect: (values) => {+ seedServiceSignals(values.provider, values.services, values.enabledServices);+ },+});diff --git a/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.tsx b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.tsxnew file mode 100644index 0000000000..8ad2d298e6--- /dev/null+++ b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/CloudIntegration.stories.tsx@@ -0,0 +1,166 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import { screen, userEvent, within } from 'storybook/test';+import ROUTES from 'constants/routes';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { cloudIntegrationMocks } from './CloudIntegration.stories.mocks';++import IntegrationsDetailsPage from '../../index';++type CloudIntegrationArgs = PageStoryArgs<typeof cloudIntegrationMocks>;++const pageStory = storyMocks(cloudIntegrationMocks, { layout: 'app' });++/**+ * A cloud provider account: the credential flow, the services it can collect from,+ * and which of them are enabled.+ *+ * Route: `/integrations/:provider`.+ */+const meta = {+ title: 'Pages/Integrations/Cloud Account',+ tags: ['play'],+ component: IntegrationsDetailsPage,+ // `aws`, `azure` and `gcp` are integration ids like any other, and the detail+ // page renders the cloud page instead of the built-in one for those three, so+ // the story runs on the detail route and its `route` picks the provider.+ render: (): JSX.Element => (+ <Route+ path={ROUTES.INTEGRATIONS_DETAIL}+ component={IntegrationsDetailsPage}+ />+ ),+ ...pageStory,+ // The built-in-integration lookup is expected to 404 for a cloud provider.+ parameters: { ...pageStory.parameters, allowConsoleErrors: true },+} satisfies Meta<CloudIntegrationArgs>;++export default meta;++type Story = StoryObj<CloudIntegrationArgs>;++/** The page picks its first service before it can render it. */+const untilLoaded = { timeout: 20_000 };++/**+ * An AWS account SigNoz collects from: the services it can watch split by+ * whether a signal is switched on, and the first enabled one open on its+ * collection switches, its dashboards and what it collects.+ */+export const Default: Story = {};++/**+ * The page before any account is connected, which is what the Integrations list+ * opens for a provider: the catalogue is browsable, the switches are not.+ */+export const NoAccountConnected: Story = {+ args: { accounts: 0 },+};++/** An account whose services are all still off. */+export const NothingEnabled: Story = {+ args: { enabledServices: 0 },+};++/** The Azure catalogue, which is the same page over a subscription. */+export const MicrosoftAzure: Story = {+ args: { provider: 'azure' },+};++/** The GCP catalogue, which is the same page over a project. */+export const GoogleCloudPlatform: Story = {+ args: { provider: 'gcp' },+};++/** Every log attribute and metric a service collects, as the agent names them. */+export const DataCollected: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText(/^data collected$/i, undefined, untilLoaded),+ );+ await canvas.findByRole(+ 'tab',+ { name: 'Data Collected', selected: true },+ untilLoaded,+ );+ },+};++/** The regions and buckets a new AWS account is connected over. */+export const ConnectAccount: Story = {+ args: { accounts: 0 },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /integrate now/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(+ 'Which regions do you want to monitor?',+ undefined,+ untilLoaded,+ );+ },+};++/** The regions an already-connected account collects from. */+export const EditAccount: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /edit account/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByRole('dialog', undefined, untilLoaded);+ },+};++/**+ * The GCP connect flow with the catalogue behind it: the help beside every field+ * the drawer asks for, and the dashboard card on the service underneath saying+ * why it cannot be opened.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true, provider: 'gcp', accounts: 0 },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /integrate now/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByTestId('gcp-ingestion-key-input', undefined, untilLoaded);+ },+};++/**+ * The Data Collected tab of a GCP service, where the Metrics heading explains+ * that the list is what the collector config suggests rather than what arrives.+ * The tabs unmount each other, so this is the one tooltip the Overview tab+ * cannot show alongside its own.+ */+export const TooltipsInDataCollected: Story = {+ args: { tooltipsOpen: true, provider: 'gcp' },+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText(/^data collected$/i, undefined, untilLoaded),+ );+ await canvas.findByRole(+ 'tab',+ { name: 'Data Collected', selected: true },+ untilLoaded,+ );+ },+};diff --git a/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/__story_mockdata__/cloudIntegration.ts b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/__story_mockdata__/cloudIntegration.tsnew file mode 100644index 0000000000..fd21f4f4c6--- /dev/null+++ b/frontend/src/pages/IntegrationsDetailsPage/CloudIntegration/stories/__story_mockdata__/cloudIntegration.ts@@ -0,0 +1,553 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ CloudintegrationtypesAccountConfigDTO,+ CloudintegrationtypesAccountDTO,+ CloudintegrationtypesServiceConfigDTO,+ CloudintegrationtypesServiceDTO,+ CreateAccount201,+ GetAccount200,+ GetConnectionCredentials200,+ ListAccounts200,+ ListAccountServicesMetadata200,+} from 'api/generated/services/sigNoz.schemas';++import { monogramIcon } from '@/pages/IntegrationsModulePage/stories/__story_mockdata__/integrations';++export const CLOUD_PROVIDERS = ['aws', 'azure', 'gcp'] as const;+export type CloudProvider = (typeof CLOUD_PROVIDERS)[number];++interface CloudServiceSeed {+ id: string;+ title: string;+ logs: boolean;+ metrics: boolean;+ dashboards: number;+}++/**+ * The services each provider ships, with the signals and dashboard counts from+ * `pkg/modules/cloudintegration/implcloudintegration/fs/definitions`, ordered by+ * id the way the backend lists them.+ */+const CLOUD_SERVICES: Record<CloudProvider, readonly CloudServiceSeed[]> = {+ aws: [+ { id: 'alb', title: 'ALB', logs: false, metrics: true, dashboards: 1 },+ {+ id: 'api-gateway',+ title: 'API Gateway',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'dynamodb',+ title: 'DynamoDB',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ { id: 'ec2', title: 'EC2', logs: false, metrics: true, dashboards: 1 },+ { id: 'ecs', title: 'ECS', logs: true, metrics: true, dashboards: 3 },+ { id: 'eks', title: 'EKS', logs: true, metrics: true, dashboards: 2 },+ {+ id: 'elasticache',+ title: 'ElastiCache',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ { id: 'lambda', title: 'Lambda', logs: true, metrics: true, dashboards: 1 },+ { id: 'msk', title: 'MSK', logs: false, metrics: true, dashboards: 1 },+ { id: 'rds', title: 'RDS', logs: true, metrics: true, dashboards: 1 },+ {+ id: 's3sync',+ title: 'S3 Sync',+ logs: true,+ metrics: false,+ dashboards: 0,+ },+ { id: 'sns', title: 'SNS', logs: false, metrics: true, dashboards: 1 },+ { id: 'sqs', title: 'SQS', logs: false, metrics: true, dashboards: 1 },+ ],+ azure: [+ {+ id: 'aks',+ title: 'Azure Kubernetes Service (AKS)',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'appservice',+ title: 'App Services',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'cassandradb',+ title: 'Cassandra DB',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'cdnprofile',+ title: 'CDN Profile',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'containerapp',+ title: 'Container App',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'cosmosdb',+ title: 'Cosmos DB',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'mongodb',+ title: 'MongoDB (DocumentDB)',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'mysqlflexibleserver',+ title: 'MySQL - Flexible Server',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'postgresqlflexibleserver',+ title: 'PostgreSQL - Flexible Server',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ { id: 'redis', title: 'Redis', logs: true, metrics: true, dashboards: 1 },+ {+ id: 'sqldatabase',+ title: 'SQL Database',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'sqldatabasemi',+ title: 'SQL Database Managed Instance',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'storageaccountsblob',+ title: 'Storage Accounts Blob Storage',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'virtualmachine',+ title: 'Virtual Machines',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ ],+ gcp: [+ {+ id: 'cloudsql_mysql',+ title: 'GCP Cloud SQL for MySQL',+ logs: true,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'cloudsql_postgres',+ title: 'GCP Cloud SQL for PostgreSQL',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'cloudstorage',+ title: 'GCP Cloud Storage',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'computeengine',+ title: 'GCP Compute Engine',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'gke',+ title: 'GCP Kubernetes Engine',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ {+ id: 'memorystore_redis',+ title: 'GCP Memorystore Redis',+ logs: false,+ metrics: true,+ dashboards: 1,+ },+ ],+};++/** AWS is the longest catalogue, so one control covers all three providers. */+export const CLOUD_SERVICE_CAP = Math.max(+ ...CLOUD_PROVIDERS.map((provider) => CLOUD_SERVICES[provider].length),+);++export const ACCOUNT_CAP = 3;++const PROVIDER_COLOUR: Record<CloudProvider, string> = {+ aws: '#FF9900',+ azure: '#0078D4',+ gcp: '#4285F4',+};++const serviceIcon = (provider: CloudProvider, id: string): string =>+ monogramIcon(+ id+ .replace(/[^a-z0-9]/gi, '')+ .slice(0, 3)+ .toUpperCase(),+ PROVIDER_COLOUR[provider],+ );++const cloudServices = (+ provider: CloudProvider,+ count: number,+): readonly CloudServiceSeed[] => CLOUD_SERVICES[provider].slice(0, count);++const findService = (+ provider: CloudProvider,+ serviceId: string,+): CloudServiceSeed | undefined =>+ CLOUD_SERVICES[provider].find((service) => service.id === serviceId);++/**+ * The account ids the story hands out. They are what `cloudAccountId` in the+ * URL holds and what the account selector lists, so they stay stable across+ * renders rather than being generated per request.+ */+const ACCOUNTS: Record<CloudProvider, readonly string[]> = {+ aws: ['482913150238', '755401882910', '119003467721'],+ azure: [+ '0f4b21ca-58d3-4d17-9d0e-1c8b3a67f4e2',+ '7d19c8ba-2e64-4f31-8a55-9b0c2d4e6f81',+ 'b2c58e17-4a90-4c26-bd73-6f81e0a35c94',+ ],+ gcp: ['signoz-prod-4471', 'signoz-analytics-8820', 'signoz-sandbox-1023'],+};++const accountConfig = (+ provider: CloudProvider,+): CloudintegrationtypesAccountConfigDTO => {+ if (provider === 'aws') {+ return { aws: { regions: ['us-east-1', 'eu-west-1', 'ap-south-1'] } };+ }++ if (provider === 'azure') {+ return {+ azure: {+ deploymentRegion: 'eastus',+ resourceGroups: ['signoz-prod-rg', 'signoz-staging-rg'],+ },+ };+ }++ return {+ gcp: {+ deploymentRegion: 'us-central1',+ deploymentProjectId: 'signoz-prod-4471',+ projectIds: ['signoz-prod-4471', 'signoz-analytics-8820'],+ },+ };+};++const account = (+ provider: CloudProvider,+ index: number,+): CloudintegrationtypesAccountDTO => ({+ id: `${provider}-account-${index + 1}`,+ orgId: 'story-org',+ provider,+ providerAccountId: ACCOUNTS[provider][index],+ config: accountConfig(provider),+ agentReport: { timestampMillis: Date.now() - 45 * 1000, data: null },+ createdAt: new Date(Date.now() - 21 * 24 * 60 * 60 * 1000).toISOString(),+ updatedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),+ removedAt: null,+});++export const accountsResponse = (+ provider: CloudProvider,+ count: number,+): ListAccounts200 => ({+ status: 'success',+ data: {+ accounts: Array.from({ length: count }, (_, index) =>+ account(provider, index),+ ),+ },+});++export const accountResponse = (+ provider: CloudProvider,+ id: string,+): GetAccount200 => {+ const index = Math.max(+ 0,+ Number.parseInt(id.replace(`${provider}-account-`, ''), 10) - 1,+ );++ return { status: 'success', data: account(provider, index) };+};++/**+ * Which signals each service has switched on. The controls own it: the mocks'+ * `effect` reseeds it from the Services and Enabled controls on every story+ * render, and the update handler writes what the form submitted, so Save moves+ * the service between the Enabled and Not Enabled lists.+ */+type ServiceSignals = { logs: boolean; metrics: boolean };++let serviceSignals = new Map<string, ServiceSignals>();++export const seedServiceSignals = (+ provider: CloudProvider,+ count: number,+ enabled: number,+): void => {+ serviceSignals = new Map(+ cloudServices(provider, count).map((service, index) => [+ service.id,+ {+ logs: index < enabled && service.logs,+ metrics: index < enabled && service.metrics,+ },+ ]),+ );+};++export const setServiceSignals = (+ serviceId: string,+ config: CloudintegrationtypesServiceConfigDTO,+): void => {+ const signals = config.aws ?? config.azure ?? config.gcp;++ serviceSignals.set(serviceId, {+ logs: Boolean(signals?.logs?.enabled),+ metrics: Boolean(signals?.metrics?.enabled),+ });+};++const signalsOf = (serviceId: string): ServiceSignals =>+ serviceSignals.get(serviceId) ?? { logs: false, metrics: false };++/**+ * `withAccount` is false for the provider catalogue the page falls back to when+ * no account is connected: with no account there is no stored configuration, so+ * nothing can be enabled.+ */+export const servicesMetadataResponse = (+ provider: CloudProvider,+ count: number,+ withAccount: boolean,+): ListAccountServicesMetadata200 => ({+ status: 'success',+ data: {+ services: cloudServices(provider, count).map((service) => {+ const signals = signalsOf(service.id);++ return {+ id: service.id,+ title: service.title,+ icon: serviceIcon(provider, service.id),+ enabled: withAccount && (signals.logs || signals.metrics),+ };+ }),+ },+});++const LOG_ATTRIBUTES = [+ { name: 'Timestamp', path: 'timestamp', type: 'timestamp' },+ { name: 'Account Id', path: 'resources.cloud.account.id', type: 'string' },+ { name: 'Region', path: 'resources.cloud.region', type: 'string' },+ { name: 'Resource Id', path: 'resources.cloud.resource_id', type: 'string' },+ { name: 'Body', path: 'body', type: 'string' },+];++const METRICS = [+ { suffix: 'RequestCount_sum', type: 'Sum', unit: 'Count' },+ { suffix: 'Latency_avg', type: 'Gauge', unit: 'Milliseconds' },+ { suffix: 'ErrorCount_sum', type: 'Sum', unit: 'Count' },+ { suffix: 'CPUUtilization_avg', type: 'Gauge', unit: 'Percent' },+ { suffix: 'MemoryUtilization_avg', type: 'Gauge', unit: 'Percent' },+ { suffix: 'ThrottledRequests_sum', type: 'Sum', unit: 'Count' },+];++const serviceConfig = (+ provider: CloudProvider,+ service: CloudServiceSeed,+): CloudintegrationtypesServiceConfigDTO => {+ const signals = signalsOf(service.id);+ const logs = {+ enabled: signals.logs,+ // The Save button stays disabled while s3sync has logs on and no bucket+ // picked, so an enabled s3sync comes back with the bucket it was set up on.+ ...(service.id === 's3sync' && signals.logs+ ? { s3Buckets: { 'us-east-1': ['acme-cloudtrail-use1'] } }+ : {}),+ };+ const metrics = { enabled: signals.metrics };++ if (provider === 'aws') {+ return { aws: { logs, metrics } };+ }++ if (provider === 'gcp') {+ return { gcp: { logs, metrics } };+ }++ return { azure: { logs, metrics } };+};++const serviceDetail = (+ provider: CloudProvider,+ service: CloudServiceSeed,+ /** Read-only, which is the page with no account connected. */+ withAccount: boolean,+): CloudintegrationtypesServiceDTO => ({+ id: service.id,+ title: service.title,+ icon: serviceIcon(provider, service.id),+ supportedSignals: { logs: service.logs, metrics: service.metrics },+ overview: [+ `### ${service.title}`,+ '',+ `SigNoz reads ${service.title} telemetry through the ${provider.toUpperCase()} integration agent: no collector to run, no credentials to rotate. Switch a signal on and the agent starts forwarding within a few minutes.`,+ ].join('\n'),+ assets: {+ dashboards: Array.from({ length: service.dashboards }, (_, index) => ({+ title:+ index === 0+ ? `${service.title} overview`+ : `${service.title} #${index + 1}`,+ description: `Prebuilt ${service.title} dashboard, installed with the service.`,+ // The dashboards are installed with the service, so one nobody enabled+ // has none and the card is the disabled one with the tooltip.+ ...(withAccount && signalsOf(service.id).metrics+ ? {+ integrationDashboard: {+ id: `${service.id}-dashboard-${index + 1}`,+ dashboardId: `${service.id}-dashboard-${index + 1}`,+ provider,+ slug: `${service.id}-overview`,+ createdAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000).toISOString(),+ updatedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),+ },+ }+ : {}),+ })),+ },+ dataCollected: {+ logs: service.logs ? LOG_ATTRIBUTES : [],+ metrics: service.metrics+ ? METRICS.map((metric) => ({+ name: `${provider}_${service.id}_${metric.suffix}`,+ type: metric.type,+ unit: metric.unit,+ description: '',+ }))+ : [],+ },+ cloudIntegrationService: withAccount+ ? {+ id: `${provider}-${service.id}`,+ cloudIntegrationId: `${provider}-integration`,+ config: serviceConfig(provider, service),+ createdAt: new Date(Date.now() - 20 * 24 * 60 * 60 * 1000).toISOString(),+ updatedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(),+ }+ : null,+});++export const serviceResponse = (+ provider: CloudProvider,+ serviceId: string,+ withAccount: boolean,+): { status: string; data: CloudintegrationtypesServiceDTO } | null => {+ const service = findService(provider, serviceId);++ if (!service) {+ return null;+ }++ return {+ status: 'success',+ data: serviceDetail(provider, service, withAccount),+ };+};++/**+ * `IntegrationDetailPage` calls `useGetIntegration` before it decides to render+ * the cloud page, so every visit to `/integrations/{aws,azure,gcp}` asks for a+ * built-in integration under that id and throws the answer away. There is no+ * such built-in, so the backend answers 404 and the mock does too. See BUGS.md.+ */+export const BUILT_IN_INTEGRATION_NOT_FOUND = {+ status: 'error',+ errorType: 'not_found',+ error: 'integration not found',+ data: null,+};++export const credentialsResponse = (): GetConnectionCredentials200 => ({+ status: 'success',+ data: {+ ingestionKey: 'story-ingestion-key-2f9c41',+ ingestionUrl: 'https://ingest.us.signoz.cloud:443',+ sigNozApiKey: 'story-api-key-8b7d02',+ sigNozApiUrl: 'https://story.us.signoz.cloud',+ },+});++/**+ * The connection URL is what the setup flow opens in a new tab, which the story+ * reports through the navigation overlay rather than following.+ */+export const createdAccountResponse = (+ provider: CloudProvider,+): CreateAccount201 => ({+ status: 'success',+ data: {+ id: `${provider}-account-new`,+ connectionArtifact: {+ aws: {+ connectionUrl: `https://console.aws.amazon.com/cloudformation/home#/stacks/create?templateURL=https://signoz.io/${provider}.yaml`,+ },+ },+ },+});diff --git a/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.mocks.tsx b/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.mocks.tsxnew file mode 100644index 0000000000..553eb3a27e--- /dev/null+++ b/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.mocks.tsx@@ -0,0 +1,87 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import type { InstallIntegrationKeyProps } from 'types/api/integrations/types';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import {+ type IntegrationId,+ INTEGRATION_IDS,+} from '@/pages/IntegrationsModulePage/stories/__story_mockdata__/integrations';++import {+ CONNECTION_STATES,+ type ConnectionState,+ installedResponse,+ integrationResponse,+ integrationStatusResponse,+ setInstallState,+ uninstalledResponse,+} from './__story_mockdata__/integrationDetail';++const INTEGRATION = 'Integration details · integration';+const CONNECTION = 'Integration details · connection';++export const integrationDetailMocks = defineStoryMocks({+ controls: {+ integration: choiceControl<IntegrationId>('Integration', {+ group: INTEGRATION,+ description:+ 'Which integration the page is opened on. It is the last segment of the pathname, so it decides the title, the categories, the configuration steps and which of the two Data Collected tables has rows.',+ options: INTEGRATION_IDS,+ value: 'redis',+ }),+ connection: choiceControl<ConnectionState>('Connection', {+ group: CONNECTION,+ description:+ '`connected` has both signals arriving; `listening` is installed with nothing received yet; `stale` last received eleven days ago; `not-installed` has no installation, which is the only state without the removal bar.',+ options: CONNECTION_STATES,+ value: 'connected',+ }),+ },+ handlers: (_values, response) => [+ rest.post(+ 'http://localhost/api/v1/integrations/install',+ response.json(async (req) => {+ const body = (await req.json()) as InstallIntegrationKeyProps;++ setInstallState('listening');++ return installedResponse(body.integration_id);+ }),+ ),++ rest.post(+ 'http://localhost/api/v1/integrations/uninstall',+ response.json(() => {+ setInstallState('not-installed');++ return uninstalledResponse();+ }),+ ),++ rest.get(+ 'http://localhost/api/v1/integrations/:integrationId/connection_status',+ response.json((req) =>+ integrationStatusResponse(String(req.params.integrationId)),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/integrations/:integrationId',+ response.json((req) =>+ integrationResponse(String(req.params.integrationId)),+ ),+ ),+ ],+ config: (values) => ({+ route: `/integrations/${values.integration}`,+ }),+ effect: (values) => {+ setInstallState(values.connection);+ },+});diff --git a/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.tsx b/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.tsxnew file mode 100644index 0000000000..8a2d2c6b1d--- /dev/null+++ b/frontend/src/pages/IntegrationsDetailsPage/stories/IntegrationsDetailsPage.stories.tsx@@ -0,0 +1,128 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import { screen, userEvent, within } from 'storybook/test';+import ROUTES from 'constants/routes';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { integrationDetailMocks } from './IntegrationsDetailsPage.stories.mocks';+import IntegrationsDetailsPage from '../index';++type IntegrationDetailArgs = PageStoryArgs<typeof integrationDetailMocks>;++const pageStory = storyMocks(integrationDetailMocks, { layout: 'app' });++/**+ * One integration: what it collects, its install state, and the connection status+ * the agent reports back.+ *+ * Route: `/integrations/:integrationId`.+ */+const meta = {+ title: 'Pages/Integrations/Details',+ tags: ['play'],+ component: IntegrationsDetailsPage,+ // The page reads the integration id out of the pathname, so it renders under+ // its own route rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route+ path={ROUTES.INTEGRATIONS_DETAIL}+ component={IntegrationsDetailsPage}+ />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<IntegrationDetailArgs>;++export default meta;++type Story = StoryObj<IntegrationDetailArgs>;++/** The page fetches before it renders a tab, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++const clickTab = async (+ canvasElement: HTMLElement,+ label: RegExp,+): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(await canvas.findByText(label, undefined, untilLoaded));+ // The panels swap a render after the click, so the tab's own selected state+ // is what says the story has reached the tab it names.+ await canvas.findByRole('tab', { name: label, selected: true }, untilLoaded);+};++/**+ * An installed integration that is receiving data: what it collects, the+ * dashboard it ships, and when the last record arrived.+ */+export const Default: Story = {};++/**+ * An integration the workspace has not connected yet, which is the page a row+ * in the list opens for everything it has not installed: no connection banner,+ * no removal bar, and Connect in place of Test Connection.+ */+export const NotInstalled: Story = {+ args: { connection: 'not-installed' },+};++/**+ * Installed and quiet for eleven days, which the page reports rather than+ * leaving the banner on the last good state.+ */+export const NoDataSinceLong: Story = {+ args: { connection: 'stale' },+};++/** The steps for pointing a collector at the instance, one section at a time. */+export const Configure: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await clickTab(canvasElement, /^configure$/i);+ await within(canvasElement).findByText(+ /prerequisites/i,+ undefined,+ untilLoaded,+ );+ },+};++/** Every log field and metric the integration collects, as it is named. */+export const DataCollected: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await clickTab(canvasElement, /^data collected$/i);+ },+};++/**+ * The connection check on an integration that is already installed: where the+ * last record came from and when.+ */+export const TestConnection: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /test connection/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(/last recieved from/i);+ },+};++/** What removing the integration warns is left to do by hand. */+export const RemoveIntegration: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /remove from signoz/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(/you would still have to manually remove/i);+ },+};diff --git a/frontend/src/pages/IntegrationsDetailsPage/stories/__story_mockdata__/integrationDetail.ts b/frontend/src/pages/IntegrationsDetailsPage/stories/__story_mockdata__/integrationDetail.tsnew file mode 100644index 0000000000..da1e79c191--- /dev/null+++ b/frontend/src/pages/IntegrationsDetailsPage/stories/__story_mockdata__/integrationDetail.ts@@ -0,0 +1,270 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ GetIntegrationProps,+ GetIntegrationStatusProps,+ IntegrationConnectionStatus,+ IntegrationDetailedProps,+ InstalledIntegrationsSuccessResponse,+} from 'types/api/integrations/types';++import {+ findIntegrationSeed,+ type IntegrationSeed,+ SIGNOZ_AUTHOR,+} from '@/pages/IntegrationsModulePage/stories/__story_mockdata__/integrations';++export const CONNECTION_STATES = [+ 'connected',+ 'listening',+ 'stale',+ 'not-installed',+] as const;+export type ConnectionState = (typeof CONNECTION_STATES)[number];++/**+ * What the page shows is derived, not sent: `getConnectionStatesFromConnectionStatus`+ * reads the installation date and the last-received timestamps and decides+ * between connected, listening, no-data-in-a-while and not-installed. These are+ * the payloads that land on each of the four.+ */+const DAY_MS = 24 * 60 * 60 * 1000;++const installedAt = (+ state: ConnectionState,+): { installed_at: string } | null => {+ if (state === 'not-installed') {+ return null;+ }++ const daysAgo = { connected: 34, listening: 1, stale: 63 }[state];++ return { installed_at: new Date(Date.now() - daysAgo * DAY_MS).toISOString() };+};++/**+ * `last_received_from` is the resource attributes of the last matching record,+ * joined by the connection-status handler, so it reads as a list rather than a+ * host name.+ */+const signalStatus = (+ state: ConnectionState,+ receivedFrom: string,+): IntegrationConnectionStatus['logs'] => {+ if (state === 'connected') {+ return {+ last_received_ts_ms: Date.now() - 2 * 60 * 1000,+ last_received_from: receivedFrom,+ };+ }++ if (state === 'stale') {+ return {+ last_received_ts_ms: Date.now() - 11 * DAY_MS,+ last_received_from: receivedFrom,+ };+ }++ return null;+};++const connectionStatus = (+ seed: IntegrationSeed,+ state: ConnectionState,+): IntegrationConnectionStatus => ({+ logs: seed.signals.logs+ ? signalStatus(+ state,+ `host.name=ip-10-4-11-38, os.type=linux, service.name=${seed.id}`,+ )+ : null,+ metrics: seed.signals.metrics+ ? signalStatus(+ state,+ `host.name=ip-10-4-11-38, service.name=${seed.id}-exporter`,+ )+ : null,+});++const LOG_FIELDS = [+ { name: 'Timestamp', path: 'timestamp', type: 'timestamp' },+ { name: 'Severity Text', path: 'severity_text', type: 'string' },+ { name: 'Severity Number', path: 'severity_number', type: 'number' },+ { name: 'Process ID', path: 'attributes.pid', type: 'string' },+ { name: 'Request Method', path: 'attributes.request_method', type: 'string' },+ { name: 'Request Path', path: 'attributes.request_path', type: 'string' },+ { name: 'Response Status Code', path: 'attributes.status', type: 'string' },+ { name: 'Remote Address', path: 'attributes.remote_addr', type: 'string' },+];++const METRIC_FIELDS = [+ { suffix: 'operations', type: 'Sum', unit: 'number' },+ { suffix: 'connections', type: 'Sum', unit: 'number' },+ { suffix: 'cpu_time', type: 'Sum', unit: 's' },+ { suffix: 'memory_usage', type: 'Gauge', unit: 'By' },+ { suffix: 'network_io', type: 'Sum', unit: 'By' },+ { suffix: 'uptime', type: 'Sum', unit: 's' },+ { suffix: 'replication_lag', type: 'Gauge', unit: 's' },+ { suffix: 'errors', type: 'Sum', unit: 'number' },+];++/** `aws_rds_postgresql` exports `postgresql_*`, the way the exporters name them. */+const metricPrefix = (id: string): string => id.split('_').at(-1) ?? id;++const dataCollected = (+ seed: IntegrationSeed,+): { logs: unknown[]; metrics: unknown[] } => ({+ logs: seed.signals.logs ? LOG_FIELDS : [],+ metrics: seed.signals.metrics+ ? METRIC_FIELDS.map((metric) => ({+ name: `${metricPrefix(seed.id)}_${metric.suffix}`,+ type: metric.type,+ unit: metric.unit,+ }))+ : [],+});++const overview = (seed: IntegrationSeed): string =>+ [+ `### Monitor ${seed.title} with SigNoz`,+ '',+ `Ship ${seed.signals.metrics ? 'metrics and logs' : 'logs'} from your ${seed.title} instances to SigNoz through the OpenTelemetry Collector. The receiver scrapes the instance, the collector tags the records with the resource they came from, and this page reports when the last one arrived.`,+ '',+ '#### What you get',+ '',+ seed.signals.metrics+ ? '- A dashboard over throughput, connections, memory and replication'+ : '- A dashboard over request rate, status codes and upstream latency',+ '- Log parsing that pulls severity and the request fields out of each line',+ '- Connection status on this page, so a misconfigured collector is visible',+ ].join('\n');++const configurationSteps = (+ seed: IntegrationSeed,+): { title: string; instructions: string }[] => {+ const steps = [+ {+ title: 'Prerequisites',+ instructions: [+ `- ${seed.title} is reachable from the host running the collector`,+ '- OpenTelemetry Collector v0.88.0 or newer',+ '- A SigNoz ingestion key',+ ].join('\n'),+ },+ ];++ if (seed.signals.metrics) {+ steps.push({+ title: 'Collect Metrics',+ instructions: [+ `Add the ${metricPrefix(seed.id)} receiver to your collector config:`,+ '',+ '```yaml',+ 'receivers:',+ ` ${metricPrefix(seed.id)}:`,+ ' endpoint: localhost:9090',+ ' collection_interval: 60s',+ '```',+ ].join('\n'),+ });+ }++ steps.push({+ title: 'Collect Logs',+ instructions: [+ 'Point a filelog receiver at the log file and tag it so this page can find it:',+ '',+ '```yaml',+ 'receivers:',+ ' filelog:',+ ` include: ['/var/log/${metricPrefix(seed.id)}/*.log']`,+ ' operators:',+ ' - type: add',+ ' field: attributes.source',+ ` value: ${seed.id}`,+ '```',+ ].join('\n'),+ });++ return steps;+};++/**+ * `types/api/integrations/types.ts` types `configuration` as a one-element+ * tuple, `assets.dashboards` as an empty one and `data_collected` as lists of+ * strings, while the API sends N configuration steps and objects the Data+ * Collected table reads `name`, `path`, `type` and `unit` off. The payload is+ * built the way the API sends it and cast to the app's type.+ */+const integrationDetail = (+ seed: IntegrationSeed,+ state: ConnectionState,+): IntegrationDetailedProps =>+ ({+ id: seed.id,+ title: seed.title,+ description: seed.description,+ icon: seed.icon,+ author: SIGNOZ_AUTHOR,+ categories: seed.categories,+ installation: installedAt(state),+ connection_status: connectionStatus(seed, state),+ assets: {+ logs: { pipelines: [] },+ dashboards: seed.signals.metrics+ ? [{ id: `${seed.id}-overview`, title: `${seed.title} overview` }]+ : [],+ alerts: [],+ },+ overview: overview(seed),+ configuration: configurationSteps(seed),+ data_collected: dataCollected(seed),+ }) as IntegrationDetailedProps;++/**+ * Where the story's install state lives. The Connection control owns it: the+ * mocks' `effect` puts it back to what the control says on every story render,+ * and the install and uninstall handlers move it, so Connect and Remove change+ * the page instead of being answered by the control again.+ */+let installState: ConnectionState = 'connected';++export const setInstallState = (state: ConnectionState): void => {+ installState = state;+};++export const integrationResponse = (id: string): GetIntegrationProps => ({+ data: integrationDetail(findIntegrationSeed(id), installState),+});++export const integrationStatusResponse = (+ id: string,+): GetIntegrationStatusProps => ({+ data: connectionStatus(findIntegrationSeed(id), installState),+});++export const installedResponse = (+ id: string,+): { status: string; data: InstalledIntegrationsSuccessResponse['data'] } => {+ const seed = findIntegrationSeed(id);++ return {+ status: 'success',+ data: {+ id: seed.id,+ title: seed.title,+ description: seed.description,+ icon: seed.icon,+ author: SIGNOZ_AUTHOR,+ is_installed: true,+ },+ };+};++export const uninstalledResponse = (): { status: string; data: null } => ({+ status: 'success',+ data: null,+});diff --git a/frontend/src/pages/IntegrationsModulePage/stories/IntegrationsModulePage.stories.mocks.tsx b/frontend/src/pages/IntegrationsModulePage/stories/IntegrationsModulePage.stories.mocks.tsxnew file mode 100644index 0000000000..76d4980e6d--- /dev/null+++ b/frontend/src/pages/IntegrationsModulePage/stories/IntegrationsModulePage.stories.mocks.tsx@@ -0,0 +1,45 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ allIntegrationsResponse,+ INSTALLATION_MIXES,+ INTEGRATION_CATALOGUE_SIZE,+ type InstallationMix,+} from './__story_mockdata__/integrations';++const LIST = 'Integrations · list';++export const integrationsMocks = defineStoryMocks({+ controls: {+ integrations: countControl('Integrations', {+ group: LIST,+ description:+ 'Rows the list endpoint answers with. The page renders all of them; at 0 the All Integrations section keeps its heading and has no table under it.',+ value: INTEGRATION_CATALOGUE_SIZE,+ max: INTEGRATION_CATALOGUE_SIZE,+ }),+ installation: choiceControl<InstallationMix>('Installation', {+ group: LIST,+ description:+ 'Which rows come back installed, which is what the Status column reads.',+ options: INSTALLATION_MIXES,+ value: 'mixed',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/integrations',+ response.json(() =>+ allIntegrationsResponse(values.integrations, values.installation),+ ),+ ),+ ],+});diff --git a/frontend/src/pages/IntegrationsModulePage/stories/IntegrationsModulePage.stories.tsx b/frontend/src/pages/IntegrationsModulePage/stories/IntegrationsModulePage.stories.tsxnew file mode 100644index 0000000000..dd04cd1d0c--- /dev/null+++ b/frontend/src/pages/IntegrationsModulePage/stories/IntegrationsModulePage.stories.tsx@@ -0,0 +1,87 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';+import ROUTES from 'constants/routes';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { integrationsMocks } from './IntegrationsModulePage.stories.mocks';+import IntegrationsModulePage from '../IntegrationsModulePage';++type IntegrationsArgs = PageStoryArgs<typeof integrationsMocks>;++const pageStory = storyMocks(integrationsMocks, {+ route: ROUTES.INTEGRATIONS,+ layout: 'app',+});++/**+ * The integrations catalogue, installed ones first.+ *+ * Route: `/integrations`.+ */+const meta = {+ title: 'Pages/Integrations/List',+ tags: ['play'],+ component: IntegrationsModulePage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<IntegrationsArgs>;++export default meta;++type Story = StoryObj<IntegrationsArgs>;++/** The list fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++const search = async (+ canvasElement: HTMLElement,+ query: string,+): Promise<void> => {+ const input = await within(canvasElement).findByPlaceholderText(+ /search for an integration/i,+ undefined,+ untilLoaded,+ );++ await userEvent.type(input, query);+};++/**+ * The integrations a workspace can install: the three cloud providers SigNoz+ * sets up in one click, then every built-in integration with who published it+ * and whether it is installed.+ */+export const Default: Story = {};++/**+ * A search that matches nothing, which both sections answer for themselves.+ * The search filters what is already loaded, so no request goes out for it.+ */+export const NoSearchMatches: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await search(canvasElement, 'kafka');+ await within(canvasElement).findAllByText(/no integrations found/i);+ },+};++/**+ * The form for an integration SigNoz does not publish yet. Submitting it is a+ * telemetry event, not an endpoint.+ */+export const RequestIntegration: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /request integration/i,+ undefined,+ untilLoaded,+ ),+ );+ await userEvent.type(+ await screen.findByPlaceholderText(/enter integration name/i),+ 'Kafka',+ );+ },+};diff --git a/frontend/src/pages/IntegrationsModulePage/stories/__story_mockdata__/integrations.ts b/frontend/src/pages/IntegrationsModulePage/stories/__story_mockdata__/integrations.tsnew file mode 100644index 0000000000..482c96bc4d--- /dev/null+++ b/frontend/src/pages/IntegrationsModulePage/stories/__story_mockdata__/integrations.ts@@ -0,0 +1,171 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ AllIntegrationsProps,+ IntegrationsProps,+} from 'types/api/integrations/types';++export const INSTALLATION_MIXES = ['mixed', 'all', 'none'] as const;+export type InstallationMix = (typeof INSTALLATION_MIXES)[number];++/**+ * The backend base64-encodes each integration's `icon.svg` into a data URI+ * (`readFileIfUri` in `pkg/query-service/app/integrations/builtin.go`), so the+ * mocks answer with data URIs too and no story reaches for an image on a host+ * msw does not answer on.+ */+export const monogramIcon = (label: string, background: string): string => {+ const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" rx="7" fill="${background}"/><text x="16" y="21" text-anchor="middle" font-family="sans-serif" font-size="12" font-weight="700" fill="#ffffff">${label}</text></svg>`;++ return `data:image/svg+xml;base64,${btoa(svg)}`;+};++export const SIGNOZ_AUTHOR = {+ name: 'SigNoz',+ email: '[email protected]',+ homepage: 'https://signoz.io',+};++export interface IntegrationSeed {+ id: string;+ title: string;+ description: string;+ categories: readonly string[];+ icon: string;+ /** Whether the `mixed` installation value has this one already installed. */+ installed: boolean;+ /** Which of the two Data Collected tables the integration fills. */+ signals: { readonly logs: boolean; readonly metrics: boolean };+}++/**+ * The built-in integrations, ordered by id the way `BuiltInIntegrations.list`+ * sorts them, so a slice of the first N is the page the backend would answer+ * with.+ */+const INTEGRATION_CATALOGUE = [+ {+ id: 'aws_elasticache_redis',+ title: 'AWS ElastiCache (redis)',+ description: 'Monitor AWS ElastiCache with metrics and logs',+ categories: ['Database'],+ icon: monogramIcon('EC', '#8C4FFF'),+ installed: false,+ signals: { logs: true, metrics: true },+ },+ {+ id: 'aws_rds_mysql',+ title: 'AWS RDS (MySQL)',+ description: 'Monitor AWS RDS (MySQL) with metrics and logs',+ categories: ['Database'],+ icon: monogramIcon('MY', '#00758F'),+ installed: false,+ signals: { logs: true, metrics: true },+ },+ {+ id: 'aws_rds_postgresql',+ title: 'AWS RDS (PostgreSQL)',+ description: 'Monitor AWS RDS (PostgreSQL) with metrics and logs',+ categories: ['Database'],+ icon: monogramIcon('RDS', '#2F6FAF'),+ installed: true,+ signals: { logs: true, metrics: true },+ },+ {+ id: 'clickhouse',+ title: 'Clickhouse',+ description: 'Monitor Clickhouse with metrics and logs',+ categories: ['Database'],+ icon: monogramIcon('CH', '#C7770B'),+ installed: false,+ signals: { logs: true, metrics: true },+ },+ {+ id: 'mongo',+ title: 'Mongo',+ description: 'Monitor mongo using logs and metrics.',+ categories: ['Database'],+ icon: monogramIcon('MG', '#13AA52'),+ installed: true,+ signals: { logs: true, metrics: true },+ },+ {+ id: 'nginx',+ title: 'Nginx',+ description: 'Monitor nginx using logs and metrics.',+ categories: ['Ingress', 'HTTP'],+ icon: monogramIcon('NX', '#009639'),+ installed: true,+ signals: { logs: true, metrics: false },+ },+ {+ id: 'postgres',+ title: 'PostgreSQL',+ description: 'Monitor Postgres with metrics and logs',+ categories: ['Database'],+ icon: monogramIcon('PG', '#336791'),+ installed: false,+ signals: { logs: true, metrics: true },+ },+ {+ id: 'redis',+ title: 'Redis',+ description: 'Monitor redis with metrics and logs',+ categories: ['Database'],+ icon: monogramIcon('RD', '#C6302B'),+ installed: true,+ signals: { logs: true, metrics: true },+ },+] as const satisfies readonly IntegrationSeed[];++export type IntegrationId = (typeof INTEGRATION_CATALOGUE)[number]['id'];++export const INTEGRATION_IDS: readonly IntegrationId[] =+ INTEGRATION_CATALOGUE.map((seed) => seed.id);++export const INTEGRATION_CATALOGUE_SIZE = INTEGRATION_CATALOGUE.length;++export const findIntegrationSeed = (id: string): IntegrationSeed =>+ INTEGRATION_CATALOGUE.find((seed) => seed.id === id) ??+ INTEGRATION_CATALOGUE[0];++const isInstalled = (+ seed: IntegrationSeed,+ installation: InstallationMix,+): boolean => {+ if (installation === 'all') {+ return true;+ }+ if (installation === 'none') {+ return false;+ }++ return seed.installed;+};++const summary = (+ seed: IntegrationSeed,+ installation: InstallationMix,+): IntegrationsProps => ({+ id: seed.id,+ title: seed.title,+ description: seed.description,+ icon: seed.icon,+ author: SIGNOZ_AUTHOR,+ is_installed: isInstalled(seed, installation),+});++export const allIntegrationsResponse = (+ count: number,+ installation: InstallationMix,+): AllIntegrationsProps => ({+ status: 'success',+ data: {+ integrations: INTEGRATION_CATALOGUE.slice(0, count).map((seed) =>+ summary(seed, installation),+ ),+ },+});diff --git a/frontend/src/pages/LLMObservability/AttributeMapping/stories/AttributeMapping.stories.mocks.tsx b/frontend/src/pages/LLMObservability/AttributeMapping/stories/AttributeMapping.stories.mocks.tsxnew file mode 100644index 0000000000..6a7bcc26cd--- /dev/null+++ b/frontend/src/pages/LLMObservability/AttributeMapping/stories/AttributeMapping.stories.mocks.tsx@@ -0,0 +1,43 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ MAPPING_GROUP_MAX,+ spanMapperGroupsResponse,+ wideConditionGroupsResponse,+} from './__story_mockdata__/attributeMapping';++const GROUPS = 'Attribute mapping · groups';++export const wideConditionGroup = rest.get(+ 'http://localhost/api/v1/span_mapper_groups',+ (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(wideConditionGroupsResponse())),+);++export const attributeMappingMocks = defineStoryMocks({+ controls: {+ groups: countControl('Mapping groups', {+ group: GROUPS,+ description:+ 'Groups the list has, one per SDK whose attributes are remapped. Zero is a workspace that has not set any up.',+ value: 3,+ max: MAPPING_GROUP_MAX,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/span_mapper_groups',+ response.json(() => spanMapperGroupsResponse(values.groups)),+ ),+ ],+ config: () => ({ route: ROUTES.AI_OBSERVABILITY_ATTRIBUTE_MAPPING }),+});diff --git a/frontend/src/pages/LLMObservability/AttributeMapping/stories/AttributeMapping.stories.tsx b/frontend/src/pages/LLMObservability/AttributeMapping/stories/AttributeMapping.stories.tsxnew file mode 100644index 0000000000..c43534020d--- /dev/null+++ b/frontend/src/pages/LLMObservability/AttributeMapping/stories/AttributeMapping.stories.tsx@@ -0,0 +1,71 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import LLMObservabilityPage from '../../index';+import {+ attributeMappingMocks,+ wideConditionGroup,+} from './AttributeMapping.stories.mocks';++type AttributeMappingArgs = PageStoryArgs<typeof attributeMappingMocks>;++const pageStory = storyMocks(attributeMappingMocks, { layout: 'app' });++/**+ * Mapping groups that tell SigNoz which span attributes carry LLM data, and the+ * tab that tests a mapping against a sample span. Managing a group is gated on an+ * authz permission rather than a role.+ *+ * Route: `/ai-observability/attribute-mapping`.+ */+const meta = {+ title: 'Pages/AI Observability/Attribute Mapping',+ tags: ['authz', 'play'],+ component: LLMObservabilityPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<AttributeMappingArgs>;++export default meta;++type Story = StoryObj<AttributeMappingArgs>;++/**+ * The rules that bring another SDK's span attributes onto the `gen_ai.*` names+ * the rest of AI observability reads.+ */+export const Default: Story = {};++/** No mapping set up yet, which is what a workspace on plain OTel stays on. */+export const NoGroups: Story = {+ args: { groups: 0 },+};++/**+ * The conditions tooltip on every group header, held open: what a span has to+ * carry for the group to run. The first group matches on far more keys than the+ * tab's own fixture, so the Mapping groups control does not reach this story.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+ parameters: { msw: { handlers: [wideConditionGroup] } },+};++/**+ * The first mapping group's own menu, open: edit the group, clone it, delete it.+ */+export const GroupActionsMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const [first] = await within(canvasElement).findAllByRole(+ 'button',+ { name: 'Group actions' },+ { timeout: 10000 },+ );++ await userEvent.click(first);+ await screen.findByRole('menu');+ },+};diff --git a/frontend/src/pages/LLMObservability/AttributeMapping/stories/__story_mockdata__/attributeMapping.ts b/frontend/src/pages/LLMObservability/AttributeMapping/stories/__story_mockdata__/attributeMapping.tsnew file mode 100644index 0000000000..c6c02ff281--- /dev/null+++ b/frontend/src/pages/LLMObservability/AttributeMapping/stories/__story_mockdata__/attributeMapping.ts@@ -0,0 +1,112 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ ListSpanMapperGroups200,+ SpantypesSpanMapperGroupConditionKeyDTO,+ SpantypesSpanMapperGroupDTO,+} from 'api/generated/services/sigNoz.schemas';+import { SpantypesSpanMapperOriginDTO } from 'api/generated/services/sigNoz.schemas';++const ORG_ID = 'org-signoz';++interface GroupSeed {+ name: string;+ attributes: string[];+ enabled: boolean;+}++/**+ * A group is a condition over span attributes plus the mappings that apply once+ * it matches, which is how a non-OTel SDK's field names are brought onto the+ * `gen_ai.*` names the rest of the product reads.+ */+const GROUPS: GroupSeed[] = [+ {+ name: 'LangChain callbacks',+ attributes: ['langchain.model', 'langchain.prompt_tokens'],+ enabled: true,+ },+ {+ name: 'LlamaIndex spans',+ attributes: ['llamaindex.llm', 'llamaindex.token_count'],+ enabled: true,+ },+ {+ name: 'Vendor SDK (legacy)',+ attributes: ['ai.model_id', 'ai.usage.tokens'],+ enabled: false,+ },+];++export const MAPPING_GROUP_MAX = GROUPS.length;++const conditionKeys = (+ values: readonly string[],+): SpantypesSpanMapperGroupConditionKeyDTO[] =>+ values.map((value) => ({ value, enabled: true }));++const group = (+ seed: GroupSeed,+ index: number,+): SpantypesSpanMapperGroupDTO => ({+ id: `group-${index + 1}`,+ orgId: ORG_ID,+ name: seed.name,+ enabled: seed.enabled,+ origin: SpantypesSpanMapperOriginDTO.user,+ version: 1,+ condition: { attributes: conditionKeys(seed.attributes), resource: null },+ createdAt: '2026-07-18T11:20:00Z',+ createdBy: '[email protected]',+ updatedAt: '2026-08-05T08:40:00Z',+ updatedBy: '[email protected]',+});++export const spanMapperGroupsResponse = (+ count: number,+): ListSpanMapperGroups200 => ({+ status: 'success',+ data: { items: GROUPS.slice(0, count).map(group) },+});++const MANY_ATTRIBUTES = [+ 'langchain.model',+ 'langchain.prompt_tokens',+ 'langchain.completion_tokens',+ 'langchain.chain.name',+ 'langchain.chain.run_id',+ 'langchain.retriever.source',+ 'langchain.tool.invocation',+ 'langchain.callbacks.handler_name',+];++const MANY_RESOURCE_KEYS = [+ 'service.namespace',+ 'deployment.environment.name',+ 'telemetry.sdk.language',+];++/** The first group's condition widened to far more keys than its own fixture. */+export const wideConditionGroupsResponse = (): ListSpanMapperGroups200 => {+ const list = spanMapperGroupsResponse(MAPPING_GROUP_MAX);++ return {+ ...list,+ data: {+ items: list.data.items?.map((item, index) =>+ index === 0+ ? {+ ...item,+ condition: {+ attributes: conditionKeys(MANY_ATTRIBUTES),+ resource: conditionKeys(MANY_RESOURCE_KEYS),+ },+ }+ : item,+ ),+ },+ };+};diff --git a/frontend/src/pages/LLMObservability/Explorer/stories/Explorer.stories.mocks.tsx b/frontend/src/pages/LLMObservability/Explorer/stories/Explorer.stories.mocks.tsxnew file mode 100644index 0000000000..a61d4af3e2--- /dev/null+++ b/frontend/src/pages/LLMObservability/Explorer/stories/Explorer.stories.mocks.tsx@@ -0,0 +1,221 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import { ExplorerViews } from 'pages/LogsExplorer/utils';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';+import { explorerViewToPanelType } from 'utils/explorerUtils';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import { fieldValuesResponse } from '@/storybook/msw/__story_mockdata__/fields';+import {+ queryRangeV5RawResponse,+ queryRangeV5ScalarResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++// The tab renders the traces explorer over `DataSource.TRACES`, so it asks the+// same endpoints for the same shapes and answers from the traces builders.+import {+ exportDashboardsResponse,+ savedTraceViewsResponse,+ traceAttributeValuesResponse,+ traceFieldKeysResponse,+ traceFieldValues,+ traceQuickFiltersResponse,+ traceRootSpanRows,+ traceSpanRows,+ TRACES_EXPLORER_VIEWS,+} from '../../../TracesModulePage/stories/__story_mockdata__/traces';++const VIEW = 'Explorer · view';+const LIST = 'Explorer · list';+const FILTERS = 'Explorer · filters';+const SAVED = 'Explorer · saved';++const explorerRoute = (view: ExplorerViews): string => {+ const params = new URLSearchParams({+ [QueryParams.panelTypes]: JSON.stringify(explorerViewToPanelType[view]),+ [QueryParams.selectedExplorerView]: view,+ });++ return `${ROUTES.AI_OBSERVABILITY_EXPLORER}?${params.toString()}`;+};++interface RawQuerySpec {+ limit?: number;+ offset?: number;+}++const rawSpecOf = (body: QueryRangeRequestV5): RawQuerySpec => {+ const spec = body.compositeQuery?.queries?.[0]?.spec ?? {};++ return spec as RawQuerySpec;+};++export const llmExplorerMocks = defineStoryMocks({+ controls: {+ view: choiceControl<ExplorerViews>('Explorer view', {+ group: VIEW,+ description:+ 'Which of the explorer views renders: spans, root spans, a chart or an aggregation table.',+ options: TRACES_EXPLORER_VIEWS,+ value: ExplorerViews.LIST,+ }),+ spans: countControl('Spans', {+ group: LIST,+ description:+ 'LLM spans the endpoint has, one root span per trace in the Trace view. The table asks for a page at a time, so a higher count paginates.',+ value: 24,+ max: 40,+ }),+ errors: toggleControl('Failing spans', {+ group: LIST,+ description:+ 'Answers 503 on the spans of the services that fail, which is what the status column and the error colouring read.',+ value: true,+ }),+ warning: toggleControl('Query warning', {+ group: LIST,+ description: 'Attaches a warning to the response, next to the toolbar.',+ value: false,+ }),+ quickFilters: countControl('Quick filters', {+ group: FILTERS,+ description:+ 'Filters the org has configured for traces. At 0 the panel shows its empty state.',+ value: 6,+ max: 8,+ }),+ savedViews: countControl('Saved views', {+ group: SAVED,+ description: 'Fills the views dropdown the explorer options offer.',+ value: 4,+ max: 8,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/quick_filters/:source',+ response.json(() => traceQuickFiltersResponse(values.quickFilters)),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ traceFieldKeysResponse(req.url.searchParams.get('searchText')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(traceFieldValues(req.url.searchParams.get('name'))),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/ai_observability/fields/keys',+ response.json((req) =>+ traceFieldKeysResponse(req.url.searchParams.get('searchText')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/ai_observability/fields/values',+ response.json((req) =>+ fieldValuesResponse(traceFieldValues(req.url.searchParams.get('name'))),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ traceAttributeValuesResponse(req.url.searchParams.get('attributeKey')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/explorer/views',+ response.json(() => savedTraceViewsResponse(values.savedViews)),+ ),++ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json(exportDashboardsResponse),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const { start, end, requestType } = body;+ const { limit = 10, offset = 0 } = rawSpecOf(body);++ const rows = {+ count: values.spans,+ offset,+ limit,+ start,+ end,+ errors: values.errors,+ };++ const warning = values.warning+ ? {+ code: 'storybook_warning',+ message: 'Query scanned more rows than the limit allows.',+ url: '',+ warnings: [],+ }+ : undefined;++ if (requestType === 'raw' || requestType === 'trace') {+ return queryRangeV5RawResponse(+ requestType === 'trace' ? traceRootSpanRows(rows) : traceSpanRows(rows),+ {+ type: requestType,+ hasMore: offset + limit < values.spans,+ warning,+ },+ );+ }++ if (requestType === 'scalar') {+ return queryRangeV5ScalarResponse(values.spans, 'A', { warning });+ }++ return queryRangeV5TimeSeriesResponse(+ [+ {+ queryName: 'A',+ series: [+ {+ labels: [],+ values: timeSeriesPoints({+ start,+ end,+ base: 420,+ amplitude: 120,+ }),+ },+ ],+ },+ ],+ { warning },+ );+ }),+ ),+ ],+ config: (values) => ({ route: explorerRoute(values.view) }),+});diff --git a/frontend/src/pages/LLMObservability/Explorer/stories/Explorer.stories.tsx b/frontend/src/pages/LLMObservability/Explorer/stories/Explorer.stories.tsxnew file mode 100644index 0000000000..fb86f6c791--- /dev/null+++ b/frontend/src/pages/LLMObservability/Explorer/stories/Explorer.stories.tsx@@ -0,0 +1,159 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { ExplorerViews } from 'pages/LogsExplorer/utils';+import { expect, screen, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import LLMObservabilityPage from '../../index';+import { llmExplorerMocks } from './Explorer.stories.mocks';++type LLMExplorerArgs = PageStoryArgs<typeof llmExplorerMocks>;++const pageStory = storyMocks(llmExplorerMocks, { layout: 'app' });++/**+ * The AI observability explorer: the traces explorer scoped to LLM spans, with+ * the query builder, the view switcher and the quick filters beside it. The+ * view is driven by the URL, so the control below is what switches it.+ *+ * Route: `/ai-observability/explorer`.+ */+const meta = {+ title: 'Pages/AI Observability/Explorer',+ tags: ['play'],+ component: LLMObservabilityPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<LLMExplorerArgs>;++export default meta;++type Story = StoryObj<LLMExplorerArgs>;++/** The page fetches before it renders a filter, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The quick-filter panel has no test id of its own, and it only mounts once the+ * workspace's filters have answered.+ */+const selectFirstQuickFilterValue = async (+ canvasElement: HTMLElement,+): Promise<void> => {+ const panel = await waitFor(() => {+ const found = canvasElement.querySelector<HTMLElement>('.quick-filters');++ if (!found) {+ throw new Error('Quick filters did not render');+ }++ return found;+ }, untilLoaded);++ const [filter] = await within(panel).findAllByTestId(+ 'checkbox-filter-v2',+ undefined,+ untilLoaded,+ );++ const [row] = await within(filter).findAllByTestId(+ /^checkbox-value-row-/,+ undefined,+ untilLoaded,+ );+ const value = row.dataset.testid?.replace('checkbox-value-row-', '');++ // Every value starts selected, so the checkbox only excludes one; the row+ // itself is the "Only" action that narrows the query to a single value.+ await userEvent.click(within(row).getByRole('button'));+ // The rows remount around the new query and regroup into sections, so they+ // are looked up again on every attempt rather than held from before the click.+ await waitFor(() => {+ const selected = within(filter).getByTestId('section-selected');++ expect(+ within(selected)+ .getAllByTestId(/^checkbox-value-row-/)+ .map((item) => item.dataset.testid),+ ).toEqual([`checkbox-value-row-${value}`]);+ }, untilLoaded);+};++const openQuickFiltersSettings = async (): Promise<void> => {+ // The settings control renders disabled while its permission check is in+ // flight and is swapped for the enabled one once the check answers, so it is+ // looked up again on every attempt; a click on the disabled one is dropped in+ // silence.+ const control = await waitFor(() => {+ const settings = screen.getByTestId('settings-icon-container');++ expect(settings).toBeEnabled();++ return settings;+ }, untilLoaded);++ await userEvent.click(control);+ await screen.findByText('Edit quick filters', undefined, untilLoaded);+};++/**+ * A full window of LLM spans: the org's quick filters down the left, the query+ * builder and the view switcher above, and the list paging ten spans at a time+ * with the failing ones answering 503.+ */+export const Default: Story = {};++/**+ * The Trace view, which shows one row per trace: its root span, the root+ * duration and how many spans the trace has.+ */+export const RootSpans: Story = {+ args: { view: ExplorerViews.TRACE },+};++/**+ * The time series view, which charts the spans the query matches instead of+ * listing them.+ */+export const TimeSeries: Story = {+ args: { view: ExplorerViews.TIMESERIES },+};++/**+ * A workspace with the SDK wired up but no LLM spans in the window, and no+ * quick filters configured yet, so the list and the filter panel both show+ * their empty states.+ */+export const NoSpans: Story = {+ args: { spans: 0, quickFilters: 0, savedViews: 0 },+};++/** The list mid-query, with the cancel action the toolbar offers while it runs. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** A query response carrying the backend's warning details. */+export const QueryWarning: Story = {+ args: { warning: true },+};++/** A failed explorer request. */+export const Failed: Story = {+ args: { dataState: 'error' },+ // The failure is the state under test, so its console errors are expected.+ parameters: { allowConsoleErrors: true },+};++/** The editable quick-filter settings panel. */+export const QuickFiltersSettings: Story = {+ play: openQuickFiltersSettings,+};++/** A quick-filter value selected against the LLM span query. */+export const QuickFilterSelected: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await selectFirstQuickFilterValue(canvasElement);+ },+};diff --git a/frontend/src/pages/LLMObservability/ModelPricing/stories/ModelPricing.stories.mocks.tsx b/frontend/src/pages/LLMObservability/ModelPricing/stories/ModelPricing.stories.mocks.tsxnew file mode 100644index 0000000000..844491e12f--- /dev/null+++ b/frontend/src/pages/LLMObservability/ModelPricing/stories/ModelPricing.stories.mocks.tsx@@ -0,0 +1,57 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ PRICING_RULE_MAX,+ pricingRulesResponse,+ UNPRICED_MODEL_MAX,+ unmappedModelsResponse,+} from './__story_mockdata__/modelPricing';++const RULES = 'Model pricing · rules';++export const modelPricingMocks = defineStoryMocks({+ controls: {+ rules: countControl('Pricing rules', {+ group: RULES,+ description:+ 'Rows the model costs table has. Every fourth is a user override, which is what the source filter splits on.',+ value: 10,+ max: PRICING_RULE_MAX,+ }),+ unpricedModels: countControl('Unpriced models', {+ group: RULES,+ description:+ 'Models seen in traces that no rule matches: the count on the tab badge, and the rows behind it.',+ value: 3,+ max: UNPRICED_MODEL_MAX,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/llm_pricing_rules/unmapped_models',+ response.json(() => unmappedModelsResponse(values.unpricedModels)),+ ),+ rest.get(+ 'http://localhost/api/v1/llm_pricing_rules',+ response.json((req) => {+ const isOverride = req.url.searchParams.get('isOverride');++ return pricingRulesResponse(values.rules, {+ offset: Number(req.url.searchParams.get('offset') ?? 0),+ limit: Number(req.url.searchParams.get('limit') ?? 20),+ overridesOnly: isOverride === 'true',+ });+ }),+ ),+ ],+ config: () => ({ route: ROUTES.AI_OBSERVABILITY_CONFIGURATION }),+});diff --git a/frontend/src/pages/LLMObservability/ModelPricing/stories/ModelPricing.stories.tsx b/frontend/src/pages/LLMObservability/ModelPricing/stories/ModelPricing.stories.tsxnew file mode 100644index 0000000000..d7c2fd685e--- /dev/null+++ b/frontend/src/pages/LLMObservability/ModelPricing/stories/ModelPricing.stories.tsx@@ -0,0 +1,56 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import LLMObservabilityPage from '../../index';+import { modelPricingMocks } from './ModelPricing.stories.mocks';++type ModelPricingArgs = PageStoryArgs<typeof modelPricingMocks>;++const pageStory = storyMocks(modelPricingMocks, { layout: 'app' });++/**+ * Per model token pricing, plus the models seen in spans that no rule prices yet.+ *+ * Route: `/ai-observability/configuration`.+ */+const meta = {+ title: 'Pages/AI Observability/Model Pricing',+ tags: ['play'],+ component: LLMObservabilityPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ModelPricingArgs>;++export default meta;++type Story = StoryObj<ModelPricingArgs>;++/**+ * What every model costs per million tokens, which is what the spend on the+ * overview is computed from.+ */+export const Default: Story = {};++/** Nothing priced yet, with every model the workspace calls still unmatched. */+export const NothingPriced: Story = {+ args: { rules: 0 },+};++/**+ * The first pricing rule's menu, open over the table: edit the rule or drop it.+ */+export const ModelCostActionsMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const [first] = await within(canvasElement).findAllByRole(+ 'button',+ { name: 'Model cost actions' },+ { timeout: 10000 },+ );++ await userEvent.click(first);+ await screen.findByRole('menu');+ },+};diff --git a/frontend/src/pages/LLMObservability/ModelPricing/stories/__story_mockdata__/modelPricing.ts b/frontend/src/pages/LLMObservability/ModelPricing/stories/__story_mockdata__/modelPricing.tsnew file mode 100644index 0000000000..594c7e66b3--- /dev/null+++ b/frontend/src/pages/LLMObservability/ModelPricing/stories/__story_mockdata__/modelPricing.ts@@ -0,0 +1,115 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ ListLLMPricingRules200,+ ListUnmappedLLMModels200,+ LlmpricingruletypesLLMPricingRuleDTO,+} from 'api/generated/services/sigNoz.schemas';+import {+ LlmpricingruletypesLLMPricingRuleCacheModeDTO,+ LlmpricingruletypesLLMPricingRuleUnitDTO,+} from 'api/generated/services/sigNoz.schemas';++const ORG_ID = 'org-signoz';++interface ModelSeed {+ provider: string;+ modelName: string;+ input: number;+ output: number;+}++/** Prices are dollars per million tokens, which is the only unit the rules have. */+const CATALOGUE: ModelSeed[] = [+ { provider: 'openai', modelName: 'gpt-4o', input: 2.5, output: 10 },+ { provider: 'openai', modelName: 'gpt-4o-mini', input: 0.15, output: 0.6 },+ { provider: 'openai', modelName: 'o3', input: 2, output: 8 },+ { provider: 'anthropic', modelName: 'claude-sonnet-4', input: 3, output: 15 },+ { provider: 'anthropic', modelName: 'claude-haiku-4', input: 0.8, output: 4 },+ { provider: 'google', modelName: 'gemini-2.5-pro', input: 1.25, output: 10 },+ { provider: 'google', modelName: 'gemini-2.5-flash', input: 0.3, output: 2.5 },+ { provider: 'meta', modelName: 'llama-3.1-70b', input: 0.6, output: 0.6 },+ { provider: 'mistral', modelName: 'mistral-large', input: 2, output: 6 },+ { provider: 'cohere', modelName: 'command-r-plus', input: 2.5, output: 10 },+];++export const PRICING_RULE_MAX = CATALOGUE.length;++/**+ * A rule the org wrote itself is an override; the rest are the catalogue SigNoz+ * ships and syncs, which is what the source filter splits the table by.+ */+const isOverride = (index: number): boolean => index % 4 === 0;++const rule = (+ seed: ModelSeed,+ index: number,+): LlmpricingruletypesLLMPricingRuleDTO => ({+ id: `rule-${seed.modelName}`,+ orgId: ORG_ID,+ enabled: true,+ isOverride: isOverride(index),+ modelName: seed.modelName,+ modelPattern: [`${seed.modelName}*`],+ provider: seed.provider,+ unit: LlmpricingruletypesLLMPricingRuleUnitDTO.per_million_tokens,+ pricing: {+ input: seed.input,+ output: seed.output,+ cache: {+ mode: LlmpricingruletypesLLMPricingRuleCacheModeDTO.subtract,+ read: seed.input / 10,+ write: seed.input * 1.25,+ },+ },+ sourceId: isOverride(index) ? undefined : 'signoz-catalogue',+ syncedAt: isOverride(index) ? null : '2026-08-01T00:00:00Z',+ createdAt: '2026-07-04T09:15:00Z',+ createdBy: '[email protected]',+ updatedAt: '2026-08-01T00:00:00Z',+ updatedBy: '[email protected]',+});++export interface PricingRulesQuery {+ offset: number;+ limit: number;+ overridesOnly?: boolean;+}++export const pricingRulesResponse = (+ count: number,+ { offset, limit, overridesOnly }: PricingRulesQuery,+): ListLLMPricingRules200 => {+ const rules = CATALOGUE.slice(0, count)+ .map(rule)+ .filter((candidate) => !overridesOnly || candidate.isOverride);++ return {+ status: 'success',+ data: {+ items: rules.slice(offset, offset + limit),+ total: rules.length,+ offset,+ limit,+ },+ };+};++const UNPRICED = [+ { modelName: 'gpt-5-preview', provider: 'openai', spanCount: 18_420 },+ { modelName: 'claude-opus-5', provider: 'anthropic', spanCount: 6_310 },+ { modelName: 'deepseek-r2', provider: 'deepseek', spanCount: 940 },+];++export const UNPRICED_MODEL_MAX = UNPRICED.length;++/** Models seen in the last hour of traces that no rule's pattern matches. */+export const unmappedModelsResponse = (+ count: number,+): ListUnmappedLLMModels200 => ({+ status: 'success',+ data: { items: UNPRICED.slice(0, count) },+});diff --git a/frontend/src/pages/LLMObservability/Overview/stories/Overview.stories.mocks.tsx b/frontend/src/pages/LLMObservability/Overview/stories/Overview.stories.mocks.tsxnew file mode 100644index 0000000000..c1e7054aff--- /dev/null+++ b/frontend/src/pages/LLMObservability/Overview/stories/Overview.stories.mocks.tsx@@ -0,0 +1,79 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { StatusCodes } from 'http-status-codes';+import ROUTES from 'constants/routes';+import { rest } from 'msw';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ LLM_ENVIRONMENTS,+ LLM_MODELS,+ LLM_SERVICES,+ llmPanelResponse,+} from './__story_mockdata__/llmOverview';++const PANELS = 'AI overview · panels';++/**+ * The dashboard itself is bundled with the app rather than fetched, so the only+ * thing left to answer is the panels, the variables and the share state its+ * header reads.+ */+export const llmOverviewMocks = defineStoryMocks({+ controls: {+ series: countControl('Breakdown series', {+ group: PANELS,+ description:+ 'Lines or rows a broken-down panel carries: one per model, error type or span name. Zero is a workspace with no LLM spans yet.',+ value: 4,+ max: 5,+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) =>+ llmPanelResponse((await req.json()) as QueryRangeRequestV5, values.series),+ ),+ ),+ rest.post(+ 'http://localhost/api/v2/variables/query',+ response.json(async (req) => {+ const body = (await req.json()) as { name?: string };+ const byName: Record<string, string[]> = {+ model: LLM_MODELS,+ environment: LLM_ENVIRONMENTS,+ service_name: LLM_SERVICES,+ };++ return {+ status: 'success',+ data: { variableValues: byName[body.name ?? ''] ?? LLM_MODELS },+ };+ }),+ ),+ // The header reads the share state on every load, so it answers even while+ // the panels are held in the loading or failed state.+ rest.get('http://localhost/api/v1/dashboards/:id/public', (_req, res, ctx) =>+ res(+ ctx.status(StatusCodes.NOT_FOUND),+ ctx.json({+ status: 'error',+ error: {+ code: 'public_dashboard_not_found',+ message: "the AI observability overview isn't public",+ url: '',+ errors: [],+ },+ }),+ ),+ ),+ ],+ config: () => ({ route: ROUTES.AI_OBSERVABILITY_OVERVIEW }),+});diff --git a/frontend/src/pages/LLMObservability/Overview/stories/Overview.stories.tsx b/frontend/src/pages/LLMObservability/Overview/stories/Overview.stories.tsxnew file mode 100644index 0000000000..e4ba27fe86--- /dev/null+++ b/frontend/src/pages/LLMObservability/Overview/stories/Overview.stories.tsx@@ -0,0 +1,41 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import LLMObservabilityPage from '../../index';+import { llmOverviewMocks } from './Overview.stories.mocks';++type LLMOverviewArgs = PageStoryArgs<typeof llmOverviewMocks>;++const pageStory = storyMocks(llmOverviewMocks, { layout: 'app' });++/**+ * The AI observability overview: cost, token and latency panels over+ * `query_range`.+ *+ * Route: `/ai-observability/overview`.+ */+const meta = {+ title: 'Pages/AI Observability/Overview',+ component: LLMObservabilityPage,+ ...pageStory,+ // The header's public-dashboard lookup is expected to 404, so every story opts out.+ parameters: { ...pageStory.parameters, allowConsoleErrors: true },+} satisfies Meta<LLMOverviewArgs>;++export default meta;++type Story = StoryObj<LLMOverviewArgs>;++/**+ * The bundled overview dashboard: spend, tokens, latency and errors across+ * every model the workspace calls, scoped by the model, environment and+ * service variables above it.+ */+export const Default: Story = {};++/** A workspace with the SDK wired up but no LLM spans yet. */+export const NoSpans: Story = {+ args: { series: 0 },+};diff --git a/frontend/src/pages/LLMObservability/Overview/stories/__story_mockdata__/llmOverview.ts b/frontend/src/pages/LLMObservability/Overview/stories/__story_mockdata__/llmOverview.tsnew file mode 100644index 0000000000..16883c3931--- /dev/null+++ b/frontend/src/pages/LLMObservability/Overview/stories/__story_mockdata__/llmOverview.ts@@ -0,0 +1,163 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ MetricRangePayloadV5,+ QueryRangeRequestV5,+} from 'types/api/v5/queryRange';++import {+ queryRangeV5EmptyResponse,+ queryRangeV5ScalarResponse,+ queryRangeV5ScalarTableResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++export const LLM_MODELS = [+ 'gpt-4o',+ 'claude-sonnet-4',+ 'gemini-2.5-pro',+ 'llama-3.1-70b',+];++export const LLM_ENVIRONMENTS = ['production', 'staging'];++export const LLM_SERVICES = ['assistant-api', 'summarizer', 'rag-indexer'];++const ERROR_TYPES = ['rate_limit', 'context_length', 'upstream_timeout'];++const SPAN_NAMES = [+ 'chat gpt-4o',+ 'chat claude-sonnet-4',+ 'embeddings text-embedding-3-large',+ 'tool web_search',+ 'tool sql_query',+];++/** The three group-by keys every panel on this dashboard breaks down by. */+const GROUP_VALUES: Record<string, readonly string[]> = {+ 'gen_ai.request.model': LLM_MODELS,+ 'gen_ai.error.type': ERROR_TYPES,+ name: SPAN_NAMES,+};++interface PanelSpec {+ requestType: string;+ groupBy?: string;+ /** How many aggregations the query asked for, which is a column each. */+ aggregations: string[];+ start: number;+ end: number;+}++const readPanel = (body: QueryRangeRequestV5): PanelSpec => {+ const spec = body.compositeQuery?.queries?.[0]?.spec as+ | {+ groupBy?: Array<{ name: string }>;+ aggregations?: Array<{ expression?: string }>;+ }+ | undefined;++ return {+ requestType: body.requestType ?? 'time_series',+ groupBy: spec?.groupBy?.[0]?.name,+ aggregations: (spec?.aggregations ?? [{}]).map(+ (aggregation) => aggregation.expression ?? '',+ ),+ start: body.start,+ end: body.end,+ };+};++const valuesFor = (groupBy: string, count: number): string[] =>+ (GROUP_VALUES[groupBy] ?? LLM_MODELS).slice(0, count);++/**+ * The single-number tiles all come back as one scalar, so the figure is read off+ * what the tile aggregates rather than being the same everywhere.+ */+const SCALAR_BY_AGGREGATION: Array<[string, number]> = [+ ['gen_ai.usage.cost', 1_284.37],+ ['gen_ai.usage', 48_216_400],+ ['gen_ai.server.ttft', 412],+ ['duration_nano', 2_840_000_000],+ ['has_error', 0.021],+];++const scalarFor = (aggregations: string[]): number => {+ const expression = aggregations.join(' ');+ const match = SCALAR_BY_AGGREGATION.find(([needle]) =>+ expression.includes(needle),+ );++ return match ? match[1] : 812.6;+};++/**+ * Every panel names its query `A`, so the request is what tells them apart: the+ * request type says number, table or chart, the group-by says which breakdown+ * the legend carries, and the aggregations say how many columns a table has.+ */+export const llmPanelResponse = (+ body: QueryRangeRequestV5,+ seriesCount: number,+): MetricRangePayloadV5 => {+ const { requestType, groupBy, aggregations, start, end } = readPanel(body);++ if (seriesCount === 0) {+ return queryRangeV5EmptyResponse();+ }++ if (requestType === 'scalar') {+ if (groupBy) {+ return queryRangeV5ScalarTableResponse({+ groupBy: [groupBy],+ aggregations: aggregations.map((_unused, index) => ({+ queryName: 'A',+ aggregationIndex: index,+ })),+ rows: valuesFor(groupBy, seriesCount).map((value, rowIndex) => [+ value,+ ...aggregations.map(+ (_unused, index) => 4_180 - rowIndex * 620 + index * 940,+ ),+ ]),+ });+ }++ return queryRangeV5ScalarResponse(scalarFor(aggregations));+ }++ if (!groupBy) {+ return queryRangeV5TimeSeriesResponse([+ {+ queryName: 'A',+ series: [+ {+ labels: [],+ values: timeSeriesPoints({ start, end, base: 640, amplitude: 180 }),+ },+ ],+ },+ ]);+ }++ return queryRangeV5TimeSeriesResponse([+ {+ queryName: 'A',+ series: valuesFor(groupBy, seriesCount).map((value, index) => ({+ labels: [{ key: { name: groupBy }, value }],+ values: timeSeriesPoints({+ start,+ end,+ base: 520 - index * 90,+ amplitude: 140,+ seed: index * 4,+ }),+ })),+ },+ ]);+};diff --git a/frontend/src/pages/License/stories/License.stories.mocks.tsx b/frontend/src/pages/License/stories/License.stories.mocks.tsxnew file mode 100644index 0000000000..250bd6b2b7--- /dev/null+++ b/frontend/src/pages/License/stories/License.stories.mocks.tsx@@ -0,0 +1,47 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { StatusCodes } from 'http-status-codes';+import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++const KEY = 'License · key';++const APPLY_RESULTS = ['accepted', 'rejected'] as const;++type ApplyResult = (typeof APPLY_RESULTS)[number];++export const licenseMocks = defineStoryMocks({+ controls: {+ apply: choiceControl('Apply result', {+ group: KEY,+ description:+ 'What the backend answers when a key is applied, which is the notification the form raises.',+ options: APPLY_RESULTS,+ value: 'accepted' as ApplyResult,+ }),+ },+ handlers: (values) => [+ rest.post('http://localhost/api/v4/licenses', (_req, res, ctx) =>+ values.apply === 'accepted'+ ? res(ctx.json({ status: 'success', data: null }))+ : res(+ ctx.status(StatusCodes.BAD_REQUEST),+ ctx.json({+ error: {+ code: 'invalid_license',+ message: 'That key is not valid for this deployment.',+ url: '',+ errors: [],+ },+ }),+ ),+ ),+ ],+ config: () => ({ route: ROUTES.LIST_LICENSES }),+});diff --git a/frontend/src/pages/License/stories/License.stories.tsx b/frontend/src/pages/License/stories/License.stories.tsxnew file mode 100644index 0000000000..d04c979895--- /dev/null+++ b/frontend/src/pages/License/stories/License.stories.tsx@@ -0,0 +1,52 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import LicensePage from '../index';+import { licenseMocks } from './License.stories.mocks';++type LicenseArgs = PageStoryArgs<typeof licenseMocks>;++const pageStory = storyMocks(licenseMocks, { layout: 'app' });++/**+ * Licence keys applied to the workspace, and the form that applies another.+ *+ * Route: `/licenses`.+ */+const meta = {+ title: 'Pages/System/License',+ tags: ['play'],+ component: LicensePage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<LicenseArgs>;++export default meta;++type Story = StoryObj<LicenseArgs>;++const applyKey = async (canvasElement: HTMLElement): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.type(+ await canvas.findByRole('textbox'),+ '96a1c6a4-3f1e-4b7d-9f2a-8c0d5e6f7a8b',+ );+ await userEvent.click(canvas.getByRole('button', { name: /apply/i }));+};++/** Where a self-hosted deployment puts the key it was sold. */+export const Default: Story = {};++/** A key the backend will not take, which the form reports where it stands. */+export const KeyRejected: Story = {+ args: { apply: 'rejected' },+ // The deliberate 400 is the state under test.+ parameters: { allowConsoleErrors: true },+ play: async ({ canvasElement }): Promise<void> => {+ await applyKey(canvasElement);+ },+};diff --git a/frontend/src/pages/Login/stories/Login.stories.mocks.tsx b/frontend/src/pages/Login/stories/Login.stories.mocks.tsxnew file mode 100644index 0000000000..b0c62110fb--- /dev/null+++ b/frontend/src/pages/Login/stories/Login.stories.mocks.tsx@@ -0,0 +1,71 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ AUTHN_MECHANISMS,+ CALLBACK_ERROR_PARAMS,+ ORG_MAX,+ sessionsContextResponse,+ type AuthNMechanism,+} from './__story_mockdata__/login';++const WORKSPACE = 'Login · workspace';++export const loginMocks = defineStoryMocks({+ controls: {+ orgs: countControl('Organizations', {+ group: WORKSPACE,+ description:+ 'Workspaces the email belongs to. More than one adds the organization select above the password.',+ value: 1,+ max: ORG_MAX,+ }),+ authN: choiceControl<AuthNMechanism>('Sign-in method', {+ group: WORKSPACE,+ description:+ 'What the organization supports: a password field, or the button that hands off to its identity provider.',+ options: AUTHN_MECHANISMS,+ value: 'password',+ }),+ orgWarning: toggleControl('Organization warning', {+ group: WORKSPACE,+ description:+ 'A warning the backend returns with the workspace, shown where a failed sign-in would be.',+ value: false,+ }),+ callbackError: toggleControl('Callback error', {+ group: WORKSPACE,+ description:+ 'Land on the page the way the identity provider redirects back when the assertion fails.',+ value: false,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/sessions/context',+ response.json(() =>+ sessionsContextResponse(values.orgs, values.authN, values.orgWarning),+ ),+ ),+ ],+ config: (values) => ({+ route: values.callbackError+ ? `${ROUTES.LOGIN}?${CALLBACK_ERROR_PARAMS}`+ : ROUTES.LOGIN,+ // The login page is what a signed-out browser lands on, so the shell has no+ // side nav, top nav or banners to draw.+ appContext: { isLoggedIn: false },+ }),+});diff --git a/frontend/src/pages/Login/stories/Login.stories.tsx b/frontend/src/pages/Login/stories/Login.stories.tsxnew file mode 100644index 0000000000..08de2423b1--- /dev/null+++ b/frontend/src/pages/Login/stories/Login.stories.tsx@@ -0,0 +1,85 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { LOGIN_EMAIL } from './__story_mockdata__/login';+import Login from '../index';+import { loginMocks } from './Login.stories.mocks';++type LoginArgs = PageStoryArgs<typeof loginMocks>;++const pageStory = storyMocks(loginMocks, { layout: 'app' });++/**+ * The login page: the auth methods the org offers, the SSO redirect, and what a+ * failed callback leaves behind.+ *+ * Route: `/login`.+ */+const meta = {+ title: 'Pages/Auth/Login',+ tags: ['play'],+ component: Login,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<LoginArgs>;++export default meta;++type Story = StoryObj<LoginArgs>;++/** The page resolves the workspace before it asks for anything else. */+const submitEmail = async (canvasElement: HTMLElement): Promise<void> => {+ const canvas = within(canvasElement);++ // Both the field and the button are disabled until the version call the page+ // gates on has come back, which outlasts the story's first paint.+ const email = await canvas.findByTestId('email');+ await waitFor(() => expect(email).toBeEnabled());+ await userEvent.type(email, LOGIN_EMAIL);++ const next = canvas.getByRole('button', { name: /next/i });+ await waitFor(() => expect(next).toBeEnabled());+ await userEvent.click(next);+};++/** The first step: the email, which is what decides how the user signs in. */+export const Default: Story = {};++/** The email resolved to one password workspace, so the password field is next. */+export const PasswordStep: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await submitEmail(canvasElement);+ await expect(+ await within(canvasElement).findByTestId('password'),+ ).toBeVisible();+ },+};++/** An email in three workspaces: the organization has to be picked first. */+export const MultipleOrganizations: Story = {+ args: { orgs: 3 },+ play: async ({ canvasElement }): Promise<void> => {+ await submitEmail(canvasElement);+ await expect(await within(canvasElement).findByTestId('orgId')).toBeVisible();+ },+};++/** A workspace behind an identity provider: no password, a hand-off instead. */+export const SingleSignOn: Story = {+ args: { authN: 'sso' },+ play: async ({ canvasElement }): Promise<void> => {+ await submitEmail(canvasElement);+ // The hand-off only renders once the session context has answered.+ await within(canvasElement).findByRole('button', {+ name: /sign in with sso/i,+ });+ },+};++/** Redirected back from the provider with the assertion rejected. */+export const CallbackFailed: Story = {+ args: { callbackError: true },+};diff --git a/frontend/src/pages/Login/stories/__story_mockdata__/login.ts b/frontend/src/pages/Login/stories/__story_mockdata__/login.tsnew file mode 100644index 0000000000..587f04f43e--- /dev/null+++ b/frontend/src/pages/Login/stories/__story_mockdata__/login.ts@@ -0,0 +1,73 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ OrgSessionContext,+ SessionsContext,+} from 'types/api/v2/sessions/context/get';++export const LOGIN_EMAIL = '[email protected]';++export const AUTHN_MECHANISMS = ['password', 'sso'] as const;++export type AuthNMechanism = (typeof AUTHN_MECHANISMS)[number];++const ORGS = [+ { id: 'org-signoz', name: 'SigNoz' },+ { id: 'org-acme', name: 'Acme Corp' },+ { id: 'org-globex', name: 'Globex' },+];++export const ORG_MAX = ORGS.length;++const authNSupport = (+ mechanism: AuthNMechanism,+): OrgSessionContext['authNSupport'] =>+ mechanism === 'sso'+ ? {+ password: [],+ callback: [+ { provider: 'google', url: 'https://accounts.google.com/o/saml2/idp' },+ ],+ }+ : { password: [{ provider: 'password' }], callback: [] };++/**+ * The org warning is what the backend attaches to a workspace the user can+ * still authenticate against but should not: the form renders it in the same+ * place as a failed sign-in.+ */+const orgWarning = {+ code: 'workspace_suspended',+ message:+ 'This workspace is suspended. Contact your administrator to restore it.',+ url: 'https://signoz.io/docs/',+ errors: [],+};++export const sessionsContextResponse = (+ orgs: number,+ mechanism: AuthNMechanism,+ withWarning: boolean,+): { status: string; data: SessionsContext } => ({+ status: 'success',+ data: {+ exists: true,+ orgs: ORGS.slice(0, orgs).map((org) => ({+ ...org,+ authNSupport: authNSupport(mechanism),+ ...(withWarning ? { warning: orgWarning } : {}),+ })),+ },+});++/** What the callback provider redirects back with when the assertion fails. */+export const CALLBACK_ERROR_PARAMS = new URLSearchParams({+ callbackauthnerr: 'true',+ code: 'invalid_assertion',+ message: 'The identity provider rejected the assertion.',+ url: 'https://signoz.io/docs/userguide/sso-authentication/',+ errors: JSON.stringify([{ message: 'Signature could not be verified.' }]),+}).toString();diff --git a/frontend/src/pages/LogsModulePage/LiveLogs/stories/LiveLogs.stories.mocks.tsx b/frontend/src/pages/LogsModulePage/LiveLogs/stories/LiveLogs.stories.mocks.tsxnew file mode 100644index 0000000000..9db5b3ee71--- /dev/null+++ b/frontend/src/pages/LogsModulePage/LiveLogs/stories/LiveLogs.stories.mocks.tsx@@ -0,0 +1,212 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import setLocalStorage from 'api/browser/localstorage/set';+import { LOCALSTORAGE } from 'constants/localStorage';+import { QueryParams } from 'constants/query';+import { PANEL_TYPES } from 'constants/queryBuilder';+import ROUTES from 'constants/routes';+import { FontSize, type LogViewMode } from 'container/OptionsMenu/types';+import { rest } from 'msw';+import type {+ BaseBuilderQuery,+ QueryRangeRequestV5,+} from 'types/api/v5/queryRange';++import {+ choiceControl,+ countControl,+ multiChoiceControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import { logsSavedViewsResponse } from '../../SavedViews/stories/__story_mockdata__/savedViews';+import {+ attributeValuesResponse,+ dashboardsResponse,+ logFieldKeysResponse,+ logFieldValuesResponse,+ logHistogramResponse,+ logRowsResponse,+ logsListOptions,+ logTimeseriesResponse,+ LOG_SEVERITIES,+ type LogSeverity,+ QUICK_FILTER_MAX,+ logsQuickFiltersResponse,+ RELATIVE_TIME,+ timeRangeState,+} from '../../stories/__story_mockdata__/logs';+import {+ LIVE_TAIL_LIMIT,+ liveLogsQuery,+ liveLogsStream,+} from './__story_mockdata__/liveLogs';++const STREAM = 'Live tail · stream';+const LIST = 'Live tail · list';++const LIST_FORMATS: readonly LogViewMode[] = ['table', 'list', 'raw'];++const liveRoute = (): string => {+ const params = new URLSearchParams({+ [QueryParams.panelTypes]: JSON.stringify(PANEL_TYPES.LIST),+ [QueryParams.relativeTime]: RELATIVE_TIME,+ });++ params.set(+ QueryParams.compositeQuery,+ encodeURIComponent(JSON.stringify(liveLogsQuery())),+ );++ return `${ROUTES.LOGS_EXPLORER}?${params.toString()}`;+};++/**+ * How long the connection takes to answer. The container opens, closes and+ * reopens on mount, and only attaches its `message` listener on the render the+ * connection's own state change causes. Answering immediately would put every+ * frame out before anything was listening.+ */+const CONNECT_LATENCY_MS = 600;++export const liveLogsMocks = defineStoryMocks({+ controls: {+ liveLogs: countControl('Lines received', {+ group: STREAM,+ description:+ 'Lines the connection has delivered so far. None reads as connected and waiting, which is where live tail starts.',+ value: 30,+ max: LIVE_TAIL_LIMIT,+ }),+ severities: multiChoiceControl<LogSeverity>('Severities', {+ group: STREAM,+ description:+ 'Severities the streamed lines carry, cycled through the list and stacked in the frequency chart.',+ options: LOG_SEVERITIES,+ value: LOG_SEVERITIES,+ }),+ format: choiceControl<LogViewMode>('Line format', {+ group: LIST,+ description: 'Columns, one line per log, or the raw line.',+ options: LIST_FORMATS,+ value: 'table',+ }),+ },+ handlers: (values, response) => [+ // The frequency chart above the list stays empty here: it only queries+ // while the connection is open, and a connection msw answers in one piece+ // is open for an instant. The chart's other source is the payload the+ // explorer pushes in `location.state`, which the story's own navigation+ // drops as soon as the page writes its first query param.+ //+ // The stream the live list is. It is answered plainly rather than through+ // `response`: the polyfill reads a non-200 as a dropped connection and the+ // provider answers that by rotating the session and reconnecting, so the+ // Data control on `error` would drive a reconnect loop rather than show a+ // live tail that failed.+ rest.get('http://localhost/api/v3/logs/livetail', (_req, res, ctx) =>+ res(+ ctx.delay(CONNECT_LATENCY_MS),+ ctx.status(200),+ ctx.set('Content-Type', 'text/event-stream'),+ ctx.set('Cache-Control', 'no-cache'),+ // The connection is cross-origin, and the polyfill sends an+ // `Authorization` header, so without these the browser refuses the+ // response the same way it would refuse the backend's.+ ctx.set('Access-Control-Allow-Origin', '*'),+ ctx.body(liveLogsStream(values.liveLogs, values.severities, Date.now())),+ ),+ ),++ // The end of a response is a dropped connection as far as the polyfill is+ // concerned, and the provider answers that by rotating the session and then+ // reconnecting. A story cannot follow that: msw has no stream to reopen, so+ // every reconnection ends immediately and starts the next one, and the list+ // is cleared each time round. Left hanging, the rotation never resolves, the+ // reconnection is never scheduled, and the lines that arrived stay put.+ rest.post('http://localhost/api/v2/sessions/rotate', (_req, res, ctx) =>+ res(ctx.delay('infinite')),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const timeWindow = { start: body.start, end: body.end };++ if (body.requestType === 'raw') {+ return logRowsResponse(values.liveLogs, values.severities, body.end);+ }++ const spec = body.compositeQuery?.queries?.[0]?.spec as+ | BaseBuilderQuery+ | undefined;+ const bySeverity = (spec?.groupBy ?? []).some(+ (key) => key.name === 'severity_text',+ );++ return bySeverity+ ? logHistogramResponse(values.severities, timeWindow)+ : logTimeseriesResponse(timeWindow);+ }),+ ),++ rest.get(+ 'http://localhost/api/v2/quick_filters/:source',+ response.json(() => logsQuickFiltersResponse(QUICK_FILTER_MAX)),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ logFieldKeysResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ logFieldValuesResponse(+ req.url.searchParams.get('name') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ attributeValuesResponse(+ req.url.searchParams.get('attributeKey') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/explorer/views',+ response.json(() => logsSavedViewsResponse(4)),+ ),++ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json(dashboardsResponse),+ ),+ ],+ config: () => ({+ route: liveRoute(),+ reduxState: timeRangeState(),+ }),+ effect: ({ format }) => {+ setLocalStorage(LOCALSTORAGE.SHOW_LOGS_QUICK_FILTERS, 'true');+ setLocalStorage(+ LOCALSTORAGE.LOGS_LIST_OPTIONS,+ JSON.stringify(+ logsListOptions({ format, maxLines: 1, fontSize: FontSize.SMALL }),+ ),+ );+ },+});diff --git a/frontend/src/pages/LogsModulePage/LiveLogs/stories/LiveLogs.stories.tsx b/frontend/src/pages/LogsModulePage/LiveLogs/stories/LiveLogs.stories.tsxnew file mode 100644index 0000000000..2e32c71436--- /dev/null+++ b/frontend/src/pages/LogsModulePage/LiveLogs/stories/LiveLogs.stories.tsx@@ -0,0 +1,86 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { liveLogsMocks } from './LiveLogs.stories.mocks';++import LogsModulePage from '../../LogsModulePage';++type LiveLogsArgs = PageStoryArgs<typeof liveLogsMocks>;++const pageStory = storyMocks(liveLogsMocks, { layout: 'app' });++/** The page connects before it renders a line, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/** Live tail is reached through the time picker, which owns the `Live` option. */+const goLive = async (canvasElement: HTMLElement): Promise<void> => {+ const canvas = within(canvasElement);++ const timePicker = await waitFor(() => {+ const input = canvasElement.querySelector<HTMLElement>(+ '.timeSelection-input',+ );++ if (!input) {+ throw new Error('Time picker did not render');+ }++ return input;+ }, untilLoaded);++ await userEvent.click(timePicker);+ await userEvent.click(+ await canvas.findByRole('button', { name: 'Live' }, untilLoaded),+ );+};++/**+ * Live tail: the explorer following a filter as lines arrive, over the log+ * stream at `/api/v3/logs/livetail` rather than a query. It is a mode of the+ * explorer rather than a page of its own, and nothing in the URL says it is on,+ * so every story here turns it on the way someone does.+ *+ * Route: `/logs/logs-explorer`.+ */+const meta = {+ title: 'Pages/Logs/Live Tail',+ tags: ['play'],+ component: LogsModulePage,+ play: async ({ mount, args, canvasElement }): Promise<void> => {+ await mount();+ await goLive(canvasElement);++ // The stream answers after a connect delay, so without this the story is+ // captured on `Fetching live logs...` rather than on the lines it names.+ if (args.liveLogs > 0) {+ await within(canvasElement).findAllByText(+ /order 8412 placed/,+ undefined,+ untilLoaded,+ );+ }+ },+ ...pageStory,+ // The stream mock answers in one piece, so the polyfill reads its end as a+ // dropped connection and logs the error it would on any reconnect; that is the+ // state under test, not a regression.+ parameters: { ...pageStory.parameters, allowConsoleErrors: true },+} satisfies Meta<LiveLogsArgs>;++export default meta;++type Story = StoryObj<LiveLogsArgs>;++/**+ * The explorer live-tailing a service: the lines the connection has delivered,+ * newest on top, with the pause control beside the time picker.+ */+export const Default: Story = {};++/** Connected with nothing through yet, which is where every live tail starts. */+export const Waiting: Story = {+ args: { liveLogs: 0 },+};diff --git a/frontend/src/pages/LogsModulePage/LiveLogs/stories/__story_mockdata__/liveLogs.ts b/frontend/src/pages/LogsModulePage/LiveLogs/stories/__story_mockdata__/liveLogs.tsnew file mode 100644index 0000000000..87b919233a--- /dev/null+++ b/frontend/src/pages/LogsModulePage/LiveLogs/stories/__story_mockdata__/liveLogs.ts@@ -0,0 +1,83 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { initialQueriesMap } from 'constants/queryBuilder';+import type {+ IBuilderQuery,+ Query,+} from 'types/api/queryBuilder/queryBuilderData';+import { DataSource } from 'types/common/queryBuilder';++import {+ logRows,+ type LogSeverity,+} from '../../../stories/__story_mockdata__/logs';++/** `QueryRawStream` asks the querier for at most this many rows. */+export const LIVE_TAIL_LIMIT = 500;++/** A reconnection delay the story will never reach. */+const NO_RECONNECT_MS = 24 * 60 * 60 * 1000;++/** The filter the story live-tails on. See `liveLogsQuery`. */+export const LIVE_TAIL_FILTER = "service.name = 'checkout'";++/**+ * The query the live tail runs on, seeded from the app's own so a change to the+ * query-builder shape reaches the story.+ *+ * The filter is not decoration. The container remembers the expression it+ * connected with, but stores an empty one as `null`, and its "has the filter+ * changed" guard is `!previous || previous !== current`. An unfiltered live tail+ * therefore reads as changed on every render: it clears the lines it has and+ * reopens the connection, and the list never fills.+ */+export const liveLogsQuery = (): Query => {+ const seed = initialQueriesMap[DataSource.LOGS];++ return {+ ...seed,+ builder: {+ ...seed.builder,+ queryData: seed.builder.queryData.map(+ (data): IBuilderQuery => ({+ ...data,+ filter: { expression: LIVE_TAIL_FILTER },+ }),+ ),+ },+ };+};++/**+ * The frames a live-tail connection carries, oldest first.+ *+ * Two things the shape has to match that the explorer's does not. The stream+ * sends one `RawRow` per `data:` frame rather than a page of them, and the+ * container hands `row.data` to the list untouched, so the timestamp has to be+ * on the row's own data as well as beside it. And each batch is reversed before+ * it is prepended, so the last frame in the body is the line that ends up at the+ * top of the list.+ *+ * msw answers a request in one piece rather than as a stream, so the response+ * ends the moment the backlog is out and the client reconnects on its own. A+ * reconnection would replay every line, so the stream sets a reconnection time+ * it will never reach.+ */+export const liveLogsStream = (+ count: number,+ severities: readonly LogSeverity[],+ endMilli: number,+): string =>+ `retry: ${NO_RECONNECT_MS}\n\n${logRows(count, severities, endMilli, false)+ .map(+ (row) =>+ `data: ${JSON.stringify({+ timestamp: row.timestamp,+ data: { ...row.data, timestamp: row.timestamp },+ })}\n\n`,+ )+ .reverse()+ .join('')}`;diff --git a/frontend/src/pages/LogsModulePage/Pipelines/stories/Pipelines.stories.mocks.tsx b/frontend/src/pages/LogsModulePage/Pipelines/stories/Pipelines.stories.mocks.tsxnew file mode 100644index 0000000000..566f2c77ad--- /dev/null+++ b/frontend/src/pages/LogsModulePage/Pipelines/stories/Pipelines.stories.mocks.tsx@@ -0,0 +1,163 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { PANEL_TYPES } from 'constants/queryBuilder';+import ROUTES from 'constants/routes';+import { rest } from 'msw';+import type { ILog } from 'types/api/logs/log';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ attributeValuesResponse,+ filterSuggestionsResponse,+ logCountV3Response,+ logFieldKeysResponse,+ logFieldValuesResponse,+ LOG_SEVERITIES,+ logRowsV3Response,+ timeRangeState,+} from '../../stories/__story_mockdata__/logs';+import {+ DEPLOY_STATUSES,+ type DeployStatus,+ logsPipelinesResponse,+ PIPELINE_MAX,+ pipelinePreviewResponse,+ PROCESSOR_MAX,+ VERSION_MAX,+} from './__story_mockdata__/pipelines';++const LIST = 'Pipelines · list';+const DEPLOYMENT = 'Pipelines · deployment';+const PREVIEW = 'Pipelines · preview';++/** `useSampleLogs` asks for five, so a longer response is not one the backend sends. */+const SAMPLE_LOGS_REQUESTED = 5;++export const pipelinesMocks = defineStoryMocks({+ controls: {+ pipelines: countControl('Pipelines', {+ group: LIST,+ value: 3,+ max: PIPELINE_MAX,+ }),+ processors: countControl('Processors per pipeline', {+ group: LIST,+ description:+ 'The operators a pipeline runs, listed when its row is expanded. A pipeline without any cannot be previewed.',+ value: 3,+ max: PROCESSOR_MAX,+ }),+ deployStatus: choiceControl<DeployStatus>('Deploy status', {+ group: DEPLOYMENT,+ description:+ 'Where the latest config version got to. Anything other than deployed or failed keeps the page polling every three seconds.',+ options: DEPLOY_STATUSES,+ value: 'DEPLOYED',+ }),+ versions: countControl('Config versions', {+ group: DEPLOYMENT,+ description: 'How many versions the change history lists.',+ value: 4,+ max: VERSION_MAX,+ }),+ sampleLogs: countControl('Sample logs', {+ group: PREVIEW,+ description:+ "The logs a pipeline's filter matches, which the preview runs its processors over.",+ value: SAMPLE_LOGS_REQUESTED,+ max: SAMPLE_LOGS_REQUESTED,+ }),+ },+ handlers: (values, response) => {+ const pipelines = (): ReturnType<typeof logsPipelinesResponse> =>+ logsPipelinesResponse({+ pipelines: values.pipelines,+ processors: values.processors,+ deployStatus: values.deployStatus,+ versions: values.versions,+ });++ return [+ rest.get(+ 'http://localhost/api/v1/logs/pipelines/:version',+ response.json(pipelines),+ ),++ rest.post(+ 'http://localhost/api/v1/logs/pipelines',+ response.json(pipelines),+ ),++ rest.post(+ 'http://localhost/api/v1/logs/pipelines/preview',+ response.json(async (req) => {+ const body = (await req.json()) as { logs: ILog[] };++ return pipelinePreviewResponse(body.logs);+ }),+ ),++ // The preview queries on `DEFAULT_ENTITY_VERSION`, so it asks v3 rather+ // than the v5 endpoint the explorer uses: the panel type says whether it+ // wants the matching logs or how many there are.+ rest.post(+ 'http://localhost/api/v3/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as {+ end: number;+ compositeQuery: { panelType: PANEL_TYPES };+ };++ if (body.compositeQuery?.panelType === 'table') {+ return logCountV3Response(4213, body.end);+ }++ return logRowsV3Response(values.sampleLogs, LOG_SEVERITIES, body.end);+ }),+ ),++ rest.get(+ 'http://localhost/api/v3/filter_suggestions',+ response.json((req) =>+ filterSuggestionsResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ logFieldKeysResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ logFieldValuesResponse(+ req.url.searchParams.get('name') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ attributeValuesResponse(+ req.url.searchParams.get('attributeKey') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),+ ];+ },+ config: () => ({+ route: ROUTES.LOGS_PIPELINES,+ reduxState: timeRangeState(),+ }),+});diff --git a/frontend/src/pages/LogsModulePage/Pipelines/stories/Pipelines.stories.tsx b/frontend/src/pages/LogsModulePage/Pipelines/stories/Pipelines.stories.tsxnew file mode 100644index 0000000000..c35a7906da--- /dev/null+++ b/frontend/src/pages/LogsModulePage/Pipelines/stories/Pipelines.stories.tsx@@ -0,0 +1,145 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { pipelinesMocks } from './Pipelines.stories.mocks';++import LogsModulePage from '../../LogsModulePage';++type PipelinesArgs = PageStoryArgs<typeof pipelinesMocks>;++const pageStory = storyMocks(pipelinesMocks, { layout: 'app' });++/**+ * Log processing pipelines: the operators each runs, the sample preview, the+ * deploy state and the version history.+ *+ * Route: `/logs/pipelines`.+ */+const meta = {+ title: 'Pages/Logs/Pipelines',+ tags: ['play'],+ component: LogsModulePage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<PipelinesArgs>;++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.+ */+export const Default: Story = {};++/** A workspace with no pipeline yet, which is where the tab explains itself. */+export const NoPipelines: Story = {+ args: { pipelines: 0 },+};++/** A pipeline opened up: the operators it runs, in order. */+export const ExpandedProcessors: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await clickFirst(canvasElement, 'pipeline-row-expand');+ },+};++/** Edit mode: rows can be reordered, switched off, edited and deleted. */+export const EditMode: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await enterEditMode(canvasElement);+ },+};++/** The form a new pipeline is written in: what it matches and what to call it. */+export const AddPipeline: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await enterEditMode(canvasElement);+ await userEvent.click(+ await within(canvasElement).findByText(/add a new pipeline/i),+ );+ await screen.findByText(/create new pipeline/i);+ },+};++/** The same form over an existing pipeline, filter included. */+export const EditPipeline: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await enterEditMode(canvasElement);+ await clickFirst(canvasElement, 'pipeline-edit-action');+ await screen.findByText(/edit pipeline/i);+ },+};++/** Adding an operator to a pipeline: the type decides the rest of the form. */+export const AddProcessor: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ 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);+ },+};++/**+ * The logs a pipeline matches, over the interval the preview asks for, with the+ * simulation of its processors one click away.+ */+export const ProcessingPreview: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await clickFirst(canvasElement, 'pipeline-preview-action');+ await screen.findByText(/processed output/i, undefined, untilLoaded);+ },+};++/** Every config version the org deployed, and how each deployment went. */+export const ChangeHistory: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText(/change history/i, undefined, untilLoaded),+ );+ await canvas.findByText('Deployment Stage', undefined, untilLoaded);+ },+};++/** A deployment the collector has not finished, which the page polls for. */+export const Deploying: Story = {+ args: { deployStatus: 'IN_PROGRESS' },+};diff --git a/frontend/src/pages/LogsModulePage/Pipelines/stories/__story_mockdata__/pipelines.ts b/frontend/src/pages/LogsModulePage/Pipelines/stories/__story_mockdata__/pipelines.tsnew file mode 100644index 0000000000..9520b2c7b3--- /dev/null+++ b/frontend/src/pages/LogsModulePage/Pipelines/stories/__story_mockdata__/pipelines.ts@@ -0,0 +1,248 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { ILog } from 'types/api/logs/log';+import type {+ HistoryData,+ Pipeline,+ PipelineData,+ ProcessorData,+} from 'types/api/pipeline/def';+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';+import type { TagFilter } from 'types/api/queryBuilder/queryBuilderData';++/**+ * What the API sends. The change-history column renders the lowercase spelling,+ * so a version's stage stays blank there: see the story's PR.+ */+export const DEPLOY_STATUSES = [+ 'DEPLOYED',+ 'IN_PROGRESS',+ 'FAILED',+ 'DIRTY',+ 'UNKNOWN',+] as const;++export type DeployStatus = (typeof DEPLOY_STATUSES)[number];++const DEPLOY_RESULTS: Record<DeployStatus, string> = {+ DEPLOYED: 'deploy success',+ IN_PROGRESS: 'deployment started',+ FAILED: 'collector rejected the config: unknown processor "grok_parser"',+ DIRTY: 'config on the collector is older than this version',+ UNKNOWN: '',+};++const filterOn = (key: string, value: string): TagFilter => ({+ op: 'AND',+ items: [+ {+ id: `${key}-${value}`,+ key: { key, dataType: DataTypes.String, type: '' },+ op: '=',+ value,+ },+ ],+});++type ProcessorSeed = Omit<ProcessorData, 'orderId' | 'id' | 'output'>;++const PROCESSORS: ProcessorSeed[] = [+ {+ type: 'grok_parser',+ name: 'Parse the access log line',+ enabled: true,+ pattern: '%{COMMONAPACHELOG}',+ parse_from: 'body',+ parse_to: 'attributes',+ on_error: 'send',+ },+ {+ type: 'json_parser',+ name: 'Parse the JSON payload',+ enabled: true,+ parse_from: 'body',+ parse_to: 'attributes',+ enable_flattening: true,+ enable_paths: false,+ path_prefix: '',+ mapping: {},+ },+ {+ type: 'severity_parser',+ name: 'Read severity off level',+ enabled: true,+ parse_from: 'attributes.level',+ },+ {+ type: 'move',+ name: 'Rename auth to username',+ enabled: true,+ from: 'attributes.auth',+ to: 'attributes.username',+ },+ {+ type: 'remove',+ name: 'Drop the raw payload',+ enabled: false,+ field: 'attributes.payload',+ },+];++export const PROCESSOR_MAX = PROCESSORS.length;++/**+ * `output` chains each processor to the next one, which is what cancelling an+ * edit rebuilds the list from.+ */+const processorsFor = (pipelineId: string, count: number): ProcessorData[] => {+ const ids = PROCESSORS.slice(0, count).map(+ (_unused, index) => `${pipelineId}-processor-${index + 1}`,+ );++ return PROCESSORS.slice(0, count).map((processor, index) => ({+ ...processor,+ id: ids[index],+ orderId: index + 1,+ output: ids[index + 1],+ }));+};++interface PipelineSeed {+ name: string;+ description: string;+ filter: TagFilter;+}++const PIPELINES: PipelineSeed[] = [+ {+ name: 'Parse nginx access logs',+ description: 'grok the access log line into attributes',+ filter: filterOn('source', 'nginx'),+ },+ {+ name: 'Drop health check noise',+ description: 'filter out the /healthz requests',+ filter: filterOn('http.route', '/healthz'),+ },+ {+ name: 'Extract trace context',+ description: 'read trace_id and span_id from the body',+ filter: filterOn('service.name', 'checkout'),+ },+ {+ name: 'Rename severity field',+ description: 'level becomes severity_text',+ filter: filterOn('service.name', 'payments'),+ },+ {+ name: 'Flatten JSON payloads',+ description: 'expand nested attributes into their own keys',+ filter: filterOn('deployment.environment', 'production'),+ },+];++export const PIPELINE_MAX = PIPELINES.length;++export const VERSION_MAX = 6;++export interface PipelinesOptions {+ pipelines: number;+ processors: number;+ deployStatus: DeployStatus;+ versions: number;+}++const historyFor = (+ versions: number,+ deployStatus: DeployStatus,+): HistoryData[] =>+ Array.from({ length: versions }, (_unused, index) => {+ const version = versions - index;+ const isLatest = index === 0;+ const status = isLatest ? deployStatus : 'DEPLOYED';++ return {+ active: isLatest,+ createdAt: `2026-07-${String(10 + version).padStart(2, '0')}T13:48:31.032106578Z`,+ createdBy: isLatest ? '[email protected]' : '[email protected]',+ createdByName: isLatest ? 'Ada Lovelace' : 'Grace Hopper',+ deployStatus: status,+ deployResult: DEPLOY_RESULTS[status],+ disabled: false,+ elementType: 'log_pipelines',+ id: `storybook-pipelines-v${version}`,+ isValid: true,+ lastConf: '',+ lastHash: '',+ version,+ };+ });++/**+ * A latest version still deploying makes the page poll every three seconds,+ * which is the app's own behaviour and what the `Deploy status` control shows.+ */+export const logsPipelinesResponse = ({+ pipelines,+ processors,+ deployStatus,+ versions,+}: PipelinesOptions): { status: string; data: Pipeline } => ({+ status: 'success',+ data: {+ active: true,+ createdBy: '[email protected]',+ deployResult: DEPLOY_RESULTS[deployStatus],+ deployStatus,+ disabled: false,+ elementType: 'log_pipelines',+ id: 'storybook-pipelines',+ is_valid: true,+ lastConf: '',+ lastHash: '',+ version: versions,+ history: historyFor(versions, deployStatus),+ pipelines: PIPELINES.slice(0, pipelines).map(+ (pipeline, index): PipelineData => {+ const id = `storybook-pipeline-${index + 1}`;++ return {+ ...pipeline,+ id,+ alias: pipeline.name.toLowerCase().replace(/\s+/g, '-'),+ createdAt: '2026-07-16T13:48:31.032106578Z',+ createdBy: '[email protected]',+ enabled: index !== 3,+ orderId: index + 1,+ config: processorsFor(id, processors),+ };+ },+ ),+ },+});++/**+ * The simulation answers on the logs it was sent, so the preview can diff input+ * against output: the parsed fields land on the ones the pipeline writes to.+ */+export const pipelinePreviewResponse = (+ logs: ILog[],+): { status: string; data: { logs: ILog[] } } => ({+ status: 'success',+ data: {+ logs: logs.map((log) => ({+ ...log,+ // `ILog` types every attribute map as `Record<string, never>`, so a value+ // only goes in through a cast.+ attributes_string: {+ ...log.attributes_string,+ 'http.method': 'POST',+ username: 'ada',+ level: String(log.severity_text ?? '').toLowerCase(),+ } as unknown as ILog['attributes_string'],+ })),+ },+});diff --git a/frontend/src/pages/LogsModulePage/SavedViews/stories/SavedViews.stories.mocks.tsx b/frontend/src/pages/LogsModulePage/SavedViews/stories/SavedViews.stories.mocks.tsxnew file mode 100644index 0000000000..4992bd4bca--- /dev/null+++ b/frontend/src/pages/LogsModulePage/SavedViews/stories/SavedViews.stories.mocks.tsx@@ -0,0 +1,47 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ logsSavedViewsResponse,+ SAVED_VIEW_MAX,+ SAVED_VIEWS_PAGE_SIZE,+ savedViewWriteResponse,+} from './__story_mockdata__/savedViews';++const LIST = 'Views · list';++export const savedViewsMocks = defineStoryMocks({+ controls: {+ views: countControl('Saved views', {+ group: LIST,+ description: `The views the org saved for logs. Past ${SAVED_VIEWS_PAGE_SIZE} the table paginates.`,+ value: 4,+ max: SAVED_VIEW_MAX,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/explorer/views',+ response.json(() => logsSavedViewsResponse(values.views)),+ ),++ rest.put(+ 'http://localhost/api/v1/explorer/views/:viewId',+ response.json(savedViewWriteResponse),+ ),++ rest.delete(+ 'http://localhost/api/v1/explorer/views/:viewId',+ response.json(savedViewWriteResponse),+ ),+ ],+ config: () => ({ route: ROUTES.LOGS_SAVE_VIEWS }),+});diff --git a/frontend/src/pages/LogsModulePage/SavedViews/stories/SavedViews.stories.tsx b/frontend/src/pages/LogsModulePage/SavedViews/stories/SavedViews.stories.tsxnew file mode 100644index 0000000000..65069859de--- /dev/null+++ b/frontend/src/pages/LogsModulePage/SavedViews/stories/SavedViews.stories.tsx@@ -0,0 +1,88 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { savedViewsMocks } from './SavedViews.stories.mocks';++import LogsModulePage from '../../LogsModulePage';++type SavedViewsArgs = PageStoryArgs<typeof savedViewsMocks>;++const pageStory = storyMocks(savedViewsMocks, { layout: 'app' });++/**+ * Saved views on the logs explorer, and the actions the legacy editor role gates.+ *+ * Route: `/logs/saved-views`.+ */+const meta = {+ title: 'Pages/Logs/Saved Views',+ tags: ['role-gated', 'play'],+ component: LogsModulePage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<SavedViewsArgs>;++export default meta;++type Story = StoryObj<SavedViewsArgs>;++/** The page fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/** Row actions are per-view icons, so a story that opens one picks the first. */+const openFirstAction = async (+ canvasElement: HTMLElement,+ testId: string,+): Promise<void> => {+ const [action] = await within(canvasElement).findAllByTestId(+ testId,+ undefined,+ untilLoaded,+ );++ await userEvent.click(action);+};++/**+ * The views tab: every view the org saved for logs, who saved it and when, with+ * the colour the view picker shows it under.+ */+export const Default: Story = {};++/** A workspace where nobody has saved a view yet. */+export const NoViews: Story = {+ args: { views: 0 },+};++/** Enough views to paginate, which is the only place the second page shows up. */+export const Paginated: Story = {+ args: { views: 8 },+};++/** Renaming a view: its label and the colour the picker shows it under. */+export const EditView: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openFirstAction(canvasElement, 'edit-view');+ await screen.findByText('Edit view details', undefined, untilLoaded);+ },+};++/** The confirmation a view has to pass before it is deleted. */+export const DeleteView: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openFirstAction(canvasElement, 'delete-view');+ await screen.findByText(+ /are you sure you want to delete/i,+ undefined,+ untilLoaded,+ );+ },+};++/** A viewer: the views are listed, none of them editable. */+export const ViewerAccess: Story = {+ args: { access: 'viewer' },+};diff --git a/frontend/src/pages/LogsModulePage/SavedViews/stories/__story_mockdata__/savedViews.ts b/frontend/src/pages/LogsModulePage/SavedViews/stories/__story_mockdata__/savedViews.tsnew file mode 100644index 0000000000..79d36f262c--- /dev/null+++ b/frontend/src/pages/LogsModulePage/SavedViews/stories/__story_mockdata__/savedViews.ts@@ -0,0 +1,62 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { explorerView } from 'mocks-server/__mockdata__/explorer_views';+import type { AllViewsProps, ViewProps } from 'types/api/saveViews/types';+import { DataSource } from 'types/common/queryBuilder';++const VIEWS: { name: string; color: string; createdBy: string }[] = [+ { name: 'Checkout errors', color: '#f2536b', createdBy: '[email protected]' },+ {+ name: 'Auth service warnings',+ color: '#ffbe0b',+ createdBy: '[email protected]',+ },+ {+ name: 'Slow SQL statements',+ color: '#00ffd0',+ createdBy: '[email protected]',+ },+ { name: 'Payment webhooks', color: '#7c4dff', createdBy: '[email protected]' },+ {+ name: 'Rate limited requests',+ color: '#4e74f8',+ createdBy: '[email protected]',+ },+ { name: 'Cron job failures', color: '#ff7d3b', createdBy: '[email protected]' },+ { name: 'Cold start traces', color: '#189e5f', createdBy: '[email protected]' },+ { name: 'Kafka consumer lag', color: '#c7c7c7', createdBy: '[email protected]' },+];++export const SAVED_VIEW_MAX = VIEWS.length;++/** The table paginates past this, which is the only place page 2 shows up. */+export const SAVED_VIEWS_PAGE_SIZE = 5;++/** The jest fixture is the shape of a view; only what the list shows changes. */+const [baseView] = explorerView.data as unknown as ViewProps[];++export const logsSavedViewsResponse = (count: number): AllViewsProps => ({+ status: 'success',+ data: VIEWS.slice(0, count).map(({ name, color, createdBy }, index) => ({+ ...baseView,+ id: `storybook-logs-view-${index + 1}`,+ name,+ sourcePage: DataSource.LOGS,+ tags: ['logs'],+ createdBy,+ createdAt: `2026-08-${String(4 + index).padStart(2, '0')}T09:24:11.000Z`,+ extraData: JSON.stringify({ color }),+ })),+});++/**+ * Renaming and deleting answer, so the modal closes and the notification is the+ * one the page shows on success. The list itself is what the `Saved views`+ * control says it is, so the refetch reads it back unchanged: see the PR.+ */+export const savedViewWriteResponse = (): { status: string } => ({+ status: 'success',+});diff --git a/frontend/src/pages/LogsModulePage/stories/LogsModulePage.stories.mocks.tsx b/frontend/src/pages/LogsModulePage/stories/LogsModulePage.stories.mocks.tsxnew file mode 100644index 0000000000..6004e3c21a--- /dev/null+++ b/frontend/src/pages/LogsModulePage/stories/LogsModulePage.stories.mocks.tsx@@ -0,0 +1,278 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import setLocalStorage from 'api/browser/localstorage/set';+import { FeatureKeys } from 'constants/features';+import { LOCALSTORAGE } from 'constants/localStorage';+import { QueryParams } from 'constants/query';+import { PANEL_TYPES } from 'constants/queryBuilder';+import ROUTES from 'constants/routes';+import { FontSize, type LogViewMode } from 'container/OptionsMenu/types';+import { rest } from 'msw';+import { defaultFeatureFlags } from 'tests/fixtures/appContextMock';+import type { Warning } from 'types/api';+import type {+ BaseBuilderQuery,+ QueryRangeRequestV5,+} from 'types/api/v5/queryRange';++import {+ choiceControl,+ countControl,+ multiChoiceControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ logsSavedViewsResponse,+ SAVED_VIEW_MAX,+} from '../SavedViews/stories/__story_mockdata__/savedViews';+import {+ attributeValuesResponse,+ dashboardsResponse,+ logCountResponse,+ logFieldKeysResponse,+ logFieldValuesResponse,+ logHistogramResponse,+ logsListOptions,+ logTimeseriesResponse,+ LOG_SEVERITIES,+ type LogSeverity,+ logRowsResponse,+ QUICK_FILTER_MAX,+ logsQuickFiltersResponse,+ RELATIVE_TIME,+ timeRangeState,+} from './__story_mockdata__/logs';++const EXPLORER = 'Logs · explorer';+const LIST = 'Logs · list';+const FILTERS = 'Logs · filters';++const EXPLORER_VIEWS = ['list', 'timeseries', 'table'] as const;++type ExplorerView = (typeof EXPLORER_VIEWS)[number];++const VIEW_PANEL_TYPES: Record<ExplorerView, PANEL_TYPES> = {+ list: PANEL_TYPES.LIST,+ timeseries: PANEL_TYPES.TIME_SERIES,+ table: PANEL_TYPES.TABLE,+};++const LIST_FORMATS: readonly LogViewMode[] = ['table', 'list', 'raw'];++const FONT_SIZES = [FontSize.SMALL, FontSize.MEDIUM, FontSize.LARGE] as const;++/**+ * The list requests a page at a time, so a longer response is not a body the+ * backend can send.+ */+const PAGE_SIZE = 100;++/** Lines a raw-format row wraps to before it is clipped. */+const MAX_LINES_CAP = 10;++const QUERY_WARNING: Warning = {+ code: 'index_not_used',+ message: 'The query did not use an index and read the whole time range.',+ url: 'https://signoz.io/docs/userguide/logs/',+ warnings: [+ { message: 'body ILIKE cannot use the bloom filter on `body`.' },+ { message: 'severity_text is not indexed in this workspace.' },+ ],+};++const explorerRoute = (view: ExplorerView): string => {+ const panelType = encodeURIComponent(JSON.stringify(VIEW_PANEL_TYPES[view]));++ return `${ROUTES.LOGS_EXPLORER}?${QueryParams.panelTypes}=${panelType}&${QueryParams.relativeTime}=${RELATIVE_TIME}`;+};++export const logsMocks = defineStoryMocks({+ controls: {+ view: choiceControl<ExplorerView>('Explorer view', {+ group: EXPLORER,+ description:+ 'Which panel the explorer renders: the log list, the timeseries chart or the aggregated table.',+ options: EXPLORER_VIEWS,+ value: 'list',+ }),+ logs: countControl('Log lines', {+ group: EXPLORER,+ value: 30,+ max: PAGE_SIZE,+ }),+ severities: multiChoiceControl<LogSeverity>('Severities', {+ group: EXPLORER,+ description:+ 'Severities the logs carry, cycled through the list and stacked in the frequency chart. None selected reads as nothing matching the query.',+ options: LOG_SEVERITIES,+ value: LOG_SEVERITIES,+ }),+ frequencyChart: toggleControl('Frequency chart', {+ group: EXPLORER,+ description: 'The counts-per-severity chart above the log list.',+ value: true,+ }),+ warning: toggleControl('Query warning', {+ group: EXPLORER,+ description:+ 'A warning on the response, which the toolbar offers next to the run button.',+ value: false,+ }),+ format: choiceControl<LogViewMode>('Line format', {+ group: LIST,+ description:+ 'Columns, one line per log, or the raw line. Only the raw format reads the line limit.',+ options: LIST_FORMATS,+ value: 'table',+ }),+ maxLines: countControl('Max lines', {+ group: LIST,+ value: 1,+ max: MAX_LINES_CAP,+ }),+ fontSize: choiceControl<FontSize>('Font size', {+ group: LIST,+ options: FONT_SIZES,+ value: FontSize.SMALL,+ }),+ jsonBody: toggleControl('JSON body', {+ group: LIST,+ description:+ '`use_json_body`: the service logs JSON and the backend hands the body over parsed, so the body is a tree and its keys are queryable as `body.x`.',+ value: false,+ }),+ filtersPanel: toggleControl('Filters panel', {+ group: FILTERS,+ description: 'The quick filters panel down the left of the explorer.',+ value: true,+ }),+ quickFilters: countControl('Quick filters', {+ group: FILTERS,+ description:+ 'Filters the org configured for logs. Without any, the left panel offers to add some.',+ value: QUICK_FILTER_MAX,+ max: QUICK_FILTER_MAX,+ }),+ savedViews: countControl('Saved views', {+ group: FILTERS,+ description: 'The views the view picker above the query builder lists.',+ value: 4,+ max: SAVED_VIEW_MAX,+ }),+ },+ handlers: (values, response) => {+ const warning = values.warning ? QUERY_WARNING : undefined;++ return [+ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const timeWindow = { start: body.start, end: body.end };++ if (body.requestType === 'time_series') {+ // The frequency chart asks for counts grouped by severity; the+ // timeseries view asks the same aggregation without a group by.+ const spec = body.compositeQuery?.queries?.[0]?.spec as+ | BaseBuilderQuery+ | undefined;+ const bySeverity = (spec?.groupBy ?? []).some(+ (key) => key.name === 'severity_text',+ );++ return bySeverity+ ? logHistogramResponse(values.severities, timeWindow, { warning })+ : logTimeseriesResponse(timeWindow, { warning });+ }++ if (body.requestType === 'scalar') {+ return logCountResponse(values.severities);+ }++ return logRowsResponse(values.logs, values.severities, body.end, {+ jsonBody: values.jsonBody,+ warning,+ });+ }),+ ),++ rest.get(+ 'http://localhost/api/v2/quick_filters/:source',+ response.json(() => logsQuickFiltersResponse(values.quickFilters)),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ logFieldKeysResponse(req.url.searchParams.get('searchText') ?? '', {+ jsonBody: values.jsonBody,+ }),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ logFieldValuesResponse(+ req.url.searchParams.get('name') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ attributeValuesResponse(+ req.url.searchParams.get('attributeKey') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/explorer/views',+ response.json(() => logsSavedViewsResponse(values.savedViews)),+ ),++ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json(dashboardsResponse),+ ),+ ];+ },+ config: ({ view, jsonBody }) => ({+ route: explorerRoute(view),+ reduxState: timeRangeState(),+ appContext: jsonBody+ ? {+ featureFlags: [+ ...defaultFeatureFlags,+ {+ name: FeatureKeys.USE_JSON_BODY,+ active: true,+ usage: 0,+ usage_limit: -1,+ route: '',+ },+ ],+ }+ : {},+ }),+ effect: ({ frequencyChart, filtersPanel, format, maxLines, fontSize }) => {+ setLocalStorage(LOCALSTORAGE.SHOW_FREQUENCY_CHART, String(frequencyChart));+ setLocalStorage(LOCALSTORAGE.SHOW_LOGS_QUICK_FILTERS, String(filtersPanel));++ // The preferences loader reads localStorage ahead of the URL, so this is+ // what the options menu opens on.+ setLocalStorage(+ LOCALSTORAGE.LOGS_LIST_OPTIONS,+ JSON.stringify(logsListOptions({ format, maxLines, fontSize })),+ );+ },+});diff --git a/frontend/src/pages/LogsModulePage/stories/LogsModulePage.stories.tsx b/frontend/src/pages/LogsModulePage/stories/LogsModulePage.stories.tsxnew file mode 100644index 0000000000..0678f1b21b--- /dev/null+++ b/frontend/src/pages/LogsModulePage/stories/LogsModulePage.stories.tsx@@ -0,0 +1,198 @@+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 { logsMocks } from './LogsModulePage.stories.mocks';++import LogsModulePage from '../LogsModulePage';++type LogsArgs = PageStoryArgs<typeof logsMocks>;++const pageStory = storyMocks(logsMocks, { layout: 'app' });++/**+ * The logs explorer: the query builder, the list, the frequency chart and the log+ * detail drawer, with quick filters and saved views beside them.+ *+ * Route: `/logs/logs-explorer`.+ */+const meta = {+ title: 'Pages/Logs/Explorer',+ tags: ['play'],+ component: LogsModulePage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<LogsArgs>;++export default meta;++type Story = StoryObj<LogsArgs>;++/** The page fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++const openQuickFiltersSettings = async (): Promise<void> => {+ // The settings control renders disabled while its permission check is in+ // flight and is swapped for the enabled one once the check answers, so it is+ // looked up again on every attempt; a click on the disabled one is dropped in+ // silence.+ const control = await waitFor(() => {+ const settings = screen.getByTestId('settings-icon-container');++ expect(settings).toBeEnabled();++ return settings;+ }, untilLoaded);++ await userEvent.click(control);+ await screen.findByText('Edit quick filters');+};++/** Opening a log is what the drawer is for, and the first row will do. */+const openFirstLog = async (canvasElement: HTMLElement): Promise<void> => {+ const [row] = await within(canvasElement).findAllByTestId(+ /^logs-table-row-/,+ undefined,+ untilLoaded,+ );++ // The list hangs its click handler off the cells rather than the row, so a+ // click on the row itself opens nothing.+ const [, timestamp] = within(row).getAllByRole('cell');++ await userEvent.click(timestamp);+ await screen.findByTestId('log-detail-drawer', undefined, untilLoaded);+};++/**+ * The explorer on its list view: quick filters down the left, the frequency+ * chart over a page of log lines across every severity, and the org's saved+ * views in the view picker.+ */+export const Default: Story = {};++/** A workspace with logs ingesting but nothing matching the query. */+export const NoLogs: Story = {+ args: { logs: 0 },+};++/** One aggregated line over the selected range instead of the log lines. */+export const TimeseriesView: Story = {+ args: { view: 'timeseries' },+};++/** Aggregated log values rendered in the table explorer view. */+export const TableView: Story = {+ args: { view: 'table' },+};++/** Log lines rendered one per entry. */+export const ListFormat: Story = {+ args: { format: 'list' },+};++/** The raw log-body format with its line clipping. */+export const RawFormat: Story = {+ args: { format: 'raw' },+};++/** An explorer with no configured quick filters. */+export const NoQuickFilters: Story = {+ args: { quickFilters: 0 },+};++/** The query area with the quick-filter panel hidden. */+export const FiltersHidden: Story = {+ args: { filtersPanel: false },+};++/**+ * A service that logs JSON, with `use_json_body` on: the body is an object the+ * backend already parsed, and its keys can be filtered on as `body.x`.+ */+export const JsonBody: Story = {+ args: { jsonBody: true },+};++/** One log opened up: its own fields, then the resource that sent it. */+export const LogDetails: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openFirstLog(canvasElement);+ },+};++/** The logs either side of the one that was opened, on the same filters. */+export const LogDetailsContext: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openFirstLog(canvasElement);+ await userEvent.click(+ await screen.findByText('Context', undefined, untilLoaded),+ );+ // The tab queries the logs either side before it can render them.+ await screen.findAllByText(/cache lookup for cart/, undefined, untilLoaded);+ },+};++/** The log detail drawer with its header actions menu open. */+export const LogDetailsMenuOpen: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openFirstLog(canvasElement);+ await userEvent.click(await screen.findByTestId('log-details-header-menu'));+ await screen.findByText('Copy link to log');+ },+};++/** A response warning shown beside the query actions. */+export const QueryWarning: Story = {+ args: { warning: true },+};++/** The table waiting on its query. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** A failed logs query. */+export const Failed: Story = {+ args: { dataState: 'error' },+ // The mocked queries deliberately fail; the resulting console errors are the state under test.+ parameters: { allowConsoleErrors: true },+};++/** The editable quick-filter settings panel. */+export const QuickFiltersSettings: Story = {+ play: openQuickFiltersSettings,+};++/** Settings with an unsaved filter removal and the fixed action footer. */+export const QuickFiltersSettingsDirty: Story = {+ play: async (): Promise<void> => {+ await openQuickFiltersSettings();+ // One Remove per added filter; the first row's is the one clicked.+ const [removeFilter] = await screen.findAllByRole('button', {+ name: 'Remove',+ });++ await userEvent.click(removeFilter);+ await screen.findByRole('button', { name: 'Save changes' });+ },+};++/**+ * 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+ * previous and next log. The drawer steps forward one log first, because the+ * first log has nothing before it and the arrow keeps its tooltip shut while+ * disabled.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }): Promise<void> => {+ await openFirstLog(canvasElement);+ await userEvent.click(+ await screen.findByTestId('log-details-header-next', undefined, untilLoaded),+ );+ },+};diff --git a/frontend/src/pages/LogsModulePage/stories/__story_mockdata__/logs.ts b/frontend/src/pages/LogsModulePage/stories/__story_mockdata__/logs.tsnew file mode 100644index 0000000000..568689bae0--- /dev/null+++ b/frontend/src/pages/LogsModulePage/stories/__story_mockdata__/logs.ts@@ -0,0 +1,472 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ type GetFieldsKeys200,+ type GetFieldsValues200,+ type GetQuickFilters200,+ type ListDashboardsForUserV2200,+ QuickfiltertypesSourceDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesFieldDataTypeDTO,+ type TelemetrytypesTelemetryFieldKeyDTO,+} from 'api/generated/services/sigNoz.schemas';+import { defaultLogsSelectedColumns } from 'container/OptionsMenu/constants';+import type { OptionsQuery } from 'container/OptionsMenu/types';+import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';+import { quickFiltersListResponse } from 'mocks-server/__mockdata__/customQuickFilters';+import type { AppState } from 'store/reducers';+import type { Warning } from 'types/api';+import type { ILogBody } from 'types/api/logs/log';+import type { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';+import type { IGetAttributeSuggestionsSuccessResponse } from 'types/api/queryBuilder/getAttributeSuggestions';+import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';+import type { MetricRangePayloadV5, TimeSeries } from 'types/api/v5/queryRange';+import type { ListItem } from 'types/api/widgets/getQuery';++import { dashboardsForUserResponse } from '@/storybook/msw/__story_mockdata__/dashboards';+import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';+import {+ queryRangeV5RawResponse,+ queryRangeV5ScalarResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++export const RELATIVE_TIME: Time = '30m';++const THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;++const NANOSECONDS_IN_MS = 1_000_000;++/**+ * `globalTime` defaults its window from `window.location.pathname`, which in a+ * story is the preview's rather than the page's, so the time picker (reading the+ * route) and the queries (reading the store) would ask for different ranges and+ * a chart would draw a range narrower than its own axis.+ */+export const timeRangeState = (): Partial<AppState> => {+ const now = Date.now();++ return {+ globalTime: {+ minTime: (now - THIRTY_MINUTES_IN_MS) * NANOSECONDS_IN_MS,+ maxTime: now * NANOSECONDS_IN_MS,+ loading: false,+ selectedTime: RELATIVE_TIME,+ isAutoRefreshDisabled: false,+ selectedAutoRefreshInterval: '',+ },+ };+};++export const LOG_SEVERITIES = [+ 'TRACE',+ 'DEBUG',+ 'INFO',+ 'WARN',+ 'ERROR',+ 'FATAL',+] as const;++export type LogSeverity = (typeof LOG_SEVERITIES)[number];++/** OpenTelemetry severity numbers, which the list falls back to for colour. */+const SEVERITY_NUMBERS: Record<LogSeverity, number> = {+ TRACE: 1,+ DEBUG: 5,+ INFO: 9,+ WARN: 13,+ ERROR: 17,+ FATAL: 21,+};++const MESSAGES: Record<LogSeverity, string> = {+ TRACE: 'entering handler CheckoutService/PlaceOrder',+ DEBUG: 'cache lookup for cart:8412 took 1.4ms',+ INFO: 'order 8412 placed, 3 items, total 129.90 USD',+ WARN: 'retrying payment authorization, attempt 2 of 3',+ ERROR: 'payment authorization failed: gateway timeout after 5s',+ FATAL: 'connection pool exhausted, shutting down worker',+};++const SERVICES = ['frontend', 'checkout', 'payments', 'cart', 'auth'];++const PODS = ['checkout-7b9f4d', 'payments-5c8a12', 'frontend-9d3e77'];++interface LogRowData {+ id: string;+ body: string | ILogBody;+ severity_text: LogSeverity;+ severity_number: number;+ trace_id: string;+ span_id: string;+ trace_flags: number;+ attributes_string: Record<string, string>;+ resources_string: Record<string, string>;+ scope_string: Record<string, string>;+}++const hex = (index: number, length: number): string =>+ index.toString(16).padStart(length, '0');++/**+ * What a JSON-logging service sends, which the backend hands over pre-parsed+ * once `use_json_body` is on: an object rather than a line.+ */+const jsonBodyFor = (+ severity: LogSeverity,+ service: string,+ index: number,+): ILogBody => ({+ message: MESSAGES[severity],+ level: severity.toLowerCase(),+ service,+ order: {+ id: 8412 - index,+ items: 3,+ total: 129.9,+ currency: 'USD',+ coupons: ['WELCOME10', 'FREESHIP'],+ },+ http: { method: 'POST', route: '/api/v1/checkout', status_code: 200 },+});++export interface LogsResponseOptions {+ /** `use_json_body`: the body arrives as an object instead of a line. */+ jsonBody?: boolean;+ warning?: Warning;+}++export interface LogRow {+ timestamp: string;+ data: LogRowData;+}++/**+ * Newest first and one second apart, which is the order the list requests+ * (`timestamp:desc`) and the order pagination assumes.+ */+export const logRows = (+ count: number,+ severities: readonly LogSeverity[],+ endMilli: number,+ jsonBody: boolean,+): LogRow[] =>+ Array.from({ length: severities.length ? count : 0 }, (_unused, index) => {+ const severity = severities[index % severities.length];+ const service = SERVICES[index % SERVICES.length];+ const timestamp = new Date(endMilli - index * 1000).toISOString();++ return {+ timestamp,+ data: {+ id: `01JBQ${hex(index, 8).toUpperCase()}`,+ body: jsonBody+ ? jsonBodyFor(severity, service, index)+ : `${timestamp} ${severity} ${service} ${MESSAGES[severity]}`,+ severity_text: severity,+ severity_number: SEVERITY_NUMBERS[severity],+ trace_id: hex(index + 1, 32),+ span_id: hex(index + 1, 16),+ trace_flags: 1,+ attributes_string: {+ 'code.function': 'PlaceOrder',+ 'http.method': 'POST',+ 'http.route': '/api/v1/checkout',+ 'order.id': String(8412 - index),+ },+ resources_string: {+ 'service.name': service,+ 'deployment.environment': 'production',+ 'k8s.pod.name': PODS[index % PODS.length],+ },+ scope_string: {},+ },+ };+ });++export const logRowsResponse = (+ count: number,+ severities: readonly LogSeverity[],+ endMilli: number,+ { jsonBody = false, warning }: LogsResponseOptions = {},+): MetricRangePayloadV5 =>+ queryRangeV5RawResponse<LogRowData>(+ logRows(count, severities, endMilli, jsonBody),+ { warning },+ );++/**+ * The pipeline preview queries on `DEFAULT_ENTITY_VERSION`, so it reads its+ * sample logs off v3, where rows arrive as `list` and a count as a series.+ */+export const logRowsV3Response = (+ count: number,+ severities: readonly LogSeverity[],+ endMilli: number,+): { status: string } & MetricRangePayloadV3 => ({+ status: 'success',+ data: {+ resultType: '',+ result: [+ {+ queryName: 'A',+ series: null,+ // `ListItem['data']` is the frontend's `ILog`, which carries fields the+ // backend never sends.+ list: logRows(count, severities, endMilli, false) as unknown as ListItem[],+ },+ ],+ },+});++export const logCountV3Response = (+ value: number,+ endMilli: number,+): { status: string } & MetricRangePayloadV3 => ({+ status: 'success',+ data: {+ resultType: '',+ result: [+ {+ queryName: 'A',+ list: null,+ series: [+ {+ labels: {},+ labelsArray: [],+ values: [{ timestamp: endMilli, value: String(value) }],+ },+ ],+ },+ ],+ },+});++/** Counts per severity, which the frequency chart stacks and the legend names. */+export const logHistogramResponse = (+ severities: readonly LogSeverity[],+ window: { start: number; end: number },+ { warning }: Pick<LogsResponseOptions, 'warning'> = {},+): MetricRangePayloadV5 => {+ const series: TimeSeries[] = severities.map((severity, index) => ({+ labels: [{ key: { name: 'severity_text' }, value: severity }],+ values: timeSeriesPoints({+ ...window,+ base: 120 / (index + 1),+ amplitude: 40 / (index + 1),+ seed: index * 3,+ }),+ }));++ return queryRangeV5TimeSeriesResponse([{ queryName: 'A', series }], {+ warning,+ });+};++/** The timeseries view aggregates without a group by, so it draws one line. */+export const logTimeseriesResponse = (+ window: { start: number; end: number },+ { warning }: Pick<LogsResponseOptions, 'warning'> = {},+): MetricRangePayloadV5 =>+ queryRangeV5TimeSeriesResponse(+ [+ {+ queryName: 'A',+ series: [+ { values: timeSeriesPoints({ ...window, base: 420, amplitude: 90 }) },+ ],+ },+ ],+ { warning },+ );++export const logCountResponse = (+ severities: readonly LogSeverity[],+): MetricRangePayloadV5 => queryRangeV5ScalarResponse(severities.length * 1284);++export const QUICK_FILTER_MAX = quickFiltersListResponse.data.filters.length;++export const logsQuickFiltersResponse = (count: number): GetQuickFilters200 =>+ quickFiltersResponse(+ QuickfiltertypesSourceDTO.logs,+ quickFiltersListResponse.data.filters.slice(+ 0,+ count,+ ) as TelemetrytypesTelemetryFieldKeyDTO[],+ );++const { log, resource, attribute } = TelemetrytypesFieldContextDTO;+const { string: stringType, int64 } = TelemetrytypesFieldDataTypeDTO;++const LOG_FIELDS: TelemetrytypesTelemetryFieldKeyDTO[] = [+ { name: 'body', fieldContext: log, fieldDataType: stringType },+ { name: 'severity_text', fieldContext: log, fieldDataType: stringType },+ { name: 'service.name', fieldContext: resource, fieldDataType: stringType },+ {+ name: 'deployment.environment',+ fieldContext: resource,+ fieldDataType: stringType,+ },+ {+ name: 'k8s.namespace.name',+ fieldContext: resource,+ fieldDataType: stringType,+ },+ { name: 'k8s.pod.name', fieldContext: resource, fieldDataType: stringType },+ { name: 'http.route', fieldContext: attribute, fieldDataType: stringType },+ { name: 'http.status_code', fieldContext: attribute, fieldDataType: int64 },+];++/**+ * With `use_json_body` on, the keys inside the body are queryable in their own+ * right, so the query builder offers them alongside the log's own fields.+ */+const BODY_JSON_FIELDS: TelemetrytypesTelemetryFieldKeyDTO[] = [+ { name: 'body.level', fieldContext: log, fieldDataType: stringType },+ { name: 'body.service', fieldContext: log, fieldDataType: stringType },+ { name: 'body.order.id', fieldContext: log, fieldDataType: int64 },+ { name: 'body.http.method', fieldContext: log, fieldDataType: stringType },+ {+ name: 'body.http.status_code',+ fieldContext: log,+ fieldDataType: int64,+ },+];++export const logFieldKeysResponse = (+ searchText: string,+ { jsonBody = false }: Pick<LogsResponseOptions, 'jsonBody'> = {},+): GetFieldsKeys200 => {+ const fields = jsonBody ? [...LOG_FIELDS, ...BODY_JSON_FIELDS] : LOG_FIELDS;+ const matches = fields.filter((field) =>+ field.name.includes(searchText.toLowerCase()),+ );++ return {+ status: 'success',+ data: {+ complete: true,+ keys: Object.fromEntries(matches.map((field) => [field.name, [field]])),+ },+ };+};++/** Keyed by the fields the quick filters and the query builder ask about. */+const STRING_VALUES: Record<string, string[]> = {+ severity_text: [...LOG_SEVERITIES],+ 'service.name': SERVICES,+ 'service.namespace': ['checkout', 'platform'],+ 'service.instance.id': ['checkout-0', 'checkout-1', 'payments-0'],+ 'deployment.environment': ['production', 'staging', 'development'],+ 'k8s.namespace.name': ['default', 'checkout', 'observability'],+ 'k8s.pod.name': PODS,+ 'k8s.cluster.name': ['us-east-1', 'eu-west-1'],+ 'k8s.deployment.name': ['checkout', 'payments', 'frontend'],+ 'host.name': ['ip-10-0-1-14', 'ip-10-0-2-31'],+ 'os.description': ['Linux 6.8.0 x86_64', 'Darwin 23.5.0 arm64'],+ 'process.owner': ['root', 'app'],+ 'http.route': ['/api/v1/checkout', '/api/v1/cart', '/api/v1/auth/token'],+ 'body.level': LOG_SEVERITIES.map((severity) => severity.toLowerCase()),+ 'body.service': SERVICES,+ 'body.http.method': ['POST', 'GET', 'DELETE'],+};++const NUMBER_VALUES: Record<string, number[]> = {+ duration_nano: [1_200_000, 8_400_000, 32_000_000],+ quantity: [1, 3, 12],+ 'http.status_code': [200, 404, 500],+ 'body.order.id': [8412, 8411, 8410],+ 'body.http.status_code': [200, 404, 500],+};++const matching = <TValue>(values: TValue[], searchText: string): TValue[] =>+ searchText+ ? values.filter((value) =>+ String(value).toLowerCase().includes(searchText.toLowerCase()),+ )+ : values;++export const logFieldValuesResponse = (+ name: string,+ searchText: string,+): GetFieldsValues200 => ({+ status: 'success',+ data: {+ complete: true,+ values: {+ stringValues: matching(STRING_VALUES[name] ?? [], searchText),+ numberValues: matching(NUMBER_VALUES[name] ?? [], searchText),+ relatedValues: [],+ },+ },+});++/**+ * The quick filters read values off the v3 autocomplete endpoint rather than+ * `/fields/values`, and it answers numbers as strings.+ */+export const attributeValuesResponse = (+ attributeKey: string,+ searchText: string,+): { status: string; data: IAttributeValuesResponse } => ({+ status: 'success',+ data: {+ stringAttributeValues: matching(+ STRING_VALUES[attributeKey] ?? [],+ searchText,+ ),+ numberAttributeValues: matching(+ NUMBER_VALUES[attributeKey] ?? [],+ searchText,+ ).map(String),+ boolAttributeValues: null,+ },+});++/**+ * What the query builder's search box offers while a filter is being typed. The+ * types are the v3 spelling of the same fields the v5 endpoints answer with.+ */+export const filterSuggestionsResponse = (+ searchText: string,+): { status: string; data: IGetAttributeSuggestionsSuccessResponse } => ({+ status: 'success',+ data: {+ attributes: LOG_FIELDS.filter((field) =>+ field.name.includes(searchText.toLowerCase()),+ ).map((field) => ({+ key: field.name,+ dataType: field.fieldDataType === int64 ? DataTypes.Int64 : DataTypes.String,+ type: field.fieldContext === resource ? 'resource' : 'tag',+ })),+ example_queries: [],+ },+});++/**+ * The list's own options: the loader reads localStorage ahead of the URL, so+ * this is what decides the format, and the columns have to be in it or the list+ * loses `body` and `timestamp`.+ */+export const logsListOptions = (+ options: Pick<OptionsQuery, 'format' | 'maxLines' | 'fontSize'>,+): OptionsQuery => ({+ selectColumns: defaultLogsSelectedColumns,+ version: 1,+ ...options,+});++const DASHBOARD_NAMES = [+ 'Logs overview',+ 'Checkout health',+ 'Kubernetes workloads',+ 'Ingestion volume',+];++export const dashboardsResponse = (): ListDashboardsForUserV2200 =>+ dashboardsForUserResponse(DASHBOARD_NAMES);diff --git a/frontend/src/pages/LogsSettings/stories/LogsSettings.stories.mocks.tsx b/frontend/src/pages/LogsSettings/stories/LogsSettings.stories.mocks.tsxnew file mode 100644index 0000000000..e8d08f9986--- /dev/null+++ b/frontend/src/pages/LogsSettings/stories/LogsSettings.stories.mocks.tsx@@ -0,0 +1,17 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';++import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++/**+ * The page is a tab strip over one tab, and the tab's body is a placeholder:+ * nothing here is fetched, so there is nothing to turn.+ */+export const logsSettingsMocks = defineStoryMocks({+ controls: {},+ config: () => ({ route: ROUTES.LOGS_INDEX_FIELDS }),+});diff --git a/frontend/src/pages/LogsSettings/stories/LogsSettings.stories.tsx b/frontend/src/pages/LogsSettings/stories/LogsSettings.stories.tsxnew file mode 100644index 0000000000..e3eb3a6663--- /dev/null+++ b/frontend/src/pages/LogsSettings/stories/LogsSettings.stories.tsx@@ -0,0 +1,33 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import LogsSettings from '../index';+import { logsSettingsMocks } from './LogsSettings.stories.mocks';++type LogsSettingsArgs = PageStoryArgs<typeof logsSettingsMocks>;++const pageStory = storyMocks(logsSettingsMocks, { layout: 'app' });++/**+ * The logs settings page, which opens on its index fields tab.+ *+ * Route: `/logs-explorer/index-fields`.+ */+const meta = {+ title: 'Pages/Logs/Settings',+ component: LogsSettings,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<LogsSettingsArgs>;++export default meta;++type Story = StoryObj<LogsSettingsArgs>;++/**+ * The index-fields tab, which is where the logs settings page opens and the+ * only tab it has. The tab body is still a placeholder in the app.+ */+export const Default: Story = {};diff --git a/frontend/src/pages/MessagingQueues/CeleryTask/stories/CeleryTask.stories.mocks.tsx b/frontend/src/pages/MessagingQueues/CeleryTask/stories/CeleryTask.stories.mocks.tsxnew file mode 100644index 0000000000..02210e37a7--- /dev/null+++ b/frontend/src/pages/MessagingQueues/CeleryTask/stories/CeleryTask.stories.mocks.tsx@@ -0,0 +1,110 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import type { QueryRangePayload } from 'types/api/metrics/getQueryRange';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ attributeValuesResponse,+ queryRangeV3ForRequest,+ timeRangeState,+} from '../../stories/__story_mockdata__/messagingQueues';+import {+ celeryStateCountResponse,+ groupsByWorker,+ TASK_HEALTH_STATES,+ type TaskHealth,+} from './__story_mockdata__/celeryTask';++const TASKS = 'Celery · tasks';+const GRAPHS = 'Celery · graphs';++/** Worker names the metrics carry, which is what the online card counts. */+const WORKER_MAX = 3;++export const celeryTaskMocks = defineStoryMocks({+ controls: {+ tasks: countControl('Tasks run', {+ group: TASKS,+ description:+ 'The all-states counter above the state graph, which the other three are a share of.',+ value: 1200,+ max: 5000,+ }),+ health: choiceControl<TaskHealth>('Task health', {+ group: TASKS,+ description:+ 'How the run splits across success, retry and failure, which is what the counters and the state graph tabs show.',+ options: TASK_HEALTH_STATES,+ value: 'degraded',+ }),+ workers: countControl('Workers online', {+ group: TASKS,+ description:+ 'Workers the flower metrics report: the card next to the active tasks graph counts them, and the per-worker charts draw one line each.',+ value: WORKER_MAX,+ max: WORKER_MAX,+ }),+ series: countControl('Graph series', {+ group: GRAPHS,+ description:+ 'Lines the span-based charts draw per task. The per-worker charts follow the worker count instead.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => {+ const queryRange = response.json(async (req) => {+ const body = (await req.json()) as QueryRangePayload;++ return (+ celeryStateCountResponse(body, values.tasks, values.health) ??+ queryRangeV3ForRequest(+ body,+ groupsByWorker(body) ? values.workers : values.series,+ )+ );+ });++ return [+ rest.post('http://localhost/api/v3/query_range', queryRange),+ rest.post('http://localhost/api/v4/query_range', queryRange),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) => {+ const attributeKey = req.url.searchParams.get('attributeKey') ?? '';+ const values_ = attributeValuesResponse(+ attributeKey,+ req.url.searchParams.get('searchText') ?? '',+ );++ if (attributeKey !== 'worker') {+ return values_;+ }++ return {+ ...values_,+ data: {+ ...values_.data,+ stringAttributeValues: (values_.data.stringAttributeValues ?? []).slice(+ 0,+ values.workers,+ ),+ },+ };+ }),+ ),+ ];+ },+ config: () => ({+ route: ROUTES.MESSAGING_QUEUES_CELERY_TASK,+ reduxState: timeRangeState(),+ }),+});diff --git a/frontend/src/pages/MessagingQueues/CeleryTask/stories/CeleryTask.stories.tsx b/frontend/src/pages/MessagingQueues/CeleryTask/stories/CeleryTask.stories.tsxnew file mode 100644index 0000000000..00b3c2b11c--- /dev/null+++ b/frontend/src/pages/MessagingQueues/CeleryTask/stories/CeleryTask.stories.tsx@@ -0,0 +1,67 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { celeryTaskMocks } from './CeleryTask.stories.mocks';++import MessagingQueuesMainPage from '../../MessagingQueuesMainPage';++type CeleryTaskArgs = PageStoryArgs<typeof celeryTaskMocks>;++const pageStory = storyMocks(celeryTaskMocks, { layout: 'app' });++/**+ * Celery tasks over the period: state per task, the workers running them, and the+ * slowest and failing ones.+ *+ * Route: `/messaging-queues/celery-task`.+ */+const meta = {+ title: 'Pages/Messaging Queues/Celery',+ tags: ['play'],+ component: MessagingQueuesMainPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<CeleryTaskArgs>;++export default meta;++type Story = StoryObj<CeleryTaskArgs>;++/** The counters fetch before the tabs settle, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The celery tab: flower's per-worker metrics up top, then the span-based view+ * of every task run, split by state and broken down per worker.+ */+export const Default: Story = {};++/** A run where a fifth of the tasks fail and a quarter are retried. */+export const FailingTasks: Story = {+ args: { health: 'failing' },+};++/** The state graph narrowed to the runs that failed, over the same range. */+export const FailedTasksOnly: Story = {+ args: { health: 'failing' },+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText('Failed', undefined, untilLoaded),+ );+ // The panel the tab opens carries the same label as the tab itself.+ await waitFor(+ () => expect(canvas.getAllByText('Failed')).toHaveLength(2),+ untilLoaded,+ );+ },+};++/** Flower not scraped: the worker card counts nothing and its charts are empty. */+export const NoFlowerMetrics: Story = {+ args: { workers: 0 },+};diff --git a/frontend/src/pages/MessagingQueues/CeleryTask/stories/__story_mockdata__/celeryTask.ts b/frontend/src/pages/MessagingQueues/CeleryTask/stories/__story_mockdata__/celeryTask.tsnew file mode 100644index 0000000000..daee6f2638--- /dev/null+++ b/frontend/src/pages/MessagingQueues/CeleryTask/stories/__story_mockdata__/celeryTask.ts@@ -0,0 +1,110 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { QueryRangePayload } from 'types/api/metrics/getQueryRange';+import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';++import {+ type QueryRangeV3Body,+ queryRangeV3TimeSeriesResponse,+ v3Series,+} from '@/storybook/msw/__story_mockdata__/queryRange';++export const TASK_HEALTH_STATES = ['healthy', 'degraded', 'failing'] as const;++export type TaskHealth = (typeof TASK_HEALTH_STATES)[number];++/** Share of tasks that end in each terminal state, per health. */+const FAILURE_SHARE: Record<TaskHealth, { failed: number; retried: number }> = {+ healthy: { failed: 0.004, retried: 0.011 },+ degraded: { failed: 0.038, retried: 0.092 },+ failing: { failed: 0.21, retried: 0.27 },+};++const CELERY_STATE_KEY = 'celery.state';++/**+ * The four counters above the state graph are four `VALUE` requests that differ+ * only by their `celery.state` filter, so the split has to be read off the+ * request rather than answered the same way four times.+ */+const filteredState = (body: QueryRangePayload): string | undefined => {+ const queries = Object.values(body.compositeQuery.builderQueries ?? {});++ for (const query of queries) {+ const items = (query as IBuilderQuery).filters?.items ?? [];+ const stateFilter = items.find((item) => item.key?.key === CELERY_STATE_KEY);++ if (stateFilter) {+ return String(stateFilter.value);+ }+ }++ return undefined;+};++const countFor = (+ state: string | undefined,+ tasks: number,+ health: TaskHealth,+): number => {+ const { failed, retried } = FAILURE_SHARE[health];++ if (state === 'FAILURE') {+ return Math.round(tasks * failed);+ }++ if (state === 'RETRY') {+ return Math.round(tasks * retried);+ }++ if (state === 'SUCCESS') {+ return Math.round(tasks * (1 - failed - retried));+ }++ return tasks;+};++/**+ * Answers a state counter, or `null` when the request is one of the page's other+ * `VALUE` panels and the generic builder should take it.+ */+export const celeryStateCountResponse = (+ body: QueryRangePayload,+ tasks: number,+ health: TaskHealth,+): QueryRangeV3Body | null => {+ const queries = Object.values(body.compositeQuery.builderQueries ?? {});+ const aggregatesSpans = queries.some(+ (query) => (query as IBuilderQuery).aggregateAttribute?.key === 'span_id',+ );++ if (!aggregatesSpans) {+ return null;+ }++ return queryRangeV3TimeSeriesResponse([+ {+ queryName: 'A',+ series: [+ v3Series({}, [+ {+ timestamp: body.end,+ value: String(countFor(filteredState(body), tasks, health)),+ },+ ]),+ ],+ },+ ]);+};++/**+ * The flower graphs and the online-worker card read the same set of workers, so+ * a request grouped by `worker` has to draw as many lines as the card counts.+ */+export const groupsByWorker = (body: QueryRangePayload): boolean =>+ Object.values(body.compositeQuery.builderQueries ?? {}).some((query) =>+ ((query as IBuilderQuery).groupBy ?? []).some((key) => key.key === 'worker'),+ );diff --git a/frontend/src/pages/MessagingQueues/MQDetailPage/stories/MQDetailPage.stories.mocks.tsx b/frontend/src/pages/MessagingQueues/MQDetailPage/stories/MQDetailPage.stories.mocks.tsxnew file mode 100644index 0000000000..790bb4eefe--- /dev/null+++ b/frontend/src/pages/MessagingQueues/MQDetailPage/stories/MQDetailPage.stories.mocks.tsx@@ -0,0 +1,132 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import type { MessagingQueuesViewTypeOptions } from 'pages/MessagingQueues/MessagingQueuesUtils';+import type { QueryRangePayload } from 'types/api/metrics/getQueryRange';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ attributeValuesResponse,+ queryRangeV3ForRequest,+ timeRangeState,+} from '../../stories/__story_mockdata__/messagingQueues';+import {+ consumerLagDetails,+ KAFKA_VIEWS,+ kafkaDetailRoute,+ partitionLatencyDetails,+ partitionLatencyOverview,+ spanEvaluationResponse,+ topicThroughputDetails,+ topicThroughputOverview,+} from './__story_mockdata__/kafkaDetail';++const VIEWS = 'Kafka detail · views';+const DATA = 'Kafka detail · data';++/** Rows past the tenth are a second page, which is where the pager appears. */+const TABLE_MAX = 24;++export const kafkaDetailMocks = defineStoryMocks({+ controls: {+ view: choiceControl<MessagingQueuesViewTypeOptions>('View', {+ group: VIEWS,+ description:+ 'The view the `mqServiceView` param selects, which is also what the header dropdown writes.',+ options: KAFKA_VIEWS,+ value: KAFKA_VIEWS[0],+ }),+ selected: toggleControl('Row selected', {+ group: VIEWS,+ description:+ 'Whether the route already carries the co-ordinate or row the tables at the bottom need. Without it they ask to be clicked on.',+ value: true,+ }),+ rows: countControl('Table rows', {+ group: DATA,+ value: 12,+ max: TABLE_MAX,+ }),+ series: countControl('Graph series', {+ group: DATA,+ description:+ 'Lines each chart draws: the consumer lag graph groups by consumer group, topic and partition, the metric view by broker.',+ value: 4,+ max: 8,+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v1/messaging-queues/kafka/consumer-lag/:detailType',+ response.json((req) =>+ consumerLagDetails(String(req.params.detailType), values.rows),+ ),+ ),++ rest.post(+ 'http://localhost/api/v1/messaging-queues/kafka/partition-latency/overview',+ response.json(() => partitionLatencyOverview(values.rows)),+ ),++ rest.post(+ 'http://localhost/api/v1/messaging-queues/kafka/partition-latency/consumer',+ response.json(() => partitionLatencyDetails(values.rows)),+ ),++ rest.post(+ 'http://localhost/api/v1/messaging-queues/kafka/topic-throughput/:detailType',+ response.json((req) => {+ const detailType = String(req.params.detailType);++ return detailType.endsWith('-details')+ ? topicThroughputDetails(values.rows)+ : topicThroughputOverview(detailType, values.rows);+ }),+ ),++ rest.post(+ 'http://localhost/api/v1/messaging-queues/kafka/span/evaluation',+ response.json(async (req) => {+ const body = (await req.json()) as { end: number };++ return {+ status: 'success',+ data: spanEvaluationResponse(values.rows, body.end / 1e6),+ };+ }),+ ),++ rest.post(+ 'http://localhost/api/v3/query_range',+ response.json(async (req) =>+ queryRangeV3ForRequest(+ (await req.json()) as QueryRangePayload,+ values.series,+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ attributeValuesResponse(+ req.url.searchParams.get('attributeKey') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),+ ],+ config: ({ view, selected }) => ({+ route: kafkaDetailRoute(view, selected),+ reduxState: timeRangeState(),+ }),+});diff --git a/frontend/src/pages/MessagingQueues/MQDetailPage/stories/MQDetailPage.stories.tsx b/frontend/src/pages/MessagingQueues/MQDetailPage/stories/MQDetailPage.stories.tsxnew file mode 100644index 0000000000..3c8b07a0c1--- /dev/null+++ b/frontend/src/pages/MessagingQueues/MQDetailPage/stories/MQDetailPage.stories.tsx@@ -0,0 +1,104 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { MessagingQueuesViewTypeOptions } from 'pages/MessagingQueues/MessagingQueuesUtils';+import { expect, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { kafkaDetailMocks } from './MQDetailPage.stories.mocks';++import MessagingQueuesMainPage from '../../MessagingQueuesMainPage';++type KafkaDetailArgs = PageStoryArgs<typeof kafkaDetailMocks>;++const pageStory = storyMocks(kafkaDetailMocks, { layout: 'app' });++/**+ * Kafka consumer lag, partition latency and topic throughput for the view the+ * route names, drilled into by the co-ordinate it carries.+ *+ * Route: `/messaging-queues/kafka/detail`.+ */+const meta = {+ title: 'Pages/Messaging Queues/Kafka Detail',+ tags: ['play'],+ component: MessagingQueuesMainPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<KafkaDetailArgs>;++export default meta;++type Story = StoryObj<KafkaDetailArgs>;++/** The tables fetch after the view has rendered, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * Consumer lag over the selected consumer groups, topics and partitions, with+ * the producer, consumer and network latency tables for the co-ordinate that is+ * selected on the graph.+ */+export const Default: Story = {};++/** The same view before anything on the graph has been clicked. */+export const NothingSelected: Story = {+ args: { selected: false },+};++/**+ * The round trip between the selected producer and consumer, which is the one+ * detail tab with a client and an instance of its own.+ */+export const NetworkLatency: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText('Network Latency', undefined, untilLoaded),+ );+ // The table refetches for the tab, and titles itself after it: the label is+ // on the toggle and on the table once the swap is through.+ await waitFor(+ () => expect(canvas.getAllByText('Network Latency')).toHaveLength(2),+ untilLoaded,+ );+ },+};++/** Latency per topic partition, and the producers writing to the selected one. */+export const PartitionLatency: Story = {+ args: { view: MessagingQueuesViewTypeOptions.PartitionLatency },+};++/** Throughput per producer and topic, with the byte rate merged in. */+export const ProducerLatency: Story = {+ args: { view: MessagingQueuesViewTypeOptions.ProducerLatency },+};++/** The consumers of the same topics, which the toggle above the table swaps to. */+export const ProducerLatencyConsumers: Story = {+ args: { view: MessagingQueuesViewTypeOptions.ProducerLatency },+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByText('Consumers', undefined, untilLoaded),+ );+ // Byte Rate is the column only the producer table has.+ await waitFor(+ () => expect(canvas.queryByText('Byte Rate')).not.toBeInTheDocument(),+ untilLoaded,+ );+ },+};++/** Producer/consumer pairs whose spans breached the evaluation interval. */+export const DropRate: Story = {+ args: { view: MessagingQueuesViewTypeOptions.DropRate },+};++/** The broker, producer, consumer and JVM metrics kafka itself reports. */+export const MetricView: Story = {+ args: { view: MessagingQueuesViewTypeOptions.MetricPage },+};diff --git a/frontend/src/pages/MessagingQueues/MQDetailPage/stories/__story_mockdata__/kafkaDetail.ts b/frontend/src/pages/MessagingQueues/MQDetailPage/stories/__story_mockdata__/kafkaDetail.tsnew file mode 100644index 0000000000..c8b9e4a698--- /dev/null+++ b/frontend/src/pages/MessagingQueues/MQDetailPage/stories/__story_mockdata__/kafkaDetail.ts@@ -0,0 +1,276 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { MessagingQueuesPayloadProps } from 'api/messagingQueues/getConsumerLagDetails';+import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import type { DropRateAPIResponse } from 'pages/MessagingQueues/MQDetails/DropRateView/dropRateViewUtils';+import {+ MessagingQueueServiceDetailType,+ MessagingQueuesViewTypeOptions,+} from 'pages/MessagingQueues/MessagingQueuesUtils';++import {+ CONSUMER_GROUPS,+ KAFKA_SERVICES,+ kafkaTableResponse,+ PARTITIONS,+ RELATIVE_TIME,+ seeded,+ TOPICS,+} from '../../../stories/__story_mockdata__/messagingQueues';++export const KAFKA_VIEWS = [+ MessagingQueuesViewTypeOptions.ConsumerLag,+ MessagingQueuesViewTypeOptions.PartitionLatency,+ MessagingQueuesViewTypeOptions.ProducerLatency,+ MessagingQueuesViewTypeOptions.DropRate,+ MessagingQueuesViewTypeOptions.MetricPage,+] as const;++/** The row the details tables render for, as the page writes it on a click. */+const SELECTED_TIMELINE = {+ group: CONSUMER_GROUPS[0],+ topic: TOPICS[0],+ partition: PARTITIONS[0],+};++const SELECTED_PARTITION = {+ topic: TOPICS[0],+ partition: PARTITIONS[0],+};++const SELECTED_PRODUCER = {+ topic: TOPICS[0],+ service_name: KAFKA_SERVICES[0],+};++/**+ * `setConfigDetail` and `setSelectedTimelineQuery` both write their JSON through+ * `encodeURIComponent` before `URLSearchParams` encodes it again, and the page+ * decodes twice on the way back, so a route that seeds a selection has to carry+ * the same double encoding.+ */+const selectionParam = (value: unknown): string =>+ encodeURIComponent(JSON.stringify(value));++const FIVE_MINUTES_IN_MS = 5 * 60 * 1000;++const timelineSelection = (): string => {+ const now = Date.now();++ return selectionParam({+ ...SELECTED_TIMELINE,+ start: now - FIVE_MINUTES_IN_MS,+ end: now,+ });+};++export const kafkaDetailRoute = (+ view: MessagingQueuesViewTypeOptions,+ selected: boolean,+): string => {+ const params = new URLSearchParams({+ [QueryParams.mqServiceView]: view,+ [QueryParams.relativeTime]: RELATIVE_TIME,+ });++ if (selected && view === MessagingQueuesViewTypeOptions.ConsumerLag) {+ params.set(QueryParams.selectedTimelineQuery, timelineSelection());+ }++ if (selected && view === MessagingQueuesViewTypeOptions.PartitionLatency) {+ params.set(QueryParams.configDetail, selectionParam(SELECTED_PARTITION));+ }++ if (selected && view === MessagingQueuesViewTypeOptions.ProducerLatency) {+ params.set(QueryParams.configDetail, selectionParam(SELECTED_PRODUCER));+ }++ return `${ROUTES.MESSAGING_QUEUES_KAFKA_DETAIL}?${params.toString()}`;+};++type KafkaTable = {+ status: string;+ data: MessagingQueuesPayloadProps['payload'];+};++const rowsOf = (+ count: number,+ build: (index: number) => Record<string, string>,+): Array<Record<string, string>> =>+ Array.from({ length: count }, (_u, i) => build(i));++const metric = (index: number, base: number, spread: number): string =>+ String(seeded(index, base, spread));++const serviceRows = (+ count: number,+ offset = 0,+): Array<Record<string, string>> =>+ rowsOf(count, (index) => ({+ service_name: KAFKA_SERVICES[(index + offset) % KAFKA_SERVICES.length],+ p99: metric(index, 120, 400),+ error_rate: metric(index, 0, 12),+ throughput: metric(index, 30, 250),+ }));++/** The three tabs under the consumer lag graph, each on its own detail type. */+export const consumerLagDetails = (+ detailType: string,+ count: number,+): KafkaTable => {+ if (detailType === MessagingQueueServiceDetailType.NetworkLatency) {+ return kafkaTableResponse(+ [+ 'consumer_service',+ 'service_instance_id',+ 'client_id',+ 'p99',+ 'throughput',+ ],+ rowsOf(count, (index) => ({+ consumer_service: KAFKA_SERVICES[index % KAFKA_SERVICES.length],+ service_instance_id: `instance-${index % 4}`,+ client_id: `${CONSUMER_GROUPS[index % CONSUMER_GROUPS.length]}-${index % 3}`,+ p99: metric(index, 90, 320),+ throughput: metric(index, 20, 180),+ })),+ ['p99', 'throughput'],+ );+ }++ const isConsumer =+ detailType === MessagingQueueServiceDetailType.ConsumerDetails;++ return kafkaTableResponse(+ isConsumer+ ? ['service_name', 'p99', 'error_rate', 'throughput', 'avg_msg_size']+ : ['service_name', 'p99', 'error_rate', 'throughput'],+ serviceRows(count, isConsumer ? 1 : 0).map((row, index) =>+ isConsumer ? { ...row, avg_msg_size: metric(index, 400, 2400) } : row,+ ),+ ['p99', 'error_rate', 'throughput', 'avg_msg_size'],+ );+};++/** The partition latency overview, whose rows carry the topic and partition+ * the details tables below it need. */+export const partitionLatencyOverview = (count: number): KafkaTable =>+ kafkaTableResponse(+ ['topic', 'partition', 'p99', 'error_rate', 'throughput'],+ rowsOf(count, (index) => ({+ topic: TOPICS[index % TOPICS.length],+ partition: PARTITIONS[index % PARTITIONS.length],+ p99: metric(index, 150, 380),+ error_rate: metric(index, 0, 9),+ throughput: metric(index, 40, 300),+ })),+ ['p99', 'error_rate', 'throughput'],+ );++export const partitionLatencyDetails = (count: number): KafkaTable =>+ kafkaTableResponse(+ ['service_name', 'p99', 'error_rate', 'throughput'],+ serviceRows(count),+ ['p99', 'error_rate', 'throughput'],+ );++/**+ * The producer side of the topic throughput overview answers two tables: the+ * page merges `byte_rate` from the second onto the first, keyed by+ * `service_name--topic`, and renders it as a column the first table never had.+ */+export const topicThroughputOverview = (+ detailType: string,+ count: number,+): KafkaTable => {+ const rows = rowsOf(count, (index) => ({+ service_name: KAFKA_SERVICES[index % KAFKA_SERVICES.length],+ topic: TOPICS[index % TOPICS.length],+ p99: metric(index, 110, 360),+ error_rate: metric(index, 0, 7),+ throughput: metric(index, 25, 210),+ ingestion_rate: metric(index, 500, 4200),+ }));++ const overview = kafkaTableResponse(+ [+ 'service_name',+ 'topic',+ 'p99',+ 'error_rate',+ 'throughput',+ 'ingestion_rate',+ ],+ rows,+ ['p99', 'error_rate', 'throughput', 'ingestion_rate'],+ );++ if (detailType !== 'producer') {+ return overview;+ }++ const byteRate = kafkaTableResponse(+ ['service_name', 'topic', 'byte_rate'],+ rows.map((row, index) => ({+ service_name: row.service_name,+ topic: row.topic,+ byte_rate: metric(index, 1200, 8600),+ })),+ ['byte_rate'],+ );++ return {+ status: 'success',+ data: {+ resultType: 'table',+ result: [...overview.data.result, ...byteRate.data.result],+ },+ };+};++export const topicThroughputDetails = (count: number): KafkaTable =>+ kafkaTableResponse(+ ['service_name', 'p99', 'error_rate', 'throughput'],+ serviceRows(count, 2),+ ['p99', 'error_rate', 'throughput'],+ );++/** Trace ids the drop rate table lists four at a time behind a "+ n more". */+const traceIds = (index: number): string[] =>+ Array.from({ length: 7 }, (_u, position) => {+ const seed = (index + 1) * 977 + position * 31;++ return Array.from({ length: 4 }, (_v, chunk) =>+ ((seed * (chunk + 7) * 0x1f123bb5) % 0xffffffff)+ .toString(16)+ .padStart(8, '0')+ .slice(-8),+ ).join('');+ });++export const spanEvaluationResponse = (+ count: number,+ timestamp: number,+): DropRateAPIResponse['data'] => ({+ resultType: 'list',+ result: [+ {+ queryName: 'A',+ list: Array.from({ length: count }, (_u, index) => ({+ timestamp: new Date(timestamp).toISOString(),+ data: {+ producer_service: KAFKA_SERVICES[index % KAFKA_SERVICES.length],+ consumer_service: KAFKA_SERVICES[(index + 1) % KAFKA_SERVICES.length],+ breach_percentage: seeded(index, 0, 45),+ breached_spans: 40 + index * 13,+ total_spans: 4000 + index * 317,+ top_traceIDs: traceIds(index),+ },+ })),+ },+ ],+});diff --git a/frontend/src/pages/MessagingQueues/Overview/stories/Overview.stories.mocks.tsx b/frontend/src/pages/MessagingQueues/Overview/stories/Overview.stories.mocks.tsxnew file mode 100644index 0000000000..ecca72cc52--- /dev/null+++ b/frontend/src/pages/MessagingQueues/Overview/stories/Overview.stories.mocks.tsx@@ -0,0 +1,108 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import type { QueryRangePayload } from 'types/api/metrics/getQueryRange';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ attributeValuesResponse,+ queryRangeV3ForRequest,+ timeRangeState,+} from '../../stories/__story_mockdata__/messagingQueues';+import {+ MESSAGING_SYSTEMS,+ type MessagingSystemFilter,+ overviewValueResponse,+ queueOverviewResponse,+} from './__story_mockdata__/queueOverview';++const QUEUES = 'Overview · queues';+const DETAIL = 'Overview · detail';++/** The table pages at twenty, so the cap has to leave room for a second page. */+const QUEUE_MAX = 40;++export const queueOverviewMocks = defineStoryMocks({+ controls: {+ queues: countControl('Queues', {+ group: QUEUES,+ value: 14,+ max: QUEUE_MAX,+ }),+ system: choiceControl<MessagingSystemFilter>('Messaging system', {+ group: QUEUES,+ description:+ 'Which broker the rows report. The detail panel filters celery destinations on a different attribute than everything else.',+ options: MESSAGING_SYSTEMS,+ value: 'mixed',+ }),+ failing: toggleControl('Failing queues', {+ group: QUEUES,+ description:+ 'Pushes every third row past the error thresholds the progress bar colours amber and red at.',+ value: false,+ }),+ series: countControl('Detail series', {+ group: DETAIL,+ description: 'Lines the charts in the right panel draw per group.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => {+ const queryRange = response.json(async (req) => {+ const body = (await req.json()) as QueryRangePayload;++ return (+ overviewValueResponse(body, values.failing) ??+ queryRangeV3ForRequest(body, values.series)+ );+ });++ return [+ rest.post(+ 'http://localhost/api/v1/messaging-queues/queue-overview',+ response.json(async (req) => {+ const body = (await req.json()) as { end: number };++ return {+ status: 'success',+ data: queueOverviewResponse(+ values.queues,+ values.system,+ values.failing,+ body.end / 1e6,+ ),+ };+ }),+ ),++ rest.post('http://localhost/api/v3/query_range', queryRange),+ rest.post('http://localhost/api/v4/query_range', queryRange),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ attributeValuesResponse(+ req.url.searchParams.get('attributeKey') ?? '',+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),+ ];+ },+ config: () => ({+ route: ROUTES.MESSAGING_QUEUES_OVERVIEW,+ reduxState: timeRangeState(),+ }),+});diff --git a/frontend/src/pages/MessagingQueues/Overview/stories/Overview.stories.tsx b/frontend/src/pages/MessagingQueues/Overview/stories/Overview.stories.tsxnew file mode 100644index 0000000000..44e28bb645--- /dev/null+++ b/frontend/src/pages/MessagingQueues/Overview/stories/Overview.stories.tsx@@ -0,0 +1,77 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { queueOverviewMocks } from './Overview.stories.mocks';++import MessagingQueuesMainPage from '../../MessagingQueuesMainPage';++type OverviewArgs = PageStoryArgs<typeof queueOverviewMocks>;++const pageStory = storyMocks(queueOverviewMocks, { layout: 'app' });++/**+ * Queues with their producers and consumers over the period, failing ones first.+ *+ * Route: `/messaging-queues/overview`.+ */+const meta = {+ title: 'Pages/Messaging Queues/Overview',+ tags: ['play'],+ component: MessagingQueuesMainPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<OverviewArgs>;++export default meta;++type Story = StoryObj<OverviewArgs>;++/** The table fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * Every producer and consumer the workspace traces, across brokers: error rate,+ * p95 and throughput per service, span and destination.+ */+export const Default: Story = {};++/** The same table when a third of the queues are erroring. */+export const FailingQueues: Story = {+ args: { failing: true },+};++/** One queue opened up: its rate, error rate and latency over the range. */+export const QueueDetails: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ // Every row opens the same panel, so the first one will do. The header row+ // and antd's zero-height measuring row both answer to the row role, and the+ // header is there before the fetch returns, so waiting on the role alone+ // resolves against a table that has no data in it yet. The measuring row is+ // non-interactive, so it is excluded along with anything a loading mask has+ // left without pointer events.+ const firstRow = await waitFor(() => {+ const [row] = within(canvasElement)+ .getAllByRole('row')+ .filter(+ (candidate) =>+ candidate.classList.contains('ant-table-row') &&+ !candidate.classList.contains('ant-table-measure-row') &&+ getComputedStyle(candidate).pointerEvents !== 'none',+ );++ if (!row) {+ throw new Error('the queue table has not rendered a clickable row yet');+ }++ return row;+ }, untilLoaded);++ // The click handler is on the row, and a click routed at one of its cells+ // does not reach it.+ await userEvent.click(firstRow);+ await screen.findByText('Request Rate', undefined, untilLoaded);+ },+};diff --git a/frontend/src/pages/MessagingQueues/Overview/stories/__story_mockdata__/queueOverview.ts b/frontend/src/pages/MessagingQueues/Overview/stories/__story_mockdata__/queueOverview.tsnew file mode 100644index 0000000000..5935a8507b--- /dev/null+++ b/frontend/src/pages/MessagingQueues/Overview/stories/__story_mockdata__/queueOverview.ts@@ -0,0 +1,208 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { PANEL_TYPES } from 'constants/queryBuilder';+import type { QueryRangePayload } from 'types/api/metrics/getQueryRange';+import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';++import {+ type QueryRangeV3Body,+ queryRangeV3TimeSeriesResponse,+ v3Series,+} from '@/storybook/msw/__story_mockdata__/queryRange';++import {+ KAFKA_SERVICES,+ seeded,+ TOPICS,+} from '../../../stories/__story_mockdata__/messagingQueues';++export const MESSAGING_SYSTEMS = ['mixed', 'celery', 'kafka'] as const;++export type MessagingSystemFilter = (typeof MESSAGING_SYSTEMS)[number];++const CELERY_SERVICES = [+ 'billing-worker',+ 'email-worker',+ 'reports-worker',+ 'media-worker',+];++const CELERY_QUEUES = ['billing', 'emails', 'reports', 'media'];++const CELERY_TASKS = [+ 'billing.charge_customer',+ 'emails.send_welcome',+ 'reports.rebuild_daily',+ 'media.transcode',+];++/** A span's kind follows what it does, the way the instrumentation sets it. */+const KAFKA_OPERATIONS = [+ { name: 'publish', kind: 'Producer' },+ { name: 'process', kind: 'Consumer' },+ { name: 'receive', kind: 'Consumer' },+];++const CELERY_OPERATIONS = [+ { name: 'run', kind: 'Consumer' },+ { name: 'apply_async', kind: 'Producer' },+];++interface QueueRow {+ service: string;+ span: string;+ system: string;+ destination: string;+ kind: string;+}++const cycle = <T>(pool: T[], index: number): T => pool[index % pool.length];++/**+ * A queue is a service, a span and a destination together, so the pools are+ * walked at different rates: on `index % length` alone every fifth row would+ * repeat the first.+ */+const kafkaRow = (index: number): QueueRow => {+ const topic = cycle(TOPICS, index);+ const operation = cycle(KAFKA_OPERATIONS, Math.floor(index / TOPICS.length));++ return {+ service: cycle(KAFKA_SERVICES, index + Math.floor(index / TOPICS.length)),+ span: `${topic} ${operation.name}`,+ system: 'kafka',+ destination: topic,+ kind: operation.kind,+ };+};++const celeryRow = (index: number): QueueRow => {+ const operation = cycle(+ CELERY_OPERATIONS,+ Math.floor(index / CELERY_QUEUES.length),+ );++ return {+ service: cycle(+ CELERY_SERVICES,+ index + Math.floor(index / CELERY_QUEUES.length),+ ),+ span: `${operation.name}/${cycle(CELERY_TASKS, index)}`,+ system: 'celery',+ destination: cycle(CELERY_QUEUES, index),+ kind: operation.kind,+ };+};++const rowFor = (index: number, system: MessagingSystemFilter): QueueRow => {+ if (system === 'celery') {+ return celeryRow(index);+ }++ if (system === 'kafka') {+ return kafkaRow(index);+ }++ return index % 2 === 0 ? kafkaRow(index / 2) : celeryRow((index - 1) / 2);+};++/**+ * The error column is a progress bar the page colours at 60% and 90%, so a+ * failing workspace has to push some rows past both thresholds rather than+ * raise every row a little.+ */+const errorPercentage = (index: number, failing: boolean): number => {+ if (!failing) {+ return seeded(index, 0, 4);+ }++ return index % 3 === 0 ? seeded(index, 60, 40) : seeded(index, 5, 45);+};++/**+ * `QueueOverviewResponse` declares each entry's `data` as an array of column+ * objects, but `getTableData` indexes it as a single object and casts the key to+ * get past the compiler, so the builder follows what the page reads.+ */+export interface QueueOverviewEntry {+ timestamp: string;+ data: {+ service_name: string;+ span_name: string;+ messaging_system: string;+ destination: string;+ kind_string: string;+ error_percentage: number;+ p95_latency: number;+ throughput: number;+ };+}++export const queueOverviewResponse = (+ count: number,+ system: MessagingSystemFilter,+ failing: boolean,+ timestamp: number,+): QueueOverviewEntry[] =>+ Array.from({ length: count }, (_unused, index) => {+ const row = rowFor(index, system);++ return {+ timestamp: new Date(timestamp).toISOString(),+ data: {+ service_name: row.service,+ span_name: row.span,+ messaging_system: row.system,+ destination: row.destination,+ kind_string: row.kind,+ error_percentage: errorPercentage(index, failing),+ p95_latency: seeded(index, 80, 900),+ throughput: seeded(index, 5, 120),+ },+ };+ });++/**+ * The three tiles at the top of the detail panel are three `VALUE` requests that+ * differ only by what they aggregate, so they are told apart the way the+ * backend would: the error tile filters on `has_error`, the latency tile+ * aggregates `duration_nano`, and what is left is the request rate.+ */+export const overviewValueResponse = (+ body: QueryRangePayload,+ failing: boolean,+): QueryRangeV3Body | null => {+ if (body.compositeQuery.panelType !== PANEL_TYPES.VALUE) {+ return null;+ }++ const [query] = Object.values(+ body.compositeQuery.builderQueries ?? {},+ ) as IBuilderQuery[];++ const isError = (query?.filters?.items ?? []).some(+ (item) => item.key?.key === 'has_error',+ );+ const isLatency = query?.aggregateAttribute?.key === 'duration_nano';++ const errorRate = failing ? 63.4 : 2.4;+ // The tile divides by 1e6 to label itself in ms.+ const latencyNs = 148 * 1e6;++ return queryRangeV3TimeSeriesResponse([+ {+ queryName: query?.queryName ?? 'A',+ series: [+ v3Series({}, [+ {+ timestamp: body.end,+ value: String(isError ? errorRate : isLatency ? latencyNs : 42.6),+ },+ ]),+ ],+ },+ ]);+};diff --git a/frontend/src/pages/MessagingQueues/stories/MessagingQueues.stories.mocks.tsx b/frontend/src/pages/MessagingQueues/stories/MessagingQueues.stories.mocks.tsxnew file mode 100644index 0000000000..3469da0eed--- /dev/null+++ b/frontend/src/pages/MessagingQueues/stories/MessagingQueues.stories.mocks.tsx@@ -0,0 +1,47 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import { MessagingQueueHealthCheckService } from 'pages/MessagingQueues/MessagingQueuesUtils';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ CONFIGURATION_STATES,+ type ConfigurationState,+ onboardingStatusResponse,+} from './__story_mockdata__/kafkaOverview';+import { timeRangeState } from './__story_mockdata__/messagingQueues';++const HEALTH = 'Kafka · health check';++export const kafkaOverviewMocks = defineStoryMocks({+ controls: {+ configuration: choiceControl<ConfigurationState>('Configuration', {+ group: HEALTH,+ description:+ 'How much of the kafka instrumentation the onboarding checks find. Anything short of complete turns the header button into a count of what is missing.',+ options: CONFIGURATION_STATES,+ value: 'complete',+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v1/messaging-queues/kafka/onboarding/:service',+ response.json((req) =>+ onboardingStatusResponse(+ req.params.service as MessagingQueueHealthCheckService,+ values.configuration,+ ),+ ),+ ),+ ],+ config: () => ({+ route: ROUTES.MESSAGING_QUEUES_KAFKA,+ reduxState: timeRangeState(),+ }),+});diff --git a/frontend/src/pages/MessagingQueues/stories/MessagingQueues.stories.tsx b/frontend/src/pages/MessagingQueues/stories/MessagingQueues.stories.tsxnew file mode 100644index 0000000000..6bae7eea59--- /dev/null+++ b/frontend/src/pages/MessagingQueues/stories/MessagingQueues.stories.tsx@@ -0,0 +1,73 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { kafkaOverviewMocks } from './MessagingQueues.stories.mocks';++import MessagingQueuesMainPage from '../MessagingQueuesMainPage';++type KafkaOverviewArgs = PageStoryArgs<typeof kafkaOverviewMocks>;++const pageStory = storyMocks(kafkaOverviewMocks, { layout: 'app' });++/**+ * The Kafka setup page: what each part of the pipeline reports before the detail+ * views have anything to show.+ *+ * Route: `/messaging-queues/kafka`.+ */+const meta = {+ title: 'Pages/Messaging Queues/Kafka',+ tags: ['play'],+ component: MessagingQueuesMainPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<KafkaOverviewArgs>;++export default meta;++type Story = StoryObj<KafkaOverviewArgs>;++/** The button waits on all three onboarding calls, and swallows clicks until. */+const untilLoaded = { timeout: 15_000 };++/**+ * The kafka landing tab: how to instrument producers, consumers and the broker,+ * then the five views the detail page offers, with the instrumentation health+ * check in the header.+ */+export const Default: Story = {};++/**+ * The header button when the instrumentation is incomplete, counting the+ * attributes the onboarding checks did not find.+ */+export const MissingConfiguration: Story = {+ args: { configuration: 'partial' },+};++/** The checklist behind the header button: every attribute, per service. */+export const ConfigurationChecklist: Story = {+ args: { configuration: 'partial' },+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ // The button reads plain "Configuration" while the checks are in flight and+ // ignores clicks until they land, so the count is what to wait on.+ await userEvent.click(+ await canvas.findByRole(+ 'button',+ { name: /missing configuration/i },+ untilLoaded,+ ),+ );+ // The modal header and its title both carry the text.+ await screen.findAllByText(+ 'Kafka Service Attributes',+ undefined,+ untilLoaded,+ );+ },+};diff --git a/frontend/src/pages/MessagingQueues/stories/__story_mockdata__/kafkaOverview.ts b/frontend/src/pages/MessagingQueues/stories/__story_mockdata__/kafkaOverview.tsnew file mode 100644index 0000000000..3137a46fae--- /dev/null+++ b/frontend/src/pages/MessagingQueues/stories/__story_mockdata__/kafkaOverview.ts@@ -0,0 +1,78 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { OnboardingStatusResponse } from 'api/messagingQueues/onboarding/getOnboardingStatus';+import { MessagingQueueHealthCheckService } from 'pages/MessagingQueues/MessagingQueuesUtils';++export const CONFIGURATION_STATES = ['complete', 'partial', 'missing'] as const;++export type ConfigurationState = (typeof CONFIGURATION_STATES)[number];++/**+ * What each onboarding endpoint checks for. The page never reads the names, so+ * the only thing that matters is that they are the span attributes the kafka+ * instrumentation is supposed to emit.+ */+const CHECKED_ATTRIBUTES: Record<MessagingQueueHealthCheckService, string[]> = {+ [MessagingQueueHealthCheckService.Consumers]: [+ 'messaging.system',+ 'messaging.destination.name',+ 'messaging.kafka.consumer.group',+ 'messaging.kafka.message.offset',+ 'messaging.destination.partition.id',+ 'service.name',+ ],+ [MessagingQueueHealthCheckService.Producers]: [+ 'messaging.system',+ 'messaging.destination.name',+ 'messaging.destination.partition.id',+ 'messaging.message.body.size',+ 'service.name',+ ],+ [MessagingQueueHealthCheckService.Kafka]: [+ 'kafka.consumer_group.lag',+ 'kafka.partition.current_offset',+ 'kafka.partition.oldest_offset',+ 'kafka.topic.partitions',+ 'kafka.brokers',+ ],+};++/**+ * `'1'` is a checked attribute the backend saw, `'0'` one it did not: the+ * header button counts the zeroes and the checklist tree renders their+ * `error_message` behind the Fix link.+ */+const attributeStatus = (+ state: ConfigurationState,+ index: number,+): '0' | '1' => {+ if (state === 'complete') {+ return '1';+ }++ if (state === 'missing') {+ return '0';+ }++ return index % 3 === 0 ? '0' : '1';+};++export const onboardingStatusResponse = (+ service: MessagingQueueHealthCheckService,+ state: ConfigurationState,+): OnboardingStatusResponse => ({+ status: 'success',+ data: CHECKED_ATTRIBUTES[service].map((attribute, index) => {+ const status = attributeStatus(state, index);++ return {+ attribute,+ status,+ error_message:+ status === '0' ? `No span in the selected range carried ${attribute}.` : '',+ };+ }),+});diff --git a/frontend/src/pages/MessagingQueues/stories/__story_mockdata__/messagingQueues.ts b/frontend/src/pages/MessagingQueues/stories/__story_mockdata__/messagingQueues.tsnew file mode 100644index 0000000000..fe43077a2f--- /dev/null+++ b/frontend/src/pages/MessagingQueues/stories/__story_mockdata__/messagingQueues.ts@@ -0,0 +1,290 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { MessagingQueuesPayloadProps } from 'api/messagingQueues/getConsumerLagDetails';+import { PANEL_TYPES } from 'constants/queryBuilder';+import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';+import type { AppState } from 'store/reducers';+import type { QueryRangePayload } from 'types/api/metrics/getQueryRange';+import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';+import type {+ IBuilderFormula,+ IBuilderQuery,+} from 'types/api/queryBuilder/queryBuilderData';+import type { Column } from 'types/api/widgets/getQuery';++import {+ type QueryRangeV3Body,+ queryRangeV3TimeSeriesResponse,+ v3Series,+ v3TimeSeriesValues,+} from '@/storybook/msw/__story_mockdata__/queryRange';++export const RELATIVE_TIME: Time = '30m';++const THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;++const NANOSECONDS_IN_MS = 1_000_000;++/**+ * `globalTime` defaults its window from `window.location.pathname`, which in a+ * story is the preview's rather than the page's, so the time picker (reading the+ * route) and the queries (reading the store) would ask for different ranges and+ * a chart would draw a range narrower than its own axis.+ */+export const timeRangeState = (): Partial<AppState> => {+ const now = Date.now();++ return {+ globalTime: {+ minTime: (now - THIRTY_MINUTES_IN_MS) * NANOSECONDS_IN_MS,+ maxTime: now * NANOSECONDS_IN_MS,+ loading: false,+ selectedTime: RELATIVE_TIME,+ isAutoRefreshDisabled: false,+ selectedAutoRefreshInterval: '',+ },+ };+};++export const CONSUMER_GROUPS = [+ 'orders-consumer',+ 'payments-consumer',+ 'shipping-consumer',+ 'analytics-consumer',+];++export const TOPICS = [+ 'order-events',+ 'payment-events',+ 'shipment-events',+ 'audit-log',+];++export const PARTITIONS = ['0', '1', '2', '3'];++export const KAFKA_SERVICES = [+ 'checkout-api',+ 'payments-worker',+ 'shipping-worker',+ 'notification-worker',+];++const CELERY_TASKS = [+ 'billing.tasks.charge_customer',+ 'emails.tasks.send_welcome',+ 'reports.tasks.rebuild_daily',+ 'media.tasks.transcode',+];++const CELERY_WORKERS = ['worker-a', 'worker-b', 'worker-c'];++/**+ * Values per autocomplete attribute key. The kafka config selects and both+ * celery filter rows read the same v3 endpoint, so one map answers for all of+ * them; a key nobody seeded answers empty rather than 501.+ */+const ATTRIBUTE_VALUES: Record<string, string[]> = {+ group: CONSUMER_GROUPS,+ topic: TOPICS,+ partition: PARTITIONS,+ serviceName: KAFKA_SERVICES,+ name: [+ 'order-events send',+ 'order-events process',+ 'payment-events send',+ 'payment-events process',+ ],+ 'messaging.system': ['kafka', 'celery', 'rabbitmq'],+ 'messaging.destination.name': TOPICS,+ 'messaging.destination': TOPICS,+ kind_string: ['Producer', 'Consumer', 'Client', 'Server'],+ 'celery.task_name': CELERY_TASKS,+ worker: CELERY_WORKERS,+};++const matching = (values: string[], searchText: string): string[] =>+ searchText+ ? values.filter((value) =>+ value.toLowerCase().includes(searchText.toLowerCase()),+ )+ : values;++export const attributeValuesResponse = (+ attributeKey: string,+ searchText: string,+): { status: string; data: IAttributeValuesResponse } => ({+ status: 'success',+ data: {+ stringAttributeValues: matching(+ ATTRIBUTE_VALUES[attributeKey] ?? [],+ searchText,+ ),+ numberAttributeValues: null,+ boolAttributeValues: null,+ },+});++/**+ * The kafka detail tables all answer on this one shape: a single result whose+ * `table` carries the columns the page turns into headers and the rows it+ * renders. `isValueColumn` is what tells a metric column from a grouping one.+ */+export const kafkaTableResponse = (+ columnNames: string[],+ rows: Array<Record<string, string>>,+ valueColumns: string[] = [],+): { status: string; data: MessagingQueuesPayloadProps['payload'] } => {+ const columns: Column[] = columnNames.map((name) => ({+ name,+ queryName: name,+ isValueColumn: valueColumns.includes(name),+ }));++ return {+ status: 'success',+ data: {+ resultType: 'table',+ result: [{ table: { columns, rows: rows.map((data) => ({ data })) } }],+ },+ };+};++/**+ * A metric value derived from the row index rather than random, so a refetch+ * redraws the same table.+ */+export const seeded = (index: number, base: number, spread: number): number =>+ Number((base + (spread * ((index * 37) % 100)) / 100).toFixed(2));++/** Values a group-by key is given, so a legend reads like the real one. */+const LABEL_VALUES: Record<string, string[]> = {+ group: CONSUMER_GROUPS,+ topic: TOPICS,+ partition: PARTITIONS,+ service_name: KAFKA_SERVICES,+ 'service.name': KAFKA_SERVICES,+ 'celery.task_name': CELERY_TASKS,+ 'celery.state': ['SUCCESS', 'RETRY', 'FAILURE'],+ 'celery.hostname': CELERY_WORKERS.map((worker) => `celery@${worker}`),+ worker: CELERY_WORKERS,+ 'messaging.destination.name': TOPICS,+ 'messaging.system': ['kafka', 'celery'],+ kind_string: ['Producer', 'Consumer'],+};++const labelValue = (key: string, index: number): string => {+ const pool = LABEL_VALUES[key];++ return pool ? pool[index % pool.length] : `${key}-${index + 1}`;+};++const groupByKeys = (query: IBuilderQuery | IBuilderFormula): string[] =>+ 'groupBy' in query+ ? (query.groupBy ?? []).map((attribute) => attribute.key)+ : [];++/**+ * Every widget on these pages is a builder query the backend answers per+ * `queryName`, so the response is derived from the request rather than written+ * per widget: one series per group-by combination the query asked for, and a+ * plain series when it grouped by nothing.+ */+export const builderTimeSeriesResponse = (+ body: QueryRangePayload,+ seriesCount: number,+): QueryRangeV3Body => {+ const { start, end } = body;+ const queries = Object.values(body.compositeQuery.builderQueries ?? {});+ const isValue = body.compositeQuery.panelType === PANEL_TYPES.VALUE;++ return queryRangeV3TimeSeriesResponse(+ queries+ .filter((query) => !query.disabled)+ .map((query, queryIndex) => {+ const keys = groupByKeys(query);+ // A single number, or a query that grouped by nothing, is one series.+ const seriesCountForQuery =+ isValue || !keys.length ? Math.min(seriesCount, 1) : seriesCount;++ return {+ queryName: query.queryName,+ legend: query.legend,+ series: Array.from(+ { length: seriesCountForQuery },+ (_unused, seriesIndex) =>+ v3Series(+ Object.fromEntries(+ keys.map((key) => [key, labelValue(key, seriesIndex)]),+ ),+ v3TimeSeriesValues({+ start,+ end,+ points: isValue ? 1 : 30,+ base: 40 + queryIndex * 15 + seriesIndex * 8,+ amplitude: 12 + seriesIndex * 3,+ seed: queryIndex * 5 + seriesIndex,+ }),+ ),+ ),+ };+ }),+ );+};++/**+ * The table spelling of the same request: the group-by keys become the leading+ * columns and each query contributes one value column, which is what+ * `GridTableComponent` builds its headers from.+ */+export const builderTableResponse = (+ body: QueryRangePayload,+ rowCount: number,+): QueryRangeV3Body => {+ const queries = Object.values(body.compositeQuery.builderQueries ?? {}).filter(+ (query) => !query.disabled,+ );+ const keys = [...new Set(queries.flatMap(groupByKeys))];++ const columns: Column[] = [+ ...keys.map((name) => ({ name, queryName: '', isValueColumn: false })),+ ...queries.map((query) => ({+ name: query.queryName,+ queryName: query.queryName,+ isValueColumn: true,+ })),+ ];++ const rows = Array.from({ length: rowCount }, (_unused, index) => ({+ data: {+ ...Object.fromEntries(keys.map((key) => [key, labelValue(key, index)])),+ ...Object.fromEntries(+ queries.map((query, queryIndex) => [+ query.queryName,+ seeded(index + queryIndex, 20 + queryIndex * 30, 60),+ ]),+ ),+ },+ }));++ return {+ status: 'success',+ data: {+ resultType: 'table',+ result: [+ { queryName: 'A', series: null, list: null, table: { columns, rows } },+ ],+ },+ };+};++/** What the graph-bearing tabs answer `query_range` with, panel type decides. */+export const queryRangeV3ForRequest = (+ body: QueryRangePayload,+ count: number,+): QueryRangeV3Body =>+ body.compositeQuery.panelType === PANEL_TYPES.TABLE+ ? builderTableResponse(body, count)+ : builderTimeSeriesResponse(body, count);diff --git a/frontend/src/pages/MeterExplorer/stories/MeterExplorer.stories.mocks.tsx b/frontend/src/pages/MeterExplorer/stories/MeterExplorer.stories.mocks.tsxnew file mode 100644index 0000000000..b07d719c3b--- /dev/null+++ b/frontend/src/pages/MeterExplorer/stories/MeterExplorer.stories.mocks.tsx@@ -0,0 +1,275 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import set from 'api/browser/localstorage/set';+import {+ TelemetrytypesFieldContextDTO,+ TelemetrytypesSignalDTO,+} from 'api/generated/services/sigNoz.schemas';+import { LOCALSTORAGE } from 'constants/localStorage';+import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';++import {+ choiceControl,+ countControl,+ multiChoiceControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import {+ fieldKeysResponse,+ fieldValuesResponse,+} from '@/storybook/msw/__story_mockdata__/fields';+import {+ queryRangeV5ScalarResponse,+ queryRangeV5TimeSeriesResponse,+} from '@/storybook/msw/__story_mockdata__/queryRange';++import {+ exportDashboardsResponse,+ METER_METRICS,+ METER_SIGNALS,+ METER_TABS,+ METER_TIME_RANGES,+ METER_VOLUMES,+ meterAttributeKeys,+ meterExplorerQuery,+ meterFieldKeys,+ meterFieldValues,+ meterMetricSignal,+ meterMetricsListResponse,+ meterQuickFiltersResponse,+ meterSeries,+ meterTimeWindow,+ meterTotal,+ meterVolumeUnit,+ savedMeterViewsResponse,+ type MeterSignal,+ type MeterTab,+ type MeterTimeRange,+ type MeterVolume,+} from './__story_mockdata__/meter';++const VIEW = 'Cost Meter · view';+const USAGE = 'Cost Meter · usage';+const EXPLORER = 'Cost Meter · explorer';++const isMetricName = (name: string): boolean =>+ (METER_METRICS as readonly string[]).includes(name);++/**+ * The meter metrics themselves and the resource attributes they carry come back+ * from one call, each under its own context, so the query builder tells the+ * metric picker and the filter suggestions apart the way it does against a real+ * backend.+ */+const meterFieldKeysResponse = (+ searchText: string | null,+): ReturnType<typeof fieldKeysResponse> => {+ const names = meterFieldKeys(searchText);++ const byContext = [+ TelemetrytypesFieldContextDTO.metric,+ TelemetrytypesFieldContextDTO.resource,+ ].map((fieldContext) =>+ fieldKeysResponse(+ names.filter(+ (name) =>+ isMetricName(name) ===+ (fieldContext === TelemetrytypesFieldContextDTO.metric),+ ),+ { signal: TelemetrytypesSignalDTO.metrics, fieldContext },+ ),+ );++ return {+ status: 'success',+ data: {+ complete: true,+ keys: Object.assign({}, ...byContext.map(({ data }) => data?.keys)),+ },+ };+};++interface RouteValues {+ tab: MeterTab;+ metric: MeterVolume;+ timeRange: MeterTimeRange;+}++const meterRoute = ({ tab, metric, timeRange }: RouteValues): string => {+ const params = new URLSearchParams(meterTimeWindow(timeRange).search);++ if (tab === 'views') {+ return `${ROUTES.METER_EXPLORER_VIEWS}?${params.toString()}`;+ }++ if (tab === 'explorer') {+ // Encoded the way `redirectWithQueryBuilderData` writes it, so the param+ // survives the extra decode the query builder does when reading it back.+ params.set(+ QueryParams.compositeQuery,+ encodeURIComponent(JSON.stringify(meterExplorerQuery(metric))),+ );+ params.set(QueryParams.yAxisUnit, meterVolumeUnit(metric));++ return `${ROUTES.METER_EXPLORER}?${params.toString()}`;+ }++ return `${ROUTES.METER}?${params.toString()}`;+};++interface MeterQuerySpec {+ name?: string;+ aggregations?: { metricName?: string }[];+}++const meterSpecOf = (body: QueryRangeRequestV5): MeterQuerySpec =>+ (body.compositeQuery?.queries?.[0]?.spec ?? {}) as MeterQuerySpec;++export const meterMocks = defineStoryMocks({+ controls: {+ tab: choiceControl<MeterTab>('Tab', {+ group: VIEW,+ description:+ 'The three pathnames the module tabs between. Clicking another tab leaves the story, so switch it here.',+ options: METER_TABS,+ value: 'meter',+ }),+ timeRange: choiceControl<MeterTimeRange>('Time range', {+ group: VIEW,+ description:+ 'The window every widget asks for. Under 61 minutes the page warns that the meter aggregates hourly; a window inside the beta phase warns that the data predates 22 August 2025, which only a cloud tenant is told.',+ options: METER_TIME_RANGES,+ value: 'last-1-day',+ }),+ billingNotice: toggleControl('Billing notice', {+ group: VIEW,+ description:+ 'The UTC billing note above the breakdown. Closing it is what the app persists, so a returning user does not see it.',+ value: true,+ }),+ signals: multiChoiceControl<MeterSignal>('Ingesting signals', {+ group: USAGE,+ description:+ 'Which signals the meter has volume for. A signal left out answers with no series, so its section and its total go empty.',+ options: METER_SIGNALS,+ value: [...METER_SIGNALS],+ }),+ metric: choiceControl<MeterVolume>('Explorer metric', {+ group: EXPLORER,+ description:+ 'Which `signoz.meter.*` metric the explorer opens with staged and charted.',+ options: METER_VOLUMES,+ value: 'log-size',+ }),+ quickFilters: countControl('Quick filters', {+ group: EXPLORER,+ description:+ 'Filters the org has configured for the meter. At 0 the panel shows its empty state.',+ value: 6,+ max: meterAttributeKeys.length,+ }),+ savedViews: countControl('Saved views', {+ group: EXPLORER,+ description: 'Fills the views dropdown and the Views tab.',+ value: 4,+ max: 6,+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const { start, end, requestType } = body;+ const { name = 'A', aggregations } = meterSpecOf(body);+ const metricName = aggregations?.[0]?.metricName ?? '';++ const signal = meterMetricSignal(metricName);+ const ingesting = !!signal && values.signals.includes(signal);++ if (requestType === 'scalar') {+ return queryRangeV5ScalarResponse(+ ingesting ? meterTotal(metricName, { start, end }) : 0,+ name,+ );+ }++ return queryRangeV5TimeSeriesResponse([+ {+ queryName: name,+ series: ingesting ? meterSeries(metricName, { start, end }) : [],+ },+ ]);+ }),+ ),++ rest.get(+ 'http://localhost/api/v2/quick_filters/:source',+ response.json(() => meterQuickFiltersResponse(values.quickFilters)),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ meterFieldKeysResponse(req.url.searchParams.get('searchText')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(meterFieldValues(req.url.searchParams.get('name'))),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics',+ response.json((req) =>+ meterMetricsListResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/explorer/views',+ response.json(() => savedMeterViewsResponse(values.savedViews)),+ ),++ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json(exportDashboardsResponse),+ ),+ ],+ config: (values) => {+ const { minTime, maxTime, selectedTime } = meterTimeWindow(values.timeRange);++ return {+ route: meterRoute(values),+ // The breakdown reads the window off the store rather than the picker, so+ // the range the widgets ask for is the seeded one, not the reducer's+ // default for `/iframe.html`.+ reduxState: {+ globalTime: {+ minTime,+ maxTime,+ selectedTime,+ loading: false,+ isAutoRefreshDisabled: false,+ selectedAutoRefreshInterval: '',+ },+ },+ };+ },+ effect: ({ billingNotice }) => {+ set(+ LOCALSTORAGE.DISSMISSED_COST_METER_INFO,+ billingNotice ? 'false' : 'true',+ );+ },+});diff --git a/frontend/src/pages/MeterExplorer/stories/MeterExplorer.stories.tsx b/frontend/src/pages/MeterExplorer/stories/MeterExplorer.stories.tsxnew file mode 100644index 0000000000..9d97d51091--- /dev/null+++ b/frontend/src/pages/MeterExplorer/stories/MeterExplorer.stories.tsx@@ -0,0 +1,90 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { meterMocks } from './MeterExplorer.stories.mocks';+import MeterExplorerPage from '../MeterExplorerPage';++type MeterArgs = PageStoryArgs<typeof meterMocks>;++const pageStory = storyMocks(meterMocks, { layout: 'app' });++/**+ * What the workspace is metered for, per signal: the explorer over `query_range`,+ * its saved views and the billing notice above them.+ *+ * Routes: `/meter`, `/meter/explorer` and `/meter/explorer/views`.+ */+const meta = {+ title: 'Pages/Metering/Cost Meter',+ component: MeterExplorerPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<MeterArgs>;++export default meta;++type Story = StoryObj<MeterArgs>;++/**+ * The Meter tab over the last day: what the workspace ingested in total, then+ * the hourly count and size of log records, of spans, and the metric datapoints+ * behind the bill.+ */+export const Default: Story = {};++/**+ * The Explorer tab with a meter metric staged, so the bar chart, the quick+ * filters and the query builder all show what a saved cost query looks like.+ */+export const Explorer: Story = {+ args: { tab: 'explorer' },+};++/** The Views tab, where the meter queries the workspace has saved are managed. */+export const SavedViews: Story = {+ args: { tab: 'views' },+};++/**+ * A workspace that has not sent telemetry yet: the totals read zero and every+ * section reports no data. Its quick filters and saved views are unset too, so+ * the Explorer and Views tabs are empty from here as well.+ */+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'] },+};++/** The Explorer tab with no quick filters configured. */+export const ExplorerWithoutQuickFilters: Story = {+ args: { tab: 'explorer', quickFilters: 0 },+};++/** The Views tab without any saved meter queries. */+export const ViewsEmpty: Story = {+ args: { tab: 'views', savedViews: 0 },+};diff --git a/frontend/src/pages/MeterExplorer/stories/__story_mockdata__/meter.ts b/frontend/src/pages/MeterExplorer/stories/__story_mockdata__/meter.tsnew file mode 100644index 0000000000..bb8f749500--- /dev/null+++ b/frontend/src/pages/MeterExplorer/stories/__story_mockdata__/meter.ts@@ -0,0 +1,387 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ GetQuickFilters200,+ ListMetrics200,+ TelemetrytypesTelemetryFieldKeyDTO,+} from 'api/generated/services/sigNoz.schemas';+import {+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+ QuickfiltertypesSourceDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesFieldDataTypeDTO,+} from 'api/generated/services/sigNoz.schemas';+import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';+import {+ getLogCountWidgetData,+ getLogSizeWidgetData,+ getMetricCountWidgetData,+ getSpanCountWidgetData,+ getSpanSizeWidgetData,+} from 'container/MeterExplorer/Breakdown/graphs';+import { explorerView } from 'mocks-server/__mockdata__/explorer_views';+import type { Widgets } from 'types/api/widgets/widget';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';+import type { TimeSeries } from 'types/api/v5/queryRange';++import { timeSeriesPoints } from '@/storybook/msw/__story_mockdata__/queryRange';+import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';++export const METER_TABS = ['meter', 'explorer', 'views'] as const;++export type MeterTab = (typeof METER_TABS)[number];++export const METER_SIGNALS = ['logs', 'traces', 'metrics'] as const;++export type MeterSignal = (typeof METER_SIGNALS)[number];++/** The metrics the meter module emits, as the widgets and the explorer ask for them. */+export const METER_METRICS = [+ 'signoz.meter.log.count',+ 'signoz.meter.log.size',+ 'signoz.meter.span.count',+ 'signoz.meter.span.size',+ 'signoz.meter.metric.datapoint.count',+] as const;++export type MeterMetric = (typeof METER_METRICS)[number];++/**+ * The metrics as a control names them. Storybook drops URL args containing+ * dots, so a story cannot be linked at a raw metric name.+ */+export const METER_VOLUMES = [+ 'log-count',+ 'log-size',+ 'span-count',+ 'span-size',+ 'metric-datapoints',+] as const;++export type MeterVolume = (typeof METER_VOLUMES)[number];++const VOLUME_METRICS: Record<MeterVolume, MeterMetric> = {+ 'log-count': 'signoz.meter.log.count',+ 'log-size': 'signoz.meter.log.size',+ 'span-count': 'signoz.meter.span.count',+ 'span-size': 'signoz.meter.span.size',+ 'metric-datapoints': 'signoz.meter.metric.datapoint.count',+};++export const meterVolumeMetric = (volume: MeterVolume): MeterMetric =>+ VOLUME_METRICS[volume];++interface MeterMetricShape {+ signal: MeterSignal;+ /** Volume of one hourly bucket, which is what the meter aggregates over. */+ perHour: number;+ /** The unit the panels read, as `yAxisUnit`. */+ unit: string;+ description: string;+ /** OpenTelemetry unit, which is what the metric catalogue reports. */+ otelUnit: string;+}++const METRICS: Record<MeterMetric, MeterMetricShape> = {+ 'signoz.meter.log.count': {+ signal: 'logs',+ perHour: 52_400_000,+ unit: 'short',+ description: 'Log records ingested',+ otelUnit: '1',+ },+ 'signoz.meter.log.size': {+ signal: 'logs',+ perHour: 36_800_000_000,+ unit: 'bytes',+ description: 'Uncompressed size of the log records ingested',+ otelUnit: 'By',+ },+ 'signoz.meter.span.count': {+ signal: 'traces',+ perHour: 18_600_000,+ unit: 'short',+ description: 'Spans ingested',+ otelUnit: '1',+ },+ 'signoz.meter.span.size': {+ signal: 'traces',+ perHour: 12_400_000_000,+ unit: 'bytes',+ description: 'Uncompressed size of the spans ingested',+ otelUnit: 'By',+ },+ 'signoz.meter.metric.datapoint.count': {+ signal: 'metrics',+ perHour: 194_000_000,+ unit: 'short',+ description: 'Metric datapoints ingested',+ otelUnit: '1',+ },+};++const HOUR_IN_MS = 60 * 60 * 1000;++const isMeterMetric = (name: string): name is MeterMetric => name in METRICS;++export const meterMetricSignal = (name: string): MeterSignal | undefined =>+ isMeterMetric(name) ? METRICS[name].signal : undefined;++export const meterVolumeUnit = (volume: MeterVolume): string =>+ METRICS[VOLUME_METRICS[volume]].unit;++interface MeterWindowRequest {+ /** Request window in epoch milliseconds, as `query_range` sends it. */+ start: number;+ end: number;+}++/**+ * One bar per hour of the requested window, capped at a week's worth so a long+ * range stays a chart rather than a wall of bars.+ */+const bucketCount = ({ start, end }: MeterWindowRequest): number =>+ Math.min(Math.max(Math.round((end - start) / HOUR_IN_MS), 1), 168);++export const meterSeries = (+ name: string,+ window: MeterWindowRequest,+): TimeSeries[] => {+ if (!isMeterMetric(name)) {+ return [];+ }++ const { perHour } = METRICS[name];++ return [+ {+ labels: [],+ values: timeSeriesPoints({+ ...window,+ points: bucketCount(window),+ base: perHour,+ amplitude: perHour * 0.18,+ seed: METER_METRICS.indexOf(name),+ }),+ },+ ];+};++/** The totals row, which sums what the bars of the same window show. */+export const meterTotal = (+ name: string,+ window: MeterWindowRequest,+): number => {+ const values = meterSeries(name, window)[0]?.values ?? [];++ return values.reduce((total, { value }) => total + Number(value), 0);+};++export const METER_TIME_RANGES = [+ 'last-1-day',+ 'last-30-minutes',+ 'august-2025',+] as const;++export type MeterTimeRange = (typeof METER_TIME_RANGES)[number];++export interface MeterTimeWindow {+ /** Epoch nanoseconds, the unit `globalTime` holds. */+ minTime: number;+ maxTime: number;+ selectedTime: Time;+ /** What the time picker reads back off the URL. */+ search: Record<string, string>;+}++const relativeWindow = (+ spanInMs: number,+ selectedTime: Time,+): MeterTimeWindow => {+ const end = Date.now();++ return {+ minTime: (end - spanInMs) * 1e6,+ maxTime: end * 1e6,+ selectedTime,+ search: { relativeTime: selectedTime },+ };+};++/**+ * A day inside the meter's beta phase, which is what the cloud-only accuracy+ * warning reads: the module only vouches for data from 22 August 2025 onwards.+ */+const BETA_PHASE_DAY = {+ start: Date.UTC(2025, 7, 10),+ end: Date.UTC(2025, 7, 11),+};++export const meterTimeWindow = (range: MeterTimeRange): MeterTimeWindow => {+ if (range === 'last-30-minutes') {+ return relativeWindow(30 * 60 * 1000, '30m');+ }++ if (range === 'august-2025') {+ return {+ minTime: BETA_PHASE_DAY.start * 1e6,+ maxTime: BETA_PHASE_DAY.end * 1e6,+ selectedTime: 'custom',+ search: {+ startTime: String(BETA_PHASE_DAY.start),+ endTime: String(BETA_PHASE_DAY.end),+ },+ };+ }++ return relativeWindow(24 * HOUR_IN_MS, '1d');+};++const EXPLORER_WIDGETS: Record<MeterVolume, () => Widgets> = {+ 'log-count': getLogCountWidgetData,+ 'log-size': getLogSizeWidgetData,+ 'span-count': getSpanCountWidgetData,+ 'span-size': getSpanSizeWidgetData,+ 'metric-datapoints': getMetricCountWidgetData,+};++/**+ * The query the explorer starts on, taken from the breakdown widget for the+ * same metric so the story asks for what the page itself would build.+ */+export const meterExplorerQuery = (volume: MeterVolume): Query =>+ EXPLORER_WIDGETS[volume]().query;++/** The metric picker in the query builder lists what the meter reports. */+export const meterMetricsListResponse = (+ searchText: string,+): ListMetrics200 => {+ const search = searchText.toLowerCase();++ return {+ status: 'success',+ data: {+ metrics: METER_METRICS.filter((name) =>+ name.toLowerCase().includes(search),+ ).map((name) => ({+ metricName: name,+ description: METRICS[name].description,+ unit: METRICS[name].otelUnit,+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.delta,+ isMonotonic: true,+ })),+ },+ };+};++const QUICK_FILTER_NAMES = [+ 'service.name',+ 'deployment.environment',+ 'k8s.cluster.name',+ 'k8s.namespace.name',+ 'host.name',+ 'telemetry.sdk.language',+ 'cloud.region',+ 'signoz.collector.id',+] as const;++const QUICK_FILTERS: TelemetrytypesTelemetryFieldKeyDTO[] =+ QUICK_FILTER_NAMES.map((name) => ({+ name,+ fieldDataType: TelemetrytypesFieldDataTypeDTO.string,+ fieldContext: TelemetrytypesFieldContextDTO.resource,+ }));++export const meterQuickFiltersResponse = (count: number): GetQuickFilters200 =>+ quickFiltersResponse(+ QuickfiltertypesSourceDTO.meter,+ QUICK_FILTERS.slice(0, count),+ );++const FIELD_VALUES: Record<string, string[]> = {+ 'service.name': [+ 'frontend',+ 'checkout',+ 'payments',+ 'cart',+ 'inventory',+ 'shipping',+ ],+ 'deployment.environment': ['production', 'staging'],+ 'k8s.cluster.name': ['prod-us-east-1', 'prod-eu-west-1', 'staging'],+ 'k8s.namespace.name': ['default', 'checkout', 'observability'],+ 'host.name': ['ip-10-0-3-14', 'ip-10-0-3-22', 'ip-10-0-4-8'],+ 'telemetry.sdk.language': ['go', 'nodejs', 'java', 'python'],+ 'cloud.region': ['us-east-1', 'eu-west-1', 'ap-south-1'],+ 'signoz.collector.id': ['collector-a1b2', 'collector-c3d4'],+};++export const meterAttributeKeys = [+ ...METER_METRICS,+ ...Object.keys(FIELD_VALUES),+];++/**+ * `/fields/keys` is asked once per keystroke in the query builder and once per+ * quick filter the panel resolves, both with a `searchText`, so the answer+ * filters the catalogue rather than always returning it whole.+ */+export const meterFieldKeys = (searchText: string | null): string[] => {+ const search = (searchText ?? '').toLowerCase();++ return search+ ? meterAttributeKeys.filter((key) => key.toLowerCase().includes(search))+ : meterAttributeKeys;+};++export const meterFieldValues = (name: string | null): string[] =>+ FIELD_VALUES[name ?? ''] ?? [];++const VIEW_NAMES = [+ 'Log volume by service',+ 'Span size by environment',+ 'Datapoints by cluster',+ 'Staging spend',+ 'Top ingesting namespaces',+ 'Collector breakdown',+];++export const savedMeterViewsResponse = (+ count: number,+): { status: string; data: unknown[] } => ({+ status: 'success',+ data: Array.from(+ { length: Math.min(count, VIEW_NAMES.length) },+ (_unused, index) => ({+ ...explorerView.data[0],+ id: `storybook-meter-view-${index + 1}`,+ name: VIEW_NAMES[index],+ sourcePage: 'meter',+ tags: ['meter'],+ }),+ ),+});++const DASHBOARD_NAMES = [+ 'Cost overview',+ 'Ingestion by team',+ 'Log volume trend',+ 'Telemetry spend',+];++export const exportDashboardsResponse = (): Record<string, unknown> => ({+ status: 'success',+ data: {+ dashboards: DASHBOARD_NAMES.map((name, index) => ({+ id: `storybook-dashboard-${index + 1}`,+ name,+ spec: { display: { name } },+ tags: ['meter'],+ })),+ },+});diff --git a/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.mocks.tsx b/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.mocks.tsxnew file mode 100644index 0000000000..4fd498c54a--- /dev/null+++ b/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.mocks.tsx@@ -0,0 +1,136 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { QueryParams } from 'constants/query';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import {+ attributeKeysResponse,+ attributeValuesResponse,+} from '@/storybook/msw/__story_mockdata__/attributes';+import { queryRangeV3ForRequest } from '@/storybook/msw/__story_mockdata__/queryRange';++import {+ apDexSettingsResponse,+ METRICS_APPLICATION_TABS,+ METRICS_LABEL_VALUES,+ metricMetaResponse,+ SERVICE_NAME,+ TOP_OPERATION_MAX,+ topLevelOperationsResponse,+ topOperationsResponse,+ type MetricsApplicationTabKey,+} from './__story_mockdata__/metricsApplication';++const VIEW = 'Service · view';+const DATA = 'Service · data';++const DEPLOYMENT_KEY = 'resource_deployment.environment';++const RESOURCE_ATTRIBUTE_KEYS = [+ DEPLOYMENT_KEY,+ 'resource_k8s.cluster.name',+ 'resource_k8s.namespace.name',+ 'resource_host.name',+];++const APDEX_THRESHOLD = 0.5;++export const metricsApplicationMocks = defineStoryMocks({+ controls: {+ tab: choiceControl<MetricsApplicationTabKey>('Tab', {+ group: VIEW,+ description: 'Which of the service tabs is open, which is the `tab` param.',+ options: METRICS_APPLICATION_TABS,+ value: 'OVER_METRICS',+ }),+ operations: countControl('Key operations', {+ group: DATA,+ description: 'Rows in the key operations table below the graphs.',+ value: 8,+ max: TOP_OPERATION_MAX,+ }),+ series: countControl('Graph series', {+ group: DATA,+ description:+ 'Lines a grouped graph draws: one per operation, database or upstream address it broke down by.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => {+ const queryRange = response.json(async (req) =>+ queryRangeV3ForRequest(await req.json(), {+ count: values.series,+ labelValues: METRICS_LABEL_VALUES,+ }),+ );++ return [+ rest.post('http://localhost/api/v3/query_range', queryRange),+ rest.post('http://localhost/api/v4/query_range', queryRange),+ rest.post(+ 'http://localhost/api/v1/service/top_level_operations',+ response.json(() => topLevelOperationsResponse(SERVICE_NAME)),+ ),+ rest.post(+ 'http://localhost/api/v2/service/top_operations',+ response.json(() => topOperationsResponse(values.operations, false)),+ ),+ rest.post(+ 'http://localhost/api/v2/service/entry_point_operations',+ response.json(() => topOperationsResponse(values.operations, true)),+ ),+ // The apdex settings and the histogram buckets are what the apdex widget+ // reads its threshold off, so they answer while the graphs hang or fail.+ rest.get('http://localhost/api/v1/settings/apdex', (req, res, ctx) =>+ res(+ ctx.json(+ apDexSettingsResponse(+ req.url.searchParams.get('services') ?? SERVICE_NAME,+ APDEX_THRESHOLD,+ ),+ ),+ ),+ ),+ rest.post('http://localhost/api/v1/settings/apdex', (_req, res, ctx) =>+ res(ctx.json({ data: 'ok' })),+ ),+ rest.get(+ 'http://localhost/api/v4/metric/metric_metadata',+ (_req, res, ctx) => res(ctx.json(metricMetaResponse())),+ ),+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_keys',+ response.json((req) => {+ const match = req.url.searchParams.get('searchText') ?? '';++ return attributeKeysResponse(+ match === DEPLOYMENT_KEY+ ? [DEPLOYMENT_KEY]+ : RESOURCE_ATTRIBUTE_KEYS.filter((key) => key !== DEPLOYMENT_KEY),+ );+ }),+ ),+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) => {+ const attributeKey = req.url.searchParams.get('attributeKey') ?? '';++ return attributeValuesResponse(+ attributeKey === DEPLOYMENT_KEY+ ? ['production', 'staging', 'canary']+ : [`${attributeKey.replace('resource_', '')}-01`],+ );+ }),+ ),+ ];+ },+ config: (values) => ({+ route: `/services/${SERVICE_NAME}?${QueryParams.tab}=${values.tab}`,+ }),+});diff --git a/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.tsx b/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.tsxnew file mode 100644index 0000000000..e13f306d25--- /dev/null+++ b/frontend/src/pages/MetricsApplication/stories/MetricsApplication.stories.tsx@@ -0,0 +1,80 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import MetricsApplication from '../MetricsApplication';+import { metricsApplicationMocks } from './MetricsApplication.stories.mocks';++type MetricsApplicationArgs = PageStoryArgs<typeof metricsApplicationMocks>;++const pageStory = storyMocks(metricsApplicationMocks, { layout: 'app' });++/**+ * One service: its latency, rate and error panels, its top and entry point+ * operations, and the apdex setting the panels read.+ *+ * Route: `/services/:servicename`.+ */+const meta = {+ title: 'Pages/Services/Detail',+ tags: ['play'],+ component: MetricsApplication,+ // The page reads the service out of the pathname, so it renders under its own+ // route rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route path={ROUTES.SERVICE_METRICS} component={MetricsApplication} />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<MetricsApplicationArgs>;++export default meta;++type Story = StoryObj<MetricsApplicationArgs>;++/**+ * A service's overview: latency, rate, apdex and error percentage over the+ * selected range, with the key operations behind them.+ */+export const Default: Story = {};++/** The database calls the service makes, by system and by upstream. */+export const DatabaseCalls: Story = {+ args: { tab: 'DB_CALL_METRICS' },+};++/** The calls the service makes out of the mesh, by address. */+export const ExternalCalls: Story = {+ args: { tab: 'EXTERNAL_METRICS' },+};++/** Every available operation and graph series, for the page's densest layout. */+export const DenseOperations: Story = {+ args: { operations: 10, series: 6 },+};++/** The real empty table branch when this service has no top or entry-point operations. */+export const NoOperations: Story = {+ args: { operations: 0 },+};++/**+ * The Download menu on the top operations table, open: the formats the rows can+ * be taken away in.+ */+export const DownloadMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'download-menu-trigger',+ {},+ { timeout: 15000 },+ ),+ );+ await screen.findByRole('menu');+ },+};diff --git a/frontend/src/pages/MetricsApplication/stories/__story_mockdata__/metricsApplication.ts b/frontend/src/pages/MetricsApplication/stories/__story_mockdata__/metricsApplication.tsnew file mode 100644index 0000000000..f2c3a0518b--- /dev/null+++ b/frontend/src/pages/MetricsApplication/stories/__story_mockdata__/metricsApplication.ts@@ -0,0 +1,99 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { ServiceDataProps } from 'api/metrics/getTopLevelOperations';+import type { TopOperationList } from 'container/MetricsApplication/TopOperationsTable';+import type {+ ApDexPayloadAndSettingsProps,+ MetricMetaProps,+} from 'types/api/metrics/getApDex';++import { seededMetricValue } from '@/storybook/msw/__story_mockdata__/queryRange';++export const SERVICE_NAME = 'checkout';++/**+ * Spelled as the `tab` param carries them rather than as `MetricsApplicationTab`,+ * so a story's arg and the URL agree on a plain string.+ */+export const METRICS_APPLICATION_TABS = [+ 'OVER_METRICS',+ 'DB_CALL_METRICS',+ 'EXTERNAL_METRICS',+] as const;++export type MetricsApplicationTabKey =+ (typeof METRICS_APPLICATION_TABS)[number];++const OPERATION_NAMES = [+ 'POST /api/checkout',+ 'GET /api/cart',+ 'oteldemo.CheckoutService/PlaceOrder',+ 'POST /api/payment/authorize',+ 'GET /api/shipping/quote',+ 'SELECT orders',+ 'INSERT order_items',+ 'GET /api/currency/convert',+ 'POST /api/email/confirmation',+ 'oteldemo.CartService/EmptyCart',+];++export const TOP_OPERATION_MAX = OPERATION_NAMES.length;++/** The lines every grouped graph on the page draws, and its DB/external legends. */+export const METRICS_LABEL_VALUES: Record<string, readonly string[]> = {+ 'service.name': [SERVICE_NAME, 'cart', 'payment'],+ operation: OPERATION_NAMES,+ address: [+ 'payment.svc.cluster.local:8080',+ 'shipping.svc.cluster.local:8080',+ 'currency.svc.cluster.local:8080',+ ],+ 'db.system': ['postgresql', 'redis', 'mysql'],+ 'status.code': ['200', '400', '500'],+};++/** The service the page is on, with the entry points its overview graphs cover. */+export const topLevelOperationsResponse = (+ servicename: string,+): ServiceDataProps => ({+ [servicename]: OPERATION_NAMES.slice(0, 4),+});++export const topOperationsResponse = (+ count: number,+ isEntryPoint: boolean,+): { status: string; data: TopOperationList[] } => ({+ status: 'success',+ data: OPERATION_NAMES.slice(0, count).map((name, index) => {+ const p50 = seededMetricValue(index, 18, 40) * 1_000_000;+ const numCalls = Math.round(seededMetricValue(index, 400, 2600));++ return {+ // The entry-point view keeps only the operations a request enters on, so+ // it reads the same rows back with the inbound calls counted.+ name: isEntryPoint ? `${name} (entry)` : name,+ p50,+ p95: p50 * 2.4,+ p99: p50 * 3.6,+ numCalls,+ errorCount: Math.round(numCalls * (index % 4 === 0 ? 0.045 : 0)),+ };+ }),+});++export const apDexSettingsResponse = (+ servicename: string,+ threshold: number,+): { status: string; data: ApDexPayloadAndSettingsProps[] } => ({+ status: 'success',+ data: [{ servicename, threshold, excludeStatusCode: '' }],+});++/** The latency histogram's buckets, which is what the apdex score is read off. */+export const metricMetaResponse = (): MetricMetaProps => ({+ delta: false,+ le: [0.1, 0.25, 0.5, 1, 2.5, 5, 10],+});diff --git a/frontend/src/pages/MetricsExplorer/stories/MetricsExplorerPage.stories.mocks.tsx b/frontend/src/pages/MetricsExplorer/stories/MetricsExplorerPage.stories.mocks.tsxnew file mode 100644index 0000000000..ea888baf28--- /dev/null+++ b/frontend/src/pages/MetricsExplorer/stories/MetricsExplorerPage.stories.mocks.tsx@@ -0,0 +1,541 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import setLocalStorage from 'api/browser/localstorage/set';+import type {+ MetricsexplorertypesInspectMetricsRequestDTO,+ MetricsexplorertypesStatsRequestDTO,+} from 'api/generated/services/sigNoz.schemas';+import { FeatureKeys } from 'constants/features';+import { QueryParams } from 'constants/query';+import { PANEL_TYPES } from 'constants/queryBuilder';+import ROUTES from 'constants/routes';+import { getMetricDetailsQuery } from 'container/MetricsExplorer/MetricDetails/utils';+import {+ IS_INSPECT_MODAL_OPEN_KEY,+ IS_METRIC_DETAILS_OPEN_KEY,+ METRICS_TABLE_PAGE_SIZE,+ SELECTED_METRIC_NAME_KEY,+} from 'container/MetricsExplorer/Summary/constants';+import type { Time } from 'container/TopNav/DateTimeSelectionV2/types';+import { rest } from 'msw';+import type { AppState } from 'store/reducers';+import { defaultFeatureFlags } from 'tests/fixtures/appContextMock';+import type { Query } from 'types/api/queryBuilder/queryBuilderData';+import type { QueryRangeRequestV5, TimeSeries } from 'types/api/v5/queryRange';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import { dashboardsForUserResponse } from '@/storybook/msw/__story_mockdata__/dashboards';+import {+ fieldKeysResponse,+ fieldValuesResponse,+} from '@/storybook/msw/__story_mockdata__/fields';+import {+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++import {+ ATTRIBUTE_MAX,+ DRAWER_METRIC_TYPES,+ type DrawerMetricType,+ drawerMetricName,+ explorerMetricNames,+ INSPECT_SERIES_MAX,+ inspectMetricsResponse,+ listMetricsResponse,+ METRIC_MAX,+ metricAlertsResponse,+ metricAttributesResponse,+ metricDashboardsResponse,+ metricFieldKeys,+ metricFieldValues,+ metricHighlightsResponse,+ metricIsMonotonic,+ metricMetadataResponse,+ metricTemporalityOf,+ metricTypeOf,+ metricsSavedViewsResponse,+ metricsStatsResponse,+ metricsTreemapResponse,+ REDUCTION_RULE_MAX,+ RELATED_ASSET_MAX,+ reductionRuleStatsResponse,+ reductionRuleTimeseriesResponse,+ reductionRulesResponse,+ SAVED_VIEW_MAX,+} from './__story_mockdata__/metricsExplorer';++const VIEW = 'Metrics · view';+const SUMMARY = 'Metrics · summary';+const EXPLORER = 'Metrics · explorer';+const VOLUME = 'Metrics · volume control';++const METRICS_TABS = [+ 'summary',+ 'volume-control',+ 'explorer',+ 'views',+] as const;++type MetricsTab = (typeof METRICS_TABS)[number];++const DRAWER_STATES = ['closed', 'details', 'inspect'] as const;++type DrawerState = (typeof DRAWER_STATES)[number];++const RELATIVE_TIME: Time = '30m';++const THIRTY_MINUTES_IN_MS = 30 * 60 * 1000;++const NANOSECONDS_IN_MS = 1_000_000;++/** The volume chart has no time range of its own: it labels itself last 6 hours. */+const SIX_HOURS_IN_MS = 6 * 60 * 60 * 1000;++/**+ * `globalTime` defaults its window from `window.location.pathname`, which in a+ * story is the preview's rather than the page's, so the time picker (reading the+ * route) and the queries (reading the store) would ask for different ranges and+ * the treemap would size tiles against a window the table never asked for.+ */+const timeRange = (): Partial<AppState> => {+ const now = Date.now();++ return {+ globalTime: {+ minTime: (now - THIRTY_MINUTES_IN_MS) * NANOSECONDS_IN_MS,+ maxTime: now * NANOSECONDS_IN_MS,+ loading: false,+ selectedTime: RELATIVE_TIME,+ isAutoRefreshDisabled: false,+ selectedAutoRefreshInterval: '',+ },+ };+};++const QUERY_NAMES = ['A', 'B', 'C'];++/**+ * The staged query the explorer plots, one builder query per metric. The+ * explorer reads the metric names off it, and without one it only offers its+ * "select a metric" placeholder.+ */+const explorerQuery = (count: number): Query => {+ const names = explorerMetricNames(count);++ const queryFor = (metricName: string): Query =>+ getMetricDetailsQuery(+ metricName,+ metricTypeOf(metricName),+ undefined,+ undefined,+ undefined,+ metricIsMonotonic(metricName),+ metricTemporalityOf(metricName),+ );++ const base = queryFor(names[0]);++ return {+ ...base,+ id: 'storybook-metrics-explorer-query',+ builder: {+ ...base.builder,+ queryData: names.map((metricName, index) => ({+ ...queryFor(metricName).builder.queryData[0],+ queryName: QUERY_NAMES[index],+ expression: QUERY_NAMES[index],+ })),+ },+ };+};++interface RouteValues {+ tab: MetricsTab;+ drawer: DrawerState;+ drawerMetric: DrawerMetricType;+ explorerMetrics: number;+}++const metricsRoute = ({+ tab,+ drawer,+ drawerMetric,+ explorerMetrics,+}: RouteValues): string => {+ if (tab === 'views') {+ return ROUTES.METRICS_EXPLORER_VIEWS;+ }++ if (tab === 'volume-control') {+ return ROUTES.METRICS_EXPLORER_VOLUME_CONTROL;+ }++ const params = new URLSearchParams({+ [QueryParams.relativeTime]: RELATIVE_TIME,+ });++ if (tab === 'explorer') {+ params.set(+ QueryParams.compositeQuery,+ JSON.stringify(explorerQuery(explorerMetrics)),+ );+ params.set(QueryParams.panelTypes, JSON.stringify(PANEL_TYPES.TIME_SERIES));++ return `${ROUTES.METRICS_EXPLORER_EXPLORER}?${params.toString()}`;+ }++ if (drawer !== 'closed') {+ params.set(SELECTED_METRIC_NAME_KEY, drawerMetricName(drawerMetric));+ params.set(+ drawer === 'inspect'+ ? IS_INSPECT_MODAL_OPEN_KEY+ : IS_METRIC_DETAILS_OPEN_KEY,+ 'true',+ );+ }++ return `${ROUTES.METRICS_EXPLORER}?${params.toString()}`;+};++interface MetricScale {+ base: number;+ amplitude: number;+}++const METRIC_SCALES: Record<string, MetricScale> = {+ container_cpu_utilization: { base: 0.42, amplitude: 0.16 },+ 'k8s.pod.memory.usage': { base: 620_000_000, amplitude: 140_000_000 },+ 'http.server.request.count': { base: 1_840, amplitude: 460 },+};++const DEFAULT_SCALE: MetricScale = { base: 120, amplitude: 40 };++const EXPORT_DASHBOARDS = [+ 'API latency overview',+ 'Kubernetes capacity',+ 'Checkout funnel',+ 'Ingress health',+];++const SERIES_SERVICES = [+ 'frontend',+ 'checkout',+ 'payments',+ 'cart',+ 'auth',+ 'search',+];++const metricNameOf = (+ spec: QueryRangeRequestV5['compositeQuery']['queries'][number]['spec'],+): string | undefined => {+ if (!('aggregations' in spec)) {+ return undefined;+ }++ const [aggregation] = spec.aggregations ?? [];++ return aggregation && 'metricName' in aggregation+ ? aggregation.metricName+ : undefined;+};++const chartSeries = (+ metricName: string | undefined,+ count: number,+ { start, end }: { start: number; end: number },+): TimeSeries[] => {+ const scale = METRIC_SCALES[metricName ?? ''] ?? DEFAULT_SCALE;++ return SERIES_SERVICES.slice(0, count).map((service, index) => ({+ labels: [{ key: { name: 'service.name' }, value: service }],+ values: timeSeriesPoints({ start, end, seed: index * 2, ...scale }),+ }));+};++export const metricsMocks = defineStoryMocks({+ controls: {+ tab: choiceControl<MetricsTab>('Tab', {+ group: VIEW,+ description:+ 'The four pathnames the module tabs between. Clicking another tab leaves the story, so switch it here.',+ options: METRICS_TABS,+ value: 'summary',+ }),+ drawer: choiceControl<DrawerState>('Metric drawer', {+ group: VIEW,+ description:+ 'What the Summary tab opens over the table: the metric details drawer, or the inspect modal.',+ options: DRAWER_STATES,+ value: 'closed',+ }),+ drawerMetric: choiceControl<DrawerMetricType>('Drawer metric', {+ group: VIEW,+ description:+ 'Which metric the drawer opens, by type. Only a gauge offers Inspect, so the other two drop that action.',+ options: DRAWER_METRIC_TYPES,+ value: 'gauge',+ }),+ metrics: countControl('Metrics', {+ group: SUMMARY,+ description:+ 'Metrics the stats endpoint has. The table asks for ten at a time, so a higher count paginates.',+ value: METRIC_MAX,+ max: METRIC_MAX,+ }),+ treemap: countControl('Treemap tiles', {+ group: SUMMARY,+ description:+ 'Metrics the proportion view plots. At 0 it shows its own empty state above a populated table.',+ value: 12,+ max: METRIC_MAX,+ }),+ attributes: countControl('Drawer attributes', {+ group: SUMMARY,+ description: 'Attribute keys the metric details drawer lists.',+ value: 8,+ max: ATTRIBUTE_MAX,+ }),+ relatedAssets: countControl('Dashboards and alerts', {+ group: SUMMARY,+ description:+ 'Panels and alert rules the drawer reports the metric is used in. At 0 the popover is gone.',+ value: 4,+ max: RELATED_ASSET_MAX,+ }),+ inspectSeries: countControl('Inspect series', {+ group: SUMMARY,+ description: 'Time series the inspect modal plots for the metric.',+ value: 5,+ max: INSPECT_SERIES_MAX,+ }),+ explorerMetrics: countControl('Explorer metrics', {+ group: EXPLORER,+ description:+ 'Metrics in the explorer query. Their units differ, so past one the page forces one chart per query.',+ value: 1,+ max: 3,+ }),+ chartSeries: countControl('Chart series', {+ group: EXPLORER,+ description: 'Series each explorer chart draws.',+ value: 4,+ max: SERIES_SERVICES.length,+ }),+ savedViews: countControl('Saved views', {+ group: EXPLORER,+ description: 'Fills the explorer views dropdown and the Views tab.',+ value: 4,+ max: SAVED_VIEW_MAX,+ }),+ volumeControl: toggleControl('Volume control', {+ group: VOLUME,+ description:+ 'The metrics-reduction feature flag the tab hangs off. Off, the module has no Volume Control tab at all.',+ value: true,+ }),+ rules: countControl('Reduction rules', {+ group: VOLUME,+ description:+ 'Rules the workspace has configured. The table pages ten at a time and the stat tiles sum all of them.',+ value: REDUCTION_RULE_MAX,+ max: REDUCTION_RULE_MAX,+ }),+ pendingRules: toggleControl('Pending rules', {+ group: VOLUME,+ description:+ 'Leaves every fourth rule inactive, which the table badges as pending until it takes effect.',+ value: true,+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v2/metrics/stats',+ response.json(async (req) => {+ const { limit, offset } =+ (await req.json()) as MetricsexplorertypesStatsRequestDTO;++ return metricsStatsResponse(values.metrics, {+ limit: limit ?? METRICS_TABLE_PAGE_SIZE,+ offset: offset ?? 0,+ });+ }),+ ),++ rest.post(+ 'http://localhost/api/v2/metrics/treemap',+ response.json(() => metricsTreemapResponse(values.treemap)),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics',+ response.json((req) =>+ listMetricsResponse(req.url.searchParams.get('searchText') ?? ''),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/metadata',+ response.json((req) =>+ metricMetadataResponse(req.url.searchParams.get('metricName') ?? ''),+ ),+ ),++ // The drawer writes description, unit and type back. The metadata a story+ // answers with comes from the catalogue, so the save succeeds and the+ // refetch reads the metric as it was.+ rest.post('http://localhost/api/v2/metrics/metadata', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json({ status: 'success', data: null })),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/highlights',+ response.json((req) =>+ metricHighlightsResponse(+ req.url.searchParams.get('metricName') ?? '',+ Date.now(),+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/attributes',+ response.json(() => metricAttributesResponse(values.attributes)),+ ),++ rest.get(+ 'http://localhost/api/v3/metrics/dashboards',+ response.json(() => metricDashboardsResponse(values.relatedAssets)),+ ),++ rest.get(+ 'http://localhost/api/v2/metrics/alerts',+ response.json(() => metricAlertsResponse(values.relatedAssets)),+ ),++ rest.post(+ 'http://localhost/api/v2/metrics/inspect',+ response.json(async (req) => {+ const { start, end } =+ (await req.json()) as MetricsexplorertypesInspectMetricsRequestDTO;++ return inspectMetricsResponse(values.inspectSeries, { start, end });+ }),+ ),++ rest.get(+ 'http://localhost/api/v2/metric_reduction_rules',+ response.json((req) => {+ const { searchParams } = req.url;++ return reductionRulesResponse(+ values.rules,+ {+ limit: Number(searchParams.get('limit') ?? METRICS_TABLE_PAGE_SIZE),+ offset: Number(searchParams.get('offset') ?? 0),+ },+ values.pendingRules,+ searchParams.get('metricName'),+ );+ }),+ ),++ rest.get(+ 'http://localhost/api/v2/metric_reduction_rules/stats',+ response.json(() => reductionRuleStatsResponse(values.rules)),+ ),++ rest.get(+ 'http://localhost/api/v2/metric_reduction_rules/timeseries',+ response.json(() => {+ const now = Date.now();++ return reductionRuleTimeseriesResponse(values.rules, {+ start: now - SIX_HOURS_IN_MS,+ end: now,+ });+ }),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ fieldKeysResponse(metricFieldKeys(req.url.searchParams.get('searchText'))),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(+ metricFieldValues(+ req.url.searchParams.get('name'),+ req.url.searchParams.get('searchText'),+ ),+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json(() => dashboardsForUserResponse(EXPORT_DASHBOARDS)),+ ),++ rest.get(+ 'http://localhost/api/v1/explorer/views',+ response.json(() => metricsSavedViewsResponse(values.savedViews)),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const { start, end } = body;+ const queries = body.compositeQuery?.queries ?? [];++ return queryRangeV5TimeSeriesResponse(+ queries.map(({ spec }) => ({+ queryName: 'name' in spec ? (spec.name ?? 'A') : 'A',+ series: chartSeries(metricNameOf(spec), values.chartSeries, {+ start,+ end,+ }),+ })),+ );+ }),+ ),+ ],+ config: (values) => ({+ route: metricsRoute(values),+ reduxState: timeRange(),+ appContext: {+ featureFlags: [+ ...defaultFeatureFlags,+ {+ name: FeatureKeys.ENABLE_METRICS_REDUCTION,+ active: values.volumeControl,+ usage: 0,+ usage_limit: -1,+ route: '',+ },+ ],+ },+ }),+ // The table's page size is persisted, so a size picked in a real dev session+ // would decide how many rows the story's first request asks for.+ effect: () => {+ setLocalStorage(+ 'k8s-metricsExplorer-page-size',+ String(METRICS_TABLE_PAGE_SIZE),+ );+ },+});diff --git a/frontend/src/pages/MetricsExplorer/stories/MetricsExplorerPage.stories.tsx b/frontend/src/pages/MetricsExplorer/stories/MetricsExplorerPage.stories.tsxnew file mode 100644index 0000000000..41d2dec8a8--- /dev/null+++ b/frontend/src/pages/MetricsExplorer/stories/MetricsExplorerPage.stories.tsx@@ -0,0 +1,116 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { metricsMocks } from './MetricsExplorerPage.stories.mocks';+import MetricsExplorerPage from '../MetricsExplorerPage';++type MetricsArgs = PageStoryArgs<typeof metricsMocks>;++const pageStory = storyMocks(metricsMocks, { layout: 'app' });++/**+ * Metrics: the summary treemap, the explorer over `query_range`, the metric drawer+ * with its attributes and related assets, saved views, and the volume control+ * rules.+ *+ * Route: `/metrics-explorer/*`, the tab control picks which.+ */+const meta = {+ title: 'Pages/Metrics/Explorer',+ tags: ['play'],+ component: MetricsExplorerPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<MetricsArgs>;++export default meta;++type Story = StoryObj<MetricsArgs>;++/**+ * The Summary tab on a workspace ingesting a full catalogue of metrics: the+ * proportion view sizing each metric against the others, and the list view+ * below it paging ten metrics at a time with their type, unit and cardinality.+ */+export const Default: Story = {};++/**+ * The metric details drawer, opened from a row: the metric's metadata, the+ * cardinality highlights, the dashboards and alerts it feeds, and its attribute+ * keys with the values seen in the window.+ */+export const MetricDetails: Story = {+ args: { drawer: 'details' },+};++/**+ * The inspect modal, which plots the raw time series behind one gauge before any+ * time or space aggregation is applied.+ */+export const Inspect: Story = {+ args: { drawer: 'inspect' },+};++/**+ * The Volume Control tab: what the workspace ingests against what the reduction+ * rules retain, and the rule per metric that decides it.+ */+export const VolumeControl: Story = {+ args: { tab: 'volume-control' },+};++/**+ * The Explorer tab plotting one metric, with the query builder above the chart+ * and the saved-view actions in the toolbar.+ */+export const Explorer: Story = {+ args: { tab: 'explorer' },+};++/** The Views tab, where the saved views the explorer offers are managed. */+export const SavedViews: Story = {+ args: { tab: 'views' },+};++/**+ * A fresh workspace: nothing ingested in the window, so the Summary tab drops+ * both views for its onboarding state and nothing is saved or reduced yet.+ */+export const NoMetrics: Story = {+ args: { metrics: 0, treemap: 0, rules: 0, savedViews: 0 },+};++/** The Summary tab mid-query, with the cancel action the toolbar offers. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/**+ * The metric details drawer's highlights, all three held open: the exact sample+ * count behind the abbreviated one, what counts as an active time series, and+ * the timestamp the last data point arrived at.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true, drawer: 'details' },+};++/**+ * The dashboards pill in the metric details drawer, open: every dashboard that+ * charts this metric, each a link out to it.+ */+export const MetricDetailsDashboardsMenu: Story = {+ args: { drawer: 'details' },+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByTestId(+ 'metric-dashboards-popover',+ {},+ { timeout: 10000 },+ ),+ );+ await screen.findByRole('menu');+ },+};diff --git a/frontend/src/pages/MetricsExplorer/stories/__story_mockdata__/metricsExplorer.ts b/frontend/src/pages/MetricsExplorer/stories/__story_mockdata__/metricsExplorer.tsnew file mode 100644index 0000000000..3cb7b089b0--- /dev/null+++ b/frontend/src/pages/MetricsExplorer/stories/__story_mockdata__/metricsExplorer.ts@@ -0,0 +1,817 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ GetMetricAlerts200,+ GetMetricAttributes200,+ GetMetricDashboardsV2200,+ GetMetricHighlights200,+ GetMetricMetadata200,+ GetMetricReductionRuleStats200,+ GetMetricReductionRuleTimeseries200,+ GetMetricsStats200,+ GetMetricsTreemap200,+ InspectMetrics200,+ ListMetricReductionRules200,+ ListMetrics200,+ MetricreductionruletypesGettableReductionRuleDTO,+ MetricsexplorertypesStatDTO,+ MetricsexplorertypesTreemapEntryDTO,+} from 'api/generated/services/sigNoz.schemas';+import {+ MetricreductionruletypesMatchTypeDTO,+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+ Querybuildertypesv5RequestTypeDTO,+} from 'api/generated/services/sigNoz.schemas';+import { explorerView } from 'mocks-server/__mockdata__/explorer_views';+import type { AllViewsProps, ViewProps } from 'types/api/saveViews/types';+import { DataSource } from 'types/common/queryBuilder';++interface MetricSeed {+ metricName: string;+ description: string;+ type: MetrictypesTypeDTO;+ temporality: MetrictypesTemporalityDTO;+ unit: string;+ samples: number;+ timeseries: number;+}++/**+ * Ordered by samples descending, which is the order the table asks for by+ * default, so the first page reads the way the backend would answer it.+ */+const METRICS: MetricSeed[] = [+ {+ metricName: 'http.server.duration',+ description: 'Duration of inbound HTTP requests',+ type: MetrictypesTypeDTO.histogram,+ temporality: MetrictypesTemporalityDTO.delta,+ unit: 'ms',+ samples: 48_120_400,+ timeseries: 32_480,+ },+ {+ metricName: 'signoz_latency_bucket',+ description: 'Span latency histogram written by the collector',+ type: MetrictypesTypeDTO.histogram,+ temporality: MetrictypesTemporalityDTO.cumulative,+ unit: 'ms',+ samples: 31_880_100,+ timeseries: 24_960,+ },+ {+ metricName: 'container_cpu_utilization',+ description: 'CPU utilization of a container, as a ratio of its limit',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: 'percentunit',+ samples: 18_402_900,+ timeseries: 12_240,+ },+ {+ metricName: 'k8s.pod.memory.usage',+ description: 'Memory currently in use by a pod',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: 'bytes',+ samples: 14_760_320,+ timeseries: 9_820,+ },+ {+ metricName: 'http.server.request.count',+ description: 'Inbound HTTP requests, counted per route and status',+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.delta,+ unit: '',+ samples: 9_430_650,+ timeseries: 7_410,+ },+ {+ metricName: 'system.cpu.time',+ description: 'Seconds the CPU spent in each state',+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.cumulative,+ unit: 's',+ samples: 6_120_480,+ timeseries: 5_260,+ },+ {+ metricName: 'kafka.consumer.lag',+ description: 'Messages a consumer group is behind the partition head',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: '',+ samples: 4_890_210,+ timeseries: 3_180,+ },+ {+ metricName: 'runtime.jvm.gc.duration',+ description: 'Time spent in garbage collection',+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.cumulative,+ unit: 'ms',+ samples: 3_204_770,+ timeseries: 2_640,+ },+ {+ metricName: 'db.client.connections.usage',+ description: 'Connections held by the client pool',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: '',+ samples: 2_640_190,+ timeseries: 1_980,+ },+ {+ metricName: 'redis.command.duration',+ description: 'Latency quantiles reported by the Redis client',+ type: MetrictypesTypeDTO.summary,+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: 'ms',+ samples: 1_980_540,+ timeseries: 1_420,+ },+ {+ metricName: 'payment.transaction.amount',+ description: 'Distribution of settled payment amounts',+ type: MetrictypesTypeDTO.exponentialhistogram,+ temporality: MetrictypesTemporalityDTO.delta,+ unit: '',+ samples: 1_412_300,+ timeseries: 940,+ },+ {+ metricName: 'otelcol_receiver_accepted_metric_points',+ description: 'Metric points the collector accepted',+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.cumulative,+ unit: '',+ samples: 980_640,+ timeseries: 720,+ },+ {+ metricName: 'queue.depth',+ description: 'Jobs waiting in the worker queue',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: '',+ samples: 612_480,+ timeseries: 410,+ },+ {+ metricName: 'nginx.requests',+ description: 'Requests served by the ingress',+ type: MetrictypesTypeDTO.sum,+ temporality: MetrictypesTemporalityDTO.delta,+ unit: '',+ samples: 420_310,+ timeseries: 260,+ },+ {+ metricName: 'service.availability',+ description: 'Share of successful probes over the window',+ type: MetrictypesTypeDTO.gauge,+ temporality: MetrictypesTemporalityDTO.unspecified,+ unit: 'percent',+ samples: 210_900,+ timeseries: 120,+ },+ {+ metricName: 'checkout.cart.items',+ description: 'Items per cart at checkout',+ type: MetrictypesTypeDTO.histogram,+ temporality: MetrictypesTemporalityDTO.delta,+ unit: '',+ samples: 96_240,+ timeseries: 60,+ },+];++export const METRIC_MAX = METRICS.length;++const seedOf = (metricName: string): MetricSeed =>+ METRICS.find((metric) => metric.metricName === metricName) ?? METRICS[0];++/** Sums are monotonic unless the metric is a non-monotonic cumulative gauge. */+const isMonotonic = ({ type }: MetricSeed): boolean =>+ type === MetrictypesTypeDTO.sum ||+ type === MetrictypesTypeDTO.histogram ||+ type === MetrictypesTypeDTO.exponentialhistogram;++/**+ * What the drawer opens on, one per branch it has: only a gauge offers Inspect,+ * and only a sum carries a temporality worth showing.+ */+export const DRAWER_METRIC_TYPES = ['gauge', 'sum', 'histogram'] as const;++export type DrawerMetricType = (typeof DRAWER_METRIC_TYPES)[number];++const DRAWER_METRICS: Record<DrawerMetricType, string> = {+ gauge: 'container_cpu_utilization',+ sum: 'http.server.request.count',+ histogram: 'http.server.duration',+};++export const drawerMetricName = (type: DrawerMetricType): string =>+ DRAWER_METRICS[type];++/**+ * The metrics the explorer plots, in the order the query builder adds them.+ * Their units differ, which is what makes the page force one chart per query.+ */+export const EXPLORER_METRICS = [+ 'container_cpu_utilization',+ 'k8s.pod.memory.usage',+ 'http.server.request.count',+] as const;++export const explorerMetricNames = (count: number): string[] => [+ ...EXPLORER_METRICS.slice(0, count),+];++export const metricTypeOf = (metricName: string): MetrictypesTypeDTO =>+ seedOf(metricName).type;++export const metricTemporalityOf = (+ metricName: string,+): MetrictypesTemporalityDTO => seedOf(metricName).temporality;++export const metricIsMonotonic = (metricName: string): boolean =>+ isMonotonic(seedOf(metricName));++const statOf = ({+ metricName,+ description,+ type,+ unit,+ samples,+ timeseries,+}: MetricSeed): MetricsexplorertypesStatDTO => ({+ metricName,+ description,+ type,+ unit,+ samples,+ timeseries,+});++interface Page {+ offset: number;+ limit: number;+}++/**+ * `total` is what the table paginates on, so it answers the control's count+ * while `metrics` only carries the page that was asked for.+ */+export const metricsStatsResponse = (+ count: number,+ { offset, limit }: Page,+): GetMetricsStats200 => ({+ status: 'success',+ data: {+ total: count,+ metrics: METRICS.slice(0, count)+ .slice(offset, offset + limit)+ .map(statOf),+ },+});++const treemapEntries = (+ count: number,+ value: (seed: MetricSeed) => number,+): MetricsexplorertypesTreemapEntryDTO[] => {+ const seeds = METRICS.slice(0, count);+ const total = seeds.reduce((sum, seed) => sum + value(seed), 0);++ return seeds.map((seed) => ({+ metricName: seed.metricName,+ totalValue: value(seed),+ percentage: total > 0 ? (value(seed) / total) * 100 : 0,+ }));+};++/** Both modes come back on one response; the tile switcher picks between them. */+export const metricsTreemapResponse = (+ count: number,+): GetMetricsTreemap200 => ({+ status: 'success',+ data: {+ samples: treemapEntries(count, (seed) => seed.samples),+ timeseries: treemapEntries(count, (seed) => seed.timeseries),+ },+});++export const listMetricsResponse = (searchText: string): ListMetrics200 => {+ const search = searchText.toLowerCase();++ return {+ status: 'success',+ data: {+ metrics: METRICS.filter((metric) =>+ metric.metricName.toLowerCase().includes(search),+ ).map(({ metricName, description, type, unit, temporality }) => ({+ metricName,+ description,+ type,+ unit,+ temporality,+ isMonotonic: isMonotonic(seedOf(metricName)),+ })),+ },+ };+};++export const metricMetadataResponse = (+ metricName: string,+): GetMetricMetadata200 => {+ const seed = seedOf(metricName);++ return {+ status: 'success',+ data: {+ description: seed.description,+ type: seed.type,+ unit: seed.unit,+ temporality: seed.temporality,+ isMonotonic: isMonotonic(seed),+ },+ };+};++const FIVE_MINUTES_IN_MS = 5 * 60 * 1000;++export const metricHighlightsResponse = (+ metricName: string,+ now: number,+): GetMetricHighlights200 => {+ const seed = seedOf(metricName);++ return {+ status: 'success',+ data: {+ activeTimeSeries: Math.round(seed.timeseries * 0.82),+ totalTimeSeries: seed.timeseries,+ dataPoints: seed.samples,+ lastReceived: now - FIVE_MINUTES_IN_MS,+ },+ };+};++const ATTRIBUTES: { key: string; values: string[] }[] = [+ {+ key: 'service.name',+ values: ['frontend', 'checkout', 'payments', 'cart', 'auth'],+ },+ {+ key: 'deployment.environment',+ values: ['production', 'staging'],+ },+ {+ key: 'k8s.cluster.name',+ values: ['us-east-1-prod', 'eu-west-1-prod'],+ },+ {+ key: 'k8s.namespace.name',+ values: ['default', 'checkout', 'observability'],+ },+ {+ key: 'http.route',+ values: ['/api/orders', '/api/cart', '/api/checkout', '/healthz'],+ },+ { key: 'http.method', values: ['GET', 'POST', 'PUT', 'DELETE'] },+ { key: 'http.status_code', values: ['200', '201', '404', '500', '503'] },+ { key: 'host.name', values: ['ip-10-0-1-42', 'ip-10-0-2-17'] },+ { key: 'container.name', values: ['app', 'sidecar'] },+ { key: 'telemetry.sdk.language', values: ['go', 'java', 'nodejs', 'python'] },+];++export const ATTRIBUTE_MAX = ATTRIBUTES.length;++/**+ * `valueCount` is the cardinality of the key, which the drawer shows next to the+ * values it actually returns, so it stays above the length of the sample.+ */+export const metricAttributesResponse = (+ count: number,+): GetMetricAttributes200 => {+ const attributes = ATTRIBUTES.slice(0, count);++ return {+ status: 'success',+ data: {+ totalKeys: attributes.length,+ attributes: attributes.map(({ key, values }, index) => ({+ key,+ values,+ valueCount: values.length + index * 3,+ })),+ },+ };+};++const DASHBOARD_PANELS: { dashboard: string; panel: string }[] = [+ { dashboard: 'API latency overview', panel: 'p99 by route' },+ { dashboard: 'Kubernetes capacity', panel: 'CPU utilization by pod' },+ { dashboard: 'Checkout funnel', panel: 'Requests per minute' },+ { dashboard: 'Ingress health', panel: 'Error rate' },+ { dashboard: 'Cost overview', panel: 'Series per metric' },+ { dashboard: 'On-call board', panel: 'Saturation' },+];++const ALERT_NAMES = [+ 'High p99 latency',+ 'Pod memory above limit',+ 'Error rate over 5%',+ 'Queue backing up',+ 'Availability under SLO',+ 'Kafka consumer falling behind',+];++export const RELATED_ASSET_MAX = DASHBOARD_PANELS.length;++export const metricDashboardsResponse = (+ count: number,+): GetMetricDashboardsV2200 => ({+ status: 'success',+ data: {+ dashboards: DASHBOARD_PANELS.slice(0, count).map(+ ({ dashboard, panel }, index) => ({+ dashboardId: `storybook-dashboard-${index + 1}`,+ dashboardName: dashboard,+ panelId: `storybook-panel-${index + 1}`,+ panelName: panel,+ }),+ ),+ },+});++export const metricAlertsResponse = (count: number): GetMetricAlerts200 => ({+ status: 'success',+ data: {+ alerts: ALERT_NAMES.slice(0, count).map((alertName, index) => ({+ alertId: `storybook-alert-${index + 1}`,+ alertName,+ })),+ },+});++interface Window {+ start: number;+ end: number;+}++const INSPECT_LABELS: { service: string; pod: string }[] = [+ { service: 'frontend', pod: 'frontend-9d3e77' },+ { service: 'checkout', pod: 'checkout-7b9f4d' },+ { service: 'payments', pod: 'payments-5c8a12' },+ { service: 'cart', pod: 'cart-2f7b31' },+ { service: 'auth', pod: 'auth-84cd09' },+ { service: 'notifications', pod: 'notify-61ba55' },+ { service: 'search', pod: 'search-3ac902' },+ { service: 'recommendations', pod: 'recs-77de41' },+];++export const INSPECT_SERIES_MAX = INSPECT_LABELS.length;++const POINTS_PER_SERIES = 40;++/**+ * The inspect graph reads one point per series per timestamp, so every series+ * carries the same timestamps and only the values differ.+ */+export const inspectMetricsResponse = (+ count: number,+ { start, end }: Window,+): InspectMetrics200 => {+ const step = (end - start) / Math.max(POINTS_PER_SERIES - 1, 1);++ return {+ status: 'success',+ data: {+ series: INSPECT_LABELS.slice(0, count).map(({ service, pod }, index) => ({+ labels: [+ { key: { name: 'service.name' }, value: service },+ { key: { name: 'k8s.pod.name' }, value: pod },+ ],+ values: Array.from({ length: POINTS_PER_SERIES }, (_unused, point) => ({+ timestamp: Math.round(start + point * step),+ value:+ 0.42 ++ 0.18 * Math.sin((point + index * 4) / 5) ++ 0.06 * Math.cos((point + index) / 3),+ })),+ })),+ },+ };+};++interface ReductionRuleSeed {+ metricName: string;+ matchType: MetricreductionruletypesMatchTypeDTO;+ labels: string[];+ reduction: number;+}++const REDUCTION_RULES: ReductionRuleSeed[] = [+ {+ metricName: 'http.server.duration',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['http.url', 'http.user_agent'],+ reduction: 0.68,+ },+ {+ metricName: 'signoz_latency_bucket',+ matchType: MetricreductionruletypesMatchTypeDTO.keep,+ labels: ['service.name', 'operation'],+ reduction: 0.54,+ },+ {+ metricName: 'container_cpu_utilization',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['container.id'],+ reduction: 0.47,+ },+ {+ metricName: 'k8s.pod.memory.usage',+ matchType: MetricreductionruletypesMatchTypeDTO.keep,+ labels: ['k8s.namespace.name', 'k8s.pod.name'],+ reduction: 0.41,+ },+ {+ metricName: 'http.server.request.count',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['http.target'],+ reduction: 0.36,+ },+ {+ metricName: 'system.cpu.time',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['cpu', 'state'],+ reduction: 0.32,+ },+ {+ metricName: 'kafka.consumer.lag',+ matchType: MetricreductionruletypesMatchTypeDTO.keep,+ labels: ['topic', 'consumer_group'],+ reduction: 0.28,+ },+ {+ metricName: 'runtime.jvm.gc.duration',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['gc.name'],+ reduction: 0.24,+ },+ {+ metricName: 'db.client.connections.usage',+ matchType: MetricreductionruletypesMatchTypeDTO.keep,+ labels: ['pool.name'],+ reduction: 0.19,+ },+ {+ metricName: 'redis.command.duration',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['command'],+ reduction: 0.15,+ },+ {+ metricName: 'otelcol_receiver_accepted_metric_points',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['receiver'],+ reduction: 0.12,+ },+ {+ metricName: 'queue.depth',+ matchType: MetricreductionruletypesMatchTypeDTO.keep,+ labels: ['queue.name'],+ reduction: 0.08,+ },+ {+ metricName: 'nginx.requests',+ matchType: MetricreductionruletypesMatchTypeDTO.drop,+ labels: ['upstream'],+ reduction: 0.06,+ },+ {+ metricName: 'checkout.cart.items',+ matchType: MetricreductionruletypesMatchTypeDTO.keep,+ labels: ['store.id'],+ reduction: 0.04,+ },+];++export const REDUCTION_RULE_MAX = REDUCTION_RULES.length;++const RULE_UPDATED_AT = '2026-08-20T09:24:00Z';++const RULE_EFFECTIVE_FROM = '2026-08-20T09:29:00Z';++const ruleOf = (+ seed: ReductionRuleSeed,+ index: number,+ pending: boolean,+): MetricreductionruletypesGettableReductionRuleDTO => {+ const { samples, timeseries } = seedOf(seed.metricName);++ return {+ id: `storybook-reduction-rule-${index + 1}`,+ metricName: seed.metricName,+ matchType: seed.matchType,+ 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),+ effectiveFrom: RULE_EFFECTIVE_FROM,+ ingestedSeries: timeseries,+ retainedSeries: Math.round(timeseries * (1 - seed.reduction)),+ ingestedSamples: samples,+ retainedSamples: Math.round(samples * (1 - seed.reduction)),+ updatedAt: RULE_UPDATED_AT,+ updatedBy: '[email protected]',+ createdAt: RULE_UPDATED_AT,+ createdBy: '[email protected]',+ };+};++/**+ * The metric details drawer asks for one metric's rule, the tab asks for a page+ * of all of them, and both read `rules[0]` off the same response.+ */+export const reductionRulesResponse = (+ count: number,+ { offset, limit }: Page,+ pending: boolean,+ metricName?: string | null,+): ListMetricReductionRules200 => {+ const configured = REDUCTION_RULES.slice(0, count)+ .map((seed, index) => ({ seed, index }))+ .filter(({ seed }) => !metricName || seed.metricName === metricName);++ const page = metricName+ ? configured+ : configured.slice(offset, offset + limit);++ return {+ status: 'success',+ data: {+ total: configured.length,+ rules: page.map(({ seed, index }) => ruleOf(seed, index, pending)),+ },+ };+};++const DOLLARS_PER_SERIES_PER_MONTH = 0.006;++/**+ * The stat tiles compare ingested against retained across every rule, so the+ * totals are the sum over the rules the list answers with.+ */+export const reductionRuleStatsResponse = (+ count: number,+): GetMetricReductionRuleStats200 => {+ const seeds = REDUCTION_RULES.slice(0, count);++ const totals = seeds.reduce(+ (sum, seed) => {+ const { samples, timeseries } = seedOf(seed.metricName);++ return {+ ingestedSeries: sum.ingestedSeries + timeseries,+ retainedSeries:+ sum.retainedSeries + Math.round(timeseries * (1 - seed.reduction)),+ ingestedSamples: sum.ingestedSamples + samples,+ retainedSamples:+ sum.retainedSamples + Math.round(samples * (1 - seed.reduction)),+ };+ },+ {+ ingestedSeries: 0,+ retainedSeries: 0,+ ingestedSamples: 0,+ retainedSamples: 0,+ },+ );++ return {+ status: 'success',+ data: {+ ...totals,+ estimatedMonthlySavingsUsd:+ (totals.ingestedSeries - totals.retainedSeries) *+ DOLLARS_PER_SERIES_PER_MONTH,+ },+ };+};++const VOLUME_BUCKETS = 24;++/**+ * The bar chart looks the two series up by label value, so `ingested` and+ * `retained` are the labels the response has to carry.+ */+export const reductionRuleTimeseriesResponse = (+ count: number,+ { start, end }: Window,+): GetMetricReductionRuleTimeseries200 => {+ const step = (end - start) / Math.max(VOLUME_BUCKETS - 1, 1);+ const { data } = reductionRuleStatsResponse(count);++ const bucketValues = (total: number): { timestamp: number; value: number }[] =>+ Array.from({ length: VOLUME_BUCKETS }, (_unused, index) => ({+ timestamp: Math.round(start + index * step),+ value: Math.round(+ (total / VOLUME_BUCKETS) * (1 + 0.18 * Math.sin(index / 3)),+ ),+ }));++ return {+ status: 'success',+ data: {+ type: Querybuildertypesv5RequestTypeDTO.time_series,+ data: {+ results: [+ {+ queryName: 'volume',+ aggregations: [+ {+ index: 0,+ series: [+ {+ labels: [{ key: { name: 'kind' }, value: 'ingested' }],+ values: bucketValues(data.ingestedSeries),+ },+ {+ labels: [{ key: { name: 'kind' }, value: 'retained' }],+ values: bucketValues(data.retainedSeries),+ },+ ],+ },+ ],+ },+ ],+ },+ },+ };+};++const VIEW_NAMES = [+ 'Container CPU by namespace',+ 'Pod memory saturation',+ 'Kafka lag by topic',+ 'JVM GC pressure',+ 'Ingress request rate',+ 'Payment latency p99',+];++export const SAVED_VIEW_MAX = VIEW_NAMES.length;++/** The jest fixture is the shape of a view; only what the list shows changes. */+const [baseView] = explorerView.data as unknown as ViewProps[];++export const metricsSavedViewsResponse = (count: number): AllViewsProps => ({+ status: 'success',+ data: VIEW_NAMES.slice(0, count).map((name, index) => ({+ ...baseView,+ id: `storybook-metrics-view-${index + 1}`,+ name,+ sourcePage: DataSource.METRICS,+ tags: ['metrics'],+ createdBy: '[email protected]',+ extraData: '{"color":"#7cd4fd"}',+ })),+});++const FIELD_KEYS = [+ 'service.name',+ 'deployment.environment',+ 'k8s.cluster.name',+ 'k8s.namespace.name',+ 'k8s.pod.name',+ 'host.name',+ 'http.route',+ 'http.method',+ 'http.status_code',+ 'container.name',+];++const FIELD_VALUES: Record<string, string[]> = Object.fromEntries(+ ATTRIBUTES.map(({ key, values }) => [key, values]),+);++const matching = (values: readonly string[], searchText: string): string[] => {+ const search = searchText.toLowerCase();++ return values.filter((value) => value.toLowerCase().includes(search));+};++export const metricFieldKeys = (searchText: string | null): string[] =>+ matching(FIELD_KEYS, searchText ?? '');++export const metricFieldValues = (+ name: string | null,+ searchText: string | null,+): string[] => matching(FIELD_VALUES[name ?? ''] ?? [], searchText ?? '');diff --git a/frontend/src/pages/OnboardingPageV2/stories/OnboardingPageV2.stories.mocks.tsx b/frontend/src/pages/OnboardingPageV2/stories/OnboardingPageV2.stories.mocks.tsxnew file mode 100644index 0000000000..50f4cc75fe--- /dev/null+++ b/frontend/src/pages/OnboardingPageV2/stories/OnboardingPageV2.stories.mocks.tsx@@ -0,0 +1,87 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import { rest } from 'msw';+import { ingestionKeysResponse } from 'pages/Settings/Ingestion/stories/__story_mockdata__/ingestion';+import { rolesListResponse } from 'pages/Settings/stories/__story_mockdata__/roles';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++const SOURCE = 'Onboarding · source';++/**+ * `catalogue` is the picker itself; the rest are `getStartedSource` values,+ * which is how a docs link or an in-app card lands someone straight on a+ * source's setup instructions.+ */+const SOURCES = ['catalogue', 'quickstart', 'java', 'kubernetes'] as const;++type Source = (typeof SOURCES)[number];++const DATA_SOURCE_ID: Partial<Record<Source, string>> = {+ quickstart: 'quickstart',+ java: 'java',+ kubernetes: 'kubernetes-pod-logs',+};++/**+ * How far through the picker the story starts. The page asks one question at a+ * time and keeps the answers in component state, so a story reaches a later+ * question by answering the ones before it; `advanceToSetupStep` in the story+ * file walks Java → Spring Boot → VM.+ */+export const SETUP_STEPS = [+ 'select-data-source',+ 'select-framework',+ 'select-environment',+ 'ready-to-configure',+ 'configure-product',+] as const;++export type SetupStep = (typeof SETUP_STEPS)[number];++export const onboardingV2Mocks = defineStoryMocks({+ controls: {+ source: choiceControl<Source>('Data source', {+ group: SOURCE,+ description:+ 'Which source the page opens on. Anything but `catalogue` arrives through the `getStartedSource` param and skips straight to step 2.',+ options: SOURCES,+ value: 'catalogue',+ }),+ step: choiceControl<SetupStep>('Setup step', {+ group: SOURCE,+ description:+ 'How far through the catalogue the story is answered. Nothing to walk when the data source arrives through the param, which is already past every question.',+ options: SETUP_STEPS,+ value: 'select-data-source',+ }),+ },+ handlers: (_values, response) => [+ // The setup instructions quote the workspace's ingestion key, which is the+ // same payload the ingestion settings tab reads.+ rest.get(+ 'http://localhost/api/v2/gateway/ingestion_keys',+ response.json(() => ingestionKeysResponse(1, ['logs', 'traces'], 'none', 1)),+ ),+ // 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)),+ ),+ ],+ config: (values) => {+ const dataSource = DATA_SOURCE_ID[values.source];++ return {+ route: dataSource+ ? `${ROUTES.GET_STARTED_WITH_CLOUD}?${QueryParams.getStartedSource}=${dataSource}`+ : ROUTES.GET_STARTED_WITH_CLOUD,+ };+ },+});diff --git a/frontend/src/pages/OnboardingPageV2/stories/OnboardingPageV2.stories.tsx b/frontend/src/pages/OnboardingPageV2/stories/OnboardingPageV2.stories.tsxnew file mode 100644index 0000000000..966c33ef9d--- /dev/null+++ b/frontend/src/pages/OnboardingPageV2/stories/OnboardingPageV2.stories.tsx@@ -0,0 +1,169 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import OnboardingPageV2 from '../OnboardingPageV2';+import {+ onboardingV2Mocks,+ SETUP_STEPS,+ type SetupStep,+} from './OnboardingPageV2.stories.mocks';++type OnboardingV2Args = PageStoryArgs<typeof onboardingV2Mocks>;++type Canvas = ReturnType<typeof within>;++/** The catalogue mounts before the first group of sources paints. */+const untilRendered = { timeout: 15_000 };++/**+ * Every option is a button wrapping its own logo, so the accessible name carries+ * the label twice and matches the other sources with the label as a prefix+ * (`Java`, `JavaScript`). The label's own text node is the one thing that is+ * exact.+ */+const chooseOption = async (canvas: Canvas, label: string): Promise<void> => {+ const option = await canvas.findByText(label, undefined, untilRendered);++ await userEvent.click(option.closest('button') as HTMLElement);+};++const answerDataSource = (canvas: Canvas): Promise<void> =>+ chooseOption(canvas, 'Java');++const answerFramework = (canvas: Canvas): Promise<void> =>+ chooseOption(canvas, 'Spring Boot');++const answerEnvironment = (canvas: Canvas): Promise<void> =>+ chooseOption(canvas, 'VM');++const openConfigureProduct = async (canvas: Canvas): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole(+ 'button',+ { name: /configure your product/i },+ untilRendered,+ ),+ );+};++const ANSWER_STEP = [+ answerDataSource,+ answerFramework,+ answerEnvironment,+ openConfigureProduct,+];++const advanceToSetupStep = async (+ canvasElement: HTMLElement,+ step: SetupStep,+): Promise<void> => {+ const canvas = within(canvasElement);++ // A source that arrived through the param is already on the setup+ // instructions, with no question left to answer.+ if (!canvas.queryByText('Select your data source')) {+ return;+ }++ const answers = ANSWER_STEP.slice(0, SETUP_STEPS.indexOf(step));++ // Sequential: each answer is what renders the question the next one reads.+ await answers.reduce(+ (walked, answer) => walked.then(() => answer(canvas)),+ Promise.resolve(),+ );+};++const pageStory = storyMocks(onboardingV2Mocks, { layout: 'app' });++/**+ * The add data source flow: pick a source, then walk its steps, with the ingestion+ * key the snippets carry.+ *+ * Route: `/get-started-with-signoz-cloud`.+ */+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);+ },+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<OnboardingV2Args>;++export default meta;++type Story = StoryObj<OnboardingV2Args>;++/** Everything a new workspace can send data from, grouped by signal. */+export const Default: Story = {};++/** A language picked, which is where the catalogue asks what it is written with. */+export const FrameworkQuestion: Story = {+ args: { step: 'select-framework' },+};++/** The last question a source asks: where the instrumented service runs. */+export const EnvironmentQuestion: Story = {+ args: { step: 'select-environment' },+};++/** Every question answered, with the setup instructions one click away. */+export const ReadyToConfigure: Story = {+ args: { step: 'ready-to-configure' },+};++/** The setup instructions for the answered source, next to the ingestion key. */+export const ConfigureProduct: Story = {+ args: { step: 'configure-product' },+};++/** Arrived on a source already picked, which is what a docs link does. */+export const SourcePreselected: Story = {+ args: { source: 'java' },+};++/** 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);+ },+};++/** 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);+ },+};diff --git a/frontend/src/pages/OrgOnboarding/stories/OrgOnboarding.stories.mocks.tsx b/frontend/src/pages/OrgOnboarding/stories/OrgOnboarding.stories.mocks.tsxnew file mode 100644index 0000000000..ee2581179a--- /dev/null+++ b/frontend/src/pages/OrgOnboarding/stories/OrgOnboarding.stories.mocks.tsx@@ -0,0 +1,52 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import { rolesListResponse } from 'pages/Settings/stories/__story_mockdata__/roles';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++const QUESTIONNAIRE = 'Onboarding · questionnaire';++/**+ * The four pages the questionnaire holds in component state. Nothing in the URL+ * says which one is open, so a story reaches one by answering the ones before+ * it; `advanceToQuestionnairePage` in the story file is that walk.+ */+export const QUESTIONNAIRE_PAGES = [+ 'about-your-org',+ 'about-signoz',+ 'your-scale',+ 'invite-team',+] as const;++export type QuestionnairePage = (typeof QUESTIONNAIRE_PAGES)[number];++export const orgOnboardingMocks = defineStoryMocks({+ controls: {+ page: choiceControl<QuestionnairePage>('Questionnaire page', {+ group: QUESTIONNAIRE,+ description:+ 'Which page of the questionnaire the story opens on. Every page before it is answered with the least its Next button accepts.',+ options: QUESTIONNAIRE_PAGES,+ value: 'about-your-org',+ }),+ },+ handlers: (_values, response) => [+ // Answering the scale page saves the profile, and the last page only opens+ // once that call settles: a plain resolver, so `Data` cannot strand the+ // questionnaire two pages in.+ rest.put('http://localhost/api/v2/zeus/profiles', (_req, res, ctx) =>+ res(ctx.status(204)),+ ),+ rest.get(+ 'http://localhost/api/v1/roles',+ response.json(() => rolesListResponse(0)),+ ),+ ],+ config: () => ({ route: ROUTES.ONBOARDING }),+});diff --git a/frontend/src/pages/OrgOnboarding/stories/OrgOnboarding.stories.tsx b/frontend/src/pages/OrgOnboarding/stories/OrgOnboarding.stories.tsxnew file mode 100644index 0000000000..3e4bc21a42--- /dev/null+++ b/frontend/src/pages/OrgOnboarding/stories/OrgOnboarding.stories.tsx@@ -0,0 +1,119 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import OrgOnboarding from '../OrgOnboarding';+import {+ orgOnboardingMocks,+ QUESTIONNAIRE_PAGES,+ type QuestionnairePage,+} from './OrgOnboarding.stories.mocks';++type OrgOnboardingArgs = PageStoryArgs<typeof orgOnboardingMocks>;++type Canvas = ReturnType<typeof within>;++/** The provider tree mounts before the first question paints. */+const untilRendered = { timeout: 15_000 };++const clickNext = async (canvas: Canvas): Promise<void> => {+ await userEvent.click(canvas.getByRole('button', { name: /next/i }));+};++/** Starting fresh with no OpenTelemetry: the shortest answer Next accepts. */+const answerAboutYourOrg = async (canvas: Canvas): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole(+ 'radio',+ { name: 'None/Starting fresh' },+ untilRendered,+ ),+ );+ await userEvent.click(canvas.getByRole('radio', { name: 'No' }));+ await clickNext(canvas);+};++const answerAboutSignoz = async (canvas: Canvas): Promise<void> => {+ await userEvent.type(+ await canvas.findByRole('textbox', undefined, untilRendered),+ 'A colleague mentioned it',+ );+ await userEvent.click(+ canvas.getByRole('checkbox', { name: 'Lowering observability costs' }),+ );+ await clickNext(canvas);+};++/** Next stays disabled until a slider moves; doing it later sends the same zeroes. */+const answerYourScale = async (canvas: Canvas): Promise<void> => {+ await userEvent.click(+ await canvas.findByRole('button', { name: /do this later/i }, untilRendered),+ );+ // The next page is set from the profile mutation's result, not from the click.+ await canvas.findByText('Invite your team', undefined, untilRendered);+};++const ANSWER_PAGE = [answerAboutYourOrg, answerAboutSignoz, answerYourScale];++const advanceToQuestionnairePage = async (+ canvasElement: HTMLElement,+ page: QuestionnairePage,+): Promise<void> => {+ const canvas = within(canvasElement);+ const answers = ANSWER_PAGE.slice(0, QUESTIONNAIRE_PAGES.indexOf(page));++ // Sequential: each answer is what renders the page the next one reads.+ await answers.reduce(+ (walked, answer) => walked.then(() => answer(canvas)),+ Promise.resolve(),+ );+};++const pageStory = storyMocks(orgOnboardingMocks, { layout: 'app' });++/**+ * The org onboarding questionnaire, page by page, before the workspace has data.+ *+ * Route: `/onboarding`.+ */+const meta = {+ title: 'Pages/Onboarding/Questionnaire',+ tags: ['play'],+ component: OrgOnboarding,+ /**+ * Destructuring `mount` is what makes the page 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 advanceToQuestionnairePage(canvasElement, args.page);+ },+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<OrgOnboardingArgs>;++export default meta;++type Story = StoryObj<OrgOnboardingArgs>;++/** The first thing a new organisation sees, before any data is sent. */+export const Default: Story = {};++/** Why the workspace is here: how they found SigNoz, and what they came for. */+export const AboutSigNoz: Story = {+ args: { page: 'about-signoz' },+};++/** The scale the workspace expects, which is what sizes the plan they are offered. */+export const YourScale: Story = {+ args: { page: 'your-scale' },+};++/** The last page, where the workspace is opened up to the rest of the team. */+export const InviteTeam: Story = {+ args: { page: 'invite-team' },+};diff --git a/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.mocks.tsx b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.mocks.tsxnew file mode 100644index 0000000000..4e4816966d--- /dev/null+++ b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.mocks.tsx@@ -0,0 +1,126 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import { generatePath } from 'react-router-dom';+import ROUTES from 'constants/routes';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ dashboardResponse,+ PANEL_IDS,+ panelQueryShape,+ STORY_DASHBOARD_ID,+ type PanelId,+} from '../../DashboardPage/stories/__story_mockdata__/dashboard';+import {+ emptyPanelResponse,+ panelResponse,+} from '../../DashboardPage/stories/__story_mockdata__/panelData';+import {+ PUBLIC_SCHEMAS,+ publicDashboardV2Response,+ SCHEMA_MISMATCH_ERROR,+ UNPUBLISHED_ERROR,+ type PublicSchema,+} from './__story_mockdata__/publicDashboard';++const VIEWER = 'Public dashboard · viewer';+const DATA = 'Public dashboard · panels';++export const publicDashboardRoute = (): string =>+ generatePath(ROUTES.PUBLIC_DASHBOARD, { dashboardId: STORY_DASHBOARD_ID });++export const publicDashboardMocks = defineStoryMocks({+ controls: {+ schema: choiceControl<PublicSchema>('Schema', {+ group: VIEWER,+ description:+ 'Which viewer answers. The page probes v2 first and falls back to v1 only when the v2 endpoint reports a schema mismatch, so `v1` is a dashboard saved before the Perses spec.',+ options: PUBLIC_SCHEMAS,+ value: 'v2',+ }),+ panels: countControl('Panels', {+ group: VIEWER,+ description: 'Panels the published v2 dashboard carries.',+ value: PANEL_IDS.length,+ max: PANEL_IDS.length,+ }),+ timeRange: toggleControl('Time range enabled', {+ group: VIEWER,+ description:+ 'Whether the publisher let viewers change the window. Off hides the time picker and the auto-refresh control.',+ value: true,+ }),+ unpublished: toggleControl('Unpublished', {+ group: VIEWER,+ description:+ 'The link no longer resolves, which is the branded "does not exist or has been unpublished" page.',+ value: false,+ }),+ noData: toggleControl('Panels return nothing', {+ group: DATA,+ description: 'Every panel query answers with an empty result.',+ value: false,+ }),+ },+ handlers: (values, response) => [+ // The published document is what the viewer renders from, so it answers on+ // its own rather than through the Data control.+ rest.get(+ 'http://localhost/api/v2/public/dashboards/:id',+ (_req, res, ctx) => {+ if (values.unpublished) {+ return res(ctx.status(404), ctx.json(UNPUBLISHED_ERROR));+ }++ if (values.schema === 'v1') {+ return res(ctx.status(400), ctx.json(SCHEMA_MISMATCH_ERROR));+ }++ return res(+ ctx.status(200),+ ctx.json(+ publicDashboardV2Response(+ dashboardResponse({+ panels: values.panels,+ sectioned: true,+ variables: [],+ locked: true,+ }).data,+ values.timeRange,+ ),+ ),+ );+ },+ ),++ rest.get(+ 'http://localhost/api/v2/public/dashboards/:id/panels/:key/query_range',+ response.json((req) => {+ if (values.noData) {+ return emptyPanelResponse();+ }++ const key = String(req.params.key) as PanelId;++ return panelResponse({+ ...panelQueryShape(key),+ window: {+ start: Number(req.url.searchParams.get('startTime') ?? 0),+ end: Number(req.url.searchParams.get('endTime') ?? 0),+ },+ });+ }),+ ),+ ],+ config: () => ({ route: publicDashboardRoute() }),+});diff --git a/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.tsx b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.tsxnew file mode 100644index 0000000000..cd2e305ed6--- /dev/null+++ b/frontend/src/pages/PublicDashboard/stories/PublicDashboard.stories.tsx@@ -0,0 +1,92 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';+import { screen, userEvent } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { publicDashboardMocks } from './PublicDashboard.stories.mocks';++import PublicDashboardPage from '../index';++type PublicDashboardArgs = PageStoryArgs<typeof publicDashboardMocks>;++const pageStory = storyMocks(publicDashboardMocks, { layout: 'app' });++/**+ * A dashboard as an anonymous viewer sees it through a public link: the public+ * endpoints answer, and there is no shell around it.+ *+ * Route: `/public/dashboard/:dashboardId`.+ */+const meta = {+ title: 'Pages/Dashboards/Public',+ tags: ['play'],+ component: PublicDashboardPage,+ // The published id comes out of the pathname, so the viewer renders under its+ // own route rather than being mounted on its own. The layout drops the app+ // chrome on this path, which is what a signed-out viewer sees.+ render: (): JSX.Element => (+ <Route path={ROUTES.PUBLIC_DASHBOARD} component={PublicDashboardPage} />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<PublicDashboardArgs>;++export default meta;++/** The viewer fetches the dashboard before it renders its header. */+const untilLoaded = { timeout: 15_000 };++type Story = StoryObj<PublicDashboardArgs>;++/**+ * A published dashboard as an outside viewer sees it: the SigNoz brand, the+ * dashboard's sections and panels read-only, and the time picker the publisher+ * left enabled.+ */+export const Default: Story = {};++/** The publisher pinned the window, so the viewer cannot change it. */+export const FixedTimeRange: Story = {+ args: { timeRange: false },+};++/** Panels resolve successfully but have no matching data. */+export const NoData: Story = {+ args: { noData: true },+};++/** The viewer shell and header remain while the panel queries are loading. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** The public viewer's auto-refresh popover is visibly open. */+export const AutoRefreshMenuOpen: Story = {+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByTestId(+ 'public-dashboard-auto-refresh',+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText('Refresh Interval', undefined, untilLoaded);+ },+};++/** A dashboard saved before the Perses spec, which falls back to the v1 viewer. */+export const LegacySchema: Story = {+ args: { schema: 'v1' },+ // The deliberate 400 is the state under test.+ parameters: { allowConsoleErrors: true },+};++/** The link after it was unpublished, or one that never existed. */+export const Unpublished: Story = {+ args: { unpublished: true },+ // The deliberate 404 is the state under test.+ parameters: { allowConsoleErrors: true },+};diff --git a/frontend/src/pages/PublicDashboard/stories/__story_mockdata__/publicDashboard.ts b/frontend/src/pages/PublicDashboard/stories/__story_mockdata__/publicDashboard.tsnew file mode 100644index 0000000000..452d42ed62--- /dev/null+++ b/frontend/src/pages/PublicDashboard/stories/__story_mockdata__/publicDashboard.ts@@ -0,0 +1,53 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ DashboardtypesGettableDashboardV2DTO,+ GetPublicDashboardDataV2200,+} from 'api/generated/services/sigNoz.schemas';++/** The two shapes a published link can resolve to. */+export const PUBLIC_SCHEMAS = ['v2', 'v1'] as const;++export type PublicSchema = (typeof PUBLIC_SCHEMAS)[number];++export const publicDashboardV2Response = (+ dashboard: DashboardtypesGettableDashboardV2DTO,+ timeRangeEnabled: boolean,+): GetPublicDashboardDataV2200 => ({+ status: 'success',+ data: {+ dashboard,+ publicDashboard: {+ timeRangeEnabled,+ defaultTimeRange: '30m',+ publicPath: `/public/dashboard/${dashboard.id}`,+ },+ },+});++/**+ * The only v2 failure the page reads as "this is a v1 dashboard"; every other+ * error re-throws instead of mis-rendering the older viewer.+ */+export const SCHEMA_MISMATCH_ERROR = {+ status: 'error',+ error: {+ code: 'dashboard_invalid_data',+ message: 'dashboard is not stored in the v6 schema',+ url: '',+ errors: [],+ },+};++export const UNPUBLISHED_ERROR = {+ status: 'error',+ error: {+ code: 'public_dashboard_not_found',+ message: 'public dashboard not found',+ url: '',+ errors: [],+ },+};diff --git a/frontend/src/pages/ResetPassword/stories/ResetPassword.stories.mocks.tsx b/frontend/src/pages/ResetPassword/stories/ResetPassword.stories.mocks.tsxnew file mode 100644index 0000000000..2cb40537a6--- /dev/null+++ b/frontend/src/pages/ResetPassword/stories/ResetPassword.stories.mocks.tsx@@ -0,0 +1,66 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { StatusCodes } from 'http-status-codes';+import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++const LINK = 'Reset password · link';++const RESET_TOKENS = ['valid', 'expired'] as const;++type ResetToken = (typeof RESET_TOKENS)[number];++/** The token the reset email put in the link, which the page verifies on load. */+const RESET_TOKEN = 'e5a3f0c1-2b47-4d5e-9a7c-8f1b2d3e4c5d';++const VERIFY_URL = 'http://localhost/api/v2/reset_password_tokens/verify';++const expiredTokenHandler = rest.post(VERIFY_URL, (_req, res, ctx) =>+ res(+ ctx.status(StatusCodes.GONE),+ ctx.json({+ error: {+ code: 'token_expired',+ message:+ 'This reset link has expired. Ask for a new one from the login page.',+ url: 'https://signoz.io/docs/userguide/manage-users/',+ errors: [],+ },+ }),+ ),+);++export const resetPasswordMocks = defineStoryMocks({+ controls: {+ token: choiceControl<ResetToken>('Reset link', {+ group: LINK,+ description:+ 'What the token in the link verifies as. An expired one replaces the form with the dead-link screen.',+ options: RESET_TOKENS,+ value: 'valid',+ }),+ },+ handlers: (values, response) => [+ values.token === 'valid'+ ? rest.post(+ VERIFY_URL,+ response.json(() => ({ status: 'success' })),+ )+ : expiredTokenHandler,+ rest.post('http://localhost/api/v2/factor_password/reset', (_req, res, ctx) =>+ res(ctx.status(StatusCodes.NO_CONTENT)),+ ),+ ],+ config: () => ({+ route: `${ROUTES.PASSWORD_RESET}?token=${RESET_TOKEN}`,+ // The link is opened signed out, so the shell has no side nav, top nav or+ // banners to draw.+ appContext: { isLoggedIn: false },+ }),+});diff --git a/frontend/src/pages/ResetPassword/stories/ResetPassword.stories.tsx b/frontend/src/pages/ResetPassword/stories/ResetPassword.stories.tsxnew file mode 100644index 0000000000..e7484fe9f3--- /dev/null+++ b/frontend/src/pages/ResetPassword/stories/ResetPassword.stories.tsx@@ -0,0 +1,37 @@+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>;++const pageStory = storyMocks(resetPasswordMocks, { layout: 'app' });++/**+ * The reset form behind a token, valid or not.+ *+ * Route: `/password-reset?token=...`.+ */+const meta = {+ title: 'Pages/Auth/Reset Password',+ component: ResetPassword,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ResetPasswordArgs>;++export default meta;++type Story = StoryObj<ResetPasswordArgs>;++/** What the link in the reset email opens: a new password and its confirmation. */+export const Default: Story = {};++/** The link used too late, which the page tells the user to ask again for. */+export const ExpiredLink: Story = {+ args: { token: 'expired' },+ // The deliberate 410 is the state under test.+ parameters: { allowConsoleErrors: true },+};diff --git a/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.mocks.tsx b/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.mocks.tsxnew file mode 100644index 0000000000..c294f26842--- /dev/null+++ b/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.mocks.tsx@@ -0,0 +1,35 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ SERVICE_NAME,+ servicesWithTopLevelOpsResponse,+} from './__story_mockdata__/serviceTopLevelOperations';++const LIST = 'Top level operations · list';++export const serviceTopLevelOperationsMocks = defineStoryMocks({+ controls: {+ operations: countControl('Operations', {+ group: LIST,+ description:+ 'Entry-point spans the service reported. The page exists for the case where this runs past 2500, and the table pages at 100.',+ value: 24,+ max: 2501,+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v2/services',+ response.json(() => servicesWithTopLevelOpsResponse(values.operations)),+ ),+ ],+ config: () => ({ route: `/services/${SERVICE_NAME}/top-level-operations` }),+});diff --git a/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.tsx b/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.tsxnew file mode 100644index 0000000000..33f498e5db--- /dev/null+++ b/frontend/src/pages/ServiceTopLevelOperations/stories/ServiceTopLevelOperations.stories.tsx@@ -0,0 +1,55 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import ServiceTopLevelOperations from '../index';+import { serviceTopLevelOperationsMocks } from './ServiceTopLevelOperations.stories.mocks';++type ServiceTopLevelOperationsArgs = PageStoryArgs<+ typeof serviceTopLevelOperationsMocks+>;++const pageStory = storyMocks(serviceTopLevelOperationsMocks, { layout: 'app' });++/**+ * Top level operations for one service, the list the service detail page reads.+ *+ * Route: `/services/:servicename/top-level-operations`.+ */+const meta = {+ title: 'Pages/Services/Top Level Operations',+ component: ServiceTopLevelOperations,+ // The page reads the service out of the pathname, so it renders under its own+ // route rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route+ path={ROUTES.SERVICE_TOP_LEVEL_OPERATIONS}+ component={ServiceTopLevelOperations}+ />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ServiceTopLevelOperationsArgs>;++export default meta;++type Story = StoryObj<ServiceTopLevelOperationsArgs>;++/**+ * The entry-point spans SigNoz derived a service's RED metrics from, which is+ * what the warning on the services table links to.+ */+export const Default: Story = {};++/** Instrumentation with enough distinct entry points for the table to paginate. */+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 },+};diff --git a/frontend/src/pages/ServiceTopLevelOperations/stories/__story_mockdata__/serviceTopLevelOperations.ts b/frontend/src/pages/ServiceTopLevelOperations/stories/__story_mockdata__/serviceTopLevelOperations.tsnew file mode 100644index 0000000000..277537c514--- /dev/null+++ b/frontend/src/pages/ServiceTopLevelOperations/stories/__story_mockdata__/serviceTopLevelOperations.ts@@ -0,0 +1,51 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { ServicesList } from 'types/api/metrics/getService';++export const SERVICE_NAME = 'checkout';++/**+ * Span names an under-instrumented service reports: an id baked into the path is+ * what makes each request its own entry point, which is the case this page is+ * shown for.+ */+const operationName = (index: number): string =>+ `GET /api/orders/${(918_400 + index * 137).toString(16)}/status`;++/**+ * `dataWarning.topLevelOps` on the page's own service is the whole payload it+ * reads; every other service is there so the list is not the only row.+ */+export const servicesWithTopLevelOpsResponse = (+ operations: number,+): { status: string; data: ServicesList[] } => ({+ status: 'success',+ data: [+ {+ serviceName: SERVICE_NAME,+ p99: 184_000_000,+ avgDuration: 61_000_000,+ numCalls: 42_100,+ callRate: 23.4,+ numErrors: 190,+ errorRate: 0.45,+ dataWarning: {+ topLevelOps: Array.from({ length: operations }, (_unused, index) =>+ operationName(index),+ ),+ },+ },+ {+ serviceName: 'cart',+ p99: 96_000_000,+ avgDuration: 31_000_000,+ numCalls: 18_600,+ callRate: 10.3,+ numErrors: 0,+ errorRate: 0,+ },+ ],+});diff --git a/frontend/src/pages/Services/stories/Services.stories.mocks.tsx b/frontend/src/pages/Services/stories/Services.stories.mocks.tsxnew file mode 100644index 0000000000..9462be7f7e--- /dev/null+++ b/frontend/src/pages/Services/stories/Services.stories.mocks.tsx@@ -0,0 +1,137 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { FeatureKeys } from 'constants/features';+import { rest } from 'msw';+import { createAppContextMock } from 'tests/fixtures/appContextMock';+import type { FeatureFlagProps } from 'types/api/features/getFeaturesFlags';+import { USER_ROLES } from 'types/roles';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import {+ attributeKeysResponse,+ attributeValuesResponse,+} from '@/storybook/msw/__story_mockdata__/attributes';++import {+ DEPLOYMENT_ENVIRONMENTS,+ RESOURCE_ATTRIBUTE_KEYS,+ SERVICE_HEALTH_STATES,+ SERVICE_MAX,+ SERVICE_MODES,+ SERVICE_TRAFFIC_LEVELS,+ serviceMetricsResponse,+ servicesResponse,+ topLevelOperationsResponse,+ type ServiceHealth,+ type ServiceMode,+ type ServiceTraffic,+} from './__story_mockdata__/services';++const LIST = 'Services · list';+const HEALTH = 'Services · health';++const DEPLOYMENT_KEY = 'resource_deployment.environment';++const { featureFlags: baseFeatureFlags } = createAppContextMock(+ USER_ROLES.ADMIN,+);++const featureFlagsFor = (mode: ServiceMode): FeatureFlagProps[] =>+ (baseFeatureFlags ?? []).map((flag) =>+ flag.name === FeatureKeys.USE_SPAN_METRICS+ ? { ...flag, active: mode === 'span-metrics' }+ : flag,+ );++/**+ * The span-metrics table derives one point per series, so every request answers+ * on the same timestamp and a refetch redraws the same numbers.+ */+const POINT_AT = 1_735_689_600_000;++export const servicesMocks = defineStoryMocks({+ controls: {+ mode: choiceControl<ServiceMode>('Source', {+ group: LIST,+ description:+ 'Where the table reads from: the trace-derived service list, or the span metrics the `use_span_metrics` flag switches it to.',+ options: SERVICE_MODES,+ value: 'traces',+ }),+ services: countControl('Services', {+ group: LIST,+ description: 'Rows the table has, ten of which fit on a page.',+ value: 8,+ max: SERVICE_MAX,+ }),+ health: choiceControl<ServiceHealth>('Health', {+ group: HEALTH,+ description:+ 'How the error rate and p99 columns are spread across the rows.',+ options: SERVICE_HEALTH_STATES,+ value: 'mixed',+ }),+ traffic: choiceControl<ServiceTraffic>('Traffic', {+ group: HEALTH,+ description:+ '`over-trial-limit` sends more than 100 rps through the services, which is the warning above the table. It needs Banner on `trial-expiry` to show: the app only warns a workspace still on its cloud trial.',+ options: SERVICE_TRAFFIC_LEVELS,+ value: 'steady',+ }),+ },+ handlers: (values, response) => [+ rest.post(+ 'http://localhost/api/v2/services',+ response.json(() =>+ servicesResponse(values.services, values.health, values.traffic),+ ),+ ),+ rest.post(+ 'http://localhost/api/v1/service/top_level_operations',+ response.json(() => topLevelOperationsResponse(values.services)),+ ),+ rest.post(+ 'http://localhost/api/v4/query_range',+ response.json(async (req) =>+ serviceMetricsResponse(+ (await req.json()) as Record<string, unknown>,+ values.services,+ values.health,+ values.traffic,+ POINT_AT,+ ),+ ),+ ),+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_keys',+ response.json((req) => {+ const match = req.url.searchParams.get('searchText') ?? '';++ return attributeKeysResponse(+ match === DEPLOYMENT_KEY+ ? [DEPLOYMENT_KEY]+ : RESOURCE_ATTRIBUTE_KEYS.filter((key) => key !== DEPLOYMENT_KEY),+ );+ }),+ ),+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) => {+ const attributeKey = req.url.searchParams.get('attributeKey') ?? '';++ return attributeValuesResponse(+ attributeKey === DEPLOYMENT_KEY+ ? DEPLOYMENT_ENVIRONMENTS+ : [`${attributeKey.replace('resource_', '')}-01`],+ );+ }),+ ),+ ],+ config: (values) => ({+ appContext: { featureFlags: featureFlagsFor(values.mode) },+ }),+});diff --git a/frontend/src/pages/Services/stories/Services.stories.tsx b/frontend/src/pages/Services/stories/Services.stories.tsxnew file mode 100644index 0000000000..a148107183--- /dev/null+++ b/frontend/src/pages/Services/stories/Services.stories.tsx@@ -0,0 +1,63 @@+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 Services from '../index';+import { servicesMocks } from './Services.stories.mocks';++type ServicesArgs = PageStoryArgs<typeof servicesMocks>;++const pageStory = storyMocks(servicesMocks, {+ route: ROUTES.APPLICATION,+ layout: 'app',+});++/**+ * Every instrumented service with its p99, error rate and throughput, read from+ * either span metrics or the traces themselves.+ *+ * Route: `/services`.+ */+const meta = {+ title: 'Pages/Services/List',+ component: Services,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ServicesArgs>;++export default meta;++type Story = StoryObj<ServicesArgs>;++/**+ * Every instrumented service with its p99, error rate and operations per+ * second, over the resource attribute filter the page scopes them with.+ */+export const Default: Story = {};++/** The same list read from span metrics instead of traces, so p99 is in ns. */+export const SpanMetrics: Story = {+ args: { mode: 'span-metrics' },+};++/** A workspace with nothing instrumented yet: the table has no services. */+export const NoServices: Story = {+ args: { services: 0 },+};++/** All rows are failing, making the error-rate and latency columns visibly severe. */+export const UnhealthyServices: Story = {+ args: { health: 'degraded' },+};++/** Fourteen services exercise the table's second-page pagination controls. */+export const Pagination: Story = {+ args: { services: 14 },+};++/** Cloud trial pushed past 100 rps, which is what the warning above the table reads. */+export const OverTrialLimit: Story = {+ args: { traffic: 'over-trial-limit', banner: 'trial-expiry' },+};diff --git a/frontend/src/pages/Services/stories/__story_mockdata__/services.ts b/frontend/src/pages/Services/stories/__story_mockdata__/services.tsnew file mode 100644index 0000000000..06639fc04b--- /dev/null+++ b/frontend/src/pages/Services/stories/__story_mockdata__/services.ts@@ -0,0 +1,212 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { ServiceDataProps } from 'api/metrics/getTopLevelOperations';+import type { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';+import type { ServicesList } from 'types/api/metrics/getService';+import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';++import {+ queryRangeV3TimeSeriesResponse,+ v3Series,+} from '@/storybook/msw/__story_mockdata__/queryRange';++export const SERVICE_MODES = ['traces', 'span-metrics'] as const;++export type ServiceMode = (typeof SERVICE_MODES)[number];++export const SERVICE_HEALTH_STATES = ['healthy', 'mixed', 'degraded'] as const;++export type ServiceHealth = (typeof SERVICE_HEALTH_STATES)[number];++export const SERVICE_TRAFFIC_LEVELS = ['steady', 'over-trial-limit'] as const;++export type ServiceTraffic = (typeof SERVICE_TRAFFIC_LEVELS)[number];++const SERVICE_NAMES = [+ 'frontend',+ 'checkout',+ 'cart',+ 'payment',+ 'shipping',+ 'product-catalog',+ 'recommendation',+ 'currency',+ 'email',+ 'ad',+ 'quote',+ 'accounting',+ 'fraud-detection',+ 'notification',+] as const;++export const SERVICE_MAX = SERVICE_NAMES.length;++const OPERATIONS = [+ 'HTTP GET /',+ 'HTTP POST /api/checkout',+ 'grpc.Execute',+ 'oteldemo.CartService/GetCart',+];++export const DEPLOYMENT_ENVIRONMENTS = ['production', 'staging', 'canary'];++export const RESOURCE_ATTRIBUTE_KEYS = [+ 'resource_deployment.environment',+ 'resource_k8s.cluster.name',+ 'resource_k8s.namespace.name',+ 'resource_host.name',+ 'resource_cloud.region',+];++const namesFor = (count: number): string[] =>+ SERVICE_NAMES.slice(0, Math.min(count, SERVICE_MAX));++/** Latency in nanoseconds, which is what both the table columns divide down from. */+const p99Of = (index: number, health: ServiceHealth): number => {+ const base = 118_000_000 + index * 11_500_000;++ return health === 'degraded' ? base * 4 : base;+};++const errorRateOf = (index: number, health: ServiceHealth): number => {+ if (health === 'healthy') {+ return 0;+ }++ if (health === 'degraded') {+ return 12.5 + (index % 4) * 3.25;+ }++ return index % 3 === 0 ? 4.75 + (index % 2) * 1.5 : 0;+};++/**+ * `over-trial-limit` spreads more than `MAX_RPS_LIMIT` across however many+ * services are on, so the cloud trial warning above the table shows at any count.+ */+const callRateOf = (+ index: number,+ count: number,+ traffic: ServiceTraffic,+): number => {+ const jitter = (index % 5) * 0.7;++ return traffic === 'over-trial-limit'+ ? 110 / Math.max(count, 1) + jitter+ : 2.4 + jitter;+};++interface ServiceMetrics {+ p99: number;+ errorRate: number;+ callRate: number;+}++const metricsOf = (+ index: number,+ count: number,+ health: ServiceHealth,+ traffic: ServiceTraffic,+): ServiceMetrics => ({+ p99: p99Of(index, health),+ errorRate: errorRateOf(index, health),+ callRate: callRateOf(index, count, traffic),+});++export const servicesResponse = (+ count: number,+ health: ServiceHealth,+ traffic: ServiceTraffic,+): { status: string; data: ServicesList[] } => {+ const names = namesFor(count);++ return {+ status: 'success',+ data: names.map((serviceName, index) => {+ const { p99, errorRate, callRate } = metricsOf(+ index,+ names.length,+ health,+ traffic,+ );+ const numCalls = Math.round(callRate * 1800);++ return {+ serviceName,+ p99,+ avgDuration: p99 / 3,+ numCalls,+ callRate,+ numErrors: Math.round((numCalls * errorRate) / 100),+ errorRate,+ };+ }),+ };+};++/** The span-metrics branch lists services by the operations reported for each. */+export const topLevelOperationsResponse = (count: number): ServiceDataProps =>+ Object.fromEntries(+ namesFor(count).map((serviceName, index) => [+ serviceName,+ OPERATIONS.slice(0, 2 + (index % 3)),+ ]),+ );++const serviceOf = (+ body: Record<string, unknown>,+ names: string[],+): string | undefined => {+ const composite = body.compositeQuery as+ | { builderQueries?: Record<string, IBuilderQuery> }+ | undefined;+ const item = composite?.builderQueries?.A?.filters?.items?.find(+ (filter) => filter.key?.key === 'service.name',+ );+ const value = Array.isArray(item?.value) ? item?.value[0] : item?.value;++ return names.find((name) => name === value);+};++/**+ * One request per service, so the row a response fills is the one named in its+ * own `service.name` filter. `A` is p99, `D` the call rate and `F1` the error+ * rate formula, which is the only three values the table reads back.+ */+export const serviceMetricsResponse = (+ body: Record<string, unknown>,+ count: number,+ health: ServiceHealth,+ traffic: ServiceTraffic,+ timestamp: number,+): MetricRangePayloadProps => {+ const names = namesFor(count);+ const service = serviceOf(body, names);+ const index = service ? names.indexOf(service) : 0;+ const { p99, errorRate, callRate } = metricsOf(+ index,+ names.length,+ health,+ traffic,+ );++ const point = (value: number): { timestamp: number; value: string } => ({+ timestamp,+ value: String(Number(value.toFixed(4))),+ });++ return {+ data: {+ result: [],+ resultType: '',+ newResult: queryRangeV3TimeSeriesResponse([+ { queryName: 'A', series: [v3Series({}, [point(p99)])] },+ { queryName: 'D', series: [v3Series({}, [point(callRate)])] },+ { queryName: 'F1', series: [v3Series({}, [point(errorRate)])] },+ ]),+ },+ };+};diff --git a/frontend/src/pages/Settings/Account/stories/Account.stories.mocks.tsx b/frontend/src/pages/Settings/Account/stories/Account.stories.mocks.tsxnew file mode 100644index 0000000000..d725f02e2a--- /dev/null+++ b/frontend/src/pages/Settings/Account/stories/Account.stories.mocks.tsx@@ -0,0 +1,44 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ seedTimezone,+ TIMEZONES,+ type TimezoneChoice,+ updatedUserResponse,+} from './__story_mockdata__/account';++const PREFERENCES = 'Account · preferences';++export const accountMocks = defineStoryMocks({+ controls: {+ timezone: choiceControl<TimezoneChoice>('Timezone', {+ group: PREFERENCES,+ description:+ "Whether a timezone other than the browser's is stored. An override adds the amber marker and the button that clears it.",+ options: TIMEZONES,+ value: 'browser',+ }),+ },+ handlers: (_values, response) => [+ rest.patch(+ 'http://localhost/api/v2/users/me',+ response.json(() => updatedUserResponse()),+ ),++ rest.post(+ 'http://localhost/api/v2/users/me/factor_password',+ response.json(() => updatedUserResponse()),+ ),+ ],+ config: () => ({ route: ROUTES.MY_SETTINGS }),+ effect: ({ timezone }) => seedTimezone(timezone),+});diff --git a/frontend/src/pages/Settings/Account/stories/Account.stories.tsx b/frontend/src/pages/Settings/Account/stories/Account.stories.tsxnew file mode 100644index 0000000000..9ec71a3255--- /dev/null+++ b/frontend/src/pages/Settings/Account/stories/Account.stories.tsx@@ -0,0 +1,79 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { accountMocks } from './Account.stories.mocks';++import SettingsPage from '../../Settings';++type AccountArgs = PageStoryArgs<typeof accountMocks>;++const pageStory = storyMocks(accountMocks, { layout: 'app' });++/**+ * The signed in user's own settings: name, password and timezone.+ *+ * Route: `/settings/my-settings`.+ */+const meta = {+ title: 'Pages/Settings/Account',+ tags: ['play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<AccountArgs>;++export default meta;++type Story = StoryObj<AccountArgs>;++/** The page fetches before it renders a control, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The signed-in user's own settings: who they are signed in as, the theme and+ * console preferences that follow them, and the license key of the instance.+ */+export const Default: Story = {};++/**+ * A user reading timestamps in a zone other than their browser's, which the+ * console flags so a misread graph is traceable to the setting.+ */+export const TimezoneOverridden: Story = {+ args: { timezone: 'overridden' },+};++/** The name the rest of the console shows this user under. */+export const UpdateName: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /update name/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByPlaceholderText(+ /e\.g\. john doe/i,+ undefined,+ untilLoaded,+ );+ },+};++/** Changing the password from inside the console rather than the reset flow. */+export const ResetPassword: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /reset password/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(/current password/i, undefined, untilLoaded);+ },+};diff --git a/frontend/src/pages/Settings/Account/stories/__story_mockdata__/account.ts b/frontend/src/pages/Settings/Account/stories/__story_mockdata__/account.tsnew file mode 100644index 0000000000..6e7bac6f6b--- /dev/null+++ b/frontend/src/pages/Settings/Account/stories/__story_mockdata__/account.ts@@ -0,0 +1,30 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import setLocalStorageKey from 'api/browser/localstorage/set';+import { LOCALSTORAGE } from 'constants/localStorage';++export const TIMEZONES = ['browser', 'overridden'] as const;++export type TimezoneChoice = (typeof TIMEZONES)[number];++/** Far enough from any CI machine's zone that the override banner always shows. */+const OVERRIDE_TIMEZONE = 'Asia/Tokyo';++/**+ * `TimezoneProvider` seeds itself from localStorage on mount and never asks the+ * backend, so the override is module state rather than a response.+ */+export const seedTimezone = (choice: TimezoneChoice): void => {+ setLocalStorageKey(+ LOCALSTORAGE.PREFERRED_TIMEZONE,+ choice === 'overridden' ? OVERRIDE_TIMEZONE : '',+ );+};++export const updatedUserResponse = (): Record<string, unknown> => ({+ status: 'success',+ data: { id: 'some-user-id' },+});diff --git a/frontend/src/pages/Settings/Billing/stories/Billing.stories.mocks.tsx b/frontend/src/pages/Settings/Billing/stories/Billing.stories.mocks.tsxnew file mode 100644index 0000000000..deb4522a6e--- /dev/null+++ b/frontend/src/pages/Settings/Billing/stories/Billing.stories.mocks.tsx@@ -0,0 +1,81 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ BILLED_DAYS_MAX,+ checkoutResponse,+ PLAN_STATES,+ type PlanState,+ PRICING_MODES,+ type PricingMode,+ SUBSCRIPTION_STATUSES,+ type SubscriptionStatus,+ trialInfoFor,+ usageResponse,+} from './__story_mockdata__/billing';++const USAGE = 'Billing · usage';+const PLAN = 'Billing · plan';++export const billingMocks = defineStoryMocks({+ controls: {+ plan: choiceControl<PlanState>('Plan', {+ group: PLAN,+ description:+ 'Where the workspace is in its subscription. This tab owns `trialInfo`, so the App shell Banner control does not reach it here. `grace-period` is an expired evaluation the console still lets in; `workspace-blocked` is the same one on cloud, where everything but billing is shut.',+ options: PLAN_STATES,+ value: 'subscribed',+ }),+ billedDays: countControl('Days billed so far', {+ group: USAGE,+ description:+ 'How far into the period the workspace is. One bar per day, and the bill is what those days add up to.',+ value: 12,+ max: BILLED_DAYS_MAX,+ }),+ pricing: choiceControl<PricingMode>('Pricing', {+ group: USAGE,+ description:+ 'How each signal is priced. `volume-tiers` bills the month down a schedule, and every tier past the first takes its own row under a blank signal name.',+ options: PRICING_MODES,+ value: 'flat',+ }),+ subscription: choiceControl<SubscriptionStatus>('Subscription', {+ group: USAGE,+ description:+ 'A past-due subscription puts the payment-failure callout above the graph.',+ options: SUBSCRIPTION_STATUSES,+ value: 'active',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/subscriptions',+ response.json(() =>+ usageResponse(values.billedDays, values.subscription, values.pricing),+ ),+ ),++ rest.post(+ 'http://localhost/api/v1/subscriptions',+ response.json(() => checkoutResponse()),+ ),++ rest.put(+ 'http://localhost/api/v1/subscriptions',+ response.json(() => checkoutResponse()),+ ),+ ],+ config: ({ plan }) => ({+ route: ROUTES.BILLING,+ appContext: { trialInfo: trialInfoFor(plan) },+ }),+});diff --git a/frontend/src/pages/Settings/Billing/stories/Billing.stories.tsx b/frontend/src/pages/Settings/Billing/stories/Billing.stories.tsxnew file mode 100644index 0000000000..0b9a8ddb42--- /dev/null+++ b/frontend/src/pages/Settings/Billing/stories/Billing.stories.tsx@@ -0,0 +1,173 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { expect, screen, userEvent, waitFor } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { billingMocks } from './Billing.stories.mocks';++import SettingsPage from '../../Settings';++type BillingArgs = PageStoryArgs<typeof billingMocks>;++const pageStory = storyMocks(billingMocks, { layout: 'app' });++/**+ * The plan and what the workspace used in the billing period, with the checkout+ * and portal links. Every action on it is gated on a `subscription` permission,+ * one story per permission under `Billing/Authz`.+ *+ * Route: `/settings/billing`.+ */+const meta = {+ title: 'Pages/Settings/Billing/Overview',+ tags: ['authz', 'play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<BillingArgs>;++export default meta;++type Story = StoryObj<BillingArgs>;++/** The page fetches the period before it renders a bar, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/** The last day the period covers, which is where it reports nothing remaining. */+const PERIOD_LENGTH = 31;++/**+ * What the workspace has sent this billing period, day by day and signal by+ * signal, and what it adds up to.+ */+export const Default: Story = {};++/**+ * The usage graph's legend, where each signal the workspace is billed for+ * carries its own name as a tooltip.+ *+ * Kept right after `Default`: test-runner shares one page across a file's+ * stories, and a story after this one would otherwise inherit whatever+ * `dataState` a state-mutating story (`Loading`, `Error`) last left behind.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+};++/** The first day of a period, before there is a shape to the graph. */+export const PeriodJustStarted: Story = {+ args: { billedDays: 1 },+};++/** The last day of the period, with nothing left to run and the month's full bill. */+export const PeriodEnding: Story = {+ args: { billedDays: PERIOD_LENGTH },+};++/** Empty: a period nothing has been sent in yet, which bills nothing. */+export const NoUsage: Story = {+ args: { billedDays: 0 },+};++/**+ * A workspace far enough into the month to have crossed a price step, where each+ * signal is billed in tiers and the cheaper ones sit under it unnamed.+ */+export const VolumeTiers: Story = {+ args: { pricing: 'volume-tiers' },+};++/**+ * A workspace whose last payment did not go through, which is announced above+ * the graph and again over the plan.+ */+export const PaymentPastDue: Story = {+ args: { subscription: 'past_due' },+};++/** A workspace still inside its trial, which is billed nothing until it ends. */+export const OnTrial: Story = {+ args: { plan: 'on-trial' },+};++/**+ * A trial with a card already on file: the console says the billing starts when+ * the trial ends, and the plan is managed rather than upgraded.+ */+export const TrialCardAdded: Story = {+ args: { plan: 'trial-card-added' },+};++/**+ * A trial that has run out without a card on file, where the console says how+ * long the data is kept before it goes.+ */+export const GracePeriod: Story = {+ args: { plan: 'grace-period' },+};++/**+ * The same expired trial on cloud, where the workspace is shut: billing is the+ * only tab left open and the side nav is down to what an unpaid workspace keeps.+ */+export const WorkspaceBlocked: Story = {+ args: { plan: 'workspace-blocked' },+};++/**+ * A self-hosted instance, billed as Teams rather than Teams Cloud, where the+ * subscription is not the console's to cancel.+ */+export const SelfHosted: Story = {+ args: { license: 'enterprise' },+};++/**+ * Interaction: cancelling is deliberate. The dialog only arms its own button+ * once the word is typed out, and the cancellation itself goes to support.+ */+export const CancelSubscription: Story = {+ play: async (): Promise<void> => {+ await screen.findByTestId('cancel-subscription-btn', undefined, untilLoaded);++ // The button is cloned disabled while its own permission check is in+ // flight, and the click that lands there is dropped rather than queued.+ await waitFor(() =>+ expect(screen.getByTestId('cancel-subscription-btn')).toBeEnabled(),+ );++ await userEvent.click(screen.getByTestId('cancel-subscription-btn'));++ // The dialog's `data-testid` never reaches the input: the design system's+ // `Input` forwards a fixed prop list, and `data-*` is not on it.+ await userEvent.type(+ await screen.findByPlaceholderText(+ /enter the word cancel/i,+ undefined,+ untilLoaded,+ ),+ 'cancel',+ );++ await waitFor(() =>+ expect(screen.getByTestId('cancel-subscription-confirm-btn')).toBeEnabled(),+ );+ },+};++/**+ * The period being fetched: the plan, the graph and the table all stand in.+ *+ * Kept last with `Error`: test-runner shares one page across a file's+ * stories, and a story after either of these would otherwise inherit the+ * `dataState` it sets instead of its own.+ */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** Error: the usage request failed, leaving the plan card with nothing to report. */+export const Error: Story = {+ args: { dataState: 'error' },+};diff --git a/frontend/src/pages/Settings/Billing/stories/__story_mockdata__/billing.ts b/frontend/src/pages/Settings/Billing/stories/__story_mockdata__/billing.tsnew file mode 100644index 0000000000..95b534cc01--- /dev/null+++ b/frontend/src/pages/Settings/Billing/stories/__story_mockdata__/billing.ts@@ -0,0 +1,281 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ CreateSubscription201,+ GetSubscription200,+ SubscriptiontypesSubscriptionUsageBreakdownDTO,+ SubscriptiontypesSubscriptionUsageDayWiseDataDTO,+ SubscriptiontypesSubscriptionUsageTierDTO,+} from 'api/generated/services/sigNoz.schemas';+import type { TrialInfo } from 'types/api/licensesV3/getActive';++export const SUBSCRIPTION_STATUSES = ['active', 'past_due'] as const;++export type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];++export const PRICING_MODES = ['flat', 'volume-tiers'] as const;++export type PricingMode = (typeof PRICING_MODES)[number];++export const BILLED_DAYS_MAX = 31;++const DAY_IN_SECONDS = 24 * 60 * 60;++/**+ * The graph plots one bar per day of the period, so the period has to end in the+ * future for the header to report days remaining rather than zero.+ */+const nowInSeconds = (): number => Math.floor(Date.now() / 1000);++interface VolumeStep {+ /** Cumulative quantity this price covers up to; the last step is unbounded. */+ upTo: number;+ unitPrice: number;+}++interface SignalSeed {+ type: string;+ unit: string;+ /** Per-day quantity, which the tiers and the bars are both derived from. */+ perDay: number;+ unitPrice: number;+ volume: VolumeStep[];+}++const SIGNALS: SignalSeed[] = [+ {+ type: 'Logs',+ unit: 'GB',+ perDay: 42,+ unitPrice: 0.3,+ volume: [+ { upTo: 200, unitPrice: 0.3 },+ { upTo: 500, unitPrice: 0.25 },+ { upTo: Infinity, unitPrice: 0.2 },+ ],+ },+ {+ type: 'Traces',+ unit: 'GB',+ perDay: 18,+ unitPrice: 0.3,+ volume: [+ { upTo: 100, unitPrice: 0.3 },+ { upTo: 300, unitPrice: 0.25 },+ { upTo: Infinity, unitPrice: 0.2 },+ ],+ },+ {+ type: 'Metrics',+ unit: 'mn samples',+ perDay: 96,+ unitPrice: 0.1,+ volume: [+ { upTo: 500, unitPrice: 0.1 },+ { upTo: 1500, unitPrice: 0.08 },+ { upTo: Infinity, unitPrice: 0.06 },+ ],+ },+];++const round = (value: number): number => Number(value.toFixed(2));++const dayWiseBreakdown = (+ seed: SignalSeed,+ days: number,+ periodStart: number,+): SubscriptiontypesSubscriptionUsageDayWiseDataDTO[] =>+ Array.from({ length: days }, (_, index) => {+ // A fixed wobble per day, so the bars are not a flat block and the same+ // story renders the same graph every time.+ const quantity = seed.perDay * (1 + ((index % 5) - 2) / 10);++ return {+ // Unix seconds: the graph adds a bare 86400 to space a single-day series.+ timestamp: periodStart + index * DAY_IN_SECONDS,+ total: round(quantity * seed.unitPrice),+ quantity: round(quantity),+ count: Math.round(quantity),+ size: Math.round(quantity),+ };+ });++const tier = (+ quantity: number,+ unitPrice: number,+): SubscriptiontypesSubscriptionUsageTierDTO => ({+ quantity: round(quantity),+ unitPrice,+ tierCost: round(quantity * unitPrice),+});++/**+ * The month's quantity walked down the signal's volume schedule, one tier per+ * price it crossed. The table gives every tier past the first its own row under+ * a blank signal name, so a workspace only shows them once it is over a step.+ */+const volumeTiers = (+ seed: SignalSeed,+ quantity: number,+): SubscriptiontypesSubscriptionUsageTierDTO[] => {+ const tiers: SubscriptiontypesSubscriptionUsageTierDTO[] = [];+ let remaining = quantity;+ let covered = 0;++ for (const step of seed.volume) {+ if (remaining <= 0) {+ break;+ }++ const span = Math.min(remaining, step.upTo - covered);++ tiers.push(tier(span, step.unitPrice));+ remaining -= span;+ covered = step.upTo;+ }++ return tiers;+};++const breakdownFor = (+ seed: SignalSeed,+ days: number,+ periodStart: number,+ pricing: PricingMode,+): SubscriptiontypesSubscriptionUsageBreakdownDTO => {+ const quantity = round(seed.perDay * days);++ return {+ type: seed.type,+ unit: seed.unit,+ dayWiseBreakdown: { breakdown: dayWiseBreakdown(seed, days, periodStart) },+ tiers:+ pricing === 'volume-tiers'+ ? volumeTiers(seed, quantity)+ : [tier(quantity, seed.unitPrice)],+ };+};++const billTotalFor = (+ breakdown: SubscriptiontypesSubscriptionUsageBreakdownDTO[],+): number =>+ round(+ breakdown.reduce(+ (total, entry) =>+ total ++ (entry.tiers ?? []).reduce(+ (signalTotal, entryTier) => signalTotal + (entryTier.tierCost ?? 0),+ 0,+ ),+ 0,+ ),+ );++export const usageResponse = (+ days: number,+ subscriptionStatus: SubscriptionStatus,+ pricing: PricingMode,+): GetSubscription200 => {+ const periodStart = nowInSeconds() - days * DAY_IN_SECONDS;+ const periodEnd = periodStart + BILLED_DAYS_MAX * DAY_IN_SECONDS;++ const breakdown = SIGNALS.map((seed) =>+ breakdownFor(seed, days, periodStart, pricing),+ );++ return {+ status: 'success',+ data: {+ billingPeriodStart: periodStart,+ billingPeriodEnd: periodEnd,+ details: { baseFee: 0, breakdown, billTotal: billTotalFor(breakdown) },+ discount: 0,+ subscriptionStatus,+ },+ };+};++export const checkoutResponse = (): CreateSubscription201 => ({+ status: 'success',+ data: { redirectURL: 'https://billing.signoz.local/checkout/storybook' },+});++export const PLAN_STATES = [+ 'subscribed',+ 'on-trial',+ 'trial-card-added',+ 'grace-period',+ 'workspace-blocked',+] as const;++export type PlanState = (typeof PLAN_STATES)[number];++/**+ * `-1` is the backend's "not set" for every field here. `gracePeriodEnd` is read+ * for truthiness rather than compared, so leaving the sentinel in place puts the+ * grace-period callout up with a 1970 date: see the story's PR.+ */+const NOT_SET = -1;++export const trialInfoFor = (plan: PlanState): TrialInfo => {+ const now = nowInSeconds();++ switch (plan) {+ case 'on-trial':+ return {+ trialStart: now - 21 * DAY_IN_SECONDS,+ trialEnd: now + 9 * DAY_IN_SECONDS,+ onTrial: true,+ workSpaceBlock: false,+ trialConvertedToSubscription: false,+ gracePeriodEnd: NOT_SET,+ };++ // `AppProvider` reads a card added mid-trial as both: the license has left+ // the evaluating states while `freeUntil` is still ahead.+ case 'trial-card-added':+ return {+ trialStart: now - 21 * DAY_IN_SECONDS,+ trialEnd: now + 9 * DAY_IN_SECONDS,+ onTrial: true,+ workSpaceBlock: false,+ trialConvertedToSubscription: true,+ gracePeriodEnd: NOT_SET,+ };++ case 'grace-period':+ return {+ trialStart: now - 45 * DAY_IN_SECONDS,+ trialEnd: now - 15 * DAY_IN_SECONDS,+ onTrial: false,+ workSpaceBlock: false,+ trialConvertedToSubscription: false,+ gracePeriodEnd: now + 7 * DAY_IN_SECONDS,+ };++ // The same expired evaluation on cloud, where `AppProvider` also blocks the+ // workspace: the console keeps billing reachable and shuts the rest.+ case 'workspace-blocked':+ return {+ trialStart: now - 45 * DAY_IN_SECONDS,+ trialEnd: now - 15 * DAY_IN_SECONDS,+ onTrial: false,+ workSpaceBlock: true,+ trialConvertedToSubscription: false,+ gracePeriodEnd: now + 7 * DAY_IN_SECONDS,+ };++ default:+ return {+ trialStart: now - 120 * DAY_IN_SECONDS,+ trialEnd: now - 90 * DAY_IN_SECONDS,+ onTrial: false,+ workSpaceBlock: false,+ trialConvertedToSubscription: true,+ gracePeriodEnd: NOT_SET,+ };+ }+};diff --git a/frontend/src/pages/Settings/Billing/stories/authz/Billing.authz.stories.tsx b/frontend/src/pages/Settings/Billing/stories/authz/Billing.authz.stories.tsxnew file mode 100644index 0000000000..7228aed5c5--- /dev/null+++ b/frontend/src/pages/Settings/Billing/stories/authz/Billing.authz.stories.tsx@@ -0,0 +1,116 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { billingMocks } from '../Billing.stories.mocks';++import SettingsPage from '../../../Settings';++type BillingArgs = PageStoryArgs<typeof billingMocks>;++const pageStory = storyMocks(billingMocks, { layout: 'app' });++/**+ * The billing tab with one permission missing at a time. Every story here is an+ * admin who is denied exactly what its name says, so what goes with a permission+ * is what the story shows.+ *+ * Route: `/settings/billing`.+ */+const meta = {+ title: 'Pages/Settings/Billing/Authz',+ tags: ['authz'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<BillingArgs>;++export default meta;++type Story = StoryObj<BillingArgs>;++const READ = 'read:subscription';+const CREATE = 'create:subscription';+const LIST = 'list:subscription';+const UPDATE = 'update:subscription';+const DELETE = 'delete:subscription';++/** `RefreshPaymentStatus` asks to update the license it refreshes, not the subscription. */+const REFRESH = 'update:license';++const SUBSCRIPTION = [READ, CREATE, LIST, UPDATE, DELETE];++/**+ * Without it the usage graph, the CSV and the breakdown are replaced by the+ * permission callout, and the request behind them is never made. Paying is a+ * different permission, so the plan card above still works.+ */+export const NoRead: Story = {+ args: { revoked: [READ] },+};++/**+ * Managing the plan takes `list` and `update` together, so losing `list` alone+ * is enough to lock the Manage Billing button.+ */+export const NoList: Story = {+ args: { revoked: [LIST] },+};++/** The other half of the same pair, which locks the same button. */+export const NoUpdate: Story = {+ args: { revoked: [UPDATE] },+};++/** Neither half: the portal is out of reach however the workspace asks for it. */+export const NoManage: Story = {+ args: { revoked: [LIST, UPDATE] },+};++/**+ * A past-due workspace that cannot reach the portal: the callout still tells it+ * to update its card, and the link that would is dead.+ */+export const PastDueWithoutManage: Story = {+ args: { subscription: 'past_due', revoked: [LIST, UPDATE] },+};++/**+ * Checkout is a create, so a trial that cannot create one is left with both+ * upgrade buttons locked and no way off the trial.+ */+export const NoCreate: Story = {+ args: { plan: 'on-trial', revoked: [CREATE] },+};++/** The cancellation banner stays up, with the button that opens it locked. */+export const NoDelete: Story = {+ args: { revoked: [DELETE] },+};++/** The workspace can pay but cannot make the console go and look. */+export const NoLicenseRefresh: Story = {+ args: { revoked: [REFRESH] },+};++/** Everything but reading: the bill is in view and nothing on it can be acted on. */+export const ReadOnly: Story = {+ args: { revoked: [CREATE, LIST, UPDATE, DELETE] },+};++/** No subscription permission at all, which is the page with nothing on it to use. */+export const NoSubscriptionAccess: Story = {+ args: { revoked: SUBSCRIPTION },+};++/**+ * The permission check failing rather than denying, which the page treats as a+ * reason to ask for the usage anyway and leaves every action open.+ */+export const CheckFailed: Story = {+ args: { authzState: 'error' },+ // The mocked check intentionally fails; the resulting console error is the+ // point of the story, not a regression.+ parameters: { allowConsoleErrors: true },+};diff --git a/frontend/src/pages/Settings/Ingestion/stories/Ingestion.stories.mocks.tsx b/frontend/src/pages/Settings/Ingestion/stories/Ingestion.stories.mocks.tsxnew file mode 100644index 0000000000..0fdba56ce8--- /dev/null+++ b/frontend/src/pages/Settings/Ingestion/stories/Ingestion.stories.mocks.tsx@@ -0,0 +1,132 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { FeatureKeys } from 'constants/features';+import ROUTES from 'constants/routes';+import { rest } from 'msw';+import { defaultFeatureFlags } from 'tests/fixtures/appContextMock';++import {+ choiceControl,+ countControl,+ multiChoiceControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ EXPIRIES,+ type Expiry,+ ingestionKeysResponse,+ KEYS_PER_PAGE,+ legacyIngestionResponse,+ LIMIT_SIGNALS,+ type LimitSignal,+} from './__story_mockdata__/ingestion';++const KEYS = 'Ingestion · keys';+const LIMITS = 'Ingestion · limits';++export const ingestionMocks = defineStoryMocks({+ controls: {+ gateway: toggleControl('Gateway', {+ group: KEYS,+ description:+ 'The feature that puts key management in the console. Without it the tab is the read-only card of the single key the workspace was given.',+ value: true,+ }),+ keys: countControl('Ingestion keys', {+ group: KEYS,+ description: 'The page asks for ten at a time, which is the whole page.',+ value: 4,+ max: KEYS_PER_PAGE,+ }),+ expiry: choiceControl<Expiry>('Expiry', {+ group: KEYS,+ description:+ 'When the keys run out. `soon` is inside the window the row warns about; `expired` is past it.',+ options: EXPIRIES,+ value: 'none',+ }),+ limits: multiChoiceControl<LimitSignal>('Signals with a limit', {+ group: LIMITS,+ description:+ 'A signal without a limit shows the button that adds one instead of its usage against a cap.',+ options: LIMIT_SIGNALS,+ value: ['logs', 'traces'],+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/gateway/ingestion_keys/search',+ response.json((req) =>+ ingestionKeysResponse(+ values.keys,+ values.limits,+ values.expiry,+ Number(req.url.searchParams.get('page') ?? 1),+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/gateway/ingestion_keys',+ response.json((req) =>+ ingestionKeysResponse(+ values.keys,+ values.limits,+ values.expiry,+ Number(req.url.searchParams.get('page') ?? 1),+ ),+ ),+ ),++ rest.post(+ 'http://localhost/api/v2/gateway/ingestion_keys',+ response.json(() => ({+ status: 'success',+ data: { id: 'ingestion-key-new', value: 'sk_new' },+ })),+ ),++ rest.patch(+ 'http://localhost/api/v2/gateway/ingestion_keys/:keyId',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.delete(+ 'http://localhost/api/v2/gateway/ingestion_keys/:keyId',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.post(+ 'http://localhost/api/v2/gateway/ingestion_keys/:keyId/limits',+ response.json(() => ({ status: 'success', data: { id: 'limit-new' } })),+ ),++ rest.patch(+ 'http://localhost/api/v2/gateway/ingestion_keys/limits/:limitId',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.delete(+ 'http://localhost/api/v2/gateway/ingestion_keys/limits/:limitId',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.get(+ 'http://localhost/api/v1/settings/ingestion_key',+ response.json(() => legacyIngestionResponse()),+ ),+ ],+ config: ({ gateway }) => ({+ route: ROUTES.INGESTION_SETTINGS,+ appContext: {+ featureFlags: defaultFeatureFlags.map((flag) =>+ flag.name === FeatureKeys.GATEWAY ? { ...flag, active: gateway } : flag,+ ),+ },+ }),+});diff --git a/frontend/src/pages/Settings/Ingestion/stories/Ingestion.stories.tsx b/frontend/src/pages/Settings/Ingestion/stories/Ingestion.stories.tsxnew file mode 100644index 0000000000..25b83e01b2--- /dev/null+++ b/frontend/src/pages/Settings/Ingestion/stories/Ingestion.stories.tsx@@ -0,0 +1,91 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { ingestionMocks } from './Ingestion.stories.mocks';++import SettingsPage from '../../Settings';++type IngestionArgs = PageStoryArgs<typeof ingestionMocks>;++const pageStory = storyMocks(ingestionMocks, { layout: 'app' });++/**+ * Ingestion keys, their expiry and their per signal limits, against the gateway+ * that owns them.+ *+ * Route: `/settings/ingestion-settings`.+ */+const meta = {+ title: 'Pages/Settings/Ingestion',+ tags: ['play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<IngestionArgs>;++export default meta;++type Story = StoryObj<IngestionArgs>;++/** The list fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The keys collectors send data with, and how much each one is allowed to send+ * per signal before the gateway starts rejecting.+ */+export const Default: Story = {};++/** A workspace that has not been given a key yet. */+export const NoKeys: Story = {+ args: { keys: 0 },+};++/** Keys the org has to rotate before their collectors stop being accepted. */+export const ExpiringKeys: Story = {+ args: { expiry: 'soon' },+};++/** Keys with no cap on any signal, which is what a fresh workspace looks like. */+export const NoLimits: Story = {+ args: { limits: [] },+};++/**+ * The same tab on a workspace without the gateway: the ingestion URL, key and+ * region it was handed, and nothing to manage.+ */+export const WithoutGateway: Story = {+ args: { gateway: false },+};++/** A key opened up: the caps per signal, and the usage against each. */+export const KeyLimits: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /production-us-east/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByRole('button', { name: 'Edit logs limit' }, untilLoaded);+ },+};++/** The form a new key is named and dated in. */+export const CreateKey: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ 'New Ingestion key',+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText('Create new ingestion key', undefined, untilLoaded);+ },+};diff --git a/frontend/src/pages/Settings/Ingestion/stories/__story_mockdata__/ingestion.ts b/frontend/src/pages/Settings/Ingestion/stories/__story_mockdata__/ingestion.tsnew file mode 100644index 0000000000..7d05d8dc4e--- /dev/null+++ b/frontend/src/pages/Settings/Ingestion/stories/__story_mockdata__/ingestion.ts@@ -0,0 +1,137 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ GatewaytypesIngestionKeyDTO,+ GatewaytypesLimitDTO,+ GetIngestionKeys200,+} from 'api/generated/services/sigNoz.schemas';+import type { IngestionInfo } from 'types/api/settings/ingestion';++/** `per_page` the page asks for, so a longer page is a body the gateway never sends. */+export const KEYS_PER_PAGE = 10;++export const LIMIT_SIGNALS = ['logs', 'traces', 'metrics'] as const;++export type LimitSignal = (typeof LIMIT_SIGNALS)[number];++export const EXPIRIES = ['none', 'soon', 'expired'] as const;++export type Expiry = (typeof EXPIRIES)[number];++const KEY_NAMES = [+ 'production-us-east',+ 'production-eu-west',+ 'staging',+ 'load-test',+ 'edge-collectors',+ 'k8s-daemonset',+ 'lambda-forwarder',+ 'batch-jobs',+ 'partner-sandbox',+ 'legacy-agents',+];++const DAY = 24 * 60 * 60 * 1000;+const GIB = 1024 * 1024 * 1024;++/** Fixed epoch so the created and updated columns do not move between renders. */+const CREATED_AT = Date.UTC(2026, 0, 21, 10, 0);++/** The gateway's zero date, which the column reads as "No Expiry". */+const NEVER = '0001-01-01T00:00:00.000Z';++const expiresAt = (expiry: Expiry, index: number): string => {+ switch (expiry) {+ case 'soon':+ return new Date(Date.now() + (index + 2) * DAY).toISOString();++ case 'expired':+ return new Date(CREATED_AT - DAY).toISOString();++ default:+ return NEVER;+ }+};++/** Logs and traces are limited on bytes, metrics on datapoints. */+const limit = (+ signal: LimitSignal,+ keyId: string,+ index: number,+): GatewaytypesLimitDTO => ({+ id: `limit-${keyId}-${signal}`,+ key_id: keyId,+ signal,+ config:+ signal === 'metrics'+ ? { day: { count: 500_000_000 }, second: { count: 20_000 } }+ : { day: { size: (index + 1) * 200 * GIB }, second: { size: 8 * GIB } },+ metric:+ signal === 'metrics'+ ? { day: { count: 187_400_000 }, second: { count: 6_400 } }+ : { day: { size: (index + 1) * 96 * GIB }, second: { size: 2 * GIB } },+ created_at: new Date(CREATED_AT).toISOString(),+ updated_at: new Date(CREATED_AT).toISOString(),+});++const ingestionKey = (+ index: number,+ signals: readonly LimitSignal[],+ expiry: Expiry,+): GatewaytypesIngestionKeyDTO => {+ const id = `ingestion-key-${index}`;++ return {+ id,+ name: KEY_NAMES[index % KEY_NAMES.length],+ value: `sk_${index}${'x'.repeat(28)}${index}9`,+ workspace_id: 'story-workspace',+ tags: index === 0 ? ['production', 'us-east-1'] : [],+ limits: signals.map((signal) => limit(signal, id, index)),+ created_at: new Date(CREATED_AT - index * DAY).toISOString(),+ updated_at: new Date(CREATED_AT - index * DAY + 3600_000).toISOString(),+ expires_at: expiresAt(expiry, index),+ };+};++export const ingestionKeysResponse = (+ keys: number,+ signals: readonly LimitSignal[],+ expiry: Expiry,+ page: number,+): GetIngestionKeys200 => ({+ status: 'success',+ data: {+ keys: Array.from({ length: keys }, (_, index) =>+ ingestionKey(index, signals, expiry),+ ),+ _pagination: {+ page,+ per_page: KEYS_PER_PAGE,+ total: keys,+ pages: Math.max(1, Math.ceil(keys / KEYS_PER_PAGE)),+ },+ },+});++/**+ * The pre-gateway endpoint, which answers with one record and no limits: the tab+ * falls back to it when the gateway feature is off.+ *+ * The body is the bare array. `IngestionResponseProps` says the records sit+ * under a `payload` key, but `getIngestionData` already puts the whole body+ * there and the tab indexes into it, so a wrapped body renders three blank rows.+ */+export const legacyIngestionResponse = (): IngestionInfo[] => [+ {+ keyId: 'ingestion-key-0',+ name: KEY_NAMES[0],+ createdAt: new Date(CREATED_AT).toISOString(),+ ingestionKey: 'sk_0xxxxxxxxxxxxxxxxxxxxxxxxxxx09',+ ingestionURL: 'https://ingest.us.signoz.cloud:443',+ dataRegion: 'us-east-1',+ },+];diff --git a/frontend/src/pages/Settings/McpServer/stories/McpServer.stories.mocks.tsx b/frontend/src/pages/Settings/McpServer/stories/McpServer.stories.mocks.tsxnew file mode 100644index 0000000000..1bd4fe5850--- /dev/null+++ b/frontend/src/pages/Settings/McpServer/stories/McpServer.stories.mocks.tsx@@ -0,0 +1,61 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { toggleControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++const SERVER = 'MCP server · server';++const INSTANCE_URL = 'https://nightswatch.us.signoz.cloud';++/**+ * The tab is a set of client snippets built from the config, so nothing on it+ * renders until the config has answered: both endpoints take a plain resolver.+ */+export const mcpServerMocks = defineStoryMocks({+ controls: {+ mcpEnabled: toggleControl('MCP endpoint', {+ group: SERVER,+ description:+ 'Whether the deployment publishes an MCP URL. Without one the tab is the docs pointer instead of the setup steps.',+ value: true,+ }),+ },+ handlers: ({ mcpEnabled }) => [+ rest.get('http://localhost/api/v1/global/config', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: {+ ai_assistant_url: null,+ external_url: INSTANCE_URL,+ ingestion_url: 'https://ingest.us.signoz.cloud:443',+ mcp_url: mcpEnabled ? `${INSTANCE_URL}/mcp` : null,+ },+ }),+ ),+ ),++ rest.get('http://localhost/api/v2/zeus/hosts', (_req, res, ctx) =>+ res(+ ctx.status(200),+ ctx.json({+ status: 'success',+ data: {+ name: 'nightswatch',+ state: 'HEALTHY',+ tier: 'production',+ hosts: [{ name: 'nightswatch', url: INSTANCE_URL, is_default: true }],+ },+ }),+ ),+ ),+ ],+ config: () => ({ route: ROUTES.MCP_SERVER }),+});diff --git a/frontend/src/pages/Settings/McpServer/stories/McpServer.stories.tsx b/frontend/src/pages/Settings/McpServer/stories/McpServer.stories.tsxnew file mode 100644index 0000000000..62d7076984--- /dev/null+++ b/frontend/src/pages/Settings/McpServer/stories/McpServer.stories.tsx@@ -0,0 +1,79 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { mcpServerMocks } from './McpServer.stories.mocks';++import SettingsPage from '../../Settings';++type McpServerArgs = PageStoryArgs<typeof mcpServerMocks>;++const pageStory = storyMocks(mcpServerMocks, { layout: 'app' });++/**+ * The workspace's MCP server: the connection details, and the toggle that enables+ * it.+ *+ * Route: `/settings/mcp-server`.+ */+const meta = {+ title: 'Pages/Settings/MCP Server',+ tags: ['role-gated', 'play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<McpServerArgs>;++export default meta;++type Story = StoryObj<McpServerArgs>;++/** The config fetches before the snippets render, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * How an AI client is pointed at this workspace: the snippet to paste, the+ * instance URL it authorises against, and where the key comes from.+ */+export const Default: Story = {};++/** The same tab where MCP is not served, which sends the reader to the docs. */+export const NoMcpEndpoint: Story = {+ args: { mcpEnabled: false },+};++/** The snippet for a different client, which is the whole of what the tab swaps. */+export const ClaudeCode: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /claude code/i,+ undefined,+ untilLoaded,+ ),+ );+ await within(canvasElement).findByText(+ /^claude mcp add/,+ undefined,+ untilLoaded,+ );+ },+};++/**+ * A member who is not an admin, who can read the setup but cannot issue the+ * service account the client authenticates with.+ */+export const NonAdmin: Story = {+ args: { access: 'editor' },+};++/**+ * The copy buttons the tab carries, held open: the one on the client config+ * snippet and the one beside the instance URL, both saying what they copy.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+};diff --git a/frontend/src/pages/Settings/Members/stories/Members.stories.mocks.tsx b/frontend/src/pages/Settings/Members/stories/Members.stories.mocks.tsxnew file mode 100644index 0000000000..d0e8306e68--- /dev/null+++ b/frontend/src/pages/Settings/Members/stories/Members.stories.mocks.tsx@@ -0,0 +1,123 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ ACTIVE_MEMBER_MAX,+ createdUserResponse,+ DELETED_MEMBER_MAX,+ INVITED_MEMBER_MAX,+ RESET_TOKEN_STATES,+ type ResetTokenState,+ resetPasswordTokenResponse,+ userDetailResponse,+ usersResponse,+} from './__story_mockdata__/members';++import {+ CUSTOM_ROLE_MAX,+ rolesListResponse,+} from '../../stories/__story_mockdata__/roles';++const LIST = 'Members · list';+const INVITES = 'Members · invites';++export const membersMocks = defineStoryMocks({+ controls: {+ active: countControl('Active members', {+ group: LIST,+ description: 'The table pages at twenty, so a longer list shows the pager.',+ value: 8,+ max: ACTIVE_MEMBER_MAX,+ }),+ invited: countControl('Pending invites', {+ group: LIST,+ value: 3,+ max: INVITED_MEMBER_MAX,+ }),+ deleted: countControl('Deleted members', {+ group: LIST,+ value: 1,+ max: DELETED_MEMBER_MAX,+ }),+ roles: countControl('Assignable custom roles', {+ group: LIST,+ description:+ 'Custom roles the drawer offers on top of the three managed ones.',+ value: 3,+ max: CUSTOM_ROLE_MAX,+ }),+ inviteToken: choiceControl<ResetTokenState>('Invite link', {+ group: INVITES,+ description:+ "Whether the link mailed to a pending member is still good. Expired swaps the drawer's copy action for a new-link one.",+ options: RESET_TOKEN_STATES,+ value: 'valid',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/users',+ response.json(() =>+ usersResponse({+ active: values.active,+ invited: values.invited,+ deleted: values.deleted,+ }),+ ),+ ),++ rest.post(+ 'http://localhost/api/v2/users',+ response.json(() => createdUserResponse()),+ ),++ rest.get(+ 'http://localhost/api/v2/users/:id/reset_password_tokens',+ response.json(() => resetPasswordTokenResponse(values.inviteToken)),+ ),++ rest.post(+ 'http://localhost/api/v2/users/:id/reset_password_tokens',+ response.json(() => resetPasswordTokenResponse('valid')),+ ),++ rest.get(+ 'http://localhost/api/v2/users/:id',+ response.json((req) => userDetailResponse(String(req.params.id))),+ ),++ rest.patch(+ 'http://localhost/api/v2/users/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.delete(+ 'http://localhost/api/v2/users/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.post(+ 'http://localhost/api/v2/user_roles',+ response.json(() => ({ status: 'success', data: { id: 'user-role-new' } })),+ ),++ rest.delete(+ 'http://localhost/api/v2/user_roles/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.get(+ 'http://localhost/api/v1/roles',+ response.json(() => rolesListResponse(values.roles)),+ ),+ ],+ config: () => ({ route: ROUTES.MEMBERS_SETTINGS }),+});diff --git a/frontend/src/pages/Settings/Members/stories/Members.stories.tsx b/frontend/src/pages/Settings/Members/stories/Members.stories.tsxnew file mode 100644index 0000000000..136aa70b7b--- /dev/null+++ b/frontend/src/pages/Settings/Members/stories/Members.stories.tsx@@ -0,0 +1,216 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { membersMocks } from './Members.stories.mocks';++import SettingsPage from '../../Settings';++type MembersArgs = PageStoryArgs<typeof membersMocks>;++const pageStory = storyMocks(membersMocks, { layout: 'app' });++/**+ * Members, pending invites and deleted users, the role each holds, and the invite+ * link flow.+ *+ * Route: `/settings/members`.+ */+const meta = {+ title: 'Pages/Settings/Members',+ tags: ['play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<MembersArgs>;++export default meta;++type Story = StoryObj<MembersArgs>;++/** The table fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/** One more than the twenty rows a page holds. */+const OVER_ONE_PAGE = 21;++/**+ * The click handler sits on the row rather than the cell, and the header row+ * resolves before the body has one: wait on a cell, then click the row it is in.+ */+const openMember = async (+ canvasElement: HTMLElement,+ name: RegExp,+): Promise<void> => {+ const cell = await within(canvasElement).findByText(+ name,+ undefined,+ untilLoaded,+ );++ await userEvent.click(cell.closest('tr') as HTMLElement);+};++const openPendingMember = async ({+ canvasElement,+}: {+ canvasElement: HTMLElement;+}): Promise<void> => {+ await openMember(canvasElement, /podrick payne/i);+ await screen.findByText(/invited on/i, undefined, untilLoaded);+};++/**+ * Everyone with a seat in the workspace: who they are, whether they have taken+ * up their invite, and when they joined.+ */+export const Default: Story = {};++/** A workspace where everyone invited is still to sign in for the first time. */+export const AllPending: Story = {+ args: { active: 0, invited: 5, deleted: 0 },+};++/** Interaction: the status menu is open with the real member counts. */+export const FilterMenuOpen: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /all members/i,+ undefined,+ untilLoaded,+ ),+ );+ await screen.findByText(/pending invites/i, undefined, untilLoaded);+ },+};++/** Interaction: the pending-invite filter narrows the real member table. */+export const PendingOnly: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /all members/i,+ undefined,+ untilLoaded,+ ),+ );+ await userEvent.click(+ await screen.findByText(/^pending invites/i, undefined, untilLoaded),+ );+ // One badge per pending row.+ await screen.findAllByText('INVITED', undefined, untilLoaded);+ },+};++/** Interaction: the deleted-member filter exposes the read-only member rows. */+export const DeletedOnly: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /all members/i,+ undefined,+ untilLoaded,+ ),+ );+ await userEvent.click(+ // The unfiltered table already shows a DELETED badge, so the menu option+ // is matched on its own count suffix.+ await screen.findByText(/^deleted ⎯/i, undefined, untilLoaded),+ );+ await screen.findAllByText('DELETED', undefined, untilLoaded);+ },+};++/** Empty: searching for a non-member renders the table's supported empty state. */+export const SearchNoResults: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.type(+ await within(canvasElement).findByPlaceholderText(+ /search by name or email/i,+ undefined,+ untilLoaded,+ ),+ 'no-such-member',+ );+ await screen.findByText(/no results for/i, undefined, untilLoaded);+ },+};++/** More members than one page holds, which is where the pager appears. */+export const Paginated: Story = {+ args: { active: OVER_ONE_PAGE },+};++/** A member opened up: the name and roles that can be changed from here. */+export const EditMember: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openMember(canvasElement, /jon snow/i);+ await screen.findByPlaceholderText(/enter name/i, undefined, untilLoaded);+ },+};++/**+ * A member who has not accepted yet, whose drawer carries the invite link and+ * the date it runs out.+ */+export const PendingInvite: Story = {+ play: openPendingMember,+};++/** The same member after the link that was mailed to them has run out. */+export const ExpiredInvite: Story = {+ args: { inviteToken: 'expired' },+ play: openPendingMember,+};++/** Interaction: deleting an active member is guarded by its confirmation dialog. */+export const DeleteMemberConfirm: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openMember(canvasElement, /jon snow/i);+ await userEvent.click(+ await screen.findByRole('button', { name: 'Delete Member' }),+ );+ await screen.findByRole('dialog', { name: 'Delete Member' });+ },+};++/** Interaction: revoking a pending invite uses its distinct confirmation copy. */+export const RevokeInviteConfirm: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openPendingMember({ canvasElement });+ await userEvent.click(+ await screen.findByRole('button', { name: 'Revoke Invite' }),+ );+ await screen.findByRole('dialog', { name: 'Revoke Invite' });+ },+};++/**+ * The roles a member can be given. The dropdown opens off the inner combobox,+ * not the wrapper the click lands on first.+ */+export const AssignRoles: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await openMember(canvasElement, /jon snow/i);+ await userEvent.click(await screen.findByRole('combobox'));+ await screen.findByText('oncall-responder', undefined, untilLoaded);+ },+};++/** The form that mails seats out: an email and a role per row. */+export const InviteMembers: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByText(+ /invite member/i,+ undefined,+ untilLoaded,+ ),+ );+ // The form opens with a row per seat, each carrying its own email field.+ await screen.findAllByTestId(/^invite-email-/, undefined, untilLoaded);+ },+};diff --git a/frontend/src/pages/Settings/Members/stories/__story_mockdata__/members.ts b/frontend/src/pages/Settings/Members/stories/__story_mockdata__/members.tsnew file mode 100644index 0000000000..0f8dc2be6b--- /dev/null+++ b/frontend/src/pages/Settings/Members/stories/__story_mockdata__/members.ts@@ -0,0 +1,156 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ AuthtypesUserRoleDTO,+ CreateUser201,+ GetResetPasswordToken200,+ GetUser200,+ ListUsers200,+ TypesUserDTO,+} from 'api/generated/services/sigNoz.schemas';+import { RoleType } from 'types/roles';+import { UserApiStatus } from 'container/MembersSettings/utils';++export const ACTIVE_MEMBER_MAX = 26;+export const INVITED_MEMBER_MAX = 6;+export const DELETED_MEMBER_MAX = 4;++const NAMES = [+ 'Jon Snow',+ 'Arya Stark',+ 'Samwell Tarly',+ 'Brienne of Tarth',+ 'Davos Seaworth',+ 'Missandei Naath',+ 'Tormund Giantsbane',+ 'Gilly Craster',+ 'Podrick Payne',+ 'Yara Greyjoy',+ 'Grey Worm',+ 'Beric Dondarrion',+ 'Meera Reed',+ 'Edd Tollett',+ 'Alys Karstark',+ 'Lyanna Mormont',+ 'Gendry Baratheon',+ 'Ellaria Sand',+ 'Qyburn Maester',+ 'Jaqen Hghar',+ 'Osha Wildling',+ 'Hot Pie',+ 'Anguy Archer',+ 'Jorah Mormont',+ 'Rakharo Dothraki',+ 'Doreah Lysene',+];++const DAY = 24 * 60 * 60 * 1000;++/** Fixed epoch so the "joined on" column does not move between renders. */+const JOINED_AT = Date.UTC(2026, 2, 3, 8, 0);++const emailFor = (name: string): string =>+ `${name.toLowerCase().replace(/[^a-z]+/g, '.')}@nightswatch.io`;++const user = (index: number, status: UserApiStatus): TypesUserDTO => {+ const name = NAMES[index % NAMES.length];++ return {+ id: `user-${status}-${index}`,+ displayName: name,+ email: emailFor(name),+ orgId: 'story-org',+ status,+ createdAt: new Date(JOINED_AT - index * DAY).toISOString(),+ updatedAt: new Date(JOINED_AT - index * DAY + 3600_000).toISOString(),+ };+};++interface MemberCounts {+ active: number;+ invited: number;+ deleted: number;+}++export const usersResponse = ({+ active,+ invited,+ deleted,+}: MemberCounts): ListUsers200 => ({+ status: 'success',+ data: [+ ...Array.from({ length: active }, (_, index) =>+ user(index, UserApiStatus.Active),+ ),+ ...Array.from({ length: invited }, (_, index) =>+ user(index + active, UserApiStatus.PendingInvite),+ ),+ ...Array.from({ length: deleted }, (_, index) =>+ user(index + active + invited, UserApiStatus.Deleted),+ ),+ ],+});++const userRole = (userId: string): AuthtypesUserRoleDTO => ({+ id: `user-role-${userId}`,+ userId,+ roleId: 'role-editor',+ role: {+ id: 'role-editor',+ name: 'editor',+ description: 'Can create and change dashboards, alerts and views.',+ orgId: 'story-org',+ type: RoleType.MANAGED,+ transactionGroups: [],+ },+ createdAt: new Date(JOINED_AT).toISOString(),+ updatedAt: new Date(JOINED_AT).toISOString(),+});++/**+ * The drawer reads the member's roles off the user record rather than a roles+ * endpoint, and the join-row id is what a role removal is keyed on.+ */+export const userDetailResponse = (id: string): GetUser200 => {+ const index = Number.parseInt(id.split('-').pop() ?? '0', 10);+ const status = id.includes(UserApiStatus.PendingInvite)+ ? UserApiStatus.PendingInvite+ : id.includes(UserApiStatus.Deleted)+ ? UserApiStatus.Deleted+ : UserApiStatus.Active;++ return {+ status: 'success',+ data: { ...user(index, status), userRoles: [userRole(id)] },+ };+};++export const RESET_TOKEN_STATES = ['valid', 'expired'] as const;++export type ResetTokenState = (typeof RESET_TOKEN_STATES)[number];++/**+ * An invite is a reset-password token with an expiry: past it, the drawer offers+ * a new link instead of the one that was mailed out.+ */+export const resetPasswordTokenResponse = (+ state: ResetTokenState,+): GetResetPasswordToken200 => ({+ status: 'success',+ data: {+ id: 'reset-token-1',+ passwordId: 'password-1',+ token: 'storybook-invite-token',+ expiresAt: new Date(+ state === 'expired' ? JOINED_AT - DAY : Date.now() + 3 * DAY,+ ).toISOString(),+ },+});++export const createdUserResponse = (): CreateUser201 => ({+ status: 'success',+ data: { id: 'user-active-new' },+});diff --git a/frontend/src/pages/Settings/Roles/RoleDetails/stories/RoleDetails.stories.mocks.tsx b/frontend/src/pages/Settings/Roles/RoleDetails/stories/RoleDetails.stories.mocks.tsxnew file mode 100644index 0000000000..4d65d2a676--- /dev/null+++ b/frontend/src/pages/Settings/Roles/RoleDetails/stories/RoleDetails.stories.mocks.tsx@@ -0,0 +1,80 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import { RoleType } from 'types/roles';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ CUSTOM_ROLE_ID,+ MANAGED_ROLE_ID,+ PERMISSION_BREADTHS,+ type PermissionBreadth,+ roleResponse,+ rolesListResponse,+} from '../../../stories/__story_mockdata__/roles';++const ROLE = 'Role details · role';++const ROLE_TYPES = [RoleType.CUSTOM, RoleType.MANAGED] as const;++/** Named after the role the route points at, which the header reads off `?name`. */+const roleFor = (type: RoleType): { id: string; name: string } =>+ type === RoleType.MANAGED+ ? { id: MANAGED_ROLE_ID, name: 'admin' }+ : { id: CUSTOM_ROLE_ID, name: 'oncall-responder' };++export const roleDetailsMocks = defineStoryMocks({+ controls: {+ roleType: choiceControl<RoleType>('Role type', {+ group: ROLE,+ description:+ "A managed role is the backend's own: it can be read but not edited or deleted, so the header actions go with it.",+ options: ROLE_TYPES,+ value: RoleType.CUSTOM,+ }),+ grants: choiceControl<PermissionBreadth>('Granted permissions', {+ group: ROLE,+ description:+ 'How much the role grants. `broad` covers whole resources and named subsets, `narrow` one object, `none` nothing at all.',+ options: PERMISSION_BREADTHS,+ value: 'broad',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/roles/:id',+ response.json((req) =>+ roleResponse(String(req.params.id), values.roleType, values.grants),+ ),+ ),++ rest.delete(+ 'http://localhost/api/v1/roles/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.get(+ 'http://localhost/api/v1/roles',+ response.json(() => rolesListResponse(4)),+ ),+ ],+ config: (values) => {+ const role = roleFor(values.roleType);++ return {+ route: `${ROUTES.ROLE_DETAILS.replace(':roleId', role.id)}?name=${role.name}`,+ };+ },+});++export const deleteRoleFailed = [+ rest.delete('http://localhost/api/v1/roles/:id', (_req, res, ctx) =>+ res(ctx.status(500), ctx.json({ message: 'Role deletion failed' })),+ ),+];diff --git a/frontend/src/pages/Settings/Roles/RoleDetails/stories/RoleDetails.stories.tsx b/frontend/src/pages/Settings/Roles/RoleDetails/stories/RoleDetails.stories.tsxnew file mode 100644index 0000000000..bf0acb6a61--- /dev/null+++ b/frontend/src/pages/Settings/Roles/RoleDetails/stories/RoleDetails.stories.tsx@@ -0,0 +1,152 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { expect, screen, userEvent, waitFor, within } from 'storybook/test';+import { RoleType } from 'types/roles';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import {+ deleteRoleFailed,+ roleDetailsMocks,+} from './RoleDetails.stories.mocks';++import SettingsPage from '../../../Settings';++type RoleDetailsArgs = PageStoryArgs<typeof roleDetailsMocks>;++const pageStory = storyMocks(roleDetailsMocks, { layout: 'app' });++/**+ * One role read only: what it grants, by resource, built in or custom. Gated on+ * authz permissions.+ *+ * Route: `/settings/roles/:roleId`.+ */+const meta = {+ title: 'Pages/Settings/Role Details',+ tags: ['authz', 'beta', 'play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<RoleDetailsArgs>;++export default meta;++type Story = StoryObj<RoleDetailsArgs>;++/** The role fetches before the overview renders, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * One custom role read-only: every resource it touches, the verbs granted on+ * each, and whether the grant covers the whole resource or named objects.+ */+export const Default: Story = {};++/**+ * A role that has been created but not given anything yet, which is what the+ * overview looks like between saving a name and writing the permissions.+ */+export const NothingGranted: Story = {+ args: { grants: 'none' },+};++/** Loading: the role details request is pending while the stable page header remains. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** Error: the real role-details error banner appears after a failed fetch. */+export const LoadError: Story = {+ args: { dataState: 'error' },+ // The deliberate 500 is the state under test.+ parameters: { allowConsoleErrors: true },+};++/**+ * A role the backend owns. It reads the same, but it cannot be edited or+ * deleted, so the header keeps only the way back.+ */+export const ManagedRole: Story = {+ args: { roleType: RoleType.MANAGED },+};++/** The same grant as the API stores it, which is what the editor writes. */+export const JsonView: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'permission-view-mode-json',+ undefined,+ untilLoaded,+ ),+ );+ },+};++/** Interaction: deleting a custom role opens the irreversible-action confirmation. */+export const DeleteRoleConfirm: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ // The header renders a disabled Delete while the role loads and swaps it for+ // the real one once its permission check answers, so the button is looked up+ // again on every attempt; a click on the disabled one is dropped in silence.+ const deleteRole = await waitFor(() => {+ const button = within(canvasElement).getByTestId('delete-button');++ expect(button).toBeEnabled();++ return button;+ }, untilLoaded);++ await userEvent.click(deleteRole);+ await screen.findByRole('dialog', { name: 'Delete Role' });+ },+};++/** Failure: the delete dialog retains the action and exposes the server error. */+export const DeleteRoleFailed: Story = {+ // The deliberate 500 is the state under test.+ parameters: {+ msw: { handlers: deleteRoleFailed },+ allowConsoleErrors: true,+ },+ play: async ({ canvasElement }): Promise<void> => {+ // The header renders a disabled Delete while the role loads and swaps it for+ // the real one once its permission check answers, so the button is looked up+ // again on every attempt; a click on the disabled one is dropped in silence.+ const deleteRole = await waitFor(() => {+ const button = within(canvasElement).getByTestId('delete-button');++ expect(button).toBeEnabled();++ return button;+ }, untilLoaded);++ await userEvent.click(deleteRole);+ const dialog = await screen.findByRole('dialog', { name: 'Delete Role' });++ await userEvent.click(+ within(dialog).getByRole('button', { name: 'Delete Role' }),+ );+ await screen.findByText(/failed to delete role/i, undefined, untilLoaded);+ },+};++/**+ * Every tooltip the role overview carries, held open at once: the two refusals+ * on a managed role's header actions, and the copy action over the JSON the API+ * stores. The role has to be managed for the header ones to exist at all, so+ * the Role type control does not reach this story.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true, roleType: RoleType.MANAGED },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'permission-view-mode-json',+ undefined,+ untilLoaded,+ ),+ );+ },+};diff --git a/frontend/src/pages/Settings/Roles/RoleEditor/stories/RoleEditor.stories.mocks.tsx b/frontend/src/pages/Settings/Roles/RoleEditor/stories/RoleEditor.stories.mocks.tsxnew file mode 100644index 0000000000..a8728f95de--- /dev/null+++ b/frontend/src/pages/Settings/Roles/RoleEditor/stories/RoleEditor.stories.mocks.tsx@@ -0,0 +1,86 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import { RoleType } from 'types/roles';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ CUSTOM_ROLE_ID,+ PERMISSION_BREADTHS,+ type PermissionBreadth,+ roleResponse,+} from '../../../stories/__story_mockdata__/roles';++const EDITOR = 'Role editor · editor';++const MODES = ['create', 'edit'] as const;++type Mode = (typeof MODES)[number];++const EDITORS = ['interactive', 'json'] as const;++type Editor = (typeof EDITORS)[number];++const CUSTOM_ROLE_NAME = 'oncall-responder';++/**+ * Create and edit are the same page on two routes: `roles/new` reads as create,+ * anything else as an edit of the role in the pathname.+ */+const routeFor = (mode: Mode, editor: Editor): string => {+ const search = `viewMode=${editor}`;++ return mode === 'create'+ ? `${ROUTES.ROLE_CREATE}?${search}`+ : `${ROUTES.ROLE_EDIT.replace(':roleId', CUSTOM_ROLE_ID)}?name=${CUSTOM_ROLE_NAME}&${search}`;+};++export const roleEditorMocks = defineStoryMocks({+ controls: {+ mode: choiceControl<Mode>('Mode', {+ group: EDITOR,+ description:+ 'Whether the page is writing a new role or changing one that exists. Create starts from nothing and asks for a name.',+ options: MODES,+ value: 'create',+ }),+ editor: choiceControl<Editor>('Editor', {+ group: EDITOR,+ description:+ 'The permission editor: resource cards, or the JSON the API stores.',+ options: EDITORS,+ value: 'interactive',+ }),+ grants: choiceControl<PermissionBreadth>('Granted permissions', {+ group: EDITOR,+ description: 'What the edited role already grants. Ignored while creating.',+ options: PERMISSION_BREADTHS,+ value: 'broad',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/roles/:id',+ response.json((req) =>+ roleResponse(String(req.params.id), RoleType.CUSTOM, values.grants),+ ),+ ),++ rest.post(+ 'http://localhost/api/v1/roles',+ response.json(() => ({ status: 'success', data: { id: CUSTOM_ROLE_ID } })),+ ),++ rest.put(+ 'http://localhost/api/v1/roles/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),+ ],+ config: (values) => ({ route: routeFor(values.mode, values.editor) }),+});diff --git a/frontend/src/pages/Settings/Roles/RoleEditor/stories/RoleEditor.stories.tsx b/frontend/src/pages/Settings/Roles/RoleEditor/stories/RoleEditor.stories.tsxnew file mode 100644index 0000000000..0c0e97cfa8--- /dev/null+++ b/frontend/src/pages/Settings/Roles/RoleEditor/stories/RoleEditor.stories.tsx@@ -0,0 +1,77 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { roleEditorMocks } from './RoleEditor.stories.mocks';++import SettingsPage from '../../../Settings';++type RoleEditorArgs = PageStoryArgs<typeof roleEditorMocks>;++const pageStory = storyMocks(roleEditorMocks, { layout: 'app' });++/**+ * Creating or editing a custom role, through the permission wizard or the JSON+ * editor. Gated on authz permissions.+ *+ * Route: `/settings/roles/new` and `/settings/roles/:roleId/edit`.+ */+const meta = {+ title: 'Pages/Settings/Role Editor',+ tags: ['authz', 'beta', 'play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<RoleEditorArgs>;++export default meta;++type Story = StoryObj<RoleEditorArgs>;++/**+ * Writing a role from scratch: a name, and a card per resource where each verb+ * is granted over everything, over named objects, or not at all.+ */+export const Default: Story = {};++/** The same editor over a role that already grants a good deal. */+export const EditExisting: Story = {+ args: { mode: 'edit' },+};++/** The JSON the API stores, which is the other way the same grant is written. */+export const JsonEditor: Story = {+ args: { mode: 'edit', editor: 'json' },+};++/**+ * An unlicensed instance, where custom roles do not exist: the editor refuses+ * rather than letting a role be written that cannot be saved.+ */+export const Unlicensed: Story = {+ args: { license: 'community-enterprise' },+};++/**+ * The selector hint on the resource cards, held open: the tallest tooltip in+ * settings, two lines of prose around a docs link. It only exists on a verb+ * scoped to named objects that already has some, so this edits a role that+ * grants those and expands every card to reach them.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true, mode: 'edit' },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId('expand-all-button', undefined, {+ timeout: 15_000,+ }),+ );+ },+};++/** The copy action over the JSON editor, which the resource cards replace. */+export const TooltipsInJsonEditor: Story = {+ args: { tooltipsOpen: true, mode: 'edit', editor: 'json' },+};diff --git a/frontend/src/pages/Settings/Roles/stories/Roles.stories.mocks.tsx b/frontend/src/pages/Settings/Roles/stories/Roles.stories.mocks.tsxnew file mode 100644index 0000000000..e870dd74cf--- /dev/null+++ b/frontend/src/pages/Settings/Roles/stories/Roles.stories.mocks.tsx@@ -0,0 +1,36 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ CUSTOM_ROLE_MAX,+ rolesListResponse,+} from '../../stories/__story_mockdata__/roles';++const LIST = 'Roles · list';++export const rolesMocks = defineStoryMocks({+ controls: {+ customRoles: countControl('Custom roles', {+ group: LIST,+ description:+ 'Roles the org wrote itself. The three managed ones are always listed above them.',+ value: 4,+ max: CUSTOM_ROLE_MAX,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/roles',+ response.json(() => rolesListResponse(values.customRoles)),+ ),+ ],+ config: () => ({ route: ROUTES.ROLES_SETTINGS }),+});diff --git a/frontend/src/pages/Settings/Roles/stories/Roles.stories.tsx b/frontend/src/pages/Settings/Roles/stories/Roles.stories.tsxnew file mode 100644index 0000000000..7f7f7d9b84--- /dev/null+++ b/frontend/src/pages/Settings/Roles/stories/Roles.stories.tsx@@ -0,0 +1,75 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { rolesMocks } from './Roles.stories.mocks';++import SettingsPage from '../../Settings';++type RolesArgs = PageStoryArgs<typeof rolesMocks>;++const pageStory = storyMocks(rolesMocks, { layout: 'app' });++/**+ * Built in and custom roles for the workspace. Gated on authz permissions.+ *+ * Route: `/settings/roles`.+ */+const meta = {+ title: 'Pages/Settings/Roles',+ tags: ['authz', 'beta'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<RolesArgs>;++export default meta;++type Story = StoryObj<RolesArgs>;++/**+ * The roles a member or a service account can be given: the three the backend+ * ships with, and the ones the org has written on top of them.+ */+export const Default: Story = {};++/** An org still on the built-in roles alone. */+export const ManagedOnly: Story = {+ args: { customRoles: 0 },+};++/** Loading: the roles table waits on the actual list request. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** Error: a failed roles list uses the table's inline error branch. */+export const LoadError: Story = {+ args: { dataState: 'error' },+ // The deliberate 500 is the state under test.+ parameters: { allowConsoleErrors: true },+};++/**+ * Density: every supported custom-role fixture renders beside the managed roles.+ * It follows `LoadError`, whose deliberate 500 on the same endpoint can land+ * while this story is running, so the opt-out covers the attribution as well.+ */+export const MaximumCustomRoles: Story = {+ args: { customRoles: 8 },+ parameters: { allowConsoleErrors: true },+};++/**+ * The same list without a valid license, where the built-in roles are all there+ * is: no custom role can be written, so the toolbar loses its button.+ */+export const Unlicensed: Story = {+ args: { license: 'community-enterprise', customRoles: 0 },+};++/** A viewer, who cannot list roles at all and is told so in place of the table. */+export const Viewer: Story = {+ args: { access: 'viewer' },+};diff --git a/frontend/src/pages/Settings/ServiceAccounts/stories/ServiceAccounts.stories.mocks.tsx b/frontend/src/pages/Settings/ServiceAccounts/stories/ServiceAccounts.stories.mocks.tsxnew file mode 100644index 0000000000..19e96d9663--- /dev/null+++ b/frontend/src/pages/Settings/ServiceAccounts/stories/ServiceAccounts.stories.mocks.tsx@@ -0,0 +1,161 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { handleInternalServerError } from 'mocks-server/utils';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import type { MockResolver } from '@/storybook/msw/types';++import {+ ACTIVE_ACCOUNT_MAX,+ createdServiceAccountKeyResponse,+ createdServiceAccountResponse,+ DELETED_ACCOUNT_MAX,+ KEY_MAX,+ SAVE_OUTCOMES,+ type SaveOutcome,+ serviceAccountDetailResponse,+ serviceAccountKeysResponse,+ serviceAccountSaveError,+ serviceAccountsResponse,+} from './__story_mockdata__/serviceAccounts';++import {+ CUSTOM_ROLE_MAX,+ rolesListResponse,+} from '../../stories/__story_mockdata__/roles';++const LIST = 'Service accounts · list';+const KEYS = 'Service accounts · keys';+const DRAWER = 'Service accounts · drawer';++const rejectSave: MockResolver = (_req, res, ctx) =>+ res(ctx.status(500), ctx.json(serviceAccountSaveError()));++export const accountsLoadError = rest.get(+ 'http://localhost/api/v1/service_accounts',+ handleInternalServerError,+);++export const keysLoadingForever = rest.get(+ 'http://localhost/api/v1/service_accounts/:id/keys',+ (_req, res, ctx) => res(ctx.delay('infinite')),+);++export const serviceAccountsMocks = defineStoryMocks({+ controls: {+ accounts: countControl('Active accounts', {+ group: LIST,+ description: 'The table paginates past 20.',+ value: 5,+ max: ACTIVE_ACCOUNT_MAX,+ }),+ deleted: countControl('Deleted accounts', {+ group: LIST,+ value: 1,+ max: DELETED_ACCOUNT_MAX,+ }),+ roles: countControl('Assignable custom roles', {+ group: LIST,+ description:+ 'Custom roles the drawer offers on top of the three managed ones.',+ value: 3,+ max: CUSTOM_ROLE_MAX,+ }),+ keys: countControl('API keys per account', {+ group: KEYS,+ description:+ 'Keys listed on the drawer’s Keys tab, which paginates past 15. The first three are the never-expiring, the expired and the never-used one.',+ value: 4,+ max: KEY_MAX,+ }),+ saveOutcome: choiceControl<SaveOutcome>('Saving the account', {+ group: DRAWER,+ description:+ 'Whether the rename behind Save Changes succeeds or comes back a failure the drawer offers to retry.',+ options: SAVE_OUTCOMES,+ value: 'succeeds',+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v1/service_accounts',+ response.json(() =>+ serviceAccountsResponse(values.accounts, values.deleted),+ ),+ ),++ rest.post(+ 'http://localhost/api/v1/service_accounts',+ response.json(() => createdServiceAccountResponse()),+ ),++ rest.get(+ 'http://localhost/api/v1/service_accounts/:id/keys',+ response.json((req) =>+ serviceAccountKeysResponse(String(req.params.id), values.keys),+ ),+ ),++ rest.post(+ 'http://localhost/api/v1/service_accounts/:id/keys',+ response.json(() => createdServiceAccountKeyResponse()),+ ),++ rest.put(+ 'http://localhost/api/v1/service_accounts/:id/keys/:fid',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.delete(+ 'http://localhost/api/v1/service_accounts/:id/keys/:fid',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.get(+ 'http://localhost/api/v1/service_accounts/:id',+ response.json((req) => {+ const id = String(req.params.id);+ const index = Number.parseInt(id.split('-').pop() ?? '0', 10);++ return serviceAccountDetailResponse(id, index >= values.accounts);+ }),+ ),++ rest.put(+ 'http://localhost/api/v1/service_accounts/:id',+ values.saveOutcome === 'fails'+ ? rejectSave+ : response.json(() => ({ status: 'success', data: null })),+ ),++ rest.delete(+ 'http://localhost/api/v1/service_accounts/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.post(+ 'http://localhost/api/v1/service_account_roles',+ response.json(() => ({+ status: 'success',+ data: { id: 'service-account-role-new' },+ })),+ ),++ rest.delete(+ 'http://localhost/api/v1/service_account_roles/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),++ rest.get(+ 'http://localhost/api/v1/roles',+ response.json(() => rolesListResponse(values.roles)),+ ),+ ],+ config: () => ({ route: ROUTES.SERVICE_ACCOUNTS_SETTINGS }),+});diff --git a/frontend/src/pages/Settings/ServiceAccounts/stories/ServiceAccounts.stories.tsx b/frontend/src/pages/Settings/ServiceAccounts/stories/ServiceAccounts.stories.tsxnew file mode 100644index 0000000000..ec58819ada--- /dev/null+++ b/frontend/src/pages/Settings/ServiceAccounts/stories/ServiceAccounts.stories.tsx@@ -0,0 +1,278 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import ROUTES from 'constants/routes';+import { expect, screen, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import {+ accountsLoadError,+ keysLoadingForever,+ serviceAccountsMocks,+} from './ServiceAccounts.stories.mocks';++import SettingsPage from '../../Settings';++type ServiceAccountsArgs = PageStoryArgs<typeof serviceAccountsMocks>;++const pageStory = storyMocks(serviceAccountsMocks, { layout: 'app' });++/**+ * Service accounts, the roles they hold and the API keys they carry, with the+ * drawer that creates and revokes keys. Every action is gated on an authz+ * permission.+ *+ * Route: `/settings/service-accounts`.+ */+const meta = {+ title: 'Pages/Settings/Service Accounts',+ tags: ['authz', 'play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ServiceAccountsArgs>;++export default meta;++type Story = StoryObj<ServiceAccountsArgs>;++/** The table fetches before it renders a row, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * The page keeps the drawer, the tab, the modals and the list filters in the+ * query string, so a story reaches any of them by starting there.+ */+const at = (params: string): { signoz: { route: string } } => ({+ signoz: { route: `${ROUTES.SERVICE_ACCOUNTS_SETTINGS}?${params}` },+});++const ACCOUNT = 'service-account-0';+const KEYS_TAB = `account=${ACCOUNT}&tab=keys`;++/**+ * The non-human identities the workspace has issued: what each one is called,+ * whether it is still live, and when it was created.+ */+export const Default: Story = {};++/** A workspace that has not issued one yet. */+export const NoAccounts: Story = {+ args: { accounts: 0, deleted: 0 },+};++/** Enough accounts to paginate, read from the second page. */+export const SecondPage: Story = {+ args: { accounts: 24 },+ parameters: at('page=2'),+};++/** The list narrowed to the accounts that have been deleted. */+export const DeletedOnly: Story = {+ parameters: at('filter=deleted'),+};++/** The list narrowed by a search on the name and email column. */+export const Searched: Story = {+ parameters: at('search=terraform'),+};++/** Interaction: the status menu is open with its active and deleted counts. */+export const FilterMenuOpen: Story = {+ play: async (): Promise<void> => {+ // The trigger is disabled until the list and its permission check answer, so+ // waiting on the text alone lands on a button that drops the click.+ const trigger = await waitFor(() => {+ const button = screen.getByRole('button', { name: /all accounts/i });++ if ((button as HTMLButtonElement).disabled) {+ throw new Error('the filter trigger is still disabled');+ }++ return button;+ }, untilLoaded);++ await userEvent.click(trigger);+ // Every active row carries an ACTIVE badge, so the menu option is matched on+ // its own count suffix.+ await screen.findByText(/^active ⎯/i, undefined, untilLoaded);+ },+};++/** Empty: a search that matches no account keeps the list shell and empty state. */+export const SearchNoResults: Story = {+ parameters: at('search=no-such-service-account'),+};++/** Error: the list request failed while the rest of the settings shell stays usable. */+export const LoadError: Story = {+ parameters: { msw: { handlers: [accountsLoadError] } },+};++/** An account opened up: the name and the roles it acts under. */+export const AccountOverview: Story = {+ // The deliberate 500 is the state under test.+ parameters: { ...at(`account=${ACCOUNT}`), allowConsoleErrors: true },+};++/**+ * A deleted account, which opens read-only: the name is locked, the keys cannot+ * be touched, and the footer that saves and deletes is gone.+ */+export const DeletedAccount: Story = {+ parameters: at('account=service-account-5'),+};++/**+ * The roles an account can be given. The dropdown opens off the inner combobox,+ * not the wrapper the click lands on first.+ */+export const AssignRoles: Story = {+ parameters: at(`account=${ACCOUNT}`),+ play: async (): Promise<void> => {+ await userEvent.click(+ await screen.findByRole('combobox', undefined, untilLoaded),+ );+ await screen.findByText('oncall-responder', undefined, untilLoaded);+ },+};++/**+ * A rename that comes back a failure: the drawer keeps the edit, names what+ * broke, and offers the retry rather than dropping the change.+ */+export const SaveFailed: Story = {+ args: { saveOutcome: 'fails' },+ // The deliberate 500 is the state under test.+ parameters: { ...at(`account=${ACCOUNT}`), allowConsoleErrors: true },+ play: async (): Promise<void> => {+ await userEvent.type(+ await screen.findByDisplayValue('ci-pipeline', undefined, untilLoaded),+ '-v2',+ );+ await userEvent.click(await screen.findByText(/save changes/i));+ await screen.findByText(/name update/i, undefined, untilLoaded);+ },+};++/** The dialog a new account is named in. */+export const CreateAccount: Story = {+ parameters: at('create-sa=true'),+};++/** The confirmation an account is deleted behind, keys and all. */+export const DeleteAccount: Story = {+ parameters: at(`account=${ACCOUNT}&delete-sa=true`),+};++/**+ * The keys issued against one account: the one that never expires, the one that+ * has lapsed, and the one nothing has ever called.+ */+export const AccountKeys: Story = {+ parameters: at(KEYS_TAB),+};++/** Loading: account details remain available while only the keys list is pending. */+export const KeysLoading: Story = {+ parameters: { ...at(KEYS_TAB), msw: { handlers: [keysLoadingForever] } },+};++/** An account with nothing issued against it yet. */+export const NoKeys: Story = {+ args: { keys: 0 },+ parameters: at(KEYS_TAB),+};++/**+ * Enough keys to paginate. The drawer resets the page to 1 whenever the account+ * loads, so the second page is reached by clicking rather than by the route.+ * The table carries a second, hidden pagination of its own, so the page number+ * has to be taken from the visible one.+ */+export const KeysSecondPage: Story = {+ args: { keys: 20 },+ parameters: at(KEYS_TAB),+ play: async (): Promise<void> => {+ const pagination = await waitFor(() => {+ const rendered = document.querySelector('.sa-drawer__keys-pagination');+ if (!rendered) {+ throw new Error('the keys pagination has not rendered yet');+ }+ return rendered as HTMLElement;+ }, untilLoaded);++ await userEvent.click(within(pagination).getByTitle('2'));+ await screen.findByText('archive-exporter', undefined, untilLoaded);+ },+};++/** The form a key is named and given an expiry in. */+export const AddKey: Story = {+ parameters: at(`${KEYS_TAB}&add-key=true`),+};++/**+ * What the form turns into once the key exists: the secret in full, which is+ * the only time it is ever shown.+ */+export const KeyCreated: Story = {+ parameters: at(`${KEYS_TAB}&add-key=true`),+ play: async (): Promise<void> => {+ await userEvent.type(+ await screen.findByPlaceholderText(+ /enter key name/i,+ undefined,+ untilLoaded,+ ),+ 'release-signer',+ );+ await userEvent.click(await screen.findByText(/create key/i));+ await screen.findByText(+ /only time it will be displayed/i,+ undefined,+ untilLoaded,+ );+ },+};++/** One key opened up: what can still be changed about it, and what cannot. */+export const EditKey: Story = {+ parameters: at(`${KEYS_TAB}&edit-key=factor-api-key-0`),+};++/** Interaction: revocation can be reached from the real key-edit dialog. */+export const EditKeyThenRevokeConfirm: Story = {+ parameters: at(`${KEYS_TAB}&edit-key=factor-api-key-0`),+ play: async (): Promise<void> => {+ // The control is rendered disabled until its permission check answers, and a+ // click on a disabled button is dropped without an error.+ const revoke = await waitFor(() => {+ const button = screen.getByRole('button', { name: 'Revoke Key' });++ expect(button).toBeEnabled();++ return button;+ }, untilLoaded);++ await userEvent.click(revoke);+ await screen.findByRole(+ 'dialog',+ { name: /revoke production-writer/i },+ untilLoaded,+ );+ },+};++/** The confirmation a key is revoked behind, straight from its row. */+export const RevokeKey: Story = {+ parameters: at(`${KEYS_TAB}&revoke-key=factor-api-key-0`),+};++/**+ * A viewer, who cannot list service accounts at all and is told so in place of+ * the table.+ */+export const Viewer: Story = {+ args: { access: 'viewer' },+};diff --git a/frontend/src/pages/Settings/ServiceAccounts/stories/__story_mockdata__/serviceAccounts.ts b/frontend/src/pages/Settings/ServiceAccounts/stories/__story_mockdata__/serviceAccounts.tsnew file mode 100644index 0000000000..41937e33a7--- /dev/null+++ b/frontend/src/pages/Settings/ServiceAccounts/stories/__story_mockdata__/serviceAccounts.ts@@ -0,0 +1,221 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ CreateServiceAccount201,+ CreateServiceAccountKey201,+ GetServiceAccount200,+ ListServiceAccountKeys200,+ ListServiceAccounts200,+ RenderErrorResponseDTO,+ ServiceaccounttypesServiceAccountDTO,+ ServiceaccounttypesServiceAccountRoleDTO,+} from 'api/generated/services/sigNoz.schemas';+import { ServiceAccountStatus } from 'container/ServiceAccountsSettings/utils';+import { RoleType } from 'types/roles';++/** Past the table's own page size of 20, so a story can reach the second page. */+export const ACTIVE_ACCOUNT_MAX = 24;+export const DELETED_ACCOUNT_MAX = 4;+/** Past the Keys tab's page size of 15, for the same reason. */+export const KEY_MAX = 20;++/** One per account the two counts can produce, so no name is ever reused. */+const ACCOUNT_NAMES = [+ 'ci-pipeline',+ 'terraform-runner',+ 'grafana-bridge',+ 'pagerduty-sync',+ 'cost-exporter',+ 'nightly-backfill',+ 'load-generator',+ 'slo-reporter',+ 'log-shipper',+ 'trace-sampler',+ 'metrics-relay',+ 'audit-archiver',+ 'otel-collector',+ 'k8s-operator',+ 'billing-sync',+ 'uptime-prober',+ 'chaos-runner',+ 'deploy-notifier',+ 'schema-migrator',+ 'alert-forwarder',+ 'synthetic-canary',+ 'usage-reporter',+ 'snapshot-pruner',+ 'ingest-throttler',+ 'replay-worker',+ 'quota-watcher',+ 'span-rewriter',+ 'digest-mailer',+];++const DAY = 24 * 60 * 60 * 1000;++/** Fixed epoch so the created column does not move between renders. */+const CREATED_AT = Date.UTC(2026, 1, 20, 13, 45);++const account = (+ index: number,+ status: ServiceAccountStatus,+): ServiceaccounttypesServiceAccountDTO => {+ const name = ACCOUNT_NAMES[index % ACCOUNT_NAMES.length];++ return {+ id: `service-account-${index}`,+ name,+ email: `${name}@service.nightswatch.io`,+ orgId: 'story-org',+ status,+ createdAt: new Date(CREATED_AT - index * DAY).toISOString(),+ updatedAt: new Date(CREATED_AT - index * DAY + 3600_000).toISOString(),+ };+};++export const serviceAccountsResponse = (+ active: number,+ deleted: number,+): ListServiceAccounts200 => ({+ status: 'success',+ data: [+ ...Array.from({ length: active }, (_, index) =>+ account(index, ServiceAccountStatus.Active),+ ),+ ...Array.from({ length: deleted }, (_, index) =>+ account(index + active, ServiceAccountStatus.Deleted),+ ),+ ],+});++const serviceAccountRole = (+ id: string,+): ServiceaccounttypesServiceAccountRoleDTO => ({+ id: `service-account-role-${id}`,+ serviceAccountId: id,+ roleId: 'role-editor',+ role: {+ id: 'role-editor',+ name: 'editor',+ description: 'Can create and change dashboards, alerts and views.',+ orgId: 'story-org',+ type: RoleType.MANAGED,+ transactionGroups: [],+ },+ createdAt: new Date(CREATED_AT).toISOString(),+ updatedAt: new Date(CREATED_AT).toISOString(),+});++export const serviceAccountDetailResponse = (+ id: string,+ deleted: boolean,+): GetServiceAccount200 => {+ const index = Number.parseInt(id.split('-').pop() ?? '0', 10);+ const base = account(+ index,+ deleted ? ServiceAccountStatus.Deleted : ServiceAccountStatus.Active,+ );++ return {+ status: 'success',+ data: { ...base, id, serviceAccountRoles: [serviceAccountRole(id)] },+ };+};++const KEY_NAMES = [+ 'production-writer',+ 'staging-writer',+ 'read-only-dashboards',+ 'incident-bot',+ 'legacy-collector',+ 'canary-agent',+ 'batch-loader',+ 'edge-forwarder',+ 'eu-region-writer',+ 'ap-region-writer',+ 'terraform-plan',+ 'ci-smoke-tests',+ 'grafana-datasource',+ 'pagerduty-webhook',+ 'cost-report',+ 'archive-exporter',+ 'preview-env',+ 'on-prem-relay',+ 'sandbox-writer',+ 'audit-reader',+];++/** What Go marshals a zero time as, which the tab reads as "never used". */+const NEVER_OBSERVED = '0001-01-01T00:00:00Z';++/**+ * `expiresAt` is a unix second count, and zero is what "never expires" is sent+ * as. The rest are dated off now, because the column reads them against today+ * rather than against the account: a fixed date would read as expired forever.+ * The first three keys are the three ways the expiry column renders, and the+ * third is also the one that has never been called.+ */+const keyExpiry = (index: number): number => {+ if (index === 0) {+ return 0;+ }++ if (index === 1) {+ return Math.floor((Date.now() - 14 * DAY) / 1000);+ }++ return Math.floor((Date.now() + index * 30 * DAY) / 1000);+};++export const serviceAccountKeysResponse = (+ id: string,+ keys: number,+): ListServiceAccountKeys200 => ({+ status: 'success',+ data: Array.from({ length: keys }, (_, index) => ({+ id: `factor-api-key-${index}`,+ serviceAccountId: id,+ name: KEY_NAMES[index % KEY_NAMES.length],+ expiresAt: keyExpiry(index),+ lastObservedAt:+ index === 2+ ? NEVER_OBSERVED+ : new Date(CREATED_AT - index * DAY).toISOString(),+ createdAt: new Date(CREATED_AT - index * 7 * DAY).toISOString(),+ updatedAt: new Date(CREATED_AT - index * DAY).toISOString(),+ })),+});++export const createdServiceAccountResponse = (): CreateServiceAccount201 => ({+ status: 'success',+ data: { id: 'service-account-0' },+});++/** The one and only time the secret comes back, which is what the modal says. */+export const createdServiceAccountKeyResponse =+ (): CreateServiceAccountKey201 => ({+ status: 'success',+ data: {+ id: 'factor-api-key-new',+ key: 'sk-story-8f14e45fceea167a5a36dedd4bea2543',+ },+ });++export const SAVE_OUTCOMES = ['succeeds', 'fails'] as const;++export type SaveOutcome = (typeof SAVE_OUTCOMES)[number];++export const serviceAccountSaveError = (): RenderErrorResponseDTO => ({+ status: 'error',+ error: {+ code: 'internal_error',+ type: 'internal',+ message: 'Could not rename the service account.',+ url: '',+ errors: [],+ suggestions: [],+ },+});diff --git a/frontend/src/pages/Settings/Shortcuts/stories/Shortcuts.stories.mocks.tsx b/frontend/src/pages/Settings/Shortcuts/stories/Shortcuts.stories.mocks.tsxnew file mode 100644index 0000000000..0fc91d77d6--- /dev/null+++ b/frontend/src/pages/Settings/Shortcuts/stories/Shortcuts.stories.mocks.tsx@@ -0,0 +1,17 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';++import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++/**+ * The tab reads its rows from `pages/Shortcuts/utils`, so it has no endpoint and+ * no knob of its own: what the panel offers here is the shell around it.+ */+export const shortcutsMocks = defineStoryMocks({+ controls: {},+ config: () => ({ route: ROUTES.SHORTCUTS }),+});diff --git a/frontend/src/pages/Settings/Shortcuts/stories/Shortcuts.stories.tsx b/frontend/src/pages/Settings/Shortcuts/stories/Shortcuts.stories.tsxnew file mode 100644index 0000000000..7b9c32adbe--- /dev/null+++ b/frontend/src/pages/Settings/Shortcuts/stories/Shortcuts.stories.tsx@@ -0,0 +1,31 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { shortcutsMocks } from './Shortcuts.stories.mocks';++import SettingsPage from '../../Settings';++type ShortcutsArgs = PageStoryArgs<typeof shortcutsMocks>;++const pageStory = storyMocks(shortcutsMocks, { layout: 'app' });++/**+ * The shortcut reference. Static: nothing fetches.+ *+ * Route: `/settings/shortcuts`.+ */+const meta = {+ title: 'Pages/Settings/Keyboard Shortcuts',+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<ShortcutsArgs>;++export default meta;++type Story = StoryObj<ShortcutsArgs>;++/** Every key binding the console listens for, grouped by the page it works on. */+export const Default: Story = {};diff --git a/frontend/src/pages/Settings/SingleSignOn/stories/SingleSignOn.stories.mocks.tsx b/frontend/src/pages/Settings/SingleSignOn/stories/SingleSignOn.stories.mocks.tsxnew file mode 100644index 0000000000..0a3a0f36a2--- /dev/null+++ b/frontend/src/pages/Settings/SingleSignOn/stories/SingleSignOn.stories.mocks.tsx@@ -0,0 +1,93 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ AUTHN_PROVIDERS,+ type AuthnProvider,+ authDomainsResponse,+ DOMAIN_MAX,+ myOrganizationResponse,+} from './__story_mockdata__/singleSignOn';++import { rolesListResponse } from '../../stories/__story_mockdata__/roles';++const DOMAINS = 'Single sign-on · domains';++export const singleSignOnMocks = defineStoryMocks({+ controls: {+ domains: countControl('Authenticated domains', {+ group: DOMAINS,+ value: 2,+ max: DOMAIN_MAX,+ }),+ provider: choiceControl<AuthnProvider>('Identity provider', {+ group: DOMAINS,+ description:+ 'What each domain authenticates against. Google has no IdP-initiated URL, so that column reports N/A for it.',+ options: AUTHN_PROVIDERS,+ value: 'saml',+ }),+ enforced: toggleControl('Enforce SSO', {+ group: DOMAINS,+ description:+ 'Whether members of the domain are made to sign in through the provider rather than with a password.',+ value: true,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/auth_domains',+ response.json(() =>+ authDomainsResponse(values.domains, values.provider, values.enforced),+ ),+ ),++ rest.put(+ 'http://localhost/api/v2/auth_domains/:id',+ response.json(() => ({ status: 'success', data: { id: 'auth-domain-0' } })),+ ),++ rest.post(+ 'http://localhost/api/v2/auth_domains',+ response.json(() => ({+ status: 'success',+ data: { id: 'auth-domain-new' },+ })),+ ),++ rest.delete(+ 'http://localhost/api/v2/auth_domains/:id',+ response.json(() => ({ status: 'success', data: null })),+ ),++ // The provider form maps IdP groups onto SigNoz roles, so it reads the role+ // catalogue that the Roles tab owns.+ rest.get(+ 'http://localhost/api/v1/roles',+ response.json(() => rolesListResponse(4)),+ ),++ // The org name is the top half of the tab and the domain table the bottom;+ // a plain resolver keeps the name in place while the table loads or fails.+ rest.get('http://localhost/api/v2/orgs/me', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(myOrganizationResponse())),+ ),++ rest.put('http://localhost/api/v2/orgs/me', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(myOrganizationResponse())),+ ),+ ],+ config: () => ({ route: ROUTES.ORG_SETTINGS }),+});diff --git a/frontend/src/pages/Settings/SingleSignOn/stories/SingleSignOn.stories.tsx b/frontend/src/pages/Settings/SingleSignOn/stories/SingleSignOn.stories.tsxnew file mode 100644index 0000000000..18b08ec8b5--- /dev/null+++ b/frontend/src/pages/Settings/SingleSignOn/stories/SingleSignOn.stories.tsx@@ -0,0 +1,160 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { singleSignOnMocks } from './SingleSignOn.stories.mocks';++import SettingsPage from '../../Settings';++type SingleSignOnArgs = PageStoryArgs<typeof singleSignOnMocks>;++const pageStory = storyMocks(singleSignOnMocks, { layout: 'app' });++/**+ * SAML and OIDC domains for the org, whether SSO is enforced, and the role a new+ * user lands on.+ *+ * Route: `/settings/org-settings`.+ */+const meta = {+ title: 'Pages/Settings/Single Sign-on',+ tags: ['play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<SingleSignOnArgs>;++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.+ */+export const Default: Story = {};++/** An org that has not connected an identity provider yet. */+export const NoDomains: Story = {+ args: { domains: 0 },+};++/** Provider: Google-specific configuration renders the provider's supported row. */+export const GoogleProvider: Story = {+ args: { provider: 'google' },+};++/** Provider: OIDC configuration exposes its issuer-based provider branch. */+export const OidcProvider: Story = {+ args: { provider: 'oidc' },+};++/** Policy: domains that allow password fallback show enforcement switched off. */+export const SsoNotEnforced: Story = {+ args: { enforced: false },+};++/** 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);+ },+};++/** 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,+ ),+ );+ },+};++/** 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,+ );+ },+};++/** 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);+ },+};++/** 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);+ },+};++/** 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,+ );+ },+};diff --git a/frontend/src/pages/Settings/SingleSignOn/stories/__story_mockdata__/singleSignOn.ts b/frontend/src/pages/Settings/SingleSignOn/stories/__story_mockdata__/singleSignOn.tsnew file mode 100644index 0000000000..98627672d0--- /dev/null+++ b/frontend/src/pages/Settings/SingleSignOn/stories/__story_mockdata__/singleSignOn.ts@@ -0,0 +1,114 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ AuthtypesAuthDomainConfigDTO,+ AuthtypesGettableAuthDomainDTO,+ GetMyOrganization200,+ ListAuthDomains200,+} from 'api/generated/services/sigNoz.schemas';+import {+ AuthtypesAuthDomainConfigGoogleDTOKind,+ AuthtypesAuthDomainConfigOIDCDTOKind,+ AuthtypesAuthDomainConfigSAMLDTOKind,+} from 'api/generated/services/sigNoz.schemas';++export const AUTHN_PROVIDERS = ['saml', 'google', 'oidc'] as const;++export type AuthnProvider = (typeof AUTHN_PROVIDERS)[number];++export const DOMAIN_MAX = 4;++const DOMAIN_NAMES = [+ 'nightswatch.io',+ 'nightswatch-labs.io',+ 'contractors.nightswatch.io',+ 'acquired-team.dev',+];++const CREATED_AT = Date.UTC(2026, 0, 8, 11, 15);++const configFor = (provider: AuthnProvider): AuthtypesAuthDomainConfigDTO => {+ switch (provider) {+ case 'google':+ return {+ kind: AuthtypesAuthDomainConfigGoogleDTOKind.google,+ spec: {+ clientId: '918273645-storybook.apps.googleusercontent.com',+ clientSecret: 'GOCSPX-storybook-secret',+ fetchGroups: true,+ allowedGroups: ['[email protected]'],+ },+ };++ case 'oidc':+ return {+ kind: AuthtypesAuthDomainConfigOIDCDTOKind.oidc,+ spec: {+ clientId: 'signoz-console',+ clientSecret: 'storybook-oidc-secret',+ issuer: 'https://id.nightswatch.io',+ getUserInfo: true,+ },+ };++ default:+ return {+ kind: AuthtypesAuthDomainConfigSAMLDTOKind.saml,+ spec: {+ entityId: 'https://id.nightswatch.io/saml/metadata',+ location: 'https://id.nightswatch.io/saml/sso',+ certificate:+ '-----BEGIN CERTIFICATE-----\nMIIDazCCAlOgAwIBAgIUStorybookOnly\n-----END CERTIFICATE-----',+ },+ };+ }+};++/**+ * Only SAML and OIDC carry an IdP-initiated entry point, so the Google row is+ * the one that reports N/A in that column.+ */+const relayStatePath = (provider: AuthnProvider): string | null =>+ provider === 'google' ? null : 'api/v1/complete/saml';++const authDomain = (+ index: number,+ provider: AuthnProvider,+ enforced: boolean,+): AuthtypesGettableAuthDomainDTO => ({+ id: `auth-domain-${index}`,+ name: DOMAIN_NAMES[index] ?? `domain-${index}.io`,+ orgId: 'story-org',+ enabled: enforced,+ config: configFor(provider),+ authNProviderInfo: { relayStatePath: relayStatePath(provider) },+ roleMapping: { defaultRole: 'viewer', useRoleAttribute: false },+ createdAt: new Date(CREATED_AT).toISOString(),+ updatedAt: new Date(CREATED_AT).toISOString(),+});++export const authDomainsResponse = (+ domains: number,+ provider: AuthnProvider,+ enforced: boolean,+): ListAuthDomains200 => ({+ status: 'success',+ data: Array.from({ length: domains }, (_, index) =>+ authDomain(index, provider, enforced),+ ),+});++export const myOrganizationResponse = (): GetMyOrganization200 => ({+ status: 'success',+ data: {+ id: 'does-not-matter-id',+ name: 'nightswatch',+ displayName: 'Pentagon',+ alias: 'nightswatch',+ createdAt: new Date(CREATED_AT).toISOString(),+ updatedAt: new Date(CREATED_AT).toISOString(),+ },+});diff --git a/frontend/src/pages/Settings/Workspace/stories/Workspace.stories.mocks.tsx b/frontend/src/pages/Settings/Workspace/stories/Workspace.stories.mocks.tsxnew file mode 100644index 0000000000..aba312a345--- /dev/null+++ b/frontend/src/pages/Settings/Workspace/stories/Workspace.stories.mocks.tsx@@ -0,0 +1,80 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import type { TStatus } from 'types/api/settings/getRetention';++import { choiceControl, toggleControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ disksResponse,+ hostsResponse,+ logsRetentionResponse,+ metricsRetentionResponse,+ RETENTION_STATUSES,+ tracesRetentionResponse,+ WORKSPACE_URLS,+ type WorkspaceUrl,+} from './__story_mockdata__/workspace';++const RETENTION = 'Workspace · retention';+const DOMAIN = 'Workspace · domain';++export const workspaceMocks = defineStoryMocks({+ controls: {+ coldStorage: toggleControl('Cold storage', {+ group: RETENTION,+ description:+ 'Whether the instance reports an s3 disk. Without one the "Move to S3" field is hidden on all three signals.',+ value: true,+ }),+ retentionStatus: choiceControl<TStatus>('Retention change', {+ group: RETENTION,+ description:+ 'State of the last retention change. Anything other than the empty value adds the status row and, while pending, blocks the save button. Self-hosted only: cloud has no retention controls to report on, so nothing moves while License is `cloud`.',+ options: RETENTION_STATUSES,+ value: '',+ }),+ workspaceUrl: choiceControl<WorkspaceUrl>('Workspace URL', {+ group: DOMAIN,+ description:+ 'Whether a custom subdomain is set. Cloud admins only: self-hosted has no domain card.',+ options: WORKSPACE_URLS,+ value: 'custom',+ }),+ },+ handlers: (values, response) => [+ // One path, two signals: the type the page asks for is a query param.+ rest.get(+ 'http://localhost/api/v1/settings/ttl',+ response.json((req) =>+ req.url.searchParams.get('type') === 'traces'+ ? tracesRetentionResponse(values.retentionStatus, values.coldStorage)+ : metricsRetentionResponse(values.retentionStatus, values.coldStorage),+ ),+ ),++ rest.get(+ 'http://localhost/api/v2/settings/ttl',+ response.json(() =>+ logsRetentionResponse(values.retentionStatus, values.coldStorage),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/disks',+ response.json(() => disksResponse(values.coldStorage)),+ ),++ // The domain card is the shell of the page rather than its data, so it keeps+ // answering while the retention endpoints hang or fail.+ rest.get('http://localhost/api/v2/zeus/hosts', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(hostsResponse(values.workspaceUrl))),+ ),+ ],+ config: () => ({ route: ROUTES.SETTINGS }),+});diff --git a/frontend/src/pages/Settings/Workspace/stories/Workspace.stories.tsx b/frontend/src/pages/Settings/Workspace/stories/Workspace.stories.tsxnew file mode 100644index 0000000000..c0d12dbb29--- /dev/null+++ b/frontend/src/pages/Settings/Workspace/stories/Workspace.stories.tsx@@ -0,0 +1,74 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { workspaceMocks } from './Workspace.stories.mocks';++import SettingsPage from '../../Settings';++type WorkspaceArgs = PageStoryArgs<typeof workspaceMocks>;++const pageStory = storyMocks(workspaceMocks, { layout: 'app' });++/**+ * Retention per signal, cold storage, and the workspace's own URL.+ *+ * Route: `/settings`.+ */+const meta = {+ title: 'Pages/Settings/Workspace',+ tags: ['play'],+ component: SettingsPage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<WorkspaceArgs>;++export default meta;++type Story = StoryObj<WorkspaceArgs>;++/**+ * The workspace tab on cloud: the URL the workspace answers on, the license key,+ * and how long each signal is kept before it is dropped.+ */+export const Default: Story = {};++/**+ * The same tab on a self-hosted instance, where retention is the org's to change:+ * every signal gets a save button and a status row under it.+ */+export const SelfHosted: Story = {+ args: { license: 'enterprise', retentionStatus: 'success' },+};++/**+ * A retention change the instance has accepted but not finished applying, which+ * keeps the save button down until it lands.+ */+export const RetentionPending: Story = {+ args: { license: 'enterprise', retentionStatus: 'pending' },+};++/** An instance with no object storage attached: nothing can be moved to S3. */+export const NoColdStorage: Story = {+ args: { license: 'enterprise', coldStorage: false },+};++/**+ * The workspace URL menu, open: the hosts the workspace answers on, and which+ * 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');+ },+};diff --git a/frontend/src/pages/Settings/Workspace/stories/__story_mockdata__/workspace.ts b/frontend/src/pages/Settings/Workspace/stories/__story_mockdata__/workspace.tsnew file mode 100644index 0000000000..ac22e530ce--- /dev/null+++ b/frontend/src/pages/Settings/Workspace/stories/__story_mockdata__/workspace.ts@@ -0,0 +1,104 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { PayloadProps as DisksPayload } from 'types/api/disks/getDisks';+import type {+ PayloadPropsLogs,+ PayloadPropsMetrics,+ PayloadPropsTraces,+ TStatus,+} from 'types/api/settings/getRetention';++export const RETENTION_STATUSES: TStatus[] = [+ '',+ 'pending',+ 'success',+ 'failed',+];++const HOURS_IN_DAY = 24;++const RETAIN_DAYS = { metrics: 30, traces: 15, logs: 7 };+const MOVE_DAYS = { metrics: 15, traces: 7, logs: 3 };++/** What the status row reports as the pending target, not the current value. */+const EXPECTED_DAYS = { metrics: 90, traces: 45 };++const hours = (days: number): number => days * HOURS_IN_DAY;++export const disksResponse = (coldStorage: boolean): DisksPayload => [+ { name: 'default', type: 'local' },+ ...(coldStorage ? [{ name: 's3', type: 's3' }] : []),+];++export const metricsRetentionResponse = (+ status: TStatus,+ coldStorage: boolean,+): PayloadPropsMetrics => ({+ metrics_ttl_duration_hrs: hours(RETAIN_DAYS.metrics),+ metrics_move_ttl_duration_hrs: coldStorage ? hours(MOVE_DAYS.metrics) : -1,+ status,+ expected_metrics_ttl_duration_hrs: hours(EXPECTED_DAYS.metrics),+ expected_metrics_move_ttl_duration_hrs: coldStorage+ ? hours(MOVE_DAYS.metrics)+ : -1,+});++export const tracesRetentionResponse = (+ status: TStatus,+ coldStorage: boolean,+): PayloadPropsTraces => ({+ traces_ttl_duration_hrs: hours(RETAIN_DAYS.traces),+ traces_move_ttl_duration_hrs: coldStorage ? hours(MOVE_DAYS.traces) : -1,+ status,+ expected_traces_ttl_duration_hrs: hours(EXPECTED_DAYS.traces),+ expected_traces_move_ttl_duration_hrs: coldStorage+ ? hours(MOVE_DAYS.traces)+ : -1,+});++/** The logs endpoint answers in days, the other two in hours. */+export const logsRetentionResponse = (+ status: TStatus,+ coldStorage: boolean,+): PayloadPropsLogs => ({+ version: 'v2',+ default_ttl_days: RETAIN_DAYS.logs,+ cold_storage_ttl_days: coldStorage ? MOVE_DAYS.logs : -1,+ status,+});++const DEFAULT_HOST = {+ name: 'nightswatch',+ url: 'https://nightswatch.us.signoz.cloud',+ is_default: true,+};++const CUSTOM_HOST = {+ name: 'observability',+ url: 'https://observability.us.signoz.cloud',+ is_default: false,+};++export const WORKSPACE_URLS = ['default', 'custom'] as const;++export type WorkspaceUrl = (typeof WORKSPACE_URLS)[number];++/**+ * The non-default host is the custom domain: the card reads the workspace URL+ * off the first host that is not flagged as the default one.+ */+export const hostsResponse = (+ workspaceUrl: WorkspaceUrl,+): Record<string, unknown> => ({+ status: 'success',+ data: {+ name: DEFAULT_HOST.name,+ state: 'HEALTHY',+ tier: 'production',+ hosts:+ workspaceUrl === 'custom' ? [CUSTOM_HOST, DEFAULT_HOST] : [DEFAULT_HOST],+ },+});diff --git a/frontend/src/pages/Settings/stories/__story_mockdata__/roles.ts b/frontend/src/pages/Settings/stories/__story_mockdata__/roles.tsnew file mode 100644index 0000000000..a70ccd63b3--- /dev/null+++ b/frontend/src/pages/Settings/stories/__story_mockdata__/roles.ts@@ -0,0 +1,217 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ AuthtypesGettableRoleDTO,+ AuthtypesRoleDTO,+ AuthtypesTransactionGroupDTO,+ GetRole200,+ ListRoles200,+} from 'api/generated/services/sigNoz.schemas';+import {+ AuthtypesRelationDTO,+ CoretypesKindDTO,+ CoretypesTypeDTO,+} from 'api/generated/services/sigNoz.schemas';+import { RoleType } from 'types/roles';++export const CUSTOM_ROLE_MAX = 8;++/** The three the backend ships with every org, which the list groups on their own. */+const MANAGED_ROLES = [+ { name: 'admin', description: 'Full access to every resource in the org.' },+ {+ name: 'editor',+ description: 'Can create and change dashboards, alerts and views.',+ },+ {+ name: 'viewer',+ description: 'Read-only access to telemetry and saved work.',+ },+];++const CUSTOM_ROLES = [+ {+ name: 'oncall-responder',+ description: 'Reads telemetry and acknowledges alerts.',+ },+ {+ name: 'billing-owner',+ description: 'Manages the subscription and ingestion keys.',+ },+ {+ name: 'integration-bot',+ description: 'Writes pipelines from CI, reads nothing else.',+ },+ {+ name: 'dashboard-author',+ description: 'Builds dashboards over the shared metrics.',+ },+ {+ name: 'platform-sre',+ description: 'Runs the collectors and the ingestion limits.',+ },+ {+ name: 'support-engineer',+ description: 'Reads customer traces during an incident.',+ },+ {+ name: 'security-auditor',+ description: 'Reads audit logs and every role definition.',+ },+ {+ name: 'release-manager',+ description: 'Reads deploy dashboards and manages funnels.',+ },+];++const DAY = 24 * 60 * 60 * 1000;++/** Fixed epoch so a rerender does not move the "created" column. */+const CREATED_AT = Date.UTC(2026, 1, 14, 9, 30);++const timestamps = (+ index: number,+): Pick<AuthtypesGettableRoleDTO, 'createdAt' | 'updatedAt'> => ({+ createdAt: new Date(CREATED_AT - index * 3 * DAY).toISOString(),+ updatedAt: new Date(CREATED_AT - index * DAY).toISOString(),+});++export const CUSTOM_ROLE_ID = 'role-oncall-responder';+export const MANAGED_ROLE_ID = 'role-admin';++const roleId = (name: string): string => `role-${name}`;++const gettableRole = (+ seed: { name: string; description: string },+ type: RoleType,+ index: number,+): AuthtypesGettableRoleDTO => ({+ id: roleId(seed.name),+ name: seed.name,+ description: seed.description,+ orgId: 'story-org',+ type,+ ...timestamps(index),+});++export const rolesListResponse = (customRoles: number): ListRoles200 => ({+ status: 'success',+ data: [+ ...MANAGED_ROLES.map((seed, index) =>+ gettableRole(seed, RoleType.MANAGED, index),+ ),+ ...CUSTOM_ROLES.slice(0, customRoles).map((seed, index) =>+ gettableRole(seed, RoleType.CUSTOM, index + MANAGED_ROLES.length),+ ),+ ],+});++const objectGroup = (+ kind: CoretypesKindDTO,+ type: CoretypesTypeDTO,+ selectors: string[],+ relation: AuthtypesRelationDTO,+): AuthtypesTransactionGroupDTO => ({+ objectGroup: { resource: { kind, type }, selectors },+ relation,+});++const WILDCARD = ['*'];++/**+ * A grant wide enough that the overview shows all three scopes: whole-resource,+ * a named subset, and resources with nothing granted at all.+ */+const BROAD_GRANT: AuthtypesTransactionGroupDTO[] = [+ objectGroup(+ CoretypesKindDTO.logs,+ CoretypesTypeDTO.telemetryresource,+ WILDCARD,+ AuthtypesRelationDTO.read,+ ),+ objectGroup(+ CoretypesKindDTO.traces,+ CoretypesTypeDTO.telemetryresource,+ WILDCARD,+ AuthtypesRelationDTO.read,+ ),+ objectGroup(+ CoretypesKindDTO.metrics,+ CoretypesTypeDTO.telemetryresource,+ ['attribute/service.name/checkout', 'attribute/service.name/payments'],+ AuthtypesRelationDTO.read,+ ),+ objectGroup(+ CoretypesKindDTO.serviceaccount,+ CoretypesTypeDTO.serviceaccount,+ WILDCARD,+ AuthtypesRelationDTO.list,+ ),+ objectGroup(+ CoretypesKindDTO['factor-api-key'],+ CoretypesTypeDTO.metaresource,+ ['key-ci-pipeline'],+ AuthtypesRelationDTO.read,+ ),+ objectGroup(+ CoretypesKindDTO.role,+ CoretypesTypeDTO.role,+ WILDCARD,+ AuthtypesRelationDTO.list,+ ),+];++/** The narrow end: one resource, one verb, one named object. */+const NARROW_GRANT: AuthtypesTransactionGroupDTO[] = [+ objectGroup(+ CoretypesKindDTO.logs,+ CoretypesTypeDTO.telemetryresource,+ ['attribute/deployment.environment/production'],+ AuthtypesRelationDTO.read,+ ),+];++export const PERMISSION_BREADTHS = ['broad', 'narrow', 'none'] as const;++export type PermissionBreadth = (typeof PERMISSION_BREADTHS)[number];++const grantFor = (+ breadth: PermissionBreadth,+): AuthtypesTransactionGroupDTO[] => {+ switch (breadth) {+ case 'narrow':+ return NARROW_GRANT;++ case 'none':+ return [];++ default:+ return BROAD_GRANT;+ }+};++export const roleResponse = (+ id: string,+ type: RoleType,+ breadth: PermissionBreadth,+): GetRole200 => {+ const name = id.replace(/^role-/, '');+ const seed =+ [...MANAGED_ROLES, ...CUSTOM_ROLES].find((entry) => entry.name === name) ??+ CUSTOM_ROLES[0];++ const role: AuthtypesRoleDTO = {+ id,+ name,+ description: seed.description,+ orgId: 'story-org',+ type,+ transactionGroups: grantFor(breadth),+ ...timestamps(0),+ };++ return { status: 'success', data: role };+};diff --git a/frontend/src/pages/SignUp/stories/SignUp.stories.mocks.tsx b/frontend/src/pages/SignUp/stories/SignUp.stories.mocks.tsxnew file mode 100644index 0000000000..aa4b9dbe5f--- /dev/null+++ b/frontend/src/pages/SignUp/stories/SignUp.stories.mocks.tsx@@ -0,0 +1,48 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { StatusCodes } from 'http-status-codes';+import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import {+ REGISTRATIONS,+ registerRejectedResponse,+ registerResponse,+ type Registration,+} from './__story_mockdata__/signUp';++const ACCOUNT = 'Sign up · account';++export const signUpMocks = defineStoryMocks({+ controls: {+ registration: choiceControl<Registration>('Registration', {+ group: ACCOUNT,+ description:+ 'What `POST /register` answers when the form is submitted. `accepted` signs the new admin straight in, which leaves the page.',+ options: REGISTRATIONS,+ value: 'accepted',+ }),+ },+ handlers: (values) => [+ rest.post('http://localhost/api/v1/register', (_req, res, ctx) =>+ values.registration === 'accepted'+ ? res(ctx.json(registerResponse()))+ : res(+ ctx.status(StatusCodes.CONFLICT),+ ctx.json(registerRejectedResponse()),+ ),+ ),+ ],+ config: () => ({+ route: ROUTES.SIGN_UP,+ // Signing up is what a browser with no session does, so the shell has no+ // side nav, top nav or banners to draw.+ appContext: { isLoggedIn: false },+ }),+});diff --git a/frontend/src/pages/SignUp/stories/SignUp.stories.tsx b/frontend/src/pages/SignUp/stories/SignUp.stories.tsxnew file mode 100644index 0000000000..c4c267f091--- /dev/null+++ b/frontend/src/pages/SignUp/stories/SignUp.stories.tsx@@ -0,0 +1,79 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { SIGNUP_EMAIL, SIGNUP_PASSWORD } from './__story_mockdata__/signUp';+import SignUp from '../SignUp';+import { signUpMocks } from './SignUp.stories.mocks';++type SignUpArgs = PageStoryArgs<typeof signUpMocks>;++const pageStory = storyMocks(signUpMocks, { layout: 'app' });++/**+ * The sign up form, including the first run of a self hosted instance.+ *+ * Route: `/signup`.+ */+const meta = {+ title: 'Pages/Auth/Sign Up',+ tags: ['play'],+ component: SignUp,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<SignUpArgs>;++export default meta;++type Story = StoryObj<SignUpArgs>;++const fillForm = async (+ canvasElement: HTMLElement,+ confirmPassword: string,+): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.type(+ canvas.getByPlaceholderText(/[email protected]/i),+ SIGNUP_EMAIL,+ );+ await userEvent.type(+ canvas.getByPlaceholderText(/enter new password/i),+ SIGNUP_PASSWORD,+ );+ await userEvent.type(+ canvas.getByPlaceholderText(/confirm your new password/i),+ confirmPassword,+ );+ // The mismatch message is what the blur is for, not the typing.+ await userEvent.tab();+};++/** The first account on a fresh install, which is always an admin. */+export const Default: Story = {};++/** The confirmation typed differently, caught when the field is left. */+export const PasswordMismatch: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await fillForm(canvasElement, 'something-else');+ await within(canvasElement).findByText(/passwords don't match/i);+ },+};++/** A workspace that already has its admin, which is what setup being done looks like. */+export const RegistrationRejected: Story = {+ args: { registration: 'rejected' },+ // The deliberate 409 is the state under test.+ parameters: { allowConsoleErrors: true },+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await fillForm(canvasElement, SIGNUP_PASSWORD);+ await userEvent.click(+ canvas.getByRole('button', { name: /access my workspace/i }),+ );+ await canvas.findByText(/already_exists/i);+ },+};diff --git a/frontend/src/pages/SignUp/stories/__story_mockdata__/signUp.ts b/frontend/src/pages/SignUp/stories/__story_mockdata__/signUp.tsnew file mode 100644index 0000000000..534dca9b83--- /dev/null+++ b/frontend/src/pages/SignUp/stories/__story_mockdata__/signUp.ts@@ -0,0 +1,41 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { ErrorV2Resp } from 'types/api';+import type { SignupResponse } from 'types/api/v1/register/post';+import type { ROLES } from 'types/roles';++export const SIGNUP_EMAIL = '[email protected]';++export const SIGNUP_PASSWORD = 'correct-horse-battery';++export const REGISTRATIONS = ['accepted', 'rejected'] as const;++export type Registration = (typeof REGISTRATIONS)[number];++export const registerResponse = (): {+ status: string;+ data: SignupResponse;+} => ({+ status: 'success',+ data: {+ id: 'user-anna',+ orgId: 'org-signoz',+ email: SIGNUP_EMAIL,+ displayName: 'Anna',+ role: 'ADMIN' as ROLES,+ createdAt: 0,+ },+});++/** What the backend rejects a first account with once setup has already run. */+export const registerRejectedResponse = (): ErrorV2Resp => ({+ error: {+ code: 'already_exists',+ message: 'This workspace already has an admin. Ask them for an invite link.',+ url: 'https://signoz.io/docs/userguide/manage-users/',+ errors: [],+ },+});diff --git a/frontend/src/pages/Status/stories/Status.stories.mocks.tsx b/frontend/src/pages/Status/stories/Status.stories.mocks.tsxnew file mode 100644index 0000000000..df21278231--- /dev/null+++ b/frontend/src/pages/Status/stories/Status.stories.mocks.tsx@@ -0,0 +1,69 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { StatusCodes } from 'http-status-codes';+import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++const VERSION = 'Status · version';++const VERSION_STATES = ['up-to-date', 'outdated', 'unavailable'] as const;++type VersionState = (typeof VERSION_STATES)[number];++const CURRENT = 'v0.104.2';++const LATEST_RELEASE_URL =+ 'https://api.github.com/repos/signoz/signoz/releases/latest';++/**+ * The page reads both versions off redux, which the app layout fills from these+ * two calls: seeding the store instead would be overwritten as soon as they+ * answer.+ */+export const statusMocks = defineStoryMocks({+ controls: {+ version: choiceControl<VersionState>('Version', {+ group: VERSION,+ description:+ 'How the running build compares to the newest release. `unavailable` fails both calls, which is what the page falls back to N/A for.',+ options: VERSION_STATES,+ value: 'up-to-date',+ }),+ },+ handlers: (values) => {+ const latest = values.version === 'outdated' ? 'v0.110.0' : CURRENT;++ if (values.version === 'unavailable') {+ return [+ rest.get('http://localhost/api/v1/version', (_req, res, ctx) =>+ res(ctx.status(StatusCodes.INTERNAL_SERVER_ERROR)),+ ),+ rest.get(LATEST_RELEASE_URL, (_req, res, ctx) =>+ res(ctx.status(StatusCodes.SERVICE_UNAVAILABLE)),+ ),+ ];+ }++ return [+ rest.get('http://localhost/api/v1/version', (_req, res, ctx) =>+ res(ctx.json({ version: CURRENT, ee: 'Y', setupCompleted: true })),+ ),+ rest.get(LATEST_RELEASE_URL, (_req, res, ctx) =>+ res(+ ctx.json({+ tag_name: latest,+ name: latest,+ html_url: `https://github.com/SigNoz/signoz/releases/tag/${latest}`,+ }),+ ),+ ),+ ];+ },+ config: () => ({ route: ROUTES.VERSION }),+});diff --git a/frontend/src/pages/Status/stories/Status.stories.tsx b/frontend/src/pages/Status/stories/Status.stories.tsxnew file mode 100644index 0000000000..4ecd0069b8--- /dev/null+++ b/frontend/src/pages/Status/stories/Status.stories.tsx@@ -0,0 +1,42 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import Status from '../index';+import { statusMocks } from './Status.stories.mocks';++type StatusArgs = PageStoryArgs<typeof statusMocks>;++const pageStory = storyMocks(statusMocks, { layout: 'app' });++/**+ * Version and update state of the running instance.+ *+ * Route: `/status`.+ */+const meta = {+ title: 'Pages/System/Status',+ component: Status,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<StatusArgs>;++export default meta;++type Story = StoryObj<StatusArgs>;++/** The build this deployment runs, against the newest one released. */+export const Default: Story = {};++/** A deployment a few releases behind, which is what the upgrade link is for. */+export const UpdateAvailable: Story = {+ args: { version: 'outdated' },+};++/** Neither version could be read, so the page says so rather than guessing. */+export const VersionUnavailable: Story = {+ args: { version: 'unavailable' },+ // The deliberate 500 and 503 are the state under test.+ parameters: { allowConsoleErrors: true },+};diff --git a/frontend/src/pages/Support/stories/Support.stories.mocks.tsx b/frontend/src/pages/Support/stories/Support.stories.mocks.tsxnew file mode 100644index 0000000000..16027f6bbb--- /dev/null+++ b/frontend/src/pages/Support/stories/Support.stories.mocks.tsx@@ -0,0 +1,61 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { FeatureKeys } from 'constants/features';+import ROUTES from 'constants/routes';+import { rest } from 'msw';+import type { IAppContext } from 'providers/App/types';+import { createAppContextMock } from 'tests/fixtures/appContextMock';+import { USER_ROLES } from 'types/roles';++import { toggleControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++const CHANNELS = 'Support · channels';++const { featureFlags: baseFeatureFlags, trialInfo } = createAppContextMock(+ USER_ROLES.ADMIN,+);++/**+ * Chat is the one channel the plan gates: without premium support the card+ * opens the add-a-card modal instead of the widget.+ */+const supportContext = (premium: boolean): Partial<IAppContext> => ({+ featureFlags: (baseFeatureFlags ?? []).map((flag) =>+ flag.name === FeatureKeys.PREMIUM_SUPPORT+ ? { ...flag, active: premium }+ : flag,+ ),+ trialInfo: trialInfo && {+ ...trialInfo,+ trialConvertedToSubscription: premium,+ },+});++export const supportMocks = defineStoryMocks({+ controls: {+ premiumSupport: toggleControl('Premium support', {+ group: CHANNELS,+ description:+ 'Whether the plan carries chat support. Without it the chat card asks for a card first.',+ value: true,+ }),+ },+ handlers: () => [+ rest.post('http://localhost/api/v1/subscriptions', (_req, res, ctx) =>+ res(+ ctx.json({+ status: 'success',+ data: { redirectURL: 'https://billing.signoz.io/checkout' },+ }),+ ),+ ),+ ],+ config: (values) => ({+ route: ROUTES.SUPPORT,+ appContext: supportContext(values.premiumSupport),+ }),+});diff --git a/frontend/src/pages/Support/stories/Support.stories.tsx b/frontend/src/pages/Support/stories/Support.stories.tsxnew file mode 100644index 0000000000..d7171f899a--- /dev/null+++ b/frontend/src/pages/Support/stories/Support.stories.tsx@@ -0,0 +1,46 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import Support from '../Support';+import { supportMocks } from './Support.stories.mocks';++type SupportArgs = PageStoryArgs<typeof supportMocks>;++const pageStory = storyMocks(supportMocks, { layout: 'app' });++/**+ * The support page: the channels the plan includes, and the way to premium+ * support.+ *+ * Route: `/support`.+ */+const meta = {+ title: 'Pages/System/Support',+ tags: ['play'],+ component: Support,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<SupportArgs>;++export default meta;++type Story = StoryObj<SupportArgs>;++/** Every way to reach the team or the community, in one place. */+export const Default: Story = {};++/** A plan without chat: the card asks for billing details before the widget. */+export const AddCreditCard: Story = {+ args: { premiumSupport: false },+ play: async ({ canvasElement }): Promise<void> => {+ const canvas = within(canvasElement);++ await userEvent.click(+ await canvas.findByRole('button', { name: /launch chat/i }),+ );+ await within(document.body).findByText(/add a credit card/i);+ },+};diff --git a/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.mocks.tsx b/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.mocks.tsxnew file mode 100644index 0000000000..6292f911cc--- /dev/null+++ b/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.mocks.tsx@@ -0,0 +1,261 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import set from 'api/browser/localstorage/set';+import {+ TelemetrytypesFieldContextDTO,+ TelemetrytypesSignalDTO,+} from 'api/generated/services/sigNoz.schemas';+import type { SpantypesPostableTraceAggregationsDTO } from 'api/generated/services/sigNoz.schemas';+import { LOCALSTORAGE } from 'constants/localStorage';+import { USER_PREFERENCES } from 'constants/userPreferences';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import {+ fieldKeysResponse,+ fieldValuesResponse,+} from '@/storybook/msw/__story_mockdata__/fields';+import {+ queryRangeV5RawResponse,+ queryRangeV5ScalarResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++import { SpanDetailVariant } from '../SpanDetailsPanel/constants';+import {+ focusSpanIndex,+ spanIdAt,+ spanLogRows,+ type SpanLogScope,+ spanMatchRows,+ spanPercentilesResponse,+ STORY_TRACE_ID,+ traceAggregationsResponse,+ traceDetailFieldKeys,+ traceDetailFieldValues,+ traceFlamegraphResponse,+ traceWaterfallResponse,+} from './__story_mockdata__/traceDetails';++const TRACE = 'Trace · trace';+const PANEL = 'Trace · span panel';++const PANEL_POSITIONS = [+ SpanDetailVariant.DOCKED_RIGHT,+ SpanDetailVariant.DOCKED,+ SpanDetailVariant.DIALOG,+] as const;++/**+ * The trace starts two minutes back, so the header's absolute times read as a+ * trace that just came in rather than one from the fixture's epoch.+ */+const TRACE_AGE_MS = 2 * 60 * 1000;++const traceStartOf = (): number => Date.now() - TRACE_AGE_MS;++const specOf = (+ body: QueryRangeRequestV5,+):+ | QueryRangeRequestV5['compositeQuery']['queries'][number]['spec']+ | undefined => body.compositeQuery?.queries?.[0]?.spec;++const signalOf = (body: QueryRangeRequestV5): string | undefined => {+ const spec = specOf(body);++ return spec && 'signal' in spec ? spec.signal : undefined;+};++/** Which of the panel's three log queries this is, read off its filter. */+const spanLogScopeOf = (body: QueryRangeRequestV5): SpanLogScope => {+ const spec = specOf(body);+ const expression =+ (spec && 'filter' in spec ? spec.filter?.expression : '') ?? '';++ if (expression.includes('span_id')) {+ return 'span';+ }++ if (expression.includes('id <')) {+ return 'before';+ }++ return expression.includes('id >') ? 'after' : 'trace';+};++export const traceDetailsMocks = defineStoryMocks({+ controls: {+ spans: countControl('Spans', {+ group: TRACE,+ description:+ 'Spans the trace has, spread over a balanced tree. At 0 the page shows the "we cannot show this trace" state.',+ value: 15,+ max: 60,+ }),+ errors: toggleControl('Failing spans', {+ group: TRACE,+ description:+ '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,+ }),+ missingSpans: toggleControl('Missing spans', {+ group: TRACE,+ description:+ 'Sets hasMissingSpans, the banner for a trace whose spans have not all arrived.',+ value: false,+ }),+ spanPanel: toggleControl('Span details panel', {+ group: PANEL,+ description:+ 'Opens the panel on the first failing span, the way a spanId in the URL does.',+ value: true,+ }),+ panelPosition: choiceControl<SpanDetailVariant>('Panel position', {+ group: PANEL,+ description:+ 'Where the panel docks. The page remembers this in localStorage, so the control seeds it before the page mounts.',+ options: PANEL_POSITIONS,+ value: SpanDetailVariant.DOCKED_RIGHT,+ }),+ spanLogs: countControl('Span log rows', {+ group: PANEL,+ description: 'Rows the Logs tab of the panel answers with.',+ value: 8,+ max: 20,+ }),+ },+ handlers: (values, response) => {+ const trace = {+ spans: values.spans,+ errors: values.errors,+ traceStart: traceStartOf(),+ };++ return [+ rest.post(+ 'http://localhost/api/v4/traces/:traceId/waterfall',+ response.json(() =>+ traceWaterfallResponse({ ...trace, missingSpans: values.missingSpans }),+ ),+ ),++ rest.post(+ 'http://localhost/api/v3/traces/:traceId/flamegraph',+ response.json(() => traceFlamegraphResponse(trace)),+ ),++ rest.post(+ 'http://localhost/api/v1/traces/:traceId/aggregations',+ response.json(async (req) => {+ const body = (await req.json()) as SpantypesPostableTraceAggregationsDTO;++ return traceAggregationsResponse(body.aggregations ?? [], trace);+ }),+ ),++ rest.post(+ 'http://localhost/api/v1/span_percentile',+ response.json(spanPercentilesResponse),+ ),++ // The percentile panel reads the attributes it compares on straight from+ // the preference, and dereferences its value without a guard.+ rest.get(+ 'http://localhost/api/v1/user/preferences/:name',+ response.json((req) => ({+ status: 'success',+ data: {+ name: String(req.params.name),+ description: 'storybook',+ valueType: 'array',+ defaultValue: [],+ allowedValues: [],+ allowedScopes: ['user'],+ value:+ String(req.params.name) ===+ USER_PREFERENCES.SPAN_PERCENTILE_RESOURCE_ATTRIBUTES+ ? ['service.name', 'deployment.environment']+ : [],+ },+ })),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ fieldKeysResponse(+ traceDetailFieldKeys(req.url.searchParams.get('searchText')),+ {+ signal: TelemetrytypesSignalDTO.traces,+ fieldContext: TelemetrytypesFieldContextDTO.span,+ },+ ),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(+ traceDetailFieldValues(req.url.searchParams.get('name')),+ ),+ ),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const { start, end, requestType } = body;++ if (requestType === 'raw') {+ return queryRangeV5RawResponse(+ signalOf(body) === 'logs'+ ? spanLogRows(values.spanLogs, trace, spanLogScopeOf(body))+ : spanMatchRows(trace),+ );+ }++ if (requestType === 'scalar') {+ return queryRangeV5ScalarResponse(values.spans);+ }++ return queryRangeV5TimeSeriesResponse([+ {+ queryName: 'A',+ series: [+ {+ labels: [],+ values: timeSeriesPoints({+ start,+ end,+ base: 64,+ amplitude: 22,+ }),+ },+ ],+ },+ ]);+ }),+ ),+ ];+ },+ config: (values) => ({+ route: values.spanPanel+ ? `/trace/${STORY_TRACE_ID}?spanId=${spanIdAt(focusSpanIndex(values.spans))}`+ : `/trace/${STORY_TRACE_ID}`,+ }),+ effect: (values) => {+ set(LOCALSTORAGE.TRACE_DETAILS_SPAN_DETAILS_POSITION, values.panelPosition);+ },+});diff --git a/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.tsx b/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.tsxnew file mode 100644index 0000000000..28451cd091--- /dev/null+++ b/frontend/src/pages/TraceDetailsV3/stories/TraceDetailsV3.stories.tsx@@ -0,0 +1,174 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';+import { fireEvent, screen, userEvent, waitFor, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { traceDetailsMocks } from './TraceDetailsV3.stories.mocks';+import TraceDetailsV3 from '../index';++type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;++const pageStory = storyMocks(traceDetailsMocks, { layout: 'app' });++/**+ * One trace: the waterfall, the flamegraph, and the span panel with its+ * attributes, events and logs. A trace with spans the backend never received shows+ * them as gaps.+ *+ * Route: `/trace/:id`.+ */+const meta = {+ title: 'Pages/Traces/Trace Details',+ tags: ['play'],+ component: TraceDetailsV3,+ // The page reads the trace id out of the pathname, so it renders under its+ // own route rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route path={ROUTES.TRACE_DETAIL} component={TraceDetailsV3} />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<TraceDetailsArgs>;++export default meta;++type Story = StoryObj<TraceDetailsArgs>;++/**+ * A checkout trace whose payment call failed: the flamegraph and the waterfall+ * over its spans, and the span details panel open on the span that errored,+ * with its percentile, attributes, events and logs.+ */+export const Default: Story = {};++/**+ * A deep trace: sixty spans over six levels, which is where the waterfall+ * scrolls and the flamegraph starts packing rows.+ */+export const LargeTrace: Story = {+ args: { spans: 60 },+};++/**+ * A trace the backend has nothing for, which is what a link to a trace past its+ * retention window opens.+ */+export const NoTrace: Story = {+ args: { spans: 0 },+};++/** The waterfall and the flamegraph mid-fetch, shell included. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** The waterfall renders once the trace resolves, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++/**+ * Turns on Highlight errors, which writes `has_error = true` into the filter and+ * expands the bar to show it.+ */+const highlightErrors = async (canvasElement: HTMLElement): Promise<void> => {+ const toggle = await within(canvasElement).findByTestId(+ 'highlight-errors-toggle',+ undefined,+ untilLoaded,+ );++ await userEvent.click(within(toggle).getByRole('switch'));+};++/**+ * Every tooltip the trace carries, held open at once: the panel's dock modes and+ * its span metadata, the trace metadata over the header, Analytics, the search+ * pill's own popover over the filter the Highlight errors switch wrote, the copy+ * and funnel actions on every span row, the card a hovered row raises, and the+ * details behind a hovered event dot.+ */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }): Promise<void> => {+ await highlightErrors(canvasElement);++ // Collapsing puts the filter back behind the pill, which is where it carries+ // its popover. Neither expanded action carries a label of its own, so the+ // row is located by its container and the collapse is its last button.+ const actions = await waitFor(() => {+ const found = canvasElement.querySelector<HTMLElement>(+ '[class*="expandedActions"]',+ );++ if (!found) {+ throw new Error('Filter row is not expanded');+ }++ return found;+ }, untilLoaded);+ const expandedActions = within(actions).getAllByRole('button');++ await userEvent.click(expandedActions[expandedActions.length - 1]);++ // `userEvent.hover` tracks the pointer, so hovering the dot would fire the+ // row's mouseleave and drop the hover card. `mouseOver` is what React reads+ // to synthesise mouseenter, and it leaves the previous target alone, so both+ // stay open. The dot has no test id.+ const [row] = await within(canvasElement).findAllByTestId(+ /^cell-0-/,+ undefined,+ untilLoaded,+ );++ await fireEvent.mouseOver(row);++ await waitFor(async () => {+ const dot = canvasElement.querySelector('[class*="eventDot"]');++ if (!dot) {+ throw new Error('no event dot rendered');+ }++ await fireEvent.mouseOver(dot);+ }, untilLoaded);++ // The dot opens its card on a 200ms timer rather than on the event itself.+ await waitFor(() => {+ if (!document.querySelector('[class*="popover"]')) {+ throw new Error('event popover did not open');+ }+ }, untilLoaded);+ },+};++/**+ * The filter bar expanded, where the query editor stands in for the pill and the+ * header's own actions: the clear and collapse buttons beside it, clear being+ * there because Highlight errors has written a filter to clear.+ */+export const TooltipsInFilterBar: Story = {+ args: { tooltipsOpen: true },+ play: async ({ canvasElement }): Promise<void> => {+ await highlightErrors(canvasElement);+ },+};++/**+ * The trace options menu, open off the header: the trace details toggle, preview+ * fields, and the Colour by submenu over the fields the spans can be coloured+ * on.+ */+export const TraceOptionsMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByRole(+ 'button',+ { name: 'Trace options' },+ untilLoaded,+ ),+ );+ await screen.findByText('Preview fields');+ },+};diff --git a/frontend/src/pages/TraceDetailsV3/stories/__story_mockdata__/traceDetails.ts b/frontend/src/pages/TraceDetailsV3/stories/__story_mockdata__/traceDetails.tsnew file mode 100644index 0000000000..7d2b6a0b15--- /dev/null+++ b/frontend/src/pages/TraceDetailsV3/stories/__story_mockdata__/traceDetails.ts@@ -0,0 +1,527 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ GetFlamegraph200,+ GetTraceAggregations200,+ GetWaterfallV4200,+ SpantypesFlamegraphSpanDTO,+ SpantypesSpanAggregationDTO,+ SpantypesWaterfallSpanDTO,+} from 'api/generated/services/sigNoz.schemas';+import { SpantypesSpanAggregationTypeDTO } from 'api/generated/services/sigNoz.schemas';+import type { GetSpanPercentilesResponseDataProps } from 'types/api/trace/getSpanPercentiles';+import type { RawRow } from 'types/api/v5/queryRange';++export const STORY_TRACE_ID = '4f2a6cbb9d3e17c0084bd42f9e7a1b33';++interface SpanTemplate {+ service: string;+ name: string;+ kind: string;+ failing?: boolean;+ attributes: Record<string, string | number | boolean>;+}++/** Walked in order, so the tree keeps the same services at the same depths. */+const SPAN_TEMPLATES: SpanTemplate[] = [+ {+ service: 'frontend',+ name: 'HTTP GET /checkout',+ kind: 'Server',+ attributes: {+ 'http.method': 'GET',+ 'http.url': 'https://shop.signoz.io/checkout',+ 'http.status_code': 200,+ 'net.peer.name': 'shop.signoz.io',+ },+ },+ {+ service: 'checkout',+ name: 'POST /api/orders',+ kind: 'Server',+ attributes: {+ 'http.method': 'POST',+ 'http.route': '/api/orders',+ 'http.status_code': 201,+ 'messaging.system': 'kafka',+ },+ },+ {+ service: 'cart',+ name: 'GET /cart/items',+ kind: 'Client',+ attributes: {+ 'http.method': 'GET',+ 'http.route': '/cart/items',+ 'http.status_code': 200,+ },+ },+ {+ service: 'payments',+ name: 'charge.authorize',+ kind: 'Client',+ failing: true,+ attributes: {+ 'rpc.system': 'grpc',+ 'rpc.method': 'Authorize',+ 'payment.provider': 'stripe',+ 'http.status_code': 503,+ },+ },+ {+ service: 'inventory',+ name: 'reserve.stock',+ kind: 'Client',+ attributes: { 'rpc.system': 'grpc', 'rpc.method': 'ReserveStock' },+ },+ {+ service: 'redis',+ name: 'GET cart:42',+ kind: 'Client',+ attributes: { 'db.system': 'redis', 'db.operation': 'GET' },+ },+ {+ service: 'postgres',+ name: 'SELECT orders',+ kind: 'Client',+ attributes: {+ 'db.system': 'postgresql',+ 'db.name': 'orders',+ 'db.operation': 'SELECT',+ 'db.statement': 'SELECT * FROM orders WHERE id = $1',+ },+ },+ {+ service: 'shipping',+ name: 'GET /rates',+ kind: 'Client',+ failing: true,+ attributes: {+ 'http.method': 'GET',+ 'http.route': '/rates',+ 'http.status_code': 500,+ },+ },+ {+ service: 'notifications',+ name: 'email.send',+ kind: 'Producer',+ attributes: {+ 'messaging.system': 'ses',+ 'messaging.destination': 'order-confirmation',+ },+ },+ {+ service: 'auth',+ name: 'POST /token',+ kind: 'Client',+ attributes: { 'http.method': 'POST', 'http.route': '/token' },+ },+];++const TRACE_SERVICES = [+ ...new Set(SPAN_TEMPLATES.map(({ service }) => service)),+];++const ROOT_DURATION_MS = 1840;++/** A balanced binary tree, which gives every level more than one span. */+const parentIndexOf = (index: number): number => Math.floor((index - 1) / 2);++interface BuiltSpan {+ index: number;+ spanId: string;+ parentSpanId: string;+ level: number;+ startMs: number;+ durationMs: number;+ hasChildren: boolean;+ subTreeNodeCount: number;+ hasError: boolean;+ template: SpanTemplate;+}++interface TraceOptions {+ spans: number;+ errors: boolean;+ /** Epoch milliseconds the root span starts at. */+ traceStart: number;+}++export const spanIdAt = (index: number): string =>+ `b17e${index.toString(16).padStart(12, '0')}`;++/**+ * The span the story opens the panel on: the first failing one, so its events+ * and error styling are on screen, and the root when nothing fails.+ */+export const focusSpanIndex = (spans: number): number => {+ const failing = SPAN_TEMPLATES.findIndex(({ failing }) => failing);++ return failing >= 0 && failing < spans ? failing : 0;+};++const buildSpans = ({+ spans,+ errors,+ traceStart,+}: TraceOptions): BuiltSpan[] => {+ const built: BuiltSpan[] = [];++ for (let index = 0; index < spans; index += 1) {+ const template = SPAN_TEMPLATES[index % SPAN_TEMPLATES.length];+ const parent = index === 0 ? undefined : built[parentIndexOf(index)];+ // Children fit inside their parent's window, second child after the first,+ // so no span outlives its parent and no two siblings overlap.+ const durationMs = parent+ ? Math.max(parent.durationMs * 0.42, 4)+ : ROOT_DURATION_MS;+ const offsetShare = index === 0 ? 0 : 0.05 + ((index - 1) % 2) * 0.5;++ built.push({+ index,+ spanId: spanIdAt(index),+ parentSpanId: parent ? parent.spanId : '',+ level: parent ? parent.level + 1 : 0,+ startMs: parent+ ? parent.startMs + parent.durationMs * offsetShare+ : traceStart,+ durationMs,+ hasChildren: false,+ subTreeNodeCount: 0,+ hasError: errors && !!template.failing,+ template,+ });+ }++ built.forEach((span) => {+ if (span.index === 0) {+ return;+ }++ const parent = built[parentIndexOf(span.index)];+ parent.hasChildren = true;+ });++ // Descendant counts, cheapest bottom-up: a child is always built after its+ // parent, so one reverse pass is enough.+ [...built].reverse().forEach((span) => {+ if (span.index === 0) {+ return;+ }++ const parent = built[parentIndexOf(span.index)];+ parent.subTreeNodeCount += span.subTreeNodeCount + 1;+ });++ return built;+};++const eventsOf = (span: BuiltSpan): SpantypesWaterfallSpanDTO['events'] =>+ span.hasError+ ? [+ {+ name: 'exception',+ timeUnixNano: Math.round(+ (span.startMs + span.durationMs * 0.8) * 1_000_000,+ ),+ attributeMap: {+ 'exception.type': 'UpstreamUnavailable',+ 'exception.message': `${span.template.service} refused the request`,+ },+ isError: true,+ },+ ]+ : [];++const resourceOf = (span: BuiltSpan): Record<string, string> => ({+ 'service.name': span.template.service,+ 'deployment.environment': 'production',+ 'host.name': `ip-10-0-1-${20 + (span.index % 6)}`,+ 'os.type': 'linux',+});++const waterfallSpan = (span: BuiltSpan): SpantypesWaterfallSpanDTO => ({+ 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: span.hasError ? 2 : 1,+ status_code_string: span.hasError ? 'Error' : 'Ok',+ status_message: span.hasError ? 'upstream unavailable' : '',+ response_status_code: span.hasError ? '503' : '200',+ has_children: span.hasChildren,+ sub_tree_node_count: span.subTreeNodeCount,+ level: span.level,+ attributes: span.template.attributes,+ resource: resourceOf(span),+ events: eventsOf(span),+ references: [],+ http_method: String(span.template.attributes['http.method'] ?? ''),+ http_url: String(span.template.attributes['http.url'] ?? ''),+ db_name: String(span.template.attributes['db.name'] ?? ''),+ db_operation: String(span.template.attributes['db.operation'] ?? ''),+ is_remote: span.level === 0 ? 'true' : 'false',+ flags: 0,+ trace_state: '',+});++/**+ * `totalSpansCount` equals what the response carries, which is what puts the+ * waterfall in its all-loaded mode: every parent expands and no further window+ * is fetched.+ */+export const traceWaterfallResponse = (+ options: TraceOptions & { missingSpans: boolean },+): GetWaterfallV4200 => {+ const spans = buildSpans(options);+ const root = spans[0];++ return {+ status: 'success',+ data: {+ spans: spans.map(waterfallSpan),+ hasMissingSpans: options.missingSpans,+ hasMore: false,+ uncollapsedSpans: spans+ .filter(({ hasChildren }) => hasChildren)+ .map(({ spanId }) => spanId),+ startTimestampMillis: Math.round(options.traceStart),+ endTimestampMillis: Math.round(options.traceStart + ROOT_DURATION_MS),+ totalSpansCount: spans.length,+ totalErrorSpansCount: spans.filter(({ hasError }) => hasError).length,+ rootServiceName: root?.template.service ?? '',+ rootServiceEntryPoint: root?.template.name ?? '',+ },+ };+};++const flamegraphSpan = (span: BuiltSpan): SpantypesFlamegraphSpanDTO => ({+ spanId: span.spanId,+ parentSpanId: span.parentSpanId,+ name: span.template.name,+ timestamp: Math.round(span.startMs),+ durationNano: Math.round(span.durationMs * 1_000_000),+ hasError: span.hasError,+ level: span.level,+ attributes: span.template.attributes,+ resource: resourceOf(span),+ event: [],+});++/** The flamegraph asks for its spans grouped by level, one array per level. */+export const traceFlamegraphResponse = (+ options: TraceOptions,+): GetFlamegraph200 => {+ const spans = buildSpans(options);+ const depth = Math.max(...spans.map(({ level }) => level), 0);++ return {+ status: 'success',+ data: {+ spans: Array.from({ length: depth + 1 }, (_, level) =>+ spans.filter((span) => span.level === level).map(flamegraphSpan),+ ),+ hasMore: false,+ startTimestampMillis: Math.round(options.traceStart),+ endTimestampMillis: Math.round(options.traceStart + ROOT_DURATION_MS),+ },+ };+};++const aggregationValue = (+ aggregation: SpantypesSpanAggregationTypeDTO,+ spans: BuiltSpan[],+ fieldName: string,+): Record<string, number> => {+ const totals = new Map<string, number>();++ spans.forEach((span) => {+ const key =+ fieldName === 'name'+ ? span.template.name+ : (resourceOf(span)[fieldName] ?? span.template.service);+ const previous = totals.get(key) ?? 0;++ totals.set(+ key,+ aggregation === SpantypesSpanAggregationTypeDTO.span_count+ ? previous + 1+ : previous + span.durationMs * 1_000_000,+ );+ });++ if (+ aggregation !== SpantypesSpanAggregationTypeDTO.execution_time_percentage+ ) {+ return Object.fromEntries(totals);+ }++ const sum = [...totals.values()].reduce((total, value) => total + value, 0);++ return Object.fromEntries(+ [...totals].map(([key, value]) => [+ key,+ sum === 0 ? 0 : Math.round((value / sum) * 1000) / 10,+ ]),+ );+};++/** Answers per requested aggregation, keyed by the field the panel colours by. */+export const traceAggregationsResponse = (+ requested: SpantypesSpanAggregationDTO[],+ options: TraceOptions,+): GetTraceAggregations200 => {+ const spans = buildSpans(options);++ return {+ status: 'success',+ data: {+ aggregations: requested.map(({ aggregation, field }) => ({+ aggregation,+ field,+ value: aggregationValue(aggregation, spans, field.name),+ })),+ },+ };+};++export const spanPercentilesResponse = (): {+ status: string;+ data: GetSpanPercentilesResponseDataProps;+} => ({+ status: 'success',+ data: {+ percentiles: {+ p50: 412_000_000,+ p90: 1_024_000_000,+ p95: 1_380_000_000,+ p99: 1_910_000_000,+ },+ position: {+ percentile: 92,+ description: 'Slower than 92% of spans with the same name',+ },+ },+});++const LOG_BODIES = [+ 'authorizing charge for order 4821',+ 'upstream stripe call returned 503',+ 'retrying charge in 200ms',+ 'reserving stock for 3 line items',+ 'cart 42 loaded from cache',+ 'order 4821 written to orders',+];++/**+ * Which of the panel's log queries is asking: the span's own logs, the context+ * above or below them, or the whole trace when the span has none.+ */+const SPAN_LOG_SCOPES = ['span', 'before', 'after', 'trace'] as const;++export type SpanLogScope = (typeof SPAN_LOG_SCOPES)[number];++const SCOPE_OFFSET_MS: Record<SpanLogScope, number> = {+ before: -ROOT_DURATION_MS,+ span: 0,+ after: ROOT_DURATION_MS,+ trace: 0,+};++/**+ * The Logs tab of the span panel, answered on the raw query_range shape. Each+ * scope answers with its own ids and window, so the panel stacks the span's+ * logs between their context instead of showing one set three times. The rows+ * sit inside the trace's window rather than the request's, because the span-log+ * queries ask in microseconds while a row's timestamp is a date.+ */+export const spanLogRows = (+ count: number,+ options: TraceOptions,+ scope: SpanLogScope,+): RawRow[] => {+ const step = ROOT_DURATION_MS / Math.max(count, 1);+ const spans = buildSpans(options);+ const focus = spans[focusSpanIndex(options.spans)];++ return Array.from({ length: count }, (_, index) => {+ const at = options.traceStart + SCOPE_OFFSET_MS[scope] + index * step;+ const span = scope === 'span' ? focus : spans[index % spans.length];++ return {+ timestamp: new Date(at).toISOString(),+ data: {+ body: LOG_BODIES[index % LOG_BODIES.length],+ id: `storybook-${scope}-log-${index + 1}`,+ trace_id: STORY_TRACE_ID,+ span_id: span?.spanId ?? '',+ severity_text: index % 4 === 1 ? 'ERROR' : 'INFO',+ severity_number: index % 4 === 1 ? 17 : 9,+ attributes_string: {+ 'service.name': span?.template.service ?? '',+ },+ resources_string: {+ 'service.name': span?.template.service ?? '',+ },+ scope_name: '',+ },+ };+ });+};++/**+ * Span ids for the header's span search. Every span answers, so a filter typed+ * in the story highlights the whole trace rather than nothing.+ */+export const spanMatchRows = (options: TraceOptions): RawRow[] =>+ buildSpans(options).map((span) => ({+ timestamp: new Date(span.startMs).toISOString(),+ data: {+ span_id: span.spanId,+ spanID: span.spanId,+ timestamp: Math.round(span.startMs * 1_000_000),+ },+ }));++const TRACE_FIELD_KEYS = [+ 'service.name',+ 'name',+ 'duration_nano',+ 'http.method',+ 'http.status_code',+ 'db.system',+ 'rpc.method',+ 'deployment.environment',+ 'host.name',+ 'status_code_string',+];++export const traceDetailFieldKeys = (searchText: string | null): string[] => {+ const search = (searchText ?? '').toLowerCase();++ return search+ ? TRACE_FIELD_KEYS.filter((key) => key.toLowerCase().includes(search))+ : TRACE_FIELD_KEYS;+};++const FIELD_VALUES: Record<string, string[]> = {+ 'service.name': TRACE_SERVICES,+ name: SPAN_TEMPLATES.map(({ name }) => name),+ 'http.method': ['GET', 'POST'],+ 'http.status_code': ['200', '201', '500', '503'],+ 'db.system': ['postgresql', 'redis'],+ 'rpc.method': ['Authorize', 'ReserveStock'],+ 'deployment.environment': ['production', 'staging'],+ status_code_string: ['Ok', 'Error'],+};++export const traceDetailFieldValues = (name: string | null): string[] =>+ FIELD_VALUES[name ?? ''] ?? [];diff --git a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsx b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsxindex c71877d195..e953b0beed 100644--- a/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsx+++ b/frontend/src/pages/TracesFunnelDetails/components/FunnelConfiguration/FunnelStep.tsx@@ -213,7 +213,7 @@ function FunnelStep({<div className="latency-pointer__label">Latency pointer</div>{hasEditPermission ? (<DropdownMenuSimple menu={{ items: latencyPointerItems }}>- <Space>+ <Space data-testid={`funnel-step-latency-pointer-${index}`}>{LatencyPointers.find((option) => option.value === stepData.latency_pointer,diff --git a/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.mocks.tsx b/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.mocks.tsxnew file mode 100644index 0000000000..2e732cc084--- /dev/null+++ b/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.mocks.tsx@@ -0,0 +1,138 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { choiceControl, countControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import {+ attributeKeysResponse,+ attributeValuesResponse,+} from '@/storybook/msw/__story_mockdata__/attributes';++import {+ FUNNEL_ID,+ FUNNEL_STEP_MAX,+ funnelErrorTracesResponse,+ funnelOverviewResponse,+ funnelResponse,+ funnelSlowTracesResponse,+ funnelStepsOverviewResponse,+ funnelStepsResponse,+ funnelValidateResponse,+} from './__story_mockdata__/tracesFunnelDetails';++const FUNNEL = 'Funnel · shape';+const TRACES = 'Funnel · traces';++const DROP_OFF = ['none', 'mild', 'severe'] as const;++type DropOff = (typeof DROP_OFF)[number];++/** Share of the previous step's spans that reach the next one. */+const CONVERSION: Record<DropOff, number> = {+ none: 1,+ mild: 0.86,+ severe: 0.42,+};++const ENTERED = 24_000;++const STEP_FILTER_KEYS = [+ 'service.name',+ 'name',+ 'http.status_code',+ 'deployment.environment',+ 'hasError',+];++const STEP_FILTER_VALUES: Record<string, string[]> = {+ 'service.name': ['frontend', 'checkout', 'payment', 'shipping'],+ name: ['POST /api/checkout', 'payment.authorize', 'shipping.quote'],+ 'http.status_code': ['200', '400', '500'],+ 'deployment.environment': ['production', 'staging'],+ hasError: ['true', 'false'],+};++export const tracesFunnelDetailsMocks = defineStoryMocks({+ controls: {+ steps: countControl('Steps', {+ group: FUNNEL,+ description:+ 'Stages the funnel is built from, which is what the configuration list and the graph draw.',+ value: 4,+ max: FUNNEL_STEP_MAX,+ }),+ dropOff: choiceControl<DropOff>('Drop-off', {+ group: FUNNEL,+ description:+ 'How much of the traffic is lost between steps, which the conversion rate and the graph follow.',+ options: DROP_OFF,+ value: 'mild',+ }),+ traces: countControl('Trace rows', {+ group: TRACES,+ description:+ 'Rows the slowest-traces and errored-traces tables under the graph carry.',+ value: 5,+ max: 10,+ }),+ },+ handlers: (values, response) => {+ const conversion = CONVERSION[values.dropOff];++ return [+ rest.get(+ `http://localhost/api/v1/trace-funnels/${FUNNEL_ID}`,+ response.json(() => funnelResponse(values.steps)),+ ),+ rest.post(+ 'http://localhost/api/v1/trace-funnels/analytics/validate',+ response.json(() => funnelValidateResponse(values.traces)),+ ),+ rest.post(+ 'http://localhost/api/v1/trace-funnels/analytics/steps',+ response.json(() => funnelStepsResponse(values.steps, ENTERED, conversion)),+ ),+ rest.post(+ 'http://localhost/api/v1/trace-funnels/analytics/steps/overview',+ response.json(() => funnelStepsOverviewResponse(conversion)),+ ),+ rest.post(+ 'http://localhost/api/v1/trace-funnels/analytics/overview',+ response.json(() =>+ funnelOverviewResponse(ENTERED, conversion, values.steps),+ ),+ ),+ rest.post(+ 'http://localhost/api/v1/trace-funnels/analytics/slow-traces',+ response.json(() => funnelSlowTracesResponse(values.traces)),+ ),+ rest.post(+ 'http://localhost/api/v1/trace-funnels/analytics/error-traces',+ response.json(() => funnelErrorTracesResponse(values.traces)),+ ),+ // The `Where` box on every step is the trace query builder, which reads+ // its suggestions as soon as the step renders.+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_keys',+ response.json(() => attributeKeysResponse(STEP_FILTER_KEYS)),+ ),+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ attributeValuesResponse(+ STEP_FILTER_VALUES[req.url.searchParams.get('attributeKey') ?? ''] ?? [],+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ ),+ ];+ },+ config: () => ({+ route: ROUTES.TRACES_FUNNELS_DETAIL.replace(':funnelId', FUNNEL_ID),+ }),+});diff --git a/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.tsx b/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.tsxnew file mode 100644index 0000000000..b4757bb5ae--- /dev/null+++ b/frontend/src/pages/TracesFunnelDetails/stories/TracesFunnelDetails.stories.tsx@@ -0,0 +1,70 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { Route } from 'react-router-dom';+import ROUTES from 'constants/routes';+import { screen, userEvent, within } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import TracesFunnelDetails from '../index';+import { tracesFunnelDetailsMocks } from './TracesFunnelDetails.stories.mocks';++type TracesFunnelDetailsArgs = PageStoryArgs<typeof tracesFunnelDetailsMocks>;++const pageStory = storyMocks(tracesFunnelDetailsMocks, { layout: 'app' });++/**+ * One trace funnel: conversion and drop off per step, with the slow and erroring+ * traces behind each.+ *+ * Route: `/traces/funnels/:funnelId`.+ */+const meta = {+ title: 'Pages/Traces/Funnel Details',+ tags: ['play'],+ component: TracesFunnelDetails,+ // The funnel id is in the pathname, so the page renders under its own route+ // rather than being mounted on its own.+ render: (): JSX.Element => (+ <Route path={ROUTES.TRACES_FUNNELS_DETAIL} component={TracesFunnelDetails} />+ ),+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<TracesFunnelDetailsArgs>;++export default meta;++type Story = StoryObj<TracesFunnelDetailsArgs>;++/**+ * A four-step checkout funnel: the steps on the left, and the conversion,+ * timing and the traces behind each transition on the right.+ */+export const Default: Story = {};++/** Most of the traffic lost at the first hop, which is what the funnel is for. */+export const SevereDropOff: Story = {+ args: { dropOff: 'severe' },+};++/** A funnel someone has started but only defined the entry step of. */+export const SingleStep: Story = {+ args: { steps: 1 },+};++/**+ * The latency pointer menu on the first step, open over the funnel+ * configuration: which end of a step's span the funnel times from.+ */+export const LatencyPointerMenu: Story = {+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ await within(canvasElement).findByTestId(+ 'funnel-step-latency-pointer-0',+ {},+ { timeout: 10000 },+ ),+ );+ await screen.findByRole('menu');+ },+};diff --git a/frontend/src/pages/TracesFunnelDetails/stories/__story_mockdata__/tracesFunnelDetails.ts b/frontend/src/pages/TracesFunnelDetails/stories/__story_mockdata__/tracesFunnelDetails.tsnew file mode 100644index 0000000000..83b63d8f2d--- /dev/null+++ b/frontend/src/pages/TracesFunnelDetails/stories/__story_mockdata__/tracesFunnelDetails.ts@@ -0,0 +1,204 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ ErrorTraceData,+ FunnelOverviewResponse,+ FunnelStepsResponse,+ SlowTraceData,+} from 'api/traceFunnels';+import type { FunnelData, FunnelStepData } from 'types/api/traceFunnels';++export const FUNNEL_ID = 'funnel-checkout';++const AT = 1_766_000_000_000;++interface StepSeed {+ service: string;+ span: string;+ name: string;+ description: string;+}++const STEPS: StepSeed[] = [+ {+ service: 'frontend',+ span: 'POST /api/checkout',+ name: 'Checkout opened',+ description: 'The request that starts a checkout.',+ },+ {+ service: 'payment',+ span: 'payment.authorize',+ name: 'Payment authorised',+ description: 'The upstream authorisation call.',+ },+ {+ service: 'shipping',+ span: 'shipping.quote',+ name: 'Shipping quoted',+ description: 'The quote returned to the buyer.',+ },+ {+ service: 'checkout',+ span: 'order.persist',+ name: 'Order placed',+ description: 'The order written to the database.',+ },+];++export const FUNNEL_STEP_MAX = STEPS.length;++const step = (seed: StepSeed, index: number): FunnelStepData => ({+ id: `step-${index + 1}`,+ step_order: index + 1,+ service_name: seed.service,+ span_name: seed.span,+ filters: { items: [], op: 'AND' },+ latency_pointer: 'start',+ latency_type: 'p99',+ has_errors: false,+ name: seed.name,+ description: seed.description,+});++export const funnelResponse = (+ steps: number,+): { status: string; data: FunnelData } => ({+ status: 'success',+ data: {+ funnel_id: FUNNEL_ID,+ funnel_name: 'Checkout conversion',+ description: 'Where a checkout drops off between the cart and the order.',+ created_at: AT,+ updated_at: AT,+ user_email: '[email protected]',+ steps: STEPS.slice(0, steps).map(step),+ },+});++const timestamp = (index: number): string =>+ new Date(AT + index * 60_000).toISOString();++/**+ * Conversion falls off step by step, which is the whole point of the funnel:+ * the drop is what the graph and the transition metrics are read from.+ */+const spansAtStep = (+ entered: number,+ index: number,+ conversion: number,+): number => Math.round(entered * conversion ** index);++export const funnelStepsResponse = (+ steps: number,+ entered: number,+ conversion: number,+): FunnelStepsResponse => ({+ status: 'success',+ data: [+ {+ timestamp: timestamp(0),+ data: Object.fromEntries(+ Array.from({ length: steps }, (_unused, index) => [+ [`total_s${index + 1}_spans`, spansAtStep(entered, index, conversion)],+ [+ `total_s${index + 1}_errored_spans`,+ Math.round(spansAtStep(entered, index, conversion) * 0.03),+ ],+ ]).flat() as Array<[string, number]>,+ ),+ },+ ],+});++export const funnelOverviewResponse = (+ entered: number,+ conversion: number,+ steps: number,+): FunnelOverviewResponse => ({+ status: 'success',+ data: [+ {+ timestamp: timestamp(0),+ data: {+ avg_duration: 1_840,+ avg_rate: 4.2,+ conversion_rate: Number((conversion ** (steps - 1) * 100).toFixed(2)),+ errors: Math.round(entered * 0.03),+ latency: 2_460,+ },+ },+ ],+});++/** The per-transition numbers, keyed the way the metrics list reads them. */+export const funnelStepsOverviewResponse = (+ conversion: number,+): {+ status: string;+ data: Array<{ timestamp: string; data: Record<string, number> }>;+} => ({+ status: 'success',+ data: [+ {+ timestamp: timestamp(0),+ data: {+ avg_duration: 640,+ avg_rate: 3.8,+ conversion_rate: Number((conversion * 100).toFixed(2)),+ errors: 42,+ latency: 910,+ },+ },+ ],+});++/** A 32-hex id, derived from the row so a refetch lists the same traces. */+const traceId = (seed: number, index: number): string => {+ const half = (offset: number): string =>+ ((seed * (index + 1 + offset) * 2_654_435_761) >>> 0)+ .toString(16)+ .padStart(8, '0');++ return `${half(0)}${half(7)}${half(13)}${half(29)}`;+};++const traceRows = (count: number, slow: boolean): SlowTraceData['data'] =>+ Array.from({ length: count }, (_unused, index) => ({+ timestamp: timestamp(index),+ data: {+ duration_ms: String(slow ? 4_800 - index * 260 : 1_200 - index * 90),+ span_count: 18 + index * 3,+ trace_id: traceId(slow ? 0x51ad : 0xe770, index),+ },+ }));++export const funnelSlowTracesResponse = (count: number): SlowTraceData => ({+ status: 'success',+ data: traceRows(count, true),+});++export const funnelErrorTracesResponse = (count: number): ErrorTraceData => ({+ status: 'success',+ data: traceRows(count, false),+});++/** Trace ids the step validation found, which is what turns the run button green. */+export const funnelValidateResponse = (+ count: number,+): {+ status: string;+ data: Array<{ timestamp: string; data: { trace_id: string } }> | null;+} => ({+ status: 'success',+ data:+ count === 0+ ? null+ : Array.from({ length: count }, (_unused, index) => ({+ timestamp: timestamp(index),+ data: { trace_id: traceId(0x7a11, index) },+ })),+});diff --git a/frontend/src/pages/TracesModulePage/stories/TracesModulePage.stories.mocks.tsx b/frontend/src/pages/TracesModulePage/stories/TracesModulePage.stories.mocks.tsxnew file mode 100644index 0000000000..c3762b69e5--- /dev/null+++ b/frontend/src/pages/TracesModulePage/stories/TracesModulePage.stories.mocks.tsx@@ -0,0 +1,239 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import { rest } from 'msw';+import { QueryParams } from 'constants/query';+import ROUTES from 'constants/routes';+import { ExplorerViews } from 'pages/LogsExplorer/utils';+import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';+import { explorerViewToPanelType } from 'utils/explorerUtils';++import {+ choiceControl,+ countControl,+ toggleControl,+} from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';+import { fieldValuesResponse } from '@/storybook/msw/__story_mockdata__/fields';+import {+ queryRangeV5RawResponse,+ queryRangeV5ScalarResponse,+ queryRangeV5TimeSeriesResponse,+ timeSeriesPoints,+} from '@/storybook/msw/__story_mockdata__/queryRange';++import {+ exportDashboardsResponse,+ savedTraceViewsResponse,+ traceAttributeValuesResponse,+ traceFieldKeysResponse,+ traceFieldValues,+ traceFunnelsResponse,+ traceQuickFiltersResponse,+ traceRootSpanRows,+ traceSpanRows,+ TRACES_EXPLORER_VIEWS,+ TRACES_TABS,+ type TracesTab,+} from './__story_mockdata__/traces';++const VIEW = 'Traces · view';+const LIST = 'Traces · list';+const FILTERS = 'Traces · filters';+const SAVED = 'Traces · saved';++interface RouteValues {+ tab: TracesTab;+ view: ExplorerViews;+}++const tracesRoute = ({ tab, view }: RouteValues): string => {+ if (tab === 'funnels') {+ return ROUTES.TRACES_FUNNELS;+ }++ if (tab === 'views') {+ return ROUTES.TRACES_SAVE_VIEWS;+ }++ const params = new URLSearchParams({+ [QueryParams.panelTypes]: JSON.stringify(explorerViewToPanelType[view]),+ [QueryParams.selectedExplorerView]: view,+ });++ return `${ROUTES.TRACES_EXPLORER}?${params.toString()}`;+};++interface RawQuerySpec {+ limit?: number;+ offset?: number;+}++const rawSpecOf = (body: QueryRangeRequestV5): RawQuerySpec => {+ const spec = body.compositeQuery?.queries?.[0]?.spec ?? {};++ return spec as RawQuerySpec;+};++export const tracesMocks = defineStoryMocks({+ controls: {+ tab: choiceControl<TracesTab>('Tab', {+ group: VIEW,+ description:+ 'The three pathnames the module tabs between. Clicking another tab leaves the story, so switch it here.',+ options: TRACES_TABS,+ value: 'explorer',+ }),+ view: choiceControl<ExplorerViews>('Explorer view', {+ group: VIEW,+ description:+ 'Which of the explorer views renders: spans, root spans, a chart or an aggregation table.',+ options: TRACES_EXPLORER_VIEWS,+ value: ExplorerViews.LIST,+ }),+ spans: countControl('Spans', {+ group: LIST,+ description:+ 'Spans the endpoint has, one root span per trace in the Trace view. The table asks for a page at a time, so a higher count paginates.',+ value: 24,+ max: 40,+ }),+ errors: toggleControl('Failing spans', {+ group: LIST,+ description:+ 'Answers 503 on the spans of the services that fail, which is what the status column and the error colouring read.',+ value: true,+ }),+ warning: toggleControl('Query warning', {+ group: LIST,+ description: 'Attaches a warning to the response, next to the toolbar.',+ value: false,+ }),+ quickFilters: countControl('Quick filters', {+ group: FILTERS,+ description:+ 'Filters the org has configured for traces. At 0 the panel shows its empty state.',+ value: 6,+ max: 8,+ }),+ savedViews: countControl('Saved views', {+ group: SAVED,+ description: 'Fills the views dropdown and the Views tab.',+ value: 4,+ max: 8,+ }),+ funnels: countControl('Funnels', {+ group: SAVED,+ description: 'Fills the Funnels tab.',+ value: 3,+ max: 6,+ }),+ },+ handlers: (values, response) => [+ rest.get(+ 'http://localhost/api/v2/quick_filters/:source',+ response.json(() => traceQuickFiltersResponse(values.quickFilters)),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/keys',+ response.json((req) =>+ traceFieldKeysResponse(req.url.searchParams.get('searchText')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/fields/values',+ response.json((req) =>+ fieldValuesResponse(traceFieldValues(req.url.searchParams.get('name'))),+ ),+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ response.json((req) =>+ traceAttributeValuesResponse(req.url.searchParams.get('attributeKey')),+ ),+ ),++ rest.get(+ 'http://localhost/api/v1/explorer/views',+ response.json(() => savedTraceViewsResponse(values.savedViews)),+ ),++ rest.get(+ 'http://localhost/api/v1/trace-funnels/list',+ response.json(() => traceFunnelsResponse(values.funnels)),+ ),++ rest.get(+ 'http://localhost/api/v2/users/me/dashboards',+ response.json(exportDashboardsResponse),+ ),++ rest.post(+ 'http://localhost/api/v5/query_range',+ response.json(async (req) => {+ const body = (await req.json()) as QueryRangeRequestV5;+ const { start, end, requestType } = body;+ const { limit = 10, offset = 0 } = rawSpecOf(body);++ const rows = {+ count: values.spans,+ offset,+ limit,+ start,+ end,+ errors: values.errors,+ };++ const warning = values.warning+ ? {+ code: 'storybook_warning',+ message: 'Query scanned more rows than the limit allows.',+ url: '',+ warnings: [],+ }+ : undefined;++ if (requestType === 'raw' || requestType === 'trace') {+ return queryRangeV5RawResponse(+ requestType === 'trace' ? traceRootSpanRows(rows) : traceSpanRows(rows),+ {+ type: requestType,+ hasMore: offset + limit < values.spans,+ warning,+ },+ );+ }++ if (requestType === 'scalar') {+ return queryRangeV5ScalarResponse(values.spans, 'A', { warning });+ }++ return queryRangeV5TimeSeriesResponse(+ [+ {+ queryName: 'A',+ series: [+ {+ labels: [],+ values: timeSeriesPoints({+ start,+ end,+ base: 420,+ amplitude: 120,+ }),+ },+ ],+ },+ ],+ { warning },+ );+ }),+ ),+ ],+ config: (values) => ({ route: tracesRoute(values) }),+});diff --git a/frontend/src/pages/TracesModulePage/stories/TracesModulePage.stories.tsx b/frontend/src/pages/TracesModulePage/stories/TracesModulePage.stories.tsxnew file mode 100644index 0000000000..8b991935a4--- /dev/null+++ b/frontend/src/pages/TracesModulePage/stories/TracesModulePage.stories.tsx@@ -0,0 +1,131 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { ExplorerViews } from 'pages/LogsExplorer/utils';+import { expect, screen, userEvent, waitFor } from 'storybook/test';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import { tracesMocks } from './TracesModulePage.stories.mocks';+import TracesModulePage from '../TracesModulePage';++type TracesArgs = PageStoryArgs<typeof tracesMocks>;++const pageStory = storyMocks(tracesMocks, { layout: 'app' });++/**+ * The traces explorer: the query builder, the span list and its detail drawer,+ * with saved views and funnels as tabs.+ *+ * Route: `/traces-explorer`.+ */+const meta = {+ title: 'Pages/Traces/Explorer',+ tags: ['play'],+ component: TracesModulePage,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<TracesArgs>;++export default meta;++/** The page fetches before it renders its filters, which outlasts the 1s default. */+const untilLoaded = { timeout: 15_000 };++type Story = StoryObj<TracesArgs>;++const openQuickFiltersSettings = async (): Promise<void> => {+ // The settings control renders disabled while its permission check is in+ // flight and is swapped for the enabled one once the check answers, so it is+ // looked up again on every attempt; a click on the disabled one is dropped in+ // silence.+ const control = await waitFor(() => {+ const settings = screen.getByTestId('settings-icon-container');++ expect(settings).toBeEnabled();++ return settings;+ }, untilLoaded);++ await userEvent.click(control);+ await screen.findByText('Edit quick filters');+};++/**+ * The Explorer tab on a full window of spans: the org's quick filters down the+ * left, the query builder and the view switcher above, and the list paging ten+ * spans at a time with the failing ones answering 503.+ */+export const Default: Story = {};++/**+ * The Trace view, which shows one row per trace: its root span, the root+ * duration and how many spans the trace has.+ */+export const RootSpans: Story = {+ args: { view: ExplorerViews.TRACE },+};++/** The charted view of the same trace query. */+export const Timeseries: Story = {+ args: { view: ExplorerViews.TIMESERIES },+};++/** The aggregation-table view of the same trace query. */+export const AggregationTable: Story = {+ args: { view: ExplorerViews.TABLE },+};++/** The Funnels tab, listing the funnels the workspace has saved. */+export const Funnels: Story = {+ args: { tab: 'funnels' },+};++/** The Views tab, where the saved views the explorer offers are managed. */+export const SavedViews: Story = {+ args: { tab: 'views' },+};++/**+ * 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+ * states.+ */+export const NoTraces: Story = {+ args: { spans: 0, quickFilters: 0, savedViews: 0, funnels: 0 },+};++/** The list mid-query, with the cancel action the toolbar offers while it runs. */+export const Loading: Story = {+ args: { dataState: 'loading' },+};++/** A query response carrying the backend's warning details. */+export const QueryWarning: Story = {+ args: { warning: true },+};++/** A failed explorer request. */+export const Failed: Story = {+ args: { dataState: 'error' },+ // The mocked request deliberately fails; the resulting console errors are the state under test.+ parameters: { allowConsoleErrors: true },+};++/** The editable quick-filter settings panel. */+export const QuickFiltersSettings: Story = {+ play: openQuickFiltersSettings,+};++/** Settings with an unsaved filter removal and the fixed action footer. */+export const QuickFiltersSettingsDirty: Story = {+ play: async (): Promise<void> => {+ await openQuickFiltersSettings();+ // One Remove per added filter; the first row's is the one clicked.+ const [removeFilter] = await screen.findAllByRole('button', {+ name: 'Remove',+ });++ await userEvent.click(removeFilter);+ await screen.findByRole('button', { name: 'Save changes' });+ },+};diff --git a/frontend/src/pages/TracesModulePage/stories/__story_mockdata__/traces.ts b/frontend/src/pages/TracesModulePage/stories/__story_mockdata__/traces.tsnew file mode 100644index 0000000000..79019d8fc6--- /dev/null+++ b/frontend/src/pages/TracesModulePage/stories/__story_mockdata__/traces.ts@@ -0,0 +1,375 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ QuickfiltertypesSourceDTO,+ TelemetrytypesFieldContextDTO,+ TelemetrytypesFieldDataTypeDTO,+ TelemetrytypesSignalDTO,+} from 'api/generated/services/sigNoz.schemas';+import type {+ GetQuickFilters200,+ TelemetrytypesTelemetryFieldKeyDTO,+} from 'api/generated/services/sigNoz.schemas';+import { explorerView } from 'mocks-server/__mockdata__/explorer_views';+import { ExplorerViews } from 'pages/LogsExplorer/utils';+import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';+import type { FunnelData } from 'types/api/traceFunnels';+import type { RawRow } from 'types/api/v5/queryRange';++import { fieldKeysResponse } from '@/storybook/msw/__story_mockdata__/fields';+import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';++export const TRACES_TABS = ['explorer', 'funnels', 'views'] as const;++export type TracesTab = (typeof TRACES_TABS)[number];++export const TRACES_EXPLORER_VIEWS = [+ ExplorerViews.LIST,+ ExplorerViews.TRACE,+ ExplorerViews.TIMESERIES,+ ExplorerViews.TABLE,+] as const;++interface SpanShape {+ service: string;+ operation: string;+ method: string;+ durationMs: number;+ failing: boolean;+}++/** Ordered so any slice keeps a spread of services, methods and durations. */+const SPANS: SpanShape[] = [+ {+ service: 'frontend',+ operation: 'HTTP GET /checkout',+ method: 'GET',+ durationMs: 1840,+ failing: false,+ },+ {+ service: 'checkout',+ operation: 'POST /api/orders',+ method: 'POST',+ durationMs: 1215,+ failing: true,+ },+ {+ service: 'payments',+ operation: 'charge.authorize',+ method: 'POST',+ durationMs: 964,+ failing: false,+ },+ {+ service: 'cart',+ operation: 'HTTP GET /cart/items',+ method: 'GET',+ durationMs: 612,+ failing: false,+ },+ {+ service: 'inventory',+ operation: 'reserve.stock',+ method: 'POST',+ durationMs: 488,+ failing: true,+ },+ {+ service: 'shipping',+ operation: 'HTTP GET /rates',+ method: 'GET',+ durationMs: 331,+ failing: false,+ },+ {+ service: 'notifications',+ operation: 'email.send',+ method: 'POST',+ durationMs: 214,+ failing: false,+ },+ {+ service: 'auth',+ operation: 'HTTP POST /token',+ method: 'POST',+ durationMs: 96,+ failing: false,+ },+];++const TRACE_SERVICE_NAMES = SPANS.map(({ service }) => service);++const hex = (prefix: string, index: number): string =>+ `${prefix}${index.toString(16).padStart(4, '0')}`;++const traceIdAt = (index: number): string => hex('4f2a6cbb9d3e17', index);++const spanIdAt = (index: number): string => hex('a71c3e', index);++interface SpanRowsOptions {+ /** Rows the endpoint has, which pagination walks through. */+ count: number;+ offset: number;+ limit: number;+ /** Request window in epoch milliseconds. */+ start: number;+ end: number;+ errors: boolean;+}++const rowWindow = ({+ count,+ offset,+ limit,+}: Pick<SpanRowsOptions, 'count' | 'offset' | 'limit'>): number[] => {+ const first = Math.min(offset, count);+ const last = Math.min(offset + limit, count);++ return Array.from({ length: Math.max(last - first, 0) }, (_, i) => first + i);+};++/** Newest first, which is the order the list asks for. */+const timestampAt = (index: number, start: number, end: number): string => {+ const step = (end - start) / 64;++ return new Date(end - index * step).toISOString();+};++export const traceSpanRows = ({+ count,+ offset,+ limit,+ start,+ end,+ errors,+}: SpanRowsOptions): RawRow[] =>+ rowWindow({ count, offset, limit }).map((index) => {+ const span = SPANS[index % SPANS.length];+ const hasError = errors && span.failing;++ return {+ timestamp: timestampAt(index, start, end),+ data: {+ 'service.name': span.service,+ name: span.operation,+ duration_nano: span.durationMs * 1_000_000,+ http_method: span.method,+ response_status_code: hasError ? '503' : '200',+ status_code_string: hasError ? 'Error' : 'Ok',+ has_error: hasError,+ trace_id: traceIdAt(index),+ span_id: spanIdAt(index),+ },+ };+ });++/** The Trace view lists root spans, with the span count of the whole trace. */+export const traceRootSpanRows = (options: SpanRowsOptions): RawRow[] =>+ traceSpanRows(options).map((row, index) => ({+ ...row,+ data: {+ ...row.data,+ span_count: 6 + ((index * 7) % 34),+ },+ }));++const { resource, attribute } = TelemetrytypesFieldContextDTO;+const { string: stringType, bool } = TelemetrytypesFieldDataTypeDTO;++const QUICK_FILTERS: TelemetrytypesTelemetryFieldKeyDTO[] = [+ { name: 'service.name', fieldDataType: stringType, fieldContext: resource },+ { name: 'name', fieldDataType: stringType, fieldContext: attribute },+ { name: 'has_error', fieldDataType: bool, fieldContext: attribute },+ { name: 'http_method', fieldDataType: stringType, fieldContext: attribute },+ {+ name: 'response_status_code',+ fieldDataType: stringType,+ fieldContext: attribute,+ },+ {+ name: 'deployment.environment',+ fieldDataType: stringType,+ fieldContext: resource,+ },+ { name: 'kind_string', fieldDataType: stringType, fieldContext: attribute },+ { name: 'rpc.method', fieldDataType: stringType, fieldContext: attribute },+];++export const traceQuickFiltersResponse = (count: number): GetQuickFilters200 =>+ quickFiltersResponse(+ QuickfiltertypesSourceDTO.traces,+ QUICK_FILTERS.slice(0, count),+ );++const FIELD_KEYS = [+ 'service.name',+ 'name',+ 'duration_nano',+ 'http_method',+ 'http_url',+ 'response_status_code',+ 'status_code_string',+ 'kind_string',+ 'has_error',+ 'timestamp',+ 'deployment.environment',+ 'rpc.method',+ 'db.system',+];++/**+ * `/fields/keys` is asked once per column the options menu resolves and once+ * per keystroke in the query builder, both with a `searchText`, so the answer+ * filters the catalogue rather than always returning it whole.+ */+export const traceFieldKeys = (searchText: string | null): string[] => {+ const search = (searchText ?? '').toLowerCase();++ return search+ ? FIELD_KEYS.filter((key) => key.toLowerCase().includes(search))+ : FIELD_KEYS;+};++const RESOURCE_KEYS = ['service.name', 'deployment.environment'];++/**+ * Resource and span keys come back from one call, each under its own context,+ * so the query builder groups the suggestions the way it does against a real+ * backend.+ */+export const traceFieldKeysResponse = (+ searchText: string | null,+): ReturnType<typeof fieldKeysResponse> => {+ const names = traceFieldKeys(searchText);+ const context = (name: string): TelemetrytypesFieldContextDTO =>+ RESOURCE_KEYS.includes(name)+ ? TelemetrytypesFieldContextDTO.resource+ : TelemetrytypesFieldContextDTO.span;++ const byContext = [+ TelemetrytypesFieldContextDTO.resource,+ TelemetrytypesFieldContextDTO.span,+ ].map((fieldContext) =>+ fieldKeysResponse(+ names.filter((name) => context(name) === fieldContext),+ { signal: TelemetrytypesSignalDTO.traces, fieldContext },+ ),+ );++ return {+ status: 'success',+ data: {+ complete: true,+ keys: Object.assign({}, ...byContext.map(({ data }) => data?.keys)),+ },+ };+};++const FIELD_VALUES: Record<string, string[]> = {+ 'service.name': TRACE_SERVICE_NAMES,+ name: SPANS.map(({ operation }) => operation),+ http_method: ['GET', 'POST', 'PUT', 'DELETE'],+ response_status_code: ['200', '201', '400', '404', '500', '503'],+ status_code_string: ['Ok', 'Error', 'Unset'],+ kind_string: ['Server', 'Client', 'Internal', 'Producer', 'Consumer'],+ has_error: ['true', 'false'],+ 'deployment.environment': ['production', 'staging'],+ 'rpc.method': ['ListOrders', 'GetOrder', 'CreateOrder'],+ 'db.system': ['postgresql', 'redis', 'mysql'],+};++export const traceFieldValues = (name: string | null): string[] =>+ FIELD_VALUES[name ?? ''] ?? [];++/**+ * The quick-filter checkboxes read values off the v3 autocomplete endpoint+ * rather than `/fields/values`, so both answer from the same catalogue.+ */+export const traceAttributeValuesResponse = (+ attributeKey: string | null,+): { status: string; data: IAttributeValuesResponse } => ({+ status: 'success',+ data: {+ stringAttributeValues: traceFieldValues(attributeKey),+ numberAttributeValues: null,+ boolAttributeValues: null,+ },+});++const VIEW_NAMES = [+ 'Failing checkouts',+ 'Slow payment spans',+ 'Cart p99 over 1s',+ 'gRPC errors by env',+ 'Redis calls over 200ms',+ 'Auth token latency',+ 'Shipping rate lookups',+ 'Notification retries',+];++export const savedTraceViewsResponse = (+ count: number,+): { status: string; data: unknown[] } => ({+ status: 'success',+ data: Array.from(+ { length: Math.min(count, VIEW_NAMES.length) },+ (_, index) => ({+ ...explorerView.data[0],+ id: `storybook-traces-view-${index + 1}`,+ name: VIEW_NAMES[index],+ sourcePage: 'traces',+ tags: ['traces'],+ }),+ ),+});++const FUNNEL_NAMES = [+ 'Checkout conversion',+ 'Signup to first order',+ 'Cart abandonment',+ 'Payment retry path',+ 'Search to product view',+ 'Refund request',+];++/** `updated_at` descends because that is the order the funnels list sorts on. */+export const traceFunnelsResponse = (+ count: number,+): { status: string; data: FunnelData[] } => ({+ status: 'success',+ data: Array.from(+ { length: Math.min(count, FUNNEL_NAMES.length) },+ (_, index) => ({+ funnel_id: `storybook-funnel-${index + 1}`,+ funnel_name: FUNNEL_NAMES[index],+ created_at: Date.UTC(2026, 6, 4 + index),+ updated_at: Date.UTC(2026, 7, 20 - index),+ user_email: '[email protected]',+ description: '',+ steps: [],+ }),+ ),+});++const DASHBOARD_NAMES = [+ 'Traces overview',+ 'Checkout funnel health',+ 'Service latency',+ 'Error budget',+];++export const exportDashboardsResponse = (): Record<string, unknown> => ({+ status: 'success',+ data: {+ dashboards: DASHBOARD_NAMES.map((name, index) => ({+ id: `storybook-dashboard-${index + 1}`,+ name,+ spec: { display: { name } },+ tags: ['traces'],+ })),+ },+});diff --git a/frontend/src/pages/UnAuthorized/stories/UnAuthorized.stories.mocks.tsx b/frontend/src/pages/UnAuthorized/stories/UnAuthorized.stories.mocks.tsxnew file mode 100644index 0000000000..f846f0f042--- /dev/null+++ b/frontend/src/pages/UnAuthorized/stories/UnAuthorized.stories.mocks.tsx@@ -0,0 +1,17 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';++import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++/**+ * The page calls nothing: what it says is decided by the role, which the Access+ * control already owns.+ */+export const unAuthorizedMocks = defineStoryMocks({+ controls: {},+ config: () => ({ route: ROUTES.UN_AUTHORIZED }),+});diff --git a/frontend/src/pages/UnAuthorized/stories/UnAuthorized.stories.tsx b/frontend/src/pages/UnAuthorized/stories/UnAuthorized.stories.tsxnew file mode 100644index 0000000000..dd0e14704f--- /dev/null+++ b/frontend/src/pages/UnAuthorized/stories/UnAuthorized.stories.tsx@@ -0,0 +1,40 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import UnAuthorized from '../index';+import { unAuthorizedMocks } from './UnAuthorized.stories.mocks';++type UnAuthorizedArgs = PageStoryArgs<typeof unAuthorizedMocks>;++const pageStory = storyMocks(unAuthorizedMocks, { layout: 'app' });++/**+ * What a route the user's role cannot open shows.+ *+ * Route: `/un-authorized`.+ */+const meta = {+ title: 'Pages/System/Unauthorized',+ component: UnAuthorized,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<UnAuthorizedArgs>;++export default meta;++type Story = StoryObj<UnAuthorizedArgs>;++/** Where a route guard sends someone whose grant does not cover the page. */+export const Default: Story = {+ args: { access: 'viewer' },+};++/**+ * The same wall with no role derived at all, which is what a grant covering+ * nothing yields: the page offers support instead of an administrator.+ */+export const Anonymous: Story = {+ args: { access: 'deny-all' },+};diff --git a/frontend/src/pages/WorkspaceAccessRestricted/stories/WorkspaceAccessRestricted.stories.mocks.tsx b/frontend/src/pages/WorkspaceAccessRestricted/stories/WorkspaceAccessRestricted.stories.mocks.tsxnew file mode 100644index 0000000000..7861940482--- /dev/null+++ b/frontend/src/pages/WorkspaceAccessRestricted/stories/WorkspaceAccessRestricted.stories.mocks.tsx@@ -0,0 +1,39 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { LicenseState } from 'types/api/licensesV3/getActive';++import { choiceControl } from '@/storybook/controls/controls';+import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import { licenseInState } from '../../WorkspaceLocked/stories/__story_mockdata__/workspaceStates';++const LICENSE = 'Workspace · license';++/** The three states that shut the workspace, each with its own sentence. */+const RESTRICTED_STATES = [+ LicenseState.TERMINATED,+ LicenseState.EXPIRED,+ LicenseState.CANCELLED,+] as const;++type RestrictedState = (typeof RESTRICTED_STATES)[number];++export const workspaceAccessRestrictedMocks = defineStoryMocks({+ controls: {+ state: choiceControl<RestrictedState>('License state', {+ group: LICENSE,+ description:+ 'Why access was cut, which is the whole difference on the page.',+ options: RESTRICTED_STATES,+ value: LicenseState.TERMINATED,+ }),+ },+ config: (values) => ({+ route: ROUTES.WORKSPACE_ACCESS_RESTRICTED,+ appContext: licenseInState(values.state),+ }),+});diff --git a/frontend/src/pages/WorkspaceAccessRestricted/stories/WorkspaceAccessRestricted.stories.tsx b/frontend/src/pages/WorkspaceAccessRestricted/stories/WorkspaceAccessRestricted.stories.tsxnew file mode 100644index 0000000000..54ce4428ae--- /dev/null+++ b/frontend/src/pages/WorkspaceAccessRestricted/stories/WorkspaceAccessRestricted.stories.tsx@@ -0,0 +1,38 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { LicenseState } from 'types/api/licensesV3/getActive';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import WorkspaceAccessRestricted from '../WorkspaceAccessRestricted';+import { workspaceAccessRestrictedMocks } from './WorkspaceAccessRestricted.stories.mocks';++type WorkspaceAccessRestrictedArgs = PageStoryArgs<+ typeof workspaceAccessRestrictedMocks+>;++const pageStory = storyMocks(workspaceAccessRestrictedMocks, { layout: 'app' });++/**+ * A cloud workspace the user cannot enter yet, in the state the control picks.+ *+ * Route: `/workspace-access-restricted`.+ */+const meta = {+ title: 'Pages/System/Workspace Access Restricted',+ component: WorkspaceAccessRestricted,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<WorkspaceAccessRestrictedArgs>;++export default meta;++type Story = StoryObj<WorkspaceAccessRestrictedArgs>;++/** A licence that was terminated, which needs a new deployment to undo. */+export const Default: Story = {};++/** A licence that simply ran out, which support can renew. */+export const Expired: Story = {+ args: { state: LicenseState.EXPIRED },+};diff --git a/frontend/src/pages/WorkspaceLocked/stories/WorkspaceLocked.stories.mocks.tsx b/frontend/src/pages/WorkspaceLocked/stories/WorkspaceLocked.stories.mocks.tsxnew file mode 100644index 0000000000..c8a07f5b9e--- /dev/null+++ b/frontend/src/pages/WorkspaceLocked/stories/WorkspaceLocked.stories.mocks.tsx@@ -0,0 +1,35 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';++import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import { blockedTrial } from './__story_mockdata__/workspaceStates';++/**+ * The trial's own dates are what the page counts down from, so they are pinned+ * rather than read off the clock and the copy stays the same on every run.+ */+const BLOCKED_AT = 1_766_000_000;++export const workspaceLockedMocks = defineStoryMocks({+ controls: {},+ handlers: () => [+ rest.post('http://localhost/api/v1/subscriptions', (_req, res, ctx) =>+ res(+ ctx.json({+ status: 'success',+ data: { redirectURL: 'https://billing.signoz.io/checkout' },+ }),+ ),+ ),+ ],+ config: () => ({+ route: ROUTES.WORKSPACE_LOCKED,+ appContext: blockedTrial(BLOCKED_AT),+ }),+});diff --git a/frontend/src/pages/WorkspaceLocked/stories/WorkspaceLocked.stories.tsx b/frontend/src/pages/WorkspaceLocked/stories/WorkspaceLocked.stories.tsxnew file mode 100644index 0000000000..bee6e9539b--- /dev/null+++ b/frontend/src/pages/WorkspaceLocked/stories/WorkspaceLocked.stories.tsx@@ -0,0 +1,39 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import WorkspaceLocked from '../index';+import { workspaceLockedMocks } from './WorkspaceLocked.stories.mocks';++type WorkspaceLockedArgs = PageStoryArgs<typeof workspaceLockedMocks>;++const pageStory = storyMocks(workspaceLockedMocks, { layout: 'app' });++/**+ * A workspace locked for non payment: what an admin sees, with checkout, and what+ * everyone else sees.+ *+ * Route: `/workspace-locked`.+ */+const meta = {+ title: 'Pages/System/Workspace Locked',+ component: WorkspaceLocked,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<WorkspaceLockedArgs>;++export default meta;++type Story = StoryObj<WorkspaceLockedArgs>;++/**+ * The trial ran out: the whole app is behind this, with the card form, the+ * customer stories and the FAQ that come with it.+ */+export const Default: Story = {};++/** The same wall for someone who cannot pay: no card form, only the ask. */+export const NonAdmin: Story = {+ args: { access: 'editor' },+};diff --git a/frontend/src/pages/WorkspaceLocked/stories/__story_mockdata__/workspaceStates.ts b/frontend/src/pages/WorkspaceLocked/stories/__story_mockdata__/workspaceStates.tsnew file mode 100644index 0000000000..f803a0c226--- /dev/null+++ b/frontend/src/pages/WorkspaceLocked/stories/__story_mockdata__/workspaceStates.ts@@ -0,0 +1,38 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { IAppContext } from 'providers/App/types';+import { createAppContextMock } from 'tests/fixtures/appContextMock';+import { LicenseState } from 'types/api/licensesV3/getActive';+import { USER_ROLES } from 'types/roles';++const { activeLicense, trialInfo } = createAppContextMock(USER_ROLES.ADMIN);++const DAY_IN_SECONDS = 24 * 60 * 60;++/**+ * Each of the three blocked-workspace pages bounces to home unless the license+ * says what put it there, so the state the page exists for is what the context+ * has to carry.+ */+export const licenseInState = (state: LicenseState): Partial<IAppContext> => ({+ activeLicense: activeLicense && { ...activeLicense, state },+ activeLicenseFetchError: null,+ isFetchingActiveLicense: false,+});++/** A trial that ran out, which is what locks the workspace. */+export const blockedTrial = (nowInSeconds: number): Partial<IAppContext> => ({+ trialInfo: {+ ...trialInfo,+ onTrial: true,+ workSpaceBlock: true,+ trialStart: nowInSeconds - 30 * DAY_IN_SECONDS,+ trialEnd: nowInSeconds - DAY_IN_SECONDS,+ trialConvertedToSubscription: false,+ gracePeriodEnd: nowInSeconds + 14 * DAY_IN_SECONDS,+ },+ isFetchingActiveLicense: false,+});diff --git a/frontend/src/pages/WorkspaceSuspended/stories/WorkspaceSuspended.stories.mocks.tsx b/frontend/src/pages/WorkspaceSuspended/stories/WorkspaceSuspended.stories.mocks.tsxnew file mode 100644index 0000000000..d57304a04f--- /dev/null+++ b/frontend/src/pages/WorkspaceSuspended/stories/WorkspaceSuspended.stories.mocks.tsx@@ -0,0 +1,30 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import ROUTES from 'constants/routes';+import { rest } from 'msw';+import { LicenseState } from 'types/api/licensesV3/getActive';++import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';++import { licenseInState } from '../../WorkspaceLocked/stories/__story_mockdata__/workspaceStates';++export const workspaceSuspendedMocks = defineStoryMocks({+ controls: {},+ handlers: () => [+ rest.put('http://localhost/api/v1/subscriptions', (_req, res, ctx) =>+ res(+ ctx.json({+ status: 'success',+ data: { redirectURL: 'https://billing.signoz.io/portal' },+ }),+ ),+ ),+ ],+ config: () => ({+ route: ROUTES.WORKSPACE_SUSPENDED,+ appContext: licenseInState(LicenseState.DEFAULTED),+ }),+});diff --git a/frontend/src/pages/WorkspaceSuspended/stories/WorkspaceSuspended.stories.tsx b/frontend/src/pages/WorkspaceSuspended/stories/WorkspaceSuspended.stories.tsxnew file mode 100644index 0000000000..fc4ddd6fe6--- /dev/null+++ b/frontend/src/pages/WorkspaceSuspended/stories/WorkspaceSuspended.stories.tsx@@ -0,0 +1,35 @@+import type { Meta, StoryObj } from '@storybook/react-vite';++import { storyMocks } from '@/storybook/controls/defineStoryMocks';+import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';++import WorkspaceSuspended from '../WorkspaceSuspended';+import { workspaceSuspendedMocks } from './WorkspaceSuspended.stories.mocks';++type WorkspaceSuspendedArgs = PageStoryArgs<typeof workspaceSuspendedMocks>;++const pageStory = storyMocks(workspaceSuspendedMocks, { layout: 'app' });++/**+ * A suspended workspace, with the billing portal link an admin gets.+ *+ * Route: `/workspace-suspended`.+ */+const meta = {+ title: 'Pages/System/Workspace Suspended',+ component: WorkspaceSuspended,+ ...pageStory,+ parameters: { ...pageStory.parameters },+} satisfies Meta<WorkspaceSuspendedArgs>;++export default meta;++type Story = StoryObj<WorkspaceSuspendedArgs>;++/** A payment that did not go through: the card has to be fixed to get back in. */+export const Default: Story = {};++/** The same wall for someone who cannot pay, who is told to ask an admin. */+export const NonAdmin: Story = {+ args: { access: 'editor' },+};diff --git a/frontend/src/storybook/README.md b/frontend/src/storybook/README.mdindex 2b3d468dbd..3407403e2c 100644--- a/frontend/src/storybook/README.md+++ b/frontend/src/storybook/README.md@@ -21,11 +21,64 @@ pnpm storybook:build # static build into storybook-static/| `navigation/` | Keeping a story on its page, and reporting what it tried to leave for || `msw/` | The default handler set and the shell's endpoints || `mocks/` | Modules aliased in place of the app's own |-| `decorators/` | `withProviders`, the global decorator |+| `decorators/` | `withProviders` (global) and `withCanvas` (opt-in per component) |+| `docs/` | The `Docs/*` pages, the docs page template, and the sidebar order |+| `foundations/` | Cross-cutting stories with no single owning component, and their fixtures |A page's own mocks live with the page, not here. See [Adding a pagestory](#adding-a-page-story).+## The sidebar++Titles mirror the app's own side nav (`container/SideNav/menuItems.tsx`):+`Pages/<Area>/<Page>`, where the area is the nav section and the page is the+label the nav gives it, so a page sits where someone would click it in the+product. The leaf is the product's label rather than the component's name, never+repeats its area (`Alerts/Rules`, not `Alerts/AlertRules`), and never shares a+name with a sibling folder: a page beside its own detail page is `List`, or+`Overview` for a tab strip.++The `storySort.order` literal in `.storybook/preview.tsx` carries the order of+every level, mirroring the nav again. Anything missing from a level falls to the+end of it, so a new story shows up at the bottom of its area rather than not at+all.++Tags on the meta are what the sidebar's tag filter reads: `authz` (the page gates+UI on permission checks through `lib/authz`), `role-gated` (it still branches on+the legacy role), `beta`, `legacy` (superseded but still routed) and `play` (a+state the story reaches by interacting). `autodocs` comes from `preview.tsx` and+is never written on a meta.++`Components/<Component>` and `Foundations/<Concern>` sit beside `Pages`, for the+shared pieces a page is assembled from and for the cross-cutting behaviour no+single page owns (feedback, layering, tooltips). Neither is in the+`storySort.order` literal, so both land after `Pages`, in file order.++## Docs pages++`@storybook/addon-docs` is on, and `preview.tsx` tags every story `autodocs`, so+each page gets a Docs page: the doc comment above its `const meta`, the controls+table, and one row per state from the story's own doc comment. Those comments are+the page's documentation; without the addon they render nowhere.++`docs/PageDocs.tsx` replaces Storybook's default template, which renders a canvas+per story. A page story is the whole app behind msw, so that is one boot per+state; this one renders no canvas and lists every state as a link.++`docs/*.mdx` are the `Docs/*` pages in the sidebar: `Introduction`, for someone+opening Storybook for the first time. This README is the reference and stays a+file; it is not rendered in the sidebar.++`docs/ThemedDocsContainer.tsx` is the container for every docs page. It themes+the page off the theme toolbar, which Storybook's own container does not do, and+it lets the page scroll: a docs page renders in the story iframe, where+`styles.scss` pins `html` and `body` with `overflow: hidden` for `AppLayout`.+Both are undone when the page unmounts, so a story keeps the viewport the app+expects.++MDX here is not GFM: a pipe table renders as its own pipes. Write the table as+JSX and Storybook's docs styles pick it up.+## What a story gets for free`withProviders` (global decorator, `.storybook/preview.tsx`) wraps every story in@@ -57,6 +110,12 @@ Storybook fills the seams with:- A fresh react-query client and redux store per story: no cache or state bleed.- `nuqs` on its testing adapter, so query-param state lives in memory and nevertouches the iframe URL.+- A clock frozen at the instant `.storybook/preview-head.html` names, so chart+ windows, `4 mins ago` labels and trial countdowns are the same in two builds+ of the same code. `new Date()` is that instant; `Date.now()` runs on from it,+ because elapsed-time code reads it — `lodash.debounce` compares two readings+ to decide its trailing call is due, and a frozen one leaves every debounced+ input in the app filtering nothing. `?storyClock=live` opts out.- Theme from the toolbar (dark/light). `applyThemeBodyClass` puts `<body>` in thestate the app gets from `index.html` plus `AppLayout`: `data-theme="default"`(every `@signozhq/design-tokens` semantic token is scoped to it, and without it@@ -79,12 +138,18 @@ Handlers resolve first-match-wins, in this order:3. the global mocks' handlers (access);4. `msw/appShellHandlers.ts`, the endpoints the shell hits on every route, andthe ones whose jest fixture is too thin to show it doing its job;-5. `src/mocks-server/handlers.ts`, the jest handlers verbatim. An endpoint both+5. `msw/queryBuilderHandlers.ts`, the legacy v3 autocomplete pair, which the+ jest handlers answer for one query and 500 for every other;+6. `src/mocks-server/handlers.ts`, the jest handlers verbatim. An endpoint bothrunners need belongs here so jest gets it too;-6. a catch-all for `http://localhost/api/*` that logs and answers 501, so an+7. a catch-all for `http://localhost/api/*` that logs and answers 501, so anendpoint nobody mocked fails loudly instead of hanging on a refusedconnection.+A handler that returns nothing hands the request to the next one in the list, so+a Storybook-level handler can cover the cases a jest fixture does not and leave+the ones it does.+The whole set is re-registered on every story render rather than handed to`setupWorker` once. Editing a handler module then takes effect on the nextrender; with the handlers baked in at worker creation, a long-lived dev server@@ -171,10 +236,19 @@ export const homeMocks = defineStoryMocks({// src/pages/HomePage/stories/HomePage.stories.tsxtype HomeArgs = PageStoryArgs<typeof homeMocks>;+const pageStory = storyMocks(homeMocks, { route: ROUTES.HOME, layout: 'app' });++/**+ * The workspace landing page: ingestion state per signal, the welcome checklist+ * while a signal is missing, then the widgets over what the workspace has.+ *+ * Route: `/home`.+ */const meta = {title: 'Pages/Home',component: HomePage,- ...storyMocks(homeMocks, { route: ROUTES.HOME, layout: 'app' }),+ ...pageStory,+ parameters: { ...pageStory.parameters },} satisfies Meta<HomeArgs>;export const NoIngestion: StoryObj<HomeArgs> = {@@ -182,6 +256,14 @@ export const NoIngestion: StoryObj<HomeArgs> = {};```+The trailing `parameters` line is not decoration. `storyMocks` returns the mocks+under `parameters.signoz`, and the doc comment above `const meta` compiles to a+`parameters` property that the csf plugin appends **after** the spread, which+would overwrite it. Restating `parameters` as a literal gives the plugin+something to merge into, so both survive. A meta that skips it renders the page+against the global handlers alone, and `resolveStory` says so in the console+rather than leaving it to be guessed at.+`toggleControl`, `countControl`, `choiceControl` and `multiChoiceControl` buildthe panel row and carry the value's type, so `values` inside `handlers` is typedand a story's `args` are checked.@@ -267,8 +349,16 @@ rather than a story that fails at render:| Module | Replacement | Why || --------------------- | ---------------------------------- | ------------------------------------------ || `lib/history` | `navigation/history.alias.ts` | keeps a story on its page, see below |+| `store` | `mocks/store.mock.ts` | the singleton answers from the story's store || `api/common/logEvent` | `mocks/logEvent.mock.ts` | analytics never leave the iframe || `constants/env` | `mocks/env.mock.ts` | pins the API origin the handlers answer on |+| `@signozhq/ui/tooltip` | `mocks/tooltip.mock.tsx` | the Tooltips control, see below |++`store` is the redux singleton, not the provider. A story mounts its own store,+but around a dozen modules read `store.getState()` directly, and one of them,+`lib/getStartEndRangeTime`, is how every query decides the time range it asks+for. Without the alias those modules answer from a store no story seeded, so the+time picker shows one range and the data covers another.Mocks use `fn()` from `storybook/test`, so a play function can assert on them:@@ -280,6 +370,45 @@ play: async () => {},```+## Tooltips++**Hold tooltips open** is a project-level control, so every story has it. Turning+it on opens every tooltip the page renders and keeps it open, which is what makes+a page's tooltips one screenshot rather than one hover each.++Hovering cannot do this. Radix dispatches a `tooltip.open` event on `document`+when a tooltip opens, and every mounted tooltip closes itself on it, so exactly+one is open at a time no matter how many providers the tree has. A tooltip whose+`open` is controlled ignores the event, which is what the alias passes:+`mocks/tooltip.mock.tsx` wraps `TooltipSimple` and `TooltipRoot` and hands them+`open` while the control is on.++Two cases keep their own state. A tooltip the page already drives, such as+`SpanHoverCard`, is left alone: only the page knows what its popup is anchored+to. A tooltip whose title is empty is left alone too, because there is nothing to+show but the padding of a popup.++What the control cannot reach is a tooltip that is not mounted: one inside a+closed drawer or modal, one in a row that renders its actions on hover, and+`TanStackHoverTooltip`, which renders its children bare until the row is+hovered. Those need a `play` that reaches the state first; the control then holds+open whatever it uncovered.++Every page whose tooltips are worth reviewing has a `Tooltips` story, so the+state can be linked to and snapshotted rather than reproduced by hand:++```tsx+/** Every tooltip on the page, held open. */+export const Tooltips: Story = {+ args: { tooltipsOpen: true },+};+```++A page whose interesting tooltips only exist in a drawer, a modal or a hovered+row gets the `play` that opens that surface first, and `tags: ['play']` on the+meta. Where the page's own fixture is too tame to show a tooltip growing, the+story turns the control that lengthens it rather than a story-only prop.+## NavigationA story renders one page, so leaving that page would unmount it.@@ -298,17 +427,54 @@ pathname:`NavigationBlockedOverlay`, which lists what was attempted. Nothing is silentlydropped.+The story's search is mirrored onto the iframe's URL, keeping the preview's own+params (`id`, `viewMode`, `args`, `globals`). Much of the app reads+`window.location.search` rather than the router, which is how every writer that+builds a target on top of the current params reads them, and in a story that+read would otherwise answer with the preview's query and nothing the page put+there. Two writers would then publish over each other forever: the query builder+dropping the time range, the time range dropping the query builder. Whatever the+app hands back is stripped of the preview's params again on the way in, so the+story's history stays the page's own URL.+`nuqs` is the one gap: it runs on its testing adapter and keeps its own copy ofthe query string, seeded from the story's `route`. A page that writes paramsthrough both `useQueryState` and `history.push({ search })` sees the two divergeinside a story; a page that stays on one mechanism does not.+## Adding a component story++A component story covers a piece several pages share, or a concern that no single+page owns. It differs from a page story in three ways:++1. **Bound the canvas.** `preview.tsx` lays every story out `fullscreen`, which+ is what a page wants and what leaves a select stretched across 1440px. Give+ the meta `decorators: [withCanvas({ maxWidth: 400 })]`+ (`storybook/decorators/withCanvas`) with the slot the app actually gives the+ component: `QuickFilters` gets the explorers' 260px rail, a table gets the+ height it scrolls in. A component that portals out of the canvas, such as+ `FieldsSelector`, needs no decorator.+2. **Drive the component, not a route.** Props come from `args`, not from+ `storyMocks`; a component that still calls an endpoint declares+ `parameters.msw` handlers of its own. `layout: 'app'` is for pages only.+3. **Fix the first-run state.** A component that reads localStorage shows its+ announcement or its onboarding tooltip in every story, on top of the thing the+ story is about. Set the key from a `beforeEach` on the meta and keep one story+ that clears it.++A concern rather than a component — how feedback stacks, what sits above what,+every tooltip a surface renders — goes under `storybook/foundations/` as a+fixture plus its story file, since there is no single app component to point at.+## Adding a page storyThe `signoz-page-story` skill in `.claude/skills/` carries this as a workflow:mapping the page, deriving its controls, and the checks a story has to pass.-1. Point the story at the page component under `src/pages/<Page>`.+1. Point the story at the page component under `src/pages/<Page>`. Title it+ `Pages/<Area>/<Page>` per [The sidebar](#the-sidebar), tag it, add its entry+ to the `storySort.order` literal in `.storybook/preview.tsx`, and give the+ meta a doc comment: what the page is, then its route.2. Keep every story file under `src/pages/<Page>/stories/`: the story, thepage's mocks in `<Page>.stories.mocks.ts`, and its payload builders under`stories/__story_mockdata__/`. Spread `storyMocks(<page>Mocks, { route })`@@ -316,8 +482,45 @@ mapping the page, deriving its controls, and the checks a story has to pass.3. Pass `layout: 'app'` in the same config, so the page renders inside`AppLayout` where a route puts it.4. Give the default story every widget populated. A page story earns its keep by- showing what the page looks like with data, not with empty states.+ showing what the page looks like with data, not with empty states. Every story+ export gets a doc comment saying what that state shows: it is the row the Docs+ page renders for it.5. Run it and watch the console: an msw warning or a `[storybook] no msw handler`line is an endpoint the page hits that no handler covers yet.6. Reach for a control before a story. A variant earns a story only when it isworth linking to; anything else is a control someone can turn.++A page that is a tab strip over several routes, such as+`src/pages/LogsModulePage`, gets one story file per tab, each in its own+`stories/` folder under the module page+(`LogsModulePage/Pipelines/stories/Pipelines.stories.tsx`) with its own mocks and+`__story_mockdata__/`. All of them render the module page, so the tab strip is+there; the `route` its mocks return is what decides which tab is open. Builders+more than one tab needs stay in the module page's own+`stories/__story_mockdata__/`, which a tab reaches as+`../../stories/__story_mockdata__/<page>`.++A state that only a click reaches, such as a drawer or a modal a page holds in+component state, is a story with a `play` function rather than a control. Use+`userEvent` and the queries from `storybook/test`, take the first of a repeated+row action, and wait on the state's own text. The page fetches before it renders+a row, so the finder needs a timeout past the 1s default.++A *sequence* of those states, such as the steps of a wizard or the pages of a+questionnaire, is still a control. Declare the steps in the page's mocks and walk+them from a `play` on the meta, so every story of the page inherits the walk and+only sets `args`:++```tsx+play: async ({ mount, args, canvasElement }): Promise<void> => {+ await mount();+ await advanceToStep(canvasElement, args.step);+},+```++Destructuring `mount` is what makes the panel row work. Storybook replays a play+function on an arg change only for a story whose play asks to be remounted;+without it the story re-renders the tree the previous walk left behind and the+control looks dead. The endpoint that settles a transition between two steps then+needs a plain resolver rather than `response.json`, or the Data control on+`loading` strands the walk halfway.diff --git a/frontend/src/storybook/decorators/withCanvas.tsx b/frontend/src/storybook/decorators/withCanvas.tsxnew file mode 100644index 0000000000..23be7139ec--- /dev/null+++ b/frontend/src/storybook/decorators/withCanvas.tsx@@ -0,0 +1,18 @@+import type { CSSProperties } from 'react';+import type { Decorator } from '@storybook/react-vite';++/**+ * Bounds a component story to the slot the app gives that component. The preview+ * lays every story out `fullscreen`, which is what a page wants and what leaves+ * a select or a filter rail stretched across the whole canvas.+ *+ * Opt in per component story with `decorators: [withCanvas({ maxWidth: 400 })]`.+ */+export const withCanvas = (style: CSSProperties): Decorator =>+ function Canvas(Story): JSX.Element {+ return (+ <div style={{ padding: 24, ...style }}>+ <Story />+ </div>+ );+ };diff --git a/frontend/src/storybook/docs/Introduction.mdx b/frontend/src/storybook/docs/Introduction.mdxnew file mode 100644index 0000000000..8cf3f2d0b0--- /dev/null+++ b/frontend/src/storybook/docs/Introduction.mdx@@ -0,0 +1,113 @@+import { Meta } from '@storybook/addon-docs/blocks';++<Meta title="Docs/Introduction" />++# SigNoz pages, without a backend++Every story here is a real SigNoz page: the app's own provider tree, the real+`AppLayout` with its side nav and banners, and msw answering every request. No+backend, no seeded database, no login.++What that buys you:++- a page in a state that is hard to reach against a live backend (empty+ workspace, expired license, a viewer's permissions, an endpoint that fails);+- a state you can link to, so a bug report can point at it;+- design and a11y review of a page without waiting on data.++## Finding a page++The sidebar mirrors the app's own side nav, so a page sits where you would click+it in the product. `Alerts`, `Dashboards`, `Services`, `Logs`, `Traces` and the+rest come first, then `Settings`, then `Auth` and `System` for the pages you+reach by accident rather than on purpose.++A page that is one route with several tabs is one story per tab, under the+module: `Logs / Explorer`, `Logs / Pipelines`, `Logs / Saved Views`. Every tab+renders the module page, so the tab strip is there either way; the story decides+which tab is open.++## Reading a story++Three things drive what you see, and none of them is a prop:++- **Controls panel.** Every knob is a knob on a response. Turning one+ re-registers the msw handlers and remounts the page with an empty query cache,+ so the page fetches again. `Data` (loaded, loading, error) and `Access` are on+ every story; the rest belong to the page.+- **Theme toolbar.** Dark and light, the same classes and tokens the app sets at+ boot.+- **The story itself.** A named state worth linking to, `Default` first. Anything+ reachable by turning a knob is a control, not a story.++`⌘K` works inside a story, dev tools included: **AuthZ DevTools** lists the+permissions the page actually checked and overrides them one at a time.++## Tags++Filter the sidebar by tag to answer a question about the whole set at once.++<table>+ <thead>+ <tr>+ <th>Tag</th>+ <th>What it means</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>+ <code>authz</code>+ </td>+ <td>+ The page gates UI on permission checks through <code>lib/authz</code>. These+ are the stories to re-check when a resource or verb changes.+ </td>+ </tr>+ <tr>+ <td>+ <code>role-gated</code>+ </td>+ <td>+ The page still branches on the legacy role (<code>user.role</code>,{' '}+ <code>hasEditPermission</code>) rather than on a permission.+ </td>+ </tr>+ <tr>+ <td>+ <code>beta</code>+ </td>+ <td>Beta in the product. Drop the tag when it ships.</td>+ </tr>+ <tr>+ <td>+ <code>legacy</code>+ </td>+ <td>+ Kept for parity with a page that is on its way out. Start from the current+ page instead.+ </td>+ </tr>+ <tr>+ <td>+ <code>play</code>+ </td>+ <td>+ At least one state is reached by an interaction the story performs on mount,+ so the canvas moves before it settles.+ </td>+ </tr>+ <tr>+ <td>+ <code>autodocs</code>+ </td>+ <td>Carried by every page story, and what gives it a Docs page.</td>+ </tr>+ </tbody>+</table>++## Adding one++The `signoz-page-story` skill in `.claude/skills/` carries the workflow, and+`src/storybook/README.md` is the harness it runs on: the runtime, the controls,+the access model, the module mocks and the navigation containment.diff --git a/frontend/src/storybook/docs/PageDocs.tsx b/frontend/src/storybook/docs/PageDocs.tsxnew file mode 100644index 0000000000..a67c7b89cf--- /dev/null+++ b/frontend/src/storybook/docs/PageDocs.tsx@@ -0,0 +1,31 @@+import {+ Controls,+ Description,+ Subtitle,+ Title,+} from '@storybook/addon-docs/blocks';++import StoryStates from './StoryStates';++/**+ * The docs page every page story gets, in place of Storybook's default: what the+ * page is, its controls, and its states as links.+ *+ * No canvas. A page story is the whole app behind msw, so the default template's+ * canvas per story is one app boot per story, and a story rendered on a docs page+ * re-registers the worker's handlers after the docs entry has already replaced+ * them, which leaves the page fetching against the global set.+ */+function PageDocs(): JSX.Element {+ return (+ <>+ <Title />+ <Subtitle />+ <Description />+ <Controls />+ <StoryStates />+ </>+ );+}++export default PageDocs;diff --git a/frontend/src/storybook/docs/StoryStates.tsx b/frontend/src/storybook/docs/StoryStates.tsxnew file mode 100644index 0000000000..bb8d8108f8--- /dev/null+++ b/frontend/src/storybook/docs/StoryStates.tsx@@ -0,0 +1,54 @@+// Storybook's docs blocks publish their context as a React context, which is the+// only way to read the stories of the file being documented.+// eslint-disable-next-line no-restricted-imports+import { useContext } from 'react';+import { DocsContext } from '@storybook/addon-docs/blocks';++import styles from './pageDocs.module.scss';++/**+ * The page's states as a list rather than a canvas each. A page story mounts the+ * whole app shell behind msw, so rendering every state on the docs page costs a+ * full boot per state; the name, its description and a link to it carry the same+ * information for a fraction of it.+ */+function StoryStates(): JSX.Element | null {+ const context = useContext(DocsContext);+ const stories = context.componentStories();++ if (stories.length === 0) {+ return null;+ }++ return (+ <section className={styles.states} data-testid="page-docs-states">+ <h2 className={styles.heading}>States</h2>+ <ul className={styles.list}>+ {stories.map((story) => {+ const description = story.parameters?.docs?.description?.story as+ | string+ | undefined;++ return (+ <li className={styles.item} key={story.id}>+ <a+ className={styles.name}+ href={`./?path=/story/${story.id}`}+ target="_top"+ >+ {story.name}+ </a>+ {description ? (+ <p className={styles.description}>{description}</p>+ ) : (+ <p className={styles.undocumented}>Undocumented.</p>+ )}+ </li>+ );+ })}+ </ul>+ </section>+ );+}++export default StoryStates;diff --git a/frontend/src/storybook/docs/ThemedDocsContainer.tsx b/frontend/src/storybook/docs/ThemedDocsContainer.tsxnew file mode 100644index 0000000000..554388339d--- /dev/null+++ b/frontend/src/storybook/docs/ThemedDocsContainer.tsx@@ -0,0 +1,60 @@+import { useEffect } from 'react';+import type { PropsWithChildren } from 'react';+import {+ DocsContainer,+ type DocsContainerProps,+} from '@storybook/addon-docs/blocks';+import { themes } from 'storybook/theming';++import { applyThemeBodyClass } from '../providers/applyThemeBodyClass';++import styles from './themedDocsContainer.module.scss';+import { useDocsTheme } from './useDocsTheme';++/**+ * The container for every docs page, `Docs/*` and autodocs alike.+ *+ * It carries the two things a docs page needs and a story does not, which is why+ * they live here rather than in the preview decorator:+ *+ * - Storybook's own container is always on its light theme, so a docs page came+ * out white inside a dark app. The body classes go on for the same reason: the+ * docs page renders in the story iframe, where `styles.scss` paints `body` from+ * `--l1-background`, and those variables only resolve under a theme class.+ * - That same stylesheet pins `html` and `body` to the viewport with+ * `overflow: hidden` so `AppLayout` can lay a page out inside it, which leaves+ * anything below the fold of a docs page unreachable. Lifting it for a story+ * too would let a page scroll the iframe instead of its own panes, so the class+ * goes on only while a docs page is mounted.+ */+function ThemedDocsContainer({+ context,+ children,+}: PropsWithChildren<DocsContainerProps>): JSX.Element {+ const theme = useDocsTheme();++ useEffect(() => {+ applyThemeBodyClass(theme);+ }, [theme]);++ useEffect(() => {+ const root = document.documentElement;++ root.classList.add(styles.scrollable);++ return (): void => {+ root.classList.remove(styles.scrollable);+ };+ }, []);++ return (+ <DocsContainer+ context={context}+ theme={theme === 'dark' ? themes.dark : themes.light}+ >+ {children}+ </DocsContainer>+ );+}++export default ThemedDocsContainer;diff --git a/frontend/src/storybook/docs/pageDocs.module.scss b/frontend/src/storybook/docs/pageDocs.module.scssnew file mode 100644index 0000000000..2239a3ca75--- /dev/null+++ b/frontend/src/storybook/docs/pageDocs.module.scss@@ -0,0 +1,45 @@+.states {+ margin: 24px 0;+}++.heading {+ margin-bottom: 8px;+ font-size: 16px;+ font-weight: 600;+}++.list {+ margin: 0;+ padding: 0;+ list-style: none;+ border-top: 1px solid var(--sb-docs-border, rgba(38, 85, 115, 0.15));+}++.item {+ display: grid;+ grid-template-columns: minmax(160px, 240px) 1fr;+ gap: 16px;+ padding: 10px 0;+ border-bottom: 1px solid var(--sb-docs-border, rgba(38, 85, 115, 0.15));++ @media (max-width: 720px) {+ grid-template-columns: 1fr;+ gap: 4px;+ }+}++.name {+ font-weight: 600;+ text-decoration: none;+}++.description {+ margin: 0;+ opacity: 0.8;+}++.undocumented {+ margin: 0;+ font-style: italic;+ opacity: 0.6;+}diff --git a/frontend/src/storybook/docs/themedDocsContainer.module.scss b/frontend/src/storybook/docs/themedDocsContainer.module.scssnew file mode 100644index 0000000000..319aa82f15--- /dev/null+++ b/frontend/src/storybook/docs/themedDocsContainer.module.scss@@ -0,0 +1,8 @@+.scrollable {+ &,+ body {+ height: auto;+ min-height: 100%;+ overflow: visible;+ }+}diff --git a/frontend/src/storybook/docs/useDocsTheme.ts b/frontend/src/storybook/docs/useDocsTheme.tsnew file mode 100644index 0000000000..8414bf9bed--- /dev/null+++ b/frontend/src/storybook/docs/useDocsTheme.ts@@ -0,0 +1,56 @@+import { useEffect, useState } from 'react';+import { GLOBALS_UPDATED, SET_GLOBALS } from 'storybook/internal/core-events';+import { addons } from 'storybook/preview-api';++import type { StoryTheme } from '../types';++const DEFAULT_THEME: StoryTheme = 'dark';++const isTheme = (value: unknown): value is StoryTheme =>+ value === 'dark' || value === 'light';++/**+ * The theme the toolbar is on, for a docs entry that has no story attached.+ *+ * Such an entry never runs the preview loaders or the decorators, which is where+ * every other part of the harness reads `globals.theme`, so the value has to come+ * off the channel the manager pushes it down. `SET_GLOBALS` is emitted while the+ * preview boots, before this can subscribe, so the initial value is parsed out of+ * the iframe's own `globals` query param (`theme:light`, `;`-separated).+ */+const readThemeFromUrl = (): StoryTheme => {+ const globals = new URLSearchParams(window.location.search).get('globals');+ const theme = globals+ ?.split(';')+ .map((entry) => entry.split(':'))+ .find(([key]) => key === 'theme')?.[1];++ return isTheme(theme) ? theme : DEFAULT_THEME;+};++export function useDocsTheme(): StoryTheme {+ const [theme, setTheme] = useState<StoryTheme>(readThemeFromUrl);++ useEffect(() => {+ const channel = addons.getChannel();+ const onGlobals = ({+ globals,+ }: {+ globals?: Record<string, unknown>;+ }): void => {+ if (isTheme(globals?.theme)) {+ setTheme(globals.theme);+ }+ };++ channel.on(SET_GLOBALS, onGlobals);+ channel.on(GLOBALS_UPDATED, onGlobals);++ return (): void => {+ channel.off(SET_GLOBALS, onGlobals);+ channel.off(GLOBALS_UPDATED, onGlobals);+ };+ }, []);++ return theme;+}diff --git a/frontend/src/storybook/foundations/Feedback.stories.tsx b/frontend/src/storybook/foundations/Feedback.stories.tsxnew file mode 100644index 0000000000..bbd9e37c61--- /dev/null+++ b/frontend/src/storybook/foundations/Feedback.stories.tsx@@ -0,0 +1,113 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import { expect, screen, userEvent, waitFor, within } from 'storybook/test';++import { withCanvas } from '../decorators/withCanvas';+import FeedbackFixture from './FeedbackFixture';++const meta = {+ title: 'Foundations/Feedback',+ component: FeedbackFixture,+ tags: ['play'],+ decorators: [withCanvas({ maxWidth: 640 })],+} satisfies Meta<typeof FeedbackFixture>;++export default meta;++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(),+ );+ },+};++/** 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(),+ );+ },+};++/** 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();+ },+};++/** Mutation: the inline application alert preserves its action affordance. */+export const InlineAlert: Story = {+ args: { state: 'inline-alert' },+};++/**+ * Interaction: verifies Escape closes the destructive confirmation. The dialog+ * drops focus on the body rather than returning it to the trigger, so the story+ * asserts what it does; see `docs/reviews/signozhq-ui-drawer-feedback.md`.+ */+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(),+ );+ },+};++/** 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();+ },+};diff --git a/frontend/src/storybook/foundations/FeedbackFixture.tsx b/frontend/src/storybook/foundations/FeedbackFixture.tsxnew file mode 100644index 0000000000..24f045543c--- /dev/null+++ b/frontend/src/storybook/foundations/FeedbackFixture.tsx@@ -0,0 +1,111 @@+import { useState } from 'react';+import { Trash2, TriangleAlert } from '@signozhq/icons';+import { Button } from '@signozhq/ui/button';+import { ConfirmDialog } from '@signozhq/ui/dialog';+import { Toaster, toast } from '@signozhq/ui/sonner';++import MessageTip from '@/components/MessageTip';++export type FeedbackState =+ | 'success-toast'+ | 'actionable-error-toast'+ | 'long-toast'+ | 'inline-alert'+ | 'confirmation'+ | 'toast-over-confirmation';++interface FeedbackFixtureProps {+ state: FeedbackState;+}++const longMessage =+ 'We could not apply the retention policy because the selected storage tier is unavailable. Review the workspace settings, then try again.';++function FeedbackFixture({ state }: FeedbackFixtureProps): JSX.Element {+ const [isConfirmationOpen, setIsConfirmationOpen] = useState(false);++ const showToast = (): void => {+ if (state === 'success-toast') {+ toast.success('Retention policy updated successfully');+ return;+ }++ if (state === 'actionable-error-toast') {+ toast.error('Failed to save the notification channel', {+ action: { label: 'Retry', onClick: (): void => undefined },+ });+ return;+ }++ toast.error(longMessage, { duration: Infinity });+ };++ const isToastStory =+ state === 'success-toast' ||+ state === 'actionable-error-toast' ||+ state === 'long-toast';+ const confirmationTitle = 'Delete environment';++ return (+ <>+ {isToastStory && (+ <Button data-testid="show-feedback-toast" onClick={showToast}>+ Show feedback+ </Button>+ )}+ {state === 'inline-alert' && (+ <MessageTip+ action={+ <Button color="secondary" size="sm" variant="outlined">+ Review settings+ </Button>+ }+ message="Some collectors have not reported data in the last 15 minutes."+ show+ />+ )}+ {(state === 'confirmation' || state === 'toast-over-confirmation') && (+ <>+ <Button+ data-testid="open-feedback-confirmation"+ onClick={(): void => setIsConfirmationOpen(true)}+ >+ Delete environment+ </Button>+ <ConfirmDialog+ cancelText="Cancel"+ confirmColor="destructive"+ confirmIcon={<Trash2 size={14} />}+ confirmText="Delete environment"+ disableOutsideClick+ open={isConfirmationOpen}+ title={confirmationTitle}+ titleIcon={<TriangleAlert size={14} />}+ onCancel={(): void => setIsConfirmationOpen(false)}+ onConfirm={(): boolean => {+ setIsConfirmationOpen(false);+ return true;+ }}+ onOpenChange={setIsConfirmationOpen}+ >+ This removes the environment and its saved views. This action cannot be+ undone.+ {state === 'toast-over-confirmation' && (+ <Button+ color="secondary"+ size="sm"+ variant="outlined"+ onClick={showToast}+ >+ Show error notification+ </Button>+ )}+ </ConfirmDialog>+ </>+ )}+ <Toaster closeButton position="top-right" />+ </>+ );+}++export default FeedbackFixture;diff --git a/frontend/src/storybook/foundations/Layering.stories.tsx b/frontend/src/storybook/foundations/Layering.stories.tsxnew file mode 100644index 0000000000..e58f47a17b--- /dev/null+++ b/frontend/src/storybook/foundations/Layering.stories.tsx@@ -0,0 +1,76 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import {+ expect,+ screen,+ userEvent,+ waitFor,+ waitForElementToBeRemoved,+ within,+} from 'storybook/test';++import LayeringFixture from './LayeringFixture';++const meta = {+ title: 'Foundations/Layering',+ tags: ['play'],+ component: LayeringFixture,+} satisfies Meta<typeof LayeringFixture>;++export default meta;++type Story = StoryObj<typeof meta>;++/** Interaction: modal and body portal; verifies the select stays above its host. */+export const SelectOverModal: Story = {+ args: { host: 'modal' },+ play: async ({ canvasElement }): Promise<void> => {+ const trigger = within(canvasElement).getByTestId('open-layering-modal');++ await userEvent.click(trigger);+ await screen.findByRole('dialog', { name: 'Layering modal' });+ await userEvent.keyboard('{Escape}');+ await waitFor(() => expect(trigger).toHaveFocus());+ await userEvent.click(trigger);+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Modal environment' }),+ );+ await screen.findByRole('listbox');+ },+};++/**+ * Interaction: drawer and its local popup container; verifies overlay stacking.+ * Escape closes the drawer but leaves focus on the body instead of the trigger,+ * so the story asserts the close; see+ * `docs/reviews/signozhq-ui-drawer-feedback.md`.+ */+export const SelectOverDrawer: Story = {+ args: { host: 'drawer' },+ play: async ({ canvasElement }): Promise<void> => {+ const trigger = within(canvasElement).getByTestId('open-layering-drawer');++ await userEvent.click(trigger);+ const drawer = await screen.findByRole('dialog', { name: 'Layering drawer' });++ await userEvent.keyboard('{Escape}');+ await waitForElementToBeRemoved(drawer);+ await userEvent.click(trigger);+ await userEvent.click(+ await screen.findByRole('combobox', { name: 'Drawer environment' }),+ );+ await screen.findByRole('listbox');+ },+};++/** Interaction: scrollable local container; exposes clipping and positioning branches. */+export const SelectOverScrollablePanel: Story = {+ args: { host: 'scrollable-panel' },+ play: async ({ canvasElement }): Promise<void> => {+ await userEvent.click(+ within(canvasElement).getByRole('combobox', {+ name: 'Scrollable panel environment',+ }),+ );+ await screen.findByRole('listbox');+ },+};diff --git a/frontend/src/storybook/foundations/LayeringFixture.module.scss b/frontend/src/storybook/foundations/LayeringFixture.module.scssnew file mode 100644index 0000000000..6f2fa20233--- /dev/null+++ b/frontend/src/storybook/foundations/LayeringFixture.module.scss@@ -0,0 +1,20 @@+.fixture {+ padding: 24px;+}++.overlayContent {+ min-height: 180px;+}++.scrollPanel {+ height: 280px;+ max-width: 480px;+ overflow: auto;+ padding: 16px;+ border: 1px solid var(--bg-slate-200);+ border-radius: 4px;+}++.scrollSpacer {+ height: 220px;+}diff --git a/frontend/src/storybook/foundations/LayeringFixture.tsx b/frontend/src/storybook/foundations/LayeringFixture.tsxnew file mode 100644index 0000000000..802083064d--- /dev/null+++ b/frontend/src/storybook/foundations/LayeringFixture.tsx@@ -0,0 +1,112 @@+import { DrawerWrapper } from '@signozhq/ui/drawer';+import { Button } from 'antd';+import { useState } from 'react';++import { CustomSelect } from '@/components/NewSelect';+import SignozModal from '@/components/SignozModal/SignozModal';++import styles from './LayeringFixture.module.scss';++export type LayeringHost = 'modal' | 'drawer' | 'scrollable-panel';++interface LayeringFixtureProps {+ host: LayeringHost;+}++const environmentOptions = [+ { label: 'Development', value: 'development' },+ { label: 'Staging', value: 'staging' },+ { label: 'Production', value: 'production' },+];++function LayeringFixture({ host }: LayeringFixtureProps): JSX.Element {+ const [isHostOpen, setIsHostOpen] = useState(false);+ const [environment, setEnvironment] = useState('production');++ if (host === 'modal') {+ return (+ <div className={styles.fixture}>+ <Button+ data-testid="open-layering-modal"+ type="primary"+ onClick={(): void => setIsHostOpen(true)}+ >+ Open modal+ </Button>+ <SignozModal+ footer={null}+ open={isHostOpen}+ title="Layering modal"+ onCancel={(): void => setIsHostOpen(false)}+ >+ <div className={styles.overlayContent}>+ <CustomSelect+ aria-label="Modal environment"+ getPopupContainer={(): HTMLElement => document.body}+ options={environmentOptions}+ value={environment}+ onChange={(value): void => setEnvironment(String(value))}+ />+ </div>+ </SignozModal>+ </div>+ );+ }++ if (host === 'drawer') {+ return (+ <div className={styles.fixture}>+ <Button+ data-testid="open-layering-drawer"+ type="primary"+ onClick={(): void => setIsHostOpen(true)}+ >+ Open drawer+ </Button>+ <DrawerWrapper+ direction="right"+ open={isHostOpen}+ title="Layering drawer"+ onOpenChange={setIsHostOpen}+ >+ <div+ className={styles.overlayContent}+ data-testid="layering-drawer-content"+ >+ <CustomSelect+ aria-label="Drawer environment"+ getPopupContainer={(trigger): HTMLElement =>+ trigger.closest(+ '[data-testid="layering-drawer-content"]',+ ) as HTMLElement+ }+ options={environmentOptions}+ value={environment}+ onChange={(value): void => setEnvironment(String(value))}+ />+ </div>+ </DrawerWrapper>+ </div>+ );+ }++ return (+ <div className={styles.fixture}>+ <div className={styles.scrollPanel} data-testid="layering-scroll-panel">+ <p>Scrollable panel</p>+ <div className={styles.scrollSpacer} />+ <CustomSelect+ aria-label="Scrollable panel environment"+ getPopupContainer={(trigger): HTMLElement =>+ trigger.closest('[data-testid="layering-scroll-panel"]') as HTMLElement+ }+ options={environmentOptions}+ value={environment}+ onChange={(value): void => setEnvironment(String(value))}+ />+ </div>+ </div>+ );+}++export default LayeringFixture;diff --git a/frontend/src/storybook/foundations/Tooltips.stories.tsx b/frontend/src/storybook/foundations/Tooltips.stories.tsxnew file mode 100644index 0000000000..6ab8e3d960--- /dev/null+++ b/frontend/src/storybook/foundations/Tooltips.stories.tsx@@ -0,0 +1,63 @@+import type { Meta, StoryObj } from '@storybook/react-vite';+import type { ComponentProps } from 'react';++import { nozGlobalConfigHandler } from '@/storybook/msw/appShellHandlers';++import type { GlobalMockArgs } from '../globals';+import TooltipsFixture from './TooltipsFixture';++type TooltipsArgs = ComponentProps<typeof TooltipsFixture> & GlobalMockArgs;++const meta = {+ title: 'Foundations/Tooltips',+ component: TooltipsFixture,+ args: { tooltipsOpen: true },+} satisfies Meta<TooltipsArgs>;++export default meta;++type Story = StoryObj<TooltipsArgs>;++/**+ * The refusal an `AuthZButton` or `AuthZTooltip` puts on a control the grant+ * does not cover. Nothing bounds the list, so the button is checked against+ * five permissions and denied all of them.+ */+export const DeniedPermissions: Story = {+ args: { access: 'deny-all', site: 'authz-denied' },+};++/**+ * The full series name behind a clipped chart legend entry. A metric series+ * carries every label it was grouped by, so the legend is given a real one.+ */+export const ChartLegendSeries: Story = {+ args: { site: 'chart-legend' },+};++/**+ * The preview a long cell value opens over itself: the value in a `pre`, which+ * does not wrap, above the button that opens it full size.+ */+export const ExpandedValuePreview: Story = {+ args: { site: 'expandable-value' },+};++/** The one-word label on the export control, the shortest tooltip the app has. */+export const ExportDownload: Story = {+ args: { site: 'export-menu' },+};++/**+ * The label on the Noz entry point in the top nav. The AI assistant is off until+ * the backend ships a URL for it, so the story answers the global config with+ * one.+ */+export const NozEntryPoint: Story = {+ args: { site: 'noz' },+ parameters: {+ msw: {+ handlers: [nozGlobalConfigHandler],+ },+ },+};diff --git a/frontend/src/storybook/foundations/TooltipsFixture.module.scss b/frontend/src/storybook/foundations/TooltipsFixture.module.scssnew file mode 100644index 0000000000..792240f32a--- /dev/null+++ b/frontend/src/storybook/foundations/TooltipsFixture.module.scss@@ -0,0 +1,17 @@+.fixture {+ max-width: 640px;+ padding: 160px 24px 24px;+}++.legend {+ height: 120px;+ max-width: 640px;+}++.truncatedValue {+ display: block;+ max-width: 320px;+ overflow: hidden;+ white-space: nowrap;+ text-overflow: ellipsis;+}diff --git a/frontend/src/storybook/foundations/TooltipsFixture.tsx b/frontend/src/storybook/foundations/TooltipsFixture.tsxnew file mode 100644index 0000000000..488728c3d8--- /dev/null+++ b/frontend/src/storybook/foundations/TooltipsFixture.tsx@@ -0,0 +1,143 @@+import { Button } from '@signozhq/ui/button';+import { DataSource } from 'types/common/queryBuilder';++import ExportMenu from '@/components/ExportMenu/ExportMenu';+import HeaderRightSection from '@/components/HeaderRightSection/HeaderRightSection';+import type { ClientExportData } from '@/hooks/useExportData/useClientExport';+import AuthZTooltip from '@/lib/authz/components/AuthZTooltip/AuthZTooltip';+import {+ APIKeyCreatePermission,+ RoleAttachWildcardPermission,+ RoleDetachWildcardPermission,+ SACreatePermission,+ SAListPermission,+} from '@/lib/authz/hooks/useAuthZ/permissions/service-account.permissions';+import Legend from '@/lib/uPlotV2/components/Legend/Legend';+import { LegendPosition } from '@/lib/uPlotV2/components/types';+import type { LegendItem } from '@/lib/uPlotV2/config/types';+import ExpandableValue from '@/periscope/components/ExpandableValue/ExpandableValue';++import styles from './TooltipsFixture.module.scss';++export type TooltipSite =+ | 'authz-denied'+ | 'chart-legend'+ | 'expandable-value'+ | 'export-menu'+ | 'noz';++interface TooltipsFixtureProps {+ site: TooltipSite;+}++const DENIED_CHECKS = [+ SACreatePermission,+ SAListPermission,+ APIKeyCreatePermission,+ RoleAttachWildcardPermission,+ RoleDetachWildcardPermission,+];++const LEGEND_ITEMS: LegendItem[] = [+ {+ seriesIndex: 1,+ label:+ 'signoz_latency_bucket{service_name="checkout", operation="POST /api/v1/orders/{orderId}/payment-authorisation", deployment_environment="production", cluster="eu-central-1"}',+ color: '#F24769',+ show: true,+ },+];++const LONG_JSON_VALUE = JSON.stringify(+ {+ exception: 'io.signoz.checkout.PaymentAuthorisationTimeout',+ message:+ 'Authorisation for order 8f21c4a0-6d1e-4c73-9b02-0f5a1d7e33aa timed out after 30000ms',+ stack: [+ 'io.signoz.checkout.PaymentClient.authorise(PaymentClient.java:184)',+ 'io.signoz.checkout.OrderService.placeOrder(OrderService.java:96)',+ 'io.signoz.checkout.OrderController.post(OrderController.java:41)',+ ],+ attributes: {+ 'deployment.environment': 'production',+ 'k8s.namespace.name': 'checkout',+ 'net.peer.name': 'payments-authorisation.production.svc.cluster.local',+ },+ },+ null,+ 2,+);++const EXPORT_DATA: ClientExportData = {+ statusCode: 200,+ message: 'success',+ error: null,+ payload: {+ data: {+ result: [],+ resultType: 'matrix',+ newResult: { data: { result: [], resultType: 'matrix' } },+ },+ },+};++const noOp = (): void => undefined;++function TooltipsFixture({ site }: TooltipsFixtureProps): JSX.Element {+ if (site === 'authz-denied') {+ return (+ <div className={styles.fixture}>+ <AuthZTooltip checks={DENIED_CHECKS}>+ <Button color="primary" variant="solid">+ Create service account+ </Button>+ </AuthZTooltip>+ </div>+ );+ }++ if (site === 'chart-legend') {+ return (+ <div className={styles.fixture}>+ <div className={styles.legend}>+ <Legend+ focusedSeriesIndex={null}+ items={LEGEND_ITEMS}+ position={LegendPosition.BOTTOM}+ onAction={noOp}+ />+ </div>+ </div>+ );+ }++ if (site === 'expandable-value') {+ return (+ <div className={styles.fixture}>+ <ExpandableValue title="Exception" value={LONG_JSON_VALUE}>+ <span className={styles.truncatedValue}>{LONG_JSON_VALUE}</span>+ </ExpandableValue>+ </div>+ );+ }++ if (site === 'export-menu') {+ return (+ <div className={styles.fixture}>+ <ExportMenu data={EXPORT_DATA} dataSource={DataSource.METRICS} />+ </div>+ );+ }++ return (+ <div className={styles.fixture}>+ <HeaderRightSection+ enableAnnouncements={false}+ enableFeedback={false}+ enableShare={false}+ />+ </div>+ );+}++export default TooltipsFixture;diff --git a/frontend/src/storybook/globals/index.ts b/frontend/src/storybook/globals/index.tsindex c2b3e317fb..a6712f4bde 100644--- a/frontend/src/storybook/globals/index.ts+++ b/frontend/src/storybook/globals/index.ts@@ -1,12 +1,17 @@import { composeStoryMocks } from '../controls/composeStoryMocks';import { appShellMocks } from './appShellMocks';import { authzMocks } from './authzMocks';+import { tooltipMocks } from './tooltipMocks';/*** The mock modules every story carries, page or component, declared at project* level in `.storybook/preview.tsx`. Adding one here publishes its controls and* widens `PageStoryArgs` in the same edit.*/-export const globalMocks = composeStoryMocks(authzMocks, appShellMocks);+export const globalMocks = composeStoryMocks(+ authzMocks,+ appShellMocks,+ tooltipMocks,+);export type GlobalMockArgs = typeof globalMocks.args;diff --git a/frontend/src/storybook/globals/tooltipMocks.ts b/frontend/src/storybook/globals/tooltipMocks.tsnew file mode 100644index 0000000000..dc60705d89--- /dev/null+++ b/frontend/src/storybook/globals/tooltipMocks.ts@@ -0,0 +1,27 @@+import { toggleControl } from '../controls/controls';+import { defineStoryMocks } from '../controls/defineStoryMocks';+import type { StoryMockArgs } from '../controls/types';+import { holdTooltipsOpen } from '../mocks/tooltipsHeldOpen';++const TOOLTIPS = 'Tooltips';++/**+ * Holds every tooltip the story renders open, so a page's tooltips are one+ * screenshot rather than one hover each. Radix closes the open tooltip from a+ * `document` event when the next one opens, so hovering can never hold more+ * than one; a controlled `open` ignores that event, and `mocks/tooltip.mock.tsx`+ * is what passes it.+ */+export const tooltipMocks = defineStoryMocks({+ controls: {+ tooltipsOpen: toggleControl('Hold tooltips open', {+ group: TOOLTIPS,+ description:+ 'Opens every tooltip on the page at once and keeps it open. A tooltip the page opens itself, and one with an empty title, are left alone. Tooltips behind a hover, a drawer or a modal are not rendered until something reaches them, so those still need a `play`.',+ value: false,+ }),+ },+ effect: ({ tooltipsOpen }) => holdTooltipsOpen(tooltipsOpen),+});++export type TooltipArgs = StoryMockArgs<typeof tooltipMocks>;diff --git a/frontend/src/storybook/mocks/store.mock.ts b/frontend/src/storybook/mocks/store.mock.tsnew file mode 100644index 0000000000..11afa1e0e0--- /dev/null+++ b/frontend/src/storybook/mocks/store.mock.ts@@ -0,0 +1,34 @@+// eslint-disable-next-line no-restricted-imports+import type { Store } from 'redux';++import { createStorybookStore } from '../providers/createStorybookStore';++/**+ * Replaces the app's redux singleton (`store`) in Storybook (aliased in+ * `.storybook/main.ts`).+ *+ * A story gets its own store so nothing leaks between stories, but a dozen+ * modules read `store.getState()` straight off the singleton rather than through+ * the provider: `lib/getStartEndRangeTime` is how every query decides the range+ * it asks for. Left alone, those modules answer from a store no story ever+ * seeded, so the time picker and the data would disagree. This forwards to+ * whichever store the current story mounted.+ *+ * The annotation checks the module's shape against the real one, so an export+ * added to `store` fails to compile here rather than at render.+ */+let current: Store = createStorybookStore();++export const setStoryStore = (store: Store): void => {+ current = store;+};++const storyStore: Store = new Proxy({} as Store, {+ get(_target, prop, receiver) {+ return Reflect.get(current, prop, receiver);+ },+});++const storeModule: typeof import('store') = { default: storyStore };++export default storeModule.default;diff --git a/frontend/src/storybook/mocks/tooltip.mock.tsx b/frontend/src/storybook/mocks/tooltip.mock.tsxnew file mode 100644index 0000000000..e26ddb1b3e--- /dev/null+++ b/frontend/src/storybook/mocks/tooltip.mock.tsx@@ -0,0 +1,71 @@+// The barrel is banned for the ~90 components it eagerly loads in a test run.+// This module stands in for the `tooltip` subpath, so importing that subpath+// here would resolve back to itself; the barrel is the only specifier left that+// reaches the real components, and it never runs under jest.+import {+ TooltipContent as UiTooltipContent,+ TooltipProvider as UiTooltipProvider,+ TooltipRoot as UiTooltipRoot,+ TooltipSimple as UiTooltipSimple,+ TooltipTrigger as UiTooltipTrigger,+ type TooltipRootProps,+ type TooltipSimpleProps,+ // eslint-disable-next-line signoz/no-signozhq-ui-barrel+} from '@signozhq/ui';+import { forwardRef } from 'react';++import { heldOpenState } from './tooltipsHeldOpen';++/**+ * Replaces `@signozhq/ui/tooltip` in Storybook (aliased in `.storybook/main.ts`)+ * so the Tooltips control can hold every tooltip a page renders open at once.+ * See the Tooltips section of `src/storybook/README.md`.+ *+ * The real components are imported from the package root, which re-exports them+ * over a relative path the alias does not match. The app therefore still sees+ * one tooltip context rather than two that cannot talk to each other.+ */+const HeldTooltipSimple = forwardRef<HTMLButtonElement, TooltipSimpleProps>(+ (props, ref) => (+ <UiTooltipSimple+ {...props}+ ref={ref}+ open={heldOpenState(props.open, props.title)}+ />+ ),+);++HeldTooltipSimple.displayName = 'TooltipSimple';++function HeldTooltipRoot({ open, ...props }: TooltipRootProps): JSX.Element {+ return <UiTooltipRoot {...props} open={heldOpenState(open, true)} />;+}++/**+ * The annotation checks the module's shape against the real one, so an export+ * added to the tooltip module fails to compile here rather than at render.+ */+const tooltipModule: typeof import('@signozhq/ui/tooltip') = {+ TooltipContent: UiTooltipContent,+ TooltipProvider: UiTooltipProvider,+ TooltipRoot: HeldTooltipRoot,+ TooltipSimple: HeldTooltipSimple,+ TooltipTrigger: UiTooltipTrigger,+};++export const {+ TooltipContent,+ TooltipProvider,+ TooltipRoot,+ TooltipSimple,+ TooltipTrigger,+} = tooltipModule;++export type {+ TooltipContentProps,+ TooltipProviderProps,+ TooltipRootProps,+ TooltipSimpleProps,+ TooltipTriggerProps,+ // eslint-disable-next-line signoz/no-signozhq-ui-barrel+} from '@signozhq/ui';diff --git a/frontend/src/storybook/mocks/tooltipsHeldOpen.ts b/frontend/src/storybook/mocks/tooltipsHeldOpen.tsnew file mode 100644index 0000000000..e9b368f48f--- /dev/null+++ b/frontend/src/storybook/mocks/tooltipsHeldOpen.ts@@ -0,0 +1,26 @@+import type { ReactNode } from 'react';++let held = false;++/** Set from the Tooltips control, through `globals/tooltipMocks.ts`. */+export const holdTooltipsOpen = (value: boolean): void => {+ held = value;+};++/**+ * The `open` a tooltip renders with while the control is on.+ *+ * A tooltip the page opens itself keeps its own state: only the page knows what+ * the popup is anchored to, and holding it open renders whatever it carries+ * while closed. An empty title has no popup to show, only the padding of one.+ */+export const heldOpenState = (+ own: boolean | undefined,+ title: ReactNode,+): boolean | undefined => {+ if (own !== undefined || !held) {+ return own;+ }++ return title === undefined || title === null || title === '' ? own : true;+};diff --git a/frontend/src/storybook/msw/__story_mockdata__/appShell.ts b/frontend/src/storybook/msw/__story_mockdata__/appShell.tsindex d496ff5f43..a4f4e502e5 100644--- a/frontend/src/storybook/msw/__story_mockdata__/appShell.ts+++ b/frontend/src/storybook/msw/__story_mockdata__/appShell.ts@@ -3,6 +3,7 @@* Do not hand-edit: regenerate instead.*/+import type { GetLicense200 } from 'api/generated/services/sigNoz.schemas';import { USER_PREFERENCES } from 'constants/userPreferences';import type { UserPreference } from 'types/api/preferences/preference';@@ -49,6 +50,43 @@ export const latestGithubReleaseResponse = {html_url: 'https://github.com/SigNoz/signoz/releases/tag/v0.0.0',};+/**+ * The license `useActiveLicenseKey` reads the key off, keyed by the id the+ * app-shell context carries. Only the key reaches the UI; the rest of the DTO+ * mirrors the context fixture so the two agree on which license this is.+ */+export const licenseWithKeyResponse = {+ status: 'success',+ data: {+ id: 'test-license-id',+ key: '96a1c6a4-3f1e-4b7d-9f2a-8c0d5e6f7a8b',+ state: 'ACTIVATED',+ status: 'VALID',+ platform: 'CLOUD',+ eventQueue: {+ createdAt: '0',+ event: '',+ scheduledAt: '0',+ status: '',+ updatedAt: '0',+ },+ plan: {+ id: '0',+ createdAt: '0',+ description: '',+ isActive: true,+ name: '',+ updatedAt: '0',+ },+ features: [],+ createdAt: '0',+ updatedAt: '0',+ freeUntil: '0',+ validFrom: 0,+ validUntil: 0,+ },+} satisfies GetLicense200;+export const globalConfigResponse = {status: 'success',data: {@@ -59,6 +97,18 @@ export const globalConfigResponse = {},};+/**+ * The Noz entry point in the top nav is off until the backend ships a URL for+ * it, so this variant answers with one.+ */+export const nozGlobalConfigResponse = {+ ...globalConfigResponse,+ data: {+ ...globalConfigResponse.data,+ ai_assistant_url: 'https://ai.storybook.signoz.local',+ },+};+/*** `ChangelogSchema` for the current version. Kept non-empty because* `getChangelogByVersion` treats an empty list as a failure, and media is leftdiff --git a/frontend/src/storybook/msw/__story_mockdata__/attributes.ts b/frontend/src/storybook/msw/__story_mockdata__/attributes.tsnew file mode 100644index 0000000000..4e88749cc0--- /dev/null+++ b/frontend/src/storybook/msw/__story_mockdata__/attributes.ts@@ -0,0 +1,43 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';+import type { IQueryAutocompleteResponse } from 'types/api/queryBuilder/queryAutocompleteResponse';+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';++/**+ * Typed builders for the v3 `/autocomplete/attribute_keys` and+ * `/autocomplete/attribute_values` pair, which the APM pages and the resource+ * attribute filter still read.+ */++interface AttributeKeysOptions {+ dataType?: DataTypes;+ type?: string;+}++export const attributeKeysResponse = (+ keys: readonly string[],+ { dataType = DataTypes.String, type = 'tag' }: AttributeKeysOptions = {},+): { status: string; data: IQueryAutocompleteResponse } => ({+ status: 'success',+ data: {+ attributeKeys: keys.map((key) => ({ key, dataType, type })),+ },+});++export const attributeValuesResponse = (+ values: readonly string[],+ searchText = '',+): { status: string; data: IAttributeValuesResponse } => ({+ status: 'success',+ data: {+ stringAttributeValues: values.filter((value) =>+ value.toLowerCase().includes(searchText.toLowerCase()),+ ),+ numberAttributeValues: null,+ boolAttributeValues: null,+ },+});diff --git a/frontend/src/storybook/msw/__story_mockdata__/dashboards.ts b/frontend/src/storybook/msw/__story_mockdata__/dashboards.tsnew file mode 100644index 0000000000..910aa47601--- /dev/null+++ b/frontend/src/storybook/msw/__story_mockdata__/dashboards.ts@@ -0,0 +1,37 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type { ListDashboardsForUserV2200 } from 'api/generated/services/sigNoz.schemas';+import { DashboardtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';++/**+ * The dashboards every explorer offers to export a panel into. Only the name+ * reaches the export menu, so the rest of a dashboard is the shape the endpoint+ * answers with and nothing more.+ */+export const dashboardsForUserResponse = (+ names: readonly string[],+): ListDashboardsForUserV2200 => ({+ status: 'success',+ data: {+ total: names.length,+ reservedKeywords: [],+ tags: [],+ dashboards: names.map((name, index) => ({+ id: `storybook-dashboard-${index + 1}`,+ orgId: 'storybook-org',+ name,+ spec: { display: { name } },+ schemaVersion: 'v2',+ source: DashboardtypesSourceDTO.user,+ legacy: false,+ locked: false,+ pinned: false,+ tags: [],+ createdBy: '[email protected]',+ updatedBy: '[email protected]',+ })),+ },+});diff --git a/frontend/src/storybook/msw/__story_mockdata__/fields.ts b/frontend/src/storybook/msw/__story_mockdata__/fields.tsnew file mode 100644index 0000000000..3de58f380b--- /dev/null+++ b/frontend/src/storybook/msw/__story_mockdata__/fields.ts@@ -0,0 +1,50 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ GetFieldsKeys200,+ GetFieldsValues200,+} from 'api/generated/services/sigNoz.schemas';+import {+ TelemetrytypesFieldContextDTO,+ TelemetrytypesSignalDTO,+} from 'api/generated/services/sigNoz.schemas';++/** Typed builders for the `/fields/keys` and `/fields/values` responses. */++interface FieldKeysOptions {+ signal?: TelemetrytypesSignalDTO;+ fieldContext?: TelemetrytypesFieldContextDTO;+}++/**+ * `keys` is a map from field name to every context that name was seen in, so a+ * single-context key is a one-entry array under its own name.+ */+export const fieldKeysResponse = (+ names: readonly string[],+ {+ signal = TelemetrytypesSignalDTO.metrics,+ fieldContext = TelemetrytypesFieldContextDTO.resource,+ }: FieldKeysOptions = {},+): GetFieldsKeys200 => ({+ status: 'success',+ data: {+ complete: true,+ keys: Object.fromEntries(+ names.map((name) => [name, [{ name, signal, fieldContext }]]),+ ),+ },+});++export const fieldValuesResponse = (+ values: readonly string[],+): GetFieldsValues200 => ({+ status: 'success',+ data: {+ complete: true,+ values: { stringValues: [...values], relatedValues: [...values] },+ },+});diff --git a/frontend/src/storybook/msw/__story_mockdata__/metrics.ts b/frontend/src/storybook/msw/__story_mockdata__/metrics.tsnew file mode 100644index 0000000000..ca47fdc558--- /dev/null+++ b/frontend/src/storybook/msw/__story_mockdata__/metrics.ts@@ -0,0 +1,71 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import {+ MetrictypesTemporalityDTO,+ MetrictypesTypeDTO,+ type GetMetricMetadata200,+ type ListMetrics200,+} from 'api/generated/services/sigNoz.schemas';++/**+ * A metric as the catalogue endpoints describe it. Anywhere a metric name is+ * typed, whether in the query builder's aggregation field or a panel's unit+ * seed, reads it from here.+ */+export interface MetricSeed {+ metricName: string;+ description: string;+ type: MetrictypesTypeDTO;+ temporality: MetrictypesTemporalityDTO;+ unit: string;+}++export const metricSeed = (+ metricName: string,+ description: string,+ unit = '',+ type = MetrictypesTypeDTO.sum,+ temporality = MetrictypesTemporalityDTO.cumulative,+): MetricSeed => ({ metricName, description, type, unit, temporality });++/** Sums are monotonic; gauges and histograms are not. */+const isMonotonic = (seed: MetricSeed): boolean =>+ seed.type === MetrictypesTypeDTO.sum;++export const listMetricsResponse = (+ seeds: readonly MetricSeed[],+ searchText = '',+): ListMetrics200 => {+ const search = searchText.toLowerCase();++ return {+ status: 'success',+ data: {+ metrics: seeds+ .filter((seed) => seed.metricName.toLowerCase().includes(search))+ .map((seed) => ({ ...seed, isMonotonic: isMonotonic(seed) })),+ },+ };+};++export const metricMetadataResponse = (+ seeds: readonly MetricSeed[],+ metricName: string,+): GetMetricMetadata200 => {+ const seed =+ seeds.find((candidate) => candidate.metricName === metricName) ?? seeds[0];++ return {+ status: 'success',+ data: {+ description: seed.description,+ type: seed.type,+ unit: seed.unit,+ temporality: seed.temporality,+ isMonotonic: isMonotonic(seed),+ },+ };+};diff --git a/frontend/src/storybook/msw/__story_mockdata__/queryBuilderAutocomplete.ts b/frontend/src/storybook/msw/__story_mockdata__/queryBuilderAutocomplete.tsnew file mode 100644index 0000000000..39fccd3b4d--- /dev/null+++ b/frontend/src/storybook/msw/__story_mockdata__/queryBuilderAutocomplete.ts@@ -0,0 +1,129 @@+import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';+import type {+ BaseAutocompleteData,+ IQueryAutocompleteResponse,+} from 'types/api/queryBuilder/queryAutocompleteResponse';+import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';+import { DataSource } from 'types/common/queryBuilder';++/**+ * The keys the legacy v3 query builder offers per signal, so a page that reaches+ * it without declaring its own autocomplete opens on a list that looks like the+ * product's rather than on a failed request.+ */+const ATTRIBUTE_KEYS: Record<DataSource, BaseAutocompleteData[]> = {+ [DataSource.LOGS]: [+ { key: 'body', dataType: DataTypes.String, type: '' },+ { key: 'severity_text', dataType: DataTypes.String, type: '' },+ { key: 'trace_id', dataType: DataTypes.String, type: '' },+ { key: 'service.name', dataType: DataTypes.String, type: 'resource' },+ {+ key: 'deployment.environment',+ dataType: DataTypes.String,+ type: 'resource',+ },+ { key: 'k8s.namespace.name', dataType: DataTypes.String, type: 'resource' },+ { key: 'k8s.pod.name', dataType: DataTypes.String, type: 'resource' },+ { key: 'http.status_code', dataType: DataTypes.Int64, type: 'tag' },+ { key: 'http.method', dataType: DataTypes.String, type: 'tag' },+ { key: 'log.level', dataType: DataTypes.String, type: 'tag' },+ ],+ [DataSource.TRACES]: [+ { key: 'name', dataType: DataTypes.String, type: '' },+ { key: 'durationNano', dataType: DataTypes.Int64, type: '' },+ { key: 'hasError', dataType: DataTypes.bool, type: '' },+ { key: 'service.name', dataType: DataTypes.String, type: 'resource' },+ {+ key: 'deployment.environment',+ dataType: DataTypes.String,+ type: 'resource',+ },+ { key: 'host.name', dataType: DataTypes.String, type: 'resource' },+ { key: 'http.method', dataType: DataTypes.String, type: 'tag' },+ { key: 'http.route', dataType: DataTypes.String, type: 'tag' },+ { key: 'response_status_code', dataType: DataTypes.String, type: 'tag' },+ { key: 'rpc.method', dataType: DataTypes.String, type: 'tag' },+ ],+ [DataSource.METRICS]: [+ { key: 'service_name', dataType: DataTypes.String, type: 'tag' },+ { key: 'operation', dataType: DataTypes.String, type: 'tag' },+ { key: 'status_code', dataType: DataTypes.String, type: 'tag' },+ { key: 'le', dataType: DataTypes.String, type: 'tag' },+ {+ key: 'resource_deployment.environment',+ dataType: DataTypes.String,+ type: 'resource',+ },+ { key: 'resource_host.name', dataType: DataTypes.String, type: 'resource' },+ {+ key: 'resource_k8s.cluster.name',+ dataType: DataTypes.String,+ type: 'resource',+ },+ ],+};++/**+ * Values per key, keyed on the last segment so `resource_service.name`,+ * `service.name` and `serviceName` all answer with the same list.+ */+const ATTRIBUTE_VALUES: Record<string, string[]> = {+ 'service.name': ['checkout', 'frontend', 'payments', 'cart', 'shipping'],+ service_name: ['checkout', 'frontend', 'payments', 'cart', 'shipping'],+ servicename: ['checkout', 'frontend', 'payments', 'cart', 'shipping'],+ 'deployment.environment': ['production', 'staging', 'canary'],+ 'k8s.namespace.name': ['default', 'observability', 'payments'],+ 'k8s.pod.name': ['checkout-7d9f', 'frontend-5b21', 'payments-0c4a'],+ 'host.name': ['ip-10-0-1-14', 'ip-10-0-2-31', 'ip-10-0-3-77'],+ 'k8s.cluster.name': ['prod-us-east-1', 'staging-eu-west-1'],+ 'http.status_code': ['200', '301', '404', '500'],+ status_code: ['200', '301', '404', '500'],+ response_status_code: ['200', '301', '404', '500'],+ 'http.method': ['GET', 'POST', 'PUT', 'DELETE'],+ 'http.route': ['/api/cart', '/api/checkout', '/api/products'],+ 'rpc.method': ['GetCart', 'PlaceOrder', 'ListProducts'],+ 'log.level': ['debug', 'info', 'warn', 'error'],+ severity_text: ['DEBUG', 'INFO', 'WARN', 'ERROR'],+ operation: ['HTTP GET', 'HTTP POST', 'grpc.Execute'],+ le: ['0.1', '0.5', '1', '5', '+Inf'],+};++const DEFAULT_VALUES = ['value-01', 'value-02', 'value-03'];++const isDataSource = (value: string | null): value is DataSource =>+ value !== null && value in ATTRIBUTE_KEYS;++const matches = (candidate: string, searchText: string): boolean =>+ candidate.toLowerCase().includes(searchText.toLowerCase());++export const autocompleteKeysResponse = (+ dataSource: string | null,+ searchText: string,+): { status: string; data: IQueryAutocompleteResponse } => ({+ status: 'success',+ data: {+ attributeKeys: ATTRIBUTE_KEYS[+ isDataSource(dataSource) ? dataSource : DataSource.LOGS+ ].filter((attribute) => matches(attribute.key, searchText)),+ },+});++export const autocompleteValuesResponse = (+ attributeKey: string | null,+ searchText: string,+): { status: string; data: IAttributeValuesResponse } => {+ const normalized = (attributeKey ?? '')+ .replace(/^resource_/, '')+ .toLowerCase();++ return {+ status: 'success',+ data: {+ stringAttributeValues: (+ ATTRIBUTE_VALUES[normalized] ?? DEFAULT_VALUES+ ).filter((value) => matches(value, searchText)),+ numberAttributeValues: null,+ boolAttributeValues: null,+ },+ };+};diff --git a/frontend/src/storybook/msw/__story_mockdata__/queryRange.ts b/frontend/src/storybook/msw/__story_mockdata__/queryRange.tsindex eb2fcd0a2d..4d321faa81 100644--- a/frontend/src/storybook/msw/__story_mockdata__/queryRange.ts+++ b/frontend/src/storybook/msw/__story_mockdata__/queryRange.ts@@ -3,15 +3,32 @@* Do not hand-edit: regenerate instead.*/-import type { MetricRangePayloadV5 } from 'types/api/v5/queryRange';+import type { Warning } from 'types/api';+import type { MetricRangePayloadV3 } from 'types/api/metrics/getQueryRange';+import type {+ ColumnDescriptor,+ MetricRangePayloadV5,+ RequestType,+ TimeSeries,+ TimeSeriesValue,+} from 'types/api/v5/queryRange';+import type { Column, SeriesItem } from 'types/api/widgets/getQuery';-/** Typed builders for the query_range v5 response shapes. */+/** Typed builders for the query_range response shapes, v5 first then v3. */++/** What every builder takes on top of its data: the warning the toolbar reads. */+interface ResponseOptions {+ queryName?: string;+ warning?: Warning;+}export const queryRangeV5ScalarResponse = (value: number,queryName = 'A',+ { warning }: Pick<ResponseOptions, 'warning'> = {},): MetricRangePayloadV5 => ({data: {+ warning,type: 'scalar',data: {results: [@@ -32,6 +49,68 @@ export const queryRangeV5ScalarResponse = (},});+/**+ * An aggregation column: the query it answers for, and which of that query's+ * aggregations it is when the query asked for several.+ */+export interface ScalarAggregationColumn {+ queryName: string;+ aggregationIndex?: number;+}++export interface ScalarTableSpec {+ /** Group-by columns, in the order the rows carry their values. */+ groupBy?: string[];+ /** Query names the aggregation columns answer for, after the group columns. */+ aggregations: Array<string | ScalarAggregationColumn>;+ rows: unknown[][];+}++/**+ * A table panel's answer: group columns first, then one column per query. The+ * legacy conversion keys each cell by the group column's name or the query's+ * name, which is what the table formatters read (`row.data.http_url`,+ * `row.data.A`).+ */+export const queryRangeV5ScalarTableResponse = ({+ groupBy = [],+ aggregations,+ rows,+}: ScalarTableSpec): MetricRangePayloadV5 => {+ const columns: ColumnDescriptor[] = [+ ...groupBy.map((name) => ({+ name,+ queryName: '',+ aggregationIndex: 0,+ columnType: 'group' as const,+ })),+ ...aggregations.map((aggregation) => {+ const { queryName, aggregationIndex = 0 } =+ typeof aggregation === 'string' ? { queryName: aggregation } : aggregation;++ return {+ name: `__result_${aggregationIndex}`,+ queryName,+ aggregationIndex,+ columnType: 'aggregation' as const,+ };+ }),+ ];++ return {+ data: {+ type: 'scalar',+ data: { results: [{ columns, data: rows }] },+ meta: {+ rowsScanned: rows.length,+ bytesScanned: 0,+ durationMs: 0,+ stepIntervals: {},+ },+ },+ };+};+export const queryRangeV5EmptyResponse = (queryName = 'A',): MetricRangePayloadV5 => ({@@ -46,13 +125,18 @@ export const queryRangeV5EmptyResponse = (export const queryRangeV5RawResponse = <T>(rows: Array<{ timestamp: string; data: T }>,- options: { queryName?: string; hasMore?: boolean } = {},+ options: ResponseOptions & {+ hasMore?: boolean;+ /** `trace` for the root-span views, which answer on the same shape. */+ type?: Extract<RequestType, 'raw' | 'trace'>;+ } = {},): MetricRangePayloadV5 => {- const { queryName = 'A', hasMore = false } = options;+ const { queryName = 'A', hasMore = false, type = 'raw', warning } = options;return {data: {- type: 'raw',+ warning,+ type,data: {results: [{@@ -71,3 +155,319 @@ export const queryRangeV5RawResponse = <T>(},};};++export interface TimeSeriesPointsOptions {+ /** Epoch milliseconds, as `query_range` sends them. */+ start: number;+ end: number;+ points?: number;+ base: number;+ amplitude: number;+ seed?: number;+}++/**+ * Points spread evenly across the requested window, so a chart drawn from them+ * lands inside whatever range the page asked for. The wave is derived from the+ * index rather than random, so a re-render redraws the same line.+ */+export const timeSeriesPoints = ({+ start,+ end,+ points = 30,+ base,+ amplitude,+ seed = 0,+}: TimeSeriesPointsOptions): TimeSeriesValue[] => {+ const step = (end - start) / Math.max(points - 1, 1);++ return Array.from({ length: points }, (_unused, index) => ({+ timestamp: Math.round(start + index * step),+ value:+ base ++ amplitude * Math.sin((index + seed) / 3) ++ amplitude * 0.3 * Math.cos((index + seed) / 7),+ }));+};++export interface TimeSeriesResult {+ /** The query or formula the series answers for, as the request named it. */+ queryName: string;+ series: TimeSeries[];+ alias?: string;+}++export const queryRangeV5TimeSeriesResponse = (+ results: TimeSeriesResult[],+ { warning }: Pick<ResponseOptions, 'warning'> = {},+): MetricRangePayloadV5 => ({+ data: {+ warning,+ type: 'time_series',+ data: {+ results: results.map(({ queryName, series, alias = '' }) => ({+ queryName,+ aggregations: [{ index: 0, alias, meta: {}, series }],+ })),+ },+ meta: { rowsScanned: 0, bytesScanned: 0, durationMs: 0, stepIntervals: {} },+ },+});++/**+ * The v3 shapes, which the legacy dashboard path still answers on: `GridCard`+ * without a `version` prop and `useGetValueFromWidget` both go to+ * `/api/v3/query_range` or `/api/v4/query_range` rather than v5.+ */+export interface QueryRangeV3Body extends MetricRangePayloadV3 {+ status: string;+}++export const v3Series = (+ labels: Record<string, string>,+ values: SeriesItem['values'],+): SeriesItem => ({+ labels,+ labelsArray: Object.entries(labels).map(([key, value]) => ({ [key]: value })),+ values,+});++/** Same wave as `timeSeriesPoints`, in the v3 spelling: values are strings. */+export const v3TimeSeriesValues = ({+ start,+ end,+ points = 30,+ base,+ amplitude,+ seed = 0,+}: TimeSeriesPointsOptions): SeriesItem['values'] =>+ timeSeriesPoints({ start, end, points, base, amplitude, seed }).map(+ ({ timestamp, value }) => ({+ timestamp,+ value: String(Number(value.toFixed(4))),+ }),+ );++export interface V3TimeSeriesResult {+ queryName: string;+ series: SeriesItem[];+ legend?: string;+}++export const queryRangeV3TimeSeriesResponse = (+ results: V3TimeSeriesResult[],+): QueryRangeV3Body => ({+ status: 'success',+ data: {+ resultType: 'matrix',+ result: results.map(({ queryName, series, legend }) => ({+ queryName,+ legend,+ series,+ list: null,+ })),+ },+});++export interface V3TableResult {+ queryName: string;+ columns: Column[];+ rows: Array<Record<string, string | number>>;+}++export const queryRangeV3TableResponse = (+ results: V3TableResult[],+): QueryRangeV3Body => ({+ status: 'success',+ data: {+ resultType: 'table',+ result: results.map(({ queryName, columns, rows }) => ({+ queryName,+ series: null,+ list: null,+ table: { columns, rows: rows.map((data) => ({ data })) },+ })),+ },+});++export const queryRangeV3EmptyResponse = (+ queryNames: string[],+): QueryRangeV3Body => ({+ status: 'success',+ data: {+ resultType: 'matrix',+ result: queryNames.map((queryName) => ({+ queryName,+ series: [],+ list: null,+ })),+ },+});++/**+ * Every builder-query panel asks for the same shape back, keyed by `queryName`,+ * so a page whose widgets are all builder queries answers them from the request+ * rather than one handler per widget: one series (or row) per group-by+ * combination the query asked for, and a single one where it grouped by nothing.+ */+export interface BuilderResponseOptions {+ /** Series per time-series query, or rows per table query. */+ count?: number;+ /** Values a group-by key is given, so a legend reads like the real one. */+ labelValues?: Record<string, readonly string[]>;+}++const builderLabelValue = (+ key: string,+ index: number,+ labelValues: Record<string, readonly string[]>,+): string => {+ const pool = labelValues[key];++ return pool ? pool[index % pool.length] : `${key}-${index + 1}`;+};++const builderGroupByKeys = (query: {+ groupBy?: Array<{ key: string }>;+}): string[] => (query.groupBy ?? []).map((attribute) => attribute.key);++interface BuilderQueryShape {+ queryName: string;+ legend?: string;+ disabled?: boolean;+ groupBy?: Array<{ key: string }>;+}++interface BuilderRequestShape {+ start: number;+ end: number;+ compositeQuery: {+ panelType?: string;+ builderQueries?: Record<string, BuilderQueryShape>;+ };+}++const allQueries = (body: BuilderRequestShape): BuilderQueryShape[] =>+ Object.values(body.compositeQuery.builderQueries ?? {});++const enabledQueries = (body: BuilderRequestShape): BuilderQueryShape[] =>+ allQueries(body).filter((query) => !query.disabled);++/**+ * A formula carries no `groupBy` of its own: it is grouped by whatever the+ * queries it combines were, so its series take the same labels and a `{{key}}`+ * legend resolves on it too. Those queries are usually disabled — the widget+ * draws the formula alone — so the group-by is read off every query in the+ * request, not just the ones that answer.+ */+const keysFor = (+ query: BuilderQueryShape,+ queries: BuilderQueryShape[],+): string[] =>+ query.groupBy !== undefined+ ? builderGroupByKeys(query)+ : [+ ...new Set(+ queries+ .filter((candidate) => candidate.groupBy !== undefined)+ .flatMap(builderGroupByKeys),+ ),+ ];++export const builderTimeSeriesResponse = (+ body: BuilderRequestShape,+ { count = 1, labelValues = {} }: BuilderResponseOptions = {},+): QueryRangeV3Body => {+ const { start, end } = body;+ const isValue = body.compositeQuery.panelType === 'value';++ const queries = allQueries(body);++ return queryRangeV3TimeSeriesResponse(+ enabledQueries(body).map((query, queryIndex) => {+ const keys = keysFor(query, queries);+ const seriesCount = isValue || !keys.length ? Math.min(count, 1) : count;++ return {+ queryName: query.queryName,+ legend: query.legend,+ series: Array.from({ length: seriesCount }, (_unused, seriesIndex) =>+ v3Series(+ Object.fromEntries(+ keys.map((key) => [+ key,+ builderLabelValue(key, seriesIndex, labelValues),+ ]),+ ),+ v3TimeSeriesValues({+ start,+ end,+ points: isValue ? 1 : 30,+ base: 40 + queryIndex * 15 + seriesIndex * 8,+ amplitude: 12 + seriesIndex * 3,+ seed: queryIndex * 5 + seriesIndex,+ }),+ ),+ ),+ };+ }),+ );+};++export const builderTableResponse = (+ body: BuilderRequestShape,+ { count = 1, labelValues = {} }: BuilderResponseOptions = {},+): QueryRangeV3Body => {+ const queries = enabledQueries(body);+ const keys = [+ ...new Set(queries.flatMap((query) => keysFor(query, allQueries(body)))),+ ];++ const columns: Column[] = [+ ...keys.map((name) => ({ name, queryName: '', isValueColumn: false })),+ ...queries.map((query) => ({+ name: query.queryName,+ queryName: query.queryName,+ isValueColumn: true,+ })),+ ];++ const rows = Array.from({ length: count }, (_unused, index) => ({+ data: {+ ...Object.fromEntries(+ keys.map((key) => [key, builderLabelValue(key, index, labelValues)]),+ ),+ ...Object.fromEntries(+ queries.map((query, queryIndex) => [+ query.queryName,+ seededMetricValue(index + queryIndex, 20 + queryIndex * 30, 60),+ ]),+ ),+ },+ }));++ return {+ status: 'success',+ data: {+ resultType: 'table',+ result: [+ { queryName: 'A', series: null, list: null, table: { columns, rows } },+ ],+ },+ };+};++/** Derived from the index rather than random, so a refetch redraws the same values. */+export const seededMetricValue = (+ index: number,+ base: number,+ spread: number,+): number => Number((base + (spread * ((index * 37) % 100)) / 100).toFixed(2));++export const queryRangeV3ForRequest = (+ body: BuilderRequestShape,+ options: BuilderResponseOptions = {},+): QueryRangeV3Body =>+ body.compositeQuery.panelType === 'table'+ ? builderTableResponse(body, options)+ : builderTimeSeriesResponse(body, options);diff --git a/frontend/src/storybook/msw/__story_mockdata__/quickFilters.ts b/frontend/src/storybook/msw/__story_mockdata__/quickFilters.tsnew file mode 100644index 0000000000..c19601789d--- /dev/null+++ b/frontend/src/storybook/msw/__story_mockdata__/quickFilters.ts@@ -0,0 +1,24 @@+/**+ * AI-owned. Generated and maintained by the `signoz-page-story` skill.+ * Do not hand-edit: regenerate instead.+ */++import type {+ GetQuickFilters200,+ QuickfiltertypesSourceDTO,+ TelemetrytypesTelemetryFieldKeyDTO,+} from 'api/generated/services/sigNoz.schemas';++/** Typed builder for `/api/v2/quick_filters/{source}`. */+export const quickFiltersResponse = (+ source: QuickfiltertypesSourceDTO,+ filters: readonly TelemetrytypesTelemetryFieldKeyDTO[],+): GetQuickFilters200 => ({+ status: 'success',+ data: {+ id: `quick-filters-${source}`,+ orgId: 'org-signoz',+ source,+ filters: [...filters],+ },+});diff --git a/frontend/src/storybook/msw/appShellHandlers.ts b/frontend/src/storybook/msw/appShellHandlers.tsindex fd08eaa4d1..6a96226949 100644--- a/frontend/src/storybook/msw/appShellHandlers.ts+++ b/frontend/src/storybook/msw/appShellHandlers.ts@@ -4,6 +4,8 @@ import {changelogResponse,globalConfigResponse,latestGithubReleaseResponse,+ licenseWithKeyResponse,+ nozGlobalConfigResponse,userPreferencesResponse,versionResponse,zeusHostsResponse,@@ -32,6 +34,19 @@ export const appShellHandlers = [res(ctx.status(200), ctx.json(globalConfigResponse)),),+ // The settings, account and billing pages each read the workspace's licence+ // key off this endpoint, which the app-shell context does not cover: it+ // carries the active licence, and the key is only served by id.+ rest.get('http://localhost/api/v4/licenses/:id', (_req, res, ctx) =>+ res(ctx.status(200), ctx.json(licenseWithKeyResponse)),+ ),++ // `RefreshPaymentStatus`, which the billing tab, the payment banners and the+ // locked and suspended pages all carry.+ rest.put('http://localhost/api/v4/licenses/:id', (_req, res, ctx) =>+ res(ctx.status(200)),+ ),+rest.get('http://localhost/api/v1/version', (_req, res, ctx) =>res(ctx.status(200), ctx.json(versionResponse)),),@@ -54,3 +69,14 @@ export const appShellHandlers = [res(ctx.status(200), ctx.text('')),),];++/**+ * A story's own `parameters.msw.handlers` are resolved ahead of+ * `appShellHandlers`, so the `Foundations/Tooltips` Noz story wires this in to+ * override the global config's `ai_assistant_url` without the default set+ * doing so for every other story.+ */+export const nozGlobalConfigHandler = rest.get(+ 'http://localhost/api/v1/global/config',+ (_req, res, ctx) => res(ctx.status(200), ctx.json(nozGlobalConfigResponse)),+);diff --git a/frontend/src/storybook/msw/handlers.ts b/frontend/src/storybook/msw/handlers.tsindex 4e1256920d..ed36d6f6a4 100644--- a/frontend/src/storybook/msw/handlers.ts+++ b/frontend/src/storybook/msw/handlers.ts@@ -2,6 +2,7 @@ import { rest } from 'msw';import { handlers as sharedHandlers } from 'mocks-server/handlers';import { appShellHandlers } from './appShellHandlers';+import { queryBuilderHandlers } from './queryBuilderHandlers';/*** Last resort: every axios instance is built on `ENVIRONMENT.baseURL`, which@@ -24,13 +25,15 @@ const unmockedApiGuard = [/*** Default handler set for every story, resolved first match wins: the- * Storybook-only shell handlers override the jest ones where the shell needs- * richer data, and both a page's control-driven handlers and a story's own- * `parameters.msw.handlers` are layered on top at render time. An endpoint both- * runners need belongs in `src/mocks-server/handlers.ts` instead.+ * Storybook-only shell and query builder handlers override the jest ones where+ * those answer with a fixture too thin for a page to render on, and both a+ * page's control-driven handlers and a story's own `parameters.msw.handlers`+ * are layered on top at render time. An endpoint both runners need belongs in+ * `src/mocks-server/handlers.ts` instead.*/export const storybookHandlers = [...appShellHandlers,+ ...queryBuilderHandlers,...sharedHandlers,...unmockedApiGuard,];diff --git a/frontend/src/storybook/msw/queryBuilderHandlers.ts b/frontend/src/storybook/msw/queryBuilderHandlers.tsnew file mode 100644index 0000000000..ebc9aad3ae--- /dev/null+++ b/frontend/src/storybook/msw/queryBuilderHandlers.ts@@ -0,0 +1,78 @@+import { rest } from 'msw';++import {+ autocompleteKeysResponse,+ autocompleteValuesResponse,+} from './__story_mockdata__/queryBuilderAutocomplete';++/**+ * The query shapes `src/mocks-server/handlers.ts` answers from its own fixture:+ * the APM resource attribute filter, the one case its two autocomplete handlers+ * were written for. Everything else there falls through to a 500, which is what+ * these handlers exist to cover, so those shapes are handed back rather than+ * answered twice with different data.+ */+const isSharedFixtureKeysQuery = (params: URLSearchParams): boolean =>+ params.get('metricName') === 'signoz_calls_total' &&+ params.get('match') === 'resource_';++const isSharedFixtureValuesQuery = (params: URLSearchParams): boolean => {+ const attributeKey = params.get('attributeKey');++ return (+ attributeKey === 'serviceName' ||+ attributeKey === 'name' ||+ (params.get('metricName') === 'signoz_calls_total' &&+ params.get('tagKey') === 'resource_signoz_collector_id')+ );+};++/**+ * The legacy v3 autocomplete pair. The jest handlers answer it for the one query+ * the suite asserts on and return 500 for every other, which is every other+ * filter input in the product: the panel editor's logs list panel, the+ * explorers' legacy query builder, the resource attribute filter on a signal+ * they were not written for. Resolved ahead of the jest set so those get a+ * usable list; a page that wants its own keys still declares them and wins over+ * both. Returning nothing hands the request on to the next matching handler.+ */+export const queryBuilderHandlers = [+ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_keys',+ (req, res, ctx) => {+ if (isSharedFixtureKeysQuery(req.url.searchParams)) {+ return undefined;+ }++ return res(+ ctx.status(200),+ ctx.json(+ autocompleteKeysResponse(+ req.url.searchParams.get('dataSource'),+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ );+ },+ ),++ rest.get(+ 'http://localhost/api/v3/autocomplete/attribute_values',+ (req, res, ctx) => {+ if (isSharedFixtureValuesQuery(req.url.searchParams)) {+ return undefined;+ }++ return res(+ ctx.status(200),+ ctx.json(+ autocompleteValuesResponse(+ req.url.searchParams.get('attributeKey') ??+ req.url.searchParams.get('tagKey'),+ req.url.searchParams.get('searchText') ?? '',+ ),+ ),+ );+ },+ ),+];diff --git a/frontend/src/storybook/navigation/pageScope.ts b/frontend/src/storybook/navigation/pageScope.tsindex 2f977907a8..5c2285b50a 100644--- a/frontend/src/storybook/navigation/pageScope.ts+++ b/frontend/src/storybook/navigation/pageScope.ts@@ -5,6 +5,19 @@ import {parsePath,} from 'history';+/**+ * Query keys the Storybook preview owns. They live in the iframe's URL, which+ * the app has no business reading or rewriting.+ */+const PREVIEW_PARAMS = [+ 'id',+ 'viewMode',+ 'args',+ 'globals',+ 'path',+ 'singleStory',+];+/*** The story's own history. A story renders one page, so this never leaves it:* `pageScope` decides what counts as staying, and `containment.ts` is what the@@ -17,6 +30,45 @@ export const storyHistory: MemoryHistory = createMemoryHistory({export const toHref = (to: LocationDescriptor): string =>typeof to === 'string' ? to : storyHistory.createHref(to);+const withoutPreviewParams = (search: string): URLSearchParams => {+ const params = new URLSearchParams(search);+ PREVIEW_PARAMS.forEach((param) => params.delete(param));+ return params;+};++/**+ * Copies the story's search onto the iframe's URL, keeping the preview's own+ * params. A lot of the app reads `window.location.search` directly rather than+ * through the router, which is how every writer that rebuilds a target on top+ * of the current params reads them. In a story that read would otherwise answer+ * with the preview's query and nothing the page put there, so two writers+ * publish over each other forever: the query builder drops the time range, the+ * time range drops the query builder, and the page never settles.+ */+const mirrorSearchToBrowser = (): void => {+ const mirrored = new URLSearchParams();++ const previewParams = new URLSearchParams(window.location.search);+ PREVIEW_PARAMS.forEach((param) => {+ const value = previewParams.get(param);+ if (value !== null) {+ mirrored.set(param, value);+ }+ });++ withoutPreviewParams(storyHistory.location.search).forEach((value, key) => {+ mirrored.set(key, value);+ });++ window.history.replaceState(+ window.history.state,+ '',+ `${window.location.pathname}?${mirrored}${window.location.hash}`,+ );+};++storyHistory.listen(mirrorSearchToBrowser);+/** `/home/` and `/home` are the same page as far as a story is concerned. */const normalizePathname = (pathname: string): string =>pathname.length > 1 && pathname.endsWith('/')@@ -43,8 +95,12 @@ export const navigateWithinPage = (return false;}+ // The preview's params ride along in whatever the app read out of+ // `window.location.search`, so they are dropped on the way back in and the+ // story's history stays the page's own URL.storyHistory[replace ? 'replace' : 'push']({...target,+ search: `?${withoutPreviewParams(target.search ?? '')}`,pathname: storyHistory.location.pathname,});@@ -54,6 +110,7 @@ export const navigateWithinPage = (/** Places the story at a route without going through the block. */export const setStoryLocation = (to: LocationDescriptor): void => {storyHistory.replace(to);+ mirrorSearchToBrowser();};/**diff --git a/frontend/src/storybook/providers/StorybookProviders.tsx b/frontend/src/storybook/providers/StorybookProviders.tsxindex 1b6904f7cf..f530a5885e 100644--- a/frontend/src/storybook/providers/StorybookProviders.tsx+++ b/frontend/src/storybook/providers/StorybookProviders.tsx@@ -13,6 +13,7 @@ import { NuqsTestingAdapter } from 'nuqs/adapters/testing';import { AppContext, useAppContext } from 'providers/App/App';import { createStoryAppContext } from '../mocks/createStoryAppContext';+import { setStoryStore } from '../mocks/store.mock';import { interceptExternalNavigation } from '../navigation/interceptExternalNavigation';import NavigationBlockedOverlay from '../navigation/NavigationBlockedOverlay';import { ResolvedStoryConfig } from '../types';@@ -59,11 +60,18 @@ function StorybookProviders({queryBuilder,route = '/',layout = 'none',+ routeState,reduxState,}: StorybookProvidersProps): JSX.Element {- const searchParams = useStoryRoute(route);+ const searchParams = useStoryRoute(route, routeState);const queryClient = useMemo(createStorybookQueryClient, []);- const store = useMemo(() => createStorybookStore(reduxState), [reduxState]);+ const store = useMemo(() => {+ const created = createStorybookStore(reduxState);+ // The modules that read the redux singleton have to answer from this story's+ // store, not the one the app module created at import time.+ setStoryStore(created);+ return created;+ }, [reduxState]);const appContextValue = useMemo(() => createStoryAppContext(role, appContext),[role, appContext],diff --git a/frontend/src/storybook/providers/createStorybookStore.ts b/frontend/src/storybook/providers/createStorybookStore.tsindex c704f28482..f61ee077c5 100644--- a/frontend/src/storybook/providers/createStorybookStore.ts+++ b/frontend/src/storybook/providers/createStorybookStore.ts@@ -10,6 +10,8 @@ import reducers, { AppState } from 'store/reducers';/*** A fresh store per story, seeded with the real reducers so dispatches keep* working, unlike the mock store used in jest. Nothing leaks between stories.+ * The modules that read the redux singleton directly are pointed at it too,+ * through `mocks/store.mock.ts`.*/export const createStorybookStore = (reduxState?: Partial<AppState>): Store =>createStore(diff --git a/frontend/src/storybook/providers/useStoryRoute.ts b/frontend/src/storybook/providers/useStoryRoute.tsindex 0c3f3f8c06..4160b0f09d 100644--- a/frontend/src/storybook/providers/useStoryRoute.ts+++ b/frontend/src/storybook/providers/useStoryRoute.ts@@ -1,4 +1,5 @@import { useMemo } from 'react';+import { parsePath } from 'history';import { setStoryLocation } from '../navigation/pageScope';@@ -6,9 +7,12 @@ import { setStoryLocation } from '../navigation/pageScope';* Places the story's history at its route before the router mounts and hands* back the search params for the nuqs testing adapter.*/-export const useStoryRoute = (route: string): URLSearchParams =>+export const useStoryRoute = (+ route: string,+ routeState?: unknown,+): URLSearchParams =>useMemo(() => {- setStoryLocation(route);+ setStoryLocation({ ...parsePath(route), state: routeState });const [, search = ''] = route.split('?');return new URLSearchParams(search);- }, [route]);+ }, [route, routeState]);diff --git a/frontend/src/storybook/runtime/resolveStory.ts b/frontend/src/storybook/runtime/resolveStory.tsindex 34ca0dada5..108122ccd7 100644--- a/frontend/src/storybook/runtime/resolveStory.ts+++ b/frontend/src/storybook/runtime/resolveStory.ts@@ -80,8 +80,34 @@ const firstAnswer = <TAnswer>(): TAnswer =>answers.find((answer): answer is TAnswer => answer !== undefined) ?? fallback;+const parametersLookClobbered = (parameters: SignozStoryParameters): boolean =>+ !parameters.signoz && Boolean(parameters.docs?.description?.component);++/**+ * `parameters.signoz` gone while a docs description is there is the signature of+ * a meta that spreads `storyMocks(...)` and lets the csf plugin append its own+ * `parameters` after it: the doc comment above `const meta` compiles to a+ * `parameters` property, which overwrites the one the spread brought. The page+ * then renders against the global handlers only, which reads as a page whose+ * endpoints are all unmocked. The meta has to re-state+ * `parameters: { ...pageStory.parameters }` after the spread.+ */+const warnOnClobberedParameters = (context: StoryRuntimeContext): void => {+ if (parametersLookClobbered(context.parameters)) {+ // eslint-disable-next-line no-console+ console.error(+ `[storybook] ${context.id} has a docs description but no parameters.signoz: ` ++ 'the doc comment above `const meta` overwrote the mocks. Add ' ++ '`parameters: { ...pageStory.parameters }` after the spread.',+ );+ }+};+const resolveWorld = (context: StoryRuntimeContext): StoryWorld => {const { parameters, args } = context;++ warnOnClobberedParameters(context);+const storyConfig = parameters.signoz ?? {};// A page's own mocks resolve ahead of the global ones, so the page wins everydiff --git a/frontend/src/storybook/types.ts b/frontend/src/storybook/types.tsindex 84d11ca1c3..2e6946bf37 100644--- a/frontend/src/storybook/types.ts+++ b/frontend/src/storybook/types.ts@@ -20,6 +20,11 @@ export interface StoryOwnedConfig {queryBuilder?: Partial<QueryBuilderContextType>;/** Initial route, search included, e.g. `/home?relativeTime=1h`. */route?: string;+ /**+ * `location.state` the story starts on, for a page reached by a push that+ * carried state rather than by its URL alone.+ */+ routeState?: unknown;/** Overrides the theme toolbar for this story. */theme?: StoryTheme;/**@@ -55,4 +60,6 @@ export interface ResolvedStoryConfig extends StoryOwnedConfig {export interface SignozStoryParameters {signoz?: SignozStoryConfig;msw?: StoryMswParameter;+ /** Written by the csf plugin from the doc comments in the story file. */+ docs?: { description?: { component?: string } };}