Compare commits

...

1 Commits

Author SHA1 Message Date
Gaurav Tewari
f414e212e0 feat(noz): add the context V2 store and route surfaces 2026-12-03 17:09:20 +05:30
15 changed files with 1009 additions and 6 deletions

View File

@@ -56,7 +56,7 @@
"@sentry/vite-plugin": "5.3.0",
"@signozhq/design-tokens": "2.8.0",
"@signozhq/icons": "0.4.0",
"@signozhq/noz-client": "1.13.0",
"@signozhq/noz-client": "1.15.0-experimental.5",
"@signozhq/ui": "0.4.1-rc.2",
"@tanstack/react-table": "8.21.3",
"@tanstack/react-virtual": "3.13.22",

View File

@@ -83,8 +83,8 @@ importers:
specifier: 0.4.0
version: 0.4.0
'@signozhq/noz-client':
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)
specifier: 1.15.0-experimental.5
version: 1.15.0-experimental.5(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)
@@ -3094,8 +3094,8 @@ packages:
'@signozhq/icons@0.4.0':
resolution: {integrity: sha512-QctNvNPlQlsefFdIVmSy/P/7a1IcQ3IryKP0KPMqtoqew3q89FGUmFa5IfEJ7Z3CHhtG1zaXwBKqP72QkLyA3g==}
'@signozhq/noz-client@1.13.0':
resolution: {integrity: sha512-130L2xomHnQZK8ZtAst34qFz9d2rSF/JYpg9gKvJkZVS9+46CPZeTW8Va9PNS9Oa5owezVHIXZStTEbsHIxnwg==}
'@signozhq/noz-client@1.15.0-experimental.5':
resolution: {integrity: sha512-CxLEj9g+/QK9zjumREhg2U+D5RShGa6N73XucEbgISCQpWdNKEasSh6vmpDyZpEgLEKq7g4g38Pb6EGN7yg5Pg==}
peerDependencies:
axios: ^1.20.0
react: ^18.2.0
@@ -12058,7 +12058,7 @@ snapshots:
'@signozhq/icons@0.4.0': {}
'@signozhq/noz-client@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/noz-client@1.15.0-experimental.5(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)':
dependencies:
axios: 1.21.1
react: 18.2.0

View File

