mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-28 19:20:41 +00:00
Compare commits
54 Commits
feat/distr
...
fix/flaky-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
11fe039285 | ||
|
|
755ee024f0 | ||
|
|
588279392f | ||
|
|
c4cb2345bc | ||
|
|
9acca906e9 | ||
|
|
b9e5391df5 | ||
|
|
07fe39eb16 | ||
|
|
9885bd8c0b | ||
|
|
1f429966dd | ||
|
|
28fca8e0c7 | ||
|
|
c91f7108b3 | ||
|
|
fa321cc29b | ||
|
|
41e8c61bc3 | ||
|
|
d33e00786b | ||
|
|
820321d708 | ||
|
|
022a342971 | ||
|
|
8d948ac996 | ||
|
|
47460148dc | ||
|
|
c7db24de68 | ||
|
|
20ea81824a | ||
|
|
ef51388130 | ||
|
|
2bc6e22ed6 | ||
|
|
8a15d4bae5 | ||
|
|
a0fa24ccbe | ||
|
|
0591355924 | ||
|
|
ee31775d5b | ||
|
|
0994fb7aea | ||
|
|
4bb7fbd9a7 | ||
|
|
0e4ca91193 | ||
|
|
2a6d569834 | ||
|
|
a6be4d894c | ||
|
|
b1f271a505 | ||
|
|
c92bb94caf | ||
|
|
8e3a4f8775 | ||
|
|
a8433ad9e0 | ||
|
|
d07b0f1d82 | ||
|
|
a02330438f | ||
|
|
cb2b3db771 | ||
|
|
40ee169d94 | ||
|
|
865e1c97b3 | ||
|
|
5f24193de6 | ||
|
|
3d63ed6353 | ||
|
|
3af06adabc | ||
|
|
7b20abbeb7 | ||
|
|
73e6fa555a | ||
|
|
91525d721e | ||
|
|
251d49efce | ||
|
|
7d92c443b3 | ||
|
|
11cc323ca5 | ||
|
|
2d5a07048a | ||
|
|
6921b40467 | ||
|
|
d655a8998b | ||
|
|
70ab9c2321 | ||
|
|
e085decc05 |
@@ -20,12 +20,16 @@ You are the Playwright Test Generator for the SigNoz frontend. You take a plan w
|
||||
await expect(routing.activeRouteTab(PATH.metricsSummary)).toBeVisible();
|
||||
});
|
||||
```
|
||||
- A driver is a function closing over the page that returns `Locator` getters and async actions. Actions wait inside themselves (e.g. `run()` pairs the click with `waitForResponse(/query_range/)`), so specs don't.
|
||||
- A driver is a function closing over the page that returns `Locator` getters and async actions. Actions wait inside themselves (e.g. `run()` pairs the click with `waitForResponse(/query_range/)`), so specs don't. A wait for "the request the action fired" skips aborted requests, which have no response: Run after a cancel re-sends the cancelled query and aborts it, and `query-builder/run` TC-34 read that one.
|
||||
- A page action that opens an explorer waits for the content pane's scrollbar viewport (`quick-filters-layout-content [data-overlayscrollbars-viewport]`) before anything types. The scrollbar starts on idle and re-parents the editors, so keys typed across it land at the start of the text. Typing into a CodeMirror editor retypes until the editor holds exactly the text, as `editorAt(...).type` and `querySearch.apply` do: `query-builder/aggregation` TC-17 sent `c()` for `count()`.
|
||||
- `driver(name, build, dispose?)` in `drivers/kit.ts` makes it a test-scoped fixture on `authedPage`; `dispose` deletes what it seeded. `seeded(name, open, close)` makes a worker-scoped seed.
|
||||
- Read [tests/e2e/tests/dashboards/editor/query.spec.ts](../../tests/e2e/tests/dashboards/editor/query.spec.ts) and [drivers/panel-editor.ts](../../tests/e2e/drivers/panel-editor.ts) for the canonical shape.
|
||||
- **Seeds are layers on the feature's `test`.** A spec destructures the seed it needs (`alertList`, `ownedRules`, `resolvedHistory` for alerts) instead of importing a fixtures module. A new seed goes in the feature's driver directory: `seeded()` for read-only data shared by a worker, a test-scoped layer for anything a test mutates.
|
||||
- **Test titles:** `TC-NN <short description>` — matches the planner's IDs.
|
||||
- **Self-contained state.** The bootstrap creates a fresh stack with **zero** dashboards / alerts / etc. Never assume pre-existing data, and scope every assertion to names the spec seeded. Pick the scope per the Seeding table in [tests/e2e/AGENTS.md](../../tests/e2e/AGENTS.md): test scope (a test-scoped layer, or `try / finally` through the driver) for mutations, worker scope (`seeded()`) for read-only data, suite `beforeAll` for a dataset only one file uses.
|
||||
- **A seed adds to org-wide settings, never replaces them.** Quick filters, org preferences and similar settings are shared by every spec on the stack, and `fullyParallel` runs those specs at once. Read the stored value and write a superset with only the missing entries, as `quickFilters.seed` does. A seed that replaced the logs filters made `query-builder/filter` TC-16 fail later on the same stack, and a restore in teardown races a parallel spec that seeded the same setting.
|
||||
- **Close a multiple combobox from its trigger, never with Escape.** A multi-select stays open after a pick, and Escape also closes the dialog or page around it; `onboarding/get-started` TC-09 landed on `/home`. `comboboxAt(...).pick` already does this.
|
||||
- **A context you open yourself drops its routes before closing.** Call `page.unrouteAll({ behavior: 'ignoreErrors' })` before `ctx.close()`, as `authedPage` does; a handler still inside `route.fetch` otherwise fails a test that already passed.
|
||||
- **Drive everything through the feature's driver** in `tests/e2e/drivers/`. A spec that reaches for `page.locator(...)` or `page.getByTestId(...)` is missing a driver method — add the method instead. `onAdminPage(browser, …)` from `drivers/kit.ts` is what suite hooks use, because `authedPage` is test-scoped and not visible to them.
|
||||
- **Seed through the kit when the UI flow is not under test.** Control-plane objects go through the feature driver (`dashboards.seed`, `alerts.seed.threshold`), which uses `apiDriver(page)` from `drivers/api.ts`; telemetry goes to the seeder. `page.request.*` does **not** carry the token, so never seed with it.
|
||||
- **Golden telemetry is pre-seeded.** `bootstrap/global.setup.ts` loads logs, traces and metrics over the last 6h (constants in `GOLDEN`, `drivers/dashboard-spec.ts`). Query within ≤ 6h and assert structure (series, rows, request payload), never exact counts.
|
||||
|
||||
@@ -50,6 +50,9 @@ Don't try to start the stack yourself — it can take ~4 minutes on a cold build
|
||||
- **Auth.** `tests/e2e/drivers/auth.ts` logs in once per worker and caches `storageState` (localStorage with `AUTH_TOKEN`). For API-driven seeding and cleanup use `apiDriver(page)` from `drivers/api.ts`, which attaches the header for you. Never re-implement login.
|
||||
- **Seeds.** Feature seeds are layers on the feature's `test`, e.g. `alertList`, `ownedRules` and `resolvedHistory` in `drivers/alerts/seeds.ts`. When a test fails on missing data, check which seed it destructures and whether it scopes to that seed's names.
|
||||
- **Timeouts.** Never add `test.slow()` to a driver: it triples the remaining budget per call and compounds in loops. Use `allowFor(floor)` from `drivers/kit.ts`. Budgets and their measurements are in `tests/e2e/docs/flake-notes.md`.
|
||||
- **A failure that shows only late in a long local run.** Run that spec's shard alone on a freshly seeded stack before fixing it, as CI does. A setting another spec changed and never restored, or golden telemetry aging past a query window, fails it only after the rest of the suite.
|
||||
- **`route.fetch: Target page, context or browser has been closed` after the test passed.** A route handler was still fetching when the context closed. Unroute with `page.unrouteAll({ behavior: 'ignoreErrors' })` before `ctx.close()` in the fixture that opened the context.
|
||||
- **Escape after a multi-select pick lands on another page.** Escape closed the dialog around the combobox too. Close it from its trigger (`comboboxAt(...).pick` does), never with another Escape.
|
||||
- **CI-only failures.** Reproduce with `STRESS=1 CI=1 pnpm test <path>` from `tests/e2e/` before calling it a product bug.
|
||||
- **Commits.** Driver fixes and spec fixes go in separate commits (see Commits in `tests/e2e/AGENTS.md`).
|
||||
- **Ant Design popovers** (sort menu, action menu) are click-toggle. The trigger element is often an inline `<svg>` with a `data-testid` — clicking it opens the popover; clicking it again closes. After selecting an option, the popover auto-closes. If a test interacts with the popover twice, wait for the menu items to be visible explicitly between toggles.
|
||||
|
||||
@@ -11,6 +11,7 @@ Examples and the harness API live in [`frontend/src/tests/README.md`](../../fron
|
||||
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
|
||||
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` checks the computed style of every element it visits and is the slowest query. Always go through Testing Library (`screen`, `within`), never the DOM: no `querySelector`, `closest`, `container` or `document.body`. `signoz/no-dom-node-access` flags the DOM calls in test files; a test that checks DOM structure on purpose disables it on that line with a reason. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
|
||||
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check: Base UI popups sit inside an element with an inline `pointer-events: none`, and the stylesheet that turns it back on for the popup never loads in jsdom, so the check would block every click on them. Never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
|
||||
- **Drop user-event's pause: `userEvent.setup(NO_DELAY_USER_EVENT)`** from `tests/test-utils`; spread it when the test needs other options. The default `delay: 0` waits a `setTimeout` after every key and click, so typing 40 characters waits 40 timer turns, each slower on a busy CI runner. With `delay: null` the actions run back to back. For a long value, click the field and `user.paste(text)` instead of typing it. Keep the default when the test checks what happens between two actions, such as a debounce per key or an update on a timer or `requestAnimationFrame` between steps: with `null` that code runs only after the whole action. Under `null` the Jest timeout can't fire mid-action, so judge a slow test by its `--verbose` time, not by whether it fails.
|
||||
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
|
||||
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
|
||||
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -122,10 +123,11 @@ Before writing the clicks, list what has to be on screen for the play's target t
|
||||
|
||||
Make those checks with the page's own code instead of restating a condition. Build the rows with the builder the handler uses and the view's own filter, and check a permission with the page's own check through `accessFor(...).allows(...)`, or the role against the constant the page gates on, such as `componentPermission.action`. Export the checks from the mocks module, next to the handlers, so a handler change moves them too. The alert rules page has `listedRules`, `hasRowMenu`, `showsNoRulesPage` and `listsSavedViews`; the dashboards list has `listedDashboards`, `canList`, `canCreate` and `canUpdate`.
|
||||
|
||||
Two habits cover the rest:
|
||||
Three habits cover the rest:
|
||||
|
||||
- Use `findAllBy*` and take the first whenever the text can appear twice, such as in a tooltip or a popover title.
|
||||
- Wrap `toBeVisible` in `waitFor` for anything that fades in. A tooltip or toast found the moment it mounts is not visible yet.
|
||||
- Wait for what a click depends on before clicking. A control can do something else until a request answers: in the cloud account setup, Cancel closes the drawer outright until the agent command exists, and asks to confirm only after. Clicking Cancel straight after Generate raced the account POST on CI; find `<provider>-agent-command` first.
|
||||
|
||||
## Rules
|
||||
|
||||
|
||||
12
.github/workflows/goci.yaml
vendored
12
.github/workflows/goci.yaml
vendored
@@ -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
|
||||
|
||||
@@ -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{}
|
||||
|
||||
@@ -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"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -21,7 +21,7 @@ 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/styles.scss';
|
||||
|
||||
@@ -197,7 +197,9 @@ const preview: Preview = {
|
||||
['Overview', 'Authz'],
|
||||
'Service Accounts',
|
||||
'Ingestion',
|
||||
['Overview', 'Authz'],
|
||||
'Single Sign-on',
|
||||
['Overview', 'Authz'],
|
||||
'Keyboard Shortcuts',
|
||||
],
|
||||
'Auth',
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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 }],
|
||||
},
|
||||
],
|
||||
});
|
||||
51
frontend/plugins/rules/no-builder-ai-query-access.mjs
Normal file
51
frontend/plugins/rules/no-builder-ai-query-access.mjs
Normal 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' });
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
@@ -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,
|
||||
},
|
||||
};
|
||||
|
||||
10
frontend/pnpm-lock.yaml
generated
10
frontend/pnpm-lock.yaml
generated
@@ -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
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -28,4 +28,6 @@ until curl -sf http://127.0.0.1:6006/index.json >/dev/null 2>&1; do
|
||||
sleep 1
|
||||
done
|
||||
|
||||
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 30000 "$@"
|
||||
# The first story of a heavy page compiles it on the cold dev server inside its
|
||||
# own test, which outlasts 30s on a loaded runner.
|
||||
pnpm exec test-storybook --ci --maxWorkers=2 --testTimeout 60000 "$@"
|
||||
|
||||
@@ -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 &&
|
||||
|
||||
@@ -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: {
|
||||
|
||||
BIN
frontend/src/assets/sounds/noz-reply.wav
Normal file
BIN
frontend/src/assets/sounds/noz-reply.wav
Normal file
Binary file not shown.
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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(),
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
|
||||
&-line {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
left: 3px;
|
||||
top: 6px;
|
||||
bottom: -30px;
|
||||
width: 1px;
|
||||
|
||||
52
frontend/src/components/ChangelogModal/useChangelogScroll.ts
Normal file
52
frontend/src/components/ChangelogModal/useChangelogScroll.ts
Normal 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 };
|
||||
}
|
||||
@@ -64,7 +64,7 @@ describe('InviteMembers - Submission', () => {
|
||||
|
||||
render(
|
||||
<InviteMembers
|
||||
initialRowCount={3}
|
||||
initialRowCount={2}
|
||||
renderFooter={({ submit }): JSX.Element => (
|
||||
<button data-testid="submit-btn" onClick={submit}>
|
||||
Submit
|
||||
@@ -77,13 +77,11 @@ describe('InviteMembers - Submission', () => {
|
||||
await pickRole(user, 0, 'role-viewer');
|
||||
await enterInviteEmail(user, 1, 'bob@signoz.io');
|
||||
await pickRole(user, 1, 'role-editor');
|
||||
await enterInviteEmail(user, 2, 'charlie@signoz.io');
|
||||
await pickRole(user, 2, 'role-admin');
|
||||
|
||||
await user.click(screen.getByTestId('submit-btn'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(calls).toHaveLength(3);
|
||||
expect(calls).toHaveLength(2);
|
||||
});
|
||||
|
||||
expect(calls[0]).toMatchObject({
|
||||
@@ -94,10 +92,6 @@ describe('InviteMembers - Submission', () => {
|
||||
email: 'bob@signoz.io',
|
||||
userRoles: [{ id: 'role-editor' }],
|
||||
});
|
||||
expect(calls[2]).toMatchObject({
|
||||
email: 'charlie@signoz.io',
|
||||
userRoles: [{ id: 'role-admin' }],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
: {};
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
|
||||
@@ -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('');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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 =>
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -16,6 +16,7 @@ import CodeMirror, { EditorView, keymap } from '@uiw/react-codemirror';
|
||||
import { Button } from 'antd';
|
||||
import { Having } from 'api/v5/v5';
|
||||
import { useQueryBuilderV2Context } from 'components/QueryBuilderV2/QueryBuilderV2Context';
|
||||
import { useEditorDraft } from 'components/QueryBuilderV2/QueryV2/useEditorDraft';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { ChevronUp } from '@signozhq/icons';
|
||||
import { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
@@ -99,28 +100,20 @@ function HavingFilter({
|
||||
const { getAggregationOptions } = useQueryBuilderV2Context();
|
||||
const aggregationOptions = getAggregationOptions(queryData.queryName);
|
||||
const having = queryData?.having as Having;
|
||||
const [input, setInput] = useState(having?.expression || '');
|
||||
|
||||
useEffect(() => {
|
||||
setInput(having?.expression || '');
|
||||
}, [having?.expression]);
|
||||
const { editorRef, editorProps } = useEditorDraft(
|
||||
having?.expression || '',
|
||||
onChange,
|
||||
);
|
||||
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
|
||||
const [options, setOptions] = useState<{ label: string; value: string }[]>([]);
|
||||
|
||||
const handleChange = (value: string): void => {
|
||||
setInput(value);
|
||||
onChange(value);
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (isFocused && editorRef.current && options.length > 0) {
|
||||
startCompletion(editorRef.current);
|
||||
}
|
||||
}, [isFocused, options]);
|
||||
}, [editorRef, isFocused, options]);
|
||||
|
||||
// Update options when aggregation options change
|
||||
useEffect(() => {
|
||||
@@ -329,8 +322,7 @@ function HavingFilter({
|
||||
<div className="having-filter-container">
|
||||
<div className="having-filter-select-container">
|
||||
<CodeMirror
|
||||
value={input}
|
||||
onChange={handleChange}
|
||||
{...editorProps}
|
||||
theme={isDarkMode ? copilot : githubLight}
|
||||
data-testid="having-editor"
|
||||
className="having-filter-select-editor"
|
||||
@@ -354,9 +346,6 @@ function HavingFilter({
|
||||
autocompletion: true,
|
||||
completionKeymap: true,
|
||||
}}
|
||||
onCreateEditor={(view: EditorView): void => {
|
||||
editorRef.current = view;
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
if (editorRef.current) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/* eslint-disable import/no-extraneous-dependencies */
|
||||
/* eslint-disable sonarjs/cognitive-complexity */
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
autocompletion,
|
||||
closeCompletion,
|
||||
@@ -36,6 +36,7 @@ import {
|
||||
} from 'types/common/queryBuilder';
|
||||
|
||||
import { useQueryBuilderV2Context } from '../../QueryBuilderV2Context';
|
||||
import { useEditorDraft } from '../useEditorDraft';
|
||||
|
||||
import './QueryAggregation.styles.scss';
|
||||
|
||||
@@ -175,20 +176,17 @@ function QueryAggregationSelect({
|
||||
[],
|
||||
);
|
||||
|
||||
const [input, setInput] = useState(
|
||||
formatAggregations(queryData?.aggregations),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
setInput(formatAggregations(queryData?.aggregations));
|
||||
}, [queryData?.aggregations, formatAggregations]);
|
||||
const {
|
||||
draft: input,
|
||||
editorRef,
|
||||
editorProps,
|
||||
} = useEditorDraft(formatAggregations(queryData?.aggregations), onChange);
|
||||
|
||||
const [cursorPos, setCursorPos] = useState(0);
|
||||
const [functionArgPairs, setFunctionArgPairs] = useState<
|
||||
{ func: string; arg: string }[]
|
||||
>([]);
|
||||
const [validationError, setValidationError] = useState<string | null>(null);
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
const [isFocused, setIsFocused] = useState(false);
|
||||
|
||||
// Get valid function names (lowercase)
|
||||
@@ -204,7 +202,7 @@ function QueryAggregationSelect({
|
||||
startCompletion(editorRef.current);
|
||||
}
|
||||
});
|
||||
}, []);
|
||||
}, [editorRef]);
|
||||
|
||||
// Update cursor position on every editor update
|
||||
const handleUpdate = (update: { view: EditorView }): void => {
|
||||
@@ -601,11 +599,7 @@ function QueryAggregationSelect({
|
||||
return (
|
||||
<div className="query-aggregation-select-container">
|
||||
<CodeMirror
|
||||
value={input}
|
||||
onChange={(value): void => {
|
||||
setInput(value);
|
||||
onChange?.(value);
|
||||
}}
|
||||
{...editorProps}
|
||||
data-testid="query-aggregation-editor"
|
||||
className={`query-aggregation-select-editor ${
|
||||
validationError ? 'error' : ''
|
||||
@@ -637,9 +631,6 @@ function QueryAggregationSelect({
|
||||
completionKeymap: true,
|
||||
}}
|
||||
onUpdate={handleUpdate}
|
||||
onCreateEditor={(view: EditorView): void => {
|
||||
editorRef.current = view;
|
||||
}}
|
||||
onFocus={(): void => {
|
||||
setIsFocused(true);
|
||||
safeStartCompletion();
|
||||
|
||||
@@ -8,7 +8,14 @@ import { ENVIRONMENT } from 'constants/env';
|
||||
import { DEBOUNCE_DELAY } from 'constants/queryBuilderFilterConfig';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { act, render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import {
|
||||
act,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import type { IBuilderQuery } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import DistributionFieldSelect from '../DistributionFieldSelect';
|
||||
@@ -74,7 +81,7 @@ describe('DistributionFieldSelect', () => {
|
||||
});
|
||||
|
||||
it('picks a numeric field, keeping its context', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={onChange} />,
|
||||
@@ -97,7 +104,7 @@ describe('DistributionFieldSelect', () => {
|
||||
});
|
||||
|
||||
it('replaces the saved field with the newly picked one', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onChange = jest.fn() as jest.MockedFunction<(field: string) => void>;
|
||||
render(
|
||||
<DistributionFieldSelect
|
||||
@@ -119,7 +126,7 @@ describe('DistributionFieldSelect', () => {
|
||||
});
|
||||
|
||||
it('only offers listed fields: typed text is a filter, not a value', async () => {
|
||||
const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
render(
|
||||
<DistributionFieldSelect queryData={tracesQuery('')} onChange={jest.fn()} />,
|
||||
);
|
||||
|
||||
@@ -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);
|
||||
}}
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -0,0 +1,115 @@
|
||||
import { EditorView } from '@uiw/react-codemirror';
|
||||
import { act, renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useEditorDraft } from '../useEditorDraft';
|
||||
|
||||
function setup(
|
||||
external = '',
|
||||
onEdit?: (value: string) => void,
|
||||
): {
|
||||
result: { current: ReturnType<typeof useEditorDraft> };
|
||||
rerender: (props: { external: string }) => void;
|
||||
} {
|
||||
return renderHook(
|
||||
({ external: value }: { external: string }) => useEditorDraft(value, onEdit),
|
||||
{ initialProps: { external } },
|
||||
);
|
||||
}
|
||||
|
||||
// Reports document changes to `onChange` the way `@uiw/react-codemirror` does.
|
||||
function attachEditor(
|
||||
result: { current: ReturnType<typeof useEditorDraft> },
|
||||
doc: string,
|
||||
): EditorView {
|
||||
const view = new EditorView({
|
||||
doc,
|
||||
extensions: EditorView.updateListener.of((update) => {
|
||||
if (update.docChanged) {
|
||||
result.current.editorProps.onChange(update.state.doc.toString());
|
||||
}
|
||||
}),
|
||||
});
|
||||
act(() => result.current.editorProps.onCreateEditor(view));
|
||||
return view;
|
||||
}
|
||||
|
||||
function type(view: EditorView, text: string): void {
|
||||
act(() => {
|
||||
view.dispatch({ changes: { from: view.state.doc.length, insert: text } });
|
||||
});
|
||||
}
|
||||
|
||||
describe('useEditorDraft', () => {
|
||||
it('keeps newer typing when an older edit comes back', () => {
|
||||
const { result, rerender } = setup();
|
||||
|
||||
act(() => result.current.editorProps.onChange('count() > 1'));
|
||||
act(() => result.current.editorProps.onChange('count() > 10'));
|
||||
rerender({ external: 'count() > 1' });
|
||||
|
||||
expect(result.current.draft).toBe('count() > 10');
|
||||
});
|
||||
|
||||
it('takes a value set outside the editor', () => {
|
||||
const { result, rerender } = setup('count() > 1');
|
||||
|
||||
act(() => result.current.editorProps.onChange('count() > 10'));
|
||||
rerender({ external: 'count() > 10' });
|
||||
rerender({ external: 'count() < 5' });
|
||||
|
||||
expect(result.current.draft).toBe('count() < 5');
|
||||
});
|
||||
|
||||
it('takes an outside value equal to an edit older than the last echo', () => {
|
||||
const { result, rerender } = setup();
|
||||
|
||||
act(() => result.current.editorProps.onChange('a'));
|
||||
act(() => result.current.editorProps.onChange('ab'));
|
||||
rerender({ external: 'ab' });
|
||||
rerender({ external: 'a' });
|
||||
|
||||
expect(result.current.draft).toBe('a');
|
||||
});
|
||||
|
||||
it('keeps the editor value at the first text while the user types', () => {
|
||||
const { result, rerender } = setup('count()');
|
||||
|
||||
act(() => result.current.editorProps.onChange('count() >'));
|
||||
rerender({ external: 'count() >' });
|
||||
act(() => result.current.editorProps.onChange('count() > 1'));
|
||||
|
||||
expect(result.current.editorProps.value).toBe('count()');
|
||||
});
|
||||
|
||||
it('passes each edit on', () => {
|
||||
const onEdit = jest.fn();
|
||||
const { result } = setup('', onEdit);
|
||||
|
||||
act(() => result.current.editorProps.onChange('count()'));
|
||||
|
||||
expect(onEdit).toHaveBeenCalledWith('count()');
|
||||
});
|
||||
|
||||
it('writes an outside change into the editor without passing it on', () => {
|
||||
const onEdit = jest.fn();
|
||||
const { result, rerender } = setup('count() > 1', onEdit);
|
||||
const view = attachEditor(result, 'count() > 1');
|
||||
|
||||
rerender({ external: 'count() < 5' });
|
||||
|
||||
expect(view.state.doc.toString()).toBe('count() < 5');
|
||||
expect(view.state.selection.main.head).toBe('count() < 5'.length);
|
||||
expect(onEdit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('leaves the editor alone when an older edit comes back', () => {
|
||||
const { result, rerender } = setup();
|
||||
const view = attachEditor(result, '');
|
||||
|
||||
type(view, 'count_');
|
||||
type(view, 'di');
|
||||
rerender({ external: 'count_' });
|
||||
|
||||
expect(view.state.doc.toString()).toBe('count_di');
|
||||
});
|
||||
});
|
||||
109
frontend/src/components/QueryBuilderV2/QueryV2/useEditorDraft.ts
Normal file
109
frontend/src/components/QueryBuilderV2/QueryV2/useEditorDraft.ts
Normal file
@@ -0,0 +1,109 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { MutableRefObject } from 'react';
|
||||
import type { EditorView } from '@uiw/react-codemirror';
|
||||
|
||||
// Bounds the history when no parent ever echoes the edits back.
|
||||
const MAX_PENDING_ECHOES = 200;
|
||||
|
||||
interface EditorDraft {
|
||||
/** The editor's current text. */
|
||||
draft: string;
|
||||
editorRef: MutableRefObject<EditorView | null>;
|
||||
/** Spread on `CodeMirror`. */
|
||||
editorProps: {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
onCreateEditor: (view: EditorView) => void;
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Text of a query editor whose edits round-trip through query state. Each
|
||||
* edit comes back as `external` one or more renders later; writing an older
|
||||
* copy into the editor would drop the keys typed since and move the caret to
|
||||
* the start. Values the editor sent are ignored when they come back, and any
|
||||
* other `external` value replaces the text.
|
||||
*
|
||||
* The editor owns its text, so `editorProps.value` never changes after the
|
||||
* first render: `@uiw/react-codemirror` writes a changed `value` over the
|
||||
* document in a passive effect, which on a busy page runs after newer keys and
|
||||
* drops them. Outside changes are written through the view instead.
|
||||
*/
|
||||
export function useEditorDraft(
|
||||
external: string,
|
||||
onEdit?: (value: string) => void,
|
||||
): EditorDraft {
|
||||
const [draft, setDraft] = useState(external);
|
||||
const [initialValue] = useState(external);
|
||||
const editorRef = useRef<EditorView | null>(null);
|
||||
const pendingEchoes = useRef<string[]>([]);
|
||||
const writingOutsideChange = useRef(false);
|
||||
|
||||
const writeIntoEditor = useCallback((view: EditorView, text: string): void => {
|
||||
if (view.state.doc.toString() === text) {
|
||||
return;
|
||||
}
|
||||
writingOutsideChange.current = true;
|
||||
try {
|
||||
view.dispatch({
|
||||
changes: { from: 0, to: view.state.doc.length, insert: text },
|
||||
selection: { anchor: text.length },
|
||||
});
|
||||
} finally {
|
||||
writingOutsideChange.current = false;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Echoes arrive in order, and a batched render can skip some, so a match
|
||||
// also drops every older entry: they can no longer come back.
|
||||
//
|
||||
// type "c", "co", "cou" pending [c, co, cou] draft "cou"
|
||||
// echo "c" pending [co, cou] ignored, draft stays "cou"
|
||||
// echo "cou" (skipped co) pending [] ignored
|
||||
// "count() > 5" from a saved view, never sent: applied
|
||||
//
|
||||
// Keeping the older entries would also swallow an outside change that
|
||||
// happens to equal one of them: after typing "a", "ab", a saved view with
|
||||
// "a" would be taken for an echo.
|
||||
useEffect(() => {
|
||||
const index = pendingEchoes.current.indexOf(external);
|
||||
if (index === -1) {
|
||||
pendingEchoes.current = [];
|
||||
setDraft(external);
|
||||
if (editorRef.current) {
|
||||
writeIntoEditor(editorRef.current, external);
|
||||
}
|
||||
return;
|
||||
}
|
||||
pendingEchoes.current = pendingEchoes.current.slice(index + 1);
|
||||
}, [external, writeIntoEditor]);
|
||||
|
||||
const onChange = useCallback(
|
||||
(value: string): void => {
|
||||
if (writingOutsideChange.current) {
|
||||
return;
|
||||
}
|
||||
pendingEchoes.current.push(value);
|
||||
if (pendingEchoes.current.length > MAX_PENDING_ECHOES) {
|
||||
pendingEchoes.current.shift();
|
||||
}
|
||||
setDraft(value);
|
||||
onEdit?.(value);
|
||||
},
|
||||
[onEdit],
|
||||
);
|
||||
|
||||
const onCreateEditor = useCallback(
|
||||
(view: EditorView): void => {
|
||||
editorRef.current = view;
|
||||
writeIntoEditor(view, draft);
|
||||
},
|
||||
[draft, writeIntoEditor],
|
||||
);
|
||||
|
||||
return {
|
||||
draft,
|
||||
editorRef,
|
||||
editorProps: { value: initialValue, onChange, onCreateEditor },
|
||||
};
|
||||
}
|
||||
@@ -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}>
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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> => {
|
||||
|
||||
@@ -10,6 +10,8 @@ import {
|
||||
import { getHostsQuickFiltersConfig } from 'container/InfraMonitoringHostsV2/utils';
|
||||
import { INFRA_MONITORING_ATTR_KEYS } from 'container/InfraMonitoringK8sV2/constants';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { mockUseAuthZGrantAll } from 'lib/authz/utils/authz-test-utils';
|
||||
import {
|
||||
otherFiltersResponse,
|
||||
quickFiltersFieldValuesResponse,
|
||||
@@ -17,7 +19,14 @@ import {
|
||||
} from 'mocks-server/__mockdata__/customQuickFilters';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { render, screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
|
||||
import { QueryBuilderContextType } from 'types/common/queryBuilder';
|
||||
|
||||
@@ -32,6 +41,7 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: jest.fn(),
|
||||
}));
|
||||
jest.mock('container/ApiMonitoring/queryParams');
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
jest.mock(
|
||||
'components/OverlayScrollbar/OverlayScrollbar',
|
||||
() =>
|
||||
@@ -55,6 +65,7 @@ const mockSetApiMonitoringParams = jest.fn() as jest.MockedFunction<
|
||||
(newParams: Partial<ApiMonitoringParams>, replace?: boolean) => void
|
||||
>;
|
||||
const mockUseApiMonitoringParams = jest.mocked(useApiMonitoringParams);
|
||||
const mockedUseAuthZ = jest.mocked(useAuthZ);
|
||||
|
||||
const BASE_URL = ENVIRONMENT.baseURL;
|
||||
const quickFiltersListURL = `${BASE_URL}/api/v2/quick_filters/logs`;
|
||||
@@ -78,11 +89,12 @@ const QUERY_NAME = 'Test Query';
|
||||
|
||||
const savedFilters = quickFiltersListResponse.data
|
||||
.filters as TelemetryFieldKey[];
|
||||
const smallSavedFilters = savedFilters.slice(0, 2);
|
||||
const smallFiltersListResponse = {
|
||||
...quickFiltersListResponse,
|
||||
data: {
|
||||
...quickFiltersListResponse.data,
|
||||
filters: savedFilters.slice(0, 2),
|
||||
filters: smallSavedFilters,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -134,7 +146,7 @@ function renderSettings(): void {
|
||||
<QuickFiltersSettings
|
||||
savedFiltersSource={QuickfiltertypesSourceDTO.logs}
|
||||
setIsSettingsOpen={jest.fn()}
|
||||
customFilters={savedFilters}
|
||||
customFilters={smallSavedFilters}
|
||||
refetchCustomFilters={jest.fn()}
|
||||
/>,
|
||||
);
|
||||
@@ -180,12 +192,13 @@ beforeEach(() => {
|
||||
{ showIP: true } as ApiMonitoringParams,
|
||||
mockSetApiMonitoringParams,
|
||||
]);
|
||||
mockedUseAuthZ.mockImplementation(mockUseAuthZGrantAll);
|
||||
setupServer();
|
||||
});
|
||||
|
||||
describe('Quick Filters', () => {
|
||||
it('displays the correct query name in the header', () => {
|
||||
render(<TestQuickFilters />);
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
expect(screen.getByText('Filters for')).toBeInTheDocument();
|
||||
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
|
||||
});
|
||||
@@ -194,7 +207,7 @@ describe('Quick Filters', () => {
|
||||
const setLastUsedQuery = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['setLastUsedQuery']
|
||||
>;
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
(useQueryBuilder as jest.Mock).mockReturnValue({
|
||||
currentQuery: {
|
||||
@@ -221,7 +234,7 @@ describe('Quick Filters', () => {
|
||||
panelType: 'graph', // not LIST view
|
||||
});
|
||||
|
||||
render(<TestQuickFilters />);
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
|
||||
// The dropdown trigger should show the first query name
|
||||
const trigger = screen.getByTestId('quick-filters-query-select');
|
||||
@@ -243,12 +256,10 @@ describe('Quick Filters', () => {
|
||||
|
||||
// jsdom cannot deliver the pointer click Base UI expects on an option,
|
||||
// so pick Query B with the arrow keys and Enter
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
screen.getByTestId('quick-filters-query-select-search'),
|
||||
).toHaveFocus(),
|
||||
await user.type(
|
||||
screen.getByTestId('quick-filters-query-select-search'),
|
||||
'{ArrowDown}{Enter}',
|
||||
);
|
||||
await user.keyboard('{ArrowDown}{Enter}');
|
||||
|
||||
// Verify setLastUsedQuery was called with index 1
|
||||
expect(setLastUsedQuery).toHaveBeenCalledWith(1);
|
||||
@@ -275,7 +286,7 @@ describe('Quick Filters', () => {
|
||||
panelType: 'list', // ListView
|
||||
});
|
||||
|
||||
render(<TestQuickFilters />);
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
|
||||
// Should show static query name without dropdown
|
||||
expect(screen.getByText('Query A')).toBeInTheDocument();
|
||||
@@ -286,7 +297,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
|
||||
it('should display static query name when only one query exists', () => {
|
||||
render(<TestQuickFilters />);
|
||||
render(<TestQuickFilters config={[]} />);
|
||||
|
||||
// Should show static query name
|
||||
expect(screen.getByText(QUERY_NAME)).toBeInTheDocument();
|
||||
@@ -298,7 +309,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
|
||||
it('should add filter data to query when checkbox is clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
render(<TestQuickFilters />);
|
||||
|
||||
@@ -330,7 +341,7 @@ describe('Quick Filters', () => {
|
||||
});
|
||||
});
|
||||
it('toggles Show IP addresses and updates API Monitoring params', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.API_MONITORING} />,
|
||||
@@ -364,7 +375,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('opens the settings with the saved filters added and the rest under other filters', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
server.use(
|
||||
rest.get(quickFiltersListURL, (_, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(smallFiltersListResponse)),
|
||||
@@ -386,7 +397,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('keeps same-name fields with different context as distinct entries', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
server.use(
|
||||
rest.get(quickFiltersSuggestionsURL, (_req, res, ctx) =>
|
||||
res(
|
||||
@@ -438,7 +449,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('adds a filter from OTHER FILTERS to ADDED FILTERS when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
renderSettings();
|
||||
|
||||
@@ -450,7 +461,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('removes a filter from ADDED FILTERS and moves it to OTHER FILTERS', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
@@ -468,7 +479,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('restores original filter state on Discard', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
renderSettings();
|
||||
const addedSection = screen.getByTestId(ADDED_FILTERS_TEST_ID);
|
||||
@@ -491,7 +502,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
});
|
||||
|
||||
it('saves the updated filters by calling PUT with correct payload', async () => {
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
|
||||
renderSettings();
|
||||
|
||||
@@ -506,7 +517,7 @@ describe('Quick Filters with custom filters', () => {
|
||||
expect(requestBody.filters).not.toContainEqual(
|
||||
expect.objectContaining({ name: FILTER_OS_DESCRIPTION }),
|
||||
);
|
||||
expect(requestBody.filters).toHaveLength(10);
|
||||
expect(requestBody.filters).toHaveLength(smallSavedFilters.length - 1);
|
||||
});
|
||||
|
||||
it('should render duration slider for duration_nono filter', async () => {
|
||||
@@ -548,10 +559,10 @@ describe('Quick Filters with custom filters', () => {
|
||||
expect(maxDuration).toHaveProperty('placeholder', '100000000');
|
||||
|
||||
// Type values and advance debounce
|
||||
await user.clear(minDuration);
|
||||
await user.type(minDuration, '10000');
|
||||
await user.clear(maxDuration);
|
||||
await user.type(maxDuration, '20000');
|
||||
await user.click(minDuration);
|
||||
await user.paste('10000');
|
||||
await user.click(maxDuration);
|
||||
await user.paste('20000');
|
||||
jest.advanceTimersByTime(2000);
|
||||
|
||||
await waitFor(() => {
|
||||
@@ -650,7 +661,7 @@ describe('Quick Filters refetch behavior', () => {
|
||||
}),
|
||||
);
|
||||
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
@@ -692,7 +703,7 @@ describe('Quick Filters refetch behavior', () => {
|
||||
),
|
||||
);
|
||||
|
||||
const user = userEvent.setup();
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
render(
|
||||
<TestQuickFilters quickFilterSource={QuickFiltersSource.LOGS_EXPLORER} />,
|
||||
);
|
||||
|
||||
17
frontend/src/constants/__tests__/alerts.test.ts
Normal file
17
frontend/src/constants/__tests__/alerts.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
@@ -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"
|
||||
|
||||
@@ -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: [],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -41,6 +41,10 @@
|
||||
&.isReplying {
|
||||
background: var(--accent-amber);
|
||||
}
|
||||
|
||||
&.hasUnreadReply {
|
||||
background: var(--accent-primary);
|
||||
}
|
||||
}
|
||||
|
||||
.body {
|
||||
|
||||
@@ -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 ? (
|
||||
|
||||
@@ -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',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -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,
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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] : [];
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
: [],
|
||||
};
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
@@ -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 =>
|
||||
|
||||
@@ -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',
|
||||
});
|
||||
}
|
||||
@@ -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>
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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"
|
||||
|
||||
@@ -27,6 +27,7 @@ function TopContributorsRenderer({
|
||||
labels: labelsArrayToObject(contributor.labels),
|
||||
relatedLogsLink: contributor.relatedLogsLink ?? '',
|
||||
relatedTracesLink: contributor.relatedTracesLink ?? '',
|
||||
relatedAITracesLink: contributor.relatedAITracesLink ?? '',
|
||||
}));
|
||||
}, [data?.data]);
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ function TimelineTableContent(): JSX.Element {
|
||||
labels: labelsArrayToObject(item.labels),
|
||||
relatedLogsLink: item.relatedLogsLink,
|
||||
relatedTracesLink: item.relatedTracesLink,
|
||||
relatedAITracesLink: item.relatedAITracesLink,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -93,6 +93,7 @@ describe('Alert history navigations keep the expression', () => {
|
||||
count: fingerprint,
|
||||
relatedLogsLink: '',
|
||||
relatedTracesLink: '',
|
||||
relatedAITracesLink: '',
|
||||
}));
|
||||
render(
|
||||
<>
|
||||
|
||||
@@ -2,7 +2,13 @@ import {
|
||||
GetMetricQueryRange,
|
||||
GetQueryResultsProps,
|
||||
} from 'lib/dashboard/getQueryResults';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import {
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { MetricQueryRangeSuccessResponse } from 'types/api/metrics/getQueryRange';
|
||||
|
||||
import EndPointPicker from '../Explorer/Domains/DomainDetails/components/EndPointPicker';
|
||||
@@ -65,7 +71,7 @@ describe('EndPointPicker', () => {
|
||||
});
|
||||
|
||||
it('reports the picked endpoint', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
(endPointName: string) => void
|
||||
>;
|
||||
@@ -83,7 +89,7 @@ describe('EndPointPicker', () => {
|
||||
});
|
||||
|
||||
it('shows All endpoints when none is picked and clears through it', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const onChange = jest.fn() as jest.MockedFunction<
|
||||
(endPointName: string) => void
|
||||
>;
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
userEvent,
|
||||
waitFor,
|
||||
within,
|
||||
NO_DELAY_USER_EVENT,
|
||||
} from 'tests/test-utils';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
@@ -209,7 +210,7 @@ describe('TopErrors', () => {
|
||||
});
|
||||
|
||||
it('scopes the query to the endpoint picked in the picker', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
const user = userEvent.setup(NO_DELAY_USER_EVENT);
|
||||
const expressions: string[] = [];
|
||||
server.use(
|
||||
rest.post(V5_QUERY_RANGE_API_PATH, async (req) => {
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
30
frontend/src/container/AppLayout/__tests__/testUtils.tsx
Normal file
30
frontend/src/container/AppLayout/__tests__/testUtils.tsx
Normal 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 },
|
||||
);
|
||||
}
|
||||
@@ -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 />
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
162
frontend/src/container/BottomStrip/NozHistory/NozHistory.tsx
Normal file
162
frontend/src/container/BottomStrip/NozHistory/NozHistory.tsx
Normal 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;
|
||||
@@ -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;
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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>
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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}`),
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user