Compare commits

..

6 Commits

Author SHA1 Message Date
Gaurav Tewari
35b2605435 test(e2e): reject wrong methods and paths in the noz fake 2026-11-24 00:24:50 +05:30
Gaurav Tewari
4e8971ec85 test(e2e): import frontend types through an @frontend alias 2026-11-24 00:24:50 +05:30
Gaurav Tewari
7e3cfce33b test(e2e): cover noz chat flows 2026-11-24 00:24:50 +05:30
Gaurav Tewari
0bda515783 test(e2e): add the noz driver and a fake AI service
Noz is enabled per test by patching ai_assistant_url on the global config,

so the shared stack keeps it off.
2026-11-24 00:24:50 +05:30
Gaurav Tewari
1e8e832918 test(ai-assistant): add testids to the conversation view and history rows 2026-11-24 00:24:50 +05:30
Gaurav Tewari
9fd35b5110 refactor(ai-assistant): move the SSE event union to a types-only file
e2e imports it; chat.ts pulls in frontend-only modules e2e can't resolve.
2026-11-24 00:24:50 +05:30
26 changed files with 909 additions and 261 deletions

View File

@@ -9,14 +9,12 @@ paths:
Examples and the harness API live in [`frontend/src/tests/README.md`](../../frontend/src/tests/README.md).
- **Import from the harness.** `render`, `screen`, `userEvent`, `waitFor` and the rest come from `tests/test-utils`, never from `@testing-library/react`. The harness mounts the router, React Query, Redux, app context and preferences. When it can't do what a test needs, extend `tests/test-utils` instead of importing around it.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query. Never call a `*ByRole` query inside `waitFor` or a loop: `waitFor` re-runs its callback every 50 ms. Wait with `findByTestId`, then query.
- **Interact like a user.** `const user = userEvent.setup()`, then an awaited `user.click`, `hover`, `keyboard` or `type`. The harness turns off the pointer-events check, which walks `getComputedStyle` up the tree on every action; never turn it back on. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Find elements by test ID.** Query with `getByTestId`/`findByTestId` on the `data-testid` or `testId` the component exposes, and add one to the component when it has none. Fall back to role or text only for markup the app doesn't own. A test ID matches exactly one element and survives copy and markup changes; `getByRole` computes the accessibility tree on every call and is the slowest query.
- **Interact like a user.** `const user = userEvent.setup({ pointerEventsCheck: 0 })`, then an awaited `user.click`, `hover`, `keyboard` or `type`. `fireEvent` only for events `userEvent` has no equivalent for: scroll, resize, setting `scrollTop`.
- **Fake timers per test only**, for debounce or throttle, with `userEvent.setup({ advanceTimers: (ms) => jest.advanceTimersByTime(ms) })`. Never global.
- **Network through MSW.** The global server runs for every test; override per test with `server.use(...)` from `mocks-server/server`. Large fixtures go in `mocks-server/__mockdata__`.
- **Router through the harness.** Pass `initialRoute`/`routePath` to `render` and assert with `getCurrentLocation()` from `lib/router/navigation`. Never mock `react-router`, `react-router-dom` or `lib/history`; when a test can't render at a route, use the `lib/router` spies in `tests/router-mocks`.
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides (`@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`) or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Mock only business boundaries.** Local `jest.mock` for API modules, custom hooks and domain components. Never re-mock what the harness provides or what `jest.config.ts` maps (`uplot`, `@signozhq/icons`, `useSafeNavigate`, `logEvent`).
- **Type mocks and fixtures.** `jest.mocked(fn)` for module mocks, `jest.fn() as jest.MockedFunction<T>` for a standalone mock you configure or assert on. Fixtures carry their real type, from `src/api/generated` where it exists. No `any`, no `as unknown as`. An inline `onX={jest.fn()}` on a typed prop that is never asserted needs no annotation.
- **One behaviour per test, at the smallest render.** Render the component that owns the behaviour, not the page around it, unless the page wiring is the behaviour. A flow of steps (a wizard, a multi-step form) becomes one test per step that starts at that step through props, store or route. A full click-through belongs in the e2e suite (`tests/e2e`).
- **Each test under 500 ms.** `pnpm jest <file> --verbose` prints each test's time. CI runs about four times slower than a laptop, and the timeout is 5 s. Never raise a timeout (`jest.setTimeout`, a third argument to `it`) to make a slow test pass; slim the test instead.
- **A test fails without its change.** At the gate in [`frontend/AGENTS.md`](../../frontend/AGENTS.md), revert the change, or break the line under test, and run the test: it must fail, and each test must stay under 500 ms. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **A test fails without its change.** Revert the change, or break the line under test, and run the test before you finish: it must fail. Assert the specific outcome (exact text, request payload, call arguments), never only that an element exists.
- **No limit on tests per file.** Split a file when it mixes unrelated behaviour, not to hit a count.

View File