@@ -0,0 +1,106 @@
import { KnownAssistantSurfaceDTO as Surface } from '@signozhq/noz-client';
import ROUTES from 'constants/routes';
import { AlertListSubTabs, AlertListTabs } from 'pages/AlertList/types';
import type { RouteKey } from './types';
// Copied from the backend (signoz-ai-assistant app/schemas/context.py); one over cuts the page to `surface` and `root`.
export const MAX_PATHS = 4;
export const MAX_PATH_NODES = 6;
export const MAX_VIEW_PATH = 6;
export const MAX_DATA_VIEWS = 8;
export const MAX_SELECTIONS = 4;
export const MAX_VARIABLES = 32;
export const MAX_SETTINGS = 16;
// Maps, not objects: a `?tab=constructor` must not resolve to Object.prototype.
export const ALERT_TAB_SURFACES = new Map<string | null, Surface>([
[AlertListTabs.TRIGGERED_ALERTS, Surface.alerttriggered],
[AlertListTabs.CHANNELS, Surface.alertchannellist],
[AlertListTabs.ROUTING_POLICIES, Surface.alertrouting],
[AlertListTabs.PLANNED_DOWNTIME, Surface.alertdowntime],
]);
export const ALERT_SUB_TAB_SURFACES = new Map<string | null, Surface>([
[AlertListSubTabs.ROUTING_POLICIES, Surface.alertrouting],
[AlertListSubTabs.PLANNED_DOWNTIME, Surface.alertdowntime],
]);
export const SETTINGS_SURFACES: [string, Surface][] = [
[ROUTES.SETTINGS, Surface.settingsworkspace],
[ROUTES.MY_SETTINGS, Surface.settingsaccount],
[ROUTES.ORG_SETTINGS, Surface.settingssso],
[ROUTES.INGESTION_SETTINGS, Surface.settingsingestion],
[ROUTES.BILLING, Surface.settingsbilling],
[ROUTES.MEMBERS_SETTINGS, Surface.settingsmembers],
[ROUTES.ROLES_SETTINGS, Surface.settingsroles],
[ROUTES.ROLE_CREATE, Surface.settingsroles],
[ROUTES.ROLE_DETAILS, Surface.settingsroles],
[ROUTES.ROLE_EDIT, Surface.settingsroles],
[ROUTES.SERVICE_ACCOUNTS_SETTINGS, Surface.settingsservice_accounts],
[ROUTES.SHORTCUTS, Surface.settingsshortcuts],
[ROUTES.MCP_SERVER, Surface.settingsmcp_server],
];
/** Every key in the route table but those in `URL_SURFACES`, with its surface; `null` sends no page. */
export const ROUTE_SURFACES: Partial<Record<RouteKey, Surface | null>> = {
HOME: Surface.homeoverview,
APPLICATION: Surface.servicelist,
SERVICE_METRICS: Surface.servicedetail,
SERVICE_TOP_LEVEL_OPERATIONS: Surface.servicedetail,
SERVICE_MAP: Surface.servicemap,
ALL_DASHBOARD: Surface.dashboardlist,
DASHBOARD: Surface.dashboarddetail,
DASHBOARD_PANEL_EDITOR: Surface.dashboardpaneleditor,
ALERT_OVERVIEW: Surface.alertruledetail,
ALERT_HISTORY: Surface.alertruledetail,
EDIT_ALERTS: Surface.alertruledetail,
ALERTS_NEW: Surface.alertruleeditor,
CHANNELS_NEW: Surface.alertchanneleditor,
CHANNELS_EDIT: Surface.alertchanneleditor,
LOGS: Surface.logexplorer,
LOGS_PIPELINES: Surface.logpipeline,
// The backend has no surface for logs settings yet.
LOGS_INDEX_FIELDS: null,
TRACES_EXPLORER: Surface.traceexplorer,
TRACE_DETAIL: Surface.tracedetail,
TRACES_FUNNELS: Surface.tracefunnellist,
TRACES_FUNNELS_DETAIL: Surface.tracefunneldetail,
METRICS_EXPLORER: Surface.metricsummary,
METRICS_EXPLORER_EXPLORER: Surface.metricexplorer,
METRICS_EXPLORER_VOLUME_CONTROL: Surface.metricvolume_control,
ALL_ERROR: Surface.exceptionlist,
ERROR_DETAIL: Surface.exceptiondetail,
INFRASTRUCTURE_MONITORING_HOSTS: Surface.infrastructurehostlist,
INFRASTRUCTURE_MONITORING_KUBERNETES: Surface.infrastructurekuberneteslist,
API_MONITORING: Surface.api_monitoringexplorer,
MESSAGING_QUEUES_OVERVIEW: Surface.messagingoverview,
MESSAGING_QUEUES_KAFKA: Surface.messagingkafka,
MESSAGING_QUEUES_KAFKA_DETAIL: Surface.messagingkafkadetail,
MESSAGING_QUEUES_CELERY_TASK: Surface.messagingcelery,
METER: Surface.meteroverview,
METER_EXPLORER: Surface.meterexplorer,
USAGE_EXPLORER: Surface.usageexplorer,
INTEGRATIONS: Surface.integrationcatalog,
INTEGRATIONS_DETAIL: Surface.integrationdetail,
AI_OBSERVABILITY_OVERVIEW: Surface.ai_observabilityoverview,
AI_OBSERVABILITY_EXPLORER: Surface.ai_observabilityexplorer,
AI_OBSERVABILITY_CONFIGURATION: Surface.ai_observabilitymodel_pricing,
AI_OBSERVABILITY_ATTRIBUTE_MAPPING: Surface.ai_observabilityattribute_mapping,
ONBOARDING: Surface.onboardingorganization,
GET_STARTED_WITH_CLOUD: Surface.onboardingdata_source,
SUPPORT: Surface.supportoverview,
LIST_LICENSES: Surface.licenseapply,
AI_ASSISTANT: null,
PUBLIC_DASHBOARD: null,
VERSION: null,
SIGN_UP: null,
LOGIN: null,
FORGOT_PASSWORD: null,
PASSWORD_RESET: null,
UN_AUTHORIZED: null,
SOMETHING_WENT_WRONG: null,
WORKSPACE_LOCKED: null,
WORKSPACE_SUSPENDED: null,
WORKSPACE_ACCESS_RESTRICTED: null,
};

View File

