Compare commits

..

2 Commits

Author SHA1 Message Date
Vinícius Lourenço
65eb2d3765 chore(lint): report Monaco features the production build strips 2026-11-25 13:04:46 -03:00
Vinícius Lourenço
b018fdf4a8 perf(web): load only the Monaco languages SigNoz uses 2026-11-25 13:04:46 -03:00
220 changed files with 1914 additions and 7238 deletions

View File

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

View File

@@ -110,9 +110,8 @@ 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. 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:
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:
- An arg the story sets. The story sets it because the play needs what that value renders, and the panel can flip it. On the `mine` view the dashboards Created-by filter opens with a tag to remove; on the other views it opens empty and there is no × to click. Check the tag is there by parsing the route the view resolves to.
- The controls every story has. `State` on loading or error renders no rows and no filter suggestions. `Access`, `Permissions` and `Revoked` remove rows, row actions and gated buttons, and the `editor` and `viewer` presets grant telemetry reads only, so a page gated on its own resource shows them nothing. `Check state` on loading disables every gated control, and on error an `AuthZButton` stays enabled while an `AuthZGuardContent` set to fail closed hides what it wraps. `License` and `Banner` decide the plan, so a cloud-only form is gone on the others. `Hold tooltips open` shows a label a second time, inside its tooltip.
- A count at 0. The page can swap its whole list for an empty state, and the header, filters and column picker go with it.
- A view, filter or invalid query that leaves no rows, even when the count is above 0.

View File

@@ -63,7 +63,7 @@ jobs:
- name: self-checkout
uses: actions/checkout@v4
- name: go-install
uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
uses: actions/setup-go@v5
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@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
uses: actions/setup-go@v5
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@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
uses: actions/setup-go@v5
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@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
uses: actions/setup-go@v5
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@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
uses: actions/setup-go@v5
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@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0
uses: actions/setup-go@v5
with:
go-version: "1.25"
- name: generate-transaction-groups

View File

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

View File

@@ -298,6 +298,8 @@
// 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)
"signoz/no-monaco-stripped-features": "error",
// Bans Monaco features the production build strips, and monaco-editor value imports outside src/lib/monaco (allowlisted in overrides below)
"no-restricted-globals": [
"error",
{
@@ -318,11 +320,6 @@
"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."
@@ -345,11 +342,6 @@
"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."
@@ -644,6 +636,13 @@
"rules": {
"signoz/no-builder-ai-query-access": "off"
}
},
{
// src/lib/monaco owns the monaco-editor imports that pick the languages and workers
"files": ["src/lib/monaco/**"],
"rules": {
"signoz/no-monaco-stripped-features": "off"
}
}
]
}

View File

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

View File

@@ -22,7 +22,6 @@ import i18n from '../src/ReactI18';
// 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/loader';
import '../src/lib/uPlotStylesheet';
import '../src/styles.scss';
@@ -198,9 +197,7 @@ const preview: Preview = {
['Overview', 'Authz'],
'Service Accounts',
'Ingestion',
['Overview', 'Authz'],
'Single Sign-on',
['Overview', 'Authz'],
'Keyboard Shortcuts',
],
'Auth',

View File

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

View File

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

View File

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

View File

@@ -0,0 +1,123 @@
import { ruleTester } from './rule-tester.mjs';
const IMPORT = 'Import Monaco from lib/monaco/setup';
const STRIPPED = 'which the production build strips';
await ruleTester({
rule: 'no-monaco-stripped-features',
valid: [
{
name: 'setup import',
code: "import { monaco } from 'lib/monaco/setup';",
},
{
name: 'type-only import',
code: "import type { editor } from 'monaco-editor';",
},
{
name: 'inline type specifiers only',
code: "import { type editor, type languages } from 'monaco-editor';",
},
{
name: 'type-only re-export',
code: "export type { editor } from 'monaco-editor';",
},
{
name: 'react wrapper',
code: "import Editor from '@monaco-editor/react';",
},
{
name: 'kept provider',
code: "monaco.languages.registerCompletionItemProvider('json', {});",
},
{
name: 'stripped option turned off',
code:
"const o = { experimentalGpuAcceleration: 'off', minimap: { showMarkSectionHeaders: false } };",
},
],
invalid: [
{
name: 'package entry import',
code: "import * as monaco from 'monaco-editor';",
errors: [{ message: IMPORT, line: 1, column: 25 }],
},
{
name: 'deep import',
code:
"import 'monaco-editor/esm/vs/basic-languages/python/python.contribution.js';",
errors: [{ message: IMPORT }],
},
{
name: 'mixed value and type specifiers',
code: "import { editor, type languages } from 'monaco-editor';",
errors: [{ message: IMPORT }],
},
{
name: 'dynamic import',
code: "const m = await import('monaco-editor');",
errors: [{ message: IMPORT }],
},
{
name: 'require',
code: "const m = require('monaco-editor');",
errors: [{ message: IMPORT }],
},
{
name: 're-export',
code: "export { editor } from 'monaco-editor';",
errors: [{ message: IMPORT }],
},
{
name: 'export all',
code: "export * from 'monaco-editor';",
errors: [{ message: IMPORT }],
},
{
name: 'stripped provider on monaco.languages',
code: "monaco.languages.registerInlayHintsProvider('sql', {});",
errors: [
{
message: 'needs the Monaco `inlayHints` contribution',
line: 1,
column: 1,
},
],
},
{
name: 'stripped provider on a destructured languages',
code: "languages.registerSignatureHelpProvider('sql', {});",
errors: [{ message: '`parameterHints`' }],
},
{
name: 'stripped provider called bare',
code: "registerRenameProvider('json', {});",
errors: [{ message: '`rename`' }],
},
{
name: 'stripped provider through a string key',
code: "monaco.languages['registerRenameProvider']('json', {});",
errors: [{ message: '`rename`' }],
},
{
name: 'semantic tokens provider',
code: "monaco.languages.registerDocumentSemanticTokensProvider('json', {});",
errors: [{ message: '`semanticTokens`' }],
},
{
name: 'stripped option turned on',
code: "const o = { experimentalGpuAcceleration: 'on' };",
errors: [{ message: '`gpu`', line: 1, column: 13 }],
},
{
name: 'stripped option with a variable value',
code: 'const o = { minimap: { showRegionSectionHeaders: enabled } };',
errors: [{ message: STRIPPED }],
},
{
name: 'quoted option key',
code: "const o = { 'showMarkSectionHeaders': true };",
errors: [{ message: '`sectionHeaders`' }],
},
],
});

View File

@@ -0,0 +1,138 @@
/**
* Rule: no-monaco-stripped-features
*
* The production build drops the Monaco contributions listed in
* plugins/rules/shared/monaco-stripped-features.mjs. Dev and Storybook still carry them,
* so a provider or option for one of them works there and silently does nothing
* in production. This rule reports them, plus value imports of `monaco-editor`
* outside src/lib/monaco: the package entry registers every language and worker.
*
* src/lib/monaco is allowlisted via overrides in .oxlintrc.json.
*/
import { MONACO_STRIPPED_FEATURES } from './shared/monaco-stripped-features.mjs';
const featureByApi = new Map();
const featureByOption = new Map();
for (const [feature, { providers = [], options = [] }] of Object.entries(
MONACO_STRIPPED_FEATURES,
)) {
providers.forEach((name) => featureByApi.set(name, feature));
options.forEach((name) => featureByOption.set(name, feature));
}
function isMonacoSource(value) {
return value === 'monaco-editor' || value.startsWith('monaco-editor/');
}
function isTypeOnlyImport(node) {
return (
node.importKind === 'type' ||
(node.specifiers.length > 0 &&
node.specifiers.every((s) => s.importKind === 'type'))
);
}
function propertyName(node) {
if (node.type === 'Identifier') {
return node.name;
}
if (node.type === 'Literal' && typeof node.value === 'string') {
return node.value;
}
return null;
}
function isDisabledValue(node) {
return (
node.type === 'Literal' && (node.value === false || node.value === 'off')
);
}
export default {
meta: {
type: 'problem',
docs: {
description:
'Disallow Monaco features the production build strips, and value imports of monaco-editor outside src/lib/monaco',
category: 'Monaco',
},
schema: [],
messages: {
provider:
'{{name}} needs the Monaco `{{feature}}` contribution, which the production build strips, so it works in dev and does nothing in production. Remove `{{feature}}` from plugins/rules/shared/monaco-stripped-features.mjs to use it.',
option:
'`{{name}}` needs the Monaco `{{feature}}` contribution, which the production build strips, so it works in dev and does nothing in production. Remove `{{feature}}` from plugins/rules/shared/monaco-stripped-features.mjs to use it.',
import:
'Import Monaco from lib/monaco/setup, not monaco-editor: the package entry registers every language and worker. Type-only imports are fine.',
},
},
create(context) {
const reportSource = (source) => {
if (
source?.type === 'Literal' &&
typeof source.value === 'string' &&
isMonacoSource(source.value)
) {
context.report({ node: source, messageId: 'import' });
}
};
return {
ImportDeclaration(node) {
if (!isTypeOnlyImport(node)) {
reportSource(node.source);
}
},
ImportExpression: (node) => reportSource(node.source),
ExportAllDeclaration(node) {
if (node.exportKind !== 'type') {
reportSource(node.source);
}
},
ExportNamedDeclaration(node) {
if (node.exportKind !== 'type') {
reportSource(node.source);
}
},
CallExpression(node) {
const { callee } = node;
if (callee.type === 'Identifier' && callee.name === 'require') {
reportSource(node.arguments[0]);
return;
}
const name =
callee.type === 'MemberExpression'
? propertyName(callee.property)
: callee.type === 'Identifier'
? callee.name
: null;
if (name !== null && featureByApi.has(name)) {
context.report({
node: callee,
messageId: 'provider',
data: { name, feature: featureByApi.get(name) },
});
}
},
Property(node) {
if (node.computed) {
return;
}
const name = propertyName(node.key);
if (
name !== null &&
featureByOption.has(name) &&
!isDisabledValue(node.value)
) {
context.report({
node: node.key,
messageId: 'option',
data: { name, feature: featureByOption.get(name) },
});
}
},
};
},
};