@@ -99,7 +99,7 @@ is still by hand. The generator never adds a SideNav item; do that in
CSS Modules (`docs/css-modules-guide.md`), React Query for server state (prefer
`api/generated` hooks), nuqs for URL state, Zustand for client state, `data-testid` on
every interactive element.
5. **Verify** at the gate in `AGENTS.md` (commit, push or PR), not after each edit; skip it while the user says `no checks`:
5. **Verify** before reporting done:
```bash
pnpm tsgo --noEmit
pnpm oxlint src/pages/<Feature>

View File

@@ -34,18 +34,14 @@ You are operating within a constrained context window and strict system prompts.
- Identity keys (legend groups, color groups, CSV headers, React keys) come from structured values, never from joined display text: `['us, east', 'prod']` and `['us', 'east, prod']` both join to `us, east, prod`.
- A payload saved under another kind or schema copies only the fields that schema accepts, and drops bindings to columns the user removed. The server rejects unknown or stale fields, so the preview works and the save fails.
3. CHECKS AT THE GATE: Your internal tools mark file writes as successful even if the code does not compile, so the checks below are required, but only at the gate. The gate is when the user says commit, push, raise or update the PR, mark it ready, or "run checks". Never run them after each edit or between the user's iterations.
- Between gates, after an edit, run at most the one test file that covers it.
- `no checks`: when the user says it (or "don't run tests", "just making changes"), run nothing: no tests, type check, lint, format or build. Make the change and stop. This holds until the user names a gate.
At the gate, you are FORBIDDEN from reporting a task as complete until you have:
3. FORCED VERIFICATION: Your internal tools mark file writes as successful even if the code does not compile. Run these checks once all changes of a task are done, never after each edit. You are FORBIDDEN from reporting a task as complete until you have:
- Run `pnpm tsgo --noEmit`
- Run `pnpm lint:js --quiet` to find critical errors
- Run `pnpm oxlint <file1> <file2>` and fix all warnings
- Run `pnpm build`
- Find if the file has tests for it, or if there's `__test__` folder or the parent folder has tests, and run. Run them before coding the change or after all changes, never in between.
- For e2e, run only the specs you added or changed: the stack is heavy. Leave the full jest and e2e suites to CI unless the user asks.
- For every test you added or changed, revert the change it covers and confirm the test fails, and that each test runs under 500 ms (`pnpm jest <file> --verbose`)
- For every test you added or changed, revert the change it covers and confirm the test fails
- On a stacked branch (`gh stack`), run `pnpm tsgo --noEmit` on every branch above it before pushing: a renamed prop or moved export breaks them
- Fixed ALL resulting errors

View File

@@ -6,8 +6,6 @@ const LOG_EVENT_MOCK_PATH = '<rootDir>/src/__tests__/logEventMock.ts';
const config: Config.InitialOptions = {
silent: true,
// CI runners are slow enough that multi-step userEvent tests pass 5s.
testTimeout: 10000,
clearMocks: true,
coverageDirectory: 'coverage',
coverageReporters: ['text', 'cobertura', 'html', 'json-summary'],
@@ -69,8 +67,6 @@ const config: Config.InitialOptions = {
testPathIgnorePatterns: ['/node_modules/', '/public/'],
moduleDirectories: ['node_modules', 'src'],
testEnvironment: '<rootDir>/jest.environment.cjs',
// Local only: the default (cores - 1) workers exhaust RAM when several runs overlap.
...(process.env.CI ? {} : { maxWorkers: 4, workerIdleMemoryLimit: '1GB' }),
coverageThreshold: {
global: {
statements: 80,

View File

@@ -146,39 +146,6 @@ window.getComputedStyle = function (
}
};
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs up to ~1 s per open.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
jest.mock('@testing-library/user-event', () =>
jest.requireActual('tests/userEventWithDefaults'),
);
// antd popups walk getComputedStyle up every ancestor to find scroll
// containers on each open. pnpm keeps the package under antd, not at the root.
jest.mock(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
() => ({
...jest.requireActual(
require.resolve('@rc-component/trigger/lib/util', {
paths: [require.resolve('antd')],
}),
),
collectScroller: (): HTMLElement[] => [],
}),
);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());

View File

@@ -30,16 +30,11 @@ import rotateSession from 'api/v2/sessions/rotate/post';
import afterLogin from 'AppRoutes/utils';
import type {
ActionResultResponseDTO,
ApprovalEventDTO,
ApproveResponseDTO,
CancelResponseDTO,
ClarificationEventDTO,
ClarifyResponseDTO,
ConversationEventDTO,
CreateMessageResponseDTO,
CreateThreadResponseDTO,
DoneEventDTO,
ErrorEventDTO,
ExecutionStateDTO,
FeedbackRatingDTO,
ListThreadsApiV1AssistantThreadsGetArchived,
@@ -47,19 +42,14 @@ import type {
MessageContextDTO,
MessageContextDTOSource,
MessageContextDTOType,
MessageEventDTO,
MessageSummaryDTO,
RegenerateResponseDTO,
StatusEventDTO,
ThinkingEventDTO,
ThreadDetailResponseDTO,
ThreadListResponseDTO,
ThreadSummaryDTO,
ChipDTO,
ChipsResponseDTO,
PageTypeDTO,
ToolCallEventDTO,
ToolResultEventDTO,
} from '@signozhq/noz-client';
import { LOCALSTORAGE } from 'constants/localStorage';
@@ -70,6 +60,10 @@ import {
} from '../AIAPIInstance';
import { getSigNozInstanceUrl } from 'utils/signozInstanceUrl';
import type { SSEEvent } from './sseEvent';
export type { SSEEvent };
// ---------------------------------------------------------------------------
// SSE-only auth wrapper.
//
@@ -183,26 +177,6 @@ async function fetchSSEWithAuth(
return res;
}
// ---------------------------------------------------------------------------
// SSE event types
//
// The generated event DTOs each declare `type?: string` (loose). The UI needs
// a discriminated union, so we intersect each variant with a string-literal
// `type` to enable narrowing via `event.type === 'status'`.
// ---------------------------------------------------------------------------
export type SSEEvent =
| (StatusEventDTO & { type: 'status' })
| (MessageEventDTO & { type: 'message' })
| (ThinkingEventDTO & { type: 'thinking' })
| (ToolCallEventDTO & { type: 'tool_call' })
| (ToolResultEventDTO & { type: 'tool_result' })
| (ApprovalEventDTO & { type: 'approval' })
| (ClarificationEventDTO & { type: 'clarification' })
| (ErrorEventDTO & { type: 'error' })
| (ConversationEventDTO & { type: 'conversation' })
| (DoneEventDTO & { type: 'done' });
/** String-literal view of `ExecutionStateDTO` for ergonomic comparisons. */
export type ExecutionState = `${ExecutionStateDTO}`;

View File

@@ -0,0 +1,32 @@
import type {
ApprovalEventDTO,
ClarificationEventDTO,
ConversationEventDTO,
DoneEventDTO,
ErrorEventDTO,
MessageEventDTO,
StatusEventDTO,
ThinkingEventDTO,
ToolCallEventDTO,
ToolResultEventDTO,
} from '@signozhq/noz-client';
// ---------------------------------------------------------------------------
// SSE event types
//
// The generated event DTOs each declare `type?: string` (loose). The UI needs
// a discriminated union, so we intersect each variant with a string-literal
// `type` to enable narrowing via `event.type === 'status'`.
// ---------------------------------------------------------------------------
export type SSEEvent =
| (StatusEventDTO & { type: 'status' })
| (MessageEventDTO & { type: 'message' })
| (ThinkingEventDTO & { type: 'thinking' })
| (ToolCallEventDTO & { type: 'tool_call' })
| (ToolResultEventDTO & { type: 'tool_result' })
| (ApprovalEventDTO & { type: 'approval' })
| (ClarificationEventDTO & { type: 'clarification' })
| (ErrorEventDTO & { type: 'error' })
| (ConversationEventDTO & { type: 'conversation' })
| (DoneEventDTO & { type: 'done' });

View File

@@ -194,7 +194,7 @@ export default function ConversationView({
}
return (
<div className={conversationClass}>
<div className={conversationClass} data-testid="conversation-view">
<VirtualizedMessages
key={conversationId}
conversationId={conversationId}

View File

@@ -167,6 +167,7 @@ export default function ConversationItem({
return (
<div
className={itemClass}
data-testid={`ai-conversation-item-${conversation.id}`}
onClick={(): void => onSelect(conversation.id)}
role="button"
tabIndex={0}

View File

@@ -83,7 +83,6 @@ import { MeterAggregateOperator } from 'types/common/queryBuilder';
import { USER_ROLES } from 'types/roles';
import { getDaysUntilExpiry } from 'utils/timeUtils';
import 'components/LearnMore/LearnMore.styles.scss';
import './IngestionSettings.styles.scss';
const { Option } = Select;

View File

@@ -30,6 +30,10 @@ jest.mock('@signozhq/ui/toast', () => ({
},
}));
jest.mock('@floating-ui/dom', () =>
jest.requireActual('./floatingUiDomMock').floatingUiDomMock(),
);
type AccountSettingsDrawerProps = ComponentProps<typeof AccountSettingsDrawer>;
const onClose = jest.fn() as jest.MockedFunction<

View File

@@ -18,6 +18,19 @@ import {
import { renderListAlertRules, runSearchQuery } from './_helpers';
// jsdom has no layout, and Floating UI's getComputedStyle walk over every
// popover ancestor costs ~1 s per open here, enough to time out under load.
jest.mock('@floating-ui/dom', () => ({
...jest.requireActual('@floating-ui/dom'),
autoUpdate: (): (() => void) => (): void => {},
computePosition: (
_reference: unknown,
_floating: unknown,
{ placement = 'bottom', strategy = 'absolute' } = {},
): Promise<unknown> =>
Promise.resolve({ x: 0, y: 0, placement, strategy, middlewareData: {} }),
}));
jest.setTimeout(15_000);
const VIEW_1_ORDER_BY = JSON.stringify({ columnName: 'name', order: 'asc' });

View File

@@ -1,16 +1,14 @@
import Loadable from 'components/Loadable';
import { TabRoutes } from 'components/RouteTab/types';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import AlertHistory from 'container/AlertHistory';
import { AlertDetailsTab } from 'container/AlertHistory/types';
import useUrlQuery from 'hooks/useUrlQuery';
import { buildRoutePath } from 'lib/router/buildRoutePath';
import { History, Table } from '@signozhq/icons';
import EditRules from 'pages/EditRules';
import BetaTag from 'periscope/components/BetaTag/BetaTag';
const EditRules = Loadable(() => import('pages/EditRules'));
const AlertHistory = Loadable(() => import('container/AlertHistory'));
export const useRouteTabUtils = (): { routes: TabRoutes[] } => {
const urlQuery = useUrlQuery();

View File

@@ -1,35 +0,0 @@
import ROUTES from 'constants/routes';
import { render, screen } from 'tests/test-utils';
import { USER_ROLES } from 'types/roles';
const mockBillingModuleLoaded = jest.fn();
jest.mock('pages/MembersSettings', () => ({
__esModule: true,
default: (): JSX.Element => <div data-testid="members-settings-tab" />,
}));
jest.mock('container/BillingContainer/BillingContainer', () => {
mockBillingModuleLoaded();
return {
__esModule: true,
default: (): JSX.Element => <div data-testid="billing-settings-tab" />,
};
});
describe('SettingsPage tabs', () => {
it('loads only the tab of the current route', async () => {
const { default: SettingsPage } = await import('pages/Settings/Settings');
render(<SettingsPage />, undefined, {
role: USER_ROLES.ADMIN,
initialRoute: ROUTES.MEMBERS_SETTINGS,
});
await expect(
screen.findByTestId('members-settings-tab'),
).resolves.toBeInTheDocument();
expect(screen.queryByTestId('billing-settings-tab')).not.toBeInTheDocument();
expect(mockBillingModuleLoaded).not.toHaveBeenCalled();
});
});

View File

@@ -1,7 +1,16 @@
import { lazy } from 'react';
import Loadable from 'components/Loadable';
import { RouteTabProps } from 'components/RouteTab/types';
import ROUTES from 'constants/routes';
import BillingContainer from 'container/BillingContainer/BillingContainer';
import GeneralSettings from 'container/GeneralSettings';
import GeneralSettingsCloud from 'container/GeneralSettingsCloud';
import IngestionSettings from 'container/IngestionSettings/IngestionSettings';
import MultiIngestionSettings from 'container/IngestionSettings/MultiIngestionSettings';
import MCPServerSettings from 'container/MCPServerSettings/MCPServerSettings';
import MySettings from 'container/MySettings';
import OrganizationSettings from 'container/OrganizationSettings';
import RolesSettings from 'container/RolesSettings';
import CreateEditRolePage from 'container/RolesSettings/CreateEditRolePage';
import ViewRolePage from 'container/RolesSettings/ViewRolePage';
import { TFunction } from 'i18next';
import {
Backpack,
@@ -15,41 +24,9 @@ import {
User,
Users,
} from '@signozhq/icons';
import { lazyRetry } from 'utils/lazyWithRetries';
const BillingContainer = Loadable(
() => import('container/BillingContainer/BillingContainer'),
);
const GeneralSettings = Loadable(() => import('container/GeneralSettings'));
const GeneralSettingsCloud = Loadable(
() => import('container/GeneralSettingsCloud'),
);
const IngestionSettings = Loadable(
() => import('container/IngestionSettings/IngestionSettings'),
);
const MultiIngestionSettings = Loadable(
() => import('container/IngestionSettings/MultiIngestionSettings'),
);
const MCPServerSettings = Loadable(
() => import('container/MCPServerSettings/MCPServerSettings'),
);
const MySettings = Loadable(() => import('container/MySettings'));
const OrganizationSettings = Loadable(
() => import('container/OrganizationSettings'),
);
const RolesSettings = Loadable(() => import('container/RolesSettings'));
// Loadable's prop type rejects the authz HOC's ComponentType<object>.
const CreateEditRolePage = lazy(() =>
lazyRetry(() => import('container/RolesSettings/CreateEditRolePage')),
);
const ViewRolePage = Loadable(
() => import('container/RolesSettings/ViewRolePage'),
);
const MembersSettings = Loadable(() => import('pages/MembersSettings'));
const ServiceAccountsSettings = Loadable(
() => import('pages/ServiceAccountsSettings'),
);
const Shortcuts = Loadable(() => import('pages/Shortcuts'));
import MembersSettings from 'pages/MembersSettings';
import ServiceAccountsSettings from 'pages/ServiceAccountsSettings';
import Shortcuts from 'pages/Shortcuts';
export const organizationSettings = (t: TFunction): RouteTabProps['routes'] => [
{

View File

@@ -20,7 +20,7 @@ import MyComponent from '../MyComponent';
describe('MyComponent', () => {
it('renders and interacts', async () => {
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get('*/api/v1/example', (_req, res, ctx) => res(ctx.status(200), ctx.json({ value: 42 })))
@@ -40,8 +40,6 @@ The full list is [`.claude/rules/frontend-tests.md`](../../../.claude/rules/fron
- Import from `tests/test-utils` only.
- Prefer `userEvent` for real interactions; use `fireEvent` only for low-level events (scroll/resize/setting `scrollTop`).
- One behaviour per test, rendering the smallest component that owns it; each test under 500 ms (`pnpm jest <file> --verbose`).
- Never call `*ByRole` inside `waitFor`; never raise a timeout to make a slow test pass.
- Use MSW to mock network calls; large JSON goes in `mocks-server/__mockdata__`.
- Keep tests type-safe (`jest.MockedFunction<T>`, avoid `any`).
- Find elements by test ID (`getByTestId`, `findByTestId`); role or text only for markup the app doesn't own.
@@ -50,7 +48,6 @@ The full list is [`.claude/rules/frontend-tests.md`](../../../.claude/rules/fron
Repo-specific reasons:
- The harness wires Redux, React Query, i18n, timezone, preferences, so importing from RTL directly bypasses critical providers.
- Some infra deps are globally mocked (e.g., `uplot`) to keep tests fast and stable.
- `jest.setup.ts` turns off user-event's pointer-events check, Floating UI positioning and antd's scroll-container lookup for every test. Each walks `getComputedStyle` up the DOM, which jsdom computes slowly.
- For virtualization (react-virtuoso), there is no `userEvent` scroll helper; use `fireEvent.scroll` after setting `element.scrollTop`.
#### Example patterns (from `components/QuickFilters/tests/QuickFilters.test.tsx`)
@@ -76,7 +73,7 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
Interact via test IDs:
```ts
const user = userEvent.setup();
const user = userEvent.setup({ pointerEventsCheck: 0 });
await user.click(screen.getByTestId('save-changes'));
expect(screen.getByText(/ADDED FILTERS/i)).toBeInTheDocument();
```
@@ -116,5 +113,5 @@ const navigateSpy = mockNavigate(); // module-level navigate()
```
#### Notes
- Global mocks configured in Jest: `uplot` → `__mocks__/uplotMock.ts`; `@floating-ui/dom`, `@testing-library/user-event` and antd's `collectScroller` in `jest.setup.ts`.
- Global mocks configured in Jest: `uplot` → `__mocks__/uplotMock.ts`.
- If a test needs custom behavior (e.g., different API response), override with `server.use(...)` locally.

