Compare commits

..

29 Commits

Author SHA1 Message Date
Manika Malhotra
c47aadb714 feat(frontend): adopt reworked @signozhq/ui components across remaining areas (#13087)
Some checks are pending
build-staging / prepare (push) Waiting to run
build-staging / js-build (push) Blocked by required conditions
build-staging / go-build (push) Blocked by required conditions
build-staging / staging (push) Blocked by required conditions
cacheci / tests (push) Waiting to run
Release Drafter / update_release_draft (push) Waiting to run
#### Summary

> You can see the sbshot diff at:
https://pr-docs.viniciusl.com.br/signoz-v3-pr13087-1118

Closes https://github.com/SigNoz/uforge-pod/issues/6284

This PR moves the rest of the app onto the reworked SigNoz UI library
(0.4.0-rc.4) and the new design tokens. Inputs, selects, dialogs,
drawers, popovers, toasts and text now all come from the library, so a
later design change happens in one place instead of in overrides on each
page.

Pages should look and work as they do on main. If something looks
different and is not mentioned below, treat it as a bug.

#### What looks different

Text now uses Inter from the design tokens, so numbers and a few letters
look slightly different, and monospace text uses the system code font.
Truncated text shows its full value on hover. Error toasts stay on
screen until you dismiss them.

A few flows changed on purpose. Saving or renaming a view opens a dialog
instead of a small popover. The Kubernetes entity drawer has a
breadcrumb, so you can go back to the entity you came from.

#### How to review

The commits are grouped by area and named after the pod that owns it,
such as pulse-dashboards or events-traces, so each team can review only
its part. Shared components, the query builder and styles come first,
and the tests sit in the last three commits. Only the final commit
builds, because the library upgrade breaks every page at once.

On your pages, the things most likely to be off are field heights,
spacing, text that now wraps or truncates, and popups opened from inside
a drawer or dialog. Most pages have Storybook stories from #13493, which
this PR is stacked on.

#### What changed in the components

Each block below shows one component, with a before and after taken from
this PR.

<details>
<summary>Typography</summary>

Typography is now a single component. Instead of choosing between Text
and Title, you pick a variant (paragraph, label, uppercase or code), a
size and a weight. Capitals only come from the uppercase variant, and
"muted" is now "secondary". Text cut with an ellipsis shows the full
value in a tooltip.

```diff
- <Typography.Text className="total"> of {total}</Typography.Text>
+ <Typography variant="paragraph" size="base" weight="regular" color="inherit" as="span" textOverflow="wrap">
+   of {total}
+ </Typography>
```

</details>

<details>
<summary>Dialog and AlertDialog</summary>

Dialogs take a single close callback instead of an open-change handler,
and footers are split into a left and a right slot. Confirmations moved
from ConfirmDialog to AlertDialog. Library dialogs now sit above antd
modals.

```diff
- <ConfirmDialog
-   onOpenChange={(next): void => {
-     if (!next) {
-       handleDiscardCancel();
-     }
-   }}
-   confirmColor="danger"
+ <AlertDialog
+   color="danger"
```

</details>

<details>
<summary>Drawer</summary>

Drawers close the same way as dialogs. A drawer has to say whether it
blocks the page (a task) or sits beside it (an inspector), and how it
stacks over other drawers. A drawer can also show a breadcrumb trail,
which the Kubernetes entity drawer uses to step back.

```diff
- <DrawerWrapper
-   onOpenChange={(isOpen): void => {
-     if (!isOpen) {
-       onClose();
-     }
-   }}
+ <Drawer
+   type="task"
+   stack="overlay"
+   closePosition="start"
+   trail={trail}
+   onTrailSelect={handleTrailSelect}
+   onClose={onClose}
```

</details>

<details>
<summary>Popover</summary>

Popovers take their trigger as a prop instead of being assembled from
parts. The content unmounts when the popover closes.

```diff
- <Popover>
-   <PopoverTrigger asChild>{button}</PopoverTrigger>
-   <PopoverContent align="end">{content}</PopoverContent>
- </Popover>
+ <Popover nativeButton side="bottom" align="end" trigger={button}>
+   {content}
+ </Popover>
```

</details>

<details>
<summary>Input</summary>

Inputs no longer take a container class name. Wrap them, or use the
width and size props. The test id and data attributes now sit on the
outer frame, and the input element gets the same id with a "-field"
suffix. Number inputs use Input.Number, which hands back a number or
null, so the string parsing at call sites is gone.

```diff
- <Input
-   testId="panel-type-search"
-   containerClassName={styles.search}
- />
+ <div className={styles.search}>
+   <Input testId="panel-type-search" />
+ </div>
```

</details>

<details>
<summary>Select and Combobox</summary>

SelectSimple and ComboboxSimple are now Select and Combobox. They size
with a width prop instead of a class name, and take a placeholder. The
roles picker moved from antd Select to Combobox.

```diff
- <SelectSimple
-   className={styles.filtersBarSource}
+ <Select
+   width={160}
+   placeholder="Filter by source"
```

</details>

<details>
<summary>Toast</summary>

Toasts come from the library toast module. An error toast is now called
danger, and it needs an action because it stays until dismissed.

```diff
- toast.error('Failed to copy link');
+ toast.danger('Failed to copy link', { action: { label: 'Dismiss' } });
```

</details>

<details>
<summary>Callout</summary>

Callouts use color names (primary, danger, warning), take their text as
children and render links with Callout.Link.

```diff
- <Callout type="info" showIcon title="Store the key securely." />
+ <Callout color="primary" size="sm" icon={<SolidInfoCircle />}>
+   Store the key securely.
+ </Callout>
```

</details>

<details>
<summary>AlertStrip</summary>

The no-auth banner moved from our own persisted banner to the library
AlertStrip, which remembers when it was closed.

```diff
- <PersistedAnnouncementBanner type="warning" className={styles.banner}>
-   <a href={docsLink} rel="noreferrer">
+ <AlertStrip.CloseablePersisted color="warning" side={bottomSlot ? 'bottom' : 'top'}>
+   <AlertStrip.Link href={docsLink}>
```

</details>

<details>
<summary>Resizable</summary>

Resizable takes its panes as an items array instead of panel and handle
parts, and saves the layout under a storage key.

```diff
- <ResizablePanelGroup id="panel-editor-v2">
-   <ResizablePanel minSize="75%" maxSize="80%" defaultSize="80%">
+ <Resizable
+   orientation="horizontal"
+   storageKey="panel-editor-v2"
+   storage={layoutStorage}
+   items={[{ value: 'main', label: 'Preview and editor', minSize: '75%', maxSize: '80%' }]}
```

</details>

<details>
<summary>Breadcrumb</summary>

Breadcrumb takes an items array instead of list, item, link and
separator parts.

```diff
- <Breadcrumb>
-   <BreadcrumbList>
-     <BreadcrumbItem>
-       <BreadcrumbLink icon={<LayoutGrid size={14} />} href={dashboardPageLink}>
+ <Breadcrumb
+   testId="dashboard-page-breadcrumb"
+   items={[
+     { title: 'Dashboard', icon: <LayoutGrid size={14} />, href: dashboardPageLink },
+     { title },
+   ]}
+ />
```

</details>

<details>
<summary>Kbd</summary>

Kbd takes the key name as a value, and named keys render as glyphs
(Escape shows ⎋).

```diff
- <Kbd>Esc</Kbd>
+ <Kbd value="Escape" testId="pie-tooltip-escape-key" />
```

</details>

<details>
<summary>Smaller changes</summary>

Tabs and Toaster no longer accept a class name, so the styles moved to a
wrapper. Avatar needs a name, which it uses for the initials. List
headers show their count in a Badge, with a Skeleton while the count
loads.

</details>

#### Patterns in the code

<details>
<summary>Details</summary>

Most of the diff is text styling. About 2,500 font declarations left the
SCSS files. They were replaced by Typography props or, where a
stylesheet still needs them, by the new text-style tokens described in
the CSS modules guide. The old font size, weight and line height tokens
no longer exist in design tokens 2.7.0, and the legacy card background
is now surface-2.

```diff
- font-size: var(--font-size-sm);
- font-weight: var(--font-weight-normal);
+ font-size: var(--paragraph-base-400-font-size);
```

Tests find inputs through the "-field" id. They pick combobox options by
typing in the search box and pressing Enter, since jsdom cannot click
the new options. The e2e drivers have shared helpers for inputs,
comboboxes and toasts, described in tests/e2e/AGENTS.md.

```diff
- await user.click(await screen.findByLabelText('Roles'));
- await user.click(await screen.findByTitle('signoz-editor'));
+ await user.click(await screen.findByTestId('member-roles-select'));
+ await user.type(
+   await screen.findByTestId('member-roles-select-search'),
+   `${managedRoles[1].name}{Enter}`,
+ );
```

</details>

#### New lint rules

Text style now belongs to Typography, and two rules keep it there. Both
warn for now, because about 2,700 font declarations remain in SCSS.

- signoz/no-text-css (oxlint) flags font and text properties in style
props, CSSProperties objects and styled-components.
- Stylelint flags the same properties in SCSS.

You can disable either rule where Typography cannot render the text,
such as canvas or chart labels. The disable must say why after "--", or
it fails as an error.

<details>
<summary>Example</summary>

```tsx
// oxlint-disable-next-line signoz/no-text-css -- canvas text, not DOM
ctx.font = '12px Inter';
```

```scss
/* stylelint-disable-next-line property-disallowed-list -- antd table header, no Typography slot */
font-weight: 500;
```

</details>

---------

Co-authored-by: Vinícius Lourenço <vinicius@signoz.io>
2026-11-20 19:42:44 +05:30
Vinicius Lourenço
d317275b36 test(storybook): cover the states the component migration changes (#13493)
#### Description

This PR adds the stories we wrote while migrating to the new version of
`@signozhq/ui` (#13087), but running against the components we have on
main today.

I'm splitting them out so the screenshot diff of the migration has a
"before" for every story. Without this, the new stories only exist on
the migration branch and there is nothing to compare them with.

They cover the states the migration touches: open selects, dialogs,
drawers and popovers, more toast variants, the command palette, the
license and trial banners, the K8s drawer opened a few levels deep, SSO
attribute mapping and the query builder add-ons. A few existing plays
also moved into their `*.play.ts` files. No app code changes, only
stories and the mocks they need.

#### Screenshots / Screen Recordings

Every new story, in dark and light:
https://claude.ai/artifact/TeBTXRkB9puh7W6LnGXFQ8

#### Additional Information

#13087 sits on top of this one, so its diff only shows the migration.

---------

Co-authored-by: Manika Malhotra <manika@signoz.io>
2026-11-20 19:41:57 +05:30
Vikrant Gupta
61bc6698d1 feat(serviceaccount): paginate and filter the list endpoint (#13545)
#### Description

- `GET /api/v1/service_accounts` returns a page (`serviceAccounts`,
`total`, `reservedKeywords`) with `limit`, `offset`, `sort` and `order`.
- `query` is a SigNoz filter expression over `name`, `email`, `status`,
`created_at` and `updated_at`; a bare token matches name or email.

#### Issues Closed by this PR

Closes: https://github.com/SigNoz/keystone-pod/issues/221

---------

Co-authored-by: hardik-signoz <hardik.saini@signoz.io>
2026-11-20 11:59:55 +00:00
Ashwin Bhatkal
518def70e0 feat(infra-monitoring): keep filters when switching kubernetes resources (#13406)
#### Description

- Switching resources under "Viewing · Resource" no longer clears the
filter. Clauses the new resource can filter by are kept and the rest are
dropped, the same rule the drawer already uses, so the quick filter
checkboxes stay in step.
- The drawer's locked filter shows every clause instead of the last one
plus a `+N` count, so the scope reads without hovering. The existing
"Infra monitoring/Drawer overview tab" story already renders this state.
- Switching resources no longer changes what a filter means. A filter
with an OR, or a NOT over a group, is not carried at all, because no
subset of its clauses means the same thing. A clause with a leading NOT
is left out and the rest are carried. Before, `a = 1 OR b = 2` arrived
as `a = 1 AND b = 2`, and `NOT a = 1` arrived as `a = 1`.
- Stacked on #13405, which fixes the clause cutting this relies on.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/535
2026-11-20 11:44:40 +00:00
Aditya Singh
164ff1faec fix(messaging-queues): move the Kafka and Celery pages to query_range v5 (#13644)
#### Description

- The Kafka and Celery messaging queue pages load their graphs, tiles
and drawer tables with the v3 and v4 `query_range` APIs. The backend
plans to remove those APIs.
- The pages now load from v5 `query_range` and show the same data. The
Kafka group, topic and partition dropdowns read `/api/v1/fields/values`
instead of the v3 autocomplete.
- Chart clicks did nothing on the Kafka Consumer Lag graph, the Celery
state bars, the worker graphs and the Overview drawer graphs. The new
time series and bar panels dropped the page's own click handler. The
panels call it again when drilldown is off.
- The Drop Rate view is removed. It read the legacy `span/evaluation`
endpoint.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/157

#### Screenshots / Screen Recordings

Main vs this branch, diff view:
https://claude.ai/artifact/BpiYPvdSVXPAD7goQdfVhh

| Screen | On `main` | On this branch |
| --- | --- | --- |
| Kafka overview (3 stories) | Five view cards, including Drop Rate View
| Four view cards. Drop Rate View is gone. |
| Celery task (Default, Failing Tasks, Failed Tasks Only, No Flower
Metrics) | Error% by worker draws a single point on a 0–2000% axis |
Error% by worker draws one line per worker (30–80%) |
| Celery task, State Drawer (new story) | Not reachable. A chart click
does nothing on `main`. | A click on the All state graph opens the
drawer with the slowest tasks for that state |

- Each side is a static Storybook build, shot in dark and light. The
`main` side uses its own v3/v4 story mocks.
- 14 pairs changed and 20 are pixel-identical (Kafka Detail and the
queue Overview).
- The Error% difference comes partly from the mocks: on `main`, the
story's v4 mock answers the formula as a single point.

#### Additional Information

- Part of https://github.com/SigNoz/events-pod/issues/156.
- Stories serve v5. A new `StateDrawer` play opens the Celery drawer
from a chart click. The Kafka detail state is already covered by the
story's `selected` arg.

**FAQ (v4/v3 → v5)**

**Celery traces queries carry `aggregations: [{ expression }]`**
v5 builds a traces aggregation only from the expression. Without it,
`aggregateOperator` is ignored and the query becomes `count()`.

**Celery queries order by `p99(duration_nano)`, not `#SIGNOZ_VALUE`**
`#SIGNOZ_VALUE` was a v4 alias for the value column, and v5 rejects it.
The order key has to name the aggregation expression. This affects the
latency tabs and the drawer tables.

**Grouped Celery queries filter on `<key> exists`**
_Where:_ Messaging Queues › Celery › All state graph and Task Latency
v4 dropped spans that lack the group-by key. v5 returns them as an extra
group with an empty label, which shows as a blank bar on All and an
extra line on Task Latency. API Monitoring got the same fix (`http_url
exists`).

**Kafka metrics graphs send no step**
_Where:_ Messaging Queues › Kafka › Metric view, on ranges over 5 hours
v5 clamps a metrics step to at least range/300, with a 60s floor. A
fixed 60s on a 1-week range shows "requesting aggregation interval 60
seconds…". Sending no step lets v5 pick one. Service details (#13617)
does the same.

**Celery formulas moved to `queryFormulas`**
_Where:_ Messaging Queues › Celery › Error% by worker; Messaging Queues
› Overview › row drawer › Error %
v4 took them inside `builderQueries`. The v5 payload builder reads
formulas only from `queryFormulas`, so in the old place they went out as
metrics builder queries.

**State tiles show bigger numbers**
_Where:_ Messaging Queues › Celery › All Tasks / Failed / Retry /
Successful; Messaging Queues › Overview › row drawer tiles
v4 value panels showed one bucket of a time series (the last minute). v5
scalar requests aggregate the whole window. The numbers match ClickHouse
for the selected range.

**Graphs show the most recent data**
_Where:_ Messaging Queues › Celery › the last bar or point of each graph
v4 traces queries rounded the end down to a whole step, which dropped up
to one step of recent data. v5 keeps the partial bucket.

**Kafka group/topic/partition dropdowns call `/fields/values`**
_Where:_ Messaging Queues › Kafka › Consumer Lag view › group / topic /
partition selects
They used the v3 autocomplete endpoint. `/fields/values` takes the
metric name and filters `searchText` on the server.

**Chart clicks call the page's handler again**
_Where:_ Messaging Queues › Kafka › Consumer Lag graph; Messaging Queues
› Celery › state bars and worker graphs; Messaging Queues › Overview ›
row drawer graphs
When the panels moved to the new time series and bar panels, a page's
own `onClickHandler` stopped being called with drilldown off. The Kafka
lag graph, the Celery state bars and the Overview drawer graphs ignored
clicks. The handler is called again from `usePanelContextMenu`, so API
Monitoring endpoint graphs get their View Traces click back too. A click
outside a series no longer opens a Celery drawer.

**Drop Rate removed**
_Where:_ Messaging Queues › Kafka › view cards and the view selector
Agreed with Pandey to remove it rather than port it. It read the legacy
`span/evaluation` endpoint, which the backend serves only behind the
experimental `kafka_span_eval` flag. The flag is off by default, so the
view returned an error unless `KAFKA_SPAN_EVAL=true` was set. Old
`?mqServiceView=dropRate` links open Consumer Lag.

**Warning icon on empty metric graphs**
_Where:_ Messaging Queues › Kafka › Metric view
v5 reports a metric that was never ingested, and the graph shows that.

Issues found on `main` while testing are filed in
https://github.com/SigNoz/events-pod/issues/280. The ones this PR fixes
are ticked there.
2026-11-20 11:15:24 +00:00
Ashwin Bhatkal
f6f7144a80 fix(infra-monitoring): keep list filter clauses whole when carried into the drawer (#13405)
#### Description

- Opening a pod or container from a list filtered by a quick filter
broke the drawer's overview tab. A list filter like `k8s.cluster.name in
['cluster-a']` arrived in the drawer as `k8s.cluster.name in
['cluster-a'`, which does not parse.
- Each carried clause is now cut from its key to the end of its value,
which for `in [...]` is the closing bracket.
- The same cut also dropped the key from a `NOT IN` clause, and pulled
every dropped clause in front of a kept one into the result. Both are
fixed and covered in `relations.test.ts`.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/756
2026-11-20 10:28:30 +00:00
Naman Verma
73f02c25e7 feat(rules): report threshold names in the v3 list api (#13606)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

A rule's alerts carry the lowercased name of the threshold that fired as
their severity; the rule's own `severity` label is a plain label since
#13612. The v3 list row's new `thresholds` field reports exactly that:
each distinct threshold name, ranked critical, error, warning, info,
then the rest.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/653

---------

Co-authored-by: Ashu Ghildiyal <ashu.ghildiyal@signoz.io>
2026-11-20 09:46:00 +00:00
Nityananda Gohain
a01cc1aef9 fix(llm-observability): mirror the collector's bounded prefix match for pricing patterns (#13334)
#### Description

- `ModelMatchesAnyRule` and pattern validation now call the collector's
`pkg/llmpricing` (SigNoz/signoz-otel-collector#973) instead of a copied
regex, so a pattern matches the model exactly or followed by snapshot
suffixes (`-20260921`, `-latest`, `-v2:0`, `@20260921`), and a trailing
`*` matches
  any suffix. Priced snapshots no longer show up as unmapped.
- Validation rejects a non-trailing `*`, surrounding whitespace and
control characters; other glob characters are literal in the collector
now, so rejecting them was wrong.
- `PatternEditor` shows the stored pattern instead of appending a
cosmetic `*`, and the help text describes the actual matching.
  - Companion to SigNoz/zeus#606 for nerve-pod#517.

  #### Issues closed by this PR

  Closes https://github.com/SigNoz/nerve-pod/issues/517

#### Screenshots
Before:
<img width="541" height="531" alt="image"
src="https://github.com/user-attachments/assets/2a0cde21-ab05-40c2-be25-2a759ac01426"
/>

After:

<img width="541" height="531" alt="image"
src="https://github.com/user-attachments/assets/a50d8a62-1096-4c89-9871-019d9f6cb26d"
/>




  #### Additional Information

- `signoz-otel-collector` is pinned to `v0.144.17-rc.1`, the first tag
with `pkg/llmpricing`; bump to `v0.144.17` once it's released.
- No story change: the `ModelCostDrawer` story already renders the
pattern chips.
- Rules saved with glob syntax keep working as literal patterns,
matching the collector.

---------

Co-authored-by: Vishal Sharma <makeavish786@gmail.com>
2026-11-20 08:52:27 +00:00
Nikhil Soni
0bd8d52c42 refactor(saved-views): remove v1 explorer views api (breaking) (#13356)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Removes `/api/v1/explorer/views` (list/create/get/update/delete) along
with its legacy request/response converters and `v3.SavedView`.
- Folds the `*V2` handlers into plain `Create/Get/Update/List`;
`/api/v2/saved_views` is unchanged (OpenAPI spec has no diff).
- The UI and the signoz-mcp-server already use v2. Nightswatch is still
on older version which uses v1 APIs

Closes https://github.com/SigNoz/signoz/issues/13651

#### Additional Information

Breaking: external API clients still calling `/api/v1/explorer/views`
must switch to `/api/v2/saved_views`.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 05:57:12 +00:00
Swapnil Nakade
e1168108f2 feat: generating audit enum type for openapi spec (#13655)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description
- adding audit value for source enum and generating openapi spec

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR
contributes to https://github.com/signoz/keystone-pod/issues/214
2026-11-19 17:52:38 +00:00
Gaurav Tewari
7f8a1b283e feat(trace-details): add AI thread view stories (#13559)
#### Description

- Adds a page story for the Trace Details **Thread** tab, mocking `GET
/api/v1/traces/{id}/thread` with controls for scenario (tool-calling
conversation, every part type, roles and finish reasons, raw attributes
only, no AI spans), Formatted / JSON view, opened-on span and paging.
- Covers loading, next page pending, span not found (404), and a span
dropped for having no messages.
- Adds `SpanMessages` stories for its edge cases: empty state, role-less
output, empty parts, and large JSON behind Show more.
- Moves the existing story to `Trace Details/Overview` so Thread sits
beside it; Thread reuses its mocks for the header and span panel.

#### Issues closed by this PR


https://github.com/orgs/SigNoz/projects/59/views/18?pane=issue&itemId=308646781&issue=SigNoz%7Cnerve-pod%7C646

#### Screenshots / Screen Recordings


https://github.com/user-attachments/assets/69a26f1f-1c20-4b74-872e-0e5e1a5af3c4

#### Additional Information

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-19 17:42:40 +00:00
Gaurav Tewari
4553c9c9a6 test(noz): add stories for the step timeline, contexts and Latest pill (#13654)
#### Description

Stacked on #13598; merge after it.

- Pages/Noz stories for the UI #13598 changed: `Thinking`,
`StreamingSteps`, `DraftWhileStreaming`, `ScrolledUp`, `SingleStep`,
`PickedContexts`, `SentContexts`.
- The thread fixture gains picked contexts on the opening question, a
one-step answer and a `thinking` agent state; the default thread shows
the first two.
- `AddContext`'s play no longer waits for an idle agent, since the input
stays editable while Noz replies.

#### Issues closed by this PR


https://github.com/orgs/SigNoz/projects/59/views/18?pane=issue&itemId=308646781&issue=SigNoz%7Cnerve-pod%7C646

#### Screenshots / Screen Recordings

#### Additional Information

- `Default`, `AddContext` and `PickedContexts` sometimes open at the
thread's top: AppLayout's deferred `OverlayScrollbars` re-parents the
page after the thread has scrolled to its end, resetting it without a
scroll event. Pre-existing; the `ScrolledUp` play allows for it.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-19 17:32:55 +00:00
Aditya Singh
a2709c0272 feat(services): move the resource filter lookups off v3 autocomplete (#13656)
#### Description

- The resource attribute filter on the Services list, Service details
and Service Map loads its suggestions from the v3 autocomplete API. The
backend plans to remove that API.
- The filter now reads `/api/v1/fields/keys` and `/api/v1/fields/values`
for the `signoz_calls_total` span metric. The key list, the URL
parameter and the chips are unchanged.
- The v3 client, its types and its story builders are removed.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/151

#### Screenshots


https://github.com/user-attachments/assets/39f1f9bb-6f96-4319-bb29-39678ebbf25a


https://claude.ai/artifact/Lxma5VmYjdfywyyyv4gY7Z?sk=vynxojQhQ6bzovWbhPFWpQ

#### Additional Information

- Part of https://github.com/SigNoz/events-pod/issues/156.
- Stories serve `/fields/*`. The existing Service Map plays already open
the attribute search, the values, the Environment options and the empty
state, so no new story is needed.
- Tested on a local backend with span metrics from two seeded
environments. The key list matches main exactly, in traces mode and in
metrics mode.

**FAQ (v3 → v5)**

**Value suggestions are not limited to the selected time range**
_Where:_ Services, Service details, Service Map › Environment dropdown
and attribute values
v3 returned values reported since 00:00 UTC today. The v5 call sends no
time range, so it also returns older values that the metadata table
still holds. The QB v5 search bar sends no time range either. Metric
keys are not filtered by time on the backend, so the key list is
unchanged.
2026-11-19 17:12:59 +00:00
Gaurav Tewari
d8eda78322 feat(noz): polish the thread with a step timeline, pills, tables, cards and scrolling (#13598)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

Stacked on #13597.

- While Noz works, its steps fold into one row naming the running step,
with a shimmer; it opens to the steps as they happen, and once done
reads "Worked through N steps".
- The @ context picker and context pills follow the design; a sent
message shows the contexts picked for it.
- Reply links render as pills, tables scroll sideways in a striped
panel, and text uses the design's type.
- Suggested actions stack as chips; approval and clarification cards
share one layout.
- The loading view mirrors the thread, at the input's width on the full
page.
- Sidebar chat titles use the design's neutral grey (vanilla-400) in
dark mode; light mode keeps `--l2-foreground`, since vanilla-400 doesn't
follow the theme.
- Selected text on the Noz page and in the chat uses the input's accent
highlight, from one shared `_selection.scss`.
- The thread no longer scrolls on its own while Noz replies; only a send
brings the end into view. A "↓ Latest" pill shows when there's more
below and shimmers while the reply streams.
- Only the streaming row re-renders as a reply arrives; earlier messages
are memoized.
- The input stays editable while Noz replies or waits on an approval or
question; only sending is blocked. Snake and thread loading still lock
it.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

<!--If applicable, include screenshots or screen recordings that clearly
show the behavior before the change and the result after the change. -->
#### Screenshots / Screen Recordings



https://github.com/user-attachments/assets/2452ecb8-3de2-4c26-a1f2-9e2258190867


<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information

- Pages/Noz Default, Streaming, Awaiting Approval, Awaiting
Clarification, Loading Thread and Add Context reach the changed states;
Latest shows on scrolling up in Default.
- The thread renders 1500px above the view (`increaseViewportBy`) so
Virtuoso measures rows before they scroll in; without it, scrolling up
jumps as it corrects estimated heights.
- Departs from Figma: "Worked through N steps" instead of "Worked for N
seconds", since step timings aren't persisted; the picker's "Active
Resource" row waits on a defined action.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-19 16:33:25 +00:00
Gaurav Tewari
a79ff07e77 feat(noz): minimize the full page and restyle replies and the conversation list (#13597)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

Stacked on #13596.

- A minimize button on the full page reopens the floating panel on the
page Noz was expanded from, or on home after a deep link.
- Full-page replies render as plain text instead of a bubble; errors
keep their callout, and the activity line and reply actions follow the
design (in the panel too).
- The conversation list follows the design: search line, full-width "New
conversation", uppercase group labels, and rows with a status dot and
short time.
- Conversation rows are flat, with a restyled ⋮ menu.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

<!--If applicable, include screenshots or screen recordings that clearly
show the behavior before the change and the result after the change. -->
#### Screenshots / Screen Recordings


https://github.com/user-attachments/assets/e05be601-b7a6-4438-85ff-5e38c51b6520



<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information

- Covered by the existing Pages/Noz Default and Streaming stories and
Bottom Strip NozPanel; `AIAssistantPage.test` covers minimizing back
after switching chats.
- The dot only marks a chat Noz is still replying in; the design's other
dot colours need a definition.
- The list keeps its date groups and replies keep their timestamp, where
the design differs.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-19 15:21:30 +00:00
Gaurav Tewari
ebc2ba4fee feat(noz): redesign the new chat and the full-page layout (#13596)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

Stacked on #13552.

- New-chat screen per the design: "Noz · BETA" intro and suggestion
pills, with fixed-size placeholders while they load.
- An aurora dot grid above it that glows under the cursor and turns into
Snake on the Konami code; it follows the light and dark theme. (YES WE
ARE ADDING AN SNAKE GAME 🐍 )
- On first send, the new chat fades out and the first message floats up.
- New user bubble style and an L2 panel surface.
- Full-page layout: a faint pane, a 768px input over its edge and a
672px message column.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

<!--If applicable, include screenshots or screen recordings that clearly
show the behavior before the change and the result after the change. -->
#### Screenshots / Screen Recordings


https://github.com/user-attachments/assets/203121b7-e0d9-41ce-98ad-1ecea72690ea



<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information

- Covered by the existing Pages/Noz NewConversation and Default stories
and Bottom Strip NozPanel; Snake and the send transition are transient,
so no story holds them.
- The "New chat" header and Skills button are follow-ups.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-19 14:10:23 +00:00
Nikhil Mantri
edcb9028ce fix(alertmanager): keep notification log entries for twice the re-notify off interval (#13652)
#### Description

- An alert with re-notify off was notified again every 120 hours while
it stayed firing.
- Re-notify off is a repeat interval of 8760h, and alertmanager keeps
the notification log entry for 2x the repeat interval, capped by the
nflog retention. The retention was 120h, so the entry was dropped and
the alert looked new.
- The default nflog retention is now 2x the re-notify off interval,
derived from a shared `NoRenotifyInterval` constant so the two cannot
drift.
- Rules with a normal re-notify interval are not affected: their entries
still expire at 2x their own interval.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/751

#### Additional Information

- Entries written before the upgrade keep their 120h expiry, so an alert
already firing at upgrade time is notified one more time.
- Entries of re-notify off rules now stay for up to 2 years, one small
entry per alert group and receiver.
- Deployments that set `alertmanager.signoz.nflog.retention` explicitly
keep their value.
2026-11-19 14:09:20 +00:00
Yunus M
d74035f233 refactor: switch antd Flex, Row, Col, Space, Layout, Empty and List to periscope components (#13544)
#### Description

- Switches every screen from antd's Flex, Row, Col, Space, Layout, Empty
and List to our own versions from #13542.
- Stylesheets that targeted antd's internal classes (like `.ant-row`)
now use classes of their own.
- Adds Storybook stories for the app layout, the changelog modal and the
Services list column filter.

#### Screenshots / Screen Recordings

Before and after, dark and light:
https://claude.ai/artifact/X4c8YXVYe1kgdSpAnT1eVv

- No layout changes. 203 of 250 screenshots are identical.
- 17 differ in colour only: dark mode links and the light onboarding
background now use design system colours.
- The rest are capture noise (timestamps, scroll position) or new
stories.

#### Additional Information

- Merge #13542 first; this PR targets its branch.
2026-11-19 13:10:07 +00:00
Gaurav Tewari
d41447d4ee feat(noz): restyle the chat input to the new design (#13552)
<!--A few plain bullets saying what changed and why, for a reviewer
skimming it - not a wall of text, not a restatement of the diff, not
generated boilerplate.-->
#### Description

Stacked on #13549. One commit per change:

- Restyles the chat input to the new design: a card on the full page,
flush with the panel's edges inside the panel. Add Context becomes an
`@` button beside send; send turns primary once there is something to
send. The placeholder reads "Ask Noz…".
- Removes voice input: the mic button, push-to-talk, the speech hook and
its two analytics events.
- The textarea draws its own blinking robin-500 caret, with a short
trail on arrow-key jumps, and a robin-500 selection.
- While Noz replies, a gradient sweeps the input's top edge, timed from
the stream's start so a remount does not restart it.
- In an empty conversation, Noz climbs over the input's top-right corner
and his eye follows the cursor.

<!--Reference issues using `Closes #issue-number` to enable automatic
closure on merge. -->
#### Issues closed by this PR

<!--If applicable, include screenshots or screen recordings that clearly
show the behavior before the change and the result after the change. -->
#### Screenshots / Screen Recordings

Visual diff (sbshot, dark + light):
https://claude.ai/artifact/3h4e3kqX7i67DEwN4HSE4q



https://github.com/user-attachments/assets/352121ec-c7c9-4d5f-a869-7511dfa1995d




https://github.com/user-attachments/assets/2e6d0c40-4796-4ad6-8763-3cf6cbbadabf




https://github.com/user-attachments/assets/0e2db3a8-a75b-49a5-adc2-cfc41c670a4f


<!--Anything reviewers should keep in mind while reviewing -->
#### Additional Information

- Skills, queueing, steering and the new context-chip style are
follow-ups.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-19 12:25:19 +00:00
Yunus M
2e20b154c3 feat(periscope): add in-house versions of antd's Flex, Row, Col, Space, Layout, Empty and List (#13542)
#### Description

- Adds our own versions of seven antd layout components: Flex, Row, Col,
Space, Layout, Empty and List. They lay out exactly like antd's, so we
can move off antd without layout changes.
- Colours and fonts come from our design system tokens, so they switch
with light and dark mode and match the rest of the app.
- Each component has a Storybook page showing antd's version and ours
side by side, with an automatic check that sizes, spacing and positions
match.
- Checked in light and dark: every story lays out the same as antd.

#### Additional Information

- This PR only adds the components. Switching existing screens over to
them comes in a follow-up PR.
- Colours intentionally differ slightly from antd, because they now
follow the design system. Links use the same colour as the design
system's Typography.Link: identical to antd in light mode, slightly
brighter in dark mode.
- A few antd features nobody in the app uses were left out, for example
Layout's sidebar (`Sider`) and List's pagination.
2026-11-19 12:15:49 +00:00
Aditya Singh
bcd7182757 test(storybook): cover the events-pod states the component migration changes (#13637)
#### Description
- The component migration (#13087) uses sbshot diffs of the stories as
its regression check. Several events-pod states that render
`@signozhq/ui` had no story.
- This PR adds stories for the logs, traces and shared surfaces. The
commits are split by area: logs explorer, Live Tail, Pipelines, trace
details, traces explorer and funnels, query builder, quick filters and
saved views.
- New controls reach states the old mocks could not:
  - Logs: "Linked filter" and "Infra resource".
  - Trace details: "Analytics".
  - Saved views: "Writes" and "View queries".
- Some mocks now match the backend more closely:
- When nothing matches, the logs frequency chart and the table count
show no data.
  - Trace details highlights only the failing spans.
  - The exception event has a stacktrace.

#### Issues closed by this PR
Closes https://github.com/SigNoz/events-pod/issues/279

#### Screenshots / Screen Recordings
Every new story, in dark and light:
https://claude.ai/artifact/BMo2zjbqdwmddK7Hsmw1uZ

`FormatMenuOpen` (logs explorer) and `AddSeverityParserProcessor`
(pipelines) are not in it, because #13493 adds the same two stories and
[its shots](https://claude.ai/artifact/TeBTXRkB9puh7W6LnGXFQ8) cover
them.

#### Additional Information
- Some stories match #13493 on purpose: `FormatMenuOpen`,
`AddSeverityParserProcessor`, and the span drawer and funnel helpers.
The second PR to merge drops its copy.
- The AI thread states need #13493's Tab control and thread mock. Those
states go in after #13493 merges.
- `Tooltips`, `TooltipsInFilterBar` and the Events tab screenshots
change. The highlight mock and the stacktrace cause this.
- Some older Saved Views plays stay in the mocks module to limit
conflicts with #13087. They move to the play file after #13087 merges.
- These paths are dead code and have no story: the OptionsMenu fields,
`LogsPanelTable`, the ResizeTable Date and Time, the waterfall Error and
NoData, and the funnel details error branch.
- test-storybook passes 195 of 195 stories in the touched areas. cc.
@H4ad
2026-11-19 12:14:57 +00:00
Aditya Singh
b1dbea3eaa fix(services): move the span-metrics services list and home widget to query_range v5 (#13630)
#### Description
- With span metrics on, the services list and the home services widget
load with the v4 `query_range` API. The backend plans to remove the v4
APIs.
- On `main`, both show 0.00 for every P99, error rate and ops/s. The
reader looks for `newResult`, which v4 table responses do not carry.
- Both now load from v5 `query_range` and read the v5 table, so they
show real values.
- Span metrics store latency in ms, but three places treated it as ns:
  - the home P99 column read 0.00;
  - the services list header said "(in ns)";
  - the service details latency axis showed µs.

All three now show ms in span-metrics mode. Traces mode does not change.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/148

#### Screenshots / Screen Recordings

<img width="3400" height="1582" alt="pages-home--default--dark"
src="https://github.com/user-attachments/assets/5da53065-b470-4064-8769-5c6fc02e7b60"
/>
<img width="3400" height="1364"
alt="pages-services-detail--span-metrics--dark"
src="https://github.com/user-attachments/assets/3d3bd054-fb74-4973-8c06-b7ecb0f9ff72"
/>
<img width="3400" height="1364"
alt="pages-services-list--span-metrics--dark"
src="https://github.com/user-attachments/assets/aa7f72f2-a41a-4865-afa6-4863bcf2a258"
/>

https://claude.ai/artifact/EKYK1oeQfy3RsCw7fDHhoh
(feat/service-details-v5 vs this branch)

#### Additional Information
- Part of https://github.com/SigNoz/events-pod/issues/156. This PR
stacks on #13617.
- #3196 added span metrics to screens built for traces, which read
`duration_nano` in ns. Those screens kept the ns unit for span metrics,
but `signoz_latency` is stored in ms. Nobody saw it because the list and
home showed 0.00.
- Span-metrics P99 and traces P99 differ for the same service. Span
metrics estimate p99 from histogram buckets for each step and average
the steps. Traces take the exact p99 over the spans. The unit is the
same.
- The services list query now sends no step, so v5 picks it, like the
service details metrics queries.
- A failed refetch now shows one row for the service. Before, the
service showed twice: zeros and the old values.
- Follow-up: an operation name that starts with `$` (for example
`$connect`) breaks that service's row on v5. The shared filter converter
treats the whole list as a dashboard variable. Service details has the
same issue. A fix follows in its own PR.
- These are the same on `main` and stay out of this PR:
- The resource attribute filter has no effect on the span-metrics
services list.
- The home widget's time picker changes only the operations window. The
metric queries use the global time.
  - The services list row link drops the time range.
- Stories: the Home story's Services source control and the Services
Detail SpanMetrics story already reach the changed states. Both story
mocks now serve v5 and send P99 in ms.
- I tested it on a local backend with span metrics. The home widget and
the services list show the same values for the same window.
2026-11-19 11:38:16 +00:00
Aditya Singh
a30398bf1a feat(service-details): move the details page graphs to query_range v5 (#13617)
#### Description
- The service details page loads its graphs and the span-metrics key
operations table with the v4 `query_range` API. The backend plans to
remove the v4 APIs.
- The graphs and the span-metrics key operations table now load from v5
`query_range` and show the same data. The queries set their v5
aggregations explicitly, so v5 does not fall back to the default avg,
sum or `count()`.
- On v5, the Apdex graph drew two wrong lines. v5 treats
`signoz_latency.bucket` as a histogram, so B and C keep their `le`
label. The formula cannot join series with different `le` values. B and
C now count the requests at or below the threshold with
`comparisonSpaceAggregationParam`.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/150

#### Screenshots / Screen Recordings

https://claude.ai/artifact/KeUB5YZafsDGCSf6uPZMME (main vs this branch,
diff view)

Not covered:
- Services list and Home render `ServiceMetricsQuery`, which this branch
touches. That query stays on v4 and sends the same step as before, so it
has no visual change. No shots were taken for them.

#### Additional Information
- Part of https://github.com/SigNoz/events-pod/issues/156.
- The backend team confirmed that the `count` aggregation is meant for
the Apdex query:
https://signoz-team.slack.com/archives/C089D1B5516/p1794900404107019
- In span-metrics mode, the key operations table on `main` shows No
data. For a v4 table panel, `GetMetricQueryRange` returns the response
without `newResult`, and the table reads only `newResult`. The table now
reads the v5 result, so it shows its rows.
- Formula panels show No Data instead of a flat 0 line when the service
has no calls of that kind. This affects DB and external avg duration and
error %. v4 returned a series of zeros for empty inputs.
- The traces-mode key operations table stays on
`/v2/service/top_operations` and `/v2/service/entry_point_operations`,
as the ticket says.
- Metrics queries now send no step, so v5 picks it. This removes the
step warning at ranges of 1 day and more. Traces queries keep the card
step. The services list is still on v4 and keeps its step until
https://github.com/SigNoz/events-pod/issues/148.
- Known: on the metrics cards, View in Logs and View in Traces open a
60s window at ranges over about 5 hours. The shared
`usePanelContextMenu` hook uses 60s when the request has no step. This
already happens on any v5 panel without a step. A fix in the hook
follows in its own PR.
- The calls go through the existing `useGetQueryRange` wrapper, like the
other v5 migrations.
- Stories: the service details story serves v5 `query_range`. A new
Source control and a Span Metrics story show span-metrics mode.
2026-11-19 10:25:28 +00:00
Swapnil Nakade
8b923e88ce feat(licensing): cache the active license per org (#13640)
#### Description

- `licensing.GetActive` now reads the org's active license from the
shared cache (`cache.Cache`, 5 minute TTL) instead of querying the
`license` table on every call. Every audited request in the otlphttp,
kafka and file auditors calls it, as do authz and gateway checks.
- "No active license" is cached too, as most self-hosted enterprise
installs run without a license. Store and parse errors are never cached.
- A cached license that has expired is reloaded from the store on read.
- `Activate`, `Delete` and both write paths of `Refresh` clear the org's
entry after a successful write.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#3

#### Additional Information

- Any new code that writes the `license` table must clear cache entry,
otherwise the change is served for up to 5 minute.
- A request that read the old license before a `Refresh` write can put
it back into the cache after the delete. The TTL bounds this to 1
minute, which is why the TTL is not 0.
2026-11-19 10:12:05 +00:00
ashu8912
89c1dfe332 fix(alerts): show invalid rule list queries the way the dashboards list does (#13621)
#### Description

- An unparseable query on the alert rules list put the server message
under the search box in `--danger-foreground`, which is white: invisible
in light theme. The list body only said "No matching alert rules".
- The list now shows the dashboards list's Invalid query state: the
cleaned-up server message and Contact Support, in place of the list.
- That state moved to `components/ListFilter/InvalidQueryState`, shared
by both lists. `FilterZone` loses its `error` prop, which nothing else
used.

#### Issues closed by this PR

Closes SigNoz/pulse-pod#745

#### Screenshots / Screen Recordings

[Visual diff](https://claude.ai/artifact/6NUY2jcvjyfzLPEbugYPVt),
merge-base vs branch, dark and light: `Pages/Alerts/Rules/Invalid Query`
changed; `Pages/Dashboards/List/Invalid Query` pixel-identical.

#### Additional Information

Storybook already covers both states (`Invalid Query` on each page);
only the alert story's description changed.
2026-11-19 09:42:55 +00:00
Ashwin Bhatkal
0add9cce0d feat(dashboards): let dashboard creators set the default time range (#13446)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Dashboard settings get a "Default time range" select on the Overview
tab, saved to `spec.duration`. Picking "Default (Last 30 minutes)"
clears it.
- When a viewer opens a dashboard with no time range in the URL and no
saved choice for that dashboard, the URL gets `relativeTime=<duration>`
before the time picker and panels mount. A time in the URL or a saved
choice still wins.
- When the default changes while a viewer is still on the old one, they
move to the new one. A viewer who picked a time keeps it.
- The JSON editor and JSON import reject a `spec.duration` that is not a
whole number of minutes above zero (`1s`, `90s`, `0m`), since the time
picker has no seconds. The editor footer names the line of an invalid
duration or image and shows the full error on hover.
- A value set through the API can still carry seconds. It opens rounded
up to whole minutes: `15s` opens as `1m`, `1h30m` as `90m`. An empty or
zero duration is ignored, and the picker behaves as before: the viewer's
saved choice, else 30 minutes.
- Settings show a stored value that is not one of the options with how
it opens, e.g. "Last 1s (opens as 1m)" or "0m (not applied)".
- The API description of `spec.duration` now says how the UI applies it.
It said "Stored, but not applied by the UI".
- The Prometheus duration parser behind Jira reopen durations moves to
`utils/prometheusDuration.ts`, shared with the dashboard code. Units
must now come largest first and each only once, as the API requires, so
`30m1h` is rejected in the JSON editor, on import, and in the Jira form.
- Carries the frontend part of
[#12861](https://github.com/SigNoz/signoz/pull/12861), moved onto the
`lib/router` facade. Its backend validation is left out: `spec.duration`
is already checked when the spec is decoded.
- The dashboard stories get a "Default time range" control and four new
states: the settings select open, a stored value off the list, the
dashboard opening on its default, and the JSON editor rejecting `1s`.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/695
Closes https://github.com/SigNoz/signoz/issues/12860

#### Screenshots / Screen Recordings

[Visual diff](https://claude.ai/artifact/5mSCBVGEirWfkiC29ZbnEo) against
the merge-base, dark and light: 38 shots, 8 new, 15 changed, 15
identical. `default-time-range-card` is the new card on the settings
Overview tab (12), `new-stories` the four new states (8), and `noise` a
focus ring left on a clicked tab or button in the before shots (3).
2026-11-18 18:46:46 +00:00
Aditya Singh
4ffa6ac5da fix(hotkeys): ignore keydown events whose target is not an element (#13149)
#### Description
- The hotkeys handler threw `t.closest is not a function` when a script
dispatched `keydown` on `document` itself. The `Document` node has no
`closest`.
- The handler now ignores events whose target is not an `Element`. Real
key presses always target an element, so shortcuts work the same.

#### Issues closed by this PR

Closes https://github.com/SigNoz/events-pod/issues/179
2026-11-18 15:12:43 +00:00
ashu8912
824315b093 fix(alerts): let the empty rules page scroll to the sample alerts (#13619)
#### Description

- With no alert rules, the empty state sat in a `min-height: 0` flex
column with no overflow, so "Or get started with these sample alerts"
and its cards were clipped below the fold with no way to scroll to them.
- The empty state is now its own scroll container; `margin: auto` keeps
it centered when it fits and top-aligned when it doesn't.
- Only the empty state's stylesheet changes; the rule list is
unaffected.

#### Issues closed by this PR

Closes SigNoz/pulse-pod#744

#### Screenshots / Screen Recordings

[Visual diff](https://claude.ai/artifact/Y3cH28AULH1vvj62uNebgP) of
`Pages/Alerts/Rules/No Rules`, merge-base vs branch, dark and light: 2
changed, 0 new.

#### Additional Information

Storybook already covers this state with `Pages/Alerts/Rules/No Rules`;
no story edit needed.
2026-11-18 14:41:05 +00:00
Gaurav Tewari
1ee097b60a feat(noz): add support for floatingpanel in noz (#13549)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- The Noz panel floats above the bottom strip (420 × 601), drags by its
header and resizes from its edges, reusing `FloatingPanel`.
- Panel and popup headers show the open chat's title instead of "Noz".
- Ask Noz stays in the strip; with the panel open, it closes it on the
same chat.
- Opening Support slides the panel clear of Pylon's chat (new
`FloatingPanel` `moveTo` handle), and back on close.

#### Issues closed by this PR


https://github.com/orgs/SigNoz/projects/59/views/18?pane=issue&itemId=298456403&issue=SigNoz%7Cnerve-pod%7C631

#### Screenshots / Screen Recordings



https://github.com/user-attachments/assets/0d72eaeb-36a3-4a99-8f96-b0de883390dc



#### Additional Information

- Pylon and the alert footer drop their fixed 420px offsets; the panel
stacks over the footer.
- No story for the Support slide: Pylon never loads in Storybook.
- Ideally for Pylon we could have a global state and store things their,
but i am not sure if their would be any other place apart from NOZ. that
would use that.
- we should add ```keepInViewport``` prop in all the places where we are
using floating panel

Design -
https://www.figma.com/design/TGMORuL0k2Y94c5UpdjyAw/AI-Assistant?node-id=645-6554&t=dtjsBRSuhNxT971O-0
Notion -
https://app.notion.com/p/signoz/Noz-UI-Update-3b4fcc6bcd1980e0956fde2fb1b6ae04

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
Co-authored-by: Vishal Sharma <makeavish786@gmail.com>
2026-11-18 11:33:31 +00:00
1900 changed files with 47989 additions and 31135 deletions

View File

@@ -86,7 +86,7 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
zeus.Config{},
noopzeus.NewProviderFactory(),
licensing.Config{},
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics, _ cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return nooplicensing.NewFactory()
},
func(_ zeus.Zeus, _ licensing.Licensing) subscription.Subscription {

View File

@@ -103,8 +103,8 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
enterprisezeus.Config(),
httpzeus.NewProviderFactory(),
enterpriselicensing.Config(24*time.Hour, 3),
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics)
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics, cache)
},
func(zeus zeus.Zeus, licensing licensing.Licensing) subscription.Subscription {
return httpsubscription.New(zeus, licensing)

View File

@@ -261,8 +261,8 @@ alertmanager:
nflog:
# Interval between garbage collection and snapshotting of the notification logs. The snapshot will be stored in the state store.
maintenance_interval: 15m
# Retention of the notification logs.
retention: 120h
# Retention of the notification logs. Must be at least twice the longest repeat interval, which is 8760h for rules with re-notify off.
retention: 17520h
##################### Emailing #####################
emailing:

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,26 @@
package httplicensing
import (
"encoding/json"
"time"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
)
const (
activeLicenseCacheKey string = "active_license"
activeLicenseCacheTTL time.Duration = 5 * time.Minute
)
// A nil License means the organization has no active license.
type cachedActiveLicense struct {
License *licensetypes.License
}
func (typ cachedActiveLicense) MarshalBinary() ([]byte, error) {
return json.Marshal(typ)
}
func (typ *cachedActiveLicense) UnmarshalBinary(data []byte) error {
return json.Unmarshal(data, typ)
}

View File

@@ -7,6 +7,7 @@ import (
"github.com/SigNoz/signoz/ee/licensing/licensingstore/sqllicensingstore"
"github.com/SigNoz/signoz/pkg/analytics"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/factory"
"github.com/SigNoz/signoz/pkg/licensing"
@@ -25,16 +26,17 @@ type provider struct {
settings factory.ScopedProviderSettings
orgGetter organization.Getter
analytics analytics.Analytics
cache cache.Cache
stopChan chan struct{}
}
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
func NewProviderFactory(store sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return factory.NewProviderFactory(factory.MustNewName("http"), func(ctx context.Context, providerSettings factory.ProviderSettings, config licensing.Config) (licensing.Licensing, error) {
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics)
return New(ctx, providerSettings, config, store, zeus, orgGetter, analytics, cache)
})
}
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) (licensing.Licensing, error) {
func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Config, sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics, cache cache.Cache) (licensing.Licensing, error) {
settings := factory.NewScopedProviderSettings(ps, "github.com/SigNoz/signoz/ee/licensing/httplicensing")
licensestore := sqllicensingstore.New(sqlstore)
return &provider{
@@ -45,6 +47,7 @@ func New(ctx context.Context, ps factory.ProviderSettings, config licensing.Conf
orgGetter: orgGetter,
stopChan: make(chan struct{}),
analytics: analytics,
cache: cache,
}, nil
}
@@ -109,6 +112,7 @@ func (provider *provider) Activate(ctx context.Context, organizationID valuer.UU
return nil, err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return license, nil
}
@@ -150,25 +154,38 @@ func (provider *provider) Delete(ctx context.Context, organizationID valuer.UUID
return errors.WithAdditionalf(err, "license %s cannot be deleted", licenseID.StringValue())
}
return provider.store.Delete(ctx, organizationID, licenseID)
if err := provider.store.Delete(ctx, organizationID, licenseID); err != nil {
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
}
// Caches both an active license and no active license, but never a store error.
func (provider *provider) GetActive(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
if cached, ok := provider.getActiveFromCache(ctx, organizationID); ok {
if cached.License == nil {
return nil, licensetypes.ErrActiveLicenseNotFound(organizationID)
}
return cached.License, nil
}
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
if err != nil && !errors.Ast(err, errors.TypeNotFound) {
return nil, err
}
activeLicense, err := licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
if err != nil {
return nil, err
if cacheErr := provider.cache.Set(ctx, organizationID, activeLicenseCacheKey, &cachedActiveLicense{License: activeLicense}, activeLicenseCacheTTL); cacheErr != nil {
provider.settings.Logger().WarnContext(ctx, "failed to write active license to cache", errors.Attr(cacheErr), slog.String("org_id", organizationID.StringValue()))
}
return activeLicense, nil
return activeLicense, err
}
func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUID) error {
activeLicense, err := provider.GetActive(ctx, organizationID)
activeLicense, err := provider.getActiveFromStore(ctx, organizationID)
if err != nil {
if errors.Ast(err, errors.TypeNotFound) {
return nil
@@ -187,6 +204,7 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
return nil
}
return err
@@ -203,6 +221,8 @@ func (provider *provider) Refresh(ctx context.Context, organizationID valuer.UUI
return err
}
provider.cache.Delete(ctx, organizationID, activeLicenseCacheKey)
stats := licensetypes.NewStatsFromLicense(activeLicense)
provider.analytics.Send(ctx,
analyticstypes.Track{
@@ -249,3 +269,30 @@ func (provider *provider) Collect(ctx context.Context, orgID valuer.UUID) (map[s
return licensetypes.NewStatsFromLicense(activeLicense), nil
}
func (provider *provider) getActiveFromCache(ctx context.Context, organizationID valuer.UUID) (*cachedActiveLicense, bool) {
cached := new(cachedActiveLicense)
err := provider.cache.Get(ctx, organizationID, activeLicenseCacheKey, cached)
if err != nil {
if !errors.Ast(err, errors.TypeNotFound) {
provider.settings.Logger().WarnContext(ctx, "failed to read active license from cache", errors.Attr(err), slog.String("org_id", organizationID.StringValue()))
}
return nil, false
}
if cached.License != nil && cached.License.IsExpired() {
return nil, false
}
return cached, true
}
func (provider *provider) getActiveFromStore(ctx context.Context, organizationID valuer.UUID) (*licensetypes.License, error) {
storableLicenses, err := provider.store.GetAll(ctx, organizationID)
if err != nil {
return nil, err
}
return licensetypes.GetActiveLicenseFromStorableLicenses(storableLicenses, organizationID)
}

View File

@@ -0,0 +1,214 @@
package httplicensing
import (
"context"
"encoding/json"
"testing"
"time"
"github.com/DATA-DOG/go-sqlmock"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/SigNoz/signoz/pkg/analytics/analyticstest"
"github.com/SigNoz/signoz/pkg/cache"
"github.com/SigNoz/signoz/pkg/cache/cachetest"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
"github.com/SigNoz/signoz/pkg/licensing"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/sqlstore/sqlstoretest"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/SigNoz/signoz/pkg/zeus"
"github.com/SigNoz/signoz/pkg/zeus/noopzeus"
)
var (
testOrganizationID = valuer.MustNewUUID("0196f794-ff30-7bee-a5f4-ef5ad315715e")
testLicenseID = valuer.MustNewUUID("0196360e-90cd-7a74-8313-1aa815ce2a67")
licenseColumns = []string{"id", "created_at", "updated_at", "key", "data", "last_validated_at", "org_id"}
)
const (
selectLicensesQuery = `SELECT (.+) FROM "license"`
updateLicenseQuery = `UPDATE "license"`
deleteLicenseQuery = `DELETE FROM "license"`
)
func newTestLicensing(t *testing.T) (licensing.Licensing, sqlmock.Sqlmock, cache.Cache) {
t.Helper()
sqlStore := sqlstoretest.New(sqlstore.Config{Provider: "sqlite"}, sqlmock.QueryMatcherRegexp)
licenseCache, err := cachetest.New(cache.Config{Provider: "memory", Memory: cache.Memory{NumCounters: 1000, MaxCost: 1 << 20}})
require.NoError(t, err)
providerSettings := instrumentationtest.New().ToProviderSettings()
noopZeus, err := noopzeus.New(context.Background(), providerSettings, zeus.Config{})
require.NoError(t, err)
licensing, err := New(context.Background(), providerSettings, licensing.Config{PollInterval: time.Hour, FailureThreshold: 3}, sqlStore, noopZeus, nil, analyticstest.New(), licenseCache)
require.NoError(t, err)
return licensing, sqlStore.Mock(), licenseCache
}
func newLicenseRows(lastValidatedAt time.Time) *sqlmock.Rows {
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
data := `{"status":"VALID","state":"EVALUATING","platform":"SELF_HOSTED","plan":{"name":"ENTERPRISE"},"valid_from":1732146923,"valid_until":-1,"features":[],"event_queue":{}}`
return sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", data, lastValidatedAt, testOrganizationID.StringValue())
}
func TestGetActiveServesRepeatReadsFromCache(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
fromStore, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
fromCache, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, licensetypes.NewGettableLicenseWithKey(fromStore), licensetypes.NewGettableLicenseWithKey(fromCache))
assert.Equal(t, fromStore.OrganizationID, fromCache.OrganizationID)
assert.True(t, fromStore.LastValidatedAt.Equal(fromCache.LastValidatedAt))
fromStoreData, err := json.Marshal(fromStore.Data)
require.NoError(t, err)
fromCacheData, err := json.Marshal(fromCache.Data)
require.NoError(t, err)
assert.JSONEq(t, string(fromStoreData), string(fromCacheData))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveCachesNoActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
for range 2 {
license, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
assert.Nil(t, license)
}
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveDoesNotCacheErrors(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
createdAt := time.Date(2026, 1, 1, 0, 0, 0, 0, time.UTC)
licenseRowWithoutStatus := sqlmock.
NewRows(licenseColumns).
AddRow(testLicenseID.StringValue(), createdAt, createdAt, "test-license-key", `{"plan":{"name":"ENTERPRISE"}}`, createdAt, testOrganizationID.StringValue())
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(licenseRowWithoutStatus)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.ErrorContains(t, err, "license status is missing")
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestGetActiveReloadsExpiredCachedLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
expiredLicense := &licensetypes.License{
ID: valuer.GenerateUUID(),
ValidFrom: time.Now().Add(-2 * time.Hour).Unix(),
ValidUntil: time.Now().Add(-time.Hour).Unix(),
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: expiredLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
license, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
assert.Equal(t, testLicenseID, license.ID)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestDeleteClearsCachedActiveLicense(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(time.Now().UTC()))
mock.ExpectExec(deleteLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(sqlmock.NewRows(licenseColumns))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Delete(ctx, testOrganizationID, testLicenseID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.Error(t, err)
assert.True(t, errors.Ast(err, errors.TypeNotFound))
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshClearsCachedActiveLicenseOnDowngrade(t *testing.T) {
ctx := context.Background()
licensing, mock, _ := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(updateLicenseQuery).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
_, err := licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
_, err = licensing.GetActive(ctx, testOrganizationID)
require.NoError(t, err)
require.NoError(t, mock.ExpectationsWereMet())
}
func TestRefreshWritesActiveLicenseFromStoreNotCache(t *testing.T) {
ctx := context.Background()
licensing, mock, licenseCache := newTestLicensing(t)
staleLastValidatedAt := time.Now().Add(-4 * time.Hour).UTC()
staleCachedLicense := &licensetypes.License{
ID: testLicenseID,
Key: "stale-cached-license-key",
ValidFrom: 1732146923,
ValidUntil: -1,
LastValidatedAt: staleLastValidatedAt,
OrganizationID: testOrganizationID,
}
require.NoError(t, licenseCache.Set(ctx, testOrganizationID, activeLicenseCacheKey, &cachedActiveLicense{License: staleCachedLicense}, activeLicenseCacheTTL))
mock.ExpectQuery(selectLicensesQuery).WillReturnRows(newLicenseRows(staleLastValidatedAt))
mock.ExpectExec(`UPDATE "license" .*'test-license-key'`).WillReturnResult(sqlmock.NewResult(0, 1))
require.NoError(t, licensing.Refresh(ctx, testOrganizationID))
require.NoError(t, mock.ExpectationsWereMet())
}

View File

@@ -52,7 +52,7 @@ func (f *formatter) JSONIsArray(column, path string) []byte {
func (f *formatter) JSONArrayElements(column, path, alias string) ([]byte, []byte) {
var sql []byte
sql = append(sql, "jsonb_array_elements("...)
sql = f.bunf.AppendIdent(sql, column)
sql = append(sql, f.TextToJsonColumn(column)...)
sql = append(sql, f.convertJSONPathToPostgresWithMode(path, false)...)
sql = append(sql, ") AS "...)
sql = f.bunf.AppendIdent(sql, alias)

View File

@@ -213,28 +213,28 @@ func TestJSONArrayElements(t *testing.T) {
column: "data",
path: "$",
alias: "elem",
expected: `jsonb_array_elements("data") AS "elem"`,
expected: `jsonb_array_elements("data"::jsonb) AS "elem"`,
},
{
name: "root path empty",
column: "data",
path: "",
alias: "elem",
expected: `jsonb_array_elements("data") AS "elem"`,
expected: `jsonb_array_elements("data"::jsonb) AS "elem"`,
},
{
name: "nested path",
column: "metadata",
path: "$.items",
alias: "item",
expected: `jsonb_array_elements("metadata"->'items') AS "item"`,
expected: `jsonb_array_elements("metadata"::jsonb->'items') AS "item"`,
},
{
name: "deeply nested path",
column: "json_col",
path: "$.user.tags",
alias: "tag",
expected: `jsonb_array_elements("json_col"->'user'->'tags') AS "tag"`,
expected: `jsonb_array_elements("json_col"::jsonb->'user'->'tags') AS "tag"`,
},
}

View File

@@ -8,5 +8,5 @@
.title {
color: var(--l1-foreground);
font-size: var(--font-size-lg);
font-size: var(--label-large-400-font-size);
}

View File

@@ -497,7 +497,11 @@
// Requires final else in if-else-if chains (was disabled)
"signoz/no-conditional-text-nodes-with-siblings": "warn",
// Vendored from eslint-plugin-react-google-translate
"signoz/no-return-text-nodes": "warn"
"signoz/no-return-text-nodes": "warn",
"signoz/no-text-css": "warn",
// Font and text CSS in style props, CSSProperties objects and styled-components; text style goes through Typography props
"signoz/require-disable-reason": "error"
// A disable of signoz/no-text-css must say why Typography cannot render the text
},
"ignorePatterns": [
"src/parser/*.ts",

View File

@@ -40,8 +40,8 @@ const mockAliases = [
},
{
// jest: not replaced, a test asserts on the toast it fires.
find: /^@signozhq\/ui\/sonner$/,
replacement: `${srcPath}/storybook/mocks/sonner.mock.tsx`,
find: /^@signozhq\/ui\/toast$/,
replacement: `${srcPath}/storybook/mocks/toast.mock.tsx`,
},
];

View File

@@ -1,8 +1,6 @@
<!--
`index.html` links Inter from Google Fonts here. The link is parsed before the
msw worker has started, so that one request escapes the iframe while every
other font request the app makes is answered with an empty stylesheet; the
local faces stand in for both.
Every Google Fonts request the app makes is answered with an empty
stylesheet; the local faces stand in for them.
-->
<link rel="stylesheet" href="storybook-fonts.css" />
@@ -76,49 +74,3 @@
Object.defineProperty(window, 'Date', { value: FrozenDate, writable: true });
})();
</script>
<script>
// Storybook has no microphone. Chromium's recognizer asks for one and for
// Google's speech service, and the `not-allowed` or `network` it reports makes
// the assistant hide its mic for the rest of the tab. This one starts
// listening at once and hears only what a story passes to `hear`.
(() => {
class StorySpeechRecognition extends EventTarget {
static listening = null;
lang = 'en-US';
continuous = false;
interimResults = false;
onstart = null;
onresult = null;
onerror = null;
onend = null;
start() {
StorySpeechRecognition.listening = this;
setTimeout(() => this.onstart?.());
}
stop() {
if (StorySpeechRecognition.listening === this) {
StorySpeechRecognition.listening = null;
}
setTimeout(() => this.onend?.());
}
abort() {
this.stop();
}
/** An interim result: the words so far, still listening. */
hear(transcript) {
const result = Object.assign([{ transcript, confidence: 1 }], {
isFinal: false,
});
this.onresult?.({ resultIndex: 0, results: [result] });
}
}
window.SpeechRecognition = StorySpeechRecognition;
window.webkitSpeechRecognition = StorySpeechRecognition;
})();
</script>

View File

@@ -147,6 +147,7 @@ const preview: Preview = {
'Explorer',
['Overview', 'Span Drawer'],
'Trace Details',
['Overview', 'Thread'],
'Funnel Details',
],
'Metrics',

View File

@@ -1,22 +1,11 @@
/*
* The five families the app pulls from Google Fonts, served from the files in
* The three families the app pulls from Google Fonts, served from the files in
* `public/fonts` instead. `msw/appShellHandlers.ts` answers the CDN with an
* empty stylesheet so no request leaves the iframe, which without this left
* every story on a fallback for the four families `src/styles.scss` imports at
* runtime, and on whatever the Inter link in `index.html` happened to fetch
* before the worker had started.
* every story on a fallback for the three families `src/styles.scss` imports at
* runtime. Inter and Geist Mono come from `src/styles.scss` itself.
*/
@font-face {
font-family: 'Inter';
/* The comma is part of the filename and the dev server serves it raw, so it
stays literal inside the quoted url rather than percent-encoded. */
src: url('fonts/Inter-VariableFont_opsz,wght.ttf') format('truetype');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Work Sans';
src: url('fonts/WorkSans-VariableFont_wght.ttf') format('truetype');
@@ -40,11 +29,3 @@
font-style: normal;
font-display: swap;
}
@font-face {
font-family: 'Geist Mono';
src: url('fonts/GeistMonoVF.woff2') format('woff2');
font-weight: 100 900;
font-style: normal;
font-display: swap;
}

View File

@@ -14,9 +14,23 @@ module.exports = {
path.join(__dirname, 'stylelint-rules/css-modules/class-name-pattern.js'),
],
customSyntax: 'postcss-scss',
// Disables of property-disallowed-list must say why after "--"
reportDescriptionlessDisables: [
false,
{ except: ['property-disallowed-list'], severity: 'error' },
],
rules: {
// Applies to all SCSS files
'local/no-unsupported-asset-url': true,
// Text style goes through @signozhq/ui/typography props
'property-disallowed-list': [
['/^font/', '/^text-/', 'line-height', 'letter-spacing'],
{
severity: 'warning',
message: (property) =>
`Do not set "${property}" in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after "--" saying why Typography cannot.`,
},
],
},
overrides: [
{

View File

@@ -191,34 +191,30 @@ You can read the ./node_modules/@signozhq/design-tokens/dist/style.css to find c
### Typography
Text styles are tokens named `--{variant}-{size}-{weight}-{property}`:
- Variant: `label` (line height 1), `paragraph` (line height 18, 20 or 26px), `uppercase` (11 and 13px) or `code` (SF Mono, 11 and 13px).
- Size: `small` (11px), `base` (13px), `medium` (16px) or `large` (18px). Paragraph has no `large`; uppercase and code have only `small` and `base`.
- Weight: `400`, `500` or `600`.
- Property: `font-family`, `font-size`, `font-weight`, `line-height`, `letter-spacing` or `text-transform`.
```scss
// Font sizes (preferred)
.title {
font-size: var(--periscope-font-size-large); // 18px
font-size: var(--periscope-font-size-medium); // 16px
font-size: var(--periscope-font-size-base); // 13px
font-size: var(--periscope-font-size-small); // 11px
font-family: var(--label-large-500-font-family);
font-size: var(--label-large-500-font-size);
font-weight: var(--label-large-500-font-weight);
line-height: var(--label-large-500-line-height);
letter-spacing: var(--label-large-500-letter-spacing);
}
// Alternative scale (rem-based)
.heading {
font-size: var(--font-size-xl); // 1.25rem
font-size: var(--font-size-lg); // 1.125rem
font-size: var(--font-size-base); // 1rem
font-size: var(--font-size-sm); // 0.875rem
.hint {
font-size: var(--paragraph-small-400-font-size); // 11px
line-height: var(--paragraph-small-400-line-height); // 18px
}
// Font weights
.bold {
font-weight: var(--font-weight-semibold); // 600
font-weight: var(--font-weight-medium); // 500
font-weight: var(--font-weight-normal); // 400
}
// Line heights
.text {
line-height: var(--line-height-20); // 20px
line-height: var(--line-height-24); // 24px
.id {
font-family: var(--code-base-400-font-family);
font-size: var(--code-base-400-font-size); // 13px
}
```
@@ -312,7 +308,7 @@ Each component exposes `--<component>-<property>` variables:
--button-background: var(--success-background);
--button-border-radius: var(--radius-2);
--button-padding: var(--spacing-4) var(--spacing-8);
--button-font-size: var(--periscope-font-size-base);
--button-font-size: var(--label-base-400-font-size);
}
// Override Input
@@ -342,7 +338,7 @@ Components use data attributes for variants/states. Target them for state-specif
// Target size
.wrapper :global([data-size="sm"]) {
--button-font-size: var(--periscope-font-size-small);
--button-font-size: var(--label-small-400-font-size);
}
// Target color

View File

@@ -14,11 +14,6 @@
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="preconnect" href="https://cdn.vercel.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Inter:ital,opsz,wght@0,14..32,100..900;1,14..32,100..900&display=swap"
rel="stylesheet"
/>
<title data-react-helmet="true">
Open source Observability platform | SigNoz
</title>

View File

@@ -36,6 +36,8 @@ const config: Config.InitialOptions = {
'^test-mocks/(.*)$': '<rootDir>/__mocks__/$1',
'^react-syntax-highlighter/dist/esm/(.*)$':
'<rootDir>/node_modules/react-syntax-highlighter/dist/cjs/$1',
// `antd` resolves to lib/ here; es/ deep imports must share its module instances (contexts).
'^antd/es/(.*)$': '<rootDir>/node_modules/antd/lib/$1',
'^@signozhq/(?!ui(?:/|$))([^/]+)$':
'<rootDir>/node_modules/@signozhq/$1/dist/$1.js',
},

View File

@@ -54,9 +54,9 @@
"@monaco-editor/react": "^4.7.0",
"@sentry/react": "10.57.0",
"@sentry/vite-plugin": "5.3.0",
"@signozhq/design-tokens": "2.2.1",
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/ui": "0.2.0",
"@signozhq/ui": "0.4.0-rc.5",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",
"@uiw/codemirror-theme-copilot": "4.23.11",

View File

@@ -0,0 +1,170 @@
import { ruleTester } from './rule-tester.mjs';
const message = (property) =>
`Do not set '${property}' in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after \`--\` saying why Typography cannot.`;
await ruleTester({
rule: 'no-text-css',
valid: [
{
name: 'layout properties in a style prop',
code: 'export const A = () => <div style={{ width: 10, color: "red" }} />;',
},
{
name: 'font properties in an object that is not a style',
code: 'export const options = { fontSize: 12, font: "12px Inter" };',
},
{
name: 'font properties in a prop that is not a style',
code: 'export const A = () => <Chart options={{ fontSize: 12 }} />;',
},
{
name: 'computed key',
code:
'const k = "fontSize";\nexport const A = () => <div style={{ [k]: 12 }} />;',
},
{
name: 'style identifier from a parameter',
code: 'export const A = ({ s }) => <div style={s} />;',
},
{
name: 'template without a styled tag',
code: 'export const s = html`font-size: 12px;`;',
},
{
name: 'styled template with layout only',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\tdisplay: flex;\n\ttext: none;\n`;",
},
{
name: 'custom property that ends in a banned name',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\t--my-font-size: 12px;\n`;",
},
],
invalid: [
{
name: 'inline style',
code: 'export const A = () => <div style={{ fontSize: 12, width: 1 }} />;',
errors: [{ message: message('fontSize'), line: 1, column: 38 }],
},
{
name: 'string key',
code: "export const A = () => <div style={{ 'line-height': 1 }} />;",
errors: [{ message: message('line-height') }],
},
{
name: 'every banned family',
code:
'export const A = () => (\n\t<div\n\t\tstyle={{\n\t\t\tfont: "x",\n\t\t\tfontWeight: 500,\n\t\t\tfontFamily: "x",\n\t\t\ttextAlign: "center",\n\t\t\ttextTransform: "none",\n\t\t\tlineHeight: 1,\n\t\t\tletterSpacing: 1,\n\t\t}}\n\t/>\n);',
errors: [
{ message: message('font') },
{ message: message('fontWeight') },
{ message: message('fontFamily') },
{ message: message('textAlign') },
{ message: message('textTransform') },
{ message: message('lineHeight') },
{ message: message('letterSpacing') },
],
},
{
name: 'conditional, logical and spread',
code:
'export const A = ({ a, b }) => (\n\t<div style={{ ...(a ? { fontSize: 1 } : {}), ...(b && { lineHeight: 1 }) }} />\n);',
errors: [
{ message: message('fontSize') },
{ message: message('lineHeight') },
],
},
{
name: 'style prop with a Style suffix',
code:
'export const A = () => <Card headStyle={{ fontWeight: 600 }} bodyStyle={{ padding: 0 }} />;',
errors: [{ message: message('fontWeight') }],
},
{
name: 'antd semantic styles',
code:
'export const A = () => <Modal styles={{ body: { fontSize: 12 }, header: { padding: 0 } }} />;',
errors: [{ message: message('fontSize') }],
},
{
name: 'identifier resolved to a local object',
code:
'const s = { fontSize: 12 };\nexport const A = () => (\n\t<>\n\t\t<div style={s} />\n\t\t<span style={s} />\n\t</>\n);',
errors: [{ message: message('fontSize'), line: 1, column: 13 }],
},
{
name: 'useMemo style',
code:
"import { useMemo } from 'react';\nexport const A = () => {\n\tconst s = useMemo(() => ({ textAlign: 'left' }), []);\n\treturn <div style={s} />;\n};",
errors: [{ message: message('textAlign') }],
},
{
name: 'object typed CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const s: CSSProperties = { fontStyle: 'italic' };",
errors: [{ message: message('fontStyle') }],
},
{
name:
'object typed React.CSSProperties, reported once when also used as style',
code:
"import React from 'react';\nconst s: React.CSSProperties = { fontSize: 1 };\nexport const A = () => <div style={s} />;",
errors: [{ message: message('fontSize') }],
},
{
name: 'Record of CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const s: Record<string, CSSProperties> = { a: { lineHeight: 1 } };",
errors: [{ message: message('lineHeight') }],
},
{
name: 'as and satisfies CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const a = { fontSize: 1 } as CSSProperties;\nexport const b = { fontWeight: 1 } satisfies CSSProperties;",
errors: [
{ message: message('fontSize') },
{ message: message('fontWeight') },
],
},
{
name: 'styled-components template',
code:
"import styled from 'styled-components';\nexport const A = styled.div`\n\tdisplay: flex;\n\tfont-size: 12px;\n\tcolor: ${(p) => p.c};\n\ttext-transform: none;line-height: 1;\n`;",
errors: [
{ message: message('font-size'), line: 4, column: 2 },
{ message: message('text-transform'), line: 6, column: 2 },
{ message: message('line-height'), line: 6, column: 23 },
],
},
{
name: 'function returning CSSProperties',
code:
"import type { CSSProperties } from 'react';\nexport const a = (): CSSProperties => ({ fontSize: 1 });\nexport function b(): CSSProperties {\n\treturn { lineHeight: 1 };\n}",
errors: [
{ message: message('fontSize') },
{ message: message('lineHeight') },
],
},
{
name: 'strings in styled interpolations',
code:
"import styled, { css } from 'styled-components';\nexport const A = styled.div`\n\t${(p) => (p.s ? 'font-size: 11px;' : `line-height: 1;`)}\n\t${(p) => p.b && css`font-weight: 500;`}\n`;",
errors: [
{ message: message('font-size'), line: 3, column: 19 },
{ message: message('line-height'), line: 3, column: 40 },
{ message: message('font-weight'), line: 4, column: 22 },
],
},
{
name: 'styled(Component) and css helper',
code:
"import styled, { css } from 'styled-components';\nexport const A = styled(B)`letter-spacing: 1px;`;\nexport const c = css`\n\tfont-weight: 500;\n`;",
errors: [
{ message: message('letter-spacing'), line: 2, column: 28 },
{ message: message('font-weight'), line: 4, column: 2 },
],
},
],
});

View File

@@ -0,0 +1,49 @@
import { ruleTester } from './rule-tester.mjs';
const message = 'Disabling signoz/no-text-css needs a reason after `--`.';
await ruleTester({
rule: 'require-disable-reason',
valid: [
{
name: 'reason after --',
code:
'// oxlint-disable-next-line signoz/no-text-css -- canvas label\nexport const a = 1;',
},
{
name: 'block comment with a reason',
code:
'/* eslint-disable signoz/no-text-css -- email HTML */\nexport const a = 1;',
},
{
name: 'another rule without a reason',
code: '// oxlint-disable-next-line no-console\nexport const a = 1;',
},
{
name: 'disable of every rule',
code: '// eslint-disable-next-line\nexport const a = 1;',
},
{
name: 'plain comment naming the rule',
code: '// signoz/no-text-css flags font CSS\nexport const a = 1;',
},
],
invalid: [
{
name: 'next-line without a reason',
code: '// oxlint-disable-next-line signoz/no-text-css\nexport const a = 1;',
errors: [{ message, line: 1, column: 1 }],
},
{
name: 'empty reason',
code: '// eslint-disable-line signoz/no-text-css --\nexport const a = 1;',
errors: [{ message }],
},
{
name: 'among other rules',
code:
'/* oxlint-disable no-console, signoz/no-text-css */\nexport const a = 1;',
errors: [{ message }],
},
],
});

View File

@@ -0,0 +1,324 @@
/**
* Rule: no-text-css
*
* Text style (font, line height, letter spacing, case, alignment, overflow)
* belongs to Typography props, not to CSS written in a component.
*
* This rule catches font and text properties in:
* <div style={{ fontSize: 12 }} /> style and *Style props
* <Modal styles={{ body: { fontWeight: 500 } }} />
* const s: CSSProperties = { lineHeight: 1 } objects typed CSSProperties
* ({ ... }) as CSSProperties, satisfies CSSProperties
* (): CSSProperties => ({ ... }) functions returning CSSProperties
* styled.div`font-size: 12px;` styled-components templates,
* ${(p) => p.small && 'font-size: 11px;'} strings in their interpolations
*
* Identifiers passed to a style prop are followed to a local object literal.
* SCSS is covered by the stylelint config.
*/
const MESSAGE = (property) =>
`Do not set '${property}' in CSS. Render the text with @signozhq/ui/typography and use its props, or disable this rule with a reason after \`--\` saying why Typography cannot.`;
const BANNED_JS = /^(font([A-Z]\w*)?|text[A-Z]\w*|lineHeight|letterSpacing)$/;
const BANNED_CSS =
/(^|[\s;{])(font(-[a-z]+)*|text-[a-z-]+|line-height|letter-spacing)\s*:/g;
const STYLE_TAGS = new Set(['css', 'createGlobalStyle', 'keyframes']);
const FUNCTIONS = new Set([
'ArrowFunctionExpression',
'FunctionExpression',
'FunctionDeclaration',
]);
const camelCase = (name) =>
name.replace(/-([a-z])/g, (_, letter) => letter.toUpperCase());
function propertyName(property) {
if (property.computed) {
return null;
}
if (property.key.type === 'Identifier') {
return property.key.name;
}
if (
property.key.type === 'Literal' &&
typeof property.key.value === 'string'
) {
return property.key.value;
}
return null;
}
function isCssPropertiesType(typeNode) {
if (!typeNode || typeNode.type !== 'TSTypeReference') {
return false;
}
const name = typeNode.typeName;
if (name.type === 'Identifier') {
return name.name === 'CSSProperties';
}
return name.type === 'TSQualifiedName' && name.right.name === 'CSSProperties';
}
// Record<K, CSSProperties> and { [key: string]: CSSProperties }
function isCssPropertiesMapType(typeNode) {
if (!typeNode) {
return false;
}
if (
typeNode.type === 'TSTypeReference' &&
typeNode.typeName.type === 'Identifier' &&
typeNode.typeName.name === 'Record'
) {
const params = (typeNode.typeArguments ?? typeNode.typeParameters)?.params;
return isCssPropertiesType(params?.[1]);
}
if (typeNode.type === 'TSTypeLiteral') {
return typeNode.members.some(
(member) =>
member.type === 'TSIndexSignature' &&
isCssPropertiesType(member.typeAnnotation?.typeAnnotation),
);
}
return false;
}
function rootIdentifier(node) {
let current = node;
while (current) {
if (current.type === 'Identifier') {
return current.name;
}
if (current.type === 'MemberExpression') {
current = current.object;
} else if (current.type === 'CallExpression') {
current = current.callee;
} else {
return null;
}
}
return null;
}
function isStyleTag(tag) {
if (tag.type === 'Identifier') {
return tag.name === 'styled' || STYLE_TAGS.has(tag.name);
}
return rootIdentifier(tag) === 'styled';
}
export default {
create(context) {
const reported = new Set();
const followed = new Set();
const reportedCss = new Set();
function report(property, name) {
if (reported.has(property)) {
return;
}
reported.add(property);
context.report({ node: property.key, message: MESSAGE(name) });
}
function resolveIdentifier(identifier) {
const scope = context.sourceCode.getScope(identifier);
let current = scope;
while (current) {
const variable = current.set.get(identifier.name);
if (variable) {
const definition = variable.defs[0];
if (
definition?.node?.type === 'VariableDeclarator' &&
definition.node.init
) {
return definition.node.init;
}
return null;
}
current = current.upper;
}
return null;
}
function checkObject(object) {
for (const property of object.properties) {
if (property.type === 'SpreadElement') {
checkStyle(property.argument);
continue;
}
const name = propertyName(property);
if (name && BANNED_JS.test(camelCase(name))) {
report(property, name);
}
}
}
function checkStyle(expression) {
if (!expression) {
return;
}
switch (expression.type) {
case 'ObjectExpression':
checkObject(expression);
return;
case 'ConditionalExpression':
checkStyle(expression.consequent);
checkStyle(expression.alternate);
return;
case 'LogicalExpression':
checkStyle(expression.left);
checkStyle(expression.right);
return;
case 'TSAsExpression':
case 'TSSatisfiesExpression':
case 'TSNonNullExpression':
case 'ParenthesizedExpression':
checkStyle(expression.expression);
return;
case 'CallExpression':
// useMemo(() => ({ ... }), deps)
if (
expression.callee.type === 'Identifier' &&
expression.callee.name === 'useMemo'
) {
checkReturned(expression.arguments[0]);
}
return;
case 'Identifier': {
const init = resolveIdentifier(expression);
if (!init || followed.has(init)) {
return;
}
followed.add(init);
checkStyle(init);
return;
}
default:
}
}
function checkReturned(fn) {
if (!fn || !FUNCTIONS.has(fn.type)) {
return;
}
if (fn.body.type !== 'BlockStatement') {
checkStyle(fn.body);
return;
}
for (const statement of fn.body.body) {
if (statement.type === 'ReturnStatement') {
checkStyle(statement.argument);
}
}
}
function checkStyleMap(expression) {
if (expression?.type !== 'ObjectExpression') {
return;
}
for (const property of expression.properties) {
if (property.type === 'Property') {
checkStyle(property.value);
}
}
}
// `start` is the index of the first character after the opening quote.
function checkCss(text, start) {
for (const match of text.matchAll(BANNED_CSS)) {
const index = start + match.index + match[1].length;
if (reportedCss.has(index)) {
continue;
}
reportedCss.add(index);
context.report({
loc: {
start: context.sourceCode.getLocFromIndex(index),
end: context.sourceCode.getLocFromIndex(index + match[2].length),
},
message: MESSAGE(match[2]),
});
}
}
// CSS returned from interpolations: ${(p) => p.small && 'font-size: 11px;'}
function checkCssStrings(node) {
if (!node || typeof node.type !== 'string') {
return;
}
if (node.type === 'TemplateLiteral') {
for (const quasi of node.quasis) {
checkCss(quasi.value.raw, quasi.range[0] + 1);
}
} else if (node.type === 'Literal' && typeof node.value === 'string') {
checkCss(node.raw.slice(1, -1), node.range[0] + 1);
return;
}
for (const [key, value] of Object.entries(node)) {
if (key === 'parent') {
continue;
}
if (Array.isArray(value)) {
value.forEach(checkCssStrings);
} else if (value && typeof value === 'object') {
checkCssStrings(value);
}
}
}
function checkFunction(node) {
if (isCssPropertiesType(node.returnType?.typeAnnotation)) {
checkReturned(node);
}
}
return {
JSXAttribute(node) {
if (
node.name.type !== 'JSXIdentifier' ||
node.value?.type !== 'JSXExpressionContainer'
) {
return;
}
const name = node.name.name;
if (name === 'styles') {
checkStyleMap(node.value.expression);
} else if (name === 'style' || name.endsWith('Style')) {
checkStyle(node.value.expression);
}
},
VariableDeclarator(node) {
const type = node.id.typeAnnotation?.typeAnnotation;
if (isCssPropertiesType(type)) {
checkStyle(node.init);
} else if (isCssPropertiesMapType(type)) {
checkStyleMap(node.init);
}
},
TSAsExpression(node) {
if (isCssPropertiesType(node.typeAnnotation)) {
checkStyle(node.expression);
}
},
TSSatisfiesExpression(node) {
if (isCssPropertiesType(node.typeAnnotation)) {
checkStyle(node.expression);
} else if (isCssPropertiesMapType(node.typeAnnotation)) {
checkStyleMap(node.expression);
}
},
TaggedTemplateExpression(node) {
if (!isStyleTag(node.tag)) {
return;
}
checkCssStrings(node.quasi);
},
ArrowFunctionExpression: checkFunction,
FunctionExpression: checkFunction,
FunctionDeclaration: checkFunction,
};
},
};

View File

@@ -0,0 +1,38 @@
/**
* Rule: require-disable-reason
*
* A disable directive that names one of RULES must say why after `--`:
* // oxlint-disable-next-line signoz/no-text-css -- canvas text, not DOM
*
* Directives that disable every rule are not checked.
*/
const RULES = new Set(['signoz/no-text-css']);
const DIRECTIVE = /^\s*(?:eslint|oxlint)-disable(?:-next-line|-line)?\s+(.*)$/s;
export default {
create(context) {
return {
Program() {
for (const comment of context.sourceCode.getAllComments()) {
const match = comment.value.match(DIRECTIVE);
if (!match) {
continue;
}
const [rules, reason] = match[1].split(/\s--\s?/);
const named = rules
.split(',')
.map((rule) => rule.trim())
.filter((rule) => RULES.has(rule));
if (named.length > 0 && !reason?.trim()) {
context.report({
node: comment,
message: `Disabling ${named.join(', ')} needs a reason after \`--\`.`,
});
}
}
},
};
},
};

View File

@@ -17,6 +17,8 @@ import noConditionalTextNodesWithSiblings from './rules/no-conditional-text-node
import noReturnTextNodes from './rules/no-return-text-nodes.mjs';
import noMswInStoryFile from './rules/no-msw-in-story-file.mjs';
import noDirectReactRouterImport from './rules/no-direct-react-router-import.mjs';
import noTextCss from './rules/no-text-css.mjs';
import requireDisableReason from './rules/require-disable-reason.mjs';
export default {
meta: {
@@ -35,5 +37,7 @@ export default {
'no-return-text-nodes': noReturnTextNodes,
'no-msw-in-story-file': noMswInStoryFile,
'no-direct-react-router-import': noDirectReactRouterImport,
'no-text-css': noTextCss,
'require-disable-reason': requireDisableReason,
},
};

1189
frontend/pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -34,10 +34,6 @@
"title": "Partition Latency view",
"description": "Connect and Monitor Your Data Streams"
},
"dropRate": {
"title": "Drop Rate view",
"description": "Connect and Monitor Your Data Streams"
},
"metricPage": {
"title": "Metric View",
"description": "Connect and Monitor Your Data Streams"

View File

@@ -34,10 +34,6 @@
"title": "Partition Latency view",
"description": "Connect and Monitor Your Data Streams"
},
"dropRate": {
"title": "Drop Rate view",
"description": "Connect and Monitor Your Data Streams"
},
"metricPage": {
"title": "Metric View",
"description": "Connect and Monitor Your Data Streams"

View File

@@ -1746,7 +1746,7 @@ export const useTestRule = <
return useMutation(getTestRuleMutationOptions(options));
};
/**
* Returns a page of alert rules with their current evaluation state, trimmed to the fields the list page renders. Supports a filter DSL (`query`), a repeated `states` filter applied after the state overlay, sort (`updated_at`/`created_at`/`name`/`state`/`severity`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`). In the filter DSL, a non-reserved key is matched as a rule label directly (`team = infra`); a key that collides with a reserved keyword matches either interpretation (negative operators exclude both), and `labels.<key>` targets only the label. The response also carries the org's label pairs and the reserved filter keys for building filter suggestions.
* Returns a page of alert rules with their current evaluation state, trimmed to the fields the list page renders. Supports a filter DSL (`query`), a repeated `states` filter applied after the state overlay, sort (`updated_at`/`created_at`/`name`/`state`/`thresholds`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`). In the filter DSL, a non-reserved key is matched as a rule label directly (`team = infra`); a key that collides with a reserved keyword matches either interpretation (negative operators exclude both), and `labels.<key>` targets only the label. The response also carries the org's label pairs and the reserved filter keys for building filter suggestions.
* @summary List alert rules (v3)
*/
export const listRulesV3 = (

View File

@@ -34,6 +34,7 @@ import type {
ListServiceAccountKeys200,
ListServiceAccountKeysPathParameters,
ListServiceAccounts200,
ListServiceAccountsParams,
RenderErrorResponseDTO,
RevokeServiceAccountKeyPathParameters,
ServiceaccounttypesPostableFactorAPIKeyDTO,
@@ -334,38 +335,48 @@ export const invalidateGetServiceAccountRole = async (
};
/**
* This endpoint lists the service accounts for an organisation
* Returns a page of the service accounts for an organisation. `query` is a filter expression over name, email, status, created_at and updated_at, for example `status = 'active'`; `sort`/`order` pick the ordering and `limit`/`offset` the page.
* @summary List service accounts
*/
export const listServiceAccounts = (signal?: AbortSignal) => {
export const listServiceAccounts = (
params?: ListServiceAccountsParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<ListServiceAccounts200>({
url: `/api/v1/service_accounts`,
method: 'GET',
params,
signal,
});
};
export const getListServiceAccountsQueryKey = () => {
return [`/api/v1/service_accounts`] as const;
export const getListServiceAccountsQueryKey = (
params?: ListServiceAccountsParams,
) => {
return [`/api/v1/service_accounts`, ...(params ? [params] : [])] as const;
};
export const getListServiceAccountsQueryOptions = <
TData = Awaited<ReturnType<typeof listServiceAccounts>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
}) => {
>(
params?: ListServiceAccountsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey = queryOptions?.queryKey ?? getListServiceAccountsQueryKey();
const queryKey =
queryOptions?.queryKey ?? getListServiceAccountsQueryKey(params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof listServiceAccounts>>
> = ({ signal }) => listServiceAccounts(signal);
> = ({ signal }) => listServiceAccounts(params, signal);
return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
@@ -386,14 +397,17 @@ export type ListServiceAccountsQueryError = ErrorType<RenderErrorResponseDTO>;
export function useListServiceAccounts<
TData = Awaited<ReturnType<typeof listServiceAccounts>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListServiceAccountsQueryOptions(options);
>(
params?: ListServiceAccountsParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof listServiceAccounts>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getListServiceAccountsQueryOptions(params, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
@@ -407,10 +421,11 @@ export function useListServiceAccounts<
*/
export const invalidateListServiceAccounts = async (
queryClient: QueryClient,
params?: ListServiceAccountsParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getListServiceAccountsQueryKey() },
{ queryKey: getListServiceAccountsQueryKey(params) },
options,
);

View File

@@ -5284,6 +5284,7 @@ export interface TelemetrytypesTelemetryFieldKeyDTO {
}
export enum TelemetrytypesSourceDTO {
audit = 'audit',
meter = 'meter',
'' = '',
}
@@ -8042,7 +8043,7 @@ export interface DashboardtypesDashboardSpecDTO {
display: DashboardtypesDisplayDTO;
/**
* @type string
* @description The default time range, as a Prometheus duration such as 1h or 7d. Stored, but not applied by the UI.
* @description The default time range, as a Prometheus duration such as 1h or 7d. The UI opens the dashboard on it, rounded up to whole minutes, when neither the URL nor the viewer's last pick sets a time range.
*/
duration?: string;
/**
@@ -13017,7 +13018,7 @@ export enum RuletypesListSortDTO {
created_at = 'created_at',
name = 'name',
state = 'state',
severity = 'severity',
thresholds = 'thresholds',
}
/**
* The labels attached to alerts the rule fires.
@@ -13076,6 +13077,11 @@ export interface RuletypesListableRuleDTO {
* @description The current evaluation state: inactive, pending, recovering, firing, nodata or disabled.
*/
state: RuletypesAlertStateDTO;
/**
* @type array
* @description The rule's threshold names in lowercase, deduplicated and ordered critical, error, warning, info, then other names. An alert carries the name of the threshold that fired as its severity. Read-only.
*/
thresholds: string[];
/**
* @type string
* @format date-time
@@ -13098,7 +13104,7 @@ export interface RuletypesRuleViewDataDTO {
*/
query?: string;
/**
* @description The field to sort by: updated_at (the default), created_at, name, state or severity.
* @description The field to sort by: updated_at (the default), created_at, name, state or thresholds. Sorting by thresholds ranks each rule by its first threshold name.
*/
sort?: RuletypesListSortDTO;
/**
@@ -13611,6 +13617,13 @@ export interface SavedviewtypesUpdatableSavedViewDTO {
spec: SavedviewtypesSavedViewSpecDTO;
}
export enum ServiceaccounttypesDSLKeyDTO {
created_at = 'created_at',
email = 'email',
name = 'name',
status = 'status',
updated_at = 'updated_at',
}
export interface ServiceaccounttypesGettableFactorAPIKeyDTO {
/**
* @type string
@@ -13657,6 +13670,59 @@ export interface ServiceaccounttypesGettableFactorAPIKeyWithKeyDTO {
key: string;
}
export enum ServiceaccounttypesServiceAccountStatusDTO {
active = 'active',
deleted = 'deleted',
}
export interface ServiceaccounttypesServiceAccountDTO {
/**
* @type string
* @format date-time
*/
createdAt: string;
/**
* @type string
*/
email: string;
/**
* @type string
*/
id: string;
/**
* @type string
*/
name: string;
/**
* @type string
*/
orgId: string;
status: ServiceaccounttypesServiceAccountStatusDTO;
/**
* @type string
* @format date-time
*/
updatedAt: string;
}
export interface ServiceaccounttypesListableServiceAccountDTO {
/**
* @type array
* @description The filter keys the query accepts.
*/
reservedKeywords: ServiceaccounttypesDSLKeyDTO[];
/**
* @type array
* @description The service accounts on this page.
*/
serviceAccounts: ServiceaccounttypesServiceAccountDTO[];
/**
* @type integer
* @format int64
* @description The number of service accounts the filter matches across all pages.
*/
total: number;
}
export interface ServiceaccounttypesPostableFactorAPIKeyDTO {
/**
* @type integer
@@ -13687,39 +13753,15 @@ export interface ServiceaccounttypesPostableServiceAccountRoleDTO {
serviceAccountId: string;
}
export interface ServiceaccounttypesServiceAccountDTO {
/**
* @type string
* @format date-time
*/
createdAt?: string;
/**
* @type string
*/
email: string;
/**
* @type string
*/
id: string;
/**
* @type string
*/
name: string;
/**
* @type string
*/
orgId: string;
/**
* @type string
*/
status: string;
/**
* @type string
* @format date-time
*/
updatedAt?: string;
export enum ServiceaccounttypesServiceAccountListOrderDTO {
asc = 'asc',
desc = 'desc',
}
export enum ServiceaccounttypesServiceAccountListSortDTO {
created_at = 'created_at',
updated_at = 'updated_at',
name = 'name',
}
export interface ServiceaccounttypesServiceAccountRoleDTO {
/**
* @type string
@@ -13751,7 +13793,7 @@ export interface ServiceaccounttypesServiceAccountWithRolesDTO {
* @type string
* @format date-time
*/
createdAt?: string;
createdAt: string;
/**
* @type string
*/
@@ -13772,15 +13814,12 @@ export interface ServiceaccounttypesServiceAccountWithRolesDTO {
* @type array,null
*/
serviceAccountRoles: ServiceaccounttypesServiceAccountRoleDTO[] | null;
/**
* @type string
*/
status: string;
status: ServiceaccounttypesServiceAccountStatusDTO;
/**
* @type string
* @format date-time
*/
updatedAt?: string;
updatedAt: string;
}
export interface ServiceaccounttypesUpdatableFactorAPIKeyDTO {
@@ -13817,28 +13856,6 @@ export interface SpantypesEventDTO {
timeUnixNano?: number;
}
export type SpantypesEventV2DTOAttributes = { [key: string]: unknown };
export interface SpantypesEventV2DTO {
/**
* @type object
*/
attributes?: SpantypesEventV2DTOAttributes;
/**
* @type boolean
*/
isError?: boolean;
/**
* @type string
*/
name?: string;
/**
* @type integer
* @minimum 0
*/
timeUnixNano?: number;
}
export enum SpantypesFieldContextDTO {
attribute = 'attribute',
resource = 'resource',
@@ -14529,17 +14546,6 @@ export interface SpantypesGettableWaterfallTraceDTO {
uncollapsedSpans?: string[] | null;
}
export interface SpantypesLinkDTO {
/**
* @type string
*/
spanId?: string;
/**
* @type string
*/
traceId?: string;
}
export interface SpantypesPostableFlamegraphDTO {
/**
* @type array
@@ -14626,497 +14632,6 @@ export interface SpantypesPostableWaterfallDTO {
uncollapsedSpans?: string[] | null;
}
export type SpantypesSpanRecordDTOAttributes = { [key: string]: unknown };
export type SpantypesSpanRecordDTOResource = { [key: string]: string };
export interface SpantypesTruncatedFieldDTO {
/**
* @type string
*/
field: string;
/**
* @type integer
* @minimum 0
*/
length: number;
}
export interface SpantypesSpanRecordDTO {
/**
* @type object
*/
attributes: SpantypesSpanRecordDTOAttributes;
/**
* @type array
*/
events: SpantypesEventV2DTO[];
/**
* @type array
*/
links: SpantypesLinkDTO[];
/**
* @type object
*/
resource: SpantypesSpanRecordDTOResource;
/**
* @type string
*/
spanId: string;
/**
* @type string
*/
statusCode: string;
/**
* @type string
*/
statusMessage: string;
/**
* @type array
*/
truncated: SpantypesTruncatedFieldDTO[];
}
export interface SpantypesSpanSummaryDTO {
/**
* @type integer
* @minimum 0
*/
childCount: number;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type boolean
*/
hasError: boolean;
/**
* @type string
*/
kind: string;
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type string
*/
name: string;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
parentSpanId?: string;
/**
* @type string
*/
responseStatusCode?: string;
/**
* @type string
*/
serviceName: string;
/**
* @type string
*/
spanId: string;
/**
* @type integer
* @minimum 0
*/
startOffsetNano: number;
/**
* @type integer
* @minimum 0
*/
subtreeSpanCount: number;
}
export interface SpantypesSpanTextMatchDTO {
/**
* @type string
*/
field: string;
/**
* @type string
*/
snippet: string;
}
export interface SpantypesTraceAIIdentityDTO {
/**
* @type integer
* @minimum 0
*/
modelCallCount: number;
tokens: SpantypesTraceAITokensDTO;
/**
* @type integer
* @minimum 0
*/
toolCallCount: number;
/**
* @type number
*/
totalCost?: number;
}
export interface SpantypesTraceErrorItemDTO {
/**
* @type integer
* @minimum 0
*/
errorAncestorCount: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type string
*/
statusMessage: string;
}
export interface SpantypesTraceErrorListDTO {
/**
* @type array
*/
items: SpantypesTraceErrorItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceExpensiveItemDTO {
/**
* @type number
*/
cost?: number;
/**
* @type integer
* @minimum 0
*/
inputTokens: number;
/**
* @type integer
* @minimum 0
*/
outputTokens: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceExpensiveListDTO {
/**
* @type array
*/
items: SpantypesTraceExpensiveItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceServiceStatsDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
/**
* @type string
*/
serviceName: string;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceIdentityDTO {
ai?: SpantypesTraceAIIdentityDTO;
/**
* @type integer
* @minimum 0
*/
durationNano: number;
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type boolean
*/
hasMissingSpans: boolean;
root?: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
rootCount: number;
/**
* @type integer
* @minimum 0
*/
serviceCount: number;
/**
* @type array
*/
services: SpantypesTraceServiceStatsDTO[];
/**
* @type integer
* @minimum 0
*/
spanCount: number;
/**
* @type integer
* @minimum 0
*/
startTimestampMillis: number;
/**
* @type string
*/
traceId: string;
}
export interface SpantypesTraceLinkItemDTO {
/**
* @type integer
* @minimum 0
*/
linkCount: number;
/**
* @type array
*/
links: SpantypesLinkDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceLinkListDTO {
/**
* @type array
*/
items: SpantypesTraceLinkItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSlowestItemDTO {
/**
* @type integer
* @minimum 0
*/
errorSpanCount: number;
/**
* @type integer
* @minimum 0
*/
ownTimeNano: number;
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
/**
* @type integer
* @minimum 0
*/
spanCount: number;
}
export interface SpantypesTraceSlowestListDTO {
/**
* @type array
*/
items: SpantypesTraceSlowestItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceTreeDTO {
/**
* @type boolean
*/
complete: boolean;
/**
* @type array
*/
records?: SpantypesSpanRecordDTO[];
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export enum SpantypesUnmarkedFailureReasonDTO {
http_4xx = 'http_4xx',
grpc_status = 'grpc_status',
exception_event = 'exception_event',
}
export interface SpantypesTraceUnmarkedFailureItemDTO {
parent?: SpantypesSpanSummaryDTO;
reason: SpantypesUnmarkedFailureReasonDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceUnmarkedFailureListDTO {
/**
* @type array
*/
items: SpantypesTraceUnmarkedFailureItemDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceOverviewDTO {
errors?: SpantypesTraceErrorListDTO;
expensive?: SpantypesTraceExpensiveListDTO;
identity?: SpantypesTraceIdentityDTO;
links?: SpantypesTraceLinkListDTO;
slowest?: SpantypesTraceSlowestListDTO;
tree?: SpantypesTraceTreeDTO;
unmarkedFailures?: SpantypesTraceUnmarkedFailureListDTO;
}
export interface SpantypesTraceSpanLevelDTO {
/**
* @type integer
* @minimum 0
*/
level: number;
/**
* @type array
*/
spans: SpantypesSpanSummaryDTO[];
/**
* @type integer
* @minimum 0
*/
total: number;
}
export interface SpantypesTraceSpanPercentileDTO {
/**
* @type integer
* @minimum 0
*/
p50Nano: number;
/**
* @type integer
* @minimum 0
*/
p90Nano: number;
/**
* @type integer
* @minimum 0
*/
p99Nano: number;
/**
* @type number
* @format double
*/
position: number;
/**
* @type integer
* @minimum 0
*/
windowMinutes: number;
}
export interface SpantypesTraceSpanDetailDTO {
/**
* @type integer
* @minimum 0
*/
ancestorCount: number;
/**
* @type array
*/
ancestors: SpantypesSpanSummaryDTO[];
/**
* @type array
*/
descendants: SpantypesTraceSpanLevelDTO[];
percentile?: SpantypesTraceSpanPercentileDTO;
record: SpantypesSpanRecordDTO;
summary: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceSpanMatchDTO {
/**
* @type array
*/
matches: SpantypesSpanTextMatchDTO[];
parent?: SpantypesSpanSummaryDTO;
span: SpantypesSpanSummaryDTO;
}
export interface SpantypesTraceSpanListDTO {
/**
* @type array
*/
items: SpantypesTraceSpanMatchDTO[];
/**
* @type string
*/
nextCursor?: string;
/**
* @type integer
* @minimum 0
*/
total: number;
/**
* @type array
*/
warnings?: string[];
}
export interface SpantypesUpdatableSpanMapperDTO {
config?: SpantypesSpanMapperConfigDTO;
/**
@@ -16352,11 +15867,34 @@ export type GetServiceAccountRole200 = {
status: string;
};
export type ListServiceAccounts200 = {
export type ListServiceAccountsParams = {
/**
* @type array
* @type string
* @description A filter expression over the reserved keys name, email, status, created_at and updated_at using the SigNoz filter grammar: comparisons such as =, !=, CONTAINS, LIKE, IN, < and >, single-quoted strings, RFC3339 timestamps in quotes for created_at and updated_at, combined with AND, OR and NOT, for example name CONTAINS 'ci' AND status = 'active'. A bare or quoted token without a key matches name or email case-insensitively. At most 1024 characters. Empty matches every service account.
*/
data: ServiceaccounttypesServiceAccountDTO[];
query?: string;
/**
* @description The sort column: created_at (default), updated_at or name.
*/
sort?: ServiceaccounttypesServiceAccountListSortDTO;
/**
* @description The sort order: asc or desc (default).
*/
order?: ServiceaccounttypesServiceAccountListOrderDTO;
/**
* @type integer
* @description The page size; defaults to 20 and is capped at 200.
*/
limit?: number;
/**
* @type integer
* @description The number of service accounts to skip; defaults to 0.
*/
offset?: number;
};
export type ListServiceAccounts200 = {
data: ServiceaccounttypesListableServiceAccountDTO;
/**
* @type string
*/
@@ -16559,84 +16097,6 @@ export type GetTraceAggregations200 = {
status: string;
};
export type InspectTracePathParameters = {
traceID: string;
};
export type InspectTraceParams = {
/**
* @type string
* @description The nextCursor of one list of the overview; returns the next page of that list and nothing else.
*/
cursor?: string;
};
export type InspectTrace200 = {
data: SpantypesTraceOverviewDTO;
/**
* @type string
*/
status: string;
};
export type InspectTraceSpansPathParameters = {
traceID: string;
};
export type InspectTraceSpansParams = {
/**
* @type string
* @description Returns the spans that match, earliest first: words, a filter expression, or both, such as worldpay AND has_error = true. Words match the span name, status message, attributes, resource attributes and events, ignoring case. Without it every span is returned, in tree order.
*/
search?: string;
/**
* @type string
* @description A span ID; returns that span and every span below it. Cannot be combined with search.
*/
under?: string;
/**
* @type integer
* @description Page size, at most 1000; when not given, 20 with search and 400 without. A page holds fewer spans when it would pass the response size limit.
*/
limit?: number;
/**
* @type string
* @description The nextCursor of an earlier response to the same request; returns the next page.
*/
cursor?: string;
};
export type InspectTraceSpans200 = {
data: SpantypesTraceSpanListDTO;
/**
* @type string
*/
status: string;
};
export type InspectTraceSpanPathParameters = {
traceID: string;
spanID: string;
};
export type InspectTraceSpanParams = {
/**
* @type integer
* @description The number of levels of ancestors and of descendants returned, 1 to 10; 2 when not given. The root span is always returned.
*/
depth?: number;
/**
* @type array
* @description Attribute names returned without the 500 character cut; the record then holds only these attributes.
*/
selectFields?: string[];
};
export type InspectTraceSpan200 = {
data: SpantypesTraceSpanDetailDTO;
/**
* @type string
*/
status: string;
};
export type GetTraceSummaryPathParameters = {
traceID: string;
};
@@ -18186,7 +17646,7 @@ export type ListRulesV3Params = {
*/
states?: string[];
/**
* @description The field to sort by: updated_at (the default), created_at, name, state or severity.
* @description The field to sort by: updated_at (the default), created_at, name, state or thresholds. Sorting by thresholds ranks each rule by its first threshold name.
*/
sort?: RuletypesListSortDTO;
/**

View File

@@ -29,15 +29,6 @@ import type {
GetTraceThreadPathParameters,
GetWaterfallV4200,
GetWaterfallV4PathParameters,
InspectTrace200,
InspectTraceParams,
InspectTracePathParameters,
InspectTraceSpan200,
InspectTraceSpanParams,
InspectTraceSpanPathParameters,
InspectTraceSpans200,
InspectTraceSpansParams,
InspectTraceSpansPathParameters,
RenderErrorResponseDTO,
SpantypesPostableFlamegraphDTO,
SpantypesPostableTraceAggregationsDTO,
@@ -167,352 +158,6 @@ export const useGetTraceAggregations = <
> => {
return useMutation(getGetTraceAggregationsMutationOptions(options));
};
/**
* Returns the overview of a trace of any size: its identity with per-service totals, the spans where each error started, the failures not marked as errors, the slowest spans by own time, the most expensive gen_ai spans, the spans that link to other spans, and the top of the span tree. A small trace also returns each span's full record. Every list carries its total and a nextCursor when more items follow.
* @summary Inspect a trace
*/
export const inspectTrace = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTrace200>({
url: `/api/v1/traces/${traceID}/inspect`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceQueryKey = (
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getInspectTraceQueryKey({ traceID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof inspectTrace>>> = ({
signal,
}) => inspectTrace({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTrace>>
>;
export type InspectTraceQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Inspect a trace
*/
export function useInspectTrace<
TData = Awaited<ReturnType<typeof inspectTrace>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTrace>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceQueryOptions({ traceID }, params, options);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Inspect a trace
*/
export const invalidateInspectTrace = async (
queryClient: QueryClient,
{ traceID }: InspectTracePathParameters,
params?: InspectTraceParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns the spans of a trace that match a search, each with its direct parent and where the words were found. Without a search it returns every span in tree order, or with under one span and the spans below it.
* @summary Search or list the spans of a trace
*/
export const inspectTraceSpans = (
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTraceSpans200>({
url: `/api/v1/traces/${traceID}/inspect/spans`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceSpansQueryKey = (
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect/spans`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceSpansQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTraceSpans>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpans>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ?? getInspectTraceSpansQueryKey({ traceID }, params);
const queryFn: QueryFunction<
Awaited<ReturnType<typeof inspectTraceSpans>>
> = ({ signal }) => inspectTraceSpans({ traceID }, params, signal);
return {
queryKey,
queryFn,
enabled: traceID !== null && traceID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpans>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceSpansQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTraceSpans>>
>;
export type InspectTraceSpansQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Search or list the spans of a trace
*/
export function useInspectTraceSpans<
TData = Awaited<ReturnType<typeof inspectTraceSpans>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpans>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceSpansQueryOptions(
{ traceID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Search or list the spans of a trace
*/
export const invalidateInspectTraceSpans = async (
queryClient: QueryClient,
{ traceID }: InspectTraceSpansPathParameters,
params?: InspectTraceSpansParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceSpansQueryKey({ traceID }, params) },
options,
);
return queryClient;
};
/**
* Returns one span in full: its summary and record, its nearest ancestors with the root, the spans below it level by level, and where its duration sits among recent spans of the same name and service. Long values are cut and listed in truncated; selectFields returns named attributes without the cut.
* @summary Inspect a span of a trace
*/
export const inspectTraceSpan = (
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
signal?: AbortSignal,
) => {
return GeneratedAPIInstance<InspectTraceSpan200>({
url: `/api/v1/traces/${traceID}/inspect/spans/${spanID}`,
method: 'GET',
params,
signal,
});
};
export const getInspectTraceSpanQueryKey = (
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
) => {
return [
`/api/v1/traces/${traceID}/inspect/spans/${spanID}`,
...(params ? [params] : []),
] as const;
};
export const getInspectTraceSpanQueryOptions = <
TData = Awaited<ReturnType<typeof inspectTraceSpan>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpan>>,
TError,
TData
>;
},
) => {
const { query: queryOptions } = options ?? {};
const queryKey =
queryOptions?.queryKey ??
getInspectTraceSpanQueryKey({ traceID, spanID }, params);
const queryFn: QueryFunction<Awaited<ReturnType<typeof inspectTraceSpan>>> = ({
signal,
}) => inspectTraceSpan({ traceID, spanID }, params, signal);
return {
queryKey,
queryFn,
enabled:
traceID !== null &&
traceID !== undefined &&
spanID !== null &&
spanID !== undefined,
...queryOptions,
} as UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpan>>,
TError,
TData
> & { queryKey: QueryKey };
};
export type InspectTraceSpanQueryResult = NonNullable<
Awaited<ReturnType<typeof inspectTraceSpan>>
>;
export type InspectTraceSpanQueryError = ErrorType<RenderErrorResponseDTO>;
/**
* @summary Inspect a span of a trace
*/
export function useInspectTraceSpan<
TData = Awaited<ReturnType<typeof inspectTraceSpan>>,
TError = ErrorType<RenderErrorResponseDTO>,
>(
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
options?: {
query?: UseQueryOptions<
Awaited<ReturnType<typeof inspectTraceSpan>>,
TError,
TData
>;
},
): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
const queryOptions = getInspectTraceSpanQueryOptions(
{ traceID, spanID },
params,
options,
);
const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
return withQueryKey(query, queryOptions.queryKey);
}
/**
* @summary Inspect a span of a trace
*/
export const invalidateInspectTraceSpan = async (
queryClient: QueryClient,
{ traceID, spanID }: InspectTraceSpanPathParameters,
params?: InspectTraceSpanParams,
options?: InvalidateOptions,
): Promise<QueryClient> => {
await queryClient.invalidateQueries(
{ queryKey: getInspectTraceSpanQueryKey({ traceID, spanID }, params) },
options,
);
return queryClient;
};
/**
* Returns the trace's time range, root span, span and error counts, and whether any spans are missing. AI traces also include token and cost totals.
* @summary Get summary for a trace

View File

@@ -12,7 +12,6 @@ export interface MessagingQueueServicePayload {
service_name?: string;
};
detailType?: MessagingQueueServiceDetailType | 'producer' | 'consumer';
evalTime?: number;
}
export interface MessagingQueuesPayloadProps {

View File

@@ -1,23 +0,0 @@
import axios from 'api';
import { DropRateAPIResponse } from 'pages/MessagingQueues/MQDetails/DropRateView/dropRateViewUtils';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { MessagingQueueServicePayload } from './getConsumerLagDetails';
export const getKafkaSpanEval = async (
props: Omit<MessagingQueueServicePayload, 'detailType' | 'variables'>,
): Promise<SuccessResponse<DropRateAPIResponse['data']> | ErrorResponse> => {
const { start, end, evalTime } = props;
const response = await axios.post(`messaging-queues/kafka/span/evaluation`, {
start,
end,
eval_time: evalTime,
});
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data.data,
};
};

View File

@@ -1,61 +0,0 @@
import { ApiV3Instance as axios } from 'api';
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
import { AxiosError } from 'axios';
import createQueryParams from 'lib/createQueryParams';
import { ErrorResponse, SuccessResponse } from 'types/api';
import {
TagKeyProps,
TagKeysPayloadProps,
TagValueProps,
TagValuesPayloadProps,
} from 'types/api/metrics/getResourceAttributes';
import { DataSource, MetricAggregateOperator } from 'types/common/queryBuilder';
export const getResourceAttributesTagKeys = async (
props: TagKeyProps,
): Promise<SuccessResponse<TagKeysPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_keys?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
searchText: props.match,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};
export const getResourceAttributesTagValues = async (
props: TagValueProps,
): Promise<SuccessResponse<TagValuesPayloadProps> | ErrorResponse> => {
try {
const response = await axios.get(
`/autocomplete/attribute_values?${createQueryParams({
aggregateOperator: MetricAggregateOperator.RATE,
dataSource: DataSource.METRICS,
aggregateAttribute: props.metricName,
attributeKey: props.tagKey,
searchText: '',
})}`,
);
return {
statusCode: 200,
error: null,
message: response.data.status,
payload: response.data,
};
} catch (error) {
return ErrorResponseHandler(error as AxiosError);
}
};

View File

@@ -302,6 +302,10 @@ export function createAggregation(
reduceTo: haveReduceTo
? queryData?.aggregations?.[0]?.reduceTo || queryData?.reduceTo
: undefined,
...(queryData?.aggregations?.[0]?.comparisonSpaceAggregationParam && {
comparisonSpaceAggregationParam:
queryData.aggregations[0].comparisonSpaceAggregationParam,
}),
},
];
}

View File

@@ -1,5 +1,6 @@
import { useMutation } from 'react-query';
import { Button, Modal } from 'antd';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import { Typography } from '@signozhq/ui/typography';
import { createSubscription } from 'api/generated/services/subscriptions';
import type { CreateSubscription201 } from 'api/generated/services/sigNoz.schemas';
@@ -55,46 +56,51 @@ function AddCreditCardModal({
};
return (
<Modal
className="add-credit-card-modal"
title={<span className="title">Add Credit Card for Chat Support</span>}
<Dialog
open={open}
closable
onCancel={onClose}
destroyOnClose
footer={[
<Button
key="cancel"
onClick={onClose}
className="cancel-btn"
icon={<X size={16} />}
>
Cancel
</Button>,
<AuthZTooltip
key="submit"
checks={[SubscriptionCreatePermission]}
withPortal={false}
>
onClose={onClose}
title="Add Credit Card for Chat Support"
testId="add-credit-card-modal"
footerSuffix={
<>
<Button
type="primary"
icon={<CreditCard size={16} />}
size="middle"
loading={isLoadingBilling}
disabled={isLoadingBilling}
onClick={handleAddCreditCard}
className="add-credit-card-btn"
variant="outlined"
color="secondary"
size="md"
prefix={<X size={16} />}
onClick={onClose}
testId="add-credit-card-cancel"
>
Add Credit Card
Cancel
</Button>
</AuthZTooltip>,
]}
<AuthZTooltip checks={[SubscriptionCreatePermission]}>
<Button
variant="solid"
color="primary"
size="md"
prefix={<CreditCard size={16} />}
loading={isLoadingBilling}
onClick={handleAddCreditCard}
testId="add-credit-card-submit"
>
Add Credit Card
</Button>
</AuthZTooltip>
</>
}
>
<Typography.Text className="add-credit-card-text">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
You&apos;re currently on <span className="highlight-text">Trial plan</span>.
Add a credit card to access SigNoz chat support to your workspace.
</Typography.Text>
</Modal>
</Typography>
</Dialog>
);
}

View File

@@ -1,6 +1,9 @@
.breadcrumb {
padding: var(--spacing-4) 16px var(--spacing-2);
// The antd breadcrumb provides the item spacing.
--button-padding: 0;
ol {
align-items: center;
}
@@ -8,13 +11,4 @@
:global(.ant-breadcrumb-separator) {
color: var(--muted-foreground);
}
[data-slot='button'] {
padding: 0px;
}
}
.divider {
--divider-color: var(--l1-border);
--divider-margin: 10px 0 16px 0;
}

View File

@@ -28,7 +28,7 @@ function AlertBreadcrumb({
items={breadcrumbItems}
data-testid={testId}
/>
{showDivider && <Divider className={styles.divider} />}
{showDivider && <Divider spacing="10px 16px" />}
</>
);
}

View File

@@ -1,5 +1,4 @@
.itemLast {
color: var(--button-secondary-label);
font-size: var(--button-font-size, var(--periscope-font-size-base));
line-height: var(--button-size-line-height, 16px);
}

View File

@@ -1,6 +1,6 @@
import { Copy } from '@signozhq/icons';
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
import { toast } from '@signozhq/ui/sonner';
import { toast } from '@signozhq/ui/toast';
import { Tooltip } from '@signozhq/ui/tooltip';
import cx from 'classnames';
import { useLayoutEffect, useRef, useState } from 'react';
@@ -15,12 +15,14 @@ export interface LabelColumnProps {
labels: string[];
color?: BadgeColorType;
value?: { [key: string]: string };
testId?: string;
}
function LabelColumn({
labels,
value,
color = 'primary',
testId = 'label-column',
}: LabelColumnProps): JSX.Element {
const containerRef = useRef<HTMLDivElement>(null);
const [visibleCount, setVisibleCount] = useState(labels.length);
@@ -56,11 +58,7 @@ function LabelColumn({
const remainingLabels = labels.slice(visibleCount);
return (
<div
ref={containerRef}
className={styles.labelColumn}
data-testid="label-column"
>
<div ref={containerRef} className={styles.labelColumn} data-testid={testId}>
{labels.map((label, index) => (
<LabelTag
key={label}

View File

@@ -1,6 +1,6 @@
import { Copy } from '@signozhq/icons';
import { Badge, type BadgeColorType } from '@signozhq/ui/badge';
import { toast } from '@signozhq/ui/sonner';
import { toast } from '@signozhq/ui/toast';
import { Tooltip } from '@signozhq/ui/tooltip';
import { useCopyToClipboard } from 'react-use';

View File

@@ -26,8 +26,6 @@
}
.brand-title {
font-size: 20px;
font-weight: 600;
color: var(--l1-foreground); // Primary text
margin: 0;
}

View File

@@ -28,15 +28,29 @@ function AppLoading(): JSX.Element {
<div className="brand">
<img src={signozBrandLogoUrl} alt="SigNoz" className="brand-logo" />
<Typography.Title level={2} className="brand-title">
<Typography
variant="label"
size="large"
weight="bold"
color="main"
as="h2"
textOverflow="wrap"
>
SigNoz
</Typography.Title>
</Typography>
</div>
<div className="brand-tagline">
<Typography.Text>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
OpenTelemetry-Native Logs, Metrics and Traces in a single pane
</Typography.Text>
</Typography>
</div>
<div className="loader" />

View File

@@ -0,0 +1,9 @@
import { Toaster } from '@signozhq/ui/toast';
const PAGE_INSET = { bottom: 'var(--bottom-strip-height, 0px)' };
function AppToaster(): JSX.Element {
return <Toaster position="bottom-right" pageInset={PAGE_INSET} />;
}
export default AppToaster;

View File

@@ -35,7 +35,6 @@
&__error-code {
color: var(--bg-cherry-100);
font-size: 13px;
font-weight: 500;
line-height: 1;
letter-spacing: -0.065px;
}
@@ -43,8 +42,6 @@
&__error-message {
color: var(--bg-cherry-300);
font-size: 13px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.065px;
}
@@ -75,7 +72,6 @@
&__message-item {
color: var(--bg-cherry-300);
font-size: 13px;
font-weight: 400;
line-height: 20px;
letter-spacing: -0.065px;

View File

@@ -45,9 +45,8 @@
}
.auth-footer-text {
font-family: var(--font-family-inter, Inter, sans-serif);
font-family: var(--label-small-400-font-family);
font-size: 11px;
font-weight: 400;
line-height: 1;
color: var(--l2-foreground);
text-align: center;
@@ -57,7 +56,6 @@
display: flex;
align-items: center;
gap: 6px;
text-decoration: none;
transition: opacity 0.2s ease;
&:hover {

View File

@@ -16,7 +16,6 @@
display: flex;
align-items: center;
gap: 4.9px;
text-decoration: none;
}
.auth-header-logo-icon {
@@ -26,7 +25,7 @@
}
.auth-header-logo-text {
font-family: Satoshi, var(--font-family-inter, Inter), sans-serif;
font-family: Satoshi, var(--label-medium-500-font-family), sans-serif;
font-size: 15.4px;
font-weight: 500;
line-height: 17.5px;

View File

@@ -17,8 +17,3 @@
letter-spacing: -0.01em;
color: var(--l1-foreground);
}
.divider {
--divider-color: var(--l1-border);
--divider-margin: 10px 0 16px 0;
}

View File

@@ -44,7 +44,7 @@ function BackHeader({
</Button>
<div className={styles.title}>{title}</div>
</div>
<Divider className={styles.divider} />
<Divider spacing="10px 16px" />
</>
);
}

View File

@@ -1,6 +1,7 @@
import React, { Dispatch, SetStateAction, useState } from 'react';
import { Check, Plus, X } from '@signozhq/icons';
import { Button, Flex } from 'antd';
import { Button } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Pill } from '@signozhq/ui/pill';
import Input from 'components/Input';

View File

@@ -1,6 +1,7 @@
import { useCallback, useMemo, useState } from 'react';
import { Row, Select, Spin } from 'antd';
import { Select, Spin } from 'antd';
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
import Row from 'periscope/components/Row/Row';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import {

View File

@@ -23,7 +23,6 @@
.ant-table {
.ant-table-thead > tr > th {
padding: 12px;
font-weight: 500;
font-size: 12px;
line-height: 18px;
@@ -31,10 +30,7 @@
border-bottom: none;
color: var(--l2-foreground);
font-family: Inter;
font-size: 11px;
font-style: normal;
font-weight: 600;
line-height: 18px; /* 163.636% */
letter-spacing: 0.44px;
@@ -45,7 +41,6 @@
.ant-table-cell {
padding: 12px;
font-size: 13px;
line-height: 20px;
color: var(--l1-foreground);
background: var(--l1-background);
@@ -67,12 +62,6 @@
.ant-table-cell:nth-child(n + 3) {
padding-right: 24px;
}
.column-header-right {
text-align: right;
}
.column-header-left {
text-align: left;
}
.ant-table-tbody > tr > td {
border-bottom: none;
}

View File

@@ -6,15 +6,15 @@ import { Loader, Search } from '@signozhq/icons';
import { Color } from '@signozhq/design-tokens';
import {
Button,
Flex,
Input,
InputRef,
Space,
Spin,
TableColumnsType,
TableColumnType,
Tooltip,
} from 'antd';
import Space from 'periscope/components/Space/Space';
import Flex from 'periscope/components/Flex/Flex';
import { Progress } from '@signozhq/ui/progress';
import { Typography } from '@signozhq/ui/typography';
import type { FilterDropdownProps } from 'antd/lib/table/interface';
@@ -40,10 +40,27 @@ const INITIAL_PAGE_SIZE = 20;
const showPaginationItem = (total: number, range: number[]): JSX.Element => (
<>
<Typography.Text className="numbers">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
{range[0]} &#8212; {range[1]}
</Typography.Text>
<Typography.Text className="total"> of {total}</Typography.Text>
</Typography>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
{' '}
of {total}
</Typography>
</>
);
@@ -56,22 +73,15 @@ function ProgressRender(item: string | number): JSX.Element {
const percent = Number(Number(item).toFixed(1));
return (
<div className="progress-container">
<Progress
percent={percent}
strokeLinecap="butt"
showInfo
strokeColor={((): string => {
const cpuPercent = percent;
if (cpuPercent >= 90) {
return Color.BG_SAKURA_500;
<div className="progress-bar">
<Progress
percent={percent}
showInfo
color={
percent >= 90 ? 'highlight-danger' : percent >= 60 ? 'warning' : 'success'
}
if (cpuPercent >= 60) {
return Color.BG_AMBER_500;
}
return Color.BG_FOREST_500;
})()}
className="progress-bar"
/>
/>
</div>
</div>
);
}
@@ -526,7 +536,18 @@ export default function CeleryOverviewTable({
),
}}
locale={{
emptyText: isLoading ? null : <Typography.Text>No data</Typography.Text>,
emptyText: isLoading ? null : (
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
No data
</Typography>
),
}}
scroll={{ x: 'max-content' }}
showSorterTooltip

View File

@@ -24,9 +24,16 @@ function CeleryTaskConfigOptions(): JSX.Element {
return (
<div className="celery-task-filters">
<div className="celery-filters">
<Typography.Text style={{ whiteSpace: 'nowrap' }}>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="visible"
>
Task Name
</Typography.Text>
</Typography>
<Select
data-testid="celery-task-name-select"
placeholder="Task Name"

View File

@@ -49,11 +49,7 @@
.subtitle {
color: var(--l2-foreground);
font-family: Inter;
font-size: 12px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
}
@@ -64,11 +60,6 @@
.footer-text {
color: var(--l2-foreground);
font-family: Inter;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
}
}

View File

@@ -65,15 +65,38 @@ export default function CeleryTaskDetail({
width="45%"
title={
<div>
<Typography.Text className="title">{`Details - ${taskData.entity}`}</Typography.Text>
<Typography
variant="label"
size="large"
weight="bold"
color="main"
as="span"
textOverflow="wrap"
>{`Details - ${taskData.entity}`}</Typography>
<div>
<Typography.Text className="subtitle">
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
{`${formatTimestamp(startTime)} ${
endTime ? `- ${formatTimestamp(endTime)}` : ''
}`}
</Typography.Text>
<Divider type="vertical" />
<Typography.Text className="subtitle">{taskData.value}</Typography.Text>
</Typography>
<Divider orientation="vertical" />
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
{taskData.value}
</Typography>
</div>
</div>
}
@@ -88,7 +111,14 @@ export default function CeleryTaskDetail({
destroyOnClose
closeIcon={<X size={16} style={{ marginTop: Spacing.MARGIN_1 }} />}
footer={
<Typography.Text className="footer-text">{`Total Task: ${totalTask}`}</Typography.Text>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>{`Total Task: ${totalTask}`}</Typography>
}
>
<CeleryTaskGraph

View File

@@ -7,11 +7,11 @@ import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ViewMenuAction } from 'container/WidgetCard/config';
import { ENTITY_VERSION_V5 } from 'constants/app';
import GridCard from 'container/WidgetCard/Card';
import { Card } from 'container/WidgetCard/styles';
import { useIsDarkMode } from 'hooks/useDarkMode';
import useUrlQuery from 'hooks/useUrlQuery';
import { isEmpty } from 'lodash-es';
import { getStartAndEndTimesInMilliseconds } from 'pages/MessagingQueues/MessagingQueuesUtils';
import { UpdateTimeInterval } from 'store/actions';
import { AppState } from 'store/reducers';
@@ -33,6 +33,7 @@ import {
celerySlowestTasksTableWidgetData,
celerySuccessStateWidgetData,
celerySuccessTasksTableWidgetData,
getClickedSeries,
} from './CeleryTaskGraphUtils';
import {
CeleryTaskState,
@@ -142,24 +143,19 @@ function CeleryTaskBar({
data?: {
[key: string]: string;
},
queryData?: { inFocusOrNot: boolean },
): void => {
const clickedSeries = getClickedSeries(data, queryData);
if (!clickedSeries) {
return;
}
const { start, end } = getStartAndEndTimesInMilliseconds(xValue);
// Extract entity and value from data
const [firstDataPoint] = Object.entries(data || {});
const [entity, value] = (firstDataPoint || ([] as unknown)) as [
string,
string,
];
if (!isEmpty(entity) || !isEmpty(value)) {
onClick?.({
entity,
value,
timeRange: [start, end],
widgetData,
});
}
onClick?.({
...clickedSeries,
timeRange: [start, end],
widgetData,
});
};
const { getCustomSeries } = useGetGraphCustomSeries({
@@ -183,10 +179,11 @@ function CeleryTaskBar({
{barState === CeleryTaskState.All && (
<GridCard
widget={celeryAllStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onGraphClick(
celerySlowestTasksTableWidgetData,
xValue,
@@ -194,6 +191,7 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}
@@ -203,10 +201,11 @@ function CeleryTaskBar({
{barState === CeleryTaskState.Failed && (
<GridCard
widget={celeryFailedStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onGraphClick(
celeryFailedTasksTableWidgetData,
xValue,
@@ -214,6 +213,7 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}
@@ -222,10 +222,11 @@ function CeleryTaskBar({
{barState === CeleryTaskState.Retry && (
<GridCard
widget={celeryRetryStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onGraphClick(
celeryRetryTasksTableWidgetData,
xValue,
@@ -233,6 +234,7 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}
@@ -241,10 +243,11 @@ function CeleryTaskBar({
{barState === CeleryTaskState.Successful && (
<GridCard
widget={celerySuccessStateFilteredData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
isQueryEnabled={queryEnabled}
onClickHandler={(xValue, yValue, mouseX, mouseY, data): void =>
onClickHandler={(xValue, yValue, mouseX, mouseY, data, queryData): void =>
onGraphClick(
celerySuccessTasksTableWidgetData,
xValue,
@@ -252,6 +255,7 @@ function CeleryTaskBar({
mouseX,
mouseY,
data,
queryData,
)
}
customSeries={getCustomSeries}

View File

@@ -48,15 +48,11 @@
}
.worker-count-text-container {
--typography-font-size: 2.5vw;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
.celery-task-graph-worker-count-text {
font-size: 2.5vw;
text-align: center;
}
}
.worker-count-header {
@@ -148,14 +144,12 @@
.configure-option-Info-text {
color: var(--l2-foreground);
font-size: 12px;
font-weight: 400;
}
}
.row-panel {
border-radius: 4px;
background: color-mix(in srgb, var(--card) 40%, transparent);
background: color-mix(in srgb, var(--surface-2) 40%, transparent);
padding: 8px;
display: flex;
gap: 6px;
@@ -217,7 +211,6 @@
}
&__label {
font-family: 'Inter';
font-size: 14px;
color: var(--l2-foreground);
line-height: 20px;
@@ -225,7 +218,7 @@
}
&__value {
font-family: 'Geist Mono';
font-family: var(--code-base-400-font-family);
font-size: 24px;
color: var(--l1-foreground);
line-height: 32px;

View File

@@ -1,7 +1,7 @@
import { useCallback, useMemo } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch } from 'react-redux';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { QueryParams } from 'constants/query';
@@ -22,7 +22,10 @@ import {
applyCeleryFilterOnWidgetData,
getFiltersFromQueryParams,
} from '../CeleryUtils';
import { celeryTimeSeriesTablesWidgetData } from './CeleryTaskGraphUtils';
import {
celeryTimeSeriesTablesWidgetData,
getClickedSeries,
} from './CeleryTaskGraphUtils';
function CeleryTaskGraph({
widgetData,
@@ -102,13 +105,21 @@ function CeleryTaskGraph({
widget={applyCeleryTaskFilter ? updatedWidgetData : widgetData}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={(xValue, _yValue, _mouseX, _mouseY, data): void => {
onClickHandler={(
xValue,
_yValue,
_mouseX,
_mouseY,
data,
queryData,
): void => {
const clickedSeries = getClickedSeries(data, queryData);
if (!clickedSeries) {
return;
}
const { entity, value } = clickedSeries;
const { start, end } = getStartAndEndTimesInMilliseconds(xValue);
// Extract entity and value from data
const [firstDataPoint] = Object.entries(data || {});
const [entity, value] = firstDataPoint || [];
const widgetData = celeryTimeSeriesTablesWidgetData(
entity,
value,
@@ -126,7 +137,7 @@ function CeleryTaskGraph({
isQueryEnabled={queryEnabled}
openTracesButton={openTracesButton}
onOpenTraceBtnClick={onOpenTraceBtnClick}
version={ENTITY_VERSION_V4}
version={ENTITY_VERSION_V5}
customErrorMessage={customErrorMessage}
start={start}
end={end}

View File

@@ -104,9 +104,16 @@ export default function CeleryTaskGraphGrid({
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<div className="row-panel">
<div className="row-panel-section">
<Typography.Text className="section-title">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
Flower Metrics
</Typography.Text>
</Typography>
{collapsedSections.metricBasedGraphs ? (
<ChevronDown
size={14}
@@ -137,17 +144,31 @@ export default function CeleryTaskGraphGrid({
/>
<Card className="celery-task-graph-worker-count">
<div className="worker-count-header">
<Typography.Text className="worker-count-header-text">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
textOverflow="wrap"
>
Worker Online
</Typography.Text>
</Typography>
</div>
<div className="worker-count-text-container">
<Typography.Text
className="celery-task-graph-worker-count-text"
data-testid="celery-worker-count"
<Typography
variant="paragraph"
size="base"
weight="regular"
color="inherit"
as="span"
display="inline-block"
align="center"
textOverflow="wrap"
testId="celery-worker-count"
>
{workerCount ?? '-'}
</Typography.Text>
</Typography>
</div>
</Card>
</div>
@@ -158,9 +179,16 @@ export default function CeleryTaskGraphGrid({
<CardContainer className="row-card" isDarkMode={isDarkMode}>
<div className="row-panel">
<div className="row-panel-section">
<Typography.Text className="section-title">
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
Span Based Stats
</Typography.Text>
</Typography>
{collapsedSections.traceBasedGraphs ? (
<ChevronDown
size={14}
@@ -179,9 +207,16 @@ export default function CeleryTaskGraphGrid({
</CardContainer>
<div className="configure-option-Info">
{configureOptionComponent}
<Typography.Text className="configure-option-Info-text">
<Typography
variant="paragraph"
size="small"
weight="regular"
color="secondary"
as="span"
textOverflow="wrap"
>
Click on a graph co-ordinate to see more details
</Typography.Text>
</Typography>
</div>
</div>
{!collapsedSections.traceBasedGraphs && (

View File

@@ -9,9 +9,11 @@ import {
} from 'api/generated/services/sigNoz.schemas';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { getWidgetQueryBuilder } from 'container/MetricsApplication/MetricsApplication.factory';
import { getFiltersFromKeyValue } from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
import { getWidgetQuery } from 'pages/MessagingQueues/MQDetails/MetricPage/MetricPageUtil';
import { Widgets } from 'types/api/widgets/widget';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { TagFilterItem } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import { v4 as uuidv4 } from 'uuid';
@@ -40,6 +42,29 @@ export const getStepInterval = (startTime: number, endTime: number): number => {
return 54000; // More than a week (use monthly interval)
};
// v5 returns spans without the group-by key as an empty-label series.
const groupByKeyExists = (key: string): TagFilterItem =>
getFiltersFromKeyValue(key, '', 'tag', 'exists');
const latencyExpression = (type: string): string =>
`${type || 'p99'}(duration_nano)`;
// Without a hovered series, the click data holds only `clickedTimestamp`.
export const getClickedSeries = (
data?: Record<string, string>,
queryData?: { inFocusOrNot: boolean },
): { entity: string; value: string } | undefined => {
const series = Object.entries(data || {}).find(
([key]) => key !== 'clickedTimestamp',
);
if (!queryData?.inFocusOrNot || !series) {
return undefined;
}
const [entity, value] = series;
return { entity, value };
};
// State Graphs
export const celeryAllStateWidgetData = (
startTime: number,
@@ -56,11 +81,12 @@ export const celeryAllStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [],
items: [groupByKeyExists('celery.state')],
op: 'AND',
},
functions: [],
@@ -108,11 +134,13 @@ export const celeryRetryStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -168,11 +196,13 @@ export const celeryFailedStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -228,11 +258,13 @@ export const celerySuccessStateWidgetData = (
type: '',
},
aggregateOperator: 'count',
aggregations: [{ expression: 'count()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -287,11 +319,12 @@ export const celeryTasksByWorkerWidgetData = (
type: '',
},
aggregateOperator: 'rate',
aggregations: [{ expression: 'rate()' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [],
items: [groupByKeyExists('celery.hostname')],
op: 'AND',
},
functions: [],
@@ -331,8 +364,9 @@ export const celeryErrorByWorkerWidgetData = (
dataSource: DataSource.TRACES,
queryName: 'A',
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
aggregateAttribute: {
dataType: 'string',
dataType: DataTypes.String,
id: 'span_id--string----true',
key: 'span_id',
type: '',
@@ -342,6 +376,7 @@ export const celeryErrorByWorkerWidgetData = (
functions: [],
filters: {
items: [
groupByKeyExists('celery.hostname'),
{
id: uuidv4(),
key: {
@@ -374,11 +409,12 @@ export const celeryErrorByWorkerWidgetData = (
reduceTo: ReduceOperators.AVG,
},
{
dataSource: 'traces',
dataSource: DataSource.TRACES,
queryName: 'B',
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
aggregateAttribute: {
dataType: 'string',
dataType: DataTypes.String,
id: 'span_id--string----true',
key: 'span_id',
type: '',
@@ -387,7 +423,7 @@ export const celeryErrorByWorkerWidgetData = (
spaceAggregation: 'sum',
functions: [],
filters: {
items: [],
items: [groupByKeyExists('celery.hostname')],
op: 'AND',
},
expression: 'B',
@@ -407,12 +443,14 @@ export const celeryErrorByWorkerWidgetData = (
legend: '',
reduceTo: ReduceOperators.AVG,
},
],
queryFormulas: [
{
queryName: 'F1',
expression: '(A/B)*100',
disabled: false,
legend: '{{celery.hostname}}',
} as any,
},
],
yAxisUnit: 'percent',
}),
@@ -435,11 +473,12 @@ export const celeryLatencyByWorkerWidgetData = (
type: '',
},
aggregateOperator: 'p99',
aggregations: [{ expression: 'p99(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [],
items: [groupByKeyExists('celery.hostname')],
op: 'AND',
},
functions: [],
@@ -532,11 +571,12 @@ export const celeryTaskLatencyWidgetData = (
type: '',
},
aggregateOperator: type || 'p99',
aggregations: [{ expression: latencyExpression(type) }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [],
items: [groupByKeyExists('celery.task_name')],
op: 'AND',
},
functions: [],
@@ -553,7 +593,7 @@ export const celeryTaskLatencyWidgetData = (
limit: null,
orderBy: [
{
columnName: '#SIGNOZ_VALUE',
columnName: latencyExpression(type),
order: 'asc',
},
],
@@ -583,11 +623,12 @@ export const celerySlowestTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [],
items: [groupByKeyExists('celery.task_name')],
op: 'AND',
},
functions: [],
@@ -604,7 +645,7 @@ export const celerySlowestTasksTableWidgetData = getWidgetQueryBuilder(
limit: 10,
orderBy: [
{
columnName: '#SIGNOZ_VALUE',
columnName: 'avg(duration_nano)',
order: 'desc',
},
],
@@ -633,11 +674,13 @@ export const celeryRetryTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -666,7 +709,7 @@ export const celeryRetryTasksTableWidgetData = getWidgetQueryBuilder(
limit: 10,
orderBy: [
{
columnName: '#SIGNOZ_VALUE',
columnName: 'avg(duration_nano)',
order: 'desc',
},
],
@@ -696,11 +739,13 @@ export const celeryFailedTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -729,7 +774,7 @@ export const celeryFailedTasksTableWidgetData = getWidgetQueryBuilder(
limit: null,
orderBy: [
{
columnName: '#SIGNOZ_VALUE',
columnName: 'avg(duration_nano)',
order: 'desc',
},
],
@@ -757,11 +802,13 @@ export const celerySuccessTasksTableWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -790,7 +837,7 @@ export const celerySuccessTasksTableWidgetData = getWidgetQueryBuilder(
limit: null,
orderBy: [
{
columnName: '#SIGNOZ_VALUE',
columnName: 'avg(duration_nano)',
order: 'desc',
},
],
@@ -824,11 +871,13 @@ export const celeryTimeSeriesTablesWidgetData = (
type: '',
},
aggregateOperator: 'avg',
aggregations: [{ expression: 'avg(duration_nano)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
filters: {
items: [
groupByKeyExists('celery.task_name'),
{
id: uuidv4(),
key: {
@@ -882,6 +931,7 @@ export const celeryAllStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
@@ -919,6 +969,7 @@ export const celerySuccessStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
@@ -968,6 +1019,7 @@ export const celeryFailedStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',
@@ -1017,6 +1069,7 @@ export const celeryRetryStateCountWidgetData = getWidgetQueryBuilder(
type: '',
},
aggregateOperator: 'count_distinct',
aggregations: [{ expression: 'count_distinct(span_id)' }],
dataSource: DataSource.TRACES,
disabled: false,
expression: 'A',

View File

@@ -1,13 +1,15 @@
import { useCallback, useMemo, useState } from 'react';
// eslint-disable-next-line no-restricted-imports
import { useDispatch, useSelector } from 'react-redux';
import { Col, Row } from 'antd';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { ViewMenuAction } from 'container/WidgetCard/config';
import { ENTITY_VERSION_V5 } from 'constants/app';
import GridCard from 'container/WidgetCard/Card';
import { Card } from 'container/WidgetCard/styles';
import { Button } from 'container/MetricsApplication/Tabs/styles';
@@ -27,7 +29,10 @@ import {
getFiltersFromQueryParams,
} from '../CeleryUtils';
import { useNavigateToExplorer } from '../useNavigateToExplorer';
import { celeryTaskLatencyWidgetData } from './CeleryTaskGraphUtils';
import {
celeryTaskLatencyWidgetData,
getClickedSeries,
} from './CeleryTaskGraphUtils';
import './CeleryTaskGraph.style.scss';
@@ -128,13 +133,12 @@ function CeleryTaskLatencyGraph({
const onGraphClick = useCallback(
(type: string): OnClickPluginOpts['onClick'] =>
(xValue, yValue, mouseX, mouseY, data): Promise<void> => {
const [firstDataPoint] = Object.entries(data || {});
const [entity, value] = firstDataPoint;
setEntityData({
entity,
value,
});
(xValue, yValue, mouseX, mouseY, data, queryData): Promise<void> => {
const clickedSeries = getClickedSeries(data, queryData);
if (!clickedSeries) {
return Promise.resolve();
}
setEntityData(clickedSeries);
return onGraphClickHandler(xValue, yValue, mouseX, mouseY, type);
},
@@ -198,6 +202,7 @@ function CeleryTaskLatencyGraph({
</Button>
<GridCard
widget={updatedWidgetData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={onGraphClick('Celery_p99_latency')}
@@ -219,6 +224,7 @@ function CeleryTaskLatencyGraph({
</Button>
<GridCard
widget={updatedWidgetData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={onGraphClick('Celery_p95_latency')}
@@ -239,6 +245,7 @@ function CeleryTaskLatencyGraph({
</Button>
<GridCard
widget={updatedWidgetData}
version={ENTITY_VERSION_V5}
headerMenuList={[...ViewMenuAction]}
onDragSelect={onDragSelect}
onClickHandler={onGraphClick('Celery_p90_latency')}

View File

@@ -1,5 +1,6 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
import { Col, Row } from 'antd';
import Col from 'periscope/components/Col/Col';
import Row from 'periscope/components/Row/Row';
import logEvent from 'api/common/logEvent';
import { QueryParams } from 'constants/query';
import useUrlQuery from 'hooks/useUrlQuery';
@@ -89,7 +90,10 @@ function CeleryTaskStateGraphConfig({
>
<div className="celery-task-states__label-wrapper">
<div className="celery-task-states__label">{tab.label}</div>
<div className="celery-task-states__value">
<div
className="celery-task-states__value"
data-testid={`celery-state-value-${tab.key}`}
>
{isLoading
? '-'
: isError

View File

@@ -61,7 +61,13 @@ describe('CeleryTaskGraphGrid worker count', () => {
);
const { minTime, maxTime } = store.getState().globalTime;
expect(requests).toStrictEqual([
expect(
requests.filter((request) =>
request.compositeQuery?.queries?.some(
(query) => (query.spec as { signal?: string }).signal === 'metrics',
),
),
).toStrictEqual([
{
schemaVersion: 'v1',
start: Math.floor(minTime / 1e6),

View File

@@ -0,0 +1,92 @@
import {
Querybuildertypesv5ColumnTypeDTO,
Querybuildertypesv5QueryEnvelopeBuilderDTOType,
type Querybuildertypesv5QueryRangeRequestDTO,
Querybuildertypesv5RequestTypeDTO,
type QueryRangeV5200,
} from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { render, screen, waitFor } from 'tests/test-utils';
import {
CeleryTaskState,
CeleryTaskStateGraphConfig,
} from '../CeleryTaskStateGraphConfig';
const COUNT_PER_STATE: Record<string, number> = {
FAILURE: 12,
RETRY: 30,
SUCCESS: 958,
};
const stateOf = (body: Querybuildertypesv5QueryRangeRequestDTO): string => {
const [envelope] = body.compositeQuery?.queries ?? [];
const expression =
envelope?.type ===
Querybuildertypesv5QueryEnvelopeBuilderDTOType.builder_query
? (envelope.spec?.filter?.expression ?? '')
: '';
return /celery\.state = '(\w+)'/.exec(expression)?.[1] ?? '';
};
const scalarResponse = (value: number): QueryRangeV5200 => ({
status: 'success',
data: {
type: Querybuildertypesv5RequestTypeDTO.scalar,
data: {
results: [
{
columns: [
{
name: '__result_0',
queryName: 'A',
aggregationIndex: 0,
columnType: Querybuildertypesv5ColumnTypeDTO.aggregation,
},
],
data: [[value]],
},
],
},
},
});
describe('CeleryTaskStateGraphConfig', () => {
beforeEach(() => {
server.use(
rest.post('*/api/v5/query_range', async (req, res, ctx) => {
const body: Querybuildertypesv5QueryRangeRequestDTO = await req.json();
return res(
ctx.status(200),
ctx.json(scalarResponse(COUNT_PER_STATE[stateOf(body)] ?? 1000)),
);
}),
);
});
it('shows the v5 count for each task state', async () => {
render(
<CeleryTaskStateGraphConfig
barState={CeleryTaskState.All}
setBarState={jest.fn()}
/>,
);
await waitFor(() =>
expect(screen.getByTestId('celery-state-value-all')).toHaveTextContent(
'1000',
),
);
expect(screen.getByTestId('celery-state-value-failed')).toHaveTextContent(
'12',
);
expect(screen.getByTestId('celery-state-value-retry')).toHaveTextContent(
'30',
);
expect(screen.getByTestId('celery-state-value-successful')).toHaveTextContent(
'958',
);
});
});

View File

@@ -0,0 +1,136 @@
import { prepareQueryRangePayloadV5 } from 'api/v5/queryRange/prepareQueryRangePayloadV5';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { celeryOverviewErrorRateGraphData } from 'pages/Celery/CeleryOverview/CeleryOverviewGraphUtils';
import { Widgets } from 'types/api/widgets/widget';
import {
celeryAllStateWidgetData,
celeryErrorByWorkerWidgetData,
celeryLatencyByWorkerWidgetData,
celerySlowestTasksTableWidgetData,
celeryTaskLatencyWidgetData,
celeryTasksByWorkerWidgetData,
} from '../CeleryTaskGraphUtils';
const START = 1_700_000_000_000_000_000;
const END = START + 3_600_000_000_000;
const v5Queries = (
widget: Widgets,
): ReturnType<
typeof prepareQueryRangePayloadV5
>['queryPayload']['compositeQuery']['queries'] =>
prepareQueryRangePayloadV5({
query: widget.query,
graphType: PANEL_TYPES.TIME_SERIES,
selectedTime: 'GLOBAL_TIME',
start: 1_700_000_000,
end: 1_700_003_600,
}).queryPayload.compositeQuery.queries;
const builderQuery = (
name: string,
expression: string,
): ReturnType<typeof expect.objectContaining> =>
expect.objectContaining({
type: 'builder_query',
spec: expect.objectContaining({
name,
signal: 'traces',
aggregations: [{ expression }],
}),
});
const formula = (
name: string,
expression: string,
): ReturnType<typeof expect.objectContaining> =>
expect.objectContaining({
type: 'builder_formula',
spec: expect.objectContaining({ name, expression }),
});
describe('Celery widgets on query_range v5', () => {
it.each([
['tasks by worker', celeryTasksByWorkerWidgetData(START, END), 'rate()'],
[
'latency by worker',
celeryLatencyByWorkerWidgetData(START, END),
'p99(duration_nano)',
],
[
'task latency tab',
celeryTaskLatencyWidgetData('p95', START, END),
'p95(duration_nano)',
],
])('%s sends its own aggregation', (_name, widget, expression) => {
expect(v5Queries(widget)).toStrictEqual([builderQuery('A', expression)]);
});
it.each([
[
'task latency tab',
celeryTaskLatencyWidgetData('p95', START, END),
'p95(duration_nano)',
'asc',
],
[
'slowest tasks table',
celerySlowestTasksTableWidgetData,
'avg(duration_nano)',
'desc',
],
])('%s orders by its aggregation', (_name, widget, name, direction) => {
expect(v5Queries(widget)).toStrictEqual([
expect.objectContaining({
spec: expect.objectContaining({
order: [{ key: { name }, direction }],
}),
}),
]);
});
it.each([
[
'all states bar',
celeryAllStateWidgetData(START, END),
'celery.state exists',
],
[
'tasks by worker',
celeryTasksByWorkerWidgetData(START, END),
'celery.hostname exists',
],
[
'task latency tab',
celeryTaskLatencyWidgetData('p95', START, END),
'celery.task_name exists',
],
])('%s drops spans without its group-by key', (_name, widget, expression) => {
expect(v5Queries(widget)).toStrictEqual([
expect.objectContaining({
spec: expect.objectContaining({ filter: { expression } }),
}),
]);
});
it('error % by worker sends its formula as a formula', () => {
expect(v5Queries(celeryErrorByWorkerWidgetData(START, END))).toStrictEqual([
builderQuery('A', 'count_distinct(span_id)'),
builderQuery('B', 'count_distinct(span_id)'),
formula('F1', '(A/B)*100'),
]);
});
it('overview error rate sends both formulas as formulas', () => {
expect(v5Queries(celeryOverviewErrorRateGraphData(START, END))).toStrictEqual(
[
builderQuery('A', 'count_distinct(span_id)'),
builderQuery('B', 'count_distinct(span_id)'),
builderQuery('C', 'count_distinct(span_id)'),
formula('F1', '(A/C)*100'),
formula('F2', '(B/C)*100'),
],
);
});
});

View File

@@ -0,0 +1,27 @@
import { getClickedSeries } from '../CeleryTaskGraphUtils';
const focused = { queryName: 'A', inFocusOrNot: true };
const unfocused = { queryName: '', inFocusOrNot: false };
describe('getClickedSeries', () => {
it('returns the clicked series label', () => {
expect(
getClickedSeries(
{ 'celery.state': 'RETRY', clickedTimestamp: '1700000000' },
focused,
),
).toStrictEqual({ entity: 'celery.state', value: 'RETRY' });
});
it('ignores a click outside any series', () => {
expect(
getClickedSeries({ clickedTimestamp: '1700000000' }, unfocused),
).toBeUndefined();
});
it('ignores a series that has no label', () => {
expect(
getClickedSeries({ clickedTimestamp: '1700000000' }, focused),
).toBeUndefined();
});
});

View File

@@ -2,10 +2,13 @@ import { useCallback } from 'react';
import { useQueries } from 'react-query';
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { ENTITY_VERSION_V4 } from 'constants/app';
import { ENTITY_VERSION_V5 } from 'constants/app';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
import { getQueryPayloadFromWidgetsData } from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
import {
getQueryPayloadFromWidgetsData,
getValueFromScalarResponse,
} from 'pages/Celery/CeleryOverview/CeleryOverviewUtils';
import { AppState } from 'store/reducers';
import { SuccessResponse } from 'types/api';
import { Widgets } from 'types/api/widgets/widget';
@@ -39,9 +42,9 @@ export const useGetValueFromWidget = (
const queries = useQueries(
queryPayloads().map((payload) => ({
queryKey: [...queryKey, payload, ENTITY_VERSION_V4],
queryKey: [...queryKey, payload, ENTITY_VERSION_V5],
queryFn: (): Promise<SuccessResponse<MetricRangePayloadProps>> =>
GetMetricQueryRange(payload, ENTITY_VERSION_V4),
GetMetricQueryRange(payload, ENTITY_VERSION_V5),
enabled: !!payload,
})),
);
@@ -57,11 +60,7 @@ export const useGetValueFromWidget = (
return 'Error';
}
const value = parseFloat(
query.data?.payload?.data?.newResult?.data?.result?.[0]?.series?.[0]
?.values?.[0]?.value || 'NaN',
);
return Number.isNaN(value) ? 'NaN' : value.toFixed(2);
return getValueFromScalarResponse(query.data);
});
return { values, isLoading, isError };

View File

@@ -11,9 +11,7 @@
justify-content: center;
}
&__label {
font-family: 'Geist Mono';
font-size: 12px;
line-height: normal;
font-family: var(--code-base-400-font-family);
}
&--positive {
.change-percentage-pill {

View File

@@ -1,7 +1,8 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button, Flex, Modal } from 'antd';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';
@@ -97,6 +98,10 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
}
};
// TODO: antd stacks at 1000, under `@signozhq/ui` dialogs (1001). It opens on
// its own a second after load, so a dialog opened from a deep link
// (`?add-key`, `?invite=true`) covers it. Moving to the `@signozhq/ui` Dialog
// fixes it.
return (
<Modal
className={cx('changelog-modal')}

View File

@@ -0,0 +1,29 @@
import type { ComponentProps } from 'react';
import type { Meta, StoryObj } from '@storybook/react-vite';
import { fn } from 'storybook/test';
import type { GlobalMockArgs } from '@/storybook/globals';
import ChangelogModal from '../ChangelogModal';
import { changelog } from './__story_mockdata__/changelog';
type ChangelogModalArgs = ComponentProps<typeof ChangelogModal> &
GlobalMockArgs;
const meta = {
title: 'Components/Changelog Modal',
component: ChangelogModal,
args: { changelog, onClose: fn() },
} satisfies Meta<ChangelogModalArgs>;
export default meta;
type Story = StoryObj<ChangelogModalArgs>;
/** A cloud workspace: no upgrade actions, since cloud updates itself. */
export const Default: Story = {};
/** A self-hosted workspace, offered Skip for now and Update my workspace. */
export const SelfHosted: Story = {
args: { license: 'enterprise' },
};

View File

@@ -0,0 +1,65 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
const PUBLISHED_AT = '2026-08-12T09:00:00.000Z';
const feature = (
id: number,
title: string,
description: string,
): ChangelogSchema['features'][number] => ({
id,
documentId: `feature-${id}`,
title,
sort_order: id,
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
description,
deployment_type: DeploymentType.ALL,
// Media stays null so no story reaches out to the CMS for an image.
media: null,
});
export const changelog: ChangelogSchema = {
id: 1,
documentId: 'changelog-v0-99-0',
version: 'v0.99.0',
release_date: '2026-08-12',
createdAt: PUBLISHED_AT,
updatedAt: PUBLISHED_AT,
publishedAt: PUBLISHED_AT,
features: [
feature(
1,
'Metrics explorer',
'Browse every metric you send, inspect its labels and turn it into a panel without writing a query.\n\n- Search metrics by name, type or unit\n- See cardinality per label before you group by it\n- Open any metric straight in the query builder\n\nRead more in the [metrics explorer docs](https://signoz.io/docs/metrics-management/metrics-explorer/).',
),
feature(
2,
'Trace funnels',
'Measure conversion and drop-off across a multi-service request path. Define each step as a span filter, then compare the latency and error rate between any two steps.',
),
feature(
3,
'Saved views for logs',
'Save a logs query with its columns and time range, share it with your team and pin the ones you open most.',
),
feature(
4,
'Alert history',
'Every alert now keeps a timeline of its state changes, with the value that crossed the threshold and the labels it fired for.',
),
],
bug_fixes:
'- Fixed dashboard variables losing their selection on refresh.\n- Fixed alert history pagination skipping a page.\n- Fixed the logs list jumping to the top after a live tail update.',
maintenance:
'- Upgraded the query service to Go 1.24.\n- Reduced the ClickHouse memory used by trace aggregation queries.',
};

View File

@@ -17,10 +17,6 @@
color: var(--l2-foreground);
/* Bifrost (Ancient)/Content/sm */
font-family: Inter;
font-size: 13px;
font-style: normal;
font-weight: 400;
line-height: 20px; /* 142.857% */
letter-spacing: -0.07px;

View File

@@ -17,13 +17,13 @@
pre {
color: var(--l2-foreground) !important;
font-family: 'Geist Mono' !important;
font-family: var(--code-small-400-font-family) !important;
font-size: 12px !important;
}
code {
color: var(--l1-foreground) !important;
font-family: 'Geist Mono' !important;
font-family: var(--code-small-400-font-family) !important;
font-size: 12px !important;
}
}

View File

@@ -1,36 +1,3 @@
.create-sa-modal {
max-width: 530px;
background: var(--popover);
border: 1px solid var(--secondary);
border-radius: 4px;
box-shadow: 0 4px 9px 0 rgba(0, 0, 0, 0.04);
[data-slot='dialog-header'] {
padding: var(--padding-4);
border-bottom: 1px solid var(--secondary);
flex-shrink: 0;
background: transparent;
margin: 0;
}
[data-slot='dialog-title'] {
font-size: var(--label-base-400-font-size);
font-weight: var(--label-base-400-font-weight);
line-height: var(--label-base-400-line-height);
letter-spacing: -0.065px;
color: var(--l1-foreground);
margin: 0;
}
[data-slot='dialog-description'] {
padding: 0;
.create-sa-modal__content {
padding: var(--padding-4);
}
}
}
.create-sa-form {
display: flex;
flex-direction: column;
@@ -43,32 +10,11 @@
margin-bottom: var(--spacing-4);
> label {
font-size: var(--paragraph-base-400-font-size);
font-weight: var(--paragraph-base-400-font-weight);
color: var(--foreground);
letter-spacing: -0.07px;
}
}
&__input {
height: 32px;
color: var(--l1-foreground);
background-color: var(--l2-background);
border-color: var(--l1-border);
font-size: var(--paragraph-base-400-font-size);
border-radius: 2px;
width: 100%;
&::placeholder {
color: var(--l3-foreground);
}
&:focus {
border-color: var(--primary);
box-shadow: none;
}
}
&__error {
font-size: var(--paragraph-small-400-font-size);
color: var(--destructive);
@@ -77,22 +23,7 @@
}
&__helper {
font-size: var(--paragraph-small-400-font-size);
color: var(--l3-foreground);
margin: calc(var(--spacing-2) * -1) 0 var(--spacing-4) 0;
line-height: var(--paragraph-small-400-line-height);
}
}
.create-sa-modal__footer {
display: flex;
flex-direction: row;
align-items: center;
justify-content: flex-end;
padding: 0 var(--padding-4);
height: 56px;
min-height: 56px;
border-top: 1px solid var(--secondary);
gap: var(--spacing-4);
flex-shrink: 0;
}

View File

@@ -5,9 +5,9 @@ import { Button } from '@signozhq/ui/button';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import { SACreatePermission } from 'lib/authz/hooks/useAuthZ/permissions/service-account.permissions';
import { DialogFooter, DialogWrapper } from '@signozhq/ui/dialog';
import { Dialog } from '@signozhq/ui/dialog';
import { Input } from '@signozhq/ui/input';
import { toast } from '@signozhq/ui/sonner';
import { toast } from '@signozhq/ui/toast';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import {
invalidateListServiceAccounts,
@@ -35,7 +35,7 @@ function CreateServiceAccountModal(): JSX.Element {
);
const [, setSelectedAccountId] = useQueryState(SA_QUERY_PARAMS.ACCOUNT);
const { showErrorModal, isErrorModalVisible } = useErrorModal();
const { showErrorModal } = useErrorModal();
const {
control,
@@ -82,84 +82,75 @@ function CreateServiceAccountModal(): JSX.Element {
}
return (
<DialogWrapper
<Dialog
title="New Service Account"
open={isOpen}
onOpenChange={(open): void => {
if (!open) {
handleClose();
}
}}
showCloseButton
width="narrow"
className="create-sa-modal"
disableOutsideClick={isErrorModalVisible}
onClose={handleClose}
width="base"
testId="create-service-account-modal"
>
<div className="create-sa-modal__content">
<AuthZGuardContent
checks={[SACreatePermission]}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 1 }} />}
>
<form
id="create-sa-form"
className="create-sa-form"
onSubmit={handleSubmit(handleCreate)}
footerSuffix={
<>
<Button
size="md"
type="button"
variant="solid"
color="secondary"
onClick={handleClose}
testId="create-sa-cancel-btn"
prefix={<X size={12} />}
>
<div className="create-sa-form__item">
<label htmlFor="sa-name">Name</label>
<Controller
name="name"
control={control}
rules={{ required: 'Name is required' }}
render={({ field }): JSX.Element => (
<Input
id="sa-name"
placeholder="Enter a name"
className="create-sa-form__input"
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
data-testid="create-sa-name-input"
/>
)}
/>
{errors.name && (
<p className="create-sa-form__error">{errors.name.message}</p>
Cancel
</Button>
<AuthZButton
size="md"
checks={[SACreatePermission]}
type="submit"
form="create-sa-form"
variant="solid"
color="primary"
loading={isSubmitting}
disabled={!isValid}
testId="create-sa-submit-btn"
>
Create Service Account
</AuthZButton>
</>
}
>
<AuthZGuardContent
checks={[SACreatePermission]}
fallbackOnLoading={<Skeleton active paragraph={{ rows: 1 }} />}
>
<form
id="create-sa-form"
className="create-sa-form"
onSubmit={handleSubmit(handleCreate)}
>
<div className="create-sa-form__item">
<label htmlFor="sa-name">Name</label>
<Controller
name="name"
control={control}
rules={{ required: 'Name is required' }}
render={({ field }): JSX.Element => (
<Input
id="sa-name"
placeholder="Enter a name"
value={field.value}
onChange={field.onChange}
onBlur={field.onBlur}
testId="create-sa-name-input"
/>
)}
</div>
</form>
</AuthZGuardContent>
</div>
<DialogFooter className="create-sa-modal__footer">
<Button
size="md"
type="button"
variant="solid"
color="secondary"
onClick={handleClose}
testId="create-sa-cancel-btn"
prefix={<X size={12} />}
>
Cancel
</Button>
<AuthZButton
size="md"
checks={[SACreatePermission]}
type="submit"
form="create-sa-form"
variant="solid"
color="primary"
loading={isSubmitting}
disabled={!isValid}
testId="create-sa-submit-btn"
>
Create Service Account
</AuthZButton>
</DialogFooter>
</DialogWrapper>
/>
{errors.name && (
<p className="create-sa-form__error">{errors.name.message}</p>
)}
</div>
</form>
</AuthZGuardContent>
</Dialog>
);
}

View File

@@ -1,4 +1,4 @@
import { toast } from '@signozhq/ui/sonner';
import { toast } from '@signozhq/ui/toast';
import {
setupAuthzAdmin,
setupAuthzDenyAll,
@@ -10,9 +10,9 @@ import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import CreateServiceAccountModal from '../CreateServiceAccountModal';
jest.mock('@signozhq/ui/sonner', () => ({
...jest.requireActual('@signozhq/ui/sonner'),
toast: { success: jest.fn(), error: jest.fn() },
jest.mock('@signozhq/ui/toast', () => ({
...jest.requireActual('@signozhq/ui/toast'),
toast: { success: jest.fn(), danger: jest.fn() },
}));
const mockToast = jest.mocked(toast);
@@ -23,7 +23,6 @@ jest.mock('providers/ErrorModalProvider', () => ({
...jest.requireActual('providers/ErrorModalProvider'),
useErrorModal: jest.fn(() => ({
showErrorModal,
isErrorModalVisible: false,
})),
}));
@@ -58,7 +57,7 @@ describe('CreateServiceAccountModal', () => {
// The form only renders once the create check resolves, and the name field
// registers its `required` rule on mount, so the empty-form invalid state
// settles a tick later.
await screen.findByTestId('create-sa-name-input');
await screen.findByTestId('create-sa-name-input-field');
await waitFor(() =>
expect(screen.getByTestId('create-sa-submit-btn')).toHaveAttribute(
@@ -72,7 +71,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input');
const nameInput = await screen.findByTestId('create-sa-name-input-field');
const submitBtn = await screen.findByTestId('create-sa-submit-btn');
await user.type(nameInput, 'test');
@@ -90,7 +89,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input');
const nameInput = await screen.findByTestId('create-sa-name-input-field');
await user.type(nameInput, 'Deploy Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -128,7 +127,7 @@ describe('CreateServiceAccountModal', () => {
renderModal();
const nameInput = await screen.findByTestId<HTMLInputElement>(
'create-sa-name-input',
'create-sa-name-input-field',
);
await user.type(nameInput, 'Deploy Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -160,7 +159,7 @@ describe('CreateServiceAccountModal', () => {
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input');
const nameInput = await screen.findByTestId('create-sa-name-input-field');
await user.type(nameInput, 'Dupe Bot');
const submitBtn = screen.getByTestId('create-sa-submit-btn');
@@ -209,7 +208,9 @@ describe('CreateServiceAccountModal', () => {
screen.findByText(/is not authorized to perform/i),
).resolves.toBeInTheDocument();
expect(screen.queryByTestId('create-sa-name-input')).not.toBeInTheDocument();
expect(
screen.queryByTestId('create-sa-name-input-field'),
).not.toBeInTheDocument();
expect(
screen.getByTestId('create-service-account-modal'),
).toBeInTheDocument();
@@ -244,7 +245,7 @@ describe('CreateServiceAccountModal', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderModal();
const nameInput = await screen.findByTestId('create-sa-name-input');
const nameInput = await screen.findByTestId('create-sa-name-input-field');
await user.type(nameInput, 'Bot');
await user.clear(nameInput);

View File

@@ -65,8 +65,6 @@
.valid-format-error {
margin-top: 4px;
color: var(--bg-cherry-400) !important;
font-size: 13px !important;
font-weight: 400 !important;
}
.info-text {
@@ -76,11 +74,6 @@
padding: 4px;
cursor: default;
color: var(--l2-foreground) !important;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: normal;
letter-spacing: 0.14px;
}
.info-text:hover {
@@ -104,15 +97,11 @@
gap: 6px;
.timezone__name {
font-size: 12px;
line-height: 16px;
color: var(--bg-robin-400);
font-weight: 500;
}
.timezone__separator {
font-size: 12px;
line-height: 16px;
color: var(--bg-robin-300);
font-weight: 500;
}
@@ -228,10 +217,6 @@
border-radius: 2px;
background: color-mix(in srgb, var(--bg-robin-200) 4%, transparent);
color: var(--l1-foreground);
font-size: 12px;
font-weight: 400;
line-height: 16px;
letter-spacing: -0.06px;
cursor: pointer;
height: 20px;
width: 20px;

View File

@@ -531,7 +531,7 @@ function CustomTimePicker({
// Use setTimeout to wait for React to update the DOM and make input editable
setTimeout(() => {
const inputElement = inputRef.current?.input;
if (inputElement) {
if (inputElement && !document.activeElement?.closest('.timezone-picker')) {
inputElement.focus();
inputElement.select();
}

View File

@@ -21,7 +21,6 @@ $item-spacing: 8px;
.timezone-picker {
width: 532px;
color: var(--l2-foreground);
font-family: $font-family;
&__search {
@include flex-center;
@@ -34,34 +33,8 @@ $item-spacing: 8px;
@include flex-center;
gap: 6px;
width: -webkit-fill-available;
}
&__input {
@include text-style-base;
width: 100%;
background: transparent;
border: none;
border-radius: 0;
box-shadow: none;
outline: none;
height: auto;
color: var(--l1-foreground);
font-size: 14px;
line-height: 20px;
letter-spacing: -0.07px;
padding: 0;
&:focus,
&:focus-visible,
&:hover {
border: none;
box-shadow: none;
outline: none;
}
&::placeholder {
color: var(--l2-foreground);
}
--input-hover-border-color: transparent;
}
&__esc-key {

View File

@@ -65,7 +65,8 @@ function SearchBar({
/>
<Input
type="text"
className="timezone-picker__input"
variant="unstyled"
noFocusRing
placeholder="Search timezones..."
value={value}
onChange={(e): void => onChange(e.target.value)}

View File

@@ -12,5 +12,4 @@
.name {
color: var(--danger-background);
font-weight: var(--font-weight-medium);
}

View File

@@ -1,7 +1,4 @@
.details-header {
// ghost + secondary missing hover bg token in @signozhq/button
--button-ghost-hover-background: var(--l3-background);
box-sizing: border-box;
display: flex;
align-items: center;
@@ -12,7 +9,6 @@
background: var(--l2-background);
&__title {
font-size: 13px;
font-weight: 500;
color: var(--l1-foreground);
flex: 1;

View File

@@ -1,17 +0,0 @@
.drawer {
overflow: hidden;
border-color: var(--l2-border);
background: var(--l2-background);
box-shadow: -4px 10px 16px 2px var(--l1-shadow);
&:focus,
&:focus-visible {
outline: none;
}
}
.body {
display: flex;
flex-direction: column;
height: 100%;
}

View File

@@ -1,56 +1,46 @@
import { Drawer, DrawerContent } from '@signozhq/ui/drawer';
import cx from 'classnames';
import { AnimatePresence } from 'motion/react';
import styles from './DetailsPanelDrawer.module.scss';
import { ReactNode } from 'react';
import { Drawer } from '@signozhq/ui/drawer';
interface DetailsPanelDrawerProps {
isOpen: boolean;
onClose: () => void;
children: React.ReactNode;
className?: string;
title: string;
children: ReactNode;
headerSuffix?: ReactNode;
loading?: boolean;
testId?: string;
}
function DetailsPanelDrawer({
isOpen,
onClose,
title,
children,
className,
headerSuffix,
loading,
testId,
}: DetailsPanelDrawerProps): JSX.Element {
return (
<Drawer
type="inspector"
stack="overlay"
open={isOpen}
onOpenChange={(open): void => {
if (!open) {
onClose();
}
}}
modal={false}
onClose={onClose}
title={title}
width="extra-wide"
closePosition="start"
headerSuffix={headerSuffix}
loading={loading}
testId={testId}
>
<AnimatePresence>
{isOpen && (
<DrawerContent
forceMount
direction="right"
width="extra-wide"
showOverlay={false}
// Outside presses are left to the page, which knows what counts as inside.
onInteractOutside={(e): void => e.preventDefault()}
className={cx(styles.drawer, className)}
testId={testId}
>
<div className={styles.body}>{children}</div>
</DrawerContent>
)}
</AnimatePresence>
{children}
</Drawer>
);
}
DetailsPanelDrawer.defaultProps = {
className: undefined,
headerSuffix: undefined,
loading: false,
testId: undefined,
};

View File

@@ -0,0 +1,28 @@
.dotGrid {
position: relative;
}
.canvas {
position: absolute;
inset: 0;
display: block;
width: 100%;
height: 100%;
// Read by the snake as its colour on the light page.
color: var(--l1-foreground);
}
// The Snake score line, faint in the grid's bottom-left corner.
.label {
position: absolute;
left: var(--spacing-6);
bottom: var(--spacing-1);
font-family: var(--code-small-400-font-family);
font-size: var(--paragraph-small-400-font-size);
letter-spacing: 0.34em;
text-transform: uppercase;
white-space: nowrap;
color: var(--l3-foreground);
pointer-events: none;
user-select: none;
}

View File

@@ -0,0 +1,35 @@
import { useRef } from 'react';
import cx from 'classnames';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useDotGrid } from './useDotGrid';
import styles from './DotGrid.module.scss';
interface DotGridProps {
/** Sizes and places the grid; it fills whatever box it gets. */
className?: string;
/** Called when a Snake game starts or ends. */
onGameChange?: (isPlaying: boolean) => void;
}
/** Aurora dot grid that drifts on its own and lights up under the cursor. */
export default function DotGrid({
className,
onGameChange,
}: DotGridProps): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const isDarkMode = useIsDarkMode();
const label = useDotGrid(canvasRef, isDarkMode, onGameChange);
return (
<div
className={cx(styles.dotGrid, className)}
data-testid="ai-dot-grid"
aria-hidden
>
<canvas ref={canvasRef} className={styles.canvas} />
{label && <span className={styles.label}>{label}</span>}
</div>
);
}

View File

@@ -0,0 +1,103 @@
import { useRef } from 'react';
import { act, render, screen, userEvent } from 'tests/test-utils';
import DotGrid from '../DotGrid';
import { useDotGrid } from '../useDotGrid';
const KONAMI =
'{ArrowUp}{ArrowUp}{ArrowDown}{ArrowDown}{ArrowLeft}{ArrowRight}{ArrowLeft}{ArrowRight}ba';
function Chat({
onGameChange,
}: {
onGameChange: (isPlaying: boolean) => void;
}): JSX.Element {
return (
<div>
<DotGrid onGameChange={onGameChange} />
<textarea data-testid="chat-textarea" />
</div>
);
}
function ThemedGrid({ isDarkMode }: { isDarkMode: boolean }): JSX.Element {
const canvasRef = useRef<HTMLCanvasElement>(null);
const label = useDotGrid(canvasRef, isDarkMode);
return (
<>
<canvas ref={canvasRef} />
<span data-testid="score-line">{label}</span>
</>
);
}
describe('DotGrid Snake', () => {
beforeEach(() => {
jest.useFakeTimers();
// jsdom has no canvas or layout: a 9 × 7 game grid is enough for a snake.
jest
.spyOn(HTMLCanvasElement.prototype, 'getContext')
.mockReturnValue(
new Proxy({}, { get: () => jest.fn() }) as CanvasRenderingContext2D,
);
jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(120);
jest.spyOn(HTMLElement.prototype, 'clientHeight', 'get').mockReturnValue(120);
});
afterEach(() => {
jest.useRealTimers();
jest.restoreAllMocks();
});
it('quits the game on Esc and hands the keyboard back', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
expect(onGameChange).toHaveBeenLastCalledWith(true);
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent(
'Snake · score 0 · ↑ ↓ ← → · Esc to quit',
);
await user.keyboard('{Escape}');
expect(onGameChange).toHaveBeenLastCalledWith(false);
expect(screen.getByTestId('ai-dot-grid')).not.toHaveTextContent('Snake');
});
it('leaves arrows in the chat input alone after game over', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const onGameChange = jest.fn();
render(<Chat onGameChange={onGameChange} />);
await user.keyboard(KONAMI);
// Heading right, the snake reaches the wall within a few steps.
act(() => {
jest.advanceTimersByTime(1500);
});
expect(screen.getByTestId('ai-dot-grid')).toHaveTextContent('Game over');
onGameChange.mockClear();
await user.click(screen.getByTestId('chat-textarea'));
await user.keyboard('{ArrowUp}');
expect(onGameChange).not.toHaveBeenCalled();
});
it('drops the score line when the theme changes mid-game', async () => {
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const { rerender } = render(<ThemedGrid isDarkMode />);
await user.keyboard(KONAMI);
expect(screen.getByTestId('score-line')).toHaveTextContent('Snake · score 0');
rerender(<ThemedGrid isDarkMode={false} />);
expect(screen.getByTestId('score-line')).toBeEmptyDOMElement();
});
});

View File

@@ -0,0 +1,32 @@
import { getSnakeColors } from '../dotGridTheme';
function canvasWithInk(ink: string): HTMLCanvasElement {
const canvas = document.createElement('canvas');
canvas.style.color = ink;
document.body.appendChild(canvas);
return canvas;
}
describe('getSnakeColors', () => {
afterEach(() => {
document.body.innerHTML = '';
});
it('keeps the snake white on the dark page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), true)).toStrictEqual({
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
});
});
it('draws the snake in the page ink on the light page', () => {
expect(getSnakeColors(canvasWithInk('rgb(30, 31, 36)'), false)).toStrictEqual(
{
head: 'rgba(30,31,36,1)',
body: 'rgba(30,31,36,0.85)',
food: 'rgba(30,31,36,0.95)',
},
);
});
});

View File

@@ -0,0 +1,112 @@
import { SnakeGame, startSnake, stepSnake } from '../snakeGame';
const COLS = 10;
const ROWS = 6;
function newGame(): SnakeGame {
const game = startSnake(COLS, ROWS);
if (!game) {
throw new Error('a 10 × 6 grid fits a game');
}
return game;
}
describe('snakeGame', () => {
beforeEach(() => {
// Food lands on the first free cell, the top-left corner.
jest.spyOn(Math, 'random').mockReturnValue(0);
});
afterEach(() => {
jest.restoreAllMocks();
});
it('needs at least an 8 × 6 grid', () => {
expect(startSnake(7, 6)).toBeNull();
expect(startSnake(8, 5)).toBeNull();
});
it('starts four cells long in the middle, heading right', () => {
expect(newGame()).toStrictEqual({
body: [
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
{ c: 2, r: 3 },
],
dir: { c: 1, r: 0 },
nextDir: { c: 1, r: 0 },
food: { c: 0, r: 0 },
score: 0,
});
});
it('moves one cell in its direction', () => {
const next = stepSnake(newGame(), COLS, ROWS);
expect(next?.body).toStrictEqual([
{ c: 6, r: 3 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
{ c: 3, r: 3 },
]);
expect(next?.score).toBe(0);
});
it('grows and scores when it eats', () => {
const next = stepSnake({ ...newGame(), food: { c: 6, r: 3 } }, COLS, ROWS);
expect(next?.body).toHaveLength(5);
expect(next?.score).toBe(1);
});
it('ends when it hits a wall', () => {
const atEdge: SnakeGame = {
...newGame(),
body: [
{ c: 9, r: 3 },
{ c: 8, r: 3 },
{ c: 7, r: 3 },
{ c: 6, r: 3 },
],
};
expect(stepSnake(atEdge, COLS, ROWS)).toBeNull();
});
it('ends when it runs into itself', () => {
const coiled: SnakeGame = {
...newGame(),
body: [
{ c: 5, r: 3 },
{ c: 5, r: 4 },
{ c: 6, r: 4 },
{ c: 6, r: 3 },
{ c: 7, r: 3 },
],
};
expect(stepSnake(coiled, COLS, ROWS)).toBeNull();
});
it('moves into the cell its tail is leaving', () => {
const up = { c: 0, r: -1 };
const turnedDownThenLeft: SnakeGame = {
...newGame(),
body: [
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
{ c: 4, r: 3 },
],
nextDir: up,
};
expect(stepSnake(turnedDownThenLeft, COLS, ROWS)?.body).toStrictEqual([
{ c: 4, r: 3 },
{ c: 4, r: 4 },
{ c: 5, r: 4 },
{ c: 5, r: 3 },
]);
});
});

View File

@@ -0,0 +1,53 @@
export const DOT_SPACING = 12;
export const DOT_RADIUS = 1.15;
export const TRAIL_RADIUS = 72;
export const TRAIL_LIFT = 0.24;
export const TRAIL_MAX_POINTS = 18;
export const TRAIL_LIFE_MS = 1000;
export const TRAIL_MIN_STEP = 7;
// Time the field rests at when motion is reduced.
export const STILL_TIME_MS = 12000;
type Rgb = [number, number, number];
// Green, teal, blue, violet and pink, in the order the field drifts through them.
const AURORA: Rgb[] = [
[64, 224, 150],
[48, 200, 210],
[90, 130, 245],
[170, 110, 245],
[235, 110, 200],
];
/** Brightness of the field at a point, between -1 and 1. */
export function auroraBrightness(x: number, y: number, t: number): number {
return (
(Math.sin(x * 0.009 + t * 0.0006) +
Math.sin(y * 0.015 - t * 0.00085 + x * 0.002) +
Math.sin((x + y) * 0.006 + t * 0.0011) +
Math.sin((x - y) * 0.0048 - t * 0.0007)) /
4
);
}
/** Colour of the field at a point, blended along the aurora palette. */
export function auroraColor(x: number, y: number, t: number): Rgb {
const position =
((Math.sin(x * 0.0035 + t * 0.00018) +
Math.sin(y * 0.005 - t * 0.00026) +
Math.sin((x + y) * 0.0028 + t * 0.0002)) /
3 +
1) /
2;
const scaled = position * (AURORA.length - 1);
const from = AURORA[Math.floor(scaled)];
const to = AURORA[Math.min(Math.floor(scaled) + 1, AURORA.length - 1)];
const mix = scaled - Math.floor(scaled);
return [
from[0] + (to[0] - from[0]) * mix,
from[1] + (to[1] - from[1]) * mix,
from[2] + (to[2] - from[2]) * mix,
];
}

View File

@@ -0,0 +1,34 @@
// Colours for the dot grid that depend on the page behind it.
export interface SnakeColors {
head: string;
body: string;
food: string;
}
const DARK_SNAKE: SnakeColors = {
head: 'rgba(255,255,255,1)',
body: 'rgba(232,238,245,0.92)',
food: 'rgba(255,255,255,0.97)',
};
function withAlpha(rgb: string, alpha: number): string {
const channels = rgb.match(/\d+(\.\d+)?/g)?.slice(0, 3) ?? ['0', '0', '0'];
return `rgba(${channels.join(',')},${alpha})`;
}
/** Snake colours: white on the dark page, the canvas's ink (`color`) on the light one. */
export function getSnakeColors(
canvas: HTMLCanvasElement,
isDarkMode: boolean,
): SnakeColors {
if (isDarkMode) {
return DARK_SNAKE;
}
const ink = getComputedStyle(canvas).color;
return {
head: withAlpha(ink, 1),
body: withAlpha(ink, 0.85),
food: withAlpha(ink, 0.95),
};
}

View File

@@ -0,0 +1,102 @@
// Painting for the dot grid: the aurora field with the cursor's glow, and plain dots.
import {
auroraBrightness,
auroraColor,
DOT_RADIUS,
TRAIL_LIFE_MS,
TRAIL_LIFT,
TRAIL_RADIUS,
} from './dotGridField';
// Coloured dots on white read fainter than lit ones on black.
const LIGHT_ALPHA_BOOST = 1.6;
export interface TrailPoint {
x: number;
y: number;
born: number;
}
interface AuroraFrame {
/** Field time; frozen when motion is reduced. */
t: number;
now: number;
height: number;
trail: TrailPoint[];
isGameOn: boolean;
/** Light adds up on the dark page; on the light one colours sit on the paper instead. */
isDarkMode: boolean;
/** Dots below this stay dark. */
cutoffY: number;
}
/** The faint light that washes up from the bottom while the game is on. */
export function gameFloor(y: number, height: number): number {
return 0.07 + 0.16 * (y / height);
}
export function drawDot(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
radius: number,
fill: string,
): void {
ctx.beginPath();
ctx.fillStyle = fill;
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
/** Paints the aurora dots, brightest at the top and lit along the cursor's trail. */
export function drawAuroraDots(
ctx: CanvasRenderingContext2D,
dots: { x: number; y: number }[],
{ t, now, height, trail, isGameOn, isDarkMode, cutoffY }: AuroraFrame,
): void {
// Overlapping glows add up, as light does.
ctx.globalCompositeOperation = isDarkMode ? 'lighter' : 'source-over';
dots.forEach(({ x, y }) => {
if (y > cutoffY) {
return;
}
// Brightest at the top, fading toward the content below.
const topWeight = 1 - 0.82 * Math.min(1, y / height);
const lum = Math.max(0, auroraBrightness(x, y, t)) ** 1.6;
let intensity = (0.06 + lum * 0.4) * topWeight * (isGameOn ? 0.5 : 1);
if (isGameOn) {
intensity += gameFloor(y, height);
}
let glow = 0;
trail.forEach((point) => {
const distance2 = (x - point.x) ** 2 + (y - point.y) ** 2;
if (distance2 < TRAIL_RADIUS ** 2) {
const life = 1 - (now - point.born) / TRAIL_LIFE_MS;
glow += (1 - distance2 / TRAIL_RADIUS ** 2) ** 3 * life;
}
});
intensity += Math.min(glow, 1.3) * TRAIL_LIFT * topWeight;
if (intensity <= 0.02) {
return;
}
const [red, green, blue] = auroraColor(x, y, t);
// The hottest dots burn toward white on the dark page and deepen on the light one.
const heat = Math.min(1, Math.max(0, intensity - 0.9)) * 0.9;
const toward = isDarkMode ? 255 : 0;
const mix = isDarkMode ? heat : heat * 0.4;
const rgb = `${Math.round(red + (toward - red) * mix)},${Math.round(
green + (toward - green) * mix,
)},${Math.round(blue + (toward - blue) * mix)}`;
const alpha = Math.min(1, intensity * (isDarkMode ? 1 : LIGHT_ALPHA_BOOST));
const radius = DOT_RADIUS + Math.min(intensity, 1.2) * 0.7;
if (intensity > 0.6) {
drawDot(ctx, x, y, radius * 2.6, `rgba(${rgb},${alpha * 0.06})`);
}
drawDot(ctx, x, y, radius, `rgba(${rgb},${alpha})`);
});
ctx.globalCompositeOperation = 'source-over';
}

View File

@@ -0,0 +1,100 @@
// Snake on the dot grid, the easter egg the Konami code unlocks.
interface Cell {
c: number;
r: number;
}
export interface SnakeGame {
body: Cell[];
dir: Cell;
nextDir: Cell;
food: Cell;
score: number;
}
export const SNAKE_STEP_MS = 110;
// Lowercase: keys are lowercased before matching, so B/b and A/a both count.
export const KONAMI_CODE = [
'arrowup',
'arrowup',
'arrowdown',
'arrowdown',
'arrowleft',
'arrowright',
'arrowleft',
'arrowright',
'b',
'a',
];
export const SNAKE_DIRECTIONS: Record<string, Cell> = {
arrowup: { c: 0, r: -1 },
w: { c: 0, r: -1 },
arrowdown: { c: 0, r: 1 },
s: { c: 0, r: 1 },
arrowleft: { c: -1, r: 0 },
a: { c: -1, r: 0 },
arrowright: { c: 1, r: 0 },
d: { c: 1, r: 0 },
};
const isOn = (cells: Cell[], cell: Cell): boolean =>
cells.some(({ c, r }) => c === cell.c && r === cell.r);
/** A free cell for the food, or null when the snake fills the grid. */
function placeFood(body: Cell[], cols: number, rows: number): Cell | null {
const free: Cell[] = [];
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
if (!isOn(body, { c, r })) {
free.push({ c, r });
}
}
}
return free.length ? free[Math.floor(Math.random() * free.length)] : null;
}
/** A four-cell snake in the middle heading right, or null when the grid is too small. */
export function startSnake(cols: number, rows: number): SnakeGame | null {
if (cols < 8 || rows < 6) {
return null;
}
const c = Math.floor(cols / 2);
const r = Math.floor(rows / 2);
const body = [0, 1, 2, 3].map((i) => ({ c: c - i, r }));
const food = placeFood(body, cols, rows);
if (!food) {
return null;
}
const right = { c: 1, r: 0 };
return { body, dir: right, nextDir: right, food, score: 0 };
}
/** Moves the snake one cell; null when it hits a wall, itself, or fills the grid. */
export function stepSnake(
game: SnakeGame,
cols: number,
rows: number,
): SnakeGame | null {
const dir = game.nextDir;
const head = { c: game.body[0].c + dir.c, r: game.body[0].r + dir.r };
const ate = head.c === game.food.c && head.r === game.food.r;
const kept = ate ? game.body : game.body.slice(0, -1);
if (
head.c < 0 ||
head.c >= cols ||
head.r < 0 ||
head.r >= rows ||
isOn(kept, head)
) {
return null;
}
const body = [head, ...kept];
const food = ate ? placeFood(body, cols, rows) : game.food;
if (!food) {
return null;
}
return { ...game, body, dir, food, score: game.score + (ate ? 1 : 0) };
}

View File

@@ -0,0 +1,320 @@
import { RefObject, useEffect, useLayoutEffect, useRef, useState } from 'react';
import {
DOT_RADIUS,
DOT_SPACING,
STILL_TIME_MS,
TRAIL_LIFE_MS,
TRAIL_MAX_POINTS,
TRAIL_MIN_STEP,
TRAIL_RADIUS,
} from './dotGridField';
import { drawAuroraDots, drawDot, gameFloor, TrailPoint } from './drawDots';
import {
KONAMI_CODE,
SNAKE_DIRECTIONS,
SNAKE_STEP_MS,
SnakeGame,
startSnake,
stepSnake,
} from './snakeGame';
import { getSnakeColors } from './dotGridTheme';
const GAME_OVER_LABEL_MS = 4000;
const REPLAY_LABEL = '↑ to replay';
const playingLabel = (score: number): string =>
`Snake · score ${score} · ↑ ↓ ← → · Esc to quit`;
// Unlocked once per page load; after that a click on the dots starts a game.
let isSnakeUnlocked = false;
// Room left under the snake's lowest row for the score line, so the two never touch.
const SCORE_LINE_CLEARANCE = 30;
const isField = (target: EventTarget | null): target is HTMLElement =>
target instanceof HTMLElement &&
Boolean(target.closest('input, textarea, select, [contenteditable="true"]'));
/** Draws the aurora dot grid; the Konami code turns it into Snake. Returns the score line. */
export function useDotGrid(
canvasRef: RefObject<HTMLCanvasElement>,
isDarkMode: boolean,
onGameChange?: (isPlaying: boolean) => void,
): string | null {
const [label, setLabel] = useState<string | null>(null);
const onGameChangeRef = useRef(onGameChange);
useLayoutEffect(() => {
onGameChangeRef.current = onGameChange;
});
useEffect(() => {
const canvas = canvasRef.current;
const ctx = canvas?.getContext('2d');
if (!canvas || !ctx) {
return undefined;
}
const isStill = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
const snakeColors = getSnakeColors(canvas, isDarkMode);
let width = 0;
let height = 0;
let cols = 0;
let rows = 0;
let gameRows = 0;
let left = 0;
let dots: { x: number; y: number }[] = [];
const trail: TrailPoint[] = [];
let frame = 0;
let game: SnakeGame | null = null;
let lastStep = 0;
// With reduced motion the field stands still, so frames repaint only after a change.
let needsDraw = true;
let isScoreLineShown = false;
const showScoreLine = (text: string | null): void => {
isScoreLineShown = text !== null;
needsDraw = true;
setLabel(text);
};
const recentKeys: string[] = [];
let labelTimer = 0;
// An arrow key replays while the game over line is up.
let canReplay = false;
const showPlayCursor = (): void => {
canvas.style.cursor = isSnakeUnlocked && !game ? 'pointer' : '';
};
const cellCenter = (c: number, r: number): { x: number; y: number } => ({
x: left + c * DOT_SPACING,
y: DOT_SPACING + r * DOT_SPACING,
});
const play = (): void => {
game = startSnake(cols, gameRows);
lastStep = performance.now();
canReplay = false;
window.clearTimeout(labelTimer);
showScoreLine(game ? playingLabel(0) : null);
showPlayCursor();
onGameChangeRef.current?.(game !== null);
};
const quit = (): void => {
game = null;
canReplay = false;
window.clearTimeout(labelTimer);
showScoreLine(null);
showPlayCursor();
onGameChangeRef.current?.(false);
};
const endGame = (score: number): void => {
game = null;
canReplay = true;
showScoreLine(`Game over · score ${score} · ${REPLAY_LABEL}`);
showPlayCursor();
onGameChangeRef.current?.(false);
labelTimer = window.setTimeout(() => {
canReplay = false;
showScoreLine(null);
}, GAME_OVER_LABEL_MS);
};
const layout = (): void => {
const dpr = Math.min(window.devicePixelRatio || 1, 2);
width = canvas.clientWidth;
height = canvas.clientHeight;
canvas.width = Math.floor(width * dpr);
canvas.height = Math.floor(height * dpr);
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
cols = Math.max(0, Math.floor((width - DOT_SPACING) / DOT_SPACING));
rows = Math.max(0, Math.floor((height - DOT_SPACING) / DOT_SPACING));
gameRows = Math.min(
rows,
Math.max(0, Math.floor((height - SCORE_LINE_CLEARANCE) / DOT_SPACING)),
);
left = (width - cols * DOT_SPACING) / 2 + DOT_SPACING / 2;
dots = [];
for (let r = 0; r < rows; r += 1) {
for (let c = 0; c < cols; c += 1) {
dots.push(cellCenter(c, r));
}
}
needsDraw = true;
// A game carries on through a resize unless it no longer fits.
if (
game &&
[...game.body, game.food].some(({ c, r }) => c >= cols || r >= gameRows)
) {
play();
}
};
const onPointer = (event: PointerEvent): void => {
const rect = canvas.getBoundingClientRect();
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
if (
x < -TRAIL_RADIUS ||
y < -TRAIL_RADIUS ||
x > width + TRAIL_RADIUS ||
y > height + TRAIL_RADIUS
) {
return;
}
const head = trail[trail.length - 1];
// Barely moved: keep the head lit instead of stacking points.
if (head && Math.hypot(x - head.x, y - head.y) < TRAIL_MIN_STEP) {
head.born = performance.now();
return;
}
trail.push({ x, y, born: performance.now() });
if (trail.length > TRAIL_MAX_POINTS) {
trail.shift();
}
};
// Keys typed into a field outside this chat belong to that field.
const isOtherField = (target: EventTarget | null): boolean => {
if (!isField(target)) {
return false;
}
let chat = canvas.parentElement;
while (chat && !chat.querySelector('textarea')) {
chat = chat.parentElement;
}
return !chat?.contains(target);
};
const onKeyDown = (event: KeyboardEvent): void => {
if (isOtherField(event.target)) {
return;
}
const key = event.key.toLowerCase();
if (game) {
if (key === 'escape') {
event.preventDefault();
quit();
return;
}
const next = SNAKE_DIRECTIONS[key];
if (next) {
// Steering keys drive the snake, not the input; no turning back onto the neck.
event.preventDefault();
if (next.c !== -game.dir.c || next.r !== -game.dir.r) {
game.nextDir = next;
}
}
return;
}
// Arrows in the chat's input move its caret instead.
if (canReplay && key.startsWith('arrow') && !isField(event.target)) {
event.preventDefault();
play();
return;
}
recentKeys.push(key);
if (recentKeys.length > KONAMI_CODE.length) {
recentKeys.shift();
}
if (recentKeys.join() === KONAMI_CODE.join()) {
recentKeys.length = 0;
isSnakeUnlocked = true;
play();
}
};
const onClick = (): void => {
if (isSnakeUnlocked && !game) {
play();
}
};
// The snake and its food: flat white dots the size of their neighbours.
const stepAndDrawSnake = (now: number): void => {
if (game && now - lastStep >= SNAKE_STEP_MS) {
lastStep = now;
const next = stepSnake(game, cols, gameRows);
if (next) {
if (next.score !== game.score) {
showScoreLine(playingLabel(next.score));
}
game = next;
} else {
endGame(game.score);
}
}
if (game) {
const sizeAt = (y: number): number =>
DOT_RADIUS + Math.min(gameFloor(y, height), 1.2) * 0.7;
const food = cellCenter(game.food.c, game.food.r);
drawDot(ctx, food.x, food.y, sizeAt(food.y), snakeColors.food);
game.body.forEach((cell, i) => {
const { x, y } = cellCenter(cell.c, cell.r);
drawDot(
ctx,
x,
y,
sizeAt(y),
i === 0 ? snakeColors.head : snakeColors.body,
);
});
}
};
const draw = (now: number): void => {
const hadTrail = trail.length > 0;
for (let i = trail.length - 1; i >= 0; i -= 1) {
if (now - trail[i].born >= TRAIL_LIFE_MS) {
trail.splice(i, 1);
}
}
if (isStill && !game && !hadTrail && !needsDraw) {
frame = requestAnimationFrame(draw);
return;
}
needsDraw = false;
const t = isStill ? STILL_TIME_MS : now;
ctx.clearRect(0, 0, width, height);
drawAuroraDots(ctx, dots, {
t,
now,
height,
trail,
isGameOn: game !== null,
isDarkMode,
// Keeps the score line's strip clear of dots.
cutoffY: isScoreLineShown ? gameRows * DOT_SPACING : Infinity,
});
stepAndDrawSnake(now);
frame = requestAnimationFrame(draw);
};
const observer = new ResizeObserver(layout);
observer.observe(canvas);
layout();
window.addEventListener('pointermove', onPointer);
window.addEventListener('pointerdown', onPointer);
window.addEventListener('keydown', onKeyDown);
canvas.addEventListener('click', onClick);
showPlayCursor();
frame = requestAnimationFrame(draw);
return (): void => {
cancelAnimationFrame(frame);
observer.disconnect();
window.clearTimeout(labelTimer);
setLabel(null);
if (game) {
onGameChangeRef.current?.(false);
}
window.removeEventListener('pointermove', onPointer);
window.removeEventListener('pointerdown', onPointer);
window.removeEventListener('keydown', onKeyDown);
canvas.removeEventListener('click', onClick);
};
}, [canvasRef, isDarkMode]);
return label;
}

View File

@@ -68,7 +68,17 @@ export default function DownloadOptionsMenu({
aria-modal="true"
>
<div className="export-format">
<Typography.Text className="title">FORMAT</Typography.Text>
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
FORMAT
</Typography>
<RadioGroup
color="primary"
value={exportFormat}
@@ -83,7 +93,17 @@ export default function DownloadOptionsMenu({
<div className="horizontal-line" />
<div className="row-limit">
<Typography.Text className="title">Number of Rows</Typography.Text>
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
Number of Rows
</Typography>
<RadioGroup
color="primary"
value={String(rowLimit)}
@@ -101,7 +121,17 @@ export default function DownloadOptionsMenu({
<div className="horizontal-line" />
<div className="columns-scope">
<Typography.Text className="title">Columns</Typography.Text>
<Typography
variant="uppercase"
size="small"
weight="medium"
color="main"
as="p"
marginBottom={4}
textOverflow="wrap"
>
Columns
</Typography>
<RadioGroup
color="primary"
value={columnsScope}

View File

@@ -1,6 +1,5 @@
import { Trash2, X } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { DialogWrapper } from '@signozhq/ui/dialog';
import { AlertDialog } from '@signozhq/ui/alert-dialog';
import { MemberRow } from 'components/MembersTable/MembersTable';
interface DeleteMemberDialogProps {
@@ -9,7 +8,7 @@ interface DeleteMemberDialogProps {
member: MemberRow | null;
isDeleting: boolean;
onClose: () => void;
onConfirm: () => void;
onConfirm: () => Promise<void>;
}
function DeleteMemberDialog({
@@ -36,47 +35,20 @@ function DeleteMemberDialog({
</>
);
const footer = (
<>
<Button
size="md"
variant="solid"
color="secondary"
onClick={onClose}
prefix={<X size={12} />}
>
Cancel
</Button>
<Button
size="md"
variant="solid"
color="danger"
onClick={onConfirm}
testId="member-delete-confirm-btn"
loading={isDeleting}
prefix={<Trash2 size={12} />}
>
{isDeleting ? 'Processing...' : title}
</Button>
</>
);
return (
<DialogWrapper
<AlertDialog
open={open}
onOpenChange={(isOpen): void => {
if (!isOpen) {
onClose();
}
}}
title={title}
width="narrow"
showCloseButton={false}
disableOutsideClick={false}
footer={footer}
color="danger"
confirmText={isDeleting ? 'Processing...' : title}
confirmIcon={<Trash2 size={12} />}
cancelIcon={<X size={12} />}
onConfirm={onConfirm}
onCancel={onClose}
testId="member-delete"
>
{body}
</DialogWrapper>
</AlertDialog>
);
}

Some files were not shown because too many files have changed in this diff Show More