View File

@@ -0,0 +1,29 @@
/**
* Monaco editor contributions the production build drops (vite.config.ts marks
* them side-effect free), with the API that would need them at runtime.
* `signoz/no-monaco-stripped-features` reports those APIs, since the build
* leaves them without an error and without an effect.
*
* To use one, delete its entry here.
*/
export const MONACO_STRIPPED_FEATURES = {
codelens: { providers: ['registerCodeLensProvider'] },
dropOrPasteInto: {},
gpu: { options: ['experimentalGpuAcceleration'] },
inlayHints: { providers: ['registerInlayHintsProvider'] },
inlineCompletions: { providers: ['registerInlineCompletionsProvider'] },
linkedEditing: { providers: ['registerLinkedEditingRangeProvider'] },
parameterHints: { providers: ['registerSignatureHelpProvider'] },
rename: {
providers: ['registerRenameProvider', 'registerNewSymbolNameProvider'],
},
sectionHeaders: {
options: ['showRegionSectionHeaders', 'showMarkSectionHeaders'],
},
semanticTokens: {
providers: [
'registerDocumentSemanticTokensProvider',
'registerDocumentRangeSemanticTokensProvider',
],
},
};

View File

@@ -21,6 +21,7 @@ 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';
import noMonacoStrippedFeatures from './rules/no-monaco-stripped-features.mjs';
export default {
meta: {
@@ -43,5 +44,6 @@ export default {
'require-disable-reason': requireDisableReason,
'no-dom-node-access': noDomNodeAccess,
'no-builder-ai-query-access': noBuilderAiQueryAccess,
'no-monaco-stripped-features': noMonacoStrippedFeatures,
},
};

View File

@@ -86,8 +86,8 @@ importers:
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react-dom@18.2.0(react@18.2.0))(react@18.2.0))(react@18.2.0)
'@signozhq/ui':
specifier: 0.4.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)
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)
'@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.1-rc.2':
resolution: {integrity: sha512-pCMRzrJ6CmGjEgAQ2B6wRRengP2sy7Y860Npr5nkCapc9NPH5jy4VO48CDv5gnKwWSKShmLHwzbiK2E1cGndKQ==}
'@signozhq/ui@0.4.0-rc.5':
resolution: {integrity: sha512-WlJMfeDfvL2hjMpTpHhhND/tuK7X0sfXQlx6E1ZG+6E/DYHpuhYljfvW3E6/BohIlHFlTyCs/ZMl9wnV2k9Zcw==}
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.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)':
'@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)':
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

1
frontend/public/css/uPlot.min.css vendored Normal file
View File

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

View File

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

View File