View File

@@ -1,36 +0,0 @@
import { render, screen, userEvent } from 'tests/test-utils';
describe('userEvent from the harness', () => {
const onClick = jest.fn() as jest.MockedFunction<
React.MouseEventHandler<HTMLButtonElement>
>;
const renderBlockedButton = (): void => {
render(
<button
type="button"
data-testid="blocked"
style={{ pointerEvents: 'none' }}
onClick={onClick}
>
Blocked
</button>,
);
};
it('skips the pointer-events check for setup()', async () => {
renderBlockedButton();
await userEvent.setup().click(screen.getByTestId('blocked'));
expect(onClick).toHaveBeenCalledTimes(1);
});
it('skips the pointer-events check for the direct API', async () => {
renderBlockedButton();
await userEvent.click(screen.getByTestId('blocked'));
expect(onClick).toHaveBeenCalledTimes(1);
});
});

View File

@@ -1,60 +0,0 @@
type UserEventModule = typeof import('@testing-library/user-event');
type UserEvent = UserEventModule['default'];
type DirectMethod = Exclude<keyof UserEvent, 'setup'>;
const actual = jest.requireActual<UserEventModule>(
'@testing-library/user-event',
);
const userEvent = actual.default;
// The pointer-events check walks getComputedStyle up the tree on every action.
const DEFAULTS = {
pointerEventsCheck: actual.PointerEventsCheckLevel.Never,
};
// Position of the options argument in each direct API call.
const OPTIONS_INDEX: Record<Exclude<DirectMethod, 'clear'>, number> = {
copy: 0,
cut: 0,
tab: 0,
click: 1,
dblClick: 1,
tripleClick: 1,
hover: 1,
unhover: 1,
keyboard: 1,
pointer: 1,
paste: 1,
deselectOptions: 2,
selectOptions: 2,
type: 2,
upload: 2,
};
const withDefaults =
(name: DirectMethod, optionsIndex: number) =>
(...args: unknown[]): Promise<unknown> => {
const next = [...args];
next[optionsIndex] = {
...DEFAULTS,
...(next[optionsIndex] as object | undefined),
};
return Reflect.apply(userEvent[name], userEvent, next);
};
const directApi = Object.fromEntries(
Object.entries(OPTIONS_INDEX).map(([name, index]) => [
name,
withDefaults(name as DirectMethod, index),
]),
);
const userEventWithDefaults: UserEvent = {
...userEvent,
...directApi,
clear: (element) => userEvent.setup(DEFAULTS).clear(element),
setup: (options) => userEvent.setup({ ...DEFAULTS, ...options }),
};
export const { PointerEventsCheckLevel } = actual;
export default userEventWithDefaults;