@@ -0,0 +1,69 @@
import {
type ContextNodeDTO,
KnownAssistantSurfaceDTO,
type PageContextDTO,
} from '@signozhq/noz-client';
import { renderHook } from 'tests/test-utils';
import { snapshotAssistantContext } from '../../store/usePageContextStore';
import type { AssistantContextPart } from '../../types';
import { useAssistantState } from '../useAssistantState';
const SURFACE = KnownAssistantSurfaceDTO.dashboarddetail;
function snapshot(): PageContextDTO | null {
return snapshotAssistantContext({
surface: SURFACE,
activeViewPath: [],
});
}
function panelPath(id: string): ContextNodeDTO[] {
return [{ target: { kind: 'dashboard_panel', resourceId: id } }];
}
function focusedPanels(): (string | null | undefined)[] {
return (snapshot()?.activePaths ?? [])
.filter((path) => path.focused)
.map((path) => path.nodes[0].target.resourceId);
}
describe('useAssistantState', () => {
it('reads the latest getter only on Send, and leaves the page on unmount', () => {
const getter = jest.fn((env: string) => ({
state: { variableValues: [{ name: 'env', value: env }] },
})) as jest.MockedFunction<(env: string) => AssistantContextPart>;
const { rerender, unmount } = renderHook(
({ env }) => useAssistantState(() => getter(env)),
{ initialProps: { env: 'prod' } },
);
rerender({ env: 'staging' });
expect(getter).not.toHaveBeenCalled();
expect(snapshot()?.state?.variableValues).toStrictEqual([
{ name: 'env', value: 'staging' },
]);
unmount();
expect(snapshot()).toStrictEqual({ surface: SURFACE });
});
it('marks its path focused only while `focused` is set', () => {
renderHook(() => useAssistantState(() => ({ path: panelPath('a') })));
const { rerender, unmount } = renderHook(
({ focused }: { focused: boolean }) =>
useAssistantState(() => ({ path: panelPath('b') }), { focused }),
{ initialProps: { focused: true } },
);
expect(focusedPanels()).toStrictEqual(['b']);
rerender({ focused: false });
expect(focusedPanels()).toStrictEqual([]);
rerender({ focused: true });
unmount();
expect(focusedPanels()).toStrictEqual([]);
});
});

View File

@@ -0,0 +1,62 @@
import { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { render, screen } from 'tests/test-utils';
import { useAssistantScreen } from '../useAssistantScreen';
import { useAssistantSurface } from '../useAssistantSurface';
function LiveLogs({ liveMode }: { liveMode: boolean }): null {
useAssistantScreen({ liveMode });
return null;
}
function SurfaceProbe(): JSX.Element {
return <span data-testid="surface">{useAssistantSurface() ?? 'none'}</span>;
}
function LogsScreen({
liveMode,
mounted = true,
}: {
liveMode: boolean;
mounted?: boolean;
}): JSX.Element {
return (
<>
{mounted && <LiveLogs liveMode={liveMode} />}
<SurfaceProbe />
</>
);
}
describe('useAssistantSurface', () => {
it('follows live mode on the logs explorer, and drops it when the screen goes', () => {
const { rerender } = render(<LogsScreen liveMode />, undefined, {
initialRoute: '/logs/logs-explorer',
});
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.loglive,
);
rerender(<LogsScreen liveMode={false} />);
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.logexplorer,
);
rerender(<LogsScreen liveMode />);
rerender(<LogsScreen liveMode mounted={false} />);
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.logexplorer,
);
});
it('reads the URL query', () => {
render(<SurfaceProbe />, undefined, {
initialRoute: '/alerts?tab=TriggeredAlerts',
});
expect(screen.getByTestId('surface')).toHaveTextContent(
KnownAssistantSurfaceDTO.alerttriggered,
);
});
});

View File

@@ -0,0 +1,12 @@
import { useEffect } from 'react';
import type { AssistantScreenState } from '../types';
import { setAssistantScreen } from '../store/useAssistantPageStore';
/** Publishes what the screen knows about itself, and clears it when the screen goes. */
export function useAssistantScreen({ liveMode }: AssistantScreenState): void {
useEffect(() => {
setAssistantScreen({ liveMode });
return (): void => setAssistantScreen({ liveMode: undefined });
}, [liveMode]);
}

View File

@@ -0,0 +1,32 @@
import { useEffect, useId, useLayoutEffect, useRef } from 'react';
import type { AssistantContextGetter } from '../types';
import {
focusAssistantContext,
registerAssistantContext,
} from '../store/usePageContextStore';
interface UseAssistantStateOptions {
/** The user is working in the path this component adds, such as an open panel. */
focused?: boolean;
}
/** Adds this component's part to the page context while it is mounted; `getter` runs only on Send. */
export function useAssistantState(
getter: AssistantContextGetter,
{ focused = false }: UseAssistantStateOptions = {},
): void {
const id = useId();
const getterRef = useRef(getter);
useLayoutEffect(() => {
getterRef.current = getter;
});
useEffect(() => registerAssistantContext(id, () => getterRef.current()), [id]);
useEffect(
() => (focused ? focusAssistantContext(id) : undefined),
[id, focused],
);
}

