diff --git a/.env b/.env
index 32c2952ff..0f31ad49a 100644
--- a/.env
+++ b/.env
@@ -2,14 +2,15 @@
HDX_IMAGE_REPO=docker.hyperdx.io
CH_IMAGE_REPO=docker.clickhouse.com
IMAGE_NAME_DOCKERHUB=hyperdx/hyperdx
+NEXT_IMAGE_NAME_DOCKERHUB=clickhouse/clickstack
NEXT_LOCAL_IMAGE_NAME_DOCKERHUB=clickhouse/clickstack-local
LOCAL_IMAGE_NAME_DOCKERHUB=hyperdx/hyperdx-local
NEXT_ALL_IN_ONE_IMAGE_NAME_DOCKERHUB=clickhouse/clickstack-all-in-one
ALL_IN_ONE_IMAGE_NAME_DOCKERHUB=hyperdx/hyperdx-all-in-one
NEXT_OTEL_COLLECTOR_IMAGE_NAME_DOCKERHUB=clickhouse/clickstack-otel-collector
OTEL_COLLECTOR_IMAGE_NAME_DOCKERHUB=hyperdx/hyperdx-otel-collector
-CODE_VERSION=2.43.0
-IMAGE_VERSION_SUB_TAG=.43.0
+CODE_VERSION=2.45.0
+IMAGE_VERSION_SUB_TAG=.45.0
IMAGE_VERSION=2
IMAGE_NIGHTLY_TAG=2-nightly
IMAGE_LATEST_TAG=latest
diff --git a/.fork-surface b/.fork-surface
index 6cd51e08e..06ac07e64 100644
--- a/.fork-surface
+++ b/.fork-surface
@@ -44,9 +44,10 @@
# top of every session, and keep their line intact at the bottom. Low churn -
# upstream rarely touches that single line - so rerere replays it cleanly.
CLAUDE.md
-LOCAL.md
knip.json
README.md
+# Our security policy, kept whole in place of the one upstream ships.
+SECURITY.md
agent_docs/tech_stack.md
# Published on the DFE docs site, so its HyperDX mentions say the console - see docs/fork/what-we-changed.md.
docs/alert-webhook-template-variables.md
@@ -56,7 +57,6 @@ docs/alert-webhook-template-variables.md
docker-compose.ci.yml
docker/hyperdx/entry.prod.sh
docker/nginx/README.md
-docker/otel-collector/custom.config.yaml
docker/otel-collector/schema/README.md
nx.json
package.json
@@ -86,6 +86,10 @@ packages/app/public/pyodide/pyodide.asm.js
packages/app/public/pyodide/pyodide.js
# One hook entry on the ky instance: a 4xx carries the response body's reason.
packages/app/src/api.ts
+# The DFE brand: the name, marks and Mantine theme come from dfe/brand.tsx, and
+# the CSS tokens from theme/themes/dfe - see docs/fork/what-we-changed.md.
+packages/app/src/ThemeWrapper.tsx
+packages/app/src/brand/index.tsx
packages/app/src/DBChartPage.tsx
packages/app/src/DBDashboardPage.tsx
packages/app/src/DBSearchPage.tsx
@@ -94,7 +98,6 @@ packages/app/src/LandingPage.tsx
# and the preset dashboards route through dfe/presetDashboards.ts, which offers
# none - see docs/fork/what-we-changed.md.
packages/app/src/Spotlights.tsx
-packages/app/src/UserPreferencesModal.tsx
packages/app/src/components/AppNav/AppNav.tsx
packages/app/src/components/ContextSidePanel.tsx
# The restore-shipped control in the toolbar, and the preset dashboards removed
@@ -111,11 +114,7 @@ packages/app/src/config.ts
packages/app/src/fonts.ts
packages/app/src/hooks/useRowWhere.tsx
packages/app/src/layout.tsx
-packages/app/src/theme/ThemeProvider.tsx
-packages/app/src/theme/index.ts
-packages/app/src/theme/themes/_base-tokens.scss
-packages/app/src/theme/types.ts
-packages/app/src/utils.ts
+packages/app/src/theme/_base-tokens.scss
packages/app/styles/LogTable.module.scss
packages/app/styles/globals.css
packages/app/src/components/SQLEditor/SQLInlineEditor.tsx
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
new file mode 100644
index 000000000..853acf197
--- /dev/null
+++ b/.github/CODEOWNERS
@@ -0,0 +1,2 @@
+# One reviewer is picked round robin by the team's code review settings.
+* @ClickHouse/clickstack
diff --git a/.github/ISSUE_TEMPLATE/bug-report.md b/.github/ISSUE_TEMPLATE/bug-report.md
index 93dc43ee4..49cf5f8d8 100644
--- a/.github/ISSUE_TEMPLATE/bug-report.md
+++ b/.github/ISSUE_TEMPLATE/bug-report.md
@@ -17,7 +17,7 @@ paste the URL if it does. If you're working from the repo, `yarn app:dev:local`
plus onboarding → "Connect to Demo Server" gives you the same data locally. If
it only happens with your own data, include the table schema
(`SHOW CREATE TABLE ...`) and source settings.
-See https://github.com/hyperdxio/hyperdx/blob/main/CONTRIBUTING.md#reproducing-issues-and-prs
+See https://github.com/ClickHouse/ClickStack/blob/main/CONTRIBUTING.md#reproducing-issues-and-prs
-->
**Reproduces on play.hyperdx.io?**
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index cfa0fd29c..042c90c39 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -7,7 +7,7 @@ contact_links:
about:
For usage questions, setup help, and general discussion, ask on Discord.
- name: First-time contributor?
- url: https://github.com/hyperdxio/hyperdx/blob/main/CONTRIBUTING.md#getting-vouched
+ url: https://github.com/ClickHouse/ClickStack/blob/main/CONTRIBUTING.md#getting-vouched
about:
No need to open an issue to get vouched. Open your pull request and a
maintainer vouches from there.
diff --git a/.github/ISSUE_TEMPLATE/feature-request.md b/.github/ISSUE_TEMPLATE/feature-request.md
index 98b7b2990..8d80c0289 100644
--- a/.github/ISSUE_TEMPLATE/feature-request.md
+++ b/.github/ISSUE_TEMPLATE/feature-request.md
@@ -26,4 +26,4 @@ labels: enhancement, Needs Feedback
New issues start as `Needs Feedback` so we can discuss scope before anyone
writes code. Once a maintainer swaps that for `Accepting PR`, the issue is ready
to be picked up — see
-[CONTRIBUTING.md](https://github.com/hyperdxio/hyperdx/blob/main/CONTRIBUTING.md#from-issue-to-pull-request).
+[CONTRIBUTING.md](https://github.com/ClickHouse/ClickStack/blob/main/CONTRIBUTING.md#from-issue-to-pull-request).
diff --git a/.github/VOUCHED.td b/.github/VOUCHED.td
index 95533ec1a..34f99e793 100644
--- a/.github/VOUCHED.td
+++ b/.github/VOUCHED.td
@@ -1,4 +1,4 @@
-# Vouched contributors for hyperdxio/hyperdx.
+# Vouched contributors for ClickHouse/ClickStack.
#
# Pull requests from GitHub users who are not in this list are closed
# automatically by .github/workflows/vouch.yml. See CONTRIBUTING.md for how to
@@ -29,10 +29,13 @@
adityapimpalkar
alex-fedotyev
alok87
+andrewdunndev
archat-hash
arj22
aryainguz
bahltushar
+bcanvural
+bferreirq
bilalatique
brandon-pereira
colehpage
diff --git a/.github/images/search_splash.png b/.github/images/search_splash.png
index d6d6d4fb7..2342a18bf 100644
Binary files a/.github/images/search_splash.png and b/.github/images/search_splash.png differ
diff --git a/.github/prompts/code-review.md b/.github/prompts/code-review.md
index 62605a048..a7f9adf73 100644
--- a/.github/prompts/code-review.md
+++ b/.github/prompts/code-review.md
@@ -1,4 +1,4 @@
-REPO: hyperdxio/hyperdx
+REPO: ClickHouse/ClickStack
PR: #{{PR_NUMBER}}
Review this pull request.
diff --git a/.github/scripts/code-review/review-comments.cjs b/.github/scripts/code-review/review-comments.cjs
index 8818e6c2f..f0cdc1b4f 100644
--- a/.github/scripts/code-review/review-comments.cjs
+++ b/.github/scripts/code-review/review-comments.cjs
@@ -25,7 +25,7 @@ const MAX_BODY = 65536;
* FOOTER repeats the rule and this anchor; the anchor test pins both to the AGENTS.md heading.
*/
const GUIDE_URL =
- 'https://github.com/hyperdxio/hyperdx/blob/main/AGENTS.md#responding-to-review-feedback';
+ 'https://github.com/ClickHouse/ClickStack/blob/main/AGENTS.md#responding-to-review-feedback';
const GUIDE_LINK = `[How to respond](${GUIDE_URL})`;
/**
diff --git a/.upstream-version b/.upstream-version
index 327aa79bd..b30d9add0 100644
--- a/.upstream-version
+++ b/.upstream-version
@@ -9,6 +9,6 @@
#
# Written by the sync workflow; bump it in the same commit as the merge.
-upstream_ref: '@hyperdx/app@2.43.0'
-upstream_sha: 31f865e9d326cd081afec1b9ba3a89a27858f1cf
-synced: 2026-10-30
+upstream_ref: '@hyperdx/app@2.45.0'
+upstream_sha: 0096a355c0f6fba3e691d2e8efe83228bc35751b
+synced: 2026-11-14
diff --git a/.vex/openssl-mongodb.vex.json b/.vex/openssl-mongodb.vex.json
index 20e3a67fd..4a8aecdd8 100644
--- a/.vex/openssl-mongodb.vex.json
+++ b/.vex/openssl-mongodb.vex.json
@@ -1,6 +1,6 @@
{
"@context": "https://openvex.dev/ns/v0.2.0",
- "@id": "https://github.com/hyperdxio/hyperdx/blob/main/.vex/openssl-mongodb.vex.json",
+ "@id": "https://github.com/ClickHouse/ClickStack/blob/main/.vex/openssl-mongodb.vex.json",
"author": "HyperDX Team",
"role": "Supplier",
"timestamp": "2026-02-17T00:00:00Z",
diff --git a/.yarn/patches/uplot-npm-1.6.32-350d2da00d.patch b/.yarn/patches/uplot-npm-1.6.32-350d2da00d.patch
new file mode 100644
index 000000000..80a885b11
--- /dev/null
+++ b/.yarn/patches/uplot-npm-1.6.32-350d2da00d.patch
@@ -0,0 +1,40 @@
+diff --git a/dist/uPlot.cjs.js b/dist/uPlot.cjs.js
+index 98b7582dff68d4f4d9e0068cc77bec9d33ea4904..d137fbcb9f24358d7e59350907181106fc5b231d 100644
+--- a/dist/uPlot.cjs.js
++++ b/dist/uPlot.cjs.js
+@@ -441,7 +441,14 @@ function _rangeNum(_min, _max, cfg) {
+ }
+
+ // alternative: https://stackoverflow.com/a/2254896
+-const numFormatter = new Intl.NumberFormat(domEnv ? nav.language : 'en-US');
++// Patched: Intl rejects POSIX-style tags such as 'en-US@posix', which some
++// browsers report as navigator.language. Fall back instead of throwing at import.
++let numFormatter;
++try {
++ numFormatter = new Intl.NumberFormat(domEnv ? nav.language : 'en-US');
++} catch (e) {
++ numFormatter = new Intl.NumberFormat('en-US');
++}
+ const fmtNum = val => numFormatter.format(val);
+
+ const M = Math;
+diff --git a/dist/uPlot.esm.js b/dist/uPlot.esm.js
+index 87473c9cfb3366f57883cb803114a87c64d4b6b8..740bd3626a1f8bd6bbe352878e55e898e759784c 100644
+--- a/dist/uPlot.esm.js
++++ b/dist/uPlot.esm.js
+@@ -439,7 +439,14 @@ function _rangeNum(_min, _max, cfg) {
+ }
+
+ // alternative: https://stackoverflow.com/a/2254896
+-const numFormatter = new Intl.NumberFormat(domEnv ? nav.language : 'en-US');
++// Patched: Intl rejects POSIX-style tags such as 'en-US@posix', which some
++// browsers report as navigator.language. Fall back instead of throwing at import.
++let numFormatter;
++try {
++ numFormatter = new Intl.NumberFormat(domEnv ? nav.language : 'en-US');
++} catch (e) {
++ numFormatter = new Intl.NumberFormat('en-US');
++}
+ const fmtNum = val => numFormatter.format(val);
+
+ const M = Math;
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d5c49e905..8298c188c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,536 @@ PR — keep the `hyperdx-release-notes` comment marker intact when editing so yo
edits survive regeneration. Per-package detail lives in each
`packages/*/CHANGELOG.md`.
+## v2.45.0 — 2026-11-13
+
+
+
+**PromQL evaluation choice and ClickHouse 26.10**
+
+You can now choose how a PromQL source on ClickHouse is evaluated — through the
+Prometheus HTTP API or the `prometheusQuery` table functions — instead of
+leaving HyperDX to probe the server on every query. The service map can also now
+be split by up to three extra group-by expressions, so a single slow or failing
+pod no longer disappears into its service average. This release also moves the
+all-in-one image and the Docker Compose files to ClickHouse 26.10.3.7. Two
+things change underneath you: TimeSeries tables created from now on default to
+schema version 8, which keeps each series' time range in a separate inner table,
+and ClickHouse's own `system.metric_log` switches to the bucketed schema. Your
+existing TimeSeries tables keep the layout they already have, but metric_log
+rows written before the upgrade are left behind in `system.metric_log_0`, so
+check anything that reads that table before you upgrade.
+
+### 💥 Breaking Changes
+
+- **`system.metric_log` moves to the bucketed schema**: ClickHouse now writes
+ `system.metric_log` in its bucketed form, and the rows recorded before the
+ upgrade move to `system.metric_log_0`. A dashboard, alert or saved query
+ reading ClickHouse's own metrics from `system.metric_log` will see only
+ post-upgrade rows until you point it at both tables.
+- **New TimeSeries tables default to schema version 8**: TimeSeries tables
+ created after the upgrade keep each series' time range in a separate inner
+ table. Existing tables are untouched and keep their current layout, so a table
+ created after the upgrade no longer matches the shape of one created before
+ it.
+- **`clickstack_service_health` no longer returns a verdict**: the MCP tool has
+ stopped labelling services critical, degraded or healthy, and no longer tells
+ an agent a service needs "no action" — each service keeps its threshold flags,
+ score and a factual summary, so agents reason from the numbers rather than a
+ verdict that service-wide totals can get wrong. `summary.statusCounts` is
+ replaced by `summary.servicesFlagged`, and the span attributes
+ `mcp.service_health.critical_count` and `mcp.service_health.degraded_count`
+ are replaced by `mcp.service_health.flagged_count`, so update anything that
+ reads those fields.
+
+### ✨ New Features
+
+- **Choose how a PromQL source is evaluated**: a PromQL source on ClickHouse can
+ now be set to use either the Prometheus HTTP API or the `prometheusQuery`
+ table functions, rather than having HyperDX work it out for itself. A source
+ pinned to the HTTP API against a server that does not serve it now fails with
+ a clear error instead of an obscure one, and onboarding pins a PromQL source
+ it detects to the HTTP API when the server serves it.
+- **Split the service map by extra dimensions**: you can now add up to three
+ extra group-by SQL expressions to the service map — for example
+ `ResourceAttributes['k8s.pod.name']` — so a node becomes a service plus those
+ values and a slow or failing pod stands on its own instead of being averaged
+ into its service.
+
+### 🔧 Improvements
+
+- **PromQL label lookups go through ClickHouse's Prometheus HTTP API**: on
+ ClickHouse 26.9+ with the `prometheus_api_v1` handler, label and label-value
+ lookups for a ClickHouse-backed PromQL source now proxy to the handler instead
+ of querying the TimeSeries tags table with SQL. Older servers, servers without
+ the handler, and sources set to `table-function` keep the SQL path, so a
+ source that runs queries over HTTP on 26.6-26.8 still gets label
+ autocomplete.
+- **The MCP `describe_source` tool reads its label catalogue the same way**:
+ asked about a ClickHouse-backed PromQL source, `describe_source` now lists
+ label and metric names through the `prometheus_api_v1` handler on ClickHouse
+ 26.9+, so an agent sees the same catalogue the app does. It falls back to SQL
+ on older servers, servers without the handler, and sources set to
+ `table-function`.
+- **Fewer probes for sources without an explicit choice**: a PromQL source that
+ does not say how it should be evaluated is still probed, but the answer is now
+ kept for 5 minutes instead of being worked out again on every query.
+
+### 🐛 Bug Fixes
+
+- **`{{note}}` is filled in when an alert actually fires**: a webhook body using
+ `{{note}}` now carries the alert's note on real alert notifications, not only
+ on "Send test", so the context you wrote on the alert reaches the people
+ paged by it.
+- **MCP webhook and alert tools are declared open-world**: saving a webhook or
+ an alert sends HTTP requests to third-party endpoints, so
+ `clickstack_save_webhook` and `clickstack_save_alert` now carry
+ `openWorldHint: true`. MCP clients that treat open-world tools differently —
+ by asking you to confirm before they run, for instance — will now do so for
+ these two.
+
+### 📦 Build / Packaging
+
+- **Bundled ClickHouse is now 26.10.3.7**: the all-in-one image and the Docker
+ Compose files use `clickhouse/clickhouse-server:26.10.3.7-alpine`.
+
+
+
+### 📦 Package changelogs
+
+- `@hyperdx/api` 2.44.0 → 2.45.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/api/CHANGELOG.md#2450)
+- `@hyperdx/app` 2.44.0 → 2.45.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/app/CHANGELOG.md#2450)
+- `@hyperdx/common-utils` 0.34.0 → 0.35.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/common-utils/CHANGELOG.md#0350)
+- `@hyperdx/otel-collector` 2.44.0 → 2.45.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/otel-collector/CHANGELOG.md#2450)
+
+
+
+## v2.44.0 — 2026-11-11
+
+
+
+**Time zone picker and optional webhook emoji**
+
+You can now pick a time zone straight from the time picker on the search and
+dashboard pages, overriding the one set in your User Preferences, and teams can
+create their own API keys — with a description and an expiry — that keep working
+after the person who created them leaves. Webhooks now take an optional
+`titleEmoji` setting: set it to `false` and notification titles sent through that
+webhook arrive without the emoji prefix. Columns added to a ClickHouse table
+after HyperDX starts — a new MATERIALIZED column, say — are now visible within
+five minutes, with no restart needed. Note before upgrading that the app now
+always uses ClickStack branding — brand selection, the HyperDX palette and the
+font picker are gone — that HyperDX instruments itself with the ClickStack SDKs
+now, which changes the shape of its own telemetry and where that telemetry goes
+by default, and that webhooks pointing at private or reserved addresses are now
+blocked unless you allowlist their hostnames.
+
+### 💥 Breaking Changes
+
+- **ClickStack branding is now the only theme**: brand selection, the HyperDX
+ palette and the font picker have been removed, so the app always uses
+ ClickStack branding and its standard font. If you or your team had chosen the
+ HyperDX palette or a different font, that choice no longer applies. Light,
+ dark and system colour mode stay in Preferences.
+- **Webhooks to private or reserved addresses are blocked**: generic and
+ incident.io webhooks whose hostname resolves to a private or reserved address
+ are now rejected, and the check runs on the address actually dialled, so it
+ also covers DNS rebinding. If your self-hosted setup notifies an internal
+ hostname, add it to `WEBHOOK_HOSTNAME_ALLOWLIST` before upgrading or those
+ notifications will stop going out.
+- **HyperDX self-instruments with the ClickStack SDKs**: HyperDX's own telemetry
+ now comes from `@clickhouse/clickstack-node` and
+ `@clickhouse/clickstack-browser` in place of `@hyperdx/node-opentelemetry` and
+ `@hyperdx/browser`, and it changes shape. HTTP spans carry the stable semantic
+ convention keys (`http.request.method`, `http.response.status_code`,
+ `url.full`), pino records arrive under the
+ `@opentelemetry/instrumentation-pino` scope with real severity numbers instead
+ of the `node-logger` scope at severity number 0, console capture covers every
+ `console` call in the API, browser console output is recorded as log records
+ rather than spans, uncaught exceptions are recorded as FATAL log records, and
+ an API error is an exception event on the Express span instead of a separate
+ error span. Browser telemetry names the user as `user.id`, `user.email` and
+ `user.name` instead of `userEmail` and `userName`, keeps the team name as
+ `teamName`, no longer records a `user navigated` action, and no longer records
+ request and response headers or bodies on fetch and XHR spans; browser
+ sessions restart once after the upgrade. Update anything — a saved search,
+ alert or dashboard — keyed on the old attribute names before you upgrade.
+- **Self-telemetry is configured with the OpenTelemetry variables**:
+ `HYPERDX_API_KEY` still enables self-instrumentation, but without
+ `OTEL_EXPORTER_OTLP_ENDPOINT` server-side self-telemetry now goes to
+ `http://localhost:4318` instead of `https://in-otel.hyperdx.io`, so set the
+ endpoint explicitly. `HDX_NODE_*` variables are no longer read; capture
+ request headers and bodies with `OTEL_INSTRUMENTATION_HTTP_CAPTURE_HEADERS_*`
+ and `CLICKSTACK_CAPTURE_HTTP_BODY` instead. Browser traces and logs are now
+ sent gzip-compressed every 5 seconds, so if the browser sends to a collector
+ other than ClickStack's, that collector's CORS `allowed_headers` must be `"*"`
+ or include `content-type` and `content-encoding` (and `authorization`), and a
+ proxy in front of it must forward `Content-Encoding` unchanged. The per-signal
+ browser endpoints and `NEXT_PUBLIC_OTEL_RESOURCE_ATTRIBUTES` work as before.
+- **The Next.js server reports telemetry from production builds too**: with
+ `HYPERDX_API_KEY` or `OTEL_EXPORTER_OTLP_HEADERS` set, the Next.js server now
+ sends its own telemetry in production builds, not only under `next dev`. It
+ reports under its own service name — the configured one plus `-next`
+ (`hdx-oss-app-next` in the docker-compose `app` service and when no name is
+ set) — so its spans stay apart from the API's and the browser's, and the
+ HyperDX images now default `OTEL_SERVICE_NAME` to `hdx-oss-app`. Each `/api`
+ request gains Next.js server spans for the proxy hop, while requests for build
+ and `public/` assets such as `/_next/static/*`, `/__ENV.js` and `/pyodide/*`
+ are not traced. `HDX_EXPORTER_ENABLED=false` turns it off along with browser
+ telemetry.
+
+### ✨ New Features
+
+- **Pick a time zone from the time picker**: the search and dashboard pages let
+ you choose the time zone they display, overriding the zone set in User
+ Preferences. The picker shows the zone it is using, and your choice is kept in
+ the URL and carried through links from charts and tables, so a shared link
+ opens in the same zone you were reading.
+- **Emoji prefix in webhook titles is now optional**: webhooks take a new
+ `titleEmoji` option, and setting it to `false` sends notification titles
+ through that webhook without the leading emoji — useful where the receiving
+ system renders it poorly or your team would rather read a plain title.
+- **Team-owned API keys**: team members can now create API keys that belong to
+ the team rather than to the person who made them, each with a description and
+ an expiry. A key keeps working after its creator leaves, so an integration no
+ longer stops the day someone moves on.
+- **Ad hoc dashboard filters can narrow their own suggestions**: an ad hoc
+ filter on a SQL source can now carry a SQL or Lucene "Keys and values filter",
+ much like a queried filter's dropdown values filter, limiting the rows its
+ keys and values are suggested from, and it can reference the dashboard's other
+ variables. While it points at a required filter with nothing selected, the ad
+ hoc filter won't add or edit conditions and names the filter it is waiting on,
+ and a suggestion lookup that fails now shows the database's error message.
+- **Browser events on the trace waterfall and in the row side panel**: the
+ waterfall now plots the request timings an OpenTelemetry browser SDK records
+ as dots along fetch and XHR spans, and shows the click that triggered a
+ browser trace, so you can see where time went in the browser without leaving
+ the trace. The row side panel summarises the clicks, navigations and console
+ messages those SDKs record, and navigation rows no longer show an HTTP Request
+ section that never applied to them.
+- **JavaScript stack traces broken into frames**: the Exception panel now parses
+ the JavaScript stack traces that OpenTelemetry SDKs report into individual
+ frames, with its own section for each `Caused by:` error, so you can follow an
+ exception and the errors behind it instead of reading one block of text.
+- **Session IDs from older browser SDKs land on `session.id`**: spans, logs and
+ session replay events from older `@hyperdx/browser` SDKs carry the session id
+ only in the `rum.sessionId` resource attribute, and the collector now gives
+ them the OpenTelemetry `session.id` attribute as well, so anything keyed off
+ the standard attribute sees them too. An existing `session.id` is never
+ overwritten and `rum.sessionId` is kept; if you override pipeline
+ `processors:` lists in `CUSTOM_OTELCOL_CONFIG_FILE`, add `transform/session_id`
+ to keep this. Newly created `hyperdx_sessions` and `otel_logs` tables also get
+ `MATERIALIZED` session id columns with skip indexes, so session queries no
+ longer read the attribute maps — existing tables need an
+ `ALTER TABLE ... ADD COLUMN` to benefit.
+- **Filter the v2 list alerts endpoint**: the v2 API for listing alerts now
+ accepts tag, search, source and state filters, so you can ask for just the
+ alerts you care about rather than fetching them all and filtering yourself.
+- **Connect an AI agent without pasting a key**: the new
+ `npx @hyperdx/cli mcp install` asks for a personal access key or an
+ organisation API key with hidden input, checks it, and adds the ClickStack MCP
+ server to Claude Code, Codex, Cursor and VS Code. Team Settings now leads with
+ this command, so a key no longer has to go into a copied command or an agent
+ chat; the per-agent snippets are still there for setting up one agent by hand.
+- **Describe any table over MCP**: the new `clickstack_describe_table` tool
+ lists the tables in a database and describes one that is not a registered
+ source — its columns, keys, engine, skipping indices, approximate size and an
+ optional row sample — so an assistant can look into data you have not set up
+ as a source yet.
+- **Set a dashboard's saved filter values over MCP**: the MCP dashboard tools
+ can now set a dashboard's `savedFilterValues`, so an assistant building or
+ updating a dashboard can leave its filters pre-filled rather than having you
+ set them by hand afterwards.
+- **Run up to ten MCP SQL queries in parallel**: `clickstack_sql` now accepts a
+ `queries` array and runs up to ten independent queries at once under a shared
+ 60 second deadline, with each query reporting its own `ok`, `error` or
+ `timeout` status so one failure does not take the others down with it.
+ Single-query calls using `sql` behave exactly as before.
+- **Narrower MCP table queries**: `clickstack_table` now takes an optional
+ `limit` and `having`, so an assistant can cut a grouped result down to the
+ rows worth reading rather than filtering them afterwards. Grouped results with
+ no `orderBy` now come back ordered by the first select item, descending, which
+ puts the largest values first instead of leaving the order to ClickHouse.
+
+### 🧪 Experimental
+
+PromQL support is gated behind the `ENABLE_PROMQL` flag; these changes apply
+once it is on.
+
+- **PromQL sources and tiles over MCP**: `clickstack_describe_source` now
+ returns a PromQL source's label names and metric names — from a ClickHouse
+ TimeSeries table or a Prometheus-compatible endpoint — instead of a column
+ schema, and both it and `clickstack_list_sources` say which backend the source
+ uses, explaining how to read a TimeSeries table with `clickstack_sql`.
+ Prometheus endpoint sources no longer show a placeholder table, and the MCP
+ dashboard tools read and write PromQL tiles and `PROMETHEUS_LABEL` filters.
+ With `ENABLE_PROMQL` off, MCP hides PromQL sources from listing, describing
+ and deleting, `clickstack_save_source` no longer accepts `kind: "promql"`, and
+ the dashboard tools hide PromQL tiles rather than discarding them, so a
+ dashboard edited through MCP keeps its PromQL tiles intact.
+- **Run a PromQL query over MCP**: the new `clickstack_promql` tool runs PromQL
+ against a PromQL source, and the MCP prompts and instructions now cover
+ PromQL sources, tiles and label filters while PromQL is enabled, so an
+ assistant knows how to reach them. Label lookups and queries also refuse a
+ Prometheus endpoint response over 8 MB rather than buffering the whole thing
+ into memory.
+- **Query a PromQL tile over MCP**: the `query_tile` and `query_tiles` tools now
+ run PromQL tiles as well, against both Prometheus-compatible endpoints and
+ ClickHouse TimeSeries tables, so an assistant can read the numbers behind a
+ PromQL tile rather than only its definition. PromQL table and histogram
+ heatmap tiles come back in the rows the dashboard itself draws, so what the
+ assistant reads matches what you see on the dashboard.
+
+### 🔧 Improvements
+
+- **The ClickStack hexagon and bolt mark across the app**: the logo, the
+ collapsed nav and the favicon now carry the ClickStack hexagon and bolt mark,
+ so the browser tab and the sidebar match the branding the rest of the app
+ uses. The expanded sidebar spells out the ClickStack name as text beside the
+ symbol, and a new favicon set, an SVG included, covers the browser tab,
+ bookmarks and touch icon.
+- **A tighter trace side panel**: the trace waterfall starts higher up the
+ panel, because a span no longer repeats its name in a box under the panel
+ title or shows its service as a chip beside the metadata row that already
+ names it, and the "⌘/Ctrl + scroll to zoom" hint has moved into the timeline's
+ top-left corner instead of claiming a row of its own. Span names too long for
+ the title keep their box, and log panels are unchanged.
+- **Opening a row queries it once**: the side panel ran the same `SELECT *` row
+ query twice, once for the panel and again when its Overview or Column Values
+ tab mounted. A row that was found is now reused from the cache, so that tab
+ and later tab switches do not query it again; a different row or source still
+ runs the query, and a row that was not found is looked up again.
+- **One name when you alert on a search**: creating an alert from the search
+ page now asks for a single name rather than two. An unsaved search is named
+ once in the alert modal's header and the alert inherits that name and its
+ tags; on a saved search the alert's own field is labelled "Alert name" and
+ shows the inherited name as its placeholder instead of pre-filling a
+ duplicate.
+- **Collapsed pinned filters stay collapsed**: a pinned filter you collapse in
+ the search sidebar stays collapsed the next time that source loads, instead of
+ opening again every time.
+- **Better compression for newly created tables**: the collector's seed schemas
+ now pin `ZSTD(3)` rather than `ZSTD(1)`, which compresses your data further
+ for a small insert-time CPU cost and no change to read performance. Only
+ tables created from here on are affected; existing tables keep the codecs they
+ already have.
+- **Logs with a severity number but no severity text get a level**: logs that
+ arrive with a severity number and an empty severity text, such as those from
+ the new browser SDK, now get the matching level text (`info`, `error`, and so
+ on), so they read and filter like every other log. Severity text set by the
+ producer is never overwritten.
+- **Browsers cache the collector's CORS preflights for 10 minutes**: the OTLP
+ receiver now answers preflight requests with `Access-Control-Max-Age: 600`.
+ Browsers previously cached a preflight for only 5 seconds, which is exactly
+ how often the browser SDK exports, so about half of its requests to the
+ collector were preflights.
+- **Persisted `_block_number` and `_block_offset` columns detected more
+ reliably**: when a table's `CREATE` query omits them, HyperDX now falls back to
+ the server's MergeTree settings to work out whether they are persisted —
+ reading `system.shared_merge_tree_settings` first on ClickHouse Cloud, then
+ `system.merge_tree_settings` per key — so the features that rely on those
+ columns keep working on tables where the setting is applied server-side rather
+ than spelled out in the schema.
+- **Sharper query guidance for MCP agents**: the MCP tool descriptions and the
+ query guide now recommend the quoted Lucene form `field:"value"` for exact
+ matches, and bare terms or phrases for log body text, so the queries an
+ assistant writes still make use of the primary key and the text index.
+- **`minAutoGranularity` documented in the external API**: `GET`, `POST` and
+ `PUT /api/v2/sources` already accepted and returned `minAutoGranularity` on
+ metric and PromQL sources, but the OpenAPI spec left it out, so clients
+ generated from the spec dropped or rejected the field. The spec now documents
+ it, and generated clients can set and read it like any other source setting.
+
+### 🐛 Bug Fixes
+
+- **Metric points with no recorded value stay out of charts and alerts**: when a
+ scraped series goes away or a scrape fails, the collector's `prometheus`
+ receiver sends a point flagged "no recorded value" — a Prometheus staleness
+ marker — and the ClickHouse exporter stores it as zeros. Charts and alerts
+ read that as a real measurement, so a gauge's `min` and `avg` dropped and its
+ `count` still included the series that had gone, and a counter or histogram
+ that came back after the marker counted its whole total over again. Metric
+ queries now skip points carrying the flag.
+- **Cached table columns refresh after 5 minutes**: the metadata cache kept each
+ table's `DESCRIBE` result for the life of the process, so columns added with
+ `ALTER TABLE`, such as new MATERIALIZED columns, were not picked up until the
+ API restarted. Cached columns now expire after 5 minutes; other cached
+ metadata is unchanged.
+- **Alerts can no longer be set on tiles that never fire**: dashboard tiles the
+ alert checker does not evaluate — PromQL tiles, and builder tiles with an
+ unsupported display type — now reject alerts outright, instead of accepting
+ one that stayed silent forever. Any such alert already saved is dropped the
+ next time its dashboard is saved, so move it to a tile the checker supports if
+ you were relying on it.
+- **Resolved grouped alerts name the group that resolved**: when a group
+ vanishes from the data, the alert resolves with that group's values filled in
+ for `{{attributes.*}}` in the title and message, and `{{var.*}}` in the webhook
+ body, so you can tell from the notification which group went quiet.
+- **Row detail lookups work on FIPS ClickHouse and with special characters in
+ JSON keys**: looking up a JSON row no longer relies on MD5, which FIPS-enabled
+ deployments refuse to run — the lookup uses SHA256 instead — and path segments
+ containing special characters, a key prefixed with `@`, say, now stay quoted.
+ Row details and drill-down return the row rather than failing or reading the
+ key as something else.
+- **Row details no longer open the wrong row on tables with a single block
+ column**: the key-only lookup is used only where a table persists both
+ `_block_number` and `_block_offset`. One block column on its own — from a
+ server-wide `enable_block_offset_column`, say — is not unique against a
+ second-precision primary key and could open a different row, so it is now
+ added only as a tiebreaker to the full-row lookup.
+- **"Denoise results" removes noise on ordinary data again**: a pattern now
+ counts as noisy above 5% of the sampled events rather than 10%, a bar that
+ often matched nothing at all, so denoising a typical result set actually hides
+ the repetitive lines it was meant to — and patterns containing error or
+ warning lines are never hidden. Denoise also mines the source's body column
+ instead of whatever the last column in the table happened to be, strips
+ ANSI-coloured rows matching a noisy pattern, tells you when results can't be
+ denoised, and lists what it hid as a short, expandable summary. The MCP
+ `denoise` option uses the same 5% threshold.
+- **Charts show a spinner while they load**: a chart tile now shows a spinner
+ and "Loading Chart Data..." while its query is in flight, including when the
+ previous result was empty — before, it kept reading "No data found within time
+ range." until the new query finished, which looked like an answer rather than
+ a wait. Loaders are a neutral grey now instead of yellow.
+- **Row details show a loader while they load**: expanded search rows and the
+ trace viewer's span details read "Empty" or "No body for this event." while
+ the row was still on its way, which looked like a row with nothing in it. Both
+ now show a loader until the row arrives.
+- **Session replays from separate page loads no longer collide**: browser SDKs
+ up to `@clickhouse/clickstack-browser` 1.2.0 number replay events from 1 again
+ on every page load, so when a page closed before all the chunks of a large
+ event were sent, its leftover chunk could be joined onto a later page's event
+ of the same number — that snapshot then failed to parse and never rendered.
+ Chunks are now grouped by event number and full-precision timestamp, and
+ replay rows are ordered by that timestamp, so rows from two page loads in the
+ same second no longer interleave. The app's own browser telemetry moves to
+ `@clickhouse/clickstack-browser` 1.2.1, whose replay event numbers no longer
+ repeat across page loads.
+- **Legacy `STATUS_CODE_ERROR` spans count as errors on the service map and
+ trace waterfall**: spans from collectors that emit the long status form were
+ not recognised as errored in either view, so both undercounted errors. That
+ value is now counted alongside the short `Error` form.
+- **Prometheus connections with credentials in the host work again**: a host
+ such as `http://user:pass@prometheus:9090` failed every PromQL query with
+ "Failed to reach Prometheus", because `fetch` rejects URLs carrying
+ credentials. Those credentials are now sent as a Basic auth header instead.
+- **PromQL label lookups work on ClickHouse 26.10's TimeSeries tables**: schema
+ version 8, the default from ClickHouse 26.10, keeps each series' time range in
+ a separate time ranges table rather than in the tags table's
+ `min_time`/`max_time`, so dashboard variables and label autocomplete failed
+ with "requires store_min_time_and_max_time = 1" and time-bounded lookups read
+ the whole tags table. Those lookups now read the time ranges table, so they
+ resolve on version 8 tables and stay bounded by the window you asked for, and
+ a lookup with `match[]` reads only the matched metrics' tags rows when every
+ selector names its metric, rather than every metric's.
+- **Saving a search no longer reloads the page**: the newly saved search opens
+ with a client-side navigation instead of a full page load, which also fixes
+ the 404 this caused on the static ClickStack build.
+- **Heatmap tooltips no longer shift the tile**: hovering a heatmap added
+ scrollbars and nudged the tile, because the tooltip was drawn inside the
+ chart. It now sits above the chart, so the tile stays put as you read across
+ it.
+- **The sidebar toggle works on narrow screens**: on compact viewports the
+ toggle did nothing at all. It now opens the full nav as an overlay over the
+ page, so you can reach every section without widening the window.
+- **The app loads in browsers reporting a POSIX-style language**: a browser
+ whose language reads as something like `en-US@posix` crashed the app on load.
+ Those locales are handled now, so the app starts as it should.
+- **Dashboards and saved searches keep their team and owner**: a PATCH request
+ that included `team` or `createdBy` could move a dashboard or saved search to
+ another team, or rewrite who owned it. Both fields are now ignored on update,
+ so neither can be changed that way.
+- **Usage stats run against password-protected ClickHouse connections**: the
+ usage stats job failed ClickHouse authentication whenever the connection
+ required a password. It now authenticates correctly, so those deployments
+ report usage stats again.
+- **Event pattern drill-downs return the events they describe**: each pattern
+ from `clickstack_event_patterns` now carries a SQL `whereSnippet` that keeps
+ the template's token order and variable positions and includes both the
+ caller's filter and the source table filter, so handing it to
+ `clickstack_search` returns that pattern's events. Previously a template like
+ `Sending <*> rows` produced `Body:"Sending rows"`, which matched nothing, and
+ map fields produced Lucene that would not parse. Patterns can also be mined
+ from a key inside a JSON body, and the tool now reports its sample coverage
+ and the trend bucket interval and boundaries it actually used.
+ `clickstack_event_patterns`, `clickstack_emerging_signals` and dashboard
+ event-pattern tiles also apply the log source's `tableFilterExpression` now,
+ so their counts can drop for sources that set one, and each cluster is
+ reported with its own template rather than occasionally that of a different
+ cluster of the same length.
+- **Oversized MCP responses keep more of what you asked for**: a response over
+ the size budget now shortens a long string with a `…(+N chars)` suffix instead
+ of replacing it outright, and records what it cut in `trimNotes`.
+ `clickstack_event_patterns` and `clickstack_emerging_signals` drop samples and
+ shorten long patterns before they discard whole patterns, so the `topN` you
+ asked for survives wherever it can.
+
+### 📦 Build / Packaging
+
+- **systeminformation updated past its command injection advisories**: the API
+ pulls systeminformation in through
+ `@opentelemetry/instrumentation-host-metrics`, but the root `resolutions` pin
+ held the lockfile at 5.30.7, which carries known command injection advisories
+ — among them two high-severity ones in `networkInterfaces()` on Linux
+ (GHSA-5xpp-75jx-m839, GHSA-hvx9-hwr7-wjj9). The pin now starts at 5.33.19, the
+ newest 5.x release, which fixes all of them.
+- **The app image is now published as `clickhouse/clickstack` as well**: the
+ HyperDX image goes out under `clickhouse/clickstack` alongside the existing
+ `hyperdx/hyperdx`, matching the other `clickhouse/clickstack-*` images, so you
+ can pull it under either name. Release workflows no longer log in to ghcr.io,
+ which was receiving no pushes.
+- **Project links and the bundled compose file point at ClickStack**: the GitHub
+ links the app and packages carry — changelog, support and package metadata —
+ now point at `ClickHouse/ClickStack`, and `docker-compose.yml` pulls the app
+ image as `clickhouse/clickstack`.
+- **App builds no longer fail on extensionless Google Fonts URLs**: the app
+ moves to Next.js 16.4.3, fixing the intermittent build failures that happened
+ when Google Fonts returned a font URL without a file extension. Only builds of
+ the app from source are affected.
+
+
+
+### 📦 Package changelogs
+
+- `@hyperdx/api` 2.43.1 → 2.44.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/api/CHANGELOG.md#2440)
+- `@hyperdx/app` 2.43.1 → 2.44.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/app/CHANGELOG.md#2440)
+- `@hyperdx/cli` 0.8.0 → 0.9.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/cli/CHANGELOG.md#090)
+- `@hyperdx/common-utils` 0.33.0 → 0.34.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/common-utils/CHANGELOG.md#0340)
+- `@hyperdx/otel-collector` 2.43.1 → 2.44.0 — [changelog](https://github.com/ClickHouse/ClickStack/blob/main/packages/otel-collector/CHANGELOG.md#2440)
+
+
+
+## v2.43.1 — 2026-10-31
+
+
+
+**Multipath TCP disabled in the collector image**
+
+The collector image now sets `GODEBUG=multipathtcp=0` at startup, so it no longer
+opens Multipath TCP listeners — Go 1.24 and later turn them on by default — which
+mitigates CVE-2026-98432 with no change needed on your side. The all-in-one image
+picks up the same setting. Any other `GODEBUG` values you pass through are kept,
+and an explicit `multipathtcp=` of your own is left exactly as you set it, so you
+can still opt back in to MPTCP. Patching the host kernel remains the actual fix.
+
+### 📦 Build / Packaging
+
+- **Multipath TCP listeners no longer opened by the collector**: the collector
+ image, and the all-in-one image with it, starts with
+ `GODEBUG=multipathtcp=0`, mitigating CVE-2026-98432 on hosts where Go 1.24+
+ would otherwise listen over MPTCP. Your own `GODEBUG` settings are preserved
+ and an explicit `multipathtcp=` value is honoured as written; patching the host
+ kernel is still the real fix.
+
+
+
+### 📦 Package changelogs
+
+- `@hyperdx/api` 2.43.0 → 2.43.1 — [changelog](https://github.com/hyperdxio/hyperdx/blob/main/packages/api/CHANGELOG.md#2431)
+- `@hyperdx/app` 2.43.0 → 2.43.1 — [changelog](https://github.com/hyperdxio/hyperdx/blob/main/packages/app/CHANGELOG.md#2431)
+- `@hyperdx/otel-collector` 2.43.0 → 2.43.1 — [changelog](https://github.com/hyperdxio/hyperdx/blob/main/packages/otel-collector/CHANGELOG.md#2431)
+
+
+
## v2.43.0 — 2026-10-30
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 5c22126a8..fd948ba21 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -30,7 +30,7 @@ steps](#reproducing-issues-and-prs), and has [before/after
screenshots](#ui-changes-need-beforeafter-screenshots) if it touches the UI.
Good places to start: the [good first
-issue](https://github.com/hyperdxio/hyperdx/labels/good%20first%20issue) label,
+issue](https://github.com/ClickHouse/ClickStack/labels/good%20first%20issue) label,
and [Discord](https://discord.gg/FErRRKU78j) if the dev setup gives you trouble.
Why we do this: AI tools make it cheap to open a plausible-looking PR with no
@@ -96,7 +96,7 @@ problem (or the fix) for themselves. If a maintainer can't reproduce it, they
can't triage the issue or review the PR.
**Try the demo environment first.** [play.hyperdx.io](https://play.hyperdx.io)
-is a hosted HyperDX connected to a public demo dataset (logs, traces, metrics
+is a hosted ClickStack instance connected to a public demo dataset (logs, traces, metrics
and session replays from the OpenTelemetry demo app). If your bug shows up
there, link the exact URL — search and chart explorer keep their query, filters
and time range in the URL — and that's most of the repro.
@@ -176,13 +176,13 @@ Service Descriptions:
- OpenTelemetry Collector (otel-collector): Receives OpenTelemetry data from
instrumented applications and forwards it to ClickHouse for storage. Includes
- OpAMP supervisor that dynamically pulls configuration from HyperDX API.
+ OpAMP supervisor that dynamically pulls configuration from ClickStack API.
- ClickHouse (ch-server): ClickHouse database, stores all telemetry.
- MongoDB (db): Stores user/saved search/alert/dashboard data.
-- HyperDX API (api): Node.js API, executes ClickHouse queries on behalf of the
+- ClickStack API (api): Node.js API, executes ClickHouse queries on behalf of the
frontend and serves the frontend. serves the frontend. Can also run alert
checker.
-- HyperDX UI (app): Next.js frontend, serves the UI.
+- ClickStack UI (app): Next.js frontend, serves the UI.
## Development
@@ -214,6 +214,11 @@ yarn dev:down
To enable self-instrumentation and demo logs, you can set the `HYPERDX_API_KEY`
to your ingestion key (visit the Team settings page after creating your account).
+The API and the Next.js server pass it to the ClickStack SDK
+(`@clickhouse/clickstack-node`) as `apiKey`, and the browser SDK
+(`@clickhouse/clickstack-browser`) gets it from `/api/config`. The API and the
+alert task report as `hdx-oss-dev-api`, the Next.js server as
+`hdx-oss-dev-app-next`, and the browser as `hdx-oss-dev-app`.
To do this, create a `.env.local` file in the root of the project and add the
following:
@@ -335,7 +340,7 @@ pin. Drop it if that blanket resolution is ever narrowed.
## AI-Assisted Development
-HyperDX includes an [MCP server](https://modelcontextprotocol.io/) that lets AI assistants query observability data, manage dashboards, and
+ClickStack includes an [MCP server](https://modelcontextprotocol.io/) that lets AI assistants query observability data, manage dashboards, and
explore data sources. See [MCP.md](/MCP.md) for setup instructions.
The repo also ships with configuration for AI coding assistants that enables interactive browser-based E2E test generation and debugging via
diff --git a/DEPLOY.md b/DEPLOY.md
index 52735ada6..3710de6c0 100644
--- a/DEPLOY.md
+++ b/DEPLOY.md
@@ -1,26 +1,44 @@
-# HyperDX Deployment Guide
+# ClickStack Deployment Guide
-[HyperDX](https://hyperdx.io) helps engineers quickly figure out why production
+[ClickStack](https://hyperdx.io) helps engineers quickly figure out why production
is broken by making it easy to search & visualize logs and traces on top of any
ClickHouse cluster (imagine Kibana, for ClickHouse). You can learn more about
-HyperDX in our [README](/README.md).
+ClickStack in our [README](/README.md).
-HyperDX can be deployed in a few different ways:
+ClickStack can be deployed in a few different ways:
- [Bring Your Own ClickHouse](#bring-your-own-clickhouse)
- [All-in-one Docker Compose Stack](#all-in-one-docker-compose-stack)
- [Local Development Mode](#local-development-mode)
+## Container image names
+
+ClickStack images are published to Docker Hub under the `clickhouse` namespace
+and are also served from `docker.clickhouse.com`:
+
+| Image | Name |
+| --------------------------- | -------------------------------------- |
+| ClickStack (UI + API) | `clickhouse/clickstack` |
+| All-in-one (with auth) | `clickhouse/clickstack-all-in-one` |
+| Local (all-in-one, no auth) | `clickhouse/clickstack-local` |
+| OpenTelemetry collector | `clickhouse/clickstack-otel-collector` |
+
+The legacy `hyperdx/hyperdx`, `hyperdx/hyperdx-all-in-one`,
+`hyperdx/hyperdx-local` and `hyperdx/hyperdx-otel-collector` names (also served
+from `docker.hyperdx.io`) keep receiving the same tags for a transition period.
+Switch to the `clickhouse/clickstack-*` names now; the date the legacy names
+stop updating will be announced in the changelog.
+
## Bring Your Own ClickHouse
-If you already have an existing ClickHouse cluster, you can simply deploy a
-HyperDX container that connects to your ClickHouse cluster. You'll need a
+If you already have an existing ClickHouse cluster, you can simply deploy the
+ClickStack container that connects to your ClickHouse cluster. You'll need a
separate MongoDB instance to persist your users, dashboards, searches and more.
To get started, you can run the following image:
```bash
-docker run -e MONGO_URI=mongodb://YOUR_MONGODB_URI -p 8080:8080 docker.hyperdx.io/hyperdx/hyperdx:2-beta
+docker run -e MONGO_URI=mongodb://YOUR_MONGODB_URI -p 8080:8080 docker.clickhouse.com/clickhouse/clickstack:2
```
You'll need to set the `MONGO_URI` environment variable to the URI of your
@@ -34,13 +52,13 @@ replicas from sharing sessions. The old public value `hyperdx is cool 👋` is
also replaced with a per-process secret when authentication is enabled.
To customize the frontend URL, set the `FRONTEND_URL` environment variable to
-the URL your HyperDX instance is hosted on.
+the URL your ClickStack instance is hosted on.
## All-in-one Docker Compose Stack
-The easiest way to get started with HyperDX from scratch is to use our
+The easiest way to get started with ClickStack from scratch is to use our
all-in-one Docker Compose stack. This stack will start ClickHouse, an
-OpenTelemetry collector, and HyperDX with a MongoDB instance.
+OpenTelemetry collector, the ClickStack UI and API, and MongoDB.
To get started, clone this repository and run the following command:
@@ -48,7 +66,7 @@ To get started, clone this repository and run the following command:
docker compose up -d
```
-This will start the HyperDX stack and open a port for the UI, API, and OTel
+This will start the ClickStack stack and open a port for the UI, API, and OTel
collector.
When deploying into production, you'll want to disable any extra ports outside
@@ -73,13 +91,13 @@ replicas from sharing sessions. The old public value is not a production secret.
## Local Development Mode
-HyperDX can also be deployed alongside your existing local development stack to
+ClickStack can also be deployed alongside your existing local development stack to
help you debug issues locally. This mode will start an OpenTelemetry collector,
-ClickHouse, and HyperDX with a MongoDB in a single instance, without any
+ClickHouse, the ClickStack UI and API, and MongoDB in a single container, without any
authentication or configuration persistence.
To get started, spin up the local mode container:
```bash
-docker run -p 8080:8080 docker.hyperdx.io/hyperdx/hyperdx-local:2-beta
+docker run -p 8080:8080 docker.clickhouse.com/clickhouse/clickstack-local:2
```
diff --git a/Dockerfile b/Dockerfile
index 30bac664e..ccbc0d8dc 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -67,8 +67,6 @@ ENV NEXT_PUBLIC_HDX_LOCAL_DEFAULT_CONNECTIONS=$NEXT_PUBLIC_HDX_LOCAL_DEFAULT_CON
ARG NEXT_PUBLIC_HDX_LOCAL_DEFAULT_SOURCES=
ENV NEXT_PUBLIC_HDX_LOCAL_DEFAULT_SOURCES=$NEXT_PUBLIC_HDX_LOCAL_DEFAULT_SOURCES
-ARG NEXT_PUBLIC_THEME=hyperi
-ENV NEXT_PUBLIC_THEME=$NEXT_PUBLIC_THEME
ENV NX_DAEMON=false
RUN npx nx run-many --target=build --projects=@hyperdx/common-utils,@hyperdx/api,@hyperdx/app
diff --git a/LOCAL.md b/LOCAL.md
index 6eb000a99..7a218147f 100644
--- a/LOCAL.md
+++ b/LOCAL.md
@@ -1,22 +1,13 @@
-# HyperDX Local
+# ClickStack Local
-HyperDX Local is a single container local-optimized version of
-[HyperDX](https://www.hyperdx.io/) that allows you to pipe OpenTelemetry
-telemetry (logs, metrics, traces) to a local instance of HyperDX running on your
-own machine. This makes it easily to debug complex applications locally using
-the same telemetry you have in prod or to test your instrumentation before
-pushing it into production.
+ClickStack Local is a single container local-optimized version of [ClickStack](https://www.hyperdx.io/) that allows you to pipe OpenTelemetry telemetry (logs, metrics, traces) to a local instance of ClickStack running on your own machine. This makes it easily to debug complex applications locally using the same telemetry you have in prod or to test your instrumentation before pushing it into production.
-HyperDX Local has a few additional benefits tuned to local development over the
-regular version:
-
-- 📦 Packaged in a single container, to slot alongside your existing dev
- environment (ex. Docker Compose stack)
+ClickStack Local has a few additional benefits tuned to local development over the regular version:
+- 📦 Packaged in a single container, to slot alongside your existing dev environment (ex. Docker Compose stack)
- 🔑 No need to auth to send and view telemetry
- 🐏 Optimized for lower memory footprint
-And it has all the features you would expect from HyperDX:
-
+And it has all the features you would expect from ClickStack:
- 🔭 Native OpenTelemetry logs, metrics, and traces support
- 🔍 Full text searching of logs and traces
- `{` Automatic JSON structured log parsing
@@ -24,48 +15,36 @@ And it has all the features you would expect from HyperDX:
- 📈 Charting logs, metrics and traces in a single UI
-
+
## Getting Started
-To get started, simply run the Docker container with the appropriate ports
-forwarded:
+To get started, simply run the Docker container with the appropriate ports forwarded:
```
-docker run -p 8000:8000 -p 4318:4318 -p 4317:4317 -p 8080:8080 -p 8002:8002 docker.hyperdx.io/hyperdx/hyperdx-local
+docker run -p 8000:8000 -p 4318:4318 -p 4317:4317 -p 8080:8080 -p 8002:8002 docker.clickhouse.com/clickhouse/clickstack-local
```
-Afterwards, you can visit `http://localhost:8080` and immediately jump into the
-HyperDX UI.
+Afterwards, you can visit `http://localhost:8080` and immediately jump into the ClickStack UI.
-> We recommend having _at least_ 1GB of RAM and 1 CPU core available for the
-> container.
+> We recommend having _at least_ 1GB of RAM and 1 CPU core available for the container.
## Configuring Instrumentation
-Configuring instrumentation for HyperDX local is similar to configuring it for
-the regular open source version. You should point your OpenTelemetry
-instrumentation to the OpenTelemetry endpoints:
+Configuring instrumentation for ClickStack Local is similar to configuring it for the regular open source version. You should point your OpenTelemetry instrumentation to the OpenTelemetry endpoints:
- `http://localhost:4318` for HTTP
- `localhost:4317` for gRPC
-Most instrumentations can be configured using the `OTEL_EXPORTER_OTLP_ENDPOINT`
-environment variable. Ex: `OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318`.
+Most instrumentations can be configured using the `OTEL_EXPORTER_OTLP_ENDPOINT` environment variable. Ex: `OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318`.
-If you're using a HyperDX maintained SDK, you may need to give a non-empty
-`HYPERDX_API_KEY` as well, API keys are not validated in HyperDX Local and
-therefore can be any non-empty value.
+If you're using a ClickStack SDK, pass the key as the `apiKey` init option. `@clickhouse/clickstack-node` also accepts `OTEL_EXPORTER_OTLP_HEADERS=authorization=`, and `@clickhouse/clickstack-browser` only takes `apiKey`. Older HyperDX SDKs (`@hyperdx/*`) may need a non-empty `HYPERDX_API_KEY` instead. API keys are not validated in ClickStack Local and therefore can be any non-empty value.
## Customizing Ports
-If you need to customize the app (8080) or api (8000) ports that HyperDX Local
-runs on, you'll need to modify the `docker run` command to forward the
-appropriate ports and set a few environment variables.
+If you need to customize the app (8080) or api (8000) ports that ClickStack Local runs on, you'll need to modify the `docker run` command to forward the appropriate ports and set a few environment variables.
-Customizing the OpenTelemetry ports can simply be changed by modifying the port
-forwarding flags. Ex. Replacing `-p 4318:4318` with `-p 4999:4318` to change the
-OpenTelemetry HTTP port to 4999.
+Customizing the OpenTelemetry ports can simply be changed by modifying the port forwarding flags. Ex. Replacing `-p 4318:4318` with `-p 4999:4318` to change the OpenTelemetry HTTP port to 4999.
```bash
HYPERDX_APP_PORT=YOUR_CUSTOM_APP_PORT \
@@ -77,26 +56,22 @@ docker run \
-p 4318:4318 -p 4317:4317 \
-p $HYPERDX_APP_PORT:8080 \
-p 8002:8002 \
-docker.hyperdx.io/hyperdx/hyperdx-local
+docker.clickhouse.com/clickhouse/clickstack-local
```
## Open Source & Cloud Versions (Beyond Local)
-If you're looking to deploy HyperDX to monitor a production environment (or
-anything outside your local environment), you can check out the
-[regular open source version](https://github.com/hyperdxio/hyperdx) or the
-[cloud hosted version](https://hyperdx.io/).
+If you're looking to deploy ClickStack to monitor a production environment (or anything outside your local environment), you can check out the [regular open source version](https://github.com/ClickHouse/ClickStack) or the [cloud hosted version](https://hyperdx.io/).
### Local vs Non-Local Versions
-There are a few missing features in HyperDX Local compared to the other versions
-of HyperDX:
+There are a few missing features in ClickStack Local compared to other ClickStack deployments:
-- HyperDX Local is single-user only (due to skipping auth)
+- ClickStack Local is single-user only (due to skipping auth)
- Has no support for [management APIs](https://www.hyperdx.io/docs/api/alerts)
- No alerting support (alerts will not fire)
- DB queries will not be reduced into query patterns
-- No persistence of data (telemetry and settings) if the container is torn down
+- No persistence of data (telemetry and settings) if the container is torn down
## Notes
@@ -104,14 +79,13 @@ of HyperDX:
- `4317` - OpenTelemetry gRPC endpoint
- `4318` - OpenTelemetry HTTP endpoint
-- `8000` - Private HyperDX API for the UI
-- `8002` - HyperDX HTTP Logging Endpoint
-- `8080` - HyperDX UI (Next.js)
+- `8000` - Private ClickStack API for the UI
+- `8002` - ClickStack HTTP Logging Endpoint
+- `8080` - ClickStack UI (Next.js)
### Build Image (Only For Development)
-To develop this image, you can build the image locally by running the build
-script from project root:
+To develop this image, you can build the image locally by running the build script from project root:
```
./docker/local/build.sh
diff --git a/MCP.md b/MCP.md
index a380fb890..8f8834943 100644
--- a/MCP.md
+++ b/MCP.md
@@ -38,21 +38,34 @@ The MCP server uses the **Streamable HTTP** transport with Bearer token
authentication. In the examples below, replace `` with your
instance URL (e.g. `http://localhost:8080`).
+### Install with the CLI (recommended)
+
+This asks for a personal access key or an organization API key with hidden
+input, checks it, and adds the server to Claude Code, Codex, Cursor and VS Code.
+The key stays out of your shell history and agent chats.
+
+```bash
+npx @hyperdx/cli mcp install --app-url
+```
+
### Claude Code
+`read -rs` waits for you to paste the key and press Enter, without echoing it,
+so the key isn't saved in your shell history:
+
```bash
-claude mcp add --transport http clickstack /api/mcp \
- --header "Authorization: Bearer "
+read -rs CLICKSTACK_ACCESS_KEY
+claude mcp add --scope user --transport http clickstack /api/mcp \
+ --header "Authorization: Bearer $CLICKSTACK_ACCESS_KEY"
```
### Codex CLI
The Codex CLI reads the bearer token from an environment variable rather than a
-`--header` flag. Export your personal access key, then register the server with
-`--bearer-token-env-var`:
+`--header` flag, so the variable must be set wherever Codex runs:
```bash
-export CLICKSTACK_ACCESS_KEY=""
+read -rs CLICKSTACK_ACCESS_KEY && export CLICKSTACK_ACCESS_KEY
codex mcp add clickstack --url /api/mcp \
--bearer-token-env-var CLICKSTACK_ACCESS_KEY
```
@@ -122,6 +135,7 @@ with:
| ----------------------------- | -------------------------------------------------------------------------------------------- |
| `clickstack_list_sources` | List all data sources and connections as a lightweight catalog (IDs, names, kinds) |
| `clickstack_describe_source` | Full column schema, attribute keys, sampled low-cardinality values, and a round-trippable `config` block (the exact shape `clickstack_save_source` accepts, incl. correlation IDs) for a single source; for metric sources also returns a per-kind metric-name sample |
+| `clickstack_describe_table` | Inspect a ClickHouse table that is not a registered source: columns, keys, engine, skipping indices, approximate size, and an optional row sample. Without a table, lists the tables in a database (paginated) |
| `clickstack_save_source` | Create (omit id) or update (provide id) a data source (log, trace, session, metric, or promql) so shipped telemetry becomes queryable. To clone a source, read its `config` from `clickstack_describe_source`, drop `id`, and pass it here |
| `clickstack_delete_source` | Permanently delete a data source by ID |
| `clickstack_list_metrics` | Paginated catalog of metric names on a metric source with optional kind / namePattern / time-window filters |
@@ -133,7 +147,8 @@ with:
| `clickstack_event_patterns` | Discover the most common log messages and event patterns using Drain clustering |
| `clickstack_event_deltas` | Compare two row groups and rank properties by how their value distributions differ |
| `clickstack_emerging_signals` | Detect NEW or GONE log/event patterns between a baseline and a current window (two-window Drain novelty diff) |
-| `clickstack_sql` | Execute raw ClickHouse SQL for advanced queries (JOINs, CTEs, sub-queries) |
+| `clickstack_sql` | Execute raw ClickHouse SQL for advanced queries (JOINs, CTEs, sub-queries); pass `queries` to run up to 10 in parallel |
+| `clickstack_promql` | Run a PromQL expression (range or instant) against a PromQL source. Only registered when PromQL is enabled |
| `clickstack_get_dashboard` | List all dashboards or get full detail for a specific dashboard |
| `clickstack_save_dashboard` | Create or update a dashboard with tiles (charts, tables, numbers, search, markdown) |
| `clickstack_delete_dashboard` | Permanently delete a dashboard and its attached alerts |
@@ -196,3 +211,40 @@ Discovery workflow for metrics:
4. `clickstack_describe_metric` to drill into a specific metric and
discover its attribute keys + sampled values before authoring queries.
5. `clickstack_timeseries` / `clickstack_table` to chart the metric.
+
+### PromQL Sources
+
+Available when PromQL is enabled for the deployment (self-hosted: the API's
+`ENABLE_PROMQL` setting). With it off, PromQL sources, tiles, label filters,
+the `clickstack_promql` tool and the PromQL prompt sections are all hidden
+from MCP.
+
+A source with `kind: "promql"` holds Prometheus metrics, either on a
+Prometheus-compatible endpoint or in a ClickHouse `TimeSeries` table. The
+builder tools do not read it; use PromQL:
+
+1. `clickstack_list_sources` shows each PromQL source with its `backend`
+ (`prometheus` or `clickhouse`).
+2. `clickstack_describe_source` lists its metric names and label names.
+3. `clickstack_promql` runs an expression. A `range` query (default) returns
+ `{ __hdx_time_bucket, series_name, value }` rows plus `seriesLabels`; an
+ `instant` query evaluates at `endTime` and returns one row per series with
+ a column per label. `granularity` sets the step and `$__interval` in the
+ same `""` format PromQL tiles use.
+4. `clickstack_save_dashboard` with a `configType: "promql"` tile keeps the
+ chart; `clickstack_query_tile` returns the same rows for the same
+ expression and granularity. `PROMETHEUS_LABEL` filters give the dashboard
+ a label dropdown that tiles reference as `{job=~"$job"}`.
+
+```jsonc
+{
+ "sourceId": "",
+ "expression": "sum by (job) (rate(http_requests_total[$__rate_interval]))",
+ "startTime": "2026-01-01T00:00:00Z",
+ "endTime": "2026-01-01T01:00:00Z"
+}
+```
+
+The `$__interval`, `$__rate_interval` and `$__range` macros expand as they do
+in a PromQL tile. Dashboard variables do not resolve in `clickstack_promql`;
+write the value inline.
diff --git a/Makefile b/Makefile
index 91896878e..c682bacfc 100644
--- a/Makefile
+++ b/Makefile
@@ -283,6 +283,7 @@ build-app:
--build-context app=./packages/app \
--build-arg CODE_VERSION=${CODE_VERSION} \
-t ${IMAGE_NAME_DOCKERHUB}:${IMAGE_VERSION}${IMAGE_VERSION_SUB_TAG} \
+ -t ${NEXT_IMAGE_NAME_DOCKERHUB}:${IMAGE_VERSION}${IMAGE_VERSION_SUB_TAG} \
--target prod
.PHONY: build-otel-collector-nightly
@@ -300,6 +301,7 @@ build-app-nightly:
--build-context app=./packages/app \
--build-arg CODE_VERSION=${CODE_VERSION} \
-t ${IMAGE_NAME_DOCKERHUB}:${IMAGE_NIGHTLY_TAG} \
+ -t ${NEXT_IMAGE_NAME_DOCKERHUB}:${IMAGE_NIGHTLY_TAG} \
--target prod
.PHONY: build-local-nightly
diff --git a/agent_docs/README.md b/agent_docs/README.md
index 2e3c1de63..58ff6241a 100644
--- a/agent_docs/README.md
+++ b/agent_docs/README.md
@@ -1,6 +1,6 @@
# Agent Documentation Directory
-This directory contains detailed documentation for AI coding agents working on the HyperDX codebase. These files use **progressive disclosure** - they're referenced from `AGENTS.md` but only read when needed.
+This directory contains detailed documentation for AI coding agents working on the ClickStack codebase. These files use **progressive disclosure** - they're referenced from `AGENTS.md` but only read when needed.
## Purpose
@@ -19,7 +19,7 @@ Instead of stuffing all instructions into `AGENTS.md` (which goes into every con
- **`page_layout.md`** - PageHeader, PageLayout, and consistent page chrome (titles, actions, tool pages)
- **`naming_objects.md`** - How users name and rename objects (dashboards, saved searches, tiles) with `InlineNameInput`. Read before adding or changing any place where something gets a name.
- **`data_viz_colors.md`** - Chart, heatmap, and semantic status colors. Read before adding or changing any color in a chart, sparkline, heatmap, legend, or status pill.
-- **`themes.md`** - How the brand theme system (HyperDX vs ClickStack) and color mode (light/dark/system) work. Read before changing anything in `packages/app/src/theme/`, adding semantic CSS variables, or touching brand-conditional UI.
+- **`themes.md`** - ClickStack appearance and color mode (light/dark/system). Read before changing anything in `packages/app/src/theme/`, adding semantic CSS variables, or hard-coding a color, logo, or favicon.
- **`observability.md`** - Instrumentation standards (tracing, metrics, context) and the shared helpers. Read when adding or changing a feature.
- **`evals.md`** - MCP eval framework: dual-slot setup, running A/B comparisons between branches, interpreting results. Read before running evals or benchmarking MCP changes.
diff --git a/agent_docs/architecture.md b/agent_docs/architecture.md
index 30dfce452..b42eaebe5 100644
--- a/agent_docs/architecture.md
+++ b/agent_docs/architecture.md
@@ -1,9 +1,9 @@
-# HyperDX Architecture
+# ClickStack Architecture
## Core Services
-- **HyperDX UI (`packages/app`)**: Next.js frontend serving the user interface
-- **HyperDX API (`packages/api`)**: Node.js/Express backend handling queries and business logic
+- **ClickStack UI (`packages/app`)**: Next.js frontend serving the user interface
+- **ClickStack API (`packages/api`)**: Node.js/Express backend handling queries and business logic
- **OpenTelemetry Collector**: Receives and processes telemetry data
- **ClickHouse**: Primary data store for all telemetry (logs, metrics, traces)
- **MongoDB**: Metadata storage (users, dashboards, alerts, saved searches)
diff --git a/agent_docs/code_style.md b/agent_docs/code_style.md
index cc4b5ff14..16b4836eb 100644
--- a/agent_docs/code_style.md
+++ b/agent_docs/code_style.md
@@ -177,14 +177,14 @@ This pattern cannot be enforced by ESLint and requires manual code review.
### Semantic component variants (Alert / Text / danger controls)
-We ship **themed semantic variants** for `Alert`, `Text`, `Button`, and `ActionIcon` so callouts and status text are token-driven and consistent across the HyperDX and ClickStack brands (and light/dark). **Prefer these over raw Mantine palette colors** (`color="yellow"`, `color="red"`, `c="green"`, etc.).
+We ship **semantic variants** for `Alert`, `Text`, `Button`, and `ActionIcon` so callouts and status text are token-driven in both light and dark. **Prefer these over raw Mantine palette colors** (`color="yellow"`, `color="red"`, `c="green"`, etc.).
-The variant → token mapping is centralized in `packages/app/src/theme/themes/semanticVariants.ts` (the single source of truth, consumed by both brand themes' `mantineTheme.ts`). See the Storybook stories `Components/Alert` (interactive `Playground`) and `Design tokens/Semantic variants` for the full visual matrix.
+The variant → token mapping is centralized in `packages/app/src/theme/semanticVariants.ts` (the single source of truth, consumed by `theme/mantineTheme.ts`). See the Storybook stories `Components/Alert` (interactive `Playground`) and `Design tokens/Semantic variants` for the full visual matrix.
**`Alert`** — `info` | `success` | `warning` | `danger`. Renders a tinted `-subtle` background with the title, icon, **and body text** in the semantic color token:
```tsx
-// ✅ token-driven, works in both brands + light/dark, meets WCAG AA
+// ✅ token-driven, works in light and dark, meets WCAG AA
This may take a while.Could not save the alert.
@@ -398,11 +398,11 @@ render those verbatim.
## Semantic design tokens (prefer over raw Mantine colors)
-The UI is built with **Mantine components**, but **colors and surfaces** should follow the **semantic CSS custom properties** in our themes (`--color-*`, etc.), not ad-hoc Mantine palette values. Those tokens are defined in `packages/app/src/theme/themes/**/_tokens.scss`, align with a **Click UI**–style system, and keep HyperDX and ClickStack visually consistent. They are the path toward a shared design system even while Mantine remains the component layer.
+The UI is built with **Mantine components**, but **colors and surfaces** should follow the **semantic CSS custom properties** in our themes (`--color-*`, etc.), not ad-hoc Mantine palette values. Those tokens are defined in `packages/app/src/theme/_tokens.scss`, align with a **Click UI**–style system, and are shared by every deployment. They are the path toward a shared design system even while Mantine remains the component layer.
- **Do**: Use Mantine for layout, components, and spacing; use **semantic tokens** for themed backgrounds, text colors, borders, and states (e.g. `style={{ color: 'var(--color-text-muted)' }}` or `style={{ border: '1px solid var(--color-border)' }}`).
- **Do not**: Rely on raw Mantine color props for app chrome and content when a semantic token exists — e.g. `c="gray.5"`, `bg="dark.7"`, or arbitrary `color="blue.4"` for surfaces that should match the rest of the product.
-- **Reference**: `packages/app/src/theme/semanticColorsGrouped.ts` (token names), theme SCSS under `packages/app/src/theme/themes/`, and Storybook (`SemanticColors` and related theme stories) for a visual map.
+- **Reference**: `packages/app/src/theme/semanticColorsGrouped.ts` (token names), `packages/app/src/theme/_tokens.scss`, and Storybook (`SemanticColors` and related theme stories) for a visual map.
Mantine theme overrides in `packages/app/src/theme/**` may map Mantine’s scale to our palette; that does not replace using **`var(--color-...)`** in new styling where you need explicit color control.
@@ -410,7 +410,7 @@ Mantine theme overrides in `packages/app/src/theme/**` may map Mantine’s scale
`@clickhouse/click-ui` is a dependency of `packages/app`. `ThemeWrapper` mounts
`ClickUIProvider` inside `MantineProvider` with `persistTheme={false}`, so it
-follows the HyperDX color mode and never writes its own theme to localStorage.
+follows the app color mode and never writes its own theme to localStorage.
Storybook and `renderWithMantine` in tests get the provider for free.
- **Do**: Prefer a click-ui component over a new Mantine one when click-ui has
diff --git a/agent_docs/data_viz_colors.md b/agent_docs/data_viz_colors.md
index 53fec0618..bc7209e2f 100644
--- a/agent_docs/data_viz_colors.md
+++ b/agent_docs/data_viz_colors.md
@@ -1,6 +1,6 @@
# Data Visualization Colors
-> Single source of truth for chart and visualization colors in HyperDX. Read
+> Single source of truth for chart and visualization colors in ClickStack. Read
> this before adding, changing, or hard-coding a color in any chart, sparkline,
> heatmap, legend, status pill, or other data display.
@@ -51,13 +51,12 @@ and ClickStack:
| `chart-gray` | `#9498a0` |
**Source of truth for categorical hues lives in JS.** The matching
-`--color-chart-{hue}` CSS vars in both
-`packages/app/src/theme/themes/hyperdx/_tokens.scss` and
-`packages/app/src/theme/themes/clickstack/_tokens.scss` are a stylesheet-author
+`--color-chart-{hue}` CSS vars, included from
+`packages/app/src/theme/_tokens.scss`, are a stylesheet-author
affordance only — `getColorFromCSSVariable` and `getColorFromCSSToken` skip
`getComputedStyle` for categorical tokens and return values straight from
-`CATEGORICAL_HEX_BY_TOKEN` in `utils.ts`. The palette is the same on every theme
-today, so a DOM round-trip per series buys nothing.
+`CATEGORICAL_HEX_BY_TOKEN` in `utils.ts`. A DOM round-trip per series buys
+nothing.
The CSS vars exist for:
@@ -69,21 +68,20 @@ The CSS vars exist for:
add per-brand entries to `CATEGORICAL_HEX_BY_TOKEN`.
The categorical hues and semantic chart colors live in a single shared partial,
-`packages/app/src/theme/themes/_chart-categorical-tokens.scss` (`chart-categorical-tokens`
-and `chart-semantic-tokens` mixins). Both brand themes `@use` it and `@include`
-both mixins inside their per-theme `chart-tokens` mixin. Each theme's
-`chart-tokens` mixin is then `@include`'d inside both `[data-mantine-color-scheme]`
-selectors. Sass inlines the bodies at each call site, so the emitted CSS has the
-same per-scheme specificity as a hand-duplicated block would — but the source
-lives in **one place** for both layers. **If you change a categorical hex in the
-shared partial, change it in `CATEGORICAL_HEX_BY_TOKEN` in `utils.ts` too. If
-you change a semantic hex, update `SEMANTIC_CHART_PALETTE` in `utils.ts` too —
-the SCSS and JS sources are intentionally mirrored.**
-
-Brand identity for charts is carried by non-chart UI chrome (Mantine accent,
-sidebar gradient, Click UI globals), not by per-brand chart semantic colors —
-`success` and `info` reuse categorical `chart-green` and `chart-blue` on both
-brands.
+`packages/app/src/theme/_chart-categorical-tokens.scss` (`chart-categorical-tokens`
+and `chart-semantic-tokens` mixins). `theme/_tokens.scss` `@use`s it and
+`@include`s both mixins inside its `chart-tokens` mixin, which is then
+`@include`'d inside both `[data-mantine-color-scheme]` selectors. Sass inlines
+the bodies at each call site, so the emitted CSS has the same per-scheme
+specificity as a hand-duplicated block would — but the source lives in **one
+place**. **If you change a categorical hex in the shared partial, change it in
+`CATEGORICAL_HEX_BY_TOKEN` in `utils.ts` too. If you change a semantic hex,
+update `SEMANTIC_CHART_PALETTE` in `utils.ts` too — the SCSS and JS sources are
+intentionally mirrored.**
+
+Chart series colors are not the brand accent. `success` and `info` reuse
+categorical `chart-green` and `chart-blue`. The yellow ClickStack accent stays
+in non-chart chrome (Mantine accent, sidebar, Click UI globals).
### Semantic chart colors (`--color-chart-{success|warning|error|info}`)
@@ -97,23 +95,22 @@ brands.
--color-chart-error-highlight
```
-Defined in both `_tokens.scss` files. **Unified on both brands**: `success`
-reuses categorical `chart-green` (`#3ca951`); `info` reuses categorical
-`chart-blue` (`#437eef`). Warning and error use the same Observable hexes across
-themes.
+Defined in the shared `chart-semantic-tokens` mixin. `success` reuses
+categorical `chart-green` (`#3ca951`); `info` reuses categorical `chart-blue`
+(`#437eef`). Warning and error use the same Observable hexes.
Unlike the categorical hues, **the semantic CSS vars are read at runtime** via
`getComputedStyle` (see `getSemanticChartColor` in `utils.ts`). That keeps
-inline `var(--color-chart-warning)` consumers like `LogLevel.tsx` reacting to
-theme switches without a React re-render, and it lets JS callers like
-`getChartColorSuccess()` return the correct hex for the active theme.
+inline `var(--color-chart-warning)` consumers like `LogLevel.tsx` in sync with
+the stylesheet, and it lets JS callers like `getChartColorSuccess()` return the
+same hex.
### Single source of truth in TS (`packages/app/src/utils.ts`)
```text
CATEGORICAL_HEX_BY_TOKEN # { 'chart-blue': '#437eef', ... } — file-private,
# authoritative for categorical hues
-SEMANTIC_CHART_PALETTE # { hyperdx: {...}, clickstack: {...} } — file-private,
+SEMANTIC_CHART_PALETTE # { success, warning, error, info, …highlight } — file-private,
# SSR/fallback for the semantic CSS vars
COLORS # ordered hex array, derived from CATEGORICAL_PALETTE_TOKENS
```
@@ -153,14 +150,12 @@ Internals worth knowing:
`CATEGORICAL_HEX_BY_TOKEN` — same shortcut, no `getComputedStyle`.
- Semantic tokens (`chart-success`, `-warning`, `-error`) read
`--color-{token}` from `documentElement` via `getComputedStyle` and fall
- back to the active theme's `SEMANTIC_CHART_PALETTE` entry when running
- server-side or when the DOM read fails.
+ back to `SEMANTIC_CHART_PALETTE` when running server-side or when the DOM
+ read fails.
- `getSemanticChartColor(varName, key)` is the shared helper that backs the
- `getChartColor{Success,Warning,Error,Info}()` readers. It uses
- `detectActiveTheme()` (checks for the `theme-clickstack` class on ``) to
- pick the correct per-brand fallback.
-- During SSR, semantic readers return the **HyperDX** default — the hydration
- mismatch window is tiny because charts render after data fetch on the client.
+ `getChartColor{Success,Warning,Error,Info}()` readers. SSR and DOM-read
+ failures use `SEMANTIC_CHART_PALETTE`. Charts usually render after data
+ fetch on the client, so that fallback rarely reaches the DOM.
### Legacy `chart-1` … `chart-10` tokens
@@ -361,38 +356,21 @@ const slices = sorted.map((d, i) => ({
`ChartUtils.tsx → buildPieChartData` already does this.
-## Per-theme considerations
-
-The categorical palette is identical on both themes — Observable 10. Semantic
-`success` and `info` also reuse categorical hues on both brands.
-
-### HyperDX
+## Color mode
- `--color-chart-success` uses categorical `chart-green` (`#3ca951`).
-- `--color-chart-info` uses categorical `chart-blue` (`#437eef`), so info-level
- logs and `getChartColorInfo()` render the same blue as multi-series slot 0.
-- Multi-series charts start at brand blue (slot 0, `#437eef`) and proceed
- through the canonical palette — brand identity is preserved via the Mantine
- green accent and sidebar gradient, not via chart semantic colors.
-
-### ClickStack
-
+- `--color-chart-info` uses categorical `chart-blue` (`#437eef`, same as
+ `--click-global-color-text-link-default`), so info-level logs and
+ `getChartColorInfo()` render that blue.
- The brand accent is **yellow** (`--palette-brand-300: #faff69`). It is **not**
in the chart palette and should not be added — yellow on a light background
fails contrast, and yellow as a series color reads as "warning" in most
contexts.
-- `--color-chart-success` uses categorical `chart-green` (`#3ca951`).
-- `--color-chart-info` uses categorical `chart-blue` (`#437eef`, same as
- `--click-global-color-text-link-default`), so info-level logs and
- `getChartColorInfo()` render the brand blue.
-
-### Both themes
-
- The dark/light scheme split is handled by CSS (the same vars get redefined
inside each scheme selector). React code does not need to branch on scheme
except for the heatmap palette.
-- The chart vars in `_tokens.scss` are intentionally duplicated across the dark
- and light blocks. If you change one, change the other.
+- The chart vars are intentionally included in both the dark and light blocks.
+ Change the shared mixin, not one selector.
## Adding new entries
@@ -406,8 +384,8 @@ preference:
1. **Group small categories** into "Other" before charting.
2. **Reuse slots** with patterns/strokes/labels for disambiguation.
3. If you really must extend: add `--color-chart-{newhue}` to the shared
- `_chart-categorical-tokens.scss` partial — one edit covers both brands and
- both schemes via the existing `@include` chain. Then append
+ `_chart-categorical-tokens.scss` partial — one edit covers both schemes via
+ the existing `@include` chain. Then append
`'chart-{newhue}'` to `CHART_PALETTE_TOKENS` in `common-utils/src/types.ts`,
add the hex to `CATEGORICAL_HEX_BY_TOKEN` in `utils.ts`, and add a label
entry in `ColorSwatchInput.tsx` → `TOKEN_LABELS` and
@@ -415,15 +393,14 @@ preference:
### A new semantic color (e.g. `--color-chart-pending`)
-1. Pick the hex (unified across brands unless you have a deliberate per-brand split).
+1. Pick the hex.
2. Add `--color-chart-pending` and (if needed) `--color-chart-pending-highlight`
to the `@mixin chart-semantic-tokens` block in
- `_chart-categorical-tokens.scss`. The mixin is `@include`'d in each theme's
- `chart-tokens` mixin, which is `@include`'d in each scheme selector — one edit
- covers dark and light for both brands. For a per-brand override only, declare
- the var in that brand's `chart-tokens` mixin after the shared `@include`.
-3. Add `pending` (and optionally `pendingHighlight`) to
- `SEMANTIC_CHART_PALETTE.hyperdx` and `.clickstack` in `utils.ts`.
+ `_chart-categorical-tokens.scss`. The mixin is `@include`'d from
+ `theme/_tokens.scss` inside each scheme selector — one edit covers dark
+ and light.
+3. Add `pending` (and optionally `pendingHighlight`) to `SEMANTIC_CHART_PALETTE`
+ in `utils.ts`.
4. Append `'chart-pending'` to `CHART_PALETTE_TOKENS` (and
`SEMANTIC_PALETTE_TOKENS` slice will pick it up automatically) in
`common-utils/src/types.ts`.
@@ -470,8 +447,6 @@ Why each is wrong:
## Pre-merge checklist for chart-touching PRs
-- [ ] Toggled HyperDX ↔ ClickStack theme — semantic success and info stay
- unified (chart-green / chart-blue); categorical palette stays identical.
- [ ] Toggled dark ↔ light — categorical and semantic colors stay legible on
both backgrounds; heatmap gradient flips palettes.
- [ ] Status indicators use `getChartColor*()` / `var(--color-chart-*)`, not raw
@@ -483,15 +458,15 @@ Why each is wrong:
`CATEGORICAL_HEX_BY_TOKEN` in `utils.ts`).
- [ ] If you added or changed a semantic hex, changed it in **both** places
(`chart-semantic-tokens` mixin in `_chart-categorical-tokens.scss`,
- `SEMANTIC_CHART_PALETTE.{theme}` in `utils.ts`).
+ `SEMANTIC_CHART_PALETTE` in `utils.ts`).
- [ ] Storybook `Design tokens / Chart colors` still renders correctly.
## File reference summary
| What | Where |
| --------------------------------------------------- | -------------------------------------------------------------------------------- |
-| Shared chart vars (10 categorical hues + semantics) | `packages/app/src/theme/themes/_chart-categorical-tokens.scss` |
-| Per-theme `chart-tokens` mixin (`@include` chain) | `packages/app/src/theme/themes/hyperdx/_tokens.scss`, `clickstack/_tokens.scss` |
+| Shared chart vars (10 categorical hues + semantics) | `packages/app/src/theme/_chart-categorical-tokens.scss` |
+| `chart-tokens` mixin (`@include` chain) | `packages/app/src/theme/_tokens.scss` |
| JS palette objects + reader functions | `packages/app/src/utils.ts` |
| Palette token enum + legacy migration | `packages/common-utils/src/types.ts` |
| Multi-series wiring (`setLineColors` etc.) | `packages/app/src/ChartUtils.tsx` |
diff --git a/agent_docs/evals.md b/agent_docs/evals.md
index ff918e3df..d7e091aa3 100644
--- a/agent_docs/evals.md
+++ b/agent_docs/evals.md
@@ -41,7 +41,7 @@ This is the standard workflow for comparing a feature branch against main.
### Architecture
Evals run from **one worktree** (the branch being tested). The eval harness
-talks to **two separate HyperDX API instances** running on different slots:
+talks to **two separate ClickStack API instances** running on different slots:
```
┌──────────────────────┐
@@ -68,7 +68,7 @@ talks to **two separate HyperDX API instances** running on different slots:
```
Each slot runs its own ClickHouse instance. `setup-hyperdx` (step 2) creates
-the HyperDX account, Connection, and Sources on each instance, but does **not**
+the ClickStack account, Connection, and Sources on each instance, but does **not**
seed telemetry data. The `run` command auto-seeds on first run, but only into
the single ClickHouse specified in the top-level `clickhouse` config — so for
dual-slot comparisons you must seed each instance explicitly (step 4b).
@@ -106,7 +106,7 @@ curl -s -o /dev/null -w "Slot 99 CH: %{http_code}\n" http://localhost:30599/
> branch under test).
This registers an eval account, creates a ClickHouse Connection, and creates
-per-scenario Sources on each HyperDX instance. The command is **idempotent** —
+per-scenario Sources on each ClickStack instance. The command is **idempotent** —
it skips anything that already exists, so it's safe to run every time.
**Skip this step** if `eval.config.branch.json` and `eval.config.main.json`
@@ -189,7 +189,7 @@ curl -s -o /dev/null -w "Main MCP: %{http_code}\n" \
### 5. Seed both ClickHouse instances
-`setup-hyperdx` creates the HyperDX account and Sources but does **not** seed
+`setup-hyperdx` creates the ClickStack account and Sources but does **not** seed
telemetry data. The `run` command's auto-seed only writes to the single
ClickHouse in the top-level `clickhouse` config, so you must seed each
instance explicitly:
@@ -267,10 +267,10 @@ yarn workspace @hyperdx/hdx-eval dev run error-root-cause \
--mcp hyperdx --model claude-opus-4-6 --runs 3
```
-### Non-HyperDX MCP (e.g. raw ClickHouse)
+### Non-ClickStack MCP (e.g. raw ClickHouse)
The framework works with any MCP. The `clickhouse` stdio MCP is included by
-default in `eval.config.json` after setup. Use it to compare HyperDX's MCP
+default in `eval.config.json` after setup. Use it to compare ClickStack's MCP
against querying ClickHouse directly.
```bash
diff --git a/agent_docs/observability.md b/agent_docs/observability.md
index a814e3643..1de5356b4 100644
--- a/agent_docs/observability.md
+++ b/agent_docs/observability.md
@@ -1,6 +1,6 @@
# Observability & Instrumentation
-HyperDX is an observability product, so our own code should be a shining example
+ClickStack is an observability product, so our own code should be a shining example
of well-instrumented software. When you add or change a feature, instrument it
as part of the change - not as an afterthought.
@@ -30,7 +30,7 @@ aligned with the
already in flight, and put point-in-time / gauge-style values (sizes, counts,
depths, current state) there rather than in a gauge. This is an internal
engineering preference, not a rule against metrics — counters and histograms
- remain first-class, feed alerts and SLOs, and many HyperDX deployments depend
+ remain first-class, feed alerts and SLOs, and many ClickStack deployments depend
heavily on them. See [Wide events over gauges](#wide-events-over-gauges).
5. **Use the shared helpers** in
[`packages/api/src/utils/instrumentation.ts`](../packages/api/src/utils/instrumentation.ts).
@@ -47,7 +47,7 @@ All manual instrumentation in `packages/api` goes through
| Helper | Purpose |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `withSpan(name, fn, opts?)` | Run an async unit of work in an active span. Records exceptions, sets OK/ERROR status, always ends the span. |
-| `setBusinessContext({ teamId, userId, email, ...extra })` | Attach standardized incident-remediation context to the trace + active span. |
+| `setBusinessContext({ teamId, userId, email, ...extra })` | Attach standardized incident-remediation context to the active span and the request's HTTP server span. |
| `getStaticFeatureFlags()` | Returns the static (env/compile-time) feature-flag states as `feature_flag.*` attributes. |
| `getCounter(name, opts?)` / `getHistogram(name, opts?)` | Memoized OTel instrument accessors. Always use these instead of `meter.create*`. |
| `recordDuration(histogram, fn, attrs?)` | Run `fn`, recording its wall-clock duration on a histogram (even on throw). |
@@ -57,10 +57,10 @@ types, so a single import is usually enough.
### Tracing
-Rely on the HyperDX SDK auto-instrumentation (HTTP, Express, Mongo, etc.) for
-the common path. Add a **manual span only for a meaningful unit of work** that
-auto-instrumentation can't see - a background job step, a fan-out, an expensive
-computation, an external tool invocation.
+Rely on the ClickStack SDK (`@clickhouse/clickstack-node`) auto-instrumentation
+(HTTP, Express, Mongo, etc.) for the common path. Add a **manual span only for a
+meaningful unit of work** that auto-instrumentation can't see - a background job
+step, a fan-out, an expensive computation, an external tool invocation.
```ts
import { withSpan } from '@/utils/instrumentation';
@@ -91,8 +91,10 @@ Span rules to follow (from the Instrumentation Score spec):
### Business context
Attach team/user context as early as possible (at the auth boundary or the top
-of a job). `setBusinessContext` writes both to the whole trace (via the HyperDX
-SDK, requires `HDX_NODE_BETA_MODE=1`) and to the active span.
+of a job). `setBusinessContext` writes to the active span and, inside an HTTP
+request, to the request's HTTP server span, so the context stays on the request
+even when the active span is a short Express middleware span. Other spans in the
+trace do not get it.
```ts
import {
@@ -120,9 +122,9 @@ Standard attribute keys:
### Wide events over gauges
-> **Scope:** this is HyperDX's _internal_ instrumentation philosophy for the
+> **Scope:** this is ClickStack's _internal_ instrumentation philosophy for the
> code in this repo — not a recommendation that users pick wide events over
-> metrics. Metrics are a first-class HyperDX signal that many operators rely on;
+> metrics. Metrics are a first-class ClickStack signal that many operators rely on;
> nothing here discourages them. What follows is simply how _we_ prefer to
> instrument our own services.
@@ -237,7 +239,7 @@ auto-instrumentation and error middleware already cover.
## Query attribution
-Every ClickHouse query HyperDX runs is tagged with what asked for it, so a row
+Every ClickHouse query ClickStack runs is tagged with what asked for it, so a row
in the customer's `system.query_log` points back to a dashboard tile, a saved
search, an alert, or an MCP tool. This is the one piece of our instrumentation
that lands in *their* data rather than ours, so it stays small, carries no
@@ -303,9 +305,10 @@ calls `/api/v1/prometheus/query{,_range}`, and `/labels` and
(`QUERY_ATTRIBUTION_HEADER`), and the router parses it with `parseLogComment`
into a `withQueryAttribution` scope layered over the auth middleware's `api`
scope. The browser's surface and ids win; `trace` and `label` stay the
-server's. Queries the route runs through a ClickHouse client (label lookups,
-and the `prometheusQuery()`/`prometheusQueryRange()` fallback) pick the scope
-up as usual. Requests proxied to ClickHouse's Prometheus HTTP API on 26.6+ are tagged
+server's. Queries the route runs through a ClickHouse client (label lookups
+before 26.9, and the `prometheusQuery()`/`prometheusQueryRange()` fallback)
+pick the scope up as usual. Requests proxied to ClickHouse's Prometheus HTTP
+API (queries on 26.6+, label lookups on 26.9+) are tagged
by `clickhousePrometheusRequest`: `log_comment` as a URL setting, `query_id` as
the `X-ClickHouse-Query-Id` header, because the handler rejects `query_id` as an
unknown setting in the URL.
diff --git a/agent_docs/page_layout.md b/agent_docs/page_layout.md
index c1ca24476..cde50f3c0 100644
--- a/agent_docs/page_layout.md
+++ b/agent_docs/page_layout.md
@@ -1,6 +1,6 @@
# Page layout and headers
-HyperDX 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
diff --git a/agent_docs/tech_stack.md b/agent_docs/tech_stack.md
index 330cd238c..dab5aac5c 100644
--- a/agent_docs/tech_stack.md
+++ b/agent_docs/tech_stack.md
@@ -1,4 +1,4 @@
-# HyperDX Technology Stack
+# ClickStack Technology Stack
## Frontend (`packages/app`)
@@ -20,7 +20,7 @@ Mantine primitives → Custom SCSS modules as last resort
- **Database**: ClickHouse (telemetry data), MongoDB via Mongoose (metadata)
- **Authentication**: Passport.js with local strategy
- **Validation**: Zod schemas
-- **Telemetry**: Self-instrumented with `@hyperdx/node-opentelemetry`
+- **Telemetry**: Self-instrumented with `@clickhouse/clickstack-node` (API and Next.js server) and `@clickhouse/clickstack-browser` (frontend)
## Common Utilities (`packages/common-utils`)
diff --git a/agent_docs/themes.md b/agent_docs/themes.md
index e162f9c9a..c32265080 100644
--- a/agent_docs/themes.md
+++ b/agent_docs/themes.md
@@ -1,179 +1,94 @@
-# Themes (HyperDX & ClickStack)
+# Appearance (ClickStack + color mode)
-> How the brand theme system works, how it interacts with light/dark color
-> mode, and where to make changes safely. Read this before touching anything
-> in `packages/app/src/theme/`, before adding a new brand, or before
-> hard-coding any color, logo, or favicon path in the app.
+> How colors, logos, and light/dark mode work. Read this before changing
+> anything in `packages/app/src/theme/`, adding a semantic CSS variable, or
+> hard-coding a color, logo, or favicon path.
>
-> For **chart colors specifically** (categorical palette, heatmap gradient,
-> semantic success/warn/error chart colors) see
-> [`data_viz_colors.md`](data_viz_colors.md) — it covers the chart-specific
-> rules in more depth. This doc covers everything else.
+> For chart colors see [`data_viz_colors.md`](data_viz_colors.md).
## TL;DR
-The app has **two independent theming concepts**:
-
-| Concept | Values | Who controls it | Stored in | What it affects |
-| ------------------ | ------------------------------ | --------------------------- | ------------------------------------------ | ----------------------------------------------------- |
-| **Brand theme** | `hyperdx` \| `clickstack` | Deployment (build/env) | `NEXT_PUBLIC_THEME` + html class | Branding: logos, favicons, accent colors, fonts |
-| **Color mode** | `light` \| `dark` \| `system` | End user (preferences UI) | `localStorage: hdx-user-preferences` | Light/dark appearance: backgrounds, text, borders |
-
-Each deployment ships **one** brand theme. Users can flip between light and
-dark inside that brand but cannot switch brands in production. In dev you
-can override the brand via `window.__HDX_THEME.set('clickstack')`.
-
-The runtime wiring is:
-
-1. Server-side (`pages/_document.tsx`) puts `theme-hyperdx` or
- `theme-clickstack` on `` based on `NEXT_PUBLIC_THEME`.
-2. An inline script (`SystemColorSchemeScript`) sets
- `data-mantine-color-scheme="light|dark"` on `` from
- `localStorage.hdx-user-preferences.colorMode` before React hydrates.
-3. SCSS in `packages/app/src/theme/themes/{brand}/_tokens.scss` defines all
- semantic CSS variables (`--color-bg-body`, `--color-text-primary`, …)
- inside `.theme-{brand}[data-mantine-color-scheme='{mode}']` selectors —
- one block per (brand × mode) combination, four blocks total.
-4. Mantine config (`{brand}/mantineTheme.ts`) sets `primaryColor`,
- font, spacing, and per-component overrides — most colors come back out
- via CSS vars rather than Mantine palette entries.
-5. React reads the active brand via `useAppTheme()` (rarely needed —
- prefer CSS vars).
+The product is ClickStack. There is no brand switch, no `NEXT_PUBLIC_THEME`,
+and no second palette.
-**Hard rules**:
+| Concept | Values | Who controls it | Stored in | What it affects |
+| -------------- | ----------------------------- | ------------------------- | ------------------------------------ | ------------------------------------------------- |
+| **Color mode** | `light` \| `dark` \| `system` | End user (preferences) | `localStorage: hdx-user-preferences` | Backgrounds, text, borders |
-- **Never** hard-code a hex/named color in a component. Use a semantic CSS
- var (`var(--color-bg-surface)`, `var(--color-text-primary)`, …).
-- **Never** branch on `themeName` to choose colors. The CSS var already
- resolves to the right value per brand. Branching is OK for *layout* or
- *content* differences (different copy, different logo placement) — not
- colors.
-- **Never** confuse `IS_CLICKHOUSE_BUILD` with the theme. That flag gates
- *features* (e.g. embedded mode, ClickHouse Cloud onboarding) and is
- unrelated to brand colors. A `clickstack`-themed build can have
- `IS_CLICKHOUSE_BUILD=false` and vice versa.
+The UI font is Inter. Mono faces (IBM Plex Mono, Roboto Mono) stay available
+for logs and code. The preferences modal does not offer a font picker.
-## Brand theme
+Color mode:
-### Where the themes are defined
+- Values: `'system' | 'light' | 'dark'`. Default `'system'`.
+- `'system'` follows `window.matchMedia('(prefers-color-scheme: dark)')`.
+- `SystemColorSchemeScript` sets `data-mantine-color-scheme` on ``
+ before React hydrates.
+- `useResolvedColorScheme()` returns `'light' | 'dark'` for `ThemeWrapper`,
+ which passes it to `MantineProvider` as `forceColorScheme`.
-Everything lives under `packages/app/src/theme/`:
+Older stored preferences used a `theme` key for light/dark. Migration in
+`useUserPreferences.tsx` rewrites that to `colorMode`. Don't reintroduce
+the old name.
-```text
-theme/
-├── index.ts # Registry, validation, DEFAULT_THEME, getDevThemeName
-├── types.ts # ThemeName, ThemeConfig, FaviconConfig types
-├── ThemeProvider.tsx # AppThemeProvider + useAppTheme/useWordmark/useLogomark hooks
-├── semanticColorsGrouped.ts # Grouping metadata for the storybook
-├── ChartColors.stories.tsx # Visual reference for chart palette
-├── SemanticColors.stories.tsx# Visual reference for semantic vars
-├── themes/
-│ ├── _base-tokens.scss # Fallback vars when no theme class is applied (SSR safety)
-│ ├── components.module.scss# Shared component overrides (slider marks, etc.)
-│ ├── hyperdx/
-│ │ ├── index.ts # ThemeConfig export: name, displayName, logos, favicon, mantineTheme
-│ │ ├── _tokens.scss # All semantic CSS vars (dark + light), scoped to .theme-hyperdx
-│ │ ├── mantineTheme.ts # Mantine palette + component overrides
-│ │ ├── Logomark.tsx # Icon-only logo (used in collapsed sidenav, favicons context)
-│ │ └── Wordmark.tsx # Full "HyperDX" wordmark
-│ └── clickstack/
-│ ├── index.ts # Same shape as hyperdx/index.ts
-│ ├── _tokens.scss # Same shape — adds Click UI palette + yellow brand
-│ ├── mantineTheme.ts # Same shape — yellow primaryColor
-│ ├── Logomark.tsx
-│ └── Wordmark.tsx
-└── __tests__/ # ThemeProvider + theme validation tests
-```
-
-Favicons live under `packages/app/public/favicons/{brand}/`. The
-`FaviconConfig` type in `types.ts` enforces the directory/filename
-convention via Zod.
-
-### Each `ThemeConfig` ships:
-
-```ts
-type ThemeConfig = {
- name: 'hyperdx' | 'clickstack';
- displayName: string; // 'HyperDX' | 'ClickStack' — used in UI copy
- cssClass: string; // 'theme-hyperdx' | 'theme-clickstack'
- mantineTheme: MantineThemeOverride;
- Wordmark: React.ComponentType;
- Logomark: React.ComponentType<{ size?: number }>;
- favicon: { svg, png32, png16, appleTouchIcon, themeColor };
-};
+```html
+
```
-The registry in `theme/index.ts` validates both themes against a Zod
-schema at module load time. In production, a failed validation throws;
-in development it logs and falls back to `hyperdx`.
+Tokens live in `packages/app/src/theme/_tokens.scss`, scoped to
+`[data-mantine-color-scheme='dark']` and
+`[data-mantine-color-scheme='light']`.
+`packages/app/src/theme/_base-tokens.scss` imports that file.
+Mantine component overrides are in `packages/app/src/theme/mantineTheme.ts`.
-### How brand resolution works at runtime
-
-| Phase | Source of truth | Notes |
-| --------------------------- | -------------------------------------------------- | ---------------------------------------------------------------------------------- |
-| SSR (`_document.tsx`) | `process.env.NEXT_PUBLIC_THEME` | Adds `theme-{name}` class to `` so SCSS vars resolve on the first paint. |
-| Initial React render | `propsThemeName ?? DEFAULT_THEME` in provider | Matches SSR — never reads localStorage during render to avoid hydration mismatch. |
-| Post-hydration (dev only) | `localStorage.hdx-dev-theme` via `getDevThemeName` | Updates state in a `useEffect`. Causes a one-frame flash; intentional for dev UX. |
-| Post-hydration (prod) | Stable — no reads from storage | `setTheme`/`toggleTheme` are no-ops in production. Confirmed by the `IS_DEV` gate. |
-
-`IS_DEV` is true when `NODE_ENV === 'development'` **or**
-`NEXT_PUBLIC_IS_LOCAL_MODE === 'true'` — so the OSS local-mode build also
-exposes the dev theme switcher in `UserPreferencesModal`.
-
-### Dev-mode theme switching
-
-Three ways to flip brand in dev:
-
-1. **UI**: open the user preferences modal — there's a "Brand theme"
- select gated on `isDev`.
-2. **Console**: `window.__HDX_THEME.set('clickstack')`,
- `window.__HDX_THEME.toggle()`, `window.__HDX_THEME.clear()`.
-3. **Storage**: set `localStorage.setItem('hdx-dev-theme', 'clickstack')`
- and reload.
+**Hard rules**:
-`clear()` removes the override and reverts to `NEXT_PUBLIC_THEME` (or
-`hyperdx` if unset).
+- Don't hard-code a hex or named color in a component. Use a semantic CSS
+ var (`var(--color-bg-surface)`, `var(--color-text-primary)`, …).
+- Don't branch on color mode to pick a semantic color. The var already
+ resolves. Branch only when a component truly needs a different asset
+ (for example the heatmap palette).
+- Don't confuse `IS_CLICKHOUSE_BUILD` with appearance. That flag gates
+ features (embedded mode, ClickHouse Cloud onboarding).
-## Color mode (light / dark / system)
+## Brand
-Color mode is **per-user**, persisted to
-`localStorage.hdx-user-preferences` under the `colorMode` key. Defined in
-`packages/app/src/useUserPreferences.tsx`:
+Product name, page titles, and logos come from `packages/app/src/brand/`.
+`useBrandDisplayName()` and `usePageTitle()` return ClickStack (plus
+`INSTANCE_TITLE_SUFFIX` on titles). `useWordmark()` and `useLogomark()`
+return the marks in that folder. Call sites use those hooks. A downstream
+build replaces `brand/` and keeps the same call sites. The color tokens
+stay shared.
-- Values: `'system' | 'light' | 'dark'`. Default `'system'`.
-- `'system'` follows `window.matchMedia('(prefers-color-scheme: dark)')`
- and reacts to changes.
-- The inline `SystemColorSchemeScript` (rendered very early) sets
- `data-mantine-color-scheme` before React hydrates so there's no flash.
-- `useResolvedColorScheme()` returns the resolved `'light' | 'dark'` for
- consumption by `ThemeWrapper` (which forwards it to `MantineProvider`
- as `forceColorScheme`).
-
-The user preferences storage also handles **migration from the legacy
-`theme` key** — older versions used `theme: 'light'|'dark'|'system'`;
-the migration code in `useUserPreferences.tsx` rewrites it to
-`colorMode` so existing users don't lose their preference. Don't
-re-introduce the old name.
-
-### Why two attributes (`class` + `data-attr`)?
+```tsx
+import { useLogomark, useWordmark } from '@/brand';
-```html
-
+function TopBar() {
+ const logo = useLogomark({ size: 24 });
+ const wordmark = useWordmark();
+ return (
+
+ {logo}
+ {wordmark}
+
+ );
+}
```
-The combined selector `.theme-clickstack[data-mantine-color-scheme='dark']`
-in `_tokens.scss` lets a single SCSS file define **all four** variants
-(2 brands × 2 modes) without duplication at the call site. Each block
-redefines `--color-bg-body`, `--color-text`, etc. for that specific
-combination. There is no JS branching on brand/mode for color
-resolution — CSS handles it.
+Favicons are static links in `packages/app/pages/_document.tsx`, under
+`packages/app/public/favicons/clickstack/`.
-## How to consume themes in code
+ClickStack specifics:
-### From CSS / SCSS
+- Mantine `primaryColor: 'yellow'`. The yellow ramp is the Click UI brand
+ palette (`--palette-brand-*`) from `theme/_tokens.scss`.
+- Accent `#faff69` (`--palette-brand-300`) is for links and outlines, not
+ chart series.
+- Warning tokens use Mantine `orange`, because yellow is the brand gold.
+- Most semantic vars reference Click UI globals (`--click-global-color-*`).
+- Tabler icons use `stroke-width: 1.5`.
-Just use the semantic vars. They resolve automatically based on the
-brand + mode classes on ``:
+## How to consume colors
```scss
.sidenav {
@@ -181,339 +96,57 @@ brand + mode classes on ``:
color: var(--color-text-sidenav-link);
border-right: 1px solid var(--color-border);
}
-
-.sidenav__link[data-active='true'] {
- background: var(--color-bg-sidenav-link-active);
- color: var(--color-text-sidenav-link-active);
-}
-```
-
-The full list of semantic vars is in
-`packages/app/src/theme/semanticColorsGrouped.ts` (used to build the
-storybook story). Categories: backgrounds, borders, text, icons,
-overlay, states, json (syntax highlight), charts.
-
-### From React (inline style, when CSS won't reach)
-
-Use the var string directly in `style={}` — `MantineProvider` doesn't
-need to know about it:
-
-```tsx
-
```
-Use **`useMantineColorScheme()`** when you genuinely need to branch on
-`light` vs `dark` (e.g. picking a heatmap palette). Don't branch on it
-to pick a semantic color — the var does that for you.
+The list of semantic vars is in
+`packages/app/src/theme/semanticColorsGrouped.ts`. In React, use the var
+string in `style={{}}`. Use `useMantineColorScheme()` only when you must
+branch on light vs dark.
-### From React (reading the active brand)
+### Semantic component variants
-```tsx
-import { useAppTheme, useThemeName, useBrandDisplayName } from '@/theme/ThemeProvider';
+Prefer these over raw Mantine palette props (`color="yellow"`, `c="green"`):
-function Header() {
- const { theme } = useAppTheme(); // full ThemeConfig
- const themeName = useThemeName(); // 'hyperdx' | 'clickstack'
- const brand = useBrandDisplayName(); // 'HyperDX' | 'ClickStack' — use in UI copy
- // …
-}
-```
+- ``
+- ``
+- `
{defaultValues
- ? 'Save Alert'
+ ? 'Save alert'
: hasSavedSearch
- ? 'Create Alert'
- : 'Save Search with Alert'}
+ ? 'Create alert'
+ : 'Save search and alert'}
@@ -480,22 +556,22 @@ export const DBSearchPageAlertModal = ({
}
};
- const [name, setName] = React.useState('');
+ const newSavedSearchForm = useForm({
+ defaultValues: { name: '' },
+ });
+ const [newSavedSearchTags, setNewSavedSearchTags] = React.useState(
+ [],
+ );
const onSubmit = async (data: Alert) => {
try {
// Create new search along with alert
if (!id && searchedConfig) {
- if (!name) {
- notifications.show({
- color: 'red',
- message: 'Please provide a name for the saved search.',
- autoClose: 5000,
- });
+ if (!(await newSavedSearchForm.trigger())) {
return;
}
const result = await createSavedSearch.mutateAsync({
- name,
+ name: newSavedSearchForm.getValues('name').trim(),
select: searchedConfig.select ?? '',
where: searchedConfig.where ?? '',
whereLanguage:
@@ -503,7 +579,7 @@ export const DBSearchPageAlertModal = ({
source: searchedConfig.source ?? '',
orderBy: searchedConfig.orderBy ?? '',
filters: searchedConfig.filters ?? [],
- tags: [],
+ tags: newSavedSearchTags,
});
await createAlert.mutateAsync({
...data,
@@ -590,56 +666,49 @@ export const DBSearchPageAlertModal = ({
}}
loaderProps={{ type: 'dots' }}
/>
-
-
+
+ {id ? (
Alerts for {savedSearch?.name}
- {!id && (
- setName(e.currentTarget.value)}
- required
- />
- )}
-
- {savedSearch?.where}
+ ) : (
+
+ )}
+ {savedSearch?.where ?? searchedConfig?.where}
-
-
- {(savedSearch?.alerts || []).map((alert, index) => (
-
-
- {getWebhookChannelIcon(alert.channel?.type)}
- Alert {index + 1}
-
+ {/* An unsaved search has no alerts to switch between, and the one tab
+ left reads as a control that does something. */}
+ {id && (
+
+
+ {(savedSearch?.alerts || []).map((alert, index) => (
+
+
+ {getWebhookChannelIcon(alert.channel?.type)}
+ Alert {index + 1}
+
+
+
+ ))}
+
+
+
+ New alert
- ))}
-
-
-
- New Alert
-
-
-
-
+
+
+ )}
void newSavedSearchForm.trigger()
+ }
onDelete={onDelete}
deleteLoading={deleteAlert.isPending}
onClose={onClose}
diff --git a/packages/app/src/DBServiceMapPage.tsx b/packages/app/src/DBServiceMapPage.tsx
index 459cf3bae..8945769d1 100644
--- a/packages/app/src/DBServiceMapPage.tsx
+++ b/packages/app/src/DBServiceMapPage.tsx
@@ -34,6 +34,10 @@ import { PageLayout } from '@/components/PageLayout';
import SearchWhereInput, {
getStoredLanguage,
} from '@/components/SearchInput/SearchWhereInput';
+import { parseServiceMapGroupBy } from '@/components/ServiceMap/dimensions';
+import ServiceMapGroupByInput, {
+ ServiceMapSearchFormValues,
+} from '@/components/ServiceMap/ServiceMapGroupByInput';
import { IS_LOCAL_MODE } from '@/config';
import { useGetKeyValues } from '@/hooks/useMetadata';
import { useResolvedSourceParam } from '@/hooks/useResolvedSourceParam';
@@ -49,7 +53,7 @@ import SourceSchemaPreview, {
} from './components/SourceSchemaPreview';
import { SourceSelectControlled } from './components/SourceSelect';
import { TimePicker } from './components/TimePicker';
-import { usePageTitle } from './theme/ThemeProvider';
+import { usePageTitle } from './brand';
import { useSources } from './source';
import { useDefaultTimeRange, useNewTimeQuery } from './timeQuery';
@@ -86,6 +90,8 @@ const searchQueryStateMap = {
where: parseAsStringEncoded,
whereLanguage: parseAsStringEnum<'sql' | 'lucene'>(['sql', 'lucene']),
services: parseAsArrayOf(parseAsString),
+ // Comma-separated SQL expressions the nodes are split by, after ServiceName.
+ groupBy: parseAsStringEncoded,
};
function DBServiceMapPage() {
@@ -121,14 +127,22 @@ function DBServiceMapPage() {
// useResolvedSourceParam will show a notification to the user.
const source = paramSource ?? defaultSource;
- const { control, handleSubmit, setValue } = useForm({
- values: {
- source: source?.id,
- where: searchedConfig.where ?? '',
- whereLanguage:
- searchedConfig.whereLanguage ?? getStoredLanguage() ?? 'lucene',
- },
- });
+ const groupBy = useMemo(
+ () => parseServiceMapGroupBy(searchedConfig.groupBy),
+ [searchedConfig.groupBy],
+ );
+ const { control, handleSubmit, setValue } =
+ useForm({
+ values: {
+ source: source?.id,
+ where: searchedConfig.where ?? '',
+ whereLanguage:
+ searchedConfig.whereLanguage ?? getStoredLanguage() ?? 'lucene',
+ // Seeded from the parsed list so the editor shows exactly what the map
+ // is grouped by, even for a hand-edited URL with too many expressions.
+ groupBy: groupBy.join(', '),
+ },
+ });
const watchedSource = useWatch({ control, name: 'source' });
const [isSourceSchemaPreviewOpen, setIsSourceSchemaPreviewOpen] =
@@ -207,10 +221,17 @@ function DBServiceMapPage() {
[setSearchedConfig],
);
+ // The time range is applied together with the form values, so an invalid
+ // group-by leaves the URL untouched instead of moving the time window.
const onSubmit = useCallback(() => {
- onSearch(displayedTimeInputValue);
- handleSubmit(({ where, whereLanguage }) => {
- setSearchedConfig(prev => ({ ...prev, where, whereLanguage }));
+ handleSubmit(({ where, whereLanguage, groupBy }) => {
+ onSearch(displayedTimeInputValue);
+ setSearchedConfig(prev => ({
+ ...prev,
+ where,
+ whereLanguage,
+ groupBy: groupBy || null,
+ }));
})();
}, [handleSubmit, setSearchedConfig, displayedTimeInputValue, onSearch]);
@@ -410,6 +431,13 @@ function DBServiceMapPage() {
sqlPlaceholder="SQL WHERE to filter spans (ex. Duration > 1000000)"
minWidth="min(500px, 100%)"
/>
+ 0 ? selectedServices : undefined
}
+ groupBy={groupBy}
onFocusService={onFocusService}
/>
>
diff --git a/packages/app/src/DOMPlayer.tsx b/packages/app/src/DOMPlayer.tsx
index a711b5e30..993dd5248 100644
--- a/packages/app/src/DOMPlayer.tsx
+++ b/packages/app/src/DOMPlayer.tsx
@@ -157,7 +157,7 @@ export default function DOMPlayer({
handleDroppedEventRef.current = (error, context) => {
// Surfaced unconditionally: dropped events (e.g. a dropped full snapshot)
// can render the replay empty/unstyled with no other signal.
- // https://github.com/hyperdxio/hyperdx/issues/2569
+ // https://github.com/ClickHouse/ClickStack/issues/2569
console.error('Failed to load session replay event', context, error);
setDroppedEventCount(count => count + 1);
};
diff --git a/packages/app/src/DashboardFilters.tsx b/packages/app/src/DashboardFilters.tsx
index cf5f92623..5c15cdf9a 100644
--- a/packages/app/src/DashboardFilters.tsx
+++ b/packages/app/src/DashboardFilters.tsx
@@ -25,6 +25,7 @@ import {
DashboardFilterLabel,
FilterCaution,
FilterEffect,
+ getPendingVariablesTooltip,
} from './components/DashboardFilterLabel';
import { FilterLinkToggle } from './components/FilterLinkToggle';
import { VirtualMultiSelect } from './components/VirtualMultiSelect/VirtualMultiSelect';
@@ -46,20 +47,6 @@ interface DashboardFilterSelectProps {
pendingVariables?: string[];
}
-/**
- * Explain a dropdown query that may list nothing until one of the variables it
- * depends on is selected. Only the bare SQL reference form gets here — the
- * macros and Lucene both have an empty state that lists every value.
- */
-export const getPendingVariablesTooltip = (
- pendingVariables: string[],
-): string => {
- const names = pendingVariables.map(name => `$${name}`).join(', ');
- return `Filter depends on ${names}, which ${
- pendingVariables.length === 1 ? 'has' : 'have'
- } no selected value.`;
-};
-
/**
* Explain a required filter that has nothing selected, naming how far the block
* it imposes reaches.
@@ -184,6 +171,8 @@ interface DashboardFilterProps {
* as the gate for variable-specific copy.
*/
variables?: ChartVariable[];
+ /** Required filters with nothing selected, which can block ad hoc filters. */
+ unsatisfiedRequiredFilters?: DashboardFilter[];
}
const DashboardFilters = ({
@@ -194,6 +183,7 @@ const DashboardFilters = ({
adhocConditionsByFilterId,
onSetAdhocConditions,
variables,
+ unsatisfiedRequiredFilters,
}: DashboardFilterProps) => {
// "Link" mode (opt-in, off by default): each dropdown's values are narrowed by
// the others' selections. Off by default because contingent value lookups
@@ -235,6 +225,8 @@ const DashboardFilters = ({
}
dateRange={dateRange}
effect={getFilterEffect(filter)}
+ variables={variables}
+ unsatisfiedRequiredFilters={unsatisfiedRequiredFilters}
/>
);
}
diff --git a/packages/app/src/HDXMultiSeriesTableChart.tsx b/packages/app/src/HDXMultiSeriesTableChart.tsx
index 9392dd5fa..5df9362e6 100644
--- a/packages/app/src/HDXMultiSeriesTableChart.tsx
+++ b/packages/app/src/HDXMultiSeriesTableChart.tsx
@@ -1,6 +1,7 @@
import { useCallback, useMemo, useState } from 'react';
import Link from 'next/link';
import cx from 'classnames';
+import { MAX_TABLE_ROWS } from '@hyperdx/common-utils/dist/core/utils';
import {
ChartPaletteToken,
ColorCondition,
@@ -34,7 +35,7 @@ import DBRowTableFieldWithPopover, {
import TableHeader from './components/DBTable/TableHeader';
import { useCsvExport } from './hooks/useCsvExport';
import type { RowAction } from './hooks/useOnClickLinkBuilder';
-import { useBrandDisplayName } from './theme/ThemeProvider';
+import { useBrandDisplayName } from './brand';
import { UNDEFINED_WIDTH } from './tableUtils';
import type { NumberFormat } from './types';
import {
@@ -48,9 +49,6 @@ import focusStyles from '@styles/focus.module.scss';
export type TableVariant = 'default' | 'muted';
-// Arbitrary limit to prevent OOM crashes for very large result sets. Most result sets should be paginated anyway.
-export const MAX_TABLE_ROWS = 10_000;
-
export const Table = ({
data,
groupColumnName,
diff --git a/packages/app/src/JoinTeamPage.tsx b/packages/app/src/JoinTeamPage.tsx
index ec4e4e3b4..53f4ddd31 100644
--- a/packages/app/src/JoinTeamPage.tsx
+++ b/packages/app/src/JoinTeamPage.tsx
@@ -10,7 +10,7 @@ import {
TextInput,
} from '@mantine/core';
-import { usePageTitle } from './theme/ThemeProvider';
+import { usePageTitle } from './brand';
import { PasswordCheck } from './PasswordCheck';
export default function JoinTeam() {
diff --git a/packages/app/src/KubernetesDashboardPage.tsx b/packages/app/src/KubernetesDashboardPage.tsx
index 03d89effe..274a05dd7 100644
--- a/packages/app/src/KubernetesDashboardPage.tsx
+++ b/packages/app/src/KubernetesDashboardPage.tsx
@@ -58,7 +58,7 @@ import { SourceSelectControlled } from './components/SourceSelect';
import { useQueriedChartConfig } from './hooks/useChartConfig';
import { useDashboardRefresh } from './hooks/useDashboardRefresh';
import { useJsonColumns } from './hooks/useMetadata';
-import { usePageTitle } from './theme/ThemeProvider';
+import { usePageTitle } from './brand';
import {
convertV1ChartConfigToV2,
K8S_CPU_PERCENTAGE_NUMBER_FORMAT,
diff --git a/packages/app/src/LandingHeader.tsx b/packages/app/src/LandingHeader.tsx
index e5889011a..4b85ceacb 100644
--- a/packages/app/src/LandingHeader.tsx
+++ b/packages/app/src/LandingHeader.tsx
@@ -2,8 +2,8 @@ import Link from 'next/link';
import { Anchor, Burger, Button, Container, Group } from '@mantine/core';
import { useDisclosure } from '@mantine/hooks';
-import { useBrandDisplayName, useWordmark } from './theme/ThemeProvider';
import api from './api';
+import { useBrandDisplayName, useWordmark } from './brand';
export default function LandingHeader({
activeKey,
diff --git a/packages/app/src/OnboardingChecklist/useOnboardingCompletion.ts b/packages/app/src/OnboardingChecklist/useOnboardingCompletion.ts
index 211d8de1d..386fbf819 100644
--- a/packages/app/src/OnboardingChecklist/useOnboardingCompletion.ts
+++ b/packages/app/src/OnboardingChecklist/useOnboardingCompletion.ts
@@ -3,11 +3,11 @@ import { escapeSqlString } from '@hyperdx/common-utils/dist/core/utils';
import { isPersistableUserId } from '@hyperdx/common-utils/dist/types';
import api from '@/api';
+import { useBrandDisplayName } from '@/brand';
import { NOW } from '@/config';
import { useConnections } from '@/connection';
import { useQueriedChartConfig } from '@/hooks/useChartConfig';
import { useSources } from '@/source';
-import { useBrandDisplayName } from '@/theme/ThemeProvider';
import {
OnboardingStep,
diff --git a/packages/app/src/ServicesDashboardPage/ServicesDashboardPage.tsx b/packages/app/src/ServicesDashboardPage/ServicesDashboardPage.tsx
index d70302065..59ab35443 100644
--- a/packages/app/src/ServicesDashboardPage/ServicesDashboardPage.tsx
+++ b/packages/app/src/ServicesDashboardPage/ServicesDashboardPage.tsx
@@ -38,6 +38,7 @@ import {
IconRefresh,
} from '@tabler/icons-react';
+import { usePageTitle } from '@/brand';
import DashboardFiltersModal from '@/components/DashboardFiltersModal';
import OnboardingModal from '@/components/OnboardingModal';
import SearchWhereInput, {
@@ -57,7 +58,6 @@ import { useResolvedSourceParam } from '@/hooks/useResolvedSourceParam';
import { withAppNavForSurface } from '@/layout';
import { useServiceDashboardExpressions } from '@/serviceDashboard';
import { useSource, useSources } from '@/source';
-import { usePageTitle } from '@/theme/ThemeProvider';
import { useDefaultTimeRange, useNewTimeQuery } from '@/timeQuery';
import DatabaseTab from './DatabaseTab';
diff --git a/packages/app/src/ServicesDashboardPage/__tests__/ServicesDashboardPage.test.tsx b/packages/app/src/ServicesDashboardPage/__tests__/ServicesDashboardPage.test.tsx
index 76f26b5a0..0094ce172 100644
--- a/packages/app/src/ServicesDashboardPage/__tests__/ServicesDashboardPage.test.tsx
+++ b/packages/app/src/ServicesDashboardPage/__tests__/ServicesDashboardPage.test.tsx
@@ -162,10 +162,11 @@ jest.mock('@/layout', () => ({
withAppNavForSurface: () => (page: unknown) => page,
}));
-jest.mock('@/theme/ThemeProvider', () => ({
+jest.mock('@/brand', () => ({
__esModule: true,
- useBrandDisplayName: () => 'HyperDX',
- usePageTitle: (page?: string) => (page ? `${page} - HyperDX` : 'HyperDX'),
+ useBrandDisplayName: () => 'ClickStack',
+ usePageTitle: (page?: string) =>
+ page ? `${page} - ClickStack` : 'ClickStack',
}));
import ServicesDashboardPage from '@/ServicesDashboardPage';
diff --git a/packages/app/src/SessionsPage.tsx b/packages/app/src/SessionsPage.tsx
index 51c6be1ff..4a6350578 100644
--- a/packages/app/src/SessionsPage.tsx
+++ b/packages/app/src/SessionsPage.tsx
@@ -53,7 +53,7 @@ import OnboardingModal from './components/OnboardingModal';
import SearchWhereInput, {
getStoredLanguage,
} from './components/SearchInput/SearchWhereInput';
-import { useBrandDisplayName, usePageTitle } from './theme/ThemeProvider';
+import { useBrandDisplayName, usePageTitle } from './brand';
import { withAppNavForSurface } from './layout';
import { Session, useSessions } from './sessions';
import SessionSidePanel from './SessionSidePanel';
diff --git a/packages/app/src/Spotlights.tsx b/packages/app/src/Spotlights.tsx
index 0df60edef..bb3c78eac 100644
--- a/packages/app/src/Spotlights.tsx
+++ b/packages/app/src/Spotlights.tsx
@@ -10,7 +10,7 @@ import {
} from '@tabler/icons-react';
import { dfePresetDashboards } from './dfe/presetDashboards';
-import { useBrandDisplayName, useLogomark } from './theme/ThemeProvider';
+import { useBrandDisplayName, useLogomark } from './brand';
import { IS_K8S_DASHBOARD_ENABLED } from './config';
import { useDashboards } from './dashboard';
import { useSavedSearches } from './savedSearch';
diff --git a/packages/app/src/TeamPage.tsx b/packages/app/src/TeamPage.tsx
index b536fe529..4a465afa2 100644
--- a/packages/app/src/TeamPage.tsx
+++ b/packages/app/src/TeamPage.tsx
@@ -30,13 +30,14 @@ import ConnectionsSection from './components/TeamSettings/ConnectionsSection';
import IacMigrationSection from './components/TeamSettings/IacMigrationSection';
import IntegrationsSection from './components/TeamSettings/IntegrationsSection';
import McpServerSection from './components/TeamSettings/McpServerSection';
+import OrgApiKeysSection from './components/TeamSettings/OrgApiKeysSection';
import SecurityPoliciesSection from './components/TeamSettings/SecurityPoliciesSection';
import SourcesSection from './components/TeamSettings/SourcesSection';
import TeamMembersSection from './components/TeamSettings/TeamMembersSection';
import TeamQueryConfigSection from './components/TeamSettings/TeamQueryConfigSection';
-import { usePageTitle } from './theme/ThemeProvider';
import api from './api';
-import { IS_IAC_EXPORT_ENABLED } from './config';
+import { usePageTitle } from './brand';
+import { IS_IAC_EXPORT_ENABLED, IS_LOCAL_MODE } from './config';
import { APP_CONTENT_SCROLL_CONTAINER_ID, withAppNav } from './layout';
type TeamTab = {
@@ -166,6 +167,15 @@ export default function TeamPage() {
id: 'team-api-agents-api-keys',
content: () => ,
},
+ // Org keys are stored by the API, which local mode doesn't run.
+ ...(IS_LOCAL_MODE
+ ? []
+ : [
+ {
+ id: 'team-api-agents-org-api-keys',
+ content: () => ,
+ },
+ ]),
{
id: 'team-api-agents-mcp-server',
content: () => ,
diff --git a/packages/app/src/ThemeWrapper.tsx b/packages/app/src/ThemeWrapper.tsx
index 628df5364..5c6677d6e 100644
--- a/packages/app/src/ThemeWrapper.tsx
+++ b/packages/app/src/ThemeWrapper.tsx
@@ -3,7 +3,7 @@ import { ClickUIProvider } from '@clickhouse/click-ui';
import { MantineProvider, MantineThemeOverride } from '@mantine/core';
import { Notifications } from '@mantine/notifications';
-import { useAppTheme } from './theme/ThemeProvider';
+import { theme as baseTheme } from '@/dfe/brand';
export const ThemeWrapper = ({
fontFamily,
@@ -14,13 +14,7 @@ export const ThemeWrapper = ({
colorScheme?: 'dark' | 'light';
children: React.ReactNode;
}) => {
- const { theme: appTheme } = useAppTheme();
-
const mantineTheme = React.useMemo(() => {
- // Start with the current theme's Mantine theme
- const baseTheme = appTheme.mantineTheme;
-
- // Override font family if provided
if (fontFamily) {
return {
...baseTheme,
@@ -33,11 +27,11 @@ export const ThemeWrapper = ({
}
return baseTheme;
- }, [appTheme.mantineTheme, fontFamily]);
+ }, [fontFamily]);
return (
- {/* HyperDX user preferences determine the color mode, so click-ui should not persist preferences to localstorage. */}
+ {/* User preferences determine the color mode, so click-ui should not persist preferences to localstorage. */}
{children}
diff --git a/packages/app/src/UserPreferencesModal.tsx b/packages/app/src/UserPreferencesModal.tsx
index e7ffcbf84..6bc00950d 100644
--- a/packages/app/src/UserPreferencesModal.tsx
+++ b/packages/app/src/UserPreferencesModal.tsx
@@ -1,24 +1,9 @@
import * as React from 'react';
import { Badge } from '@clickhouse/click-ui';
-import {
- Autocomplete,
- Divider,
- Group,
- Modal,
- Select,
- Stack,
- Text,
- Tooltip,
-} from '@mantine/core';
+import { Divider, Group, Modal, Select, Stack, Text } from '@mantine/core';
-import { TimeZoneSelect } from './components/TimeZoneSelect';
-import {
- isContentFontSize,
- OPTIONS_CONTENT_FONT_SIZE,
- OPTIONS_FONTS,
-} from './config/fonts';
-import { useAppTheme } from './theme/ThemeProvider';
-import { isValidThemeName, themes } from './theme';
+import { TimeZoneSelect, TimeZoneShortcuts } from './components/TimeZoneSelect';
+import { isContentFontSize, OPTIONS_CONTENT_FONT_SIZE } from './config/fonts';
import {
DEFAULT_ROW_CLICK_ACTION,
RowClickAction,
@@ -38,12 +23,6 @@ const OPTIONS_ROW_CLICK_ACTION: { label: string; value: RowClickAction }[] = [
{ label: 'Expand inline', value: 'expand' },
];
-// Brand theme options (generated from theme registry)
-const OPTIONS_BRAND_THEMES = Object.values(themes).map(t => ({
- label: t.displayName,
- value: t.name,
-}));
-
const SettingContainer = ({
label,
description,
@@ -77,7 +56,6 @@ export const UserPreferencesModal = ({
}) => {
const { userPreferences, setUserPreference } = useUserPreferences();
const { contentFontSize } = useContentFontSize();
- const { themeName, setTheme, isDev } = useAppTheme();
return (
- setUserPreference({ timeZone })}
- />
+
+ timeZone && setUserPreference({ timeZone })}
+ />
+ setUserPreference({ timeZone })}
+ />
+
@@ -185,70 +169,6 @@ export const UserPreferencesModal = ({
allowDeselect={false}
/>
-
- {/*
- Brand Theme Selector - DEV MODE ONLY
-
- This is intentionally NOT available in production. Brand theme (HyperDX vs ClickStack)
- is deployment-configured via NEXT_PUBLIC_THEME environment variable.
- Each deployment is branded for a specific product; users don't choose this.
-
- This dev-only UI exists for testing theme implementations during development.
- */}
- {isDev && (
-
- Brand Theme
-
-
-
-
- }
- description="Switch between HyperDX and ClickStack branding"
- >
-
- )}
-
- {/* Font selection is only available for HyperDX theme */}
- {/* ClickStack theme always uses Inter font and doesn't show this setting */}
- {!(themeName === 'clickstack' || themeName === 'dfe') && (
-
- options}
- onChange={value =>
- setUserPreference({
- font: value as UserPreferences['font'],
- })
- }
- data={OPTIONS_FONTS}
- />
-
- )}
);
diff --git a/packages/app/src/__mocks__/clickstack-browser.ts b/packages/app/src/__mocks__/clickstack-browser.ts
new file mode 100644
index 000000000..c284315dd
--- /dev/null
+++ b/packages/app/src/__mocks__/clickstack-browser.ts
@@ -0,0 +1,21 @@
+import type * as ClickStackBrowser from '@clickhouse/clickstack-browser';
+
+// @clickhouse/clickstack-browser and its OpenTelemetry browser dependencies
+// are ESM-only, which Jest (with transformIgnorePatterns: ['/node_modules/'])
+// cannot parse. Unit tests never start RUM, so each export behaves as the SDK
+// does before init.
+export const init: typeof ClickStackBrowser.init = jest.fn();
+export const getSessionId: typeof ClickStackBrowser.getSessionId = jest.fn(
+ () => null,
+);
+export const startNewSession: typeof ClickStackBrowser.startNewSession =
+ jest.fn();
+export const pauseReplay: typeof ClickStackBrowser.pauseReplay = jest.fn();
+export const resumeReplay: typeof ClickStackBrowser.resumeReplay = jest.fn();
+export const shutdown: typeof ClickStackBrowser.shutdown = jest.fn(() =>
+ Promise.resolve(),
+);
+export const recordException: typeof ClickStackBrowser.recordException =
+ jest.fn();
+export const setUser: typeof ClickStackBrowser.setUser = jest.fn();
+export const setAttributes: typeof ClickStackBrowser.setAttributes = jest.fn();
diff --git a/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx b/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx
index 5b335588f..37e1f1774 100644
--- a/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx
+++ b/packages/app/src/__tests__/DBSearchPage.directTrace.test.tsx
@@ -129,10 +129,10 @@ jest.mock('@/hooks/useExplainQuery', () => ({
useExplainQuery: () => ({}),
}));
-jest.mock('@/theme/ThemeProvider', () => ({
- useAppTheme: () => ({ themeName: 'hyperdx' }),
- useBrandDisplayName: () => 'HyperDX',
- usePageTitle: (page?: string) => (page ? `${page} - HyperDX` : 'HyperDX'),
+jest.mock('@/brand', () => ({
+ useBrandDisplayName: () => 'ClickStack',
+ usePageTitle: (page?: string) =>
+ page ? `${page} - ClickStack` : 'ClickStack',
}));
jest.mock('../hooks/useMetadata', () => ({
diff --git a/packages/app/src/__tests__/DBSearchPage.saveSearch.test.tsx b/packages/app/src/__tests__/DBSearchPage.saveSearch.test.tsx
new file mode 100644
index 000000000..864c55d9f
--- /dev/null
+++ b/packages/app/src/__tests__/DBSearchPage.saveSearch.test.tsx
@@ -0,0 +1,298 @@
+import React from 'react';
+import { SourceKind } from '@hyperdx/common-utils/dist/types';
+import { MantineProvider } from '@mantine/core';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import { DBSearchPage } from '@/DBSearchPage';
+
+const mockRouterPush = jest.fn();
+const mockSetSearchedConfig = jest
+ .fn()
+ .mockResolvedValue(new URLSearchParams());
+const mockCreateSavedSearch = jest.fn();
+
+let mockSearchedConfig: Record = {};
+let mockSources: any[] = [];
+
+jest.mock('@/layout', () => ({
+ withAppNav: (component: unknown) => component,
+}));
+
+jest.mock('next/router', () => ({
+ __esModule: true,
+ default: {
+ basePath: '/clickstack',
+ push: (...args: unknown[]) => mockRouterPush(...args),
+ },
+}));
+
+jest.mock('next/head', () => ({
+ __esModule: true,
+ default: ({ children }: { children: React.ReactNode }) => <>{children}>,
+}));
+
+jest.mock('next/link', () => ({
+ __esModule: true,
+ default: ({
+ children,
+ href,
+ }: {
+ children: React.ReactNode;
+ href: string;
+ }) => {children},
+}));
+
+jest.mock('nuqs', () => ({
+ parseAsBoolean: {
+ withDefault: () => 'parseAsBoolean',
+ },
+ parseAsInteger: {
+ withDefault: () => 'parseAsInteger',
+ },
+ parseAsString: 'parseAsString',
+ parseAsStringEnum: () => ({
+ withDefault: () => 'parseAsStringEnum',
+ }),
+ useQueryState: (key: string) => {
+ switch (key) {
+ case 'isLive':
+ return [true, jest.fn()];
+ case 'denoise':
+ return [false, jest.fn()];
+ default:
+ return [null, jest.fn()];
+ }
+ },
+ useQueryStates: () => [mockSearchedConfig, mockSetSearchedConfig],
+}));
+
+jest.mock('@/source', () => ({
+ getEventBody: () => 'Body',
+ getFirstTimestampValueExpression: () => 'Timestamp',
+ useSources: () => ({ data: mockSources }),
+ useSource: ({ id }: { id?: string | null }) => ({
+ data: mockSources.find(source => source.id === id),
+ isLoading: false,
+ }),
+}));
+
+jest.mock('@/timeQuery', () => ({
+ parseRelativeTimeQuery: () => [new Date(0), new Date(1)],
+ parseTimeQuery: () => [new Date(0), new Date(1)],
+ useDefaultTimeRange: () => [new Date(0), new Date(1)],
+ useNewTimeQuery: () => ({
+ isReady: true,
+ searchedTimeRange: [
+ new Date('2024-04-01T00:00:00.000Z'),
+ new Date('2024-04-02T00:00:00.000Z'),
+ ],
+ onSearch: jest.fn(),
+ onTimeRangeSelect: jest.fn(),
+ }),
+}));
+
+jest.mock('@/savedSearch', () => ({
+ useCreateSavedSearch: () => ({
+ mutateAsync: (...args: unknown[]) => mockCreateSavedSearch(...args),
+ isPending: false,
+ }),
+ useDeleteSavedSearch: () => ({ mutate: jest.fn() }),
+ useSavedSearch: () => ({ data: undefined }),
+ useUpdateSavedSearch: () => ({ mutate: jest.fn(), isPending: false }),
+}));
+
+jest.mock('@/searchFilters', () => ({
+ useSearchPageFilterState: () => ({
+ filters: [],
+ whereSuggestions: [],
+ setFilterValue: jest.fn(),
+ clearAllFilters: jest.fn(),
+ }),
+}));
+
+jest.mock('@/hooks/useChartConfig', () => ({
+ useAliasMapFromChartConfig: () => ({ data: {} }),
+}));
+
+jest.mock('@/hooks/useExplainQuery', () => ({
+ useExplainQuery: () => ({}),
+}));
+
+jest.mock('@/brand', () => ({
+ useBrandDisplayName: () => 'ClickStack',
+ usePageTitle: (page?: string) =>
+ page ? `${page} - ClickStack` : 'ClickStack',
+}));
+
+jest.mock('../hooks/useMetadata', () => ({
+ ...jest.requireActual('../hooks/useMetadata'),
+ useTableMetadata: () => ({
+ data: { sorting_key: 'Timestamp' },
+ isLoading: false,
+ }),
+ useColumns: () => ({ data: undefined, isLoading: false }),
+}));
+
+jest.mock('../hooks/useSqlSuggestions', () => ({
+ useSqlSuggestions: () => [],
+}));
+
+jest.mock('../components/Search/DirectTraceSidePanel', () => ({
+ __esModule: true,
+ default: () => ,
+}));
+
+jest.mock('@/components/DBSearchPageFilters', () => ({
+ DBSearchPageFilters: () => ,
+}));
+jest.mock('@/components/DBTimeChart', () => ({
+ DBTimeChart: () => ,
+}));
+jest.mock('@/components/ActiveFilterPills', () => ({
+ ActiveFilterPills: () => ,
+}));
+jest.mock('@/components/ContactSupportText', () => ({
+ ContactSupportText: () => ,
+}));
+jest.mock('@/components/FavoriteButton', () => ({
+ FavoriteButton: () => ,
+}));
+jest.mock('@/components/OnboardingModal', () => () => );
+jest.mock('@/components/SearchInput/SearchWhereInput', () => ({
+ __esModule: true,
+ default: () => ,
+ getStoredLanguage: () => 'lucene',
+}));
+jest.mock('@/components/SearchGroupBy/SearchGroupBySelect', () => ({
+ SearchGroupBySelect: () => ,
+}));
+jest.mock('@/components/SearchPageActionBar', () => () => );
+jest.mock('@/components/SearchTotalCountChart', () => () => );
+jest.mock('@/components/Sources/SourceForm', () => ({
+ TableSourceForm: () => ,
+}));
+jest.mock('@/components/SourceSelect', () => ({
+ SourceSelectControlled: () => ,
+}));
+jest.mock('@/components/SQLEditor/SQLInlineEditor', () => ({
+ SQLInlineEditorControlled: () => ,
+}));
+jest.mock('@/components/Tags', () => ({
+ Tags: ({ children }: { children: React.ReactNode }) =>
{children}
,
+}));
+jest.mock('@/components/TimePicker', () => ({
+ TimePicker: () => ,
+}));
+jest.mock('../components/ChartSQLPreview', () => ({
+ SQLPreview: () => ,
+}));
+jest.mock('../components/DBSqlRowTableWithSidebar', () => () => );
+jest.mock('../components/PatternTable', () => () => );
+jest.mock('../components/Search/DBSearchHeatmapChart', () => ({
+ DBSearchHeatmapChart: () => ,
+}));
+jest.mock('../components/SourceSchemaPreview', () => ({
+ __esModule: true,
+ default: () => ,
+ isSourceSchemaPreviewEnabled: () => false,
+ getSourceSchemaTables: () => [],
+}));
+jest.mock('../components/Error/ErrorBoundary', () => ({
+ ErrorBoundary: ({ children }: { children: React.ReactNode }) => (
+ <>{children}>
+ ),
+}));
+
+jest.mock('../utils/queryParsers', () => ({
+ parseAsJsonEncoded: () => 'parseAsJsonEncoded',
+ parseAsSortingStateString: { parse: () => null },
+ parseAsStringEncoded: 'parseAsStringEncoded',
+}));
+
+jest.mock('../api', () => ({
+ __esModule: true,
+ default: {
+ useMe: () => ({ data: { team: {} }, isSuccess: true }),
+ },
+ useCompleteOnboardingTask: () => ({ mutate: jest.fn() }),
+}));
+
+jest.mock('@/utils', () => ({
+ QUERY_LOCAL_STORAGE: 'query-local-storage',
+ useLocalStorage: (_key: string, initialValue: unknown) => [
+ initialValue,
+ jest.fn(),
+ ],
+ usePrevious: (value: unknown) => value,
+ useWindowSize: () => ({ width: 1200, height: 800 }),
+}));
+
+jest.mock('@tanstack/react-query', () => ({
+ useIsFetching: () => 0,
+}));
+
+describe('DBSearchPage save search flow', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockCreateSavedSearch.mockResolvedValue({ id: 'new-saved-search' });
+ mockSearchedConfig = {
+ source: 'log-source',
+ where: 'level:error',
+ select: 'Timestamp, Body',
+ whereLanguage: 'lucene',
+ filters: [],
+ orderBy: 'Timestamp DESC',
+ };
+ mockSources = [
+ {
+ id: 'log-source',
+ kind: SourceKind.Log,
+ name: 'Log Source',
+ from: { databaseName: 'db', tableName: 'logs' },
+ timestampValueExpression: 'Timestamp',
+ defaultTableSelectExpression: 'Timestamp',
+ implicitColumnExpression: 'Body',
+ connection: 'conn',
+ },
+ ];
+ window.history.pushState({}, '', '/search?from=100&to=200&isLive=false');
+ });
+
+ async function saveSearchAs(name: string) {
+ const user = userEvent.setup();
+ render(, {
+ wrapper: ({ children }) => {children},
+ });
+
+ await user.click(await screen.findByTestId('save-search-button'));
+ await user.type(await screen.findByTestId('save-search-name-input'), name);
+ await user.click(screen.getByTestId('save-search-submit-button'));
+ }
+
+ // The route is pushed through the router rather than assigned to
+ // window.location: a document navigation reloads the whole app, and 404s on
+ // the static ClickStack export, where /search/ has no exported document.
+ // basePath is left off because the router prepends it.
+ it('navigates to the new saved search client-side', async () => {
+ await saveSearchAs('Errors');
+
+ await waitFor(() => {
+ expect(mockRouterPush).toHaveBeenCalledWith(
+ '/search/new-saved-search?from=100&to=200&isLive=false',
+ );
+ });
+ });
+
+ it('drains queued query-string updates before navigating', async () => {
+ await saveSearchAs('Errors');
+
+ await waitFor(() => expect(mockRouterPush).toHaveBeenCalled());
+ // nuqs flushes its queue onto whatever path the router reports, so a write
+ // still queued when the transition starts would land back on /search.
+ expect(mockSetSearchedConfig).toHaveBeenCalledWith({});
+ expect(mockSetSearchedConfig.mock.invocationCallOrder[0]).toBeLessThan(
+ mockRouterPush.mock.invocationCallOrder[0],
+ );
+ });
+});
diff --git a/packages/app/src/__tests__/DBSearchPage.test.tsx b/packages/app/src/__tests__/DBSearchPage.test.tsx
index fa08559ca..85b0e28c0 100644
--- a/packages/app/src/__tests__/DBSearchPage.test.tsx
+++ b/packages/app/src/__tests__/DBSearchPage.test.tsx
@@ -18,21 +18,28 @@ describe('buildSavedSearchNavigationUrl', () => {
it('drops saved-search query state when the source uses the default relative range', () => {
expect(
buildSavedSearchNavigationUrl(
- '/clickstack',
'saved-search-id',
'?where=service%3Aapi&orderBy=timestamp',
),
- ).toBe('/clickstack/search/saved-search-id');
+ ).toBe('/search/saved-search-id');
});
it('keeps an absolute range out of live-tail mode', () => {
expect(
buildSavedSearchNavigationUrl(
- '/clickstack',
'saved-search-id',
'?from=100&to=200&isLive=false&where=service%3Aapi&orderBy=timestamp',
),
- ).toBe('/clickstack/search/saved-search-id?from=100&to=200&isLive=false');
+ ).toBe('/search/saved-search-id?from=100&to=200&isLive=false');
+ });
+
+ it('carries a live-tail range over without pinning it out of live mode', () => {
+ expect(
+ buildSavedSearchNavigationUrl(
+ 'saved-search-id',
+ '?from=100&to=200&isLive=true&where=service%3Aapi',
+ ),
+ ).toBe('/search/saved-search-id?from=100&to=200');
});
});
diff --git a/packages/app/src/__tests__/DBSearchPageAlertModal.test.tsx b/packages/app/src/__tests__/DBSearchPageAlertModal.test.tsx
index 081c75a49..53f32dec2 100644
--- a/packages/app/src/__tests__/DBSearchPageAlertModal.test.tsx
+++ b/packages/app/src/__tests__/DBSearchPageAlertModal.test.tsx
@@ -14,6 +14,10 @@ import { DBSearchPageAlertModal } from '@/DBSearchPageAlertModal';
const createAlertMutateAsync = jest.fn().mockResolvedValue({ data: {} });
const updateAlertMutateAsync = jest.fn().mockResolvedValue({ data: {} });
const deleteAlertMutateAsync = jest.fn().mockResolvedValue(undefined);
+const createSavedSearchMutateAsync = jest
+ .fn()
+ .mockResolvedValue({ id: 'new-saved-search-id' });
+const routerPush = jest.fn();
// Two alerts so the test can edit the second tab and confirm the PUT targets
// the right id.
@@ -43,8 +47,8 @@ const savedSearch = {
select: '',
source: 'source-id',
orderBy: '',
- // One tag over the alert cap (32): the prefill must clamp it or the form
- // rejects on mount and Create Alert silently does nothing.
+ // One tag over the alert cap (32). The form must not copy a saved search's
+ // tags into the alert, which its own schema would then reject on submit.
tags: ['prod', 'checkout-service-payment-failures'],
alerts: [firstAlert, secondAlert],
};
@@ -78,10 +82,19 @@ jest.mock('@/api', () => ({
},
}));
+jest.mock('next/router', () => ({
+ __esModule: true,
+ default: { push: (...args: unknown[]) => routerPush(...args) },
+}));
+
jest.mock('@/savedSearch', () => ({
__esModule: true,
- useSavedSearch: () => ({ data: savedSearch, isLoading: false }),
- useCreateSavedSearch: () => ({ mutateAsync: jest.fn() }),
+ // Mirrors the hook's `enabled` option: no id, no saved search.
+ useSavedSearch: ({ id }: { id: string }) => ({
+ data: id ? savedSearch : undefined,
+ isLoading: false,
+ }),
+ useCreateSavedSearch: () => ({ mutateAsync: createSavedSearchMutateAsync }),
}));
jest.mock('@/source', () => ({
@@ -89,9 +102,9 @@ jest.mock('@/source', () => ({
useSource: () => ({ data: undefined }),
}));
-jest.mock('@/theme/ThemeProvider', () => ({
+jest.mock('@/brand', () => ({
__esModule: true,
- useBrandDisplayName: () => 'HyperDX',
+ useBrandDisplayName: () => 'ClickStack',
}));
// Heavy / visual child components are stubbed so the form still renders and
@@ -138,35 +151,53 @@ jest.mock('@/components/SQLEditor/SQLInlineEditor', () => ({
SQLInlineEditorControlled: () => ,
}));
-const renderModal = () => {
+const renderModal = (
+ props: Partial> = {},
+) => {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return renderWithMantine(
-
+ ,
);
};
+const searchedConfig = {
+ source: 'source-id',
+ select: '',
+ where: 'level:error',
+ whereLanguage: 'lucene' as const,
+ orderBy: '',
+ filters: [],
+};
+
describe('DBSearchPageAlertModal', () => {
beforeEach(() => {
createAlertMutateAsync.mockClear();
updateAlertMutateAsync.mockClear();
deleteAlertMutateAsync.mockClear();
+ createSavedSearchMutateAsync.mockClear();
+ routerPush.mockClear();
});
it('dispatches an update (PUT) with the id resolved from the selected alert tab', async () => {
renderModal();
- // Modal opens on the "New Alert" tab; select the second existing alert so
+ // Modal opens on the "New alert" tab; select the second existing alert so
// it renders in edit mode. Using the second (not first) tab confirms the
// update id is resolved by tab index.
const alertTab = await screen.findByRole('tab', { name: /Alert 2/ });
fireEvent.click(alertTab);
const saveButton = await screen.findByRole('button', {
- name: 'Save Alert',
+ name: 'Save alert',
});
fireEvent.click(saveButton);
@@ -195,7 +226,7 @@ describe('DBSearchPageAlertModal', () => {
fireEvent.click(alertTab);
const saveButton = await screen.findByRole('button', {
- name: 'Save Alert',
+ name: 'Save alert',
});
fireEvent.click(saveButton);
@@ -210,31 +241,83 @@ describe('DBSearchPageAlertModal', () => {
]);
});
- // A new alert opens prefilled from the saved search it will watch, so the
- // create payload carries those values rather than relying on the server's
- // derivation.
- it('prefills the display name and tags from the saved search, clamped to the alert caps', async () => {
+ // The saved search is already named in the modal's header, so the alert's
+ // own name field stays empty and shows what it inherits. Submitting without
+ // touching it leaves the name and tags for the server to derive.
+ it('leaves a new alert to inherit the name and tags of its saved search', async () => {
renderModal();
- expect(await screen.findByTestId('alert-display-name-input')).toHaveValue(
- 'My Search',
+ const nameInput = await screen.findByTestId('alert-display-name-input');
+ expect(nameInput).toHaveValue('');
+ expect(nameInput).toHaveAttribute('placeholder', 'My Search');
+
+ fireEvent.change(screen.getByTestId('webhook-id-input'), {
+ target: { value: 'webhook-id' },
+ });
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Create alert' }),
+ );
+
+ await waitFor(() => {
+ expect(createAlertMutateAsync).toHaveBeenCalledTimes(1);
+ });
+ const payload = createAlertMutateAsync.mock.calls[0][0];
+ expect(payload.displayName).toBeUndefined();
+ expect(payload.tags).toBeUndefined();
+ });
+
+ // An unsaved search is named once, in the header, and the alert inherits it:
+ // there is no second name field to disambiguate.
+ it('asks for one name when the search has not been saved yet', async () => {
+ renderModal({ id: undefined, searchedConfig });
+
+ expect(await screen.findByTestId('saved-search-name-input')).toHaveValue(
+ '',
);
+ expect(
+ screen.queryByTestId('alert-display-name-input'),
+ ).not.toBeInTheDocument();
+ fireEvent.change(screen.getByTestId('saved-search-name-input'), {
+ target: { value: ' Checkout errors ' },
+ });
fireEvent.change(screen.getByTestId('webhook-id-input'), {
target: { value: 'webhook-id' },
});
fireEvent.click(
- await screen.findByRole('button', { name: 'Create Alert' }),
+ await screen.findByRole('button', { name: 'Save search and alert' }),
+ );
+
+ await waitFor(() => {
+ expect(createSavedSearchMutateAsync).toHaveBeenCalledTimes(1);
+ });
+ expect(createSavedSearchMutateAsync).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'Checkout errors', tags: [] }),
);
await waitFor(() => {
expect(createAlertMutateAsync).toHaveBeenCalledTimes(1);
});
- expect(createAlertMutateAsync).toHaveBeenCalledWith(
- expect.objectContaining({
- displayName: 'My Search',
- tags: ['prod', 'checkout-service-payment-failure'],
- }),
+ const payload = createAlertMutateAsync.mock.calls[0][0];
+ expect(payload.savedSearchId).toBe('new-saved-search-id');
+ expect(payload.displayName).toBeUndefined();
+ expect(payload.tags).toBeUndefined();
+ });
+
+ // The name is validated on the same submit as the alert fields, so an
+ // unnamed search is reported the first time rather than after the rest of
+ // the form is fixed.
+ it('flags an unnamed search on the first submit and saves nothing', async () => {
+ renderModal({ id: undefined, searchedConfig });
+
+ fireEvent.click(
+ await screen.findByRole('button', { name: 'Save search and alert' }),
);
+
+ expect(
+ await screen.findByTestId('saved-search-name-error'),
+ ).toBeInTheDocument();
+ expect(createSavedSearchMutateAsync).not.toHaveBeenCalled();
+ expect(createAlertMutateAsync).not.toHaveBeenCalled();
});
});
diff --git a/packages/app/src/__tests__/DashboardFilters.test.ts b/packages/app/src/__tests__/DashboardFilters.test.ts
index 5c5df455a..6113b5727 100644
--- a/packages/app/src/__tests__/DashboardFilters.test.ts
+++ b/packages/app/src/__tests__/DashboardFilters.test.ts
@@ -1,10 +1,7 @@
import { DashboardFilter } from '@hyperdx/common-utils/dist/types';
-import {
- getFilterEffect,
- getPendingVariablesTooltip,
- getRequiredFilterTooltip,
-} from '@/DashboardFilters';
+import { getPendingVariablesTooltip } from '@/components/DashboardFilterLabel';
+import { getFilterEffect, getRequiredFilterTooltip } from '@/DashboardFilters';
const baseFilter: DashboardFilter = {
id: 'filter1',
diff --git a/packages/app/src/__tests__/OnboardingChecklist.test.tsx b/packages/app/src/__tests__/OnboardingChecklist.test.tsx
index 6b16a9a08..6e141b0e5 100644
--- a/packages/app/src/__tests__/OnboardingChecklist.test.tsx
+++ b/packages/app/src/__tests__/OnboardingChecklist.test.tsx
@@ -24,8 +24,8 @@ jest.mock('@/source', () => ({ useSources: jest.fn() }));
jest.mock('@/hooks/useChartConfig', () => ({
useQueriedChartConfig: jest.fn(),
}));
-jest.mock('@/theme/ThemeProvider', () => ({
- useBrandDisplayName: () => 'HyperDX',
+jest.mock('@/brand', () => ({
+ useBrandDisplayName: () => 'ClickStack',
}));
const mockUseMe = jest.mocked(api.useMe);
@@ -141,7 +141,7 @@ describe('OnboardingChecklist', () => {
renderChecklist();
- expect(screen.getByText('Get started with HyperDX')).toBeInTheDocument();
+ expect(screen.getByText('Get started with ClickStack')).toBeInTheDocument();
expect(screen.getByText('Build a dashboard')).toBeInTheDocument();
expect(screen.getByText('Explore your data')).toBeInTheDocument();
// 1 of 4 product tasks complete.
@@ -170,7 +170,7 @@ describe('OnboardingChecklist', () => {
renderChecklist();
expect(
- screen.queryByText('Get started with HyperDX'),
+ screen.queryByText('Get started with ClickStack'),
).not.toBeInTheDocument();
expect(screen.queryByText('Set up ClickHouse')).not.toBeInTheDocument();
});
@@ -184,7 +184,7 @@ describe('OnboardingChecklist', () => {
renderChecklist();
expect(
- screen.queryByText('Get started with HyperDX'),
+ screen.queryByText('Get started with ClickStack'),
).not.toBeInTheDocument();
expect(screen.queryByText('Set up ClickHouse')).not.toBeInTheDocument();
});
@@ -201,7 +201,7 @@ describe('OnboardingChecklist', () => {
renderChecklist();
expect(
- screen.queryByText('Get started with HyperDX'),
+ screen.queryByText('Get started with ClickStack'),
).not.toBeInTheDocument();
expect(screen.queryByText(/You're all set/)).not.toBeInTheDocument();
expect(dismissMutate).not.toHaveBeenCalled();
@@ -219,7 +219,7 @@ describe('OnboardingChecklist', () => {
setSetup(true, /* loading */ true);
const { rerender } = renderChecklist();
expect(
- screen.queryByText('Get started with HyperDX'),
+ screen.queryByText('Get started with ClickStack'),
).not.toBeInTheDocument();
expect(screen.queryByText(/You're all set/)).not.toBeInTheDocument();
@@ -238,7 +238,7 @@ describe('OnboardingChecklist', () => {
});
expect(screen.queryByText(/You're all set/)).not.toBeInTheDocument();
expect(
- screen.queryByText('Get started with HyperDX'),
+ screen.queryByText('Get started with ClickStack'),
).not.toBeInTheDocument();
} finally {
jest.useRealTimers();
@@ -296,7 +296,7 @@ describe('OnboardingChecklist', () => {
renderChecklist();
- expect(screen.getByText('Get started with HyperDX')).toBeInTheDocument();
+ expect(screen.getByText('Get started with ClickStack')).toBeInTheDocument();
expect(screen.getByText('3/4')).toBeInTheDocument();
});
@@ -342,7 +342,7 @@ describe('OnboardingChecklist', () => {
renderChecklist();
- expect(screen.getByText('Get started with HyperDX')).toBeInTheDocument();
+ expect(screen.getByText('Get started with ClickStack')).toBeInTheDocument();
});
it('hides the product phase for a team older than the product window (>7 days)', () => {
@@ -353,7 +353,7 @@ describe('OnboardingChecklist', () => {
renderChecklist();
expect(
- screen.queryByText('Get started with HyperDX'),
+ screen.queryByText('Get started with ClickStack'),
).not.toBeInTheDocument();
});
diff --git a/packages/app/src/__tests__/UserPreferencesModal.test.tsx b/packages/app/src/__tests__/UserPreferencesModal.test.tsx
index ef1b72a44..ddd9213b7 100644
--- a/packages/app/src/__tests__/UserPreferencesModal.test.tsx
+++ b/packages/app/src/__tests__/UserPreferencesModal.test.tsx
@@ -44,6 +44,25 @@ describe('UserPreferencesModal', () => {
expect(readStoredPreferences().timeZone).toBe('Etc/UTC');
});
+
+ it.each([
+ ['time-zone-utc', 'Asia/Tokyo', 'Etc/UTC'],
+ ['time-zone-local', 'Etc/UTC', 'local'],
+ ])(
+ 'stores the zone from the %s shortcut',
+ async (testId, stored, expected) => {
+ renderModal({ timeZone: stored });
+
+ await userEvent.click(screen.getByTestId(testId));
+
+ expect(readStoredPreferences().timeZone).toBe(expected);
+ },
+ );
+
+ it('has no Default shortcut, since this is the default', () => {
+ renderModal();
+ expect(screen.queryByTestId('time-zone-default')).toBeNull();
+ });
});
describe('Row click', () => {
diff --git a/packages/app/src/__tests__/connection.test.ts b/packages/app/src/__tests__/connection.test.ts
new file mode 100644
index 000000000..5b4ebb8d4
--- /dev/null
+++ b/packages/app/src/__tests__/connection.test.ts
@@ -0,0 +1,54 @@
+const mockConfig = { IS_LOCAL_MODE: false };
+jest.mock('@/config', () => ({
+ HDX_LOCAL_DEFAULT_CONNECTIONS: undefined,
+ get IS_LOCAL_MODE() {
+ return mockConfig.IS_LOCAL_MODE;
+ },
+}));
+
+const mockHdxServer = jest.fn();
+jest.mock('@/api', () => ({
+ hdxServer: (...args: unknown[]) => mockHdxServer(...args),
+}));
+
+import { fetchPrometheusHttpApiSupport } from '@/connection';
+
+const answers = (body: unknown) =>
+ mockHdxServer.mockReturnValue({ json: () => Promise.resolve(body) });
+
+describe('fetchPrometheusHttpApiSupport', () => {
+ beforeEach(() => {
+ mockHdxServer.mockReset();
+ mockConfig.IS_LOCAL_MODE = false;
+ });
+
+ it('asks the server about the connection', async () => {
+ answers({ supported: true });
+
+ await expect(fetchPrometheusHttpApiSupport('conn-1')).resolves.toBe(true);
+ expect(mockHdxServer).toHaveBeenCalledWith(
+ 'connections/conn-1/prometheus-http-api',
+ );
+ });
+
+ it('reports a server that does not serve it', async () => {
+ answers({ supported: false });
+
+ await expect(fetchPrometheusHttpApiSupport('conn-1')).resolves.toBe(false);
+ });
+
+ it('reports false when the server cannot be asked', async () => {
+ mockHdxServer.mockReturnValue({
+ json: () => Promise.reject(new Error('boom')),
+ });
+
+ await expect(fetchPrometheusHttpApiSupport('conn-1')).resolves.toBe(false);
+ });
+
+ it('does not ask the server about a local-mode connection', async () => {
+ mockConfig.IS_LOCAL_MODE = true;
+
+ await expect(fetchPrometheusHttpApiSupport('local')).resolves.toBe(false);
+ expect(mockHdxServer).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/app/src/__tests__/hdxDebug.test.ts b/packages/app/src/__tests__/hdxDebug.test.ts
index 40bd113d0..a0900c111 100644
--- a/packages/app/src/__tests__/hdxDebug.test.ts
+++ b/packages/app/src/__tests__/hdxDebug.test.ts
@@ -14,12 +14,14 @@ const baseConfig = {
IS_PROMQL_ENABLED: false,
};
-function loadHdxDebug(configOverrides: Partial = {}) {
+function loadHdxDebug(
+ configOverrides: Partial = {},
+ sessionId: string | null = null,
+) {
jest.resetModules();
jest.doMock('@/config', () => ({ ...baseConfig, ...configOverrides }));
- jest.doMock('@hyperdx/browser', () => ({
- __esModule: true,
- default: { getSessionId: () => undefined },
+ jest.doMock('@clickhouse/clickstack-browser', () => ({
+ getSessionId: () => sessionId,
}));
jest.doMock('@/utils/clipboard', () => ({
copyTextToClipboard: jest.fn().mockResolvedValue(true),
@@ -172,6 +174,20 @@ describe('report identity + features', () => {
});
});
+describe('report session line', () => {
+ it('reports N/A until the RUM SDK has a session', () => {
+ const report = reportFor(loadHdxDebug());
+ expect(report).toContain('session: N/A');
+ expect(window.hdx?.sessionId()).toBeUndefined();
+ });
+
+ it('reports the RUM session id once there is one', () => {
+ const report = reportFor(loadHdxDebug({}, 'abc123'));
+ expect(report).toContain('session: abc123');
+ expect(window.hdx?.sessionId()).toBe('abc123');
+ });
+});
+
describe('report url line', () => {
afterEach(() => {
window.history.replaceState(null, '', '/');
diff --git a/packages/app/src/__tests__/pinnedFilters.test.ts b/packages/app/src/__tests__/pinnedFilters.test.ts
index fa8a8d1ad..ca56296ce 100644
--- a/packages/app/src/__tests__/pinnedFilters.test.ts
+++ b/packages/app/src/__tests__/pinnedFilters.test.ts
@@ -4,7 +4,9 @@
* - localStorage migration logic
*/
-import { mergePinnedData } from '@/searchFilters';
+import { act, renderHook } from '@testing-library/react';
+
+import { mergePinnedData, useCollapsedPinnedFields } from '@/searchFilters';
describe('mergePinnedData', () => {
it('returns empty fields and filters when both are null', () => {
@@ -167,3 +169,77 @@ describe('localStorage migration', () => {
expect(result[sourceB]).toEqual({ level: ['error'] });
});
});
+
+describe('useCollapsedPinnedFields', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it('remembers a collapsed pinned field across remounts', () => {
+ const first = renderHook(() => useCollapsedPinnedFields('source1'));
+ expect(first.result.current.isPinnedFieldCollapsed('ServiceName')).toBe(
+ false,
+ );
+
+ act(() =>
+ first.result.current.setPinnedFieldCollapsed('ServiceName', true),
+ );
+ expect(first.result.current.isPinnedFieldCollapsed('ServiceName')).toBe(
+ true,
+ );
+ first.unmount();
+
+ const second = renderHook(() => useCollapsedPinnedFields('source1'));
+ expect(second.result.current.isPinnedFieldCollapsed('ServiceName')).toBe(
+ true,
+ );
+ });
+
+ it('forgets the field once it is expanded again', () => {
+ const { result } = renderHook(() => useCollapsedPinnedFields('source1'));
+ act(() => result.current.setPinnedFieldCollapsed('ServiceName', true));
+ act(() => result.current.setPinnedFieldCollapsed('ServiceName', false));
+
+ expect(result.current.isPinnedFieldCollapsed('ServiceName')).toBe(false);
+ expect(
+ JSON.parse(window.localStorage.getItem('hdx-collapsed-pinned-fields')!),
+ ).toEqual({ source1: [] });
+ });
+
+ it('keeps the collapsed state per source', () => {
+ const a = renderHook(() => useCollapsedPinnedFields('sourceA'));
+ act(() => a.result.current.setPinnedFieldCollapsed('ServiceName', true));
+
+ const b = renderHook(() => useCollapsedPinnedFields('sourceB'));
+ expect(b.result.current.isPinnedFieldCollapsed('ServiceName')).toBe(false);
+ });
+
+ it('does nothing without a source', () => {
+ const { result } = renderHook(() => useCollapsedPinnedFields(null));
+ act(() => result.current.setPinnedFieldCollapsed('ServiceName', true));
+
+ expect(result.current.isPinnedFieldCollapsed('ServiceName')).toBe(false);
+ expect(window.localStorage.getItem('hdx-collapsed-pinned-fields')).toBe(
+ null,
+ );
+ });
+});
+
+describe('useCollapsedPinnedFields pruning', () => {
+ beforeEach(() => {
+ window.localStorage.clear();
+ });
+
+ it('keeps only the fields still pinned after a reset', () => {
+ const { result } = renderHook(() => useCollapsedPinnedFields('source1'));
+ act(() => result.current.setPinnedFieldCollapsed('ServiceName', true));
+ act(() => result.current.setPinnedFieldCollapsed('SeverityText', true));
+
+ act(() =>
+ result.current.pruneCollapsedPinnedFields(f => f === 'SeverityText'),
+ );
+
+ expect(result.current.isPinnedFieldCollapsed('ServiceName')).toBe(false);
+ expect(result.current.isPinnedFieldCollapsed('SeverityText')).toBe(true);
+ });
+});
diff --git a/packages/app/src/__tests__/sessions.test.ts b/packages/app/src/__tests__/sessions.test.ts
index 6a0c98a81..cce6fa680 100644
--- a/packages/app/src/__tests__/sessions.test.ts
+++ b/packages/app/src/__tests__/sessions.test.ts
@@ -14,6 +14,7 @@ import {
buildRRWebStreamChartConfig,
buildSessionsQueryFilters,
fetchServiceScopeFilters,
+ getRRWebTimestampExpression,
} from '@/sessions';
jest.mock('@hyperdx/common-utils/dist/core/renderChartConfig', () => ({
@@ -39,14 +40,55 @@ describe('buildRRWebStreamChartConfig', () => {
limit: 1000000,
offset: 0,
getSessionSourceFieldExpression,
+ preciseTimestampExpression: 'Timestamp',
});
it('orders by timestamp with numeric offset and chunk tiebreaks', () => {
// Chunks of one rrweb event share a single timestamp, so without the
// tiebreaks ClickHouse can return them in arbitrary order and the replay
- // reassembly gets scrambled (hyperdxio/hyperdx#2569). The casts matter
+ // reassembly gets scrambled (ClickHouse/ClickStack#2569). The casts matter
// too: the attributes are strings, and lexicographically '10' < '2'.
+ // `Timestamp` comes before the offset because older SDKs restart the
+ // offset on every page load, and TimestampTime only has seconds.
expect(config.orderBy).toBe(
+ "TimestampTime ASC, Timestamp ASC, toUInt64OrZero(LogAttributes['rr-web.offset']) ASC, toUInt64OrZero(LogAttributes['rr-web.chunk']) ASC",
+ );
+ });
+
+ it('does not repeat the timestamp when the source already uses Timestamp', () => {
+ const jsonConfig = buildRRWebStreamChartConfig({
+ source: { ...config, timestampValueExpression: 'Timestamp' },
+ serviceName: 'my-service',
+ sessionId: 'session-1',
+ startDate: new Date(1000),
+ endDate: new Date(2000),
+ limit: 1000000,
+ offset: 0,
+ getSessionSourceFieldExpression,
+ preciseTimestampExpression: 'Timestamp',
+ });
+ expect(jsonConfig.orderBy).toBe(
+ "Timestamp ASC, toUInt64OrZero(LogAttributes['rr-web.offset']) ASC, toUInt64OrZero(LogAttributes['rr-web.chunk']) ASC",
+ );
+ });
+
+ it('falls back to the source timestamp for tables without Timestamp', () => {
+ const fallbackConfig = buildRRWebStreamChartConfig({
+ source: config,
+ serviceName: 'my-service',
+ sessionId: 'session-1',
+ startDate: new Date(1000),
+ endDate: new Date(2000),
+ limit: 1000000,
+ offset: 0,
+ getSessionSourceFieldExpression,
+ preciseTimestampExpression: 'TimestampTime',
+ });
+ expect(fallbackConfig.select).toContainEqual({
+ valueExpression: 'TimestampTime',
+ alias: 'ts',
+ });
+ expect(fallbackConfig.orderBy).toBe(
"TimestampTime ASC, toUInt64OrZero(LogAttributes['rr-web.offset']) ASC, toUInt64OrZero(LogAttributes['rr-web.chunk']) ASC",
);
});
@@ -60,6 +102,7 @@ describe('buildRRWebStreamChartConfig', () => {
alias: 'tcks',
},
{ valueExpression: "LogAttributes['rr-web.event']", alias: 'ev' },
+ { valueExpression: 'Timestamp', alias: 'ts' },
]),
);
});
@@ -83,6 +126,7 @@ describe('buildRRWebStreamChartConfig', () => {
limit: 1000000,
offset: 0,
getSessionSourceFieldExpression,
+ preciseTimestampExpression: 'Timestamp',
});
expect(otelConfig.where).toBe(
'ServiceName:"my-service" AND LogAttributes.session.id:"session-1"',
@@ -90,6 +134,74 @@ describe('buildRRWebStreamChartConfig', () => {
});
});
+describe('getRRWebTimestampExpression', () => {
+ const source = {
+ from: { databaseName: 'default', tableName: 'hyperdx_sessions' },
+ timestampValueExpression: 'TimestampTime',
+ connection: 'conn',
+ };
+
+ function metadataWithColumns(columns: string[] | Error) {
+ const metadata = new Metadata(
+ new ClickhouseClient({ host: '' }),
+ new MetadataCache(),
+ );
+ const getColumns = jest.spyOn(metadata, 'getColumns');
+ if (columns instanceof Error) {
+ getColumns.mockRejectedValue(columns);
+ } else {
+ getColumns.mockResolvedValue(
+ columns.map(name => ({
+ name,
+ type: name === 'Timestamp' ? 'DateTime64(9)' : 'String',
+ codec_expression: '',
+ comment: '',
+ default_expression: '',
+ default_type: '',
+ ttl_expression: '',
+ })),
+ );
+ }
+ return { metadata, getColumns };
+ }
+
+ it('uses Timestamp when the session table has it', async () => {
+ const { metadata, getColumns } = metadataWithColumns([
+ 'Timestamp',
+ 'TimestampTime',
+ 'Body',
+ ]);
+ expect(await getRRWebTimestampExpression(source, metadata)).toBe(
+ 'Timestamp',
+ );
+ expect(getColumns).toHaveBeenCalledWith({
+ databaseName: 'default',
+ tableName: 'hyperdx_sessions',
+ connectionId: 'conn',
+ });
+ });
+
+ it("falls back to the source's first timestamp without Timestamp", async () => {
+ const { metadata } = metadataWithColumns(['TimestampTime', 'Body']);
+ expect(
+ await getRRWebTimestampExpression(
+ { ...source, timestampValueExpression: 'TimestampTime, EventTime' },
+ metadata,
+ ),
+ ).toBe('TimestampTime');
+ });
+
+ it('falls back instead of failing when the columns lookup fails', async () => {
+ const { metadata } = metadataWithColumns(new Error('DESCRIBE failed'));
+ const warn = jest.spyOn(console, 'warn').mockImplementation(() => {});
+ expect(await getRRWebTimestampExpression(source, metadata)).toBe(
+ 'TimestampTime',
+ );
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+});
+
describe('fetchServiceScopeFilters', () => {
const traceSource: TTraceSource = {
id: 'traces',
diff --git a/packages/app/src/__tests__/timeZone.test.ts b/packages/app/src/__tests__/timeZone.test.ts
index b2022b77b..6d2a81110 100644
--- a/packages/app/src/__tests__/timeZone.test.ts
+++ b/packages/app/src/__tests__/timeZone.test.ts
@@ -1,8 +1,10 @@
import {
formatTimeZoneName,
getSupportedTimeZones,
- getTimeZoneOffsetLabel,
+ getTimeZonePreferenceLabel,
+ getTimeZoneRangeShortName,
getTimeZoneShortName,
+ isTimeZonePreference,
isValidTimeZone,
LOCAL_TIME_ZONE,
resolveTimeZonePreference,
@@ -24,19 +26,21 @@ describe('resolveTimeZonePreference', () => {
});
});
-describe('getTimeZoneOffsetLabel', () => {
- it('uses the offset in effect on the date', () => {
- expect(
- getTimeZoneOffsetLabel('America/Los_Angeles', new Date('2026-07-01Z')),
- ).toBe('UTC-07:00');
- expect(
- getTimeZoneOffsetLabel('America/Los_Angeles', new Date('2026-12-01Z')),
- ).toBe('UTC-08:00');
- expect(getTimeZoneOffsetLabel('Asia/Kolkata')).toBe('UTC+05:30');
+describe('isTimeZonePreference', () => {
+ it('accepts local and zones the browser knows', () => {
+ expect(isTimeZonePreference(LOCAL_TIME_ZONE)).toBe(true);
+ expect(isTimeZonePreference('Asia/Tokyo')).toBe(true);
+ expect(isTimeZonePreference('Mars/Olympus_Mons')).toBe(false);
});
+});
- it('labels UTC with a zero offset', () => {
- expect(getTimeZoneOffsetLabel('Etc/UTC')).toBe('UTC+00:00');
+describe('getTimeZonePreferenceLabel', () => {
+ it('names local, UTC and other zones', () => {
+ expect(getTimeZonePreferenceLabel(LOCAL_TIME_ZONE)).toBe('Local');
+ expect(getTimeZonePreferenceLabel('Etc/UTC')).toBe('UTC');
+ expect(getTimeZonePreferenceLabel('America/Los_Angeles')).toBe(
+ 'America/Los Angeles',
+ );
});
});
@@ -58,16 +62,16 @@ describe('formatTimeZoneName', () => {
});
describe('getTimeZoneShortName', () => {
- it('uses the abbreviation in effect on the date', () => {
+ it('uses the offset in effect on the date, not an abbreviation', () => {
expect(
getTimeZoneShortName('America/Los_Angeles', new Date('2026-07-01Z')),
- ).toBe('PDT');
+ ).toBe('UTC-7');
expect(
getTimeZoneShortName('America/Los_Angeles', new Date('2026-12-01Z')),
- ).toBe('PST');
+ ).toBe('UTC-8');
});
- it('names UTC and labels zones without an abbreviation from UTC', () => {
+ it('names a zero offset UTC and keeps partial-hour offsets', () => {
expect(getTimeZoneShortName('Etc/UTC')).toBe('UTC');
expect(getTimeZoneShortName('Asia/Tokyo')).toBe('UTC+9');
expect(getTimeZoneShortName('Asia/Kolkata')).toBe('UTC+5:30');
@@ -79,3 +83,38 @@ describe('getTimeZoneShortName', () => {
);
});
});
+
+describe('getTimeZoneRangeShortName', () => {
+ it('uses the offset during the range, not today', () => {
+ expect(
+ getTimeZoneRangeShortName('America/Los_Angeles', [
+ new Date('2026-01-15T10:00:00Z'),
+ new Date('2026-01-15T11:00:00Z'),
+ ]),
+ ).toBe('UTC-8');
+ });
+
+ it('shows both offsets for a range across a DST change', () => {
+ expect(
+ getTimeZoneRangeShortName('America/Los_Angeles', [
+ new Date('2026-10-31T12:00:00Z'),
+ new Date('2026-11-02T12:00:00Z'),
+ ]),
+ ).toBe('UTC-7/-8');
+ expect(
+ getTimeZoneRangeShortName('Europe/London', [
+ new Date('2026-03-28T12:00:00Z'),
+ new Date('2026-03-30T12:00:00Z'),
+ ]),
+ ).toBe('UTC+0/+1');
+ });
+
+ it('shows one offset for a zone without DST', () => {
+ expect(
+ getTimeZoneRangeShortName('Etc/UTC', [
+ new Date('2026-01-15Z'),
+ new Date('2026-07-15Z'),
+ ]),
+ ).toBe('UTC');
+ });
+});
diff --git a/packages/app/src/__tests__/useDisplayTimeZone.test.tsx b/packages/app/src/__tests__/useDisplayTimeZone.test.tsx
new file mode 100644
index 000000000..7a67910bc
--- /dev/null
+++ b/packages/app/src/__tests__/useDisplayTimeZone.test.tsx
@@ -0,0 +1,136 @@
+import { renderHook } from '@testing-library/react';
+
+import {
+ TimeZoneOverrideProvider,
+ useTimeZoneLinkParam,
+ useTimeZoneOverride,
+ withTimeZoneParam,
+} from '@/timeZoneOverride';
+import { useDisplayTimeZone } from '@/useDisplayTimeZone';
+
+let mockTz: string | null = null;
+const mockSetTz = jest.fn();
+jest.mock('nuqs', () => ({
+ parseAsString: {},
+ useQueryState: () => [mockTz, mockSetTz],
+}));
+
+let mockUserTimeZone = 'Etc/UTC';
+jest.mock('@/useUserPreferences', () => ({
+ useUserPreferences: () => ({
+ userPreferences: { timeZone: mockUserTimeZone },
+ }),
+}));
+
+const withProvider = ({ children }: { children: React.ReactNode }) => (
+ {children}
+);
+
+describe('useDisplayTimeZone', () => {
+ beforeEach(() => {
+ mockTz = null;
+ mockUserTimeZone = 'Etc/UTC';
+ mockSetTz.mockClear();
+ });
+
+ it('uses the user setting outside a page override', () => {
+ mockTz = 'Asia/Tokyo';
+ const { result } = renderHook(() => useDisplayTimeZone());
+ expect(result.current).toBe('Etc/UTC');
+ });
+
+ it('uses the user setting when the page has no override', () => {
+ const { result } = renderHook(() => useDisplayTimeZone(), {
+ wrapper: withProvider,
+ });
+ expect(result.current).toBe('Etc/UTC');
+ });
+
+ it('prefers the page override', () => {
+ mockTz = 'Asia/Tokyo';
+ const { result } = renderHook(() => useDisplayTimeZone(), {
+ wrapper: withProvider,
+ });
+ expect(result.current).toBe('Asia/Tokyo');
+ });
+
+ it('lets the page override to local time', () => {
+ mockTz = 'local';
+ const { result } = renderHook(() => useDisplayTimeZone(), {
+ wrapper: withProvider,
+ });
+ expect(result.current).toBeUndefined();
+ });
+
+ it('ignores an override the browser does not recognise', () => {
+ mockTz = 'Mars/Olympus_Mons';
+ const { result } = renderHook(
+ () => ({
+ displayTimeZone: useDisplayTimeZone(),
+ override: useTimeZoneOverride(),
+ }),
+ { wrapper: withProvider },
+ );
+ expect(result.current.displayTimeZone).toBe('Etc/UTC');
+ expect(result.current.override?.timeZone).toBeNull();
+ });
+
+ it('writes the override to the URL', () => {
+ const { result } = renderHook(() => useTimeZoneOverride(), {
+ wrapper: withProvider,
+ });
+ result.current?.setTimeZone('Asia/Tokyo');
+ expect(mockSetTz).toHaveBeenCalledWith('Asia/Tokyo');
+ result.current?.setTimeZone(null);
+ expect(mockSetTz).toHaveBeenCalledWith(null);
+ });
+});
+
+describe('withTimeZoneParam', () => {
+ it('appends tz to a URL with or without a query', () => {
+ expect(withTimeZoneParam('/search', 'Asia/Tokyo')).toBe(
+ '/search?tz=Asia%2FTokyo',
+ );
+ expect(withTimeZoneParam('/search?from=1&to=2', 'Etc/UTC')).toBe(
+ '/search?from=1&to=2&tz=Etc%2FUTC',
+ );
+ });
+
+ it('keeps the hash after the query', () => {
+ expect(withTimeZoneParam('/dashboards/1?a=b#tile', 'local')).toBe(
+ '/dashboards/1?a=b&tz=local#tile',
+ );
+ });
+
+ it('leaves the URL unchanged without an override', () => {
+ expect(withTimeZoneParam('/search?a=b', null)).toBe('/search?a=b');
+ });
+
+ it('keeps existing param encoding intact', () => {
+ const where = encodeURIComponent(encodeURIComponent('a = 1\nb = 2'));
+ expect(withTimeZoneParam(`/search?where=${where}`, 'Etc/UTC')).toBe(
+ `/search?where=${where}&tz=Etc%2FUTC`,
+ );
+ });
+});
+
+describe('useTimeZoneLinkParam', () => {
+ beforeEach(() => {
+ mockTz = null;
+ });
+
+ it("adds the page's override to links", () => {
+ mockTz = 'Asia/Tokyo';
+ const { result } = renderHook(() => useTimeZoneLinkParam(), {
+ wrapper: withProvider,
+ });
+ expect(result.current('/search')).toBe('/search?tz=Asia%2FTokyo');
+ });
+
+ it('leaves links unchanged without an override', () => {
+ const { result } = renderHook(() => useTimeZoneLinkParam(), {
+ wrapper: withProvider,
+ });
+ expect(result.current('/search')).toBe('/search');
+ });
+});
diff --git a/packages/app/src/__tests__/useSearchTelemetry.test.tsx b/packages/app/src/__tests__/useSearchTelemetry.test.tsx
index 15892b5b6..d6877ae0c 100644
--- a/packages/app/src/__tests__/useSearchTelemetry.test.tsx
+++ b/packages/app/src/__tests__/useSearchTelemetry.test.tsx
@@ -7,10 +7,9 @@ jest.mock('@/layout', () => ({
withAppNav: (component: unknown) => component,
}));
-const mockAddAction = jest.fn();
-jest.mock('@hyperdx/browser', () => ({
- __esModule: true,
- default: { addAction: (...args: unknown[]) => mockAddAction(...args) },
+const mockRecordAction = jest.fn();
+jest.mock('@/utils/browserTelemetry', () => ({
+ recordAction: (...args: unknown[]) => mockRecordAction(...args),
}));
let mockExplainData: unknown[] | undefined = undefined;
@@ -83,8 +82,8 @@ describe('useSearchTelemetry', () => {
});
expect(result.current.searchElapsedMs).toBeGreaterThanOrEqual(0);
- expect(mockAddAction).toHaveBeenCalledTimes(1);
- expect(mockAddAction).toHaveBeenCalledWith('search executed', {
+ expect(mockRecordAction).toHaveBeenCalledTimes(1);
+ expect(mockRecordAction).toHaveBeenCalledWith('search executed', {
latency_ms: expect.any(Number),
source_id: 'my-source',
});
@@ -108,8 +107,8 @@ describe('useSearchTelemetry', () => {
rerender({ isAnyQueryFetching: false, isLive: false, sourceId: 'src-a' });
});
- expect(mockAddAction).toHaveBeenCalledTimes(1);
- expect(mockAddAction).toHaveBeenCalledWith('search executed', {
+ expect(mockRecordAction).toHaveBeenCalledTimes(1);
+ expect(mockRecordAction).toHaveBeenCalledWith('search executed', {
latency_ms: expect.any(Number),
source_id: 'src-a',
});
@@ -119,7 +118,7 @@ describe('useSearchTelemetry', () => {
rerender({ isAnyQueryFetching: false, isLive: false, sourceId: 'src-b' });
});
- expect(mockAddAction).toHaveBeenCalledTimes(1); // still just 1
+ expect(mockRecordAction).toHaveBeenCalledTimes(1); // still just 1
});
it('does NOT emit during live-tail ticks (P0 fix)', async () => {
@@ -140,7 +139,7 @@ describe('useSearchTelemetry', () => {
rerender({ isAnyQueryFetching: false, isLive: true, sourceId: 'src' });
});
- expect(mockAddAction).not.toHaveBeenCalled();
+ expect(mockRecordAction).not.toHaveBeenCalled();
});
it('measures elapsed time during live tail for display but does NOT emit', async () => {
@@ -163,7 +162,7 @@ describe('useSearchTelemetry', () => {
// Latency is surfaced for display ...
expect(result.current.searchElapsedMs).toBeGreaterThanOrEqual(0);
// ... but live-tail cycles are never reported to telemetry.
- expect(mockAddAction).not.toHaveBeenCalled();
+ expect(mockRecordAction).not.toHaveBeenCalled();
});
it('keeps the previous elapsed value when a live-tail poll starts (no blink)', async () => {
@@ -224,7 +223,7 @@ describe('useSearchTelemetry', () => {
// Two emits (one per false transition) — the clock was re-anchored
// only on the first genuine false→true, so elapsed on both are valid numbers
- expect(mockAddAction).toHaveBeenCalledTimes(2);
+ expect(mockRecordAction).toHaveBeenCalledTimes(2);
expect(firstElapsed).toBeGreaterThanOrEqual(0);
expect(result.current.searchElapsedMs).toBeGreaterThanOrEqual(0);
});
@@ -247,7 +246,7 @@ describe('useSearchTelemetry', () => {
});
expect(result.current.searchElapsedMs).toBeNull();
- expect(mockAddAction).not.toHaveBeenCalled();
+ expect(mockRecordAction).not.toHaveBeenCalled();
});
it('falls back to empty string source_id when sourceId is null', async () => {
@@ -267,7 +266,7 @@ describe('useSearchTelemetry', () => {
rerender({ isAnyQueryFetching: false, isLive: false, sourceId: null });
});
- expect(mockAddAction).toHaveBeenCalledWith('search executed', {
+ expect(mockRecordAction).toHaveBeenCalledWith('search executed', {
latency_ms: expect.any(Number),
source_id: '',
});
@@ -290,7 +289,7 @@ describe('useSearchTelemetry', () => {
rerender({ isAnyQueryFetching: false, isLive: false, sourceId: 'src' });
});
- expect(mockAddAction).not.toHaveBeenCalled();
+ expect(mockRecordAction).not.toHaveBeenCalled();
});
});
diff --git a/packages/app/src/__tests__/useTimeRangeInputText.test.tsx b/packages/app/src/__tests__/useTimeRangeInputText.test.tsx
new file mode 100644
index 000000000..2667c830e
--- /dev/null
+++ b/packages/app/src/__tests__/useTimeRangeInputText.test.tsx
@@ -0,0 +1,46 @@
+import { act, renderHook } from '@testing-library/react';
+
+import { useTimeRangeInputText } from '@/timeQuery';
+
+let mockTimeZone: string | undefined = 'Etc/UTC';
+jest.mock('@/useDisplayTimeZone', () => ({
+ useDisplayTimeZone: () => mockTimeZone,
+}));
+
+const range: [Date, Date] = [
+ new Date('2026-10-22T14:00:00Z'),
+ new Date('2026-10-22T15:00:00Z'),
+];
+
+describe('useTimeRangeInputText', () => {
+ beforeEach(() => {
+ jest.useFakeTimers().setSystemTime(new Date('2026-10-23T00:00:00Z'));
+ mockTimeZone = 'Etc/UTC';
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('formats the range in the display time zone', () => {
+ const { result } = renderHook(() => useTimeRangeInputText(range));
+ expect(result.current[0]).toBe('Oct 22 14:00:00 - Oct 22 15:00:00');
+ });
+
+ it('keeps edited text while the zone is unchanged', () => {
+ const { result, rerender } = renderHook(() => useTimeRangeInputText(range));
+ act(() => result.current[1]('last monday'));
+ rerender();
+ expect(result.current[0]).toBe('last monday');
+ });
+
+ it('re-formats the range when the zone changes', () => {
+ const { result, rerender } = renderHook(() => useTimeRangeInputText(range));
+ act(() => result.current[1]('last monday'));
+
+ mockTimeZone = 'Asia/Tokyo';
+ rerender();
+
+ expect(result.current[0]).toBe('Oct 22 23:00:00 - Oct 23 00:00:00');
+ });
+});
diff --git a/packages/app/src/__tests__/utils.test.ts b/packages/app/src/__tests__/utils.test.ts
index bdfdfc67b..ee74129dc 100644
--- a/packages/app/src/__tests__/utils.test.ts
+++ b/packages/app/src/__tests__/utils.test.ts
@@ -1645,8 +1645,7 @@ describe('getColorFromCSSToken', () => {
throw new Error('getComputedStyle unavailable');
});
- // Defaults to HyperDX in jsdom because the document has no
- // theme-clickstack class.
+ // Falls back to the semantic palette when the CSS var cannot be read.
expect(getColorFromCSSToken('chart-success')).toBe('#3ca951');
expect(getColorFromCSSToken('chart-warning')).toBe('#efb118');
expect(getColorFromCSSToken('chart-error')).toBe('#ff725c');
diff --git a/packages/app/src/api.ts b/packages/app/src/api.ts
index beec3a67d..b23e4610e 100644
--- a/packages/app/src/api.ts
+++ b/packages/app/src/api.ts
@@ -13,10 +13,14 @@ import type {
AlertEvaluationsApiResponse,
AlertHistoryRangeApiResponse,
AlertsApiResponse,
+ CreateOrgApiKeyApiResponse,
+ CreateOrgApiKeyRequest,
InstallationApiResponse,
MeApiResponse,
OnboardingDataApiResponse,
OnboardingTaskId,
+ OrgApiKeyApiResponse,
+ OrgApiKeysApiResponse,
PresetDashboard,
PresetDashboardFilter,
PrometheusMatrixResult,
@@ -90,6 +94,8 @@ const server = ky.create({
timeout: false,
});
+const ORG_API_KEYS_QUERY_KEY = ['team', 'api-keys'];
+
export const hdxServer = (
url: string,
options?: Options | undefined,
@@ -476,6 +482,53 @@ const api = {
},
});
},
+ useOrgApiKeys() {
+ return useQuery({
+ queryKey: ORG_API_KEYS_QUERY_KEY,
+ queryFn: () => hdxServer('team/api-keys').json(),
+ });
+ },
+ useCreateOrgApiKey() {
+ const queryClient = useQueryClient();
+ return useMutation<
+ CreateOrgApiKeyApiResponse,
+ Error | HTTPError,
+ CreateOrgApiKeyRequest
+ >({
+ mutationFn: async json =>
+ hdxServer('team/api-keys', {
+ method: 'POST',
+ json,
+ }).json(),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: ORG_API_KEYS_QUERY_KEY }),
+ });
+ },
+ useUpdateOrgApiKey() {
+ const queryClient = useQueryClient();
+ return useMutation<
+ OrgApiKeyApiResponse,
+ Error | HTTPError,
+ { id: string; description: string }
+ >({
+ mutationFn: async ({ id, description }) =>
+ hdxServer(`team/api-keys/${id}`, {
+ method: 'PATCH',
+ json: { description },
+ }).json(),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: ORG_API_KEYS_QUERY_KEY }),
+ });
+ },
+ useDeleteOrgApiKey() {
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async ({ id }) =>
+ hdxServer(`team/api-keys/${id}`, { method: 'DELETE' }),
+ onSuccess: () =>
+ queryClient.invalidateQueries({ queryKey: ORG_API_KEYS_QUERY_KEY }),
+ });
+ },
useDismissOnboarding() {
const queryClient = useQueryClient();
return useMutation({
@@ -630,6 +683,7 @@ const api = {
url: string;
name: string;
description: string;
+ titleEmoji?: boolean;
queryParams?: Record;
headers?: Record;
body?: string;
@@ -640,6 +694,7 @@ const api = {
url,
name,
description,
+ titleEmoji,
queryParams,
headers,
body,
@@ -651,6 +706,7 @@ const api = {
service,
url,
description,
+ titleEmoji,
queryParams: queryParams || {},
headers: headers || {},
body,
@@ -672,6 +728,7 @@ const api = {
url: string;
name: string;
description: string;
+ titleEmoji?: boolean;
queryParams?: Record;
headers?: Record;
body?: string;
@@ -683,6 +740,7 @@ const api = {
url,
name,
description,
+ titleEmoji,
queryParams,
headers,
body,
@@ -694,6 +752,7 @@ const api = {
service,
url,
description,
+ titleEmoji,
queryParams: queryParams || {},
headers: headers || {},
body,
diff --git a/packages/app/src/brand/Logomark.tsx b/packages/app/src/brand/Logomark.tsx
new file mode 100644
index 000000000..701296ef5
--- /dev/null
+++ b/packages/app/src/brand/Logomark.tsx
@@ -0,0 +1,41 @@
+const VIEWBOX_WIDTH = 38.7979;
+const VIEWBOX_HEIGHT = 44.7998;
+
+/**
+ * ClickStack mark from the hexagon-and-bolt symbol.
+ * The bolt uses the page background so it stays two-tone: white on the dark
+ * surface, dark on the light one.
+ *
+ * `size` is the box height. The default box is square, which is what the
+ * collapsed rail and the other callers size against. `fit="symbol"` hugs the
+ * hexagon, which is taller than it is wide, and is what the wordmark uses.
+ */
+export default function Logomark({
+ size = 16,
+ fit = 'square',
+}: {
+ size?: number;
+ fit?: 'square' | 'symbol';
+}) {
+ const width =
+ fit === 'symbol' ? size * (VIEWBOX_WIDTH / VIEWBOX_HEIGHT) : size;
+
+ return (
+
+ );
+}
diff --git a/packages/app/src/brand/Wordmark.tsx b/packages/app/src/brand/Wordmark.tsx
new file mode 100644
index 000000000..8671da9b9
--- /dev/null
+++ b/packages/app/src/brand/Wordmark.tsx
@@ -0,0 +1,19 @@
+import { Group, Text } from '@mantine/core';
+
+import Logomark from './Logomark';
+
+// The brand lockup: a 23px symbol, an 8px gap, and the name in Inter 18px
+// medium. The name is passed in so this file does not import the brand barrel,
+// which imports this file.
+const MARK_HEIGHT = 23;
+
+export default function Wordmark({ name }: { name: string }) {
+ return (
+
+
+
+ {name}
+
+
+ );
+}
diff --git a/packages/app/src/brand/__tests__/Wordmark.test.tsx b/packages/app/src/brand/__tests__/Wordmark.test.tsx
new file mode 100644
index 000000000..3cdf08fec
--- /dev/null
+++ b/packages/app/src/brand/__tests__/Wordmark.test.tsx
@@ -0,0 +1,37 @@
+import { MantineProvider } from '@mantine/core';
+import { render, screen } from '@testing-library/react';
+
+import { useLogomark, useWordmark } from '@/brand';
+
+function Lockup() {
+ return useWordmark();
+}
+
+function SquareMark() {
+ return useLogomark({ size: 22 });
+}
+
+describe('Wordmark', () => {
+ it('renders the brand name beside a mark that hugs the hexagon', () => {
+ const { container } = render(
+
+
+ ,
+ );
+
+ expect(screen.getByText('ClickStack')).toBeInTheDocument();
+ const svg = container.querySelector('svg');
+ expect(svg).toHaveAttribute('height', '23');
+ expect(Number(svg?.getAttribute('width'))).toBeLessThan(23);
+ });
+});
+
+describe('Logomark', () => {
+ it('keeps a square box unless the wordmark asks it to hug the symbol', () => {
+ const { container } = render();
+
+ const svg = container.querySelector('svg');
+ expect(svg).toHaveAttribute('width', '22');
+ expect(svg).toHaveAttribute('height', '22');
+ });
+});
diff --git a/packages/app/src/brand/__tests__/pageTitle.test.tsx b/packages/app/src/brand/__tests__/pageTitle.test.tsx
new file mode 100644
index 000000000..25d017213
--- /dev/null
+++ b/packages/app/src/brand/__tests__/pageTitle.test.tsx
@@ -0,0 +1,20 @@
+jest.mock('next-runtime-env', () => ({
+ env: (key: string) =>
+ key === 'NEXT_PUBLIC_INSTANCE_LABEL' ? 'UK' : undefined,
+}));
+
+import { renderHook } from '@testing-library/react';
+
+import { usePageTitle } from '@/brand';
+
+describe('usePageTitle', () => {
+ it('is the brand name plus the instance label when no page is given', () => {
+ const { result } = renderHook(() => usePageTitle());
+ expect(result.current).toBe('ClickStack UK');
+ });
+
+ it('prepends the page name', () => {
+ const { result } = renderHook(() => usePageTitle('Search'));
+ expect(result.current).toBe('Search - ClickStack UK');
+ });
+});
diff --git a/packages/app/src/brand/index.tsx b/packages/app/src/brand/index.tsx
new file mode 100644
index 000000000..253c64219
--- /dev/null
+++ b/packages/app/src/brand/index.tsx
@@ -0,0 +1,36 @@
+import { useMemo } from 'react';
+
+import { INSTANCE_TITLE_SUFFIX } from '@/config';
+import { dfeBrandName, Logomark, Wordmark } from '@/dfe/brand';
+
+export const BRAND_DISPLAY_NAME = dfeBrandName('ClickStack');
+
+// Named as a hook so a downstream build can read state here without
+// renaming every call site. This build returns a constant.
+// eslint-disable-next-line @eslint-react/no-unnecessary-use-prefix
+export function useBrandDisplayName(): string {
+ return BRAND_DISPLAY_NAME;
+}
+
+/**
+ * Page title: brand name plus the configured instance label, with an
+ * optional page name prepended.
+ * e.g. usePageTitle('Search') => "Search - ClickStack"
+ */
+// eslint-disable-next-line @eslint-react/no-unnecessary-use-prefix -- see useBrandDisplayName
+export function usePageTitle(page?: string): string {
+ const brandTitle = `${BRAND_DISPLAY_NAME}${INSTANCE_TITLE_SUFFIX}`;
+ return page ? `${page} - ${brandTitle}` : brandTitle;
+}
+
+// The hooks return elements so callers do not render a component created
+// during render. A downstream build replaces this module to change the
+// name and the marks without editing each call site.
+export function useWordmark() {
+ return useMemo(() => , []);
+}
+
+export function useLogomark(props?: { size?: number }) {
+ const size = props?.size;
+ return useMemo(() => , [size]);
+}
diff --git a/packages/app/src/components/AdhocDashboardFilter/AdhocConditionEditor.tsx b/packages/app/src/components/AdhocDashboardFilter/AdhocConditionEditor.tsx
index 51135a554..cdb68e95b 100644
--- a/packages/app/src/components/AdhocDashboardFilter/AdhocConditionEditor.tsx
+++ b/packages/app/src/components/AdhocDashboardFilter/AdhocConditionEditor.tsx
@@ -1,4 +1,5 @@
import { useState } from 'react';
+import { ResolvedFilterValuesQuery } from '@hyperdx/common-utils/dist/filters';
import {
AdhocDashboardFilter,
AdhocFilterCondition,
@@ -15,6 +16,8 @@ import { useAdhocFilterOptions } from './useAdhocFilterOptions';
type AdhocConditionEditorProps = {
filter: AdhocDashboardFilter;
dateRange: [Date, Date];
+ /** The filter's `where`, variables expanded, narrowing the suggestions. */
+ suggestionsWhere?: ResolvedFilterValuesQuery;
/** The condition being edited; unset when adding one. */
initial?: AdhocFilterCondition;
onSubmit: (condition: AdhocFilterCondition) => void;
@@ -27,11 +30,17 @@ type AdhocConditionEditorProps = {
export function AdhocConditionEditor({
filter,
dateRange,
+ suggestionsWhere,
initial,
onSubmit,
}: AdhocConditionEditorProps) {
const [valueKey, setValueKey] = useState(initial?.key ?? '');
- const { keys, values } = useAdhocFilterOptions(filter, valueKey, dateRange);
+ const { keys, values } = useAdhocFilterOptions(
+ filter,
+ valueKey,
+ dateRange,
+ suggestionsWhere,
+ );
const isPromql = filter.sourceType === 'promql';
return (
@@ -41,9 +50,11 @@ export function AdhocConditionEditor({
keyOptions={keys.data}
isLoadingKeys={keys.isLoading}
isKeysError={keys.isError}
+ keysErrorMessage={keys.error?.message}
valueOptions={values.data}
isLoadingValues={values.isLoading}
isValuesError={values.isError}
+ valuesErrorMessage={values.error?.message}
onKeyChange={setValueKey}
keyLabel={isPromql ? 'Label' : 'Key'}
keyPlaceholder={
diff --git a/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx b/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx
index 2bc0eaae6..8686035ab 100644
--- a/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx
+++ b/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx
@@ -1,11 +1,19 @@
-import { useState } from 'react';
-import { isAdhocConditionSupported } from '@hyperdx/common-utils/dist/filters';
+import { useMemo, useState } from 'react';
+import {
+ getDashboardVariableFilters,
+ getPendingFilterValuesVariables,
+ isAdhocConditionSupported,
+ resolveFilterValuesWhere,
+} from '@hyperdx/common-utils/dist/filters';
import {
ADHOC_FILTER_MAX_CONDITIONS,
AdhocDashboardFilter as AdhocDashboardFilterType,
AdhocFilterCondition,
AdhocFilterConditionSchema,
+ ChartVariable,
+ DashboardFilter,
} from '@hyperdx/common-utils/dist/types';
+import { getVariableReferences } from '@hyperdx/common-utils/dist/variables';
import {
ActionIcon,
CloseButton,
@@ -19,7 +27,9 @@ import { IconPlus } from '@tabler/icons-react';
import {
DashboardFilterLabel,
+ FilterCaution,
FilterEffect,
+ getPendingVariablesTooltip,
} from '@/components/DashboardFilterLabel';
import { FilterPill, getFilterOperatorDisplay } from '@/components/FilterPill';
@@ -35,6 +45,10 @@ type AdhocDashboardFilterProps = {
onChange: (conditions: AdhocFilterCondition[]) => void;
dateRange: [Date, Date];
effect: FilterEffect;
+ /** The dashboard's variables, which the filter's `where` may reference. */
+ variables?: ChartVariable[];
+ /** Required filters with nothing selected. */
+ unsatisfiedRequiredFilters?: DashboardFilter[];
};
/** A dashboard filter bar control holding one ad hoc filter's conditions. */
@@ -44,11 +58,46 @@ export function AdhocDashboardFilter({
onChange,
dateRange,
effect,
+ variables,
+ unsatisfiedRequiredFilters,
}: AdhocDashboardFilterProps) {
const [isAdding, setIsAdding] = useState(false);
const isAtLimit = conditions.length >= ADHOC_FILTER_MAX_CONDITIONS;
+ // The `where` narrowing the suggestions, and what it is still waiting on.
+ // Blocked only by the required filters it references: a global requirement
+ // blocks tiles, not the filter bar, same as queried dropdown filters.
+ const { suggestionsWhere, pendingVariables, blockingFilterNames } =
+ useMemo(() => {
+ const where = filter.sourceType === 'sql' ? filter.where : undefined;
+ const query = { where, whereLanguage: filter.whereLanguage };
+ const referencedNames = new Set(
+ getVariableReferences(where ?? '').map(reference => reference.name),
+ );
+ return {
+ suggestionsWhere: resolveFilterValuesWhere(query, variables),
+ pendingVariables: getPendingFilterValuesVariables(query, variables),
+ blockingFilterNames: getDashboardVariableFilters(
+ unsatisfiedRequiredFilters,
+ )
+ .filter(({ name }) => referencedNames.has(name))
+ .map(({ filter: blocking }) => blocking.name),
+ };
+ }, [
+ filter.sourceType,
+ filter.where,
+ filter.whereLanguage,
+ variables,
+ unsatisfiedRequiredFilters,
+ ]);
+ const dependsOn = blockingFilterNames.length
+ ? `This filter depends on: ${blockingFilterNames.join(', ')}`
+ : undefined;
+ const disabledReason = dependsOn ?? suggestionsWhere.error;
+ const isDisabled = !!disabledReason;
+
const toggleAdding = () => {
+ if (isDisabled) return;
if (isAtLimit) {
notifyAdhocFilterFull(filter);
return;
@@ -71,7 +120,27 @@ export function AdhocDashboardFilter({
return (
-
+
+ {dependsOn && (
+
+ )}
+ {!isDisabled && pendingVariables.length > 0 && (
+
+ )}
+ {suggestionsWhere.error && (
+
+ )}
+ remove(index)}
- renderPopover={close => (
- {
- if (!isStorable(next)) return;
- replace(index, next);
- close();
- }}
- />
- )}
+ // Editing would look up suggestions; removing still works.
+ renderPopover={
+ isDisabled
+ ? undefined
+ : close => (
+ {
+ if (!isStorable(next)) return;
+ replace(index, next);
+ close();
+ }}
+ />
+ )
+ }
data-testid="adhoc-condition-pill"
/>
);
@@ -121,8 +196,8 @@ export function AdhocDashboardFilter({
setIsAdding(true)}
- style={{ cursor: 'pointer', flex: 1 }}
+ onClick={isDisabled ? undefined : () => setIsAdding(true)}
+ style={{ cursor: isDisabled ? 'default' : 'pointer', flex: 1 }}
>
{filter.name}
@@ -137,7 +212,7 @@ export function AdhocDashboardFilter({
/>
)}
@@ -167,6 +247,7 @@ export function AdhocDashboardFilter({
{
if (!isStorable(condition)) return;
onChange([...conditions, condition]);
diff --git a/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx b/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx
index 00f3f346c..14e3f710f 100644
--- a/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx
+++ b/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx
@@ -1,7 +1,9 @@
+import { ComponentProps } from 'react';
import {
ADHOC_FILTER_MAX_CONDITIONS,
AdhocDashboardFilter as AdhocDashboardFilterType,
AdhocFilterCondition,
+ DashboardFilter,
} from '@hyperdx/common-utils/dist/types';
import { notifications } from '@mantine/notifications';
import { screen } from '@testing-library/react';
@@ -43,6 +45,7 @@ const addButton = () => screen.getByTestId('adhoc-filter-add-Conditions');
const renderFilter = (
conditions: AdhocFilterCondition[],
definition: AdhocDashboardFilterType = filter,
+ props: Partial> = {},
) => {
const onChange = jest.fn();
renderWithMantine(
@@ -52,6 +55,7 @@ const renderFilter = (
onChange={onChange}
dateRange={dateRange}
effect={{ hasEffect: true, tooltip: '' }}
+ {...props}
/>,
);
return onChange;
@@ -165,4 +169,132 @@ describe('AdhocDashboardFilter', () => {
expect(onChange).toHaveBeenCalledWith([]);
});
+
+ describe('narrowed by a condition', () => {
+ const narrowed: AdhocDashboardFilterType = {
+ ...filter,
+ where: 'Namespace IN ($namespace)',
+ whereLanguage: 'sql',
+ };
+ const namespaceFilter: DashboardFilter = {
+ id: 'ns',
+ type: 'STATIC_LIST',
+ name: 'Namespace',
+ options: ['ns-a'],
+ isBroadcastEnabled: false,
+ isVariableEnabled: true,
+ variableName: 'namespace',
+ minSelections: 1,
+ };
+ const namespace = (values: string[]) => [{ name: 'namespace', values }];
+
+ it('waits for a required filter the condition references', async () => {
+ const onChange = renderFilter([existing], narrowed, {
+ variables: namespace([]),
+ unsatisfiedRequiredFilters: [namespaceFilter],
+ });
+
+ expect(addButton()).toHaveAttribute('aria-disabled', 'true');
+ await userEvent.hover(addButton());
+ expect(
+ await screen.findByText('This filter depends on: Namespace'),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByTestId('dashboard-filter-blocked-Conditions'),
+ ).toBeInTheDocument();
+
+ await userEvent.click(addButton());
+ await userEvent.click(screen.getByTestId('adhoc-condition-pill'));
+ expect(screen.queryByTestId(`${editorId}-key`)).not.toBeInTheDocument();
+
+ // Removing looks nothing up, so it still works.
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Remove filter' }),
+ );
+ expect(onChange).toHaveBeenCalledWith([]);
+ });
+
+ it('suggests from the rows the condition matches once it resolves', async () => {
+ renderFilter([], narrowed, { variables: namespace(['ns-a']) });
+
+ await userEvent.click(addButton());
+
+ expect(await screen.findByTestId(`${editorId}-key`)).toBeInTheDocument();
+ expect(jest.mocked(useAdhocFilterOptions)).toHaveBeenLastCalledWith(
+ narrowed,
+ expect.any(String),
+ dateRange,
+ { where: "Namespace IN ('ns-a')", whereLanguage: 'sql' },
+ );
+ });
+
+ it('flags an optional variable the condition needs a value for', () => {
+ renderFilter([], narrowed, { variables: namespace([]) });
+
+ expect(
+ screen.getByTestId('dashboard-filter-pending-variable-Conditions'),
+ ).toBeInTheDocument();
+ expect(addButton()).not.toHaveAttribute('aria-disabled', 'true');
+ });
+
+ it("stops suggesting when the condition's variables can't be expanded", async () => {
+ renderFilter(
+ [],
+ { ...narrowed, where: '$__filter(Namespace, $nope)' },
+ { variables: namespace(['ns-a']) },
+ );
+
+ expect(
+ screen.getByTestId('dashboard-filter-error-Conditions'),
+ ).toBeInTheDocument();
+ expect(addButton()).toHaveAttribute('aria-disabled', 'true');
+ await userEvent.click(addButton());
+ expect(screen.queryByTestId(`${editorId}-key`)).not.toBeInTheDocument();
+ });
+
+ it.each([
+ ['no condition', filter],
+ ['a condition that does not reference it', narrowed],
+ ['a PromQL source', { ...narrowed, sourceType: 'promql' as const }],
+ ])(
+ 'is not blocked by an unreferenced global required filter with %s',
+ async (_label, definition) => {
+ renderFilter([], definition, {
+ variables: namespace(['ns-a']),
+ unsatisfiedRequiredFilters: [
+ {
+ ...namespaceFilter,
+ id: 'env',
+ name: 'Env',
+ variableName: 'env',
+ isGlobalRequirement: true,
+ },
+ ],
+ });
+
+ expect(
+ screen.queryByTestId('dashboard-filter-blocked-Conditions'),
+ ).not.toBeInTheDocument();
+ await userEvent.click(addButton());
+ expect(
+ await screen.findByTestId(`${editorId}-key`),
+ ).toBeInTheDocument();
+ },
+ );
+
+ it('ignores a condition on a PromQL filter', async () => {
+ renderFilter(
+ [],
+ { ...narrowed, sourceType: 'promql' },
+ {
+ variables: namespace([]),
+ unsatisfiedRequiredFilters: [namespaceFilter],
+ },
+ );
+
+ await userEvent.click(addButton());
+
+ expect(await screen.findByTestId(`${editorId}-key`)).toBeInTheDocument();
+ });
+ });
});
diff --git a/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx b/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx
index 8f3161094..e0880af24 100644
--- a/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx
+++ b/packages/app/src/components/AdhocDashboardFilter/__tests__/useAdhocFilterOptions.test.tsx
@@ -1,5 +1,6 @@
import { ReactNode } from 'react';
import { ColumnMeta, JSDataType } from '@hyperdx/common-utils/dist/clickhouse';
+import { ResolvedFilterValuesQuery } from '@hyperdx/common-utils/dist/filters';
import {
AdhocDashboardFilter,
SourceKind,
@@ -202,13 +203,15 @@ describe('useAdhocFilterOptions', () => {
const renderOptions = (
adhocFilter: AdhocDashboardFilter,
key = 'SeverityText',
+ suggestionsWhere?: ResolvedFilterValuesQuery,
) => {
const queryClient = new QueryClient();
const wrapper = ({ children }: { children: ReactNode }) => (
{children}
);
return renderHook(
- () => useAdhocFilterOptions(adhocFilter, key, DATE_RANGE),
+ () =>
+ useAdhocFilterOptions(adhocFilter, key, DATE_RANGE, suggestionsWhere),
{ wrapper },
);
};
@@ -247,6 +250,45 @@ describe('useAdhocFilterOptions', () => {
expect(chartConfigs).toEqual([expect.objectContaining({ source: 'logs' })]);
});
+ it('reads keys and values only from rows matching its condition', () => {
+ mockSources = [
+ { ...source('logs', SourceKind.Log), implicitColumnExpression: 'Body' },
+ ];
+ mockAllFields([[column('SeverityText', 'LowCardinality(String)')]]);
+ const suggestionsWhere = {
+ where: 'Namespace:$namespace',
+ whereLanguage: 'lucene' as const,
+ };
+ renderOptions(filter('sql', ['logs']), 'SeverityText', suggestionsWhere);
+
+ expect(jest.mocked(useMultipleAllFields).mock.calls.at(-1)![1]).toEqual(
+ expect.objectContaining({
+ conditions: [
+ expect.objectContaining({
+ ...suggestionsWhere,
+ implicitColumnExpression: 'Body',
+ }),
+ ],
+ }),
+ );
+ expect(lastSqlLookup()[0].chartConfigs).toEqual([
+ expect.objectContaining(suggestionsWhere),
+ ]);
+ });
+
+ it('reads every row when its condition is blank', () => {
+ mockSources = [source('logs', SourceKind.Log)];
+ mockAllFields([[column('SeverityText', 'LowCardinality(String)')]]);
+ renderOptions(filter('sql', ['logs']), 'SeverityText', {
+ where: ' ',
+ whereLanguage: 'sql',
+ });
+
+ expect(
+ jest.mocked(useMultipleAllFields).mock.calls.at(-1)![1]?.conditions,
+ ).toBeUndefined();
+ });
+
it('quotes a map column name that is not a bare identifier', () => {
mockSources = [source('logs', SourceKind.Log)];
mockAllFields([[column('log-attributes', 'Map(String, String)')]]);
diff --git a/packages/app/src/components/AdhocDashboardFilter/useAdhocFilterOptions.ts b/packages/app/src/components/AdhocDashboardFilter/useAdhocFilterOptions.ts
index 55c2af2db..aca36927e 100644
--- a/packages/app/src/components/AdhocDashboardFilter/useAdhocFilterOptions.ts
+++ b/packages/app/src/components/AdhocDashboardFilter/useAdhocFilterOptions.ts
@@ -11,6 +11,7 @@ import { Field, tcFromSource } from '@hyperdx/common-utils/dist/core/metadata';
import {
getAdhocFilterSourceKinds,
isAdhocComparableDataType,
+ ResolvedFilterValuesQuery,
} from '@hyperdx/common-utils/dist/filters';
import {
AdhocDashboardFilter,
@@ -143,6 +144,8 @@ type AdhocFilterSuggestions = {
data: string[];
isLoading: boolean;
isError: boolean;
+ /** Set when every source's lookup failed. */
+ error?: Error | null;
};
type AdhocFilterKeys = AdhocFilterSuggestions & {
@@ -154,15 +157,32 @@ type AdhocFilterKeys = AdhocFilterSuggestions & {
function useSqlSourceKeys(
sources: TSource[],
dateRange: [Date, Date],
+ suggestionsWhere: ResolvedFilterValuesQuery | undefined,
): AdhocFilterKeys {
const tableConnections = useMemo(() => sources.map(tcFromSource), [sources]);
+ const where = suggestionsWhere?.where.trim()
+ ? suggestionsWhere.where
+ : undefined;
+ const whereLanguage = suggestionsWhere?.whereLanguage;
+ const conditions = useMemo(
+ () =>
+ where
+ ? sources.map(source => ({
+ ...pickSourceConfigFields(source),
+ where,
+ whereLanguage,
+ }))
+ : undefined,
+ [sources, where, whereLanguage],
+ );
const {
fieldsByTableConnection,
columnsByTableConnection,
isFieldMetadataDisabled,
isLoading,
isError,
- } = useMultipleAllFields(tableConnections, { dateRange });
+ error,
+ } = useMultipleAllFields(tableConnections, { dateRange, conditions });
return useMemo(() => {
const keysBySourceId = new Map();
@@ -184,6 +204,7 @@ function useSqlSourceKeys(
columnNames,
isLoading,
isError,
+ error,
};
}, [
sources,
@@ -192,6 +213,7 @@ function useSqlSourceKeys(
isFieldMetadataDisabled,
isLoading,
isError,
+ error,
]);
}
@@ -226,6 +248,7 @@ function usePromqlSourceKeys(
columnNames: NO_COLUMNS,
isLoading: results.some(result => result.isLoading),
isError: results.some(result => result.isError),
+ error: results.find(result => result.error)?.error,
};
},
[sources],
@@ -259,7 +282,10 @@ function useSqlSourceValues(
key: string,
dateRange: [Date, Date],
columnNames: Set,
+ suggestionsWhere: ResolvedFilterValuesQuery | undefined,
): AdhocFilterSuggestions {
+ const where = suggestionsWhere?.where ?? '';
+ const whereLanguage = suggestionsWhere?.whereLanguage ?? 'sql';
const chartConfigs = useMemo(
() =>
sources.map(source => ({
@@ -267,10 +293,10 @@ function useSqlSourceValues(
dateRange,
source: source.id,
select: '',
- where: '',
- whereLanguage: 'sql' as const,
+ where,
+ whereLanguage,
})),
- [sources, dateRange],
+ [sources, dateRange, where, whereLanguage],
);
// Quoted like the search sidebar does, so a column named e.g.
// `log-attributes` isn't read as a subtraction.
@@ -278,14 +304,14 @@ function useSqlSourceValues(
() => (key ? [toQuotedClickHouseKeyExpression(key, columnNames)] : []),
[key, columnNames],
);
- const { data, isFetching, isError } = useMultipleGetKeyValues(
+ const { data, isFetching, isError, error } = useMultipleGetKeyValues(
{ chartConfigs, keys, limit: SINGLE_KEY_VALUES_LIMIT },
// The previous key's values aren't suggestions for this one.
{ placeholderData: undefined, retry: false, enabled: sources.length > 0 },
);
const values = useMemo(() => getValueSuggestions(data), [data]);
- return { data: values, isLoading: !!key && isFetching, isError };
+ return { data: values, isLoading: !!key && isFetching, isError, error };
}
const combineValues = (
@@ -294,6 +320,7 @@ const combineValues = (
data: unionSorted(results.map(result => result.data)),
isLoading: results.some(result => result.isFetching),
isError: results.some(result => result.isError),
+ error: results.find(result => result.error)?.error,
});
function usePromqlSourceValues(
@@ -332,16 +359,22 @@ function usePromqlSourceValues(
* Suggestions for an ad hoc filter's condition editor, deduplicated across its
* sources. Keys are the columns and map / JSON keys of its SQL sources, in the
* search sidebar's key format, or the label names of its PromQL sources.
- * Values are those observed for `key`.
+ * Values are those observed for `key`. For SQL sources, `suggestionsWhere` (the
+ * filter's `where` with variables expanded) narrows the rows both are read from.
*/
export function useAdhocFilterOptions(
filter: AdhocDashboardFilter,
key: string,
dateRange: [Date, Date],
+ suggestionsWhere?: ResolvedFilterValuesQuery,
): { keys: AdhocFilterSuggestions; values: AdhocFilterSuggestions } {
const sources = useAdhocFilterSources(filter);
const isPromql = filter.sourceType === 'promql';
- const sqlKeys = useSqlSourceKeys(isPromql ? NO_SOURCES : sources, dateRange);
+ const sqlKeys = useSqlSourceKeys(
+ isPromql ? NO_SOURCES : sources,
+ dateRange,
+ suggestionsWhere,
+ );
const promqlKeys = usePromqlSourceKeys(
isPromql ? sources : NO_SOURCES,
dateRange,
@@ -360,6 +393,7 @@ export function useAdhocFilterOptions(
lookupKey,
dateRange,
keys.columnNames,
+ suggestionsWhere,
);
const promqlValues = usePromqlSourceValues(
isPromql ? sourcesWithKey : NO_SOURCES,
diff --git a/packages/app/src/components/Alert.stories.tsx b/packages/app/src/components/Alert.stories.tsx
index 3d6451946..0fa2e04d8 100644
--- a/packages/app/src/components/Alert.stories.tsx
+++ b/packages/app/src/components/Alert.stories.tsx
@@ -11,9 +11,8 @@ import {
/**
* Themed Mantine `Alert` with our semantic variants (`info` / `success` /
* `warning` / `danger`). Each variant is wired to the `--color-text-*` and
- * `--alert-*` design tokens in both brand themes, so use the Brand
- * (HyperDX / ClickStack) and Theme (Light / Dark) toolbar toggles to review
- * every combination. The alert body keeps a high-contrast text color while the
+ * `--alert-*` design tokens. Use the Theme (Light / Dark) toolbar toggle to
+ * review both color modes. The alert body keeps a high-contrast text color while the
* title/icon take the semantic accent.
*/
const meta = {
diff --git a/packages/app/src/components/AlertDisplayFields.tsx b/packages/app/src/components/AlertDisplayFields.tsx
index a91248669..230526476 100644
--- a/packages/app/src/components/AlertDisplayFields.tsx
+++ b/packages/app/src/components/AlertDisplayFields.tsx
@@ -32,6 +32,7 @@ export function AlertDisplayFields({
displayNameName,
tagsName,
derivedDisplayName,
+ displayNameLabel = 'Name',
displayNameRequired = false,
tagsInherit = true,
labelMarginTop = 'xs',
@@ -41,6 +42,12 @@ export function AlertDisplayFields({
tagsName: Path;
/** Name the server will derive when the field is left empty. */
derivedDisplayName?: string | null;
+ /**
+ * Label for the name field. Override where the surface already shows the
+ * name of what the alert watches, and a bare "Name" would read as that
+ * object's name rather than the alert's.
+ */
+ displayNameLabel?: string;
/**
* Whether the alert must be named here. Set for alerts with no parent to
* inherit a name from, where leaving it blank names the alert after
@@ -59,7 +66,7 @@ export function AlertDisplayFields({
- Name
+ {displayNameLabel}
{displayNameRequired && (
*
diff --git a/packages/app/src/components/AppNav/AppNav.components.tsx b/packages/app/src/components/AppNav/AppNav.components.tsx
index ab4994d3c..98515aca3 100644
--- a/packages/app/src/components/AppNav/AppNav.components.tsx
+++ b/packages/app/src/components/AppNav/AppNav.components.tsx
@@ -2,6 +2,11 @@ import React from 'react';
import Link from 'next/link';
import cx from 'classnames';
import { Badge } from '@clickhouse/click-ui';
+import {
+ setAttributes,
+ setUser,
+ startNewSession,
+} from '@clickhouse/clickstack-browser';
import {
Avatar,
Button,
@@ -174,6 +179,12 @@ export const AppNavUserMenu = ({
leftSection={}
component={Link}
href={logoutUrl}
+ onClick={() => {
+ // The next user on this device gets a RUM session of their own
+ setUser(null);
+ setAttributes(null);
+ startNewSession();
+ }}
>
Logout
diff --git a/packages/app/src/components/AppNav/AppNav.module.scss b/packages/app/src/components/AppNav/AppNav.module.scss
index 80415250f..405444075 100644
--- a/packages/app/src/components/AppNav/AppNav.module.scss
+++ b/packages/app/src/components/AppNav/AppNav.module.scss
@@ -42,6 +42,19 @@ $transition-slow: 0.2s ease;
.navGhost {
transition: width 0.2s ease;
will-change: width;
+ flex-shrink: 0;
+}
+
+// Covers the page while the rail's full nav is open on a compact viewport.
+// Dimming sits one layer below the nav, in the same layer as top-level drawers.
+.navScrim {
+ position: fixed;
+ inset: 0;
+ z-index: 9;
+ border: 0;
+ padding: 0;
+ background: rgb(0 0 0 / 40%);
+ cursor: pointer;
}
.nav {
@@ -60,6 +73,22 @@ $transition-slow: 0.2s ease;
position: fixed;
}
+ // Same layer as a top-level drawer (`contextZIndex + 10` from
+ // ZIndexContext, see DBRowSidePanel). The scrim is one below. PageHeader
+ // itself is z-index 2, so this covers the page chrome.
+ &Overlay {
+ top: 0;
+ left: 0;
+ z-index: 10;
+ box-shadow: 4px 0 16px rgb(0 0 0 / 25%);
+ }
+
+ // Closing the overlay drops the nav back into the flow. Animating its width
+ // from the overlay width would push the page content sideways first.
+ &CompactRail {
+ transition: none;
+ }
+
&Collapsed {
.navLinks {
padding-inline: 0;
@@ -123,15 +152,43 @@ $transition-slow: 0.2s ease;
}
.collapseButton {
- margin-right: -$spacing-xs;
- margin-left: -$spacing-xs;
+ /* Click UI token names are camelCase. */
+ /* stylelint-disable custom-property-pattern */
+ flex-shrink: 0;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ margin: 0;
+ padding: var(--click-button-iconButton-sm-space-y)
+ var(--click-button-iconButton-sm-space-x);
+ border: var(--click-button-stroke) solid
+ var(--click-button-iconButton-color-primary-stroke-default);
+ border-radius: var(--click-button-iconButton-radii-all);
+ background: var(--click-button-iconButton-color-primary-background-default);
+ color: var(--click-button-iconButton-color-primary-text-default);
+ cursor: pointer;
+ line-height: 0;
+
+ svg {
+ width: var(--click-image-sm-size-width);
+ height: var(--click-image-sm-size-height);
+ }
+
+ &:hover {
+ border-color: var(--click-button-iconButton-color-primary-stroke-hover);
+ background: var(--click-button-iconButton-color-primary-background-hover);
+ color: var(--click-button-iconButton-color-primary-text-hover);
+ }
+
+ &:focus-visible {
+ outline: 2px solid var(--click-global-color-outline-default);
+ outline-offset: 2px;
+ }
&Collapsed {
transform: rotate(180deg);
- margin-top: 0;
- margin-right: 0;
- margin-left: 0;
}
+ /* stylelint-enable custom-property-pattern */
}
.scrollContainer {
diff --git a/packages/app/src/components/AppNav/AppNav.tsx b/packages/app/src/components/AppNav/AppNav.tsx
index f9e541161..7e13255a5 100644
--- a/packages/app/src/components/AppNav/AppNav.tsx
+++ b/packages/app/src/components/AppNav/AppNav.tsx
@@ -1,23 +1,14 @@
-import { useCallback, useEffect, useMemo } from 'react';
+import { useCallback, useEffect, useMemo, useRef } from 'react';
import Link from 'next/link';
import Router, { useRouter } from 'next/router';
import Script from 'next/script';
import cx from 'classnames';
import { Badge } from '@clickhouse/click-ui';
-import HyperDX from '@hyperdx/browser';
+import { setAttributes, setUser } from '@clickhouse/clickstack-browser';
import { SavedSearchListApiResponse } from '@hyperdx/common-utils/dist/types';
+import { Anchor, Collapse, Flex, Group, ScrollArea, Text } from '@mantine/core';
+import { useDisclosure, useFocusTrap, useLocalStorage } from '@mantine/hooks';
import {
- ActionIcon,
- Anchor,
- Collapse,
- Flex,
- Group,
- ScrollArea,
- Text,
-} from '@mantine/core';
-import { useDisclosure, useLocalStorage } from '@mantine/hooks';
-import {
- IconArrowBarToLeft,
IconBell,
IconChartDots,
IconDeviceFloppy,
@@ -29,8 +20,10 @@ import {
} from '@tabler/icons-react';
import api from '@/api';
+import { useLogomark, useWordmark } from '@/brand';
import { AlertStatusIcon } from '@/components/AlertStatusIcon';
import { InstanceLabel } from '@/components/AppNav/InstanceLabel';
+import { useMobileNavOverlay } from '@/components/AppNav/useMobileNavOverlay';
import { useCompactViewport } from '@/components/CompactViewport/useCompactViewport';
import { APP_VERSION, IS_LOCAL_MODE } from '@/config';
import { Dashboard, useDashboards } from '@/dashboard';
@@ -40,7 +33,6 @@ import { setHdxIdentity } from '@/hdxDebug';
import InstallInstructionModal from '@/InstallInstructionsModal';
import OnboardingChecklist from '@/OnboardingChecklist';
import { useSavedSearches } from '@/savedSearch';
-import { useLogomark, useWordmark } from '@/theme/ThemeProvider';
import { getTimeZoneShortName } from '@/timeZone';
import { useDisplayTimeZone } from '@/useDisplayTimeZone';
import { UserPreferencesModal } from '@/UserPreferencesModal';
@@ -81,6 +73,9 @@ type NavLinkConfig = {
cloudOnly?: boolean; // Only show when not in local mode
};
+const RAIL_WIDTH = 50;
+const FULL_NAV_WIDTH = 250;
+
const NAV_LINKS: NavLinkConfig[] = [
{
id: 'chart',
@@ -192,25 +187,43 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) {
defaultValue: false,
});
- const isCollapsed = useCompactViewport() || isPreferCollapsed;
-
- const navWidth = isCollapsed ? 50 : 250;
-
+ const isCompact = useCompactViewport();
+ const {
+ isOpen: isMobileNavOpen,
+ toggle: toggleMobileNav,
+ close: closeMobileNav,
+ } = useMobileNavOverlay(isCompact);
+ const collapseButtonRef = useRef(null);
+ const wasMobileNavOpenRef = useRef(false);
+ // Traps Tab inside the open overlay so keys do not reach the page under the scrim.
+ const navFocusTrapRef = useFocusTrap(isMobileNavOpen);
+
+ // The toggle stays mounted when the overlay closes, so keyboard focus can
+ // return to it after Escape or the scrim removes itself.
useEffect(() => {
- HyperDX.addAction('user navigated', {
- route: pathname,
- query: JSON.stringify(query),
- });
- }, [pathname, query]);
+ if (wasMobileNavOpenRef.current && !isMobileNavOpen) {
+ collapseButtonRef.current?.focus();
+ }
+ wasMobileNavOpenRef.current = isMobileNavOpen;
+ }, [isMobileNavOpen]);
+
+ // The page layout reserves the rail width even while the overlay is open,
+ // so opening the nav does not shift the content.
+ const isRail = isCompact || isPreferCollapsed;
+ const isCollapsed = isRail && !isMobileNavOpen;
+ const navWidth = isCollapsed ? RAIL_WIDTH : FULL_NAV_WIDTH;
+ const reservedWidth = isRail ? RAIL_WIDTH : FULL_NAV_WIDTH;
+ // The in-flow rail is border-box, so its 1px border is already inside
+ // reservedWidth. The fixed nav's ghost keeps the extra pixel it had
+ // before. The overlay ghost must not, or the page shifts when it opens.
+ const ghostWidth =
+ isMobileNavOpen && !fixed ? reservedWidth : reservedWidth + 1;
useEffect(() => {
if (meData != null) {
- HyperDX.enableAdvancedNetworkCapture();
- HyperDX.setGlobalAttributes({
- userEmail: meData.email,
- userName: meData.name,
- teamName: meData.team.name,
- });
+ setUser({ id: meData.id, email: meData.email, name: meData.name });
+ // Un-namespaced because the Sessions page reads teamName (sessions.ts)
+ setAttributes({ teamName: meData.team.name });
// Fold user/team ids + per-user toggles into window.hdx for debug reports.
setHdxIdentity({
userId: meData.id,
@@ -331,24 +344,35 @@ export default function AppNav({ fixed = false }: { fixed?: boolean }) {
return (
- {fixed && (
+ {(fixed || isMobileNavOpen) && (
)}
+ {isMobileNavOpen && (
+
+ )}
- )}
+ {exceptionValues.map((exception, i) => (
+ 0} />
+ ))}
+ {/* {shouldShowSourceMapFtux && } */}
- {stacktraceHiddenRowsCount ? (
-
- {stacktraceExpanded ? (
- <>
- Hide stack trace
- >
- ) : (
- <>
-
- Show {stacktraceHiddenRowsCount} more frames
- >
- )}
-
- ) : null}
-
+ {firstException?.rawStacktrace && (
+
+
+
+
+
+ )}
{breadcrumbVisibleRows.length > 0 && (
diff --git a/packages/app/src/components/FilterPill/FilterAutocomplete.tsx b/packages/app/src/components/FilterPill/FilterAutocomplete.tsx
index 4a68d8aeb..7a1ee5a42 100644
--- a/packages/app/src/components/FilterPill/FilterAutocomplete.tsx
+++ b/packages/app/src/components/FilterPill/FilterAutocomplete.tsx
@@ -1,5 +1,10 @@
import { Ref } from 'react';
-import { Autocomplete, AutocompleteProps, Loader } from '@mantine/core';
+import {
+ Autocomplete,
+ AutocompleteProps,
+ Loader,
+ OptionsFilter,
+} from '@mantine/core';
/**
* While the user is keyboard-navigating suggestions, Enter must pick the
@@ -12,6 +17,46 @@ const isSuggestionHighlighted = (input: HTMLInputElement) => {
return !!list?.querySelector('[data-combobox-selected]');
};
+/**
+ * 0 when `label` starts with `query`, 1 when one of its parts does, 2 when it
+ * only contains it, and Infinity when it doesn't.
+ */
+const matchRank = (label: string, query: string) => {
+ let rank = Infinity;
+ for (
+ let i = label.indexOf(query);
+ i !== -1;
+ i = label.indexOf(query, i + 1)
+ ) {
+ if (i === 0) return 0;
+ // A part starts after a separator, e.g. the map key in `Map['key']`.
+ rank = Math.min(rank, /[a-z0-9]/.test(label[i - 1]) ? 2 : 1);
+ }
+ return rank;
+};
+
+/**
+ * Case-insensitive matches, best rank first and shorter first within a rank,
+ * so "Serv" lists `ServiceName` above every `LogAttributes['agentToServer…']`.
+ * Ranked before the limit is applied, so the best match can't be cut off.
+ */
+const rankedFilter: OptionsFilter = ({ options, search, limit }) => {
+ const query = search.trim().toLowerCase();
+ if (!query) return options.slice(0, limit);
+ return options
+ .flatMap(option => {
+ if ('group' in option) return [];
+ const rank = matchRank(option.label.toLowerCase(), query);
+ return rank === Infinity ? [] : [{ option, rank }];
+ })
+ .sort(
+ (a, b) =>
+ a.rank - b.rank || a.option.label.length - b.option.label.length,
+ )
+ .slice(0, limit)
+ .map(({ option }) => option);
+};
+
export type FilterAutocompleteProps = {
value: string;
onChange: (value: string) => void;
@@ -26,7 +71,10 @@ export type FilterAutocompleteProps = {
'aria-label'?: string;
'data-testid'?: string;
ref?: Ref;
-} & Pick;
+} & Pick<
+ AutocompleteProps,
+ 'w' | 'size' | 'autoFocus' | 'mb' | 'error' | 'onBlur'
+>;
/** Suggestion input for filter keys and values that also accepts free text. */
export function FilterAutocomplete({
@@ -45,6 +93,7 @@ export function FilterAutocomplete({
{...props}
size={size}
data={options}
+ filter={rankedFilter}
value={value}
onChange={onChange}
onOptionSubmit={onOptionSubmit}
diff --git a/packages/app/src/components/FilterPill/FilterConditionEditor.tsx b/packages/app/src/components/FilterPill/FilterConditionEditor.tsx
index fbee6097c..6d3751a52 100644
--- a/packages/app/src/components/FilterPill/FilterConditionEditor.tsx
+++ b/packages/app/src/components/FilterPill/FilterConditionEditor.tsx
@@ -27,11 +27,19 @@ export type FilterConditionEditorProps = {
keyOptions: string[];
isLoadingKeys?: boolean;
isKeysError?: boolean;
+ /** Why the key suggestions failed, shown after the generic error. */
+ keysErrorMessage?: string;
/** Suggestions for the key last reported by `onKeyChange`. */
valueOptions: string[];
isLoadingValues?: boolean;
isValuesError?: boolean;
- /** The trimmed key, once typing pauses, so the caller can fetch its values. */
+ /** Why the value suggestions failed, shown after the generic error. */
+ valuesErrorMessage?: string;
+ /**
+ * The key to fetch values for: a suggested key once typing pauses, or any key
+ * once committed (Enter, picking it, or leaving the input). Empty while
+ * another key is being typed.
+ */
onKeyChange?: (key: string) => void;
keyLabel?: string;
keyPlaceholder?: string;
@@ -42,6 +50,12 @@ export type FilterConditionEditorProps = {
const KEY_DEBOUNCE_MS = 300;
const SUGGESTIONS_ERROR = "Couldn't load suggestions";
+// Database errors can run to several lines; the first says what went wrong.
+const suggestionsError = (message: string | undefined) => {
+ const firstLine = message?.trim().split('\n')[0];
+ return firstLine ? `${SUGGESTIONS_ERROR}: ${firstLine}` : SUGGESTIONS_ERROR;
+};
+
/** Pick a key, an operator, and a value. Free text is accepted for both inputs. */
export function FilterConditionEditor({
operators,
@@ -49,9 +63,11 @@ export function FilterConditionEditor({
keyOptions,
isLoadingKeys,
isKeysError,
+ keysErrorMessage,
valueOptions,
isLoadingValues,
isValuesError,
+ valuesErrorMessage,
onKeyChange,
keyLabel = 'Key',
keyPlaceholder = 'Select a key',
@@ -67,14 +83,20 @@ export function FilterConditionEditor({
const trimmedKey = key.trim();
const [debouncedKey] = useDebouncedValue(trimmedKey, KEY_DEBOUNCE_MS);
+ const [committedKey, setCommittedKey] = useState(trimmedKey);
+ const commitKey = (next: string) => setCommittedKey(next.trim());
+ // A partial key names no column, so looking it up would only fail.
+ const lookupKey =
+ trimmedKey === committedKey ||
+ (trimmedKey === debouncedKey && keyOptions.includes(trimmedKey))
+ ? trimmedKey
+ : '';
useEffect(() => {
- onKeyChange?.(debouncedKey);
- }, [debouncedKey, onKeyChange]);
+ onKeyChange?.(lookupKey);
+ }, [lookupKey, onKeyChange]);
- // Values shown while the key is still settling belong to the previous key.
- const isValueLoading =
- !!trimmedKey && (!!isLoadingValues || debouncedKey !== trimmedKey);
- const isValuesErrorShown = !!trimmedKey && !isValueLoading && !!isValuesError;
+ const isValueLoading = !!lookupKey && !!isLoadingValues;
+ const isValuesErrorShown = !!lookupKey && !isValueLoading && !!isValuesError;
const selectedOperator = operators.find(op => op.value === operator);
const canSubmit = !!trimmedKey && operator != null;
@@ -90,11 +112,20 @@ export function FilterConditionEditor({
placeholder={keyPlaceholder}
options={keyOptions}
isLoading={isLoadingKeys}
- error={!isLoadingKeys && isKeysError ? SUGGESTIONS_ERROR : undefined}
+ error={
+ !isLoadingKeys && isKeysError
+ ? suggestionsError(keysErrorMessage)
+ : undefined
+ }
value={key}
onChange={setKey}
+ onOptionSubmit={commitKey}
+ onBlur={() => commitKey(key)}
// Enter moves on to the value instead of applying an empty-value filter.
- onSubmit={() => valueInputRef.current?.focus()}
+ onSubmit={() => {
+ commitKey(key);
+ valueInputRef.current?.focus();
+ }}
data-testid={`${testId}-key`}
/>
{serviceName}
+ {dimensionsLabel ? (
+
+ {dimensionsLabel}
+
+ ) : null}
>
);
diff --git a/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx b/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx
index aeb2d0c05..f2bc0fa03 100644
--- a/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx
+++ b/packages/app/src/components/ServiceMap/ServiceMapTooltip.tsx
@@ -1,7 +1,8 @@
import { useCallback } from 'react';
import SqlString from 'sqlstring';
+import { Separator } from '@clickhouse/click-ui';
import { TTraceSource } from '@hyperdx/common-utils/dist/types';
-import { Button, Divider, Group, Stack, Text } from '@mantine/core';
+import { Button, Group, Stack, Text } from '@mantine/core';
import {
IconActivity,
IconClock,
@@ -13,6 +14,11 @@ import {
import { formatDurationMs } from '@/utils';
import {
+ buildServiceMapDimensionsWhere,
+ formatServiceMapDimensions,
+} from './dimensions';
+import {
+ buildServiceMapErrorWhere,
ERROR_RATE_HIGH,
formatApproximateNumber,
formatRate,
@@ -29,6 +35,8 @@ export default function ServiceMapTooltip({
source,
dateRange,
serviceName,
+ dimensions,
+ groupBy,
isSingleTrace,
isFocused,
onFocus,
@@ -42,6 +50,10 @@ export default function ServiceMapTooltip({
source: TTraceSource;
dateRange: [Date, Date];
serviceName: string;
+ // Values of the extra group-by expressions for this node, in groupBy order.
+ dimensions: string[];
+ // The extra group-by SQL expressions, so search links can pin each value.
+ groupBy: string[];
isSingleTrace?: boolean;
// Whether the map is currently scoped to this service (the focus toggle is on)
// — flips the focus CTA to a "clear" action.
@@ -61,33 +73,35 @@ export default function ServiceMapTooltip({
? 'var(--color-text-danger)'
: 'var(--color-chart-warning)';
+ const dimensionsLabel = formatServiceMapDimensions(dimensions);
+ const dimensionsWhere = buildServiceMapDimensionsWhere(groupBy, dimensions);
+
const handleRequestsClick = useCallback(() => {
navigateToTraceSearch({
dateRange,
source,
- where: SqlString.format("? = ? AND ? IN ('Server', 'Consumer')", [
- SqlString.raw(source.serviceNameExpression ?? 'ServiceName'),
- serviceName,
- SqlString.raw(source.spanKindExpression ?? 'SpanKind'),
- ]),
+ where:
+ SqlString.format("? = ? AND ? IN ('Server', 'Consumer')", [
+ SqlString.raw(source.serviceNameExpression ?? 'ServiceName'),
+ serviceName,
+ SqlString.raw(source.spanKindExpression ?? 'SpanKind'),
+ ]) + dimensionsWhere,
});
- }, [dateRange, source, serviceName]);
+ }, [dateRange, source, serviceName, dimensionsWhere]);
const handleErrorsClick = useCallback(() => {
navigateToTraceSearch({
dateRange,
source,
- where: SqlString.format(
- "? = ? AND ? IN ('Server', 'Consumer') AND ? = 'Error'",
- [
- SqlString.raw(source.serviceNameExpression ?? 'ServiceName'),
+ where:
+ buildServiceMapErrorWhere({
+ serviceNameExpression: source.serviceNameExpression ?? 'ServiceName',
serviceName,
- SqlString.raw(source.spanKindExpression ?? 'SpanKind'),
- SqlString.raw(source.statusCodeExpression ?? 'StatusCode'),
- ],
- ),
+ spanKindExpression: source.spanKindExpression ?? 'SpanKind',
+ statusCodeExpression: source.statusCodeExpression ?? 'StatusCode',
+ }) + dimensionsWhere,
});
- }, [dateRange, source, serviceName]);
+ }, [dateRange, source, serviceName, dimensionsWhere]);
const showMetrics =
totalRequests > 0 && (requestsPerSecond != null || latencyMs != null);
@@ -105,7 +119,19 @@ export default function ServiceMapTooltip({
>
{serviceName}
-
+ {dimensionsLabel ? (
+
+ {dimensionsLabel}
+
+ ) : null}
+
-
+ {
+ it('splits on top-level commas only', () => {
+ expect(
+ parseServiceMapGroupBy(
+ "ResourceAttributes['k8s.pod.name'], concat(a, b) ,SpanAttributes['x,y']",
+ ),
+ ).toEqual([
+ "ResourceAttributes['k8s.pod.name']",
+ 'concat(a, b)',
+ "SpanAttributes['x,y']",
+ ]);
+ });
+
+ it('returns an empty list for a missing or blank param', () => {
+ expect(parseServiceMapGroupBy(null)).toEqual([]);
+ expect(parseServiceMapGroupBy(undefined)).toEqual([]);
+ expect(parseServiceMapGroupBy(' ')).toEqual([]);
+ });
+
+ it('caps a hand-edited URL at three expressions', () => {
+ expect(parseServiceMapGroupBy('a, b, c, d, e')).toEqual(['a', 'b', 'c']);
+ });
+});
+
+describe('formatServiceMapDimensions', () => {
+ it('is undefined without dimensions so nodes keep a single label line', () => {
+ expect(formatServiceMapDimensions([])).toBeUndefined();
+ });
+
+ it('joins values and names an empty value explicitly', () => {
+ expect(formatServiceMapDimensions(['api-pod-0', '', '/users'])).toBe(
+ 'api-pod-0 · (none) · /users',
+ );
+ });
+});
+
+describe('buildServiceMapDimensionsWhere', () => {
+ it('is empty without dimensions', () => {
+ expect(buildServiceMapDimensionsWhere([], [])).toBe('');
+ });
+
+ it('pins each expression, normalized like the map query, to its escaped value', () => {
+ expect(
+ buildServiceMapDimensionsWhere(
+ ["ResourceAttributes['k8s.pod.name']", "SpanAttributes['http.route']"],
+ ['api-pod-0', "/users/'quoted'"],
+ ),
+ ).toBe(
+ " AND ifNull(toString(ResourceAttributes['k8s.pod.name']), '') = 'api-pod-0' AND ifNull(toString(SpanAttributes['http.route']), '') = '/users/\\'quoted\\''",
+ );
+ });
+
+ it('matches an empty value literally and keeps operator expressions grouped', () => {
+ expect(buildServiceMapDimensionsWhere(['a OR b'], [''])).toBe(
+ " AND ifNull(toString(a OR b), '') = ''",
+ );
+ });
+});
diff --git a/packages/app/src/components/ServiceMap/__tests__/useServiceMapSizeGate.test.ts b/packages/app/src/components/ServiceMap/__tests__/useServiceMapSizeGate.test.ts
new file mode 100644
index 000000000..45a35ca57
--- /dev/null
+++ b/packages/app/src/components/ServiceMap/__tests__/useServiceMapSizeGate.test.ts
@@ -0,0 +1,57 @@
+import { act, renderHook } from '@testing-library/react';
+
+import { useServiceMapSizeGate } from '@/components/ServiceMap/useServiceMapSizeGate';
+import { MAX_SERVICE_MAP_NODES } from '@/components/ServiceMap/utils';
+import type { ServiceAggregation } from '@/hooks/useServiceMap';
+
+function servicesOfSize(size: number): Map {
+ const services = new Map();
+ for (let i = 0; i < size; i++) {
+ services.set(`svc-${i}`, {
+ key: `svc-${i}`,
+ serviceName: `svc-${i}`,
+ dimensions: [],
+ incomingRequests: {
+ totalRequests: 1,
+ errorCount: 0,
+ errorPercentage: 0,
+ p50: 0,
+ p95: 0,
+ p99: 0,
+ hasLatency: false,
+ },
+ incomingRequestsByClient: new Map(),
+ outgoingRequests: 0,
+ });
+ }
+ return services;
+}
+
+describe('useServiceMapSizeGate', () => {
+ it('does not gate a map at the limit', () => {
+ const { result } = renderHook(() =>
+ useServiceMapSizeGate(servicesOfSize(MAX_SERVICE_MAP_NODES)),
+ );
+ expect(result.current.tooLarge).toBe(false);
+ });
+
+ it('gates an oversized map until Show anyway, then gates the next result again', () => {
+ const first = servicesOfSize(MAX_SERVICE_MAP_NODES + 1);
+ const { result, rerender } = renderHook(
+ ({ services }) => useServiceMapSizeGate(services),
+ { initialProps: { services: first } },
+ );
+ expect(result.current.tooLarge).toBe(true);
+
+ act(() => result.current.showAnyway());
+ expect(result.current.tooLarge).toBe(false);
+
+ // Same result set re-rendered: still shown.
+ rerender({ services: first });
+ expect(result.current.tooLarge).toBe(false);
+
+ // A new query result of the same size is held back again.
+ rerender({ services: servicesOfSize(MAX_SERVICE_MAP_NODES + 1) });
+ expect(result.current.tooLarge).toBe(true);
+ });
+});
diff --git a/packages/app/src/components/ServiceMap/__tests__/utils.test.ts b/packages/app/src/components/ServiceMap/__tests__/utils.test.ts
index 134f59dde..2523fb7ed 100644
--- a/packages/app/src/components/ServiceMap/__tests__/utils.test.ts
+++ b/packages/app/src/components/ServiceMap/__tests__/utils.test.ts
@@ -2,6 +2,7 @@ import router from 'next/router';
import { SourceKind, TTraceSource } from '@hyperdx/common-utils/dist/types';
import {
+ buildServiceMapErrorWhere,
deriveDisplayMetrics,
ERROR_RATE_HIGH,
formatApproximateNumber,
@@ -11,6 +12,8 @@ import {
getNodeSize,
getRequestsPerSecond,
getServiceMetricValue,
+ isServiceMapTooLarge,
+ MAX_SERVICE_MAP_NODES,
navigateToTraceSearch,
rawDurationToMs,
SERVICE_MAP_METRIC_HUE,
@@ -25,6 +28,21 @@ jest.mock('next/router', () => ({
},
}));
+describe('buildServiceMapErrorWhere', () => {
+ it('includes legacy STATUS_CODE_ERROR spans in the error drill-down', () => {
+ expect(
+ buildServiceMapErrorWhere({
+ serviceNameExpression: 'ServiceName',
+ serviceName: 'api',
+ spanKindExpression: 'SpanKind',
+ statusCodeExpression: 'StatusCode',
+ }),
+ ).toBe(
+ "ServiceName = 'api' AND SpanKind IN ('Server', 'Consumer') AND lower(StatusCode) IN ('error', 'status_code_error')",
+ );
+ });
+});
+
describe('navigateToTraceSearch', () => {
const mockSource: TTraceSource = {
id: 'test-source-id',
@@ -479,7 +497,9 @@ describe('getServiceMetricValue', () => {
overrides: Partial = {},
outgoingRequests = 0,
): ServiceAggregation => ({
+ key: 'svc',
serviceName: 'svc',
+ dimensions: [],
incomingRequests: {
totalRequests: 100,
errorCount: 5,
@@ -677,3 +697,14 @@ describe('deriveDisplayMetrics', () => {
expect(m.latencyMs).toBeDefined();
});
});
+
+describe('isServiceMapTooLarge', () => {
+ it('gates only maps above the node limit', () => {
+ expect(isServiceMapTooLarge(MAX_SERVICE_MAP_NODES, false)).toBe(false);
+ expect(isServiceMapTooLarge(MAX_SERVICE_MAP_NODES + 1, false)).toBe(true);
+ });
+
+ it('is lifted by "Show anyway"', () => {
+ expect(isServiceMapTooLarge(MAX_SERVICE_MAP_NODES + 1, true)).toBe(false);
+ });
+});
diff --git a/packages/app/src/components/ServiceMap/dimensions.ts b/packages/app/src/components/ServiceMap/dimensions.ts
new file mode 100644
index 000000000..c88b753a9
--- /dev/null
+++ b/packages/app/src/components/ServiceMap/dimensions.ts
@@ -0,0 +1,52 @@
+import SqlString from 'sqlstring';
+import { splitAndTrimWithBracket } from '@hyperdx/common-utils/dist/core/utils';
+
+import {
+ dimensionValueSql,
+ MAX_SERVICE_MAP_GROUP_BY,
+} from '@/hooks/useServiceMap';
+
+const EMPTY_DIMENSION_LABEL = '(none)';
+
+/**
+ * Splits the comma-separated group-by URL param into SQL expressions, capped
+ * at MAX_SERVICE_MAP_GROUP_BY so a hand-edited URL cannot exceed the limit.
+ */
+export function parseServiceMapGroupBy(groupBy: string | null | undefined) {
+ return splitAndTrimWithBracket(groupBy ?? '').slice(
+ 0,
+ MAX_SERVICE_MAP_GROUP_BY,
+ );
+}
+
+/** The second label line of a node: dimension values joined by " · ". */
+export function formatServiceMapDimensions(
+ dimensions: string[],
+): string | undefined {
+ if (dimensions.length === 0) {
+ return undefined;
+ }
+ return dimensions
+ .map(value => (value === '' ? EMPTY_DIMENSION_LABEL : value))
+ .join(' · ');
+}
+
+/**
+ * SQL fragment, starting with " AND ", that pins a search to one node's
+ * dimension values. Each expression is normalized exactly like the map query
+ * does, so array, numeric and NULL values match the node they were grouped
+ * under. Empty when the map has no extra dimensions.
+ */
+export function buildServiceMapDimensionsWhere(
+ groupBy: string[],
+ dimensions: string[],
+): string {
+ return groupBy
+ .map((expression, i) =>
+ SqlString.format(' AND ? = ?', [
+ SqlString.raw(dimensionValueSql(expression)),
+ dimensions[i] ?? '',
+ ]),
+ )
+ .join('');
+}
diff --git a/packages/app/src/components/ServiceMap/useServiceMapSizeGate.ts b/packages/app/src/components/ServiceMap/useServiceMapSizeGate.ts
new file mode 100644
index 000000000..b515e9876
--- /dev/null
+++ b/packages/app/src/components/ServiceMap/useServiceMapSizeGate.ts
@@ -0,0 +1,22 @@
+import { useState } from 'react';
+
+import type { ServiceAggregation } from '@/hooks/useServiceMap';
+
+import { isServiceMapTooLarge } from './utils';
+
+type Services = Map | undefined;
+
+/**
+ * Holds an oversized map behind "Show anyway". The override is keyed by the
+ * result set's identity, so the next query result is gated again.
+ */
+export function useServiceMapSizeGate(services: Services) {
+ const [shownAnyway, setShownAnyway] = useState();
+ return {
+ tooLarge: isServiceMapTooLarge(
+ services?.size ?? 0,
+ services !== undefined && shownAnyway === services,
+ ),
+ showAnyway: () => setShownAnyway(services),
+ };
+}
diff --git a/packages/app/src/components/ServiceMap/utils.ts b/packages/app/src/components/ServiceMap/utils.ts
index bf898574d..9f7c70fd2 100644
--- a/packages/app/src/components/ServiceMap/utils.ts
+++ b/packages/app/src/components/ServiceMap/utils.ts
@@ -1,8 +1,32 @@
import router from 'next/router';
+import SqlString from 'sqlstring';
+import { errorStatusPredicateSql } from '@hyperdx/common-utils/dist/core/spanPredicates';
import { TTraceSource } from '@hyperdx/common-utils/dist/types';
import type { ServiceAggregation } from '@/hooks/useServiceMap';
+export function buildServiceMapErrorWhere({
+ serviceNameExpression,
+ serviceName,
+ spanKindExpression,
+ statusCodeExpression,
+}: {
+ serviceNameExpression: string;
+ serviceName: string;
+ spanKindExpression: string;
+ statusCodeExpression: string;
+}): string {
+ return SqlString.format(
+ `? = ? AND ? IN ('Server', 'Consumer') AND ${errorStatusPredicateSql('?')}`,
+ [
+ SqlString.raw(serviceNameExpression),
+ serviceName,
+ SqlString.raw(spanKindExpression),
+ SqlString.raw(statusCodeExpression),
+ ],
+ );
+}
+
export function navigateToTraceSearch({
dateRange,
source,
@@ -283,6 +307,21 @@ export function formatRate(perSecond: number): string {
return `${perSecond.toFixed(2)} req/s`;
}
+/**
+ * Largest map rendered without asking. Past this the dagre layout and React
+ * Flow render are what lock the tab, and a high-cardinality group-by (a URL,
+ * a trace id) can produce thousands of nodes from one keystroke.
+ */
+export const MAX_SERVICE_MAP_NODES = 100;
+
+/** Whether a map of `nodeCount` nodes is held back behind "Show anyway". */
+export function isServiceMapTooLarge(
+ nodeCount: number,
+ showAnyway: boolean,
+): boolean {
+ return !showAnyway && nodeCount > MAX_SERVICE_MAP_NODES;
+}
+
const MIN_NODE_SIZE = 32;
const MAX_NODE_SIZE = 60;
diff --git a/packages/app/src/components/Sources/SourceForm/LogTableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/LogTableModelForm.tsx
index 52d918fb9..b936c352f 100644
--- a/packages/app/src/components/Sources/SourceForm/LogTableModelForm.tsx
+++ b/packages/app/src/components/Sources/SourceForm/LogTableModelForm.tsx
@@ -1,13 +1,14 @@
import { useState } from 'react';
import { useWatch } from 'react-hook-form';
+import { Separator } from '@clickhouse/click-ui';
import { SourceKind } from '@hyperdx/common-utils/dist/types';
-import { Anchor, Box, Button, Divider, Group, Stack } from '@mantine/core';
+import { Anchor, Box, Button, Group, Stack } from '@mantine/core';
import { IconSettings } from '@tabler/icons-react';
+import { useBrandDisplayName } from '@/brand';
import { SourceSelectControlled } from '@/components/SourceSelect';
import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor';
import { useColumns } from '@/hooks/useMetadata';
-import { useBrandDisplayName } from '@/theme/ThemeProvider';
import {
DEFAULT_DATABASE,
@@ -110,7 +111,7 @@ export function LogTableModelForm(props: TableModelProps) {
display: showOptionalFields ? 'flex' : 'none',
}}
>
-
+
-
+
-
+
{/*
-
+
-
+
-
+
-
+
-
+
);
}
diff --git a/packages/app/src/components/Sources/SourceForm/MetricTableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/MetricTableModelForm.tsx
index 4b56d35b5..39cac1e7e 100644
--- a/packages/app/src/components/Sources/SourceForm/MetricTableModelForm.tsx
+++ b/packages/app/src/components/Sources/SourceForm/MetricTableModelForm.tsx
@@ -5,13 +5,13 @@ import { Stack, Text } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import api from '@/api';
+import { useBrandDisplayName } from '@/brand';
import { useTablesDirect } from '@/clickhouse';
import { DBTableSelectControlled } from '@/components/DBTableSelect';
import { SourceSelectControlled } from '@/components/SourceSelect';
import { useMetadataWithSettings } from '@/hooks/useMetadata';
import { useMetricsSeriesTableAvailability } from '@/hooks/useMetricsSeriesTableAvailability';
import { isValidMetricTable, useSource } from '@/source';
-import { useBrandDisplayName } from '@/theme/ThemeProvider';
import {
matchMetricTables,
matchSeriesTable,
diff --git a/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx
index 2f228c458..07f909843 100644
--- a/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx
+++ b/packages/app/src/components/Sources/SourceForm/PromqlTableModelForm.tsx
@@ -1,24 +1,51 @@
import { useEffect } from 'react';
+import { Stack } from '@mantine/core';
+import SelectControlled from '@/components/SelectControlled';
import { PROMQL_TIMESTAMP_EXPRESSION } from '@/source';
+import { PROMQL_BACKEND_OPTIONS } from './constants';
+import { FormRow } from './FormRow';
import { MinAutoGranularityFormRow } from './MinAutoGranularityFormRow';
import { TableModelProps } from './types';
const PROMQL_MIN_AUTO_GRANULARITY_HELP_TEXT =
"Floor for 'auto granularity' on charts querying this source. Set this to your metrics' scrape interval to avoid sparse-looking charts on short time ranges. Doesn't affect an explicitly chosen (non-auto) granularity. $__rate_interval is also sized from it, assuming a 15 second scrape interval when no minimum is set.";
-export function PromqlTableModelForm({ control, setValue }: TableModelProps) {
+const PROMQL_BACKEND_HELP_TEXT =
+ 'How ClickHouse evaluates queries on this source. Auto uses the Prometheus HTTP API when the server serves it (ClickHouse 26.6+ with the prometheus_api_v1 handler configured) and the prometheusQuery table functions otherwise, and re-checks every few minutes. Pick one to skip that check.';
+
+export function PromqlTableModelForm({
+ control,
+ setValue,
+ isPrometheusEndpoint,
+}: TableModelProps) {
useEffect(() => {
- setValue('timestampValueExpression' as any, PROMQL_TIMESTAMP_EXPRESSION);
+ setValue('timestampValueExpression', PROMQL_TIMESTAMP_EXPRESSION);
}, [setValue]);
// PromQL sources use the standard database + table fields from BaseSourceSchema.
// The table should point to the TimeSeries engine table.
return (
-
+
+ {/* A Prometheus endpoint is always queried through its own API. */}
+ {!isPrometheusEndpoint && (
+
+
+
+ )}
+
+
);
}
diff --git a/packages/app/src/components/Sources/SourceForm/SessionTableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/SessionTableModelForm.tsx
index ba320d2a3..629b86b02 100644
--- a/packages/app/src/components/Sources/SourceForm/SessionTableModelForm.tsx
+++ b/packages/app/src/components/Sources/SourceForm/SessionTableModelForm.tsx
@@ -3,11 +3,11 @@ import { useWatch } from 'react-hook-form';
import { Stack } from '@mantine/core';
import { notifications } from '@mantine/notifications';
+import { useBrandDisplayName } from '@/brand';
import { SourceSelectControlled } from '@/components/SourceSelect';
import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor';
import { useMetadataWithSettings } from '@/hooks/useMetadata';
import { isValidSessionsTable } from '@/source';
-import { useBrandDisplayName } from '@/theme/ThemeProvider';
import { DEFAULT_DATABASE } from './constants';
import { FormRow } from './FormRow';
diff --git a/packages/app/src/components/Sources/SourceForm/SourceForm.tsx b/packages/app/src/components/Sources/SourceForm/SourceForm.tsx
index f3d9f5e79..329a8d54e 100644
--- a/packages/app/src/components/Sources/SourceForm/SourceForm.tsx
+++ b/packages/app/src/components/Sources/SourceForm/SourceForm.tsx
@@ -734,7 +734,7 @@ export function TableSourceForm({
variant="secondary"
size="sm"
color="gray"
- mt="md"
+ mt={querySettingFields.length ? 'md' : 0}
disabled={querySettingFields.length >= 10}
onClick={() => {
if (querySettingFields.length < 10) {
@@ -752,6 +752,7 @@ export function TableSourceForm({
setValue={setValue}
kind={kind}
sourceId={sourceId}
+ isPrometheusEndpoint={isPrometheusOnlyConnection}
/>
{onCancel && (
diff --git a/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx
index 4fb5c6d46..e36b98140 100644
--- a/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx
+++ b/packages/app/src/components/Sources/SourceForm/TableModelForm.tsx
@@ -19,11 +19,13 @@ export function TableModelForm({
setValue,
kind,
sourceId,
+ isPrometheusEndpoint,
}: {
control: Control;
setValue: UseFormSetValue;
kind: SourceKind;
sourceId?: string;
+ isPrometheusEndpoint?: boolean;
}) {
switch (kind) {
case SourceKind.Log:
@@ -41,6 +43,12 @@ export function TableModelForm({
/>
);
case SourceKind.Promql:
- return ;
+ return (
+
+ );
}
}
diff --git a/packages/app/src/components/Sources/SourceForm/TraceTableModelForm.tsx b/packages/app/src/components/Sources/SourceForm/TraceTableModelForm.tsx
index 38c2fcaed..47265e50e 100644
--- a/packages/app/src/components/Sources/SourceForm/TraceTableModelForm.tsx
+++ b/packages/app/src/components/Sources/SourceForm/TraceTableModelForm.tsx
@@ -1,11 +1,12 @@
import { Controller, useWatch } from 'react-hook-form';
+import { Separator } from '@clickhouse/click-ui';
import { SourceKind } from '@hyperdx/common-utils/dist/types';
-import { Box, Divider, Slider, Stack } from '@mantine/core';
+import { Box, Slider, Stack } from '@mantine/core';
+import { useBrandDisplayName } from '@/brand';
import { SourceSelectControlled } from '@/components/SourceSelect';
import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor';
import { useColumns } from '@/hooks/useMetadata';
-import { useBrandDisplayName } from '@/theme/ThemeProvider';
import {
DEFAULT_DATABASE,
@@ -74,7 +75,7 @@ export function TraceTableModelForm(props: TableModelProps) {
placeholder="Timestamp, ServiceName, StatusCode, Duration, SpanName"
/>
-
+
-
+
-
+
-
+
-
+
-
+ option.value !== '1 second'),
];
+export const PROMQL_BACKEND_OPTIONS: {
+ value: PromqlSourceBackend;
+ label: string;
+}[] = [
+ { value: 'auto', label: 'Auto (detect from server)' },
+ { value: 'clickhouse-http', label: 'Prometheus HTTP API' },
+ { value: 'table-function', label: 'Table functions' },
+];
+
export const USE_TEXT_INDEX_OPTIONS = [
{
value: UseTextIndex.Auto,
diff --git a/packages/app/src/components/Sources/SourceForm/types.ts b/packages/app/src/components/Sources/SourceForm/types.ts
index 4e46912c1..e47f4c8ea 100644
--- a/packages/app/src/components/Sources/SourceForm/types.ts
+++ b/packages/app/src/components/Sources/SourceForm/types.ts
@@ -6,4 +6,6 @@ export interface TableModelProps {
setValue: UseFormSetValue;
// Set when editing an existing source
sourceId?: string;
+ // The selected connection is a Prometheus-compatible endpoint, not ClickHouse
+ isPrometheusEndpoint?: boolean;
}
diff --git a/packages/app/src/components/Sources/SourcesList.tsx b/packages/app/src/components/Sources/SourcesList.tsx
index 4a981f189..89fe1a635 100644
--- a/packages/app/src/components/Sources/SourcesList.tsx
+++ b/packages/app/src/components/Sources/SourcesList.tsx
@@ -1,6 +1,6 @@
import React, { useEffect, useRef, useState } from 'react';
import { useRouter } from 'next/router';
-import { Badge } from '@clickhouse/click-ui';
+import { Badge, Separator } from '@clickhouse/click-ui';
import { SourceKind } from '@hyperdx/common-utils/dist/types';
import {
ActionIcon,
@@ -8,7 +8,6 @@ import {
Box,
Button,
Card,
- Divider,
Flex,
Group,
Loader,
@@ -257,13 +256,13 @@ export function SourcesList({
/>
)}
- {index < (sources?.length ?? 0) - 1 && }
+ {index < (sources?.length ?? 0) - 1 && }
))}
{isCreatingSource && (
<>
- {sources && sources.length > 0 && }
+ {sources && sources.length > 0 && }
setIsCreatingSource(false)}
diff --git a/packages/app/src/components/TeamSettings/ApiKeysSection.tsx b/packages/app/src/components/TeamSettings/ApiKeysSection.tsx
index 03f4d9b29..8348622a9 100644
--- a/packages/app/src/components/TeamSettings/ApiKeysSection.tsx
+++ b/packages/app/src/components/TeamSettings/ApiKeysSection.tsx
@@ -1,4 +1,5 @@
-import { Box, Button, Card, Divider, Group, Text } from '@mantine/core';
+import { Separator } from '@clickhouse/click-ui';
+import { Box, Button, Card, Group, Text } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import api from '@/api';
@@ -109,7 +110,7 @@ export default function ApiKeysSection() {
return (
API keys
-
+ Ingestion API key
diff --git a/packages/app/src/components/TeamSettings/ConnectionsSection.tsx b/packages/app/src/components/TeamSettings/ConnectionsSection.tsx
index c336d7c59..5c6d7db9d 100644
--- a/packages/app/src/components/TeamSettings/ConnectionsSection.tsx
+++ b/packages/app/src/components/TeamSettings/ConnectionsSection.tsx
@@ -1,5 +1,6 @@
import { useState } from 'react';
-import { Box, Button, Card, Divider, Flex, Stack, Text } from '@mantine/core';
+import { Separator } from '@clickhouse/click-ui';
+import { Box, Button, Card, Flex, Stack, Text } from '@mantine/core';
import { IconPencil, IconX } from '@tabler/icons-react';
import { ConnectionForm } from '@/components/ConnectionForm';
@@ -16,7 +17,7 @@ export default function ConnectionsSection() {
return (
Connections
-
+
{connections?.map(connection => (
@@ -65,7 +66,7 @@ export default function ConnectionsSection() {
showDeleteButton
/>
)}
-
+
))}
diff --git a/packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx b/packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx
new file mode 100644
index 000000000..a5795172e
--- /dev/null
+++ b/packages/app/src/components/TeamSettings/CreateOrgApiKeyModal.tsx
@@ -0,0 +1,135 @@
+import { useState } from 'react';
+import {
+ type OrgApiKeyExpiry,
+ OrgApiKeyExpirySchema,
+} from '@hyperdx/common-utils/dist/types';
+import {
+ Button,
+ Group,
+ Modal,
+ SegmentedControl,
+ Stack,
+ Text,
+ TextInput,
+} from '@mantine/core';
+import { notifications } from '@mantine/notifications';
+
+import api from '@/api';
+import { RevealSnippet } from '@/components/RevealSnippet/RevealSnippet';
+
+const EXPIRY_OPTIONS = [
+ { value: '30d', label: '30 days' },
+ { value: '1y', label: '1 year' },
+ { value: 'never', label: 'Never' },
+];
+
+export default function CreateOrgApiKeyModal({
+ opened,
+ onClose,
+}: {
+ opened: boolean;
+ onClose: () => void;
+}) {
+ const createKey = api.useCreateOrgApiKey();
+ const [description, setDescription] = useState('');
+ const [expiry, setExpiry] = useState('30d');
+ const [createdKey, setCreatedKey] = useState(null);
+
+ // Closing mid-request would let the late response reopen on the old key.
+ const close = () => {
+ if (createKey.isPending) {
+ return;
+ }
+ setDescription('');
+ setExpiry('30d');
+ setCreatedKey(null);
+ onClose();
+ };
+
+ const onCreate = () => {
+ createKey.mutate(
+ { description: description.trim(), expiry },
+ {
+ onSuccess: data => setCreatedKey(data.key),
+ onError: e => {
+ notifications.show({
+ color: 'red',
+ message: e.message,
+ autoClose: 5000,
+ });
+ },
+ },
+ );
+ };
+
+ return (
+
+ {createdKey != null ? (
+
+
+ Copy this key now. You won't be able to see it again.
+
+
+
+
+
+
+ Done
+
+
+
+ ) : (
+
+ setDescription(e.currentTarget.value)}
+ data-autofocus
+ />
+
+
+ Expires
+
+ setExpiry(OrgApiKeyExpirySchema.parse(value))}
+ />
+
+
+
+ Cancel
+
+
+ Create
+
+
+
+ )}
+
+ );
+}
diff --git a/packages/app/src/components/TeamSettings/IacMigrationSection.tsx b/packages/app/src/components/TeamSettings/IacMigrationSection.tsx
index 9b10138bc..57ffb400a 100644
--- a/packages/app/src/components/TeamSettings/IacMigrationSection.tsx
+++ b/packages/app/src/components/TeamSettings/IacMigrationSection.tsx
@@ -1,5 +1,5 @@
import { useMemo, useState } from 'react';
-import { Badge } from '@clickhouse/click-ui';
+import { Badge, Separator } from '@clickhouse/click-ui';
import {
buildImportFile,
collectImportableResources,
@@ -14,7 +14,6 @@ import {
Button,
Card,
Checkbox,
- Divider,
Group,
Stack,
Text,
@@ -233,7 +232,7 @@ export default function IacMigrationSection({
Export to Terraform
-
+
Download a Terraform import file for this team's resources. Add
diff --git a/packages/app/src/components/TeamSettings/IntegrationsSection.tsx b/packages/app/src/components/TeamSettings/IntegrationsSection.tsx
index e5156da36..8a64c0497 100644
--- a/packages/app/src/components/TeamSettings/IntegrationsSection.tsx
+++ b/packages/app/src/components/TeamSettings/IntegrationsSection.tsx
@@ -1,4 +1,5 @@
-import { Box, Card, Divider, Stack, Text } from '@mantine/core';
+import { Separator } from '@clickhouse/click-ui';
+import { Box, Card, Stack, Text } from '@mantine/core';
import WebhooksSection from './WebhooksSection';
@@ -6,7 +7,7 @@ export default function IntegrationsSection() {
return (
Integrations
-
+
diff --git a/packages/app/src/components/TeamSettings/McpServerSection.tsx b/packages/app/src/components/TeamSettings/McpServerSection.tsx
index cda125130..741f83908 100644
--- a/packages/app/src/components/TeamSettings/McpServerSection.tsx
+++ b/packages/app/src/components/TeamSettings/McpServerSection.tsx
@@ -1,5 +1,6 @@
import { useMemo } from 'react';
-import { Box, Card, Divider, Text } from '@mantine/core';
+import { Separator } from '@clickhouse/click-ui';
+import { Box, Card, Text } from '@mantine/core';
import api from '@/api';
import { type DeploymentShape } from '@/components/ClickStackOnboarding/installSnippets';
@@ -15,7 +16,7 @@ import McpInstallPanel from '@/components/ClickStackOnboarding/McpInstallPanel';
*
* Structure mirrors `IntegrationsSection.tsx` and
* `ApiKeysSection.tsx`: outer `` with a ``
- * header and ``, then a single `` wrapping the
+ * header and ``, then a single `` wrapping the
* install panel. No subtitle below the header so the visual
* rhythm matches the rest of the Integrations tab.
*
@@ -45,7 +46,7 @@ export default function McpServerSection() {
return (
Connect your AI Agents
-
+
diff --git a/packages/app/src/components/TeamSettings/OrgApiKeysSection.tsx b/packages/app/src/components/TeamSettings/OrgApiKeysSection.tsx
new file mode 100644
index 000000000..1cfa80b43
--- /dev/null
+++ b/packages/app/src/components/TeamSettings/OrgApiKeysSection.tsx
@@ -0,0 +1,164 @@
+import { useEffect, useState } from 'react';
+import { Badge, Separator } from '@clickhouse/click-ui';
+import type { OrgApiKeyApiResponse } from '@hyperdx/common-utils/dist/types';
+import { Box, Button, Card, Group, Table, Text } from '@mantine/core';
+import { notifications } from '@mantine/notifications';
+
+import api from '@/api';
+import EmptyState from '@/components/EmptyState';
+import { InlineNameInput } from '@/components/InlineNameInput/InlineNameInput';
+import { currentDate } from '@/timeZone';
+import { useConfirm } from '@/useConfirm';
+import { useFormatTime } from '@/useFormatTime';
+
+import CreateOrgApiKeyModal from './CreateOrgApiKeyModal';
+
+// A minute tick is close enough for flipping the Expired badge.
+const EXPIRY_TICK_MS = 60_000;
+
+// Only read in a state initialiser and the interval, never during render.
+const currentTime = () => currentDate().getTime();
+
+function useNow() {
+ const [now, setNow] = useState(currentTime);
+ useEffect(() => {
+ const id = window.setInterval(() => setNow(currentTime()), EXPIRY_TICK_MS);
+ return () => window.clearInterval(id);
+ }, []);
+ return now;
+}
+
+function OrgApiKeyRow({
+ apiKey,
+ now,
+}: {
+ apiKey: OrgApiKeyApiResponse;
+ now: number;
+}) {
+ const updateKey = api.useUpdateOrgApiKey();
+ const deleteKey = api.useDeleteOrgApiKey();
+ const confirm = useConfirm();
+ const formatTime = useFormatTime();
+ const formatDate = (iso: string) => formatTime(iso, { format: 'withYear' });
+ const isExpired =
+ apiKey.expiresAt != null && Date.parse(apiKey.expiresAt) <= now;
+
+ const onRevoke = async () => {
+ const confirmed = await confirm(
+ "Revoking this key immediately breaks anything still using it. This can't be undone.",
+ 'Revoke',
+ { variant: 'danger' },
+ );
+ if (!confirmed) {
+ return;
+ }
+ deleteKey.mutate(
+ { id: apiKey.id },
+ {
+ onError: e => notifications.show({ color: 'red', message: e.message }),
+ },
+ );
+ };
+
+ return (
+
+
+
+ updateKey.mutateAsync({ id: apiKey.id, description }).catch(e => {
+ notifications.show({
+ color: 'red',
+ message: `Couldn't rename API key: ${e.message}`,
+ });
+ throw e;
+ })
+ }
+ />
+
+
+ {apiKey.createdBy
+ ? apiKey.createdBy.name || apiKey.createdBy.email
+ : 'Deleted user'}
+
+ {formatDate(apiKey.createdAt)}
+
+ {apiKey.lastUsedAt ? formatDate(apiKey.lastUsedAt) : 'Never'}
+
+
+ {isExpired ? (
+
+ ) : apiKey.expiresAt ? (
+ formatDate(apiKey.expiresAt)
+ ) : (
+ 'Never'
+ )}
+
+
+
+ Revoke
+
+
+
+ );
+}
+
+export default function OrgApiKeysSection() {
+ const { data, isLoading, isError } = api.useOrgApiKeys();
+ const now = useNow();
+ const [isCreateOpen, setIsCreateOpen] = useState(false);
+ const keys = data?.data ?? [];
+
+ return (
+
+
+
+ Organization API keys
+
+ Keys owned by the team. They keep working when the person who
+ created them leaves.
+
+
+ setIsCreateOpen(true)}>
+ Create API key
+
+
+
+ {isError ? (
+
+ Couldn't load organization API keys
+
+ ) : !isLoading && keys.length === 0 ? (
+
+ ) : (
+
+
+
+
+ Description
+ Created by
+ Created
+ Last used
+ Expires
+
+
+
+
+ {keys.map(apiKey => (
+
+ ))}
+
+
+
+ )}
+ setIsCreateOpen(false)}
+ />
+
+ );
+}
diff --git a/packages/app/src/components/TeamSettings/SecurityPoliciesSection.tsx b/packages/app/src/components/TeamSettings/SecurityPoliciesSection.tsx
index d3a22727d..7fa77a3be 100644
--- a/packages/app/src/components/TeamSettings/SecurityPoliciesSection.tsx
+++ b/packages/app/src/components/TeamSettings/SecurityPoliciesSection.tsx
@@ -1,4 +1,5 @@
-import { Box, Card, Divider, Text } from '@mantine/core';
+import { Separator } from '@clickhouse/click-ui';
+import { Box, Card, Text } from '@mantine/core';
export default function SecurityPoliciesSection({
allowedAuthMethods,
@@ -8,7 +9,7 @@ export default function SecurityPoliciesSection({
return (
Security Policies
-
+
Team members can only authenticate via{' '}
diff --git a/packages/app/src/components/TeamSettings/SourcesSection.tsx b/packages/app/src/components/TeamSettings/SourcesSection.tsx
index 4e4ca3701..a7e7fdc25 100644
--- a/packages/app/src/components/TeamSettings/SourcesSection.tsx
+++ b/packages/app/src/components/TeamSettings/SourcesSection.tsx
@@ -1,4 +1,5 @@
-import { Box, Divider, Text } from '@mantine/core';
+import { Separator } from '@clickhouse/click-ui';
+import { Box, Text } from '@mantine/core';
import { SourcesList } from '@/components/Sources/SourcesList';
@@ -6,7 +7,7 @@ export default function SourcesSection() {
return (
Sources
-
+ Team Members
-
+
diff --git a/packages/app/src/components/TeamSettings/TeamQueryConfigSection.tsx b/packages/app/src/components/TeamSettings/TeamQueryConfigSection.tsx
index bebf127d3..e271ec8fd 100644
--- a/packages/app/src/components/TeamSettings/TeamQueryConfigSection.tsx
+++ b/packages/app/src/components/TeamSettings/TeamQueryConfigSection.tsx
@@ -1,12 +1,12 @@
import { useCallback, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
+import { Separator } from '@clickhouse/click-ui';
import { DEFAULT_METADATA_MAX_ROWS_TO_READ } from '@hyperdx/common-utils/dist/core/metadata';
import { type TeamClickHouseSettings } from '@hyperdx/common-utils/dist/types';
import {
Box,
Button,
Card,
- Divider,
Group,
InputLabel,
Stack,
@@ -18,13 +18,13 @@ import { notifications } from '@mantine/notifications';
import { IconHelpCircle, IconPencil } from '@tabler/icons-react';
import api from '@/api';
+import { useBrandDisplayName } from '@/brand';
import SelectControlled from '@/components/SelectControlled';
import {
DEFAULT_FILTER_KEYS_FETCH_LIMIT,
DEFAULT_QUERY_TIMEOUT,
DEFAULT_SEARCH_ROW_LIMIT,
} from '@/defaults';
-import { useBrandDisplayName } from '@/theme/ThemeProvider';
type ClickhouseSettingType = 'number' | 'boolean';
@@ -282,7 +282,7 @@ export default function TeamQueryConfigSection() {
return (
ClickHouse Client Settings
-
+ = async values => {
- const { service, name, url, description, body, headers } = values;
+ const { service, name, url, description, titleEmoji, body, headers } =
+ values;
try {
// Parse headers JSON if provided (API will validate the content)
@@ -247,6 +252,7 @@ export function WebhookForm({
name,
url,
description: description || '',
+ titleEmoji,
body: defaultBody,
headers: parsedHeaders,
};
@@ -380,6 +386,11 @@ export function WebhookForm({
error={form.formState.errors.description?.message}
{...form.register('description')}
/>
+
{service === WebhookService.Generic && [
diff --git a/packages/app/src/components/TeamSettings/__tests__/McpServerSection.test.tsx b/packages/app/src/components/TeamSettings/__tests__/McpServerSection.test.tsx
index c686675ad..49c835d50 100644
--- a/packages/app/src/components/TeamSettings/__tests__/McpServerSection.test.tsx
+++ b/packages/app/src/components/TeamSettings/__tests__/McpServerSection.test.tsx
@@ -67,15 +67,16 @@ describe('McpServerSection', () => {
expect(screen.queryByTestId('mcp-server-section')).not.toBeInTheDocument();
});
- it('renders all six host options when the deployment shape is valid', () => {
+ it('offers only file and deep-link hosts for manual setup', () => {
renderSection();
- expect(screen.getByText('Claude Code')).toBeInTheDocument();
expect(screen.getByText('Cursor')).toBeInTheDocument();
expect(screen.getByText('VS Code')).toBeInTheDocument();
- expect(screen.getByText('Codex CLI')).toBeInTheDocument();
expect(screen.getByText('OpenCode')).toBeInTheDocument();
expect(screen.getByText('Other')).toBeInTheDocument();
+ // Their setup is a shell command with the key in it; the CLI covers them.
+ expect(screen.queryByText('Claude Code')).not.toBeInTheDocument();
+ expect(screen.queryByText('Codex CLI')).not.toBeInTheDocument();
});
// Auth-gate parity with `ApiKeysSection`: when `me` resolves to
@@ -89,10 +90,12 @@ describe('McpServerSection', () => {
expect(screen.queryByTestId('mcp-server-section')).not.toBeInTheDocument();
});
- it('renders the fixed clickstack server name in the install snippet', () => {
+ it('leads with the CLI installer command', () => {
renderSection();
- expect(screen.getByText(/claude mcp add clickstack /)).toBeInTheDocument();
+ expect(
+ screen.getByText(/^npx @hyperdx\/cli mcp install --app-url /),
+ ).toBeInTheDocument();
});
// `MeApiResponseSchema.accessKey` is `z.string()` non-nullable
@@ -108,22 +111,6 @@ describe('McpServerSection', () => {
expect(screen.queryByTestId('mcp-server-section')).not.toBeInTheDocument();
});
- it('switches to the Codex CLI snippet when the host picker selects Codex CLI', async () => {
- const user = userEvent.setup();
- renderSection();
-
- await user.click(screen.getByText('Codex CLI'));
-
- expect(
- screen.getByText(
- /codex mcp add clickstack --url .*--bearer-token-env-var/s,
- ),
- ).toBeInTheDocument();
- expect(
- screen.queryByText(/^claude mcp add clickstack /),
- ).not.toBeInTheDocument();
- });
-
it('renders the Cursor deeplink button with a cursor:// href when Cursor is selected', async () => {
const user = userEvent.setup();
renderSection();
diff --git a/packages/app/src/components/TeamSettings/__tests__/OrgApiKeysSection.test.tsx b/packages/app/src/components/TeamSettings/__tests__/OrgApiKeysSection.test.tsx
new file mode 100644
index 000000000..5e9f52284
--- /dev/null
+++ b/packages/app/src/components/TeamSettings/__tests__/OrgApiKeysSection.test.tsx
@@ -0,0 +1,178 @@
+import { act, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import api from '@/api';
+import OrgApiKeysSection from '@/components/TeamSettings/OrgApiKeysSection';
+import { useConfirm } from '@/useConfirm';
+
+jest.mock('@/api', () => ({
+ __esModule: true,
+ default: {
+ useOrgApiKeys: jest.fn(),
+ useCreateOrgApiKey: jest.fn(),
+ useUpdateOrgApiKey: jest.fn(),
+ useDeleteOrgApiKey: jest.fn(),
+ },
+ hdxServer: jest.fn(),
+}));
+
+jest.mock('@/useConfirm', () => ({ useConfirm: jest.fn() }));
+
+const mockUseOrgApiKeys: jest.Mock = jest.mocked(api.useOrgApiKeys);
+const mockUseCreate: jest.Mock = jest.mocked(api.useCreateOrgApiKey);
+const mockUseUpdate: jest.Mock = jest.mocked(api.useUpdateOrgApiKey);
+const mockUseDelete: jest.Mock = jest.mocked(api.useDeleteOrgApiKey);
+const mockUseConfirm: jest.Mock = jest.mocked(useConfirm);
+
+const createMutate = jest.fn();
+const deleteMutate = jest.fn();
+let confirmAccepts = true;
+
+const key = (overrides = {}) => ({
+ id: 'k1',
+ description: 'terraform',
+ createdAt: '2026-10-01T00:00:00.000Z',
+ expiresAt: '2099-01-01T00:00:00.000Z',
+ lastUsedAt: '2026-10-02T00:00:00.000Z',
+ createdBy: { id: 'u1', name: 'Ada', email: 'ada@example.com' },
+ ...overrides,
+});
+
+const setKeys = (data: ReturnType[]) =>
+ mockUseOrgApiKeys.mockReturnValue({ data: { data }, isLoading: false });
+
+beforeEach(() => {
+ jest.clearAllMocks();
+ confirmAccepts = true;
+ setKeys([]);
+ mockUseCreate.mockReturnValue({ mutate: createMutate, isPending: false });
+ mockUseUpdate.mockReturnValue({ mutateAsync: jest.fn() });
+ mockUseDelete.mockReturnValue({ mutate: deleteMutate });
+ mockUseConfirm.mockReturnValue(() => Promise.resolve(confirmAccepts));
+});
+
+describe('OrgApiKeysSection', () => {
+ it('shows an empty state with no keys', () => {
+ renderWithMantine();
+ expect(
+ screen.getByText('No organization API keys yet'),
+ ).toBeInTheDocument();
+ });
+
+ it('shows an error instead of the empty state when loading fails', () => {
+ mockUseOrgApiKeys.mockReturnValue({
+ data: undefined,
+ isLoading: false,
+ isError: true,
+ });
+ renderWithMantine();
+ expect(
+ screen.getByText("Couldn't load organization API keys"),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText('No organization API keys yet'),
+ ).not.toBeInTheDocument();
+ });
+
+ it('labels deleted creators, unused keys, and expired keys', () => {
+ setKeys([
+ key({
+ createdBy: null,
+ lastUsedAt: null,
+ expiresAt: '2020-01-01T00:00:00.000Z',
+ }),
+ ]);
+ renderWithMantine();
+ expect(screen.getByText('Deleted user')).toBeInTheDocument();
+ expect(screen.getByText('Never')).toBeInTheDocument();
+ expect(screen.getByText('Expired')).toBeInTheDocument();
+ });
+
+ it('creates a key expiring in 30 days by default and shows it once', async () => {
+ createMutate.mockImplementation((_vars, options) =>
+ options?.onSuccess?.({ ...key(), key: 'hdx_org_secret' }),
+ );
+ renderWithMantine();
+
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Create API key' }),
+ );
+ await userEvent.type(
+ await screen.findByLabelText('Description'),
+ 'terraform',
+ );
+ await userEvent.click(screen.getByRole('button', { name: 'Create' }));
+
+ expect(createMutate).toHaveBeenCalledWith(
+ { description: 'terraform', expiry: '30d' },
+ expect.anything(),
+ );
+ expect(
+ await screen.findByText(
+ "Copy this key now. You won't be able to see it again.",
+ ),
+ ).toBeInTheDocument();
+ });
+
+ it('revokes only after confirming', async () => {
+ setKeys([key()]);
+ confirmAccepts = false;
+ renderWithMantine();
+
+ await userEvent.click(screen.getByRole('button', { name: 'Revoke' }));
+ await waitFor(() => expect(deleteMutate).not.toHaveBeenCalled());
+
+ confirmAccepts = true;
+ await userEvent.click(screen.getByRole('button', { name: 'Revoke' }));
+ await waitFor(() =>
+ expect(deleteMutate).toHaveBeenCalledWith(
+ { id: 'k1' },
+ expect.anything(),
+ ),
+ );
+ });
+
+ it('marks a key expired once its expiry passes while the page is open', () => {
+ jest.useFakeTimers({ now: new Date('2026-10-01T00:00:00.000Z') });
+ try {
+ setKeys([key({ expiresAt: '2026-10-01T00:00:30.000Z' })]);
+ renderWithMantine();
+ expect(screen.queryByText('Expired')).not.toBeInTheDocument();
+ act(() => {
+ jest.advanceTimersByTime(60_000);
+ });
+ expect(screen.getByText('Expired')).toBeInTheDocument();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('limits descriptions to 100 characters and reports failed edits', async () => {
+ setKeys([key()]);
+ mockUseUpdate.mockReturnValue({
+ mutateAsync: jest.fn().mockRejectedValue(new Error('Save failed')),
+ });
+ renderWithMantine();
+
+ const input = screen.getByLabelText('API key description');
+ expect(input).toHaveAttribute('maxLength', '100');
+ await userEvent.clear(input);
+ await userEvent.type(input, 'ci{Enter}');
+ expect(
+ await screen.findByText("Couldn't rename API key: Save failed"),
+ ).toBeInTheDocument();
+ });
+
+ it('keeps the create dialog open while the key is being created', async () => {
+ mockUseCreate.mockReturnValue({ mutate: createMutate, isPending: true });
+ renderWithMantine();
+
+ await userEvent.click(
+ screen.getByRole('button', { name: 'Create API key' }),
+ );
+ const cancel = await screen.findByRole('button', { name: 'Cancel' });
+ expect(cancel).toBeDisabled();
+ await userEvent.keyboard('{Escape}');
+ expect(screen.getByLabelText('Description')).toBeInTheDocument();
+ });
+});
diff --git a/packages/app/src/components/TeamSettings/__tests__/WebhookForm.test.tsx b/packages/app/src/components/TeamSettings/__tests__/WebhookForm.test.tsx
index 2d9a22eef..91b65ffea 100644
--- a/packages/app/src/components/TeamSettings/__tests__/WebhookForm.test.tsx
+++ b/packages/app/src/components/TeamSettings/__tests__/WebhookForm.test.tsx
@@ -130,6 +130,47 @@ describe('WebhookForm', () => {
);
});
+ it('saves titleEmoji false when the emoji checkbox is cleared', async () => {
+ const user = userEvent.setup();
+ renderForm();
+
+ await user.type(screen.getByTestId('webhook-name-input'), 'ops');
+ await user.type(
+ screen.getByTestId('webhook-url-input'),
+ 'https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXX',
+ );
+ await user.click(screen.getByTestId('webhook-title-emoji-checkbox'));
+ await user.click(screen.getByTestId('add-webhook-button'));
+
+ expect(mockSaveWebhook).toHaveBeenCalledWith(
+ expect.objectContaining({ titleEmoji: false }),
+ );
+ });
+
+ it('shows an existing titleEmoji false webhook unchecked and keeps it on save', async () => {
+ const user = userEvent.setup();
+ renderForm({
+ _id: 'wh-1',
+ name: 'oncall',
+ url: 'https://example.com/****',
+ service: WebhookService.Generic,
+ body: DEFAULT_GENERIC_WEBHOOK_BODY,
+ titleEmoji: false,
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ } as React.ComponentProps['webhook']);
+
+ expect(
+ screen.getByTestId('webhook-title-emoji-checkbox'),
+ ).not.toBeChecked();
+
+ await user.click(screen.getByTestId('add-webhook-button'));
+
+ expect(mockUpdateWebhook).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'wh-1', titleEmoji: false }),
+ );
+ });
+
it('does not show the template variables for a slack webhook', () => {
renderForm();
diff --git a/packages/app/src/components/TimePicker/TimePicker.tsx b/packages/app/src/components/TimePicker/TimePicker.tsx
index 153963edf..9de4898d3 100644
--- a/packages/app/src/components/TimePicker/TimePicker.tsx
+++ b/packages/app/src/components/TimePicker/TimePicker.tsx
@@ -3,11 +3,11 @@ import { add, Duration, sub } from 'date-fns';
import { useAtom } from 'jotai';
import { atomWithStorage } from 'jotai/utils';
import { useHotkeys } from 'react-hotkeys-hook';
+import { Separator } from '@clickhouse/click-ui';
import {
Button,
Card,
CloseButton,
- Divider,
getDefaultZIndex,
Group,
Popover,
@@ -25,9 +25,15 @@ import { DateInput, DateInputProps } from '@mantine/dates';
import { useDisclosure } from '@mantine/hooks';
import { IconBolt, IconCalendarFilled } from '@tabler/icons-react';
+import { useTimeZoneOverride } from '@/timeZoneOverride';
import { useDisplayTimeZone } from '@/useDisplayTimeZone';
import { useUserPreferences } from '@/useUserPreferences';
+import {
+ TimePickerTimeZoneBadge,
+ TimePickerTimeZoneSelect,
+ useTimePickerTimeZoneLabel,
+} from './TimePickerTimeZone';
import { TimePickerMode } from './types';
import { useTimePickerForm } from './useTimePickerForm';
import {
@@ -143,6 +149,8 @@ const TimePickerComponent = ({
userPreferences: { timeFormat },
} = useUserPreferences();
const timeZone = useDisplayTimeZone();
+ // Pages that can override the time zone show it in the picker.
+ const showTimeZone = useTimeZoneOverride() != null;
const [opened, { close, toggle }] = useDisclosure(false);
@@ -166,6 +174,7 @@ const TimePickerComponent = ({
const dateRange = React.useMemo(() => {
return parseTimeRangeInput(value, timeZone);
}, [value, timeZone]);
+ const timeZoneLabel = useTimePickerTimeZoneLabel(dateRange);
React.useEffect(() => {
// Only update form values from external dateRange when popover is closed
@@ -307,12 +316,22 @@ const TimePickerComponent = ({
: 'var(--color-text)',
},
}}
+ // Sized to the label: offsets like "UTC-3:30/-2:30" run long.
+ rightSectionWidth={
+ showTimeZone
+ ? `calc(${timeZoneLabel.label.length}ch + ${opened ? 40 : 16}px)`
+ : undefined
+ }
+ rightSectionPointerEvents="none"
rightSection={
- opened && (
-
- d
-
- )
+
+ {showTimeZone && }
+ {opened && (
+
+ d
+
+ )}
+
}
value={value}
onChange={event => onChange(event.currentTarget.value)}
@@ -388,7 +407,7 @@ const TimePickerComponent = ({
{relativeTimeOptions.map((item, index) => {
if (item === 'divider') {
- return ;
+ return ;
}
const isDisabledForLiveTail =
isRelative && !item[2] && item[0] !== LIVE_TAIL_TIME_QUERY;
@@ -555,6 +574,7 @@ const TimePickerComponent = ({
+
);
diff --git a/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx
new file mode 100644
index 000000000..280133bbd
--- /dev/null
+++ b/packages/app/src/components/TimePicker/TimePickerTimeZone.tsx
@@ -0,0 +1,106 @@
+import { useMemo } from 'react';
+import { ComboboxProps, Group, Stack, Text } from '@mantine/core';
+
+import { TimeZoneSelect, TimeZoneShortcuts } from '@/components/TimeZoneSelect';
+import {
+ getLocalTimeZone,
+ getTimeZoneRangeShortName,
+ getTimeZoneShortName,
+} from '@/timeZone';
+import { useTimeZoneOverride } from '@/timeZoneOverride';
+import { useDisplayTimeZone } from '@/useDisplayTimeZone';
+import { useUserPreferences } from '@/useUserPreferences';
+
+/**
+ * Offset of the zone the picker reads and shows times in, during `range`
+ * (now if it didn't parse), and whether it is the browser's zone.
+ */
+export function useTimePickerTimeZoneLabel(
+ range: readonly [Date | null, Date | null],
+): { label: string; isLocal: boolean } {
+ const localTimeZone = getLocalTimeZone();
+ const timeZone = useDisplayTimeZone() ?? localTimeZone;
+ const startMs = range[0]?.getTime();
+ const endMs = range[1]?.getTime();
+ return useMemo(
+ () => ({
+ label:
+ startMs != null && endMs != null
+ ? getTimeZoneRangeShortName(timeZone, [
+ new Date(startMs),
+ new Date(endMs),
+ ])
+ : getTimeZoneShortName(timeZone),
+ isLocal: timeZone === localTimeZone,
+ }),
+ [timeZone, localTimeZone, startMs, endMs],
+ );
+}
+
+/** The zone's offset, highlighted when it isn't the browser's zone. */
+export function TimePickerTimeZoneBadge({
+ label,
+ isLocal,
+}: {
+ label: string;
+ isLocal: boolean;
+}) {
+ return (
+
+ {label}
+
+ );
+}
+
+/** Sets the page's time zone override. Renders nothing without one. */
+export function TimePickerTimeZoneSelect({
+ comboboxProps,
+}: {
+ comboboxProps: ComboboxProps;
+}) {
+ const override = useTimeZoneOverride();
+ const {
+ userPreferences: { timeZone: userTimeZone },
+ } = useUserPreferences();
+
+ if (override == null) {
+ return null;
+ }
+
+ return (
+
+
+ Time zone
+
+
+
+ override.setTimeZone(null)}
+ />
+
+
+ );
+}
diff --git a/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx
new file mode 100644
index 000000000..65dd68176
--- /dev/null
+++ b/packages/app/src/components/TimePicker/__tests__/TimePickerTimeZone.test.tsx
@@ -0,0 +1,149 @@
+import { fireEvent, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+
+import { TimePicker } from '@/components/TimePicker';
+
+let mockOverride: {
+ timeZone: string | null;
+ setTimeZone: jest.Mock;
+} | null = null;
+jest.mock('@/timeZoneOverride', () => ({
+ useTimeZoneOverride: () => mockOverride,
+}));
+
+let mockDisplayTimeZone: string | undefined;
+jest.mock('@/useDisplayTimeZone', () => ({
+ useDisplayTimeZone: () => mockDisplayTimeZone,
+}));
+
+const renderPicker = (inputValue = 'Oct 22 14:00:00 - Oct 22 15:00:00') => {
+ renderWithMantine(
+ ,
+ );
+};
+
+describe('TimePicker time zone override', () => {
+ beforeEach(() => {
+ mockOverride = null;
+ mockDisplayTimeZone = undefined;
+ });
+
+ it('shows no time zone without a page override', () => {
+ renderPicker();
+ fireEvent.click(screen.getByTestId('time-picker-input'));
+
+ expect(screen.queryByTestId('time-picker-time-zone')).toBeNull();
+ expect(screen.queryByTestId('time-picker-time-zone-select')).toBeNull();
+ });
+
+ it('shows the display zone in the input', () => {
+ mockOverride = { timeZone: 'Asia/Tokyo', setTimeZone: jest.fn() };
+ mockDisplayTimeZone = 'Asia/Tokyo';
+ renderPicker();
+
+ expect(screen.getByTestId('time-picker-time-zone')).toHaveTextContent(
+ 'UTC+9',
+ );
+ });
+
+ it.each([
+ ['Jan 15 2026 10:00:00 - Jan 15 2026 11:00:00', 'UTC-8'],
+ ['Oct 31 2026 10:00:00 - Nov 2 2026 10:00:00', 'UTC-7/-8'],
+ ])('shows the offset during the range %s', (inputValue, label) => {
+ mockOverride = {
+ timeZone: 'America/Los_Angeles',
+ setTimeZone: jest.fn(),
+ };
+ mockDisplayTimeZone = 'America/Los_Angeles';
+ renderPicker(inputValue);
+
+ expect(screen.getByTestId('time-picker-time-zone')).toHaveTextContent(
+ label,
+ );
+ });
+
+ // Tests run with TZ=America/New_York.
+ it.each([
+ [undefined, true],
+ ['America/New_York', true],
+ ['Asia/Tokyo', false],
+ ])(
+ 'highlights the zone %s only when it is not local',
+ (timeZone, isLocal) => {
+ mockOverride = { timeZone: timeZone ?? null, setTimeZone: jest.fn() };
+ mockDisplayTimeZone = timeZone;
+ renderPicker();
+
+ const badge = screen.getByTestId('time-picker-time-zone');
+ expect(badge).toHaveAttribute('data-local', String(isLocal));
+ },
+ );
+
+ async function pickTimeZone(option: RegExp) {
+ fireEvent.click(screen.getByTestId('time-picker-input'));
+ await userEvent.click(
+ await screen.findByTestId('time-picker-time-zone-select'),
+ );
+ await userEvent.click(
+ await screen.findByRole('option', { name: option, hidden: true }),
+ );
+ }
+
+ it('sets the page override', async () => {
+ const setTimeZone = jest.fn();
+ mockOverride = { timeZone: null, setTimeZone };
+ renderPicker();
+
+ await pickTimeZone(/^UTC/);
+
+ expect(setTimeZone).toHaveBeenCalledWith('Etc/UTC');
+ });
+
+ it.each([
+ ['time-picker-time-zone-utc', 'Etc/UTC'],
+ ['time-picker-time-zone-local', 'local'],
+ ])('sets the override from the %s shortcut', async (testId, timeZone) => {
+ const setTimeZone = jest.fn();
+ mockOverride = { timeZone: 'Asia/Tokyo', setTimeZone };
+ renderPicker();
+ fireEvent.click(screen.getByTestId('time-picker-input'));
+
+ await userEvent.click(await screen.findByTestId(testId));
+
+ expect(setTimeZone).toHaveBeenCalledWith(timeZone);
+ });
+
+ it('clears the page override with the Default shortcut', async () => {
+ const setTimeZone = jest.fn();
+ mockOverride = { timeZone: 'Asia/Tokyo', setTimeZone };
+ renderPicker();
+ fireEvent.click(screen.getByTestId('time-picker-input'));
+
+ const shortcuts = (
+ await screen.findByTestId('time-picker-time-zone-default')
+ ).parentElement;
+ expect(
+ Array.from(shortcuts?.children ?? []).map(button => button.textContent),
+ ).toEqual(['Default', 'UTC', 'Local']);
+
+ await userEvent.click(screen.getByTestId('time-picker-time-zone-default'));
+
+ expect(setTimeZone).toHaveBeenCalledWith(null);
+ });
+
+ it('clears the page override with the default option', async () => {
+ const setTimeZone = jest.fn();
+ mockOverride = { timeZone: 'Etc/UTC', setTimeZone };
+ mockDisplayTimeZone = 'Etc/UTC';
+ renderPicker();
+
+ // The default names the user setting, which is unset here.
+ await pickTimeZone(/^Default \(Local\)/);
+
+ expect(setTimeZone).toHaveBeenCalledWith(null);
+ });
+});
diff --git a/packages/app/src/components/TimePicker/utils.ts b/packages/app/src/components/TimePicker/utils.ts
index b6f207b2c..ef9f4dbd9 100644
--- a/packages/app/src/components/TimePicker/utils.ts
+++ b/packages/app/src/components/TimePicker/utils.ts
@@ -6,12 +6,7 @@ import {
toWallClock,
} from '@hyperdx/common-utils/dist/core/utils';
-import { getLocalTimeZone } from '@/timeZone';
-
-function currentDate(): Date {
- // eslint-disable-next-line no-restricted-syntax
- return new Date();
-}
+import { currentDate, getLocalTimeZone } from '@/timeZone';
function resolveTimeZone(timeZone?: string): string {
return timeZone ?? getLocalTimeZone();
diff --git a/packages/app/src/components/TimeZoneSelect.tsx b/packages/app/src/components/TimeZoneSelect.tsx
index 4de300eb1..a652b0dbc 100644
--- a/packages/app/src/components/TimeZoneSelect.tsx
+++ b/packages/app/src/components/TimeZoneSelect.tsx
@@ -2,6 +2,7 @@ import { useCallback, useMemo } from 'react';
import { UTC_TIME_ZONE } from '@hyperdx/common-utils/dist/core/utils';
import {
Box,
+ Button,
ComboboxData,
ComboboxItem,
Group,
@@ -15,7 +16,7 @@ import {
formatTimeZoneName,
getLocalTimeZone,
getSupportedTimeZones,
- getTimeZoneOffsetLabel,
+ getTimeZonePreferenceLabel,
getTimeZoneShortName,
LOCAL_TIME_ZONE,
resolveTimeZonePreference,
@@ -25,23 +26,38 @@ type TimeZoneSelectProps = Omit<
SelectProps,
'value' | 'onChange' | 'data' | 'renderOption'
> & {
- /** A time zone setting: `LOCAL_TIME_ZONE` or an IANA name. */
- value: string;
- onChange: (value: string) => void;
+ /**
+ * A time zone setting: `LOCAL_TIME_ZONE` or an IANA name, or null for the
+ * default option.
+ */
+ value: string | null;
+ onChange: (value: string | null) => void;
+ /**
+ * The setting the default option stands for, such as the user's. Adds a
+ * "Default (…)" option, pinned first, that selects null.
+ */
+ defaultTimeZone?: string;
};
-/** Offsets shown next to each option, keyed by option value. */
-function getOffsetLabels(zones: string[]): Map {
- const localZone = getLocalTimeZone();
-
- return new Map([
- [
- LOCAL_TIME_ZONE,
- `${getTimeZoneShortName(localZone)} · ${getTimeZoneOffsetLabel(localZone)}`,
- ],
- [UTC_TIME_ZONE, getTimeZoneOffsetLabel(UTC_TIME_ZONE)],
- ...zones.map(zone => [zone, getTimeZoneOffsetLabel(zone)] as const),
- ]);
+const DEFAULT_OPTION = '__default';
+
+type ZoneOption = { value: string; name: string; offset?: string };
+
+function getDefaultOption(preference: string): ZoneOption {
+ const timeZone = resolveTimeZonePreference(preference);
+ return {
+ value: DEFAULT_OPTION,
+ name: `Default (${getTimeZonePreferenceLabel(preference)})`,
+ offset:
+ timeZone === UTC_TIME_ZONE
+ ? undefined
+ : getTimeZoneShortName(timeZone ?? getLocalTimeZone()),
+ };
+}
+
+// The label is what the input shows and what search matches.
+function toComboboxItem({ value, name, offset }: ZoneOption): ComboboxItem {
+ return { value, label: offset ? `${name} ${offset}` : name };
}
/**
@@ -51,14 +67,22 @@ function getOffsetLabels(zones: string[]): Map {
export function TimeZoneSelect({
value,
onChange,
+ defaultTimeZone,
...props
}: TimeZoneSelectProps) {
- const selected = resolveTimeZonePreference(value) ?? LOCAL_TIME_ZONE;
+ const selected =
+ value == null && defaultTimeZone != null
+ ? DEFAULT_OPTION
+ : (resolveTimeZonePreference(value ?? LOCAL_TIME_ZONE) ??
+ LOCAL_TIME_ZONE);
const zones = useMemo(() => {
const supported = getSupportedTimeZones();
- const isPinned = selected === LOCAL_TIME_ZONE || selected === UTC_TIME_ZONE;
+ const isPinned =
+ selected === DEFAULT_OPTION ||
+ selected === LOCAL_TIME_ZONE ||
+ selected === UTC_TIME_ZONE;
const isListed = supported.includes(selected);
@@ -69,43 +93,57 @@ export function TimeZoneSelect({
return [...supported, selected];
}, [selected]);
- const data = useMemo(
- () => [
+ const { data, optionsByValue } = useMemo(() => {
+ const localZone = getLocalTimeZone();
+ const pinned: ZoneOption[] = [
+ ...(defaultTimeZone != null ? [getDefaultOption(defaultTimeZone)] : []),
{
value: LOCAL_TIME_ZONE,
- label: `Local (${formatTimeZoneName(getLocalTimeZone())})`,
+ name: `Local (${formatTimeZoneName(localZone)})`,
+ offset: getTimeZoneShortName(localZone),
},
- { value: UTC_TIME_ZONE, label: 'UTC' },
- {
- group: 'All time zones',
- items: zones.map(zone => ({
- value: zone,
- label: formatTimeZoneName(zone),
- })),
- },
- ],
- [zones],
- );
-
- const offsetLabels = useMemo(() => getOffsetLabels(zones), [zones]);
+ // UTC's name is already its offset.
+ { value: UTC_TIME_ZONE, name: 'UTC' },
+ ];
+ const listed: ZoneOption[] = zones.map(zone => ({
+ value: zone,
+ name: formatTimeZoneName(zone),
+ offset: getTimeZoneShortName(zone),
+ }));
+
+ return {
+ data: [
+ ...pinned.map(toComboboxItem),
+ { group: 'All time zones', items: listed.map(toComboboxItem) },
+ ] satisfies ComboboxData,
+ optionsByValue: new Map(
+ [...pinned, ...listed].map(option => [option.value, option]),
+ ),
+ };
+ }, [zones, defaultTimeZone]);
const renderOption = useCallback(
- ({ option, checked }: { option: ComboboxItem; checked?: boolean }) => (
-
-
- {option.label}
-
-
- {offsetLabels.get(option.value)}
-
-
-
- {checked && (
-
- )}
-
- ),
- [offsetLabels],
+ ({ option, checked }: { option: ComboboxItem; checked?: boolean }) => {
+ const zone = optionsByValue.get(option.value);
+ return (
+
+
+ {zone?.name ?? option.label}
+
+ {zone?.offset && (
+
+ {zone.offset}
+
+ )}
+
+
+ {checked && (
+
+ )}
+
+ );
+ },
+ [optionsByValue],
);
return (
@@ -117,8 +155,57 @@ export function TimeZoneSelect({
{...props}
data={data}
value={selected}
- onChange={next => next && onChange(next)}
+ onChange={next => {
+ if (next != null) {
+ onChange(next === DEFAULT_OPTION ? null : next);
+ }
+ }}
renderOption={renderOption}
/>
);
}
+
+/**
+ * One-click "UTC" and "Local" buttons, for under a `TimeZoneSelect`. With
+ * `onSelectDefault`, a "Default" button comes first.
+ */
+export function TimeZoneShortcuts({
+ onSelect,
+ onSelectDefault,
+ testIdPrefix,
+}: {
+ onSelect: (timeZone: string) => void;
+ onSelectDefault?: () => void;
+ testIdPrefix: string;
+}) {
+ return (
+
+ {onSelectDefault && (
+
+ Default
+
+ )}
+ onSelect(UTC_TIME_ZONE)}
+ >
+ UTC
+
+ onSelect(LOCAL_TIME_ZONE)}
+ >
+ Local
+
+
+ );
+}
diff --git a/packages/app/src/components/TimelineChart/TimelineChart.tsx b/packages/app/src/components/TimelineChart/TimelineChart.tsx
index 03f5b7ac7..991f8f63b 100644
--- a/packages/app/src/components/TimelineChart/TimelineChart.tsx
+++ b/packages/app/src/components/TimelineChart/TimelineChart.tsx
@@ -1,6 +1,6 @@
import { memo, useEffect, useLayoutEffect, useMemo, useRef } from 'react';
import cx from 'classnames';
-import { Flex, Kbd, Text } from '@mantine/core';
+import { Flex, Text } from '@mantine/core';
import { useVirtualizer } from '@tanstack/react-virtual';
import {
@@ -77,7 +77,12 @@ type TimelineChartProps = {
const MIN_VIEWPORT_FRAC = 0.02;
const axisHeight = 24;
-const rowsMarginTop = 32;
+// Gap between the axis and the first row. The hover time label
+// (TimelineMouseCursor, styled in TimelineChart.module.scss) reaches about 37px
+// below the top of the chart; the first row starts at
+// axisHeight + rowsMarginTop = 44px, which keeps it clear with some headroom.
+// Revisit this if the label's padding or offset grows.
+const rowsMarginTop = 20;
const maxScale = 100;
export const TimelineChart = memo(function (props: TimelineChartProps) {
@@ -404,12 +409,6 @@ export const TimelineChart = memo(function (props: TimelineChartProps) {
return (
-
-
- ⌘/Ctrl + scroll to zoom
-
-
-
+ {/* The corner above the label column is otherwise empty, so the
+ zoom hint lives here instead of in its own row above the chart.
+ It reuses the tick label class and inherits the axis font so it
+ reads as part of the axis header. */}
+ >
+
+ ⌘/Ctrl + scroll to zoom
+
+