65
tests/e2e/drivers/noz/driver.ts generated Normal file
View File

@@ -0,0 +1,65 @@
import type { Locator, Page } from '@playwright/test';
import { LOGS_EXPLORER_PATH } from '../logs/explorer';
import { installFakeAssistant, type FakeAssistant } from './fake';
export const NOZ_NEW_PATH = '/ai-assistant/new';
const THREAD_PATH = /^\/ai-assistant\/([^/]+)$/;
export interface Noz {
/** Turns Noz on for this page against a fake AI service; call before the first navigation. */
enable(): Promise<FakeAssistant>;
gotoHome(): Promise<void>;
gotoNew(): Promise<void>;
gotoLogsExplorer(): Promise<void>;
reload(): Promise<void>;
navItem(): Locator;
/** "Ask Noz" in the bottom strip; opens the Noz drawer over the current page. */
askNozButton(): Locator;
newChatButton(): Locator;
/** A thread's row in the history list. */
historyItem(threadId: string): Locator;
input(): Locator;
/** Text in the open conversation, from either side. */
message(text: string): Locator;
/** Types `text` and presses Enter, as a user sends. */
send(text: string): Promise<void>;
/** The id in `/ai-assistant/:id`, `null` off the page. */
conversationId(): string | null;
}
export function nozDriver(page: Page): Noz {
const conversation = (): Locator => page.getByTestId('conversation-view');
const input = (): Locator => page.getByTestId('ai-chat-input-textarea');
return {
enable: () => installFakeAssistant(page),
gotoHome: async () => {
await page.goto('/home');
},
gotoNew: async () => {
await page.goto(NOZ_NEW_PATH);
},
gotoLogsExplorer: async () => {
await page.goto(LOGS_EXPLORER_PATH);
},
reload: async () => {
await page.reload();
},
navItem: () => page.getByTestId('nav-item-ai-assistant'),
askNozButton: () => page.getByTestId('bottom-strip-ask-noz-button'),
newChatButton: () => page.getByTestId('ai-assistant-new-conversation'),
historyItem: (threadId) =>
page.getByTestId(`ai-conversation-item-${threadId}`),
input,
message: (text) => conversation().getByText(text, { exact: true }),
send: async (text) => {
await input().fill(text);
await input().press('Enter');
},
conversationId: () =>
new URL(page.url()).pathname.match(THREAD_PATH)?.[1] ?? null,
};
}

210
tests/e2e/drivers/noz/fake.ts generated Normal file
View File