View File

@@ -0,0 +1,16 @@
import { useMemo } from 'react';
import type { KnownAssistantSurfaceDTO } from '@signozhq/noz-client';
import { useAppLocation } from 'lib/router/useAppLocation';
import { getSurface } from '../utils/routeSurfaces';
import { useAssistantPageStore } from '../store/useAssistantPageStore';
/** The surface of the screen the user is on; `null` sends no page. */
export function useAssistantSurface(): KnownAssistantSurfaceDTO | null {
const { pathname, search } = useAppLocation();
const screen = useAssistantPageStore((state) => state.screen);
return useMemo(
() => getSurface({ pathname, search }, screen),
[pathname, search, screen],
);
}

View File

@@ -0,0 +1,259 @@
import {
type ContextNodeDTO,
type DataViewDTO,
DataShapeDTO,
type PageContextDTO,
type SeriesPointSelectionDTO,
StreamStateDTO,
type TimeRangeDTO,
} from '@signozhq/noz-client';
import type { AssistantContextGetter } from '../../types';
import {
focusAssistantContext,
registerAssistantContext,
snapshotAssistantContext,
} from '../usePageContextStore';
const SURFACE = 'dashboard.detail';
const TIME: TimeRangeDTO = {
mode: 'range',
startMs: 1795946400000,
endMs: 1795950000000,
preset: '1h',
};
const POINT: SeriesPointSelectionDTO = {
kind: 'series_point',
atMs: 1795948200000,
value: 812,
};
const cleanups: (() => void)[] = [];
function register(id: string, getter: AssistantContextGetter): () => void {
const cleanup = registerAssistantContext(id, getter);
cleanups.push(cleanup);
return cleanup;
}
function focus(id: string): () => void {
const cleanup = focusAssistantContext(id);
cleanups.push(cleanup);
return cleanup;
}
function snapshot(activeViewPath: string[] = []): PageContextDTO {
const page = snapshotAssistantContext({
surface: SURFACE,
activeViewPath,
});
if (!page) {
throw new Error('expected a page');
}
return page;
}
function panelNode(id: string, view?: Partial<DataViewDTO>): ContextNodeDTO {
return {
target: { kind: 'dashboard_panel', resourceId: id },
state: view
? {
dataViews: [
{ key: 'panel_chart', shape: DataShapeDTO.timeseries, ...view },
],
}
: undefined,
};
}
afterEach(() => {
cleanups.splice(0).forEach((cleanup) => cleanup());
});
describe('usePageContextStore', () => {
it('returns no page without a surface, and the surface alone when nothing is registered', () => {
expect(
snapshotAssistantContext({ surface: null, activeViewPath: [] }),
).toBeNull();
expect(snapshot()).toStrictEqual({ surface: SURFACE });
});
it('merges every owner into one page state, later owners winning by name and key', () => {
register('dashboard', () => ({
root: { kind: 'dashboard', resourceId: 'd1', resourceName: null },
state: {
variableValues: [{ name: 'env', value: 'prod' }],
dataViews: [{ key: 'panel_chart', shape: DataShapeDTO.value }],
},
}));
register('time', () => ({ state: { time: TIME } }));
register('variables', () => ({
state: {
variableValues: [
{ name: 'env', value: 'staging' },
{ name: 'service', value: ['cart'] },
],
dataViews: [{ key: 'panel_chart', shape: DataShapeDTO.timeseries }],
},
}));
expect(snapshot(['overview'])).toStrictEqual({
surface: SURFACE,
root: { kind: 'dashboard', resourceId: 'd1' },
state: {
time: TIME,
activeViewPath: ['overview'],
variableValues: [
{ name: 'env', value: 'staging' },
{ name: 'service', value: ['cart'] },
],
dataViews: [{ key: 'panel_chart', shape: DataShapeDTO.timeseries }],
},
});
});
it("marks only the focused owner's path, puts it first, and clears focus when that owner leaves", () => {
register('panel-a', () => ({ path: [panelNode('a')] }));
const leaveB = register('panel-b', () => ({ path: [panelNode('b')] }));
focus('panel-b');
expect(snapshot().activePaths).toStrictEqual([
{
focused: true,
nodes: [{ target: { kind: 'dashboard_panel', resourceId: 'b' } }],
},
{ nodes: [{ target: { kind: 'dashboard_panel', resourceId: 'a' } }] },
]);
leaveB();
register('panel-b', () => ({ path: [panelNode('b')] }));
expect(snapshot().activePaths?.some((path) => path.focused)).toBe(false);
});
it('clears focus only from the owner that still holds it', () => {
register('panel-a', () => ({ path: [panelNode('a')] }));
register('panel-b', () => ({ path: [panelNode('b')] }));
const blurA = focus('panel-a');
const blurB = focus('panel-b');
blurA();
expect(snapshot().activePaths?.[0]).toStrictEqual({
focused: true,
nodes: [{ target: { kind: 'dashboard_panel', resourceId: 'b' } }],
});
blurB();
expect(snapshot().activePaths?.some((path) => path.focused)).toBe(false);
});
it('keeps selections only on the one focused view of a focused path', () => {
register('pinned', () => ({
path: [panelNode('a', { focused: true, selections: [POINT] })],
}));
register('open', () => ({
path: [panelNode('b', { focused: true, selections: [POINT] })],
}));
register('page', () => ({
state: {
dataViews: [
{ key: 'first', shape: DataShapeDTO.table, focused: true },
{ key: 'second', shape: DataShapeDTO.table, focused: true },
],
},
}));
focus('open');
const page = snapshot();
expect(page.activePaths?.map((path) => path.nodes[0].state)).toStrictEqual([
{
dataViews: [
{
key: 'panel_chart',
shape: DataShapeDTO.timeseries,
focused: true,
selections: [POINT],
},
],
},
{
dataViews: [
{ key: 'panel_chart', shape: DataShapeDTO.timeseries, focused: true },
],
},
]);
expect(page.state?.dataViews).toStrictEqual([
{ key: 'first', shape: DataShapeDTO.table, focused: true },
{ key: 'second', shape: DataShapeDTO.table },
]);
});
it('never lets an old cleanup remove a newer getter under the same id', () => {
const leaveStale = register('picker', () => ({ state: { time: TIME } }));
register('picker', () => ({ state: { stream: StreamStateDTO.active } }));
leaveStale();
expect(snapshot().state).toStrictEqual({ stream: StreamStateDTO.active });
});
it('leaves out a getter that throws', () => {
register('broken', () => {
throw new Error('unmounted store');
});
register('time', () => ({ state: { time: TIME } }));
expect(snapshot()).toStrictEqual({ surface: SURFACE, state: { time: TIME } });
});
it('drops every time on a streaming state', () => {
register('picker', () => ({ state: { time: TIME } }));
register('live', () => ({
state: {
stream: StreamStateDTO.active,
dataViews: [{ key: 'live_log_list', shape: DataShapeDTO.list, time: TIME }],
},
}));
expect(snapshot().state).toStrictEqual({
stream: StreamStateDTO.active,
dataViews: [{ key: 'live_log_list', shape: DataShapeDTO.list }],
});
});
it('keeps lists within the backend limits', () => {
register('variables', () => ({
state: {
variableValues: Array.from({ length: 40 }, (_, i) => ({
name: `v${i}`,
value: i,
})),
},
}));
register('too-deep', () => ({
path: Array.from({ length: 7 }, (_, i) => panelNode(`deep-${i}`)),
}));
['a', 'b', 'c', 'd', 'e'].forEach((id) =>
register(`panel-${id}`, () => ({ path: [panelNode(id)] })),
);
register('panel-a-again', () => ({ path: [panelNode('a')] }));
focus('panel-e');
const page = snapshot(['a', 'b', 'c', 'd', 'e', 'f', 'g']);
expect(page.state?.variableValues).toHaveLength(32);
expect(page.state?.activeViewPath).toStrictEqual([
'a',
'b',
'c',
'd',
'e',
'f',
]);
expect(
page.activePaths?.map((path) => path.nodes[0].target.resourceId),
).toStrictEqual(['e', 'a', 'b', 'c']);
});
});