@@ -808,7 +808,7 @@ describe('PrivateRoute', () => {
assertStaysOnRoute(ROUTES.BILLING);
});
it('should allow VIEWER to access org-settings when workspace is blocked', () => {
it('should redirect VIEWER to workspace locked when trying to access org-settings', async () => {
renderPrivateRoute({
initialRoute: ROUTES.ORG_SETTINGS,
appContext: {
@@ -821,7 +821,7 @@ describe('PrivateRoute', () => {
isCloudUser: true,
});
assertStaysOnRoute(ROUTES.ORG_SETTINGS);
await assertRedirectsTo(ROUTES.WORKSPACE_LOCKED);
});
it('should allow VIEWER to access members settings when workspace is blocked', () => {
@@ -1707,7 +1707,6 @@ 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: {

View File

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

View File

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

View File

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

View File

@@ -1,9 +1,10 @@
import { useEffect } from 'react';
import { useCallback, useEffect, useRef, useState } from 'react';
import { useMutation } from 'react-query';
import { Check, ChevronsDown, ScrollText, X } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Dialog } from '@signozhq/ui/dialog';
import { Button, Modal } from 'antd';
import Flex from 'periscope/components/Flex/Flex';
import updateUserPreference from 'api/v1/user/preferences/name/update';
import cx from 'classnames';
import { USER_PREFERENCES } from 'constants/userPreferences';
import dayjs from 'dayjs';
import { useGetTenantLicense } from 'hooks/useGetTenantLicense';
@@ -12,9 +13,8 @@ import { ChangelogSchema } from 'types/api/changelog/getChangelogByVersion';
import { UserPreference } from 'types/api/preferences/preference';
import ChangelogRenderer from './components/ChangelogRenderer';
import { useChangelogScroll } from './useChangelogScroll';
import styles from './ChangelogModal.module.scss';
import './ChangelogModal.styles.scss';
interface Props {
changelog: ChangelogSchema;
@@ -22,7 +22,8 @@ interface Props {
}
function ChangelogModal({ changelog, onClose }: Props): JSX.Element {
const { contentRef, hasScroll, scrollForMore } = useChangelogScroll();
const [hasScroll, setHasScroll] = useState(false);
const changelogContentSectionRef = useRef<HTMLDivElement>(null);
const { userPreferences, updateUserPreferenceInContext } = useAppContext();
const formattedReleaseDate = dayjs(changelog?.release_date).format(
@@ -56,6 +57,30 @@ 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',
@@ -64,61 +89,75 @@ 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 (
<Dialog
<Modal
className={cx('changelog-modal')}
title={
<div className="changelog-modal-title">
<ScrollText size={16} />
What’s New ⎯ Changelog : {formattedReleaseDate}
</div>
}
width={820}
open
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>
</>
)
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>
}
>
<div data-testid="changelog-content" ref={contentRef}>
<ChangelogRenderer changelog={changelog} />
<div
className="changelog-modal-content"
data-testid="changelog-content"
ref={changelogContentSectionRef}
>
{changelog && <ChangelogRenderer changelog={changelog} />}
</div>
{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>
</Modal>
);
}

View File

@@ -1,23 +1,12 @@
import { ReactNode } from 'react';
/* eslint-disable @typescript-eslint/explicit-function-return-type */
import { fireEvent, render, screen } from '@testing-library/react';
import { USER_PREFERENCES } from 'constants/userPreferences';
import { IAppContext } from 'providers/App/types';
import {
fireEvent,
getAppContextMock,
render,
screen,
userEvent,
waitFor,
} from 'tests/test-utils';
import MockQueryClientProvider from 'providers/test/MockQueryClientProvider';
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';
@@ -51,165 +40,71 @@ const mockChangelog: ChangelogSchema = {
jest.mock(
'react-markdown',
() =>
function ReactMarkdown({ children }: { children: ReactNode }): JSX.Element {
function ReactMarkdown({ children }: any) {
return <div>{children}</div>;
},
);
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(
<ChangelogModal changelog={mockChangelog} onClose={onClose} />,
undefined,
{
appContextOverrides: {
userPreferences: [seenChangelogVersion],
...appContextOverrides,
// 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 {
render(
<MockQueryClientProvider>
<ChangelogModal changelog={mockChangelog} onClose={onClose} />
</MockQueryClientProvider>,
);
}
describe('ChangelogModal', () => {
it('renders the dialog with the changelog data', async () => {
it('renders modal with changelog data', () => {
renderChangelog();
await expect(
screen.findByTestId('changelog-dialog-title'),
).resolves.toHaveTextContent('What’s New ⎯ Changelog : June 10, 2025');
expect(
screen.getByText('What’s New ⎯ Changelog : June 10, 2025'),
).toBeInTheDocument();
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 the close button is clicked', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
it('calls onClose when Skip for now is clicked', () => {
const onClose = jest.fn();
renderChangelog(onClose);
await user.click(await screen.findByTestId('changelog-dialog-close'));
expect(onClose).toHaveBeenCalledTimes(1);
fireEvent.click(screen.getByText('Skip for now'));
expect(onClose).toHaveBeenCalled();
});
it('offers no upgrade actions to a cloud workspace', async () => {
it('opens migration docs when Update my workspace is clicked', () => {
window.open = jest.fn();
renderChangelog();
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(
fireEvent.click(screen.getByText('Update my workspace'));
expect(window.open).toHaveBeenCalledWith(
'https://signoz.io/upgrade-path',
'_blank',
'noopener,noreferrer',
);
open.mockRestore();
});
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(),
);
});
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();
}
});
});

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,4 +1,3 @@
import { useCallback, useState } from 'react';
import { ConfigProvider, Select } from 'antd';
import { Checkbox } from '@signozhq/ui/checkbox';
import cx from 'classnames';
@@ -21,9 +20,7 @@ interface Props {
placeholder: string;
testId: string;
onChange: (values: string[]) => 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;
onClear?: () => void;
onDropdownVisibleChange?: (open: boolean) => void;
disabled?: boolean;
}
@@ -34,31 +31,10 @@ function MultiSelectFilter({
placeholder,
testId,
onChange,
onCommit,
onClear,
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
@@ -75,6 +51,7 @@ function MultiSelectFilter({
menuItemSelectedIcon={null}
data-testid={testId}
disabled={disabled}
onClear={onClear}
optionRender={(option): JSX.Element => (
<div
className={styles.checkOption}
@@ -89,8 +66,8 @@ function MultiSelectFilter({
<span className={styles.checkOptionLabel}>{option.label}</span>
</div>
)}
onChange={(next): void => handleChange(next as string[])}
onDropdownVisibleChange={handleDropdownVisibleChange}
onChange={(next): void => onChange(next as string[])}
onDropdownVisibleChange={onDropdownVisibleChange}
/>
</ConfigProvider>
);

View File

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

View File

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

View File

@@ -31,7 +31,7 @@ interface FilterZoneDraft {
applyDraft: (next: string) => void;
handleCreatedByChange: (emails: string[]) => void;
handleUpdatedChange: (window: UpdatedWindow) => void;
handleCreatedByCommit: (emails: string[]) => void;
handleClearCreatedBy: () => void;
handleClear: () => void;
}
@@ -97,14 +97,10 @@ export function useFilterZoneDraft({
[draft, applyDraft, onFilterApplied],
);
// 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-all on the Created-by select removes its clause and runs immediately.
const handleClearCreatedBy = useCallback((): void => {
applyDraft(spliceClause(draft, 'created_by', null));
}, [draft, applyDraft]);
// Clear resets the draft and runs immediately (empty query).
const handleClear = useCallback((): void => {
@@ -126,7 +122,7 @@ export function useFilterZoneDraft({
applyDraft,
handleCreatedByChange,
handleUpdatedChange,
handleCreatedByCommit,
handleClearCreatedBy,
handleClear,
};
}

View File

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

View File

@@ -39,7 +39,6 @@ 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;
@@ -68,7 +67,6 @@ function ViewsRail({
saveTestIdPrefix = 'save-view',
renameTestIdPrefix = 'rename-view',
customSectionLabel = 'My views',
viewNamePlaceholder = 'e.g. Production',
deleteDescription = 'This removes the saved view.',
guard,
onViewSaved,
@@ -289,7 +287,6 @@ 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
@@ -300,7 +297,6 @@ function ViewsRail({
description="The view keeps its filters under the new name."
confirmLabel="Rename"
initialName={renameTarget?.label}
placeholder={viewNamePlaceholder}
testIdPrefix={renameTestIdPrefix}
/>
{contextHolder}

View File

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

View File

@@ -105,8 +105,6 @@ const stopEventsExtension = EditorView.domEventHandlers({
},
});
const EDITOR_BASIC_SETUP = { lineNumbers: false };
interface QuerySearchProps {
placeholder?: string;
onChange: (value: string) => void;
@@ -715,17 +713,14 @@ function QuerySearch({
}
}, []);
const onChangeRef = useRef(onChange);
onChangeRef.current = onChange;
const handleChange = useCallback((value: string): void => {
const handleChange = (value: string): void => {
if (isProgrammaticChangeRef.current) {
isProgrammaticChangeRef.current = false;
return;
}
onChangeRef.current(value);
}, []);
onChange(value);
};
const handleBlur = (): void => {
const currentExpression = getCurrentExpression();
@@ -1479,65 +1474,6 @@ 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);
@@ -1714,9 +1650,56 @@ function QuerySearch({
hasErrors: validation.errors.length > 0,
hasInitialExpression: isScopedFilter && !showScopeChip,
})}
extensions={editorExtensions}
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,
},
]),
),
]}
placeholder={placeholder}
basicSetup={EDITOR_BASIC_SETUP}
basicSetup={{
lineNumbers: false,
}}
onFocus={(): void => {
setIsFocused(true);
}}

View File

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

View File

@@ -1,3 +1,5 @@
import { useState } from 'react';
import { Tooltip } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import { ChevronDown, ChevronRight, Undo2 } from '@signozhq/icons';
@@ -20,6 +22,31 @@ 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"
@@ -40,19 +67,7 @@ export function CheckboxFilterV2Header({
) : (
<ChevronRight size={13} cursor="pointer" />
)}
<Typography
variant="paragraph"
size="base"
weight="regular"
color="secondary"
as="span"
display="inline-block"
minWidth={0}
textOverflow="ellipsis"
textTransform="capitalize"
>
{title}
</Typography>
<Tooltip title={isTitleTruncated ? title : undefined}>{titleText}</Tooltip>
</section>
{isOpen && canReset && (
<section className={styles.rightAction}>

View File

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

View File

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

View File

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

View File

@@ -8,12 +8,9 @@ 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;
@@ -64,26 +61,6 @@ export const dirtySettings = async (context: PlayContext): Promise<void> => {
await screen.findByRole('button', { name: 'Save changes' });
};
export const hoverTruncatedTitle = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const [filter] = args.config ?? [];
// Duration and slider sections render no title of their own.
if (filter?.type !== FiltersType.CHECKBOX || !filter.title) {
return;
}
const [label] = await within(canvasElement).findAllByText(
filter.title,
{},
UNTIL_LOADED,
);
await hoverTruncatableText(label, filter.title, {
cut: filter.title === longTitleConfig[0].title || undefined,
});
};
export const openQueryPicker = async ({
canvasElement,
}: PlayContext): Promise<void> => {

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect, useState } from 'react';
import { createPortal } from 'react-dom';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
@@ -6,13 +6,17 @@ import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { Maximize2, Minus, X } from '@signozhq/icons';
import { History, Maximize2, Minus, Plus, 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 } from '../hooks/useAIAssistantAnalyticsContext';
import {
normalizePage,
useAIAssistantAnalyticsContext,
} from '../hooks/useAIAssistantAnalyticsContext';
import { useActiveChatTitle } from '../hooks/useActiveChatTitle';
import { useAIAssistantStore } from '../store/useAIAssistantStore';
import { VariantContext } from '../VariantContext';
@@ -30,6 +34,7 @@ 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(
@@ -42,11 +47,13 @@ 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.
// always starts a brand-new conversation; resuming earlier
// threads is done via the in-modal history sidebar.
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;
@@ -59,6 +66,7 @@ export default function AIAssistantModal(): JSX.Element | null {
closeModal();
} else {
startNewConversation();
setShowHistory(false);
void logEvent(AIAssistantEvents.Opened, {
source: AIAssistantOpenSource.Shortcut,
currentPage: normalizePage(pathname),
@@ -94,6 +102,29 @@ 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
@@ -142,6 +173,33 @@ 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"
@@ -163,7 +221,7 @@ export default function AIAssistantModal(): JSX.Element | null {
size="sm"
icon
color="secondary"
onClick={minimizeModal}
onClick={handleMinimize}
aria-label="Minimize to side panel"
>
<Minus size={14} />
@@ -187,8 +245,12 @@ export default function AIAssistantModal(): JSX.Element | null {
{/* Body */}
<div className={styles.body}>
{activeConversationId && (
<ConversationView conversationId={activeConversationId} />
{showHistory ? (
<HistorySidebar onSelect={handleHistorySelect} />
) : (
activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)
)}
</div>
</div>

View File

@@ -1,4 +1,4 @@
import { useCallback } from 'react';
import { useCallback, useState } from 'react';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import { matchRoute } from 'lib/router/matchRoute';
@@ -6,13 +6,17 @@ import { navigate } from 'lib/router/navigation';
import { useAppLocation } from 'lib/router/useAppLocation';
import { Tooltip } from '@signozhq/ui/tooltip';
import ROUTES from 'constants/routes';
import { Maximize2, Minus, X } from '@signozhq/icons';
import { History, Maximize2, Plus, 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';
@@ -40,6 +44,7 @@ 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, {
@@ -48,23 +53,13 @@ export default function AIAssistantPanel(): JSX.Element | null {
const activeConversationId = useAIAssistantStore(
(s) => s.activeConversationId,
);
const activeThreadId = useAIAssistantStore((s) =>
s.activeConversationId
? s.conversations[s.activeConversationId]?.threadId
: undefined,
);
const closeDrawer = useAIAssistantStore((s) => s.closeDrawer);
const closeChatTab = useAIAssistantOpenConversationsStore((s) => s.close);
const startNewConversation = useAIAssistantStore(
(s) => s.startNewConversation,
);
const analyticsCtx = useAIAssistantAnalyticsContext();
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;
@@ -79,6 +74,25 @@ 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;
}
@@ -135,17 +149,29 @@ export default function AIAssistantPanel(): JSX.Element | null {
</div>
<div className={styles.actions}>
<Tooltip title="Minimize">
<Tooltip title={showHistory ? 'Back to chat' : 'Conversations'}>
<Button
variant="ghost"
size="sm"
icon
color="secondary"
testId="ai-assistant-panel-minimize"
onClick={closeDrawer}
aria-label="Minimize panel"
onClick={(): void => setShowHistory((v) => !v)}
aria-label="Toggle conversations"
>
<Minus size={14} />
<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>
@@ -171,7 +197,7 @@ export default function AIAssistantPanel(): JSX.Element | null {
icon
color="secondary"
testId="ai-assistant-panel-close"
onClick={handleClose}
onClick={closeDrawer}
aria-label="Close panel"
>
<X size={14} />
@@ -180,8 +206,12 @@ export default function AIAssistantPanel(): JSX.Element | null {
</div>
</div>
{activeConversationId && (
<ConversationView conversationId={activeConversationId} />
{showHistory ? (
<ConversationsList onSelect={handleHistorySelect} />
) : (
activeConversationId && (
<ConversationView conversationId={activeConversationId} />
)
)}
</FloatingPanel>
</VariantContext.Provider>

View File

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

View File

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

View File

@@ -3,7 +3,6 @@ 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';
@@ -82,13 +81,11 @@ 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)}
/>
@@ -154,7 +151,7 @@ describe('ConversationView — empty-state chip context', () => {
},
streams: {},
activeConversationId: CONVERSATION_ID,
loadingThreadIds: [],
isLoadingThread: false,
sendMessage,
} as unknown as Partial<ReturnType<typeof useAIAssistantStore.getState>>);
});
@@ -183,37 +180,6 @@ 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();
@@ -244,7 +210,7 @@ describe('ConversationView — reply start time', () => {
},
},
activeConversationId: CONVERSATION_ID,
loadingThreadIds: [],
isLoadingThread: false,
});
const { getByTestId } = renderView('panel');
@@ -269,7 +235,7 @@ describe('ConversationView — Snake on the empty state', () => {
},
streams: {},
activeConversationId: CONVERSATION_ID,
loadingThreadIds: [],
isLoadingThread: false,
});
});

View File

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

View File

@@ -18,7 +18,6 @@ import {
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { Conversation } from '../../types';
import { formatRelativeTime } from '../../utils/formatRelativeTime';
import styles from './ConversationItem.module.scss';
@@ -31,6 +30,32 @@ 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,
@@ -48,16 +73,6 @@ 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;
@@ -156,23 +171,13 @@ 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]: dotState === 'replying',
[styles.hasUnreadReply]: dotState === 'unread',
})}
data-state={dotState}
data-testid={`ai-conversation-item-${conversation.id}-dot`}
/>
<span className={cx(styles.dot, { [styles.isReplying]: isReplying })} />
<div className={styles.body}>
{isEditing ? (

View File

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

View File

@@ -1,26 +1,35 @@
@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;
// 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;
// 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;
}
}

View File

@@ -4,9 +4,12 @@ import { Button } from '@signozhq/ui/button';
import { Input } from '@signozhq/ui/input';
import { Plus } from '@signozhq/icons';
import { useOpenConversation } from '../../hooks/useOpenConversation';
import logEvent from 'api/common/logEvent';
import { AIAssistantEvents } from '../../events';
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
import { Conversation } from '../../types';
import { useVariant } from '../../VariantContext';
import ConversationItem from '../ConversationItem';
import styles from './ConversationsList.module.scss';
@@ -72,12 +75,16 @@ 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 openConversation = useOpenConversation();
const setActiveConversation = useAIAssistantStore(
(s) => s.setActiveConversation,
);
const loadThread = useAIAssistantStore((s) => s.loadThread);
const fetchThreads = useAIAssistantStore((s) => s.fetchThreads);
const archiveConversation = useAIAssistantStore((s) => s.archiveConversation);
const restoreConversation = useAIAssistantStore((s) => s.restoreConversation);
@@ -130,12 +137,34 @@ export default function ConversationsList({
const isSearching = trimmedQuery.length > 0;
const handleSelect = (id: string): void => {
openConversation(id);
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);
}
onSelect?.(id);
};
const variantClass =
variant === 'page' ? styles.variantPage : styles.variantPanel;
return (
<div className={styles.conversationsList}>
<div className={cx(styles.conversationsList, variantClass)}>
<div className={styles.searchBar}>
<div className={styles.search}>
<Input

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -529,26 +529,11 @@ 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);
@@ -635,8 +620,6 @@ export interface AIAssistantStore {
// UI state
isDrawerOpen: boolean;
isModalOpen: boolean;
/** The bottom strip's recent-conversations list. */
isHistoryOpen: boolean;
activeConversationId: string | null;
// Data
@@ -645,9 +628,6 @@ 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.
@@ -656,10 +636,7 @@ export interface AIAssistantStore {
// Loading state
isLoadingThreads: boolean;
/** Threads whose messages are being fetched. */
loadingThreadIds: string[];
/** True once `fetchThreads` has succeeded; a failed fetch leaves it false. */
hasLoadedThreads: boolean;
isLoadingThread: boolean;
// Actions
openDrawer: () => void;
@@ -667,13 +644,11 @@ 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>;
@@ -806,20 +781,16 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
immer<AIAssistantStore>((set, get) => ({
isDrawerOpen: false,
isModalOpen: false,
isHistoryOpen: false,
activeConversationId: null,
conversations: {},
streams: {},
unreadReplyIds: [],
isLoadingThreads: false,
loadingThreadIds: [],
hasLoadedThreads: false,
isLoadingThread: false,
answeredBlocks: {},
openDrawer: (): void => {
set((state) => {
state.isDrawerOpen = true;
state.isHistoryOpen = false;
if (!state.activeConversationId) {
const id = uuidv4();
state.conversations[id] = {
@@ -842,7 +813,6 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
openModal: (): void => {
set((state) => {
state.isModalOpen = true;
state.isHistoryOpen = false;
if (!state.activeConversationId) {
const id = uuidv4();
state.conversations[id] = {
@@ -866,7 +836,6 @@ 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] = {
@@ -880,16 +849,6 @@ 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;
@@ -935,14 +894,7 @@ 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
@@ -963,7 +915,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
const conv = s.conversations[id];
if (conv?.threadId && conv.messages.length === 0) {
activeThreadIdToLoad = conv.threadId;
setThreadLoading(s, conv.threadId, true);
s.isLoadingThread = true;
}
}
});
@@ -992,7 +944,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// eslint-disable-next-line sonarjs/cognitive-complexity
loadThread: async (threadId: string): Promise<void> => {
set((s) => {
setThreadLoading(s, threadId, true);
s.isLoadingThread = true;
s.activeConversationId = threadId;
});
try {
@@ -1026,7 +978,7 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
startedAt: null,
};
}
setThreadLoading(s, threadId, false);
s.isLoadingThread = false;
});
// Reconnect to SSE if backend execution is still running
@@ -1060,13 +1012,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;
});
}
},
@@ -1105,13 +1057,6 @@ 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);
});
},
@@ -1121,9 +1066,6 @@ 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);
@@ -1524,8 +1466,6 @@ 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,
@@ -1576,27 +1516,6 @@ export const useAIAssistantStore = create<AIAssistantStore>()(
// Standalone imperative accessors
export const openAIAssistant = (): void =>
useAIAssistantStore.getState().openDrawer();
/** Opens the panel on a fresh chat, reusing the open one while nothing has been sent in it. */
export const openNewAIAssistantChat = (): void => {
const {
activeConversationId,
conversations,
startNewConversation,
openDrawer,
} = useAIAssistantStore.getState();
const active = activeConversationId
? conversations[activeConversationId]
: undefined;
if (
!active ||
active.threadId ||
active.isHydrating ||
active.messages.length > 0
) {
startNewConversation();
}
openDrawer();
};
export const closeAIAssistant = (): void =>
useAIAssistantStore.getState().closeDrawer();
export const openAIAssistantModal = (): void =>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,5 @@
import {
lazy,
ReactNode,
Suspense,
useCallback,
useEffect,
useMemo,
@@ -29,6 +27,7 @@ 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';
@@ -39,6 +38,8 @@ 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';
@@ -80,7 +81,6 @@ 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,19 +92,6 @@ 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 {
@@ -845,21 +832,15 @@ function AppLayout(props: AppLayoutProps): JSX.Element {
</div>
{isLoggedIn && isAIAssistantEnabled && (
<Sentry.ErrorBoundary>
<Suspense fallback={null}>
<AIAssistantPanel />
<AIAssistantModal />
</Suspense>
</Sentry.ErrorBoundary>
<>
<AIAssistantPanel />
<AIAssistantModal />
</>
)}
</Flex>
{showChangelogModal && changelog && (
<Sentry.ErrorBoundary>
<Suspense fallback={null}>
<ChangelogModal changelog={changelog} onClose={toggleChangelogModal} />
</Suspense>
</Sentry.ErrorBoundary>
<ChangelogModal changelog={changelog} onClose={toggleChangelogModal} />
)}
<AppToaster />

View File

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

View File

@@ -8,51 +8,57 @@ import {
AIAssistantEvents,
AIAssistantOpenSource,
} from 'container/AIAssistant/events';
import { normalizePage } from 'container/AIAssistant/hooks/useAIAssistantAnalyticsContext';
import { selectPendingUserInputStreamCount } from 'container/AIAssistant/store/pendingInputSelectors';
import {
normalizePage,
useAIAssistantAnalyticsContext,
} from 'container/AIAssistant/hooks/useAIAssistantAnalyticsContext';
import {
openNewAIAssistantChat,
openAIAssistant,
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 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.
* 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.
*/
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 analyticsCtx = useAIAssistantAnalyticsContext();
const handleOpen = useCallback((): void => {
const handleClick = useCallback((): void => {
if (isDrawerOpen) {
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),
});
closeDrawer();
return;
}
openNewAIAssistantChat();
}, [analyticsCtx, isDrawerOpen, pathname]);
void logEvent(AIAssistantEvents.Opened, {
source: AIAssistantOpenSource.BottomStrip,
currentPage: normalizePage(pathname),
});
openAIAssistant();
}, [closeDrawer, isDrawerOpen, pathname]);
if (!isAIAssistantEnabled || isAIAssistantPage) {
return null;
@@ -60,6 +66,13 @@ 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
@@ -68,7 +81,15 @@ function AskNoz(): JSX.Element | null {
size="sm"
prefix={<Noz size={16} />}
testId="bottom-strip-ask-noz-button"
onClick={handleOpen}
onClick={handleClick}
aria-pressed={isDrawerOpen}
aria-label={
showPendingBadge
? `Ask Noz, ${pendingUserInputCount} ${
pendingUserInputCount === 1 ? 'action needs' : 'actions need'
} your response`
: 'Ask Noz'
}
>
Ask Noz
</Button>

View File

@@ -3,7 +3,7 @@ import {
AIAssistantEvents,
AIAssistantOpenSource,
} from 'container/AIAssistant/events';
import { openNewAIAssistantChat } from 'container/AIAssistant/store/useAIAssistantStore';
import { openAIAssistant } from 'container/AIAssistant/store/useAIAssistantStore';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import { render, userEvent } from 'tests/test-utils';
@@ -11,26 +11,43 @@ import AskNoz from '../AskNoz';
jest.mock('hooks/useIsAIAssistantEnabled');
jest.mock('container/AIAssistant/store/useAIAssistantStore', () => ({
openNewAIAssistantChat: jest.fn(),
openAIAssistant: jest.fn(),
useAIAssistantStore: jest.fn(),
}));
const mockEnabled = useIsAIAssistantEnabled as jest.MockedFunction<
typeof useIsAIAssistantEnabled
>;
const mockOpenNew = jest.mocked(openNewAIAssistantChat);
const mockOpen = openAIAssistant as jest.MockedFunction<typeof openAIAssistant>;
const mockClose = jest.fn() as jest.MockedFunction<() => void>;
// 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,
}: { isDrawerOpen?: boolean } = {}): void {
useAIAssistantStore.mockImplementation((selector: (s: unknown) => unknown) =>
selector({ isDrawerOpen }),
);
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;
});
}
const SLOT = 'bottom-strip-ask-noz';
@@ -58,12 +75,12 @@ describe('AskNoz', () => {
expect(queryByTestId(SLOT)).not.toBeInTheDocument();
});
it('stays while the drawer is open, to start another chat', () => {
it('stays pressed while the drawer is open', () => {
mockStore({ isDrawerOpen: true });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveTextContent('Ask Noz');
expect(getByTestId(BUTTON)).toHaveAttribute('aria-pressed', 'true');
});
it('renders nothing on the Noz full page, where the drawer does not mount', () => {
@@ -76,34 +93,25 @@ describe('AskNoz', () => {
});
describe('what it does', () => {
it('opens the drawer on a new chat', async () => {
it('opens the drawer on click', async () => {
const user = userEvent.setup();
const { getByTestId } = render(<AskNoz />);
await user.click(getByTestId(BUTTON));
expect(mockOpenNew).toHaveBeenCalledTimes(1);
expect(mockOpen).toHaveBeenCalledTimes(1);
});
it('starts a new chat from the open drawer and reports it as one', async () => {
it('closes the open drawer on the same chat instead of starting a new one', async () => {
const user = userEvent.setup();
mockStore({ isDrawerOpen: true });
const { getByTestId } = render(<AskNoz />);
await user.click(getByTestId(BUTTON));
expect(mockOpenNew).toHaveBeenCalledTimes(1);
expect(logEvent).toHaveBeenCalledWith(
AIAssistantEvents.NewChatClicked,
expect.objectContaining({
mode: 'sidepane',
source: AIAssistantOpenSource.BottomStrip,
}),
);
expect(logEvent).not.toHaveBeenCalledWith(
AIAssistantEvents.Opened,
expect.anything(),
);
expect(mockClose).toHaveBeenCalledTimes(1);
expect(mockOpen).not.toHaveBeenCalled();
expect(logEvent).not.toHaveBeenCalled();
});
it('reports the open as coming from the strip', async () => {
@@ -118,4 +126,50 @@ describe('AskNoz', () => {
);
});
});
describe('pending badge', () => {
it('announces the count when Noz is waiting on the user', () => {
mockStore({ pendingCount: 2 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute(
'aria-label',
'Ask Noz, 2 actions need your response',
);
});
it('uses the singular for one pending action', () => {
mockStore({ pendingCount: 1 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute(
'aria-label',
'Ask Noz, 1 action needs your response',
);
});
it('stays quiet when nothing is pending', () => {
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
});
it('stays quiet while the drawer is open, Noz is already on screen', () => {
mockStore({ isDrawerOpen: true, pendingCount: 3 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
});
it('stays quiet while the modal is open, Noz is already on screen', () => {
mockStore({ isModalOpen: true, pendingCount: 3 });
const { getByTestId } = render(<AskNoz />);
expect(getByTestId(BUTTON)).toHaveAttribute('aria-label', 'Ask Noz');
});
});
});

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,7 +1,10 @@
import type { Obstacle, Rect } from 'lib/obstacles/types';
import type {
FloatingObstacle,
FloatingRect,
} from 'periscope/components/FloatingPanel/types';
// Pylon's own class names, which styles.scss also targets.
export const SUPPORT_CHAT_SELECTOR = '.PylonChat-chatWindowFrameContainer';
const SUPPORT_CHAT_SELECTOR = '.PylonChat-chatWindowFrameContainer';
const SUPPORT_CHAT_CLOSED_CLASS = 'PylonChat-chatWindowFrameContainer--closed';
const listeners = new Set<() => void>();
@@ -17,7 +20,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(): Rect | null {
function getSupportChatRect(): FloatingRect | null {
const element = document.querySelector<HTMLElement>(SUPPORT_CHAT_SELECTOR);
if (!element) {
return null;
@@ -55,7 +58,7 @@ function subscribeToSupportChat(onChange: () => void): () => void {
};
}
export const supportChatObstacle: Obstacle = {
export const supportChatObstacle: FloatingObstacle = {
getRect: getSupportChatRect,
subscribe: subscribeToSupportChat,
};

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,8 +2,6 @@ import { useLayoutEffect } from 'react';
import AskNoz from './AskNoz/AskNoz';
import LeftSlot from './LeftSlot/LeftSlot';
import NozActiveChat from './NozActiveChat/NozActiveChat';
import NozHistory from './NozHistory/NozHistory';
import { useBottomStripStore } from './store/useBottomStripStore';
import SupportButton from './SupportButton/SupportButton';
@@ -61,11 +59,7 @@ function BottomStrip(): JSX.Element {
<LeftSlot />
</div>
<div className={styles.right}>
<div className={styles.chats}>
<NozActiveChat />
</div>
<AskNoz />
<NozHistory />
<SupportButton />
</div>
</div>

View File

@@ -1,4 +1,4 @@
import type { ReactElement, ReactNode } from 'react';
import type { ReactNode } from 'react';
export enum StripTone {
Default = 'default',
@@ -29,14 +29,3 @@ export type StripItem =
/** Tints the icon; the text stays neutral at every tone. */
tone?: StripTone;
};
/** One tab in `StripTabs`. */
export interface StripTabItem {
/** Stable identity, passed back to `onSelect` / `onClose`. */
id: string;
label: string;
prefix?: ReactElement;
isActive?: boolean;
/** Accessible name when the label alone doesn't say what opening does. */
ariaLabel?: string;
}

View File

@@ -71,7 +71,6 @@ function Controls({
{showSizeChanger && (
<Select<Pagination['limit']>
data-testid="controls-page-size"
style={defaultSelectStyle}
loading={isLoading}
value={countPerPage}

View File

@@ -32,10 +32,6 @@
}
}
.ingestion-keys-search-auth-trigger {
width: 100%;
}
.ant-table-row {
.ant-table-cell {
padding: 0;

View File

@@ -26,13 +26,13 @@ import type { NotificationInstance } from 'antd/es/notification/interface';
import type { CollapseProps } from 'antd/lib';
import {
useCreateIngestionKey,
useCreateIngestionLimit,
useCreateIngestionKeyLimit,
useDeleteIngestionKey,
useDeleteIngestionLimit,
useDeleteIngestionKeyLimit,
useGetIngestionKeys,
useSearchIngestionKeys,
useUpdateIngestionKey,
useUpdateIngestionLimit,
useUpdateIngestionKeyLimit,
} from 'api/generated/services/gateway';
import {
GatewaytypesIngestionKeyDTO,
@@ -71,21 +71,6 @@ import {
TriangleAlert,
X,
} from '@signozhq/icons';
import AuthZButton from 'lib/authz/components/AuthZButton/AuthZButton';
import { AuthZGuardContent } from 'lib/authz/components/AuthZGuard/AuthZGuardContent';
import AuthZTooltip from 'lib/authz/components/AuthZTooltip/AuthZTooltip';
import {
buildIngestionKeyAttachPermission,
buildIngestionKeyDeletePermission,
buildIngestionKeyDetachPermission,
buildIngestionKeyUpdatePermission,
buildIngestionLimitDeletePermission,
buildIngestionLimitUpdatePermission,
IngestionKeyCreatePermission,
IngestionKeyListPermission,
IngestionLimitCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/ingestion.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { useAppContext } from 'providers/App/App';
import { useTimezone } from 'providers/Timezone';
import {
@@ -225,13 +210,6 @@ function MultiIngestionSettings(): JSX.Element {
const [totalIngestionKeys, setTotalIngestionKeys] = useState(0);
const { permissions: authzPermissions } = useAuthZ([
IngestionKeyListPermission,
]);
const canListIngestionKeys =
authzPermissions?.[IngestionKeyListPermission].isGranted ?? false;
const [
hasCreateLimitForIngestionKeyError,
setHasCreateLimitForIngestionKeyError,
@@ -336,7 +314,7 @@ function MultiIngestionSettings(): JSX.Element {
},
{
query: {
enabled: !isSearching && canListIngestionKeys,
enabled: !isSearching,
},
},
);
@@ -356,7 +334,7 @@ function MultiIngestionSettings(): JSX.Element {
},
{
query: {
enabled: isSearching && canListIngestionKeys,
enabled: isSearching,
},
},
);
@@ -367,14 +345,7 @@ function MultiIngestionSettings(): JSX.Element {
: ingestionKeysData;
const isLoading = isSearching ? isLoadingSearch : isLoadingGet;
const isRefetching = isSearching ? isRefetchingSearch : isRefetchingGet;
const refetchKeysQuery = isSearching
? refetchSearchAPIKeys
: refetchGetAPIKeys;
const refetchAPIKeys = async (): Promise<void> => {
if (canListIngestionKeys) {
await refetchKeysQuery();
}
};
const refetchAPIKeys = isSearching ? refetchSearchAPIKeys : refetchGetAPIKeys;
const error = isSearching ? searchError : getError;
const isError = isSearching ? isSearchError : isGetError;
@@ -422,15 +393,15 @@ function MultiIngestionSettings(): JSX.Element {
useDeleteIngestionKey<AxiosError<RenderErrorResponseDTO>>();
const { mutate: createLimitForIngestionKey, isLoading: isLoadingLimitForKey } =
useCreateIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
useCreateIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
const {
mutate: updateLimitForIngestionKey,
isLoading: isLoadingUpdatedLimitForKey,
} = useUpdateIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
} = useUpdateIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
const { mutate: deleteLimitForKey, isLoading: isDeletingLimit } =
useDeleteIngestionLimit<AxiosError<RenderErrorResponseDTO>>();
useDeleteIngestionKeyLimit<AxiosError<RenderErrorResponseDTO>>();
const onDeleteHandler = (): void => {
clearSearch();
@@ -667,8 +638,8 @@ function MultiIngestionSettings(): JSX.Element {
createLimitForIngestionKey(
{
pathParams: { keyId: payload.keyID },
data: {
keyId: payload.keyID,
signal: payload.signal,
config: payload.config,
},
@@ -1056,14 +1027,12 @@ function MultiIngestionSettings(): JSX.Element {
icon
color="secondary"
aria-label="Edit ingestion key"
testId={`ingestion-key-edit-btn-${APIKey.id}`}
onClick={onEditKey}
>
<PenLine size={14} />
</Button>
<Button
aria-label="Delete ingestion key"
testId={`ingestion-key-delete-open-btn-${APIKey.id}`}
variant="ghost"
size="sm"
icon
@@ -1191,19 +1160,8 @@ function MultiIngestionSettings(): JSX.Element {
});
};
const isAddingNewLimit = !hasLimits(signalName);
const ingestionLimitPermissions = APIKey?.id
? isAddingNewLimit
? [
IngestionLimitCreatePermission,
buildIngestionKeyAttachPermission(APIKey.id),
]
: [buildIngestionLimitUpdatePermission(limit.id)]
: [];
const onSaveSignalLimit = (): void => {
if (isAddingNewLimit) {
if (!hasLimits(signalName)) {
handleAddLimit(APIKey, signalName);
} else {
handleUpdateLimit(APIKey, limitsDict[signalName]);
@@ -1242,7 +1200,6 @@ function MultiIngestionSettings(): JSX.Element {
icon
color="danger"
aria-label={`Delete ${signalName} limit`}
testId={`ingestion-limit-delete-open-btn-${signalName}`}
disabled={
!!(activeAPIKey?.id === APIKey?.id && activeSignal)
}
@@ -1260,7 +1217,6 @@ function MultiIngestionSettings(): JSX.Element {
prefix={<Plus size={12} />}
disabled={!!(activeAPIKey?.id === APIKey?.id && activeSignal)}
onClick={onAddSignalLimit}
testId={`ingestion-limit-add-btn-${signalName}`}
>
Limits
</Button>
@@ -1492,7 +1448,7 @@ function MultiIngestionSettings(): JSX.Element {
isEditAddLimitOpen && (
<div className="signal-limit-save-discard">
<div className="signal-limit-save-discard-actions">
<AuthZButton
<Button
color="primary"
variant="solid"
size="sm"
@@ -1500,11 +1456,9 @@ function MultiIngestionSettings(): JSX.Element {
isLoadingLimitForKey || isLoadingUpdatedLimitForKey
}
onClick={onSaveSignalLimit}
testId="ingestion-limit-save-btn"
checks={ingestionLimitPermissions}
>
Save
</AuthZButton>
</Button>
<Button
disabledTooltip="Wait for the limit to save"
variant="outlined"
@@ -1827,50 +1781,42 @@ function MultiIngestionSettings(): JSX.Element {
)}
<div className="ingestion-keys-search-add-new">
<AuthZTooltip
triggerClassName="ingestion-keys-search-auth-trigger"
checks={[IngestionKeyListPermission]}
>
<Input
placeholder="Search for ingestion key..."
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
value={searchValue}
onChange={handleSearch}
/>
</AuthZTooltip>
<Input
placeholder="Search for ingestion key..."
prefix={<Search size={12} color={Color.BG_VANILLA_400} />}
value={searchValue}
onChange={handleSearch}
/>
<div className="ingestion-keys-add-new">
<AuthZButton
<Button
size="md"
color="primary"
variant="solid"
prefix={<Plus size={14} />}
onClick={showAddModal}
testId="ingestion-key-add-btn"
checks={[IngestionKeyCreatePermission]}
>
New Ingestion key
</AuthZButton>
</Button>
</div>
</div>
<AuthZGuardContent checks={[IngestionKeyListPermission]}>
<Table
columns={columns}
dataSource={dataSource}
loading={isLoading || isRefetching}
showHeader={false}
onChange={handleTableChange}
pagination={{
pageSize: isSearching ? SEARCH_PAGE_SIZE : paginationParams?.per_page,
hideOnSinglePage: true,
showTotal: (total: number, range: number[]): string =>
`${range[0]}-${range[1]} of ${total} Ingestion keys`,
total: totalIngestionKeys,
}}
className="ingestion-keys-table"
/>
</AuthZGuardContent>
<Table
columns={columns}
dataSource={dataSource}
loading={isLoading || isRefetching}
showHeader={false}
onChange={handleTableChange}
pagination={{
pageSize: isSearching ? SEARCH_PAGE_SIZE : paginationParams?.per_page,
hideOnSinglePage: true,
showTotal: (total: number, range: number[]): string =>
`${range[0]}-${range[1]} of ${total} Ingestion keys`,
total: totalIngestionKeys,
}}
className="ingestion-keys-table"
/>
</div>
{/* Delete Key Modal */}
@@ -1893,7 +1839,7 @@ function MultiIngestionSettings(): JSX.Element {
>
Cancel
</Button>,
<AuthZButton
<Button
size="md"
key="submit"
variant="solid"
@@ -1901,15 +1847,9 @@ function MultiIngestionSettings(): JSX.Element {
prefix={<Trash2 size={16} />}
loading={isDeleteingAPIKey}
onClick={onDeleteHandler}
testId="ingestion-key-delete-btn"
checks={
isDeleteModalOpen && activeAPIKey?.id
? [buildIngestionKeyDeletePermission(activeAPIKey.id)]
: []
}
>
Delete Ingestion Key
</AuthZButton>,
</Button>,
]}
>
<Typography
@@ -1946,7 +1886,7 @@ function MultiIngestionSettings(): JSX.Element {
>
Cancel
</Button>,
<AuthZButton
<Button
size="md"
key="submit"
variant="solid"
@@ -1954,18 +1894,9 @@ function MultiIngestionSettings(): JSX.Element {
prefix={<Trash2 size={16} />}
loading={isDeletingLimit}
onClick={onDeleteLimitHandler}
testId="ingestion-limit-delete-btn"
checks={
isDeleteLimitModalOpen && activeSignal?.id && activeAPIKey?.id
? [
buildIngestionLimitDeletePermission(activeSignal.id),
buildIngestionKeyDetachPermission(activeAPIKey.id),
]
: []
}
>
Delete Limit
</AuthZButton>,
</Button>,
]}
>
<Typography
@@ -2005,7 +1936,7 @@ function MultiIngestionSettings(): JSX.Element {
>
Cancel
</Button>,
<AuthZButton
<Button
size="md"
color="primary"
key="submit"
@@ -2013,15 +1944,9 @@ function MultiIngestionSettings(): JSX.Element {
prefix={<Check size={14} />}
loading={isLoadingUpdateAPIKey}
onClick={onUpdateApiKey}
testId="ingestion-key-update-btn"
checks={
isEditModalOpen && activeAPIKey?.id
? [buildIngestionKeyUpdatePermission(activeAPIKey.id)]
: []
}
>
Update Ingestion Key
</AuthZButton>,
</Button>,
]}
>
<Form

View File

@@ -1,376 +0,0 @@
import dayjs from 'dayjs';
import type {
AuthtypesTransactionDTO,
GatewaytypesIngestionKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
buildIngestionKeyAttachPermission,
buildIngestionKeyDeletePermission,
buildIngestionKeyDetachPermission,
buildIngestionKeyUpdatePermission,
buildIngestionLimitDeletePermission,
buildIngestionLimitUpdatePermission,
IngestionKeyCreatePermission,
IngestionKeyListPermission,
IngestionLimitCreatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/ingestion.permissions';
import { gettableTransactionToPermission } from 'lib/authz/hooks/useAuthZ/utils';
import {
AUTHZ_CHECK_URL,
setupAuthzAdmin,
setupAuthzDeny,
} from 'lib/authz/utils/authz-test-utils';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import MultiIngestionSettings from '../MultiIngestionSettings';
jest.setTimeout(15_000);
const ROUTE = '/ingestion-settings';
const DATE = '2024-01-01T00:00:00Z';
const EXPIRES_AT = '2030-01-01T00:00:00Z';
const DENIED_TEXT = /is not authorized to perform/i;
const makeKey = (
id: string,
name: string,
limits: GatewaytypesIngestionKeyDTO['limits'] = [],
): GatewaytypesIngestionKeyDTO => ({
id,
name,
value: 'secret',
workspace_id: 'w1',
expires_at: EXPIRES_AT,
created_at: DATE,
updated_at: DATE,
tags: [],
limits,
});
const KEY_ONE = makeKey('k1', 'Key One', [
{ id: 'l1', signal: 'logs', config: { day: { size: 1073741824 } } },
]);
const KEY_TWO = makeKey('k2', 'Key Two');
const KEY_THREE = makeKey('k3', 'Key Three');
function mockKeys(keys: GatewaytypesIngestionKeyDTO[]): jest.Mock {
const onList = jest.fn();
server.use(
rest.get('*/api/v1/global/config*', (_req, res, ctx) =>
res(
ctx.status(200),
ctx.json({
status: 'success',
data: {
external_url: '',
ingestion_url: 'http://ingest.example.com',
ai_assistant_url: null,
mcp_url: null,
},
}),
),
),
rest.get('*/api/v2/gateway/ingestion_keys*', (_req, res, ctx) => {
onList();
return res(
ctx.status(200),
ctx.json({
status: 'success',
data: {
keys,
_pagination: {
page: 1,
per_page: 10,
pages: 1,
total: keys.length,
},
},
}),
);
}),
);
return onList;
}
function recordAuthzChecks(): Set<string> {
const seen = new Set<string>();
server.use(
rest.post(AUTHZ_CHECK_URL, async (req) => {
const payload = (await req.json()) as AuthtypesTransactionDTO[];
payload.forEach((txn) => seen.add(gettableTransactionToPermission(txn)));
return undefined;
}),
);
return seen;
}
async function expandKey(
user: ReturnType<typeof userEvent.setup>,
name: string,
): Promise<void> {
await user.click(
await screen.findByRole('button', { name: new RegExp(`right ${name}`, 'i') }),
);
await screen.findByText('LIMITS');
}
async function settledButton(testId: string): Promise<HTMLElement> {
const button = await screen.findByTestId(testId);
await waitFor(() => {
expect(button).not.toHaveAttribute('aria-busy');
});
return button;
}
function renderPage(): ReturnType<typeof userEvent.setup> {
render(<MultiIngestionSettings />, undefined, { initialRoute: ROUTE });
return userEvent.setup({ pointerEventsCheck: 0 });
}
describe('MultiIngestionSettings authz', () => {
afterEach(async () => {
await new Promise((resolve) => {
setTimeout(resolve, 100);
});
server.resetHandlers();
});
describe('ingestion-key:list', () => {
it('hides the list, disables search and fires no list request when denied', async () => {
const onList = mockKeys([KEY_ONE]);
server.use(setupAuthzDeny(IngestionKeyListPermission));
renderPage();
await screen.findByText(DENIED_TEXT);
expect(
screen.getByPlaceholderText('Search for ingestion key...'),
).toBeDisabled();
expect(screen.queryByText('Key One')).not.toBeInTheDocument();
expect(onList).not.toHaveBeenCalled();
});
it('shows the list and requests it when granted', async () => {
const onList = mockKeys([KEY_ONE]);
server.use(setupAuthzAdmin());
renderPage();
await screen.findByText('Key One');
expect(onList).toHaveBeenCalled();
expect(screen.queryByText(DENIED_TEXT)).not.toBeInTheDocument();
});
});
describe('ingestion-key:create', () => {
it('disables "New Ingestion key" when denied', async () => {
mockKeys([KEY_ONE]);
server.use(setupAuthzDeny(IngestionKeyCreatePermission));
renderPage();
await expect(
settledButton('ingestion-key-add-btn'),
).resolves.toHaveAttribute('aria-disabled', 'true');
});
it('enables "New Ingestion key" and opens the modal when granted', async () => {
mockKeys([KEY_ONE]);
server.use(setupAuthzAdmin());
const user = renderPage();
await expect(
settledButton('ingestion-key-add-btn'),
).resolves.not.toHaveAttribute('aria-disabled', 'true');
await user.click(screen.getByTestId('ingestion-key-add-btn'));
await screen.findByTestId('create-new-key');
});
});
describe('creating a key without list access', () => {
it('sends no list request after the key is created', async () => {
const onList = mockKeys([KEY_ONE]);
const onCreate = jest.fn();
server.use(
setupAuthzDeny(IngestionKeyListPermission),
rest.post('*/api/v2/gateway/ingestion_keys', (_req, res, ctx) => {
onCreate();
return res(
ctx.status(200),
ctx.json({ status: 'success', data: { id: 'k9', value: 'v' } }),
);
}),
);
const user = renderPage();
await expect(
settledButton('ingestion-key-add-btn'),
).resolves.not.toHaveAttribute('aria-disabled', 'true');
await user.click(screen.getByTestId('ingestion-key-add-btn'));
await user.type(await screen.findByLabelText('Name'), 'new-key');
await user.click(screen.getByLabelText('Expiration'));
await user.click(
await screen.findByTitle(dayjs().add(1, 'day').format('YYYY-MM-DD')),
);
await user.click(screen.getByTestId('create-new-key'));
await waitFor(() => expect(onCreate).toHaveBeenCalledTimes(1));
await screen.findByText(DENIED_TEXT);
expect(onList).not.toHaveBeenCalled();
});
});
describe('ingestion-key:update', () => {
it('disables "Update Ingestion Key" for the denied key', async () => {
mockKeys([KEY_ONE, KEY_TWO]);
server.use(setupAuthzDeny(buildIngestionKeyUpdatePermission('k1')));
const user = renderPage();
await user.click(await screen.findByTestId('ingestion-key-edit-btn-k1'));
await expect(
settledButton('ingestion-key-update-btn'),
).resolves.toHaveAttribute('aria-disabled', 'true');
});
it('keeps "Update Ingestion Key" enabled for another key', async () => {
mockKeys([KEY_ONE, KEY_TWO]);
server.use(setupAuthzDeny(buildIngestionKeyUpdatePermission('k1')));
const user = renderPage();
await user.click(await screen.findByTestId('ingestion-key-edit-btn-k2'));
await expect(
settledButton('ingestion-key-update-btn'),
).resolves.not.toHaveAttribute('aria-disabled', 'true');
});
});
describe('ingestion-key:delete', () => {
it('disables "Delete Ingestion Key" when denied for that key', async () => {
mockKeys([KEY_ONE]);
server.use(setupAuthzDeny(buildIngestionKeyDeletePermission('k1')));
const user = renderPage();
await user.click(
await screen.findByTestId('ingestion-key-delete-open-btn-k1'),
);
await expect(
settledButton('ingestion-key-delete-btn'),
).resolves.toHaveAttribute('aria-disabled', 'true');
});
});
describe('saving a new limit', () => {
it('disables "Save" when attach is denied on the key', async () => {
mockKeys([KEY_TWO]);
server.use(setupAuthzDeny(buildIngestionKeyAttachPermission('k2')));
const user = renderPage();
await expandKey(user, 'Key Two');
await user.click(screen.getByTestId('ingestion-limit-add-btn-logs'));
await expect(
settledButton('ingestion-limit-save-btn'),
).resolves.toHaveAttribute('aria-disabled', 'true');
});
it('disables "Save" when ingestion-limit:create is denied', async () => {
mockKeys([KEY_TWO]);
server.use(setupAuthzDeny(IngestionLimitCreatePermission));
const user = renderPage();
await expandKey(user, 'Key Two');
await user.click(screen.getByTestId('ingestion-limit-add-btn-logs'));
await expect(
settledButton('ingestion-limit-save-btn'),
).resolves.toHaveAttribute('aria-disabled', 'true');
});
});
describe('saving an existing limit', () => {
it('disables "Save" when update is denied on that limit', async () => {
mockKeys([KEY_ONE]);
server.use(setupAuthzDeny(buildIngestionLimitUpdatePermission('l1')));
const user = renderPage();
await expandKey(user, 'Key One');
await user.click(screen.getByTestId('edit-limit-btn-logs'));
await expect(
settledButton('ingestion-limit-save-btn'),
).resolves.toHaveAttribute('aria-disabled', 'true');
});
it('keeps "Save" enabled when only create and attach are denied', async () => {
mockKeys([KEY_ONE]);
server.use(
setupAuthzDeny(
IngestionLimitCreatePermission,
buildIngestionKeyAttachPermission('k1'),
),
);
const user = renderPage();
await expandKey(user, 'Key One');
await user.click(screen.getByTestId('edit-limit-btn-logs'));
await expect(
settledButton('ingestion-limit-save-btn'),
).resolves.not.toHaveAttribute('aria-disabled', 'true');
});
});
describe('deleting a limit', () => {
it.each([
['ingestion-limit:delete', buildIngestionLimitDeletePermission('l1')],
['ingestion-key:detach', buildIngestionKeyDetachPermission('k1')],
])('disables "Delete Limit" when %s is denied', async (_name, denied) => {
mockKeys([KEY_ONE]);
server.use(setupAuthzDeny(denied));
const user = renderPage();
await expandKey(user, 'Key One');
await user.click(screen.getByTestId('ingestion-limit-delete-open-btn-logs'));
await expect(
settledButton('ingestion-limit-delete-btn'),
).resolves.toHaveAttribute('aria-disabled', 'true');
});
});
describe('id checks', () => {
it('only checks list and create on load, and per-id checks once a modal opens', async () => {
mockKeys([KEY_ONE, KEY_TWO, KEY_THREE]);
server.use(setupAuthzAdmin());
const seen = recordAuthzChecks();
const user = renderPage();
await screen.findByText('Key Three');
await expect(
settledButton('ingestion-key-add-btn'),
).resolves.not.toHaveAttribute('aria-disabled', 'true');
expect([...seen].sort()).toStrictEqual(
[IngestionKeyListPermission, IngestionKeyCreatePermission].sort(),
);
await user.click(screen.getByTestId('ingestion-key-edit-btn-k1'));
await expect(
settledButton('ingestion-key-update-btn'),
).resolves.not.toHaveAttribute('aria-disabled', 'true');
expect(seen.has(buildIngestionKeyUpdatePermission('k1'))).toBe(true);
expect(seen.has(buildIngestionKeyUpdatePermission('k2'))).toBe(false);
expect(seen.has(buildIngestionKeyUpdatePermission('k3'))).toBe(false);
});
});
});

View File

@@ -1,6 +1,5 @@
import { GatewaytypesGettableIngestionKeysDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
import { rest, server } from 'mocks-server/server';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
@@ -40,7 +39,6 @@ const GLOBAL_CONFIG_RESPONSE = {
describe('MultiIngestionSettings Page', () => {
beforeEach(() => {
mockNavigate.mockClear();
server.use(setupAuthzAdmin());
});
afterEach(() => {
@@ -352,7 +350,7 @@ describe('MultiIngestionSettings Page', () => {
initialRoute: INGESTION_SETTINGS_ROUTE,
});
await screen.findByText('Key Regular', undefined, { timeout: 5000 });
await screen.findByText('Key Regular');
expect(getHandler).toHaveBeenCalled();
expect(searchHandler).not.toHaveBeenCalled();

View File

@@ -2,7 +2,8 @@ import { Dispatch, SetStateAction, useEffect, useMemo, useState } from 'react';
import { useAppNavigate } from 'lib/router/useAppNavigate';
import { Color } from '@signozhq/design-tokens';
import { Button } from '@signozhq/ui/button';
import { Select, SelectProps, Skeleton } from 'antd';
import { Select, Skeleton } from 'antd';
import { SelectProps } from 'antd/lib';
import logEvent from 'api/common/logEvent';
import { useListAccounts } from 'api/generated/services/cloudintegration';
import cx from 'classnames';

View File

@@ -1,6 +1,6 @@
import { useState } from 'react';
import { Button } from '@signozhq/ui/button';
import { Modal } from 'antd';
import { Modal } from 'antd/lib';
import logEvent from 'api/common/logEvent';
import { useDisconnectAccount } from 'api/generated/services/cloudintegration';
import { CloudintegrationtypesGCPConnectionMethodDTO } from 'api/generated/services/sigNoz.schemas';

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react';
import { useEffect, useState } from 'react';
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
import MultiSelectFilter, {
type MultiSelectFilterOption,
@@ -25,27 +25,25 @@ function RuleStatesFilter({
onChange,
}: RuleStatesFilterProps): JSX.Element {
const [draft, setDraft] = useState(states);
const [open, setOpen] = useState(false);
useEffect(() => {
setDraft(states);
}, [states]);
const handleCommit = useCallback(
(next: string[]): void => {
setDraft(next);
const handleChange = (next: string[]): void => {
setDraft(next);
if (!open) {
onChange(next);
},
[onChange],
);
}
};
const handleDropdownVisibleChange = useCallback(
(isOpen: boolean): void => {
if (!isOpen && !isSameStates(draft, states)) {
onChange(draft);
}
},
[draft, states, onChange],
);
const handleDropdownVisibleChange = (nextOpen: boolean): void => {
setOpen(nextOpen);
if (!nextOpen && !isSameStates(draft, states)) {
onChange(draft);
}
};
return (
<MultiSelectFilter
@@ -53,8 +51,7 @@ function RuleStatesFilter({
options={STATE_OPTIONS}
placeholder="Status"
testId="alert-rules-filter-states"
onChange={setDraft}
onCommit={handleCommit}
onChange={handleChange}
onDropdownVisibleChange={handleDropdownVisibleChange}
/>
);

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