@@ -0,0 +1,210 @@
import { randomUUID } from 'node:crypto';
import type { Page, Route } from '@playwright/test';
import type { GetGlobalConfig200 } from '../schemas';
import type {
ChipsResponseDTO,
CreateMessageRequestDTO,
CreateMessageResponseDTO,
CreateThreadResponseDTO,
ExecutionStateDTO,
MessageRoleDTO,
MessageSummaryDTO,
SSEEvent,
ThreadDetailResponseDTO,
ThreadListResponseDTO,
} from './schemas';
export interface SentMessage {
threadId: string;
body: CreateMessageRequestDTO;
}
export interface FakeAssistant {
/** Queue the text of the next reply; a send with nothing queued gets a 500. */
replyWith(text: string): void;
/** Bodies the app POSTed to `/threads/:id/messages`, oldest first. */
sentMessages(): SentMessage[];
}
const ASSISTANT_PATH = '/api/v1/assistant';
// Calls made before the global config loads go out with an empty base URL.
const UNPREFIXED = /^\/(threads|executions|empty-state)(\/|$)/;
/** The path under the assistant API, or `null` for any other request. */
function assistantPath(url: URL): string | null {
const at = url.pathname.indexOf(`${ASSISTANT_PATH}/`);
if (at >= 0) {
return url.pathname.slice(at + ASSISTANT_PATH.length);
}
return UNPREFIXED.test(url.pathname) ? url.pathname : null;
}
const json = (route: Route, body: unknown, status = 200): Promise<void> =>
route.fulfill({ status, json: body });
// The generated enums are TS enums; a literal typed by their values can't drift.
const role = (value: `${MessageRoleDTO}`): MessageRoleDTO =>
value as MessageRoleDTO;
const state = (value: `${ExecutionStateDTO}`): ExecutionStateDTO =>
value as ExecutionStateDTO;
function replyEvents(
executionId: string,
messageId: string,
text: string,
): SSEEvent[] {
return [
{ type: 'status', executionId, state: state('running') },
{ type: 'message', executionId, messageId, delta: text, done: false },
{ type: 'message', executionId, messageId, delta: '', done: true },
{ type: 'done', executionId, tokenInput: 0, tokenOutput: 0, latencyMs: 0 },
];
}
const sse = (events: SSEEvent[]): string =>
events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('');
/** Fakes the AI service the stack doesn't run, and enables Noz for this page only. */
export async function installFakeAssistant(page: Page): Promise<FakeAssistant> {
const threads = new Map<string, ThreadDetailResponseDTO>();
const executions = new Map<string, SSEEvent[]>();
const replies: string[] = [];
const sent: SentMessage[] = [];
const now = (): string => new Date().toISOString();
const message = (
messageRole: `${MessageRoleDTO}`,
content: string,
extra: Partial<MessageSummaryDTO> = {},
): MessageSummaryDTO => ({
messageId: randomUUID(),
role: role(messageRole),
content,
complete: true,
createdAt: now(),
updatedAt: now(),
...extra,
});
const createThread = (): CreateThreadResponseDTO => {
const threadId = randomUUID();
threads.set(threadId, {
threadId,
title: null,
state: null,
activeExecutionId: null,
archived: false,
createdAt: now(),
updatedAt: now(),
messages: [],
});
return { threadId };
};
const listThreads = (url: URL): ThreadListResponseDTO => {
const archived = url.searchParams.get('archived') === 'true';
return {
threads: [...threads.values()]
.filter((thread) => Boolean(thread.archived) === archived)
.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
.map((thread) => ({
threadId: thread.threadId,
title: thread.title,
state: thread.state,
archived: thread.archived,
createdAt: thread.createdAt,
updatedAt: thread.updatedAt,
})),
hasMore: false,
nextCursor: null,
};
};
const postMessage = async (
route: Route,
thread: ThreadDetailResponseDTO,
): Promise<void> => {
const body = route.request().postDataJSON() as CreateMessageRequestDTO;
sent.push({ threadId: thread.threadId, body });
const text = replies.shift();
if (text === undefined) {
await json(route, { error: 'no scripted reply' }, 500);
return;
}
const executionId = randomUUID();
const reply = message('assistant', text, { executionId });
executions.set(executionId, replyEvents(executionId, reply.messageId, text));
thread.messages?.push(
message('user', body.content, { contexts: body.contexts }),
reply,
);
thread.title ??= body.content;
thread.state = state('completed');
thread.updatedAt = now();
const response: CreateMessageResponseDTO = { executionId };
await json(route, response);
};
const handle = async (route: Route): Promise<void> => {
const url = new URL(route.request().url());
const method = route.request().method();
const path = assistantPath(url) ?? '';
const [, resource, id, sub, ...extra] = path.split('/');
const thread = id ? threads.get(id) : undefined;
const is = (verb: string, segment?: string): boolean =>
method === verb && sub === segment && extra.length === 0;
if (resource === 'threads' && !id && is('POST')) {
return json(route, createThread());
}
if (resource === 'threads' && !id && is('GET')) {
return json(route, listThreads(url));
}
if (resource === 'threads' && thread && is('GET')) {
return json(route, thread);
}
if (resource === 'threads' && thread && is('POST', 'messages')) {
return postMessage(route, thread);
}
if (
resource === 'executions' &&
id &&
executions.has(id) &&
is('GET', 'events')
) {
return route.fulfill({
status: 200,
contentType: 'text/event-stream',
body: sse(executions.get(id) ?? []),
});
}
if (resource === 'empty-state' && id === 'chips' && is('GET')) {
const chips: ChipsResponseDTO = { chips: [] };
return json(route, chips);
}
return json(route, { error: `fake assistant: ${method} ${path}` }, 404);
};
await page.route((url) => assistantPath(url) !== null, handle);
await page.route(
(url) => url.pathname.endsWith('/api/v1/global/config'),
async (route) => {
const response = await route.fetch();
const body = (await response.json()) as GetGlobalConfig200;
body.data.ai_assistant_url = new URL(route.request().url()).origin;
await route.fulfill({ response, json: body });
},
);
return {
replyWith: (text) => {
replies.push(text);
},
sentMessages: () => [...sent],
};
}

12
tests/e2e/drivers/noz/index.ts generated Normal file
View File

@@ -0,0 +1,12 @@
import { driver, kit, type Layer } from '../kit';
import { nozDriver, type Noz } from './driver';
export type { FakeAssistant, SentMessage } from './fake';
export const withNoz: Layer<{ noz: Noz }> = driver('noz', ({ page }) =>
nozDriver(page),
);
export const test = withNoz(kit);
export { expect } from '../kit';

3
tests/e2e/drivers/noz/schemas.ts generated Normal file
View File

@@ -0,0 +1,3 @@
/** The AI service contract; `SSEEvent` adds the `type` discriminator the package's event DTOs leave loose. */
export type * from '@signozhq/noz-client';
export type { SSEEvent } from '@frontend/api/ai-assistant/sseEvent';

View File