View File

@@ -0,0 +1,25 @@
import { create } from 'zustand';
import type { AssistantScreenState } from '../types';
interface AssistantPageState {
/** Selected tabs on the screen, outermost first. */
activeViewPath: string[];
screen: AssistantScreenState;
}
export const useAssistantPageStore = create<AssistantPageState>()(() => ({
activeViewPath: [],
screen: {},
}));
export function setAssistantActiveViewPath(activeViewPath: string[]): void {
useAssistantPageStore.setState({ activeViewPath });
}
/** Merges into the screen state; a field set to `undefined` is cleared. */
export function setAssistantScreen(screen: AssistantScreenState): void {
useAssistantPageStore.setState((state) => ({
screen: { ...state.screen, ...screen },
}));
}

View File

@@ -0,0 +1,77 @@
import type { PageContextDTO } from '@signozhq/noz-client';
import { create } from 'zustand';
import { buildPageContext } from '../utils/buildPageContext';
import type {
AssistantContextGetter,
AssistantPageInput,
RegisteredPart,
} from '../types';
interface AssistantContextState {
/** The mounted owners' getters, in the order they registered; read only on Send. */
getters: Map<string, AssistantContextGetter>;
/** The owner whose path the user is working in. */
focusedId: string | null;
}
export const usePageContextStore = create<AssistantContextState>()(() => ({
getters: new Map(),
focusedId: null,
}));
/** Returns the cleanup; it removes only this getter, never a later one under the same id. */
export function registerAssistantContext(
id: string,
getter: AssistantContextGetter,
): () => void {
usePageContextStore.setState((state) => ({
getters: new Map(state.getters).set(id, getter),
}));
return (): void => {
usePageContextStore.setState((state) => {
if (state.getters.get(id) !== getter) {
return state;
}
const getters = new Map(state.getters);
getters.delete(id);
return {
getters,
focusedId: state.focusedId === id ? null : state.focusedId,
};
});
};
}
/** Marks the path `id` adds as the one the user is working in; the cleanup clears it only while `id` holds it. */
export function focusAssistantContext(id: string): () => void {
usePageContextStore.setState({ focusedId: id });
return (): void => {
usePageContextStore.setState((state) =>
state.focusedId === id ? { focusedId: null } : state,
);
};
}
/** The page Send carries: every registered getter, read now. */
export function snapshotAssistantContext({
surface,
activeViewPath,
}: AssistantPageInput): PageContextDTO | null {
if (!surface) {
return null;
}
const { getters, focusedId } = usePageContextStore.getState();
const parts: RegisteredPart[] = [];
getters.forEach((getter, id) => {
try {
const part = getter();
if (part) {
parts.push({ id, part });
}
} catch {
// A broken getter leaves its part out; the message still sends.
}
});
return buildPageContext({ surface, activeViewPath, parts, focusedId });
}

