diff --git a/.changeset/chart-explorer-ui-refresh.md b/.changeset/chart-explorer-ui-refresh.md
new file mode 100644
index 0000000000..c054b06b14
--- /dev/null
+++ b/.changeset/chart-explorer-ui-refresh.md
@@ -0,0 +1,20 @@
+---
+'@hyperdx/app': minor
+---
+
+feat: refresh the chart explorer and chart editor UI
+
+- The AI assistant is a sparkles button in the page header that opens a popover,
+ and its last change can be undone.
+- "Save to dashboard" is a labeled button, and explorer charts are named
+ automatically when saved.
+- The explorer has a sticky page header: mode switch and source on the left of
+ the first row with Save to dashboard and the AI assistant on the right; chart
+ type on the left of the second row with the time range, granularity and Run on
+ the right.
+- Chart type is an icon switcher that names the selected type, and the header is
+ the same in every mode.
+- Each series and formula sits in a card with the color the chart draws it in.
+- Display Settings opens in the editor's side panel next to the alert panel, not
+ in a drawer.
+- Series display settings open in a popover.
diff --git a/.claude/skills/page-layout/SKILL.md b/.claude/skills/page-layout/SKILL.md
index 2a4577cc77..d0a47aa6fd 100644
--- a/.claude/skills/page-layout/SKILL.md
+++ b/.claude/skills/page-layout/SKILL.md
@@ -1,30 +1,50 @@
---
name: page-layout
-description: Add or update app page headers and layout using PageHeader and PageLayout. Use when creating a new page, fixing inconsistent headers, or migrating Service Map / Kubernetes / dashboard pages to the shared layout.
+description:
+ Add or update app page headers and layout using PageHeader and PageLayout. Use
+ when creating a new page, fixing inconsistent headers, or migrating Service
+ Map / Kubernetes / dashboard pages to the shared layout.
---
# Page layout and headers
-Read **`agent_docs/page_layout.md`** before changing any page shell. It is the source of truth for API, examples, and migration steps.
+Read **`agent_docs/page_layout.md`** before changing any page shell. It is the
+source of truth for API, examples, and migration steps.
## Quick rules
-1. **Default for new pages**: `PageLayout` with `title`, optional `leading` / `actions`, and `content` — only when the sticky bar is **text-only** (no inputs in that bar).
-2. **Sticky bar contains inputs** (source pickers, SQL/search, sliders, time range, Run, etc.): **do not** use `PageHeader` / `PageLayout` **`title`**. The sticky row is for controls only. Put **where you are** in the **`breadcrumbs` prop** (renders **inside the sticky `PageHeader`**, above the toolbar) when the page lives under a hierarchy (e.g. `Dashboards` → `Kubernetes`); otherwise you may omit `breadcrumbs` and rely on `
`, the sidebar active item, and the empty state copy.
-3. **Never** duplicate location: do not set `title="Kubernetes Dashboard"` **and** breadcrumbs that repeat the same page name.
+1. **Default for new pages**: `PageLayout` with `title`, optional `leading` /
+ `actions`, and `content` — only when the sticky bar is **text-only** (no
+ inputs in that bar).
+2. **Sticky bar contains inputs** (source pickers, SQL/search, sliders, time
+ range, Run, etc.): **do not** use `PageHeader` / `PageLayout` **`title`**.
+ The sticky row is for controls only. Put **where you are** in the
+ **`breadcrumbs` prop** (renders **inside the sticky `PageHeader`**, above the
+ toolbar) when the page lives under a hierarchy (e.g. `Dashboards` →
+ `Kubernetes`); otherwise you may omit `breadcrumbs` and rely on
+ ``, the sidebar active item, and the empty state copy.
+3. **Never** duplicate location: do not set `title="Kubernetes Dashboard"`
+ **and** breadcrumbs that repeat the same page name.
4. **Never** use `` as the page title in the body.
-5. **Global controls** (time range, Run, Save, sampling) go in `actions`, right-aligned. **Context** pickers go in `leading` (no `title` when those slots are used for inputs). **Breadcrumbs** use the `breadcrumbs` prop so they stay in the sticky header, not in `content`.
+5. **Global controls** (time range, Run, Save, sampling) go in `actions`,
+ right-aligned. **Context** pickers go in `leading` (no `title` when those
+ slots are used for inputs). **Breadcrumbs** use the `breadcrumbs` prop so
+ they stay in the sticky header, not in `content`.
6. **Full-height tools** (maps, large charts): `fillViewport` on `PageLayout`.
-7. **Search / Chart Explorer**: keep bespoke toolbars unless the task is explicitly to redesign them.
+7. **Search**: keep the bespoke toolbar unless the task is explicitly to
+ redesign it. **Chart Explorer** uses a custom `PageHeader` fed by
+ `EditTimeChartForm`'s `toolbarTargets`; see `agent_docs/page_layout.md`.
## Workflow
1. Read `agent_docs/page_layout.md`.
-2. Open a similar page already on `PageHeader` / `PageLayout` (e.g. `AlertsPage.tsx`, `DBServiceMapPage.tsx`, `KubernetesDashboardPage.tsx`).
+2. Open a similar page already on `PageHeader` / `PageLayout` (e.g.
+ `AlertsPage.tsx`, `DBServiceMapPage.tsx`, `KubernetesDashboardPage.tsx`).
3. Implement using `@/components/PageLayout` or `@/components/PageHeader`.
4. Preserve or add `data-testid` on the page root for E2E tests.
5. Run `yarn lint:fix` in the repo root when done.
-6. If the page has E2E coverage, run the relevant spec under `packages/app/tests/e2e/`.
+6. If the page has E2E coverage, run the relevant spec under
+ `packages/app/tests/e2e/`.
## Imports
@@ -35,10 +55,10 @@ import { PageLayout } from '@/components/PageLayout';
## Reference implementations
-| Page | File | Pattern |
-|------|------|---------|
-| List page | `AlertsPage.tsx` | `PageHeader` + `title` + `Container` (no inputs in header) |
-| Tool page with inputs + hierarchy | `KubernetesDashboardPage.tsx`, `ClickhousePage.tsx` | `PageLayout` **without** `title`; **`breadcrumbs`** + `leading` + `actions` in one sticky header |
-| Tool page (top-level) | `DBServiceMapPage.tsx` | `PageLayout` **without** `title`; `leading` / `actions` only; no duplicate breadcrumb unless you add a real hierarchy |
-| Custom toolbar | `SessionsPage.tsx` | `PageLayout` + `header` = custom `PageHeader` `children` with `growing` (single-row inputs, no `title`) |
-| Custom title | `TeamPage.tsx` | `PageHeader` with `children` only |
+| Page | File | Pattern |
+| --------------------------------- | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
+| List page | `AlertsPage.tsx` | `PageHeader` + `title` + `Container` (no inputs in header) |
+| Tool page with inputs + hierarchy | `KubernetesDashboardPage.tsx`, `ClickhousePage.tsx` | `PageLayout` **without** `title`; **`breadcrumbs`** + `leading` + `actions` in one sticky header |
+| Tool page (top-level) | `DBServiceMapPage.tsx` | `PageLayout` **without** `title`; `leading` / `actions` only; no duplicate breadcrumb unless you add a real hierarchy |
+| Custom toolbar | `SessionsPage.tsx` | `PageLayout` + `header` = custom `PageHeader` `children` with `growing` (single-row inputs, no `title`) |
+| Custom title | `TeamPage.tsx` | `PageHeader` with `children` only |
diff --git a/agent_docs/page_layout.md b/agent_docs/page_layout.md
index cde50f3c04..59b690c48c 100644
--- a/agent_docs/page_layout.md
+++ b/agent_docs/page_layout.md
@@ -1,15 +1,19 @@
# Page layout and headers
-ClickStack app pages share a sticky top header bar and a scrollable content region below it. Use the shared layout primitives so titles, controls, and spacing stay consistent across Search, list pages, and tool pages (Service Map, Kubernetes, Chart Explorer).
+ClickStack app pages share a sticky top header bar and a scrollable content
+region below it. Use the shared layout primitives so titles, controls, and
+spacing stay consistent across Search, list pages, and tool pages (Service Map,
+Kubernetes, Chart Explorer).
## Components
-| Component | Path | Use when |
-|-----------|------|----------|
-| `PageHeader` | `packages/app/src/components/PageHeader.tsx` | You only need the header bar (page already has its own content wrapper). |
+| Component | Path | Use when |
+| ------------ | -------------------------------------------- | --------------------------------------------------------------------------------- |
+| `PageHeader` | `packages/app/src/components/PageHeader.tsx` | You only need the header bar (page already has its own content wrapper). |
| `PageLayout` | `packages/app/src/components/PageLayout.tsx` | You want header + flex content column in one wrapper (recommended for new pages). |
-Both live next to `withAppNav` in `packages/app/src/layout.tsx`, which wraps pages with the left nav and scroll container.
+Both live next to `withAppNav` in `packages/app/src/layout.tsx`, which wraps
+pages with the left nav and scroll container.
## PageHeader API
@@ -28,16 +32,21 @@ Both live next to `withAppNav` in `packages/app/src/layout.tsx`, which wraps pag
```
-| Prop | Purpose |
-|------|---------|
-| `title` | Plain page title (`
`). **Use only when the sticky bar has no inputs** (list/settings pages). If the bar has pickers, search, sliders, or Run, omit `title` and use **`breadcrumbs`** (or rely on nav + document title only). |
-| `breadcrumbs` | Location trail **inside the sticky header**, rendered above the toolbar when `leading` / `actions` are set. Use Mantine `Breadcrumbs` (e.g. `Dashboards` → current page). Do not duplicate the same text as `title`. |
-| `leading` | Left cluster: source picker, badges, or other controls. When inputs are present, **do not** pair with `title` for the same page name. |
-| `actions` | Right-aligned cluster: time range, Run/Save, sampling, refresh. |
-| `children` | Full custom header when slots are not enough. Do not combine with `title` / `leading` / `actions` / `breadcrumbs` unless you use the breadcrumbs-only branch. |
-| `growing` | Opt in to block padding that only shows once the toolbar outgrows `min-height`. Sessions uses this for its multi-line search; title-only pages omit it. |
-
-Header styling is defined in `PageHeader.module.scss`: sticky top, bottom border, horizontal padding `var(--mantine-spacing-sm)` (same as Search `px="sm"`). Single-row headers keep `min-height: 60px`; stacked header (breadcrumbs + toolbar) grows with content. Pass `growing` when the toolbar can outgrow that min-height (Sessions' multi-line search) so block padding appears only once the row is taller than the bar.
+| Prop | Purpose |
+| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `title` | Plain page title (`
`). **Use only when the sticky bar has no inputs** (list/settings pages). If the bar has pickers, search, sliders, or Run, omit `title` and use **`breadcrumbs`** (or rely on nav + document title only). |
+| `breadcrumbs` | Location trail **inside the sticky header**, rendered above the toolbar when `leading` / `actions` are set. Use Mantine `Breadcrumbs` (e.g. `Dashboards` → current page). Do not duplicate the same text as `title`. |
+| `leading` | Left cluster: source picker, badges, or other controls. When inputs are present, **do not** pair with `title` for the same page name. |
+| `actions` | Right-aligned cluster: time range, Run/Save, sampling, refresh. |
+| `children` | Full custom header when slots are not enough. Do not combine with `title` / `leading` / `actions` / `breadcrumbs` unless you use the breadcrumbs-only branch. |
+| `growing` | Opt in to block padding that only shows once the toolbar outgrows `min-height`. Sessions uses this for its multi-line search; title-only pages omit it. |
+
+Header styling is defined in `PageHeader.module.scss`: sticky top, bottom
+border, horizontal padding `var(--mantine-spacing-sm)` (same as Search
+`px="sm"`). Single-row headers keep `min-height: 60px`; stacked header
+(breadcrumbs + toolbar) grows with content. Pass `growing` when the toolbar can
+outgrow that min-height (Sessions' multi-line search) so block padding appears
+only once the row is taller than the bar.
## PageLayout API
@@ -52,36 +61,55 @@ Header styling is defined in `PageHeader.module.scss`: sticky top, bottom border
/>
```
-| Prop | Purpose |
-|------|---------|
-| `title`, `leading`, `actions`, `breadcrumbs`, `children` | Forwarded to `PageHeader` (same rules as above). |
-| `header` | Replace the default `PageHeader` entirely. |
-| `content` | Main page body below the header (required). |
-| `fillViewport` | Set `height: 100vh` on the page root for full-height canvases (maps, charts). |
-| `contentClassName` | Extra class on the content region (e.g. padding). |
+| Prop | Purpose |
+| -------------------------------------------------------- | ----------------------------------------------------------------------------- |
+| `title`, `leading`, `actions`, `breadcrumbs`, `children` | Forwarded to `PageHeader` (same rules as above). |
+| `header` | Replace the default `PageHeader` entirely. |
+| `content` | Main page body below the header (required). |
+| `fillViewport` | Set `height: 100vh` on the page root for full-height canvases (maps, charts). |
+| `contentClassName` | Extra class on the content region (e.g. padding). |
## When to use which pattern
### List / settings pages (Alerts, Dashboards, Saved Searches, Team)
- Use `PageHeader` at the top of the page.
-- Put filters, tables, and tabs in a `Container` below the header (see `AlertsPage.tsx`, `DashboardsListPage.tsx`).
-- Simple title-only pages: `` — **only** when the header row has **no** inputs.
+- Put filters, tables, and tabs in a `Container` below the header (see
+ `AlertsPage.tsx`, `DashboardsListPage.tsx`).
+- Simple title-only pages: `` — **only** when
+ the header row has **no** inputs.
### Tool / canvas pages (Service Map, Kubernetes, Clickhouse, Chart Explorer)
-- Prefer `PageLayout` with `fillViewport` when the main UI should fill remaining height.
-- Put **global** controls in `actions` (time picker, sampling, Run)—not inside the canvas.
+- Prefer `PageLayout` with `fillViewport` when the main UI should fill remaining
+ height.
+- Put **global** controls in `actions` (time picker, sampling, Run)—not inside
+ the canvas.
- Put **context** controls in `leading` (source picker, environment).
-- **If the sticky header row includes any inputs** (selectors, sliders, search, time range, Run): **omit `title`**. Express location with the **`breadcrumbs` prop** on `PageLayout` / `PageHeader` so the trail stays **inside the sticky header** above the toolbar (see `KubernetesDashboardPage.tsx`). Do **not** repeat the same label as both `title` and the last breadcrumb. Top-level tools (e.g. Service Map) may omit `breadcrumbs` if `` and the sidebar active state are enough.
+- **If the sticky header row includes any inputs** (selectors, sliders, search,
+ time range, Run): **omit `title`**. Express location with the **`breadcrumbs`
+ prop** on `PageLayout` / `PageHeader` so the trail stays **inside the sticky
+ header** above the toolbar (see `KubernetesDashboardPage.tsx`). Do **not**
+ repeat the same label as both `title` and the last breadcrumb. Top-level tools
+ (e.g. Service Map) may omit `breadcrumbs` if `` and the sidebar
+ active state are enough.
### Search and Chart Explorer (complex query chrome)
-These pages use bespoke multi-row toolbars instead of a single title row. That is intentional until those flows are redesigned. Do not force a `title` on them; if you add a header row, use `PageHeader` `children` or a dedicated toolbar component, not ad-hoc `Text size="xl"` in the body.
+Search uses a bespoke multi-row toolbar instead of a single title row. That is
+intentional until the flow is redesigned. Chart Explorer uses a custom
+`PageHeader` (`DBChartPage.tsx`): the form portals its mode and source controls
+and its time range, granularity and Run controls into header slots
+(`toolbarTargets` on `EditTimeChartForm`), and keeps them inline wherever the
+form is embedded (tile editor, inline-alert editor). Do not force a `title` on
+either; if you add a header row, use `PageHeader` `children` or a dedicated
+toolbar component, not ad-hoc `Text size="xl"` in the body.
### Client Sessions (query + list)
-Sessions keeps a **single-row** query toolbar (source, where filter, time range, Run). Put the full toolbar in a custom `PageHeader` via `PageLayout` `header` — do not split controls across `title` / `leading` / `actions` / `content`.
+Sessions keeps a **single-row** query toolbar (source, where filter, time range,
+Run). Put the full toolbar in a custom `PageHeader` via `PageLayout` `header` —
+do not split controls across `title` / `leading` / `actions` / `content`.
## Do / don't
@@ -116,10 +144,13 @@ Sessions keeps a **single-row** query toolbar (source, where filter, time range,
## Migrating an existing page
-1. Replace `Text size="xl"` title + `Group justify="space-between"` with `PageLayout` or `PageHeader` slots.
+1. Replace `Text size="xl"` title + `Group justify="space-between"` with
+ `PageLayout` or `PageHeader` slots.
2. Move time picker and primary actions to `actions`.
3. Move source pickers and badges to `leading`.
-4. If the sticky bar has inputs, **do not** set `title`; pass **`breadcrumbs`** on `PageLayout` when the route has a hierarchy (breadcrumbs render inside the sticky `PageHeader`, not in `content`).
+4. If the sticky bar has inputs, **do not** set `title`; pass **`breadcrumbs`**
+ on `PageLayout` when the route has a hierarchy (breadcrumbs render inside the
+ sticky `PageHeader`, not in `content`).
5. Keep `data-testid` on `PageLayout` / page root for E2E tests.
6. Run affected Playwright tests (`packages/app/tests/e2e/`).
@@ -127,25 +158,44 @@ Sessions keeps a **single-row** query toolbar (source, where filter, time range,
- Alerts, Dashboards, Saved Searches — `PageHeader` with `title`
- Team — custom `PageHeader` `children` (editable name)
-- Service Map — `PageLayout` with `fillViewport`, `leading` / `actions` only (no `title`; top-level tool)
-- Kubernetes Dashboard, Clickhouse Dashboard — `PageLayout` with `breadcrumbs`, `leading`, `actions`, `padded` (no `title`)
-- Client Sessions — `PageLayout` with custom `PageHeader` containing the full single-row query toolbar
+- Service Map — `PageLayout` with `fillViewport`, `leading` / `actions` only (no
+ `title`; top-level tool)
+- Kubernetes Dashboard, Clickhouse Dashboard — `PageLayout` with `breadcrumbs`,
+ `leading`, `actions`, `padded` (no `title`)
+- Client Sessions — `PageLayout` with custom `PageHeader` containing the full
+ single-row query toolbar
## Compact viewports
-A viewport under 900px is compact. `useCompactViewport` (`packages/app/src/components/CompactViewport/useCompactViewport.ts`) is the cutoff, and the nav collapses on the same width. Pages that switch layout use this hook.
+A viewport under 900px is compact. `useCompactViewport`
+(`packages/app/src/components/CompactViewport/useCompactViewport.ts`) is the
+cutoff, and the nav collapses on the same width. Pages that switch layout use
+this hook.
-A page that is a side panel plus a main pane uses `ResponsiveSidePanel` (`packages/app/src/components/CompactViewport/ResponsiveSidePanel.tsx`):
+A page that is a side panel plus a main pane uses `ResponsiveSidePanel`
+(`packages/app/src/components/CompactViewport/ResponsiveSidePanel.tsx`):
- Wide: the panel sits beside the main pane.
-- Compact: the main pane uses the full width. The panel opens in a drawer and does not take horizontal space. Pass a `title`; the drawer has no default. The panel stays unmounted until the first open, then stays mounted so closing the drawer does not drop its state.
+- Compact: the main pane uses the full width. The panel opens in a drawer and
+ does not take horizontal space. Pass a `title`; the drawer has no default. The
+ panel stays unmounted until the first open, then stays mounted so closing the
+ drawer does not drop its state.
-The caller owns whether the panel is open. Keep that state separate from any desktop collapse preference stored in localStorage. A phone session that wrote the desktop preference would hide the panel the next time the same browser opened the page on a desktop.
+The caller owns whether the panel is open. Keep that state separate from any
+desktop collapse preference stored in localStorage. A phone session that wrote
+the desktop preference would hide the panel the next time the same browser
+opened the page on a desktop.
-Give the main pane `flex: 1` and `min-height: 0` inside a full-height column, so it keeps the space under the toolbar and scrolls inside itself. A hard `min-width` on the panel inside `overflow: hidden` clips the main pane on a phone.
+Give the main pane `flex: 1` and `min-height: 0` inside a full-height column, so
+it keeps the space under the toolbar and scrolls inside itself. A hard
+`min-width` on the panel inside `overflow: hidden` clips the main pane on a
+phone.
-Search is the first page on this pattern. Other side-panel pages should adopt it the same way instead of a one-off media query.
+Search is the first page on this pattern. Other side-panel pages should adopt it
+the same way instead of a one-off media query.
## Knip
-`packages/app` Knip entry roots are `pages/`, `scripts/`, and e2e tests. After you add or move a `PageLayout` import, run `yarn knip` from the repo root (or `yarn knip` in `packages/app` if configured) so new consumers stay wired.
+`packages/app` Knip entry roots are `pages/`, `scripts/`, and e2e tests. After
+you add or move a `PageLayout` import, run `yarn knip` from the repo root (or
+`yarn knip` in `packages/app` if configured) so new consumers stay wired.
diff --git a/packages/app/src/ChartUtils.tsx b/packages/app/src/ChartUtils.tsx
index f889fc753e..ca9cbae90c 100644
--- a/packages/app/src/ChartUtils.tsx
+++ b/packages/app/src/ChartUtils.tsx
@@ -640,6 +640,14 @@ export interface LineData {
isDashed?: boolean;
}
+/** The colors a time chart assigned, keyed by the value column they plot. */
+export interface TimeChartSeriesColors {
+ valueColumns: string[];
+ colorByColumn: Record;
+ /** Grouped charts color per group, so a column has no single color. */
+ isGrouped: boolean;
+}
+
interface LineDataWithOptionalColor extends Omit {
color?: string;
}
diff --git a/packages/app/src/DBChartPage.tsx b/packages/app/src/DBChartPage.tsx
index 186499a751..2dca9e77f9 100644
--- a/packages/app/src/DBChartPage.tsx
+++ b/packages/app/src/DBChartPage.tsx
@@ -3,210 +3,37 @@ import dynamic from 'next/dynamic';
import Head from 'next/head';
import Link from 'next/link';
import { parseAsJson, parseAsString, useQueryState } from 'nuqs';
-import { useForm } from 'react-hook-form';
import { useHotkeys } from 'react-hotkeys-hook';
-import { Badge, Separator } from '@clickhouse/click-ui';
-import { SavedChartConfig, SourceKind } from '@hyperdx/common-utils/dist/types';
-import {
- Alert,
- Anchor,
- Box,
- Button,
- Collapse,
- Divider,
- Group,
- Loader,
- Skeleton,
- Stack,
- Text,
-} from '@mantine/core';
+import { SavedChartConfig } from '@hyperdx/common-utils/dist/types';
+import { Anchor, Flex, Skeleton, Stack } from '@mantine/core';
import { notifications } from '@mantine/notifications';
-import {
- IconChevronDown,
- IconChevronUp,
- IconInfoCircle,
-} from '@tabler/icons-react';
import { useQueryClient } from '@tanstack/react-query';
import api from '@/api';
-import { useBrandDisplayName, usePageTitle } from '@/brand';
+import { usePageTitle } from '@/brand';
import { DEFAULT_CHART_CONFIG } from '@/ChartUtils';
+import {
+ ChartAssistantPopover,
+ ChartAssistantUnavailableAlert,
+} from '@/components/ChartAssistant/ChartAssistant';
import EditTimeChartForm from '@/components/DBEditTimeChartForm';
-import { InputControlled } from '@/components/InputControlled';
-import { SourceSelectControlled } from '@/components/SourceSelect';
import { IS_ALERT_DETAILS_ENABLED } from '@/config';
-import { useChartAssistant } from '@/hooks/ai';
import { useAlertSeededChartConfig } from '@/hooks/useAlertSeededChartConfig';
import { useResolvedSourceParam } from '@/hooks/useResolvedSourceParam';
import { withAppNavForSurface } from '@/layout';
import { useSources } from '@/source';
import { useDefaultTimeRange, useNewTimeQuery } from '@/timeQuery';
-import { useLocalStorage } from '@/utils';
import { buildInlineAlertPayload } from '@/utils/alerts';
import { getApiErrorMessage } from '@/utils/apiErrors';
import OnboardingModal from './components/OnboardingModal';
+import { PageHeader } from './components/PageHeader';
+import { PageLayout } from './components/PageLayout';
// Autocomplete can focus on column/map keys
// Sampled field discovery and full field discovery
-function AIAssistant({
- setConfig,
- onTimeRangeSelect,
- submitRef,
- aiAssistantEnabled,
-}: {
- setConfig: (config: SavedChartConfig) => void;
- onTimeRangeSelect: (start: Date, end: Date) => void;
- submitRef: React.RefObject<(() => void) | undefined>;
- aiAssistantEnabled: boolean;
-}) {
- const brandName = useBrandDisplayName();
- const [opened, setOpened] = useState(false);
- const [alertDismissed, setAlertDismissed] = useLocalStorage(
- 'ai-assistant-alert-dismissed',
- false,
- );
- const { control, handleSubmit } = useForm<{
- text: string;
- source: string;
- }>({
- defaultValues: {
- text: '',
- source: '',
- },
- });
-
- const chartAssistant = useChartAssistant();
-
- const onSubmit = (data: { text: string; source: string }) => {
- chartAssistant.mutate(
- {
- sourceId: data.source,
- text: data.text,
- },
- {
- onSuccess(data) {
- setConfig({ ...data, where: '' });
- onTimeRangeSelect(
- new Date(data.dateRange[0]),
- new Date(data.dateRange[1]),
- );
-
- // FIXME: This is a hack to submit after the form has been updated
- setTimeout(() => {
- if (submitRef.current) {
- submitRef.current();
- }
- }, 100);
-
- notifications.show({
- color: 'green',
- message: 'Chart generated successfully',
- autoClose: 2000,
- });
- },
- onError(err) {
- notifications.show({
- color: 'red',
- title: 'Error Generating Chart',
- message: err.message,
- autoClose: 2000,
- });
- },
- },
- );
- };
-
- useHotkeys(
- 'a',
- () => {
- setOpened(v => !v);
- },
- {
- preventDefault: true,
- },
- );
-
- if (!aiAssistantEnabled && !alertDismissed) {
- return (
-
- }
- variant="outline"
- withCloseButton
- onClose={() => setAlertDismissed(true)}
- p="xxs"
- >
-
- New AI Assistant available, enable with configuring the{' '}
- ANTHROPIC_API_KEY environment variable on the{' '}
- {brandName} server.
-
-
-
-
- );
- } else if (!aiAssistantEnabled) {
- return null;
- }
-
- return (
-
-
-
-
-
-
- {opened && (
- // eslint-disable-next-line react-hooks/refs
-
- )}
-
-
-
- );
-}
-
const DEFAULT_INTERVAL = 'Past 1h';
function DBChartExplorerPage() {
@@ -229,6 +56,22 @@ function DBChartExplorerPage() {
const { data: me } = api.useMe();
const queryClient = useQueryClient();
const createAlert = api.useCreateAlert();
+ const aiAssistantEnabled = me?.aiAssistantEnabled ?? false;
+ const [assistantOpened, setAssistantOpened] = useState(false);
+ const [leadingTarget, setLeadingTarget] = useState(null);
+ const [chartTypeTarget, setChartTypeTarget] = useState(
+ null,
+ );
+ const [saveTarget, setSaveTarget] = useState(null);
+ const [actionsTarget, setActionsTarget] = useState(null);
+
+ useHotkeys(
+ 'a',
+ () => {
+ if (aiAssistantEnabled) setAssistantOpened(v => !v);
+ },
+ { preventDefault: true },
+ );
const [rawChartConfig, setChartConfig] = useQueryState(
'config',
@@ -313,47 +156,91 @@ function DBChartExplorerPage() {
[createAlert, queryClient, setChartConfig],
);
+ const aiAssistantButton = aiAssistantEnabled ? (
+
+ ) : null;
+
return (
-
-
- {title}
-
-
-
- {/* Held back until an `alertId` seed resolves: the form auto-runs once
- on mount, and mounting it early would run the default config and
- then swap the query out from under the result. */}
- {isSeedingFromAlert ? (
-
-
-
-
- ) : (
- {
- setChartConfig(config);
- }}
- dateRange={searchedTimeRange}
- setDisplayedTimeInputValue={setDisplayedTimeInputValue}
- displayedTimeInputValue={displayedTimeInputValue}
- onTimeRangeSearch={onSearch}
- onTimeRangeSelect={onTimeRangeSelect}
- submitRef={submitRef}
- autoRun
- enableAlerts
- onSaveAlert={onSaveAlert}
- saveAlertLabel="Create alert"
- isSavingAlert={createAlert.isPending}
- />
- )}
-
+
+
+
+
+
+
+ {aiAssistantButton}
+
+
+
+
+
+
+
+
+ }
+ padded
+ content={
+ <>
+
+ {title}
+
+
+
+ {/* Held back until an `alertId` seed resolves: the form auto-runs once
+ on mount, and mounting it early would run the default config and
+ then swap the query out from under the result. */}
+ {isSeedingFromAlert ? (
+
+
+
+
+ ) : (
+ {
+ setChartConfig(config);
+ }}
+ dateRange={searchedTimeRange}
+ setDisplayedTimeInputValue={setDisplayedTimeInputValue}
+ displayedTimeInputValue={displayedTimeInputValue}
+ onTimeRangeSearch={onSearch}
+ onTimeRangeSelect={onTimeRangeSelect}
+ submitRef={submitRef}
+ showChartName={false}
+ autoRun
+ enableAlerts
+ onSaveAlert={onSaveAlert}
+ saveAlertLabel="Create alert"
+ isSavingAlert={createAlert.isPending}
+ toolbarTargets={{
+ leading: leadingTarget,
+ chartType: chartTypeTarget,
+ save: saveTarget,
+ actions: actionsTarget,
+ }}
+ />
+ )}
+ >
+ }
+ />
);
}
diff --git a/packages/app/src/components/AlertPanel.tsx b/packages/app/src/components/AlertPanel.tsx
index 4de9aa501d..105db3d2a7 100644
--- a/packages/app/src/components/AlertPanel.tsx
+++ b/packages/app/src/components/AlertPanel.tsx
@@ -136,6 +136,9 @@ export function AlertPanelLayout({
actions,
onOpen,
onCancel,
+ sidePanel,
+ sidePanelOpened,
+ onSidePanelClose,
children,
...props
}: BoxProps & {
@@ -150,6 +153,14 @@ export function AlertPanelLayout({
onOpen?: () => void;
/** Undoes the panel's changes when it is closed without confirming them. */
onCancel?: (isDraft: boolean) => void;
+ /**
+ * Another panel that shares this slot (the chart's display settings). It
+ * takes the slot while open, and the alert panel waits behind it with its
+ * changes intact. Opening the alert panel calls `onSidePanelClose`.
+ */
+ sidePanel?: ReactNode;
+ sidePanelOpened?: boolean;
+ onSidePanelClose?: () => void;
children: ReactNode;
}) {
const [opened, setOpened] = useState(defaultOpened);
@@ -157,8 +168,19 @@ export function AlertPanelLayout({
const [target, setTarget] = useState(null);
const [hasContent, setHasContent] = useState(false);
const [root, setRoot] = useState(null);
- const showPanel = opened && hasContent;
+ const sidePanelVisible = sidePanelOpened === true && sidePanel != null;
+ const alertVisible = opened && hasContent && !sidePanelVisible;
+ const showPanel = alertVisible || sidePanelVisible;
const bounds = usePanelBounds(root, showPanel);
+ const openAlertPanel = useCallback(
+ (nextOpened: boolean) => {
+ if (nextOpened) {
+ onSidePanelClose?.();
+ }
+ setOpened(nextOpened);
+ },
+ [onSidePanelClose],
+ );
// The handle sits on the panel's left edge, so dragging left widens it.
const { size: widthPercent, startResize } = useResizable(
DEFAULT_PANEL_WIDTH_PERCENT,
@@ -174,7 +196,7 @@ export function AlertPanelLayout({
const value = useMemo(
() => ({
opened,
- setOpened,
+ setOpened: openAlertPanel,
isDraft,
setIsDraft,
onOpen,
@@ -184,7 +206,7 @@ export function AlertPanelLayout({
setTarget,
setHasContent,
}),
- [opened, isDraft, onOpen, onCancel, actions, target],
+ [opened, openAlertPanel, isDraft, onOpen, onCancel, actions, target],
);
return (
@@ -214,12 +236,18 @@ export function AlertPanelLayout({
onMouseDown={startResize}
data-testid="alert-panel-resize-handle"
/>
-
+ {alertVisible ? (
+
+ ) : (
+
+ {sidePanel}
+
+ )}
)}
diff --git a/packages/app/src/components/ChartAssistant/ChartAssistant.tsx b/packages/app/src/components/ChartAssistant/ChartAssistant.tsx
new file mode 100644
index 0000000000..1812e6def8
--- /dev/null
+++ b/packages/app/src/components/ChartAssistant/ChartAssistant.tsx
@@ -0,0 +1,239 @@
+import type { RefObject } from 'react';
+import { useForm } from 'react-hook-form';
+import { SavedChartConfig, SourceKind } from '@hyperdx/common-utils/dist/types';
+import {
+ ActionIcon,
+ Alert,
+ Box,
+ Button,
+ Divider,
+ Group,
+ Kbd,
+ Loader,
+ Popover,
+ Stack,
+ Text,
+ Tooltip,
+} from '@mantine/core';
+import { notifications } from '@mantine/notifications';
+import { IconInfoCircle, IconSparkles } from '@tabler/icons-react';
+
+import { useBrandDisplayName } from '@/brand';
+import { InputControlled } from '@/components/InputControlled';
+import { SourceSelectControlled } from '@/components/SourceSelect';
+import { useChartAssistant } from '@/hooks/ai';
+import { useLocalStorage } from '@/utils';
+
+const POPOVER_WIDTH = 360;
+
+const UNDO_NOTIFICATION_MS = 8000;
+
+interface ChartAssistantFormValues {
+ text: string;
+ source: string;
+}
+
+export function ChartAssistantUnavailableAlert({
+ aiAssistantEnabled,
+}: {
+ aiAssistantEnabled: boolean;
+}) {
+ const brandName = useBrandDisplayName();
+ const [alertDismissed, setAlertDismissed] = useLocalStorage(
+ 'ai-assistant-alert-dismissed',
+ false,
+ );
+
+ if (aiAssistantEnabled || alertDismissed) return null;
+
+ return (
+
+ }
+ variant="outline"
+ withCloseButton
+ onClose={() => setAlertDismissed(true)}
+ p="xxs"
+ >
+
+ New AI Assistant available, enable with configuring the{' '}
+ ANTHROPIC_API_KEY environment variable on the {brandName}{' '}
+ server.
+
+
+
+
+ );
+}
+
+export interface ChartAssistantPopoverProps {
+ currentConfig: SavedChartConfig;
+ searchedTimeRange: [Date, Date];
+ setConfig: (config: SavedChartConfig) => void;
+ onTimeRangeSelect: (start: Date, end: Date) => void;
+ submitRef: RefObject<(() => void) | undefined>;
+ opened: boolean;
+ onOpenChange: (opened: boolean) => void;
+}
+
+/**
+ * Generates a chart from a prompt, from a sparkles button in the page header.
+ * The generated chart replaces the current one, so the notification after a
+ * successful generation offers to restore the previous chart and time range.
+ */
+export function ChartAssistantPopover({
+ currentConfig,
+ searchedTimeRange,
+ setConfig,
+ onTimeRangeSelect,
+ submitRef,
+ opened,
+ onOpenChange,
+}: ChartAssistantPopoverProps) {
+ const { control, handleSubmit, reset } = useForm({
+ defaultValues: {
+ text: '',
+ source: '',
+ },
+ });
+ const chartAssistant = useChartAssistant();
+
+ const onSubmit = (data: ChartAssistantFormValues) => {
+ const previousConfig = currentConfig;
+ const [previousStart, previousEnd] = searchedTimeRange;
+
+ chartAssistant.mutate(
+ {
+ sourceId: data.source,
+ text: data.text,
+ },
+ {
+ onSuccess(generated) {
+ reset();
+ onOpenChange(false);
+ setConfig({ ...generated, where: '' });
+ onTimeRangeSelect(
+ new Date(generated.dateRange[0]),
+ new Date(generated.dateRange[1]),
+ );
+
+ // FIXME: This is a hack to submit after the form has been updated
+ setTimeout(() => {
+ if (submitRef.current) {
+ submitRef.current();
+ }
+ }, 100);
+
+ const notificationId = notifications.show({
+ color: 'green',
+ autoClose: UNDO_NOTIFICATION_MS,
+ message: (
+
+ Chart generated.
+
+
+ ),
+ });
+ },
+ onError(err) {
+ notifications.show({
+ color: 'red',
+ title: 'Error generating chart',
+ message: err.message,
+ autoClose: 2000,
+ });
+ },
+ },
+ );
+ };
+
+ return (
+
+
+
+ AI assistant
+ A
+
+ }
+ >
+ onOpenChange(!opened)}
+ >
+
+
+
+
+
+
+
+ AI assistant
+
+
+ Describe the chart you want. It replaces the current chart, and you
+ can undo it.
+
+ {/* eslint-disable-next-line react-hooks/refs */}
+
+
+
+
+ );
+}
diff --git a/packages/app/src/components/ChartAssistant/__tests__/ChartAssistant.test.tsx b/packages/app/src/components/ChartAssistant/__tests__/ChartAssistant.test.tsx
new file mode 100644
index 0000000000..6b3f8cd72f
--- /dev/null
+++ b/packages/app/src/components/ChartAssistant/__tests__/ChartAssistant.test.tsx
@@ -0,0 +1,110 @@
+import { SavedChartConfig } from '@hyperdx/common-utils/dist/types';
+import { screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import { DEFAULT_CHART_CONFIG } from '@/ChartUtils';
+import { ChartAssistantPopover } from '@/components/ChartAssistant/ChartAssistant';
+
+const mockMutate = jest.fn();
+jest.mock('@/hooks/ai', () => ({
+ useChartAssistant: () => ({ mutate: mockMutate, isPending: false }),
+}));
+
+jest.mock('@/components/SourceSelect', () => ({
+ SourceSelectControlled: () => ,
+}));
+
+const mockNotificationShow = jest.fn();
+jest.mock('@mantine/notifications', () => ({
+ notifications: {
+ show: (...args: unknown[]) => mockNotificationShow(...args),
+ update: jest.fn(),
+ },
+}));
+
+const previousConfig: SavedChartConfig = {
+ ...DEFAULT_CHART_CONFIG,
+ source: 'previous-source',
+ where: 'service:api',
+};
+const previousRange: [Date, Date] = [
+ new Date('2026-11-27T00:00:00Z'),
+ new Date('2026-11-27T01:00:00Z'),
+];
+const generatedResponse = {
+ ...DEFAULT_CHART_CONFIG,
+ source: 'generated-source',
+ where: 'generated',
+ dateRange: ['2026-11-26T00:00:00Z', '2026-11-26T06:00:00Z'],
+};
+
+// jsdom has no layout, so the popover dropdown stays `display: none`; query
+// hidden elements.
+function renderPanel() {
+ const setConfig = jest.fn();
+ const onTimeRangeSelect = jest.fn();
+ const onOpenChange = jest.fn();
+ renderWithMantine(
+ ,
+ );
+ return { setConfig, onTimeRangeSelect, onOpenChange };
+}
+
+describe('ChartAssistantPopover', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('replaces the chart on success and offers an undo that restores it', async () => {
+ const user = userEvent.setup();
+ const { setConfig, onTimeRangeSelect, onOpenChange } = renderPanel();
+
+ await user.type(
+ screen.getByTestId('save-search-name-input'),
+ 'errors by service',
+ );
+ await user.click(
+ screen.getByRole('button', { name: 'Generate', hidden: true }),
+ );
+
+ const [input, options] = mockMutate.mock.calls[0];
+ expect(input).toEqual({ sourceId: '', text: 'errors by service' });
+
+ options.onSuccess(generatedResponse);
+ expect(onOpenChange).toHaveBeenCalledWith(false);
+ expect(setConfig).toHaveBeenCalledWith({ ...generatedResponse, where: '' });
+ expect(onTimeRangeSelect).toHaveBeenCalledWith(
+ new Date('2026-11-26T00:00:00Z'),
+ new Date('2026-11-26T06:00:00Z'),
+ );
+
+ const [{ message }] = mockNotificationShow.mock.calls[0];
+ renderWithMantine(<>{message}>);
+ setConfig.mockClear();
+ onTimeRangeSelect.mockClear();
+
+ await user.click(screen.getByRole('button', { name: 'Undo' }));
+
+ expect(setConfig).toHaveBeenCalledWith(previousConfig);
+ expect(onTimeRangeSelect).toHaveBeenCalledWith(...previousRange);
+ });
+
+ it('does not submit an empty prompt', async () => {
+ const user = userEvent.setup();
+ renderPanel();
+
+ await user.click(
+ screen.getByRole('button', { name: 'Generate', hidden: true }),
+ );
+
+ await waitFor(() => expect(mockMutate).not.toHaveBeenCalled());
+ });
+});
diff --git a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx
index 498fe93ab1..6564747b62 100644
--- a/packages/app/src/components/ChartDisplaySettingsDrawer.tsx
+++ b/packages/app/src/components/ChartDisplaySettingsDrawer.tsx
@@ -22,7 +22,7 @@ import {
Box,
Button,
Checkbox,
- Drawer,
+ CloseButton,
Group,
Input,
NumberInput,
@@ -322,13 +322,21 @@ export default function ChartDisplaySettingsDrawer({
// Log scale only means something on a numeric (distribution mode) y axis
const showHeatmapScale = isDistributionHeatmap;
+ // Rendered in the chart editor's side panel (see AlertPanelLayout), so it
+ // mounts only while open and drops unapplied edits on close.
+ if (!opened) {
+ return null;
+ }
+
return (
-
+
+
+ Display Settings
+
+
{isTimeChart && (
<>
@@ -638,6 +646,6 @@ export default function ChartDisplaySettingsDrawer({
-
+
);
}
diff --git a/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx b/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx
index a97e302986..fb75d1c2c7 100644
--- a/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx
+++ b/packages/app/src/components/ChartEditor/ChartSeriesControls.tsx
@@ -2,9 +2,10 @@ import { ReactNode } from 'react';
import { Control, Path } from 'react-hook-form';
import { NumberFormat } from '@hyperdx/common-utils/dist/types';
import {
- ActionIcon,
Button,
+ ColorSwatch,
Divider,
+ Flex,
Group,
Text,
Tooltip,
@@ -17,7 +18,7 @@ import {
} from '@tabler/icons-react';
import { TextInputControlled } from '@/components/InputControlled';
-import { FORMAT_ICONS } from '@/components/NumberFormat';
+import SeriesNumberFormatPopover from '@/components/SeriesNumberFormatPopover';
import { ChartEditorFormState } from './types';
@@ -32,9 +33,11 @@ export function ChartSeriesControls({
onSwap,
onRemove,
onDuplicate,
- onOpenNumberFormat,
+ onNumberFormatChange,
leadingSection,
trailingSection,
+ card = false,
+ color,
}: {
control: Control;
aliasName: Path;
@@ -47,92 +50,120 @@ export function ChartSeriesControls({
onRemove?: (index: number) => void;
onDuplicate?: (index: number) => void;
/** Absent where the row has no format of its own. */
- onOpenNumberFormat?: () => void;
+ onNumberFormatChange?: (format: { numberFormat?: NumberFormat }) => void;
/** Rendered before the alias (the builder's formula reference badge). */
leadingSection?: ReactNode;
/** Rendered after the format button (the builder's color picker). */
trailingSection?: ReactNode;
+ /** Lay the row out as a card header (alias left, actions right). */
+ card?: boolean;
+ /** The color the chart draws this series in, shown as a swatch. */
+ color?: string;
}) {
const isFirst = index <= 0;
const isLast = index >= length - 1;
+ const aliasInput = (
+