@@ -39,6 +39,7 @@
"license": "MIT",
"devDependencies": {
"@playwright/test": "1.57.0",
"@signozhq/noz-client": "1.13.0",
"@types/node": "^20.0.0",
"dotenv": "^16.0.0",
"eslint-plugin-playwright": "^2.10.2",

425
tests/e2e/pnpm-lock.yaml generated
View File

@@ -14,6 +14,9 @@ importers:
'@playwright/test':
specifier: 1.57.0
version: 1.57.0
'@signozhq/noz-client':
specifier: 1.13.0
version: 1.13.0(axios@1.21.1)(react-query@3.39.3(react@18.3.1))(react@18.3.1)
'@types/node':
specifier: ^20.0.0
version: 20.19.20
@@ -38,6 +41,10 @@ importers:
packages:
'@babel/runtime@7.29.7':
resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==}
engines: {node: '>=6.9.0'}
'@eslint-community/eslint-utils@4.9.1':
resolution: {integrity: sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==}
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
@@ -367,6 +374,13 @@ packages:
engines: {node: '>=18'}
hasBin: true
'@signozhq/noz-client@1.13.0':
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
peerDependencies:
axios: ^1.20.0
react: ^18.2.0
react-query: ^3.39.3
'@types/esrecurse@4.3.1':
resolution: {integrity: sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==}
@@ -389,17 +403,51 @@ packages:
engines: {node: '>=0.4.0'}
hasBin: true
agent-base@6.0.2:
resolution: {integrity: sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==}
engines: {node: '>= 6.0.0'}
ajv@6.15.0:
resolution: {integrity: sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==}
asynckit@0.4.0:
resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==}
axios@1.21.1:
resolution: {integrity: sha512-6eI5Q/Y4u/Um9dDlsRoq5pY2rxnUTv+L4PpLitnbk/i4jb3MxLZ5CsN5Ih3IysbeRYK4pR+P7qfMsOQl9fwwFQ==}
balanced-match@1.0.2:
resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==}
balanced-match@4.0.4:
resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==}
engines: {node: 18 || 20 || >=22}
big-integer@1.6.52:
resolution: {integrity: sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg==}
engines: {node: '>=0.6'}
brace-expansion@1.1.22:
resolution: {integrity: sha512-CKLDTuSsN0+r1ThM0WkzzBI7dnPI6xEGfa/JnVYIK9JNBA1N1NyPwXVHor//NKD/y3sDxp764sZdLhFK7pH8XQ==}
brace-expansion@5.0.12:
resolution: {integrity: sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==}
engines: {node: 20 || >=22}
broadcast-channel@3.7.0:
resolution: {integrity: sha512-cIAKJXAxGJceNZGTZSBzMxzyOn72cVgPnKx4dc6LRjQgbaJUQqhy5rzL3zbMxkMWsGKkv2hSFkPRMEXfoMZ2Mg==}
call-bind-apply-helpers@1.0.2:
resolution: {integrity: sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==}
engines: {node: '>= 0.4'}
combined-stream@1.0.8:
resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==}
engines: {node: '>= 0.8'}
concat-map@0.0.1:
resolution: {integrity: sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==}
cross-spawn@7.0.6:
resolution: {integrity: sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==}
engines: {node: '>= 8'}
@@ -416,10 +464,37 @@ packages:
deep-is@0.1.4:
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
delayed-stream@1.0.0:
resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==}
engines: {node: '>=0.4.0'}
detect-node@2.1.0:
resolution: {integrity: sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==}
dotenv@16.6.1:
resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==}
engines: {node: '>=12'}
dunder-proto@1.0.1:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
es-define-property@1.0.1:
resolution: {integrity: sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==}
engines: {node: '>= 0.4'}
es-errors@1.3.0:
resolution: {integrity: sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==}
engines: {node: '>= 0.4'}
es-object-atoms@1.1.2:
resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==}
engines: {node: '>= 0.4'}
es-set-tostringtag@2.1.0:
resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==}
engines: {node: '>= 0.4'}
escape-string-regexp@4.0.0:
resolution: {integrity: sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==}
engines: {node: '>=10'}
@@ -496,19 +571,70 @@ packages:
flatted@3.4.2:
resolution: {integrity: sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==}
follow-redirects@1.16.3:
resolution: {integrity: sha512-toOSoqN6d51Wjf1aOFJYcoVv1aND9rj/CwjLU0Vz40oDuSpWDayCeKe4JpL5NL0WdFvoOOCI3BRo69HahjbR1A==}
engines: {node: '>=4.0'}
peerDependencies:
debug: '*'
peerDependenciesMeta:
debug:
optional: true
form-data@4.0.6:
resolution: {integrity: sha512-vKatAh4SlVfgbv+YtmhiRjhEMJsYpsG1Y2rMQtR+SVSbytsSD1YGzDIcrAJmdFec88u/+VoGmxnl+80gL1tRCQ==}
engines: {node: '>= 6'}
fs.realpath@1.0.0:
resolution: {integrity: sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==}
fsevents@2.3.2:
resolution: {integrity: sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==}
engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}
os: [darwin]
function-bind@1.1.2:
resolution: {integrity: sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==}
get-intrinsic@1.3.0:
resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==}
engines: {node: '>= 0.4'}
get-proto@1.0.1:
resolution: {integrity: sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==}
engines: {node: '>= 0.4'}
glob-parent@6.0.2:
resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==}
engines: {node: '>=10.13.0'}
glob@7.2.3:
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me
globals@17.5.0:
resolution: {integrity: sha512-qoV+HK2yFl/366t2/Cb3+xxPUo5BuMynomoDmiaZBIdbs+0pYbjfZU+twLhGKp4uCZ/+NbtpVepH5bGCxRyy2g==}
engines: {node: '>=18'}
gopd@1.2.0:
resolution: {integrity: sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==}
engines: {node: '>= 0.4'}
has-symbols@1.1.0:
resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==}
engines: {node: '>= 0.4'}
has-tostringtag@1.0.2:
resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==}
engines: {node: '>= 0.4'}
hasown@2.0.4:
resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==}
engines: {node: '>= 0.4'}
https-proxy-agent@5.0.1:
resolution: {integrity: sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==}
engines: {node: '>= 6'}
ignore@5.3.2:
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
engines: {node: '>= 4'}
@@ -517,6 +643,13 @@ packages:
resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==}
engines: {node: '>=0.8.19'}
inflight@1.0.6:
resolution: {integrity: sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==}
deprecated: This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.
inherits@2.0.4:
resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==}
is-extglob@2.1.1:
resolution: {integrity: sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==}
engines: {node: '>=0.10.0'}
@@ -528,6 +661,12 @@ packages:
isexe@2.0.0:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
js-sha3@0.8.0:
resolution: {integrity: sha512-gF1cRrHhIzNfToc802P800N8PpXS+evLLXfsVpowqmAFR9uwbi89WvXg2QspOmXL8QL86J4T1EpFu+yUkwJY3Q==}
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
json-buffer@3.0.1:
resolution: {integrity: sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==}
@@ -548,16 +687,50 @@ packages:
resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==}
engines: {node: '>=10'}
loose-envify@1.4.0:
resolution: {integrity: sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==}
hasBin: true
match-sorter@6.3.4:
resolution: {integrity: sha512-jfZW7cWS5y/1xswZo8VBOdudUiSd9nifYRWphc9M5D/ee4w4AoXLgBEdRbgVaxbMuagBPeUC5y2Hi8DO6o9aDg==}
math-intrinsics@1.1.0:
resolution: {integrity: sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==}
engines: {node: '>= 0.4'}
microseconds@0.2.0:
resolution: {integrity: sha512-n7DHHMjR1avBbSpsTBj6fmMGh2AGrifVV4e+WYc3Q9lO+xnSZ3NyhcBND3vzzatt05LFhoKFRxrIyklmLlUtyA==}
mime-db@1.52.0:
resolution: {integrity: sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==}
engines: {node: '>= 0.6'}
mime-types@2.1.35:
resolution: {integrity: sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==}
engines: {node: '>= 0.6'}
minimatch@10.2.5:
resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==}
engines: {node: 18 || 20 || >=22}
minimatch@3.1.5:
resolution: {integrity: sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==}
ms@2.1.3:
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
nano-time@1.0.0:
resolution: {integrity: sha512-flnngywOoQ0lLQOTRNexn2gGSNuM9bKj9RZAWSzhQ+UJYaAFG9bac4DW9VHjUAzrOaIcajHybCTHe/bkvozQqA==}
natural-compare@1.4.0:
resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==}
oblivious-set@1.0.0:
resolution: {integrity: sha512-z+pI07qxo4c2CulUHCDf9lcqDlMSo72N/4rLUpRXf6fu+q8vjt8y0xS+Tlf8NTJDdTXHbdeO1n3MlbctwEoXZw==}
once@1.4.0:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
optionator@0.9.4:
resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==}
engines: {node: '>= 0.8.0'}
@@ -607,6 +780,10 @@ packages:
resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==}
engines: {node: '>=8'}
path-is-absolute@1.0.1:
resolution: {integrity: sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==}
engines: {node: '>=0.10.0'}
path-key@3.1.1:
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
engines: {node: '>=8'}
@@ -625,10 +802,38 @@ packages:
resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==}
engines: {node: '>= 0.8.0'}
proxy-from-env@2.1.0:
resolution: {integrity: sha512-cJ+oHTW1VAEa8cJslgmUZrc+sjRKgAKl3Zyse6+PV38hZe/V6Z14TbCuXcan9F9ghlz4QrFr2c92TNF82UkYHA==}
engines: {node: '>=10'}
punycode@2.3.1:
resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==}
engines: {node: '>=6'}
react-query@3.39.3:
resolution: {integrity: sha512-nLfLz7GiohKTJDuT4us4X3h/8unOh+00MLb2yJoGTPjxKs2bc1iDhkNx2bd5MKklXnOD3NrVZ+J2UXujA5In4g==}
peerDependencies:
react: ^16.8.0 || ^17.0.0 || ^18.0.0
react-dom: '*'
react-native: '*'
peerDependenciesMeta:
react-dom:
optional: true
react-native:
optional: true
react@18.3.1:
resolution: {integrity: sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==}
engines: {node: '>=0.10.0'}
remove-accents@0.5.0:
resolution: {integrity: sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A==}
rimraf@3.0.2:
resolution: {integrity: sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==}
deprecated: Rimraf versions prior to v4 are no longer supported
hasBin: true
shebang-command@2.0.0:
resolution: {integrity: sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==}
engines: {node: '>=8'}
@@ -653,6 +858,9 @@ packages:
undici-types@6.21.0:
resolution: {integrity: sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==}
unload@2.2.0:
resolution: {integrity: sha512-B60uB5TNBLtN6/LsgAf3udH9saB5p7gqJwcFfbOEZ8BcBHnGwCf6G/TGiEqkRAxX7zAFIUtzdrXQSdL3Q/wqNA==}
uri-js@4.4.1:
resolution: {integrity: sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==}
@@ -665,12 +873,17 @@ packages:
resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==}
engines: {node: '>=0.10.0'}
wrappy@1.0.2:
resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==}
yocto-queue@0.1.0:
resolution: {integrity: sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==}
engines: {node: '>=10'}
snapshots:
'@babel/runtime@7.29.7': {}
'@eslint-community/eslint-utils@4.9.1(eslint@10.2.1)':
dependencies:
eslint: 10.2.1
@@ -853,6 +1066,12 @@ snapshots:
dependencies:
playwright: 1.57.0
'@signozhq/noz-client@1.13.0(axios@1.21.1)(react-query@3.39.3(react@18.3.1))(react@18.3.1)':
dependencies:
axios: 1.21.1
react: 18.3.1
react-query: 3.39.3(react@18.3.1)
'@types/esrecurse@4.3.1': {}
'@types/estree@1.0.8': {}
@@ -869,6 +1088,12 @@ snapshots:
acorn@8.16.0: {}
agent-base@6.0.2:
dependencies:
debug: 4.4.3
transitivePeerDependencies:
- supports-color
ajv@6.15.0:
dependencies:
fast-deep-equal: 3.1.3
@@ -876,12 +1101,55 @@ snapshots:
json-schema-traverse: 0.4.1
uri-js: 4.4.1
asynckit@0.4.0: {}
axios@1.21.1:
dependencies:
follow-redirects: 1.16.3
form-data: 4.0.6
https-proxy-agent: 5.0.1
proxy-from-env: 2.1.0
transitivePeerDependencies:
- debug
- supports-color
balanced-match@1.0.2: {}
balanced-match@4.0.4: {}
big-integer@1.6.52: {}
brace-expansion@1.1.22:
dependencies:
balanced-match: 1.0.2
concat-map: 0.0.1
brace-expansion@5.0.12:
dependencies:
balanced-match: 4.0.4
broadcast-channel@3.7.0:
dependencies:
'@babel/runtime': 7.29.7
detect-node: 2.1.0
js-sha3: 0.8.0
microseconds: 0.2.0
nano-time: 1.0.0
oblivious-set: 1.0.0
rimraf: 3.0.2
unload: 2.2.0
call-bind-apply-helpers@1.0.2:
dependencies:
es-errors: 1.3.0
function-bind: 1.1.2
combined-stream@1.0.8:
dependencies:
delayed-stream: 1.0.0
concat-map@0.0.1: {}
cross-spawn@7.0.6:
dependencies:
path-key: 3.1.1
@@ -894,8 +1162,33 @@ snapshots:
deep-is@0.1.4: {}
delayed-stream@1.0.0: {}
detect-node@2.1.0: {}
dotenv@16.6.1: {}
dunder-proto@1.0.1:
dependencies:
call-bind-apply-helpers: 1.0.2
es-errors: 1.3.0
gopd: 1.2.0
es-define-property@1.0.1: {}
es-errors@1.3.0: {}
es-object-atoms@1.1.2:
dependencies:
es-errors: 1.3.0
es-set-tostringtag@2.1.0:
dependencies:
es-errors: 1.3.0
get-intrinsic: 1.3.0
has-tostringtag: 1.0.2
hasown: 2.0.4
escape-string-regexp@4.0.0: {}
eslint-plugin-playwright@2.10.2(eslint@10.2.1):
@@ -989,19 +1282,86 @@ snapshots:
flatted@3.4.2: {}
follow-redirects@1.16.3: {}
form-data@4.0.6:
dependencies:
asynckit: 0.4.0
combined-stream: 1.0.8
es-set-tostringtag: 2.1.0
hasown: 2.0.4
mime-types: 2.1.35
fs.realpath@1.0.0: {}
fsevents@2.3.2:
optional: true
function-bind@1.1.2: {}
get-intrinsic@1.3.0:
dependencies:
call-bind-apply-helpers: 1.0.2
es-define-property: 1.0.1
es-errors: 1.3.0
es-object-atoms: 1.1.2
function-bind: 1.1.2
get-proto: 1.0.1
gopd: 1.2.0
has-symbols: 1.1.0
hasown: 2.0.4
math-intrinsics: 1.1.0
get-proto@1.0.1:
dependencies:
dunder-proto: 1.0.1
es-object-atoms: 1.1.2
glob-parent@6.0.2:
dependencies:
is-glob: 4.0.3
glob@7.2.3:
dependencies:
fs.realpath: 1.0.0
inflight: 1.0.6
inherits: 2.0.4
minimatch: 3.1.5
once: 1.4.0
path-is-absolute: 1.0.1
globals@17.5.0: {}
gopd@1.2.0: {}
has-symbols@1.1.0: {}
has-tostringtag@1.0.2:
dependencies:
has-symbols: 1.1.0
hasown@2.0.4:
dependencies:
function-bind: 1.1.2
https-proxy-agent@5.0.1:
dependencies:
agent-base: 6.0.2
debug: 4.4.3
transitivePeerDependencies:
- supports-color
ignore@5.3.2: {}
imurmurhash@0.1.4: {}
inflight@1.0.6:
dependencies:
once: 1.4.0
wrappy: 1.0.2
inherits@2.0.4: {}
is-extglob@2.1.1: {}
is-glob@4.0.3:
@@ -1010,6 +1370,10 @@ snapshots:
isexe@2.0.0: {}
js-sha3@0.8.0: {}
js-tokens@4.0.0: {}
json-buffer@3.0.1: {}
json-schema-traverse@0.4.1: {}
@@ -1029,14 +1393,47 @@ snapshots:
dependencies:
p-locate: 5.0.0
loose-envify@1.4.0:
dependencies:
js-tokens: 4.0.0
match-sorter@6.3.4:
dependencies:
'@babel/runtime': 7.29.7
remove-accents: 0.5.0
math-intrinsics@1.1.0: {}
microseconds@0.2.0: {}
mime-db@1.52.0: {}
mime-types@2.1.35:
dependencies:
mime-db: 1.52.0
minimatch@10.2.5:
dependencies:
brace-expansion: 5.0.12
minimatch@3.1.5:
dependencies:
brace-expansion: 1.1.22
ms@2.1.3: {}
nano-time@1.0.0:
dependencies:
big-integer: 1.6.52
natural-compare@1.4.0: {}
oblivious-set@1.0.0: {}
once@1.4.0:
dependencies:
wrappy: 1.0.2
optionator@0.9.4:
dependencies:
deep-is: 0.1.4
@@ -1112,6 +1509,8 @@ snapshots:
path-exists@4.0.0: {}
path-is-absolute@1.0.1: {}
path-key@3.1.1: {}
playwright-core@1.57.0: {}
@@ -1124,8 +1523,27 @@ snapshots:
prelude-ls@1.2.1: {}
proxy-from-env@2.1.0: {}
punycode@2.3.1: {}
react-query@3.39.3(react@18.3.1):
dependencies:
'@babel/runtime': 7.29.7
broadcast-channel: 3.7.0
match-sorter: 6.3.4
react: 18.3.1
react@18.3.1:
dependencies:
loose-envify: 1.4.0
remove-accents@0.5.0: {}
rimraf@3.0.2:
dependencies:
glob: 7.2.3
shebang-command@2.0.0:
dependencies:
shebang-regex: 3.0.0
@@ -1142,6 +1560,11 @@ snapshots:
undici-types@6.21.0: {}
unload@2.2.0:
dependencies:
'@babel/runtime': 7.29.7
detect-node: 2.1.0
uri-js@4.4.1:
dependencies:
punycode: 2.3.1
@@ -1152,4 +1575,6 @@ snapshots:
word-wrap@1.2.5: {}
wrappy@1.0.2: {}
yocto-queue@0.1.0: {}