View File

@@ -0,0 +1,42 @@
import type {
ActivePathDTO,
ContextStateDTO,
ContextTargetRefDTO,
} from '@signozhq/noz-client';
import type ROUTES from 'constants/routes';
/** Page state one owner adds; `activeViewPath` comes from the page store instead. */
export type AssistantPartState = Omit<ContextStateDTO, 'activeViewPath'>;
/** What one mounted owner adds to the page context when the user presses Send. */
export interface AssistantContextPart {
root?: ContextTargetRefDTO;
state?: AssistantPartState;
/** One opened thing, as a chain of nodes below `root`, outermost first. */
path?: ActivePathDTO['nodes'];
}
export type AssistantContextGetter = () => AssistantContextPart | null;
export interface RegisteredPart {
id: string;
part: AssistantContextPart;
}
export interface AssistantPageInput {
surface: string | null;
activeViewPath: string[];
}
export type RouteKey = keyof typeof ROUTES;
export interface SurfaceLocation {
pathname: string;
search: string;
}
/** What a screen knows about itself that the URL doesn't carry. */
export interface AssistantScreenState {
/** The logs explorer is streaming live logs. */
liveMode?: boolean;
}

View File

@@ -0,0 +1,59 @@
import { KnownAssistantSurfaceDTO as Surface } from '@signozhq/noz-client';
import routes, { LIST_LICENSES, SUPPORT_ROUTE } from 'AppRoutes/routes';
import { ROUTE_SURFACES } from '../../constants';
import { findRouteKey, getSurface, URL_SURFACES } from '../routeSurfaces';
const TABLE = [...routes, LIST_LICENSES, SUPPORT_ROUTE];
describe('routeSurfaces', () => {
it('names a surface, or no page, once for exactly the routes in the table', () => {
const tableKeys = new Set(TABLE.map(({ key }) => key));
const mappedKeys = [
...Object.keys(ROUTE_SURFACES),
...Object.keys(URL_SURFACES),
];
expect(mappedKeys.sort()).toStrictEqual([...tableKeys].sort());
});
it('finds its own entry for every path in the table, and none outside it', () => {
const misses = TABLE.flatMap(({ key, path, nested }) =>
(Array.isArray(path) ? path : [path])
.map((pattern) => pattern.replace(/:[^/]+/g, 'id'))
.flatMap((pathname) =>
nested ? [pathname, `${pathname}/sub`] : [pathname],
)
.filter((pathname) => findRouteKey(pathname) !== key)
.map((pathname) => `${pathname} -> ${findRouteKey(pathname)}, not ${key}`),
);
expect(misses).toStrictEqual([]);
expect(findRouteKey('/')).toBeNull();
expect(findRouteKey('/not-a-route')).toBeNull();
});
it('reports live logs on no screen but the logs explorer', () => {
expect(
getSurface({ pathname: '/traces-explorer', search: '' }, { liveMode: true }),
).toBe(Surface.traceexplorer);
});
it.each([
['', Surface.alertrulelist],
['?tab=TriggeredAlerts', Surface.alerttriggered],
['?tab=Configuration', Surface.alertchannellist],
['?tab=Configuration&subTab=routing-policies', Surface.alertrouting],
['?tab=constructor', Surface.alertrulelist],
])('resolves the alerts list at "%s" to %s', (search, surface) => {
expect(getSurface({ pathname: '/alerts', search }, {})).toBe(surface);
});
it.each([
['/settings', Surface.settingsworkspace],
['/settings/roles/r1/edit', Surface.settingsroles],
['/settings/unknown', null],
])('resolves the settings page at %s to %s', (pathname, surface) => {
expect(getSurface({ pathname, search: '' }, {})).toBe(surface);
});
});

