Compare commits

...

26 Commits

Author SHA1 Message Date
Vinícius Lourenço
0fcaae2a8f chore(web): drop duplicate uPlot stylesheet import from anomaly view 2026-11-27 10:17:38 -03:00
Vinícius Lourenço
05cf64aa34 chore(web): drop past-tense note from uPlot stylesheet comment 2026-11-27 09:17:36 -03:00
Vinícius Lourenço
ca10a4806e perf(web): serve the uPlot stylesheet as a hashed asset 2026-11-26 15:43:02 -03:00
Aditya Singh
b1f271a505 fix(frontend): show the full text of truncated labels in one tooltip (#13735)
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

- Since #13087, `Typography` opens its own tooltip when its text is cut
off. Four places also had an outer tooltip, so hovering cut-off text
showed it twice.
- Quick filter section titles showed the title twice in one stacked
tooltip. Span event attribute keys and values, and query builder search
suggestions, opened two separate popups.
- This PR removes the outer tooltip at those four places. Cut-off text
now shows its full text once, and text that fits shows no tooltip.
- Suggestion value and operator rows did not shrink, so their text was
never cut and only the outer tooltip showed a long value. The row's left
section now shrinks, so a long value ends in "…" and its tooltip opens.
- New stories hover cut-off text in quick filters, span events and the
pipeline filter suggestions, and they fail on `main`. Two jest tests for
the old quick filter tooltip are removed, because jsdom cannot measure
text.

#### Issues closed by this PR

Part of https://github.com/SigNoz/events-pod/issues/306

#### Screenshots / Screen Recordings

Screenshots of the new stories, in dark and light themes:
https://claude.ai/artifact/Lcjn1xBj8qTM9yesjPDmK6

- Quick filters: before and after. On `main` the title shows twice in
one tooltip.
- Span events and the pipeline filter suggestions: after only. Their
plays use a helper this PR adds, so `main` cannot run them.

#### Additional Information

- A long span event value inside the hover popover still opens the
popover and the `Typography` tooltip together. That fix needs a change
in `@signozhq/ui`.
2026-11-26 15:42:49 +00:00
Vinicius Lourenço
c92bb94caf perf(web): load each metrics, meter and messaging queues tab when it opens (#13696)
#### Description

Metrics explorer, Meter and Messaging queues import all of their tabs up
front. Each tab now loads when it opens, using the per-tab loading state
from #13691. Tab URLs and order stay as they are. Infrastructure
monitoring and API monitoring are left alone: their tabs share almost
all of their code, or there is only one.

Opening each page's default tab, entry included: Metrics goes from 11.43
MB to 11.09 MB, Meter from 11.39 MB to 11.14 MB and Messaging queues
from 11.26 MB to 10.96 MB.

The queue details drawer on the messaging queues overview relied on
styles the Celery tab happened to load; it now imports them itself.

Part of #10192

#### Screenshots / Screen Recordings

Switching metrics explorer tabs in Storybook, main on the left, with the
network slowed to 1.6 Mbps so the loading state is visible:


https://github.com/user-attachments/assets/5802c696-680e-4afc-93d7-a59536542af9

Queue details drawer, main on the left:

![Queue details
drawer](https://github.com/user-attachments/assets/b6d0f13d-f7cc-4e0e-b2de-3c7f6af1e5f4)

The 40 metrics, meter and messaging queues stories render the same in
both themes, except the Celery state drawer table, which sits 1px
higher.
2026-11-26 14:44:51 +00:00
ashu8912
8e3a4f8775 fix(list-filter): run a filter tag's removal when its dropdown is closed (#13753)
#### Description

- Removing a Created-by tag with its × only staged the change: the query
runs when the dropdown closes, and the × never opens it. The chip
vanished but the list kept its old results.
- `MultiSelectFilter` now commits any change made with its dropdown
closed (a tag's ×, the clear icon) through `onCommit`; picks in an open
dropdown still stage until it closes.
- Dashboards' Created-by, the service accounts status filter (same bug)
and the alert rules status filter (which had its own copy of this) all
use it.

#### Issues closed by this PR

Closes SigNoz/pulse-pod#789

#### Screenshots / Screen Recordings

[Visual diff](https://claude.ai/artifact/LGAnLu31NHXY5eZ6PLz3Yx)
(sbshot, merge-base vs this branch, dark and light): removing the
Created-by tag on My dashboards and the Deleted status tag on service
accounts now reruns the list. 14 of 22 pairs are pixel-identical; the
other 4 are timestamp and anti-aliasing noise.

#### Additional Information

- The clear icon clicked while the dropdown is open now stages like any
other pick, running on close.
2026-11-26 14:01:25 +00:00
Vinicius Lourenço
a8433ad9e0 perf(web): use CSS variables instead of the design-tokens Style object (#13685)
#### Description

`Style` from `@signozhq/design-tokens` is an object of 817 `var(--...)`
strings, and the bundler keeps all of it once anything imports it. The
side nav did, for one value, so the whole object sat in the entry chunk.
The three values the app used are now written as the CSS variables they
already held, and oxlint rejects importing `Style`. The entry chunk
loses 47.6 kB (7.8 kB gzipped). Colors render the same, since the
strings are identical.

Part of #10192

#### Screenshots / Screen Recordings

Main on the left or top, this branch on the right or below:

![Settings menu in the side
nav](https://github.com/user-attachments/assets/ab0236ba-f10d-48e7-87aa-5612ea4a3dfb)

![OIDC form with claim
mapping](https://github.com/user-attachments/assets/80d7a7b6-1c0c-442b-bd6a-68ce4853573f)

The 46 stories that render these icons are pixel-identical in both
themes, apart from a focus ring left on one form input.
2026-11-26 12:47:49 +00:00
Vinicius Lourenço
d07b0f1d82 perf(integrations): import antd from its ES entry instead of antd/lib (#13683)
#### Description

The cloud integrations page imported `Modal`, `Form`, `Select` and
`Skeleton` from `antd/lib`. That path is antd's CommonJS entry, so it
pulled every antd component into the page's chunk. Importing from `antd`
takes that chunk from 1.30 MB to 108 kB (335 kB to 26 kB gzipped).

It also fixes how the remove-account modal looks. `antd/lib` is a second
copy of antd that the app's `ConfigProvider` does not reach, so that
modal used antd's default theme (larger text, bold title, rounder
buttons). It now picks up the app theme.

#10491 removed these imports once and they came back, so oxlint now
rejects runtime imports from `antd/lib`. Type-only imports stay allowed.

To check, run `pnpm build` on main and on this branch and compare
`build/assets/IntegrationsDetailsPage-*.js`.

Part of #10192

#### Screenshots / Screen Recordings

The remove-account modal, main on the left and this branch on the right:

![Remove account modal, light
theme](https://github.com/user-attachments/assets/c67a3d7b-f7b3-4631-a667-a820f4147b76)

![Remove account modal, dark
theme](https://github.com/user-attachments/assets/37dbf93b-f6f0-41f7-b5a6-d7e28e76b376)

Across the 43 cloud account stories in both themes, the only other
differences are toasts caught mid-fade.
2026-11-26 12:29:45 +00:00
Vinicius Lourenço
a02330438f perf(dashboard): emit logo assets as files instead of inlining them (#13684)
#### Description

Dashboard JSON can point at any logo under `src/assets/Logos`, so the
icon map globs all 240 of them. The glob used `?url`, but Vite still
inlines every file under `assetsInlineLimit` as base64, so the logos
shipped inside the JS whether a dashboard used them or not. With
`?no-inline` they are emitted as files and fetched only when a dashboard
shows one. The chunk that holds the icon map goes from 376 kB to 76 kB
(135 kB to 23 kB gzipped).

To check, on a production build (`pnpm build && pnpm preview`) import a
dashboard whose `image` is `/assets/Logos/redis`: the logo loads as its
own `redis-<hash>.svg` request.

Part of #10192

#### Screenshots / Screen Recordings

Dashboard list with logo images, main on top and this branch below:

![Dashboard list with
logos](https://github.com/user-attachments/assets/783b8889-629b-4e86-9990-5712015e709e)

The logo stories are pixel-identical in both themes. Across the 102
dashboard list, detail and settings stories, the other differences are
toast fades and mock timestamps a second apart.
2026-11-26 12:28:12 +00:00
Ashwin Bhatkal
cb2b3db771 chore(page-story): guard plays on the args their story sets (#13768)
#### Description

- Plays the page-story skill writes now check the args their own story
sets. A story that sets `view: 'mine'` to put a Created-by tag on screen
must still pass when someone flips the view in the panel. This is the
miss from
https://github.com/SigNoz/signoz/pull/13753#discussion_r4706154296.
- The skill now says to go through every control a story exposes, the
page's own as well as the shared ones, before writing a play's early
returns.
- New PR rule: a review fix to a file with the AI-owned banner also adds
the lesson to the skill or agent that made it, so the next run doesn't
write the same bug again.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/786
2026-11-26 12:25:02 +00:00
Ashwin Bhatkal
40ee169d94 fix(query-builder): keep value suggestions open when the editor re-renders (#13760)
#### Description

- The query search value dropdown now stays open when the editor
re-renders. Before, every render handed CodeMirror new extensions. When
the cursor sat on an empty value like `service.name = '`, that closed
the dropdown, for example when key suggestions loaded late.
- The CodeMirror extensions, `onChange` handler and `basicSetup` are now
built once. They read the latest suggestions and run handler through
refs, as `ListFilter/SearchBar` does.
- This fixes the flaky `fetches value suggestions when editing value
context` test. The "keeps the value suggestions open when the key
suggestions load" test now waits past CodeMirror's re-query, so it fails
without this fix. Its old assertion ran before the dropdown closed.
- Stories already cover this: the Traces and Metrics explorer plays type
`service.name = ` and wait for a value suggestion.

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/782
2026-11-26 12:05:03 +00:00
hardik-signoz
865e1c97b3 feat(authz): expose ingestion-key and ingestion-limit fga (#13648)
#### Description

- Gates the Ingestion keys page on the new `ingestion-key` and
`ingestion-limit` permissions, so users without them can't trigger
actions that would be rejected.
- Moves limit create/update/delete off the deprecated gateway routes to
`/ingestion_limits`; their permissions are identical.
- Shows both resources in the roles editor.
- Ingestion shows in the settings sidebar for every role. The legacy vs
multi-key page split is unchanged (multi-key when the gateway is on,
legacy for cloud otherwise); only the admin/editor condition is dropped.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#42

#### Screenshots / Screen Recordings

[sbshot diff](https://claude.ai/artifact/FutBFmcA9ERz1GzcrhjYJN) vs the
merge-base, dark and light:
- Ingestion: unchanged for permitted users (30 pairs identical), plus 9
new Authz stories.
- Roles: only the new Ingestion Keys and Limits panels and the viewer's
sidebar link changed.

#### Additional Information

- Open on the ticket: the new `/ingestion_limits` calls are not yet
tested against a real gateway.

---------

Co-authored-by: vikrantgupta25 <vikrant@signoz.io>
2026-11-26 12:03:33 +00:00
ashu8912
5f24193de6 fix(list-views): match the view name placeholder to its list (#13767)
#### Description

- The save/rename view dialog hardcoded "e.g. Prod alerts", so the
dashboards list showed an alerts example.
- `ViewsRail` now takes `viewNamePlaceholder`; alerts keep "e.g. Prod
alerts", dashboards use "e.g. Prod dashboards".
- The dashboards list story already opens this dialog in its play, so no
story change.

Found while testing SigNoz/pulse-pod#775.
2026-11-26 11:58:17 +00:00
Ashwin Bhatkal
3d63ed6353 ci(goci): bump setup-go to v7 to reuse main's module cache (#13744)
#### Description

- `goci` jobs now use the same `setup-go` as the primus jobs (v7.0.0,
pinned), so they restore the Go module cache that `build-staging` saves
on `main`.
- setup-go v5 keys its cache on `go.sum` and v7 keys it on `go.mod`.
`main` only ever gets the v7 key, so `build`, `openapi`, `authz`,
`web-settings`, `transaction-groups` and `semconv-generated` missed it
and downloaded every module from proxy.golang.org on each run.
- Those downloads failed 11 runs since Nov 23 with `stream error: ...
INTERNAL_ERROR; received from peer`, 4 of them in the merge queue. `go`
does not retry a reset download.
- To check: on this PR's run, the `go-install` step of `build` should
log `Cache restored from key: setup-go-...-e68ddbf...`.

<details>
<summary>Failed runs</summary>

- Nov 23 16:36 UTC, PR:
[transaction-groups](https://github.com/SigNoz/signoz/actions/runs/45218336614/job/137845455490)
- Nov 24 14:43 UTC, PR:
[openapi](https://github.com/SigNoz/signoz/actions/runs/45417214716/job/138526593113)
- Nov 24 15:45 UTC, merge queue:
[build](https://github.com/SigNoz/signoz/actions/runs/45429166803/job/138569346003)
- Nov 24 17:03 UTC, merge queue:
[build](https://github.com/SigNoz/signoz/actions/runs/45444178593/job/138623258070)
- Nov 24 17:10 UTC, PR:
[web-settings](https://github.com/SigNoz/signoz/actions/runs/45445506450/job/138628048194)
- Nov 24 17:58 UTC, PR:
[transaction-groups](https://github.com/SigNoz/signoz/actions/runs/45454318875/job/138659559545)
- Nov 24 17:59 UTC, PR:
[web-settings](https://github.com/SigNoz/signoz/actions/runs/45454538375/job/138660328195)
- Nov 24 18:09 UTC, PR:
[openapi](https://github.com/SigNoz/signoz/actions/runs/45456425417/job/138666985974),
[build](https://github.com/SigNoz/signoz/actions/runs/45456425417/job/138666985982)
- Nov 24 18:39 UTC, merge queue:
[authz](https://github.com/SigNoz/signoz/actions/runs/45461964073/job/138686679525),
[build](https://github.com/SigNoz/signoz/actions/runs/45461964073/job/138686679898)
- Nov 24 18:41 UTC, PR:
[build](https://github.com/SigNoz/signoz/actions/runs/45462168844/job/138687411123),
[transaction-groups](https://github.com/SigNoz/signoz/actions/runs/45462168844/job/138687412071)
- Nov 24 19:12 UTC, merge queue:
[build](https://github.com/SigNoz/signoz/actions/runs/45467713142/job/138706955705)

</details>

#### Issues closed by this PR

Closes https://github.com/SigNoz/pulse-pod/issues/776
2026-11-26 11:34:07 +00:00
hardik-signoz
3af06adabc feat(authz): auth-domains and organization fga (#13706)
#### Description

- Include auth domains and the organization in the generated frontend
permissions, so the role editor offers them.
- Show Organization Settings, and the SSO section in it, to all roles.
Access is decided by authz instead of the legacy admin-only check.
- Gate the auth domain list and delete, and the organization display
name, on their permissions. Saving a domain stays a backend check.
- Add unit tests, SSO stories and E2E specs.

#### Issues closed by this PR

Closes SigNoz/keystone-pod#39

#### Screenshots / Screen Recordings

[Before and after Storybook shots of the settings
pages](https://claude.ai/artifact/1Az85vbiW1RU1rk5JD5zRN), dark and
light. Role editor and role details list the new Auth Domains and
Organization panels. The Display name field and its Submit button use
the `@signozhq/ui` components. The baseline is the merge-base plus a
commit that only retitles the Single Sign-on stories, so old and new
stories pair.
2026-11-26 10:20:43 +00:00
ashu8912
7b20abbeb7 fix(unauthorized): align the contact link with the message text (#13758)
#### Description

- The "reach out to us." link on the anonymous Access Restricted page
sat below the text baseline and had no space before it.
- `Button` is an `inline-flex` box with a fixed 24px link height,
centring its label; letting its height size to content and aligning on
the baseline puts it on the line. Set via `--button-*` tokens since
`Button` drops `className`.
- The leading space moves outside the button, where flex layout no
longer swallows it.

#### Screenshots / Screen Recordings

Visual diff (sbshot, `Pages/System/Unauthorized`, dark + light, baseline
`main`): https://claude.ai/artifact/AxR71cviVejCEE96XhbEHM
2026-11-26 09:25:37 +00:00
Vinicius Lourenço
73e6fa555a fix(infra-monitoring): restore log navigation from the entity drawer (#13742)
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

Log details opened from an infra monitoring drawer works again: the
arrow keys step through the logs, and a click on another log row opens
that log. Both broke when the entity drawer moved to `@signozhq/ui`,
which blocked keys and clicks on the drawer below log details.
`0.4.1-rc.1` fixes it (SigNoz/components#532).

A new e2e test in the infra monitoring drawer spec covers both, and the
Pods story "Details Drawer Log Navigation" covers the arrow keys.

#### Screenshots

After:


https://github.com/user-attachments/assets/548292f3-41e7-4d8b-b1f5-40872a2f8fb2

#### Additional Information

`0.4.1-rc.1` is a prerelease because SigNoz/components#532 is still
open. I'll bump to the stable release once it merges.
2026-11-26 08:24:09 +00:00
Gaurav Tewari
91525d721e feat(noz): show open chats as bottom-strip tabs (#13602)
<!--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 #13601.

- Open Noz conversations show as tabs in the bottom strip, newest beside
Ask Noz. Clicking one opens it in the Noz panel; × closes the tab
without archiving the thread.
- A tab whose reply the user hasn't seen shows a dot, and a placeholder
chime plays when a reply lands off screen. A reply on screen is read at
once.
- Tabs and unseen replies persist in localStorage, so they survive a
reload, a closed tab or a restart. Tabs are capped at 5; past that, the
oldest tab goes.
- Saved ids are pruned only after a successful thread fetch, so a failed
fetch can't wipe them. A deleted, archived or another user's thread
drops out on the next good fetch.
- `StripTab` / `StripTabs` are generic strip components (no Noz imports)
beside `StripTypography` and `StripKeyValue`.
- When the strip runs short, the tabs shrink first and their titles
truncate; Ask Noz, history and Support keep their size, and the tabs
never cover the left slot.
- Chat tabs also show on the Noz page, where a tab opens its chat in the
page.
- The Noz page's conversation list marks a chat with an unseen reply
with the same blue dot.
- The panel header gains a minimize button, which hides the panel and
keeps the chat as a tab. × now also closes the chat's tab; a reply
landing later brings it back.
- A tab also shows the dot while Noz waits on the user's approval or
answer there, and a chat that starts waiting joins the strip. Ask Noz
loses its pulsing dot: it always starts a new chat, so it can't lead to
the waiting one.

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


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

<!--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/99192505-8df2-4108-896d-3872e1926fe2



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

- Tab state lives with Noz, not the strip:
`useAIAssistantOpenConversationsStore` in `AIAssistant/store` and
`useAIAssistantActiveChats` (which also plays the chime) in
`AIAssistant/hooks`. `BottomStrip/NozActiveChat` only renders the tabs,
so the panel doesn't import from the strip.
- The store tracks loading per thread (`loadingThreadIds` replaces the
global `isLoadingThread`), so switching tabs while another chat loads
works, and a chat's skeleton and disabled input follow only its own
load.
- Stories: Components/Strip Tabs (Default, Crowded, Focused) and
Foundations/Bottom Strip `NozChats` / `NozChatOpen`. The global Noz
mocks gain "Open chats" and "Unseen replies" controls (default 0, so
other stories are unchanged). `NozAwaitingYou` now shows the waiting dot
on a tab.
- Bottom Strip `NozChatOpen` checks each chat opens on its end.
Pages/Noz with Open chats and Unseen replies set shows the list dot. The
Noz page mock now answers each thread as itself.
- Ports the earlier work from #13573 onto the Noz stack.

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-26 07:00:30 +00:00
Gaurav Tewari
251d49efce feat(noz): open recent conversations from the bottom strip (#13601)
<!--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 #13598.

- A history icon in the bottom strip, next to Ask Noz, opens a popover
of recent conversations with a title search. Picking one opens it in the
Noz panel.
- It stays while the panel is open, and hides when Noz is off, on the
Noz full page (whose sidebar lists the chats), or with no saved
conversation.
- It reads the list the shell already loads on every page, so it adds no
request.
- The floating panel and the Cmd/Ctrl+J popup chat lose their history
toggle. The conversation list is now full-page only, so its panel layout
is gone.
- Ask Noz always starts a new chat (reusing an empty open one) and stays
in the strip while the panel is open, so the panel and the popup chat
drop their + button.
- Opening the history closes the panel behind it, so one Noz surface
shows at a time.
- The list's open state lives in the Noz store (`isHistoryOpen`), like
the panel's, so a keyboard shortcut can open it later. It isn't
persisted.
- Both history lists open a chat through `useOpenConversation`, which
always reloads it, so a chat whose load failed can be retried.
- Like the panel, the popover moves left of the support chat while it's
open and back once it closes; Support no longer dismisses it. No new
obstacle system: `FloatingPanel`'s existing obstacle types and utils
move to `lib/obstacles` (renamed, not rewritten), and
`useAvoidObstacles` now subscribes through a shared `watchObstacles`.
The only new pieces are `getRightClearance` and `usePopoverAvoidance`,
the popover's counterpart to `useAvoidObstacles`.
- The @ picker's row style and the conversation list's relative time are
shared with the popover.
- Popover rows use the full-page list's text: vanilla-400 titles in dark
mode (`--l2-foreground` in light, since vanilla-400 doesn't follow the
theme), 20px line height and plain digits.

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


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

<!--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, both themes, vs `main`):
https://claude.ai/artifact/8xwuRCyTKntdDsfktVKjLP

- 98 pairs change: History and + leave the modal and panel headers, and
the strip gains the History icon. 2 are new (the History popover), 16
are removed (the header History stories), 62 are identical.



https://github.com/user-attachments/assets/ebf88e0b-0096-40e1-b605-b1df9bd7bc94


https://github.com/user-attachments/assets/6772ab32-44b2-48bd-812f-231525860bbb




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

-  We should merge this with the next follow up

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-26 06:27:11 +00:00
Vinicius Lourenço
7d92c443b3 refactor(web): move the changelog modal to the signozhq dialog (#13692)
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 changelog modal now uses the `@signozhq/ui` dialog instead of the
antd `Modal`, with the dialog's own colors and spacing. The title row,
scrollable content, footer actions and the "Scroll for more" button
stay, and the surface is one flat panel instead of boxes inside a box.
"Scroll for more" is now a primary `@signozhq/ui` button, so Tab shows
the same focus ring on it as on the footer buttons.

On main the modal's background depended on CSS load order: its own rule
and the global `.ant-modal .ant-modal-content` rule from #10742 have the
same specificity, so whichever loaded last won. The dialog drops those
antd overrides. It also no longer sits under the other `@signozhq/ui`
dialogs, and cloud workspaces, which have no upgrade actions, no longer
get an empty footer bar.

Stacked on #13689.

#### Screenshots / Screen Recordings

![Changelog
dialog](https://github.com/user-attachments/assets/02d6a5af-229c-4ff0-b5f8-b3d196bb092b)

Self-hosted workspace in the dark theme, main on the left and this
branch on the right.
2026-11-26 01:21:47 +00:00
Vinicius Lourenço
11cc323ca5 perf(web): load the AI assistant and changelog only when they render (#13689)
#### Description

The app layout imported the AI assistant panel and modal and the
changelog modal up front, so every page downloaded them before it could
render, including for users who never see the assistant. The assistant
brings the dashboard panel registry and the query builder along, and
with them uPlot, chart.js, CodeMirror, `moment-timezone` and
react-markdown. The assistant's code now loads only when it renders for
the user, and the changelog when it opens. If one of those chunks is
gone after a deploy, the page reloads once, the same way lazy pages
recover.

The entry chunk goes from 10.94 MB to 6.67 MB (2.94 MB to 1.81 MB
gzipped). On a 10 Mbps connection with a 4x slower CPU, the login form
shows in 3.7 s instead of 5.3 s.

Part of #10192

#### Screenshots / Screen Recordings

Cold load of the login page, main on the left. The stats include a build
with every bundle PR merged, for where this is heading:


https://github.com/user-attachments/assets/934ec550-4431-4d54-be51-dc952409565e

![First load
stats](https://github.com/user-attachments/assets/1f10ec42-bea4-48cc-afcb-89a8186f0733)

The changelog modal, main on the left. It now shows "Scroll for more"
when the notes overflow; on main the modal measured before its content
had laid out:

![Changelog
modal](https://github.com/user-attachments/assets/5ca17f48-24fe-4d21-be07-d8d995af6fc5)

The other app layout and bottom strip stories are pixel-identical in
both themes.
2026-11-26 00:26:26 +00:00
Vinicius Lourenço
2d5a07048a fix(widget-card): never request the previous widget query when the card is enabled (#13722)
#### Description

A panel whose widget query changed fetched once more with the previous
query before the new one.

The card kept a copy of the query in state and refreshed it in an
effect, one render late. On the service overview this is the latency
chart: it waits for the top level operations, then sends `name in []`,
which `query_range` rejects with a 400.

The card now sends the widget query directly, and list panels keep only
their paging in the request state.

The logs list stored its page size in that copy, so a query change reset
the request to the widget's page size while the picker kept showing the
user's. It now lives in the paging params and survives a query change.

> The list of logs does not appear to be used by these legacy pages, so
it is likely that this code path is not executed.

This fails `services/detail.spec.ts` TC-04 and `services/list.spec.ts`
TC-02 on #13689, whose timing hits the race on every run.
`GridCardGraph.test.tsx` covers both stale-query cases and the page
size; all three fail without the change.

#### Screenshots

Before:

<img width="894" height="157" alt="image"
src="https://github.com/user-attachments/assets/71a50d88-c49f-4ace-9510-0d40355ec7d0"
/>

After:

<img width="893" height="132" alt="image"
src="https://github.com/user-attachments/assets/2a618cfd-6796-40f9-99a5-aca2436f5fcb"
/>

> No failed requests
2026-11-25 23:52:50 +00:00
Abhi kumar
6921b40467 fix(dashboard): paint the page background in full screen (#13752)
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

- In full screen the dashboard container had no background, so the
browser's black full-screen backdrop showed through in light mode,
hiding the dark section titles.
- The container now paints `--l1-background`, the same surface as the
app shell, in both themes.

Before: 


<img width="3024" height="1964" alt="Screenshot 2026-11-25 at 9 39
43 PM"
src="https://github.com/user-attachments/assets/0f1cf438-a3b7-4323-b532-335fcb0440f6"
/>

After: 

<img width="2056" height="1329" alt="image"
src="https://github.com/user-attachments/assets/9ed6e1dc-9b9f-4ebe-bbad-80494944fd1d"
/>
2026-11-25 17:25:19 +00:00
Vinicius Lourenço
d655a8998b perf(web): load Monaco on the first editor mount (#13686)
#### Description

Since #12515, `src/index.tsx` imports Monaco, so every page loads the
whole editor before it renders. Monaco and our setup (workers, themes,
`loader.config`) now load on the first editor mount. The entry chunk
goes from 10.94 MB to 7.19 MB (2.95 MB to 2.00 MB gzipped).

The hook sits on `@monaco-editor/react`'s loader, not on a wrapper
component, so every editor, including ones added later, gets the bundled
Monaco without changing its import. #12697 takes the wrapper route, and
the editors added or moved since it opened bypass it and can fall back
to the CDN.

Storybook's preview imported the setup directly, so it now imports the
loader as well.

#### Issues closed by this PR

Closes #12692

#### Screenshots / Screen Recordings

ClickHouse query editor, main on top and this branch below:

![ClickHouse query
editor](https://github.com/user-attachments/assets/16f807de-6c51-47f1-85a3-5d3cade864aa)

The 31 editor stories render the same in both themes. The differences
left are the role JSON view race that #13671 fixes and Monaco's overview
ruler drawn a moment later.
2026-11-25 15:42:47 +00:00
Vinicius Lourenço
70ab9c2321 perf(web): load each logs, traces and LLM observability tab when it opens (#13695)
#### Description

Logs, Traces and LLM Observability import all of their tabs up front, so
opening the logs explorer also downloads pipelines, and the traces
explorer downloads funnels. Each tab now loads when it opens, using the
per-tab loading state from #13691. Tab URLs and order stay as they are.

Opening each page's default tab, entry included: LLM Observability goes
from 12.45 MB to 11.80 MB, Logs from 11.63 MB to 11.50 MB and Traces
from 11.75 MB to 11.62 MB. The smaller tabs gain more: funnels drops to
10.97 MB. With the entry PRs in, the page shell alone is 2.55 MB.

Part of #10192

#### Screenshots / Screen Recordings

Switching from the traces explorer to funnels in Storybook, main on the
left, with the network slowed to 1.6 Mbps so the loading state is
visible:


https://github.com/user-attachments/assets/a910cbe8-2db8-431e-95a1-586ba6e0e50d

The 141 logs, traces and LLM observability stories render the same in
both themes; the differences left are live tail offsets, toasts and
loading spinners caught on different frames.
2026-11-25 14:20:48 +00:00
Gaurav Tewari
e085decc05 feat: add support for ai alerts (#13268)
#### Description

Frontend for `AI_TRACES_BASED_ALERT` (backend already supports it,
#12783).

- **Alert type:** "AI Trace-based Alert" card on `/alerts/new`, with its
defaults and alert-type map entries. No docs link until an AI docs page
exists.
- **Editor:** AI alerts open only the AI Query Builder tab (traces, no
trace operator), always in the new editor (classic page and its switch
hidden). Preview, condition query, "Group alerts by" and label-key
checks read the AI slot.
- **Query shape:** the editor keeps AI in its own slot
(`builder_ai_query`), like the dashboard panel editor. It converts to
the wire shape (`builder` + `builder_ai_query` envelopes) only on
preview/save, since a rule's `queryType` must be `builder | promql |
clickhouse_sql`. Saved rules are moved back into the AI slot on edit
(`toAISlotQuery`).
- **Dashboard:** Create Alerts is enabled for AI panels. The link keeps
the AI slot, and the alert page detects AI from the query's `queryType`.
- **History:** the alert popover / top contributors show "View AI
Traces" from `relatedAITracesLink`.

#### Issues closed by this PR


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


#### Screenshots / Screen Recordings



https://github.com/user-attachments/assets/6663a68a-5eea-4920-b30a-205eeba311d3



#### Additional Information

- was Stacked on #13486 (`refactor/ai-explorer-query-type`).
- Not in scope: Create alert from the AI explorer (its query is still in
the tagged shape; to discuss separately)
- SBSHOT -
https://claude.ai/artifact/X2JQRsNXJ8KCNFcmtgFLMd?sk=CHo7GMdRF6MGhUdbE0PkSg

---------

Co-authored-by: Gaurav Tewari <tewarig@users.noreply.github.com>
2026-11-25 13:06:39 +00:00
296 changed files with 9075 additions and 1827 deletions

View File

@@ -10,5 +10,6 @@
- **Use convensional commit format** for commits and PR title.
- **Do not amend the commits once pushed.** Always create a new commit once changes are pushed to remote.
- **Review fixes are new commits too.** A force push hides what changed from human reviewers and makes Greptile post its findings again. Bring in `main` with a merge; only a stacked branch (`gh stack`) rebases, since the stack moves as a unit.
- **A review fix to an AI-owned file fixes its generator too.** A file with the AI-owned banner (story mocks and plays, `tests/e2e/drivers/`) is rewritten by the skill or agent that made it, so a fix made only in the file comes back on the next run. In the same PR, add the lesson to that skill or agent as a concrete case.
- **Answer every Greptile thread.** Reply with the commit that fixes it (`Fixed in 4df6f3198d: <what changed>`) or the reason it stays, then resolve. Never resolve one with neither: Greptile withdraws a finding, and remembers it, only when told why.
- **Leave human review threads to the author.** Fix the code they ask for, but never reply to or resolve a human reviewer's thread.

View File

@@ -110,8 +110,9 @@ await expect(toggle.getAttribute('aria-checked')).toBe(before);
CI runs each play once, with its story's own args. Anyone can flip a control in the panel, and nothing runs the play against that value, so a play that breaks on it goes unnoticed. Write each play so it cannot.
Before writing the clicks, list what has to be on screen for the play's target to exist, and return early when the args take it away. These are the cases plays have missed:
Before writing the clicks, list what has to be on screen for the play's target to exist. Then walk every control the story exposes, the page's own as well as the shared ones, and return early for each value that takes something on that list away. These are the cases plays have missed:
- An arg the story sets. The story sets it because the play needs what that value renders, and the panel can flip it. On the `mine` view the dashboards Created-by filter opens with a tag to remove; on the other views it opens empty and there is no × to click. Check the tag is there by parsing the route the view resolves to.
- The controls every story has. `State` on loading or error renders no rows and no filter suggestions. `Access`, `Permissions` and `Revoked` remove rows, row actions and gated buttons, and the `editor` and `viewer` presets grant telemetry reads only, so a page gated on its own resource shows them nothing. `Check state` on loading disables every gated control, and on error an `AuthZButton` stays enabled while an `AuthZGuardContent` set to fail closed hides what it wraps. `License` and `Banner` decide the plan, so a cloud-only form is gone on the others. `Hold tooltips open` shows a label a second time, inside its tooltip.
- A count at 0. The page can swap its whole list for an empty state, and the header, filters and column picker go with it.
- A view, filter or invalid query that leaves no rows, even when the count is above 0.

View File

@@ -63,7 +63,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: check-semconv-generated-files
@@ -78,7 +78,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: qemu-install
@@ -114,7 +114,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-openapi
@@ -131,7 +131,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-authz
@@ -148,7 +148,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-web-settings
@@ -165,7 +165,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@v5
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
with:
go-version: "1.25"
- name: generate-transaction-groups

View File

@@ -131,6 +131,10 @@ func runGenerateAuthz(_ context.Context) error {
coretypes.NewResourceRef(coretypes.ResourceMetaResourceNotificationChannel).String(): true,
coretypes.NewResourceRef(coretypes.ResourceUser).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceFactorPassword).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionKey).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceIngestionLimit).String(): true,
coretypes.NewResourceRef(coretypes.ResourceMetaResourceAuthDomain).String(): true,
coretypes.NewResourceRef(coretypes.ResourceOrganization).String(): true,
}
allowedTypes := map[string]bool{}

View File

@@ -296,6 +296,8 @@
// Bans msw imports in *.stories.tsx; handlers/mock data belong in the sibling .stories.mocks.tsx
"signoz/no-direct-react-router-import": "error",
// Steers call sites to the src/lib/router facade (allowlisted in overrides below)
"signoz/no-builder-ai-query-access": "error",
// Steers AI slot access to lib/query/builderSlot (allowlisted in overrides below)
"no-restricted-globals": [
"error",
{
@@ -316,6 +318,11 @@
"name": "redux",
"message": "[State mgmt] redux is deprecated. Migrate to Zustand, nuqs, or react-query."
},
{
"name": "@signozhq/design-tokens",
"importNames": ["Style"],
"message": "[bundle] Style is a large object of CSS variable strings and is not tree-shaken. Write the CSS variable directly, for example 'var(--l3-foreground)'."
},
{
"name": "react-redux",
"message": "[State mgmt] react-redux is deprecated. Migrate to Zustand, nuqs, or react-query."
@@ -338,6 +345,11 @@
"importNames": ["patchDashboardV2", "usePatchDashboardV2"],
"message": "[dashboard-v2] Don't call patchDashboardV2/usePatchDashboardV2 directly — use useOptimisticPatch().patchAsync so spec edits update the react-query cache optimistically and reconcile on settle."
},
{
"name": "antd/lib",
"allowTypeImports": true,
"message": "[bundle] antd/lib is the CommonJS root and bundles every antd component. Import from 'antd' instead."
},
{
"name": "motion/react-client",
"message": "[motion] motion/react-client is for React Server Components only. Use 'motion/react' instead — it provides the same exports and works correctly in client-side SPAs."
@@ -560,6 +572,8 @@
"no-restricted-globals": "off",
// Tests need raw localStorage/sessionStorage to seed DOM state for isolation
"signoz/no-zustand-getstate-in-hooks": "off",
"signoz/no-builder-ai-query-access": "off",
// Fixtures build and assert on the raw AI slot
"@typescript-eslint/no-explicit-any": "off", // Tests often need any for mocks/stubs
"@typescript-eslint/explicit-module-boundary-types": "off", // Return types not required in tests
"@typescript-eslint/explicit-function-return-type": "off" // Same as above rule, don't need to care about return type
@@ -616,6 +630,20 @@
"rules": {
"signoz/no-direct-react-router-import": "off"
}
},
{
// builderSlot owns the AI slot; the rest normalise its wire shape or test whether it exists, which the helpers hide
"files": [
"src/lib/query/builderSlot.ts",
"src/hooks/queryBuilder/normalizeCompositeQuery.ts",
"src/hooks/queryBuilder/useGetCompositeQueryParam.ts",
"src/providers/QueryBuilder.tsx",
"src/pages/DashboardPage/DashboardContainer/PanelEditor/hooks/usePanelKindChange.ts",
"src/pages/DashboardPage/DashboardContainer/Panels/utils/seedBuilderForMode.ts"
],
"rules": {
"signoz/no-builder-ai-query-access": "off"
}
}
]
}

View File

@@ -15,8 +15,6 @@
content="frame-src 'self' blob: data:"
/>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script>
// i18n's language detector would pick the browser locale (e.g. `en-US`), which
// /public/locales does not ship; pin it to the bundled language instead.

View File

@@ -21,7 +21,8 @@ import i18n from '../src/ReactI18';
// `src/index.tsx` does this at boot: without it `@monaco-editor/react` falls back
// to its loader default and pulls Monaco from cdn.jsdelivr.net, which msw does
// not report because the requests look like static assets.
import '../src/lib/monaco/setup';
import '../src/lib/monaco/loader';
import '../src/lib/uPlotStylesheet';
import '../src/styles.scss';
@@ -197,7 +198,9 @@ const preview: Preview = {
['Overview', 'Authz'],
'Service Accounts',
'Ingestion',
['Overview', 'Authz'],
'Single Sign-on',
['Overview', 'Authz'],
'Keyboard Shortcuts',
],
'Auth',

View File

@@ -157,7 +157,6 @@
})(document, 'script');
}
</script>
<link rel="stylesheet" href="css/uPlot.min.css" />
<script type="module" src="./src/index.tsx"></script>
</body>
</html>

View File

@@ -13,7 +13,7 @@ const config: Config.InitialOptions = {
moduleFileExtensions: ['ts', 'tsx', 'js', 'json'],
modulePathIgnorePatterns: ['<rootDir>/dist/'],
moduleNameMapper: {
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff)$':
'\\.(png|jpg|jpeg|gif|svg|webp|avif|ico|bmp|tiff|wav)$':
'<rootDir>/__mocks__/fileMock.ts',
// The icon glob module uses `import.meta.glob` (Vite-only); jest can't parse
// it, so redirect any import of it to a stub.

View File

@@ -57,7 +57,7 @@
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/noz-client": "1.13.0",
"@signozhq/ui": "0.4.0-rc.5",
"@signozhq/ui": "0.4.1-rc.2",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",
"@uiw/codemirror-theme-copilot": "4.23.11",

View File

@@ -0,0 +1,59 @@
import { ruleTester } from './rule-tester.mjs';
const message =
'from lib/query/builderSlot instead of accessing builder_ai_query';
await ruleTester({
rule: 'no-builder-ai-query-access',
valid: [
{
name: 'reading through the slot helper',
code: 'export const data = getActiveBuilder(query).queryData;',
},
{
name: 'reading the builder slot',
code: 'export const data = query.builder.queryData;',
},
{
name: 'building a query with the AI slot',
code: 'export const next = { ...query, builder_ai_query: builder };',
},
{
name: 'generated enum member',
code:
'export const type = Querybuildertypesv5QueryTypeDTO.builder_ai_query;',
},
{
name: 'type position',
code: "export type Slot = Query['builder_ai_query'];",
},
],
invalid: [
{
name: 'picking the slot by query type',
code:
'export const data =\n\tquery.queryType === EQueryType.AI_QUERY_BUILDER\n\t\t? query.builder_ai_query?.queryData\n\t\t: query.builder.queryData;',
errors: [{ message, line: 3 }],
},
{
name: 'optional chaining',
code: 'export const slot = query?.builder_ai_query;',
errors: [{ message, line: 1 }],
},
{
name: 'writing the slot',
code: 'query.builder_ai_query = builder;',
errors: [{ message, line: 1 }],
},
{
name: 'bracket access',
code: "export const slot = query['builder_ai_query'];",
errors: [{ message, line: 1 }],
},
{
name: 'destructuring',
code: 'export const { builder_ai_query: slot } = query;',
errors: [{ message, line: 1 }],
},
],
});

View File

@@ -0,0 +1,51 @@
const SLOT = 'builder_ai_query';
function isSlotKey(key, computed) {
if (key.type === 'Literal') {
return key.value === SLOT;
}
return !computed && key.type === 'Identifier' && key.name === SLOT;
}
// Generated enums like Querybuildertypesv5QueryTypeDTO.builder_ai_query are not queries
function isGeneratedEnum(object) {
return object.type === 'Identifier' && /^[A-Z]/.test(object.name);
}
export default {
meta: {
type: 'suggestion',
docs: {
description:
'Disallow direct builder_ai_query access; use the lib/query/builderSlot helpers',
category: 'Query Builder',
},
schema: [],
messages: {
useSlotHelper:
'Use getActiveBuilder, getBuilderBySlotKey or replaceBuilderBySlotKey from lib/query/builderSlot instead of accessing builder_ai_query directly.',
},
},
create(context) {
return {
MemberExpression(node) {
if (
isSlotKey(node.property, node.computed) &&
!isGeneratedEnum(node.object)
) {
context.report({ node, messageId: 'useSlotHelper' });
}
},
ObjectPattern(node) {
node.properties.forEach((property) => {
if (
property.type === 'Property' &&
isSlotKey(property.key, property.computed)
) {
context.report({ node: property, messageId: 'useSlotHelper' });
}
});
},
};
},
};

View File

@@ -20,6 +20,7 @@ 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';
import noDomNodeAccess from './rules/no-dom-node-access.mjs';
import noBuilderAiQueryAccess from './rules/no-builder-ai-query-access.mjs';
export default {
meta: {
@@ -41,5 +42,6 @@ export default {
'no-text-css': noTextCss,
'require-disable-reason': requireDisableReason,
'no-dom-node-access': noDomNodeAccess,
'no-builder-ai-query-access': noBuilderAiQueryAccess,
},
};

View File

@@ -86,8 +86,8 @@ importers:
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@signozhq/ui':
specifier: 0.4.0-rc.5
version: 0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
specifier: 0.4.1-rc.2
version: 0.4.1-rc.2(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@tanstack/react-table':
specifier: 8.21.3
version: 8.21.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
@@ -3258,8 +3258,8 @@ packages:
react: ^18.2.0
react-query: ^3.39.3
'@signozhq/ui@0.4.0-rc.5':
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
'@signozhq/ui@0.4.1-rc.2':
resolution: {integrity: sha512-pCMRzrJ6CmGjEgAQ2B6wRRengP2sy7Y860Npr5nkCapc9NPH5jy4VO48CDv5gnKwWSKShmLHwzbiK2E1cGndKQ==}
peerDependencies:
'@signozhq/design-tokens': '>=2.7.0'
'@signozhq/icons': 0.3.0
@@ -12389,7 +12389,7 @@ snapshots:
react: 18.2.0
react-query: 3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@signozhq/ui@0.4.0-rc.5(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
'@signozhq/ui@0.4.1-rc.2(@date-fns/tz@1.4.1)(@signozhq/design-tokens@2.8.0)(@signozhq/icons@0.4.0)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)':
dependencies:
'@base-ui/react': 1.8.0(@date-fns/tz@1.4.1)(@types/react@18.0.26)(date-fns@4.1.0)(react-dom@18.2.0(react@18.2.0))(react@18.2.0)
'@signozhq/design-tokens': 2.8.0

View File

@@ -1 +0,0 @@
.uplot, .uplot *, .uplot *::before, .uplot *::after {box-sizing: border-box;}.uplot {font-family: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height: 1.5;width: min-content;}.u-title {text-align: center;font-size: 18px;font-weight: bold;}.u-wrap {position: relative;user-select: none;}.u-over, .u-under {position: absolute;}.u-under {overflow: hidden;}.uplot canvas {display: block;position: relative;width: 100%;height: 100%;}.u-axis {position: absolute;}.u-legend {font-size: 14px;margin: auto;text-align: center;}.u-inline {display: block;}.u-inline * {display: inline-block;}.u-inline tr {margin-right: 16px;}.u-legend th {font-weight: 600;}.u-legend th > * {vertical-align: middle;display: inline-block;}.u-legend .u-marker {width: 1em;height: 1em;margin-right: 4px;background-clip: padding-box !important;}.u-inline.u-live th::after {content: ":";vertical-align: middle;}.u-inline:not(.u-live) .u-value {display: none;}.u-series > * {padding: 4px;}.u-series th {cursor: pointer;}.u-legend .u-off > * {opacity: 0.3;}.u-select {background: rgba(0,0,0,0.07);position: absolute;pointer-events: none;}.u-cursor-x, .u-cursor-y {position: absolute;left: 0;top: 0;pointer-events: none;will-change: transform;}.u-hz .u-cursor-x, .u-vt .u-cursor-y {height: 100%;border-right: 1px dashed #607D8B;}.u-hz .u-cursor-y, .u-vt .u-cursor-x {width: 100%;border-bottom: 1px dashed #607D8B;}.u-cursor-pt {position: absolute;top: 0;left: 0;border-radius: 50%;border: 0 solid;pointer-events: none;will-change: transform;/*this has to be !important since we set inline "background" shorthand */background-clip: padding-box !important;}.u-axis.u-off, .u-select.u-off, .u-cursor-x.u-off, .u-cursor-y.u-off, .u-cursor-pt.u-off {display: none;}

View File

@@ -117,6 +117,8 @@
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
"traces_based_alert": "Trace-based Alert",
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
"ai_traces_based_alert": "AI Trace-based Alert",
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
"exceptions_based_alert": "Exceptions-based Alert",
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
"field_unit": "Threshold unit",

View File

@@ -121,6 +121,8 @@
"log_based_alert_desc": "Send a notification when a condition occurs in the logs data.",
"traces_based_alert": "Trace-based Alert",
"traces_based_alert_desc": "Send a notification when a condition occurs in the traces data.",
"ai_traces_based_alert": "AI Trace-based Alert",
"ai_traces_based_alert_desc": "Send a notification when a condition occurs in AI and LLM traces.",
"exceptions_based_alert": "Exceptions-based Alert",
"exceptions_based_alert_desc": "Send a notification when a condition occurs in the exceptions data.",
"field_unit": "Threshold unit",

View File

@@ -175,8 +175,8 @@ function PrivateRoute({ children }: PrivateRouteProps): JSX.Element {
pathname === ROUTES.SETTINGS ||
pathname === ROUTES.BILLING ||
pathname === ROUTES.MEMBERS_SETTINGS ||
(isAdmin &&
(pathname === ROUTES.ORG_SETTINGS || pathname === ROUTES.MY_SETTINGS));
pathname === ROUTES.ORG_SETTINGS ||
(isAdmin && pathname === ROUTES.MY_SETTINGS);
if (
pathname !== ROUTES.WORKSPACE_LOCKED &&

View File

@@ -808,7 +808,7 @@ describe('PrivateRoute', () => {
assertStaysOnRoute(ROUTES.BILLING);
});
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
it('should allow VIEWER to access org-settings when workspace is blocked', () => {
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
@@ -821,7 +821,7 @@ describe('PrivateRoute', () => {
isCloudUser: true,
});
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
});
it('should allow VIEWER to access members settings when workspace is blocked', () => {
@@ -1707,6 +1707,7 @@ describe('PrivateRoute', () => {
// Everything under /settings resolves to the non-exact SETTINGS route
SETTINGS: { path: ROUTES.SETTINGS, deniedRoles: DENIED_ROLES },
MY_SETTINGS: { path: ROUTES.MY_SETTINGS, deniedRoles: DENIED_ROLES },
ORG_SETTINGS: { path: ROUTES.ORG_SETTINGS, deniedRoles: DENIED_ROLES },
ROLES_SETTINGS: { path: ROUTES.ROLES_SETTINGS, deniedRoles: DENIED_ROLES },
ROLE_CREATE: { path: ROUTES.ROLE_CREATE, deniedRoles: DENIED_ROLES },
ROLE_DETAILS: {

Binary file not shown.

View File

@@ -3,7 +3,7 @@ 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} />;
return <Toaster position="top-right" pageInset={PAGE_INSET} />;
}
export default AppToaster;

View File

@@ -0,0 +1,25 @@
.scrollHint {
position: sticky;
bottom: 0;
height: 0;
}
.scrollButton {
position: absolute;
bottom: var(--spacing-7);
left: 50%;
transform: translateX(-50%);
}
.scrollIcon {
animation: pulse 1s infinite;
}
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

View File

@@ -1,129 +0,0 @@
.changelog-modal {
.ant-modal-content {
padding: unset;
background-color: var(--l2-background);
.ant-modal-header {
margin-bottom: unset;
}
.ant-modal-footer {
margin-top: unset;
}
}
&-title {
display: flex;
align-items: center;
gap: 8px;
background-color: var(--l2-background);
padding: 16px;
font-size: 14px;
line-height: 20px;
color: var(--l1-foreground);
border-bottom: 1px solid var(--l1-border);
}
&-footer.scroll-available {
.scroll-btn-container {
display: block;
}
}
&-footer {
position: relative;
border: 1px solid var(--l1-border);
padding: 12px;
display: flex;
align-items: center;
justify-content: space-between;
&-label {
color: var(--text-robin-400);
font-size: 14px;
line-height: 24px;
position: relative;
padding-left: 14px;
&::before {
content: '';
position: absolute;
top: 50%;
left: 0;
transform: translateY(-50%);
width: 6px;
height: 6px;
border-radius: 100%;
background-color: var(--primary-background);
}
}
&-ctas {
display: flex;
margin-left: auto;
& svg {
font-size: 14px;
}
}
.scroll-btn-container {
display: none;
position: absolute;
top: -40px;
left: 50%;
transform: translateX(-50%);
.scroll-btn {
all: unset;
padding: 4px 12px 4px 10px;
background-color: var(--l1-border);
border-radius: 20px;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
gap: 4px;
transition: background-color 0.1s;
&:hover {
background-color: var(--l1-border);
}
&:active {
background-color: var(--l1-border);
}
span {
font-size: 12px;
line-height: 18px;
color: var(--l2-foreground);
}
// add animation to the chevrons down icon
svg {
animation: pulse 1s infinite;
}
}
}
}
&-content {
max-height: calc(100vh - 300px);
overflow-y: auto;
padding: 16px 16px 18px 16px;
border: 1px solid var(--l1-border);
border-top-width: 0;
border-bottom-width: 0;
}
}
// pulse for the scroll for more icon
@keyframes pulse {
0% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}

View File

@@ -1,10 +1,9 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useEffect } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';
import dayjs from 'dayjs';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
@@ -13,8 +12,9 @@ import { ChangelogSchema } from 'types/api/changelog/getChangelogByVersion';
import { UserPreference } from 'types/api/preferences/preference';
import ChangelogRenderer from './components/ChangelogRenderer';
import { useChangelogScroll } from './useChangelogScroll';
import './ChangelogModal.styles.scss';
import styles from './ChangelogModal.module.scss';
interface Props {
changelog: ChangelogSchema;
@@ -22,8 +22,7 @@ interface Props {
}
function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
const [hasScroll, setHasScroll] = useState(false);
const changelogContentSectionRef = useRef<HTMLDivElement>(null);
const { contentRef, hasScroll, scrollForMore } = useChangelogScroll();
const { userPreferences, updateUserPreferenceInContext } = useAppContext();
const formattedReleaseDate = dayjs(changelog?.release_date).format(
@@ -57,30 +56,6 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
updateUserPreferenceInContext,
]);
const checkScroll = useCallback((): void => {
if (changelogContentSectionRef.current) {
const { scrollHeight, clientHeight, scrollTop } =
changelogContentSectionRef.current;
const isAtBottom = scrollHeight - clientHeight - scrollTop <= 8;
setHasScroll(scrollHeight > clientHeight + 24 && !isAtBottom); // 24px - buffer height to show show more
}
}, []);
useEffect(() => {
checkScroll();
const changelogContentSection = changelogContentSectionRef.current;
if (changelogContentSection) {
changelogContentSection.addEventListener('scroll', checkScroll);
}
return (): void => {
if (changelogContentSection) {
changelogContentSection.removeEventListener('scroll', checkScroll);
}
};
}, [checkScroll]);
const onClickUpdateWorkspace = (): void => {
window.open(
'https://signoz.io/upgrade-path',
@@ -89,75 +64,61 @@ function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
);
};
const onClickScrollForMore = (): void => {
if (changelogContentSectionRef.current) {
changelogContentSectionRef.current.scrollTo({
top: changelogContentSectionRef.current.scrollTop + 600, // Scroll 600px from the current position
behavior: 'smooth',
});
}
};
// 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')}
title={
<div className="changelog-modal-title">
<ScrollText size={16} />
What’s New ⎯ Changelog : {formattedReleaseDate}
</div>
}
width={820}
<Dialog
open
onCancel={onClose}
footer={
<div
className={cx('changelog-modal-footer', hasScroll && 'scroll-available')}
>
{!isCloudUser && (
<div className="changelog-modal-footer-ctas">
<Button type="default" onClick={onClose}>
<Flex align="center" gap="4px">
<X size="md" />
Skip for now
</Flex>
</Button>
<Button type="primary" onClick={onClickUpdateWorkspace}>
<Flex align="center" gap="4px">
<Check size="md" />
Update my workspace
</Flex>
</Button>
</div>
)}
{changelog && (
<div className="scroll-btn-container">
<button
data-testid="scroll-more-btn"
type="button"
className="scroll-btn"
onClick={onClickScrollForMore}
>
<ChevronsDown size={14} />
<span>Scroll for more</span>
</button>
</div>
)}
</div>
onClose={onClose}
title={`What’s New ⎯ Changelog : ${formattedReleaseDate}`}
titleIcon={<ScrollText size={16} />}
width="extra-wide"
testId="changelog-dialog"
footerSuffix={
isCloudUser ? undefined : (
<>
<Button
variant="outlined"
color="secondary"
size="md"
prefix={<X size={12} />}
onClick={onClose}
testId="changelog-skip-btn"
>
Skip for now
</Button>
<Button
variant="solid"
color="primary"
size="md"
prefix={<Check size={12} />}
onClick={onClickUpdateWorkspace}
testId="changelog-update-btn"
>
Update my workspace
</Button>
</>
)
}
>
<div
className="changelog-modal-content"
data-testid="changelog-content"
ref={changelogContentSectionRef}
>
{changelog && <ChangelogRenderer changelog={changelog} />}
<div data-testid="changelog-content" ref={contentRef}>
<ChangelogRenderer changelog={changelog} />
</div>
</Modal>
{hasScroll && (
<div className={styles.scrollHint}>
<div className={styles.scrollButton}>
<Button
variant="solid"
color="primary"
size="sm"
prefix={<ChevronsDown size={14} className={styles.scrollIcon} />}
onClick={scrollForMore}
testId="scroll-more-btn"
>
Scroll for more
</Button>
</div>
</div>
)}
</Dialog>
);
}

View File

@@ -1,12 +1,23 @@
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { fireEvent, render, screen } from '@testing-library/react';
import { ReactNode } from 'react';
import { USER_PREFERENCES } from 'constants/userPreferences';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
import { IAppContext } from 'providers/App/types';
import {
fireEvent,
getAppContextMock,
render,
screen,
userEvent,
waitFor,
} from 'tests/test-utils';
import {
ChangelogSchema,
DeploymentType,
} from 'types/api/changelog/getChangelogByVersion';
import {
LicensePlatform,
LicenseResModel,
} from 'types/api/licensesV3/getActive';
import { UserPreference } from 'types/api/preferences/preference';
import ChangelogModal from '../ChangelogModal';
@@ -40,71 +51,165 @@ const mockChangelog: ChangelogSchema = {
jest.mock(
'react-markdown',
() =>
function ReactMarkdown({ children }: any) {
function ReactMarkdown({ children }: { children: ReactNode }): JSX.Element {
return <div>{children}</div>;
},
);
// mock useAppContext
jest.mock('providers/App/App', () => ({
useAppContext: jest.fn(() => ({
updateUserPreferenceInContext: jest.fn(),
userPreferences: [
{
name: USER_PREFERENCES.LAST_SEEN_CHANGELOG_VERSION,
value: 'v1.0.0',
},
],
})),
}));
function renderChangelog(onClose: () => void = jest.fn()): void {
const seenChangelogVersion: UserPreference = {
name: USER_PREFERENCES.LAST_SEEN_CHANGELOG_VERSION,
description: '',
valueType: 'string',
defaultValue: '',
allowedValues: [],
allowedScopes: ['user'],
value: 'v1.0.0',
};
const selfHostedContext: Partial<IAppContext> = {
activeLicense: {
...(getAppContextMock('ADMIN').activeLicense as LicenseResModel),
platform: LicensePlatform.SELF_HOSTED,
},
};
function renderChangelog(
onClose: () => void = jest.fn(),
appContextOverrides: Partial<IAppContext> = {},
): void {
render(
<MockQueryClientProvider>
<ChangelogModal changelog={mockChangelog} onClose={onClose} />
</MockQueryClientProvider>,
<ChangelogModal changelog={mockChangelog} onClose={onClose} />,
undefined,
{
appContextOverrides: {
userPreferences: [seenChangelogVersion],
...appContextOverrides,
},
},
);
}
describe('ChangelogModal', () => {
it('renders modal with changelog data', () => {
it('renders the dialog with the changelog data', async () => {
renderChangelog();
expect(
screen.getByText('What’s New ⎯ Changelog : June 10, 2025'),
).toBeInTheDocument();
await expect(
screen.findByTestId('changelog-dialog-title'),
).resolves.toHaveTextContent('What’s New ⎯ Changelog : June 10, 2025');
expect(screen.getByText('Feature 1')).toBeInTheDocument();
expect(screen.getByText('Description for feature 1')).toBeInTheDocument();
expect(screen.getByText('Bug fix details')).toBeInTheDocument();
expect(screen.getByText('Maintenance details')).toBeInTheDocument();
});
it('calls onClose when Skip for now is clicked', () => {
it('calls onClose when the close button is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderChangelog(onClose);
fireEvent.click(screen.getByText('Skip for now'));
expect(onClose).toHaveBeenCalled();
await user.click(await screen.findByTestId('changelog-dialog-close'));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('opens migration docs when Update my workspace is clicked', () => {
window.open = jest.fn();
it('offers no upgrade actions to a cloud workspace', async () => {
renderChangelog();
fireEvent.click(screen.getByText('Update my workspace'));
expect(window.open).toHaveBeenCalledWith(
await screen.findByTestId('changelog-content');
expect(
screen.queryByTestId('changelog-dialog-footer'),
).not.toBeInTheDocument();
expect(screen.queryByTestId('changelog-skip-btn')).not.toBeInTheDocument();
expect(screen.queryByTestId('changelog-update-btn')).not.toBeInTheDocument();
});
it('calls onClose when Skip for now is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onClose = jest.fn();
renderChangelog(onClose, selfHostedContext);
await user.click(await screen.findByTestId('changelog-skip-btn'));
expect(onClose).toHaveBeenCalledTimes(1);
});
it('opens migration docs when Update my workspace is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
renderChangelog(jest.fn(), selfHostedContext);
await user.click(await screen.findByTestId('changelog-update-btn'));
expect(open).toHaveBeenCalledWith(
'https://signoz.io/upgrade-path',
'_blank',
'noopener,noreferrer',
);
open.mockRestore();
});
it('scrolls for more when Scroll for more is clicked', () => {
renderChangelog();
const scrollBtn = screen.getByTestId('scroll-more-btn');
const contentDiv = screen.getByTestId('changelog-content');
if (contentDiv) {
contentDiv.scrollTo = jest.fn();
}
fireEvent.click(scrollBtn);
if (contentDiv) {
expect(contentDiv.scrollTo).toHaveBeenCalled();
}
describe('scroll for more', () => {
let scrollHeight: jest.SpyInstance;
let clientHeight: jest.SpyInstance;
beforeEach(() => {
scrollHeight = jest.spyOn(Element.prototype, 'scrollHeight', 'get');
clientHeight = jest.spyOn(Element.prototype, 'clientHeight', 'get');
});
afterEach(() => {
scrollHeight.mockRestore();
clientHeight.mockRestore();
});
it('is hidden while the content fits', async () => {
scrollHeight.mockReturnValue(400);
clientHeight.mockReturnValue(400);
renderChangelog();
await screen.findByTestId('changelog-content');
expect(screen.queryByTestId('scroll-more-btn')).not.toBeInTheDocument();
});
it('scrolls 600px further from the current position when clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
scrollHeight.mockReturnValue(2000);
clientHeight.mockReturnValue(400);
renderChangelog();
const content = await screen.findByTestId('changelog-dialog-body');
Object.defineProperty(content, 'scrollTop', {
value: 100,
configurable: true,
});
const scrollTo = jest.fn();
Object.defineProperty(content, 'scrollTo', { value: scrollTo });
await user.click(await screen.findByTestId('scroll-more-btn'));
expect(scrollTo).toHaveBeenCalledWith({
top: 700,
behavior: 'smooth',
});
});
it('hides once the content is scrolled to the bottom', async () => {
scrollHeight.mockReturnValue(1000);
clientHeight.mockReturnValue(400);
renderChangelog();
const content = await screen.findByTestId('changelog-dialog-body');
await screen.findByTestId('scroll-more-btn');
Object.defineProperty(content, 'scrollTop', {
value: 600,
configurable: true,
});
fireEvent.scroll(content);
await waitFor(() =>
expect(screen.queryByTestId('scroll-more-btn')).not.toBeInTheDocument(),
);
});
});
});

View File

@@ -34,7 +34,7 @@
&-line {
position: absolute;
left: 0;
left: 3px;
top: 6px;
bottom: -30px;
width: 1px;

View File

@@ -0,0 +1,52 @@
import { useCallback, useEffect, useState } from 'react';
const SCROLL_STEP_PX = 600;
const MIN_OVERFLOW_PX = 24;
const BOTTOM_TOLERANCE_PX = 8;
interface UseChangelogScrollReturn {
contentRef: (node: HTMLDivElement | null) => void;
hasScroll: boolean;
scrollForMore: () => void;
}
export function useChangelogScroll(): UseChangelogScrollReturn {
const [content, setContent] = useState<HTMLElement | null>(null);
const [hasScroll, setHasScroll] = useState(false);
const checkScroll = useCallback((): void => {
if (!content) {
return;
}
const { scrollHeight, clientHeight, scrollTop } = content;
const isAtBottom =
scrollHeight - clientHeight - scrollTop <= BOTTOM_TOLERANCE_PX;
setHasScroll(scrollHeight > clientHeight + MIN_OVERFLOW_PX && !isAtBottom);
}, [content]);
useEffect(() => {
if (!content) {
return undefined;
}
checkScroll();
content.addEventListener('scroll', checkScroll);
return (): void => {
content.removeEventListener('scroll', checkScroll);
};
}, [content, checkScroll]);
const scrollForMore = useCallback((): void => {
content?.scrollTo({
top: content.scrollTop + SCROLL_STEP_PX,
behavior: 'smooth',
});
}, [content]);
// The dialog body owns the scroll; a second scroller inside it shows two scrollbars.
const contentRef = useCallback((node: HTMLDivElement | null): void => {
setContent(node?.closest<HTMLElement>('[data-slot="dialog-body"]') ?? null);
}, []);
return { contentRef, hasScroll, scrollForMore };
}

View File

@@ -14,14 +14,14 @@ export type CreatedByProps =
creatorOptions: CreatorOption[];
createdBy: string[];
onCreatedByChange: (emails: string[]) => void;
// Clear all Created-by selections and run immediately.
onClearCreatedBy: () => void;
// Run a Created-by change made with the dropdown closed.
onCreatedByCommit: (emails: string[]) => void;
}
| {
creatorOptions?: undefined;
createdBy?: undefined;
onCreatedByChange?: undefined;
onClearCreatedBy?: undefined;
onCreatedByCommit?: undefined;
};
type Props = CreatedByProps & {
@@ -61,8 +61,8 @@ function FilterChips(props: Props): JSX.Element {
placeholder="Created by"
testId={`${testIdPrefix}-filter-created-by`}
disabled={disabled}
onClear={props.onClearCreatedBy}
onChange={props.onCreatedByChange}
onCommit={props.onCreatedByCommit}
onDropdownVisibleChange={runOnClose}
/>
)}

View File

@@ -81,7 +81,7 @@ function FilterZone({
applyDraft,
handleCreatedByChange,
handleUpdatedChange,
handleClearCreatedBy,
handleCreatedByCommit,
handleClear,
} = useFilterZoneDraft({
query,
@@ -96,7 +96,7 @@ function FilterZone({
creatorOptions,
createdBy: reflected.createdBy,
onCreatedByChange: handleCreatedByChange,
onClearCreatedBy: handleClearCreatedBy,
onCreatedByCommit: handleCreatedByCommit,
}
: {};

View File

@@ -1,3 +1,4 @@
import { useCallback, useState } from 'react';
import { ConfigProvider, Select } from 'antd';
import { Checkbox } from '@signozhq/ui/checkbox';
import cx from 'classnames';
@@ -20,7 +21,9 @@ interface Props {
placeholder: string;
testId: string;
onChange: (values: string[]) => void;
onClear?: () => void;
// A change made with the dropdown closed (a tag's ×, the clear icon) has no
// close to run on, so it is committed here instead of staged via onChange.
onCommit: (values: string[]) => void;
onDropdownVisibleChange?: (open: boolean) => void;
disabled?: boolean;
}
@@ -31,10 +34,31 @@ function MultiSelectFilter({
placeholder,
testId,
onChange,
onClear,
onCommit,
onDropdownVisibleChange,
disabled = false,
}: Props): JSX.Element {
const [isOpen, setIsOpen] = useState(false);
const handleChange = useCallback(
(next: string[]): void => {
if (!isOpen) {
onCommit(next);
return;
}
onChange(next);
},
[isOpen, onChange, onCommit],
);
const handleDropdownVisibleChange = useCallback(
(nextOpen: boolean): void => {
setIsOpen(nextOpen);
onDropdownVisibleChange?.(nextOpen);
},
[onDropdownVisibleChange],
);
return (
<ConfigProvider theme={CHECKBOX_SELECT_THEME}>
<Select
@@ -51,7 +75,6 @@ function MultiSelectFilter({
menuItemSelectedIcon={null}
data-testid={testId}
disabled={disabled}
onClear={onClear}
optionRender={(option): JSX.Element => (
<div
className={styles.checkOption}
@@ -66,8 +89,8 @@ function MultiSelectFilter({
<span className={styles.checkOptionLabel}>{option.label}</span>
</div>
)}
onChange={(next): void => onChange(next as string[])}
onDropdownVisibleChange={onDropdownVisibleChange}
onChange={(next): void => handleChange(next as string[])}
onDropdownVisibleChange={handleDropdownVisibleChange}
/>
</ConfigProvider>
);

View File

@@ -1,4 +1,5 @@
import { render, screen } from 'tests/test-utils';
import userEvent from '@testing-library/user-event';
import { render, screen, within } from 'tests/test-utils';
import type { DslGrammar } from '../../dsl/types';
import FilterZone from '../FilterZone';
@@ -47,4 +48,33 @@ describe('FilterZone', () => {
).not.toBeInTheDocument();
expect(screen.getByTestId('things-filter-updated')).toBeInTheDocument();
});
it('runs the query when a creator is removed with the dropdown closed', async () => {
const user = userEvent.setup();
const onQueryChange = jest.fn();
render(
<FilterZone
query="created_by = 'ada@example.com'"
grammar={grammar}
testIdPrefix="things"
creatorOptions={[{ email: 'ada@example.com', label: 'Ada' }]}
source={source}
onQueryChange={onQueryChange}
/>,
);
// antd renders the tag's × aria-hidden.
await user.click(
within(screen.getByTitle('Ada')).getByRole('img', {
name: 'close',
hidden: true,
}),
);
expect(
within(screen.getByTestId('things-filter-created-by')).getByRole('combobox'),
).toHaveAttribute('aria-expanded', 'false');
expect(onQueryChange).toHaveBeenCalledWith('');
});
});

View File

@@ -106,12 +106,20 @@ describe('useFilterZoneDraft', () => {
"created_by = 'a@x.io' AND name = 'x'",
);
act(() => result.current.handleClearCreatedBy());
act(() => result.current.handleCreatedByCommit([]));
expect(result.current.draft).toBe("name = 'x'");
expect(onQueryChange).toHaveBeenCalledWith("name = 'x'");
});
it('runs the remaining creators when one is removed', () => {
const { result, onQueryChange } = setup("created_by IN ['a@x.io', 'b@x.io']");
act(() => result.current.handleCreatedByCommit(['b@x.io']));
expect(onQueryChange).toHaveBeenCalledWith("created_by = 'b@x.io'");
});
it('empties the draft and runs the empty query on clear', () => {
const { result, onQueryChange, onCleared, onClearAll } = setup();

View File

@@ -31,7 +31,7 @@ interface FilterZoneDraft {
applyDraft: (next: string) => void;
handleCreatedByChange: (emails: string[]) => void;
handleUpdatedChange: (window: UpdatedWindow) => void;
handleClearCreatedBy: () => void;
handleCreatedByCommit: (emails: string[]) => void;
handleClear: () => void;
}
@@ -97,10 +97,14 @@ export function useFilterZoneDraft({
[draft, applyDraft, onFilterApplied],
);
// Clear-all on the Created-by select removes its clause and runs immediately.
const handleClearCreatedBy = useCallback((): void => {
applyDraft(spliceClause(draft, 'created_by', null));
}, [draft, applyDraft]);
// Runs a Created-by change made with its dropdown closed.
const handleCreatedByCommit = useCallback(
(emails: string[]): void => {
onFilterApplied?.('createdBy', { valueCount: emails.length });
applyDraft(spliceClause(draft, 'created_by', createdByClause(emails)));
},
[draft, applyDraft, onFilterApplied],
);
// Clear resets the draft and runs immediately (empty query).
const handleClear = useCallback((): void => {
@@ -122,7 +126,7 @@ export function useFilterZoneDraft({
applyDraft,
handleCreatedByChange,
handleUpdatedChange,
handleClearCreatedBy,
handleCreatedByCommit,
handleClear,
};
}

View File

@@ -24,6 +24,7 @@ interface Props {
confirmLabel: string;
/** Name the input holds each time the dialog opens. */
initialName?: string;
placeholder: string;
testIdPrefix: string;
}
@@ -35,6 +36,7 @@ function ViewNameDialog({
description,
confirmLabel,
initialName = '',
placeholder,
testIdPrefix,
}: Props): JSX.Element {
const [name, setName] = useState(initialName);
@@ -116,7 +118,7 @@ function ViewNameDialog({
id={inputId}
value={name}
maxLength={VIEW_NAME_MAX_LENGTH}
placeholder="e.g. Prod alerts"
placeholder={placeholder}
autoComplete="off"
testId={`${testIdPrefix}-name`}
onChange={(e: ChangeEvent<HTMLInputElement>): void =>

View File

@@ -39,6 +39,7 @@ interface Props {
saveTestIdPrefix?: string;
renameTestIdPrefix?: string;
customSectionLabel?: string;
viewNamePlaceholder?: string;
deleteDescription?: string;
/** Wraps the rail body, e.g. in an authz guard. */
guard?: (content: ReactElement) => ReactElement;
@@ -67,6 +68,7 @@ function ViewsRail({
saveTestIdPrefix = 'save-view',
renameTestIdPrefix = 'rename-view',
customSectionLabel = 'My views',
viewNamePlaceholder = 'e.g. Production',
deleteDescription = 'This removes the saved view.',
guard,
onViewSaved,
@@ -287,6 +289,7 @@ function ViewsRail({
title="Save as view"
description="Save the current filters as a view you can return to."
confirmLabel="Save view"
placeholder={viewNamePlaceholder}
testIdPrefix={saveTestIdPrefix}
/>
<ViewNameDialog
@@ -297,6 +300,7 @@ function ViewsRail({
description="The view keeps its filters under the new name."
confirmLabel="Rename"
initialName={renameTarget?.label}
placeholder={viewNamePlaceholder}
testIdPrefix={renameTestIdPrefix}
/>
{contextHolder}

View File

@@ -163,6 +163,22 @@ describe('ViewsRail', () => {
);
});
it('shows the list placeholder in the save and rename dialogs', async () => {
const user = userEvent.setup();
renderRail({ viewNamePlaceholder: 'e.g. Prod things' });
await user.click(screen.getByTestId(`${PREFIX}-view-save-trigger`));
await expect(
screen.findByTestId('save-view-name-field'),
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
await user.click(screen.getByTestId('save-view-cancel'));
await user.click(screen.getByTestId(`${PREFIX}-view-rename-view-1`));
await expect(
screen.findByTestId('rename-view-name-field'),
).resolves.toHaveAttribute('placeholder', 'e.g. Prod things');
});
it('opens the save dialog empty again after a cancel', async () => {
const user = userEvent.setup();
const props = renderRail({ isModified: true });

View File

@@ -105,6 +105,8 @@ const stopEventsExtension = EditorView.domEventHandlers({
},
});
const EDITOR_BASIC_SETUP = { lineNumbers: false };
interface QuerySearchProps {
placeholder?: string;
onChange: (value: string) => void;
@@ -713,14 +715,17 @@ function QuerySearch({
}
}, []);
const handleChange = (value: string): void => {
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const handleChange = useCallback((value: string): void => {
if (isProgrammaticChangeRef.current) {
isProgrammaticChangeRef.current = false;
return;
}
onChange(value);
};
onChangeRef.current(value);
}, []);
const handleBlur = (): void => {
const currentExpression = getCurrentExpression();
@@ -1474,6 +1479,65 @@ function QuerySearch({
};
}
const completionSourceRef = useRef(combinedSuggestions);
completionSourceRef.current = combinedSuggestions;
const handleRunRef = useRef(handleRun);
handleRunRef.current = handleRun;
// Built once: new extensions reconfigure CodeMirror, which closes the open suggestions.
const editorExtensions = useMemo(
() => [
autocompletion({
override: [
(context: CompletionContext): CompletionResult | null =>
completionSourceRef.current(context),
],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,
stopEventsExtension,
Prec.highest(
keymap.of([
...completionKeymap,
{
key: 'Escape',
run: closeCompletion,
},
{
key: 'Enter',
preventDefault: true,
// Prevent default behavior of Enter to add new line
// and instead run a custom action
run: (): boolean => true,
},
{
key: 'Mod-Enter',
preventDefault: true,
// Prevent default behavior of Mod-Enter to add new line
// and instead run a custom action
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
run: (): boolean => {
handleRunRef.current();
return true;
},
},
{
key: 'Shift-Enter',
preventDefault: true,
// Prevent default behavior of Shift-Enter to add new line
run: (): boolean => true,
},
]),
),
],
[],
);
// Effect to handle focus state and trigger suggestions
useEffect(() => {
const clearTimeout = toggleSuggestions(10);
@@ -1650,56 +1714,9 @@ function QuerySearch({
hasErrors: validation.errors.length > 0,
hasInitialExpression: isScopedFilter && !showScopeChip,
})}
extensions={[
autocompletion({
override: [combinedSuggestions],
defaultKeymap: true,
closeOnBlur: true,
activateOnTyping: true,
maxRenderedOptions: 50,
addToOptions: [{ render: renderRecentDeleteButton, position: 100 }],
}),
javascript({ jsx: false, typescript: false }),
EditorView.lineWrapping,
stopEventsExtension,
Prec.highest(
keymap.of([
...completionKeymap,
{
key: 'Escape',
run: closeCompletion,
},
{
key: 'Enter',
preventDefault: true,
// Prevent default behavior of Enter to add new line
// and instead run a custom action
run: (): boolean => true,
},
{
key: 'Mod-Enter',
preventDefault: true,
// Prevent default behavior of Mod-Enter to add new line
// and instead run a custom action
// Mod-Enter is usually Ctrl-Enter or Cmd-Enter based on OS
run: (): boolean => {
handleRun();
return true;
},
},
{
key: 'Shift-Enter',
preventDefault: true,
// Prevent default behavior of Shift-Enter to add new line
run: (): boolean => true,
},
]),
),
]}
extensions={editorExtensions}
placeholder={placeholder}
basicSetup={{
lineNumbers: false,
}}
basicSetup={EDITOR_BASIC_SETUP}
onFocus={(): void => {
setIsFocused(true);
}}

View File

@@ -192,6 +192,8 @@ describe('QuerySearch (Integration with Real CodeMirror)', () => {
release();
// Outlasts the 10 ms timer QuerySearch uses to reopen suggestions.
await act(() => new Promise((resolve) => setTimeout(resolve, 50)));
// Outlasts the 100 ms CodeMirror waits before it queries suggestions again.
await new Promise((resolve) => setTimeout(resolve, 150));
expect(screen.getByText('payment-service')).toBeInTheDocument();
});

View File

@@ -1,5 +1,3 @@
import { useState } from 'react';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import { ChevronDown, ChevronRight, Undo2 } from '@signozhq/icons';
@@ -22,31 +20,6 @@ export function CheckboxFilterV2Header({
onToggleOpen,
onClear,
}: CheckboxFilterHeaderProps): JSX.Element {
const [isTitleTruncated, setIsTitleTruncated] = useState(false);
const measureTitle = (el: HTMLElement | null): void => {
if (el) {
setIsTitleTruncated(el.scrollWidth > el.clientWidth);
}
};
const titleText = (
<Typography
ref={measureTitle}
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
display="inline-block"
minWidth={0}
textOverflow="ellipsis"
textTransform="capitalize"
>
{title}
</Typography>
);
return (
<section
role="button"
@@ -67,7 +40,19 @@ export function CheckboxFilterV2Header({
) : (
<ChevronRight size={13} cursor="pointer" />
)}
<Tooltip title={isTitleTruncated ? title : undefined}>{titleText}</Tooltip>
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
display="inline-block"
minWidth={0}
textOverflow="ellipsis"
textTransform="capitalize"
>
{title}
</Typography>
</section>
{isOpen && canReset && (
<section className={styles.rightAction}>

View File

@@ -120,43 +120,4 @@ describe('CheckboxFilterV2Header', () => {
expect(onToggleOpen).not.toHaveBeenCalled();
});
});
describe('title tooltip', () => {
// jsdom has no layout, so truncation is simulated at the prototype level
// before mount (the component measures in a layout effect).
function mockTitleWidths(scrollWidth: number, clientWidth: number): void {
jest
.spyOn(HTMLElement.prototype, 'scrollWidth', 'get')
.mockReturnValue(scrollWidth);
jest
.spyOn(HTMLElement.prototype, 'clientWidth', 'get')
.mockReturnValue(clientWidth);
}
afterEach(() => {
jest.restoreAllMocks();
});
it('shows the full name on hover when the title is truncated', async () => {
mockTitleWidths(200, 100);
const user = userEvent.setup();
render(<CheckboxFilterV2Header {...defaultProps} />);
await user.hover(screen.getByText(defaultProps.title));
await expect(screen.findByRole('tooltip')).resolves.toHaveTextContent(
defaultProps.title,
);
});
it('shows no tooltip when the title fits', async () => {
mockTitleWidths(100, 100);
const user = userEvent.setup();
render(<CheckboxFilterV2Header {...defaultProps} />);
await user.hover(screen.getByText(defaultProps.title));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
});
});
});

View File

@@ -114,6 +114,19 @@ export const loadingFiltersHandlers = [
),
];
export const longTitleConfig = [
{
attributeKey: {
dataType: DataTypes.Int64,
key: 'http.request.content_length_uncompressed',
type: 'tag',
},
defaultOpen: false,
title: 'Http Request Content Length Uncompressed',
type: FiltersType.CHECKBOX,
},
];
export const LONG_FILTER_VALUES = [
'checkout-service.production-eu-central-1.svc.cluster.local',
'payments-authorisation-worker.production-us-east-2.svc.cluster.local',

View File

@@ -8,6 +8,7 @@ import type { GlobalMockArgs } from '@/storybook/globals';
import QuickFilters from '../QuickFilters';
import {
dirtySettings,
hoverTruncatedTitle,
openQueryPicker,
openSettings,
} from './__story_mockdata__/quickFilters.play';
@@ -18,6 +19,7 @@ import {
handlers,
LONG_FILTER_VALUES,
loadingFiltersHandlers,
longTitleConfig,
MANY_FILTER_VALUES,
queryBuilder,
selectedServiceQueryBuilder,
@@ -159,6 +161,15 @@ export const Tooltips: GlobalArgsStory = {
},
};
/** A section title too long for the rail: hovering it shows the full title once. */
export const TruncatedTitle: GlobalArgsStory = {
args: { config: longTitleConfig },
parameters: {
msw: { handlers: [noSavedFiltersHandler, ...handlers] },
},
play: hoverTruncatedTitle,
};
const [firstQuery] = queryBuilder.currentQuery.builder.queryData;
/** Interaction: the query picker lists every query the filters can follow. */

View File

@@ -8,9 +8,12 @@ import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissio
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import { hoverTruncatableText } from '@/storybook/play/truncatedText';
import type { GlobalMockArgs } from '@/storybook/globals';
import type QuickFilters from '../../QuickFilters';
import { longTitleConfig } from '../QuickFilters.stories.mocks';
import { FiltersType } from '../../types';
interface PlayContext {
canvasElement: HTMLElement;
@@ -61,6 +64,26 @@ export const dirtySettings = async (context: PlayContext): Promise<void> => {
await screen.findByRole('button', { name: 'Save changes' });
};
export const hoverTruncatedTitle = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const [filter] = args.config ?? [];
// Duration and slider sections render no title of their own.
if (filter?.type !== FiltersType.CHECKBOX || !filter.title) {
return;
}
const [label] = await within(canvasElement).findAllByText(
filter.title,
{},
UNTIL_LOADED,
);
await hoverTruncatableText(label, filter.title, {
cut: filter.title === longTitleConfig[0].title || undefined,
});
};
export const openQueryPicker = async ({
canvasElement,
}: PlayContext): Promise<void> => {

View File

@@ -0,0 +1,17 @@
import { RuletypesAlertTypeDTO } from 'api/generated/services/sigNoz.schemas';
import { DataSource } from 'types/common/queryBuilder';
import { dataSourceForAlertType } from '../alerts';
describe('dataSourceForAlertType', () => {
it.each([
[RuletypesAlertTypeDTO.METRIC_BASED_ALERT, DataSource.METRICS],
[RuletypesAlertTypeDTO.LOGS_BASED_ALERT, DataSource.LOGS],
[RuletypesAlertTypeDTO.TRACES_BASED_ALERT, DataSource.TRACES],
[RuletypesAlertTypeDTO.EXCEPTIONS_BASED_ALERT, DataSource.TRACES],
[RuletypesAlertTypeDTO.AI_TRACES_BASED_ALERT, DataSource.TRACES],
[undefined, DataSource.METRICS],
])('maps %s to %s', (alertType, dataSource) => {
expect(dataSourceForAlertType(alertType)).toBe(dataSource);
});
});

View File

@@ -8,6 +8,7 @@ export const ALERTS_DATA_SOURCE_MAP: Record<AlertTypes, DataSource> = {
[AlertTypes.LOGS_BASED_ALERT]: DataSource.LOGS,
[AlertTypes.TRACES_BASED_ALERT]: DataSource.TRACES,
[AlertTypes.EXCEPTIONS_BASED_ALERT]: DataSource.TRACES,
[AlertTypes.AI_TRACES_BASED_ALERT]: DataSource.TRACES,
};
export function dataSourceForAlertType(
@@ -18,6 +19,7 @@ export function dataSourceForAlertType(
return DataSource.LOGS;
case RuletypesAlertTypeDTO.TRACES_BASED_ALERT:
case RuletypesAlertTypeDTO.EXCEPTIONS_BASED_ALERT:
case RuletypesAlertTypeDTO.AI_TRACES_BASED_ALERT:
return DataSource.TRACES;
default:
return DataSource.METRICS;

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react';
import { useCallback, useEffect } from 'react';
import { createPortal } from 'react-dom';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
@@ -6,17 +6,13 @@ import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { History, Maximize2, Minus, Plus, X } from '@signozhq/icons';
import { Maximize2, Minus, X } from '@signozhq/icons';
import logEvent from 'api/common/logEvent';
import HistorySidebar from '../components/ConversationsList';
import ConversationView from '../ConversationView';
import { AIAssistantEvents, AIAssistantOpenSource } from '../events';
import {
normalizePage,
useAIAssistantAnalyticsContext,
} from '../hooks/useAIAssistantAnalyticsContext';
import { normalizePage } from '../hooks/useAIAssistantAnalyticsContext';
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
@@ -34,7 +30,6 @@ import styles from './AIAssistantModal.module.scss';
// eslint-disable-next-line sonarjs/cognitive-complexity
export default function AIAssistantModal(): JSX.Element | null {
const { pathname, search } = useAppLocation();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isModalOpen);
const activeConversationId = useAIAssistantStore(
@@ -47,13 +42,11 @@ export default function AIAssistantModal(): JSX.Element | null {
const startNewConversation = useAIAssistantStore(
(s) => s.startNewConversation,
);
const analyticsCtx = useAIAssistantAnalyticsContext();
useEffect(() => {
const handleKeyDown = (e: KeyboardEvent): void => {
// Cmd+J (Mac) / Ctrl+J (Win/Linux) — toggle modal. Opening
// always starts a brand-new conversation; resuming earlier
// threads is done via the in-modal history sidebar.
// always starts a brand-new conversation.
if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'j') {
// Don't intercept Cmd+J inside input/textarea — those are for the user
const tag = (e.target as HTMLElement).tagName;
@@ -66,7 +59,6 @@ export default function AIAssistantModal(): JSX.Element | null {
closeModal();
} else {
startNewConversation();
setShowHistory(false);
void logEvent(AIAssistantEvents.Opened, {
source: AIAssistantOpenSource.Shortcut,
currentPage: normalizePage(pathname),
@@ -102,29 +94,6 @@ export default function AIAssistantModal(): JSX.Element | null {
);
}, [activeConversationId, closeModal, pathname, search]);
const handleNew = useCallback(() => {
void logEvent(AIAssistantEvents.NewChatClicked, {
...analyticsCtx,
// useAIAssistantAnalyticsContext() runs above this component's
// VariantContext.Provider, so the hook reports the default 'page'
// mode. Override here: the modal collapses to 'sidepane' in our
// taxonomy alongside the drawer.
mode: 'sidepane',
source: 'header',
});
startNewConversation();
setShowHistory(false);
}, [startNewConversation, analyticsCtx]);
const handleHistorySelect = useCallback(() => {
setShowHistory(false);
}, []);
const handleMinimize = useCallback(() => {
minimizeModal();
setShowHistory(false);
}, [minimizeModal]);
const handleBackdropClick = useCallback(
(e: React.MouseEvent<HTMLDivElement>) => {
// Only close when clicking the backdrop itself, not the modal card
@@ -173,33 +142,6 @@ export default function AIAssistantModal(): JSX.Element | null {
</div>
<div className={styles.actions}>
<Tooltip title={showHistory ? 'Back to chat' : 'Conversations'}>
<Button
variant="ghost"
size="sm"
icon
color="secondary"
onClick={(): void => setShowHistory((v) => !v)}
aria-label="Toggle conversations"
aria-pressed={showHistory}
>
<History size={14} />
</Button>
</Tooltip>
<Tooltip title="New conversation">
<Button
variant="ghost"
size="sm"
icon
color="secondary"
onClick={handleNew}
aria-label="New conversation"
>
<Plus size={14} />
</Button>
</Tooltip>
<Tooltip title="Open full screen">
<Button
disabledTooltip="Start a conversation first"
@@ -221,7 +163,7 @@ export default function AIAssistantModal(): JSX.Element | null {
size="sm"
icon
color="secondary"
onClick={handleMinimize}
onClick={minimizeModal}
aria-label="Minimize to side panel"
>
<Minus size={14} />
@@ -245,12 +187,8 @@ export default function AIAssistantModal(): JSX.Element | null {
{/* Body */}
<div className={styles.body}>
{showHistory ? (
<HistorySidebar onSelect={handleHistorySelect} />
) : (
activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)
{activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)}
</div>
</div>

View File

@@ -1,4 +1,4 @@
import { useCallback, useState } from 'react';
import { useCallback } from 'react';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { matchRoute } from 'lib/router/matchRoute';
@@ -6,17 +6,13 @@ import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { History, Maximize2, Plus, X } from '@signozhq/icons';
import { Maximize2, Minus, X } from '@signozhq/icons';
import { BOTTOM_STRIP_HEIGHT } from 'container/BottomStrip';
import { useAIAssistantOpenConversationsStore } from '../store/useAIAssistantOpenConversationsStore';
import { supportChatObstacle } from 'container/BottomStrip/SupportButton/supportChatObstacle';
import { FloatingPanel } from 'periscope/components/FloatingPanel';
import logEvent from 'api/common/logEvent';
import ConversationsList from '../components/ConversationsList';
import ConversationView from '../ConversationView';
import { AIAssistantEvents } from '../events';
import { useAIAssistantAnalyticsContext } from '../hooks/useAIAssistantAnalyticsContext';
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
@@ -44,7 +40,6 @@ const PANEL_AVOID = [supportChatObstacle];
export default function AIAssistantPanel(): JSX.Element | null {
const { pathname, search } = useAppLocation();
const [showHistory, setShowHistory] = useState(false);
const isOpen = useAIAssistantStore((s) => s.isDrawerOpen);
const isFullScreenPage = !!matchRoute(pathname, ROUTES.AI_ASSISTANT, {
@@ -53,13 +48,23 @@ export default function AIAssistantPanel(): JSX.Element | null {
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const closeDrawer = useAIAssistantStore((s) => s.closeDrawer);
const startNewConversation = useAIAssistantStore(
(s) => s.startNewConversation,
const activeThreadId = useAIAssistantStore((s) =>
s.activeConversationId
? s.conversations[s.activeConversationId]?.threadId
: undefined,
);
const analyticsCtx = useAIAssistantAnalyticsContext();
const closeDrawer = useAIAssistantStore((s) => s.closeDrawer);
const closeChatTab = useAIAssistantOpenConversationsStore((s) => s.close);
const chatTitle = useActiveChatTitle();
// Minimize keeps the chat as a strip tab; close drops it until its next reply.
const handleClose = useCallback((): void => {
if (activeThreadId) {
closeChatTab(activeThreadId);
}
closeDrawer();
}, [activeThreadId, closeChatTab, closeDrawer]);
const handleExpand = useCallback(() => {
if (!activeConversationId) {
return;
@@ -74,25 +79,6 @@ export default function AIAssistantPanel(): JSX.Element | null {
);
}, [activeConversationId, closeDrawer, pathname, search]);
const handleNew = useCallback(() => {
void logEvent(AIAssistantEvents.NewChatClicked, {
...analyticsCtx,
// useAIAssistantAnalyticsContext() runs above this component's
// VariantContext.Provider, so the hook reports the default 'page'
// mode. Override here: this handler only runs when the drawer
// itself is mounted, which is unambiguously the sidepane surface.
mode: 'sidepane',
source: 'header',
});
startNewConversation();
setShowHistory(false);
}, [startNewConversation, analyticsCtx]);
// When user picks a conversation from the list, close the sidebar
const handleHistorySelect = useCallback(() => {
setShowHistory(false);
}, []);
if (!isOpen || isFullScreenPage) {
return null;
}
@@ -149,29 +135,17 @@ export default function AIAssistantPanel(): JSX.Element | null {
</div>
<div className={styles.actions}>
<Tooltip title={showHistory ? 'Back to chat' : 'Conversations'}>
<Tooltip title="Minimize">
<Button
variant="ghost"
size="sm"
icon
color="secondary"
onClick={(): void => setShowHistory((v) => !v)}
aria-label="Toggle conversations"
testId="ai-assistant-panel-minimize"
onClick={closeDrawer}
aria-label="Minimize panel"
>
<History size={14} />
</Button>
</Tooltip>
<Tooltip title="New conversation">
<Button
variant="ghost"
size="sm"
icon
color="secondary"
onClick={handleNew}
aria-label="New conversation"
>
<Plus size={14} />
<Minus size={14} />
</Button>
</Tooltip>
@@ -197,7 +171,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
icon
color="secondary"
testId="ai-assistant-panel-close"
onClick={closeDrawer}
onClick={handleClose}
aria-label="Close panel"
>
<X size={14} />
@@ -206,12 +180,8 @@ export default function AIAssistantPanel(): JSX.Element | null {
</div>
</div>
{showHistory ? (
<ConversationsList onSelect={handleHistorySelect} />
) : (
activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)
{activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)}
</FloatingPanel>
</VariantContext.Provider>

View File

@@ -0,0 +1,51 @@
import { useAIAssistantOpenConversationsStore } from 'container/AIAssistant/store/useAIAssistantOpenConversationsStore';
import { render, screen, userEvent } from 'tests/test-utils';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import AIAssistantPanel from '../AIAssistantPanel';
jest.mock('../../ConversationView', () => ({
__esModule: true,
default: (): JSX.Element => <div />,
}));
describe('AIAssistantPanel', () => {
beforeEach(() => {
useAIAssistantStore.setState((s) => {
s.conversations = {
c1: { id: 'c1', threadId: 't1', messages: [], createdAt: 0 },
};
s.activeConversationId = 'c1';
s.isDrawerOpen = true;
});
useAIAssistantOpenConversationsStore.setState({ threadIds: ['t0', 't1'] });
});
it('minimizes to the strip, keeping the chat as a tab', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<AIAssistantPanel />);
await user.click(screen.getByTestId('ai-assistant-panel-minimize'));
expect(
screen.queryByTestId('ai-assistant-panel-close'),
).not.toBeInTheDocument();
expect(
useAIAssistantOpenConversationsStore.getState().threadIds,
).toStrictEqual(['t0', 't1']);
});
it('closes the chat, taking its tab out of the strip', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(<AIAssistantPanel />);
await user.click(screen.getByTestId('ai-assistant-panel-close'));
expect(
screen.queryByTestId('ai-assistant-panel-close'),
).not.toBeInTheDocument();
expect(
useAIAssistantOpenConversationsStore.getState().threadIds,
).toStrictEqual(['t0']);
});
});

View File

@@ -1,4 +1,10 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useState,
} from 'react';
import cx from 'classnames';
import { useAppLocation } from 'lib/router/useAppLocation';
@@ -46,7 +52,9 @@ export default function ConversationView({
const isStreamingHere = useAIAssistantStore(
(s) => s.streams[conversationId]?.isStreaming ?? false,
);
const isLoadingThread = useAIAssistantStore((s) => s.isLoadingThread);
const isLoadingThread = useAIAssistantStore((s) =>
s.loadingThreadIds.includes(conversationId),
);
const pendingApprovalHere = useAIAssistantStore(
(s) => s.streams[conversationId]?.pendingApproval ?? null,
);
@@ -57,6 +65,17 @@ export default function ConversationView({
const cancelStream = useAIAssistantStore((s) => s.cancelStream);
const analyticsCtx = useAIAssistantAnalyticsContext(conversationId);
const hasUnreadReply = useAIAssistantStore((s) =>
s.unreadReplyIds.includes(conversationId),
);
const markReplyRead = useAIAssistantStore((s) => s.markReplyRead);
// Layout effect: clears before paint, so the strip tab never flashes for an on-screen reply.
useLayoutEffect(() => {
if (hasUnreadReply) {
markReplyRead(conversationId);
}
}, [hasUnreadReply, conversationId, markReplyRead]);
// Auto-derived contexts come from the route the user is currently looking
// at (dashboard detail, service metrics, an explorer, …). Skip when the
// user is on the standalone AI Assistant page — there's no "underlying"

View File

@@ -3,6 +3,7 @@ import { MessageContext } from 'api/ai-assistant/chat';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { VariantContext } from 'container/AIAssistant/VariantContext';
import { TestRouter } from 'tests/router';
import { screen } from 'tests/test-utils';
const CHIP_ID = 'recent-errors';
const CHIP_TEXT = 'Show me recent errors';
@@ -81,11 +82,13 @@ jest.mock('components/DotGrid/DotGrid', () => ({
<>
<button
type="button"
aria-label="Start Snake"
data-testid="start-snake"
onClick={(): void => onGameChange?.(true)}
/>
<button
type="button"
aria-label="End Snake"
data-testid="end-snake"
onClick={(): void => onGameChange?.(false)}
/>
@@ -151,7 +154,7 @@ describe('ConversationView — empty-state chip context', () => {
},
streams: {},
activeConversationId: CONVERSATION_ID,
isLoadingThread: false,
loadingThreadIds: [],
sendMessage,
} as unknown as Partial<ReturnType<typeof useAIAssistantStore.getState>>);
});
@@ -180,6 +183,37 @@ describe('ConversationView — empty-state chip context', () => {
});
});
describe('ConversationView — loading', () => {
beforeEach(() => {
useAIAssistantStore.setState({
conversations: {
[CONVERSATION_ID]: {
id: CONVERSATION_ID,
messages: [],
createdAt: 1,
updatedAt: 1,
},
},
streams: {},
activeConversationId: CONVERSATION_ID,
});
});
it('shows the skeleton while its own chat loads', () => {
useAIAssistantStore.setState({ loadingThreadIds: [CONVERSATION_ID] });
expect(renderView('panel').getByTestId('skeleton')).toBeInTheDocument();
});
it('skips the skeleton while only another chat loads', () => {
useAIAssistantStore.setState({ loadingThreadIds: ['another-thread'] });
renderView('panel');
expect(screen.queryByTestId('skeleton')).not.toBeInTheDocument();
});
});
describe('ConversationView — reply start time', () => {
afterEach(() => {
jest.restoreAllMocks();
@@ -210,7 +244,7 @@ describe('ConversationView — reply start time', () => {
},
},
activeConversationId: CONVERSATION_ID,
isLoadingThread: false,
loadingThreadIds: [],
});
const { getByTestId } = renderView('panel');
@@ -235,7 +269,7 @@ describe('ConversationView — Snake on the empty state', () => {
},
streams: {},
activeConversationId: CONVERSATION_ID,
isLoadingThread: false,
loadingThreadIds: [],
});
});

View File

@@ -41,6 +41,10 @@
&.isReplying {
background: var(--accent-amber);
}
&.hasUnreadReply {
background: var(--accent-primary);
}
}
.body {

View File

@@ -18,6 +18,7 @@ import {
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { Conversation } from '../../types';
import { formatRelativeTime } from '../../utils/formatRelativeTime';
import styles from './ConversationItem.module.scss';
@@ -30,32 +31,6 @@ interface ConversationItemProps {
onRestore: (id: string) => void;
}
function formatRelativeTime(ts: number): string {
if (!Number.isFinite(ts)) {
return '';
}
const diff = Date.now() - ts;
const mins = Math.floor(diff / 60_000);
if (mins < 1) {
return 'now';
}
if (mins < 60) {
return `${mins}m`;
}
const hrs = Math.floor(mins / 60);
if (hrs < 24) {
return `${hrs}h`;
}
const days = Math.floor(hrs / 24);
if (days < 7) {
return `${days}d`;
}
return new Date(ts).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
});
}
export default function ConversationItem({
conversation,
isActive,
@@ -73,6 +48,16 @@ export default function ConversationItem({
const isReplying = useAIAssistantStore((s) =>
Boolean(s.streams[conversation.id]?.isStreaming),
);
const hasUnreadReply = useAIAssistantStore((s) =>
s.unreadReplyIds.includes(conversation.id),
);
// Replying wins: the dot turns blue once that reply lands unseen.
let dotState: 'replying' | 'unread' | undefined;
if (isReplying) {
dotState = 'replying';
} else if (hasUnreadReply) {
dotState = 'unread';
}
const displayTitle = conversation.title ?? 'New conversation';
const ts = conversation.updatedAt ?? conversation.createdAt;
@@ -171,13 +156,23 @@ export default function ConversationItem({
onClick={(): void => onSelect(conversation.id)}
role="button"
tabIndex={0}
aria-label={
dotState === 'unread' ? `Noz replied in ${displayTitle}` : undefined
}
onKeyDown={(e): void => {
if (e.key === 'Enter' || e.key === ' ') {
onSelect(conversation.id);
}
}}
>
<span className={cx(styles.dot, { [styles.isReplying]: isReplying })} />
<span
className={cx(styles.dot, {
[styles.isReplying]: dotState === 'replying',
[styles.hasUnreadReply]: dotState === 'unread',
})}
data-state={dotState}
data-testid={`ai-conversation-item-${conversation.id}-dot`}
/>
<div className={styles.body}>
{isEditing ? (

View File

@@ -0,0 +1,89 @@
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import type {
Conversation,
ConversationStreamState,
} from 'container/AIAssistant/types';
import { render, screen } from 'tests/test-utils';
import ConversationItem from '../ConversationItem';
const initialState = useAIAssistantStore.getState();
const conversation: Conversation = {
id: 'a',
threadId: 'a',
title: 'Checkout p99',
messages: [],
createdAt: 0,
};
const streaming: ConversationStreamState = {
isStreaming: true,
streamingContent: '',
streamingStatus: 'thinking',
streamingEvents: [],
streamingMessageId: null,
streamingActions: null,
pendingApproval: null,
pendingClarification: null,
startedAt: 0,
};
const renderRow = (): void => {
render(
<ConversationItem
conversation={conversation}
isActive={false}
onSelect={jest.fn()}
onRename={jest.fn()}
onArchive={jest.fn()}
onRestore={jest.fn()}
/>,
);
};
describe('ConversationItem', () => {
afterEach(() => {
useAIAssistantStore.setState(initialState, true);
});
it('marks a reply the user has not seen with the blue dot', () => {
useAIAssistantStore.setState({ unreadReplyIds: ['a'] });
renderRow();
expect(screen.getByTestId('ai-conversation-item-a-dot')).toHaveAttribute(
'data-state',
'unread',
);
expect(screen.getByTestId('ai-conversation-item-a')).toHaveAttribute(
'aria-label',
'Noz replied in Checkout p99',
);
});
it('shows replying over unread while a new reply streams', () => {
useAIAssistantStore.setState({
unreadReplyIds: ['a'],
streams: { a: streaming },
});
renderRow();
expect(screen.getByTestId('ai-conversation-item-a-dot')).toHaveAttribute(
'data-state',
'replying',
);
});
it('has no dot without a reply to show', () => {
renderRow();
expect(screen.getByTestId('ai-conversation-item-a-dot')).not.toHaveAttribute(
'data-state',
);
expect(screen.getByTestId('ai-conversation-item-a')).not.toHaveAttribute(
'aria-label',
);
});
});

View File

@@ -1,35 +1,26 @@
@use '../../_scrollbar' as *;
@use '../../_bareInput' as *;
// Fixed-width left column; the thread pane draws the edge beside it.
.conversationsList {
position: relative;
display: flex;
flex-direction: column;
flex-shrink: 0;
width: 280px;
height: 100%;
overflow: hidden;
// Page variant: fixed-width left column; the thread pane draws the edge beside it.
&.variantPage {
position: relative;
width: 280px;
flex-shrink: 0;
// Fades the list's foot into the page.
&::after {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 46px;
background: linear-gradient(to bottom, transparent, var(--l1-background));
pointer-events: none;
}
}
// Panel variant: full-width overlay (replaces conversation view).
&.variantPanel {
width: 100%;
flex: 1;
// Fades the list's foot into the page.
&::after {
content: '';
position: absolute;
right: 0;
bottom: 0;
left: 0;
height: 46px;
background: linear-gradient(to bottom, transparent, var(--l1-background));
pointer-events: none;
}
}

View File

@@ -4,12 +4,9 @@ import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import { Plus } from '@signozhq/icons';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents } from '../../events';
import { useOpenConversation } from '../../hooks/useOpenConversation';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { Conversation } from '../../types';
import { useVariant } from '../../VariantContext';
import ConversationItem from '../ConversationItem';
import styles from './ConversationsList.module.scss';
@@ -75,16 +72,12 @@ export default function ConversationsList({
onNewConversation,
showAddNewConversation = false,
}: ConversationsListProps): JSX.Element {
const variant = useVariant();
const conversations = useAIAssistantStore((s) => s.conversations);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const isLoadingThreads = useAIAssistantStore((s) => s.isLoadingThreads);
const setActiveConversation = useAIAssistantStore(
(s) => s.setActiveConversation,
);
const loadThread = useAIAssistantStore((s) => s.loadThread);
const openConversation = useOpenConversation();
const fetchThreads = useAIAssistantStore((s) => s.fetchThreads);
const archiveConversation = useAIAssistantStore((s) => s.archiveConversation);
const restoreConversation = useAIAssistantStore((s) => s.restoreConversation);
@@ -137,34 +130,12 @@ export default function ConversationsList({
const isSearching = trimmedQuery.length > 0;
const handleSelect = (id: string): void => {
const conv = conversations[id];
// Skip re-selecting the currently active thread — Notion-style click on
// the highlighted row in the history list shouldn't inflate the funnel.
const isReselectingActive = id === activeConversationId;
if (conv?.threadId && !isReselectingActive) {
void logEvent(AIAssistantEvents.ThreadOpenedFromHistory, {
threadId: conv.threadId,
threadAgeDays: Math.floor(
(Date.now() - conv.createdAt) / (24 * 60 * 60 * 1000),
),
});
}
if (conv?.threadId) {
// Always load from backend — refreshes messages and reconnects
// to active execution if the thread is still busy.
void loadThread(conv.threadId);
} else {
// Local-only conversation (no backend thread yet)
setActiveConversation(id);
}
openConversation(id);
onSelect?.(id);
};
const variantClass =
variant === 'page' ? styles.variantPage : styles.variantPanel;
return (
<div className={cx(styles.conversationsList, variantClass)}>
<div className={styles.conversationsList}>
<div className={styles.searchBar}>
<div className={styles.search}>
<Input

View File

@@ -0,0 +1,210 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import replySoundUrl from 'assets/sounds/noz-reply.wav';
import { useShallow } from 'zustand/react/shallow';
import { selectAwaitingUserThreadIds } from '../store/pendingInputSelectors';
import { useAIAssistantOpenConversationsStore } from '../store/useAIAssistantOpenConversationsStore';
import {
openAIAssistant,
useAIAssistantStore,
} from '../store/useAIAssistantStore';
import type { Conversation } from '../types';
export interface AIAssistantChatTab {
threadId: string;
title: string | undefined;
hasUnreadReply: boolean;
/** Noz waits on an approval or answer here, and the chat is not on screen. */
isAwaitingUser: boolean;
isActive: boolean;
}
interface UseAIAssistantActiveChatsResult {
chats: AIAssistantChatTab[];
openChat: (threadId: string) => void;
closeChat: (threadId: string) => void;
}
/**
* Open Noz conversations for the strip, kept in localStorage by thread id.
* A chat joins when it becomes active in the drawer, the modal or the Noz page,
* when a reply lands in it, or when Noz starts waiting on the user in it; it
* leaves on close, archive, clear, or once the server no longer lists it.
*
* On the Noz page a chat opens in the page itself, which follows the active chat.
* A reply landing in a chat that isn't on screen chimes.
*/
export function useAIAssistantActiveChats(
isOnAssistantPage: boolean,
): UseAIAssistantActiveChatsResult {
const threadIds = useAIAssistantOpenConversationsStore((s) => s.threadIds);
const openTab = useAIAssistantOpenConversationsStore((s) => s.open);
const closeTab = useAIAssistantOpenConversationsStore((s) => s.close);
const pruneTabs = useAIAssistantOpenConversationsStore((s) => s.prune);
const openNewlyAwaiting = useAIAssistantOpenConversationsStore(
(s) => s.openNewlyAwaiting,
);
const conversations = useAIAssistantStore((s) => s.conversations);
const unreadReplyIds = useAIAssistantStore((s) => s.unreadReplyIds);
const awaitingThreadIds = useAIAssistantStore(
useShallow(selectAwaitingUserThreadIds),
);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const isAssistantOpen = useAIAssistantStore(
(s) => isOnAssistantPage || s.isDrawerOpen || s.isModalOpen,
);
const hasLoadedThreads = useAIAssistantStore((s) => s.hasLoadedThreads);
const setActiveConversation = useAIAssistantStore(
(s) => s.setActiveConversation,
);
const loadThread = useAIAssistantStore((s) => s.loadThread);
const loadingThreadIds = useAIAssistantStore((s) => s.loadingThreadIds);
const markReplyRead = useAIAssistantStore((s) => s.markReplyRead);
// A new chat keeps its local id after the server assigns a thread id.
const conversationByThreadId = useMemo(() => {
const byThreadId = new Map<string, Conversation>();
Object.values(conversations).forEach((conversation) => {
if (conversation.threadId) {
byThreadId.set(conversation.threadId, conversation);
}
});
return byThreadId;
}, [conversations]);
const activeThreadId = activeConversationId
? conversations[activeConversationId]?.threadId
: undefined;
useEffect(() => {
if (isAssistantOpen && activeThreadId) {
openTab(activeThreadId);
}
}, [isAssistantOpen, activeThreadId, openTab]);
// Each unread reply opens its tab once; one restored before the threads load opens when they do.
const openedForUnreadRef = useRef<readonly string[]>([]);
useEffect(() => {
const opened = openedForUnreadRef.current.filter((id) =>
unreadReplyIds.includes(id),
);
unreadReplyIds.forEach((conversationId) => {
const threadId = conversations[conversationId]?.threadId;
if (threadId && !opened.includes(conversationId)) {
openTab(threadId);
opened.push(conversationId);
}
});
openedForUnreadRef.current = opened;
}, [unreadReplyIds, conversations, openTab]);
const previousUnreadReplyIdsRef = useRef(unreadReplyIds);
const replySoundRef = useRef<HTMLAudioElement | null>(null);
useEffect(() => {
const previousIds = previousUnreadReplyIdsRef.current;
previousUnreadReplyIdsRef.current = unreadReplyIds;
if (unreadReplyIds.every((id) => previousIds.includes(id))) {
return undefined;
}
// A chat on screen reads its reply in the same task, which re-runs this effect and cancels the chime.
const timer = window.setTimeout(() => {
replySoundRef.current ??= new Audio(replySoundUrl);
replySoundRef.current.currentTime = 0;
// Autoplay policy rejects play() until the user has interacted with the page.
replySoundRef.current.play().catch(() => undefined);
}, 0);
return (): void => window.clearTimeout(timer);
}, [unreadReplyIds]);
// Only a chat that starts waiting joins, so closing one already waiting sticks.
useEffect(() => {
openNewlyAwaiting(awaitingThreadIds);
}, [awaitingThreadIds, openNewlyAwaiting]);
// Before the first successful fetch, a missing thread may only be unloaded.
useEffect(() => {
const staleThreadIds = threadIds.filter((threadId) => {
const conversation = conversationByThreadId.get(threadId);
return conversation ? Boolean(conversation.archived) : hasLoadedThreads;
});
if (staleThreadIds.length > 0) {
pruneTabs(staleThreadIds);
}
}, [threadIds, conversationByThreadId, hasLoadedThreads, pruneTabs]);
const chats = useMemo(
() =>
threadIds.flatMap((threadId): AIAssistantChatTab[] => {
const conversation = conversationByThreadId.get(threadId);
if (!conversation || conversation.archived) {
return [];
}
const isActive =
isAssistantOpen && activeConversationId === conversation.id;
return [
{
threadId,
title: conversation.title,
hasUnreadReply: unreadReplyIds.includes(conversation.id),
isAwaitingUser: !isActive && awaitingThreadIds.includes(threadId),
isActive,
},
];
}),
[
threadIds,
conversationByThreadId,
unreadReplyIds,
awaitingThreadIds,
isAssistantOpen,
activeConversationId,
],
);
const openChat = useCallback(
(threadId: string): void => {
const conversation = conversationByThreadId.get(threadId);
if (!conversation) {
return;
}
// After a reload only the thread list is loaded; an empty chat loads, even when selected, so a failed load retries.
const needsLoad =
conversation.messages.length === 0 && !loadingThreadIds.includes(threadId);
if (needsLoad) {
void loadThread(threadId);
} else if (conversation.id !== activeConversationId) {
setActiveConversation(conversation.id);
}
if (!isOnAssistantPage) {
openAIAssistant();
}
},
[
isOnAssistantPage,
conversationByThreadId,
activeConversationId,
loadingThreadIds,
loadThread,
setActiveConversation,
],
);
// Closing dismisses the unseen reply too, or the reply would reopen the tab.
const closeChat = useCallback(
(threadId: string): void => {
closeTab(threadId);
const conversation = conversationByThreadId.get(threadId);
if (conversation && unreadReplyIds.includes(conversation.id)) {
markReplyRead(conversation.id);
}
},
[closeTab, conversationByThreadId, unreadReplyIds, markReplyRead],
);
return { chats, openChat, closeChat };
}

View File

@@ -0,0 +1,48 @@
import { useCallback } from 'react';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents, AIAssistantOpenSource } from '../events';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
const DAY_MS = 24 * 60 * 60 * 1000;
/** Opens a chat picked from a history list; `source` tags the analytics event. */
export function useOpenConversation(
source?: AIAssistantOpenSource,
): (conversationId: string) => void {
const conversations = useAIAssistantStore((s) => s.conversations);
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const loadThread = useAIAssistantStore((s) => s.loadThread);
const setActiveConversation = useAIAssistantStore(
(s) => s.setActiveConversation,
);
return useCallback(
(conversationId: string): void => {
const conversation = conversations[conversationId];
if (!conversation?.threadId) {
setActiveConversation(conversationId);
return;
}
// Picking the open chat again doesn't count as opening one.
if (conversationId !== activeConversationId) {
void logEvent(AIAssistantEvents.ThreadOpenedFromHistory, {
threadId: conversation.threadId,
threadAgeDays: Math.floor((Date.now() - conversation.createdAt) / DAY_MS),
...(source && { source }),
});
}
// Always from the server: refreshes the messages, retries a load that failed, and rejoins a running reply.
void loadThread(conversation.threadId);
},
[
activeConversationId,
conversations,
loadThread,
setActiveConversation,
source,
],
);
}

View File

@@ -0,0 +1,80 @@
import getLocalStorageKey from 'api/browser/localstorage/get';
import setLocalStorageKey from 'api/browser/localstorage/set';
import {
AI_ASSISTANT_OPEN_CONVERSATIONS_STORAGE_KEY,
useAIAssistantOpenConversationsStore,
} from '../useAIAssistantOpenConversationsStore';
const initialTabsState = useAIAssistantOpenConversationsStore.getState();
function openAll(ids: string[]): void {
ids.forEach((id) => useAIAssistantOpenConversationsStore.getState().open(id));
}
const tabs = (): string[] =>
useAIAssistantOpenConversationsStore.getState().threadIds;
describe('useAIAssistantOpenConversationsStore', () => {
afterEach(() => {
useAIAssistantOpenConversationsStore.setState(initialTabsState, true);
localStorage.clear();
});
it('opens a tab once, in open order', () => {
openAll(['a', 'b', 'a']);
expect(tabs()).toStrictEqual(['a', 'b']);
});
it('past the cap drops the oldest tab', () => {
openAll(['a', 'b', 'c', 'd', 'e', 'f']);
expect(tabs()).toStrictEqual(['b', 'c', 'd', 'e', 'f']);
});
it('closes and prunes tabs', () => {
openAll(['a', 'b', 'c', 'd']);
useAIAssistantOpenConversationsStore.getState().close('b');
useAIAssistantOpenConversationsStore.getState().prune(['c', 'missing']);
expect(tabs()).toStrictEqual(['a', 'd']);
});
it('saves the tabs as soon as they change', () => {
openAll(['a', 'b']);
expect(
JSON.parse(
getLocalStorageKey(AI_ASSISTANT_OPEN_CONVERSATIONS_STORAGE_KEY) ?? '{}',
),
).toStrictEqual({ state: { threadIds: ['a', 'b'] }, version: 1 });
});
it('restores only string ids from storage, newest five', async () => {
setLocalStorageKey(
AI_ASSISTANT_OPEN_CONVERSATIONS_STORAGE_KEY,
JSON.stringify({
state: { threadIds: ['1', '2', 3, '4', '5', '6', null, '7'] },
version: 1,
}),
);
await useAIAssistantOpenConversationsStore.persist.rehydrate();
expect(tabs()).toStrictEqual(['2', '4', '5', '6', '7']);
});
it('restores no tabs from a stored value that is not a list', async () => {
useAIAssistantOpenConversationsStore.setState({ threadIds: ['open'] });
setLocalStorageKey(
AI_ASSISTANT_OPEN_CONVERSATIONS_STORAGE_KEY,
JSON.stringify({ state: { threadIds: 'a' }, version: 1 }),
);
await useAIAssistantOpenConversationsStore.persist.rehydrate();
expect(tabs()).toStrictEqual([]);
});
});

View File

@@ -9,9 +9,13 @@ import type {
MessageContext,
SSEEvent,
ThreadDetailResponse,
ThreadSummary,
} from 'api/ai-assistant/chat';
import { useAIAssistantStore } from '../useAIAssistantStore';
import {
openNewAIAssistantChat,
useAIAssistantStore,
} from '../useAIAssistantStore';
import type { Message } from '../../types';
// The store talks to the chat API only through these named exports. Mock the
@@ -390,3 +394,237 @@ describe('useAIAssistantStore — message contexts', () => {
expect(lastMessage('thread-1').contexts).toStrictEqual([pickedDashboard]);
});
});
describe('useAIAssistantStore — unread replies', () => {
const summary = (threadId: string, archived: boolean): ThreadSummary => ({
threadId,
title: threadId,
archived,
createdAt: '2026-11-16T09:00:00Z',
updatedAt: '2026-11-16T09:00:00Z',
});
beforeEach(() => {
jest.clearAllMocks();
useAIAssistantStore.setState((s) => {
s.conversations = {};
s.streams = {};
s.activeConversationId = null;
s.unreadReplyIds = [];
s.hasLoadedThreads = false;
});
});
it('marks a finished reply unread under its thread id and saves it', async () => {
chat.createThread.mockResolvedValue('thread-reply');
chat.sendMessage.mockResolvedValue('exec');
chat.streamEvents.mockReturnValueOnce(
eventStream([
{
type: 'message',
executionId: 'exec',
messageId: 'm1',
delta: 'Done',
done: true,
},
]),
);
useAIAssistantStore.getState().startNewConversation();
await useAIAssistantStore.getState().sendMessage('hi');
expect(useAIAssistantStore.getState().unreadReplyIds).toStrictEqual([
'thread-reply',
]);
expect(
JSON.parse(localStorage.getItem('ai-assistant-store') ?? '{}').state
.unreadReplyIds,
).toStrictEqual(['thread-reply']);
});
it('drops the mark when the reply is read, or its chat archived or cleared', () => {
chat.updateThread.mockResolvedValue(summary('b', true));
useAIAssistantStore.setState((s) => {
['a', 'b', 'c'].forEach((id) => {
s.conversations[id] = { id, threadId: id, messages: [], createdAt: 0 };
});
s.unreadReplyIds = ['a', 'b', 'c'];
});
const { markReplyRead, archiveConversation, clearConversation } =
useAIAssistantStore.getState();
markReplyRead('a');
archiveConversation('b');
clearConversation('c');
expect(useAIAssistantStore.getState().unreadReplyIds).toStrictEqual([]);
});
it('keeps only loaded, unarchived threads once the list loads', async () => {
chat.listThreads.mockImplementation(({ archived }) =>
Promise.resolve({
threads:
archived === 'true'
? [summary('archived', true)]
: [summary('live', false)],
hasMore: false,
}),
);
useAIAssistantStore.setState((s) => {
s.unreadReplyIds = ['live', 'archived', 'gone'];
});
await useAIAssistantStore.getState().fetchThreads();
expect(useAIAssistantStore.getState().unreadReplyIds).toStrictEqual(['live']);
expect(useAIAssistantStore.getState().hasLoadedThreads).toBe(true);
});
it('keeps every mark when the list fails to load', async () => {
chat.listThreads.mockRejectedValue(new Error('down'));
useAIAssistantStore.setState((s) => {
s.unreadReplyIds = ['live'];
});
await useAIAssistantStore.getState().fetchThreads();
expect(useAIAssistantStore.getState().unreadReplyIds).toStrictEqual(['live']);
expect(useAIAssistantStore.getState().hasLoadedThreads).toBe(false);
});
});
describe('useAIAssistantStore — loading threads', () => {
const detail = (threadId: string): ThreadDetailResponse => ({
threadId,
createdAt: '2026-11-17T00:00:00Z',
updatedAt: '2026-11-17T00:00:00Z',
messages: [],
});
beforeEach(() => {
jest.clearAllMocks();
useAIAssistantStore.setState((s) => {
s.conversations = {};
s.loadingThreadIds = [];
s.activeConversationId = null;
});
});
it('keeps each thread loading until its own request settles', async () => {
let resolveA: (value: ThreadDetailResponse) => void = () => undefined;
let rejectB: (reason: Error) => void = () => undefined;
chat.getThreadDetail
.mockReturnValueOnce(
new Promise((resolve) => {
resolveA = resolve;
}),
)
.mockReturnValueOnce(
new Promise((_resolve, reject) => {
rejectB = reject;
}),
);
jest.spyOn(console, 'error').mockImplementation(() => undefined);
const loadA = useAIAssistantStore.getState().loadThread('a');
const loadB = useAIAssistantStore.getState().loadThread('b');
expect(useAIAssistantStore.getState().loadingThreadIds).toStrictEqual([
'a',
'b',
]);
resolveA(detail('a'));
await loadA;
expect(useAIAssistantStore.getState().loadingThreadIds).toStrictEqual(['b']);
expect(useAIAssistantStore.getState().activeConversationId).toBe('b');
rejectB(new Error('network'));
await loadB;
expect(useAIAssistantStore.getState().loadingThreadIds).toStrictEqual([]);
});
});
describe('openNewAIAssistantChat', () => {
const reply: Message = {
id: 'm1',
role: 'assistant',
content: 'Hi',
createdAt: 0,
};
beforeEach(() => {
useAIAssistantStore.setState((s) => {
s.conversations = {};
s.activeConversationId = null;
s.isDrawerOpen = false;
});
});
it('opens the drawer on a new chat, leaving the open one as it was', () => {
useAIAssistantStore.setState((s) => {
s.conversations.old = {
id: 'old',
threadId: 'old',
messages: [reply],
createdAt: 0,
};
s.activeConversationId = 'old';
});
openNewAIAssistantChat();
const { activeConversationId, conversations, isDrawerOpen } =
useAIAssistantStore.getState();
expect(activeConversationId).not.toBe('old');
expect(conversations[activeConversationId ?? ''].messages).toStrictEqual([]);
expect(conversations.old.messages).toStrictEqual([reply]);
expect(isDrawerOpen).toBe(true);
});
it('reuses the open chat while nothing has been sent in it', () => {
useAIAssistantStore.setState((s) => {
s.conversations.blank = { id: 'blank', messages: [], createdAt: 0 };
s.activeConversationId = 'blank';
});
openNewAIAssistantChat();
expect(useAIAssistantStore.getState().activeConversationId).toBe('blank');
expect(
Object.keys(useAIAssistantStore.getState().conversations),
).toStrictEqual(['blank']);
});
});
describe('history list', () => {
beforeEach(() => {
useAIAssistantStore.setState((s) => {
s.isDrawerOpen = false;
s.isModalOpen = false;
s.isHistoryOpen = false;
});
});
it('closes the panel when it opens', () => {
useAIAssistantStore.setState((s) => {
s.isDrawerOpen = true;
});
useAIAssistantStore.getState().setHistoryOpen(true);
const { isHistoryOpen, isDrawerOpen } = useAIAssistantStore.getState();
expect(isHistoryOpen).toBe(true);
expect(isDrawerOpen).toBe(false);
});
it.each([
['panel', (): void => useAIAssistantStore.getState().openDrawer()],
['popup chat', (): void => useAIAssistantStore.getState().openModal()],
])('closes when the %s opens', (_surface, open) => {
useAIAssistantStore.getState().setHistoryOpen(true);
open();
expect(useAIAssistantStore.getState().isHistoryOpen).toBe(false);
});
});

View File

@@ -21,3 +21,18 @@ export function selectPendingUserInputStreamCount(
}
return n;
}
/** Thread ids of the saved chats whose execution is waiting on the user. */
export function selectAwaitingUserThreadIds(
state: AIAssistantStoreState,
): string[] {
return Object.entries(state.streams).flatMap(
([conversationId, { streamingStatus }]) => {
const threadId = state.conversations[conversationId]?.threadId;
const isAwaiting =
streamingStatus === 'awaiting_approval' ||
streamingStatus === 'awaiting_clarification';
return threadId && isAwaiting ? [threadId] : [];
},
);
}

View File

@@ -0,0 +1,86 @@
import getLocalStorageKey from 'api/browser/localstorage/get';
import removeLocalStorageKey from 'api/browser/localstorage/remove';
import setLocalStorageKey from 'api/browser/localstorage/set';
import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
export const MAX_OPEN_CONVERSATIONS = 5;
export const AI_ASSISTANT_OPEN_CONVERSATIONS_STORAGE_KEY =
'aiAssistantOpenConversations';
interface AIAssistantOpenConversationsState {
/** Thread ids of the open tabs, oldest first. */
threadIds: string[];
/** Waiting chats already given a tab. Not saved: the waiting state is lost on reload too. */
seenAwaitingThreadIds: readonly string[];
/** Past the cap, drops the oldest tab. */
open: (threadId: string) => void;
close: (threadId: string) => void;
prune: (staleThreadIds: readonly string[]) => void;
/** Opens a tab only for a chat that started waiting since the last call. */
openNewlyAwaiting: (awaitingThreadIds: readonly string[]) => void;
}
export const useAIAssistantOpenConversationsStore =
create<AIAssistantOpenConversationsState>()(
persist(
(set, get) => ({
threadIds: [],
seenAwaitingThreadIds: [],
open: (threadId): void => {
const { threadIds } = get();
// Every set() writes storage, so skip the no-op.
if (threadIds.includes(threadId)) {
return;
}
set({
threadIds: [...threadIds, threadId].slice(-MAX_OPEN_CONVERSATIONS),
});
},
close: (threadId): void => {
set({ threadIds: get().threadIds.filter((id) => id !== threadId) });
},
prune: (staleThreadIds): void => {
set({
threadIds: get().threadIds.filter((id) => !staleThreadIds.includes(id)),
});
},
openNewlyAwaiting: (awaitingThreadIds): void => {
const { seenAwaitingThreadIds, open } = get();
awaitingThreadIds
.filter((threadId) => !seenAwaitingThreadIds.includes(threadId))
.forEach((threadId) => open(threadId));
set({ seenAwaitingThreadIds: awaitingThreadIds });
},
}),
{
name: AI_ASSISTANT_OPEN_CONVERSATIONS_STORAGE_KEY,
version: 1,
// Scoped wrappers prefix the key when SigNoz is served under a base path.
storage: createJSONStorage(() => ({
getItem: getLocalStorageKey,
setItem: setLocalStorageKey,
removeItem: removeLocalStorageKey,
})),
partialize: (state) => ({ threadIds: state.threadIds }),
// Storage is user-editable: keep only string ids, newest within the cap.
merge: (persisted, current) => {
const stored = (
persisted as Partial<AIAssistantOpenConversationsState> | null
)?.threadIds;
return {
...current,
threadIds: Array.isArray(stored)
? stored
.filter((id): id is string => typeof id === 'string')
.slice(-MAX_OPEN_CONVERSATIONS)
: [],
};
},
},
),
);

View File

@@ -529,11 +529,26 @@ function finalizeStreamingMessage(
createdAt: Date.now(),
});
conv.updatedAt = Date.now();
dropUnreadReply(s, conversationId);
s.unreadReplyIds.push(conversationId);
}
delete s.streams[conversationId];
});
}
function dropUnreadReply(s: AIAssistantStore, conversationId: string): void {
s.unreadReplyIds = s.unreadReplyIds.filter((id) => id !== conversationId);
}
function setThreadLoading(
s: AIAssistantStore,
threadId: string,
isLoading: boolean,
): void {
const others = s.loadingThreadIds.filter((id) => id !== threadId);
s.loadingThreadIds = isLoading ? [...others, threadId] : others;
}
function hasPendingInput(conversationId: string, get: StoreGetter): boolean {
const stream = get().streams[conversationId];
return Boolean(stream?.pendingApproval || stream?.pendingClarification);
@@ -620,6 +635,8 @@ export interface AIAssistantStore {
// UI state
isDrawerOpen: boolean;
isModalOpen: boolean;
/** The bottom strip's recent-conversations list. */
isHistoryOpen: boolean;
activeConversationId: string | null;
// Data
@@ -628,6 +645,9 @@ export interface AIAssistantStore {
// Per-conversation streaming state
streams: Record<string, ConversationStreamState>;
/** Thread ids whose finished reply no open view has shown yet, oldest first; persisted. */
unreadReplyIds: string[];
/**
* Persists answered state for interactive blocks (ai-question, ai-confirm)
* so re-renders/remounts don't reset the answered UI.
@@ -636,7 +656,10 @@ export interface AIAssistantStore {
// Loading state
isLoadingThreads: boolean;
isLoadingThread: boolean;
/** Threads whose messages are being fetched. */
loadingThreadIds: string[];
/** True once `fetchThreads` has succeeded; a failed fetch leaves it false. */
hasLoadedThreads: boolean;
// Actions
openDrawer: () => void;
@@ -644,11 +667,13 @@ export interface AIAssistantStore {
openModal: () => void;
closeModal: () => void;
minimizeModal: () => void;
setHistoryOpen: (open: boolean) => void;
fetchThreads: () => Promise<void>;
loadThread: (threadId: string) => Promise<void>;
startNewConversation: () => string;
setActiveConversation: (id: string) => void;
clearConversation: (id: string) => void;
markReplyRead: (id: string) => void;
archiveConversation: (id: string) => void;
restoreConversation: (id: string) => void;
renameConversation: (id: string, title: string) => Promise<void>;
@@ -781,16 +806,20 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
immer<AIAssistantStore>((set, get) => ({
isDrawerOpen: false,
isModalOpen: false,
isHistoryOpen: false,
activeConversationId: null,
conversations: {},
streams: {},
unreadReplyIds: [],
isLoadingThreads: false,
isLoadingThread: false,
loadingThreadIds: [],
hasLoadedThreads: false,
answeredBlocks: {},
openDrawer: (): void => {
set((state) => {
state.isDrawerOpen = true;
state.isHistoryOpen = false;
if (!state.activeConversationId) {
const id = uuidv4();
state.conversations[id] = {
@@ -813,6 +842,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
openModal: (): void => {
set((state) => {
state.isModalOpen = true;
state.isHistoryOpen = false;
if (!state.activeConversationId) {
const id = uuidv4();
state.conversations[id] = {
@@ -836,6 +866,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
set((state) => {
state.isModalOpen = false;
state.isDrawerOpen = true;
state.isHistoryOpen = false;
if (!state.activeConversationId) {
const id = uuidv4();
state.conversations[id] = {
@@ -849,6 +880,16 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
});
},
// One Noz surface at a time: the list replaces the panel behind it.
setHistoryOpen: (open: boolean): void => {
set((state) => {
state.isHistoryOpen = open;
if (open) {
state.isDrawerOpen = false;
}
});
},
fetchThreads: async (): Promise<void> => {
set((s) => {
s.isLoadingThreads = true;
@@ -894,7 +935,14 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
s.conversations[thread.threadId] = mapped;
}
// Restored ids may name a deleted, archived or another user's thread.
s.unreadReplyIds = s.unreadReplyIds.filter((id) => {
const conv = s.conversations[id];
return Boolean(conv && !conv.archived);
});
s.isLoadingThreads = false;
s.hasLoadedThreads = true;
// Clear the rehydrate-time hydration flag on any entries
// the server didn't claim — those are local-only chats
@@ -915,7 +963,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
const conv = s.conversations[id];
if (conv?.threadId && conv.messages.length === 0) {
activeThreadIdToLoad = conv.threadId;
s.isLoadingThread = true;
setThreadLoading(s, conv.threadId, true);
}
}
});
@@ -944,7 +992,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// eslint-disable-next-line sonarjs/cognitive-complexity
loadThread: async (threadId: string): Promise<void> => {
set((s) => {
s.isLoadingThread = true;
setThreadLoading(s, threadId, true);
s.activeConversationId = threadId;
});
try {
@@ -978,7 +1026,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
startedAt: null,
};
}
s.isLoadingThread = false;
setThreadLoading(s, threadId, false);
});
// Reconnect to SSE if backend execution is still running
@@ -1012,13 +1060,13 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
}
}
} catch (err) {
set((s) => {
setThreadLoading(s, threadId, false);
});
if (err instanceof DOMException && err.name === 'AbortError') {
return;
}
console.error('[AIAssistant] loadThread failed:', err);
set((s) => {
s.isLoadingThread = false;
});
}
},
@@ -1057,6 +1105,13 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
state.conversations[id].archived = false;
state.conversations[id].updatedAt = Date.now();
}
dropUnreadReply(state, id);
});
},
markReplyRead: (id: string): void => {
set((state) => {
dropUnreadReply(state, id);
});
},
@@ -1066,6 +1121,9 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
return;
}
disconnectAndCommit(id, set, get);
set((state) => {
dropUnreadReply(state, id);
});
if (conv.threadId) {
updateThread(conv.threadId, { archived: true }).catch((err) => {
console.error('[AIAssistant] archiveThread failed:', err);
@@ -1466,6 +1524,8 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// Persist the active conversation so a page reload returns the
// user to the same thread instead of dumping them into a new one.
activeConversationId: state.activeConversationId,
// A reply needs a thread, and a chat is re-keyed to its threadId on first send.
unreadReplyIds: state.unreadReplyIds,
}),
migrate: () => ({
isDrawerOpen: false,
@@ -1516,6 +1576,27 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// Standalone imperative accessors
export const openAIAssistant = (): void =>
useAIAssistantStore.getState().openDrawer();
/** Opens the panel on a fresh chat, reusing the open one while nothing has been sent in it. */
export const openNewAIAssistantChat = (): void => {
const {
activeConversationId,
conversations,
startNewConversation,
openDrawer,
} = useAIAssistantStore.getState();
const active = activeConversationId
? conversations[activeConversationId]
: undefined;
if (
!active ||
active.threadId ||
active.isHydrating ||
active.messages.length > 0
) {
startNewConversation();
}
openDrawer();
};
export const closeAIAssistant = (): void =>
useAIAssistantStore.getState().closeDrawer();
export const openAIAssistantModal = (): void =>

View File

@@ -0,0 +1,26 @@
/** Compact age of a timestamp: "now", "5m", "3h", "2d", then a short date. */
export function formatRelativeTime(ts: number): string {
if (!Number.isFinite(ts)) {
return '';
}
const diff = Date.now() - ts;
const mins = Math.floor(diff / 60_000);
if (mins < 1) {
return 'now';
}
if (mins < 60) {
return `${mins}m`;
}
const hrs = Math.floor(mins / 60);
if (hrs < 24) {
return `${hrs}h`;
}
const days = Math.floor(hrs / 24);
if (days < 7) {
return `${days}d`;
}
return new Date(ts).toLocaleDateString(undefined, {
month: 'short',
day: 'numeric',
});
}

View File

@@ -5,7 +5,7 @@ import { Popover } from 'antd';
import LogsIcon from 'assets/AlertHistory/LogsIcon';
import ROUTES from 'constants/routes';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { DraftingCompass } from '@signozhq/icons';
import { Brain, DraftingCompass } from '@signozhq/icons';
import './AlertPopover.styles.scss';
@@ -13,14 +13,17 @@ type Props = {
children: React.ReactNode;
relatedTracesLink?: string;
relatedLogsLink?: string;
relatedAITracesLink?: string;
};
function PopoverContent({
relatedTracesLink,
relatedLogsLink,
relatedAITracesLink,
}: {
relatedTracesLink?: Props['relatedTracesLink'];
relatedLogsLink?: Props['relatedLogsLink'];
relatedAITracesLink?: Props['relatedAITracesLink'];
}): JSX.Element {
const isDarkMode = useIsDarkMode();
return (
@@ -52,18 +55,35 @@ function PopoverContent({
<div className="text">View Traces</div>
</AppLink>
)}
{!!relatedAITracesLink && (
<AppLink
to={`${ROUTES.AI_OBSERVABILITY_EXPLORER}?${relatedAITracesLink}`}
className="contributor-row-popover-buttons__button"
data-testid="alert-popover-view-ai-traces"
>
<div className="icon">
<Brain
size={14}
color={isDarkMode ? Color.BG_VANILLA_400 : Color.TEXT_INK_400}
/>
</div>
<div className="text">View AI Traces</div>
</AppLink>
)}
</div>
);
}
PopoverContent.defaultProps = {
relatedTracesLink: '',
relatedLogsLink: '',
relatedAITracesLink: '',
};
function AlertPopover({
children,
relatedTracesLink,
relatedLogsLink,
relatedAITracesLink,
}: Props): JSX.Element {
return (
<div className="alert-popover-trigger-action">
@@ -77,6 +97,7 @@ function AlertPopover({
<PopoverContent
relatedTracesLink={relatedTracesLink}
relatedLogsLink={relatedLogsLink}
relatedAITracesLink={relatedAITracesLink}
/>
}
trigger="click"
@@ -90,23 +111,27 @@ function AlertPopover({
AlertPopover.defaultProps = {
relatedTracesLink: '',
relatedLogsLink: '',
relatedAITracesLink: '',
};
type ConditionalAlertPopoverProps = {
relatedTracesLink: string;
relatedLogsLink: string;
relatedAITracesLink: string;
children: React.ReactNode;
};
export function ConditionalAlertPopover({
children,
relatedTracesLink,
relatedLogsLink,
relatedAITracesLink,
}: ConditionalAlertPopoverProps): JSX.Element {
if (relatedTracesLink || relatedLogsLink) {
if (relatedTracesLink || relatedLogsLink || relatedAITracesLink) {
return (
<AlertPopover
relatedTracesLink={relatedTracesLink}
relatedLogsLink={relatedLogsLink}
relatedAITracesLink={relatedAITracesLink}
>
{children}
</AlertPopover>

View File

@@ -0,0 +1,76 @@
import ROUTES from 'constants/routes';
import { render, screen, userEvent } from 'tests/test-utils';
import { ConditionalAlertPopover } from '../AlertPopover';
const AI_TRACES_LINK = 'compositeQuery=ai&startTime=1&endTime=2';
const TRACES_LINK = 'compositeQuery=traces&startTime=1&endTime=2';
const TRIGGER_TEST_ID = 'popover-trigger';
const renderPopover = (links: {
relatedTracesLink?: string;
relatedLogsLink?: string;
relatedAITracesLink?: string;
}): void => {
render(
<ConditionalAlertPopover
relatedTracesLink={links.relatedTracesLink ?? ''}
relatedLogsLink={links.relatedLogsLink ?? ''}
relatedAITracesLink={links.relatedAITracesLink ?? ''}
>
<button type="button" data-testid={TRIGGER_TEST_ID}>
open
</button>
</ConditionalAlertPopover>,
);
};
describe('ConditionalAlertPopover', () => {
it('links an AI traces alert to the AI observability explorer', async () => {
const user = userEvent.setup();
renderPopover({ relatedAITracesLink: AI_TRACES_LINK });
await user.click(screen.getByTestId(TRIGGER_TEST_ID));
const link = await screen.findByTestId('alert-popover-view-ai-traces');
expect(link).toHaveTextContent('View AI Traces');
expect(link).toHaveAttribute(
'href',
`${ROUTES.AI_OBSERVABILITY_EXPLORER}?${AI_TRACES_LINK}`,
);
expect(
screen.queryByTestId('alert-popover-view-traces'),
).not.toBeInTheDocument();
});
it('keeps traces alerts on the traces explorer', async () => {
const user = userEvent.setup();
renderPopover({ relatedTracesLink: TRACES_LINK });
await user.click(screen.getByTestId(TRIGGER_TEST_ID));
await expect(
screen.findByTestId('alert-popover-view-traces'),
).resolves.toHaveAttribute(
'href',
`${ROUTES.TRACES_EXPLORER}?${TRACES_LINK}`,
);
expect(
screen.queryByTestId('alert-popover-view-ai-traces'),
).not.toBeInTheDocument();
});
it('renders no popover without any link', async () => {
const user = userEvent.setup();
renderPopover({});
await user.click(screen.getByTestId(TRIGGER_TEST_ID));
expect(
screen.queryByTestId('alert-popover-view-ai-traces'),
).not.toBeInTheDocument();
expect(
screen.queryByTestId('alert-popover-view-traces'),
).not.toBeInTheDocument();
});
});

View File

@@ -31,6 +31,7 @@ function TopContributorsRows({
<ConditionalAlertPopover
relatedTracesLink={record.relatedTracesLink}
relatedLogsLink={record.relatedLogsLink}
relatedAITracesLink={record.relatedAITracesLink}
>
<div>
<AlertLabels labels={labels} />
@@ -47,6 +48,7 @@ function TopContributorsRows({
<ConditionalAlertPopover
relatedTracesLink={record.relatedTracesLink}
relatedLogsLink={record.relatedLogsLink}
relatedAITracesLink={record.relatedAITracesLink}
>
<div className="top-contributors-progress">
<Progress
@@ -67,6 +69,7 @@ function TopContributorsRows({
<ConditionalAlertPopover
relatedTracesLink={record.relatedTracesLink}
relatedLogsLink={record.relatedLogsLink}
relatedAITracesLink={record.relatedAITracesLink}
>
<div
className="total-contribution"

View File

@@ -27,6 +27,7 @@ function TopContributorsRenderer({
labels: labelsArrayToObject(contributor.labels),
relatedLogsLink: contributor.relatedLogsLink ?? '',
relatedTracesLink: contributor.relatedTracesLink ?? '',
relatedAITracesLink: contributor.relatedAITracesLink ?? '',
}));
}, [data?.data]);

View File

@@ -69,6 +69,7 @@ function TimelineTableContent(): JSX.Element {
labels: labelsArrayToObject(item.labels),
relatedLogsLink: item.relatedLogsLink,
relatedTracesLink: item.relatedTracesLink,
relatedAITracesLink: item.relatedAITracesLink,
};
});

View File

@@ -49,7 +49,11 @@ export const timelineTableColumns = ({
width: 140,
align: 'right',
render: (_, record): JSX.Element => {
if (!record.relatedTracesLink && !record.relatedLogsLink) {
if (
!record.relatedTracesLink &&
!record.relatedLogsLink &&
!record.relatedAITracesLink
) {
return (
<Tooltip title="No links available for this item">
<Button type="text" ghost disabled data-testid="timeline-row-actions">
@@ -63,6 +67,7 @@ export const timelineTableColumns = ({
<ConditionalAlertPopover
relatedTracesLink={record.relatedTracesLink ?? ''}
relatedLogsLink={record.relatedLogsLink ?? ''}
relatedAITracesLink={record.relatedAITracesLink ?? ''}
>
<Button type="text" ghost data-testid="timeline-row-actions">
<Ellipsis className="dropdown-icon" size="md" />

View File

@@ -93,6 +93,7 @@ describe('Alert history navigations keep the expression', () => {
count: fingerprint,
relatedLogsLink: '',
relatedTracesLink: '',
relatedAITracesLink: '',
}));
render(
<>

View File

@@ -14,7 +14,6 @@ import uPlot from 'uplot';
import tooltipPlugin from './tooltipPlugin';
import 'uplot/dist/uPlot.min.css';
import './AnomalyAlertEvaluationView.styles.scss';
const { Search } = Input;

View File

@@ -0,0 +1,60 @@
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { screen } from 'tests/test-utils';
import { flushPendingImports, renderAppLayout } from './testUtils';
const mockPanelModuleLoaded = jest.fn();
const mockModalModuleLoaded = jest.fn();
jest.mock('hooks/useIsAIAssistantEnabled', () => ({
useIsAIAssistantEnabled: jest.fn(),
}));
jest.mock('container/AIAssistant/AIAssistantPanel', () => {
mockPanelModuleLoaded();
return {
__esModule: true,
default: (): JSX.Element => <div data-testid="ai-assistant-panel" />,
};
});
jest.mock('container/AIAssistant/AIAssistantModal', () => {
mockModalModuleLoaded();
return {
__esModule: true,
default: (): JSX.Element => <div data-testid="ai-assistant-modal" />,
};
});
describe('AppLayout AI assistant', () => {
beforeEach(() => {
mockPanelModuleLoaded.mockClear();
mockModalModuleLoaded.mockClear();
useAIAssistantStore.setState({ fetchThreads: jest.fn() });
});
it('does not load the assistant for users who do not have it', async () => {
jest.mocked(useIsAIAssistantEnabled).mockReturnValue(false);
renderAppLayout({ isLoggedIn: true });
await flushPendingImports();
expect(screen.getByTestId('page-content')).toBeInTheDocument();
expect(screen.queryByTestId('ai-assistant-panel')).not.toBeInTheDocument();
expect(mockPanelModuleLoaded).not.toHaveBeenCalled();
expect(mockModalModuleLoaded).not.toHaveBeenCalled();
});
it('loads the assistant panel and modal for users who have it', async () => {
jest.mocked(useIsAIAssistantEnabled).mockReturnValue(true);
renderAppLayout({ isLoggedIn: true });
expect(screen.getByTestId('page-content')).toBeInTheDocument();
await expect(
screen.findByTestId('ai-assistant-panel'),
).resolves.toBeInTheDocument();
expect(screen.getByTestId('ai-assistant-modal')).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,36 @@
import { changelog } from 'components/ChangelogModal/stories/__story_mockdata__/changelog';
import { screen } from 'tests/test-utils';
import { flushPendingImports, renderAppLayout } from './testUtils';
const mockChangelogModuleLoaded = jest.fn();
jest.mock('components/ChangelogModal/ChangelogModal', () => {
mockChangelogModuleLoaded();
return {
__esModule: true,
default: (): JSX.Element => <div data-testid="changelog-modal" />,
};
});
describe('AppLayout changelog modal', () => {
beforeEach(() => {
mockChangelogModuleLoaded.mockClear();
});
it('does not load the changelog modal until it opens', async () => {
renderAppLayout({ changelog, showChangelogModal: false });
await flushPendingImports();
expect(screen.queryByTestId('changelog-modal')).not.toBeInTheDocument();
expect(mockChangelogModuleLoaded).not.toHaveBeenCalled();
});
it('loads and shows the changelog modal when it opens', async () => {
renderAppLayout({ changelog, showChangelogModal: true });
await expect(
screen.findByTestId('changelog-modal'),
).resolves.toBeInTheDocument();
});
});

View File

@@ -0,0 +1,56 @@
import { changelog } from 'components/ChangelogModal/stories/__story_mockdata__/changelog';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { screen } from 'tests/test-utils';
import { flushPendingImports, renderAppLayout } from './testUtils';
jest.mock('utils/lazyWithRetries', () => ({
lazyRetry: (componentImport: () => Promise<unknown>): Promise<unknown> =>
componentImport(),
}));
jest.mock('hooks/useIsAIAssistantEnabled', () => ({
useIsAIAssistantEnabled: jest.fn(),
}));
jest.mock('container/AIAssistant/AIAssistantPanel', () => {
throw new Error('Failed to fetch dynamically imported module');
});
jest.mock('container/AIAssistant/AIAssistantModal', () => {
throw new Error('Failed to fetch dynamically imported module');
});
jest.mock('components/ChangelogModal/ChangelogModal', () => {
throw new Error('Failed to fetch dynamically imported module');
});
describe('AppLayout when a lazy overlay fails to download', () => {
beforeEach(() => {
jest.spyOn(console, 'error').mockImplementation(() => {});
useAIAssistantStore.setState({ fetchThreads: jest.fn() });
});
afterEach(() => {
jest.mocked(console.error).mockRestore();
});
it('keeps the page when the assistant download fails', async () => {
jest.mocked(useIsAIAssistantEnabled).mockReturnValue(true);
renderAppLayout({ isLoggedIn: true, changelog, showChangelogModal: false });
await flushPendingImports();
expect(screen.getByTestId('page-content')).toHaveTextContent('Page content');
});
it('keeps the page when the changelog download fails', async () => {
jest.mocked(useIsAIAssistantEnabled).mockReturnValue(false);
renderAppLayout({ isLoggedIn: true, changelog, showChangelogModal: true });
await flushPendingImports();
expect(screen.getByTestId('page-content')).toHaveTextContent('Page content');
});
});

View File

@@ -0,0 +1,30 @@
import { HelmetProvider } from 'react-helmet-async';
import { CmdKProvider } from 'providers/cmdKProvider';
import { IAppContext } from 'providers/App/types';
import { act, render } from 'tests/test-utils';
import AppLayout from '../index';
export async function flushPendingImports(): Promise<void> {
await act(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 0);
});
});
}
export function renderAppLayout(
appContextOverrides: Partial<IAppContext>,
): void {
render(
<HelmetProvider>
<CmdKProvider>
<AppLayout>
<div data-testid="page-content">Page content</div>
</AppLayout>
</CmdKProvider>
</HelmetProvider>,
undefined,
{ appContextOverrides },
);
}

View File

@@ -1,5 +1,7 @@
import {
lazy,
ReactNode,
Suspense,
useCallback,
useEffect,
useMemo,
@@ -27,7 +29,6 @@ import getUserLatestVersion from 'api/v1/version/getLatestVersion';
import { AxiosError } from 'axios';
import cx from 'classnames';
import AppToaster from 'components/AppToaster/AppToaster';
import ChangelogModal from 'components/ChangelogModal/ChangelogModal';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import RefreshPaymentStatus from 'components/RefreshPaymentStatus/RefreshPaymentStatus';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
@@ -38,8 +39,6 @@ import { LOCALSTORAGE } from 'constants/localStorage';
import ROUTES from 'constants/routes';
import { GlobalShortcuts } from 'constants/shortcuts/globalShortcuts';
import { USER_PREFERENCES } from 'constants/userPreferences';
import AIAssistantModal from 'container/AIAssistant/AIAssistantModal';
import AIAssistantPanel from 'container/AIAssistant/AIAssistantPanel';
import { useAIAssistantStore } from 'container/AIAssistant/store/useAIAssistantStore';
import BottomStrip from 'container/BottomStrip';
import SideNav from 'container/SideNav';
@@ -81,6 +80,7 @@ import AppReducer from 'types/reducer/app';
import { getBaseUrl } from 'utils/basePath';
import { showErrorNotification } from 'utils/error';
import { eventEmitter } from 'utils/getEventEmitter';
import { lazyRetry } from 'utils/lazyWithRetries';
import {
getFormattedDate,
getFormattedDateWithMinutes,
@@ -92,6 +92,19 @@ import { getRouteKey } from './utils';
import './AppLayout.styles.scss';
// The assistant pulls in the dashboard panel registry and the query builder, so it
// loads only for users who have it.
const AIAssistantModal = lazy(() =>
lazyRetry(() => import('container/AIAssistant/AIAssistantModal')),
);
const AIAssistantPanel = lazy(() =>
lazyRetry(() => import('container/AIAssistant/AIAssistantPanel')),
);
const ChangelogModal = lazy(() =>
lazyRetry(() => import('components/ChangelogModal/ChangelogModal')),
);
// eslint-disable-next-line sonarjs/cognitive-complexity
function AppLayout(props: AppLayoutProps): JSX.Element {
const {
@@ -832,15 +845,21 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
</div>
{isLoggedIn && isAIAssistantEnabled && (
<>
<AIAssistantPanel />
<AIAssistantModal />
</>
<Sentry.ErrorBoundary>
<Suspense fallback={null}>
<AIAssistantPanel />
<AIAssistantModal />
</Suspense>
</Sentry.ErrorBoundary>
)}
</Flex>
{showChangelogModal && changelog && (
<ChangelogModal changelog={changelog} onClose={toggleChangelogModal} />
<Sentry.ErrorBoundary>
<Suspense fallback={null}>
<ChangelogModal changelog={changelog} onClose={toggleChangelogModal} />
</Suspense>
</Sentry.ErrorBoundary>
)}
<AppToaster />

View File

@@ -3,32 +3,3 @@
align-items: center;
flex-shrink: 0;
}
.badge {
flex-shrink: 0;
display: inline-flex;
color: var(--accent-primary);
}
.pulseDot {
position: relative;
display: inline-flex;
align-items: center;
justify-content: center;
animation: askNozDotPulse 1.5s ease-in-out infinite;
transform: scale(0.8);
margin-right: -12px;
}
@keyframes askNozDotPulse {
0%,
100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.35;
transform: scale(0.82);
}
}

View File

@@ -8,57 +8,51 @@ import {
AIAssistantEvents,
AIAssistantOpenSource,
} from 'container/AIAssistant/events';
import { normalizePage } from 'container/AIAssistant/hooks/useAIAssistantAnalyticsContext';
import { selectPendingUserInputStreamCount } from 'container/AIAssistant/store/pendingInputSelectors';
import {
openAIAssistant,
normalizePage,
useAIAssistantAnalyticsContext,
} from 'container/AIAssistant/hooks/useAIAssistantAnalyticsContext';
import {
openNewAIAssistantChat,
useAIAssistantStore,
} from 'container/AIAssistant/store/useAIAssistantStore';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { useAppLocation } from 'lib/router/useAppLocation';
import ROUTES from 'constants/routes';
import { Dot } from '@signozhq/icons';
import styles from './AskNoz.module.scss';
/**
* Opens the Noz drawer, matching the header entry it replaces. Cmd+K opens the
* modal instead; this is deliberately the drawer. It stays while the drawer is
* open, where it closes the drawer and keeps the chat for the next open.
*
* Carries the header's pending badge: when Noz is blocked on the user
* (`awaiting_approval` / `awaiting_clarification`) a dot pulses. Without it,
* hiding the header button would remove a notification rather than move it.
* Opens the Noz drawer on a new chat, matching the header entry it replaces.
* Cmd+K opens the modal instead; this is deliberately the drawer. It stays while
* the drawer is open, where it is the way to start another chat.
*/
function AskNoz(): JSX.Element | null {
const { pathname } = useAppLocation();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const isDrawerOpen = useAIAssistantStore((state) => state.isDrawerOpen);
const isModalOpen = useAIAssistantStore((state) => state.isModalOpen);
const pendingUserInputCount = useAIAssistantStore(
selectPendingUserInputStreamCount,
);
const closeDrawer = useAIAssistantStore((state) => state.closeDrawer);
// Noz is already on screen in the drawer or modal, so the "needs you" dot would be noise.
const showPendingBadge =
pendingUserInputCount > 0 && !isDrawerOpen && !isModalOpen;
// The drawer does not render on the Noz full page, so the button would be inert.
const isAIAssistantPage = pathname.startsWith(ROUTES.AI_ASSISTANT_BASE);
const handleClick = useCallback((): void => {
const analyticsCtx = useAIAssistantAnalyticsContext();
const handleOpen = useCallback((): void => {
if (isDrawerOpen) {
closeDrawer();
return;
void logEvent(AIAssistantEvents.NewChatClicked, {
...analyticsCtx,
// Outside the panel's VariantContext the hook reports 'page'; the chat opens in the drawer.
mode: 'sidepane',
source: AIAssistantOpenSource.BottomStrip,
});
} else {
void logEvent(AIAssistantEvents.Opened, {
source: AIAssistantOpenSource.BottomStrip,
currentPage: normalizePage(pathname),
});
}
void logEvent(AIAssistantEvents.Opened, {
source: AIAssistantOpenSource.BottomStrip,
currentPage: normalizePage(pathname),
});
openAIAssistant();
}, [closeDrawer, isDrawerOpen, pathname]);
openNewAIAssistantChat();
}, [analyticsCtx, isDrawerOpen, pathname]);
if (!isAIAssistantEnabled || isAIAssistantPage) {
return null;
@@ -66,13 +60,6 @@ function AskNoz(): JSX.Element | null {
return (
<div className={styles.askNoz} data-testid="bottom-strip-ask-noz">
{showPendingBadge && (
<span className={styles.badge} aria-hidden>
<span className={styles.pulseDot}>
<Dot size={36} />
</span>
</span>
)}
<span className="noz-wave">
<Tooltip title={NOZ_TOOLTIP_TITLE}>
<Button
@@ -81,15 +68,7 @@ function AskNoz(): JSX.Element | null {
size="sm"
prefix={<Noz size={16} />}
testId="bottom-strip-ask-noz-button"
onClick={handleClick}
aria-pressed={isDrawerOpen}
aria-label={
showPendingBadge
? `Ask Noz, ${pendingUserInputCount} ${
pendingUserInputCount === 1 ? 'action needs' : 'actions need'
} your response`
: 'Ask Noz'
}
onClick={handleOpen}
>
Ask Noz
</Button>

View File

@@ -3,7 +3,7 @@ import {
AIAssistantEvents,
AIAssistantOpenSource,
} from 'container/AIAssistant/events';
import { openAIAssistant } from 'container/AIAssistant/store/useAIAssistantStore';
import { openNewAIAssistantChat } from 'container/AIAssistant/store/useAIAssistantStore';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { render, userEvent } from 'tests/test-utils';
@@ -11,43 +11,26 @@ import AskNoz from '../AskNoz';
jest.mock('hooks/useIsAIAssistantEnabled');
jest.mock('container/AIAssistant/store/useAIAssistantStore', () => ({
openAIAssistant: jest.fn(),
openNewAIAssistantChat: jest.fn(),
useAIAssistantStore: jest.fn(),
}));
const mockEnabled = useIsAIAssistantEnabled as jest.MockedFunction<
typeof useIsAIAssistantEnabled
>;
const mockOpen = openAIAssistant as jest.MockedFunction<typeof openAIAssistant>;
const mockClose = jest.fn() as jest.MockedFunction<() => void>;
const mockOpenNew = jest.mocked(openNewAIAssistantChat);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const { useAIAssistantStore } = jest.requireMock(
'container/AIAssistant/store/useAIAssistantStore',
) as { useAIAssistantStore: jest.Mock };
/** The component reads the store through three separate selector calls. */
function mockStore({
isDrawerOpen = false,
isModalOpen = false,
pendingCount = 0,
}: {
isDrawerOpen?: boolean;
isModalOpen?: boolean;
pendingCount?: number;
} = {}): void {
const state = {
isDrawerOpen,
isModalOpen,
streams: {},
closeDrawer: mockClose,
};
useAIAssistantStore.mockImplementation((selector: (s: unknown) => unknown) => {
const picked = selector(state);
// `selectPendingUserInputStreamCount` walks `streams`, which is empty here,
// so stand in the count we want to assert against.
return typeof picked === 'number' ? pendingCount : picked;
});
}: { isDrawerOpen?: boolean } = {}): void {
useAIAssistantStore.mockImplementation((selector: (s: unknown) => unknown) =>
selector({ isDrawerOpen }),
);
}
const SLOT = 'bottom-strip-ask-noz';
@@ -75,12 +58,12 @@ describe('AskNoz', () => {
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
});
it('stays pressed while the drawer is open', () => {
it('stays while the drawer is open, to start another chat', () => {
mockStore({ isDrawerOpen: true });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-pressed', 'true');
expect(getByTestId(BUTTON)).toHaveTextContent('Ask Noz');
});
it('renders nothing on the Noz full page, where the drawer does not mount', () => {
@@ -93,25 +76,34 @@ describe('AskNoz', () => {
});
describe('what it does', () => {
it('opens the drawer on click', async () => {
it('opens the drawer on a new chat', async () => {
const user = userEvent.setup();
const { getByTestId } = render(<AskNoz />);
await user.click(getByTestId(BUTTON));
expect(mockOpen).toHaveBeenCalledTimes(1);
expect(mockOpenNew).toHaveBeenCalledTimes(1);
});
it('closes the open drawer on the same chat instead of starting a new one', async () => {
it('starts a new chat from the open drawer and reports it as one', async () => {
const user = userEvent.setup();
mockStore({ isDrawerOpen: true });
const { getByTestId } = render(<AskNoz />);
await user.click(getByTestId(BUTTON));
expect(mockClose).toHaveBeenCalledTimes(1);
expect(mockOpen).not.toHaveBeenCalled();
expect(logEvent).not.toHaveBeenCalled();
expect(mockOpenNew).toHaveBeenCalledTimes(1);
expect(logEvent).toHaveBeenCalledWith(
AIAssistantEvents.NewChatClicked,
expect.objectContaining({
mode: 'sidepane',
source: AIAssistantOpenSource.BottomStrip,
}),
);
expect(logEvent).not.toHaveBeenCalledWith(
AIAssistantEvents.Opened,
expect.anything(),
);
});
it('reports the open as coming from the strip', async () => {
@@ -126,50 +118,4 @@ describe('AskNoz', () => {
);
});
});
describe('pending badge', () => {
it('announces the count when Noz is waiting on the user', () => {
mockStore({ pendingCount: 2 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute(
'aria-label',
'Ask Noz, 2 actions need your response',
);
});
it('uses the singular for one pending action', () => {
mockStore({ pendingCount: 1 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute(
'aria-label',
'Ask Noz, 1 action needs your response',
);
});
it('stays quiet when nothing is pending', () => {
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
});
it('stays quiet while the drawer is open, Noz is already on screen', () => {
mockStore({ isDrawerOpen: true, pendingCount: 3 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
});
it('stays quiet while the modal is open, Noz is already on screen', () => {
mockStore({ isModalOpen: true, pendingCount: 3 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
});
});
});

View File

@@ -36,6 +36,28 @@
cursor: default;
}
// Takes what the left slot leaves; `safe` overflows to the end, not over the left slot.
.right {
flex: 1 1 0;
justify-content: safe flex-end;
}
.right > * {
flex-shrink: 0;
}
// The only right-side entity that shrinks: tabs give way before Ask Noz and Support.
.chats {
display: flex;
align-items: center;
flex-shrink: 1;
min-width: 0;
&:empty {
display: none;
}
}
// separator b/w strip entities
.left > *:not(:last-child)::after,
.right > *:not(:last-child)::after {

View File

@@ -0,0 +1,7 @@
.dot {
flex-shrink: 0;
width: var(--spacing-3);
height: var(--spacing-3);
border-radius: var(--radius-round);
background: var(--accent-primary);
}

View File

@@ -0,0 +1,62 @@
import { useMemo } from 'react';
import ROUTES from 'constants/routes';
import { useAIAssistantActiveChats } from 'container/AIAssistant/hooks/useAIAssistantActiveChats';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { matchRoute } from 'lib/router/matchRoute';
import { useAppLocation } from 'lib/router/useAppLocation';
import StripTabs from '../components/StripTabs/StripTabs';
import type { StripTabItem } from '../types';
import styles from './NozActiveChat.module.scss';
const UNTITLED = 'New conversation';
/** One tab per open Noz conversation; a dot marks an unseen reply or Noz waiting on the user. */
function NozActiveChat(): JSX.Element | null {
const { pathname } = useAppLocation();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const isAIAssistantPage = !!matchRoute(pathname, ROUTES.AI_ASSISTANT, {
exact: true,
});
const { chats, openChat, closeChat } =
useAIAssistantActiveChats(isAIAssistantPage);
const items = useMemo(
() =>
chats.map((chat): StripTabItem => {
const title = chat.title ?? UNTITLED;
let ariaLabel: string | undefined;
if (chat.isAwaitingUser) {
ariaLabel = `Noz needs your response in ${title}`;
} else if (chat.hasUnreadReply) {
ariaLabel = `Noz replied in ${title}`;
}
return {
id: chat.threadId,
label: title,
isActive: chat.isActive,
prefix: ariaLabel ? (
<span className={styles.dot} aria-hidden />
) : undefined,
ariaLabel,
};
}),
[chats],
);
if (!isAIAssistantEnabled) {
return null;
}
return (
<StripTabs
items={items}
onSelect={openChat}
onClose={closeChat}
testId="bottom-strip-noz-chats"
/>
);
}
export default NozActiveChat;

View File

@@ -0,0 +1,456 @@
import {
type AIAssistantStore,
useAIAssistantStore,
} from 'container/AIAssistant/store/useAIAssistantStore';
import type {
Conversation,
ConversationStreamState,
Message,
} from 'container/AIAssistant/types';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
import NozActiveChat from '../NozActiveChat';
import { useAIAssistantOpenConversationsStore } from 'container/AIAssistant/store/useAIAssistantOpenConversationsStore';
jest.mock('hooks/useIsAIAssistantEnabled');
const mockEnabled = jest.mocked(useIsAIAssistantEnabled);
const initialAIState = useAIAssistantStore.getState();
const initialTabsState = useAIAssistantOpenConversationsStore.getState();
const TABS = 'bottom-strip-noz-chats';
const OPEN_BUTTONS = /^bottom-strip-noz-chats-.+-open$/;
const message: Message = {
id: 'm1',
role: 'assistant',
content: 'Hi',
createdAt: 0,
};
const awaitingApproval: ConversationStreamState = {
isStreaming: false,
streamingContent: '',
streamingStatus: 'awaiting_approval',
streamingEvents: [],
streamingMessageId: null,
streamingActions: null,
pendingApproval: null,
pendingClarification: null,
startedAt: 0,
};
const chat = (id: string, title: string, loaded = false): Conversation => ({
id,
threadId: id,
title,
messages: loaded ? [message] : [],
createdAt: 0,
});
interface Seed {
conversations: Conversation[];
tabs?: string[];
unread?: string[];
streams?: Record<string, ConversationStreamState>;
activeConversationId?: string | null;
isDrawerOpen?: boolean;
hasLoadedThreads?: boolean;
}
function seed({
conversations,
tabs = [],
unread = [],
streams = {},
activeConversationId = null,
isDrawerOpen = false,
hasLoadedThreads = true,
}: Seed): jest.MockedFunction<AIAssistantStore['loadThread']> {
const loadThread = jest.fn() as jest.MockedFunction<
AIAssistantStore['loadThread']
>;
loadThread.mockResolvedValue();
useAIAssistantStore.setState({
conversations: Object.fromEntries(conversations.map((c) => [c.id, c])),
unreadReplyIds: unread,
streams,
activeConversationId,
isDrawerOpen,
hasLoadedThreads,
loadThread,
});
useAIAssistantOpenConversationsStore.setState({ threadIds: tabs });
return loadThread;
}
const tabLabels = (): (string | null)[] =>
screen.queryAllByTestId(OPEN_BUTTONS).map((button) => button.textContent);
const openTabs = (): string[] =>
useAIAssistantOpenConversationsStore.getState().threadIds;
describe('NozActiveChat', () => {
const play = jest.spyOn(HTMLMediaElement.prototype, 'play');
beforeEach(() => {
jest.clearAllMocks();
mockEnabled.mockReturnValue(true);
play.mockResolvedValue();
});
afterEach(() => {
useAIAssistantStore.setState(initialAIState, true);
useAIAssistantOpenConversationsStore.setState(initialTabsState, true);
localStorage.clear();
});
describe('tabs', () => {
it('shows the open chats in open order, with a dot on an unseen reply', () => {
seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta')],
tabs: ['a', 'b'],
unread: ['b'],
});
render(<NozActiveChat />);
expect(tabLabels()).toStrictEqual(['Alpha', 'Beta']);
expect(screen.getByTestId(`${TABS}-b-open`)).toHaveAttribute(
'aria-label',
'Noz replied in Beta',
);
expect(screen.getByTestId(`${TABS}-a-open`)).not.toHaveAttribute(
'aria-label',
);
});
it('marks a chat Noz is waiting on with a dot, until it is on screen', () => {
seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta')],
tabs: ['a', 'b'],
streams: { b: awaitingApproval },
});
render(<NozActiveChat />);
expect(screen.getByTestId(`${TABS}-b-open`)).toHaveAttribute(
'aria-label',
'Noz needs your response in Beta',
);
act(() => {
useAIAssistantStore.setState({
activeConversationId: 'b',
isDrawerOpen: true,
});
});
expect(screen.getByTestId(`${TABS}-b-open`)).not.toHaveAttribute(
'aria-label',
);
});
it('shows on the Noz page, with the chat on the page current', () => {
seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta')],
tabs: ['a', 'b'],
activeConversationId: 'a',
});
render(<NozActiveChat />, undefined, { initialRoute: '/ai-assistant/a' });
expect(tabLabels()).toStrictEqual(['Alpha', 'Beta']);
expect(screen.getByTestId(`${TABS}-a-open`)).toHaveAttribute(
'aria-current',
'true',
);
});
it('renders nothing when the assistant is disabled', () => {
mockEnabled.mockReturnValue(false);
seed({ conversations: [chat('a', 'Alpha')], tabs: ['a'] });
render(<NozActiveChat />);
expect(screen.queryByTestId(TABS)).not.toBeInTheDocument();
});
});
describe('what joins and leaves', () => {
it('adds the chat the panel is showing, marked current', () => {
seed({
conversations: [chat('a', 'Alpha')],
activeConversationId: 'a',
isDrawerOpen: true,
});
render(<NozActiveChat />);
expect(openTabs()).toStrictEqual(['a']);
expect(screen.getByTestId(`${TABS}-a-open`)).toHaveAttribute(
'aria-current',
'true',
);
});
it('adds a chat whose reply lands without a tab', () => {
seed({ conversations: [chat('a', 'Alpha')] });
render(<NozActiveChat />);
act(() => {
useAIAssistantStore.setState({ unreadReplyIds: ['a'] });
});
expect(openTabs()).toStrictEqual(['a']);
expect(tabLabels()).toStrictEqual(['Alpha']);
});
it('keeps a chat evicted past the cap out as other chats change', () => {
const chats = ['a', 'b', 'c', 'd', 'e', 'f'].map((id) => chat(id, id));
seed({
conversations: chats,
tabs: ['a', 'b', 'c', 'd', 'e'],
unread: ['a'],
});
render(<NozActiveChat />);
act(() => {
useAIAssistantOpenConversationsStore.getState().open('f');
});
act(() => {
useAIAssistantStore.setState((s) => {
s.conversations.f.messages = [message];
});
});
expect(openTabs()).toStrictEqual(['b', 'c', 'd', 'e', 'f']);
});
it('adds a chat once Noz starts waiting on the user in it', () => {
seed({ conversations: [chat('a', 'Alpha')] });
render(<NozActiveChat />);
act(() => {
useAIAssistantStore.setState({ streams: { a: awaitingApproval } });
});
expect(openTabs()).toStrictEqual(['a']);
});
it('keeps a closed chat out while Noz still waits in it', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta')],
tabs: ['a'],
streams: { a: awaitingApproval },
});
render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-a-close`));
act(() => {
useAIAssistantStore.setState({
streams: { a: awaitingApproval, b: awaitingApproval },
});
});
expect(openTabs()).toStrictEqual(['b']);
});
it('keeps a closed chat out when the strip remounts while Noz still waits in it', async () => {
const user = userEvent.setup();
seed({
conversations: [chat('a', 'Alpha')],
tabs: ['a'],
streams: { a: awaitingApproval },
});
const { unmount } = render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-a-close`));
unmount();
render(<NozActiveChat />);
expect(openTabs()).toStrictEqual([]);
});
it('closing a tab removes it and dismisses its unseen reply', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta')],
tabs: ['a', 'b'],
unread: ['b'],
});
render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-b-close`));
expect(openTabs()).toStrictEqual(['a']);
expect(useAIAssistantStore.getState().unreadReplyIds).toStrictEqual([]);
expect(tabLabels()).toStrictEqual(['Alpha']);
});
it('keeps a tab the thread list has not confirmed until the list loads', () => {
seed({
conversations: [chat('a', 'Alpha')],
tabs: ['a', 'gone'],
hasLoadedThreads: false,
});
render(<NozActiveChat />);
expect(openTabs()).toStrictEqual(['a', 'gone']);
expect(tabLabels()).toStrictEqual(['Alpha']);
act(() => {
useAIAssistantStore.setState({ hasLoadedThreads: true });
});
expect(openTabs()).toStrictEqual(['a']);
});
});
describe('opening a tab', () => {
it('loads a chat whose messages are not loaded yet and opens the panel', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const loadThread = seed({
conversations: [chat('a', 'Alpha')],
tabs: ['a'],
});
render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-a-open`));
expect(loadThread).toHaveBeenCalledWith('a');
expect(useAIAssistantStore.getState().isDrawerOpen).toBe(true);
});
it('retries loading the selected chat when its messages never arrived', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const loadThread = seed({
conversations: [chat('a', 'Alpha')],
tabs: ['a'],
activeConversationId: 'a',
isDrawerOpen: true,
});
render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-a-open`));
expect(loadThread).toHaveBeenCalledWith('a');
});
it('loads a chat while another one is loading', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const loadThread = seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta')],
tabs: ['a', 'b'],
activeConversationId: 'a',
});
useAIAssistantStore.setState({ loadingThreadIds: ['a'] });
render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-b-open`));
expect(loadThread).toHaveBeenCalledWith('b');
});
it('shows a chat that is still loading without requesting it again', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const loadThread = seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta', true)],
tabs: ['a', 'b'],
activeConversationId: 'b',
});
useAIAssistantStore.setState({ loadingThreadIds: ['a'] });
render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-a-open`));
expect(loadThread).not.toHaveBeenCalled();
expect(useAIAssistantStore.getState().activeConversationId).toBe('a');
});
it('opens a chat in the Noz page rather than the panel', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
seed({
conversations: [chat('a', 'Alpha', true), chat('b', 'Beta', true)],
tabs: ['a', 'b'],
activeConversationId: 'a',
});
render(<NozActiveChat />, undefined, { initialRoute: '/ai-assistant/a' });
await user.click(screen.getByTestId(`${TABS}-b-open`));
expect(useAIAssistantStore.getState().activeConversationId).toBe('b');
expect(useAIAssistantStore.getState().isDrawerOpen).toBe(false);
});
it('switches to a loaded chat without refetching it', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const loadThread = seed({
conversations: [chat('a', 'Alpha', true)],
tabs: ['a'],
});
render(<NozActiveChat />);
await user.click(screen.getByTestId(`${TABS}-a-open`));
expect(loadThread).not.toHaveBeenCalled();
expect(useAIAssistantStore.getState().activeConversationId).toBe('a');
expect(useAIAssistantStore.getState().isDrawerOpen).toBe(true);
});
});
describe('reply sound', () => {
it('chimes when a reply lands in a chat that is not on screen', async () => {
seed({ conversations: [chat('a', 'Alpha')] });
render(<NozActiveChat />);
act(() => {
useAIAssistantStore.setState({ unreadReplyIds: ['a'] });
});
await waitFor(() => expect(play).toHaveBeenCalledTimes(1));
});
it('stays quiet for replies it already knew about', async () => {
seed({
conversations: [chat('a', 'Alpha'), chat('b', 'Beta')],
unread: ['a', 'b'],
});
render(<NozActiveChat />);
act(() => {
useAIAssistantStore.getState().markReplyRead('b');
});
await act(
() =>
new Promise((resolve) => {
setTimeout(resolve, 20);
}),
);
expect(play).not.toHaveBeenCalled();
});
it('stays quiet when the reply is read before the chime', async () => {
seed({ conversations: [chat('a', 'Alpha')] });
render(<NozActiveChat />);
act(() => {
useAIAssistantStore.setState({ unreadReplyIds: ['a'] });
});
act(() => {
useAIAssistantStore.getState().markReplyRead('a');
});
await act(
() =>
new Promise((resolve) => {
setTimeout(resolve, 20);
}),
);
expect(play).not.toHaveBeenCalled();
});
});
});

View File

@@ -0,0 +1,62 @@
@use '../../AIAssistant/_scrollbar' as *;
.nozHistory {
display: flex;
align-items: center;
flex-shrink: 0;
}
.content {
display: flex;
flex-direction: column;
height: 326px;
max-height: calc(100vh - var(--spacing-16));
}
.search {
display: flex;
flex-shrink: 0;
align-items: center;
height: 44px;
padding: 0 var(--spacing-3);
border-bottom: 1px solid var(--l2-border);
caret-color: var(--accent-primary);
}
// Grid rows keep their height, so a long list scrolls instead of squashing them.
.list {
display: grid;
align-content: start;
flex: 1;
min-height: 0;
overflow-y: auto;
padding: var(--spacing-6) 0 calc(var(--spacing-2) + 1px);
@include scrollbar(0.2rem);
}
.label {
padding: 0 var(--spacing-6) calc(var(--spacing-3) + 1px);
font-size: var(--periscope-font-size-small);
font-weight: var(--font-weight-semibold);
line-height: 1;
letter-spacing: 0.04em;
text-transform: uppercase;
color: var(--l3-foreground);
}
.time {
margin-left: auto;
font-size: var(--periscope-font-size-small);
line-height: var(--line-height-18);
// Not the title's tracking, which the row sets.
letter-spacing: normal;
color: var(--l3-foreground);
}
.empty {
padding: 0 var(--spacing-6);
font-size: var(--periscope-font-size-base);
line-height: var(--line-height-20);
color: var(--l3-foreground);
overflow-wrap: anywhere;
}

View File

@@ -0,0 +1,162 @@
import { useCallback, useLayoutEffect, useMemo, useRef } from 'react';
import { Button } from '@signozhq/ui/button';
import {
Popover,
type PopoverProps,
usePopoverHandle,
} from '@signozhq/ui/popover';
import { Tooltip } from '@signozhq/ui/tooltip';
import logEvent from 'api/common/logEvent';
import ROUTES from 'constants/routes';
import {
AIAssistantEvents,
AIAssistantOpenSource,
} from 'container/AIAssistant/events';
import { normalizePage } from 'container/AIAssistant/hooks/useAIAssistantAnalyticsContext';
import { useOpenConversation } from 'container/AIAssistant/hooks/useOpenConversation';
import {
openAIAssistant,
useAIAssistantStore,
} from 'container/AIAssistant/store/useAIAssistantStore';
import { Conversation } from 'container/AIAssistant/types';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { matchRoute } from 'lib/router/matchRoute';
import { useAppLocation } from 'lib/router/useAppLocation';
import { usePopoverAvoidance } from 'lib/obstacles/usePopoverAvoidance';
import { FolderClock } from '@signozhq/icons';
import { isSupportChatTarget } from '../SupportButton/supportChat';
import { supportChatObstacle } from '../SupportButton/supportChatObstacle';
import NozHistoryList from './NozHistoryList';
import styles from './NozHistory.module.scss';
const AVOID = [supportChatObstacle];
/** Recent Noz conversations from any page; AppLayout has already loaded them. */
function NozHistory(): JSX.Element | null {
const { pathname } = useAppLocation();
const isAIAssistantEnabled = useIsAIAssistantEnabled();
const conversations = useAIAssistantStore((s) => s.conversations);
const isDrawerOpen = useAIAssistantStore((s) => s.isDrawerOpen);
const openConversation = useOpenConversation(
AIAssistantOpenSource.BottomStrip,
);
const isOpen = useAIAssistantStore((s) => s.isHistoryOpen);
const setHistoryOpen = useAIAssistantStore((s) => s.setHistoryOpen);
const { clearance } = usePopoverAvoidance(AVOID, isOpen);
const history = usePopoverHandle(setHistoryOpen);
const triggerRef = useRef<HTMLButtonElement>(null);
const shownClearance = useRef(0);
// The support chat stays open over the strip, so the list keeps left of it.
const showHistory = useCallback((): void => {
const trigger = triggerRef.current;
if (!trigger) {
return;
}
shownClearance.current = clearance;
const rect = trigger.getBoundingClientRect();
const maxRight = window.innerWidth - clearance;
history.showAt(
rect.right <= maxRight
? trigger
: new DOMRect(maxRight - rect.width, rect.top, rect.width, rect.height),
);
}, [clearance, history]);
// Before paint, so the list opens beside the support chat instead of sliding there.
useLayoutEffect(() => {
if (isOpen && history.isOpen && shownClearance.current !== clearance) {
showHistory();
} else if (!isOpen && history.isOpen) {
history.close();
}
}, [clearance, history, isOpen, showHistory]);
// Chats saved on the server, newest first; unsent drafts don't count.
const recent = useMemo(
() =>
Object.values(conversations)
.filter((c) => c.threadId && !c.archived)
.sort(
(a, b) => (b.updatedAt ?? b.createdAt) - (a.updatedAt ?? a.createdAt),
),
[conversations],
);
const handleSelect = useCallback(
(conversation: Conversation): void => {
setHistoryOpen(false);
openConversation(conversation.id);
if (!isDrawerOpen) {
void logEvent(AIAssistantEvents.Opened, {
source: AIAssistantOpenSource.BottomStrip,
currentPage: normalizePage(pathname),
});
openAIAssistant();
}
},
[isDrawerOpen, openConversation, pathname, setHistoryOpen],
);
// The support chat opens beside the list rather than closing it; the trigger toggles it.
const handleOpenChange = useCallback<
NonNullable<PopoverProps['onOpenChange']>
>((open, { reason, event, cancel }) => {
// Focus-out names the element losing focus; where it goes is the relatedTarget.
const towards =
reason === 'focus-out' && event instanceof FocusEvent
? event.relatedTarget
: (event?.target ?? null);
if (
!open &&
(isSupportChatTarget(towards) ||
(towards instanceof Node && triggerRef.current?.contains(towards)))
) {
cancel();
}
}, []);
// The full page lists its chats in its own sidebar.
const isAIAssistantPage = !!matchRoute(pathname, ROUTES.AI_ASSISTANT, {
exact: true,
});
if (!isAIAssistantEnabled || isAIAssistantPage || recent.length === 0) {
return null;
}
return (
<div className={styles.nozHistory} data-testid="bottom-strip-noz-history">
<Tooltip title="Recent conversations">
<Button
ref={triggerRef}
variant="ghost"
color="secondary"
size="sm"
icon
aria-label="Recent conversations"
aria-haspopup="dialog"
aria-expanded={isOpen}
onClick={(): void => (isOpen ? history.close() : showHistory())}
testId="noz-history-trigger"
>
<FolderClock size={16} />
</Button>
</Tooltip>
<Popover
handle={history}
side="top"
align="end"
width={269}
onOpenChange={handleOpenChange}
aria-label="Recent conversations"
>
<NozHistoryList conversations={recent} onSelect={handleSelect} />
</Popover>
</div>
);
}
export default NozHistory;

View File

@@ -0,0 +1,77 @@
import { useMemo, useState } from 'react';
import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import { Conversation } from 'container/AIAssistant/types';
import { formatRelativeTime } from 'container/AIAssistant/utils/formatRelativeTime';
import styles from './NozHistory.module.scss';
const UNTITLED = 'New conversation';
interface NozHistoryListProps {
conversations: Conversation[];
onSelect: (conversation: Conversation) => void;
}
function NozHistoryList({
conversations,
onSelect,
}: NozHistoryListProps): JSX.Element {
const [query, setQuery] = useState('');
const trimmedQuery = query.trim();
const matches = useMemo(() => {
const needle = trimmedQuery.toLowerCase();
return needle
? conversations.filter((c) =>
(c.title ?? UNTITLED).toLowerCase().includes(needle),
)
: conversations;
}, [conversations, trimmedQuery]);
return (
<div className={styles.content}>
<div className={styles.search}>
<Input
type="text"
variant="unstyled"
value={query}
onChange={(e): void => setQuery(e.target.value)}
placeholder="Search…"
aria-label="Search conversations"
testId="noz-history-search"
/>
</div>
<div className={styles.list}>
{matches.length > 0 ? (
<>
<div className={styles.label}>Earlier conversations</div>
{matches.map((conversation) => (
<Button
key={conversation.id}
variant="ghost"
color="secondary"
size="md"
suffix={
<span className={styles.time}>
{formatRelativeTime(conversation.updatedAt ?? conversation.createdAt)}
</span>
}
onClick={(): void => onSelect(conversation)}
testId="noz-history-item"
>
{conversation.title ?? UNTITLED}
</Button>
))}
</>
) : (
<div className={styles.empty} data-testid="noz-history-empty">
No conversations match “{trimmedQuery}”
</div>
)}
</div>
</div>
);
}
export default NozHistoryList;

View File

@@ -0,0 +1,234 @@
import logEvent from 'api/common/logEvent';
import {
AIAssistantEvents,
AIAssistantOpenSource,
} from 'container/AIAssistant/events';
import {
type AIAssistantStore,
useAIAssistantStore,
} from 'container/AIAssistant/store/useAIAssistantStore';
import { Conversation } from 'container/AIAssistant/types';
import { ChatSupportState, useChatSupport } from 'hooks/useChatSupport';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { render, screen, userEvent } from 'tests/test-utils';
import SupportButton from '../../SupportButton/SupportButton';
import NozHistory from '../NozHistory';
jest.mock('hooks/useIsAIAssistantEnabled');
jest.mock('hooks/useChatSupport', () => ({
...jest.requireActual('hooks/useChatSupport'),
useChatSupport: jest.fn(),
}));
const mockEnabled = jest.mocked(useIsAIAssistantEnabled);
const mockLogEvent = jest.mocked(logEvent);
const MINUTE = 60_000;
const saved = (
id: string,
title: string,
minutesAgo: number,
extra: Partial<Conversation> = {},
): Conversation => ({
id,
threadId: id,
title,
messages: [],
createdAt: Date.now() - minutesAgo * MINUTE,
updatedAt: Date.now() - minutesAgo * MINUTE,
...extra,
});
const THREADS = {
kafka: saved('thread-kafka', 'Kafka consumer lag', 95),
checkout: saved('thread-checkout', 'Checkout p99 regression', 4),
archived: saved('thread-old', 'Old runbook questions', 30, { archived: true }),
draft: { id: 'draft', messages: [], createdAt: Date.now() },
};
const SLOT = 'bottom-strip-noz-history';
const initialStoreState = useAIAssistantStore.getState();
function seed(
conversations: Conversation[],
state: { isDrawerOpen?: boolean; activeConversationId?: string | null } = {},
): jest.MockedFunction<AIAssistantStore['loadThread']> {
const loadThread = jest.fn() as jest.MockedFunction<
AIAssistantStore['loadThread']
>;
loadThread.mockResolvedValue();
useAIAssistantStore.setState({
conversations: Object.fromEntries(conversations.map((c) => [c.id, c])),
isDrawerOpen: state.isDrawerOpen ?? false,
activeConversationId: state.activeConversationId ?? null,
loadThread,
});
return loadThread;
}
describe('NozHistory', () => {
beforeEach(() => {
jest.clearAllMocks();
mockEnabled.mockReturnValue(true);
});
afterEach(() => {
useAIAssistantStore.setState(initialStoreState, true);
});
describe('visibility', () => {
it('renders nothing without a saved conversation, ignoring drafts and archived ones', () => {
seed([THREADS.draft, THREADS.archived]);
render(<NozHistory />);
expect(screen.queryByTestId(SLOT)).not.toBeInTheDocument();
});
it('renders nothing when the assistant is disabled', () => {
mockEnabled.mockReturnValue(false);
seed([THREADS.checkout]);
render(<NozHistory />);
expect(screen.queryByTestId(SLOT)).not.toBeInTheDocument();
});
it('renders nothing on the Noz full page, whose sidebar lists the chats', () => {
seed([THREADS.checkout]);
render(<NozHistory />, undefined, {
initialRoute: '/ai-assistant/thread-checkout',
});
expect(screen.queryByTestId(SLOT)).not.toBeInTheDocument();
});
it('closes the panel behind it when opened, leaving only the list', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
seed([THREADS.checkout], { isDrawerOpen: true });
render(<NozHistory />);
await user.click(screen.getByTestId('noz-history-trigger'));
const rows = await screen.findAllByTestId('noz-history-item');
expect(rows.map((row) => row.textContent)).toStrictEqual([
'Checkout p99 regression4m',
]);
expect(useAIAssistantStore.getState().isDrawerOpen).toBe(false);
});
});
describe('popover', () => {
it('lists saved, unarchived chats newest first', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
seed([THREADS.kafka, THREADS.draft, THREADS.archived, THREADS.checkout]);
render(<NozHistory />);
await user.click(screen.getByTestId('noz-history-trigger'));
const rows = await screen.findAllByTestId('noz-history-item');
expect(rows.map((row) => row.textContent)).toStrictEqual([
'Checkout p99 regression4m',
'Kafka consumer lag1h',
]);
});
it('filters by title and says when nothing matches', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
seed([THREADS.kafka, THREADS.checkout]);
render(<NozHistory />);
await user.click(screen.getByTestId('noz-history-trigger'));
await user.type(
await screen.findByTestId('noz-history-search-field'),
'KAFKA',
);
expect(
screen.getAllByTestId('noz-history-item').map((row) => row.textContent),
).toStrictEqual(['Kafka consumer lag1h']);
await user.type(screen.getByTestId('noz-history-search-field'), ' zzz');
expect(screen.queryByTestId('noz-history-item')).not.toBeInTheDocument();
expect(screen.getByTestId('noz-history-empty')).toHaveTextContent(
'No conversations match “KAFKA zzz”',
);
});
it('opens the picked chat in the panel and closes', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const loadThread = seed([THREADS.kafka, THREADS.checkout], {
activeConversationId: 'thread-checkout',
});
render(<NozHistory />);
await user.click(screen.getByTestId('noz-history-trigger'));
const [, kafka] = await screen.findAllByTestId('noz-history-item');
await user.click(kafka);
expect(loadThread).toHaveBeenCalledWith('thread-kafka');
expect(useAIAssistantStore.getState().isDrawerOpen).toBe(true);
expect(mockLogEvent).toHaveBeenCalledWith(
AIAssistantEvents.ThreadOpenedFromHistory,
expect.objectContaining({
threadId: 'thread-kafka',
source: AIAssistantOpenSource.BottomStrip,
}),
);
expect(screen.queryByTestId('noz-history-search')).not.toBeInTheDocument();
});
it('does not count picking the open chat as opening one from history', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
seed([THREADS.checkout], { activeConversationId: 'thread-checkout' });
render(<NozHistory />);
await user.click(screen.getByTestId('noz-history-trigger'));
await user.click(await screen.findByTestId('noz-history-item'));
expect(mockLogEvent).not.toHaveBeenCalledWith(
AIAssistantEvents.ThreadOpenedFromHistory,
expect.anything(),
);
expect(useAIAssistantStore.getState().isDrawerOpen).toBe(true);
});
it('retries loading the open chat when its messages never arrived', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const loadThread = seed([THREADS.checkout], {
activeConversationId: 'thread-checkout',
});
render(<NozHistory />);
await user.click(screen.getByTestId('noz-history-trigger'));
await user.click(await screen.findByTestId('noz-history-item'));
expect(loadThread).toHaveBeenCalledWith('thread-checkout');
});
it('stays open while Support opens the support chat beside it', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
jest.mocked(useChatSupport).mockReturnValue(ChatSupportState.Pylon);
seed([THREADS.checkout]);
render(
<>
<NozHistory />
<SupportButton />
</>,
);
await user.click(screen.getByTestId('noz-history-trigger'));
await screen.findByTestId('noz-history-item');
await user.click(screen.getByTestId('bottom-strip-support'));
expect(
screen.getAllByTestId('noz-history-item').map((row) => row.textContent),
).toStrictEqual(['Checkout p99 regression4m']);
});
});
});

View File

@@ -43,6 +43,7 @@ function SupportButton(): JSX.Element | null {
prefix={<MessageSquareText size={16} />}
onClick={handleClick}
testId="bottom-strip-support"
data-support-chat-trigger
>
Support
</Button>

View File

@@ -1,10 +1,10 @@
import type { FloatingRect } from 'periscope/components/FloatingPanel/types';
import type { Rect } from 'lib/obstacles/types';
import { supportChatObstacle } from '../supportChatObstacle';
type Pylon = Window['Pylon'];
const SUPPORT_CHAT: FloatingRect = { x: 882, y: 286, width: 384, height: 478 };
const SUPPORT_CHAT: Rect = { x: 882, y: 286, width: 384, height: 478 };
const CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
const originalPylon = window.Pylon;

View File

@@ -0,0 +1,13 @@
import { SUPPORT_CHAT_SELECTOR } from './supportChatObstacle';
const SUPPORT_CHAT_TRIGGER_SELECTOR = '[data-support-chat-trigger]';
/** Whether `target` is the support chat or the button that opens it. */
export function isSupportChatTarget(target: EventTarget | null): boolean {
return (
target instanceof Element &&
Boolean(
target.closest(`${SUPPORT_CHAT_SELECTOR}, ${SUPPORT_CHAT_TRIGGER_SELECTOR}`),
)
);
}

View File

@@ -1,10 +1,7 @@
import type {
FloatingObstacle,
FloatingRect,
} from 'periscope/components/FloatingPanel/types';
import type { Obstacle, Rect } from 'lib/obstacles/types';
// Pylon's own class names, which styles.scss also targets.
const SUPPORT_CHAT_SELECTOR = '.PylonChat-chatWindowFrameContainer';
export const SUPPORT_CHAT_SELECTOR = '.PylonChat-chatWindowFrameContainer';
const SUPPORT_CHAT_CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
const listeners = new Set<() => void>();
@@ -20,7 +17,7 @@ const onShow = (): void => setOpen(true);
const onHide = (): void => setOpen(false);
// Offsets ignore the scale animation Pylon opens with, so this is the settled box.
function getSupportChatRect(): FloatingRect | null {
function getSupportChatRect(): Rect | null {
const element = document.querySelector<HTMLElement>(SUPPORT_CHAT_SELECTOR);
if (!element) {
return null;
@@ -58,7 +55,7 @@ function subscribeToSupportChat(onChange: () => void): () => void {
};
}
export const supportChatObstacle: FloatingObstacle = {
export const supportChatObstacle: Obstacle = {
getRect: getSupportChatRect,
subscribe: subscribeToSupportChat,
};

View File

@@ -0,0 +1,43 @@
// `--strip-tab-min-width` lets a container tune how far tabs shrink.
.stripTab {
position: relative;
display: flex;
align-items: center;
flex: 0 1 auto;
min-width: var(--strip-tab-min-width, var(--spacing-32));
height: 24px;
&:hover,
&:focus-within,
&.active {
background: var(--l3-background-hover);
.close {
visibility: visible;
}
}
}
.open {
display: flex;
flex: 1 1 auto;
min-width: 0;
}
// Over the label's end on a fade, hidden rather than removed so the label never reflows.
.close {
position: absolute;
top: 0;
right: 0;
display: flex;
align-items: center;
justify-content: flex-end;
width: 37px;
height: 100%;
background: linear-gradient(
to left,
var(--l3-background-hover) 66%,
transparent
);
visibility: hidden;
}

View File

@@ -0,0 +1,66 @@
import type { ReactElement } from 'react';
import cx from 'classnames';
import { Button } from '@signozhq/ui/button';
import { X } from '@signozhq/icons';
import styles from './StripTab.module.scss';
interface StripTabProps {
label: string;
onClick: () => void;
onClose: () => void;
prefix?: ReactElement;
isActive?: boolean;
ariaLabel?: string;
testId?: string;
}
/** A closable tab: the label opens it, the × over its end closes it. */
function StripTab({
label,
onClick,
onClose,
prefix,
isActive = false,
ariaLabel,
testId,
}: StripTabProps): JSX.Element {
return (
<div
className={cx(styles.stripTab, { [styles.active]: isActive })}
data-testid={testId}
>
<span className={styles.open}>
<Button
variant="ghost"
color="secondary"
size="sm"
width="100%"
maxWidth={150.5}
prefix={prefix}
onClick={onClick}
aria-label={ariaLabel}
aria-current={isActive || undefined}
testId={testId && `${testId}-open`}
>
{label}
</Button>
</span>
<span className={styles.close}>
<Button
variant="ghost"
color="secondary"
size="sm"
icon
onClick={onClose}
aria-label={`Close ${label}`}
testId={testId && `${testId}-close`}
>
<X size={14} strokeWidth={1.5} />
</Button>
</span>
</div>
);
}
export default StripTab;

View File

@@ -0,0 +1,8 @@
.stripTabs {
display: flex;
align-items: center;
flex: 0 1 auto;
gap: var(--spacing-1);
min-width: 0;
overflow: hidden;
}

View File

@@ -0,0 +1,48 @@
import { Fragment } from 'react';
import { Divider } from '@signozhq/ui/divider';
import type { StripTabItem } from '../../types';
import StripTab from '../StripTab/StripTab';
import styles from './StripTabs.module.scss';
interface StripTabsProps {
items: StripTabItem[];
onSelect: (id: string) => void;
onClose: (id: string) => void;
/** Each tab gets `${testId}-${item.id}`, with `-open` / `-close` on its buttons. */
testId?: string;
}
/** Closable tabs that shrink to share whatever width their container leaves. */
function StripTabs({
items,
onSelect,
onClose,
testId,
}: StripTabsProps): JSX.Element | null {
if (items.length === 0) {
return null;
}
return (
<div className={styles.stripTabs} data-testid={testId}>
{items.map((item, index) => (
<Fragment key={item.id}>
{index > 0 && <Divider orientation="vertical" height={14} spacing={0} />}
<StripTab
label={item.label}
prefix={item.prefix}
isActive={item.isActive}
ariaLabel={item.ariaLabel}
onClick={(): void => onSelect(item.id)}
onClose={(): void => onClose(item.id)}
testId={testId && `${testId}-${item.id}`}
/>
</Fragment>
))}
</div>
);
}
export default StripTabs;

View File

@@ -0,0 +1,61 @@
import { render, screen, userEvent } from 'tests/test-utils';
import type { StripTabItem } from '../../../types';
import StripTabs from '../StripTabs';
const ITEMS: StripTabItem[] = [
{ id: 'a', label: 'Alpha' },
{ id: 'b', label: 'Beta', isActive: true },
];
describe('StripTabs', () => {
it('renders nothing without tabs', () => {
render(
<StripTabs
items={[]}
onSelect={jest.fn()}
onClose={jest.fn()}
testId="tabs"
/>,
);
expect(screen.queryByTestId('tabs')).not.toBeInTheDocument();
});
it('passes the tab id back on select and on close', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const onSelect = jest.fn() as jest.MockedFunction<(id: string) => void>;
const onClose = jest.fn() as jest.MockedFunction<(id: string) => void>;
render(
<StripTabs
items={ITEMS}
onSelect={onSelect}
onClose={onClose}
testId="tabs"
/>,
);
await user.click(screen.getByTestId('tabs-a-open'));
await user.click(screen.getByTestId('tabs-b-close'));
expect(onSelect.mock.calls).toStrictEqual([['a']]);
expect(onClose.mock.calls).toStrictEqual([['b']]);
});
it('marks only the active tab as current', () => {
render(
<StripTabs
items={ITEMS}
onSelect={jest.fn()}
onClose={jest.fn()}
testId="tabs"
/>,
);
expect(screen.getByTestId('tabs-b-open')).toHaveAttribute(
'aria-current',
'true',
);
expect(screen.getByTestId('tabs-a-open')).not.toHaveAttribute('aria-current');
});
});

View File

@@ -0,0 +1,44 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import StripTabsFixture from './StripTabsFixture';
import { focusFirstTab } from './__story_mockdata__/stripTabs.play';
/**
* Closable tabs for the bottom strip. The label opens a tab and the × over its
* end closes it; tabs shrink with an ellipsis to share the width they are given.
* A prefix, such as the dot Noz uses for an unseen reply, sits before the label.
*/
const meta = {
title: 'Components/Strip Tabs',
tags: ['play'],
component: StripTabsFixture,
decorators: [withCanvas({})],
// A component has no page config; stating it tells the clobbered-mocks check this is on purpose.
parameters: { signoz: {} },
args: { tabs: 4, marked: 1, active: 1, width: 900 },
argTypes: {
tabs: { control: { type: 'range', min: 0, max: 5, step: 1 } },
marked: { control: { type: 'range', min: 0, max: 5, step: 1 } },
active: { control: { type: 'range', min: -1, max: 4, step: 1 } },
width: { control: { type: 'range', min: 200, max: 1200, step: 20 } },
},
} satisfies Meta<typeof StripTabsFixture>;
export default meta;
type Story = StoryObj<typeof meta>;
/** Four tabs: one active, the last one marked. */
export const Default: Story = {};
/** Five tabs in a narrow strip, shrunk to share it. */
export const Crowded: Story = {
args: { tabs: 5, marked: 2, width: 420 },
};
/** A tab reached by keyboard: highlighted with its × shown, as on hover. */
export const Focused: Story = {
play: focusFirstTab,
};

View File

@@ -0,0 +1,19 @@
// Stands in for the bottom strip the row lives in.
.strip {
display: flex;
align-items: center;
justify-content: flex-end;
max-width: 100%;
height: 24px;
padding: 0 var(--spacing-6);
background: var(--l2-background);
border-top: 1px solid var(--l2-border);
}
.dot {
flex-shrink: 0;
width: var(--spacing-3);
height: var(--spacing-3);
border-radius: var(--radius-round);
background: var(--accent-primary);
}

View File

@@ -0,0 +1,65 @@
import { useMemo, useState } from 'react';
import type { StripTabItem } from '../../../types';
import StripTabs from '../StripTabs';
import styles from './StripTabsFixture.module.scss';
const TITLES = [
'Payment incident investigation for checkout',
'Top noisy log patterns in prod',
'Kafka lag',
'Error rate before and after the 14:05 deploy',
'Which dashboard panels load slowest?',
];
export interface StripTabsFixtureProps {
/** How many tabs the row starts with. */
tabs: number;
/** How many of the last tabs carry a dot. */
marked: number;
/** Index of the tab that starts active; -1 for none. */
active: number;
/** Width of the strip the row shrinks into, in px. */
width: number;
}
/** A strip-sized bar holding `StripTabs`; picking a tab activates it, × removes it. */
function StripTabsFixture({
tabs,
marked,
active,
width,
}: StripTabsFixtureProps): JSX.Element {
const [activeId, setActiveId] = useState(active >= 0 ? `tab-${active}` : null);
const [closedIds, setClosedIds] = useState<string[]>([]);
const items = useMemo(
() =>
TITLES.slice(0, tabs)
.map((label, index): StripTabItem => ({
id: `tab-${index}`,
label,
isActive: activeId === `tab-${index}`,
prefix:
index >= tabs - marked ? (
<span className={styles.dot} aria-hidden />
) : undefined,
}))
.filter((item) => !closedIds.includes(item.id)),
[tabs, marked, activeId, closedIds],
);
return (
<div className={styles.strip} style={{ width }}>
<StripTabs
items={items}
onSelect={setActiveId}
onClose={(id): void => setClosedIds((ids) => [...ids, id])}
testId="strip-tabs"
/>
</div>
);
}
export default StripTabsFixture;

View File

@@ -0,0 +1,21 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent } from 'storybook/test';
interface PlayContext {
args: { tabs: number };
}
/** Tabs to the first tab, which shows its × over the end of the label. */
export const focusFirstTab = async ({ args }: PlayContext): Promise<void> => {
if (args.tabs === 0) {
return;
}
await screen.findByTestId('strip-tabs-tab-0-open');
await userEvent.tab();
await expect(screen.getByTestId('strip-tabs-tab-0-open')).toHaveFocus();
await expect(screen.getByTestId('strip-tabs-tab-0-close')).toBeVisible();
};

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