View File

@@ -0,0 +1,108 @@
import { expect, test } from '../../drivers/noz';
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
const QUESTION = 'Why is checkout slow?';
const REPLY = 'Checkout waits on the payment quota.';
const FOLLOW_UP = 'Since when?';
const FOLLOW_UP_REPLY = 'Since the 14:05 deploy.';
test.describe('Noz — chat', () => {
test('TC-01 with an assistant URL the side nav opens a new chat', async ({
noz,
}) => {
await noz.enable();
await noz.gotoHome();
await noz.navItem().click();
await expect.poll(() => noz.conversationId()).toMatch(UUID);
await expect(noz.input()).toBeVisible();
});
test('TC-02 a sent message reaches the assistant and its reply renders', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
await expect(noz.message(QUESTION)).toBeVisible();
const [sent] = assistant.sentMessages();
expect(sent.body.content).toBe(QUESTION);
await expect.poll(() => noz.conversationId()).toBe(sent.threadId);
});
test('TC-03 a reload reopens the thread from the assistant', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
await noz.reload();
await expect(noz.message(QUESTION)).toBeVisible();
await expect(noz.message(REPLY)).toBeVisible();
});
test('TC-04 a follow-up stays in the same thread', async ({ noz }) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
assistant.replyWith(FOLLOW_UP_REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
await noz.send(FOLLOW_UP);
await expect(noz.message(FOLLOW_UP_REPLY)).toBeVisible();
await expect(noz.message(REPLY)).toBeVisible();
const [first, second] = assistant.sentMessages();
expect(second.body.content).toBe(FOLLOW_UP);
expect(second.threadId).toBe(first.threadId);
expect(noz.conversationId()).toBe(first.threadId);
});
test('TC-05 a new chat starts empty and the history list reopens the last one', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoNew();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
const [{ threadId }] = assistant.sentMessages();
await noz.newChatButton().click();
await expect.poll(() => noz.conversationId()).not.toBe(threadId);
await expect(noz.message(QUESTION)).toHaveCount(0);
await noz.historyItem(threadId).click();
await expect.poll(() => noz.conversationId()).toBe(threadId);
await expect(noz.message(QUESTION)).toBeVisible();
await expect(noz.message(REPLY)).toBeVisible();
});
test('TC-06 asking from the Logs Explorer sends that page as context', async ({
noz,
}) => {
const assistant = await noz.enable();
assistant.replyWith(REPLY);
await noz.gotoLogsExplorer();
await noz.askNozButton().click();
await noz.send(QUESTION);
await expect(noz.message(REPLY)).toBeVisible();
const [sent] = assistant.sentMessages();
expect(sent.body.contexts).toContainEqual(
expect.objectContaining({ source: 'auto', type: 'logs_explorer' }),
);
});
});

View File

@@ -16,7 +16,10 @@
"types": ["node", "@playwright/test"],
"paths": {
"@tests/*": ["./tests/*"],
"@specs/*": ["./specs/*"]
"@specs/*": ["./specs/*"],
"@frontend/*": ["../../frontend/src/*"],
// `drivers/noz/schemas.ts` reaches into `frontend/`, which CI never installs.
"@signozhq/noz-client": ["./node_modules/@signozhq/noz-client"]
}
},
"include": ["tests/**/*.ts", "drivers/**/*.ts", "bootstrap/**/*.ts", "playwright.config.ts"],