View File

@@ -0,0 +1,178 @@
import type {
ActivePathDTO,
ContextNodeDTO,
ContextStateDTO,
DataViewDTO,
PageContextDTO,
} from '@signozhq/noz-client';
import { isNil, omitBy } from 'lodash-es';
import {
MAX_DATA_VIEWS,
MAX_PATH_NODES,
MAX_PATHS,
MAX_SELECTIONS,
MAX_SETTINGS,
MAX_VARIABLES,
MAX_VIEW_PATH,
} from '../constants';
import type { AssistantPartState, RegisteredPart } from '../types';
interface BuildPageContextInput {
surface: string;
activeViewPath: string[];
parts: RegisteredPart[];
focusedId: string | null;
}
function compact<T extends object>(value: T): T {
return omitBy(value, isNil) as T;
}
/** `uniqBy`, but the last item per key wins; it keeps the first one's position. */
function uniqByLast<T>(items: T[], keyOf: (item: T) => string): T[] {
return [...new Map(items.map((item) => [keyOf(item), item])).values()];
}
function cleanViews(
views: DataViewDTO[],
allowSelections: boolean,
dropTime: boolean,
): DataViewDTO[] {
let hasFocus = false;
return uniqByLast(views, (view) => view.key)
.slice(0, MAX_DATA_VIEWS)
.map(({ focused, selections, time, ...view }) => {
const isFocused = focused === true && !hasFocus;
hasFocus ||= isFocused;
const keptSelections =
isFocused && allowSelections && selections?.length
? selections.slice(0, MAX_SELECTIONS)
: undefined;
return compact({
...view,
time: dropTime ? undefined : time,
focused: isFocused || undefined,
selections: keptSelections,
});
});
}
function cleanState(
state: ContextStateDTO | null | undefined,
allowSelections: boolean,
): ContextStateDTO | undefined {
if (!state) {
return undefined;
}
const { activeViewPath, variableValues, settings, dataViews, ...rest } = state;
// A live stream has no window, so any time on it or its views cuts the page.
const isStreaming = Boolean(rest.stream);
const cleaned = compact({
...rest,
time: isStreaming ? undefined : rest.time,
activeViewPath: activeViewPath?.length
? activeViewPath.slice(0, MAX_VIEW_PATH)
: undefined,
variableValues: variableValues?.length
? uniqByLast(variableValues, (v) => v.name).slice(0, MAX_VARIABLES)
: undefined,
settings: settings?.length
? uniqByLast(settings, (s) => s.name).slice(0, MAX_SETTINGS)
: undefined,
dataViews: dataViews?.length
? cleanViews(dataViews, allowSelections, isStreaming)
: undefined,
});
return Object.keys(cleaned).length ? cleaned : undefined;
}
function mergeStates(
states: (AssistantPartState | undefined)[],
activeViewPath: string[],
): ContextStateDTO {
return states.reduce<ContextStateDTO>(
(merged, state) => {
if (!state) {
return merged;
}
return {
...merged,
...compact(state),
activeViewPath,
variableValues: [
...(merged.variableValues ?? []),
...(state.variableValues ?? []),
],
settings: [...(merged.settings ?? []), ...(state.settings ?? [])],
dataViews: [...(merged.dataViews ?? []), ...(state.dataViews ?? [])],
};
},
{ activeViewPath },
);
}
function pathKey(nodes: ContextNodeDTO[]): string {
return JSON.stringify(
nodes.map(({ target }) => [target.kind, target.resourceId ?? null]),
);
}
function buildPaths(
parts: RegisteredPart[],
focusedId: string | null,
): ActivePathDTO[] {
const candidates = parts.flatMap(({ id, part }) =>
part.path?.length && part.path.length <= MAX_PATH_NODES
? [{ focused: id === focusedId, nodes: part.path }]
: [],
);
const seen = new Set<string>();
return [
...candidates.filter((path) => path.focused),
...candidates.filter((path) => !path.focused),
]
.filter(({ nodes }) => {
const key = pathKey(nodes);
const isNew = !seen.has(key);
seen.add(key);
return isNew;
})
.slice(0, MAX_PATHS)
.map(({ focused, nodes }) =>
compact({
focused: focused || undefined,
nodes: nodes.map((node) =>
compact({
target: compact(node.target),
state: cleanState(node.state, focused),
}),
),
}),
);
}
/** Merges every owner's part into one page, within the backend's list limits. */
export function buildPageContext({
surface,
activeViewPath,
parts,
focusedId,
}: BuildPageContextInput): PageContextDTO {
const rootOwner = [...parts].reverse().find(({ part }) => part.root);
const root = rootOwner?.part.root ? compact(rootOwner.part.root) : undefined;
const state = cleanState(
mergeStates(
parts.map(({ part }) => part.state),
activeViewPath,
),
true,
);
const paths = buildPaths(parts, focusedId);
return compact({
surface,
root,
state,
activePaths: paths.length ? paths : undefined,
});
}

View File

@@ -0,0 +1,66 @@
import { KnownAssistantSurfaceDTO as Surface } from '@signozhq/noz-client';
import routes, { LIST_LICENSES, SUPPORT_ROUTE } from 'AppRoutes/routes';
import { matchRoute } from 'lib/router/matchRoute';
import { AlertListTabs } from 'pages/AlertList/types';
import {
ALERT_SUB_TAB_SURFACES,
ALERT_TAB_SURFACES,
ROUTE_SURFACES,
SETTINGS_SURFACES,
} from '../constants';
import type { AssistantScreenState, RouteKey, SurfaceLocation } from '../types';
/** Mirrors the tab the alerts page shows for `tab` and `subTab`. */
function alertListSurface({ search }: SurfaceLocation): Surface {
const params = new URLSearchParams(search);
const tab = params.get('tab');
if (tab === AlertListTabs.CONFIGURATION) {
return (
ALERT_SUB_TAB_SURFACES.get(params.get('subTab')) ?? Surface.alertchannellist
);
}
return ALERT_TAB_SURFACES.get(tab) ?? Surface.alertrulelist;
}
function settingsSurface({ pathname }: SurfaceLocation): Surface | null {
const entry = SETTINGS_SURFACES.find(([pattern]) =>
matchRoute(pathname, pattern, { exact: true }),
);
return entry?.[1] ?? null;
}
/** Routes whose surface depends on more of the URL than the route itself. */
export const URL_SURFACES: Partial<
Record<RouteKey, (location: SurfaceLocation) => Surface | null>
> = {
LIST_ALL_ALERT: alertListSurface,
SETTINGS: settingsSurface,
};
const ROUTE_TABLE = [...routes, LIST_LICENSES, SUPPORT_ROUTE];
/** The route table entry the router renders at `pathname`; a nested entry also owns its sub-paths. */
export function findRouteKey(pathname: string): RouteKey | null {
const entry = ROUTE_TABLE.find(({ path, nested }) =>
(Array.isArray(path) ? path : [path]).some((pattern) =>
matchRoute(pathname, pattern, { exact: !nested }),
),
);
return entry?.key ?? null;
}
export function getSurface(
location: SurfaceLocation,
screen: AssistantScreenState,
): Surface | null {
const routeKey = findRouteKey(location.pathname);
if (!routeKey) {
return null;
}
if (routeKey === 'LOGS' && screen.liveMode) {
return Surface.loglive;
}
const fromUrl = URL_SURFACES[routeKey];
return fromUrl ? fromUrl(location) : (ROUTE_SURFACES[routeKey] ?? null);
}